@ggui-ai/ui-gen 0.22.0 → 0.23.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.
Files changed (68) hide show
  1. package/dist/adapters/generation-dispatch.d.ts +1 -1
  2. package/dist/adapters/generation-dispatch.js +55 -17
  3. package/dist/adapters/generation-dispatch.js.map +1 -1
  4. package/dist/adapters/index.js +1 -1
  5. package/dist/adapters/index.js.map +1 -1
  6. package/dist/advanced/index.d.ts +3 -3
  7. package/dist/advanced/index.js +66 -18
  8. package/dist/advanced/index.js.map +1 -1
  9. package/dist/blueprint-validator.js +37 -7
  10. package/dist/blueprint-validator.js.map +1 -1
  11. package/dist/boilerplate.js +1 -0
  12. package/dist/boilerplate.js.map +1 -1
  13. package/dist/check/index.d.ts +1 -1
  14. package/dist/check/index.js.map +1 -1
  15. package/dist/{create-ui-generator-BEkzEtNz.d.ts → create-ui-generator-D0kbWwln.d.ts} +1 -1
  16. package/dist/{dispatch-DJNpQ7DI.d.ts → dispatch-wxaIMwZt.d.ts} +1 -1
  17. package/dist/evaluation/axis-checks/index.d.ts +3 -3
  18. package/dist/evaluation/axis-checks/index.js +19 -4
  19. package/dist/evaluation/axis-checks/index.js.map +1 -1
  20. package/dist/evaluation/axis-checks/registry.d.ts +1 -1
  21. package/dist/evaluation/axis-checks/registry.js +19 -4
  22. package/dist/evaluation/axis-checks/registry.js.map +1 -1
  23. package/dist/evaluation/index.d.ts +3 -3
  24. package/dist/evaluation/index.js +21 -6
  25. package/dist/evaluation/index.js.map +1 -1
  26. package/dist/harness/check/runtime-render/index.d.ts +4 -4
  27. package/dist/harness/check/runtime-render/index.js +26 -6
  28. package/dist/harness/check/runtime-render/index.js.map +1 -1
  29. package/dist/harness/check/runtime-render/render-check-worker.js.map +1 -1
  30. package/dist/harness/index.d.ts +1 -1
  31. package/dist/harness/index.js +3 -2
  32. package/dist/harness/index.js.map +1 -1
  33. package/dist/harness/result-types.d.ts +1 -1
  34. package/dist/harness/runtime.d.ts +1 -1
  35. package/dist/harness/runtime.js +2 -1
  36. package/dist/harness/runtime.js.map +1 -1
  37. package/dist/harness/types-public.d.ts +9 -5
  38. package/dist/harness/types-public.js +1 -0
  39. package/dist/harness/types-public.js.map +1 -1
  40. package/dist/harness/validator-trace-sink.d.ts +1 -1
  41. package/dist/index.d.ts +2 -2
  42. package/dist/index.js +55 -17
  43. package/dist/index.js.map +1 -1
  44. package/dist/patch.d.ts +1 -1
  45. package/dist/{render-check-C0CqVceF.d.ts → render-check-Blwj8gB6.d.ts} +18 -0
  46. package/dist/tools/get-primitives-ts.d.ts +1 -1
  47. package/dist/tools/get-primitives-ts.js +1 -1
  48. package/dist/tools/get-primitives-ts.js.map +1 -1
  49. package/dist/{types-public-mM_-1Yk3.d.ts → types-public-Ow-tNtFE.d.ts} +26 -3
  50. package/dist/validation/index.d.ts +1 -1
  51. package/dist/validation/index.js +1 -1
  52. package/dist/validation/index.js.map +1 -1
  53. package/dist/workflows.d.ts +1 -1
  54. package/package.json +12 -12
  55. package/src/advanced/generator.ts +16 -1
  56. package/src/blueprint-validator.ts +21 -6
  57. package/src/boilerplate/hard-sections.ts +1 -0
  58. package/src/coding-agent/tools.ts +6 -1
  59. package/src/evaluation/axis-checks/checks/state-payload.ts +29 -4
  60. package/src/evaluation/types-public.ts +26 -2
  61. package/src/harness/check/runtime-render/adapter.ts +19 -0
  62. package/src/harness/check/runtime-render/render-check-host.ts +31 -9
  63. package/src/harness/check/runtime-render/render-check.ts +19 -0
  64. package/src/harness/coding/run-eval-round.ts +2 -0
  65. package/src/harness/llm-router.ts +3 -3
  66. package/src/harness/types-public.ts +9 -5
  67. package/src/tools/get-primitives-ts.ts +1 -1
  68. package/src/validation/primitives.ts +1 -1
