@ggui-ai/ui-gen 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{adapter-Cg_rkpGq.d.ts → adapter-BJwn74rx.d.ts} +49 -1
- package/dist/adapters/generation-dispatch.d.ts +8 -5
- package/dist/adapters/generation-dispatch.js +1118 -193
- package/dist/adapters/generation-dispatch.js.map +1 -1
- package/dist/adapters/index.js +27 -6
- package/dist/adapters/index.js.map +1 -1
- package/dist/advanced/index.d.ts +10 -9
- package/dist/advanced/index.js +1126 -202
- package/dist/advanced/index.js.map +1 -1
- package/dist/blueprint-validator.js +416 -92
- package/dist/blueprint-validator.js.map +1 -1
- package/dist/boilerplate.d.ts +2 -2
- package/dist/boilerplate.js +10 -3
- package/dist/boilerplate.js.map +1 -1
- package/dist/check/index.d.ts +3 -2
- package/dist/check/index.js +9 -2
- package/dist/check/index.js.map +1 -1
- package/dist/{create-ui-generator-DFnnArrv.d.ts → create-ui-generator-N4gRXpcL.d.ts} +3 -4
- package/dist/{design-mode-DLufhrNp.d.ts → design-mode-DGWN_Gkm.d.ts} +1 -1
- package/dist/{dispatch-CStl9eAw.d.ts → dispatch-BUoXRj_r.d.ts} +2 -2
- package/dist/evaluation/axis-checks/index.d.ts +5 -4
- package/dist/evaluation/axis-checks/index.js.map +1 -1
- package/dist/evaluation/axis-checks/registry.d.ts +4 -3
- package/dist/evaluation/index.d.ts +107 -539
- package/dist/evaluation/index.js +552 -55
- package/dist/evaluation/index.js.map +1 -1
- package/dist/evaluation/types.d.ts +17 -0
- package/dist/evaluation/types.js.map +1 -1
- package/dist/{generate-9IeNT4ZY.d.ts → generate-tSO_shQ0.d.ts} +1 -1
- package/dist/harness/check/runtime-render/index.d.ts +5 -5
- package/dist/harness/check/runtime-render/index.js +416 -92
- package/dist/harness/check/runtime-render/index.js.map +1 -1
- package/dist/harness/check/runtime-render/render-check-worker.js +393 -88
- package/dist/harness/check/runtime-render/render-check-worker.js.map +1 -1
- package/dist/harness/index.d.ts +4 -5
- package/dist/harness/index.js +36 -5
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/prompts.d.ts +2 -2
- package/dist/harness/prompts.js +10 -1
- package/dist/harness/prompts.js.map +1 -1
- package/dist/harness/result-types.d.ts +17 -3
- package/dist/harness/result-types.js.map +1 -1
- package/dist/harness/runtime.d.ts +14 -6
- package/dist/harness/runtime.js +11 -4
- package/dist/harness/runtime.js.map +1 -1
- package/dist/harness/types-public.d.ts +4 -2
- package/dist/harness/types-public.js +10 -3
- package/dist/harness/types-public.js.map +1 -1
- package/dist/harness/validator-trace-sink.d.ts +4 -3
- package/dist/index.d.ts +46 -11
- package/dist/index.js +1128 -200
- package/dist/index.js.map +1 -1
- package/dist/patch.d.ts +3 -3
- package/dist/{prompts-YU9piOgs.d.ts → prompts-BhNUuRoZ.d.ts} +1 -1
- package/dist/tools/render-check-worker.js +8 -1
- package/dist/tools/render-check-worker.js.map +1 -1
- package/dist/{types-public-BJTLpzWn.d.ts → types-public-B7wn4ce5.d.ts} +384 -3
- package/dist/validation/index.d.ts +1 -1
- package/dist/validation/index.js +1 -1
- package/dist/validation/index.js.map +1 -1
- package/dist/visual-evaluator-C9L-o6ap.d.ts +639 -0
- package/dist/workflows.d.ts +3 -3
- package/package.json +12 -12
- package/src/adapters/generation-dispatch.ts +2 -0
- package/src/boilerplate/free-design-prompt.ts +3 -3
- package/src/boilerplate/hard-sections.ts +1 -1
- package/src/boilerplate/templates/layouts/chat-mobile.tsx.tmpl +3 -1
- package/src/boilerplate/templates/layouts/chat-universal.tsx.tmpl +3 -1
- package/src/boilerplate/templates/layouts/fullscreen-desktop.tsx.tmpl +3 -1
- package/src/boilerplate/templates/layouts/fullscreen-universal.tsx.tmpl +3 -1
- package/src/check/run-tier0.ts +6 -3
- package/src/contract-context.ts +1 -1
- package/src/evaluation/cost-tracker.ts +54 -6
- package/src/evaluation/criteria/edge-probe.ts +286 -0
- package/src/evaluation/criteria/edge.ts +202 -0
- package/src/evaluation/criteria/resolve.ts +55 -7
- package/src/evaluation/index.ts +5 -1
- package/src/evaluation/judge-spend.ts +48 -0
- package/src/evaluation/types-public.ts +91 -0
- package/src/evaluation/types.ts +10 -0
- package/src/evaluation/visual-evaluator.ts +236 -40
- package/src/harness/check/runtime-render/adapter.ts +18 -0
- package/src/harness/check/runtime-render/probe-pending.ts +111 -0
- package/src/harness/check/runtime-render/render-check-host.ts +10 -6
- package/src/harness/check/runtime-render/render-check-worker.ts +6 -3
- package/src/harness/check/runtime-render/render-check.ts +417 -133
- package/src/harness/check/runtime-render/walk.ts +200 -0
- package/src/harness/coding/assemble-result.ts +2 -0
- package/src/harness/coding/generate-task-runner.ts +27 -0
- package/src/harness/coding/init-session.ts +5 -3
- package/src/harness/coding/run-coding-turn.ts +5 -1
- package/src/harness/coding/run-eval-round.ts +63 -3
- package/src/harness/in-loop-evaluation.ts +39 -0
- package/src/harness/llm-router.ts +58 -1
- package/src/harness/result-types.ts +9 -0
- package/src/harness/runtime.ts +9 -0
- package/src/harness/types-public.ts +10 -1
- package/src/index.ts +5 -0
- package/src/internal/verdict-line.ts +33 -0
- package/src/taught-tokens.ts +32 -0
- package/src/tools/render-check-worker.ts +2 -1
- package/src/tools/render-check.ts +8 -7
- package/src/validation/primitives.ts +1 -1
- package/dist/llm-router-nfO7wPec.d.ts +0 -267
- package/dist/{bank-CT4eEkta.d.ts → bank-Ctdp3FUA.d.ts} +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/harness/check/runtime-render/render-check-host.ts","../../../../src/harness/check/runtime-render/production-act-shim.ts","../../../../src/harness/check/runtime-render/probe.ts","../../../../src/internal/evaluate-component-source.ts","../../../../src/harness/check/runtime-render/load-component.ts","../../../../src/harness/check/runtime-render/find-wiring.ts","../../../../src/internal/open-record.ts","../../../../src/harness/check/runtime-render/host-boundary.ts","../../../../src/harness/check/runtime-render/render-check.ts","../../../../src/harness/check/runtime-render/prepare-mockup.ts","../../../../src/harness/check/runtime-render/adapter.ts","../../../../src/harness/check/runtime-render/index.ts"],"names":["createRequire","runRenderCheckViaWorker"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,IAAA,yBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,yBAAA,EAAA;AAAA,EAAA,gCAAA,EAAA,MAAA,gCAAA;AAAA,EAAA,6BAAA,EAAA,MAAA,6BAAA;AAAA,EAAA,4BAAA,EAAA,MAAA,4BAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,uBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AA0FO,SAAS,4BAAA,CACd,MAAA,GAAyC,EAAC,EACnB;AACvB,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,SAAA,IAAa,gCAAA,CAAiC,SAAA;AACvE,EAAA,MAAM,MAAA,GAAS,MAAA,CAAO,MAAA,IAAU,gCAAA,CAAiC,MAAA;AAIjE,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,SAAS,CAAA,IAAK,YAAY,CAAA,EAAG;AACjD,IAAA,MAAM,IAAI,UAAA,CAAW,CAAA,yDAAA,EAAuD,SAAS,CAAA,CAAE,CAAA;AAAA,EACzF;AACA,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,MAAM,CAAA,IAAK,SAAS,CAAA,EAAG;AAC3C,IAAA,MAAM,IAAI,UAAA,CAAW,CAAA,qDAAA,EAAwD,MAAM,CAAA,CAAE,CAAA;AAAA,EACvF;AACA,EAAA,MAAM,cAAA,GAAiB,MAAA,CAAO,aAAA,IAAiB,gCAAA,CAAiC,aAAA;AAChF,EAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,cAAA,EAAgB,IAAA,CAAK,KAAA,CAAM,SAAA,GAAY,CAAC,CAAC,CAAC,CAAA;AACrF,EAAA,OAAO,EAAE,SAAA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EAAE,OAAA,KAAY;AAAA,KACjD;AACA,IAAA,IAAI,aAAa,KAAA,CAAA,EAAW;AAC1B,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,EAAA,EAAI,QAAQ,CAAA,EAAG,QAAA,CAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,OAAO,CAAA,EAAA,EAAK,QAAA,CAAS,MAAM,CAAA,CAAA,EAAG;AAAA,IAC9F;AACA,IAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,EAAA,EAAG;AAAA,EACxB,SAAS,GAAA,EAAK;AAGZ,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,EAAA,EAAI,IAAA,CAAK,GAAA,EAAI,GAAI,KAAA;AAAA,MACjB,QAAQ,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,KACzD;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * Host side of the isolated runtime render check (#592).\n *\n * Spawns `render-check-worker.ts` in a sandboxed subprocess and maps\n * every sandbox outcome onto the check's own `RenderCheckResult`\n * vocabulary, so callers see one result shape whether the check ran\n * in-process (DOM-owning environments) or isolated (plain Node).\n *\n * Outcome mapping policy (mirrors the adapter's escaped-error\n * doctrine — component faults are `failed`, harness faults are\n * `unverified`, and nothing throws):\n *\n * - worker exit 0 + parseable verdict → the verdict, verbatim.\n * - timeout → `incomplete` (ggui#1299): the check\n * did not finish, which is NOT a verdict on the component. The bound\n * is wall-clock, and on a contended host an ordinary component\n * crosses it; mapping it to `failed` reported crashes that never\n * happened. It carries its elapsed ms, and the host load (below)\n * says how busy the host was. React's own runaway guards (\"Too many\n * re-renders\", \"Maximum update depth exceeded\") throw, so they still\n * reach `render-no-throw` as `failed`; what now reads `incomplete`\n * is a check that ran out of wall-clock time, whatever the cause.\n * - overflow → `failed` (a pathological logging or\n * error loop; output volume does not depend on host load).\n * - spawn-error / non-zero exit / unparseable stdout\n * → `unverified` (the harness could not\n * run the check; never blame the component for our plumbing).\n *\n * Every isolated check records the host's 1-minute load average at its\n * start and end, and the CPUs available, on `stats.hostLoad`.\n *\n * Spawn resolution copies the proven `src/tools/render-check.ts`\n * pattern: prefer the built `dist/.../render-check-worker.js`; in\n * dev/test (vitest imports `src/`), fall back to `node --import tsx`\n * on the `.ts` source. tsup inlines THIS module into several dist\n * entries (`dist/index.js`, `dist/harness/index.js`,\n * `dist/check/index.js`, `dist/advanced/index.js`, …), so the\n * candidate list walks from each of those locations to the one real\n * `dist/harness/check/runtime-render/render-check-worker.js`.\n */\nimport { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { availableParallelism, loadavg } from 'node:os';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { runSandboxed } from '@ggui-ai/sandbox';\nimport type { SandboxResult } from '@ggui-ai/sandbox';\nimport type { ProbeHostLoad } from '../../../evaluation/types-public.js';\nimport type { RenderCheckResult, RunRenderCheckInput } from './render-check.js';\n\n/**\n * The subprocess bounds of one isolated check (ggui#1380). They are\n * INPUTS of the host, not constants: a serving deployment runs the probe\n * under its own memory and latency budget and sets them per check\n * instance (`createRuntimeRenderCheck`); the evaluation lane runs on the\n * defaults below, which are the values the host always used.\n */\nexport interface RenderCheckHostBounds {\n /**\n * Wall-clock bound for one isolated check. The rich probe renders,\n * clicks every declared action, and re-renders streams — slower than\n * the smoke worker's 12s budget; 30s bounds runaway components while\n * staying far under any generation-turn budget.\n */\n readonly timeoutMs: number;\n /**\n * V8 heap cap. The worker realm loads react-dom, happy-dom and\n * testing-library on top of the component itself; 512 MB leaves\n * headroom while still bounding pathological allocation.\n */\n readonly heapMb: number;\n /**\n * Grace between SIGTERM and SIGKILL once the bound is crossed. The\n * effective value is `min(gracePeriodMs, floor(timeoutMs / 2))` —\n * `runSandboxed` requires the grace to be strictly below the bound, so\n * a short bound never trips its RangeError.\n */\n readonly gracePeriodMs: number;\n}\n\nexport const DEFAULT_RENDER_CHECK_HOST_BOUNDS: RenderCheckHostBounds = {\n timeoutMs: 30_000,\n heapMb: 512,\n gracePeriodMs: 2_000,\n};\n\n/**\n * Fill the caller's partial bounds from the defaults and clamp the grace\n * below the bound. Exported so the kill-path pin can run a fixture under\n * exactly the numbers the host would pass for the same input.\n */\nexport function resolveRenderCheckHostBounds(\n bounds: Partial<RenderCheckHostBounds> = {},\n): RenderCheckHostBounds {\n const timeoutMs = bounds.timeoutMs ?? DEFAULT_RENDER_CHECK_HOST_BOUNDS.timeoutMs;\n const heapMb = bounds.heapMb ?? DEFAULT_RENDER_CHECK_HOST_BOUNDS.heapMb;\n // Refused at construction, like `maxConcurrent`: a 0 / NaN / fractional\n // bound would otherwise flow into the sandbox's flags as a nonsense number.\n // `timeoutMs` needs room for a grace of at least 1 ms below it.\n if (!Number.isInteger(timeoutMs) || timeoutMs < 2) {\n throw new RangeError(`render-check: timeoutMs must be an integer ≥ 2, got ${timeoutMs}`);\n }\n if (!Number.isInteger(heapMb) || heapMb < 1) {\n throw new RangeError(`render-check: heapMb must be a positive integer, got ${heapMb}`);\n }\n const requestedGrace = bounds.gracePeriodMs ?? DEFAULT_RENDER_CHECK_HOST_BOUNDS.gracePeriodMs;\n const gracePeriodMs = Math.max(1, Math.min(requestedGrace, Math.floor(timeoutMs / 2)));\n return { timeoutMs, heapMb, gracePeriodMs };\n}\n\n/** Options of {@link runRenderCheckViaWorker}. */\nexport interface RenderCheckHostOptions {\n /** Subprocess bounds; every field omitted falls to {@link DEFAULT_RENDER_CHECK_HOST_BOUNDS}. */\n readonly bounds?: Partial<RenderCheckHostBounds>;\n}\n\n/**\n * stdout cap. The verdict JSON carries issue lists with diagnostics\n * arrays — bigger than the smoke worker's one-liner, still tiny in\n * absolute terms. 2 MiB is far above any legitimate verdict.\n */\nconst CHECK_STDOUT_CAP = 2 * 1024 * 1024;\n\nconst WORKER_BASENAME = 'render-check-worker';\n\n/**\n * How the host spawns the worker from THIS location: the built dist sibling\n * when one exists, else the source `.ts` through tsx. Exported so the entry\n * guard can be pinned with the same spawn the host makes (no build needed).\n */\nexport function resolveWorkerSpawn(): { command: string; args: string[] } {\n const jsCandidates = [\n // Sibling — when import.meta.url is already .../harness/check/runtime-render/.\n new URL(`./${WORKER_BASENAME}.js`, import.meta.url),\n // From dist/index.js.\n new URL(`./harness/check/runtime-render/${WORKER_BASENAME}.js`, import.meta.url),\n // From dist/harness/index.js.\n new URL(`./check/runtime-render/${WORKER_BASENAME}.js`, import.meta.url),\n // From dist/check/index.js, dist/advanced/index.js, dist/<flat>.js.\n new URL(`../harness/check/runtime-render/${WORKER_BASENAME}.js`, import.meta.url),\n ];\n for (const jsUrl of jsCandidates) {\n const jsPath = fileURLToPath(jsUrl);\n if (existsSync(jsPath)) {\n return { command: process.execPath, args: [jsPath] };\n }\n }\n // Dev / vitest: only the .ts source exists — run it through tsx.\n const tsCandidates = [\n new URL(`./${WORKER_BASENAME}.ts`, import.meta.url),\n new URL(`../harness/check/runtime-render/${WORKER_BASENAME}.ts`, import.meta.url),\n ];\n for (const tsUrl of tsCandidates) {\n const tsPath = fileURLToPath(tsUrl);\n if (existsSync(tsPath)) {\n const require_ = createRequire(import.meta.url);\n const tsxLoader = pathToFileURL(require_.resolve('tsx')).href;\n return { command: process.execPath, args: ['--import', tsxLoader, tsPath] };\n }\n }\n const tried = [...jsCandidates, ...tsCandidates]\n .map((u) => fileURLToPath(u))\n .join(', ');\n throw new Error(\n `render-check: isolated worker not found at any of: ${tried}. Did \\`pnpm build\\` run?`,\n );\n}\n\nfunction failed(reason: string, t0: number): RenderCheckResult {\n return {\n ok: false,\n issues: [{ check: 'render-no-throw', outcome: 'failed', reason }],\n stats: { actionsChecked: 0, streamsChecked: 0, renderMs: Date.now() - t0 },\n };\n}\n\nfunction unverified(reason: string, t0: number): RenderCheckResult {\n return {\n ok: false,\n issues: [{ check: 'render-no-throw', outcome: 'unverified', reason }],\n stats: { actionsChecked: 0, streamsChecked: 0, renderMs: Date.now() - t0 },\n };\n}\n\n/**\n * Map one sandbox result onto a `RenderCheckResult`. `boundMs` is the\n * wall-clock bound the run was given, reported on a timeout. Exported for\n * the unit pins — the spawn itself is exercised by the integration test.\n */\nexport function mapSandboxResultToCheckResult(\n result: SandboxResult,\n t0: number,\n boundMs: number = DEFAULT_RENDER_CHECK_HOST_BOUNDS.timeoutMs,\n): RenderCheckResult {\n if (result.outcome === 'timeout') {\n return {\n ok: false,\n issues: [],\n incomplete: { kind: 'timeout', elapsedMs: result.durationMs, boundMs },\n stats: { actionsChecked: 0, streamsChecked: 0, renderMs: Date.now() - t0 },\n };\n }\n if (result.outcome === 'overflow-stdout' || result.outcome === 'overflow-stderr') {\n return failed(\n `render check worker produced excessive output (${result.outcome}) — the component is likely in a pathological logging or error loop.`,\n t0,\n );\n }\n if (result.outcome === 'spawn-error') {\n return unverified(\n `render check worker failed to start — ${result.errorMessage}`,\n t0,\n );\n }\n if (result.outcome === 'canceled') {\n return unverified('render check worker was canceled before completing.', t0);\n }\n if (result.outcome !== 'exit') {\n return unverified(\n `render check worker ended with unexpected sandbox outcome '${result.outcome}'.`,\n t0,\n );\n }\n if (result.exitCode !== 0) {\n const tail = result.stderr.trim() || result.stdout.trim();\n return unverified(\n `render check worker exited ${result.exitCode}${tail ? ` — ${tail.slice(0, 600)}` : ''}`,\n t0,\n );\n }\n const stdout = result.stdout.trim();\n if (stdout.length === 0) {\n return unverified('render check worker exited without producing a verdict.', t0);\n }\n try {\n return JSON.parse(stdout) as RenderCheckResult;\n } catch (err) {\n return unverified(\n `render check worker verdict was not valid JSON — ${\n err instanceof Error ? err.message : String(err)\n }`,\n t0,\n );\n }\n}\n\n/**\n * Run the render check in an isolated subprocess. See module doc.\n * `options.bounds` sets the subprocess bounds for this run; omitted\n * fields are the evaluation lane's defaults.\n */\nexport async function runRenderCheckViaWorker(\n input: RunRenderCheckInput,\n options: RenderCheckHostOptions = {},\n): Promise<RenderCheckResult> {\n const t0 = Date.now();\n const bounds = resolveRenderCheckHostBounds(options.bounds);\n let spawn: { command: string; args: string[] };\n try {\n spawn = resolveWorkerSpawn();\n } catch (err) {\n return unverified(err instanceof Error ? err.message : String(err), t0);\n }\n\n const loadAtStart = loadavg()[0] ?? 0;\n const result = await runSandboxed({\n command: spawn.command,\n args: spawn.args,\n timeoutMs: bounds.timeoutMs,\n gracePeriodMs: bounds.gracePeriodMs,\n maxStdoutBytes: CHECK_STDOUT_CAP,\n nodeHeapMb: bounds.heapMb,\n stdin: JSON.stringify(input),\n // NODE_ENV steers React's production vs development build — keep\n // parity with the caller; everything else stays on the sandbox's\n // default allowlist.\n env: { NODE_ENV: process.env.NODE_ENV ?? 'production' },\n });\n\n const hostLoad: ProbeHostLoad = {\n start: loadAtStart,\n end: loadavg()[0] ?? 0,\n cores: availableParallelism(),\n };\n const mapped = mapSandboxResultToCheckResult(result, t0, bounds.timeoutMs);\n return { ...mapped, stats: { ...mapped.stats, hostLoad } };\n}\n","// packages/ui-gen/src/harness/check/runtime-render/production-act-shim.ts\n//\n// Minimal adaptation to two upstream constraints, neither of which\n// this package controls:\n//\n// 1. React intentionally strips `act` from its PRODUCTION build.\n// `react/cjs/react.production.js` does not export it — only the\n// development build does (`typeof require('react').act` is\n// `'function'` under a dev build, `undefined` under production).\n// 2. `@testing-library/react`'s `act-compat` module hard-requires\n// `act` at MODULE SCOPE: it snapshots\n// `typeof React.act === 'function' ? React.act : DeprecatedReactTestUtils.act`\n// into a `const` the first time it is imported in the process.\n// Under a production build, that snapshot resolves to React\n// DOM's `react-dom/test-utils` production `act` stub, which\n// THROWS `React.act is not a function` the moment it is called.\n//\n// Hosts that run this probe inside a production Node process\n// (server-side blueprint validation) hit this: every render throws\n// through RTL's `act` wrapper before the probe ever sees the\n// component. Hosts that run it under a development/test build (every\n// CI/vitest run in this repo — `NODE_ENV=test` resolves the dev\n// build) never see it; `act` is real there and this shim is a no-op.\n//\n// **Load-order constraint**: this MUST run before the FIRST import of\n// `@testing-library/react` anywhere in the process — act-compat binds\n// its `act` reference into a module-scope `const` at import time, so\n// patching `react-dom/test-utils` AFTER that import has already\n// happened does nothing (the snapshot already captured the broken\n// stub). Patch `react-dom/test-utils`, never `react` itself — that\n// entry point is deprecated and test-only, so this patch cannot\n// perturb any production rendering path; nothing else in a server\n// process legitimately imports it.\n//\n// `createRequire` (not `import`) reaches these modules deliberately:\n// ESM namespace objects are frozen, so a normal `import` gives no way\n// to mutate `act` on it. The CJS `module.exports` objects `require`\n// resolves are mutable, and RTL's act-compat interop-copies THAT\n// object's properties at its own load time — so mutating it here,\n// before RTL loads, is what makes the patch visible to RTL at all.\n\nimport { createRequire } from \"node:module\";\n\nlet installed = false;\n\n/**\n * The one property this module reads/mutates on `react` and\n * `react-dom/test-utils`'s CJS exports. A minimal local shape rather\n * than the real (deprecated, possibly absent) type declarations for\n * `react-dom/test-utils` — narrow enough to type-check the mutation\n * without `as any` / `Record<string, unknown>`.\n */\ninterface MutableActCarrier {\n act?: unknown;\n}\n\n/** The one React DOM export this module needs — typed narrowly for the same reason. */\ninterface FlushSyncCarrier {\n flushSync: (fn: () => void) => void;\n}\n\n/**\n * Patch `react-dom/test-utils`'s `act` with a `flushSync`-backed\n * replacement, but ONLY when the current process is running React's\n * production build (no real `act` exported). Idempotent — safe to\n * call more than once or from more than one call site; the actual\n * patch only ever applies once per process.\n *\n * No-op (by design, not by accident) whenever `react`'s own `act`\n * export is a real function — every dev/test build, including every\n * vitest run in this repo. This shim changes zero behavior in CI.\n */\nexport function installProductionActShim(): void {\n if (installed) return;\n installed = true;\n\n const require_ = createRequire(import.meta.url);\n\n let reactCjs: MutableActCarrier;\n try {\n reactCjs = require_(\"react\");\n } catch {\n // React itself isn't resolvable in this process — the probe\n // surfaces its own load error; nothing for this shim to patch.\n return;\n }\n\n if (typeof reactCjs.act === \"function\") {\n // Dev/test builds export a real `act` — strict no-op.\n return;\n }\n\n try {\n const testUtils: MutableActCarrier = require_(\"react-dom/test-utils\");\n const reactDom: FlushSyncCarrier = require_(\"react-dom\");\n testUtils.act = createFlushSyncAct(reactDom.flushSync);\n } catch {\n // Frozen/locked exports (or a react-dom build without flushSync)\n // — leave it. The probe then surfaces the raw upstream error,\n // which is the pre-fix behavior: an honest failure, not a\n // silently-broken patch.\n }\n}\n\n/**\n * Build an `act`-compatible replacement backed by `flushSync`, which\n * — unlike `act` — DOES exist in React's production build.\n *\n * `flushSync` is the single property this shim relies on from dev\n * `act`: it forces the scheduled render to commit SYNCHRONOUSLY\n * before returning, so a render throw propagates synchronously to the\n * caller and the DOM is fully committed by the time this resolves.\n *\n * Returned function is act-style: if the callback itself returned a\n * thenable (RTL's async act-wrapped interactions), the result\n * resolves once that thenable settles (rejecting on its rejection);\n * otherwise it resolves after one microtask, mirroring `act`'s own\n * \"flush the microtask queue\" contract for the synchronous case.\n *\n * **Known, documented delta vs. a real dev `act`**: passive effects\n * (`useEffect`) flush on a LATER task under `flushSync`, not\n * synchronously at act-exit — `flushSync` only guarantees the\n * synchronous commit, not effect flushing. The probe's uncaught-error\n * handlers plus its 100ms teardown grace window (`render-check.ts`'s\n * `cleanupAsyncInfra`) already cover a late effect throwing after this\n * resolves, so this delta does not reopen the crash class the probe\n * exists to catch.\n *\n * Exported separately so the flushSync/thenable semantics are unit\n * testable without a real React runtime.\n */\nexport function createFlushSyncAct(\n flushSync: (fn: () => void) => void,\n): (callback: () => unknown) => Promise<void> {\n return (callback: () => unknown): Promise<void> => {\n let callbackResult: unknown;\n flushSync(() => {\n callbackResult = callback();\n });\n if (isThenable(callbackResult)) {\n const pending = callbackResult;\n return new Promise<void>((resolve, reject) => {\n pending.then(() => resolve(), reject);\n });\n }\n return new Promise<void>((resolve) => {\n queueMicrotask(resolve);\n });\n };\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n","// packages/ui-gen/src/harness/check/runtime-render/probe.ts\n//\n// Probe — captures wire-surface activity for runtime render evaluation.\n//\n// Design:\n//\n// We do NOT mirror @ggui-ai/wire's hooks. The hooks already route\n// entirely through WireContext (dispatch / subscribe). So we just\n// provide a probe-backed WireConfig to the real GguiWireProvider.\n// The real hooks run; only the underlying primitives are intercepted.\n//\n// Wins:\n// - no parallel hook implementation to maintain\n// - no esbuild aliasing\n// - hook semantics stay faithful to production\n// - stream re-renders flow through the real useStream's React update path\n//\n// The Probe object is shared in two scopes:\n// - Inside the React tree, via the WireConfig captured from createProbeWireConfig()\n// - Outside the React tree, via the same Probe reference held by the test runner\n//\n// Tests use the outside reference to:\n// - emitStream(name, payload) → invokes captured subscribers, real useStream re-renders\n// - inspect getFireLog() / getRegistered() to verify wiring\n\nimport type { WireConfig } from \"@ggui-ai/wire\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event log shape\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActionFiredEvent {\n readonly kind: \"action.fired\";\n readonly name: string;\n readonly payload?: unknown;\n readonly ts: number;\n}\n\n/**\n * A `ui/open-link` envelope was emitted toward the parent — fired when\n * the iframe-runtime's anchor interceptor catches an external link\n * click and routes through the host. CHECK tier observes this when\n * the generated component renders a plain `<a href=\"https://...\">`.\n */\nexport interface LinkOpenedEvent {\n readonly kind: \"link.opened\";\n readonly url: string;\n readonly ts: number;\n}\n\n/**\n * A `ui/request-display-mode` envelope was emitted toward the parent\n * — fired when the iframe-runtime's native-API interceptor catches\n * a `requestFullscreen()` / `exitFullscreen()` call and routes it\n * through the host.\n */\nexport interface DisplayModeRequestedEvent {\n readonly kind: \"displayMode.requested\";\n readonly mode: string;\n readonly ts: number;\n}\n\nexport type ProbeEvent =\n | ActionFiredEvent\n | LinkOpenedEvent\n | DisplayModeRequestedEvent;\n\nexport interface RegisteredHooks {\n /** Stream event names that received at least one subscribe() call. */\n readonly streams: readonly string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Probe interface\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface Probe {\n // ── Inputs (test → component) ──────────────────────────────────────────\n /** Push a stream event payload. Calls all current subscribers for `eventName`. */\n emitStream<T = unknown>(eventName: string, payload: T): void;\n\n // ── Observations (read after interaction) ──────────────────────────────\n getFireLog(): readonly ProbeEvent[];\n getRegistered(): RegisteredHooks;\n /** Convenience: did any action.fired event match this name? */\n fired(actionName: string): boolean;\n\n // ── Lifecycle ──────────────────────────────────────────────────────────\n /**\n * Install a spy on `window.parent.postMessage` so envelopes emitted\n * by the iframe-runtime interceptors (anchor click → `ui/open-link`,\n * `requestFullscreen()` → `ui/request-display-mode`) are recorded\n * into the probe's fire log. Returns an uninstall function.\n *\n * Safe to call multiple times — each call replaces the previous spy.\n * The render-check harness installs the spy at render boot and\n * uninstalls during teardown.\n */\n installPostMessageSpy(): () => void;\n reset(): void;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal state — held as closures in the Probe instance for isolation\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface ProbeInternals {\n fireLog: ProbeEvent[];\n streamHandlers: Map<string, Set<(d: unknown) => void>>;\n registeredStreams: Set<string>;\n}\n\nfunction makeInternals(): ProbeInternals {\n return {\n fireLog: [],\n streamHandlers: new Map(),\n registeredStreams: new Set(),\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// createProbe()\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function createProbe(): Probe & {\n /** @internal — used by createProbeWireConfig to share state. Do not call from tests. */\n __internals: ProbeInternals;\n} {\n let internals = makeInternals();\n\n const probe: Probe & { __internals: ProbeInternals } = {\n emitStream: <T>(eventName: string, payload: T): void => {\n const handlers = internals.streamHandlers.get(eventName);\n if (!handlers) return;\n for (const handler of handlers) handler(payload);\n },\n\n getFireLog: (): readonly ProbeEvent[] => internals.fireLog.slice(),\n\n getRegistered: (): RegisteredHooks => ({\n streams: Array.from(internals.registeredStreams),\n }),\n\n fired: (actionName: string): boolean =>\n internals.fireLog.some(e => e.kind === \"action.fired\" && e.name === actionName),\n\n installPostMessageSpy: (): (() => void) => installPostMessageSpy(probe),\n\n reset: (): void => {\n internals = makeInternals();\n // Mutate __internals reference too so existing wire config still sees fresh state.\n probe.__internals = internals;\n },\n\n __internals: internals,\n };\n\n return probe;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// postMessage spy — observes envelopes emitted by the iframe-runtime\n// interceptors (anchor click, requestFullscreen). The renderer's\n// WireConfig still funnels into the probe via the closure-shared\n// internals; this spy is the parallel observation channel for\n// envelope-layer effects that bypass WireConfig.\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface JsonRpcEnvelope {\n readonly jsonrpc?: unknown;\n readonly method?: unknown;\n readonly params?: unknown;\n}\n\nfunction installPostMessageSpy(\n probe: Probe & { __internals: ProbeInternals },\n): () => void {\n // happy-dom: window.parent === window in the default test setup, so the\n // helpers' calls to `window.parent.postMessage` land on this same surface.\n // Probe state is held in the closure over `probe.__internals` so calls\n // from inside the React tree write to the same fire log the tests read.\n const parent = (globalThis as { window?: { parent?: { postMessage?: unknown } } }).window?.parent;\n if (!parent || typeof parent.postMessage !== \"function\") {\n // No parent surface to spy on — return a noop uninstaller. The probe\n // still observes WireConfig-layer events (dispatch, etc.).\n return () => {};\n }\n const original = parent.postMessage;\n const spy = (...args: unknown[]): unknown => {\n const envelope = args[0];\n recordEnvelope(probe.__internals, envelope);\n // Forward to the original so happy-dom's own postMessage semantics\n // (queueing, dispatch) keep working — the spy is observation-only.\n return (original as (...a: unknown[]) => unknown).apply(parent, args);\n };\n try {\n Object.defineProperty(parent, \"postMessage\", {\n value: spy,\n configurable: true,\n writable: true,\n });\n } catch {\n // Locked-down host runtime — give up silently. The probe still sees\n // WireConfig-layer events.\n return () => {};\n }\n return () => {\n try {\n Object.defineProperty(parent, \"postMessage\", {\n value: original,\n configurable: true,\n writable: true,\n });\n } catch {\n /* ignore */\n }\n };\n}\n\nfunction recordEnvelope(internals: ProbeInternals, envelope: unknown): void {\n if (!envelope || typeof envelope !== \"object\") return;\n const e = envelope as JsonRpcEnvelope;\n if (typeof e.method !== \"string\") return;\n const params = (e.params ?? {}) as Record<string, unknown>;\n\n switch (e.method) {\n case \"ui/open-link\": {\n const url = typeof params.url === \"string\" ? params.url : \"\";\n internals.fireLog.push({\n kind: \"link.opened\",\n url,\n ts: Date.now(),\n });\n return;\n }\n case \"ui/request-display-mode\": {\n const mode = typeof params.mode === \"string\" ? params.mode : \"\";\n internals.fireLog.push({\n kind: \"displayMode.requested\",\n mode,\n ts: Date.now(),\n });\n return;\n }\n case \"tools/call\": {\n // The only tools/call with a legitimate emitter is the audit\n // envelope (`ggui_runtime_submit_action`), and WireConfig.dispatch\n // already records its paired `action.fired` — nothing to record\n // here. The runtime never fires any other tool from the iframe:\n // every action rides the consume buffer and the agent invokes\n // tools on its own turn.\n return;\n }\n default:\n // Unrecognized envelope — ignore. New methods get explicit handling\n // when added to the protocol; silent fall-through is fine for now.\n return;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// createProbeWireConfig() — produces a WireConfig that funnels into the Probe\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Build a WireConfig backed by the given Probe. Use as the `config` prop of\n * GguiWireProvider in render-check tests.\n *\n * The WireConfig holds a closure over `probe.__internals` so that calls from\n * inside the React tree (via the real useAction/useStream/etc. hooks) flow\n * straight into the same probe state the test inspects from outside.\n */\nexport function createProbeWireConfig(\n probe: Probe & { __internals: ProbeInternals },\n): WireConfig {\n return {\n app: {\n appId: \"probe-app\",\n appName: \"Probe\",\n appDescription: \"Eval-time probe wire config\",\n },\n render: {\n sessionId: \"probe-render\",\n isConnected: true,\n },\n auth: {\n isAuthenticated: false,\n },\n\n dispatch: <T = unknown>(actionName: string, data: T): void => {\n probe.__internals.fireLog.push({\n kind: \"action.fired\",\n name: actionName,\n payload: data,\n ts: Date.now(),\n });\n },\n\n subscribe: <T = unknown>(eventType: string, handler: (data: T) => void): (() => void) => {\n probe.__internals.registeredStreams.add(eventType);\n let set = probe.__internals.streamHandlers.get(eventType);\n if (!set) {\n set = new Set();\n probe.__internals.streamHandlers.set(eventType, set);\n }\n const wrapped = handler as (d: unknown) => void;\n set.add(wrapped);\n return () => {\n set!.delete(wrapped);\n };\n },\n\n // The WireConfig surface is dispatch + subscribe only. Capability\n // hooks live in `@ggui-ai/gadgets` and own their own lifecycle —\n // they never route through WireConfig.\n };\n}\n","// packages/ui-gen/src/internal/evaluate-component-source.ts\n//\n// The ONE compile-and-evaluate helper for component source: esbuild\n// TSX→CJS transform + vm.Script in-context execution behind a\n// caller-supplied `require`. Consumed by:\n//\n// - `tools/render-check-worker.ts` — the subprocess render smoke\n// test (host isolation lives at the spawn layer, in the parent's\n// `tryRender` via `@ggui-ai/sandbox`).\n// - `harness/check/runtime-render/load-component.ts` — the in-loop\n// probe (single-realm React; caller injects module resolutions).\n//\n// The module-resolution POLICY is deliberately not shared — each\n// caller owns its own `require` shim (allowed specifiers, fallbacks,\n// error wording). What is shared is the mechanical eval pipeline:\n//\n// 1. esbuild.transform(source) → CJS\n// 2. wrap in `(function(require, exports, module) { ... })`\n// 3. vm.Script(...).runInThisContext()\n// 4. call with the caller's require + a fresh module object\n// 5. return `module.exports` read AFTER execution — esbuild's CJS\n// output REPLACES `module.exports` (`module.exports =\n// __toCommonJS(...)`), so the initial reference can't be trusted.\n\nexport async function evaluateComponentSource(\n sourceCode: string,\n sandboxRequire: (id: string) => unknown,\n): Promise<Record<string, unknown>> {\n const esbuild = await import(\"esbuild\");\n const { Script } = await import(\"node:vm\");\n\n const cjsResult = await esbuild.transform(sourceCode, {\n loader: \"tsx\",\n target: \"es2020\",\n format: \"cjs\",\n jsx: \"automatic\",\n jsxImportSource: \"react\",\n sourcefile: \"Component.tsx\",\n });\n\n const sandboxModule: { exports: Record<string, unknown> } = { exports: {} };\n\n const wrappedCode = `(function(require, exports, module) {\\n${cjsResult.code}\\n})`;\n const script = new Script(wrappedCode, { filename: \"Component.cjs\" });\n const fn = script.runInThisContext() as (\n require: (id: string) => unknown,\n exports: Record<string, unknown>,\n module: { exports: Record<string, unknown> },\n ) => void;\n\n fn(sandboxRequire, sandboxModule.exports, sandboxModule);\n\n return sandboxModule.exports;\n}\n","// packages/ui-gen/src/harness/check/runtime-render/load-component.ts\n//\n// Eval a compiled component source string into a real React component reference.\n//\n// The mechanical compile+vm pipeline is the shared\n// `evaluateComponentSource` helper (also used by the render-smoke\n// subprocess worker); this module owns the in-loop probe's\n// module-resolution POLICY — a sandboxed require() that resolves:\n// - caller-injected `moduleResolutions` first (single-realm React)\n// - react / react/jsx-runtime → real react\n// - react-dom/* → real react-dom\n// - @ggui-ai/wire → REAL wire package (we want real useAction etc.,\n// the probe is injected via WireConfig at provider level)\n// - @ggui-ai/design/* → real design package\n// then plucks `module.exports.default` as the Component.\n//\n// Why we evaluate sourceCode (not the pre-compiled bundle): the test runner\n// already has sourceCode handy, and re-compiling guarantees a CJS shape\n// the vm sandbox can run without ESM module-record juggling.\n\nimport type { ComponentType } from \"react\";\nimport { evaluateComponentSource } from \"../../../internal/evaluate-component-source.js\";\n\nexport interface LoadComponentInput {\n /** The TSX source the agent emitted. We re-transform it to CJS. */\n readonly sourceCode: string;\n /**\n * Pre-resolved module instances to inject into the sandbox. CRITICAL:\n * the caller must pass the SAME React + wire instances they use outside\n * the sandbox — otherwise React context lookups fail (different React\n * realms have different dispatchers and contexts).\n *\n * Required keys: 'react', 'react/jsx-runtime', '@ggui-ai/wire'.\n * Optional: 'react-dom', '@ggui-ai/design/*'.\n */\n readonly moduleResolutions?: Readonly<Record<string, unknown>>;\n}\n\nexport interface LoadComponentResult {\n readonly Component: ComponentType<Record<string, unknown>>;\n}\n\nexport async function loadComponent(input: LoadComponentInput): Promise<LoadComponentResult> {\n const { sourceCode, moduleResolutions = {} } = input;\n const { createRequire } = await import(\"module\");\n\n const require_ = createRequire(import.meta.url);\n\n const sandboxRequire = (id: string): unknown => {\n // 1. Caller-injected resolutions win — these guarantee single-realm\n // React + wire so context lookups work.\n if (id in moduleResolutions) return moduleResolutions[id];\n\n // 2. Fall back to Node require for the remaining standard externals.\n if (id === \"react/jsx-runtime\" || id === \"react/jsx-dev-runtime\") {\n return require_(\"react/jsx-runtime\");\n }\n if (id === \"react\") return require_(\"react\");\n if (id === \"react-dom\" || id.startsWith(\"react-dom/\")) {\n return require_(id);\n }\n if (id === \"@ggui-ai/wire\") return require_(\"@ggui-ai/wire\");\n if (id.startsWith(\"@ggui-ai/design\")) {\n try {\n return require_(id);\n } catch {\n throw new Error(\n `Required dependency not available in render-check sandbox: ${id}. ` +\n `Install @ggui-ai/design or run render-check from an environment that has it.`,\n );\n }\n }\n // `@ggui-ai/gadgets` is a first-class dependency for any component\n // that uses `clientCapabilities.gadgets`. The probe needs a real\n // implementation so the LLM's `useGeolocation()` call actually\n // resolves (Node's happy-dom doesn't carry the wrapper hooks\n // itself; this require pulls the npm package).\n if (id === \"@ggui-ai/gadgets\") {\n try {\n return require_(\"@ggui-ai/gadgets\");\n } catch {\n throw new Error(\n `Required dependency not available in render-check sandbox: ${id}. ` +\n `Install @ggui-ai/gadgets or pass it through moduleResolutions.`,\n );\n }\n }\n // Operator-registered wrapper packages — caller injects via\n // `moduleResolutions` (the (specifier, hooks) pairs the bench\n // commit declares in `commit.appGadgets`). If a wrapper is\n // referenced by source but not injected, fall through to the\n // standard \"import not allowed\" message — the upstream render path\n // would have rejected this contract before generation, so reaching\n // here is a test-fixture misconfiguration.\n throw new Error(`Import not allowed in render-check sandbox: ${id}`);\n };\n\n const exportsRecord = await evaluateComponentSource(sourceCode, sandboxRequire);\n\n const candidate = exportsRecord.default;\n if (typeof candidate !== \"function\") {\n throw new Error(\"Compiled component has no default-exported function\");\n }\n return { Component: candidate as ComponentType<Record<string, unknown>> };\n}\n","// packages/ui-gen/src/harness/check/runtime-render/find-wiring.ts\n//\n// Source-AST wiring detection.\n//\n// Given a component's TSX source and a hook reference (e.g., `useAction('save')`),\n// determine HOW the resulting callback is wired in JSX so the runtime probe knows\n// which trigger to simulate — instead of guessing by clicking everything.\n//\n// Rules:\n// - Handle ONE level of alias indirection:\n// const save = useAction('save');\n// const onSave = () => save(payload); // alias\n// <Button onClick={onSave} /> // alias used in JSX → click\n// - Be CONSERVATIVE on non-native props. Native event names are deterministic;\n// custom-component props (onValueChange, onSelect, onOpenChange) are NOT\n// guaranteed to fire on a synthetic click/change → return `unverified`.\n// - Anything we can't classify deterministically returns `unverified` with a\n// reason. NEVER pretend.\n//\n// Returns ONE detection object summarizing the strongest wiring found, plus\n// optional fallback hints. Callers use the kind to pick a simulator.\n\nimport ts from \"typescript\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type WiringKind =\n | \"click\" // wired as native onClick prop on a host element / role-button\n | \"submit\" // wired via onSubmit on a form, or button[type=submit]\n | \"change\" // wired via onChange on native select/input\n | \"keyboard-enter\" // wired via onKeyDown with Enter check\n | \"unverified\" // wiring exists but trigger style is non-deterministic\n | \"missing\"; // hook destructured but never referenced in JSX\n\nexport interface WiringDetection {\n readonly kind: WiringKind;\n /**\n * For `unverified`: human-readable reason (e.g., \"wired via Dropdown.onChange\",\n * \"wired into custom-component prop onValueChange\", \"wired into onDrop handler\").\n * For `missing`: brief explanation.\n * For verified kinds: optional element-locator hint (tag name, label).\n */\n readonly reason?: string;\n /**\n * Pure observational: the JSX element types the callback flows into.\n * Useful for richer feedback in the EvalIssue.\n */\n readonly observedJsxElements: readonly string[];\n /**\n * Native event prop names where we observed the callback (e.g., onClick, onSubmit).\n * Empty if only seen on non-native props.\n */\n readonly observedNativeProps: readonly string[];\n /**\n * Non-native event prop names where we observed it (e.g., onValueChange, onSelect).\n * Drives the unverified reason.\n */\n readonly observedCustomProps: readonly string[];\n}\n\nexport interface FindWiringInput {\n readonly sourceCode: string;\n /** \"useAction\" or \"useStream\" */\n readonly hookName: string;\n /** The hook's first-arg literal — the action/tool/event name. */\n readonly hookArg: string;\n}\n\n// Native DOM event props we can simulate deterministically.\nconst NATIVE_CLICK_PROPS = new Set([\"onClick\"]);\nconst NATIVE_SUBMIT_PROPS = new Set([\"onSubmit\"]);\nconst NATIVE_CHANGE_PROPS = new Set([\"onChange\"]);\nconst NATIVE_KEY_PROPS = new Set([\"onKeyDown\", \"onKeyUp\", \"onKeyPress\"]);\n\n// JSX element tags (lowercase) that count as host elements with native event behavior.\nconst HOST_CLICK_TAGS = new Set([\"button\", \"a\", \"div\", \"span\", \"li\", \"input\"]);\nconst HOST_CHANGE_TAGS = new Set([\"select\", \"input\", \"textarea\"]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public entry\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function findWiring(input: FindWiringInput): WiringDetection {\n const { sourceCode, hookName, hookArg } = input;\n\n const sf = ts.createSourceFile(\"Component.tsx\", sourceCode, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);\n\n // Step 1: find the destructured variable name from the hook call.\n // const save = useAction('save')\n // Returns the binding name(s) — multiple if the hook returns an object\n // destructure.\n const hookBindings = findHookBindings(sf, hookName, hookArg);\n if (hookBindings.length === 0) {\n return {\n kind: \"missing\",\n reason: `Hook ${hookName}('${hookArg}') is not destructured in the component`,\n observedJsxElements: [],\n observedNativeProps: [],\n observedCustomProps: [],\n };\n }\n\n // Step 2: collect every identifier that should \"count\" as a reference to the\n // hook's callable. This includes:\n // - The hook bindings themselves (e.g., `save`)\n // - One-level aliases: `const onSave = () => save(...); const onClick = save;`\n // → `onSave` and `onClick` count as references to `save`\n const callableNames = expandAliases(sf, hookBindings);\n\n // Step 3: scan JSX attributes. For each attribute whose value contains a\n // reference to any callableName, classify by attribute name + element kind.\n const observedJsxElements: string[] = [];\n const observedNativeProps: string[] = [];\n const observedCustomProps: string[] = [];\n\n let sawClickOnHost = false;\n let sawSubmitOnForm = false;\n let sawChangeOnNativeInput = false;\n let sawKeyOnAnything = false;\n let sawNonNativeProp = false;\n const customPropElements: string[] = [];\n const submitButton = { found: false };\n\n function visit(node: ts.Node): void {\n // <Tag attr={...} />\n if (ts.isJsxAttribute(node) && node.initializer) {\n const attrName = node.name.getText(sf);\n const initRefs = findReferencedNames(node.initializer, callableNames);\n if (initRefs.size > 0) {\n const parent = node.parent.parent; // JsxAttributes → opening element\n const tagName = getTagName(parent);\n if (tagName) observedJsxElements.push(tagName);\n const isHostTag = isHostElementTag(tagName ?? \"\");\n\n if (NATIVE_CLICK_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n if (isHostTag && (HOST_CLICK_TAGS.has((tagName ?? \"\").toLowerCase()) || tagName === \"button\")) {\n sawClickOnHost = true;\n } else {\n // onClick on a custom component (e.g., <Button>) — design-system\n // primitives may or may not forward to a real <button>. Treat as\n // host click for verification purposes — the boilerplate's\n // primitives forward onClick by convention. If they don't, the\n // probe just won't observe a fire and we'll downgrade.\n sawClickOnHost = true;\n }\n } else if (NATIVE_SUBMIT_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n if ((tagName ?? \"\").toLowerCase() === \"form\") sawSubmitOnForm = true;\n else sawSubmitOnForm = true; // wrapped form component still likely a form\n } else if (NATIVE_CHANGE_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n if (HOST_CHANGE_TAGS.has((tagName ?? \"\").toLowerCase())) {\n sawChangeOnNativeInput = true;\n } else {\n // onChange on a non-native (custom) component — Select/Dropdown\n // commonly use this name but their onChange is NOT triggered by\n // a synthetic 'change' event on a host element. Mark as custom.\n observedCustomProps.push(attrName);\n sawNonNativeProp = true;\n if (tagName) customPropElements.push(tagName);\n }\n } else if (NATIVE_KEY_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n sawKeyOnAnything = true;\n } else {\n // Custom prop — onValueChange, onSelect, onOpenChange, onDrop, etc.\n observedCustomProps.push(attrName);\n sawNonNativeProp = true;\n if (tagName) customPropElements.push(tagName);\n }\n }\n }\n\n // <button type=\"submit\"> implicitly submits its enclosing form\n if (ts.isJsxOpeningLikeElement(node)) {\n const tag = getTagName(node);\n if ((tag ?? \"\").toLowerCase() === \"button\") {\n const typeAttr = node.attributes.properties.find(\n p => ts.isJsxAttribute(p) && p.name.getText(sf) === \"type\",\n );\n if (typeAttr && ts.isJsxAttribute(typeAttr) && typeAttr.initializer) {\n const v = typeAttr.initializer.getText(sf).toLowerCase();\n if (v.includes(\"submit\")) submitButton.found = true;\n }\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n\n // Step 4: pick the strongest deterministic kind.\n // Order of preference matches \"what the user is most likely to actually do\":\n // click (most common) > submit > change > keyboard\n // Unverified wins over a deterministic kind only if NO native wiring was found.\n\n if (sawClickOnHost) {\n return wrapDetection(\"click\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n if (sawSubmitOnForm || submitButton.found) {\n return wrapDetection(\"submit\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n if (sawChangeOnNativeInput) {\n return wrapDetection(\"change\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n if (sawKeyOnAnything) {\n return wrapDetection(\"keyboard-enter\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n\n if (sawNonNativeProp) {\n const props = Array.from(new Set(observedCustomProps)).join(\", \");\n const tags = Array.from(new Set(customPropElements)).join(\", \");\n return {\n kind: \"unverified\",\n reason: `Source indicates non-click or non-native wiring; static probe did not verify execution deterministically. Callback flows into ${props} on <${tags}>.`,\n observedJsxElements: dedupe(observedJsxElements),\n observedNativeProps: dedupe(observedNativeProps),\n observedCustomProps: dedupe(observedCustomProps),\n };\n }\n\n // No JSX usage at all → hook is destructured but never referenced.\n return {\n kind: \"missing\",\n reason: `Hook ${hookName}('${hookArg}') is destructured but never referenced in any JSX attribute`,\n observedJsxElements: [],\n observedNativeProps: [],\n observedCustomProps: [],\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internals\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Find variable bindings produced by `hookName('hookArg')` calls.\n * const save = useAction('save') → ['save']\n * const { latest } = useStream('progress') → ['latest']\n */\nfunction findHookBindings(sf: ts.SourceFile, hookName: string, hookArg: string): string[] {\n const bindings: string[] = [];\n\n function visit(node: ts.Node): void {\n if (ts.isVariableDeclaration(node) && node.initializer && ts.isCallExpression(node.initializer)) {\n const call = node.initializer;\n const callee = call.expression.getText(sf);\n if (callee !== hookName) {\n ts.forEachChild(node, visit);\n return;\n }\n // First arg literal must match hookArg\n const firstArg = call.arguments[0];\n if (!firstArg || !ts.isStringLiteral(firstArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n if (firstArg.text !== hookArg) {\n ts.forEachChild(node, visit);\n return;\n }\n // Identify binding\n if (ts.isIdentifier(node.name)) {\n bindings.push(node.name.text);\n } else if (ts.isObjectBindingPattern(node.name)) {\n for (const elem of node.name.elements) {\n // const { call: doSearch } = ... → propName=call, name=doSearch\n // const { call } = ... → name=call\n const target = elem.name;\n if (ts.isIdentifier(target)) bindings.push(target.text);\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return bindings;\n}\n\n/**\n * Expand bindings with one-level aliases:\n * const save = useAction('save')\n * const onSave = () => save(payload) → onSave is alias for save\n * const handleClick = save → handleClick is alias for save\n *\n * Returns the set of identifier NAMES that should count as the hook's callable\n * (used by JSX scanner to detect references).\n */\nfunction expandAliases(sf: ts.SourceFile, bindings: string[]): Set<string> {\n const all = new Set<string>(bindings);\n\n function visit(node: ts.Node): void {\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isIdentifier(node.name)\n ) {\n const newName = node.name.text;\n const init = node.initializer;\n // Direct alias: const handleClick = save;\n if (ts.isIdentifier(init) && all.has(init.text)) {\n all.add(newName);\n }\n // Wrapper closure: const onSave = () => save(payload);\n if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {\n if (bodyReferences(init.body, all)) {\n all.add(newName);\n }\n }\n // Common React wrappers: useCallback(() => save(...), [...]) / useMemo(...)\n // Generalize: walk the entire initializer expression for hook references.\n // If found, the alias counts as a reference site.\n if (ts.isCallExpression(init)) {\n if (bodyReferences(init, all)) {\n all.add(newName);\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return all;\n}\n\nfunction bodyReferences(body: ts.Node, names: ReadonlySet<string>): boolean {\n let found = false;\n function walk(n: ts.Node): void {\n if (found) return;\n if (ts.isIdentifier(n) && names.has(n.text)) {\n found = true;\n return;\n }\n ts.forEachChild(n, walk);\n }\n walk(body);\n return found;\n}\n\n/**\n * Scan a JSX attribute initializer expression for any identifier name in `names`.\n * Returns the set of matching names found.\n */\nfunction findReferencedNames(node: ts.Node, names: ReadonlySet<string>): Set<string> {\n const found = new Set<string>();\n function walk(n: ts.Node): void {\n if (ts.isIdentifier(n) && names.has(n.text)) {\n found.add(n.text);\n }\n ts.forEachChild(n, walk);\n }\n walk(node);\n return found;\n}\n\nfunction getTagName(el: ts.Node): string | null {\n if (ts.isJsxOpeningLikeElement(el)) {\n return el.tagName.getText();\n }\n return null;\n}\n\nfunction isHostElementTag(name: string): boolean {\n // Lowercase first letter = host element (button, div, form, etc.)\n // Capitalized = React component\n if (!name) return false;\n return name[0] === name[0]!.toLowerCase();\n}\n\nfunction wrapDetection(\n kind: WiringKind,\n jsx: string[],\n native: string[],\n custom: string[],\n): WiringDetection {\n return {\n kind,\n observedJsxElements: dedupe(jsx),\n observedNativeProps: dedupe(native),\n observedCustomProps: dedupe(custom),\n };\n}\n\nfunction dedupe<T>(arr: readonly T[]): T[] {\n return Array.from(new Set(arr));\n}\n","// packages/ui-gen/src/internal/open-record.ts\n//\n// Single documented narrowing seam for \"object used as an open\n// string-keyed property bag\" — the host global object and happy-dom's\n// `Window` both genuinely ARE open records at runtime (we install /\n// restore named globals like `window` / `document` on them by key),\n// but TypeScript cannot express that without polluting the global type\n// space via declaration merging. Centralizing the one structural\n// widening here keeps every call site cast-free.\n\n/**\n * View an object as an open string-keyed record.\n *\n * Single structural widening (`Record<string, unknown>` is assignable\n * to `object`, so the cast is checked in one direction by tsc — no\n * `unknown` erasure). Returns the SAME reference: property writes land\n * on the live object.\n */\nexport function openRecord(o: object): Record<string, unknown> {\n return o as Record<string, unknown>;\n}\n\n/**\n * The host global object viewed as an open property bag.\n *\n * Used by the render-check pipeline (and its subprocess worker) to\n * install and restore DOM globals by name.\n */\nexport function hostGlobals(): Record<string, unknown> {\n return openRecord(globalThis);\n}\n","// packages/ui-gen/src/harness/check/runtime-render/host-boundary.ts\n//\n// The ONE narrowing seam between the render-check pipeline and its\n// host runtime: happy-dom elements, @testing-library/react containers,\n// and the @testing-library/user-event module. Each export is either a\n// runtime-validated guard (throws a descriptive error on violation) or\n// a single documented structural view (all-optional facet of the same\n// live object), so the check pipeline's call sites stay cast-free.\n//\n// Deliberately DOM-lib-free: some downstream tsconfigs (e.g.\n// cloud/amplify) exclude the DOM lib, so this module declares the\n// minimal structural surfaces it needs instead of importing\n// `HTMLElement` / `Element` types.\n\nimport { openRecord } from \"../../../internal/open-record.js\";\n\n/**\n * Minimal structural view of a rendered DOM element — the only element\n * surface the checks read.\n */\nexport interface MinimalElement {\n readonly tagName: string;\n readonly textContent: string | null;\n getAttribute(name: string): string | null;\n querySelectorAll<T extends MinimalElement = MinimalElement>(selector: string): Iterable<T>;\n}\n\n/** The one user-gesture surface the checks drive. */\nexport interface ClickUser {\n readonly click: (el: MinimalElement) => Promise<void>;\n}\n\n/**\n * All-optional form-control facet of an element. Used by the synthetic\n * change-value writer; absent properties are tolerated by all readers\n * and writers.\n */\nexport interface EditableSurface {\n value?: string;\n checked?: boolean;\n type?: string;\n options?: ArrayLike<{ value: string }>;\n}\n\n/** All-optional tree-climbing facet (closest-form lookup). */\nexport interface ParentLink {\n readonly tagName?: string;\n readonly parentNode?: unknown;\n}\n\n/** Look up a method on an arbitrary host object, bound to it. */\nfunction getMethod(\n o: unknown,\n name: string,\n): ((...args: unknown[]) => unknown) | undefined {\n if (typeof o !== \"object\" && typeof o !== \"function\") return undefined;\n if (o === null) return undefined;\n const v = openRecord(o)[name];\n if (typeof v !== \"function\") return undefined;\n return (v as (...args: unknown[]) => unknown).bind(o);\n}\n\n/**\n * Validating narrower: host element (RTL container, climbed parent\n * node) → {@link MinimalElement}. Throws when the value lacks the\n * element surface — a violation of the happy-dom/RTL boundary\n * contract, not a check failure.\n */\nexport function toMinimalElement(v: unknown): MinimalElement {\n if (\n typeof v === \"object\" &&\n v !== null &&\n typeof openRecord(v).tagName === \"string\" &&\n typeof openRecord(v).getAttribute === \"function\" &&\n typeof openRecord(v).querySelectorAll === \"function\"\n ) {\n // Runtime-checked above; the remaining gap (exact method\n // signatures) is the structural boundary this module owns.\n return v as MinimalElement;\n }\n throw new Error(\n \"[runtime-render] host value lacks the element surface (tagName/getAttribute/querySelectorAll)\",\n );\n}\n\n/**\n * Validating narrower over the `@testing-library/user-event` module:\n * prefers the v14 `setup()` instance, falls back to the module-level\n * `click` (pre-v14 shape). Throws when neither surface exists.\n *\n * `doc` MUST be the live document the probe rendered into, passed as\n * `setup({ document })`. user-event captures `globalThis.document` into\n * its module-scope setup defaults AT MODULE LOAD (v14 `setup.js`\n * `defaultOptionsSetup`), so a bare `setup()` binds whatever document\n * existed when the module was FIRST imported — `undefined` when the\n * import happened via `warmupRuntimeRenderProbe()` before any DOM was\n * up, which then crashes every later probe with \"Cannot read properties\n * of undefined (reading 'Symbol(Node prepared with document state\n * workarounds)')\" (ggui#403). The module-level `click` fallback derives\n * its document from the clicked node and doesn't need this.\n */\nexport function buildClickUser(userEventModule: unknown, doc: unknown): ClickUser {\n const setup = getMethod(userEventModule, \"setup\");\n const instance: unknown = setup ? setup({ document: doc }) : userEventModule;\n const click = getMethod(instance, \"click\");\n if (!click) {\n throw new Error(\n \"[runtime-render] user-event module exposes neither setup().click nor click()\",\n );\n }\n return {\n click: async (el: MinimalElement): Promise<void> => {\n await click(el);\n },\n };\n}\n\n/**\n * Validating narrower: element → its `dispatchEvent` surface. Returns\n * the live method (bound), so dispatch hits the real element.\n */\nexport function toEventDispatcher(el: MinimalElement): {\n dispatchEvent: (ev: Event) => void;\n} {\n const dispatch = getMethod(el, \"dispatchEvent\");\n if (!dispatch) {\n throw new Error(\n `[runtime-render] element <${el.tagName.toLowerCase()}> has no dispatchEvent`,\n );\n }\n return {\n dispatchEvent: (ev: Event): void => {\n dispatch(ev);\n },\n };\n}\n\n/**\n * View an element as its all-optional form-control facet. Returns the\n * SAME reference (writes must land on the live element); the facet is\n * all-optional, so every reader/writer already tolerates absence —\n * there is nothing to validate at runtime.\n */\nexport function editableSurface(el: object): EditableSurface {\n return el as EditableSurface;\n}\n\n/** View a host node as its all-optional tree-climbing facet. */\nexport function parentLink(node: object): ParentLink {\n return node as ParentLink;\n}\n","// packages/ui-gen/src/harness/check/runtime-render/render-check.ts\n//\n// Runtime render verification for compiled components.\n//\n// Pipeline:\n// 1. Spin up happy-dom globals (window/document/etc.)\n// 2. Eval compiled component → React component reference\n// 3. Render it inside <GguiWireProvider config={probeWireConfig}>\n// 4. Run 5 checks against probe + DOM\n// 5. Tear down DOM\n//\n// Block (fail outcome): render-no-throw, action-wiring\n// Warn outcome: prop-coverage, stream-rerender\n//\n// All checks are best-effort: if a heuristic can't find an element, the\n// check fails with a descriptive reason rather than throwing.\n\nimport type { RenderCheckHostOptions } from \"./render-check-host.js\";\nimport type { GenerationRuntimeProbeCheck } from \"@ggui-ai/mcp-server-core\";\nimport type { DataContract, JsonObject, PropsSpec } from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport { createProbe, createProbeWireConfig, type ActionFiredEvent, type Probe } from \"./probe.js\";\nimport { loadComponent } from \"./load-component.js\";\nimport { findWiring, type WiringDetection } from \"./find-wiring.js\";\nimport { installProductionActShim } from \"./production-act-shim.js\";\n// All happy-dom / RTL / user-event narrowing flows through the typed\n// host boundary (one set of structural interfaces + validating guards;\n// DOM-lib-free — some downstream packages, e.g. cloud/amplify, exclude\n// DOM from their tsconfig).\nimport {\n buildClickUser,\n editableSurface,\n parentLink,\n toEventDispatcher,\n toMinimalElement,\n type ClickUser,\n type MinimalElement,\n type ParentLink,\n} from \"./host-boundary.js\";\nimport { hostGlobals, openRecord } from \"../../../internal/open-record.js\";\nimport type { ProbeHostLoad } from \"../../../evaluation/types-public.js\";\nimport { primeInputs } from \"@ggui-ai/ui-visual-tester/prime-inputs\";\n\n/**\n * Module-namespace-shaped value injected into `loadComponent`'s\n * `moduleResolutions`. Structurally equivalent to\n * `@ggui-ai/iframe-runtime`'s `ModuleNamespace` (open record of\n * string keys → unknown) — declared locally so this module doesn't\n * take a dependency on the iframe-runtime package just for a type.\n */\ntype ProbeModuleNamespace = {\n readonly [key: string]: unknown;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Result types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * 3-state outcome. Internal to runtime-render.\n * The adapter maps this to existing EvalIssue shapes:\n * verified → no issue\n * failed → fail\n * unverified → warn\n * skipped → no issue\n */\nexport type CheckOutcome = \"verified\" | \"failed\" | \"unverified\" | \"skipped\";\n\n/**\n * The checks this probe runs, by name (ggui#1380). ONE union: the same\n * values a generation's metadata lists in `failChecks`\n * (`GenerationRuntimeProbeCheck` in `@ggui-ai/mcp-server-core`), declared\n * there and named here — the same pattern as `RuntimeProbeStatus`.\n */\nexport type RenderCheckKind = GenerationRuntimeProbeCheck;\n\n/**\n * Every {@link RenderCheckKind}, once, in the order the union declares them.\n * The order is the order a probe's `failChecks` lists the checks that failed,\n * so a render crash always reads first. `satisfies` refuses a kind outside\n * the union; the pin beside the adapter refuses a member missing here.\n */\nexport const RENDER_CHECK_KINDS = [\n \"render-no-throw\",\n \"prop-sensitivity\",\n \"action-wiring\",\n \"selection-identity\",\n \"prop-coverage\",\n \"optional-props-omitted\",\n \"stream-rerender\",\n] as const satisfies readonly RenderCheckKind[];\n\nexport interface RenderCheckIssue {\n readonly check: RenderCheckKind;\n readonly outcome: CheckOutcome;\n readonly subject?: string;\n readonly reason: string;\n /** Optional element description (\"button[aria-label='Save']\") for action-wiring failures. */\n readonly elementHint?: string;\n /**\n * Diagnostic context from probe + AST analysis. Populated for richer feedback\n * to the coding agent (which native props the callback flows into, what the\n * probe observed firing, etc.).\n */\n readonly diagnostics?: {\n readonly observedJsxElements?: readonly string[];\n readonly observedNativeProps?: readonly string[];\n readonly observedCustomProps?: readonly string[];\n /** For action-wiring: which actions DID fire from probe clicks (helps surface mis-wiring). */\n readonly actionsFiredFromClicks?: readonly string[];\n /** Surfaced to the agent: prop sourceTool hints from the contract (only if present). */\n readonly sourceToolHints?: Readonly<Record<string, string>>;\n /**\n * For action-wiring (ggui#1187): what input priming did before the\n * synthetic dispatch — how many controls it filled, or why it could not\n * run. A \"did not dispatch it\" on an input-gated action reads differently\n * beside `{ primed: 0 }` or `{ error }` than beside `{ primed: 1 }`.\n */\n readonly inputPriming?: InputPrimingDiagnostic;\n };\n}\n\n/**\n * Outcome of `primeInputs` before the action-wiring probe (ggui#1187). A\n * priming failure never aborts the check — it is recorded here, on every\n * action-wiring issue, so it is visible in the feedback instead of vanishing.\n */\nexport type InputPrimingDiagnostic = { readonly primed: number } | { readonly error: string };\n\n/**\n * The check started but did not finish (ggui#1299). The only kind is a\n * wall-clock timeout in the isolated worker. It is not a verdict on the\n * component: `issues` is empty and `ok` is false because nothing was\n * verified, never because something failed.\n */\nexport interface RenderCheckIncomplete {\n readonly kind: \"timeout\";\n /** How long the worker ran before it was stopped. */\n readonly elapsedMs: number;\n /** The wall-clock bound it crossed. */\n readonly boundMs: number;\n}\n\nexport interface RenderCheckResult {\n readonly ok: boolean;\n readonly issues: readonly RenderCheckIssue[];\n /** Present only when the check did not finish; see {@link RenderCheckIncomplete}. */\n readonly incomplete?: RenderCheckIncomplete;\n readonly stats: {\n readonly actionsChecked: number;\n readonly streamsChecked: number;\n readonly renderMs: number;\n /** Host load around an isolated check (absent in-process). */\n readonly hostLoad?: ProbeHostLoad;\n };\n}\n\nexport interface RunRenderCheckInput {\n readonly sourceCode: string;\n readonly mockupProps: JsonObject;\n readonly contract?: DataContract;\n}\n\n/**\n * Options of {@link runRenderCheck} (ggui#1380): the host's options —\n * `bounds` are the isolated subprocess's wall-clock, heap and grace (see\n * `RenderCheckHostBounds`); they apply to the worker path only and are\n * ignored in-process. One shape, declared once on the host.\n */\nexport type RunRenderCheckOptions = RenderCheckHostOptions;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public entry\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Run the in-loop runtime render check.\n *\n * Isolation dispatcher (#592): when the CALLING environment already\n * owns a DOM (`window` + `document` on `globalThis` — e.g. a vitest\n * `happy-dom` environment, where the environment owner installed the\n * globals deliberately), the check runs in-process exactly as before.\n * In a plain Node process it runs in an ISOLATED SUBPROCESS\n * (`render-check-host.ts` → `render-check-worker.ts`), because the\n * in-process path installs happy-dom globals on `globalThis`\n * process-wide — a TOCTOU hazard for anything that sniffs `window`\n * concurrently (provider SDKs throw \"browser-like environment\" at\n * client construction; two overlapping checks corrupt each other's\n * teardown). See #592 for the measured incident (4 bench cells hard-\n * failed on the 2026-08-19 run).\n *\n * The host is loaded lazily so the worker bundle (which imports this\n * module for `runRenderCheckInProcess`) never drags in the sandbox\n * spawn machinery.\n */\nexport async function runRenderCheck(\n input: RunRenderCheckInput,\n options: RunRenderCheckOptions = {}\n): Promise<RenderCheckResult> {\n const g = hostGlobals();\n if (\"window\" in g && \"document\" in g) {\n // In-process: nothing to bound — the check shares the caller's process.\n return runRenderCheckInProcess(input);\n }\n const { runRenderCheckViaWorker } = await import(\"./render-check-host.js\");\n return runRenderCheckViaWorker(input, options);\n}\n\n/**\n * The actual check, executed IN THE CURRENT PROCESS — installs\n * happy-dom globals on `globalThis` for the duration when the\n * environment doesn't already provide a DOM. Call sites outside this\n * module should use {@link runRenderCheck}; this export exists for the\n * isolation worker (which IS the private process the globals may own)\n * and for DOM-owning test environments that want to bypass the\n * dispatcher explicitly.\n */\nexport async function runRenderCheckInProcess(\n input: RunRenderCheckInput\n): Promise<RenderCheckResult> {\n const t0 = Date.now();\n const issues: RenderCheckIssue[] = [];\n\n // ── Stand up happy-dom ────────────────────────────────────────────────\n const teardown = await setupHappyDom();\n // Probe-spy uninstaller — set when the postMessage spy is installed\n // (after probe + happy-dom are both ready). Cleared in the outer\n // finally so early-return paths from probe-pre or probe-post don't\n // leak the spy into the next runRenderCheck invocation.\n let uninstallSpy: (() => void) | undefined;\n // Gadget stub-registry uninstaller — `globalThis.__ggui__` is a\n // process global, so it MUST be torn down in the outer finally.\n let uninstallGadgetRegistry: (() => void) | undefined;\n\n try {\n // ── Pre-resolve modules ONCE so the sandbox + test share one realm ──\n // (React contexts + dispatchers are per-instance — passing the same\n // instances into the sandbox is what makes useContext lookups work.)\n // The @ggui-ai/design package is ESM-only — must use dynamic import\n // (createRequire's CJS require fails on ESM-only packages).\n const React = await import(\"react\");\n const ReactJsxRuntime = await import(\"react/jsx-runtime\");\n const Wire = await import(\"@ggui-ai/wire\");\n const { GguiWireProvider } = Wire;\n\n const moduleResolutions: Record<string, unknown> = {\n react: React,\n \"react/jsx-runtime\": ReactJsxRuntime,\n \"@ggui-ai/wire\": Wire,\n };\n\n // Pre-load the @ggui-ai/design specifiers the boilerplate may import.\n // Post-D1, generated code imports the single bare `@ggui-ai/design`\n // barrel — that MUST be pre-resolved here: the package is ESM-only\n // with no `require` export condition, so `loadComponent`'s\n // `createRequire` fallback cannot load it (it would crash:fail the\n // render check). The subpaths stay for any legacy/first-party code.\n // Per-specifier failures are swallowed — the sandbox throws its own\n // clear error if the component actually needs a missing one.\n const designSpecifiers = [\n \"@ggui-ai/design\",\n \"@ggui-ai/design/primitives\",\n \"@ggui-ai/design/components\",\n \"@ggui-ai/design/compositions\",\n \"@ggui-ai/design/interact\",\n ];\n for (const id of designSpecifiers) {\n try {\n moduleResolutions[id] = await import(id);\n } catch {\n /* skip — sandbox will report a clear error if the component imports it */\n }\n }\n\n // Pre-load `@ggui-ai/gadgets` for components that declare\n // `clientCapabilities.gadgets`. The standard-library hooks\n // (useGeolocation, useCamera, …) live in this package; without it\n // pre-resolved here, the sandbox falls back to `require()` which\n // fails when the caller package doesn't have `@ggui-ai/gadgets` as\n // a direct dep. Swallow on miss —\n // same posture as design subpaths above.\n try {\n moduleResolutions[\"@ggui-ai/gadgets\"] = await import(\"@ggui-ai/gadgets\");\n } catch {\n /* skip — sandbox will report a clear error if the component imports it */\n }\n\n // Install a stub per-package `globalThis.__ggui__.gadgets`\n // registry so direct gadget imports resolve at component-render\n // time. Without it, every gadget-bearing component false-fails\n // `render-no-throw`. `loadGadgets()` is retired —\n // component code direct-imports each gadget export.\n uninstallGadgetRegistry = installGadgetStubRegistry(input.contract);\n\n // Register a CJS shim module for each third-party gadget package\n // the contract declares. The probe re-compiles the\n // component to CJS, so a direct `import { useLeafletMap } from\n // '@ggui-samples/gadget-leaflet'` becomes `require('@ggui-samples/\n // gadget-leaflet')`. The wrapper package itself is not installed\n // in the probe's node_modules — without a shim, `loadComponent`'s\n // sandboxRequire throws \"Import not allowed\". Each shim is a\n // module namespace whose hook exports read the stub registry's\n // per-package slot LAZILY at call time (the slot is populated by\n // `installGadgetStubRegistry` above). `@ggui-ai/gadgets` (STDLIB)\n // is excluded — its real hooks are pre-loaded above and run\n // standalone (they don't read the registry).\n for (const pkg of collectThirdPartyGadgetPackages(input.contract)) {\n if (pkg in moduleResolutions) continue;\n moduleResolutions[pkg] = buildGadgetPackageProbeShim(pkg);\n }\n\n // ── Eval compiled component ─────────────────────────────────────────\n let Component: Awaited<ReturnType<typeof loadComponent>>[\"Component\"];\n try {\n const loaded = await loadComponent({\n sourceCode: input.sourceCode,\n moduleResolutions,\n });\n Component = loaded.Component;\n } catch (e) {\n issues.push({\n check: \"render-no-throw\",\n outcome: \"failed\",\n reason: `Failed to load component: ${e instanceof Error ? e.message : String(e)}`,\n });\n return finalize(issues, t0, 0, 0);\n }\n\n // ── Build probe + wire config ───────────────────────────────────────\n const probe = createProbe();\n const wireConfig = createProbeWireConfig(probe);\n\n // Install the postMessage spy AFTER happy-dom is up so window.parent\n // exists. The spy observes envelopes emitted by the iframe-runtime\n // interceptors (anchor → ui/open-link, requestFullscreen →\n // ui/request-display-mode). WireConfig-layer events (dispatch,\n // subscribe) continue to flow through the closure-shared probe\n // internals.\n uninstallSpy = probe.installPostMessageSpy();\n\n // Must run before RTL's first import in this process — see\n // production-act-shim.ts's docstring for why.\n installProductionActShim();\n const { render, cleanup } = await import(\"@testing-library/react\");\n // user-event v14 default export — see https://testing-library.com/docs/user-event/intro/\n const userEventModule = await import(\"@testing-library/user-event\");\n const userEvent = userEventModule.default ?? userEventModule;\n\n // ── Install console.error spy to break infinite render loops ─────────\n // React logs \"Maximum update depth exceeded\" when setState-in-effect\n // loops (>~25-50 re-renders). Without a break, happy-dom keeps looping\n // until something else stops the process. We hook console.error and\n // throw from within the spy so the render() call's catch-block runs.\n //\n // This catches the dominant hang class (useEffect-dep loop) upstream\n // of the probe wall-clock guard. Also catches \"Too many re-renders\"\n // (React's alternate message) and \"Each child in a list\" (not a\n // hang, but a clear generation bug) — any of these classify as a\n // runtime-loop failure instead of a 12-minute CPU spin.\n const originalConsoleError = console.error;\n let loopSignature: string | null = null;\n // Capture React's component-stack frames when a render error occurs.\n // React 19 logs them via console.error in the form:\n // \"%s\\n\\nThe above error occurred in the <%s> component:\\n%s\\n...\"\n // The 4th argument is the component-stack string (\" at SurveyForm\n // (...) \\n at FormProvider (...) \\n...\"). We capture it so the\n // probe's \"Render threw\" diagnostic can name the offending component.\n let capturedComponentStack: string | null = null;\n const loopPatterns: ReadonlyArray<readonly [RegExp, string]> = [\n [/Maximum update depth exceeded/i, \"max-update-depth\"],\n [/Too many re-renders/i, \"too-many-renders\"],\n [/Rendered more hooks than during the previous render/i, \"hook-count-drift\"],\n ];\n console.error = (...args: unknown[]) => {\n const text = args.map((a) => (typeof a === \"string\" ? a : \"\")).join(\" \");\n // Capture component-stack FIRST (independent of throw decision).\n // Loop-class messages from React 18/19 often include the component\n // stack as a separate arg even on the same call (\"Maximum update\n // depth exceeded\\n at Component (...)\"). If we throw before\n // capture, the loop-class diagnostic is left without component\n // localization (the dominant pre-fix gap).\n if (!capturedComponentStack) {\n // Try to find any arg that looks like a \" at X (...)\" stack.\n for (const arg of args) {\n if (typeof arg === \"string\" && /^\\s*at\\s+\\S/m.test(arg) && arg.length > 20) {\n capturedComponentStack = arg;\n break;\n }\n }\n // Fallback: extract embedded \" at\" lines from the joined text.\n if (!capturedComponentStack) {\n const stackMatch = text.match(/(?:^|\\n)((?:\\s*at\\s+\\S[^\\n]*\\n?){2,})/);\n if (stackMatch) {\n capturedComponentStack = stackMatch[1].trim();\n }\n }\n }\n for (const [pattern, tag] of loopPatterns) {\n if (pattern.test(text)) {\n loopSignature = tag;\n // Throw synchronously — React's render stack unwinds, our\n // try/catch below catches the error, we classify cleanly.\n throw new Error(`[runtime-render] infinite render loop detected (${tag})`);\n }\n }\n // Forward non-matching errors to real console so they're visible.\n originalConsoleError.apply(console, args);\n };\n\n // Error boundary fallback for React's componentStack on synchronous\n // throws (e.g. \"Too many re-renders\"). React 19 throws this directly\n // without going through console.error, so the spy never sees it.\n // The boundary's getDerivedStateFromError + componentDidCatch fire\n // for every render error, sync or async, and componentDidCatch's\n // errorInfo.componentStack is the canonical React-named-component\n // chain. Stored in a closure variable read in the catch block below.\n // Use object container so TS narrowing follows property access (not\n // closure flow analysis, which can't see the componentDidCatch\n // mutation and would narrow these to `null` at the use site).\n const boundaryRef: { stack: string | null; error: Error | null } = {\n stack: null,\n error: null,\n };\n class ProbeErrorBoundary extends React.Component<\n { children: React.ReactNode },\n { caught: boolean }\n > {\n state = { caught: false };\n static getDerivedStateFromError(): { caught: boolean } {\n return { caught: true };\n }\n componentDidCatch(error: Error, errorInfo: { componentStack?: string }): void {\n if (errorInfo.componentStack && !boundaryRef.stack) {\n boundaryRef.stack = errorInfo.componentStack;\n }\n if (!boundaryRef.error) {\n boundaryRef.error = error;\n }\n }\n render(): React.ReactNode {\n if (this.state.caught) return null;\n return this.props.children;\n }\n }\n\n let renderResult: Awaited<ReturnType<typeof render>>;\n const RENDER_TIMEOUT_MS = 5000;\n try {\n // Promise.race safety net for async hangs (effect flushes, timers).\n // Synchronous hangs would block the event loop and the timer never\n // fires, but happy-dom effects are mostly microtask-scheduled so the\n // timeout is actually effective for ~95% of the hang cases.\n const renderPromise = Promise.resolve().then(() =>\n render(\n React.createElement(GguiWireProvider, {\n config: wireConfig,\n children: React.createElement(ProbeErrorBoundary, {\n children: React.createElement(Component, input.mockupProps),\n }),\n })\n )\n );\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(\n () =>\n reject(\n new Error(\n `[runtime-render] render exceeded ${RENDER_TIMEOUT_MS}ms — classified as runtime-hang`\n )\n ),\n RENDER_TIMEOUT_MS\n ).unref?.();\n });\n renderResult = await Promise.race([renderPromise, timeoutPromise]);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n const errStack = e instanceof Error ? (e.stack ?? \"\") : \"\";\n const baseReason = loopSignature\n ? `Infinite render loop (${loopSignature}) — likely setState/dispatch inside useEffect with missing or unstable dependency`\n : /runtime-hang/.test(msg)\n ? `Render wall-clock exceeded ${RENDER_TIMEOUT_MS}ms — likely async effect loop or unresolved promise`\n : `Render threw: ${msg}`;\n // Localization context for the LLM. Two complementary signals:\n // 1. JS error.stack — top frames from the throw site. Filter to\n // user-code lines (drop happy-dom / RTL / React internals)\n // so the most relevant frame is on top. The bundled output is\n // minified but esbuild keeps line numbers (`keepNames: true`),\n // so frames usually pinpoint a region of the source the LLM\n // can patch.\n // 2. React componentStack — captured via console.error spy when\n // React logs \"above error occurred in the X component\". Names\n // the failing component; on multi-component renders this is\n // the difference between \"find the bad iteration\" and \"look in\n // <SurveyStep>\". Cap to keep prompt budget bounded.\n const userFrames = errStack\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"at \"))\n .filter(\n (l) =>\n !/(node_modules|happy-dom|@testing-library|react-dom|node:internal|node:async)/.test(l)\n )\n .slice(0, 5);\n // Prefer the ErrorBoundary-captured stack (richer + names component\n // wrappers like memo/forwardRef), fall back to the spy-captured one.\n const stackSource = boundaryRef.stack ?? capturedComponentStack ?? \"\";\n const componentFrames = stackSource\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"at \"))\n .slice(0, 4);\n const stackBlock = userFrames.length\n ? `\\n Stack (user frames): ${userFrames.join(\" | \")}`\n : \"\";\n const componentBlock = componentFrames.length\n ? `\\n Component stack: ${componentFrames.join(\" > \")}`\n : \"\";\n const loopReason = `${baseReason}${stackBlock}${componentBlock}`;\n issues.push({\n check: \"render-no-throw\",\n outcome: \"failed\",\n reason: loopReason,\n });\n console.error = originalConsoleError;\n return finalize(issues, t0, 0, 0);\n }\n console.error = originalConsoleError;\n\n // ErrorBoundary caught a crash even though render() didn't throw.\n // This happens when the synchronous error happens during the commit\n // phase of a child component — the boundary swallows it and renders\n // null, but the page is still broken. Treat as render-no-throw fail.\n if (boundaryRef.stack || boundaryRef.error) {\n const componentFrames = (boundaryRef.stack ?? \"\")\n .split(\"\\n\")\n .map((l: string) => l.trim())\n .filter((l: string) => l.startsWith(\"at \"))\n .slice(0, 4);\n const compBlock = componentFrames.length\n ? `\\n Component stack: ${componentFrames.join(\" > \")}`\n : \"\";\n const errMsg = boundaryRef.error ? boundaryRef.error.message : \"(no error message)\";\n issues.push({\n check: \"render-no-throw\",\n outcome: \"failed\",\n reason: `Render threw: ${errMsg}${compBlock}`,\n });\n cleanup();\n return finalize(issues, t0, 0, 0);\n }\n\n // RTL types `container` as HTMLElement; narrow it to the structural\n // MinimalElement via the validated host boundary.\n const container = toMinimalElement(renderResult.container);\n // Pass the live document explicitly — user-event's bare `setup()`\n // binds the document captured at its module load, which is undefined\n // when the module was pre-warmed before happy-dom stood up (ggui#403).\n const user: ClickUser = buildClickUser(userEvent, hostGlobals().document);\n\n let actionsChecked = 0;\n let streamsChecked = 0;\n\n try {\n // ggui#1187: prime form inputs before the action-wiring probe. A wired\n // Send/Submit gated on a non-empty input (the chat-interface shape) is a\n // no-op on empty, so an un-primed synthetic click never dispatches and\n // the probe false-warns \"did not dispatch it\". Shared with the visual\n // tester's primeInputs (#1021/#1040) so both prime identically. Priming\n // sets input VALUES (not textContent) and fires input/change before the\n // per-candidate fire-log window is opened, so it neither perturbs the\n // prop-sensitivity text baseline nor false-positives the wiring probe.\n // A priming failure never aborts the check — it is RECORDED on every\n // action-wiring issue as `diagnostics.inputPriming`. (The first cut\n // swallowed it, and a `ReferenceError` in the check worker's realm —\n // no `HTMLInputElement` on `globalThis` — hid behind that catch while\n // every chat cell kept warning.)\n let inputPriming: InputPrimingDiagnostic;\n try {\n inputPriming = { primed: primeInputs(renderResult.container) };\n } catch (err) {\n inputPriming = { error: err instanceof Error ? err.message : String(err) };\n }\n // ── Check 2: Action wiring (BLOCK / unverified-as-warn) ───────────\n if (input.contract?.actionSpec) {\n const actionSpec = input.contract.actionSpec;\n for (const [name, entry] of Object.entries(actionSpec)) {\n actionsChecked++;\n const wiring = findWiring({\n sourceCode: input.sourceCode,\n hookName: \"useAction\",\n hookArg: name,\n });\n const issue = await checkActionWiring({\n container,\n actionName: name,\n actionLabel: entry.label,\n wiring,\n probe,\n user,\n });\n if (issue) issues.push({ ...issue, diagnostics: { ...issue.diagnostics, inputPriming } });\n }\n }\n\n // ── Check 2b: Selection identity — duplicate-label cells (#601) ───\n // The live bug: a slot grid rendered several cells with the same\n // visible label (\"09:00\" across stylist rows); clicking one\n // selected ALL of them because the generated code keyed\n // selection/payload on the DISPLAY VALUE instead of the cell's\n // identity — even though the action schema carried an id field.\n // Wire-behavior check, DOM-shape independent: click two\n // same-label clickables and require their fired payloads to\n // differ on the id-like field. Conservative: any ambiguity\n // (no duplicate labels, clicks that fire nothing, payloads\n // missing the field) yields NO issue — those belong to other\n // checks.\n if (input.contract?.actionSpec) {\n for (const [name, entry] of Object.entries(input.contract.actionSpec)) {\n const idField = idLikeRequiredStringField(\n entry.schema as Record<string, unknown> | undefined\n );\n if (idField === null) continue;\n const issue = await checkSelectionIdentity({\n container,\n probe,\n user,\n actionName: name,\n idField,\n });\n if (issue) issues.push(issue);\n }\n }\n\n // ── Check 3: Agent-tool wiring — RETIRED ──────────────────────────\n // `useWiredTool` is retired. The contract's `agentCapabilities.tools`\n // is a catalog of tools the AGENT invokes — there is no component hook\n // surface. Cross-refs from actionSpec[*].nextStep /\n // streamSpec[*].source.tool ride through checks 2 (action wiring)\n // and 6 (stream re-render); the catalog itself has no\n // component-side requirement to verify here.\n\n // ── Check 4: Client-capability hook usage (WARN) ──────────────────\n // `clientTools` is retired. Capability hooks are imported from\n // `@ggui-ai/gadgets` (or vendor packages) and own their own\n // lifecycle — the runtime-render probe doesn't intercept them.\n // The tier-0 substring check in `run-tier0.ts` is the gate that\n // detects un-called capability bindings at gen time.\n\n // ── Check 5: Prop coverage (WARN) ─────────────────────────────────\n if (input.contract?.propsSpec) {\n for (const issue of checkPropCoverage({\n container,\n propsSpec: input.contract.propsSpec as PropsSpec,\n mockupProps: input.mockupProps,\n })) {\n issues.push(issue);\n }\n }\n\n // ── Check 5c: Prop sensitivity (#563) ─────────────────────────────\n // The measured class (economy/001 run 6): generated code renders a\n // value the contract delivers via props but BAKES the request's\n // literal — `props.month ?? 'January'` date math, hardcoded display\n // text — so a cached blueprint reused under a different value serves\n // the wrong surface. Deterministic detection for the DISPLAYED-value\n // half: re-render with a distinct value for each required scalar\n // prop whose original value visibly appears in the DOM; if the\n // rendered text is IDENTICAL under the change, the prop's value is\n // dead — baked. Scope honesty: value-ANCHORED logic that still\n // reacts (differently-wrong branches) is not deterministically\n // decidable here; the matcher-side pair armor and the judge track\n // that half. Conservative nulls: non-displayed props (ids are\n // legitimately non-visual), varied-value crashes (the code READ the\n // prop — not dead), and non-scalar props are all skipped.\n if (input.contract?.propsSpec) {\n const propsSpec5c = input.contract.propsSpec as PropsSpec;\n const normalize = (s: string | null): string => (s ?? \"\").replace(/\\s+/g, \" \").trim();\n const baseText = normalize(container.textContent);\n for (const [propName, entry] of Object.entries(propsSpec5c.properties)) {\n if (!entry.required) continue;\n const orig = input.mockupProps[propName];\n if (typeof orig !== \"string\" && typeof orig !== \"number\") continue;\n const marker = pickScalarMarker(orig);\n if (marker === null || !baseText.includes(marker)) continue;\n // Distinct same-type value. A token that never substring-matches\n // the original, so value-anchored branches (`includes(orig)`)\n // genuinely flip.\n const varied: string | number =\n typeof orig === \"string\" ? \"Zzyzx Qw\" : (orig as number) + 137731;\n // Isolated probe/wire per varied mount — events must not leak\n // into the primary probe's fire log.\n const variedProbe = createProbe();\n const variedConfig = createProbeWireConfig(variedProbe);\n let variedResult: ReturnType<typeof render> | undefined;\n try {\n variedResult = render(\n React.createElement(GguiWireProvider, {\n config: variedConfig,\n children: React.createElement(ProbeErrorBoundary, {\n children: React.createElement(Component, {\n ...input.mockupProps,\n [propName]: varied,\n }),\n }),\n })\n );\n } catch {\n continue; // crash on varied value ⇒ the prop is read, not dead\n }\n await flushPromises();\n const variedText = normalize(variedResult.container.textContent);\n variedResult.unmount();\n if (variedText === baseText) {\n issues.push({\n check: \"prop-sensitivity\",\n outcome: \"failed\",\n subject: propName,\n reason: `props.${propName} is displayed ('${marker}' appears in the DOM) but changing its value to '${String(varied)}' left the rendered output BYTE-IDENTICAL — the value is baked into the component instead of derived from the prop. A cached reuse of this blueprint under a different ${propName} would show the original value.`,\n });\n }\n }\n }\n\n // ── Check 6: Stream re-render (WARN) ──────────────────────────────\n if (input.contract?.streamSpec) {\n const streamSpec = input.contract.streamSpec;\n for (const [name] of Object.entries(streamSpec)) {\n streamsChecked++;\n const issue = await checkStreamRerender({\n container,\n eventName: name,\n probe,\n React,\n });\n if (issue) issues.push(issue);\n }\n }\n\n // ── Check 7: Optional-props omission (BLOCK on crash, ggui#528) ──\n // The main pass renders with EVERY declared prop filled, so a\n // component that assumes an optional prop is present always\n // passes here and crashes only live, when an agent legitimately\n // omits it (the wire gate requires only `required === true`\n // props). Render a second instance with the optional props\n // STRIPPED — a throw is exactly the latent-undefined class this\n // check exists to surface. Runs only when the contract declares\n // at least one optional prop that the mockup filled; zero cost\n // otherwise.\n const declaredProps = input.contract?.propsSpec?.properties;\n if (declaredProps) {\n const optionalFilled = Object.entries(declaredProps)\n .filter(\n ([name, entry]) =>\n (entry as { required?: boolean }).required !== true &&\n input.mockupProps[name] !== undefined\n )\n .map(([name]) => name);\n if (optionalFilled.length > 0) {\n const requiredOnlyProps: JsonObject = { ...input.mockupProps };\n for (const name of optionalFilled) delete requiredOnlyProps[name];\n const omitBoundaryRef: { error?: Error } = {};\n class OmitErrorBoundary extends React.Component<\n { children?: React.ReactNode },\n { caught: boolean }\n > {\n state = { caught: false };\n static getDerivedStateFromError(): { caught: boolean } {\n return { caught: true };\n }\n componentDidCatch(error: Error): void {\n omitBoundaryRef.error ??= error;\n }\n render(): React.ReactNode {\n if (this.state.caught) return null;\n return this.props.children;\n }\n }\n try {\n render(\n React.createElement(GguiWireProvider, {\n config: wireConfig,\n children: React.createElement(OmitErrorBoundary, {\n children: React.createElement(Component, requiredOnlyProps),\n }),\n })\n );\n } catch (e) {\n omitBoundaryRef.error ??= e instanceof Error ? e : new Error(String(e));\n }\n if (omitBoundaryRef.error) {\n issues.push({\n check: \"optional-props-omitted\",\n outcome: \"failed\",\n subject: optionalFilled.join(\", \"),\n reason:\n `Render crashed when the optional prop(s) ${optionalFilled\n .map((n) => `'${n}'`)\n .join(\", \")} were omitted: ${omitBoundaryRef.error.message}. ` +\n `The contract marks them optional (no \\`required: true\\`), so a legitimate render may leave them out.`,\n });\n }\n }\n }\n } finally {\n cleanup();\n }\n\n return finalize(issues, t0, actionsChecked, streamsChecked);\n } finally {\n try {\n uninstallSpy?.();\n } catch {\n /* ignore */\n }\n try {\n uninstallGadgetRegistry?.();\n } catch {\n /* ignore */\n }\n teardown();\n }\n}\n\n/**\n * Install a stub `globalThis.__ggui__` gadget registry so direct\n * gadget imports resolve at component-render time.\n *\n * Generated component code direct-imports gadget exports — there is no\n * runtime `loadGadgets()` registry call. For example, `import { useGeolocation } from\n * '@ggui-ai/gadgets'`, `import { useLeafletMap } from\n * '@ggui-samples/gadget-leaflet'`. The renderer's import rewriter\n * substitutes each gadget package specifier with a per-package\n * data-URL shim (`buildGadgetPackageShim`) whose named exports read\n * `globalThis.__ggui__.gadgets[<package>][<export>]` lazily at\n * call/render time.\n *\n * The runtime-render probe does not boot an iframe runtime, so that\n * `__ggui__.gadgets` slot is absent — without this stub, every\n * gadget-bearing component false-fails `render-no-throw` with\n * \"[gadget] export '…' is not loaded\".\n *\n * The registry installed here is **per-package** (`GadgetPackageRegistry`):\n * `{ '<package>': { '<export>': fn, … }, … }`. The shim resolves\n * `gadgets[package][export]`, so a flat hook-name keying would miss.\n *\n * The probe cannot run a real third-party gadget (Leaflet, Mapbox) in\n * happy-dom, so each export the contract declares is stubbed by kind,\n * discriminated by the export-name grammar:\n * - a HOOK export (`use`-prefixed) is stubbed with the uniform gadget\n * result contract the boilerplate teaches — `{ status, value,\n * start }`: `status` is a real string (safe as a React child and in\n * comparisons), `value`'s fields are no-op functions (safe as\n * callback refs + imperative calls like `panTo`), `start` is a no-op.\n * - a COMPONENT export (PascalCase) is stubbed with a function\n * component that renders nothing (`() => null`) — React invokes it\n * when the host renders `<X … />`.\n * The probe thus verifies the COMPONENT's own render tree while\n * treating the gadget as a well-behaved black box.\n *\n * Returns an uninstaller; the caller MUST invoke it — `globalThis` is\n * a process global and a leaked slot taints the next check.\n */\nexport function installGadgetStubRegistry(contract: DataContract | undefined): () => void {\n const declared = contract?.clientCapabilities?.gadgets;\n if (!declared || Object.keys(declared).length === 0) {\n return () => {};\n }\n\n const noop = (): void => {};\n // A gadget `value` carries an imperative surface (`containerRef`\n // callback ref, `panTo`, `setView`, …) — every field resolves to a\n // no-op so refs attach and imperative calls stay safe.\n const valueStub = new Proxy(\n {},\n {\n get: (_t, key) => (key === \"then\" || typeof key === \"symbol\" ? undefined : noop),\n }\n );\n const result = { status: \"idle\", value: valueStub, start: noop };\n // Unknown top-level keys resolve to a no-op (covers `map.foo()`);\n // `then` + symbol keys pass through so `await` / coercion stay safe.\n const resultStub = new Proxy(result, {\n get: (t, key) => {\n if (key === \"status\" || key === \"value\" || key === \"start\") {\n return t[key];\n }\n return key === \"then\" || typeof key === \"symbol\" ? undefined : noop;\n },\n });\n\n // Per-package registry — `{ '<package>': { '<export>': fn } }`.\n // Mirrors the runtime `GadgetPackageRegistry` shape that\n // `buildGadgetPackageShim` reads (`gadgets[package][export]`).\n // Iterate the flattened `GadgetUse[]`; kind is discriminated\n // by the export-name grammar.\n const gadgets: Record<string, Record<string, unknown>> = {};\n for (const use of contract ? listContractGadgets(contract) : []) {\n const pkgSlot = (gadgets[use.package] ??= {});\n if (HOOK_NAME_RE.test(use.name)) {\n // Hook export — the component CALLS it; return the uniform\n // `{ status, value, start }` gadget result stub.\n pkgSlot[use.name] = () => resultStub;\n } else {\n // Component export (PascalCase) — React invokes it as a\n // function component. Render nothing: the gadget stays a\n // well-behaved black box while the host component's own render\n // tree is the thing under verification.\n pkgSlot[use.name] = () => null;\n }\n }\n\n const root = globalThis as { __ggui__?: unknown };\n const prior = root.__ggui__;\n root.__ggui__ = { gadgets, publicEnv: {} };\n return () => {\n if (prior === undefined) {\n delete root.__ggui__;\n } else {\n root.__ggui__ = prior;\n }\n };\n}\n\n/**\n * Collect the distinct third-party gadget package names a contract\n * declares. The STDLIB package `@ggui-ai/gadgets` is\n * EXCLUDED — its real hooks are pre-loaded into the probe sandbox and\n * run standalone (they implement browser APIs directly, not via the\n * `__ggui__.gadgets` registry). Only operator-registered wrapper\n * packages need a sandbox shim.\n */\nfunction collectThirdPartyGadgetPackages(contract: DataContract | undefined): string[] {\n if (!contract) return [];\n const packages = new Set<string>();\n for (const use of listContractGadgets(contract)) {\n if (use.package !== \"@ggui-ai/gadgets\") packages.add(use.package);\n }\n return [...packages];\n}\n\n/**\n * Build a CJS module-namespace shim for one third-party gadget\n * package, for injection into `loadComponent`'s\n * `moduleResolutions`.\n *\n * The probe re-compiles the component to CJS, so a direct\n * `import { useX } from '<package>'` becomes `require('<package>')`\n * and pulls `module.exports.<X>`. This shim is a Proxy whose every\n * property is a lazy thunk forwarding to the stub registry's\n * per-package slot — `globalThis.__ggui__.gadgets[<package>][<export>]`\n * — at CALL time. Lazy resolution matches the runtime rewriter's\n * `buildGadgetPackageShim` read pattern and is robust to the registry\n * being installed after the shim is built.\n *\n * The probe cannot run a real third-party gadget in happy-dom; the\n * registry slot holds the stub `installGadgetStubRegistry` plants —\n * the uniform `{ status, value, start }` result for a hook export, or\n * a render-nothing component for a PascalCase component export — so the\n * host COMPONENT's own render tree is verified while the gadget stays a\n * well-behaved black box.\n */\nfunction buildGadgetPackageProbeShim(packageName: string): ProbeModuleNamespace {\n const resolveExport = (name: string): unknown => {\n const root = globalThis as {\n __ggui__?: { gadgets?: Record<string, Record<string, unknown>> };\n };\n return root.__ggui__?.gadgets?.[packageName]?.[name];\n };\n // Lazy thunk — forwards to the registry slot at call/render time.\n // Covers both hooks (`useX()`) and gadget components (`<X />`, which\n // React invokes as a function).\n const makeThunk =\n (name: string) =>\n (...args: unknown[]): unknown => {\n const impl = resolveExport(name);\n if (typeof impl !== \"function\") {\n throw new Error(\n `[gadget] export '${name}' from '${packageName}' is not loaded in the render-check probe — the component imports it but the contract's clientCapabilities.gadgets never declared it, so installGadgetStubRegistry planted no stub.`\n );\n }\n return (impl as (...a: unknown[]) => unknown)(...args);\n };\n return new Proxy(\n {},\n {\n get: (_t, key) => {\n if (typeof key === \"symbol\" || key === \"default\" || key === \"then\") {\n return undefined;\n }\n return makeThunk(key);\n },\n // `key in ns` checks (esbuild interop may probe) report true so\n // the named import binds to the thunk rather than `undefined`.\n has: (_t, key) => typeof key !== \"symbol\" && key !== \"then\" && key !== \"default\",\n }\n ) as ProbeModuleNamespace;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Setup / teardown\n// ─────────────────────────────────────────────────────────────────────────────\n\nasync function setupHappyDom(): Promise<() => void> {\n const g = hostGlobals();\n\n // ── Async-teardown safety ───────────────────────────────────────────────\n // Generated components may call setTimeout/setInterval for polling,\n // delayed renders, debouncing, etc. If a timer fires AFTER we delete\n // window/document, its callback's setState lookup will read\n // `window.event` (React dev path) and throw an unhandled exception\n // that crashes the whole process (observed: run3 of post-probe-guard).\n //\n // Mitigations:\n // 1. Wrap setTimeout/setInterval to track pending IDs; clear them all\n // on teardown.\n // 2. Install a process-level uncaughtException/unhandledRejection\n // handler during the probe's lifetime that swallows DOM-teardown-\n // class errors and forwards anything else.\n const pendingTimeouts = new Set<NodeJS.Timeout>();\n const pendingIntervals = new Set<NodeJS.Timeout>();\n const origSetTimeout = globalThis.setTimeout;\n const origSetInterval = globalThis.setInterval;\n const origClearTimeout = globalThis.clearTimeout;\n const origClearInterval = globalThis.clearInterval;\n // Same documented adaptation as the setInterval wrapper below: the\n // arrow function satisfies the call signature but not Node's\n // `__promisify__` brand, so a single structural cast closes the gap.\n globalThis.setTimeout = ((...args: Parameters<typeof origSetTimeout>) => {\n const id = origSetTimeout(...args);\n pendingTimeouts.add(id);\n return id;\n }) as typeof globalThis.setTimeout;\n globalThis.setInterval = ((...args: Parameters<typeof origSetInterval>) => {\n const id = origSetInterval(...args);\n pendingIntervals.add(id);\n return id;\n }) as typeof globalThis.setInterval;\n globalThis.clearTimeout = (id?: string | number | NodeJS.Timeout) => {\n if (id !== undefined) pendingTimeouts.delete(id as NodeJS.Timeout);\n return origClearTimeout(id);\n };\n globalThis.clearInterval = (id?: string | number | NodeJS.Timeout) => {\n if (id !== undefined) pendingIntervals.delete(id as NodeJS.Timeout);\n return origClearInterval(id);\n };\n\n const isTeardownArtifact = (err: unknown): boolean => {\n const msg = err instanceof Error ? err.message : String(err);\n return (\n /window is not defined/i.test(msg) ||\n /document is not defined/i.test(msg) ||\n /Cannot read propert(?:y|ies) of undefined \\(reading 'event'\\)/i.test(msg) ||\n /requestAnimationFrame is not defined/i.test(msg)\n );\n };\n const uncaughtHandler = (err: Error): void => {\n if (isTeardownArtifact(err)) {\n // Expected — a generated component's late timer fired after teardown.\n // Swallow silently; the probe already recorded its outcome.\n return;\n }\n // Not ours — re-throw on next tick so the default handler runs.\n process.nextTick(() => {\n throw err;\n });\n };\n const unhandledHandler = (reason: unknown): void => {\n if (isTeardownArtifact(reason)) return;\n const err = reason instanceof Error ? reason : new Error(String(reason));\n process.nextTick(() => {\n throw err;\n });\n };\n process.on(\"uncaughtException\", uncaughtHandler);\n process.on(\"unhandledRejection\", unhandledHandler);\n\n const cleanupAsyncInfra = (): void => {\n for (const id of pendingTimeouts) origClearTimeout(id);\n for (const id of pendingIntervals) origClearInterval(id);\n pendingTimeouts.clear();\n pendingIntervals.clear();\n globalThis.setTimeout = origSetTimeout;\n globalThis.setInterval = origSetInterval;\n globalThis.clearTimeout = origClearTimeout;\n globalThis.clearInterval = origClearInterval;\n // Keep uncaughtException/unhandledRejection handlers registered for a\n // brief grace period. React 19's concurrent scheduler can defer state\n // updates via microtasks / setImmediate — those flush AFTER the probe\n // returns, and if our handlers are gone they'll crash the process.\n // Observed on exp47-control-run2: `useWiredTool.call → dispatchSetState`\n // fired post-teardown, ReferenceError: window is not defined, full\n // process crash. 100ms is long enough for React's scheduler to drain\n // without meaningfully delaying the next cell's setup.\n origSetTimeout(() => {\n process.off(\"uncaughtException\", uncaughtHandler);\n process.off(\"unhandledRejection\", unhandledHandler);\n }, 100).unref?.();\n };\n\n // If window/document already exist (e.g., Vitest happy-dom environment), trust them.\n // Just toggle the React act flag and return a teardown that restores timer state.\n if (\"window\" in g && \"document\" in g) {\n const priorActFlag = g.IS_REACT_ACT_ENVIRONMENT;\n g.IS_REACT_ACT_ENVIRONMENT = true;\n return () => {\n cleanupAsyncInfra();\n if (priorActFlag === undefined) delete g.IS_REACT_ACT_ENVIRONMENT;\n else g.IS_REACT_ACT_ENVIRONMENT = priorActFlag;\n };\n }\n\n const { Window } = await import(\"happy-dom\");\n const window = new Window({ url: \"https://render-check.local\" });\n const windowAny = openRecord(window);\n\n const keys = [\n \"window\",\n \"document\",\n \"navigator\",\n \"HTMLElement\",\n \"Node\",\n \"Element\",\n \"Event\",\n \"MouseEvent\",\n \"KeyboardEvent\",\n \"getComputedStyle\",\n \"requestAnimationFrame\",\n \"cancelAnimationFrame\",\n ];\n const prior: Record<string, { value: unknown; existed: boolean }> = {};\n for (const k of keys) {\n prior[k] = { value: g[k], existed: k in g };\n try {\n // Use defineProperty to bypass any getter-only restrictions on the host.\n Object.defineProperty(g, k, {\n value: windowAny[k],\n writable: true,\n configurable: true,\n });\n } catch {\n // Skip globals we can't override (e.g., locked-down host runtimes).\n }\n }\n\n g.IS_REACT_ACT_ENVIRONMENT = true;\n\n return () => {\n cleanupAsyncInfra();\n for (const k of keys) {\n try {\n if (prior[k]!.existed) {\n Object.defineProperty(g, k, {\n value: prior[k]!.value,\n writable: true,\n configurable: true,\n });\n } else {\n delete g[k];\n }\n } catch {\n /* ignore */\n }\n }\n delete g.IS_REACT_ACT_ENVIRONMENT;\n };\n}\n\nfunction finalize(\n issues: RenderCheckIssue[],\n t0: number,\n actionsChecked: number,\n streamsChecked: number\n): RenderCheckResult {\n const ok = !issues.some((i) => i.outcome === \"failed\");\n return {\n ok,\n issues,\n stats: {\n actionsChecked,\n streamsChecked,\n renderMs: Date.now() - t0,\n },\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Check implementations\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface CheckActionInput {\n container: MinimalElement;\n actionName: string;\n actionLabel: string;\n wiring: WiringDetection;\n probe: Probe;\n user: { click: (el: MinimalElement) => Promise<void> };\n}\n\nasync function checkActionWiring(input: CheckActionInput): Promise<RenderCheckIssue | null> {\n const { container, actionName, actionLabel, wiring, probe, user } = input;\n\n const baseDiagnostics = {\n observedJsxElements: wiring.observedJsxElements,\n observedNativeProps: wiring.observedNativeProps,\n observedCustomProps: wiring.observedCustomProps,\n };\n\n // Source says the hook is destructured but never referenced anywhere → fail.\n if (wiring.kind === \"missing\") {\n return {\n check: \"action-wiring\",\n outcome: \"failed\",\n subject: actionName,\n reason:\n wiring.reason ??\n `Action '${actionName}' is declared in contract but useAction('${actionName}') is not wired to any UI element`,\n diagnostics: baseDiagnostics,\n };\n }\n\n // Source says wired via custom-component prop / non-deterministic trigger → unverified.\n if (wiring.kind === \"unverified\") {\n return {\n check: \"action-wiring\",\n outcome: \"unverified\",\n subject: actionName,\n reason:\n wiring.reason ??\n \"Source indicates non-click or non-native wiring; static probe did not verify execution deterministically.\",\n diagnostics: baseDiagnostics,\n };\n }\n\n // Source-detected deterministic wiring → simulate the matching trigger.\n const fired = await simulateAndCheck({\n container,\n user,\n probe,\n wiringKind: wiring.kind,\n actionName,\n actionLabel,\n eventKind: \"action.fired\",\n });\n\n if (fired.fired) return null; // verified — no issue\n\n // The AST already confirmed the wiring exists in source. The\n // simulator couldn't trigger it — most likely a conditional-render or\n // required-form-fill case. Be conservative: downgrade to unverified\n // rather than reporting a fake failure.\n return {\n check: \"action-wiring\",\n outcome: \"unverified\",\n subject: actionName,\n reason: `Source confirms ${wiring.kind} wiring exists for action '${actionName}', but synthetic ${wiring.kind} did not dispatch it. Likely cause: conditional rendering, required input/form fill, or a multi-step interaction the static probe cannot complete.`,\n elementHint: fired.attemptedHint,\n diagnostics: {\n ...baseDiagnostics,\n actionsFiredFromClicks: fired.otherActionsFired,\n },\n };\n}\n\n// `checkWiredToolWiring` is retired — `useWiredTool` was removed; the\n// contract's `agentCapabilities.tools` is a catalog the AGENT invokes\n// (no component hook to verify). Cross-refs from `actionSpec[*].nextStep` and\n// `streamSpec[*].source.tool` ride through the action / stream check\n// arms in `runRenderCheck` instead.\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Selection identity (#601) — duplicate-label cells must carry their own id\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Find the id-like required string property in an action's payload\n * schema, or null. \"id-like\" = a required property whose name ends in\n * `id`/`Id`/`ID` and whose declared type is string — the shape the\n * matcher's booking/selection contracts carry (`bookSlot { slotId }`).\n */\nfunction idLikeRequiredStringField(schema: Record<string, unknown> | undefined): string | null {\n if (schema === undefined) return null;\n const properties = schema[\"properties\"];\n const required = schema[\"required\"];\n if (properties === null || typeof properties !== \"object\") return null;\n if (!Array.isArray(required)) return null;\n for (const [propName, propSchema] of Object.entries(properties as Record<string, unknown>)) {\n if (!/id$/i.test(propName)) continue;\n if (!required.includes(propName)) continue;\n const t =\n propSchema !== null && typeof propSchema === \"object\"\n ? (propSchema as Record<string, unknown>)[\"type\"]\n : undefined;\n if (t === \"string\") return propName;\n }\n return null;\n}\n\ninterface CheckSelectionIdentityInput {\n container: MinimalElement;\n probe: Probe;\n user: { click: (el: MinimalElement) => Promise<void> };\n actionName: string;\n idField: string;\n}\n\n/**\n * Click two clickables that share a visible label and require the two\n * fired payloads to DIFFER on the id-like field. Identical values mean\n * the component keys the action on the display value, not the element's\n * identity — the ggui#601 class (every \"09:00\" cell selecting together).\n *\n * Emits at most one `failed` issue; every ambiguous situation returns\n * null (covered by other checks or genuinely unjudgeable here).\n */\nasync function checkSelectionIdentity(\n input: CheckSelectionIdentityInput\n): Promise<RenderCheckIssue | null> {\n const { container, probe, user, actionName, idField } = input;\n\n const clickables = Array.from(\n container.querySelectorAll<MinimalElement>('button, [role=\"button\"]')\n );\n const byLabel = new Map<string, MinimalElement[]>();\n for (const el of clickables) {\n const label = (el.textContent ?? \"\").replace(/\\s+/g, \" \").trim();\n if (label.length === 0) continue;\n const group = byLabel.get(label);\n if (group) group.push(el);\n else byLabel.set(label, [el]);\n }\n\n for (const [label, group] of byLabel) {\n if (group.length < 2) continue;\n\n const payloadFor = async (el: MinimalElement): Promise<unknown | undefined> => {\n const before = probe.getFireLog().length;\n try {\n await user.click(el);\n } catch {\n return undefined;\n }\n await flushPromises();\n const events = probe\n .getFireLog()\n .slice(before)\n .filter((e): e is ActionFiredEvent => e.kind === \"action.fired\" && e.name === actionName);\n return events.length > 0 ? events[events.length - 1]!.payload : undefined;\n };\n\n const first = await payloadFor(group[0]!);\n const second = await payloadFor(group[1]!);\n // Either click firing nothing for this action = not this check's\n // question (wiring check owns \"does it fire\").\n if (first === undefined || second === undefined) continue;\n\n const idOf = (payload: unknown): string | undefined => {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const v = (payload as Record<string, unknown>)[idField];\n return typeof v === \"string\" ? v : undefined;\n };\n const firstId = idOf(first);\n const secondId = idOf(second);\n // Payloads missing the required field = schema territory, not ours.\n if (firstId === undefined || secondId === undefined) continue;\n\n if (firstId === secondId) {\n return {\n check: \"selection-identity\",\n outcome: \"failed\",\n subject: actionName,\n reason: `Two clickable elements share the visible label '${label}', and clicking EACH fired '${actionName}' with the same ${idField} ('${firstId}') — the action payload is keyed on the display value, not the element's identity. Distinct cells must send their own ${idField} (the contract requires it), or selecting one \"${label}\" acts on every \"${label}\".`,\n elementHint: describeElement(group[0]!),\n };\n }\n // Distinct ids on the first duplicate group — identity keying holds.\n return null;\n }\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Trigger simulators — narrow set, deterministic only\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface SimulateAndCheckInput {\n container: MinimalElement;\n user: { click: (el: MinimalElement) => Promise<void> };\n probe: Probe;\n wiringKind: \"click\" | \"submit\" | \"change\" | \"keyboard-enter\";\n actionName: string;\n actionLabel: string;\n eventKind: \"action.fired\" | \"wiredTool.called\";\n}\n\ninterface SimulateResult {\n fired: boolean;\n attemptedHint?: string;\n otherActionsFired?: string[];\n}\n\nasync function simulateAndCheck(input: SimulateAndCheckInput): Promise<SimulateResult> {\n const { container, user, probe, wiringKind, actionName, actionLabel, eventKind } = input;\n\n const candidates = findCandidateElements(container, wiringKind, actionName, actionLabel);\n if (candidates.length === 0) {\n return { fired: false, attemptedHint: `No ${wiringKind}-eligible element found in DOM` };\n }\n\n for (const el of candidates) {\n const before = probe.getFireLog().length;\n try {\n await dispatchTrigger(el, wiringKind, user);\n } catch {\n continue;\n }\n await flushPromises();\n const newEvents = probe.getFireLog().slice(before);\n const matched = newEvents.some((e) => e.kind === eventKind && e.name === actionName);\n if (matched) return { fired: true };\n }\n\n // Capture what DID fire — useful diagnostic.\n const allFired = probe\n .getFireLog()\n .filter((e) => e.kind === \"action.fired\")\n .map((e) => e.name);\n const otherActionsFired = Array.from(new Set(allFired)).filter((n) => n !== actionName);\n\n return {\n fired: false,\n attemptedHint: candidates.length ? describeElement(candidates[0]!) : undefined,\n otherActionsFired,\n };\n}\n\nasync function dispatchTrigger(\n el: MinimalElement,\n kind: \"click\" | \"submit\" | \"change\" | \"keyboard-enter\",\n user: { click: (el: MinimalElement) => Promise<void> }\n): Promise<void> {\n switch (kind) {\n case \"click\":\n await user.click(el);\n return;\n case \"submit\": {\n // Find the enclosing form (or the element itself if it IS a form) and\n // dispatch a 'submit' event on it. happy-dom respects this.\n const form = closestForm(el);\n if (!form) return;\n const ev = new (globalThis as { Event: typeof Event }).Event(\"submit\", {\n bubbles: true,\n cancelable: true,\n });\n toEventDispatcher(form).dispatchEvent(ev);\n return;\n }\n case \"change\": {\n // Set a value before dispatching change — onChange handlers typically\n // read e.target.value, and a no-op change (same value) often won't\n // trigger downstream wiring. We only reach here when source-AST said\n // wiring is on a native element (input/select/textarea).\n setSyntheticValue(el);\n const ev = new (globalThis as { Event: typeof Event }).Event(\"change\", { bubbles: true });\n toEventDispatcher(el).dispatchEvent(ev);\n return;\n }\n case \"keyboard-enter\": {\n // Click first to focus, then dispatch an Enter keydown.\n try {\n await user.click(el);\n } catch {\n /* ignore */\n }\n const KeyboardEventCtor = (\n globalThis as { KeyboardEvent?: new (type: string, init: object) => Event }\n ).KeyboardEvent;\n if (KeyboardEventCtor) {\n const ev = new KeyboardEventCtor(\"keydown\", { key: \"Enter\", bubbles: true });\n toEventDispatcher(el).dispatchEvent(ev);\n }\n return;\n }\n }\n}\n\n/**\n * Mutate a native input/select/textarea to carry a non-empty, distinct value\n * just before firing 'change'. Without this, onChange handlers that branch on\n * e.target.value see whatever the component initialized (often empty / the\n * default), and the wiring under test never observes a real edit.\n *\n * Strategy:\n * <select> — pick the first option whose value differs from the current one\n * <input type=checkbox|radio> — flip checked\n * <input type=number|range> — increment by 1 (or set to min+1 / \"1\")\n * everything else (text/email/search/textarea/...) — append \"x\" if non-empty,\n * else set to \"test\"\n *\n * Best-effort: if any access throws (sealed mocks, unexpected shape), we leave\n * the element untouched and let the bare 'change' event fire.\n */\nfunction setSyntheticValue(el: MinimalElement): void {\n try {\n const tag = el.tagName.toLowerCase();\n const node = editableSurface(el);\n\n if (tag === \"select\") {\n const opts = node.options;\n if (opts && opts.length > 0) {\n const current = node.value ?? \"\";\n let pick = opts[0]!.value;\n for (let i = 0; i < opts.length; i++) {\n if (opts[i]!.value !== current) {\n pick = opts[i]!.value;\n break;\n }\n }\n node.value = pick;\n }\n return;\n }\n\n if (tag === \"input\") {\n const type = (node.type ?? \"text\").toLowerCase();\n if (type === \"checkbox\" || type === \"radio\") {\n node.checked = !node.checked;\n return;\n }\n if (type === \"number\" || type === \"range\") {\n const cur = Number(node.value ?? \"\");\n node.value = String(Number.isFinite(cur) ? cur + 1 : 1);\n return;\n }\n // text / email / search / url / password / tel / date / etc.\n node.value = node.value && node.value.length > 0 ? `${node.value}x` : \"test\";\n return;\n }\n\n if (tag === \"textarea\") {\n node.value = node.value && node.value.length > 0 ? `${node.value}x` : \"test\";\n return;\n }\n } catch {\n // Untouched element is fine — the bare change event still fires.\n }\n}\n\nfunction closestForm(el: MinimalElement): MinimalElement | null {\n // Climb via parentNode (happy-dom + native both expose this on Element).\n let cur: ParentLink | null = parentLink(el);\n while (cur) {\n if (cur.tagName && cur.tagName.toLowerCase() === \"form\") {\n return toMinimalElement(cur);\n }\n cur =\n typeof cur.parentNode === \"object\" && cur.parentNode !== null\n ? parentLink(cur.parentNode)\n : null;\n }\n return null;\n}\n\nfunction findCandidateElements(\n container: MinimalElement,\n kind: \"click\" | \"submit\" | \"change\" | \"keyboard-enter\",\n name: string,\n label: string\n): MinimalElement[] {\n switch (kind) {\n case \"click\":\n return findActionElements(container, name, label);\n case \"submit\": {\n // submit-eligible: <form>, button[type=submit], input[type=submit]\n const all = container.querySelectorAll<MinimalElement>(\n 'form, button[type=\"submit\"], input[type=\"submit\"]'\n );\n return Array.from(all);\n }\n case \"change\": {\n const all = container.querySelectorAll<MinimalElement>(\"select, input, textarea\");\n return Array.from(all);\n }\n case \"keyboard-enter\":\n return findActionElements(container, name, label);\n }\n}\n\ninterface CheckPropCoverageInput {\n container: MinimalElement;\n propsSpec: PropsSpec;\n mockupProps: JsonObject;\n}\n\nfunction checkPropCoverage(input: CheckPropCoverageInput): RenderCheckIssue[] {\n const { container, propsSpec, mockupProps } = input;\n const issues: RenderCheckIssue[] = [];\n const text = container.textContent ?? \"\";\n\n for (const [propName, entry] of Object.entries(propsSpec.properties)) {\n if (!entry.required) continue;\n const value = mockupProps[propName];\n if (value === undefined || value === null) continue;\n\n // Pick a unique scalar marker we can search for in the DOM.\n const marker = pickScalarMarker(value);\n if (marker === null) continue;\n\n if (!text.includes(marker)) {\n issues.push({\n check: \"prop-coverage\",\n outcome: \"unverified\",\n subject: propName,\n reason: `Required prop '${propName}' value (${JSON.stringify(marker).slice(0, 60)}) not visible in rendered DOM`,\n });\n }\n }\n\n return issues;\n}\n\ninterface CheckStreamRerenderInput {\n container: MinimalElement;\n eventName: string;\n probe: Probe;\n React: typeof import(\"react\");\n}\n\nasync function checkStreamRerender(\n input: CheckStreamRerenderInput\n): Promise<RenderCheckIssue | null> {\n const { container, eventName, probe } = input;\n\n if (!probe.getRegistered().streams.includes(eventName)) {\n return {\n check: \"stream-rerender\",\n outcome: \"unverified\",\n subject: eventName,\n reason: `useStream('${eventName}') was never called — the stream event is declared in the contract but the component does not subscribe to it`,\n };\n }\n\n const before = container.textContent ?? \"\";\n const marker = `__probe_marker_${Date.now()}__`;\n // Emit a synthetic payload with a unique marker we can search for.\n // For payloads where the schema is unknown, push an object containing the marker\n // in multiple common field names so downstream consumers find it.\n const payload = { id: marker, text: marker, value: marker, message: marker, name: marker };\n\n await new Promise<void>((resolve) => {\n setTimeout(() => {\n probe.emitStream(eventName, payload);\n resolve();\n }, 0);\n });\n await flushPromises();\n\n const after = container.textContent ?? \"\";\n if (after === before) {\n return {\n check: \"stream-rerender\",\n outcome: \"unverified\",\n subject: eventName,\n reason: `useStream('${eventName}') is subscribed but emitting a payload did not change the DOM`,\n };\n }\n if (!after.includes(marker)) {\n // DOM changed but our marker isn't visible — possible the consumer renders\n // a derived value. Soft-pass.\n return null;\n }\n\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\nfunction findActionElements(\n container: MinimalElement,\n name: string,\n label: string\n): MinimalElement[] {\n const candidates: MinimalElement[] = [];\n const seen = new Set<MinimalElement>();\n\n const norm = (s: string) => s.toLowerCase().replace(/[\\s_-]+/g, \"\");\n const nameKey = norm(name);\n const labelKey = norm(label);\n\n const allClickable = container.querySelectorAll<MinimalElement>(\n 'button, [role=\"button\"], input[type=\"submit\"], input[type=\"button\"], a[href]'\n );\n\n // Pass 1: text/aria-label/data-action match\n for (const el of allClickable) {\n const aria = (el.getAttribute(\"aria-label\") ?? \"\").toLowerCase();\n const txt = (el.textContent ?? \"\").toLowerCase();\n const dataAction = (el.getAttribute(\"data-action\") ?? \"\").toLowerCase();\n if (\n aria.includes(label.toLowerCase()) ||\n txt.includes(label.toLowerCase()) ||\n norm(aria).includes(nameKey) ||\n norm(txt).includes(nameKey) ||\n dataAction === name.toLowerCase() ||\n norm(txt).includes(labelKey)\n ) {\n if (!seen.has(el)) {\n seen.add(el);\n candidates.push(el);\n }\n }\n }\n\n // Pass 2: any clickable as fallback (we'll click them all)\n for (const el of allClickable) {\n if (!seen.has(el)) {\n seen.add(el);\n candidates.push(el);\n }\n }\n\n return candidates;\n}\n\nfunction describeElement(el: MinimalElement): string {\n const tag = el.tagName.toLowerCase();\n const aria = el.getAttribute(\"aria-label\");\n const txt = (el.textContent ?? \"\").trim().slice(0, 30);\n if (aria) return `<${tag} aria-label=\"${aria}\">`;\n if (txt) return `<${tag}>${txt}</${tag}>`;\n return `<${tag}>`;\n}\n\nfunction pickScalarMarker(value: unknown): string | null {\n if (typeof value === \"string\" && value.length > 0) return value;\n if (typeof value === \"number\") return String(value);\n if (Array.isArray(value)) {\n for (const item of value) {\n const m = pickScalarMarker(item);\n if (m) return m;\n }\n return null;\n }\n if (value && typeof value === \"object\") {\n for (const v of Object.values(value)) {\n const m = pickScalarMarker(v);\n if (m) return m;\n }\n }\n return null;\n}\n\nfunction flushPromises(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0));\n}\n","// packages/ui-gen/src/harness/check/runtime-render/prepare-mockup.ts\n//\n// Schema-first mockup props for runtime render evaluation.\n//\n// Priority:\n// 1. Existing fixture props (commit/contract `props` field) — highest fidelity\n// 2. PropEntry.example\n// 3. PropEntry.default\n// 4. Deterministic schema synthesis from JSON Schema\n// (default → example → enum[0] → typed placeholder)\n// 5. LLM fallback (deferred — v2)\n// 6. Empty fallback ({}) if all else fails\n//\n// Output is validated against the contract's `properties` shape — if a field\n// is required and ends up missing, we surface that as a synthesis warning\n// (the render check will likely fail downstream, but with a clearer signal).\n\nimport type {\n DataContract,\n JsonObject,\n JsonSchema,\n JsonValue,\n PropEntry,\n PropsSpec,\n} from \"@ggui-ai/protocol\";\n\nexport interface MockupPropsResult {\n /** The synthesized props object — pass directly into render(<Component {...props} />). */\n readonly props: JsonObject;\n /** How each field was sourced — useful for debugging eval failures. */\n readonly source: Readonly<Record<string, MockupSource>>;\n /** Synthesis warnings (missing required fields, unsupported schemas, etc.). */\n readonly warnings: readonly string[];\n}\n\nexport type MockupSource =\n | \"fixture\"\n | \"entry-example\"\n | \"entry-default\"\n | \"schema-default\"\n | \"schema-example\"\n | \"schema-enum\"\n | \"schema-synth\"\n | \"empty\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public entry point\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface PrepareMockupInput {\n readonly contract: DataContract | undefined;\n /**\n * Pre-supplied fixture props (e.g., from a benchmark commit's `props` field).\n * Wins over schema synthesis when keys match.\n */\n readonly fixtureProps?: JsonObject;\n}\n\n/**\n * Synthesize a JsonObject of props matching the contract.propsSpec shape.\n *\n * Deterministic — no LLM call. Returns even if the contract is missing\n * (in which case `props` is just the fixtureProps or `{}`).\n */\nexport function prepareMockupProps(input: PrepareMockupInput): MockupPropsResult {\n const { contract, fixtureProps } = input;\n const propsSpec = contract?.propsSpec as PropsSpec | undefined;\n\n const props: JsonObject = {};\n const source: Record<string, MockupSource> = {};\n const warnings: string[] = [];\n\n if (!propsSpec || !propsSpec.properties) {\n // No props contract — mirror the fixture if present, else empty.\n if (fixtureProps) {\n Object.assign(props, fixtureProps);\n for (const k of Object.keys(fixtureProps)) source[k] = \"fixture\";\n }\n return { props, source, warnings };\n }\n\n for (const [key, entry] of Object.entries(propsSpec.properties)) {\n // Priority 1: fixture wins\n if (fixtureProps && Object.prototype.hasOwnProperty.call(fixtureProps, key)) {\n props[key] = fixtureProps[key];\n source[key] = \"fixture\";\n continue;\n }\n\n const synth = synthesizePropValue(entry, key, warnings);\n if (synth.kind === \"ok\") {\n props[key] = synth.value;\n source[key] = synth.source;\n } else if (entry.required) {\n warnings.push(`Required prop '${key}' could not be synthesized (${synth.reason})`);\n }\n // Optional props that fail synthesis are simply omitted.\n }\n\n return { props, source, warnings };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Per-prop synthesis\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype SynthOk = { kind: \"ok\"; value: JsonValue; source: MockupSource };\ntype SynthFail = { kind: \"fail\"; reason: string };\n\nfunction synthesizePropValue(\n entry: PropEntry,\n fieldName: string,\n warnings: string[],\n): SynthOk | SynthFail {\n // PropEntry-level wins over schema-level\n if (entry.example !== undefined) {\n return { kind: \"ok\", value: entry.example, source: \"entry-example\" };\n }\n if (entry.default !== undefined) {\n return { kind: \"ok\", value: entry.default, source: \"entry-default\" };\n }\n return synthesizeFromSchema(entry.schema, fieldName, warnings, 0);\n}\n\nconst MAX_DEPTH = 6;\n\nfunction synthesizeFromSchema(\n schema: JsonSchema | undefined,\n hint: string,\n warnings: string[],\n depth: number,\n /**\n * 1-based position when the value belongs to an array element (inherited\n * by the element's own fields). Every synthesized string inside an element\n * carries it, so two elements never share an id or a visible label — the\n * runtime probe's selection-identity rule (\"clicking each fired the action\n * with the same id\") is undecidable on identical items and read a correct\n * component as broken (2026-09-10, the 1.6 hello: both quick replies were\n * `Sample Id` / `Sample Label`).\n */\n ordinal?: number,\n): SynthOk | SynthFail {\n if (!schema) return { kind: \"fail\", reason: \"no schema\" };\n if (depth > MAX_DEPTH) return { kind: \"fail\", reason: \"schema too deep\" };\n\n // Schema-level overrides\n if (schema.default !== undefined) {\n return { kind: \"ok\", value: schema.default, source: \"schema-default\" };\n }\n if (schema.example !== undefined) {\n return { kind: \"ok\", value: schema.example, source: \"schema-example\" };\n }\n if (schema.enum && schema.enum.length > 0) {\n return { kind: \"ok\", value: schema.enum[0]!, source: \"schema-enum\" };\n }\n\n // Union schemas — try first branch only\n if (schema.oneOf && schema.oneOf.length > 0) {\n return synthesizeFromSchema(schema.oneOf[0], hint, warnings, depth + 1, ordinal);\n }\n if (schema.anyOf && schema.anyOf.length > 0) {\n return synthesizeFromSchema(schema.anyOf[0], hint, warnings, depth + 1, ordinal);\n }\n\n // Draft-07 type array (`['string','null']` — the canonical nullable\n // form since draft-2026-08-19): synthesize from the first non-null\n // member ('null' only when it is the sole member). The depth guard\n // above bounds the recursion.\n if (Array.isArray(schema.type)) {\n const primary = schema.type.find((t) => t !== \"null\") ?? \"null\";\n return synthesizeFromSchema({ ...schema, type: primary }, hint, warnings, depth + 1, ordinal);\n }\n\n switch (schema.type) {\n case \"string\": {\n // Format-aware placeholder\n switch (schema.format) {\n case \"date\":\n case \"date-time\":\n return { kind: \"ok\", value: \"2026-04-13T12:00:00Z\", source: \"schema-synth\" };\n case \"email\":\n return { kind: \"ok\", value: \"user@example.com\", source: \"schema-synth\" };\n case \"uri\":\n case \"url\":\n return { kind: \"ok\", value: \"https://example.com\", source: \"schema-synth\" };\n case \"uuid\":\n return { kind: \"ok\", value: \"00000000-0000-0000-0000-000000000000\", source: \"schema-synth\" };\n default: {\n // Use field name as a hint so it appears in DOM and prop-coverage check sees it.\n // Capitalize first letter for natural-looking placeholder.\n const cap = hint.charAt(0).toUpperCase() + hint.slice(1);\n // Inside an array element every string is distinct per element.\n const value = ordinal === undefined ? `Sample ${cap}` : `Sample ${cap} ${ordinal}`;\n return { kind: \"ok\", value, source: \"schema-synth\" };\n }\n }\n }\n\n case \"integer\":\n case \"number\": {\n const min = typeof schema.minimum === \"number\" ? schema.minimum : 1;\n const max = typeof schema.maximum === \"number\" ? schema.maximum : 100;\n const value = Math.min(max, Math.max(min, 42));\n return { kind: \"ok\", value, source: \"schema-synth\" };\n }\n\n case \"boolean\":\n return { kind: \"ok\", value: true, source: \"schema-synth\" };\n\n case \"null\":\n return { kind: \"ok\", value: null, source: \"schema-synth\" };\n\n case \"array\": {\n if (!schema.items) {\n return { kind: \"ok\", value: [], source: \"schema-synth\" };\n }\n // Synthesize 2 items so list-rendering checks (length > 0) pass.\n const items: JsonValue[] = [];\n for (let i = 0; i < 2; i++) {\n const itemHint = `${hint}Item${i + 1}`;\n const itemSynth = synthesizeFromSchema(schema.items, itemHint, warnings, depth + 1, i + 1);\n if (itemSynth.kind === \"ok\") {\n // Inject an `id` for list-key purposes if the item is an object lacking one.\n if (\n itemSynth.value !== null &&\n typeof itemSynth.value === \"object\" &&\n !Array.isArray(itemSynth.value) &&\n !(\"id\" in itemSynth.value)\n ) {\n (itemSynth.value as JsonObject).id = `${hint}-${i + 1}`;\n }\n items.push(itemSynth.value);\n }\n }\n return { kind: \"ok\", value: items, source: \"schema-synth\" };\n }\n\n case \"object\": {\n const obj: JsonObject = {};\n const propsMap = schema.properties ?? {};\n const required = new Set(schema.required ?? []);\n for (const [k, sub] of Object.entries(propsMap)) {\n const subSynth = synthesizeFromSchema(sub, k, warnings, depth + 1, ordinal);\n if (subSynth.kind === \"ok\") {\n obj[k] = subSynth.value;\n } else if (required.has(k)) {\n warnings.push(\n `Required object field '${hint}.${k}' could not be synthesized (${subSynth.reason})`,\n );\n }\n }\n return { kind: \"ok\", value: obj, source: \"schema-synth\" };\n }\n\n default:\n return { kind: \"fail\", reason: `unsupported schema type: ${schema.type ?? \"unknown\"}` };\n }\n}\n","// packages/ui-gen/src/harness/check/runtime-render/adapter.ts\n//\n// Adapter: convert RenderCheckResult → EvalIssue[] so runtime-render\n// integrates with the rest of the eval pipeline (axisChecks, tierChecks,\n// llmEvaluator). Fits the RuntimeRenderCheck interface from harness/types.ts.\n\nimport type { EvalIssue } from \"../../../evaluation/types-public.js\";\nimport type { RuntimeRenderCheck } from \"../../types-public.js\";\nimport {\n RENDER_CHECK_KINDS,\n runRenderCheck,\n type RenderCheckIssue,\n type RenderCheckKind,\n type RunRenderCheckOptions,\n} from \"./render-check.js\";\nimport { resolveRenderCheckHostBounds } from \"./render-check-host.js\";\nimport { prepareMockupProps } from \"./prepare-mockup.js\";\n\n/**\n * How one runtime-render check instance runs its isolated worker\n * (ggui#1380). A serving deployment sets the probe's wall-clock bound,\n * worker heap and concurrency here; every field omitted is the evaluation\n * lane's behaviour — the host's default bounds and no concurrency cap.\n */\nexport interface RuntimeRenderProbeConfig {\n /** Wall-clock bound of one isolated check, ms. Default: the host's (30 000). */\n readonly timeoutMs?: number;\n /** V8 heap cap of the worker, MB. Default: the host's (512). */\n readonly heapMb?: number;\n /**\n * Live workers this instance may have at once. The (K+1)th check waits\n * in FIFO order and spawns only when a slot frees; a check that throws\n * releases its slot. Default: unbounded. Must be a positive integer.\n */\n readonly maxConcurrent?: number;\n}\n\n/**\n * K-slot FIFO limiter. `undefined` slots = no limiter (the task runs at\n * once). A slot is released in `finally`, so a rejected task never holds\n * one.\n */\nfunction createSlotLimiter(\n maxConcurrent: number | undefined\n): <T>(task: (waitedMs: number) => Promise<T>) => Promise<T> {\n if (maxConcurrent === undefined) return (task) => task(0);\n if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) {\n throw new RangeError(\n `createRuntimeRenderCheck: maxConcurrent must be a positive integer, got ${maxConcurrent}`\n );\n }\n let active = 0;\n const waiting: Array<() => void> = [];\n /** Resolves with the time the caller actually WAITED for a slot: 0 when one was free. */\n const acquire = (): Promise<number> => {\n if (active < maxConcurrent) {\n active += 1;\n return Promise.resolve(0);\n }\n const enqueuedAt = Date.now();\n return new Promise<number>((resolve) => {\n waiting.push(() => {\n active += 1;\n resolve(Date.now() - enqueuedAt);\n });\n });\n };\n const release = (): void => {\n active -= 1;\n const next = waiting.shift();\n if (next !== undefined) next();\n };\n return async (task) => {\n const waitedMs = await acquire();\n try {\n return await task(waitedMs);\n } finally {\n release();\n }\n };\n}\n\n/** `{ queuedMs }` when the check actually waited for a slot, `{}` when one was free. */\nfunction queuedField(queuedMs: number): { readonly queuedMs?: number } {\n return queuedMs > 0 ? { queuedMs } : {};\n}\n\n/** The `runRenderCheck` options a config maps to — `undefined` when no bound is set. */\nfunction toRenderCheckOptions(config: RuntimeRenderProbeConfig): RunRenderCheckOptions | undefined {\n if (config.timeoutMs === undefined && config.heapMb === undefined) return undefined;\n return {\n bounds: {\n ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n ...(config.heapMb !== undefined ? { heapMb: config.heapMb } : {}),\n },\n };\n}\n\n/**\n * Build a runtime-render check instance. One FIFO limiter per instance;\n * the bounds reach `runRenderCheck` on every run. `createRuntimeRenderCheck()`\n * with no config is {@link DEFAULT_RUNTIME_RENDER_CHECK}'s behaviour.\n */\nexport function createRuntimeRenderCheck(\n config: RuntimeRenderProbeConfig = {}\n): RuntimeRenderCheck {\n const limit = createSlotLimiter(config.maxConcurrent);\n const options = toRenderCheckOptions(config);\n // A bad bound is refused here, at construction, never at the first probe.\n if (options !== undefined) resolveRenderCheckHostBounds(options.bounds);\n return {\n id: \"runtime-render\",\n run: async (input) => {\n const { sourceCode, compiledCode, contract, fixtureProps } = input;\n\n // Nothing to render / no contract surface to verify — the probe has\n // no subject, which is different from the probe failing to run.\n if (compiledCode === null) {\n return { status: \"not-applicable\", issues: [], reason: \"no compiled code\" };\n }\n if (!contract) {\n return { status: \"not-applicable\", issues: [], reason: \"no contract surface\" };\n }\n\n const mockup = prepareMockupProps({ contract, fixtureProps });\n\n // ggui#1380 — the adapter's own clock around the check: every status\n // that reached the check (`ran`, `timed-out`, `infra-skipped`) reports\n // how long it took, so a reader of the probe meta can tell a 2 s probe\n // from a 30 s one on the same status. The two not-applicable returns\n // above carry nothing: nothing ran.\n // The clock starts when the slot is acquired, so `elapsedMs` is the\n // check's own wall-clock; the time the check actually WAITED for a slot\n // is `queuedMs` (present only when it queued) — a latency reader needs\n // the two apart exactly when a serving deployment queues more probes\n // than it has slots. A check that found a slot free carries no key.\n let queuedMs = 0;\n let t0 = Date.now();\n let result;\n try {\n result = await limit((waitedMs) => {\n queuedMs = waitedMs;\n t0 = Date.now();\n return runRenderCheck(\n {\n sourceCode,\n mockupProps: mockup.props,\n contract,\n },\n options\n );\n });\n } catch (e) {\n // Triad audit (2026-04-27): every error that escapes `runRenderCheck`\n // is an INFRA problem — happy-dom import failure, ESM/CJS interop\n // (`Dynamic require of \"events\"`), bundler name collision (`Window2\n // is not a constructor`), missing `@testing-library/react`, etc.\n // Component-level failures are caught and emitted as `RenderCheckIssue`\n // entries from inside `runRenderCheck`; they don't propagate out.\n //\n // An infra failure must never become an eval issue (the coding\n // agent can't fix the environment — pre-2026-04-27 that phantom\n // issue dragged every score-below-80 cell's eval-fix loop), but it\n // must also never be silent to scoring: ggui#403 found the bench\n // reporting `probe_pass 3/3` on cells where this branch fired on\n // every invocation. The `infra-skipped` status is the No-Silent-\n // Block channel — consumers surface it as did-not-run, never pass.\n const message = e instanceof Error ? e.message : String(e);\n console.warn(`[runtime-render] probe skipped — infra failure: ${message}`);\n return { status: \"infra-skipped\", issues: [], reason: message, elapsedMs: Date.now() - t0, ...queuedField(queuedMs) };\n }\n\n const hostLoad = result.stats.hostLoad;\n const load = hostLoad !== undefined ? { hostLoad } : {};\n\n // ggui#1299: a check that ran out of wall-clock time is not a verdict on\n // the component. It becomes the `timed-out` status (did-not-run, never a\n // pass, never a crash), never an eval issue — so the coding agent is never\n // told to fix a crash that did not happen.\n if (result.incomplete !== undefined) {\n const { elapsedMs, boundMs } = result.incomplete;\n const loadNote =\n hostLoad !== undefined\n ? `; host load ${hostLoad.start.toFixed(1)} → ${hostLoad.end.toFixed(1)} on ${hostLoad.cores} CPUs`\n : \"\";\n const reason = `render check did not finish within ${boundMs} ms (stopped at ${elapsedMs} ms)${loadNote}`;\n console.warn(`[runtime-render] probe timed out — ${reason}`);\n // One clock for every status that reached the worker: the adapter's\n // wall-clock around the check. The worker's own reading survives in\n // `reason` (\"stopped at N ms\").\n return { status: \"timed-out\", issues: [], reason, elapsedMs: Date.now() - t0, ...queuedField(queuedMs), ...load };\n }\n\n return {\n status: \"ran\",\n issues: result.issues.map(toEvalIssue).filter((x): x is EvalIssue => x !== null),\n elapsedMs: Date.now() - t0,\n ...queuedField(queuedMs),\n renderMs: result.stats.renderMs,\n ...load,\n };\n },\n };\n}\n\n/** The evaluation lane's instance: the host's default bounds, no concurrency cap. */\nexport const DEFAULT_RUNTIME_RENDER_CHECK: RuntimeRenderCheck = createRuntimeRenderCheck();\n\n/**\n * Map a runtime-render crash reason to a class-specific fix string.\n *\n * The default fix (\"add null guards on optional props…\") is too generic\n * for the LLM to act on. Observed crash classes from n=3 benches:\n * - \"Too many re-renders\" / \"Maximum update depth exceeded\" — setState\n * during render, or in a useEffect with missing/unstable deps. The\n * diagnosis MUST point at useEffect/useState patterns, not null guards.\n * - \"Cannot access 'X' before initialization\" — TDZ, usually from\n * referencing a `let`/`const` in a useEffect deps array (or default\n * value) before its declaration line. Fix is reorder, not null-guard.\n * - \"X is not defined\" — typo or missing destructure. Fix is grep + fix\n * the symbol, not null-guard.\n * - \"X is not iterable\" / \"Cannot read property … of undefined/null\" —\n * defaulting/optional-chaining; the original generic fix applies.\n */\n/**\n * Public probe-classification surface for the in-loop runtime probe.\n *\n * Two helpers:\n * - `classifyRenderCrashFix(reason)` returns the class-specific fix\n * string. Exported so the eval-round runner can build a\n * `[runtime]` violation for the coding agent at exit-decision time.\n * - `isRecoverableRenderCrash(reason)` is a boolean variant — true\n * when `classifyRenderCrashFix` returns a CLASS-SPECIFIC string\n * (i.e., one of: re-render loop, TDZ, undeclared symbol, non-array\n * iteration, null/undefined access). False when the reason falls\n * through to the generic fallback.\n *\n * \"Recoverable\" is harness terminology, not a runtime certainty: it\n * means the LLM has a reasonable chance of fixing the crash given the\n * class-specific advice. The generic fallback (\"add null guards on\n * optional props…\") is too vague to recover from in one turn.\n */\nconst CLASS_SPECIFIC_PATTERNS: ReadonlyArray<RegExp> = [\n /too many re-renders/i,\n /maximum update depth/i,\n /infinite render loop/i,\n /cannot access\\s+'[^']+'\\s+before initialization/i,\n /\\b\\w+ is not defined\\b/i,\n /is not iterable/i,\n /symbol\\(symbol\\.iterator\\)/i,\n /cannot read propert(?:y|ies) of (?:undefined|null)/i,\n /undefined is not/i,\n /null is not/i,\n];\n\nexport function isRecoverableRenderCrash(reason: string): boolean {\n return CLASS_SPECIFIC_PATTERNS.some((rx) => rx.test(reason));\n}\n\nexport function classifyRenderCrashFix(reason: string): string {\n const r = reason.toLowerCase();\n if (\n r.includes(\"too many re-renders\") ||\n r.includes(\"maximum update depth\") ||\n r.includes(\"infinite render loop\")\n ) {\n return (\n \"Find the setState/dispatch call in your render body or useEffect. \" +\n \"Either: (a) move the setState into an event handler, (b) add a proper \" +\n \"useEffect dependency array so it doesn't fire every render, or (c) \" +\n \"guard the setState with an equality check `if (next !== current) setX(next)`. \" +\n \"Do NOT call setState in render or useEffect-without-deps.\"\n );\n }\n if (r.includes(\"cannot access\") && r.includes(\"before initialization\")) {\n const symMatch = reason.match(/'([^']+)'/);\n const sym = symMatch ? symMatch[1] : \"the variable\";\n return (\n `Temporal-dead-zone error on \\`${sym}\\`. You're referencing ${sym} ` +\n `(likely in a useEffect dependency array or a default value) BEFORE ` +\n `its \\`const\\`/\\`let\\` declaration. Move the declaration of ${sym} ` +\n `to the top of the component body, before any useEffect/useMemo/` +\n `useCallback that reads it.`\n );\n }\n if (r.includes(\"is not defined\")) {\n const symMatch = reason.match(/(\\w+) is not defined/);\n const sym = symMatch ? symMatch[1] : \"the symbol\";\n return (\n `ReferenceError: \\`${sym}\\` is used in JSX/expression but never ` +\n `declared. Either: (a) add a \\`const ${sym} = ...\\` declaration in ` +\n `the component body, (b) destructure it from props/state, or (c) ` +\n `fix the typo if you meant a similarly-named local.`\n );\n }\n if (r.includes(\"is not iterable\") || r.includes(\"symbol(symbol.iterator)\")) {\n return (\n \"Render iterated over a non-array. Find the `for...of`, `[...spread]`, \" +\n \"or `.map`/`.filter`/`.reduce` call that crashed and either: (a) \" +\n \"default the value to `[]` (`const items = props.items ?? []`), or \" +\n \"(b) check it's an array before iterating (`Array.isArray(x) && ...`).\"\n );\n }\n if (r.includes(\"cannot read\") || r.includes(\"undefined is not\") || r.includes(\"null is not\")) {\n return (\n \"Null/undefined access. Add optional chaining (`obj?.field`) and \" +\n \"default values for optional props/state before reading nested fields. \" +\n \"Check your destructure patterns — destructuring undefined throws.\"\n );\n }\n // Fallback for unrecognized crash classes — keep the original advice.\n return (\n \"Add null guards on optional props, handle empty arrays/strings, \" +\n \"and verify all hook outputs before destructuring.\"\n );\n}\n\n/** The prefix every probe issue's subcategory carries: `runtime:<check>[:<subject>]`. */\nconst RUNTIME_SUBCATEGORY_PREFIX = \"runtime:\";\n\n/**\n * The check a probe issue's subcategory names (ggui#1380) — the inverse of\n * the `runtime:<check>[:<subject>]` form {@link toEvalIssue} writes, so a\n * round can list WHICH checks failed from the issues alone. `undefined` for\n * anything that is not a probe subcategory naming a member of\n * {@link RENDER_CHECK_KINDS} (an axis check's subcategory, a did-not-run\n * code such as `runtime:probe-timeout`, a bare check name).\n */\nexport function parseRuntimeSubcategory(subcategory: string): RenderCheckKind | undefined {\n if (!subcategory.startsWith(RUNTIME_SUBCATEGORY_PREFIX)) return undefined;\n const rest = subcategory.slice(RUNTIME_SUBCATEGORY_PREFIX.length);\n const separator = rest.indexOf(\":\");\n const check = separator === -1 ? rest : rest.slice(0, separator);\n return RENDER_CHECK_KINDS.find((kind) => kind === check);\n}\n\n/**\n * One probe finding → the eval issue the loop feeds back and the metadata\n * counts. Exported for the pin that every switch case below is a member of\n * {@link RENDER_CHECK_KINDS} and round-trips through\n * {@link parseRuntimeSubcategory}.\n */\nexport function toEvalIssue(issue: RenderCheckIssue): EvalIssue | null {\n // verified → no issue (silent pass)\n if (issue.outcome === \"verified\" || issue.outcome === \"skipped\") return null;\n\n // unverified → warn (non-blocking — wiring may exist, just not deterministically simulable)\n // failed → fail (blocker — strong evidence the wiring should work but didn't)\n const result: \"fail\" | \"warn\" = issue.outcome === \"failed\" ? \"fail\" : \"warn\";\n\n const subject = issue.subject ?? \"\";\n const subcategory = subject ? `runtime:${issue.check}:${subject}` : `runtime:${issue.check}`;\n const elementHint = issue.elementHint ? ` (element: ${issue.elementHint})` : \"\";\n\n // Build a diagnostic suffix that gives the coding agent observable context.\n const diag = issue.diagnostics;\n const diagParts: string[] = [];\n if (diag?.observedNativeProps?.length) {\n diagParts.push(`native props: ${diag.observedNativeProps.join(\", \")}`);\n }\n if (diag?.observedCustomProps?.length) {\n diagParts.push(`custom props: ${diag.observedCustomProps.join(\", \")}`);\n }\n if (diag?.observedJsxElements?.length) {\n diagParts.push(`elements: ${diag.observedJsxElements.slice(0, 4).join(\", \")}`);\n }\n if (diag?.actionsFiredFromClicks?.length) {\n diagParts.push(`other actions fired from clicks: ${diag.actionsFiredFromClicks.join(\", \")}`);\n }\n if (diag?.inputPriming) {\n // ggui#1187: an input-gated action that \"did not dispatch\" reads\n // differently beside \"primed 0\" / a priming error than beside \"primed 1\".\n diagParts.push(\n \"primed\" in diag.inputPriming\n ? `input priming: ${diag.inputPriming.primed} control(s) filled before the click`\n : `input priming failed: ${diag.inputPriming.error}`\n );\n }\n const diagSuffix = diagParts.length ? ` [observed: ${diagParts.join(\"; \")}]` : \"\";\n\n switch (issue.check) {\n case \"render-no-throw\":\n return {\n tier: 0,\n result,\n category: \"crash\",\n subcategory,\n severity: \"critical\",\n description: `Component crashed at runtime: ${issue.reason}`,\n fix: classifyRenderCrashFix(issue.reason),\n };\n\n case \"optional-props-omitted\":\n // Same crash class as render-no-throw, surfaced by the second\n // render pass with optional props stripped (ggui#528): the wire\n // gate only requires `required: true` props, so a legitimate\n // render may omit these and the component must survive it.\n return {\n tier: 0,\n result,\n category: \"crash\",\n subcategory,\n severity: \"critical\",\n description: `Component crashed when optional props were omitted: ${issue.reason}`,\n fix:\n `Guard every optional prop before member access (props.${subject.split(\",\")[0]?.trim() ?? \"x\"}?.map(...), ` +\n `a default via destructuring, or an early empty-state return). Optional props (no \\`required: true\\` in the contract) ` +\n `may be absent at runtime even though the harness fills them.`,\n };\n\n case \"action-wiring\": {\n const fix =\n issue.outcome === \"unverified\"\n ? `Source shows the action callback flowing into a non-native or custom-component prop. If wiring is intentional (e.g., Dropdown.onChange, drag-drop), this warn is informational — manual/browser verification is required to confirm. Otherwise wire to a native onClick={() => ${subject}(payload)} on <button> or design-system <Button>.`\n : `Wire ${subject}() to a native event prop. Common fix: <Button onClick={() => ${subject}(payload)}>Label</Button>. Source-AST analysis didn't find this wiring in your JSX.`;\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n severity: result === \"fail\" ? \"critical\" : \"major\",\n description: `${issue.reason}${elementHint}${diagSuffix}`,\n fix,\n };\n }\n\n case \"selection-identity\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n severity: \"critical\",\n description: `${issue.reason}${elementHint}${diagSuffix}`,\n fix:\n `Key the action payload (and any selection state) on the item's ID from the data, never on its display text. ` +\n `Common fix: map over items and pass the item's id into the handler — onClick={() => ${subject}({ ...payload, id: item.id })} — ` +\n `and store selection as the id (setSelected(item.id)), not the label.`,\n };\n\n case \"prop-sensitivity\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n severity: \"critical\",\n description: `${issue.reason}${diagSuffix}`,\n fix:\n `Derive the display AND any logic from props.${subject} — render {props.${subject}} and branch on the prop's value, ` +\n `never on the literal value the request happened to mention (e.g. props.${subject} ?? 'January' followed by ` +\n `January-special-cased logic bakes the request into the component). The contract delivers the value; trust it.`,\n };\n\n case \"prop-coverage\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n description: `${issue.reason}${diagSuffix}`,\n fix: `Render props.${subject} somewhere in the JSX (e.g., <Text>{props.${subject}}</Text>). If you display a derived/formatted version, this warn may be a false positive.`,\n };\n\n case \"stream-rerender\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n description: `${issue.reason}${diagSuffix}`,\n fix: `Subscribe with const ${subject} = useStream('${subject}'); render ${subject}.latest && <Text>{${subject}.latest.field}</Text> or .all.map(...).`,\n };\n }\n}\n","// packages/ui-gen/src/harness/check/runtime-render/index.ts\n//\n// Public surface for runtime render evaluation.\n//\n// runRenderCheck() takes a compiled component + mockup props + contract,\n// renders it in happy-dom with a probe-backed WireConfig, and verifies:\n// - it renders without throw (block)\n// - declared actions fire when the bound UI is clicked (block)\n// - declared props appear in the DOM (warn)\n// - declared stream events update the DOM when emitted (warn)\n\nimport { installProductionActShim } from \"./production-act-shim.js\";\nimport type { RenderCheckHostBounds } from \"./render-check-host.js\";\n\nexport {\n RENDER_CHECK_KINDS,\n runRenderCheck,\n type RenderCheckKind,\n type RenderCheckResult,\n type RenderCheckIssue,\n} from \"./render-check.js\";\nexport { createProbe, createProbeWireConfig, type Probe } from \"./probe.js\";\nexport { prepareMockupProps, type MockupPropsResult } from \"./prepare-mockup.js\";\nexport {\n DEFAULT_RUNTIME_RENDER_CHECK,\n classifyRenderCrashFix,\n createRuntimeRenderCheck,\n isRecoverableRenderCrash,\n parseRuntimeSubcategory,\n type RuntimeRenderProbeConfig,\n} from \"./adapter.js\";\nexport type { RenderCheckHostBounds, RenderCheckHostOptions } from \"./render-check-host.js\";\n\n/**\n * Pre-warm the runtime-render probe's runtime dependencies so the first\n * actual probe call hits a warm Node module cache.\n *\n * The probe lazily loads `happy-dom`, `@testing-library/react`,\n * `@testing-library/user-event`, and `@ggui-ai/wire` on first invocation\n * — total cold cost ~700-1500ms. Bench runners can call this once at\n * startup to amortize that cost; subsequent per-cell probe calls fall\n * to ~50-200ms.\n *\n * Resolves these specifiers from THIS module's filesystem location, so\n * Node walks up from `packages/ui-gen/dist/harness/check/runtime-render/`\n * to find them in `packages/ui-gen/node_modules/...`. Bench callers\n * cannot pre-import them directly — they aren't in the bench package's\n * own `node_modules`.\n *\n * Fire-and-forget. If a dep is missing the per-cell probe will surface\n * the error on first use; pre-warm just no-ops on import failure.\n *\n * Returns the wall-clock spent loading.\n */\nexport async function warmupRuntimeRenderProbe(): Promise<{\n ms: number;\n loaded: number;\n missing: number;\n}> {\n const start = Date.now();\n let loaded = 0;\n let missing = 0;\n const tryLoad = async (specifier: string) => {\n try {\n await import(specifier);\n loaded += 1;\n } catch {\n missing += 1;\n }\n };\n // Must run before RTL's first import in this process — hosts that\n // call this warmup at process start (server-side blueprint\n // validation) land RTL in the module cache, with its act snapshot\n // taken, here — long before the first real probe call. See\n // production-act-shim.ts's docstring for why.\n installProductionActShim();\n await Promise.all([\n tryLoad(\"happy-dom\"),\n tryLoad(\"@testing-library/react\"),\n tryLoad(\"@testing-library/user-event\"),\n tryLoad(\"@ggui-ai/wire\"),\n ]);\n return { ms: Date.now() - start, loaded, missing };\n}\n\n/**\n * The component the boot warm renders: a constant element, an empty\n * contract — nothing to click, nothing to cover, one compile and one\n * render in the worker.\n */\nconst WARMUP_COMPONENT = \"export default function Warmup() { return <div>warm</div>; }\";\n\n/**\n * Warm the PROCESS that runs every probe (ggui#1380): spawn one real check\n * worker on a trivial component through the same host every probe uses.\n * Afterwards the node binary, the worker's module tree and esbuild's\n * service have all run once on this machine (OS page cache warm), and the\n * result says whether that process can run a check at all — which\n * `warmupRuntimeRenderProbe` (an import in THIS process) cannot tell.\n *\n * `bounds` are the subprocess bounds for the one run; a serving deployment\n * passes the same bounds it will probe with. Never throws: a worker that\n * cannot run is `{ ok: false, reason }`, so a boot sequence can log it and\n * decide, instead of dying in a fire-and-forget.\n */\nexport async function warmupRuntimeRenderWorker(\n bounds?: Partial<RenderCheckHostBounds>\n): Promise<{ ok: true; ms: number } | { ok: false; ms: number; reason: string }> {\n const start = Date.now();\n try {\n // Lazy: the host pulls `@ggui-ai/sandbox` (spawn machinery); keep it off\n // the import graph of everything that only needs the in-process check.\n const { runRenderCheckViaWorker } = await import(\"./render-check-host.js\");\n const result = await runRenderCheckViaWorker(\n { sourceCode: WARMUP_COMPONENT, mockupProps: {}, contract: {} },\n bounds !== undefined ? { bounds } : {}\n );\n const ms = Date.now() - start;\n if (result.incomplete !== undefined) {\n return {\n ok: false,\n ms,\n reason: `the warm-up check did not finish within ${result.incomplete.boundMs} ms (stopped at ${result.incomplete.elapsedMs} ms)`,\n };\n }\n const blocking = result.issues.find(\n (i) => i.outcome === \"failed\" || i.outcome === \"unverified\"\n );\n if (blocking !== undefined) {\n return { ok: false, ms, reason: `${blocking.check} ${blocking.outcome}: ${blocking.reason}` };\n }\n return { ok: true, ms };\n } catch (err) {\n // The host itself never throws for a worker fault; what reaches here is\n // the spawn layer refusing to run at all (an invalid bound, no binary).\n return {\n ok: false,\n ms: Date.now() - start,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../../src/internal/verdict-line.ts","../../../../src/harness/check/runtime-render/render-check-host.ts","../../../../src/harness/check/runtime-render/production-act-shim.ts","../../../../src/harness/check/runtime-render/probe.ts","../../../../src/internal/evaluate-component-source.ts","../../../../src/harness/check/runtime-render/load-component.ts","../../../../src/harness/check/runtime-render/find-wiring.ts","../../../../src/internal/open-record.ts","../../../../src/harness/check/runtime-render/host-boundary.ts","../../../../src/harness/check/runtime-render/probe-pending.ts","../../../../src/harness/check/runtime-render/walk.ts","../../../../src/harness/check/runtime-render/render-check.ts","../../../../src/harness/check/runtime-render/prepare-mockup.ts","../../../../src/harness/check/runtime-render/adapter.ts","../../../../src/harness/check/runtime-render/index.ts"],"names":["createRequire","runRenderCheckViaWorker"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBO,SAAS,iBAA0B,MAAA,EAAqC;AAC7E,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA;AAC/B,EAAA,KAAA,IAAS,IAAI,KAAA,CAAM,MAAA,GAAS,GAAG,CAAA,IAAK,CAAA,EAAG,KAAK,CAAA,EAAG;AAC7C,IAAA,MAAM,IAAA,GAAO,MAAM,CAAC,CAAA;AACpB,IAAA,IAAI,IAAA,CAAK,UAAA,CAAW,CAAA,EAAG,cAAc,GAAG,CAAA,EAAG,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,cAAA,CAAe,MAAA,GAAS,CAAC,CAAC,CAAA;AAAA,EACpG;AACA,EAAA,OAAO,MAAA;AACT;AAhCA,IAaa,cAAA;AAbb,IAAA,iBAAA,GAAA,KAAA,CAAA;AAAA,EAAA,8BAAA,GAAA;AAaO,IAAM,cAAA,GAAiB,+BAAA;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACb9B,IAAA,yBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,yBAAA,EAAA;AAAA,EAAA,gCAAA,EAAA,MAAA,gCAAA;AAAA,EAAA,6BAAA,EAAA,MAAA,6BAAA;AAAA,EAAA,4BAAA,EAAA,MAAA,4BAAA;AAAA,EAAA,kBAAA,EAAA,MAAA,kBAAA;AAAA,EAAA,uBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AA2FO,SAAS,4BAAA,CACd,MAAA,GAAyC,EAAC,EACnB;AACvB,EAAA,MAAM,SAAA,GAAY,MAAA,CAAO,SAAA,IAAa,g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A,GAAW,OAAO,MAAA,CAAO,IAAA;AAAA,MAC7B,CAAC,CAAA,KAAM,CAAA,CAAE,OAAA,KAAY,QAAA,IAAY,EAAE,OAAA,KAAY;AAAA,KACjD;AACA,IAAA,IAAI,aAAa,KAAA,CAAA,EAAW;AAC1B,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,EAAA,EAAI,QAAQ,CAAA,EAAG,QAAA,CAAS,KAAK,CAAA,CAAA,EAAI,QAAA,CAAS,OAAO,CAAA,EAAA,EAAK,QAAA,CAAS,MAAM,CAAA,CAAA,EAAG;AAAA,IAC9F;AACA,IAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,EAAA,EAAG;AAAA,EACxB,SAAS,GAAA,EAAK;AAGZ,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,EAAA,EAAI,IAAA,CAAK,GAAA,EAAI,GAAI,KAAA;AAAA,MACjB,QAAQ,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,KACzD;AAAA,EACF;AACF","file":"index.js","sourcesContent":["/**\n * How an isolated worker that runs generated component code (the\n * runtime-render check's, the render smoke test's) hands its verdict to its\n * host.\n *\n * The worker's stdout is shared with the component: card code runs in the\n * worker's own realm with Node's `console`, so a card that logs even one line\n * would corrupt a verdict read as \"the whole of stdout\". The verdict\n * therefore goes out on one line carrying {@link VERDICT_PREFIX}, and the\n * host reads the LAST such line, ignoring everything else.\n */\n\n/** The prefix of the verdict line. Not a string a card would print by accident. */\nexport const VERDICT_PREFIX = '@@ggui-render-check-verdict@@';\n\n/** The worker's verdict line, newline-terminated. */\nexport function formatVerdictLine(value: unknown): string {\n return `${VERDICT_PREFIX} ${JSON.stringify(value)}\\n`;\n}\n\n/**\n * The value on the last verdict line in `stdout`, or `undefined` when no\n * line carries the prefix. A prefixed line that is not JSON throws, so the\n * host can report it as such.\n */\nexport function parseVerdictLine<Verdict>(stdout: string): Verdict | undefined {\n const lines = stdout.split('\\n');\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const line = lines[i]!;\n if (line.startsWith(`${VERDICT_PREFIX} `)) return JSON.parse(line.slice(VERDICT_PREFIX.length + 1)) as Verdict;\n }\n return undefined;\n}\n","/**\n * Host side of the isolated runtime render check (#592).\n *\n * Spawns `render-check-worker.ts` in a sandboxed subprocess and maps\n * every sandbox outcome onto the check's own `RenderCheckResult`\n * vocabulary, so callers see one result shape whether the check ran\n * in-process (DOM-owning environments) or isolated (plain Node).\n *\n * Outcome mapping policy (mirrors the adapter's escaped-error\n * doctrine — component faults are `failed`, harness faults are\n * `unverified`, and nothing throws):\n *\n * - worker exit 0 + parseable verdict → the verdict, verbatim.\n * - timeout → `incomplete` (ggui#1299): the check\n * did not finish, which is NOT a verdict on the component. The bound\n * is wall-clock, and on a contended host an ordinary component\n * crosses it; mapping it to `failed` reported crashes that never\n * happened. It carries its elapsed ms, and the host load (below)\n * says how busy the host was. React's own runaway guards (\"Too many\n * re-renders\", \"Maximum update depth exceeded\") throw, so they still\n * reach `render-no-throw` as `failed`; what now reads `incomplete`\n * is a check that ran out of wall-clock time, whatever the cause.\n * - overflow → `failed` (a pathological logging or\n * error loop; output volume does not depend on host load).\n * - spawn-error / non-zero exit / unparseable stdout\n * → `unverified` (the harness could not\n * run the check; never blame the component for our plumbing).\n *\n * Every isolated check records the host's 1-minute load average at its\n * start and end, and the CPUs available, on `stats.hostLoad`.\n *\n * Spawn resolution copies the proven `src/tools/render-check.ts`\n * pattern: prefer the built `dist/.../render-check-worker.js`; in\n * dev/test (vitest imports `src/`), fall back to `node --import tsx`\n * on the `.ts` source. tsup inlines THIS module into several dist\n * entries (`dist/index.js`, `dist/harness/index.js`,\n * `dist/check/index.js`, `dist/advanced/index.js`, …), so the\n * candidate list walks from each of those locations to the one real\n * `dist/harness/check/runtime-render/render-check-worker.js`.\n */\nimport { existsSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { availableParallelism, loadavg } from 'node:os';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { runSandboxed } from '@ggui-ai/sandbox';\nimport type { SandboxResult } from '@ggui-ai/sandbox';\nimport type { ProbeHostLoad } from '../../../evaluation/types-public.js';\nimport type { RenderCheckResult, RunRenderCheckInput } from './render-check.js';\nimport { parseVerdictLine } from '../../../internal/verdict-line.js';\n\n/**\n * The subprocess bounds of one isolated check (ggui#1380). They are\n * INPUTS of the host, not constants: a serving deployment runs the probe\n * under its own memory and latency budget and sets them per check\n * instance (`createRuntimeRenderCheck`); the evaluation lane runs on the\n * defaults below, which are the values the host always used.\n */\nexport interface RenderCheckHostBounds {\n /**\n * Wall-clock bound for one isolated check. The rich probe renders,\n * clicks every declared action, and re-renders streams — slower than\n * the smoke worker's 12s budget; 30s bounds runaway components while\n * staying far under any generation-turn budget.\n */\n readonly timeoutMs: number;\n /**\n * V8 heap cap. The worker realm loads react-dom, happy-dom and\n * testing-library on top of the component itself; 512 MB leaves\n * headroom while still bounding pathological allocation.\n */\n readonly heapMb: number;\n /**\n * Grace between SIGTERM and SIGKILL once the bound is crossed. The\n * effective value is `min(gracePeriodMs, floor(timeoutMs / 2))` —\n * `runSandboxed` requires the grace to be strictly below the bound, so\n * a short bound never trips its RangeError.\n */\n readonly gracePeriodMs: number;\n}\n\nexport const DEFAULT_RENDER_CHECK_HOST_BOUNDS: RenderCheckHostBounds = {\n timeoutMs: 30_000,\n heapMb: 512,\n gracePeriodMs: 2_000,\n};\n\n/**\n * Fill the caller's partial bounds from the defaults and clamp the grace\n * below the bound. Exported so the kill-path pin can run a fixture under\n * exactly the numbers the host would pass for the same input.\n */\nexport function resolveRenderCheckHostBounds(\n bounds: Partial<RenderCheckHostBounds> = {},\n): RenderCheckHostBounds {\n const timeoutMs = bounds.timeoutMs ?? DEFAULT_RENDER_CHECK_HOST_BOUNDS.timeoutMs;\n const heapMb = bounds.heapMb ?? DEFAULT_RENDER_CHECK_HOST_BOUNDS.heapMb;\n // Refused at construction, like `maxConcurrent`: a 0 / NaN / fractional\n // bound would otherwise flow into the sandbox's flags as a nonsense number.\n // `timeoutMs` needs room for a grace of at least 1 ms below it.\n if (!Number.isInteger(timeoutMs) || timeoutMs < 2) {\n throw new RangeError(`render-check: timeoutMs must be an integer ≥ 2, got ${timeoutMs}`);\n }\n if (!Number.isInteger(heapMb) || heapMb < 1) {\n throw new RangeError(`render-check: heapMb must be a positive integer, got ${heapMb}`);\n }\n const requestedGrace = bounds.gracePeriodMs ?? DEFAULT_RENDER_CHECK_HOST_BOUNDS.gracePeriodMs;\n const gracePeriodMs = Math.max(1, Math.min(requestedGrace, Math.floor(timeoutMs / 2)));\n return { timeoutMs, heapMb, gracePeriodMs };\n}\n\n/** Options of {@link runRenderCheckViaWorker}. */\nexport interface RenderCheckHostOptions {\n /** Subprocess bounds; every field omitted falls to {@link DEFAULT_RENDER_CHECK_HOST_BOUNDS}. */\n readonly bounds?: Partial<RenderCheckHostBounds>;\n}\n\n/**\n * stdout cap. The verdict JSON carries issue lists with diagnostics\n * arrays — bigger than the smoke worker's one-liner, still tiny in\n * absolute terms. 2 MiB is far above any legitimate verdict.\n */\nconst CHECK_STDOUT_CAP = 2 * 1024 * 1024;\n\nconst WORKER_BASENAME = 'render-check-worker';\n\n/**\n * How the host spawns the worker from THIS location: the built dist sibling\n * when one exists, else the source `.ts` through tsx. Exported so the entry\n * guard can be pinned with the same spawn the host makes (no build needed).\n */\nexport function resolveWorkerSpawn(): { command: string; args: string[] } {\n const jsCandidates = [\n // Sibling — when import.meta.url is already .../harness/check/runtime-render/.\n new URL(`./${WORKER_BASENAME}.js`, import.meta.url),\n // From dist/index.js.\n new URL(`./harness/check/runtime-render/${WORKER_BASENAME}.js`, import.meta.url),\n // From dist/harness/index.js.\n new URL(`./check/runtime-render/${WORKER_BASENAME}.js`, import.meta.url),\n // From dist/check/index.js, dist/advanced/index.js, dist/<flat>.js.\n new URL(`../harness/check/runtime-render/${WORKER_BASENAME}.js`, import.meta.url),\n ];\n for (const jsUrl of jsCandidates) {\n const jsPath = fileURLToPath(jsUrl);\n if (existsSync(jsPath)) {\n return { command: process.execPath, args: [jsPath] };\n }\n }\n // Dev / vitest: only the .ts source exists — run it through tsx.\n const tsCandidates = [\n new URL(`./${WORKER_BASENAME}.ts`, import.meta.url),\n new URL(`../harness/check/runtime-render/${WORKER_BASENAME}.ts`, import.meta.url),\n ];\n for (const tsUrl of tsCandidates) {\n const tsPath = fileURLToPath(tsUrl);\n if (existsSync(tsPath)) {\n const require_ = createRequire(import.meta.url);\n const tsxLoader = pathToFileURL(require_.resolve('tsx')).href;\n return { command: process.execPath, args: ['--import', tsxLoader, tsPath] };\n }\n }\n const tried = [...jsCandidates, ...tsCandidates]\n .map((u) => fileURLToPath(u))\n .join(', ');\n throw new Error(\n `render-check: isolated worker not found at any of: ${tried}. Did \\`pnpm build\\` run?`,\n );\n}\n\nfunction failed(reason: string, t0: number): RenderCheckResult {\n return {\n ok: false,\n issues: [{ check: 'render-no-throw', outcome: 'failed', reason }],\n stats: { actionsChecked: 0, streamsChecked: 0, renderMs: Date.now() - t0 },\n };\n}\n\nfunction unverified(reason: string, t0: number): RenderCheckResult {\n return {\n ok: false,\n issues: [{ check: 'render-no-throw', outcome: 'unverified', reason }],\n stats: { actionsChecked: 0, streamsChecked: 0, renderMs: Date.now() - t0 },\n };\n}\n\n/**\n * Map one sandbox result onto a `RenderCheckResult`. `boundMs` is the\n * wall-clock bound the run was given, reported on a timeout. Exported for\n * the unit pins — the spawn itself is exercised by the integration test.\n */\nexport function mapSandboxResultToCheckResult(\n result: SandboxResult,\n t0: number,\n boundMs: number = DEFAULT_RENDER_CHECK_HOST_BOUNDS.timeoutMs,\n): RenderCheckResult {\n if (result.outcome === 'timeout') {\n return {\n ok: false,\n issues: [],\n incomplete: { kind: 'timeout', elapsedMs: result.durationMs, boundMs },\n stats: { actionsChecked: 0, streamsChecked: 0, renderMs: Date.now() - t0 },\n };\n }\n if (result.outcome === 'overflow-stdout' || result.outcome === 'overflow-stderr') {\n return failed(\n `render check worker produced excessive output (${result.outcome}) — the component is likely in a pathological logging or error loop.`,\n t0,\n );\n }\n if (result.outcome === 'spawn-error') {\n return unverified(\n `render check worker failed to start — ${result.errorMessage}`,\n t0,\n );\n }\n if (result.outcome === 'canceled') {\n return unverified('render check worker was canceled before completing.', t0);\n }\n if (result.outcome !== 'exit') {\n return unverified(\n `render check worker ended with unexpected sandbox outcome '${result.outcome}'.`,\n t0,\n );\n }\n if (result.exitCode !== 0) {\n const tail = result.stderr.trim() || result.stdout.trim();\n return unverified(\n `render check worker exited ${result.exitCode}${tail ? ` — ${tail.slice(0, 600)}` : ''}`,\n t0,\n );\n }\n let verdict: RenderCheckResult | undefined;\n try {\n verdict = parseVerdictLine<RenderCheckResult>(result.stdout);\n } catch (err) {\n return unverified(\n `render check worker verdict was not valid JSON — ${\n err instanceof Error ? err.message : String(err)\n }`,\n t0,\n );\n }\n if (verdict === undefined) {\n return unverified('render check worker exited without producing a verdict.', t0);\n }\n return verdict;\n}\n\n/**\n * Run the render check in an isolated subprocess. See module doc.\n * `options.bounds` sets the subprocess bounds for this run; omitted\n * fields are the evaluation lane's defaults.\n */\nexport async function runRenderCheckViaWorker(\n input: RunRenderCheckInput,\n options: RenderCheckHostOptions = {},\n): Promise<RenderCheckResult> {\n const t0 = Date.now();\n const bounds = resolveRenderCheckHostBounds(options.bounds);\n let spawn: { command: string; args: string[] };\n try {\n spawn = resolveWorkerSpawn();\n } catch (err) {\n return unverified(err instanceof Error ? err.message : String(err), t0);\n }\n\n const loadAtStart = loadavg()[0] ?? 0;\n const result = await runSandboxed({\n command: spawn.command,\n args: spawn.args,\n timeoutMs: bounds.timeoutMs,\n gracePeriodMs: bounds.gracePeriodMs,\n maxStdoutBytes: CHECK_STDOUT_CAP,\n nodeHeapMb: bounds.heapMb,\n // ggui#1398: the check learns its own deadline, so its report-only\n // pending phase can step aside instead of pushing it past the bound.\n stdin: JSON.stringify({ ...input, deadlineAt: t0 + bounds.timeoutMs }),\n // NODE_ENV steers React's production vs development build — keep\n // parity with the caller; everything else stays on the sandbox's\n // default allowlist.\n env: { NODE_ENV: process.env.NODE_ENV ?? 'production' },\n });\n\n const hostLoad: ProbeHostLoad = {\n start: loadAtStart,\n end: loadavg()[0] ?? 0,\n cores: availableParallelism(),\n };\n const mapped = mapSandboxResultToCheckResult(result, t0, bounds.timeoutMs);\n return { ...mapped, stats: { ...mapped.stats, hostLoad } };\n}\n","// packages/ui-gen/src/harness/check/runtime-render/production-act-shim.ts\n//\n// Minimal adaptation to two upstream constraints, neither of which\n// this package controls:\n//\n// 1. React intentionally strips `act` from its PRODUCTION build.\n// `react/cjs/react.production.js` does not export it — only the\n// development build does (`typeof require('react').act` is\n// `'function'` under a dev build, `undefined` under production).\n// 2. `@testing-library/react`'s `act-compat` module hard-requires\n// `act` at MODULE SCOPE: it snapshots\n// `typeof React.act === 'function' ? React.act : DeprecatedReactTestUtils.act`\n// into a `const` the first time it is imported in the process.\n// Under a production build, that snapshot resolves to React\n// DOM's `react-dom/test-utils` production `act` stub, which\n// THROWS `React.act is not a function` the moment it is called.\n//\n// Hosts that run this probe inside a production Node process\n// (server-side blueprint validation) hit this: every render throws\n// through RTL's `act` wrapper before the probe ever sees the\n// component. Hosts that run it under a development/test build (every\n// CI/vitest run in this repo — `NODE_ENV=test` resolves the dev\n// build) never see it; `act` is real there and this shim is a no-op.\n//\n// **Load-order constraint**: this MUST run before the FIRST import of\n// `@testing-library/react` anywhere in the process — act-compat binds\n// its `act` reference into a module-scope `const` at import time, so\n// patching `react-dom/test-utils` AFTER that import has already\n// happened does nothing (the snapshot already captured the broken\n// stub). Patch `react-dom/test-utils`, never `react` itself — that\n// entry point is deprecated and test-only, so this patch cannot\n// perturb any production rendering path; nothing else in a server\n// process legitimately imports it.\n//\n// `createRequire` (not `import`) reaches these modules deliberately:\n// ESM namespace objects are frozen, so a normal `import` gives no way\n// to mutate `act` on it. The CJS `module.exports` objects `require`\n// resolves are mutable, and RTL's act-compat interop-copies THAT\n// object's properties at its own load time — so mutating it here,\n// before RTL loads, is what makes the patch visible to RTL at all.\n\nimport { createRequire } from \"node:module\";\n\nlet installed = false;\n\n/**\n * The one property this module reads/mutates on `react` and\n * `react-dom/test-utils`'s CJS exports. A minimal local shape rather\n * than the real (deprecated, possibly absent) type declarations for\n * `react-dom/test-utils` — narrow enough to type-check the mutation\n * without `as any` / `Record<string, unknown>`.\n */\ninterface MutableActCarrier {\n act?: unknown;\n}\n\n/** The one React DOM export this module needs — typed narrowly for the same reason. */\ninterface FlushSyncCarrier {\n flushSync: (fn: () => void) => void;\n}\n\n/**\n * Patch `react-dom/test-utils`'s `act` with a `flushSync`-backed\n * replacement, but ONLY when the current process is running React's\n * production build (no real `act` exported). Idempotent — safe to\n * call more than once or from more than one call site; the actual\n * patch only ever applies once per process.\n *\n * No-op (by design, not by accident) whenever `react`'s own `act`\n * export is a real function — every dev/test build, including every\n * vitest run in this repo. This shim changes zero behavior in CI.\n */\nexport function installProductionActShim(): void {\n if (installed) return;\n installed = true;\n\n const require_ = createRequire(import.meta.url);\n\n let reactCjs: MutableActCarrier;\n try {\n reactCjs = require_(\"react\");\n } catch {\n // React itself isn't resolvable in this process — the probe\n // surfaces its own load error; nothing for this shim to patch.\n return;\n }\n\n if (typeof reactCjs.act === \"function\") {\n // Dev/test builds export a real `act` — strict no-op.\n return;\n }\n\n try {\n const testUtils: MutableActCarrier = require_(\"react-dom/test-utils\");\n const reactDom: FlushSyncCarrier = require_(\"react-dom\");\n testUtils.act = createFlushSyncAct(reactDom.flushSync);\n } catch {\n // Frozen/locked exports (or a react-dom build without flushSync)\n // — leave it. The probe then surfaces the raw upstream error,\n // which is the pre-fix behavior: an honest failure, not a\n // silently-broken patch.\n }\n}\n\n/**\n * Build an `act`-compatible replacement backed by `flushSync`, which\n * — unlike `act` — DOES exist in React's production build.\n *\n * `flushSync` is the single property this shim relies on from dev\n * `act`: it forces the scheduled render to commit SYNCHRONOUSLY\n * before returning, so a render throw propagates synchronously to the\n * caller and the DOM is fully committed by the time this resolves.\n *\n * Returned function is act-style: if the callback itself returned a\n * thenable (RTL's async act-wrapped interactions), the result\n * resolves once that thenable settles (rejecting on its rejection);\n * otherwise it resolves after one microtask, mirroring `act`'s own\n * \"flush the microtask queue\" contract for the synchronous case.\n *\n * **Known, documented delta vs. a real dev `act`**: passive effects\n * (`useEffect`) flush on a LATER task under `flushSync`, not\n * synchronously at act-exit — `flushSync` only guarantees the\n * synchronous commit, not effect flushing. The probe's uncaught-error\n * handlers plus its 100ms teardown grace window (`render-check.ts`'s\n * `cleanupAsyncInfra`) already cover a late effect throwing after this\n * resolves, so this delta does not reopen the crash class the probe\n * exists to catch.\n *\n * Exported separately so the flushSync/thenable semantics are unit\n * testable without a real React runtime.\n */\nexport function createFlushSyncAct(\n flushSync: (fn: () => void) => void,\n): (callback: () => unknown) => Promise<void> {\n return (callback: () => unknown): Promise<void> => {\n let callbackResult: unknown;\n flushSync(() => {\n callbackResult = callback();\n });\n if (isThenable(callbackResult)) {\n const pending = callbackResult;\n return new Promise<void>((resolve, reject) => {\n pending.then(() => resolve(), reject);\n });\n }\n return new Promise<void>((resolve) => {\n queueMicrotask(resolve);\n });\n };\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n","// packages/ui-gen/src/harness/check/runtime-render/probe.ts\n//\n// Probe — captures wire-surface activity for runtime render evaluation.\n//\n// Design:\n//\n// We do NOT mirror @ggui-ai/wire's hooks. The hooks already route\n// entirely through WireContext (dispatch / subscribe). So we just\n// provide a probe-backed WireConfig to the real GguiWireProvider.\n// The real hooks run; only the underlying primitives are intercepted.\n//\n// Wins:\n// - no parallel hook implementation to maintain\n// - no esbuild aliasing\n// - hook semantics stay faithful to production\n// - stream re-renders flow through the real useStream's React update path\n//\n// The Probe object is shared in two scopes:\n// - Inside the React tree, via the WireConfig captured from createProbeWireConfig()\n// - Outside the React tree, via the same Probe reference held by the test runner\n//\n// Tests use the outside reference to:\n// - emitStream(name, payload) → invokes captured subscribers, real useStream re-renders\n// - inspect getFireLog() / getRegistered() to verify wiring\n\nimport type { WireConfig } from \"@ggui-ai/wire\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Event log shape\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface ActionFiredEvent {\n readonly kind: \"action.fired\";\n readonly name: string;\n readonly payload?: unknown;\n readonly ts: number;\n}\n\n/**\n * A `ui/open-link` envelope was emitted toward the parent — fired when\n * the iframe-runtime's anchor interceptor catches an external link\n * click and routes through the host. CHECK tier observes this when\n * the generated component renders a plain `<a href=\"https://...\">`.\n */\nexport interface LinkOpenedEvent {\n readonly kind: \"link.opened\";\n readonly url: string;\n readonly ts: number;\n}\n\n/**\n * A `ui/request-display-mode` envelope was emitted toward the parent\n * — fired when the iframe-runtime's native-API interceptor catches\n * a `requestFullscreen()` / `exitFullscreen()` call and routes it\n * through the host.\n */\nexport interface DisplayModeRequestedEvent {\n readonly kind: \"displayMode.requested\";\n readonly mode: string;\n readonly ts: number;\n}\n\nexport type ProbeEvent =\n | ActionFiredEvent\n | LinkOpenedEvent\n | DisplayModeRequestedEvent;\n\nexport interface RegisteredHooks {\n /** Stream event names that received at least one subscribe() call. */\n readonly streams: readonly string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Probe interface\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface Probe {\n // ── Inputs (test → component) ──────────────────────────────────────────\n /** Push a stream event payload. Calls all current subscribers for `eventName`. */\n emitStream<T = unknown>(eventName: string, payload: T): void;\n\n // ── Observations (read after interaction) ──────────────────────────────\n getFireLog(): readonly ProbeEvent[];\n getRegistered(): RegisteredHooks;\n /** Convenience: did any action.fired event match this name? */\n fired(actionName: string): boolean;\n\n // ── Lifecycle ──────────────────────────────────────────────────────────\n /**\n * Install a spy on `window.parent.postMessage` so envelopes emitted\n * by the iframe-runtime interceptors (anchor click → `ui/open-link`,\n * `requestFullscreen()` → `ui/request-display-mode`) are recorded\n * into the probe's fire log. Returns an uninstall function.\n *\n * Safe to call multiple times — each call replaces the previous spy.\n * The render-check harness installs the spy at render boot and\n * uninstalls during teardown.\n */\n installPostMessageSpy(): () => void;\n reset(): void;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internal state — held as closures in the Probe instance for isolation\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface ProbeInternals {\n fireLog: ProbeEvent[];\n streamHandlers: Map<string, Set<(d: unknown) => void>>;\n registeredStreams: Set<string>;\n}\n\nfunction makeInternals(): ProbeInternals {\n return {\n fireLog: [],\n streamHandlers: new Map(),\n registeredStreams: new Set(),\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// createProbe()\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function createProbe(): Probe & {\n /** @internal — used by createProbeWireConfig to share state. Do not call from tests. */\n __internals: ProbeInternals;\n} {\n let internals = makeInternals();\n\n const probe: Probe & { __internals: ProbeInternals } = {\n emitStream: <T>(eventName: string, payload: T): void => {\n const handlers = internals.streamHandlers.get(eventName);\n if (!handlers) return;\n for (const handler of handlers) handler(payload);\n },\n\n getFireLog: (): readonly ProbeEvent[] => internals.fireLog.slice(),\n\n getRegistered: (): RegisteredHooks => ({\n streams: Array.from(internals.registeredStreams),\n }),\n\n fired: (actionName: string): boolean =>\n internals.fireLog.some(e => e.kind === \"action.fired\" && e.name === actionName),\n\n installPostMessageSpy: (): (() => void) => installPostMessageSpy(probe),\n\n reset: (): void => {\n internals = makeInternals();\n // Mutate __internals reference too so existing wire config still sees fresh state.\n probe.__internals = internals;\n },\n\n __internals: internals,\n };\n\n return probe;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// postMessage spy — observes envelopes emitted by the iframe-runtime\n// interceptors (anchor click, requestFullscreen). The renderer's\n// WireConfig still funnels into the probe via the closure-shared\n// internals; this spy is the parallel observation channel for\n// envelope-layer effects that bypass WireConfig.\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface JsonRpcEnvelope {\n readonly jsonrpc?: unknown;\n readonly method?: unknown;\n readonly params?: unknown;\n}\n\nfunction installPostMessageSpy(\n probe: Probe & { __internals: ProbeInternals },\n): () => void {\n // happy-dom: window.parent === window in the default test setup, so the\n // helpers' calls to `window.parent.postMessage` land on this same surface.\n // Probe state is held in the closure over `probe.__internals` so calls\n // from inside the React tree write to the same fire log the tests read.\n const parent = (globalThis as { window?: { parent?: { postMessage?: unknown } } }).window?.parent;\n if (!parent || typeof parent.postMessage !== \"function\") {\n // No parent surface to spy on — return a noop uninstaller. The probe\n // still observes WireConfig-layer events (dispatch, etc.).\n return () => {};\n }\n const original = parent.postMessage;\n const spy = (...args: unknown[]): unknown => {\n const envelope = args[0];\n recordEnvelope(probe.__internals, envelope);\n // Forward to the original so happy-dom's own postMessage semantics\n // (queueing, dispatch) keep working — the spy is observation-only.\n return (original as (...a: unknown[]) => unknown).apply(parent, args);\n };\n try {\n Object.defineProperty(parent, \"postMessage\", {\n value: spy,\n configurable: true,\n writable: true,\n });\n } catch {\n // Locked-down host runtime — give up silently. The probe still sees\n // WireConfig-layer events.\n return () => {};\n }\n return () => {\n try {\n Object.defineProperty(parent, \"postMessage\", {\n value: original,\n configurable: true,\n writable: true,\n });\n } catch {\n /* ignore */\n }\n };\n}\n\nfunction recordEnvelope(internals: ProbeInternals, envelope: unknown): void {\n if (!envelope || typeof envelope !== \"object\") return;\n const e = envelope as JsonRpcEnvelope;\n if (typeof e.method !== \"string\") return;\n const params = (e.params ?? {}) as Record<string, unknown>;\n\n switch (e.method) {\n case \"ui/open-link\": {\n const url = typeof params.url === \"string\" ? params.url : \"\";\n internals.fireLog.push({\n kind: \"link.opened\",\n url,\n ts: Date.now(),\n });\n return;\n }\n case \"ui/request-display-mode\": {\n const mode = typeof params.mode === \"string\" ? params.mode : \"\";\n internals.fireLog.push({\n kind: \"displayMode.requested\",\n mode,\n ts: Date.now(),\n });\n return;\n }\n case \"tools/call\": {\n // The only tools/call with a legitimate emitter is the audit\n // envelope (`ggui_runtime_submit_action`), and WireConfig.dispatch\n // already records its paired `action.fired` — nothing to record\n // here. The runtime never fires any other tool from the iframe:\n // every action rides the consume buffer and the agent invokes\n // tools on its own turn.\n return;\n }\n default:\n // Unrecognized envelope — ignore. New methods get explicit handling\n // when added to the protocol; silent fall-through is fine for now.\n return;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// createProbeWireConfig() — produces a WireConfig that funnels into the Probe\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Build a WireConfig backed by the given Probe. Use as the `config` prop of\n * GguiWireProvider in render-check tests.\n *\n * The WireConfig holds a closure over `probe.__internals` so that calls from\n * inside the React tree (via the real useAction/useStream/etc. hooks) flow\n * straight into the same probe state the test inspects from outside.\n */\nexport function createProbeWireConfig(\n probe: Probe & { __internals: ProbeInternals },\n): WireConfig {\n return {\n app: {\n appId: \"probe-app\",\n appName: \"Probe\",\n appDescription: \"Eval-time probe wire config\",\n },\n render: {\n sessionId: \"probe-render\",\n isConnected: true,\n },\n auth: {\n isAuthenticated: false,\n },\n\n dispatch: <T = unknown>(actionName: string, data: T): void => {\n probe.__internals.fireLog.push({\n kind: \"action.fired\",\n name: actionName,\n payload: data,\n ts: Date.now(),\n });\n },\n\n subscribe: <T = unknown>(eventType: string, handler: (data: T) => void): (() => void) => {\n probe.__internals.registeredStreams.add(eventType);\n let set = probe.__internals.streamHandlers.get(eventType);\n if (!set) {\n set = new Set();\n probe.__internals.streamHandlers.set(eventType, set);\n }\n const wrapped = handler as (d: unknown) => void;\n set.add(wrapped);\n return () => {\n set!.delete(wrapped);\n };\n },\n\n // The WireConfig surface is dispatch + subscribe only. Capability\n // hooks live in `@ggui-ai/gadgets` and own their own lifecycle —\n // they never route through WireConfig.\n };\n}\n","// packages/ui-gen/src/internal/evaluate-component-source.ts\n//\n// The ONE compile-and-evaluate helper for component source: esbuild\n// TSX→CJS transform + vm.Script in-context execution behind a\n// caller-supplied `require`. Consumed by:\n//\n// - `tools/render-check-worker.ts` — the subprocess render smoke\n// test (host isolation lives at the spawn layer, in the parent's\n// `tryRender` via `@ggui-ai/sandbox`).\n// - `harness/check/runtime-render/load-component.ts` — the in-loop\n// probe (single-realm React; caller injects module resolutions).\n//\n// The module-resolution POLICY is deliberately not shared — each\n// caller owns its own `require` shim (allowed specifiers, fallbacks,\n// error wording). What is shared is the mechanical eval pipeline:\n//\n// 1. esbuild.transform(source) → CJS\n// 2. wrap in `(function(require, exports, module) { ... })`\n// 3. vm.Script(...).runInThisContext()\n// 4. call with the caller's require + a fresh module object\n// 5. return `module.exports` read AFTER execution — esbuild's CJS\n// output REPLACES `module.exports` (`module.exports =\n// __toCommonJS(...)`), so the initial reference can't be trusted.\n\nexport async function evaluateComponentSource(\n sourceCode: string,\n sandboxRequire: (id: string) => unknown,\n): Promise<Record<string, unknown>> {\n const esbuild = await import(\"esbuild\");\n const { Script } = await import(\"node:vm\");\n\n const cjsResult = await esbuild.transform(sourceCode, {\n loader: \"tsx\",\n target: \"es2020\",\n format: \"cjs\",\n jsx: \"automatic\",\n jsxImportSource: \"react\",\n sourcefile: \"Component.tsx\",\n });\n\n const sandboxModule: { exports: Record<string, unknown> } = { exports: {} };\n\n const wrappedCode = `(function(require, exports, module) {\\n${cjsResult.code}\\n})`;\n const script = new Script(wrappedCode, { filename: \"Component.cjs\" });\n const fn = script.runInThisContext() as (\n require: (id: string) => unknown,\n exports: Record<string, unknown>,\n module: { exports: Record<string, unknown> },\n ) => void;\n\n fn(sandboxRequire, sandboxModule.exports, sandboxModule);\n\n return sandboxModule.exports;\n}\n","// packages/ui-gen/src/harness/check/runtime-render/load-component.ts\n//\n// Eval a compiled component source string into a real React component reference.\n//\n// The mechanical compile+vm pipeline is the shared\n// `evaluateComponentSource` helper (also used by the render-smoke\n// subprocess worker); this module owns the in-loop probe's\n// module-resolution POLICY — a sandboxed require() that resolves:\n// - caller-injected `moduleResolutions` first (single-realm React)\n// - react / react/jsx-runtime → real react\n// - react-dom/* → real react-dom\n// - @ggui-ai/wire → REAL wire package (we want real useAction etc.,\n// the probe is injected via WireConfig at provider level)\n// - @ggui-ai/design/* → real design package\n// then plucks `module.exports.default` as the Component.\n//\n// Why we evaluate sourceCode (not the pre-compiled bundle): the test runner\n// already has sourceCode handy, and re-compiling guarantees a CJS shape\n// the vm sandbox can run without ESM module-record juggling.\n\nimport type { ComponentType } from \"react\";\nimport { evaluateComponentSource } from \"../../../internal/evaluate-component-source.js\";\n\nexport interface LoadComponentInput {\n /** The TSX source the agent emitted. We re-transform it to CJS. */\n readonly sourceCode: string;\n /**\n * Pre-resolved module instances to inject into the sandbox. CRITICAL:\n * the caller must pass the SAME React + wire instances they use outside\n * the sandbox — otherwise React context lookups fail (different React\n * realms have different dispatchers and contexts).\n *\n * Required keys: 'react', 'react/jsx-runtime', '@ggui-ai/wire'.\n * Optional: 'react-dom', '@ggui-ai/design/*'.\n */\n readonly moduleResolutions?: Readonly<Record<string, unknown>>;\n}\n\nexport interface LoadComponentResult {\n readonly Component: ComponentType<Record<string, unknown>>;\n}\n\nexport async function loadComponent(input: LoadComponentInput): Promise<LoadComponentResult> {\n const { sourceCode, moduleResolutions = {} } = input;\n const { createRequire } = await import(\"module\");\n\n const require_ = createRequire(import.meta.url);\n\n const sandboxRequire = (id: string): unknown => {\n // 1. Caller-injected resolutions win — these guarantee single-realm\n // React + wire so context lookups work.\n if (id in moduleResolutions) return moduleResolutions[id];\n\n // 2. Fall back to Node require for the remaining standard externals.\n if (id === \"react/jsx-runtime\" || id === \"react/jsx-dev-runtime\") {\n return require_(\"react/jsx-runtime\");\n }\n if (id === \"react\") return require_(\"react\");\n if (id === \"react-dom\" || id.startsWith(\"react-dom/\")) {\n return require_(id);\n }\n if (id === \"@ggui-ai/wire\") return require_(\"@ggui-ai/wire\");\n if (id.startsWith(\"@ggui-ai/design\")) {\n try {\n return require_(id);\n } catch {\n throw new Error(\n `Required dependency not available in render-check sandbox: ${id}. ` +\n `Install @ggui-ai/design or run render-check from an environment that has it.`,\n );\n }\n }\n // `@ggui-ai/gadgets` is a first-class dependency for any component\n // that uses `clientCapabilities.gadgets`. The probe needs a real\n // implementation so the LLM's `useGeolocation()` call actually\n // resolves (Node's happy-dom doesn't carry the wrapper hooks\n // itself; this require pulls the npm package).\n if (id === \"@ggui-ai/gadgets\") {\n try {\n return require_(\"@ggui-ai/gadgets\");\n } catch {\n throw new Error(\n `Required dependency not available in render-check sandbox: ${id}. ` +\n `Install @ggui-ai/gadgets or pass it through moduleResolutions.`,\n );\n }\n }\n // Operator-registered wrapper packages — caller injects via\n // `moduleResolutions` (the (specifier, hooks) pairs the bench\n // commit declares in `commit.appGadgets`). If a wrapper is\n // referenced by source but not injected, fall through to the\n // standard \"import not allowed\" message — the upstream render path\n // would have rejected this contract before generation, so reaching\n // here is a test-fixture misconfiguration.\n throw new Error(`Import not allowed in render-check sandbox: ${id}`);\n };\n\n const exportsRecord = await evaluateComponentSource(sourceCode, sandboxRequire);\n\n const candidate = exportsRecord.default;\n if (typeof candidate !== \"function\") {\n throw new Error(\"Compiled component has no default-exported function\");\n }\n return { Component: candidate as ComponentType<Record<string, unknown>> };\n}\n","// packages/ui-gen/src/harness/check/runtime-render/find-wiring.ts\n//\n// Source-AST wiring detection.\n//\n// Given a component's TSX source and a hook reference (e.g., `useAction('save')`),\n// determine HOW the resulting callback is wired in JSX so the runtime probe knows\n// which trigger to simulate — instead of guessing by clicking everything.\n//\n// Rules:\n// - Handle ONE level of alias indirection:\n// const save = useAction('save');\n// const onSave = () => save(payload); // alias\n// <Button onClick={onSave} /> // alias used in JSX → click\n// - Be CONSERVATIVE on non-native props. Native event names are deterministic;\n// custom-component props (onValueChange, onSelect, onOpenChange) are NOT\n// guaranteed to fire on a synthetic click/change → return `unverified`.\n// - Anything we can't classify deterministically returns `unverified` with a\n// reason. NEVER pretend.\n//\n// Returns ONE detection object summarizing the strongest wiring found, plus\n// optional fallback hints. Callers use the kind to pick a simulator.\n\nimport ts from \"typescript\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type WiringKind =\n | \"click\" // wired as native onClick prop on a host element / role-button\n | \"submit\" // wired via onSubmit on a form, or button[type=submit]\n | \"change\" // wired via onChange on native select/input\n | \"keyboard-enter\" // wired via onKeyDown with Enter check\n | \"unverified\" // wiring exists but trigger style is non-deterministic\n | \"missing\"; // hook destructured but never referenced in JSX\n\nexport interface WiringDetection {\n readonly kind: WiringKind;\n /**\n * For `unverified`: human-readable reason (e.g., \"wired via Dropdown.onChange\",\n * \"wired into custom-component prop onValueChange\", \"wired into onDrop handler\").\n * For `missing`: brief explanation.\n * For verified kinds: optional element-locator hint (tag name, label).\n */\n readonly reason?: string;\n /**\n * Pure observational: the JSX element types the callback flows into.\n * Useful for richer feedback in the EvalIssue.\n */\n readonly observedJsxElements: readonly string[];\n /**\n * Native event prop names where we observed the callback (e.g., onClick, onSubmit).\n * Empty if only seen on non-native props.\n */\n readonly observedNativeProps: readonly string[];\n /**\n * Non-native event prop names where we observed it (e.g., onValueChange, onSelect).\n * Drives the unverified reason.\n */\n readonly observedCustomProps: readonly string[];\n}\n\nexport interface FindWiringInput {\n readonly sourceCode: string;\n /** \"useAction\" or \"useStream\" */\n readonly hookName: string;\n /** The hook's first-arg literal — the action/tool/event name. */\n readonly hookArg: string;\n}\n\n// Native DOM event props we can simulate deterministically.\nconst NATIVE_CLICK_PROPS = new Set([\"onClick\"]);\nconst NATIVE_SUBMIT_PROPS = new Set([\"onSubmit\"]);\nconst NATIVE_CHANGE_PROPS = new Set([\"onChange\"]);\nconst NATIVE_KEY_PROPS = new Set([\"onKeyDown\", \"onKeyUp\", \"onKeyPress\"]);\n\n// JSX element tags (lowercase) that count as host elements with native event behavior.\nconst HOST_CLICK_TAGS = new Set([\"button\", \"a\", \"div\", \"span\", \"li\", \"input\"]);\nconst HOST_CHANGE_TAGS = new Set([\"select\", \"input\", \"textarea\"]);\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public entry\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function findWiring(input: FindWiringInput): WiringDetection {\n const { sourceCode, hookName, hookArg } = input;\n\n const sf = ts.createSourceFile(\"Component.tsx\", sourceCode, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);\n\n // Step 1: find the destructured variable name from the hook call.\n // const save = useAction('save')\n // Returns the binding name(s) — multiple if the hook returns an object\n // destructure.\n const hookBindings = findHookBindings(sf, hookName, hookArg);\n if (hookBindings.length === 0) {\n return {\n kind: \"missing\",\n reason: `Hook ${hookName}('${hookArg}') is not destructured in the component`,\n observedJsxElements: [],\n observedNativeProps: [],\n observedCustomProps: [],\n };\n }\n\n // Step 2: collect every identifier that should \"count\" as a reference to the\n // hook's callable. This includes:\n // - The hook bindings themselves (e.g., `save`)\n // - One-level aliases: `const onSave = () => save(...); const onClick = save;`\n // → `onSave` and `onClick` count as references to `save`\n const callableNames = expandAliases(sf, hookBindings);\n\n // Step 3: scan JSX attributes. For each attribute whose value contains a\n // reference to any callableName, classify by attribute name + element kind.\n const observedJsxElements: string[] = [];\n const observedNativeProps: string[] = [];\n const observedCustomProps: string[] = [];\n\n let sawClickOnHost = false;\n let sawSubmitOnForm = false;\n let sawChangeOnNativeInput = false;\n let sawKeyOnAnything = false;\n let sawNonNativeProp = false;\n const customPropElements: string[] = [];\n const submitButton = { found: false };\n\n function visit(node: ts.Node): void {\n // <Tag attr={...} />\n if (ts.isJsxAttribute(node) && node.initializer) {\n const attrName = node.name.getText(sf);\n const initRefs = findReferencedNames(node.initializer, callableNames);\n if (initRefs.size > 0) {\n const parent = node.parent.parent; // JsxAttributes → opening element\n const tagName = getTagName(parent);\n if (tagName) observedJsxElements.push(tagName);\n const isHostTag = isHostElementTag(tagName ?? \"\");\n\n if (NATIVE_CLICK_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n if (isHostTag && (HOST_CLICK_TAGS.has((tagName ?? \"\").toLowerCase()) || tagName === \"button\")) {\n sawClickOnHost = true;\n } else {\n // onClick on a custom component (e.g., <Button>) — design-system\n // primitives may or may not forward to a real <button>. Treat as\n // host click for verification purposes — the boilerplate's\n // primitives forward onClick by convention. If they don't, the\n // probe just won't observe a fire and we'll downgrade.\n sawClickOnHost = true;\n }\n } else if (NATIVE_SUBMIT_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n if ((tagName ?? \"\").toLowerCase() === \"form\") sawSubmitOnForm = true;\n else sawSubmitOnForm = true; // wrapped form component still likely a form\n } else if (NATIVE_CHANGE_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n if (HOST_CHANGE_TAGS.has((tagName ?? \"\").toLowerCase())) {\n sawChangeOnNativeInput = true;\n } else {\n // onChange on a non-native (custom) component — Select/Dropdown\n // commonly use this name but their onChange is NOT triggered by\n // a synthetic 'change' event on a host element. Mark as custom.\n observedCustomProps.push(attrName);\n sawNonNativeProp = true;\n if (tagName) customPropElements.push(tagName);\n }\n } else if (NATIVE_KEY_PROPS.has(attrName)) {\n observedNativeProps.push(attrName);\n sawKeyOnAnything = true;\n } else {\n // Custom prop — onValueChange, onSelect, onOpenChange, onDrop, etc.\n observedCustomProps.push(attrName);\n sawNonNativeProp = true;\n if (tagName) customPropElements.push(tagName);\n }\n }\n }\n\n // <button type=\"submit\"> implicitly submits its enclosing form\n if (ts.isJsxOpeningLikeElement(node)) {\n const tag = getTagName(node);\n if ((tag ?? \"\").toLowerCase() === \"button\") {\n const typeAttr = node.attributes.properties.find(\n p => ts.isJsxAttribute(p) && p.name.getText(sf) === \"type\",\n );\n if (typeAttr && ts.isJsxAttribute(typeAttr) && typeAttr.initializer) {\n const v = typeAttr.initializer.getText(sf).toLowerCase();\n if (v.includes(\"submit\")) submitButton.found = true;\n }\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n\n // Step 4: pick the strongest deterministic kind.\n // Order of preference matches \"what the user is most likely to actually do\":\n // click (most common) > submit > change > keyboard\n // Unverified wins over a deterministic kind only if NO native wiring was found.\n\n if (sawClickOnHost) {\n return wrapDetection(\"click\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n if (sawSubmitOnForm || submitButton.found) {\n return wrapDetection(\"submit\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n if (sawChangeOnNativeInput) {\n return wrapDetection(\"change\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n if (sawKeyOnAnything) {\n return wrapDetection(\"keyboard-enter\", observedJsxElements, observedNativeProps, observedCustomProps);\n }\n\n if (sawNonNativeProp) {\n const props = Array.from(new Set(observedCustomProps)).join(\", \");\n const tags = Array.from(new Set(customPropElements)).join(\", \");\n return {\n kind: \"unverified\",\n reason: `Source indicates non-click or non-native wiring; static probe did not verify execution deterministically. Callback flows into ${props} on <${tags}>.`,\n observedJsxElements: dedupe(observedJsxElements),\n observedNativeProps: dedupe(observedNativeProps),\n observedCustomProps: dedupe(observedCustomProps),\n };\n }\n\n // No JSX usage at all → hook is destructured but never referenced.\n return {\n kind: \"missing\",\n reason: `Hook ${hookName}('${hookArg}') is destructured but never referenced in any JSX attribute`,\n observedJsxElements: [],\n observedNativeProps: [],\n observedCustomProps: [],\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Internals\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Find variable bindings produced by `hookName('hookArg')` calls.\n * const save = useAction('save') → ['save']\n * const { latest } = useStream('progress') → ['latest']\n */\nfunction findHookBindings(sf: ts.SourceFile, hookName: string, hookArg: string): string[] {\n const bindings: string[] = [];\n\n function visit(node: ts.Node): void {\n if (ts.isVariableDeclaration(node) && node.initializer && ts.isCallExpression(node.initializer)) {\n const call = node.initializer;\n const callee = call.expression.getText(sf);\n if (callee !== hookName) {\n ts.forEachChild(node, visit);\n return;\n }\n // First arg literal must match hookArg\n const firstArg = call.arguments[0];\n if (!firstArg || !ts.isStringLiteral(firstArg)) {\n ts.forEachChild(node, visit);\n return;\n }\n if (firstArg.text !== hookArg) {\n ts.forEachChild(node, visit);\n return;\n }\n // Identify binding\n if (ts.isIdentifier(node.name)) {\n bindings.push(node.name.text);\n } else if (ts.isObjectBindingPattern(node.name)) {\n for (const elem of node.name.elements) {\n // const { call: doSearch } = ... → propName=call, name=doSearch\n // const { call } = ... → name=call\n const target = elem.name;\n if (ts.isIdentifier(target)) bindings.push(target.text);\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return bindings;\n}\n\n/**\n * Expand bindings with one-level aliases:\n * const save = useAction('save')\n * const onSave = () => save(payload) → onSave is alias for save\n * const handleClick = save → handleClick is alias for save\n *\n * Returns the set of identifier NAMES that should count as the hook's callable\n * (used by JSX scanner to detect references).\n */\nfunction expandAliases(sf: ts.SourceFile, bindings: string[]): Set<string> {\n const all = new Set<string>(bindings);\n\n function visit(node: ts.Node): void {\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isIdentifier(node.name)\n ) {\n const newName = node.name.text;\n const init = node.initializer;\n // Direct alias: const handleClick = save;\n if (ts.isIdentifier(init) && all.has(init.text)) {\n all.add(newName);\n }\n // Wrapper closure: const onSave = () => save(payload);\n if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {\n if (bodyReferences(init.body, all)) {\n all.add(newName);\n }\n }\n // Common React wrappers: useCallback(() => save(...), [...]) / useMemo(...)\n // Generalize: walk the entire initializer expression for hook references.\n // If found, the alias counts as a reference site.\n if (ts.isCallExpression(init)) {\n if (bodyReferences(init, all)) {\n all.add(newName);\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return all;\n}\n\nfunction bodyReferences(body: ts.Node, names: ReadonlySet<string>): boolean {\n let found = false;\n function walk(n: ts.Node): void {\n if (found) return;\n if (ts.isIdentifier(n) && names.has(n.text)) {\n found = true;\n return;\n }\n ts.forEachChild(n, walk);\n }\n walk(body);\n return found;\n}\n\n/**\n * Scan a JSX attribute initializer expression for any identifier name in `names`.\n * Returns the set of matching names found.\n */\nfunction findReferencedNames(node: ts.Node, names: ReadonlySet<string>): Set<string> {\n const found = new Set<string>();\n function walk(n: ts.Node): void {\n if (ts.isIdentifier(n) && names.has(n.text)) {\n found.add(n.text);\n }\n ts.forEachChild(n, walk);\n }\n walk(node);\n return found;\n}\n\nfunction getTagName(el: ts.Node): string | null {\n if (ts.isJsxOpeningLikeElement(el)) {\n return el.tagName.getText();\n }\n return null;\n}\n\nfunction isHostElementTag(name: string): boolean {\n // Lowercase first letter = host element (button, div, form, etc.)\n // Capitalized = React component\n if (!name) return false;\n return name[0] === name[0]!.toLowerCase();\n}\n\nfunction wrapDetection(\n kind: WiringKind,\n jsx: string[],\n native: string[],\n custom: string[],\n): WiringDetection {\n return {\n kind,\n observedJsxElements: dedupe(jsx),\n observedNativeProps: dedupe(native),\n observedCustomProps: dedupe(custom),\n };\n}\n\nfunction dedupe<T>(arr: readonly T[]): T[] {\n return Array.from(new Set(arr));\n}\n","// packages/ui-gen/src/internal/open-record.ts\n//\n// Single documented narrowing seam for \"object used as an open\n// string-keyed property bag\" — the host global object and happy-dom's\n// `Window` both genuinely ARE open records at runtime (we install /\n// restore named globals like `window` / `document` on them by key),\n// but TypeScript cannot express that without polluting the global type\n// space via declaration merging. Centralizing the one structural\n// widening here keeps every call site cast-free.\n\n/**\n * View an object as an open string-keyed record.\n *\n * Single structural widening (`Record<string, unknown>` is assignable\n * to `object`, so the cast is checked in one direction by tsc — no\n * `unknown` erasure). Returns the SAME reference: property writes land\n * on the live object.\n */\nexport function openRecord(o: object): Record<string, unknown> {\n return o as Record<string, unknown>;\n}\n\n/**\n * The host global object viewed as an open property bag.\n *\n * Used by the render-check pipeline (and its subprocess worker) to\n * install and restore DOM globals by name.\n */\nexport function hostGlobals(): Record<string, unknown> {\n return openRecord(globalThis);\n}\n","// packages/ui-gen/src/harness/check/runtime-render/host-boundary.ts\n//\n// The ONE narrowing seam between the render-check pipeline and its\n// host runtime: happy-dom elements, @testing-library/react containers,\n// and the @testing-library/user-event module. Each export is either a\n// runtime-validated guard (throws a descriptive error on violation) or\n// a single documented structural view (all-optional facet of the same\n// live object), so the check pipeline's call sites stay cast-free.\n//\n// Deliberately DOM-lib-free: some downstream tsconfigs (e.g.\n// cloud/amplify) exclude the DOM lib, so this module declares the\n// minimal structural surfaces it needs instead of importing\n// `HTMLElement` / `Element` types.\n\nimport { openRecord } from \"../../../internal/open-record.js\";\n\n/**\n * Minimal structural view of a rendered DOM element — the only element\n * surface the checks read.\n */\nexport interface MinimalElement {\n readonly tagName: string;\n readonly textContent: string | null;\n getAttribute(name: string): string | null;\n querySelectorAll<T extends MinimalElement = MinimalElement>(selector: string): Iterable<T>;\n}\n\n/** The one user-gesture surface the checks drive. */\nexport interface ClickUser {\n readonly click: (el: MinimalElement) => Promise<void>;\n}\n\n/**\n * All-optional form-control facet of an element. Used by the synthetic\n * change-value writer; absent properties are tolerated by all readers\n * and writers.\n */\nexport interface EditableSurface {\n value?: string;\n checked?: boolean;\n type?: string;\n options?: ArrayLike<{ value: string }>;\n}\n\n/** All-optional tree-climbing facet (closest-form lookup). */\nexport interface ParentLink {\n readonly tagName?: string;\n readonly parentNode?: unknown;\n}\n\n/** Look up a method on an arbitrary host object, bound to it. */\nfunction getMethod(\n o: unknown,\n name: string,\n): ((...args: unknown[]) => unknown) | undefined {\n if (typeof o !== \"object\" && typeof o !== \"function\") return undefined;\n if (o === null) return undefined;\n const v = openRecord(o)[name];\n if (typeof v !== \"function\") return undefined;\n return (v as (...args: unknown[]) => unknown).bind(o);\n}\n\n/**\n * Validating narrower: host element (RTL container, climbed parent\n * node) → {@link MinimalElement}. Throws when the value lacks the\n * element surface — a violation of the happy-dom/RTL boundary\n * contract, not a check failure.\n */\nexport function toMinimalElement(v: unknown): MinimalElement {\n if (\n typeof v === \"object\" &&\n v !== null &&\n typeof openRecord(v).tagName === \"string\" &&\n typeof openRecord(v).getAttribute === \"function\" &&\n typeof openRecord(v).querySelectorAll === \"function\"\n ) {\n // Runtime-checked above; the remaining gap (exact method\n // signatures) is the structural boundary this module owns.\n return v as MinimalElement;\n }\n throw new Error(\n \"[runtime-render] host value lacks the element surface (tagName/getAttribute/querySelectorAll)\",\n );\n}\n\n/**\n * Validating narrower over the `@testing-library/user-event` module:\n * prefers the v14 `setup()` instance, falls back to the module-level\n * `click` (pre-v14 shape). Throws when neither surface exists.\n *\n * `doc` MUST be the live document the probe rendered into, passed as\n * `setup({ document })`. user-event captures `globalThis.document` into\n * its module-scope setup defaults AT MODULE LOAD (v14 `setup.js`\n * `defaultOptionsSetup`), so a bare `setup()` binds whatever document\n * existed when the module was FIRST imported — `undefined` when the\n * import happened via `warmupRuntimeRenderProbe()` before any DOM was\n * up, which then crashes every later probe with \"Cannot read properties\n * of undefined (reading 'Symbol(Node prepared with document state\n * workarounds)')\" (ggui#403). The module-level `click` fallback derives\n * its document from the clicked node and doesn't need this.\n */\nexport function buildClickUser(userEventModule: unknown, doc: unknown): ClickUser {\n const setup = getMethod(userEventModule, \"setup\");\n const instance: unknown = setup ? setup({ document: doc }) : userEventModule;\n const click = getMethod(instance, \"click\");\n if (!click) {\n throw new Error(\n \"[runtime-render] user-event module exposes neither setup().click nor click()\",\n );\n }\n return {\n click: async (el: MinimalElement): Promise<void> => {\n await click(el);\n },\n };\n}\n\n/**\n * Validating narrower: element → its `dispatchEvent` surface. Returns\n * the live method (bound), so dispatch hits the real element.\n */\nexport function toEventDispatcher(el: MinimalElement): {\n dispatchEvent: (ev: Event) => void;\n} {\n const dispatch = getMethod(el, \"dispatchEvent\");\n if (!dispatch) {\n throw new Error(\n `[runtime-render] element <${el.tagName.toLowerCase()}> has no dispatchEvent`,\n );\n }\n return {\n dispatchEvent: (ev: Event): void => {\n dispatch(ev);\n },\n };\n}\n\n/**\n * View an element as its all-optional form-control facet. Returns the\n * SAME reference (writes must land on the live element); the facet is\n * all-optional, so every reader/writer already tolerates absence —\n * there is nothing to validate at runtime.\n */\nexport function editableSurface(el: object): EditableSurface {\n return el as EditableSurface;\n}\n\n/** View a host node as its all-optional tree-climbing facet. */\nexport function parentLink(node: object): ParentLink {\n return node as ParentLink;\n}\n","/**\n * ggui#1398 leg 3 — the render check's stand-in for the runtime's pending\n * state, and the rule for \"the control visibly changed\".\n *\n * In a served card, the runtime marks an action pending when the card's\n * dispatch of it commits, and clears it when the session's next frame lands;\n * `useActionPending` reads that state through wire's `ActionPendingContext`.\n * The probe has no transport and no next frame, so it marks an action pending\n * right after its own synthetic click really fired the action, looks at the\n * clicked control, then clears it: one dispatch, one answer.\n */\nimport type { ActionPendingSource } from \"@ggui-ai/wire\";\n\n/** An {@link ActionPendingSource} the probe drives by hand. */\nexport interface ProbePendingSource extends ActionPendingSource {\n /** Mark `actionName` pending and notify subscribers. */\n mark(actionName: string): void;\n /** Clear every pending action (the \"answer landed\"), notifying only if something was pending. */\n clear(): void;\n}\n\nexport function createProbePendingSource(): ProbePendingSource {\n const pending = new Set<string>();\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const listener of [...listeners]) listener();\n };\n return {\n isPending: (actionName) => pending.has(actionName),\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n mark: (actionName) => {\n pending.add(actionName);\n notify();\n },\n clear: () => {\n if (pending.size === 0) return;\n pending.clear();\n notify();\n },\n };\n}\n\n/** What a control shows, for a before/after comparison around a dispatch. */\nexport interface ControlLook {\n /** Still in the document; `false` when the card replaced the control. */\n readonly connected: boolean;\n /** `disabled`, or `aria-disabled=\"true\"`. */\n readonly disabled: boolean;\n /** `aria-busy=\"true\"`. */\n readonly ariaBusy: boolean;\n /** The control's text. */\n readonly text: string;\n}\n\n/**\n * The DOM surface {@link lookOf} reads: the probe's `MinimalElement` plus\n * the optional `isConnected` a live DOM node carries, and an input's live\n * `value` (an `<input type=\"submit\">` shows its label through it).\n */\nexport interface LookableElement {\n readonly tagName?: string;\n readonly textContent: string | null;\n getAttribute(name: string): string | null;\n readonly isConnected?: boolean;\n readonly value?: unknown;\n}\n\nexport function lookOf(el: LookableElement): ControlLook {\n return {\n connected: el.isConnected !== false,\n // React renders `disabled={true}` as `disabled=\"\"`, so presence is the test.\n disabled: el.getAttribute(\"disabled\") !== null || el.getAttribute(\"aria-disabled\") === \"true\",\n ariaBusy: el.getAttribute(\"aria-busy\") === \"true\",\n text:\n el.tagName?.toLowerCase() === \"input\"\n ? String(typeof el.value === \"string\" ? el.value : (el.getAttribute(\"value\") ?? \"\"))\n : (el.textContent ?? \"\"),\n };\n}\n\n/**\n * Whether `work` settles within `ms`. It never cancels `work`; it only stops\n * waiting for it, so a phase can give up on a card that stalls.\n */\nexport async function settlesWithin(ms: number, work: Promise<unknown>): Promise<boolean> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<false>((resolve) => {\n timer = setTimeout(() => resolve(false), Math.max(0, ms));\n });\n try {\n return await Promise.race([work.then(() => true), expired]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\n/**\n * Whether the control visibly changed between two looks: it became disabled\n * or busy, its text changed (whitespace aside), or the card replaced it.\n */\nexport function lookChanged(before: ControlLook, after: ControlLook): boolean {\n if (before.connected && !after.connected) return true;\n if (!before.disabled && after.disabled) return true;\n if (!before.ariaBusy && after.ariaBusy) return true;\n return before.text.trim() !== after.text.trim();\n}\n","/**\n * The action walk (ggui#1652): find a control that dispatches one action by\n * walking the card's screens, as a person would, in a mount of its own.\n *\n * A screen is the card's set of controls, told apart by each control's tag,\n * type, label (its aria-label, placeholder or text) and disabled state, never\n * by typed values, selection or generated names.\n * Picking an answer is the same screen unless it enables or disables a\n * control; a wizard's next step, or an Edit button that now reads Save, is a\n * new one. Each control is pressed once per screen. When every control on\n * the current screen has been pressed, the walk returns over controls it has\n * already pressed to the nearest screen that still has one to press. A press\n * that leads back to a screen already seen is not progress, so Back and Next\n * cannot loop, in any language. The walk stops at the first press that\n * dispatches the action, when every reachable control has been pressed, at\n * a cap on presses, or at its deadline. Neither the cap nor the deadline\n * stops it while it is on the first screen with a control there still\n * unpressed; once a press leaves the first screen both apply, and a\n * first-screen control left unpressed is pressed only if a known route\n * leads back to it (a one-way wizard has none).\n */\nimport type { MinimalElement } from \"./host-boundary.js\";\n\n/** One control the walk can press, and how. */\nexport interface WalkControl {\n readonly element: MinimalElement;\n /** Whether the control names the action (its label, aria-label or `data-action`). */\n readonly namesAction: boolean;\n}\n\n/** A fresh copy of the card, and how to fill its screen's empty form controls. */\nexport interface WalkMount {\n readonly container: MinimalElement;\n /** Fill the current screen's empty form controls; filled ones are left as they are. */\n readonly prime: () => void;\n}\n\nexport interface WalkInput<C extends WalkControl> {\n /** Mount a fresh copy of the card; undefined when it cannot be mounted. */\n readonly mount: () => Promise<WalkMount | undefined>;\n /** The screen's controls, in the order they are tried. */\n readonly controls: (container: MinimalElement) => readonly C[];\n /** Press one control; true when the press dispatched the action. */\n readonly press: (control: C) => Promise<boolean>;\n readonly describe: (el: MinimalElement) => string;\n /** Epoch ms after which no further press is made. */\n readonly stopAt: number;\n readonly maxPresses: number;\n}\n\nexport type WalkStop = \"dispatched\" | \"explored\" | \"press-cap\" | \"deadline\" | \"no-mount\";\n\nexport interface WalkOutcome {\n readonly fired: boolean;\n /** The control whose press dispatched the action, and the mount it is in. */\n readonly element?: MinimalElement;\n readonly container?: MinimalElement;\n readonly presses: number;\n readonly screens: number;\n readonly stoppedBy: WalkStop;\n /** Whether any screen rendered a control that names the action. */\n readonly namedControlSeen: boolean;\n /** The last few controls pressed, oldest first. */\n readonly lastPressed: readonly string[];\n /** The text of every screen the walk reached, once each, in the order reached. */\n readonly screenTexts: readonly string[];\n}\n\n/** How many of the last presses an outcome keeps. */\nconst LAST_PRESSED_KEPT = 4;\n\nfunction isDisabled(el: MinimalElement): boolean {\n return el.getAttribute(\"disabled\") !== null || el.getAttribute(\"aria-disabled\") === \"true\";\n}\n\n/**\n * A control's label for the fingerprint. Never its `name` or `id`: React\n * generates those (`useId`) afresh when a step re-mounts, so a screen keyed\n * on them would look new on every return and the walk would loop on it.\n */\nfunction labelOf(el: MinimalElement): string {\n const named = el.getAttribute(\"aria-label\") ?? el.getAttribute(\"placeholder\");\n return (named ?? el.textContent ?? \"\").replace(/\\s+/g, \" \").trim().slice(0, 60);\n}\n\n/** The screen's identity: its controls' structure and disabled state, in document order. */\nexport function screenFingerprint(container: MinimalElement): string {\n const parts: string[] = [];\n for (const el of container.querySelectorAll(\n 'button, [role=\"button\"], a[href], input, select, textarea, form'\n )) {\n parts.push(\n [el.tagName.toLowerCase(), el.getAttribute(\"type\") ?? \"\", labelOf(el), isDisabled(el) ? \"disabled\" : \"\"].join(\"|\")\n );\n }\n return parts.join(\"\\n\");\n}\n\ninterface Screen {\n /** Each control's key, in try order. */\n readonly order: readonly string[];\n /** A pressed control's key → the screen its press led to. */\n readonly led: Map<string, string>;\n}\n\n/** Each control's key on a screen: its description, numbered among controls described alike. */\nfunction keyed<C extends WalkControl>(controls: readonly C[], describe: (el: MinimalElement) => string): Map<string, C> {\n const seen = new Map<string, number>();\n const out = new Map<string, C>();\n for (const c of controls) {\n const d = describe(c.element);\n const n = seen.get(d) ?? 0;\n seen.set(d, n + 1);\n out.set(`${d}#${n}`, c);\n }\n return out;\n}\n\n/** The first press of the shortest known route to a screen with a control not yet pressed. */\nfunction firstStepToUnpressed(screens: ReadonlyMap<string, Screen>, from: string): string | undefined {\n const firstStep = new Map<string, string | undefined>([[from, undefined]]);\n const queue = [from];\n while (queue.length > 0) {\n const at = queue.shift()!;\n const screen = screens.get(at);\n if (screen === undefined) continue;\n if (at !== from && screen.order.some((k) => !screen.led.has(k))) return firstStep.get(at);\n for (const [key, to] of screen.led) {\n if (to === at || firstStep.has(to)) continue;\n firstStep.set(to, firstStep.get(at) ?? key);\n queue.push(to);\n }\n }\n return undefined;\n}\n\nexport async function walkToAction<C extends WalkControl>(input: WalkInput<C>): Promise<WalkOutcome> {\n const lastPressed: string[] = [];\n const screenTexts: string[] = [];\n const screens = new Map<string, Screen>();\n let presses = 0;\n let namedControlSeen = false;\n const outcome = (stoppedBy: WalkStop, extra: Partial<WalkOutcome> = {}): WalkOutcome => ({\n fired: false,\n presses,\n screens: screens.size,\n stoppedBy,\n namedControlSeen,\n lastPressed: [...lastPressed],\n screenTexts: [...screenTexts],\n ...extra,\n });\n\n const mounted = await input.mount();\n if (mounted === undefined) return outcome(\"no-mount\");\n const { container } = mounted;\n\n const arrive = (): { id: string; controls: Map<string, C> } => {\n mounted.prime();\n const controls = keyed(input.controls(container), input.describe);\n if ([...controls.values()].some((c) => c.namesAction)) namedControlSeen = true;\n const id = screenFingerprint(container);\n if (!screens.has(id)) {\n screens.set(id, { order: [...controls.keys()], led: new Map() });\n screenTexts.push(container.textContent ?? \"\");\n }\n return { id, controls };\n };\n\n let here = arrive();\n const first = here.id;\n for (;;) {\n const screen = screens.get(here.id)!;\n const onOpenFirstScreen = here.id === first && screen.order.some((k) => !screen.led.has(k));\n if (!onOpenFirstScreen) {\n if (presses >= input.maxPresses) return outcome(\"press-cap\");\n if (Date.now() >= input.stopAt) return outcome(\"deadline\");\n }\n const key = screen.order.find((k) => !screen.led.has(k)) ?? firstStepToUnpressed(screens, here.id);\n if (key === undefined) return outcome(\"explored\");\n const control = here.controls.get(key);\n if (control === undefined) {\n // Listed when the screen was first seen, gone now: nothing to press.\n // It now leads nowhere, which a route never takes, so this cannot\n // pick the same control again.\n screen.led.set(key, here.id);\n continue;\n }\n presses += 1;\n lastPressed.push(input.describe(control.element));\n if (lastPressed.length > LAST_PRESSED_KEPT) lastPressed.shift();\n if (await input.press(control)) {\n return outcome(\"dispatched\", { fired: true, element: control.element, container });\n }\n here = arrive();\n // The first press records where a control leads; a route that later\n // leads elsewhere is simply followed on from where it led.\n if (!screen.led.has(key)) screen.led.set(key, here.id);\n }\n}\n","// packages/ui-gen/src/harness/check/runtime-render/render-check.ts\n//\n// Runtime render verification for compiled components.\n//\n// Pipeline:\n// 1. Spin up happy-dom globals (window/document/etc.)\n// 2. Eval compiled component → React component reference\n// 3. Render it inside <GguiWireProvider config={probeWireConfig}>\n// 4. Run 5 checks against probe + DOM\n// 5. Tear down DOM\n//\n// Block (fail outcome): render-no-throw, action-wiring\n// Warn outcome: prop-coverage, stream-rerender\n//\n// All checks are best-effort: if a heuristic can't find an element, the\n// check fails with a descriptive reason rather than throwing.\n\nimport type { RenderCheckHostOptions } from \"./render-check-host.js\";\nimport type { GenerationRuntimeProbeCheck } from \"@ggui-ai/mcp-server-core\";\nimport type { DataContract, JsonObject, PropsSpec } from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport { createProbe, createProbeWireConfig, type ActionFiredEvent, type Probe } from \"./probe.js\";\nimport { loadComponent } from \"./load-component.js\";\nimport { findWiring, type WiringDetection } from \"./find-wiring.js\";\nimport { installProductionActShim } from \"./production-act-shim.js\";\n// All happy-dom / RTL / user-event narrowing flows through the typed\n// host boundary (one set of structural interfaces + validating guards;\n// DOM-lib-free — some downstream packages, e.g. cloud/amplify, exclude\n// DOM from their tsconfig).\nimport {\n buildClickUser,\n editableSurface,\n parentLink,\n toEventDispatcher,\n toMinimalElement,\n type ClickUser,\n type MinimalElement,\n type ParentLink,\n} from \"./host-boundary.js\";\nimport { hostGlobals, openRecord } from \"../../../internal/open-record.js\";\nimport type { ProbeHostLoad, ProbePendingAffordance } from \"../../../evaluation/types-public.js\";\nimport { createProbePendingSource, lookChanged, lookOf, settlesWithin, type ProbePendingSource } from \"./probe-pending.js\";\nimport { primeInputs } from \"@ggui-ai/ui-visual-tester/prime-inputs\";\nimport { walkToAction, type WalkControl, type WalkMount, type WalkStop } from \"./walk.js\";\n\n/**\n * Module-namespace-shaped value injected into `loadComponent`'s\n * `moduleResolutions`. Structurally equivalent to\n * `@ggui-ai/iframe-runtime`'s `ModuleNamespace` (open record of\n * string keys → unknown) — declared locally so this module doesn't\n * take a dependency on the iframe-runtime package just for a type.\n */\ntype ProbeModuleNamespace = {\n readonly [key: string]: unknown;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Result types\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * 3-state outcome. Internal to runtime-render.\n * The adapter maps this to existing EvalIssue shapes:\n * verified → no issue\n * failed → fail\n * unverified → warn\n * skipped → no issue\n */\nexport type CheckOutcome = \"verified\" | \"failed\" | \"unverified\" | \"skipped\";\n\n/**\n * The checks this probe runs, by name (ggui#1380). ONE union: the same\n * values a generation's metadata lists in `failChecks`\n * (`GenerationRuntimeProbeCheck` in `@ggui-ai/mcp-server-core`), declared\n * there and named here — the same pattern as `RuntimeProbeStatus`.\n */\nexport type RenderCheckKind = GenerationRuntimeProbeCheck;\n\n/**\n * Every {@link RenderCheckKind}, once, in the order the union declares them.\n * The order is the order a probe's `failChecks` lists the checks that failed,\n * so a render crash always reads first. `satisfies` refuses a kind outside\n * the union; the pin beside the adapter refuses a member missing here.\n */\nexport const RENDER_CHECK_KINDS = [\n \"render-no-throw\",\n \"prop-sensitivity\",\n \"action-wiring\",\n \"selection-identity\",\n \"prop-coverage\",\n \"optional-props-omitted\",\n \"stream-rerender\",\n] as const satisfies readonly RenderCheckKind[];\n\nexport interface RenderCheckIssue {\n readonly check: RenderCheckKind;\n readonly outcome: CheckOutcome;\n readonly subject?: string;\n readonly reason: string;\n /** Optional element description (\"button[aria-label='Save']\") for action-wiring failures. */\n readonly elementHint?: string;\n /**\n * Diagnostic context from probe + AST analysis. Populated for richer feedback\n * to the coding agent (which native props the callback flows into, what the\n * probe observed firing, etc.).\n */\n readonly diagnostics?: {\n readonly observedJsxElements?: readonly string[];\n readonly observedNativeProps?: readonly string[];\n readonly observedCustomProps?: readonly string[];\n /** For action-wiring: which actions DID fire from probe clicks (helps surface mis-wiring). */\n readonly actionsFiredFromClicks?: readonly string[];\n /** Surfaced to the agent: prop sourceTool hints from the contract (only if present). */\n readonly sourceToolHints?: Readonly<Record<string, string>>;\n /**\n * For action-wiring (ggui#1187): what input priming did before the\n * synthetic dispatch — how many controls it filled, or why it could not\n * run. A \"did not dispatch it\" on an input-gated action reads differently\n * beside `{ primed: 0 }` or `{ error }` than beside `{ primed: 1 }`.\n */\n readonly inputPriming?: InputPrimingDiagnostic;\n /** For action-wiring (ggui#1652): how far the walk over the card's screens got without dispatching the action. */\n readonly walk?: ActionWalkDiagnostic;\n };\n}\n\n/**\n * The action walk's account of an action it could not dispatch (ggui#1652):\n * how many controls it pressed across how many screens, why it stopped,\n * whether any screen rendered a control naming the action, and the last\n * controls it pressed. Never the first button in the page.\n */\nexport interface ActionWalkDiagnostic {\n readonly presses: number;\n readonly screens: number;\n readonly stoppedBy: Exclude<WalkStop, \"dispatched\">;\n readonly namedControlSeen: boolean;\n readonly lastPressed: readonly string[];\n}\n\n/**\n * Outcome of `primeInputs` before the action-wiring probe (ggui#1187). A\n * priming failure never aborts the check — it is recorded here, on every\n * action-wiring issue, so it is visible in the feedback instead of vanishing.\n */\nexport type InputPrimingDiagnostic = { readonly primed: number } | { readonly error: string };\n\n/**\n * The check started but did not finish (ggui#1299). The only kind is a\n * wall-clock timeout in the isolated worker. It is not a verdict on the\n * component: `issues` is empty and `ok` is false because nothing was\n * verified, never because something failed.\n */\nexport interface RenderCheckIncomplete {\n readonly kind: \"timeout\";\n /** How long the worker ran before it was stopped. */\n readonly elapsedMs: number;\n /** The wall-clock bound it crossed. */\n readonly boundMs: number;\n}\n\nexport interface RenderCheckResult {\n readonly ok: boolean;\n readonly issues: readonly RenderCheckIssue[];\n /** Present only when the check did not finish; see {@link RenderCheckIncomplete}. */\n readonly incomplete?: RenderCheckIncomplete;\n readonly stats: {\n readonly actionsChecked: number;\n readonly streamsChecked: number;\n readonly renderMs: number;\n /** Host load around an isolated check (absent in-process). */\n readonly hostLoad?: ProbeHostLoad;\n /** ggui#1398: the pending-affordance walk, report-only; absent when no action walk ran. */\n readonly pendingAffordance?: ProbePendingAffordance;\n };\n}\n\nexport interface RunRenderCheckInput {\n readonly sourceCode: string;\n readonly mockupProps: JsonObject;\n readonly contract?: DataContract;\n /**\n * Epoch ms by which the check must finish: set by the isolating host from\n * its own bound, absent in-process. The report-only pending phase is\n * skipped when less than {@link PENDING_PHASE_RESERVE_MS} remains, so it\n * can never push a check past its bound (ggui#1398).\n */\n readonly deadlineAt?: number;\n}\n\n/** The time the pending phase needs left before the check's deadline to run at all (ggui#1398). */\nexport const PENDING_PHASE_RESERVE_MS = 5000;\n\n/**\n * The action walk's bounds (ggui#1652), applied once a press has left the\n * first screen (see walk.ts): at most this many presses and this long per\n * action, and never within the pending phase's reserve plus\n * {@link WALK_DEADLINE_MARGIN_MS} (for the checks that run after the walk)\n * of the check's deadline.\n */\nexport const WALK_MAX_PRESSES = 60;\nexport const WALK_ACTION_CAP_MS = 3000;\nconst WALK_DEADLINE_MARGIN_MS = 2000;\n\n/**\n * Options of {@link runRenderCheck} (ggui#1380): the host's options —\n * `bounds` are the isolated subprocess's wall-clock, heap and grace (see\n * `RenderCheckHostBounds`); they apply to the worker path only and are\n * ignored in-process. One shape, declared once on the host.\n */\nexport type RunRenderCheckOptions = RenderCheckHostOptions;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public entry\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Run the in-loop runtime render check.\n *\n * Isolation dispatcher (#592): when the CALLING environment already\n * owns a DOM (`window` + `document` on `globalThis` — e.g. a vitest\n * `happy-dom` environment, where the environment owner installed the\n * globals deliberately), the check runs in-process exactly as before.\n * In a plain Node process it runs in an ISOLATED SUBPROCESS\n * (`render-check-host.ts` → `render-check-worker.ts`), because the\n * in-process path installs happy-dom globals on `globalThis`\n * process-wide — a TOCTOU hazard for anything that sniffs `window`\n * concurrently (provider SDKs throw \"browser-like environment\" at\n * client construction; two overlapping checks corrupt each other's\n * teardown). See #592 for the measured incident (4 bench cells hard-\n * failed on the 2026-08-19 run).\n *\n * The host is loaded lazily so the worker bundle (which imports this\n * module for `runRenderCheckInProcess`) never drags in the sandbox\n * spawn machinery.\n */\nexport async function runRenderCheck(\n input: RunRenderCheckInput,\n options: RunRenderCheckOptions = {}\n): Promise<RenderCheckResult> {\n const g = hostGlobals();\n if (\"window\" in g && \"document\" in g) {\n // In-process: nothing to bound — the check shares the caller's process.\n return runRenderCheckInProcess(input);\n }\n const { runRenderCheckViaWorker } = await import(\"./render-check-host.js\");\n return runRenderCheckViaWorker(input, options);\n}\n\n/**\n * The actual check, executed IN THE CURRENT PROCESS — installs\n * happy-dom globals on `globalThis` for the duration when the\n * environment doesn't already provide a DOM. Call sites outside this\n * module should use {@link runRenderCheck}; this export exists for the\n * isolation worker (which IS the private process the globals may own)\n * and for DOM-owning test environments that want to bypass the\n * dispatcher explicitly.\n */\nexport async function runRenderCheckInProcess(\n input: RunRenderCheckInput\n): Promise<RenderCheckResult> {\n const t0 = Date.now();\n const issues: RenderCheckIssue[] = [];\n\n // ── Stand up happy-dom ────────────────────────────────────────────────\n const teardown = await setupHappyDom();\n // Probe-spy uninstaller — set when the postMessage spy is installed\n // (after probe + happy-dom are both ready). Cleared in the outer\n // finally so early-return paths from probe-pre or probe-post don't\n // leak the spy into the next runRenderCheck invocation.\n let uninstallSpy: (() => void) | undefined;\n // Gadget stub-registry uninstaller — `globalThis.__ggui__` is a\n // process global, so it MUST be torn down in the outer finally.\n let uninstallGadgetRegistry: (() => void) | undefined;\n\n try {\n // ── Pre-resolve modules ONCE so the sandbox + test share one realm ──\n // (React contexts + dispatchers are per-instance — passing the same\n // instances into the sandbox is what makes useContext lookups work.)\n // The @ggui-ai/design package is ESM-only — must use dynamic import\n // (createRequire's CJS require fails on ESM-only packages).\n const React = await import(\"react\");\n const ReactJsxRuntime = await import(\"react/jsx-runtime\");\n const Wire = await import(\"@ggui-ai/wire\");\n const { GguiWireProvider } = Wire;\n\n const moduleResolutions: Record<string, unknown> = {\n react: React,\n \"react/jsx-runtime\": ReactJsxRuntime,\n \"@ggui-ai/wire\": Wire,\n };\n\n // Pre-load the @ggui-ai/design specifiers the boilerplate may import.\n // Post-D1, generated code imports the single bare `@ggui-ai/design`\n // barrel — that MUST be pre-resolved here: the package is ESM-only\n // with no `require` export condition, so `loadComponent`'s\n // `createRequire` fallback cannot load it (it would crash:fail the\n // render check). The subpaths stay for any legacy/first-party code.\n // Per-specifier failures are swallowed — the sandbox throws its own\n // clear error if the component actually needs a missing one.\n const designSpecifiers = [\n \"@ggui-ai/design\",\n \"@ggui-ai/design/primitives\",\n \"@ggui-ai/design/components\",\n \"@ggui-ai/design/compositions\",\n \"@ggui-ai/design/interact\",\n ];\n for (const id of designSpecifiers) {\n try {\n moduleResolutions[id] = await import(id);\n } catch {\n /* skip — sandbox will report a clear error if the component imports it */\n }\n }\n\n // Pre-load `@ggui-ai/gadgets` for components that declare\n // `clientCapabilities.gadgets`. The standard-library hooks\n // (useGeolocation, useCamera, …) live in this package; without it\n // pre-resolved here, the sandbox falls back to `require()` which\n // fails when the caller package doesn't have `@ggui-ai/gadgets` as\n // a direct dep. Swallow on miss —\n // same posture as design subpaths above.\n try {\n moduleResolutions[\"@ggui-ai/gadgets\"] = await import(\"@ggui-ai/gadgets\");\n } catch {\n /* skip — sandbox will report a clear error if the component imports it */\n }\n\n // Install a stub per-package `globalThis.__ggui__.gadgets`\n // registry so direct gadget imports resolve at component-render\n // time. Without it, every gadget-bearing component false-fails\n // `render-no-throw`. `loadGadgets()` is retired —\n // component code direct-imports each gadget export.\n uninstallGadgetRegistry = installGadgetStubRegistry(input.contract);\n\n // Register a CJS shim module for each third-party gadget package\n // the contract declares. The probe re-compiles the\n // component to CJS, so a direct `import { useLeafletMap } from\n // '@ggui-samples/gadget-leaflet'` becomes `require('@ggui-samples/\n // gadget-leaflet')`. The wrapper package itself is not installed\n // in the probe's node_modules — without a shim, `loadComponent`'s\n // sandboxRequire throws \"Import not allowed\". Each shim is a\n // module namespace whose hook exports read the stub registry's\n // per-package slot LAZILY at call time (the slot is populated by\n // `installGadgetStubRegistry` above). `@ggui-ai/gadgets` (STDLIB)\n // is excluded — its real hooks are pre-loaded above and run\n // standalone (they don't read the registry).\n for (const pkg of collectThirdPartyGadgetPackages(input.contract)) {\n if (pkg in moduleResolutions) continue;\n moduleResolutions[pkg] = buildGadgetPackageProbeShim(pkg);\n }\n\n // ── Eval compiled component ─────────────────────────────────────────\n let Component: Awaited<ReturnType<typeof loadComponent>>[\"Component\"];\n try {\n const loaded = await loadComponent({\n sourceCode: input.sourceCode,\n moduleResolutions,\n });\n Component = loaded.Component;\n } catch (e) {\n issues.push({\n check: \"render-no-throw\",\n outcome: \"failed\",\n reason: `Failed to load component: ${e instanceof Error ? e.message : String(e)}`,\n });\n return finalize(issues, t0, 0, 0);\n }\n\n // ── Build probe + wire config ───────────────────────────────────────\n const probe = createProbe();\n const wireConfig = createProbeWireConfig(probe);\n\n // Install the postMessage spy AFTER happy-dom is up so window.parent\n // exists. The spy observes envelopes emitted by the iframe-runtime\n // interceptors (anchor → ui/open-link, requestFullscreen →\n // ui/request-display-mode). WireConfig-layer events (dispatch,\n // subscribe) continue to flow through the closure-shared probe\n // internals.\n uninstallSpy = probe.installPostMessageSpy();\n\n // Must run before RTL's first import in this process — see\n // production-act-shim.ts's docstring for why.\n installProductionActShim();\n const { render, cleanup, act } = await import(\"@testing-library/react\");\n // ggui#1398: the card mounts inside the runtime's pending context, driven\n // by the probe (see probe-pending.ts). Same wire instance as the card's.\n const { ActionPendingContext } = await import(\"@ggui-ai/wire/internal\");\n const pendingSource = createProbePendingSource();\n // user-event v14 default export — see https://testing-library.com/docs/user-event/intro/\n const userEventModule = await import(\"@testing-library/user-event\");\n const userEvent = userEventModule.default ?? userEventModule;\n\n // ── Install console.error spy to break infinite render loops ─────────\n // React logs \"Maximum update depth exceeded\" when setState-in-effect\n // loops (>~25-50 re-renders). Without a break, happy-dom keeps looping\n // until something else stops the process. We hook console.error and\n // throw from within the spy so the render() call's catch-block runs.\n //\n // This catches the dominant hang class (useEffect-dep loop) upstream\n // of the probe wall-clock guard. Also catches \"Too many re-renders\"\n // (React's alternate message) and \"Each child in a list\" (not a\n // hang, but a clear generation bug) — any of these classify as a\n // runtime-loop failure instead of a 12-minute CPU spin.\n const originalConsoleError = console.error;\n let loopSignature: string | null = null;\n // Capture React's component-stack frames when a render error occurs.\n // React 19 logs them via console.error in the form:\n // \"%s\\n\\nThe above error occurred in the <%s> component:\\n%s\\n...\"\n // The 4th argument is the component-stack string (\" at SurveyForm\n // (...) \\n at FormProvider (...) \\n...\"). We capture it so the\n // probe's \"Render threw\" diagnostic can name the offending component.\n let capturedComponentStack: string | null = null;\n const loopPatterns: ReadonlyArray<readonly [RegExp, string]> = [\n [/Maximum update depth exceeded/i, \"max-update-depth\"],\n [/Too many re-renders/i, \"too-many-renders\"],\n [/Rendered more hooks than during the previous render/i, \"hook-count-drift\"],\n ];\n console.error = (...args: unknown[]) => {\n const text = args.map((a) => (typeof a === \"string\" ? a : \"\")).join(\" \");\n // Capture component-stack FIRST (independent of throw decision).\n // Loop-class messages from React 18/19 often include the component\n // stack as a separate arg even on the same call (\"Maximum update\n // depth exceeded\\n at Component (...)\"). If we throw before\n // capture, the loop-class diagnostic is left without component\n // localization (the dominant pre-fix gap).\n if (!capturedComponentStack) {\n // Try to find any arg that looks like a \" at X (...)\" stack.\n for (const arg of args) {\n if (typeof arg === \"string\" && /^\\s*at\\s+\\S/m.test(arg) && arg.length > 20) {\n capturedComponentStack = arg;\n break;\n }\n }\n // Fallback: extract embedded \" at\" lines from the joined text.\n if (!capturedComponentStack) {\n const stackMatch = text.match(/(?:^|\\n)((?:\\s*at\\s+\\S[^\\n]*\\n?){2,})/);\n if (stackMatch) {\n capturedComponentStack = stackMatch[1].trim();\n }\n }\n }\n for (const [pattern, tag] of loopPatterns) {\n if (pattern.test(text)) {\n loopSignature = tag;\n // Throw synchronously — React's render stack unwinds, our\n // try/catch below catches the error, we classify cleanly.\n throw new Error(`[runtime-render] infinite render loop detected (${tag})`);\n }\n }\n // Forward non-matching errors to real console so they're visible.\n originalConsoleError.apply(console, args);\n };\n\n // Error boundary fallback for React's componentStack on synchronous\n // throws (e.g. \"Too many re-renders\"). React 19 throws this directly\n // without going through console.error, so the spy never sees it.\n // The boundary's getDerivedStateFromError + componentDidCatch fire\n // for every render error, sync or async, and componentDidCatch's\n // errorInfo.componentStack is the canonical React-named-component\n // chain. Stored in a closure variable read in the catch block below.\n // Use object container so TS narrowing follows property access (not\n // closure flow analysis, which can't see the componentDidCatch\n // mutation and would narrow these to `null` at the use site).\n const boundaryRef: { stack: string | null; error: Error | null; catches: number } = {\n stack: null,\n error: null,\n catches: 0,\n };\n class ProbeErrorBoundary extends React.Component<\n { children: React.ReactNode },\n { caught: boolean }\n > {\n state = { caught: false };\n static getDerivedStateFromError(): { caught: boolean } {\n return { caught: true };\n }\n componentDidCatch(error: Error, errorInfo: { componentStack?: string }): void {\n // ggui#1398: every catch is counted, so the pending phase can tell a\n // crash while pending from a control that simply went away.\n boundaryRef.catches += 1;\n if (errorInfo.componentStack && !boundaryRef.stack) {\n boundaryRef.stack = errorInfo.componentStack;\n }\n if (!boundaryRef.error) {\n boundaryRef.error = error;\n }\n }\n render(): React.ReactNode {\n if (this.state.caught) return null;\n return this.props.children;\n }\n }\n\n // The card as the runtime mounts it: inside the wire, the probe's error\n // boundary and the pending context. The main render and every action\n // walk's mount (ggui#1652) are this same tree.\n const cardTree = (): React.ReactElement =>\n React.createElement(GguiWireProvider, {\n config: wireConfig,\n children: React.createElement(ProbeErrorBoundary, {\n children: React.createElement(ActionPendingContext.Provider, {\n value: pendingSource,\n children: React.createElement(Component, input.mockupProps),\n }),\n }),\n });\n\n let renderResult: Awaited<ReturnType<typeof render>>;\n const RENDER_TIMEOUT_MS = 5000;\n try {\n // Promise.race safety net for async hangs (effect flushes, timers).\n // Synchronous hangs would block the event loop and the timer never\n // fires, but happy-dom effects are mostly microtask-scheduled so the\n // timeout is actually effective for ~95% of the hang cases.\n const renderPromise = Promise.resolve().then(() => render(cardTree()));\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(\n () =>\n reject(\n new Error(\n `[runtime-render] render exceeded ${RENDER_TIMEOUT_MS}ms — classified as runtime-hang`\n )\n ),\n RENDER_TIMEOUT_MS\n ).unref?.();\n });\n renderResult = await Promise.race([renderPromise, timeoutPromise]);\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n const errStack = e instanceof Error ? (e.stack ?? \"\") : \"\";\n const baseReason = loopSignature\n ? `Infinite render loop (${loopSignature}) — likely setState/dispatch inside useEffect with missing or unstable dependency`\n : /runtime-hang/.test(msg)\n ? `Render wall-clock exceeded ${RENDER_TIMEOUT_MS}ms — likely async effect loop or unresolved promise`\n : `Render threw: ${msg}`;\n // Localization context for the LLM. Two complementary signals:\n // 1. JS error.stack — top frames from the throw site. Filter to\n // user-code lines (drop happy-dom / RTL / React internals)\n // so the most relevant frame is on top. The bundled output is\n // minified but esbuild keeps line numbers (`keepNames: true`),\n // so frames usually pinpoint a region of the source the LLM\n // can patch.\n // 2. React componentStack — captured via console.error spy when\n // React logs \"above error occurred in the X component\". Names\n // the failing component; on multi-component renders this is\n // the difference between \"find the bad iteration\" and \"look in\n // <SurveyStep>\". Cap to keep prompt budget bounded.\n const userFrames = errStack\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"at \"))\n .filter(\n (l) =>\n !/(node_modules|happy-dom|@testing-library|react-dom|node:internal|node:async)/.test(l)\n )\n .slice(0, 5);\n // Prefer the ErrorBoundary-captured stack (richer + names component\n // wrappers like memo/forwardRef), fall back to the spy-captured one.\n const stackSource = boundaryRef.stack ?? capturedComponentStack ?? \"\";\n const componentFrames = stackSource\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => l.startsWith(\"at \"))\n .slice(0, 4);\n const stackBlock = userFrames.length\n ? `\\n Stack (user frames): ${userFrames.join(\" | \")}`\n : \"\";\n const componentBlock = componentFrames.length\n ? `\\n Component stack: ${componentFrames.join(\" > \")}`\n : \"\";\n const loopReason = `${baseReason}${stackBlock}${componentBlock}`;\n issues.push({\n check: \"render-no-throw\",\n outcome: \"failed\",\n reason: loopReason,\n });\n console.error = originalConsoleError;\n return finalize(issues, t0, 0, 0);\n }\n console.error = originalConsoleError;\n\n // ErrorBoundary caught a crash even though render() didn't throw.\n // This happens when the synchronous error happens during the commit\n // phase of a child component — the boundary swallows it and renders\n // null, but the page is still broken. Treat as render-no-throw fail.\n if (boundaryRef.stack || boundaryRef.error) {\n const componentFrames = (boundaryRef.stack ?? \"\")\n .split(\"\\n\")\n .map((l: string) => l.trim())\n .filter((l: string) => l.startsWith(\"at \"))\n .slice(0, 4);\n const compBlock = componentFrames.length\n ? `\\n Component stack: ${componentFrames.join(\" > \")}`\n : \"\";\n const errMsg = boundaryRef.error ? boundaryRef.error.message : \"(no error message)\";\n issues.push({\n check: \"render-no-throw\",\n outcome: \"failed\",\n reason: `Render threw: ${errMsg}${compBlock}`,\n });\n cleanup();\n return finalize(issues, t0, 0, 0);\n }\n\n // RTL types `container` as HTMLElement; narrow it to the structural\n // MinimalElement via the validated host boundary.\n const container = toMinimalElement(renderResult.container);\n // Pass the live document explicitly — user-event's bare `setup()`\n // binds the document captured at its module load, which is undefined\n // when the module was pre-warmed before happy-dom stood up (ggui#403).\n const user: ClickUser = buildClickUser(userEvent, hostGlobals().document);\n\n let actionsChecked = 0;\n let streamsChecked = 0;\n // ggui#1398 leg 3 — the pending-affordance tally, report-only. Set only\n // when the action walk runs, so an absent field means \"no walk\".\n let pendingTally: PendingTally | undefined;\n // The controls whose click really dispatched their action, looked at in\n // the pending phase after every other check (see runPendingPhase).\n const pendingTargets: PendingTarget[] = [];\n // The text of every screen the action walks reached (ggui#1652): a prop\n // shown on a later step is shown, though the action check never moves\n // the main render off its first screen.\n const walkedTexts: string[] = [];\n\n try {\n // ggui#1187: prime form inputs before the action-wiring probe. A wired\n // Send/Submit gated on a non-empty input (the chat-interface shape) is a\n // no-op on empty, so an un-primed synthetic click never dispatches and\n // the probe false-warns \"did not dispatch it\". Shared with the visual\n // tester's primeInputs (#1021/#1040) so both prime identically. The\n // main render is primed here, on every card, before any check reads it;\n // each action walk's mount (ggui#1652) primes every screen it reaches.\n // A priming failure never aborts the check — it is RECORDED on every\n // action-wiring issue as `diagnostics.inputPriming`. (The first cut\n // swallowed it, and a `ReferenceError` in the check worker's realm —\n // no `HTMLInputElement` on `globalThis` — hid behind that catch while\n // every chat cell kept warning.)\n let inputPriming: InputPrimingDiagnostic;\n try {\n inputPriming = { primed: primeInputs(renderResult.container) };\n } catch (err) {\n inputPriming = { error: err instanceof Error ? err.message : String(err) };\n }\n // ── Check 2: Action wiring (BLOCK / unverified-as-warn) ───────────\n // ggui#1652: each action is looked for in a mount of its own, walked\n // screen by screen (walk.ts), so this check never presses the main\n // render the later checks read. (The duplicate-label check below, #601,\n // still makes its two clicks there, as it always did.)\n if (input.contract?.actionSpec) {\n const actionSpec = input.contract.actionSpec;\n for (const [name, entry] of Object.entries(actionSpec)) {\n actionsChecked++;\n const wiring = findWiring({\n sourceCode: input.sourceCode,\n hookName: \"useAction\",\n hookArg: name,\n });\n // A priming failure on a screen the walk reached is recorded too,\n // when the main render's priming did not already fail.\n const walkPriming: { error?: string } = {};\n const mount = async (): Promise<WalkMount | undefined> => {\n let mounted: ReturnType<typeof render>;\n try {\n mounted = render(cardTree());\n } catch {\n return undefined;\n }\n await flushPromises();\n const root = mounted.container;\n return {\n container: toMinimalElement(root),\n prime: () => {\n try {\n primeInputs(root);\n } catch (err) {\n walkPriming.error ??= err instanceof Error ? err.message : String(err);\n }\n },\n };\n };\n const issue = await checkActionWiring({\n mount,\n actionName: name,\n actionLabel: entry.label,\n wiring,\n probe,\n user,\n pendingTargets,\n stopAt: walkStopAt(input.deadlineAt),\n walkedTexts,\n });\n if (issue) {\n const priming: InputPrimingDiagnostic =\n \"primed\" in inputPriming && walkPriming.error !== undefined\n ? { error: `on a screen the action walk reached: ${walkPriming.error}` }\n : inputPriming;\n issues.push({ ...issue, diagnostics: { ...issue.diagnostics, inputPriming: priming } });\n }\n }\n }\n\n // ── Check 2b: Selection identity — duplicate-label cells (#601) ───\n // The live bug: a slot grid rendered several cells with the same\n // visible label (\"09:00\" across stylist rows); clicking one\n // selected ALL of them because the generated code keyed\n // selection/payload on the DISPLAY VALUE instead of the cell's\n // identity — even though the action schema carried an id field.\n // Wire-behavior check, DOM-shape independent: click two\n // same-label clickables and require their fired payloads to\n // differ on the id-like field. Conservative: any ambiguity\n // (no duplicate labels, clicks that fire nothing, payloads\n // missing the field) yields NO issue — those belong to other\n // checks.\n if (input.contract?.actionSpec) {\n for (const [name, entry] of Object.entries(input.contract.actionSpec)) {\n const idField = idLikeRequiredStringField(\n entry.schema as Record<string, unknown> | undefined\n );\n if (idField === null) continue;\n const issue = await checkSelectionIdentity({\n container,\n probe,\n user,\n actionName: name,\n idField,\n });\n if (issue) issues.push(issue);\n }\n }\n\n // ── Check 3: Agent-tool wiring — RETIRED ──────────────────────────\n // `useWiredTool` is retired. The contract's `agentCapabilities.tools`\n // is a catalog of tools the AGENT invokes — there is no component hook\n // surface. Cross-refs from actionSpec[*].nextStep /\n // streamSpec[*].source.tool ride through checks 2 (action wiring)\n // and 6 (stream re-render); the catalog itself has no\n // component-side requirement to verify here.\n\n // ── Check 4: Client-capability hook usage (WARN) ──────────────────\n // `clientTools` is retired. Capability hooks are imported from\n // `@ggui-ai/gadgets` (or vendor packages) and own their own\n // lifecycle — the runtime-render probe doesn't intercept them.\n // The tier-0 substring check in `run-tier0.ts` is the gate that\n // detects un-called capability bindings at gen time.\n\n // ── Check 5: Prop coverage (WARN) ─────────────────────────────────\n if (input.contract?.propsSpec) {\n for (const issue of checkPropCoverage({\n container,\n walkedTexts,\n propsSpec: input.contract.propsSpec as PropsSpec,\n mockupProps: input.mockupProps,\n })) {\n issues.push(issue);\n }\n }\n\n // ── Check 5c: Prop sensitivity (#563) ─────────────────────────────\n // The measured class (economy/001 run 6): generated code renders a\n // value the contract delivers via props but BAKES the request's\n // literal — `props.month ?? 'January'` date math, hardcoded display\n // text — so a cached blueprint reused under a different value serves\n // the wrong surface. Deterministic detection for the DISPLAYED-value\n // half: re-render with a distinct value for each required scalar\n // prop whose original value visibly appears in the DOM; if the\n // rendered text is IDENTICAL under the change, the prop's value is\n // dead — baked. Scope honesty: value-ANCHORED logic that still\n // reacts (differently-wrong branches) is not deterministically\n // decidable here; the matcher-side pair armor and the judge track\n // that half. Conservative nulls: non-displayed props (ids are\n // legitimately non-visual), varied-value crashes (the code READ the\n // prop — not dead), and non-scalar props are all skipped.\n if (input.contract?.propsSpec) {\n const propsSpec5c = input.contract.propsSpec as PropsSpec;\n const normalize = (s: string | null): string => (s ?? \"\").replace(/\\s+/g, \" \").trim();\n const baseText = normalize(container.textContent);\n for (const [propName, entry] of Object.entries(propsSpec5c.properties)) {\n if (!entry.required) continue;\n const orig = input.mockupProps[propName];\n if (typeof orig !== \"string\" && typeof orig !== \"number\") continue;\n const marker = pickScalarMarker(orig);\n if (marker === null || !baseText.includes(marker)) continue;\n // Distinct same-type value. A token that never substring-matches\n // the original, so value-anchored branches (`includes(orig)`)\n // genuinely flip.\n const varied: string | number =\n typeof orig === \"string\" ? \"Zzyzx Qw\" : (orig as number) + 137731;\n // Isolated probe/wire per varied mount — events must not leak\n // into the primary probe's fire log.\n const variedProbe = createProbe();\n const variedConfig = createProbeWireConfig(variedProbe);\n let variedResult: ReturnType<typeof render> | undefined;\n try {\n variedResult = render(\n React.createElement(GguiWireProvider, {\n config: variedConfig,\n children: React.createElement(ProbeErrorBoundary, {\n children: React.createElement(Component, {\n ...input.mockupProps,\n [propName]: varied,\n }),\n }),\n })\n );\n } catch {\n continue; // crash on varied value ⇒ the prop is read, not dead\n }\n await flushPromises();\n const variedText = normalize(variedResult.container.textContent);\n variedResult.unmount();\n if (variedText === baseText) {\n issues.push({\n check: \"prop-sensitivity\",\n outcome: \"failed\",\n subject: propName,\n reason: `props.${propName} is displayed ('${marker}' appears in the DOM) but changing its value to '${String(varied)}' left the rendered output BYTE-IDENTICAL — the value is baked into the component instead of derived from the prop. A cached reuse of this blueprint under a different ${propName} would show the original value.`,\n });\n }\n }\n }\n\n // ── Check 6: Stream re-render (WARN) ──────────────────────────────\n if (input.contract?.streamSpec) {\n const streamSpec = input.contract.streamSpec;\n for (const [name] of Object.entries(streamSpec)) {\n streamsChecked++;\n const issue = await checkStreamRerender({\n container,\n eventName: name,\n probe,\n React,\n });\n if (issue) issues.push(issue);\n }\n }\n\n // ── Check 7: Optional-props omission (BLOCK on crash, ggui#528) ──\n // The main pass renders with EVERY declared prop filled, so a\n // component that assumes an optional prop is present always\n // passes here and crashes only live, when an agent legitimately\n // omits it (the wire gate requires only `required === true`\n // props). Render a second instance with the optional props\n // STRIPPED — a throw is exactly the latent-undefined class this\n // check exists to surface. Runs only when the contract declares\n // at least one optional prop that the mockup filled; zero cost\n // otherwise.\n const declaredProps = input.contract?.propsSpec?.properties;\n if (declaredProps) {\n const optionalFilled = Object.entries(declaredProps)\n .filter(\n ([name, entry]) =>\n (entry as { required?: boolean }).required !== true &&\n input.mockupProps[name] !== undefined\n )\n .map(([name]) => name);\n if (optionalFilled.length > 0) {\n const requiredOnlyProps: JsonObject = { ...input.mockupProps };\n for (const name of optionalFilled) delete requiredOnlyProps[name];\n const omitBoundaryRef: { error?: Error } = {};\n class OmitErrorBoundary extends React.Component<\n { children?: React.ReactNode },\n { caught: boolean }\n > {\n state = { caught: false };\n static getDerivedStateFromError(): { caught: boolean } {\n return { caught: true };\n }\n componentDidCatch(error: Error): void {\n omitBoundaryRef.error ??= error;\n }\n render(): React.ReactNode {\n if (this.state.caught) return null;\n return this.props.children;\n }\n }\n try {\n render(\n React.createElement(GguiWireProvider, {\n config: wireConfig,\n children: React.createElement(OmitErrorBoundary, {\n children: React.createElement(Component, requiredOnlyProps),\n }),\n })\n );\n } catch (e) {\n omitBoundaryRef.error ??= e instanceof Error ? e : new Error(String(e));\n }\n if (omitBoundaryRef.error) {\n issues.push({\n check: \"optional-props-omitted\",\n outcome: \"failed\",\n subject: optionalFilled.join(\", \"),\n reason:\n `Render crashed when the optional prop(s) ${optionalFilled\n .map((n) => `'${n}'`)\n .join(\", \")} were omitted: ${omitBoundaryRef.error.message}. ` +\n `The contract marks them optional (no \\`required: true\\`), so a legitimate render may leave them out.`,\n });\n }\n }\n }\n\n // ── Pending phase (ggui#1398, report-only) ────────────────────────\n // LAST, while the main render is still mounted: every check above has\n // already read the DOM, so a card that crashes or resets while pending\n // cannot change what they found.\n const timeLeft = input.deadlineAt === undefined ? Number.POSITIVE_INFINITY : input.deadlineAt - Date.now();\n if (input.contract?.actionSpec && timeLeft >= PENDING_PHASE_RESERVE_MS) {\n pendingTally = await runPendingPhase({\n targets: pendingTargets,\n source: pendingSource,\n act,\n catches: () => boundaryRef.catches,\n actions: Object.entries(input.contract.actionSpec).map(([name, entry]) => ({ name, label: entry.label })),\n ...(input.deadlineAt !== undefined ? { deadlineAt: input.deadlineAt } : {}),\n });\n }\n } finally {\n cleanup();\n }\n\n return finalize(issues, t0, actionsChecked, streamsChecked, pendingTally);\n } finally {\n try {\n uninstallSpy?.();\n } catch {\n /* ignore */\n }\n try {\n uninstallGadgetRegistry?.();\n } catch {\n /* ignore */\n }\n teardown();\n }\n}\n\n/**\n * Install a stub `globalThis.__ggui__` gadget registry so direct\n * gadget imports resolve at component-render time.\n *\n * Generated component code direct-imports gadget exports — there is no\n * runtime `loadGadgets()` registry call. For example, `import { useGeolocation } from\n * '@ggui-ai/gadgets'`, `import { useLeafletMap } from\n * '@ggui-samples/gadget-leaflet'`. The renderer's import rewriter\n * substitutes each gadget package specifier with a per-package\n * data-URL shim (`buildGadgetPackageShim`) whose named exports read\n * `globalThis.__ggui__.gadgets[<package>][<export>]` lazily at\n * call/render time.\n *\n * The runtime-render probe does not boot an iframe runtime, so that\n * `__ggui__.gadgets` slot is absent — without this stub, every\n * gadget-bearing component false-fails `render-no-throw` with\n * \"[gadget] export '…' is not loaded\".\n *\n * The registry installed here is **per-package** (`GadgetPackageRegistry`):\n * `{ '<package>': { '<export>': fn, … }, … }`. The shim resolves\n * `gadgets[package][export]`, so a flat hook-name keying would miss.\n *\n * The probe cannot run a real third-party gadget (Leaflet, Mapbox) in\n * happy-dom, so each export the contract declares is stubbed by kind,\n * discriminated by the export-name grammar:\n * - a HOOK export (`use`-prefixed) is stubbed with the uniform gadget\n * result contract the boilerplate teaches — `{ status, value,\n * start }`: `status` is a real string (safe as a React child and in\n * comparisons), `value`'s fields are no-op functions (safe as\n * callback refs + imperative calls like `panTo`), `start` is a no-op.\n * - a COMPONENT export (PascalCase) is stubbed with a function\n * component that renders nothing (`() => null`) — React invokes it\n * when the host renders `<X … />`.\n * The probe thus verifies the COMPONENT's own render tree while\n * treating the gadget as a well-behaved black box.\n *\n * Returns an uninstaller; the caller MUST invoke it — `globalThis` is\n * a process global and a leaked slot taints the next check.\n */\nexport function installGadgetStubRegistry(contract: DataContract | undefined): () => void {\n const declared = contract?.clientCapabilities?.gadgets;\n if (!declared || Object.keys(declared).length === 0) {\n return () => {};\n }\n\n const noop = (): void => {};\n // A gadget `value` carries an imperative surface (`containerRef`\n // callback ref, `panTo`, `setView`, …) — every field resolves to a\n // no-op so refs attach and imperative calls stay safe.\n const valueStub = new Proxy(\n {},\n {\n get: (_t, key) => (key === \"then\" || typeof key === \"symbol\" ? undefined : noop),\n }\n );\n const result = { status: \"idle\", value: valueStub, start: noop };\n // Unknown top-level keys resolve to a no-op (covers `map.foo()`);\n // `then` + symbol keys pass through so `await` / coercion stay safe.\n const resultStub = new Proxy(result, {\n get: (t, key) => {\n if (key === \"status\" || key === \"value\" || key === \"start\") {\n return t[key];\n }\n return key === \"then\" || typeof key === \"symbol\" ? undefined : noop;\n },\n });\n\n // Per-package registry — `{ '<package>': { '<export>': fn } }`.\n // Mirrors the runtime `GadgetPackageRegistry` shape that\n // `buildGadgetPackageShim` reads (`gadgets[package][export]`).\n // Iterate the flattened `GadgetUse[]`; kind is discriminated\n // by the export-name grammar.\n const gadgets: Record<string, Record<string, unknown>> = {};\n for (const use of contract ? listContractGadgets(contract) : []) {\n const pkgSlot = (gadgets[use.package] ??= {});\n if (HOOK_NAME_RE.test(use.name)) {\n // Hook export — the component CALLS it; return the uniform\n // `{ status, value, start }` gadget result stub.\n pkgSlot[use.name] = () => resultStub;\n } else {\n // Component export (PascalCase) — React invokes it as a\n // function component. Render nothing: the gadget stays a\n // well-behaved black box while the host component's own render\n // tree is the thing under verification.\n pkgSlot[use.name] = () => null;\n }\n }\n\n const root = globalThis as { __ggui__?: unknown };\n const prior = root.__ggui__;\n root.__ggui__ = { gadgets, publicEnv: {} };\n return () => {\n if (prior === undefined) {\n delete root.__ggui__;\n } else {\n root.__ggui__ = prior;\n }\n };\n}\n\n/**\n * Collect the distinct third-party gadget package names a contract\n * declares. The STDLIB package `@ggui-ai/gadgets` is\n * EXCLUDED — its real hooks are pre-loaded into the probe sandbox and\n * run standalone (they implement browser APIs directly, not via the\n * `__ggui__.gadgets` registry). Only operator-registered wrapper\n * packages need a sandbox shim.\n */\nfunction collectThirdPartyGadgetPackages(contract: DataContract | undefined): string[] {\n if (!contract) return [];\n const packages = new Set<string>();\n for (const use of listContractGadgets(contract)) {\n if (use.package !== \"@ggui-ai/gadgets\") packages.add(use.package);\n }\n return [...packages];\n}\n\n/**\n * Build a CJS module-namespace shim for one third-party gadget\n * package, for injection into `loadComponent`'s\n * `moduleResolutions`.\n *\n * The probe re-compiles the component to CJS, so a direct\n * `import { useX } from '<package>'` becomes `require('<package>')`\n * and pulls `module.exports.<X>`. This shim is a Proxy whose every\n * property is a lazy thunk forwarding to the stub registry's\n * per-package slot — `globalThis.__ggui__.gadgets[<package>][<export>]`\n * — at CALL time. Lazy resolution matches the runtime rewriter's\n * `buildGadgetPackageShim` read pattern and is robust to the registry\n * being installed after the shim is built.\n *\n * The probe cannot run a real third-party gadget in happy-dom; the\n * registry slot holds the stub `installGadgetStubRegistry` plants —\n * the uniform `{ status, value, start }` result for a hook export, or\n * a render-nothing component for a PascalCase component export — so the\n * host COMPONENT's own render tree is verified while the gadget stays a\n * well-behaved black box.\n */\nfunction buildGadgetPackageProbeShim(packageName: string): ProbeModuleNamespace {\n const resolveExport = (name: string): unknown => {\n const root = globalThis as {\n __ggui__?: { gadgets?: Record<string, Record<string, unknown>> };\n };\n return root.__ggui__?.gadgets?.[packageName]?.[name];\n };\n // Lazy thunk — forwards to the registry slot at call/render time.\n // Covers both hooks (`useX()`) and gadget components (`<X />`, which\n // React invokes as a function).\n const makeThunk =\n (name: string) =>\n (...args: unknown[]): unknown => {\n const impl = resolveExport(name);\n if (typeof impl !== \"function\") {\n throw new Error(\n `[gadget] export '${name}' from '${packageName}' is not loaded in the render-check probe — the component imports it but the contract's clientCapabilities.gadgets never declared it, so installGadgetStubRegistry planted no stub.`\n );\n }\n return (impl as (...a: unknown[]) => unknown)(...args);\n };\n return new Proxy(\n {},\n {\n get: (_t, key) => {\n if (typeof key === \"symbol\" || key === \"default\" || key === \"then\") {\n return undefined;\n }\n return makeThunk(key);\n },\n // `key in ns` checks (esbuild interop may probe) report true so\n // the named import binds to the thunk rather than `undefined`.\n has: (_t, key) => typeof key !== \"symbol\" && key !== \"then\" && key !== \"default\",\n }\n ) as ProbeModuleNamespace;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Setup / teardown\n// ─────────────────────────────────────────────────────────────────────────────\n\nasync function setupHappyDom(): Promise<() => void> {\n const g = hostGlobals();\n\n // ── Async-teardown safety ───────────────────────────────────────────────\n // Generated components may call setTimeout/setInterval for polling,\n // delayed renders, debouncing, etc. If a timer fires AFTER we delete\n // window/document, its callback's setState lookup will read\n // `window.event` (React dev path) and throw an unhandled exception\n // that crashes the whole process (observed: run3 of post-probe-guard).\n //\n // Mitigations:\n // 1. Wrap setTimeout/setInterval to track pending IDs; clear them all\n // on teardown.\n // 2. Install a process-level uncaughtException/unhandledRejection\n // handler during the probe's lifetime that swallows DOM-teardown-\n // class errors and forwards anything else.\n const pendingTimeouts = new Set<NodeJS.Timeout>();\n const pendingIntervals = new Set<NodeJS.Timeout>();\n const origSetTimeout = globalThis.setTimeout;\n const origSetInterval = globalThis.setInterval;\n const origClearTimeout = globalThis.clearTimeout;\n const origClearInterval = globalThis.clearInterval;\n // Same documented adaptation as the setInterval wrapper below: the\n // arrow function satisfies the call signature but not Node's\n // `__promisify__` brand, so a single structural cast closes the gap.\n globalThis.setTimeout = ((...args: Parameters<typeof origSetTimeout>) => {\n const id = origSetTimeout(...args);\n pendingTimeouts.add(id);\n return id;\n }) as typeof globalThis.setTimeout;\n globalThis.setInterval = ((...args: Parameters<typeof origSetInterval>) => {\n const id = origSetInterval(...args);\n pendingIntervals.add(id);\n return id;\n }) as typeof globalThis.setInterval;\n globalThis.clearTimeout = (id?: string | number | NodeJS.Timeout) => {\n if (id !== undefined) pendingTimeouts.delete(id as NodeJS.Timeout);\n return origClearTimeout(id);\n };\n globalThis.clearInterval = (id?: string | number | NodeJS.Timeout) => {\n if (id !== undefined) pendingIntervals.delete(id as NodeJS.Timeout);\n return origClearInterval(id);\n };\n\n const isTeardownArtifact = (err: unknown): boolean => {\n const msg = err instanceof Error ? err.message : String(err);\n return (\n /window is not defined/i.test(msg) ||\n /document is not defined/i.test(msg) ||\n /Cannot read propert(?:y|ies) of undefined \\(reading 'event'\\)/i.test(msg) ||\n /requestAnimationFrame is not defined/i.test(msg)\n );\n };\n const uncaughtHandler = (err: Error): void => {\n if (isTeardownArtifact(err)) {\n // Expected — a generated component's late timer fired after teardown.\n // Swallow silently; the probe already recorded its outcome.\n return;\n }\n // Not ours — re-throw on next tick so the default handler runs.\n process.nextTick(() => {\n throw err;\n });\n };\n const unhandledHandler = (reason: unknown): void => {\n if (isTeardownArtifact(reason)) return;\n const err = reason instanceof Error ? reason : new Error(String(reason));\n process.nextTick(() => {\n throw err;\n });\n };\n process.on(\"uncaughtException\", uncaughtHandler);\n process.on(\"unhandledRejection\", unhandledHandler);\n\n const cleanupAsyncInfra = (): void => {\n for (const id of pendingTimeouts) origClearTimeout(id);\n for (const id of pendingIntervals) origClearInterval(id);\n pendingTimeouts.clear();\n pendingIntervals.clear();\n globalThis.setTimeout = origSetTimeout;\n globalThis.setInterval = origSetInterval;\n globalThis.clearTimeout = origClearTimeout;\n globalThis.clearInterval = origClearInterval;\n // Keep uncaughtException/unhandledRejection handlers registered for a\n // brief grace period. React 19's concurrent scheduler can defer state\n // updates via microtasks / setImmediate — those flush AFTER the probe\n // returns, and if our handlers are gone they'll crash the process.\n // Observed on exp47-control-run2: `useWiredTool.call → dispatchSetState`\n // fired post-teardown, ReferenceError: window is not defined, full\n // process crash. 100ms is long enough for React's scheduler to drain\n // without meaningfully delaying the next cell's setup.\n origSetTimeout(() => {\n process.off(\"uncaughtException\", uncaughtHandler);\n process.off(\"unhandledRejection\", unhandledHandler);\n }, 100).unref?.();\n };\n\n // If window/document already exist (e.g., Vitest happy-dom environment), trust them.\n // Just toggle the React act flag and return a teardown that restores timer state.\n if (\"window\" in g && \"document\" in g) {\n const priorActFlag = g.IS_REACT_ACT_ENVIRONMENT;\n g.IS_REACT_ACT_ENVIRONMENT = true;\n return () => {\n cleanupAsyncInfra();\n if (priorActFlag === undefined) delete g.IS_REACT_ACT_ENVIRONMENT;\n else g.IS_REACT_ACT_ENVIRONMENT = priorActFlag;\n };\n }\n\n const { Window } = await import(\"happy-dom\");\n const window = new Window({ url: \"https://render-check.local\" });\n const windowAny = openRecord(window);\n\n const keys = [\n \"window\",\n \"document\",\n \"navigator\",\n \"HTMLElement\",\n \"Node\",\n \"Element\",\n \"Event\",\n \"MouseEvent\",\n \"KeyboardEvent\",\n \"getComputedStyle\",\n \"requestAnimationFrame\",\n \"cancelAnimationFrame\",\n ];\n const prior: Record<string, { value: unknown; existed: boolean }> = {};\n for (const k of keys) {\n prior[k] = { value: g[k], existed: k in g };\n try {\n // Use defineProperty to bypass any getter-only restrictions on the host.\n Object.defineProperty(g, k, {\n value: windowAny[k],\n writable: true,\n configurable: true,\n });\n } catch {\n // Skip globals we can't override (e.g., locked-down host runtimes).\n }\n }\n\n g.IS_REACT_ACT_ENVIRONMENT = true;\n\n return () => {\n cleanupAsyncInfra();\n for (const k of keys) {\n try {\n if (prior[k]!.existed) {\n Object.defineProperty(g, k, {\n value: prior[k]!.value,\n writable: true,\n configurable: true,\n });\n } else {\n delete g[k];\n }\n } catch {\n /* ignore */\n }\n }\n delete g.IS_REACT_ACT_ENVIRONMENT;\n };\n}\n\nfunction finalize(\n issues: RenderCheckIssue[],\n t0: number,\n actionsChecked: number,\n streamsChecked: number,\n pendingTally?: PendingTally\n): RenderCheckResult {\n const ok = !issues.some((i) => i.outcome === \"failed\");\n return {\n ok,\n issues,\n stats: {\n actionsChecked,\n streamsChecked,\n renderMs: Date.now() - t0,\n ...(pendingTally !== undefined\n ? {\n pendingAffordance: {\n dispatched: pendingTally.dispatched,\n visible: pendingTally.visible,\n missing: [...pendingTally.missing],\n gone: [...pendingTally.gone],\n },\n }\n : {}),\n },\n };\n}\n\n/** The walk's running tally (ggui#1398); frozen into `stats.pendingAffordance` by {@link finalize}. */\ninterface PendingTally {\n dispatched: number;\n visible: number;\n missing: string[];\n gone: string[];\n}\n\n/** A control whose click really dispatched its action (ggui#1398). */\ninterface PendingTarget {\n readonly actionName: string;\n readonly actionLabel: string;\n readonly wiringKind: \"click\" | \"submit\";\n readonly element: MinimalElement;\n /** The mount the action's walk pressed it in (ggui#1652), where it is looked for again. */\n readonly container: MinimalElement;\n}\n\ninterface PendingPhaseInput {\n readonly targets: readonly PendingTarget[];\n readonly source: ProbePendingSource;\n /** React Testing Library's `act`, so the pending re-render commits before the control is read. */\n readonly act: (callback: () => Promise<void>) => Promise<unknown>;\n /** How many throws the probe's error boundary has caught so far. */\n readonly catches: () => number;\n /** Every action the contract declares: a control that now names another one is no longer this action's control. */\n readonly actions: readonly { readonly name: string; readonly label: string }[];\n /** The check's deadline (epoch ms), when the isolating host set one. */\n readonly deadlineAt?: number;\n}\n\n/** The longest the phase waits on one control's pending mark and read (ggui#1398). */\nexport const PENDING_TARGET_CAP_MS = 2000;\n/** The time the phase always leaves before the check's deadline. */\nconst PENDING_PHASE_TAIL_MS = 1000;\n\n/**\n * For each control whose click dispatched: mark its action pending (the\n * runtime does this when the dispatch commits), compare the control with\n * its look just before, then clear it (the agent's answer). Visible means\n * the pending state itself changed the control.\n *\n * - The pressed element stays the action's control while it is in the page,\n * whatever it now says (\"Add to Cart\" may relabel itself \"Added\"), unless\n * it now names another of the contract's actions. Only a control that left\n * the page is looked for again, by its own action identity (label,\n * aria-label, `data-action`); if none is found it is `gone`.\n * - A form target (submit wiring) is read through its control that names the\n * action, else its first submit-type control, else the form itself.\n * - A card that throws while pending counts that control as missing, and\n * every control after it is gone (the card renders nothing).\n * - Each mark-and-read is capped ({@link PENDING_TARGET_CAP_MS}, and never\n * past the check's deadline less a tail). A control whose read does not\n * settle in time counts as missing and ends the phase, so a stalled card\n * cannot push the check past its bound. A synchronous busy loop cannot be\n * cut short this way; React turns runaway update loops into throws.\n */\nasync function runPendingPhase(input: PendingPhaseInput): Promise<PendingTally> {\n const tally: PendingTally = { dispatched: 0, visible: 0, missing: [], gone: [] };\n let stopped = false;\n for (const target of input.targets) {\n const budget = Math.min(\n PENDING_TARGET_CAP_MS,\n input.deadlineAt === undefined ? Number.POSITIVE_INFINITY : input.deadlineAt - Date.now() - PENDING_PHASE_TAIL_MS\n );\n const found = stopped || budget <= 0 ? undefined : pendingControlOf(target, input.actions);\n if (found === undefined) {\n tally.gone.push(target.actionName);\n if (budget <= 0) stopped = true;\n continue;\n }\n const el = controlToRead(found, target);\n const before = lookOf(el);\n const caughtBefore = input.catches();\n const settled = await settlesWithin(\n budget,\n (async () => {\n await input.act(async () => {\n input.source.mark(target.actionName);\n });\n await flushPromises();\n })()\n );\n const crashed = input.catches() !== caughtBefore;\n tally.dispatched += 1;\n if (settled && !crashed && lookChanged(before, lookOf(el))) tally.visible += 1;\n else tally.missing.push(target.actionName);\n if (!settled) {\n stopped = true;\n continue;\n }\n await input.act(async () => {\n input.source.clear();\n });\n await flushPromises();\n if (crashed) stopped = true;\n }\n return tally;\n}\n\n/**\n * The action's control at the phase's turn: the pressed element while it is\n * in the page and does not now name another of the contract's actions;\n * otherwise, for click wiring, the action's control found again by its own\n * identity only. A submit target (a form) has no identity to look for.\n */\nfunction pendingControlOf(\n target: PendingTarget,\n actions: readonly { readonly name: string; readonly label: string }[]\n): MinimalElement | undefined {\n const movedToAnother =\n !matchesActionIdentity(target.element, target.actionName, target.actionLabel) &&\n actions.some((a) => a.name !== target.actionName && matchesActionIdentity(target.element, a.name, a.label));\n if (lookOf(target.element).connected && !movedToAnother) return target.element;\n if (target.wiringKind !== \"click\") return undefined;\n return findActionElements(target.container, target.actionName, target.actionLabel, { identityOnly: true })[0];\n}\n\n/**\n * The control a person sees for a target. A form is read through its\n * clickable that names the action (generated forms often submit through a\n * `type=\"button\"` Button), else its first submit-type control, else itself.\n */\nfunction controlToRead(el: MinimalElement, target: PendingTarget): MinimalElement {\n if (el.tagName.toLowerCase() !== \"form\") return el;\n for (const c of el.querySelectorAll<MinimalElement>('button, input[type=\"submit\"], input[type=\"button\"], [role=\"button\"]')) {\n if (matchesActionIdentity(c, target.actionName, target.actionLabel)) return c;\n }\n for (const submitter of el.querySelectorAll<MinimalElement>(\n 'button[type=\"submit\"], input[type=\"submit\"], button:not([type])'\n )) {\n return submitter;\n }\n return el;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Check implementations\n// ─────────────────────────────────────────────────────────────────────────────\n\ninterface CheckActionInput {\n /** Mount a fresh copy of the card for this action's walk (ggui#1652). */\n mount: () => Promise<WalkMount | undefined>;\n actionName: string;\n actionLabel: string;\n wiring: WiringDetection;\n probe: Probe;\n user: { click: (el: MinimalElement) => Promise<void> };\n /** ggui#1398: where a control whose press dispatched is recorded, for the pending phase. */\n pendingTargets?: PendingTarget[];\n /** Epoch ms after which the walk stops, once a press has left the first screen. */\n stopAt: number;\n /** Where the text of every screen the walk reaches is collected, for prop coverage (ggui#1652). */\n walkedTexts: string[];\n}\n\n/** When the walk stops, once a press has left the first screen (ggui#1652). */\nfunction walkStopAt(deadlineAt: number | undefined): number {\n const cap = Date.now() + WALK_ACTION_CAP_MS;\n return deadlineAt === undefined ? cap : Math.min(cap, deadlineAt - PENDING_PHASE_RESERVE_MS - WALK_DEADLINE_MARGIN_MS);\n}\n\ntype WiredKind = \"click\" | \"submit\" | \"change\" | \"keyboard-enter\";\n\n/** A control the walk may press, and the trigger it is pressed with. */\ninterface ActionControl extends WalkControl {\n readonly how: WiredKind;\n}\n\nasync function checkActionWiring(input: CheckActionInput): Promise<RenderCheckIssue | null> {\n const { actionName, actionLabel, wiring, probe, user } = input;\n\n const baseDiagnostics = {\n observedJsxElements: wiring.observedJsxElements,\n observedNativeProps: wiring.observedNativeProps,\n observedCustomProps: wiring.observedCustomProps,\n };\n\n // Source says the hook is destructured but never referenced anywhere → fail.\n if (wiring.kind === \"missing\") {\n return {\n check: \"action-wiring\",\n outcome: \"failed\",\n subject: actionName,\n reason:\n wiring.reason ??\n `Action '${actionName}' is declared in contract but useAction('${actionName}') is not wired to any UI element`,\n diagnostics: baseDiagnostics,\n };\n }\n\n // Source says wired via custom-component prop / non-deterministic trigger → unverified.\n if (wiring.kind === \"unverified\") {\n return {\n check: \"action-wiring\",\n outcome: \"unverified\",\n subject: actionName,\n reason:\n wiring.reason ??\n \"Source indicates non-click or non-native wiring; static probe did not verify execution deterministically.\",\n diagnostics: baseDiagnostics,\n };\n }\n\n // Source-detected deterministic wiring → walk the card's screens, pressing\n // the matching trigger, until one press dispatches the action (ggui#1652).\n const kind = wiring.kind;\n const walk = await walkToAction<ActionControl>({\n mount: input.mount,\n controls: (container) => actionControls(container, kind, actionName, actionLabel),\n press: async (control) => {\n const before = probe.getFireLog().length;\n try {\n await dispatchTrigger(control.element, control.how, user);\n } catch {\n return false;\n }\n await flushPromises();\n return probe\n .getFireLog()\n .slice(before)\n .some((e) => e.kind === \"action.fired\" && e.name === actionName);\n },\n describe: describeElement,\n stopAt: input.stopAt,\n maxPresses: WALK_MAX_PRESSES,\n });\n input.walkedTexts.push(...walk.screenTexts);\n\n if (walk.fired) {\n // ggui#1398: record the control for the pending phase; nothing is marked here.\n if (input.pendingTargets && walk.element && walk.container && (kind === \"click\" || kind === \"submit\")) {\n input.pendingTargets.push({\n actionName,\n actionLabel,\n wiringKind: kind,\n element: walk.element,\n container: walk.container,\n });\n }\n return null; // verified — no issue\n }\n\n // Capture what DID fire — useful diagnostic.\n const allFired = probe\n .getFireLog()\n .filter((e) => e.kind === \"action.fired\")\n .map((e) => e.name);\n const otherActionsFired = Array.from(new Set(allFired)).filter((n) => n !== actionName);\n const stoppedBy = walk.stoppedBy === \"dispatched\" ? \"explored\" : walk.stoppedBy;\n\n // The AST already confirmed the wiring exists in source. The walk\n // couldn't trigger it — most likely a conditional-render or\n // required-form-fill case. Be conservative: downgrade to unverified\n // rather than reporting a fake failure.\n return {\n check: \"action-wiring\",\n outcome: \"unverified\",\n subject: actionName,\n reason: `Source confirms ${kind} wiring exists for action '${actionName}', but synthetic ${kind} did not dispatch it. Likely cause: conditional rendering, required input/form fill, or a multi-step interaction the static probe cannot complete.`,\n ...(walk.presses === 0 && stoppedBy === \"explored\" ? { elementHint: `No ${kind}-eligible element found in DOM` } : {}),\n diagnostics: {\n ...baseDiagnostics,\n actionsFiredFromClicks: otherActionsFired,\n walk: {\n presses: walk.presses,\n screens: walk.screens,\n stoppedBy,\n namedControlSeen: walk.namedControlSeen,\n lastPressed: walk.lastPressed,\n },\n },\n };\n}\n\n// `checkWiredToolWiring` is retired — `useWiredTool` was removed; the\n// contract's `agentCapabilities.tools` is a catalog the AGENT invokes\n// (no component hook to verify). Cross-refs from `actionSpec[*].nextStep` and\n// `streamSpec[*].source.tool` ride through the action / stream check\n// arms in `runRenderCheck` instead.\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Selection identity (#601) — duplicate-label cells must carry their own id\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Find the id-like required string property in an action's payload\n * schema, or null. \"id-like\" = a required property whose name ends in\n * `id`/`Id`/`ID` and whose declared type is string — the shape the\n * matcher's booking/selection contracts carry (`bookSlot { slotId }`).\n */\nfunction idLikeRequiredStringField(schema: Record<string, unknown> | undefined): string | null {\n if (schema === undefined) return null;\n const properties = schema[\"properties\"];\n const required = schema[\"required\"];\n if (properties === null || typeof properties !== \"object\") return null;\n if (!Array.isArray(required)) return null;\n for (const [propName, propSchema] of Object.entries(properties as Record<string, unknown>)) {\n if (!/id$/i.test(propName)) continue;\n if (!required.includes(propName)) continue;\n const t =\n propSchema !== null && typeof propSchema === \"object\"\n ? (propSchema as Record<string, unknown>)[\"type\"]\n : undefined;\n if (t === \"string\") return propName;\n }\n return null;\n}\n\ninterface CheckSelectionIdentityInput {\n container: MinimalElement;\n probe: Probe;\n user: { click: (el: MinimalElement) => Promise<void> };\n actionName: string;\n idField: string;\n}\n\n/**\n * Click two clickables that share a visible label and require the two\n * fired payloads to DIFFER on the id-like field. Identical values mean\n * the component keys the action on the display value, not the element's\n * identity — the ggui#601 class (every \"09:00\" cell selecting together).\n *\n * Emits at most one `failed` issue; every ambiguous situation returns\n * null (covered by other checks or genuinely unjudgeable here).\n */\nasync function checkSelectionIdentity(\n input: CheckSelectionIdentityInput\n): Promise<RenderCheckIssue | null> {\n const { container, probe, user, actionName, idField } = input;\n\n const clickables = Array.from(\n container.querySelectorAll<MinimalElement>('button, [role=\"button\"]')\n );\n const byLabel = new Map<string, MinimalElement[]>();\n for (const el of clickables) {\n const label = (el.textContent ?? \"\").replace(/\\s+/g, \" \").trim();\n if (label.length === 0) continue;\n const group = byLabel.get(label);\n if (group) group.push(el);\n else byLabel.set(label, [el]);\n }\n\n for (const [label, group] of byLabel) {\n if (group.length < 2) continue;\n\n const payloadFor = async (el: MinimalElement): Promise<unknown | undefined> => {\n const before = probe.getFireLog().length;\n try {\n await user.click(el);\n } catch {\n return undefined;\n }\n await flushPromises();\n const events = probe\n .getFireLog()\n .slice(before)\n .filter((e): e is ActionFiredEvent => e.kind === \"action.fired\" && e.name === actionName);\n return events.length > 0 ? events[events.length - 1]!.payload : undefined;\n };\n\n const first = await payloadFor(group[0]!);\n const second = await payloadFor(group[1]!);\n // Either click firing nothing for this action = not this check's\n // question (wiring check owns \"does it fire\").\n if (first === undefined || second === undefined) continue;\n\n const idOf = (payload: unknown): string | undefined => {\n if (payload === null || typeof payload !== \"object\") return undefined;\n const v = (payload as Record<string, unknown>)[idField];\n return typeof v === \"string\" ? v : undefined;\n };\n const firstId = idOf(first);\n const secondId = idOf(second);\n // Payloads missing the required field = schema territory, not ours.\n if (firstId === undefined || secondId === undefined) continue;\n\n if (firstId === secondId) {\n return {\n check: \"selection-identity\",\n outcome: \"failed\",\n subject: actionName,\n reason: `Two clickable elements share the visible label '${label}', and clicking EACH fired '${actionName}' with the same ${idField} ('${firstId}') — the action payload is keyed on the display value, not the element's identity. Distinct cells must send their own ${idField} (the contract requires it), or selecting one \"${label}\" acts on every \"${label}\".`,\n elementHint: describeElement(group[0]!),\n };\n }\n // Distinct ids on the first duplicate group — identity keying holds.\n return null;\n }\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Trigger simulators — narrow set, deterministic only\n// ─────────────────────────────────────────────────────────────────────────────\n\nasync function dispatchTrigger(\n el: MinimalElement,\n kind: WiredKind,\n user: { click: (el: MinimalElement) => Promise<void> }\n): Promise<void> {\n switch (kind) {\n case \"click\":\n await user.click(el);\n return;\n case \"submit\": {\n // Find the enclosing form (or the element itself if it IS a form) and\n // dispatch a 'submit' event on it. happy-dom respects this.\n const form = closestForm(el);\n if (!form) return;\n const ev = new (globalThis as { Event: typeof Event }).Event(\"submit\", {\n bubbles: true,\n cancelable: true,\n });\n toEventDispatcher(form).dispatchEvent(ev);\n return;\n }\n case \"change\": {\n // Set a value before dispatching change — onChange handlers typically\n // read e.target.value, and a no-op change (same value) often won't\n // trigger downstream wiring. We only reach here when source-AST said\n // wiring is on a native element (input/select/textarea).\n setSyntheticValue(el);\n const ev = new (globalThis as { Event: typeof Event }).Event(\"change\", { bubbles: true });\n toEventDispatcher(el).dispatchEvent(ev);\n return;\n }\n case \"keyboard-enter\": {\n // Click first to focus, then dispatch an Enter keydown.\n try {\n await user.click(el);\n } catch {\n /* ignore */\n }\n const KeyboardEventCtor = (\n globalThis as { KeyboardEvent?: new (type: string, init: object) => Event }\n ).KeyboardEvent;\n if (KeyboardEventCtor) {\n const ev = new KeyboardEventCtor(\"keydown\", { key: \"Enter\", bubbles: true });\n toEventDispatcher(el).dispatchEvent(ev);\n }\n return;\n }\n }\n}\n\n/**\n * Mutate a native input/select/textarea to carry a non-empty, distinct value\n * just before firing 'change'. Without this, onChange handlers that branch on\n * e.target.value see whatever the component initialized (often empty / the\n * default), and the wiring under test never observes a real edit.\n *\n * Strategy:\n * <select> — pick the first option whose value differs from the current one\n * <input type=checkbox|radio> — flip checked\n * <input type=number|range> — increment by 1 (or set to min+1 / \"1\")\n * everything else (text/email/search/textarea/...) — append \"x\" if non-empty,\n * else set to \"test\"\n *\n * Best-effort: if any access throws (sealed mocks, unexpected shape), we leave\n * the element untouched and let the bare 'change' event fire.\n */\nfunction setSyntheticValue(el: MinimalElement): void {\n try {\n const tag = el.tagName.toLowerCase();\n const node = editableSurface(el);\n\n if (tag === \"select\") {\n const opts = node.options;\n if (opts && opts.length > 0) {\n const current = node.value ?? \"\";\n let pick = opts[0]!.value;\n for (let i = 0; i < opts.length; i++) {\n if (opts[i]!.value !== current) {\n pick = opts[i]!.value;\n break;\n }\n }\n node.value = pick;\n }\n return;\n }\n\n if (tag === \"input\") {\n const type = (node.type ?? \"text\").toLowerCase();\n if (type === \"checkbox\" || type === \"radio\") {\n node.checked = !node.checked;\n return;\n }\n if (type === \"number\" || type === \"range\") {\n const cur = Number(node.value ?? \"\");\n node.value = String(Number.isFinite(cur) ? cur + 1 : 1);\n return;\n }\n // text / email / search / url / password / tel / date / etc.\n node.value = node.value && node.value.length > 0 ? `${node.value}x` : \"test\";\n return;\n }\n\n if (tag === \"textarea\") {\n node.value = node.value && node.value.length > 0 ? `${node.value}x` : \"test\";\n return;\n }\n } catch {\n // Untouched element is fine — the bare change event still fires.\n }\n}\n\nfunction closestForm(el: MinimalElement): MinimalElement | null {\n // Climb via parentNode (happy-dom + native both expose this on Element).\n let cur: ParentLink | null = parentLink(el);\n while (cur) {\n if (cur.tagName && cur.tagName.toLowerCase() === \"form\") {\n return toMinimalElement(cur);\n }\n cur =\n typeof cur.parentNode === \"object\" && cur.parentNode !== null\n ? parentLink(cur.parentNode)\n : null;\n }\n return null;\n}\n\n/**\n * The controls an action's walk may press on the current screen, in the\n * order they are tried (ggui#1652). Click and Enter wiring: the controls\n * that name the action, then every other clickable, each pressed the way the\n * action is wired. Submit and change wiring: the eligible elements, pressed\n * with that trigger, then every clickable, pressed with a click, so the walk\n * can reach a screen where the eligible element appears.\n */\nfunction actionControls(container: MinimalElement, kind: WiredKind, name: string, label: string): ActionControl[] {\n const clickables = findActionElements(container, name, label);\n const named = (el: MinimalElement): boolean => matchesActionIdentity(el, name, label);\n if (kind === \"click\" || kind === \"keyboard-enter\") {\n return clickables.map((element) => ({ element, namesAction: named(element), how: kind }));\n }\n const eligible = Array.from(\n container.querySelectorAll<MinimalElement>(\n kind === \"submit\" ? 'form, button[type=\"submit\"], input[type=\"submit\"]' : \"select, input, textarea\"\n )\n );\n const seen = new Set(eligible);\n return [\n ...eligible.map((element) => ({ element, namesAction: named(element), how: kind })),\n ...clickables.filter((el) => !seen.has(el)).map((element) => ({ element, namesAction: named(element), how: \"click\" as const })),\n ];\n}\n\ninterface CheckPropCoverageInput {\n container: MinimalElement;\n /** The text of the screens the action walks reached (ggui#1652). */\n walkedTexts: readonly string[];\n propsSpec: PropsSpec;\n mockupProps: JsonObject;\n}\n\nfunction checkPropCoverage(input: CheckPropCoverageInput): RenderCheckIssue[] {\n const { container, walkedTexts, propsSpec, mockupProps } = input;\n const issues: RenderCheckIssue[] = [];\n const texts = [container.textContent ?? \"\", ...walkedTexts];\n\n for (const [propName, entry] of Object.entries(propsSpec.properties)) {\n if (!entry.required) continue;\n const value = mockupProps[propName];\n if (value === undefined || value === null) continue;\n\n // Pick a unique scalar marker we can search for in the DOM.\n const marker = pickScalarMarker(value);\n if (marker === null) continue;\n\n if (!texts.some((text) => text.includes(marker))) {\n // Name the walked screens only where a walk ran (a card with actions);\n // a card without one reads exactly as it did before the walk.\n const where = walkedTexts.length > 0 ? \", on the first screen or any screen the action walk reached\" : \"\";\n issues.push({\n check: \"prop-coverage\",\n outcome: \"unverified\",\n subject: propName,\n reason: `Required prop '${propName}' value (${JSON.stringify(marker).slice(0, 60)}) not visible in rendered DOM${where}`,\n });\n }\n }\n\n return issues;\n}\n\ninterface CheckStreamRerenderInput {\n container: MinimalElement;\n eventName: string;\n probe: Probe;\n React: typeof import(\"react\");\n}\n\nasync function checkStreamRerender(\n input: CheckStreamRerenderInput\n): Promise<RenderCheckIssue | null> {\n const { container, eventName, probe } = input;\n\n if (!probe.getRegistered().streams.includes(eventName)) {\n return {\n check: \"stream-rerender\",\n outcome: \"unverified\",\n subject: eventName,\n reason: `useStream('${eventName}') was never called — the stream event is declared in the contract but the component does not subscribe to it`,\n };\n }\n\n const before = container.textContent ?? \"\";\n const marker = `__probe_marker_${Date.now()}__`;\n // Emit a synthetic payload with a unique marker we can search for.\n // For payloads where the schema is unknown, push an object containing the marker\n // in multiple common field names so downstream consumers find it.\n const payload = { id: marker, text: marker, value: marker, message: marker, name: marker };\n\n await new Promise<void>((resolve) => {\n setTimeout(() => {\n probe.emitStream(eventName, payload);\n resolve();\n }, 0);\n });\n await flushPromises();\n\n const after = container.textContent ?? \"\";\n if (after === before) {\n return {\n check: \"stream-rerender\",\n outcome: \"unverified\",\n subject: eventName,\n reason: `useStream('${eventName}') is subscribed but emitting a payload did not change the DOM`,\n };\n }\n if (!after.includes(marker)) {\n // DOM changed but our marker isn't visible — possible the consumer renders\n // a derived value. Soft-pass.\n return null;\n }\n\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Helpers\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Whether `el` names the action itself: its text, aria-label or `data-action` carries the action's name or label. */\nfunction matchesActionIdentity(el: MinimalElement, name: string, label: string): boolean {\n const norm = (s: string) => s.toLowerCase().replace(/[\\s_-]+/g, \"\");\n const aria = (el.getAttribute(\"aria-label\") ?? \"\").toLowerCase();\n const txt = (el.textContent ?? \"\").toLowerCase();\n const dataAction = (el.getAttribute(\"data-action\") ?? \"\").toLowerCase();\n return (\n aria.includes(label.toLowerCase()) ||\n txt.includes(label.toLowerCase()) ||\n norm(aria).includes(norm(name)) ||\n norm(txt).includes(norm(name)) ||\n dataAction === name.toLowerCase() ||\n norm(txt).includes(norm(label))\n );\n}\n\nfunction findActionElements(\n container: MinimalElement,\n name: string,\n label: string,\n options: { readonly identityOnly?: boolean } = {}\n): MinimalElement[] {\n const candidates: MinimalElement[] = [];\n const seen = new Set<MinimalElement>();\n\n const allClickable = container.querySelectorAll<MinimalElement>(\n 'button, [role=\"button\"], input[type=\"submit\"], input[type=\"button\"], a[href]'\n );\n\n // Pass 1: text/aria-label/data-action match\n for (const el of allClickable) {\n if (matchesActionIdentity(el, name, label)) {\n if (!seen.has(el)) {\n seen.add(el);\n candidates.push(el);\n }\n }\n }\n\n // Pass 2: any clickable as fallback (we'll click them all). Skipped when\n // only the action's own control may answer (the pending phase's re-find).\n if (options.identityOnly) return candidates;\n for (const el of allClickable) {\n if (!seen.has(el)) {\n seen.add(el);\n candidates.push(el);\n }\n }\n\n return candidates;\n}\n\nfunction describeElement(el: MinimalElement): string {\n const tag = el.tagName.toLowerCase();\n const aria = el.getAttribute(\"aria-label\");\n const txt = (el.textContent ?? \"\").trim().slice(0, 30);\n if (aria) return `<${tag} aria-label=\"${aria}\">`;\n if (txt) return `<${tag}>${txt}</${tag}>`;\n return `<${tag}>`;\n}\n\nfunction pickScalarMarker(value: unknown): string | null {\n if (typeof value === \"string\" && value.length > 0) return value;\n if (typeof value === \"number\") return String(value);\n if (Array.isArray(value)) {\n for (const item of value) {\n const m = pickScalarMarker(item);\n if (m) return m;\n }\n return null;\n }\n if (value && typeof value === \"object\") {\n for (const v of Object.values(value)) {\n const m = pickScalarMarker(v);\n if (m) return m;\n }\n }\n return null;\n}\n\nfunction flushPromises(): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, 0));\n}\n","// packages/ui-gen/src/harness/check/runtime-render/prepare-mockup.ts\n//\n// Schema-first mockup props for runtime render evaluation.\n//\n// Priority:\n// 1. Existing fixture props (commit/contract `props` field) — highest fidelity\n// 2. PropEntry.example\n// 3. PropEntry.default\n// 4. Deterministic schema synthesis from JSON Schema\n// (default → example → enum[0] → typed placeholder)\n// 5. LLM fallback (deferred — v2)\n// 6. Empty fallback ({}) if all else fails\n//\n// Output is validated against the contract's `properties` shape — if a field\n// is required and ends up missing, we surface that as a synthesis warning\n// (the render check will likely fail downstream, but with a clearer signal).\n\nimport type {\n DataContract,\n JsonObject,\n JsonSchema,\n JsonValue,\n PropEntry,\n PropsSpec,\n} from \"@ggui-ai/protocol\";\n\nexport interface MockupPropsResult {\n /** The synthesized props object — pass directly into render(<Component {...props} />). */\n readonly props: JsonObject;\n /** How each field was sourced — useful for debugging eval failures. */\n readonly source: Readonly<Record<string, MockupSource>>;\n /** Synthesis warnings (missing required fields, unsupported schemas, etc.). */\n readonly warnings: readonly string[];\n}\n\nexport type MockupSource =\n | \"fixture\"\n | \"entry-example\"\n | \"entry-default\"\n | \"schema-default\"\n | \"schema-example\"\n | \"schema-enum\"\n | \"schema-synth\"\n | \"empty\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Public entry point\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface PrepareMockupInput {\n readonly contract: DataContract | undefined;\n /**\n * Pre-supplied fixture props (e.g., from a benchmark commit's `props` field).\n * Wins over schema synthesis when keys match.\n */\n readonly fixtureProps?: JsonObject;\n}\n\n/**\n * Synthesize a JsonObject of props matching the contract.propsSpec shape.\n *\n * Deterministic — no LLM call. Returns even if the contract is missing\n * (in which case `props` is just the fixtureProps or `{}`).\n */\nexport function prepareMockupProps(input: PrepareMockupInput): MockupPropsResult {\n const { contract, fixtureProps } = input;\n const propsSpec = contract?.propsSpec as PropsSpec | undefined;\n\n const props: JsonObject = {};\n const source: Record<string, MockupSource> = {};\n const warnings: string[] = [];\n\n if (!propsSpec || !propsSpec.properties) {\n // No props contract — mirror the fixture if present, else empty.\n if (fixtureProps) {\n Object.assign(props, fixtureProps);\n for (const k of Object.keys(fixtureProps)) source[k] = \"fixture\";\n }\n return { props, source, warnings };\n }\n\n for (const [key, entry] of Object.entries(propsSpec.properties)) {\n // Priority 1: fixture wins\n if (fixtureProps && Object.prototype.hasOwnProperty.call(fixtureProps, key)) {\n props[key] = fixtureProps[key];\n source[key] = \"fixture\";\n continue;\n }\n\n const synth = synthesizePropValue(entry, key, warnings);\n if (synth.kind === \"ok\") {\n props[key] = synth.value;\n source[key] = synth.source;\n } else if (entry.required) {\n warnings.push(`Required prop '${key}' could not be synthesized (${synth.reason})`);\n }\n // Optional props that fail synthesis are simply omitted.\n }\n\n return { props, source, warnings };\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Per-prop synthesis\n// ─────────────────────────────────────────────────────────────────────────────\n\ntype SynthOk = { kind: \"ok\"; value: JsonValue; source: MockupSource };\ntype SynthFail = { kind: \"fail\"; reason: string };\n\nfunction synthesizePropValue(\n entry: PropEntry,\n fieldName: string,\n warnings: string[],\n): SynthOk | SynthFail {\n // PropEntry-level wins over schema-level\n if (entry.example !== undefined) {\n return { kind: \"ok\", value: entry.example, source: \"entry-example\" };\n }\n if (entry.default !== undefined) {\n return { kind: \"ok\", value: entry.default, source: \"entry-default\" };\n }\n return synthesizeFromSchema(entry.schema, fieldName, warnings, 0);\n}\n\nconst MAX_DEPTH = 6;\n\nfunction synthesizeFromSchema(\n schema: JsonSchema | undefined,\n hint: string,\n warnings: string[],\n depth: number,\n /**\n * 1-based position when the value belongs to an array element (inherited\n * by the element's own fields). Every synthesized string inside an element\n * carries it, so two elements never share an id or a visible label — the\n * runtime probe's selection-identity rule (\"clicking each fired the action\n * with the same id\") is undecidable on identical items and read a correct\n * component as broken (2026-09-10, the 1.6 hello: both quick replies were\n * `Sample Id` / `Sample Label`).\n */\n ordinal?: number,\n): SynthOk | SynthFail {\n if (!schema) return { kind: \"fail\", reason: \"no schema\" };\n if (depth > MAX_DEPTH) return { kind: \"fail\", reason: \"schema too deep\" };\n\n // Schema-level overrides\n if (schema.default !== undefined) {\n return { kind: \"ok\", value: schema.default, source: \"schema-default\" };\n }\n if (schema.example !== undefined) {\n return { kind: \"ok\", value: schema.example, source: \"schema-example\" };\n }\n if (schema.enum && schema.enum.length > 0) {\n return { kind: \"ok\", value: schema.enum[0]!, source: \"schema-enum\" };\n }\n\n // Union schemas — try first branch only\n if (schema.oneOf && schema.oneOf.length > 0) {\n return synthesizeFromSchema(schema.oneOf[0], hint, warnings, depth + 1, ordinal);\n }\n if (schema.anyOf && schema.anyOf.length > 0) {\n return synthesizeFromSchema(schema.anyOf[0], hint, warnings, depth + 1, ordinal);\n }\n\n // Draft-07 type array (`['string','null']` — the canonical nullable\n // form since draft-2026-08-19): synthesize from the first non-null\n // member ('null' only when it is the sole member). The depth guard\n // above bounds the recursion.\n if (Array.isArray(schema.type)) {\n const primary = schema.type.find((t) => t !== \"null\") ?? \"null\";\n return synthesizeFromSchema({ ...schema, type: primary }, hint, warnings, depth + 1, ordinal);\n }\n\n switch (schema.type) {\n case \"string\": {\n // Format-aware placeholder\n switch (schema.format) {\n case \"date\":\n case \"date-time\":\n return { kind: \"ok\", value: \"2026-04-13T12:00:00Z\", source: \"schema-synth\" };\n case \"email\":\n return { kind: \"ok\", value: \"user@example.com\", source: \"schema-synth\" };\n case \"uri\":\n case \"url\":\n return { kind: \"ok\", value: \"https://example.com\", source: \"schema-synth\" };\n case \"uuid\":\n return { kind: \"ok\", value: \"00000000-0000-0000-0000-000000000000\", source: \"schema-synth\" };\n default: {\n // Use field name as a hint so it appears in DOM and prop-coverage check sees it.\n // Capitalize first letter for natural-looking placeholder.\n const cap = hint.charAt(0).toUpperCase() + hint.slice(1);\n // Inside an array element every string is distinct per element.\n const value = ordinal === undefined ? `Sample ${cap}` : `Sample ${cap} ${ordinal}`;\n return { kind: \"ok\", value, source: \"schema-synth\" };\n }\n }\n }\n\n case \"integer\":\n case \"number\": {\n const min = typeof schema.minimum === \"number\" ? schema.minimum : 1;\n const max = typeof schema.maximum === \"number\" ? schema.maximum : 100;\n const value = Math.min(max, Math.max(min, 42));\n return { kind: \"ok\", value, source: \"schema-synth\" };\n }\n\n case \"boolean\":\n return { kind: \"ok\", value: true, source: \"schema-synth\" };\n\n case \"null\":\n return { kind: \"ok\", value: null, source: \"schema-synth\" };\n\n case \"array\": {\n if (!schema.items) {\n return { kind: \"ok\", value: [], source: \"schema-synth\" };\n }\n // Synthesize 2 items so list-rendering checks (length > 0) pass.\n const items: JsonValue[] = [];\n for (let i = 0; i < 2; i++) {\n const itemHint = `${hint}Item${i + 1}`;\n const itemSynth = synthesizeFromSchema(schema.items, itemHint, warnings, depth + 1, i + 1);\n if (itemSynth.kind === \"ok\") {\n // Inject an `id` for list-key purposes if the item is an object lacking one.\n if (\n itemSynth.value !== null &&\n typeof itemSynth.value === \"object\" &&\n !Array.isArray(itemSynth.value) &&\n !(\"id\" in itemSynth.value)\n ) {\n (itemSynth.value as JsonObject).id = `${hint}-${i + 1}`;\n }\n items.push(itemSynth.value);\n }\n }\n return { kind: \"ok\", value: items, source: \"schema-synth\" };\n }\n\n case \"object\": {\n const obj: JsonObject = {};\n const propsMap = schema.properties ?? {};\n const required = new Set(schema.required ?? []);\n for (const [k, sub] of Object.entries(propsMap)) {\n const subSynth = synthesizeFromSchema(sub, k, warnings, depth + 1, ordinal);\n if (subSynth.kind === \"ok\") {\n obj[k] = subSynth.value;\n } else if (required.has(k)) {\n warnings.push(\n `Required object field '${hint}.${k}' could not be synthesized (${subSynth.reason})`,\n );\n }\n }\n return { kind: \"ok\", value: obj, source: \"schema-synth\" };\n }\n\n default:\n return { kind: \"fail\", reason: `unsupported schema type: ${schema.type ?? \"unknown\"}` };\n }\n}\n","// packages/ui-gen/src/harness/check/runtime-render/adapter.ts\n//\n// Adapter: convert RenderCheckResult → EvalIssue[] so runtime-render\n// integrates with the rest of the eval pipeline (axisChecks, tierChecks,\n// llmEvaluator). Fits the RuntimeRenderCheck interface from harness/types.ts.\n\nimport type { EvalIssue } from \"../../../evaluation/types-public.js\";\nimport type { RuntimeRenderCheck } from \"../../types-public.js\";\nimport {\n RENDER_CHECK_KINDS,\n runRenderCheck,\n type RenderCheckIssue,\n type RenderCheckKind,\n type RunRenderCheckOptions,\n} from \"./render-check.js\";\nimport { resolveRenderCheckHostBounds } from \"./render-check-host.js\";\nimport { prepareMockupProps } from \"./prepare-mockup.js\";\n\n/**\n * How one runtime-render check instance runs its isolated worker\n * (ggui#1380). A serving deployment sets the probe's wall-clock bound,\n * worker heap and concurrency here; every field omitted is the evaluation\n * lane's behaviour — the host's default bounds and no concurrency cap.\n */\nexport interface RuntimeRenderProbeConfig {\n /** Wall-clock bound of one isolated check, ms. Default: the host's (30 000). */\n readonly timeoutMs?: number;\n /** V8 heap cap of the worker, MB. Default: the host's (512). */\n readonly heapMb?: number;\n /**\n * Live workers this instance may have at once. The (K+1)th check waits\n * in FIFO order and spawns only when a slot frees; a check that throws\n * releases its slot. Default: unbounded. Must be a positive integer.\n */\n readonly maxConcurrent?: number;\n}\n\n/**\n * K-slot FIFO limiter. `undefined` slots = no limiter (the task runs at\n * once). A slot is released in `finally`, so a rejected task never holds\n * one.\n */\nfunction createSlotLimiter(\n maxConcurrent: number | undefined\n): <T>(task: (waitedMs: number) => Promise<T>) => Promise<T> {\n if (maxConcurrent === undefined) return (task) => task(0);\n if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) {\n throw new RangeError(\n `createRuntimeRenderCheck: maxConcurrent must be a positive integer, got ${maxConcurrent}`\n );\n }\n let active = 0;\n const waiting: Array<() => void> = [];\n /** Resolves with the time the caller actually WAITED for a slot: 0 when one was free. */\n const acquire = (): Promise<number> => {\n if (active < maxConcurrent) {\n active += 1;\n return Promise.resolve(0);\n }\n const enqueuedAt = Date.now();\n return new Promise<number>((resolve) => {\n waiting.push(() => {\n active += 1;\n resolve(Date.now() - enqueuedAt);\n });\n });\n };\n const release = (): void => {\n active -= 1;\n const next = waiting.shift();\n if (next !== undefined) next();\n };\n return async (task) => {\n const waitedMs = await acquire();\n try {\n return await task(waitedMs);\n } finally {\n release();\n }\n };\n}\n\n/** `{ queuedMs }` when the check actually waited for a slot, `{}` when one was free. */\nfunction queuedField(queuedMs: number): { readonly queuedMs?: number } {\n return queuedMs > 0 ? { queuedMs } : {};\n}\n\n/** The `runRenderCheck` options a config maps to — `undefined` when no bound is set. */\nfunction toRenderCheckOptions(config: RuntimeRenderProbeConfig): RunRenderCheckOptions | undefined {\n if (config.timeoutMs === undefined && config.heapMb === undefined) return undefined;\n return {\n bounds: {\n ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n ...(config.heapMb !== undefined ? { heapMb: config.heapMb } : {}),\n },\n };\n}\n\n/**\n * Build a runtime-render check instance. One FIFO limiter per instance;\n * the bounds reach `runRenderCheck` on every run. `createRuntimeRenderCheck()`\n * with no config is {@link DEFAULT_RUNTIME_RENDER_CHECK}'s behaviour.\n */\nexport function createRuntimeRenderCheck(\n config: RuntimeRenderProbeConfig = {}\n): RuntimeRenderCheck {\n const limit = createSlotLimiter(config.maxConcurrent);\n const options = toRenderCheckOptions(config);\n // A bad bound is refused here, at construction, never at the first probe.\n if (options !== undefined) resolveRenderCheckHostBounds(options.bounds);\n return {\n id: \"runtime-render\",\n run: async (input) => {\n const { sourceCode, compiledCode, contract, fixtureProps } = input;\n\n // Nothing to render / no contract surface to verify — the probe has\n // no subject, which is different from the probe failing to run.\n if (compiledCode === null) {\n return { status: \"not-applicable\", issues: [], reason: \"no compiled code\" };\n }\n if (!contract) {\n return { status: \"not-applicable\", issues: [], reason: \"no contract surface\" };\n }\n\n const mockup = prepareMockupProps({ contract, fixtureProps });\n\n // ggui#1380 — the adapter's own clock around the check: every status\n // that reached the check (`ran`, `timed-out`, `infra-skipped`) reports\n // how long it took, so a reader of the probe meta can tell a 2 s probe\n // from a 30 s one on the same status. The two not-applicable returns\n // above carry nothing: nothing ran.\n // The clock starts when the slot is acquired, so `elapsedMs` is the\n // check's own wall-clock; the time the check actually WAITED for a slot\n // is `queuedMs` (present only when it queued) — a latency reader needs\n // the two apart exactly when a serving deployment queues more probes\n // than it has slots. A check that found a slot free carries no key.\n let queuedMs = 0;\n let t0 = Date.now();\n let result;\n try {\n result = await limit((waitedMs) => {\n queuedMs = waitedMs;\n t0 = Date.now();\n return runRenderCheck(\n {\n sourceCode,\n mockupProps: mockup.props,\n contract,\n },\n options\n );\n });\n } catch (e) {\n // Triad audit (2026-04-27): every error that escapes `runRenderCheck`\n // is an INFRA problem — happy-dom import failure, ESM/CJS interop\n // (`Dynamic require of \"events\"`), bundler name collision (`Window2\n // is not a constructor`), missing `@testing-library/react`, etc.\n // Component-level failures are caught and emitted as `RenderCheckIssue`\n // entries from inside `runRenderCheck`; they don't propagate out.\n //\n // An infra failure must never become an eval issue (the coding\n // agent can't fix the environment — pre-2026-04-27 that phantom\n // issue dragged every score-below-80 cell's eval-fix loop), but it\n // must also never be silent to scoring: ggui#403 found the bench\n // reporting `probe_pass 3/3` on cells where this branch fired on\n // every invocation. The `infra-skipped` status is the No-Silent-\n // Block channel — consumers surface it as did-not-run, never pass.\n const message = e instanceof Error ? e.message : String(e);\n console.warn(`[runtime-render] probe skipped — infra failure: ${message}`);\n return { status: \"infra-skipped\", issues: [], reason: message, elapsedMs: Date.now() - t0, ...queuedField(queuedMs) };\n }\n\n const hostLoad = result.stats.hostLoad;\n const load = hostLoad !== undefined ? { hostLoad } : {};\n\n // ggui#1299: a check that ran out of wall-clock time is not a verdict on\n // the component. It becomes the `timed-out` status (did-not-run, never a\n // pass, never a crash), never an eval issue — so the coding agent is never\n // told to fix a crash that did not happen.\n if (result.incomplete !== undefined) {\n const { elapsedMs, boundMs } = result.incomplete;\n const loadNote =\n hostLoad !== undefined\n ? `; host load ${hostLoad.start.toFixed(1)} → ${hostLoad.end.toFixed(1)} on ${hostLoad.cores} CPUs`\n : \"\";\n const reason = `render check did not finish within ${boundMs} ms (stopped at ${elapsedMs} ms)${loadNote}`;\n console.warn(`[runtime-render] probe timed out — ${reason}`);\n // One clock for every status that reached the worker: the adapter's\n // wall-clock around the check. The worker's own reading survives in\n // `reason` (\"stopped at N ms\").\n return { status: \"timed-out\", issues: [], reason, elapsedMs: Date.now() - t0, ...queuedField(queuedMs), ...load };\n }\n\n return {\n status: \"ran\",\n issues: result.issues.map(toEvalIssue).filter((x): x is EvalIssue => x !== null),\n elapsedMs: Date.now() - t0,\n ...queuedField(queuedMs),\n renderMs: result.stats.renderMs,\n ...load,\n // ggui#1398: report-only — carried to the probe's meta for the bench, never an issue.\n ...(result.stats.pendingAffordance !== undefined ? { pendingAffordance: result.stats.pendingAffordance } : {}),\n };\n },\n };\n}\n\n/** The evaluation lane's instance: the host's default bounds, no concurrency cap. */\nexport const DEFAULT_RUNTIME_RENDER_CHECK: RuntimeRenderCheck = createRuntimeRenderCheck();\n\n/**\n * Map a runtime-render crash reason to a class-specific fix string.\n *\n * The default fix (\"add null guards on optional props…\") is too generic\n * for the LLM to act on. Observed crash classes from n=3 benches:\n * - \"Too many re-renders\" / \"Maximum update depth exceeded\" — setState\n * during render, or in a useEffect with missing/unstable deps. The\n * diagnosis MUST point at useEffect/useState patterns, not null guards.\n * - \"Cannot access 'X' before initialization\" — TDZ, usually from\n * referencing a `let`/`const` in a useEffect deps array (or default\n * value) before its declaration line. Fix is reorder, not null-guard.\n * - \"X is not defined\" — typo or missing destructure. Fix is grep + fix\n * the symbol, not null-guard.\n * - \"X is not iterable\" / \"Cannot read property … of undefined/null\" —\n * defaulting/optional-chaining; the original generic fix applies.\n */\n/**\n * Public probe-classification surface for the in-loop runtime probe.\n *\n * Two helpers:\n * - `classifyRenderCrashFix(reason)` returns the class-specific fix\n * string. Exported so the eval-round runner can build a\n * `[runtime]` violation for the coding agent at exit-decision time.\n * - `isRecoverableRenderCrash(reason)` is a boolean variant — true\n * when `classifyRenderCrashFix` returns a CLASS-SPECIFIC string\n * (i.e., one of: re-render loop, TDZ, undeclared symbol, non-array\n * iteration, null/undefined access). False when the reason falls\n * through to the generic fallback.\n *\n * \"Recoverable\" is harness terminology, not a runtime certainty: it\n * means the LLM has a reasonable chance of fixing the crash given the\n * class-specific advice. The generic fallback (\"add null guards on\n * optional props…\") is too vague to recover from in one turn.\n */\nconst CLASS_SPECIFIC_PATTERNS: ReadonlyArray<RegExp> = [\n /too many re-renders/i,\n /maximum update depth/i,\n /infinite render loop/i,\n /cannot access\\s+'[^']+'\\s+before initialization/i,\n /\\b\\w+ is not defined\\b/i,\n /is not iterable/i,\n /symbol\\(symbol\\.iterator\\)/i,\n /cannot read propert(?:y|ies) of (?:undefined|null)/i,\n /undefined is not/i,\n /null is not/i,\n];\n\nexport function isRecoverableRenderCrash(reason: string): boolean {\n return CLASS_SPECIFIC_PATTERNS.some((rx) => rx.test(reason));\n}\n\nexport function classifyRenderCrashFix(reason: string): string {\n const r = reason.toLowerCase();\n if (\n r.includes(\"too many re-renders\") ||\n r.includes(\"maximum update depth\") ||\n r.includes(\"infinite render loop\")\n ) {\n return (\n \"Find the setState/dispatch call in your render body or useEffect. \" +\n \"Either: (a) move the setState into an event handler, (b) add a proper \" +\n \"useEffect dependency array so it doesn't fire every render, or (c) \" +\n \"guard the setState with an equality check `if (next !== current) setX(next)`. \" +\n \"Do NOT call setState in render or useEffect-without-deps.\"\n );\n }\n if (r.includes(\"cannot access\") && r.includes(\"before initialization\")) {\n const symMatch = reason.match(/'([^']+)'/);\n const sym = symMatch ? symMatch[1] : \"the variable\";\n return (\n `Temporal-dead-zone error on \\`${sym}\\`. You're referencing ${sym} ` +\n `(likely in a useEffect dependency array or a default value) BEFORE ` +\n `its \\`const\\`/\\`let\\` declaration. Move the declaration of ${sym} ` +\n `to the top of the component body, before any useEffect/useMemo/` +\n `useCallback that reads it.`\n );\n }\n if (r.includes(\"is not defined\")) {\n const symMatch = reason.match(/(\\w+) is not defined/);\n const sym = symMatch ? symMatch[1] : \"the symbol\";\n return (\n `ReferenceError: \\`${sym}\\` is used in JSX/expression but never ` +\n `declared. Either: (a) add a \\`const ${sym} = ...\\` declaration in ` +\n `the component body, (b) destructure it from props/state, or (c) ` +\n `fix the typo if you meant a similarly-named local.`\n );\n }\n if (r.includes(\"is not iterable\") || r.includes(\"symbol(symbol.iterator)\")) {\n return (\n \"Render iterated over a non-array. Find the `for...of`, `[...spread]`, \" +\n \"or `.map`/`.filter`/`.reduce` call that crashed and either: (a) \" +\n \"default the value to `[]` (`const items = props.items ?? []`), or \" +\n \"(b) check it's an array before iterating (`Array.isArray(x) && ...`).\"\n );\n }\n if (r.includes(\"cannot read\") || r.includes(\"undefined is not\") || r.includes(\"null is not\")) {\n return (\n \"Null/undefined access. Add optional chaining (`obj?.field`) and \" +\n \"default values for optional props/state before reading nested fields. \" +\n \"Check your destructure patterns — destructuring undefined throws.\"\n );\n }\n // Fallback for unrecognized crash classes — keep the original advice.\n return (\n \"Add null guards on optional props, handle empty arrays/strings, \" +\n \"and verify all hook outputs before destructuring.\"\n );\n}\n\n/** The prefix every probe issue's subcategory carries: `runtime:<check>[:<subject>]`. */\nconst RUNTIME_SUBCATEGORY_PREFIX = \"runtime:\";\n\n/**\n * The check a probe issue's subcategory names (ggui#1380) — the inverse of\n * the `runtime:<check>[:<subject>]` form {@link toEvalIssue} writes, so a\n * round can list WHICH checks failed from the issues alone. `undefined` for\n * anything that is not a probe subcategory naming a member of\n * {@link RENDER_CHECK_KINDS} (an axis check's subcategory, a did-not-run\n * code such as `runtime:probe-timeout`, a bare check name).\n */\nexport function parseRuntimeSubcategory(subcategory: string): RenderCheckKind | undefined {\n if (!subcategory.startsWith(RUNTIME_SUBCATEGORY_PREFIX)) return undefined;\n const rest = subcategory.slice(RUNTIME_SUBCATEGORY_PREFIX.length);\n const separator = rest.indexOf(\":\");\n const check = separator === -1 ? rest : rest.slice(0, separator);\n return RENDER_CHECK_KINDS.find((kind) => kind === check);\n}\n\n/**\n * One probe finding → the eval issue the loop feeds back and the metadata\n * counts. Exported for the pin that every switch case below is a member of\n * {@link RENDER_CHECK_KINDS} and round-trips through\n * {@link parseRuntimeSubcategory}.\n */\nexport function toEvalIssue(issue: RenderCheckIssue): EvalIssue | null {\n // verified → no issue (silent pass)\n if (issue.outcome === \"verified\" || issue.outcome === \"skipped\") return null;\n\n // unverified → warn (non-blocking — wiring may exist, just not deterministically simulable)\n // failed → fail (blocker — strong evidence the wiring should work but didn't)\n const result: \"fail\" | \"warn\" = issue.outcome === \"failed\" ? \"fail\" : \"warn\";\n\n const subject = issue.subject ?? \"\";\n const subcategory = subject ? `runtime:${issue.check}:${subject}` : `runtime:${issue.check}`;\n const elementHint = issue.elementHint ? ` (element: ${issue.elementHint})` : \"\";\n\n // Build a diagnostic suffix that gives the coding agent observable context.\n const diag = issue.diagnostics;\n const diagParts: string[] = [];\n if (diag?.observedNativeProps?.length) {\n diagParts.push(`native props: ${diag.observedNativeProps.join(\", \")}`);\n }\n if (diag?.observedCustomProps?.length) {\n diagParts.push(`custom props: ${diag.observedCustomProps.join(\", \")}`);\n }\n if (diag?.observedJsxElements?.length) {\n diagParts.push(`elements: ${diag.observedJsxElements.slice(0, 4).join(\", \")}`);\n }\n if (diag?.actionsFiredFromClicks?.length) {\n diagParts.push(`other actions fired from clicks: ${diag.actionsFiredFromClicks.join(\", \")}`);\n }\n if (diag?.inputPriming) {\n // ggui#1187: an input-gated action that \"did not dispatch\" reads\n // differently beside \"primed 0\" / a priming error than beside \"primed 1\".\n diagParts.push(\n \"primed\" in diag.inputPriming\n ? `input priming: ${diag.inputPriming.primed} control(s) filled before the click`\n : `input priming failed: ${diag.inputPriming.error}`\n );\n }\n if (diag?.walk) {\n // ggui#1652: how far the walk over the card's screens got, so a\n // multi-step card reads differently from a control that never rendered.\n const w = diag.walk;\n const stopped = {\n explored: \"every reachable control pressed\",\n \"press-cap\": \"stopped at the press cap\",\n deadline: \"stopped at the time budget\",\n \"no-mount\": \"the card could not be mounted for the walk\",\n }[w.stoppedBy];\n const named = w.namedControlSeen\n ? \"a control naming the action rendered, but pressing it did not dispatch the action\"\n : \"no screen rendered a control naming the action\";\n const last = w.lastPressed.length ? `; last pressed: ${w.lastPressed.join(\", \")}` : \"\";\n diagParts.push(`walk: ${w.presses} press(es) across ${w.screens} screen(s), ${stopped}; ${named}${last}`);\n }\n const diagSuffix = diagParts.length ? ` [observed: ${diagParts.join(\"; \")}]` : \"\";\n\n switch (issue.check) {\n case \"render-no-throw\":\n return {\n tier: 0,\n result,\n category: \"crash\",\n subcategory,\n severity: \"critical\",\n description: `Component crashed at runtime: ${issue.reason}`,\n fix: classifyRenderCrashFix(issue.reason),\n };\n\n case \"optional-props-omitted\":\n // Same crash class as render-no-throw, surfaced by the second\n // render pass with optional props stripped (ggui#528): the wire\n // gate only requires `required: true` props, so a legitimate\n // render may omit these and the component must survive it.\n return {\n tier: 0,\n result,\n category: \"crash\",\n subcategory,\n severity: \"critical\",\n description: `Component crashed when optional props were omitted: ${issue.reason}`,\n fix:\n `Guard every optional prop before member access (props.${subject.split(\",\")[0]?.trim() ?? \"x\"}?.map(...), ` +\n `a default via destructuring, or an early empty-state return). Optional props (no \\`required: true\\` in the contract) ` +\n `may be absent at runtime even though the harness fills them.`,\n };\n\n case \"action-wiring\": {\n const fix =\n issue.outcome === \"unverified\"\n ? `Source shows the action callback flowing into a non-native or custom-component prop. If wiring is intentional (e.g., Dropdown.onChange, drag-drop), this warn is informational — manual/browser verification is required to confirm. Otherwise wire to a native onClick={() => ${subject}(payload)} on <button> or design-system <Button>.`\n : `Wire ${subject}() to a native event prop. Common fix: <Button onClick={() => ${subject}(payload)}>Label</Button>. Source-AST analysis didn't find this wiring in your JSX.`;\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n severity: result === \"fail\" ? \"critical\" : \"major\",\n description: `${issue.reason}${elementHint}${diagSuffix}`,\n fix,\n };\n }\n\n case \"selection-identity\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n severity: \"critical\",\n description: `${issue.reason}${elementHint}${diagSuffix}`,\n fix:\n `Key the action payload (and any selection state) on the item's ID from the data, never on its display text. ` +\n `Common fix: map over items and pass the item's id into the handler — onClick={() => ${subject}({ ...payload, id: item.id })} — ` +\n `and store selection as the id (setSelected(item.id)), not the label.`,\n };\n\n case \"prop-sensitivity\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n severity: \"critical\",\n description: `${issue.reason}${diagSuffix}`,\n fix:\n `Derive the display AND any logic from props.${subject} — render {props.${subject}} and branch on the prop's value, ` +\n `never on the literal value the request happened to mention (e.g. props.${subject} ?? 'January' followed by ` +\n `January-special-cased logic bakes the request into the component). The contract delivers the value; trust it.`,\n };\n\n case \"prop-coverage\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n description: `${issue.reason}${diagSuffix}`,\n fix: `Render props.${subject} somewhere in the JSX (e.g., <Text>{props.${subject}}</Text>). If you display a derived/formatted version, this warn may be a false positive.`,\n };\n\n case \"stream-rerender\":\n return {\n tier: 0,\n result,\n category: \"contract\",\n subcategory,\n description: `${issue.reason}${diagSuffix}`,\n fix: `Subscribe with const ${subject} = useStream('${subject}'); render ${subject}.latest && <Text>{${subject}.latest.field}</Text> or .all.map(...).`,\n };\n }\n}\n","// packages/ui-gen/src/harness/check/runtime-render/index.ts\n//\n// Public surface for runtime render evaluation.\n//\n// runRenderCheck() takes a compiled component + mockup props + contract,\n// renders it in happy-dom with a probe-backed WireConfig, and verifies:\n// - it renders without throw (block)\n// - declared actions fire when the bound UI is clicked (block)\n// - declared props appear in the DOM (warn)\n// - declared stream events update the DOM when emitted (warn)\n\nimport { installProductionActShim } from \"./production-act-shim.js\";\nimport type { RenderCheckHostBounds } from \"./render-check-host.js\";\n\nexport {\n RENDER_CHECK_KINDS,\n runRenderCheck,\n type RenderCheckKind,\n type RenderCheckResult,\n type RenderCheckIssue,\n} from \"./render-check.js\";\nexport { createProbe, createProbeWireConfig, type Probe } from \"./probe.js\";\nexport { prepareMockupProps, type MockupPropsResult } from \"./prepare-mockup.js\";\nexport {\n DEFAULT_RUNTIME_RENDER_CHECK,\n classifyRenderCrashFix,\n createRuntimeRenderCheck,\n isRecoverableRenderCrash,\n parseRuntimeSubcategory,\n type RuntimeRenderProbeConfig,\n} from \"./adapter.js\";\nexport type { RenderCheckHostBounds, RenderCheckHostOptions } from \"./render-check-host.js\";\n\n/**\n * Pre-warm the runtime-render probe's runtime dependencies so the first\n * actual probe call hits a warm Node module cache.\n *\n * The probe lazily loads `happy-dom`, `@testing-library/react`,\n * `@testing-library/user-event`, and `@ggui-ai/wire` on first invocation\n * — total cold cost ~700-1500ms. Bench runners can call this once at\n * startup to amortize that cost; subsequent per-cell probe calls fall\n * to ~50-200ms.\n *\n * Resolves these specifiers from THIS module's filesystem location, so\n * Node walks up from `packages/ui-gen/dist/harness/check/runtime-render/`\n * to find them in `packages/ui-gen/node_modules/...`. Bench callers\n * cannot pre-import them directly — they aren't in the bench package's\n * own `node_modules`.\n *\n * Fire-and-forget. If a dep is missing the per-cell probe will surface\n * the error on first use; pre-warm just no-ops on import failure.\n *\n * Returns the wall-clock spent loading.\n */\nexport async function warmupRuntimeRenderProbe(): Promise<{\n ms: number;\n loaded: number;\n missing: number;\n}> {\n const start = Date.now();\n let loaded = 0;\n let missing = 0;\n const tryLoad = async (specifier: string) => {\n try {\n await import(specifier);\n loaded += 1;\n } catch {\n missing += 1;\n }\n };\n // Must run before RTL's first import in this process — hosts that\n // call this warmup at process start (server-side blueprint\n // validation) land RTL in the module cache, with its act snapshot\n // taken, here — long before the first real probe call. See\n // production-act-shim.ts's docstring for why.\n installProductionActShim();\n await Promise.all([\n tryLoad(\"happy-dom\"),\n tryLoad(\"@testing-library/react\"),\n tryLoad(\"@testing-library/user-event\"),\n tryLoad(\"@ggui-ai/wire\"),\n ]);\n return { ms: Date.now() - start, loaded, missing };\n}\n\n/**\n * The component the boot warm renders: a constant element, an empty\n * contract — nothing to click, nothing to cover, one compile and one\n * render in the worker.\n */\nconst WARMUP_COMPONENT = \"export default function Warmup() { return <div>warm</div>; }\";\n\n/**\n * Warm the PROCESS that runs every probe (ggui#1380): spawn one real check\n * worker on a trivial component through the same host every probe uses.\n * Afterwards the node binary, the worker's module tree and esbuild's\n * service have all run once on this machine (OS page cache warm), and the\n * result says whether that process can run a check at all — which\n * `warmupRuntimeRenderProbe` (an import in THIS process) cannot tell.\n *\n * `bounds` are the subprocess bounds for the one run; a serving deployment\n * passes the same bounds it will probe with. Never throws: a worker that\n * cannot run is `{ ok: false, reason }`, so a boot sequence can log it and\n * decide, instead of dying in a fire-and-forget.\n */\nexport async function warmupRuntimeRenderWorker(\n bounds?: Partial<RenderCheckHostBounds>\n): Promise<{ ok: true; ms: number } | { ok: false; ms: number; reason: string }> {\n const start = Date.now();\n try {\n // Lazy: the host pulls `@ggui-ai/sandbox` (spawn machinery); keep it off\n // the import graph of everything that only needs the in-process check.\n const { runRenderCheckViaWorker } = await import(\"./render-check-host.js\");\n const result = await runRenderCheckViaWorker(\n { sourceCode: WARMUP_COMPONENT, mockupProps: {}, contract: {} },\n bounds !== undefined ? { bounds } : {}\n );\n const ms = Date.now() - start;\n if (result.incomplete !== undefined) {\n return {\n ok: false,\n ms,\n reason: `the warm-up check did not finish within ${result.incomplete.boundMs} ms (stopped at ${result.incomplete.elapsedMs} ms)`,\n };\n }\n const blocking = result.issues.find(\n (i) => i.outcome === \"failed\" || i.outcome === \"unverified\"\n );\n if (blocking !== undefined) {\n return { ok: false, ms, reason: `${blocking.check} ${blocking.outcome}: ${blocking.reason}` };\n }\n return { ok: true, ms };\n } catch (err) {\n // The host itself never throws for a worker fault; what reaches here is\n // the spawn layer refusing to run at all (an invalid bound, no binary).\n return {\n ok: false,\n ms: Date.now() - start,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n"]}
|