@@ -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,6BAAA,EAAA,MAAA,6BAAA;AAAA,EAAA,uBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AA4DA,SAAS,kBAAA,GAA0D;AACjE,EAAA,MAAM,YAAA,GAAe;AAAA;AAAA,IAEnB,IAAI,GAAA,CAAI,CAAA,EAAA,EAAK,eAAe,CAAA,GAAA,CAAA,EAAO,YAAY,GAAG,CAAA;AAAA;AAAA,IAElD,IAAI,GAAA,CAAI,CAAA,+BAAA,EAAkC,eAAe,CAAA,GAAA,CAAA,EAAO,YAAY,GAAG,CAAA;AAAA;AAAA,IAE/E,IAAI,GAAA,CAAI,CAAA,uBAAA,EAA0B,eAAe,CAAA,GAAA,CAAA,EAAO,YAAY,GAAG,CAAA;AAAA;AAAA,IAEvE,IAAI,GAAA,CAAI,CAAA,gCAAA,EAAmC,eAAe,CAAA,GAAA,CAAA,EAAO,YAAY,GAAG;AAAA,GAClF;AACA,EAAA,KAAA,MAAW,SAAS,YAAA,EAAc;AAChC,IAAA,MAAM,MAAA,GAAS,cAAc,KAAK,CAAA;AAClC,IAAA,IAAI,UAAA,CAAW,MAAM,CAAA,EAAG;AACtB,MAAA,OAAO,EAAE,OAAA,EAAS,OAAA,CAAQ,UAAU,IAAA,EAAM,CAAC,MAAM,CAAA,EAAE;AAAA,IACrD;AAAA,EACF;AAEA,EAAA,MAAM,YAAA,GAAe;AAAA,IACnB,IAAI,GAAA,CAAI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BAAwB,OAAO,CAAA,cAAA,EAAiB,OAAO,CAAA,WAAA,EAAc,OAAO,qBAAqB,OAAO,CAAA,uCAAA;AAAA,OAC/G;AAAA;AAEN;;;AC1QA,eAAsB,wBAAA,GAAqF;AACzG,EAAA,MAAM,KAAA,GAAQ,KAAK,GAAA,EAAI;AACvB,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,IAAI,OAAA,GAAU,CAAA;AACd,EAAA,MAAM,OAAA,GAAU,OAAO,SAAA,KAAsB;AAC3C,IAAA,IAAI;AACF,MAAA,MAAM,OAAO,SAAA,CAAA;AACb,MAAA,MAAA,IAAU,CAAA;AAAA,IACZ,CAAA,CAAA,MAAQ;AACN,MAAA,OAAA,IAAW,CAAA;AAAA,IACb;AAAA,EACF,CAAA;AAMA,EAAA,wBAAA,EAAyB;AACzB,EAAA,MAAM,QAAQ,GAAA,CAAI;AAAA,IAChB,QAAQ,WAAW,CAAA;AAAA,IACnB,QAAQ,wBAAwB,CAAA;AAAA,IAChC,QAAQ,6BAA6B,CAAA;AAAA,IACrC,QAAQ,eAAe;AAAA,GACxB,CAAA;AACD,EAAA,OAAO,EAAE,EAAA,EAAI,IAAA,CAAK,KAAI,GAAI,KAAA,EAAO,QAAQ,OAAA,EAAQ;AACnD","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 → `failed` (runaway component: the\n * in-process check has no comparable wall-clock bound, the\n * subprocess finally gives us one).\n * - spawn-error / overflow / non-zero exit / unparseable stdout\n * → `unverified` (the harness could not\n * run the check; never blame the component for our plumbing).\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 { fileURLToPath, pathToFileURL } from 'node:url';\nimport { runSandboxed } from '@ggui-ai/sandbox';\nimport type { SandboxResult } from '@ggui-ai/sandbox';\nimport type { RenderCheckResult, RunRenderCheckInput } from './render-check.js';\n\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 */\nconst CHECK_TIMEOUT_MS = 30_000;\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\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 */\nconst CHECK_NODE_HEAP_MB = 512;\n\nconst WORKER_BASENAME = 'render-check-worker';\n\nfunction 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`. Exported for the\n * unit pins — the spawn itself is exercised by the integration test.\n */\nexport function mapSandboxResultToCheckResult(\n result: SandboxResult,\n t0: number,\n): RenderCheckResult {\n if (result.outcome === 'timeout') {\n return failed(\n `render check timed out after ${CHECK_TIMEOUT_MS}ms in the isolated worker (likely infinite loop or runaway effect in the component).`,\n 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 */\nexport async function runRenderCheckViaWorker(\n input: RunRenderCheckInput,\n): Promise<RenderCheckResult> {\n const t0 = Date.now();\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 result = await runSandboxed({\n command: spawn.command,\n args: spawn.args,\n timeoutMs: CHECK_TIMEOUT_MS,\n maxStdoutBytes: CHECK_STDOUT_CAP,\n nodeHeapMb: CHECK_NODE_HEAP_MB,\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 return mapSandboxResultToCheckResult(result, t0);\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 {\n DataContract,\n JsonObject,\n PropsSpec,\n} from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport {\n createProbe,\n createProbeWireConfig,\n type ActionFiredEvent,\n type Probe,\n} 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 { 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\nexport interface RenderCheckIssue {\n readonly check:\n | \"render-no-throw\"\n | \"action-wiring\"\n | \"selection-identity\"\n | \"prop-coverage\"\n | \"prop-sensitivity\"\n | \"stream-rerender\"\n | \"optional-props-omitted\";\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 =\n | { readonly primed: number }\n | { readonly error: string };\n\nexport interface RenderCheckResult {\n readonly ok: boolean;\n readonly issues: readonly RenderCheckIssue[];\n readonly stats: {\n readonly actionsChecked: number;\n readonly streamsChecked: number;\n readonly renderMs: number;\n };\n}\n\nexport interface RunRenderCheckInput {\n readonly sourceCode: string;\n readonly mockupProps: JsonObject;\n readonly contract?: DataContract;\n}\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): Promise<RenderCheckResult> {\n const g = hostGlobals();\n if (\"window\" in g && \"document\" in g) {\n return runRenderCheckInProcess(input);\n }\n const { runRenderCheckViaWorker } = await import(\"./render-check-host.js\");\n return runRenderCheckViaWorker(input);\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(\n \"@ggui-ai/gadgets\"\n );\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 (\n typeof arg === \"string\" &&\n /^\\s*at\\s+\\S/m.test(arg) &&\n arg.length > 20\n ) {\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(() => reject(new Error(`[runtime-render] render exceeded ${RENDER_TIMEOUT_MS}ms — classified as runtime-hang`)), RENDER_TIMEOUT_MS).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((l) => !/(node_modules|happy-dom|@testing-library|react-dom|node:internal|node:async)/.test(l))\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\n ? boundaryRef.error.message\n : \"(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 =>\n (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:\n `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(([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 ??=\n 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 { uninstallSpy?.(); } catch { /* ignore */ }\n try { uninstallGadgetRegistry?.(); } catch { /* ignore */ }\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(\n contract: DataContract | undefined,\n): () => 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) =>\n 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(\n contract: DataContract | undefined,\n): 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) =>\n 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(() => { throw err; });\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(() => { throw err; });\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: wiring.reason ?? `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: wiring.reason ?? \"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(\n schema: Record<string, unknown> | undefined,\n): 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(\n properties as Record<string, unknown>,\n )) {\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 (\n el: MinimalElement,\n ): 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(\n (e): e is ActionFiredEvent =>\n e.kind === 'action.fired' && e.name === actionName,\n );\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:\n `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\", { bubbles: true, cancelable: true });\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 { await user.click(el); } catch { /* ignore */ }\n const KeyboardEventCtor = (globalThis as { KeyboardEvent?: new (type: string, init: object) => Event }).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) { pick = opts[i]!.value; break; }\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(input: CheckStreamRerenderInput): 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(container: MinimalElement, name: string, label: string): 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 { runRenderCheck, type RenderCheckIssue } from \"./render-check.js\";\nimport { prepareMockupProps } from \"./prepare-mockup.js\";\n\nexport const DEFAULT_RUNTIME_RENDER_CHECK: RuntimeRenderCheck = {\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 let result;\n try {\n result = await runRenderCheck({\n sourceCode,\n mockupProps: mockup.props,\n contract,\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(\n `[runtime-render] probe skipped — infra failure: ${message}`,\n );\n return { status: \"infra-skipped\", issues: [], reason: message };\n }\n\n return {\n status: \"ran\",\n issues: result.issues\n .map(toEvalIssue)\n .filter((x): x is EvalIssue => x !== null),\n };\n },\n};\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 (\n r.includes(\"cannot read\") ||\n r.includes(\"undefined is not\") ||\n r.includes(\"null is not\")\n ) {\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\nfunction 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 = 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\";\n\nexport { runRenderCheck, type RenderCheckResult, type RenderCheckIssue } 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 isRecoverableRenderCrash,\n} from \"./adapter.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<{ ms: number; loaded: number; missing: number }> {\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"]}
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,6BAAA,EAAA,MAAA,6BAAA;AAAA,EAAA,uBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAyEA,SAAS,kBAAA,GAA0D;AACjE,EAAA,MAAM,YAAA,GAAe;AAAA;AAAA,IAEnB,IAAI,GAAA,CAAI,CAAA,EAAA,EAAK,eAAe,CAAA,GAAA,CAAA,EAAO,YAAY,GAAG,CAAA;AAAA;AAAA,IAElD,IAAI,GAAA,CAAI,CAAA,+BAAA,EAAkC,eAAe,CAAA,GAAA,CAAA,EAAO,YAAY,GAAG,CAAA;AAAA;AAAA,IAE/E,IAAI,GAAA,CAAI,CAAA,uBAAA,EAA0B,eAAe,CAAA,GAAA,CAAA,EAAO,YAAY,GAAG,CAAA;AAAA;AAAA,IAEvE,IAAI,GAAA,CAAI,CAAA,gCAAA,EAAmC,eAAe,CAAA,GAAA,CAAA,EAAO,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AAK,KAAI,GAAI,KAAA,EAAO,QAAQ,OAAA,EAAQ;AACnD","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 * 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 */\nconst CHECK_TIMEOUT_MS = 30_000;\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\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 */\nconst CHECK_NODE_HEAP_MB = 512;\n\nconst WORKER_BASENAME = 'render-check-worker';\n\nfunction 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`. Exported for the\n * unit pins — the spawn itself is exercised by the integration test.\n */\nexport function mapSandboxResultToCheckResult(\n result: SandboxResult,\n t0: number,\n): RenderCheckResult {\n if (result.outcome === 'timeout') {\n return {\n ok: false,\n issues: [],\n incomplete: { kind: 'timeout', elapsedMs: result.durationMs, boundMs: CHECK_TIMEOUT_MS },\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 */\nexport async function runRenderCheckViaWorker(\n input: RunRenderCheckInput,\n): Promise<RenderCheckResult> {\n const t0 = Date.now();\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: CHECK_TIMEOUT_MS,\n maxStdoutBytes: CHECK_STDOUT_CAP,\n nodeHeapMb: CHECK_NODE_HEAP_MB,\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);\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 {\n DataContract,\n JsonObject,\n PropsSpec,\n} from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport {\n createProbe,\n createProbeWireConfig,\n type ActionFiredEvent,\n type Probe,\n} 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\nexport interface RenderCheckIssue {\n readonly check:\n | \"render-no-throw\"\n | \"action-wiring\"\n | \"selection-identity\"\n | \"prop-coverage\"\n | \"prop-sensitivity\"\n | \"stream-rerender\"\n | \"optional-props-omitted\";\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 =\n | { readonly primed: number }\n | { 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// 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): Promise<RenderCheckResult> {\n const g = hostGlobals();\n if (\"window\" in g && \"document\" in g) {\n return runRenderCheckInProcess(input);\n }\n const { runRenderCheckViaWorker } = await import(\"./render-check-host.js\");\n return runRenderCheckViaWorker(input);\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(\n \"@ggui-ai/gadgets\"\n );\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 (\n typeof arg === \"string\" &&\n /^\\s*at\\s+\\S/m.test(arg) &&\n arg.length > 20\n ) {\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(() => reject(new Error(`[runtime-render] render exceeded ${RENDER_TIMEOUT_MS}ms — classified as runtime-hang`)), RENDER_TIMEOUT_MS).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((l) => !/(node_modules|happy-dom|@testing-library|react-dom|node:internal|node:async)/.test(l))\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\n ? boundaryRef.error.message\n : \"(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 =>\n (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:\n `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(([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 ??=\n 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 { uninstallSpy?.(); } catch { /* ignore */ }\n try { uninstallGadgetRegistry?.(); } catch { /* ignore */ }\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(\n contract: DataContract | undefined,\n): () => 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) =>\n 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(\n contract: DataContract | undefined,\n): 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) =>\n 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(() => { throw err; });\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(() => { throw err; });\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: wiring.reason ?? `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: wiring.reason ?? \"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(\n schema: Record<string, unknown> | undefined,\n): 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(\n properties as Record<string, unknown>,\n )) {\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 (\n el: MinimalElement,\n ): 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(\n (e): e is ActionFiredEvent =>\n e.kind === 'action.fired' && e.name === actionName,\n );\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:\n `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\", { bubbles: true, cancelable: true });\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 { await user.click(el); } catch { /* ignore */ }\n const KeyboardEventCtor = (globalThis as { KeyboardEvent?: new (type: string, init: object) => Event }).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) { pick = opts[i]!.value; break; }\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(input: CheckStreamRerenderInput): 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(container: MinimalElement, name: string, label: string): 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 { runRenderCheck, type RenderCheckIssue } from \"./render-check.js\";\nimport { prepareMockupProps } from \"./prepare-mockup.js\";\n\nexport const DEFAULT_RUNTIME_RENDER_CHECK: RuntimeRenderCheck = {\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 let result;\n try {\n result = await runRenderCheck({\n sourceCode,\n mockupProps: mockup.props,\n contract,\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(\n `[runtime-render] probe skipped — infra failure: ${message}`,\n );\n return { status: \"infra-skipped\", issues: [], reason: message };\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 return { status: \"timed-out\", issues: [], reason, elapsedMs, ...load };\n }\n\n return {\n status: \"ran\",\n issues: result.issues\n .map(toEvalIssue)\n .filter((x): x is EvalIssue => x !== null),\n ...load,\n };\n },\n};\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 (\n r.includes(\"cannot read\") ||\n r.includes(\"undefined is not\") ||\n r.includes(\"null is not\")\n ) {\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\nfunction 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 = 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\";\n\nexport { runRenderCheck, type RenderCheckResult, type RenderCheckIssue } 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 isRecoverableRenderCrash,\n} from \"./adapter.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<{ ms: number; loaded: number; missing: number }> {\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"]}