@ggui-ai/ui-gen 0.26.0 → 0.28.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 (77) hide show
  1. package/dist/{adapter-BJwn74rx.d.ts → adapter-h4_V69LI.d.ts} +1 -1
  2. package/dist/adapters/base.d.ts +6 -1
  3. package/dist/adapters/base.js.map +1 -1
  4. package/dist/adapters/generation-dispatch.d.ts +2 -2
  5. package/dist/adapters/generation-dispatch.js +233 -17
  6. package/dist/adapters/generation-dispatch.js.map +1 -1
  7. package/dist/adapters/index.js +36 -14
  8. package/dist/adapters/index.js.map +1 -1
  9. package/dist/advanced/index.d.ts +4 -4
  10. package/dist/advanced/index.js +268 -28
  11. package/dist/advanced/index.js.map +1 -1
  12. package/dist/boilerplate.js +4 -6
  13. package/dist/boilerplate.js.map +1 -1
  14. package/dist/check/index.d.ts +1 -7
  15. package/dist/check/index.js +50 -4
  16. package/dist/check/index.js.map +1 -1
  17. package/dist/{create-ui-generator-N4gRXpcL.d.ts → create-ui-generator-BrZHF0cf.d.ts} +2 -2
  18. package/dist/{dispatch-BUoXRj_r.d.ts → dispatch-B07TI30d.d.ts} +1 -1
  19. package/dist/evaluation/axis-checks/index.d.ts +3 -3
  20. package/dist/evaluation/axis-checks/index.js +97 -1
  21. package/dist/evaluation/axis-checks/index.js.map +1 -1
  22. package/dist/evaluation/axis-checks/registry.d.ts +1 -1
  23. package/dist/evaluation/axis-checks/registry.js +97 -1
  24. package/dist/evaluation/axis-checks/registry.js.map +1 -1
  25. package/dist/evaluation/index.d.ts +22 -12
  26. package/dist/evaluation/index.js +138 -14
  27. package/dist/evaluation/index.js.map +1 -1
  28. package/dist/evaluation/types.d.ts +1 -1
  29. package/dist/harness/check/runtime-render/index.d.ts +3 -3
  30. package/dist/harness/index.d.ts +1 -1
  31. package/dist/harness/index.js +6 -6
  32. package/dist/harness/index.js.map +1 -1
  33. package/dist/harness/prompts.js +1 -4
  34. package/dist/harness/prompts.js.map +1 -1
  35. package/dist/harness/result-types.d.ts +14 -3
  36. package/dist/harness/result-types.js.map +1 -1
  37. package/dist/harness/runtime.d.ts +1 -1
  38. package/dist/harness/runtime.js +6 -7
  39. package/dist/harness/runtime.js.map +1 -1
  40. package/dist/harness/types-public.d.ts +1 -1
  41. package/dist/harness/types-public.js +4 -6
  42. package/dist/harness/types-public.js.map +1 -1
  43. package/dist/harness/validator-trace-sink.d.ts +1 -1
  44. package/dist/index.d.ts +6 -6
  45. package/dist/index.js +268 -28
  46. package/dist/index.js.map +1 -1
  47. package/dist/patch.d.ts +1 -1
  48. package/dist/{types-public-B7wn4ce5.d.ts → types-public-h8IMnYuh.d.ts} +4 -0
  49. package/dist/{visual-evaluator-C9L-o6ap.d.ts → visual-evaluator-C2strxqD.d.ts} +1 -1
  50. package/dist/workflows.d.ts +1 -1
  51. package/package.json +13 -13
  52. package/src/adapters/base.ts +6 -1
  53. package/src/adapters/claude/message-parser.ts +5 -6
  54. package/src/adapters/claude/sdk-tool-pins.ts +44 -0
  55. package/src/adapters/claude/sdk.ts +3 -3
  56. package/src/adapters/claude/source-capture.ts +20 -0
  57. package/src/adapters/provider-router.ts +1 -0
  58. package/src/boilerplate/system-prompt.ts +3 -2
  59. package/src/check/run-tier0.ts +61 -0
  60. package/src/create-ui-generator.ts +4 -2
  61. package/src/design-system-docs.ts +2 -1
  62. package/src/evaluation/axis-checks/checks/state-merge.ts +1 -1
  63. package/src/evaluation/axis-checks/helpers.ts +125 -0
  64. package/src/evaluation/criteria/resolve.ts +19 -1
  65. package/src/evaluation/evaluator.ts +2 -2
  66. package/src/evaluation/llm-evaluator.ts +2 -2
  67. package/src/evaluation/loop.ts +25 -4
  68. package/src/evaluation/message-parsing.ts +11 -12
  69. package/src/evaluation/types-public.ts +4 -0
  70. package/src/evaluation/visual-evaluator.ts +1 -1
  71. package/src/harness/coding/assemble-result.ts +1 -0
  72. package/src/harness/coding/dupe-break.ts +70 -0
  73. package/src/harness/coding/generate-task-runner.ts +5 -1
  74. package/src/harness/coding/run-coding-turn.ts +56 -1
  75. package/src/harness/result-types.ts +12 -0
  76. package/src/index.ts +1 -1
  77. package/src/taught-tokens.ts +5 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/check/extract-wire-calls.ts","../../src/boilerplate/json-schema-ts.ts","../../src/check/contract-validation.ts","../../src/validation/allowed-imports.ts","../../src/check/type-checker.ts","../../src/check/react-linter.ts","../../src/design-mode.ts","../../src/taught-tokens.ts","../../src/evaluation/types-public.ts","../../src/check/run-tier0.ts","../../src/check/sample-props.ts"],"names":["ts","resolved","consumedTokenManifest"],"mappings":";;;;;;;;;;AAuGA,IAAM,YAAA,GAAmD;AAAA,EACvD,SAAA,EAAW,QAAA;AAAA,EACX,SAAA,EAAW,QAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMX,cAAA,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAMlB,CAAA;AAGA,IAAM,cAAA,GAAiB,MAAA,CAAO,IAAA,CAAK,YAAY,CAAA;AAYxC,SAAS,qBAAqB,IAAA,EAA8B;AACjE,EAAA,MAAM,KAAKA,GAAA,CAAG,gBAAA;AAAA,IACZ,eAAA;AAAA,IACA,IAAA;AAAA,IACAA,IAAG,YAAA,CAAa,MAAA;AAAA;AAAA,IACG,IAAA;AAAA,IACnBA,IAAG,UAAA,CAAW;AAAA,GAChB;AACA,EAAA,MAAM,QAAwB,EAAC;AAE/B,EAAA,SAAS,MAAM,IAAA,EAAqB;AAClC,IAAA,IAAIA,GAAA,CAAG,gBAAA,CAAiB,IAAI,CAAA,EAAG;AAC7B,MAAA,MAAM,SAAS,IAAA,CAAK,UAAA;AAIpB,MAAA,IAAIA,GAAA,CAAG,YAAA,CAAa,MAAM,CAAA,EAAG;AAC3B,QAAA,MAAM,IAAA,GAAO,YAAA,CAAa,MAAA,CAAO,IAAI,CAAA;AACrC,QAAA,IAAI,IAAA,EAAM;AACR,UAAA,MAAM,QAAA,GAAW,I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CAAM,OAAA,CAAQ,MAAA,CAAO,IAAI,CAAA,GACtC,MAAA,CAAO,IAAA,CAAK,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,KAAM,MAAM,IACpC,MAAA,CAAO,IAAA;AACX,EAAA,QAAQ,QAAA;AAAU,IAChB,KAAK,QAAA;AAAU,MAAA,OAAO,QAAA;AAAA,IACtB,KAAK,QAAA;AAAA,IACL,KAAK,SAAA;AAAW,MAAA,OAAO,CAAA;AAAA,IACvB,KAAK,SAAA;AAAW,MAAA,OAAO,KAAA;AAAA,IACvB,KAAK,MAAA;AAAQ,MAAA,OAAO,IAAA;AAAA,IACpB,KAAK,OAAA,EAAS;AACZ,MAAA,IAAI,MAAA,CAAO,OAAO,OAAO,CAAC,qBAAqB,MAAA,CAAO,KAAK,KAAK,IAAI,CAAA;AACpE,MAAA,OAAO,EAAC;AAAA,IACV;AAAA,IACA,KAAK,QAAA,EAAU;AACb,MAAA,MAAM,MAAkB,EAAC;AACzB,MAAA,IAAI,OAAO,UAAA,EAAY;AACrB,QAAA,KAAA,MAAW,CAAC,GAAG,CAAC,CAAA,IAAK,OAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG;AACtD,UAAA,GAAA,CAAI,CAAC,CAAA,GAAI,oBAAA,CAAqB,CAAC,CAAA;AAAA,QACjC;AAAA,MACF;AACA,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,IACA;AAAS,MAAA,OAAO,MAAA;AAAA;AAEpB","file":"index.js","sourcesContent":["// packages/ui-gen/src/check/extract-wire-calls.ts\n//\n// AST helper for wire-call-site extraction + sibling `checkWireImports`\n// for OSS tier-0 gate coverage.\n//\n// Used by:\n// (1) Tier-0 `wire_preservation` check — verifies the LLM hasn't\n// deleted a boilerplate-emitted hook call via `apply_patch`.\n// Deletion cannot be caught by `pnpm typecheck` alone because a\n// hook that is never called simply doesn't fire; the TypeScript\n// checker has no opinion on absence.\n// (2) Tier-0 `wire_import` check — verifies every\n// wire hook the component calls also appears as a named import\n// from `@ggui-ai/wire` at top level. Missing imports turn into\n// `ReferenceError` at mount because `rewriteImports` only\n// activates the data-URL shim for specifiers that already exist\n// in the code.\n// (3) Axis check (future) — same report shape, surfaced at eval tier\n// alongside the other deterministic axes.\n//\n// Keying is on the STRING-LITERAL first argument of the hook call, NOT\n// the variable name bound to its result. An LLM that renames\n// `const submit = useAction('submit')` to `const onSubmit =\n// useAction('submit')` is authoring the SAME wire — the identifier is\n// ergonomic sugar, the wire contract is the string. This matches the\n// `@ggui-ai/wire` hook semantics: the dispatcher routes by name.\n//\n// Regex was deliberately rejected for the call-site walk. Hook calls\n// inside callbacks, behind variable aliases, or wrapped in `useMemo`/\n// `useCallback` dependency arrays would fool a regex scan. The TS\n// compiler API walks the real AST and never confuses `useAction`\n// identifier references (e.g. in a dependency array) with actual\n// `useAction(...)` call expressions.\n\nimport ts from \"typescript\";\nimport type { DataContract } from \"@ggui-ai/protocol\";\n\n/**\n * The four contract-declared wire kinds, matching `@ggui-ai/wire` hooks.\n *\n * `'context'` covers `useGguiContext` calls. The iframe-runtime mounts\n * Contexts only when the bootstrap envelope carries `contextSlots`,\n * which fires only when the persisted GguiSession has `contextSpec`,\n * which happens only when the agent authored\n * `story.contract.contextSpec` AND render.ts plumbed it to the\n * generator. The symptom of a missing slot is a blank `/r/<id>` direct\n * preview when the LLM emitted `useGguiContext('X')` without a\n * declared slot. The undeclared-wire-call check (tier-0\n * `wire_undeclared`) catches the drift fail-loud at gen time so the\n * agent gets a remediation message instead of a silent blank page.\n *\n * `'clientTool'` retired 2026-05-11 alongside `useClientTool` +\n * `clientTools` → `clientCapabilities` reframe. Capability hooks\n * import from `@ggui-ai/gadgets` (or other vendor packages),\n * not from `@ggui-ai/wire`, so they fall outside the wire-import\n * tier-0 gate by construction.\n */\nexport type WireKind =\n | \"action\"\n | \"stream\"\n | \"context\";\n\n/** A single extracted wire reference — either from code or from the contract. */\nexport interface WireCallSite {\n readonly kind: WireKind;\n /** The string-literal argument to the hook, matching the contract key. */\n readonly name: string;\n}\n\n/**\n * Bidirectional completeness report between a contract and a component's\n * hook call sites. `missing` = contract-declared but absent from code;\n * `extra` = present in code but not declared on the contract. Item 3b\n * compile narrowing (`InferActionNames<T>` / `InferStreamNames<T>`)\n * already rejects `extra` at typecheck time — this report is primarily\n * consumed by the `wire_preservation` tier-0 check for the `missing`\n * direction.\n */\nexport interface WirePreservationReport {\n readonly missing: WireCallSite[];\n readonly extra: WireCallSite[];\n}\n\n/**\n * Report from `checkWireImports`. Each entry names a wire hook the\n * component CALLS at least once but does NOT import from\n * `@ggui-ai/wire` at the top level. Hook-name collisions (e.g. a\n * user-defined `useAction` in the same scope) are out of scope —\n * generated code lives inside the boilerplate frame, which declares\n * the hooks as imports and nothing else by that name.\n */\nexport interface WireImportReport {\n /** Hooks the component calls but does not import. */\n readonly missing: readonly WireImportSite[];\n}\n\nexport interface WireImportSite {\n /** The hook function name — `useAction` / `useStream` / etc. */\n readonly hook: string;\n /** The matching `WireKind` for reporting symmetry. */\n readonly kind: WireKind;\n}\n\nconst HOOK_TO_KIND: Readonly<Record<string, WireKind>> = {\n useAction: \"action\",\n useStream: \"stream\",\n // `useGguiContext('slot')` is the client→agent observable-state\n // hook. Treated as a wire call site for tier-0 preservation +\n // undeclared detection because the runtime registers one\n // React.Context per declared contextSpec slot at boot — referencing\n // an undeclared slot throws synchronously at first paint.\n useGguiContext: \"context\",\n // Pre-rename component-side tool hooks are retired. The contract's\n // `agentCapabilities.tools` catalog is agent-side declaration only —\n // no component hook surface. Cross-refs surface via\n // `actionSpec[*].nextStep` (already covered by the `action` kind)\n // and `streamSpec[*].source.tool` (covered by `stream`).\n};\n\n/** All known wire hook names — iteration source for `checkWireImports`. */\nconst ALL_WIRE_HOOKS = Object.keys(HOOK_TO_KIND) as ReadonlyArray<\n keyof typeof HOOK_TO_KIND\n>;\n\n/**\n * Walk the TSX AST and collect every call expression whose callee is one\n * of the four wire hooks AND whose first argument is a string literal.\n * Non-literal first arguments (e.g. `useAction(dynamicName)`) are\n * intentionally ignored — the generator always emits string literals,\n * and the contract keys by literal, so an indirection through a\n * variable can't carry the wiring.\n */\nexport function extractWireCallSites(code: string): WireCallSite[] {\n const sf = ts.createSourceFile(\n \"component.tsx\",\n code,\n ts.ScriptTarget.Latest,\n /*setParentNodes*/ true,\n ts.ScriptKind.TSX,\n );\n const sites: WireCallSite[] = [];\n\n function visit(node: ts.Node): void {\n if (ts.isCallExpression(node)) {\n const callee = node.expression;\n // Match bare hook identifiers. We do NOT match\n // `React.useAction(...)` or other member-accessed forms — wire\n // hooks are always imported by name from `@ggui-ai/wire`.\n if (ts.isIdentifier(callee)) {\n const kind = HOOK_TO_KIND[callee.text];\n if (kind) {\n const firstArg = node.arguments[0];\n if (firstArg && ts.isStringLiteral(firstArg)) {\n sites.push({ kind, name: firstArg.text });\n }\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return sites;\n}\n\n/**\n * Walk top-level `import` statements and collect named specifiers\n * imported from `@ggui-ai/wire`. Returns the set of local-binding\n * names (not aliased source names) because the checker compares\n * against identifiers USED by call expressions in the body.\n *\n * Default imports and namespace imports (`import * as w from ...`) are\n * ignored — the `@ggui-ai/wire` shim exports named members only, and\n * generated code always reaches for them by name.\n */\nexport function extractWireImports(code: string): ReadonlySet<string> {\n const sf = ts.createSourceFile(\n \"component.tsx\",\n code,\n ts.ScriptTarget.Latest,\n /*setParentNodes*/ true,\n ts.ScriptKind.TSX,\n );\n const imported = new Set<string>();\n\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const moduleSpecifier = stmt.moduleSpecifier;\n if (!ts.isStringLiteral(moduleSpecifier)) continue;\n if (moduleSpecifier.text !== \"@ggui-ai/wire\") continue;\n\n const clause = stmt.importClause;\n if (!clause) continue;\n const bindings = clause.namedBindings;\n if (!bindings) continue;\n if (!ts.isNamedImports(bindings)) continue;\n for (const el of bindings.elements) {\n // `import { useAction as a }` — the LOCAL name is what the body\n // references. But generated code never aliases wire hooks, so\n // reading `el.name.text` for both aliased and bare forms stays\n // correct either way (local = bare when no alias).\n imported.add(el.name.text);\n }\n }\n\n return imported;\n}\n\n/**\n * Enumerate every wire a contract declares. Parallels the generator's\n * emission order in `generateBoilerplate` — actions, streams, context\n * slots. Contract-key typing matches the `@ggui-ai/protocol` canonical\n * flat-map shape.\n *\n * `agentCapabilities.tools` and `clientCapabilities` are NOT enumerated:\n * - `agentCapabilities.tools` is a catalog the AGENT invokes (no component hook).\n * Cross-references surface via `actionSpec[*].nextStep` and\n * `streamSpec[*].source.tool`, already covered by `action` / `stream`.\n * - `clientCapabilities` are declarations of browser-capability hooks\n * imported from `@ggui-ai/gadgets` (or another vendor package).\n * They are NOT `@ggui-ai/wire` hooks and do NOT participate in the\n * wire-import tier-0 gate.\n */\nexport function collectExpectedWires(contract: DataContract): WireCallSite[] {\n const expected: WireCallSite[] = [];\n\n const actionsMap = contract.actionSpec ?? {};\n for (const name of Object.keys(actionsMap)) {\n expected.push({ kind: \"action\", name });\n }\n\n const streamsMap = contract.streamSpec ?? {};\n for (const name of Object.keys(streamsMap)) {\n expected.push({ kind: \"stream\", name });\n }\n\n // contextSpec slots. Each declared slot becomes one\n // `useGguiContext('<slot>')` call site the boilerplate auto-emits\n // at the top of the component body. Without this in the expected\n // set, an LLM emitting an undeclared useGguiContext call slips\n // through and the runtime throws on mount (no Context registered\n // for that slot), blanking the iframe.\n const contextMap = contract.contextSpec ?? {};\n for (const name of Object.keys(contextMap)) {\n expected.push({ kind: \"context\", name });\n }\n\n return expected;\n}\n\n/**\n * Diff the component's observed wire call sites against the contract's\n * expected wires. Symmetric set difference by `(kind, name)` pair.\n */\nexport function checkWirePreservation(\n code: string,\n contract: DataContract,\n): WirePreservationReport {\n const expected = collectExpectedWires(contract);\n const actual = extractWireCallSites(code);\n\n const actualKeys = new Set(actual.map((s) => `${s.kind}:${s.name}`));\n const expectedKeys = new Set(expected.map((s) => `${s.kind}:${s.name}`));\n\n const missing = expected.filter((s) => !actualKeys.has(`${s.kind}:${s.name}`));\n const extra = actual.filter((s) => !expectedKeys.has(`${s.kind}:${s.name}`));\n\n return { missing, extra };\n}\n\n/**\n * Guards against this failure class: componentCode calls a wire hook\n * but doesn't import it, so the data-URL shim rewrite has no\n * specifier to attach to and the hook is undeclared at eval time. Run\n * `extractWireCallSites` for the used set, `extractWireImports` for\n * the imported set, and emit the setwise difference.\n *\n * This is purely a STATIC check — it doesn't care whether the contract\n * declares each hook (that's `checkWirePreservation`'s job). Its only\n * question is: every hook the generated code CALLS, is it imported?\n * Yes → silent. No → report. A hook that is imported but unused is\n * caught by the existing `no-unused-vars` lint, not by this check.\n */\nexport function checkWireImports(code: string): WireImportReport {\n const used = extractWireCallSites(code);\n const imports = extractWireImports(code);\n const usedHookSet = new Set(\n used.map(\n (s) =>\n // Reverse the kind → hook-name lookup. Closed set of 5 —\n // hardcoded to stay cheap and explicit.\n ({\n action: \"useAction\",\n stream: \"useStream\",\n context: \"useGguiContext\",\n })[s.kind],\n ),\n );\n\n const missing: WireImportSite[] = [];\n for (const hook of ALL_WIRE_HOOKS) {\n if (!usedHookSet.has(hook)) continue;\n if (imports.has(hook)) continue;\n missing.push({ hook, kind: HOOK_TO_KIND[hook] });\n }\n\n return { missing };\n}\n","// packages/ui-gen/src/boilerplate/json-schema-ts.ts\n//\n// JSON Schema → TypeScript type string converter.\n//\n// Pure, self-contained, no env reads, no framework deps. Exposed\n// publicly on `@ggui-ai/ui-gen/boilerplate` because it's the primitive\n// that turns a contract's JSON Schema into the `interface Props { ... }`\n// block the boilerplate generator writes.\n\nimport type { JsonSchema } from '@ggui-ai/protocol';\n\n/**\n * Convert a JsonSchema to a TypeScript type string — recursive.\n *\n * Handles: string, number, integer, boolean, null, array (+ tuples), object,\n * enum, oneOf/anyOf (unions), nullable, const, additionalProperties.\n */\nexport function jsonSchemaTypeToTs(schema: JsonSchema): string {\n // ── Union types (oneOf / anyOf) ──\n const unionMembers = schema.oneOf ?? schema.anyOf;\n if (unionMembers?.length) {\n const types = [...new Set(unionMembers.map(s => jsonSchemaTypeToTs(s)))];\n return types.length === 1 ? types[0] : types.join(' | ');\n }\n\n // ── Const (literal type) ──\n if (schema.const !== undefined) {\n return typeof schema.const === 'string' ? `'${schema.const}'` : String(schema.const);\n }\n\n // ── Enum (union of literals) ──\n if (schema.enum?.length) {\n return schema.enum\n .map(v => typeof v === 'string' ? `'${v}'` : String(v))\n .join(' | ');\n }\n\n // ── Draft-07 type array (`['string','null']` — the canonical\n // nullable form since draft-2026-08-19): members' TS union. Each\n // member re-enters with the single type so object/array members\n // keep their properties/items; `nullable` is folded in here (not in\n // the recursion) so it can't double-append. ──\n if (Array.isArray(schema.type)) {\n const { nullable: _nullable, ...rest } = schema;\n const members = [...new Set(schema.type)].map((member) =>\n jsonSchemaTypeToTs({ ...rest, type: member }),\n );\n const unique = [...new Set(members)];\n if (schema.nullable && !unique.includes('null')) unique.push('null');\n return unique.join(' | ');\n }\n\n let result: string;\n\n switch (schema.type) {\n case 'string':\n result = 'string';\n break;\n case 'number':\n case 'integer':\n result = 'number';\n break;\n case 'boolean':\n result = 'boolean';\n break;\n case 'null':\n return 'null';\n\n case 'array': {\n if (schema.items) {\n const itemType = jsonSchemaTypeToTs(schema.items);\n // Use Array<T> for complex object types, T[] for simple.\n // `items.type` may be a type SET — treat any set containing\n // 'object' like the single-string form.\n const itemsDeclareObject = Array.isArray(schema.items.type)\n ? schema.items.type.includes('object')\n : schema.items.type === 'object';\n result = (itemsDeclareObject && schema.items.properties)\n ? `Array<${itemType}>`\n : (itemType.includes('|') ? `(${itemType})[]` : `${itemType}[]`);\n } else {\n result = 'unknown[]';\n }\n break;\n }\n\n case 'object': {\n if (schema.properties) {\n const required = schema.required ?? [];\n const fields = Object.entries(schema.properties)\n .map(([key, prop]) => {\n const opt = !required.includes(key);\n return `${key}${opt ? '?' : ''}: ${jsonSchemaTypeToTs(prop)}`;\n })\n .join('; ');\n result = `{ ${fields} }`;\n } else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {\n result = `Record<string, ${jsonSchemaTypeToTs(schema.additionalProperties)}>`;\n } else {\n result = 'Record<string, unknown>';\n }\n break;\n }\n\n default:\n result = 'unknown';\n }\n\n // Apply nullable (OpenAPI 3.0 shorthand)\n if (schema.nullable && result !== 'unknown') {\n return `${result} | null`;\n }\n\n return result;\n}\n","// packages/ui-gen/src/check/contract-validation.ts\n//\n// Shared validation utilities for data-contract conformance —\n// deterministic tier-0 gate for `PropsSpec` / `StreamSpec` / `ActionSpec`\n// agreement between the LLM-emitted componentCode and the contract the\n// agent handed to `ggui_render`.\n//\n// Used by:\n// (1) Self-check soft gate in the coding agent\n// (`coding-agent/self-check.ts`) — surfaces mismatches as\n// structured violations for the LLM retry loop.\n// (2) Tier-0 hard gate in the evaluation pipeline — errors (severity\n// `error`) are blocking; warnings surface as advisory.\n// (3) Adapter tool-family wiring for multi-SDK generation runs.\n// (4) Benchmarks + LLM prompt construction — `jsonSchemaTypeToTs` +\n// `propsSpecToTypeScript` + `inferPropsSpecFromSampleData` are\n// pure helpers reused outside the check path. Re-exported here so\n// those callers don't need a separate import for the subpath.\n//\n// Deps are pure: `@ggui-ai/protocol` (public types) + `typescript`\n// (compiler API) + the in-package `jsonSchemaTypeToTs` primitive from\n// `../boilerplate/json-schema-ts.js`.\n\nimport type {\n PropsSpec,\n StreamSpec,\n ActionSpec,\n DataContract,\n JsonSchema,\n JsonValue,\n PropEntry,\n JsonObject,\n} from \"@ggui-ai/protocol\";\nimport ts from \"typescript\";\n\n// Re-export the pure JSON-Schema → TypeScript-type converter from the\n// in-package `boilerplate/` primitive, so consumers of the tier-0 check\n// surface (self-check, tiers, benchmarks, prompts, adapters) import a\n// single symbol from a single subpath.\nexport { jsonSchemaTypeToTs } from \"../boilerplate/json-schema-ts.js\";\nimport { jsonSchemaTypeToTs } from \"../boilerplate/json-schema-ts.js\";\n\n// =============================================================================\n// Contract Issue\n// =============================================================================\n\nexport interface ContractIssue {\n severity: \"error\" | \"warning\";\n field: string;\n message: string;\n fix: string;\n}\n\n// =============================================================================\n// Props Interface Extraction (AST-based)\n// =============================================================================\n\ninterface ExtractedProp {\n name: string;\n type: string;\n optional: boolean;\n}\n\n/**\n * Extract field names and types from a TypeScript Props interface in source code.\n * Uses the TypeScript compiler API — handles nested types, generics, unions correctly.\n */\nexport function extractPropsInterface(code: string): ExtractedProp[] | null {\n const sf = ts.createSourceFile(\"component.tsx\", code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);\n const props: ExtractedProp[] = [];\n\n function visitMembers(members: ts.NodeArray<ts.TypeElement>): void {\n for (const member of members) {\n if (ts.isPropertySignature(member) && member.name) {\n const name = member.name.getText(sf);\n const type = member.type ? member.type.getText(sf) : \"unknown\";\n const optional = !!member.questionToken;\n props.push({ name, type, optional });\n }\n }\n }\n\n function visit(node: ts.Node): void {\n // interface Props { ... }\n if (ts.isInterfaceDeclaration(node) && node.name.text === \"Props\") {\n visitMembers(node.members);\n return;\n }\n // type Props = { ... }\n if (ts.isTypeAliasDeclaration(node) && node.name.text === \"Props\") {\n if (ts.isTypeLiteralNode(node.type)) {\n visitMembers(node.type.members);\n }\n return;\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return props.length > 0 ? props : null;\n}\n\n// =============================================================================\n// Contract Validation\n// =============================================================================\n\n/**\n * Compare extracted Props interface against a PropsSpec contract.\n * Returns issues: errors for missing required fields, warnings for type mismatches.\n */\nexport function validatePropsAgainstSchema(\n code: string,\n spec: PropsSpec,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n const extracted = extractPropsInterface(code);\n\n if (!extracted) {\n // Can't extract — not necessarily an error (might use inline types)\n return [];\n }\n\n const extractedMap = new Map(extracted.map((p) => [p.name, p]));\n\n for (const [propName, entry] of Object.entries(spec.properties)) {\n const extractedProp = extractedMap.get(propName);\n\n if (!extractedProp) {\n if (entry.required) {\n issues.push({\n severity: \"error\",\n field: propName,\n message: `Props interface is missing required field '${propName}' from the data contract`,\n fix: `Add \\`${propName}${entry.required ? \"\" : \"?\"}: ${jsonSchemaTypeToTs(entry.schema)}\\` to your Props interface`,\n });\n } else {\n issues.push({\n severity: \"warning\",\n field: propName,\n message: `Props interface is missing optional field '${propName}' from the data contract`,\n fix: `Consider adding \\`${propName}?: ${jsonSchemaTypeToTs(entry.schema)}\\` to your Props interface`,\n });\n }\n continue;\n }\n\n // Basic type compatibility check (only if we have type info)\n if (extractedProp.type !== \"unknown\") {\n const expectedTsType = jsonSchemaTypeToTs(entry.schema);\n if (!isTypeCompatible(extractedProp.type, expectedTsType, entry.schema)) {\n issues.push({\n severity: \"warning\",\n field: propName,\n message: `Field '${propName}' has type '${extractedProp.type}' but contract expects '${expectedTsType}'`,\n fix: `Change \\`${propName}\\` type to \\`${expectedTsType}\\``,\n });\n }\n }\n }\n\n return issues;\n}\n\n/**\n * Check if a TypeScript type string is compatible with a JSON Schema type.\n * Loose comparison — we only check the base type, not full structural equality.\n */\nfunction isTypeCompatible(tsType: string, expectedTsType: string, schema: JsonSchema): boolean {\n const normalized = tsType.replace(/\\s/g, \"\").toLowerCase();\n\n switch (schema.type) {\n case \"string\":\n return normalized.includes(\"string\");\n case \"number\":\n case \"integer\":\n return normalized.includes(\"number\");\n case \"boolean\":\n return normalized.includes(\"boolean\");\n case \"array\":\n return normalized.includes(\"[]\") || normalized.includes(\"array\");\n case \"object\":\n return ![\"string\", \"number\", \"boolean\"].some((t) => normalized === t);\n default:\n return true;\n }\n}\n\n// =============================================================================\n// JSON Schema → TypeScript Conversion (for LLM prompts)\n// =============================================================================\n\n// `jsonSchemaTypeToTs` lives in `@ggui-ai/ui-gen/boilerplate` and is\n// re-exported at the top of this file.\n\n/**\n * Convert a full PropsSpec to a TypeScript interface string for LLM prompt injection.\n * Includes required/optional markers and descriptions as comments.\n */\nexport function propsSpecToTypeScript(spec: PropsSpec, indent = 2): string {\n const pad = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const [propName, entry] of Object.entries(spec.properties)) {\n if (entry.description) {\n lines.push(`${pad}/** ${entry.description} */`);\n }\n const optional = !entry.required;\n const tsType = jsonSchemaTypeToTs(entry.schema);\n const defaultStr = entry.default !== undefined ? ` // default: ${JSON.stringify(entry.default)}` : \"\";\n lines.push(`${pad}${propName}${optional ? \"?\" : \"\"}: ${tsType};${defaultStr}`);\n // Include example as a comment so the LLM sees the exact data shape\n if (entry.example !== undefined) {\n const exampleStr = JSON.stringify(entry.example, null, 2)\n .split(\"\\n\")\n .map((l, i) => (i === 0 ? `${pad}// Example: ${l}` : `${pad}// ${l}`))\n .join(\"\\n\");\n lines.push(exampleStr);\n }\n }\n\n return `{\\n${lines.join(\"\\n\")}\\n}`;\n}\n\n// =============================================================================\n// StreamSpec Validation\n// =============================================================================\n\n/**\n * Validate that the generated source code properly handles stream events.\n * Requires useStream() wire hooks — legacy DOM event patterns are no longer accepted.\n */\nexport function validateStreamSpecConformance(\n code: string,\n spec: StreamSpec,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n\n const usesWireStream = code.includes(\"useStream\");\n\n if (!usesWireStream) {\n issues.push({\n severity: \"error\",\n field: \"__streamSpec__\",\n message: \"Component does not handle stream events — use useStream() from the boilerplate wire hooks\",\n fix: \"Use the useStream('eventName') hook from the boilerplate to receive real-time data from the agent\",\n });\n return issues;\n }\n\n // Check each declared channel is referenced in the code. `spec` is a\n // flat `Record<channelName, StreamChannelEntry>` — iterate directly.\n for (const [channelName, entry] of Object.entries(spec)) {\n if (!code.includes(`'${channelName}'`) && !code.includes(`\"${channelName}\"`)) {\n issues.push({\n severity: \"warning\",\n field: channelName,\n message: `StreamSpec declares channel '${channelName}' but component doesn't reference it`,\n fix: `Add useStream('${channelName}') to receive ${entry.description || channelName} events`,\n });\n }\n }\n\n return issues;\n}\n\n// =============================================================================\n// ActionSpec Validation\n// =============================================================================\n\n/**\n * Validate that the generated source code wires the declared actions.\n * Checks that action IDs are referenced via useAction() wire hooks, string literals, or prop callbacks.\n */\nexport function validateActionSpecConformance(\n code: string,\n spec: ActionSpec,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n\n // `spec` is a flat `Record<actionId, ActionEntry>` — iterate directly.\n for (const [actionId, entry] of Object.entries(spec)) {\n // Check the action ID or its label is referenced in the code\n const idReferenced = code.includes(`'${actionId}'`) || code.includes(`\"${actionId}\"`);\n const labelReferenced = code.includes(entry.label);\n const callbackName = `on${actionId.charAt(0).toUpperCase()}${actionId.slice(1)}`;\n const callbackReferenced = code.includes(callbackName);\n\n if (!idReferenced && !labelReferenced && !callbackReferenced) {\n issues.push({\n severity: \"error\",\n field: actionId,\n message: `ActionSpec declares action '${actionId}' (\"${entry.label}\") but component doesn't wire it`,\n fix: `Use the useAction('${actionId}') hook from the boilerplate and wire it to a button or form submit`,\n });\n }\n }\n\n return issues;\n}\n\n// =============================================================================\n// Unified Contract Validation\n// =============================================================================\n\n/**\n * Validate all contract (props, stream, actions) against the source code.\n * Returns combined issues from all three validations.\n */\nexport function validateAllContracts(\n code: string,\n contract: DataContract,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n\n if (contract.propsSpec) {\n issues.push(...validatePropsAgainstSchema(code, contract.propsSpec));\n }\n\n if (contract.streamSpec) {\n issues.push(...validateStreamSpecConformance(code, contract.streamSpec));\n }\n\n if (contract.actionSpec) {\n issues.push(...validateActionSpecConformance(code, contract.actionSpec));\n }\n\n return issues;\n}\n\n// =============================================================================\n// Sample Data → PropsSpec Inference (backward compat)\n// =============================================================================\n\n/**\n * Infer a PropsSpec from sample data.\n * Convenience utility for migration and for agents that pass sample data instead of schemas.\n * All fields are marked as required (can't distinguish required/optional from data alone).\n */\nexport function inferPropsSpecFromSampleData(data: JsonObject): PropsSpec {\n const properties: Record<string, PropEntry> = {};\n\n for (const [key, value] of Object.entries(data)) {\n properties[key] = {\n schema: inferJsonSchema(value),\n required: true,\n example: value as JsonValue,\n };\n }\n\n return { properties };\n}\n\nfunction inferJsonSchema(value: unknown): JsonSchema {\n if (value === null || value === undefined) return { type: \"null\" };\n if (typeof value === \"string\") return { type: \"string\" };\n if (typeof value === \"number\") return { type: \"number\" };\n if (typeof value === \"boolean\") return { type: \"boolean\" };\n\n if (Array.isArray(value)) {\n if (value.length === 0) return { type: \"array\" };\n return {\n type: \"array\",\n items: inferJsonSchema(value[0]),\n };\n }\n\n if (typeof value === \"object\") {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n for (const [k, v] of Object.entries(value as JsonObject)) {\n properties[k] = inferJsonSchema(v);\n required.push(k);\n }\n return { type: \"object\", properties, required };\n }\n\n return { type: \"string\" };\n}\n","/**\n * The single source of truth for which packages LLM-generated\n * component code may import.\n *\n * Before this module the allowlist was duplicated — as `startsWith`\n * chains, as literal arrays, as hand-written error strings — across\n * `adapters/tools.ts`, `check/run-tier0.ts`, `check/type-checker.ts`\n * and `validation/component-detailed.ts`. The copies had already\n * drifted (one rejected `react-dom`, others allowed it). Every\n * import-validation site now derives from {@link isAllowedImport}.\n *\n * The design system is imported through ONE specifier — `@ggui-ai/design`\n * — never the `/primitives`, `/components`, `/compositions`, `/interact`\n * subpaths. The barrel re-exports every layer, so the generation LLM\n * never has to predict which subpath a component lives in. Subpaths\n * still resolve (the predicate allows any `@ggui-ai/design/...`), but\n * the prompt and catalog teach the barrel exclusively.\n */\n\n/**\n * Static package specifiers generated code may import. A subpath of\n * any base (`<base>/...`) is allowed too. Per-contract gadget packages\n * are dynamic — pass them to {@link isAllowedImport}.\n */\nimport { FORBIDDEN_IMPORT_SPECIFIERS } from '@ggui-ai/design/rendering';\n\nexport const ALLOWED_IMPORT_BASES = [\n 'react',\n 'react-dom',\n '@ggui-ai/design',\n '@ggui-ai/wire',\n '@ggui-ai/gadgets',\n] as const;\n\n/**\n * True if `specifier` is a package generated component code may import:\n * one of {@link ALLOWED_IMPORT_BASES} (or a subpath of one), or a\n * contract-declared gadget package — and never one of the design package's\n * `FORBIDDEN_IMPORT_SPECIFIERS` (ggui#843: `@ggui-ai/wire/internal` is the\n * writer side of the wire; the load-time rewriter refuses it from the same\n * list, so the two gates cannot drift apart).\n */\nexport function isAllowedImport(\n specifier: string,\n gadgetPackages?: ReadonlySet<string>,\n): boolean {\n if (FORBIDDEN_IMPORT_SPECIFIERS.includes(specifier)) return false;\n for (const base of ALLOWED_IMPORT_BASES) {\n if (specifier === base || specifier.startsWith(`${base}/`)) return true;\n }\n return gadgetPackages?.has(specifier) ?? false;\n}\n\n/**\n * Human-readable allowed-import list for error messages shown to the\n * generation LLM.\n */\nexport function describeAllowedImports(): string {\n return 'react, @ggui-ai/design, @ggui-ai/wire, @ggui-ai/gadgets, or a gadget package declared on the contract — never @ggui-ai/wire/internal (the writer side of the wire; components read useRender().isConnected)';\n}\n","// packages/ui-gen/src/check/type-checker.ts\n//\n// TypeScript type-checker for LLM-generated UI components. Uses the\n// TypeScript compiler API with a virtual filesystem to type-check TSX\n// code against React types and `@ggui-ai/design` primitives, giving\n// the LLM familiar TS error feedback without writing anything to disk.\n//\n// The checker builds a virtual filesystem seeded with `typescript/lib`,\n// `@types/react`, `@ggui-ai/design/dist`, and `@ggui-ai/wire/dist`\n// `.d.ts` content, then drives `ts.createProgram` against a synthetic\n// `Component.tsx`. Exposed on `@ggui-ai/ui-gen/check` so\n// `createUiGenerator` runs the same tier-0 gate as the hosted\n// generation path.\n//\n// Path-resolution note: the three workspace-rooted lookups —\n// `.pnpm/@types+react@*`, `packages/design/dist`, and\n// `packages/wire/dist` — are anchored relative to this file. tsup\n// bundles `src/check/index.ts` (splitting: false) into a flat\n// `dist/check/index.js`, so the src and dist locations sit at the same\n// depth and both resolve correctly. `typescript/lib/typescript.js`\n// keeps using `createRequire(import.meta.url).resolve` —\n// position-independent, so no change.\n//\n// Used by:\n// (1) Tier-0 `type_check` — blocking errors (see BLOCKING_CODES)\n// map to PRODUCTION_FAILED; non-blocking TS diagnostics surface\n// as warnings so the LLM can iterate on non-crash-risk findings\n// without stalling the harness.\n// (2) The `self_check` tool — called from generator SDKs (Anthropic /\n// OpenAI / Google) to give the LLM TS feedback mid-generation.\n// (3) The tier-0 orchestrator `runTier0Checks` — runs in parallel\n// with the wire-preservation + lint checks under the same tier\n// budget.\n//\n// Design notes that motivate non-obvious choices:\n// - Classic React JSX mode (`ts.JsxEmit.React`). The synthetic\n// prefix (see SYNTHETIC_PREFIX) supplies `import React from\n// 'react'` for the classic JSX factory PLUS a self-contained\n// global `JSX` namespace. `@types/react` v19 removed the global\n// `JSX` namespace that classic mode resolves intrinsic elements +\n// the `key`/`ref` carve-out through; without the shim, `<div>`\n// degrades to `any` and every typed component falsely rejects the\n// intrinsic `key` prop. Automatic mode was tried but its\n// `react/jsx-runtime` resolution does not survive the VFS.\n// - `strict: false` + `strictNullChecks: true`: we want the runtime\n// crash classes (`undefined.foo()`, `null.bar`) to surface as\n// blocking, but not the optional-chaining / exhaustive-check\n// noise that full `strict` would emit on LLM code.\n// - `types: []`: prevents the VFS from auto-pulling every\n// `@types/*` package that happens to be hoisted — only react and\n// the design/wire dist types should be reachable, matching the\n// forbidden-import policy enforced by `react-linter` elsewhere.\n// - TS2307 (\"Cannot find module\") is deliberately NOT blocking —\n// Lambda bundles code without type declarations, so the VFS can't\n// see every package that may exist at runtime. Forbidden imports\n// are caught by `runSelfChecks` regex instead.\n\nimport ts from 'typescript';\nimport fs from 'fs';\nimport path from 'path';\nimport { createRequire } from 'module';\nimport { describeAllowedImports } from '../validation/allowed-imports.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TypeCheckDiagnostic {\n code: number;\n line: number;\n message: string;\n fix: string;\n}\n\nexport interface TypeCheckResult {\n errors: TypeCheckDiagnostic[]; // Blocking\n warnings: TypeCheckDiagnostic[]; // Non-blocking\n}\n\n// ---------------------------------------------------------------------------\n// Blocking error codes — these would break at runtime\n// ---------------------------------------------------------------------------\n\nconst BLOCKING_CODES = new Set([\n 2304, // Cannot find name\n // 2307 (Cannot find module) is NOT blocking — Lambda bundles code without\n // type declarations, so the VFS can't resolve react/@ggui-ai/design.\n // Forbidden imports are caught by runSelfChecks regex instead.\n 2305, // Module has no exported member\n 2322, // Type not assignable\n 2339, // Property does not exist on type\n 2741, // Missing required property\n 2769, // No overload matches this call\n 17004, // Cannot use JSX unless '--jsx' flag\n 18047, // 'X' is possibly 'null' — causes runtime crash\n 18048, // 'X' is possibly 'undefined' — causes runtime crash\n]);\n\n// ---------------------------------------------------------------------------\n// Fix suggestions per error code\n// ---------------------------------------------------------------------------\n\nfunction generateFix(code: number, message?: string, sourceLine?: string): string {\n // Source-line hint: when the failing line is short and self-contained,\n // appending it gives the LLM a precise target. Skip for very long lines\n // (>140 chars — usually multi-prop JSX where the line itself is the\n // diagnostic) since they bloat the violation envelope without helping.\n const sourceHint =\n sourceLine && sourceLine.length > 0 && sourceLine.length <= 140\n ? ` Offending line: \\`${sourceLine}\\``\n : '';\n\n // Detect event handler on non-interactive primitive\n if ((code === 2322 || code === 2339) && message && /onClick|onDoubleClick|onMouseEnter|onMouseLeave|onPress/.test(message)) {\n return `This structural primitive has no event handlers of its own — add the trait as a PROP: as={Clickable} (then onClick works), imported from @ggui-ai/design. Do NOT wrap it in <Clickable>…</Clickable>; as is a prop, not a wrapper element.${sourceHint}`;\n }\n\n // Detect underscore-prefix-on-prop trap: `Property '_X' does not exist`.\n // LLM saw an unused-var warning on `X` and tried to silence it by renaming\n // the destructure to `_X`, breaking prop access. Steer back.\n if (code === 2339 && message && /Property '_[a-zA-Z]/.test(message)) {\n return `You renamed a prop with a leading underscore to silence \\`no-unused-vars\\`, but the prop on \\`Props\\` doesn't have that prefix. Restore the original name; better, don't destructure props you won't render — access them via \\`props.fieldName\\` only when needed.${sourceHint}`;\n }\n\n // Detect \"Cannot find name\" for destructured props\n if (code === 2304 && message && !message.includes('module') && !message.includes('import')) {\n return `This name is not defined in scope. Either you destructured props (use \\`props.fieldName\\` directly instead) OR you removed a helper declaration in this patch but kept a JSX/expression reference to it. Read your full patch and either restore the declaration or remove the reference.${sourceHint}`;\n }\n\n // Detect \"unknown is not assignable to ReactNode\"\n if ((code === 2322 || code === 2769) && message && /unknown.*ReactNode|ReactNode.*unknown/.test(message)) {\n return `This value has type 'unknown' and cannot be rendered in JSX. Cast it: String(value) or add a type annotation.${sourceHint}`;\n }\n\n switch (code) {\n case 2307:\n return `Only these imports are allowed: ${describeAllowedImports()}${sourceHint}`;\n case 2322:\n case 2769:\n return `Type mismatch on this expression. Check the offending line below — the prop name in JSX is what TypeScript is rejecting; the message tells you the expected type.${sourceHint}`;\n case 2339:\n return `This prop doesn't exist on this component — check the available props on the component's interface (visible at the top of the file, or in the design-system reference).${sourceHint}`;\n case 2305:\n return `This name is not defined. Check your imports and variable declarations.${sourceHint}`;\n case 2741:\n return `A required prop is missing. Check the component's Props interface.${sourceHint}`;\n case 18047:\n case 18048:\n return `This value might be null/undefined. Every dereference on the same nullable still needs \\`?.\\` — \\`x?.foo && x?.bar\\`, NOT \\`x?.foo && x.bar\\`. Or hoist: \\`const v = x; if (!v) return null;\\` then access \\`v.foo\\`/\\`v.bar\\` unguarded.${sourceHint}`;\n default:\n return `Review the TypeScript error and fix the type issue.${sourceHint}`;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Virtual Filesystem — lazy singleton\n// ---------------------------------------------------------------------------\n\ninterface VfsEntry {\n content: string;\n sourceFile: ts.SourceFile;\n}\n\nlet vfsCache: Map<string, VfsEntry> | null = null;\n\nfunction parseAndStore(\n vfs: Map<string, VfsEntry>,\n virtualPath: string,\n content: string,\n): void {\n const sourceFile = ts.createSourceFile(\n virtualPath,\n content,\n ts.ScriptTarget.ES2020,\n true,\n virtualPath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n vfs.set(virtualPath, { content, sourceFile });\n}\n\n/**\n * Recursively walk a directory and return all file paths matching a filter.\n */\nfunction walkDir(dir: string, filter: (f: string) => boolean): string[] {\n const results: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...walkDir(full, filter));\n } else if (filter(full)) {\n results.push(full);\n }\n }\n return results;\n}\n\n/**\n * Resolve `@types/react`'s root directory through Node's module\n * resolution. Position-independent — walks the consumer's node_modules\n * chain. Works in monorepo (where the type package is hoisted under\n * `<root>/node_modules/.pnpm/@types+react@*`) and in standalone\n * `packages/`-only installs (e.g. the projected public OSS repo where\n * the `packages/` prefix is stripped, so a hardcoded `../../../..`\n * walk lands in the wrong place).\n */\nfunction findReactTypesDir(): string | null {\n try {\n // `@types/react` doesn't expose `package.json` as a public subpath,\n // so resolve via the always-present `index.d.ts`.\n const indexDts = createRequire(import.meta.url).resolve('@types/react/index.d.ts');\n return path.dirname(indexDts);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a workspace package's `dist/` directory through Node's\n * module resolution. Like `findReactTypesDir`, this works in both\n * monorepo (where the package is hoisted/symlinked) and standalone\n * installs — no relative-path math required.\n */\nfunction findPackageDistDir(pkg: string): string | null {\n try {\n const pkgJson = createRequire(import.meta.url).resolve(`${pkg}/package.json`);\n const dist = path.join(path.dirname(pkgJson), 'dist');\n return fs.existsSync(dist) ? dist : null;\n } catch {\n return null;\n }\n}\n\nasync function loadVfs(): Promise<Map<string, VfsEntry>> {\n if (vfsCache) return vfsCache;\n\n const vfs = new Map<string, VfsEntry>();\n\n // ---- 1. TypeScript lib files ----\n // `createRequire(import.meta.url).resolve('typescript/lib/typescript.js')`\n // is position-independent — it walks the consumer's node_modules chain,\n // so this lookup works identically from core/, packages/ui-gen/, and any\n // future host package.\n const require_ = createRequire(import.meta.url);\n const tsDir = path.dirname(require_.resolve('typescript/lib/typescript.js'));\n const libFiles = fs.readdirSync(tsDir).filter((f) => /^lib\\..*\\.d\\.ts$/.test(f));\n for (const file of libFiles) {\n const content = fs.readFileSync(path.join(tsDir, file), 'utf-8');\n parseAndStore(vfs, file, content);\n }\n\n // ---- 2. React types ----\n // Resolved through `createRequire(import.meta.url).resolve('@types/\n // react/index.d.ts')` — position-independent. Works the same in\n // monorepo (hoisted to root) and in standalone `packages/`-only\n // installs (the projected public OSS repo strips the `packages/`\n // prefix, so a hardcoded `../../../..` walk would miss).\n const reactDir = findReactTypesDir();\n if (reactDir) {\n const reactDts = fs.readdirSync(reactDir).filter((f) => f.endsWith('.d.ts'));\n for (const file of reactDts) {\n const content = fs.readFileSync(path.join(reactDir, file), 'utf-8');\n parseAndStore(vfs, `node_modules/@types/react/${file}`, content);\n }\n }\n\n // ---- 3. Design system types ----\n const designDist = findPackageDistDir('@ggui-ai/design');\n if (designDist) {\n const dtsFiles = walkDir(designDist, (f) => f.endsWith('.d.ts') && !f.endsWith('.d.ts.map'));\n for (const file of dtsFiles) {\n const rel = path.relative(designDist, file);\n const content = fs.readFileSync(file, 'utf-8');\n parseAndStore(vfs, `node_modules/@ggui-ai/design/${rel}`, content);\n }\n }\n\n // ---- 4. Wire module types ----\n const wireDist = findPackageDistDir('@ggui-ai/wire');\n if (wireDist) {\n const dtsFiles = walkDir(wireDist, (f) => f.endsWith('.d.ts') && !f.endsWith('.d.ts.map'));\n for (const file of dtsFiles) {\n const rel = path.relative(wireDist, file);\n const content = fs.readFileSync(file, 'utf-8');\n parseAndStore(vfs, `node_modules/@ggui-ai/wire/${rel}`, content);\n }\n }\n\n // ---- 5. Gadgets types ----\n // Generated component code direct-imports standard-library gadget\n // hooks — `import { useGeolocation } from '@ggui-ai/gadgets'`.\n // Loading the `@ggui-ai/gadgets` package's shipped `.d.ts` into the\n // VFS makes those bare-named imports resolve against the real hook\n // declarations (named option/return types preserved). The standard\n // gadget hooks are plain named exports the resolver finds directly.\n const clientLibsDist = findPackageDistDir('@ggui-ai/gadgets');\n if (clientLibsDist) {\n const dtsFiles = walkDir(\n clientLibsDist,\n (f) => f.endsWith('.d.ts') && !f.endsWith('.d.ts.map'),\n );\n for (const file of dtsFiles) {\n const rel = path.relative(clientLibsDist, file);\n const content = fs.readFileSync(file, 'utf-8');\n parseAndStore(vfs, `node_modules/@ggui-ai/gadgets/${rel}`, content);\n }\n }\n\n vfsCache = vfs;\n return vfs;\n}\n\n// ---------------------------------------------------------------------------\n// Module resolution helper\n// ---------------------------------------------------------------------------\n\n/**\n * Try to resolve a relative import within the VFS.\n * Given `containingFile` (e.g. `node_modules/@ggui-ai/design/primitives/index.d.ts`)\n * and `importPath` (e.g. `./Card` or, as every published declaration says\n * since 0.15.0, `./Card.js`), try:\n * - <resolved>.d.ts\n * - <resolved>/index.d.ts\n * - <resolved>.ts\n * A `.js` / `.mjs` / `.cjs` extension on the specifier is the ESM\n * convention for \"the module that compiles to this file\" — TypeScript's\n * NodeNext maps `./Card.js` to `./Card.d.ts`, and so does this: the\n * extension is stripped before the candidates are tried. Without that, a\n * `.js`-suffixed re-export resolved to nothing, the imported names typed\n * as `any`, and the checker reported zero errors on code it must reject\n * (ggui 0.15.0 publish-gate, type-checker.test.ts).\n */\nfunction resolveRelativeInVfs(\n vfs: Map<string, VfsEntry>,\n containingFile: string,\n importPath: string,\n): string | undefined {\n // Strip leading '/' from containingFile — TS may prepend getCurrentDirectory()\n const normalized = containingFile.startsWith('/') ? containingFile.slice(1) : containingFile;\n const dir = path.posix.dirname(normalized);\n // `./x.js` (`.mjs`, `.cjs`) names the declaration `./x.d.ts` — strip it.\n const specifier = importPath.replace(/\\.(?:m|c)?js$/, '');\n const resolved = path.posix.normalize(`${dir}/${specifier}`);\n\n // Try .d.ts extension\n const withDts = `${resolved}.d.ts`;\n if (vfs.has(withDts)) return withDts;\n\n // Try /index.d.ts\n const withIndexDts = `${resolved}/index.d.ts`;\n if (vfs.has(withIndexDts)) return withIndexDts;\n\n // Try .ts extension\n const withTs = `${resolved}.ts`;\n if (vfs.has(withTs)) return withTs;\n\n // Might already be the exact path\n if (vfs.has(resolved)) return resolved;\n\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// CompilerHost factory\n// ---------------------------------------------------------------------------\n\nconst COMPILER_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ES2020,\n module: ts.ModuleKind.ESNext,\n // Classic React JSX mode. The synthetic prefix (SYNTHETIC_PREFIX)\n // supplies `import React from 'react'` plus a `declare global` JSX\n // namespace shim: `@types/react` v19 removed the *global* `JSX`\n // namespace (it lives at `React.JSX` now), which classic mode needs\n // for `JSX.IntrinsicElements` and the `key`/`ref` carve-out. Without\n // the shim, `<div>` degrades to `any` and every typed component\n // falsely rejects the intrinsic `key` prop.\n jsx: ts.JsxEmit.React,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n strict: false,\n strictNullChecks: true, // Catch undefined.foo() errors that cause runtime crashes\n noEmit: true,\n skipLibCheck: true,\n noImplicitAny: true,\n types: [],\n esModuleInterop: true,\n};\n\n/**\n * Normalize a path that TS's internal module resolution might generate.\n * Since getCurrentDirectory() returns '/', TS will probe paths like\n * '/node_modules/@types/react/jsx-runtime.d.ts'. We strip the leading\n * '/' to match our VFS keys.\n */\nfunction normalizeVfsPath(f: string): string | null {\n if (f.startsWith('/')) {\n return f.slice(1);\n }\n return null;\n}\n\n/**\n * Core module resolution logic shared between resolveModuleNameLiterals\n * (for user imports) and resolveModuleNames (for TS-internal imports\n * like jsxImportSource).\n */\nfunction resolveModuleName(\n vfs: Map<string, VfsEntry>,\n name: string,\n containingFile: string,\n): ts.ResolvedModuleWithFailedLookupLocations {\n // React core\n if (name === 'react') {\n return resolved('node_modules/@types/react/index.d.ts');\n }\n if (name === 'react/jsx-runtime') {\n return resolved('node_modules/@types/react/jsx-runtime.d.ts');\n }\n if (name === 'react/jsx-dev-runtime') {\n const p = 'node_modules/@types/react/jsx-dev-runtime.d.ts';\n if (vfs.has(p)) return resolved(p);\n return resolved('node_modules/@types/react/jsx-runtime.d.ts');\n }\n\n // @ggui-ai/design sub-paths\n const designPrefix = '@ggui-ai/design/';\n if (name.startsWith(designPrefix)) {\n const subpath = name.slice(designPrefix.length);\n const indexPath = `node_modules/@ggui-ai/design/${subpath}/index.d.ts`;\n if (vfs.has(indexPath)) return resolved(indexPath);\n const directPath = `node_modules/@ggui-ai/design/${subpath}.d.ts`;\n if (vfs.has(directPath)) return resolved(directPath);\n }\n\n // @ggui-ai/design root\n if (name === '@ggui-ai/design') {\n return resolved('node_modules/@ggui-ai/design/index.d.ts');\n }\n\n // @ggui-ai/wire\n if (name === '@ggui-ai/wire') {\n return resolved('node_modules/@ggui-ai/wire/index.d.ts');\n }\n\n // @ggui-ai/gadgets — the STDLIB gadget package. Generated\n // code direct-imports the seven STDLIB hooks (`useGeolocation`, …)\n // as plain named exports from this specifier. The shipped `.d.ts`\n // (loaded into the VFS above) carries their real declarations.\n if (name === '@ggui-ai/gadgets') {\n return resolved('node_modules/@ggui-ai/gadgets/index.d.ts');\n }\n\n // Relative imports — resolve within VFS\n if (name.startsWith('./') || name.startsWith('../')) {\n const resolvedPath = resolveRelativeInVfs(vfs, containingFile, name);\n if (resolvedPath) return resolved(resolvedPath);\n }\n\n // Third-party gadget wrapper packages. The render handler fetches each\n // non-stdlib gadget's `.d.ts` and `typecheck` overlays it at\n // `node_modules/<package>/index.d.ts`. A generated direct import\n // `import { useX } from '<package>'` resolves through this\n // bare-specifier branch against the overlaid `.d.ts` — named\n // option/return types preserved instead of collapsing to `any`.\n // Generic VFS lookup — no per-package allow-list.\n const bareIndex = `node_modules/${name}/index.d.ts`;\n if (vfs.has(bareIndex)) return resolved(bareIndex);\n\n // Unknown module\n return { resolvedModule: undefined };\n}\n\nfunction createVfsHost(\n vfs: Map<string, VfsEntry>,\n componentCode: string,\n): ts.CompilerHost {\n // Create fresh source file for the user component\n const componentFile = ts.createSourceFile(\n 'Component.tsx',\n componentCode,\n ts.ScriptTarget.ES2020,\n true,\n ts.ScriptKind.TSX,\n );\n\n const host: ts.CompilerHost = {\n getSourceFile(fileName: string) {\n if (fileName === 'Component.tsx') return componentFile;\n const entry = vfs.get(fileName);\n if (entry) return entry.sourceFile;\n // Try normalized path (strip leading '/')\n const normalized = normalizeVfsPath(fileName);\n if (normalized) return vfs.get(normalized)?.sourceFile;\n return undefined;\n },\n getDefaultLibFileName() {\n return 'lib.es2020.full.d.ts';\n },\n writeFile() {\n // no-op\n },\n getCurrentDirectory() {\n return '/';\n },\n getCanonicalFileName(f: string) {\n return f;\n },\n useCaseSensitiveFileNames() {\n return true;\n },\n getNewLine() {\n return '\\n';\n },\n fileExists(f: string) {\n if (f === 'Component.tsx' || vfs.has(f)) return true;\n // Normalize bare-specifier lookups that TS's internal resolver\n // turns into relative-looking paths from getCurrentDirectory '/'.\n const normalized = normalizeVfsPath(f);\n if (normalized && vfs.has(normalized)) return true;\n return false;\n },\n readFile(f: string) {\n if (f === 'Component.tsx') return componentCode;\n const direct = vfs.get(f);\n if (direct) return direct.content;\n const normalized = normalizeVfsPath(f);\n if (normalized) return vfs.get(normalized)?.content;\n return undefined;\n },\n resolveModuleNameLiterals(\n moduleLiterals: readonly ts.StringLiteralLike[],\n containingFile: string,\n ): readonly ts.ResolvedModuleWithFailedLookupLocations[] {\n return moduleLiterals.map((literal) =>\n resolveModuleName(vfs, literal.text, containingFile),\n );\n },\n };\n\n return host;\n}\n\nfunction resolved(resolvedFileName: string): ts.ResolvedModuleWithFailedLookupLocations {\n return {\n resolvedModule: {\n resolvedFileName,\n isExternalLibraryImport: true,\n extension: ts.Extension.Dts,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport async function typecheck(\n code: string,\n /**\n * A `package -> .d.ts content` map for third-party gadget wrappers.\n * The render handler parallel-fetches each non-stdlib gadget's `.d.ts`\n * (via `GadgetDescriptor.typesUrl` + SRI) and threads the result\n * here. Each entry is overlaid into the per-call VFS at\n * `node_modules/<package>/index.d.ts`. A generated direct import\n * `import { useX } from '<package>'` resolves through the\n * bare-specifier branch in `resolveModuleName` directly against this\n * overlaid entry — named option/return types preserved, so a\n * wrong-typed hook call surfaces a blocking TS error instead of\n * collapsing to `any`.\n *\n * Stdlib gadgets (`package: '@ggui-ai/gadgets'`) need no entry —\n * `@ggui-ai/gadgets` ships its `.d.ts` into the VFS unconditionally.\n * Omit for standard-library-only callers.\n */\n dtsMap?: Readonly<Record<string, string>>,\n): Promise<TypeCheckResult> {\n const vfs = await loadVfs();\n\n // Overlay each third-party gadget wrapper's `.d.ts` per-call without\n // mutating the cached VFS. The bare-specifier branch in\n // `resolveModuleName` resolves a generated `import { useX } from\n // '<package>'` against the overlaid entry, so the LLM sandbox sees\n // the wrapper's strict hook/component types (named option/return\n // shapes) rather than `any`. A third-party wrapper with no `dtsMap`\n // entry collapses to `any` (TS2307 is non-blocking) — degraded UX,\n // not a generation blocker; the fix is to thread `gadgetTypes`.\n // Stdlib (`@ggui-ai/gadgets`) ships its `.d.ts` unconditionally.\n const effectiveVfs = (() => {\n const dtsEntries = dtsMap !== undefined ? Object.entries(dtsMap) : [];\n if (dtsEntries.length === 0) {\n return vfs;\n }\n const overlay = new Map(vfs);\n for (const [pkg, content] of dtsEntries) {\n parseAndStore(overlay, `node_modules/${pkg}/index.d.ts`, content);\n }\n return overlay;\n })();\n\n // Prepend a synthetic prefix for classic JSX mode:\n // - `import React from 'react'` — the classic-mode JSX factory\n // (`React.createElement`) needs the React namespace in scope.\n // - a `declare global` JSX shim — `@types/react` v19 dropped the\n // GLOBAL `JSX` namespace (it is `React.JSX` now); classic mode\n // resolves intrinsic elements + the `key`/`ref` carve-out through\n // the global `JSX`, so without this `<div>` degrades to `any` and\n // every typed component falsely rejects the intrinsic `key` prop.\n // Mirrors `react/jsx-runtime`'s own JSX namespace, hoisted global.\n // All prefix lines are skipped from diagnostics via `lineOffset`.\n // `@types/react` v19 removed the GLOBAL `JSX` namespace (it lives at\n // `React.JSX` now — un-exported, not reliably reachable through the\n // VFS). Classic JSX mode resolves intrinsic elements + the `key`\n // carve-out through the global `JSX`, so declare a self-contained\n // one. Intrinsic elements are permissive (`[elem]: any`): the\n // type-checker's value is on the design components — which keep\n // their real prop types regardless of this namespace — and on\n // runtime-crash detection, not on deep typing of raw HTML (which the\n // generation prompt discourages anyway).\n const globalJsxShim =\n 'declare global { namespace JSX {' +\n ' type ElementType = string | ((props: any) => any) | (new (props: any) => any);' +\n ' interface Element { type: any; props: any; key: string | number | null; }' +\n ' interface ElementClass { render(): any; }' +\n ' interface ElementAttributesProperty { props: object; }' +\n ' interface ElementChildrenAttribute { children: object; }' +\n ' interface IntrinsicAttributes { key?: string | number | bigint | null; }' +\n ' interface IntrinsicClassAttributes<T> { ref?: any; }' +\n ' interface IntrinsicElements { [elem: string]: any; }' +\n ' } }\\n';\n const SYNTHETIC_PREFIX = \"import React from 'react';\\n\" + globalJsxShim;\n const prefixedCode = SYNTHETIC_PREFIX + code;\n const lineOffset = SYNTHETIC_PREFIX.split('\\n').length - 1;\n\n const host = createVfsHost(effectiveVfs, prefixedCode);\n\n const program = ts.createProgram(['Component.tsx'], COMPILER_OPTIONS, host);\n const diagnostics = ts.getPreEmitDiagnostics(program);\n\n const errors: TypeCheckDiagnostic[] = [];\n const warnings: TypeCheckDiagnostic[] = [];\n\n for (const diag of diagnostics) {\n // Only report diagnostics from the user's component file\n if (diag.file && diag.file.fileName !== 'Component.tsx') continue;\n // Global diagnostics (no file) — skip as they come from config\n if (!diag.file) continue;\n // Skip diagnostics on the synthetic import prefix line\n const diagLine = ts.getLineAndCharacterOfPosition(diag.file, diag.start ?? 0).line;\n if (diagLine < lineOffset) continue;\n\n const rawLine = diag.file\n ? ts.getLineAndCharacterOfPosition(diag.file, diag.start ?? 0).line + 1\n : 0;\n // Subtract the synthetic import line to get the user's original line number\n const line = Math.max(1, rawLine - lineOffset);\n const message = ts.flattenDiagnosticMessageText(diag.messageText, '\\n');\n const code_ = diag.code;\n\n // Extract the offending source line for the fix hint — without it\n // \"Type 'string' is not assignable to type 'number'\" is unactionable\n // because the LLM doesn't know which prop on which primitive. With\n // the line (\"<Icon size=\\\"md\\\" ...>\"), the LLM can target precisely.\n const sourceLines = diag.file.text.split('\\n');\n const sourceLine =\n rawLine >= 1 && rawLine <= sourceLines.length\n ? sourceLines[rawLine - 1]?.trim() ?? ''\n : '';\n\n const entry: TypeCheckDiagnostic = {\n code: code_,\n line,\n message,\n fix: generateFix(code_, message, sourceLine),\n };\n\n if (BLOCKING_CODES.has(code_)) {\n errors.push(entry);\n } else {\n warnings.push(entry);\n }\n }\n\n return { errors, warnings };\n}\n","// packages/ui-gen/src/check/react-linter.ts\n//\n// React linter — runs eslint-plugin-react-hooks via ESLint's Linter API.\n//\n// Exposed on `@ggui-ai/ui-gen/check` so `createUiGenerator` can invoke\n// the same lint gate as the hosted generation path.\n//\n// Dep surface: the linter imports the `Linter` / `Rule` types from\n// `eslint` at module load and lazily imports `@typescript-eslint/parser`,\n// `eslint-plugin-react-hooks`, and `eslint-plugin-react` inside\n// `getLinter()` — those four packages are runtime deps of this package.\n//\n// Catches Rules of Hooks violations that the TS type-checker misses:\n// - Hooks inside conditionals, loops, nested functions\n// - Hooks after early returns\n// - Missing/extra dependencies in useEffect/useMemo/useCallback\n//\n// Also carries the core ESLint `no-unused-vars` rule to\n// catch wire hooks the LLM declared but never consumed — an unused\n// `const submit = useAction('submit')` ships a subscription with no\n// render/callback wiring and will not actually drive the UI. Rule 14\n// (`wire_preservation`) in self-check.ts catches the DELETION case;\n// this lint pass catches the ABANDONMENT case. Together they seal\n// bidirectional contract completeness: contract -> code.\n//\n// Uses the lightweight Linter API (no file system, no config resolution).\n// Runs in parallel with the TS type-checker during self-check.\n\nimport { Linter, type Rule } from 'eslint';\n\nexport interface ReactLintDiagnostic {\n rule: string;\n line: number;\n message: string;\n fix: string;\n severity: 'error' | 'warning';\n}\n\n// Singleton Linter instance — reused across calls.\nlet linterInstance: Linter | null = null;\n\nasync function getLinter(): Promise<Linter> {\n if (!linterInstance) {\n linterInstance = new Linter();\n\n // Register @typescript-eslint/parser so ESLint can parse TS/TSX\n const tsParser = await import('@typescript-eslint/parser');\n linterInstance.defineParser('@typescript-eslint/parser', tsParser as Linter.Parser);\n\n // Register react-hooks plugin rules\n const reactHooksPlugin = await import('eslint-plugin-react-hooks');\n const hooksRules = reactHooksPlugin.default?.rules ?? reactHooksPlugin.rules;\n for (const [name, rule] of Object.entries(hooksRules)) {\n linterInstance.defineRule(`react-hooks/${name}`, rule as Rule.RuleModule);\n }\n\n // Register eslint-plugin-react rules\n const reactPlugin = await import('eslint-plugin-react');\n const reactRules = reactPlugin.default?.rules ?? reactPlugin.rules;\n for (const [name, rule] of Object.entries(reactRules)) {\n linterInstance.defineRule(`react/${name}`, rule as Rule.RuleModule);\n }\n }\n return linterInstance;\n}\n\n/**\n * Lint TSX code for React hooks violations.\n * Returns diagnostics with line numbers and fix suggestions.\n */\nexport async function lintReactHooks(code: string): Promise<ReactLintDiagnostic[]> {\n const linter = await getLinter();\n\n let messages: Linter.LintMessage[];\n try {\n const config: Linter.LegacyConfig = {\n parser: '@typescript-eslint/parser',\n parserOptions: {\n ecmaVersion: 2022,\n sourceType: 'module',\n ecmaFeatures: { jsx: true },\n },\n rules: {\n 'react-hooks/rules-of-hooks': 2,\n 'react-hooks/exhaustive-deps': 1,\n // React rules\n 'react/jsx-no-undef': 2, // undefined JSX components\n 'react/jsx-key': 1, // missing key in lists\n 'react/no-direct-mutation-state': 2, // direct state mutation\n // An unused `const submit = useAction('submit')` is a\n // dead contract wire. Narrow the rule to variable bindings we\n // care about: skip function args (LLMs legitimately omit unused\n // params), skip destructured `rest` collectors, respect a `_`-\n // prefix escape hatch for intentionally-ignored declarations,\n // and silence the caught-error slot (async error handling can\n // leave `catch (err)` unused at a boundary).\n 'no-unused-vars': [2, {\n vars: 'all',\n args: 'none',\n ignoreRestSiblings: true,\n varsIgnorePattern: '^_',\n caughtErrors: 'none',\n }],\n },\n settings: {\n react: { version: '19.0' },\n },\n };\n messages = linter.verify(code, config, { filename: 'component.tsx' });\n } catch {\n // Parser not available or code too malformed — skip\n return [];\n }\n\n const diagnostics: ReactLintDiagnostic[] = [];\n\n // Rules surfaced from the Linter run. `no-unused-vars` is the core\n // ESLint rule (no plugin prefix) — admitted alongside react-hooks/\n // and react/ rules so the no-unused-vars diagnostic reaches self_check.\n const ADMITTED_RULES = (id: string): boolean =>\n id.startsWith('react-hooks/') ||\n id.startsWith('react/') ||\n id === 'no-unused-vars';\n\n for (const msg of messages) {\n // Skip parser errors — caught by TS type-checker\n if (!msg.ruleId) continue;\n if (!ADMITTED_RULES(msg.ruleId)) continue;\n\n diagnostics.push({\n rule: msg.ruleId,\n line: msg.line,\n message: msg.message,\n fix: generateReactFix(msg.ruleId, msg.message),\n severity: resolveSeverity(msg, code),\n });\n }\n\n return diagnostics;\n}\n\n/**\n * Resolve the self-check severity of a lint diagnostic.\n *\n * Most rules map straight from ESLint severity (2 → error, 1 → warning).\n * `no-unused-vars` is special-cased: it stays a hard `error` ONLY when\n * the unused binding is a CONTRACT WIRE — `const x = useAction(...)` /\n * `useStream(...)` / `useGguiContext(...)` — because an abandoned wire\n * ships a dead subscription. For every other unused binding (a local\n * helper the LLM declared mid-generation, a `useMemo` result, a state-\n * read gadget binding) it is downgraded to `warning`.\n *\n * Rationale: a half-wired local helper is transient coding state, not a\n * defect — blocking tier-0 self-check on it forces a whole coding-turn\n * round-trip and is the single largest turn-thrash driver on the\n * benchmark (kanban/chat hit the turn cap oscillating on `'handleNext'\n * is assigned a value but never used`). The dead-CONTRACT-wire case it\n * was built to catch is independently enforced at\n * `error` severity by `validateActionSpecConformance` /\n * `validateStreamSpecConformance` in contract-validation.ts, so the\n * downgrade loses no correctness coverage. The diagnostic still surfaces\n * as a `warn` and is fed back to the LLM during eval rounds.\n */\nfunction resolveSeverity(\n msg: Linter.LintMessage,\n code: string,\n): 'error' | 'warning' {\n const base: 'error' | 'warning' = msg.severity === 2 ? 'error' : 'warning';\n if (msg.ruleId !== 'no-unused-vars' || base !== 'error') return base;\n const name = msg.message.match(/'([^']+)'/)?.[1];\n if (name === undefined) return 'warning';\n // Escape regex metacharacters in the identifier (defensive — JS\n // identifiers can't contain them, but the message text is untrusted).\n const safe = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Contract-wire binding. Two declaration shapes:\n // - direct: `const submit = useAction('submit')`\n // - destructured: `const [step, setStep] = useGguiContext<number>('step')`\n // The destructured form covers `useGguiContext` (and a defensive\n // `useStream`), where the unused name is one tuple slot.\n const directRe = new RegExp(\n `\\\\bconst\\\\s+${safe}\\\\s*=\\\\s*use(Action|Stream|GguiContext)\\\\s*[<(]`,\n );\n const destructuredRe = new RegExp(\n `\\\\bconst\\\\s+\\\\[[^\\\\]]*\\\\b${safe}\\\\b[^\\\\]]*\\\\]\\\\s*=\\\\s*use(Action|Stream|GguiContext)\\\\s*[<(]`,\n );\n return directRe.test(code) || destructuredRe.test(code)\n ? 'error'\n : 'warning';\n}\n\nfunction generateReactFix(ruleId: string, message: string): string {\n if (ruleId === 'react-hooks/rules-of-hooks') {\n if (message.includes('called conditionally')) {\n return 'Move this hook to the top level of the component, before any early returns or conditionals. Hooks must run in the same order every render.';\n }\n return 'Hooks can only be called at the top level of a React function component or custom hook. Move it out of any conditional, loop, nested function, or callback.';\n }\n if (ruleId === 'react-hooks/exhaustive-deps') {\n return 'Add the missing dependencies to the dependency array, or remove the array to run on every render.';\n }\n if (ruleId === 'react/jsx-no-undef') {\n const match = message.match(/'(\\w+)'/);\n const name = match?.[1] ?? 'Component';\n return `'${name}' is not defined. Import it from the design system or define it in the file.`;\n }\n if (ruleId === 'react/jsx-key') {\n return 'Add a unique \"key\" prop to each element rendered inside a .map() or iterator.';\n }\n if (ruleId === 'react/no-direct-mutation-state') {\n return 'Do not mutate state directly. Use setState or the setter from useState instead.';\n }\n if (ruleId === 'no-unused-vars') {\n // Extract the identifier name from the ESLint message shape:\n // \"'submit' is assigned a value but never used.\" (varsIgnorePattern also referenced)\n const match = message.match(/'([^']+)'/);\n const name = match?.[1] ?? 'variable';\n // Wire-hook shape — if the binding is an obvious contract wire, route\n // the LLM to the right remediation. Heuristic lives on the message\n // text because we only see the rule output here, not the AST.\n const isLikelyWireBinding = /\\bconst\\s+[A-Za-z_$][\\w$]*\\s*=\\s*use(Action|Stream)\\s*\\(/.test(message);\n if (isLikelyWireBinding || /^(submit|cancel|search|progress|snapshot)$/.test(name)) {\n return `'${name}' is declared but never used. If this binding came from a wire hook (useAction / useStream) or a clientCapabilities hook (useGeolocation / useCamera / etc. from @ggui-ai/gadgets), consume it somewhere in the component — render its value in JSX, bind it to a callback prop, or use it in an effect. A contract-declared hook without consumption is a dead wire.`;\n }\n return `'${name}' is declared but never used. Remove the declaration, or consume it somewhere in the component. Prefix with '_' (e.g. '_${name}') to mark it intentionally unused.`;\n }\n return 'Fix the React violation.';\n}\n","// packages/ui-gen/src/design-mode.ts\n//\n// The ONE definition of the `designMode` option and the rendering-canvas\n// vocabulary. Every triad surface (system prompt, boilerplate, tier-0\n// gate, axis checks, evaluator criteria) AND the visual evaluator import\n// these types from here — nothing re-declares the unions.\n//\n// - `constrained` (default) — today's triad: the component composes\n// from the `@ggui-ai/design` primitives, prop enums and spacing\n// scale, and tier-0 enforces the design vocabulary. Byte-identical\n// to the pre-`designMode` behaviour (pinned by\n// `design-mode.pin.test.ts`).\n// - `free` — the design vocabulary is relaxed: raw HTML elements,\n// inline styles and `<style>` blocks are allowed; the design package\n// is importable but optional. Every HARD contract stays: the data\n// contract via the boilerplate-typed wire hooks, the import\n// allowlist + security bans, the host envelope, the budgets, the\n// blueprint-reuse shape, and brand-bearing color via the closed\n// `--ggui-color-*` token manifest (no literals, no fallbacks).\n\nexport const DESIGN_MODES = [\"constrained\", \"free\"] as const;\n\nexport type DesignMode = (typeof DESIGN_MODES)[number];\n\nexport const DEFAULT_DESIGN_MODE: DesignMode = \"constrained\";\n\n// ─── Rendering canvas ───────────────────────────────────────────────────────\n//\n// ONE canvas vocabulary shared by the prompt input (the `free` prompt\n// TELLS the agent its canvas; the `constrained` prompt keeps its\n// shell/screen descriptors byte-for-byte) and the visual evaluator (one\n// screenshot + judge score per class at `CANVAS_VIEWPORTS[class]`).\n//\n// A class is derived from DISPLAY MODE + width, never from width alone:\n// an inline chat card is `xs-chat-card` whatever the host window\n// measures (the bubble, not the window, bounds the component); a\n// fullscreen-class surface follows its width through the three\n// breakpoints. `canvasForViewportWidth` is monotonic in width per\n// display mode (pinned by `design-mode.test.ts`).\n\nexport const CANVAS_CLASSES = [\n \"xs-chat-card\",\n \"mobile-fullscreen-small\",\n \"md\",\n \"lg\",\n \"xl\",\n] as const;\n\nexport type CanvasClass = (typeof CANVAS_CLASSES)[number];\n\nexport interface CanvasViewport {\n readonly width: number;\n readonly height: number;\n}\n\n/** The viewport (CSS px) each class is rendered + judged at. */\nexport const CANVAS_VIEWPORTS: Readonly<Record<CanvasClass, CanvasViewport>> = {\n \"xs-chat-card\": { width: 400, height: 640 },\n \"mobile-fullscreen-small\": { width: 390, height: 844 },\n md: { width: 768, height: 1024 },\n lg: { width: 1024, height: 768 },\n xl: { width: 1440, height: 900 },\n};\n\n/**\n * The two display modes the canvas derivation distinguishes. `inline`\n * is the chat card (MCP Apps `inline` display mode / the `chat` shell);\n * `fullscreen` is every surface the component owns edge to edge or as\n * a panel (`fullscreen`, `pip`, the `spatial` and `partial` shells) —\n * there the width decides the class.\n */\nexport type CanvasDisplayMode = \"inline\" | \"fullscreen\";\n\n/**\n * Map a shell name (`chat` / `fullscreen` / `spatial` / `partial`) or an\n * MCP Apps display mode (`inline` / `fullscreen` / `pip`) onto the\n * canvas display mode. Only `chat` and `inline` are the inline card;\n * everything else is width-governed.\n */\n/**\n * The display mode a JUDGE canvas stands for (ggui#1100): the inline chat\n * card is `xs-chat-card`; every other canvas is a surface the component\n * owns edge to edge, which the served runtime composes with `fit: 'fill'`\n * — so the judge must too, or it scores a picture the user never sees.\n */\nexport function displayModeForCanvas(canvas: CanvasClass): CanvasDisplayMode {\n return canvas === \"xs-chat-card\" ? \"inline\" : \"fullscreen\";\n}\n\nexport function canvasDisplayModeForShell(shell: string | undefined): CanvasDisplayMode {\n return shell === \"chat\" || shell === \"inline\" ? \"inline\" : \"fullscreen\";\n}\n\n/** Fullscreen-class breakpoints (inclusive lower bounds), CSS px. */\nexport const CANVAS_BREAKPOINTS = { md: 600, lg: 1024, xl: 1440 } as const;\n\n/**\n * Derive the canvas class from display mode + container width.\n *\n * inline → `xs-chat-card` at every width\n * fullscreen → width < 600 → `mobile-fullscreen-small`\n * 600 – 1023 → `md`\n * 1024 – 1439 → `lg`\n * ≥ 1440 → `xl`\n */\nexport function canvasForViewportWidth(mode: CanvasDisplayMode, width: number): CanvasClass {\n if (mode === \"inline\") return \"xs-chat-card\";\n if (width < CANVAS_BREAKPOINTS.md) return \"mobile-fullscreen-small\";\n if (width < CANVAS_BREAKPOINTS.lg) return \"md\";\n if (width < CANVAS_BREAKPOINTS.xl) return \"lg\";\n return \"xl\";\n}\n\n/**\n * Map today's shell × screen descriptors onto a canvas class when no\n * width is known. `chat` is always the inline card; `spatial` is a\n * ~600px floating panel (`md`); `fullscreen` follows the screen. Unknown\n * values fall back to `lg` (the widest common fullscreen), matching the\n * skeleton's `fullscreen` / `universal` defaults.\n */\nexport function canvasForRendering(\n shellType: string | undefined,\n screen: string | undefined,\n): CanvasClass {\n const shell = shellType ?? \"fullscreen\";\n if (canvasDisplayModeForShell(shell) === \"inline\") return \"xs-chat-card\";\n if (shell === \"spatial\") return \"md\";\n switch (screen ?? \"universal\") {\n case \"mobile\":\n return \"mobile-fullscreen-small\";\n case \"tablet\":\n return \"md\";\n default:\n return \"lg\";\n }\n}\n\nexport interface CanvasDescriptor {\n /** Short human label. */\n readonly label: string;\n /** Inclusive width range the component must look right across, CSS px. */\n readonly minWidthPx: number;\n readonly maxWidthPx: number;\n /** What the host draws around the component at this canvas. */\n readonly host: string;\n}\n\nexport const CANVAS_DESCRIPTORS: Readonly<Record<CanvasClass, CanvasDescriptor>> = {\n \"xs-chat-card\": {\n label: \"extra-small chat card\",\n minWidthPx: 320,\n maxWidthPx: 480,\n host: \"an inline card inside a chat message bubble — the host draws the card border, shadow and rounded corners; the component fills the bubble width and takes its natural height\",\n },\n \"mobile-fullscreen-small\": {\n label: \"small mobile fullscreen\",\n minWidthPx: 320,\n maxWidthPx: 599,\n host: \"a phone-sized viewport the component owns edge to edge — single column, touch targets at least 44px, the component manages its own scroll\",\n },\n md: {\n label: \"medium panel\",\n minWidthPx: 600,\n maxWidthPx: 1023,\n host: \"a tablet viewport or a floating panel (spatial / picture-in-picture) — one or two columns, medium density\",\n },\n lg: {\n label: \"large fullscreen\",\n minWidthPx: 1024,\n maxWidthPx: 1439,\n host: \"a desktop viewport the component owns edge to edge — multi-column layouts, hover states and pointer interactions are available\",\n },\n xl: {\n label: \"extra-large fullscreen\",\n minWidthPx: 1440,\n maxWidthPx: 1920,\n host: \"a wide desktop viewport the component owns edge to edge — cap content width or use the extra room deliberately; never stretch a single column across the whole width\",\n },\n};\n\n/**\n * The explicit sentence the `free` prompt renders for a canvas — the\n * agent is TOLD the canvas, it never guesses it.\n */\nexport function describeCanvas(canvas: CanvasClass): string {\n const d = CANVAS_DESCRIPTORS[canvas];\n return (\n `This component renders on the \\`${canvas}\\` canvas (${d.label}): ` +\n `${d.minWidthPx}–${d.maxWidthPx}px wide, ${d.host}. ` +\n `Design for the whole range — the host may size the iframe anywhere inside it, and the host owns the height: size to your content, never to the viewport.`\n );\n}\n","// The consumed-token names the generator may TEACH — the manifest minus the names a card may not\n// reference yet.\n//\n// A card is minted by one release and rendered by whichever runtime serves it: during a rolling\n// deploy, or after a rollback, that runtime can be the previous release, which neither declares\n// nor completes a key derived for the first time in this one. A bare `var(--new-key)` then\n// resolves to nothing — a `border` shorthand drops whole — and the no-fallback rule leaves the\n// card nothing to fall back on. So a new derived key ships in two steps: the renderers that\n// declare and complete it serve first (the design package's own primitives read it behind a\n// fallback), and the release AFTER takes it out of this set, in the same change as the prompt\n// guidance that teaches it.\n\nimport { consumedTokenManifest } from \"@ggui-ai/design/themes\";\n\n/**\n * Manifest names held back from every surface that teaches the model a name — the free prompt's\n * colour vocabulary and token reference, and the self-check's nearest-name suggestions. The\n * closed-set check still admits them: a card that references one is valid wherever this release\n * renders it.\n *\n * - ggui#1494 — the control edges (`controlOutline`, `controlAccentOutline`): derived and completed\n * from this release; taught from the next.\n */\nexport const NOT_YET_TAUGHT_TOKENS: ReadonlySet<string> = new Set([\n \"--ggui-color-controlAccentOutline\",\n \"--ggui-color-controlOutline\",\n]);\n\n/** The manifest as the model is taught it. */\nexport const taughtTokenManifest: readonly string[] = consumedTokenManifest.filter(\n (token) => !NOT_YET_TAUGHT_TOKENS.has(token),\n);\n","// Evaluation type vocabulary shared between the harness runtime and its\n// check/evaluator surfaces. This is the narrow contract layer — the\n// type language every harness leg is written against:\n//\n// - `EvalIssue` — the single issue shape everything produces.\n// - `EvalTier` / `EvalOutcome` / `EvalCategory` — the issue's axes.\n// - `Priority` — P0/P1/P2 ranking referenced by the retry formatter.\n// - `EvalResult` — aggregate shape a runner returns.\n// - `QualityMode` / `QualityConfig` / `DEFAULT_QUALITY_CONFIG` —\n// the quality-mode knob the adapter surface consumes.\n// - `priorityForIssue` / `isBlocked` / `getActionableIssues` — the\n// purely-typed helpers over the vocabulary.\n//\n// `EvalIssue` is referenced by `PatchFn`, `TierCheck`, `LLMEvaluator`,\n// and `RuntimeRenderCheck` in the harness types hub.\n\n// ─── Priority ──────────────────────────────────────────────────────────────\n// P0 = must (compile + complete), P1 = should (safety), P2 = nice (quality).\n// Single source of truth for the retry-formatter ranking.\n\nexport type Priority = \"P0\" | \"P1\" | \"P2\";\n\nimport type { VisionFinishReason } from '../harness/llm-router.js';\nimport type { GenerationRuntimeProbeOutcome, GenerationRuntimeProbeStatus } from \"@ggui-ai/mcp-server-core\";\nimport type { CanvasClass, DesignMode } from \"../design-mode.js\";\n\n// ─── Issue shape ───────────────────────────────────────────────────────────\n\nexport type EvalTier = 0 | 1 | 2;\nexport type EvalOutcome = \"fail\" | \"warn\" | \"pass\";\n\nexport type EvalCategory =\n | \"compile\"\n | \"security\"\n | \"contract\"\n | \"types\"\n | \"imports\"\n | \"tokens\" // tier 0\n | \"mode\" // tier 0 — per-mode deterministic\n | \"functionality\"\n | \"crash\" // tier 1\n | \"interactivity\"\n | \"accessibility\"\n | \"layout\"\n | \"loading\"\n | \"visual\"; // tier 2\n\nexport interface EvalIssue {\n tier: EvalTier;\n result: EvalOutcome;\n category: EvalCategory;\n /**\n * Priority tier — threaded through to the retry formatter so the LLM can\n * rank its next patch against the prompt's P0/P1/P2 priority schema.\n * Derived from (category, result) via {@link priorityForIssue} when not\n * explicitly set. Optional on construction; check-runners typically\n * populate it before returning.\n */\n priority?: Priority;\n subcategory?: string;\n severity?: \"critical\" | \"major\";\n description: string;\n fix: string;\n line?: number;\n /**\n * The visual leg's provenance (ggui#1545): `judge` (the model's finding) or `instrument` (a deterministic\n * measurement). Absent on every other leg's issues. `visualEvaluation.actOn` acts on `judge` only.\n */\n origin?: \"judge\" | \"instrument\";\n}\n\n/**\n * Runtime-render probe execution status — four-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\". ONE union: the\n * same values a generation's metadata reports (`GenerationRuntimeProbeStatus`\n * in `@ggui-ai/mcp-server-core`), declared there and named here.\n *\n * - `ran` — probe executed; its findings (possibly none) are\n * in the issue stream under `runtime:*` subcategories.\n * - `infra-skipped` — probe could NOT execute (environment failure:\n * happy-dom load, user-event document capture,\n * ESM/CJS interop). Carries ZERO probe evidence;\n * consumers MUST NOT count it as a pass.\n * - `not-applicable`— nothing to probe (no compiled code, no contract\n * surface, or no runtimeRender check configured).\n * - `timed-out` — probe started but did not finish inside its\n * wall-clock bound (ggui#1299). Carries ZERO\n * evidence about the component: on a contended\n * host an ordinary component crosses the bound.\n * Consumers MUST NOT count it as a pass, and MUST\n * NOT count it as a crash either. `elapsedMs` and\n * `hostLoad` say how long it ran and how busy the\n * host was, so a reader can tell the two cases apart.\n */\nexport type RuntimeProbeStatus = GenerationRuntimeProbeStatus;\n\n/**\n * The host's 1-minute load average at a probe's start and end, beside the\n * number of CPUs the process can use (ggui#1299). A load well above\n * `cores` means the probe competed for CPU; a wall-clock bound crossed\n * there says more about the host than about the component.\n */\nexport interface ProbeHostLoad {\n readonly start: number;\n readonly end: number;\n readonly cores: number;\n}\n\n/**\n * ggui#1398 — whether the controls the probe clicked showed they were\n * working once their action was pending. Report-only: it is read by the\n * benchmark and never counted into the probe's warnings or fed back to\n * the coding loop.\n */\nexport interface ProbePendingAffordance {\n /** Controls the pending phase marked pending: those whose click dispatched their action (click or submit wiring) and that were still in the page. `visible + missing.length === dispatched`. */\n readonly dispatched: number;\n /** Of those, how many visibly changed while pending (disabled, busy, text, or replaced). */\n readonly visible: number;\n /** The actions whose control did not visibly change, including one whose card threw while pending. */\n readonly missing: readonly string[];\n /** Actions whose control was no longer in the page when its turn came (the card replaced it, or blanked after a throw): never marked, not counted as dispatched. */\n readonly gone: readonly string[];\n}\n\n/**\n * The engine's own fields on a probe's meta, beside the outcome a\n * generation's metadata reports: why a probe did not finish, its render\n * time, the host's load around it. Present on every arm of\n * {@link RuntimeProbeMeta}; each is absent when the probe had nothing to\n * say about it.\n */\nexport interface RuntimeProbeMetaDetail {\n /** Populated for `infra-skipped` / `not-applicable` / `timed-out` — why the probe didn't finish. */\n readonly reason?: string;\n /** `ran` only: the check's own render time, inside `elapsedMs`. */\n readonly renderMs?: number;\n /** Host load around the probe, when it ran isolated (absent for an in-process probe). */\n readonly hostLoad?: ProbeHostLoad;\n /** Time the check waited for a probe slot before it started, ms; present only when > 0 (ggui#1380 C2b). */\n readonly queuedMs?: number;\n /**\n * `ran` only: the pending-affordance walk (ggui#1398). Absent when no\n * action walk ran, so \"no data\" and \"0 of 0\" read differently.\n */\n readonly pendingAffordance?: ProbePendingAffordance;\n}\n\n/**\n * Probe execution meta stamped onto an `EvalResult` at the exit-decision\n * points that invoke the probe. Absence of this field means the eval\n * path never reached a probe invocation at all — consumers treat that\n * the same as not-run, never as a pass.\n *\n * ONE union with the generation metadata's probe outcome\n * (`GenerationRuntimeProbeOutcome` in `@ggui-ai/mcp-server-core`, declared\n * there and carried here with {@link RuntimeProbeMetaDetail} on every arm),\n * so the round's stamp and the metadata's record cannot say different\n * things (ggui#1380):\n *\n * - `ran` + `verdict: 'pass'` — the probe executed and no check failed;\n * - `ran` + `verdict: 'fail'` — ANY check failed; `failChecks` lists the\n * distinct check kinds that did (`RenderCheckKind`, the engine's name\n * for the same union), never empty, in the order `RENDER_CHECK_KINDS`\n * declares them, parsed from the probe's own\n * `runtime:<check>[:<subject>]` issues;\n * - `timed-out` / `infra-skipped` / `not-applicable` — no verdict, and the\n * type carries none. `elapsedMs` (on every status that reached the\n * check) and `hostLoad` say how long it ran and how busy the host was.\n *\n * The verdict and the repair trigger are two different questions. The\n * verdict is `fail` on any failing check. The one repair turn a probe-only\n * round buys fires on a `render-no-throw` fail the engine recognises\n * (`isRecoverableRenderCrash`) and on nothing else: on the PROBE-ONLY round a\n * `fail` verdict whose checks are `prop-sensitivity`, `action-wiring` or any\n * other kind is recorded here and never fed back. The same meta is stamped on\n * the EVALUATION lane, where a `prop-sensitivity` fail buys that lane's own\n * contract-feedback round (ggui#1261, `FEEDBACK_PROBE_CHECKS`) — a different\n * turn under a different rule, not the repair turn.\n */\nexport type RuntimeProbeMeta = GenerationRuntimeProbeOutcome & RuntimeProbeMetaDetail;\n\n/**\n * The one repair turn a probe-only round buys (ggui#1380). A serving\n * deployment that wires the runtime probe and configures no evaluator runs\n * the probe once after the coding turns; a render crash the engine\n * recognises buys exactly one repair turn, then one re-probe. This records\n * what came of it:\n * - `compiled: false` — the repair turn's code did not pass self-check, so\n * no re-probe ran (there is no `after`) and the pre-repair card is the\n * one served;\n * - `compiled: true` — the re-probe ran and `after` is its whole meta:\n * its status, its verdict when it ran, and the checks that still fail.\n * Whether the crash class the turn was bought for is still there is\n * `after.verdict === 'fail' && after.failChecks.includes('render-no-throw')`.\n * The two arms are exclusive by type.\n */\nexport type RuntimeProbeRepair =\n | { readonly attempted: true; readonly compiled: false; readonly trigger?: never }\n | { readonly attempted: true; readonly compiled: true; readonly trigger: RuntimeProbeMeta };\n\n/**\n * Per-criterion execution status — three-valued so \"the criterion\n * silently produced no verdict\" is never conflated with \"the criterion\n * ran clean\", and neither is conflated with \"not evaluated by design\".\n * Same doctrine and vocabulary family as `RuntimeProbeStatus` above.\n *\n * - `ran` — the LLM call completed and returned a verdict\n * for this criterion; its findings (possibly\n * none) are in `issues`.\n * - `skipped` — the call errored or returned no tool call. The\n * criterion carries ZERO evidence; the evaluator\n * fail-opens it into `pass` to avoid blocking\n * generation on flaky LLM calls, so consumers\n * MUST consult this field before treating `pass`\n * membership as a verdict. Counts AGAINST\n * coverage.\n * - `not-applicable` — the evaluator was bypassed by design for this\n * cell (e.g. the same-image low-risk bypass:\n * axis checks clean, tier-1/2 never invoked).\n * `reason` names the bypass. Excluded from\n * coverage denominators — it is neither evidence\n * nor a silent absence.\n */\nexport type CriterionRunStatus = \"ran\" | \"skipped\" | \"not-applicable\";\n\n/** Coverage row for one evaluation criterion of one eval run. */\nexport interface CriterionCoverage {\n readonly criterion: string;\n readonly tier: 1 | 2;\n readonly status: CriterionRunStatus;\n /** Populated for `skipped` / `not-applicable` — why no verdict. */\n readonly reason?: string;\n}\n\n/**\n * Coverage of the screenshot JUDGE leg for one eval round (ggui#1221) — a\n * different surface from the `visual` CRITERION in `criteriaCoverage` (the\n * LLM evaluator's read of the source). `ran` = a frame was captured and\n * judged; `skipped` = the leg was configured but produced no verdict\n * (no browser, a launch or in-page failure, an unbundlable component, an\n * unparsable judge answer) with `reason` naming why; `not-applicable` =\n * the round had no visual leg configured. Before this row a skipped leg\n * left NO trace on the result — `{ issues: [] }` read exactly like a\n * clean run, and every bootstrap mint on a browserless runtime \"passed\"\n * its visual round that way.\n */\nexport interface VisualCoverage {\n readonly status: CriterionRunStatus;\n /** Populated for `skipped` / `not-applicable` — why no verdict. */\n readonly reason?: string;\n}\n\n/**\n * The static criteria `runLLMEvaluation` runs, in stamp order — the\n * ONE list both the evaluator's coverage stamp and the harness's\n * bypass stamp derive from, so the two can never disagree on the set.\n * Tier 1 = binary pass/fail gates; tier 2 = fail/warn/pass quality.\n */\nexport const LLM_EVAL_STATIC_CRITERIA: ReadonlyArray<{ readonly criterion: string; readonly tier: 1 | 2 }> = [\n { criterion: \"functionality\", tier: 1 },\n { criterion: \"crash\", tier: 1 },\n { criterion: \"interactivity\", tier: 2 },\n { criterion: \"accessibility\", tier: 2 },\n { criterion: \"layout\", tier: 2 },\n { criterion: \"loading\", tier: 2 },\n { criterion: \"visual\", tier: 2 },\n];\n\n/**\n * Coverage rows for a cell where the evaluator was BYPASSED BY DESIGN\n * (never invoked) — one `not-applicable` row per static criterion, all\n * carrying `reason`. Harness exits that skip tier-1/2 evaluation stamp\n * this so the cell is neither a silent absence (field missing) nor\n * evidence. Same shape contract as `runLLMEvaluation`'s stamp: always\n * every criterion. Lives here (not in llm-evaluator) because the bypass\n * exit runs before the evaluator module is lazily loaded.\n */\nexport function notApplicableCoverage(reason: string): CriterionCoverage[] {\n return LLM_EVAL_STATIC_CRITERIA.map(({ criterion, tier }) => ({\n criterion,\n tier,\n status: \"not-applicable\",\n reason,\n }));\n}\n\n/** One contract-feedback round (ggui#1261): what bought it, and the source it was fed back on. */\nexport interface ContractFeedbackRecord {\n /** The exit-probe issue subcategories that bought the round, e.g. `runtime:prop-sensitivity:currentUser`. */\n readonly firedOn: readonly string[];\n /** The component source as it stood when the model was told — the round's BEFORE. */\n readonly sourceBefore: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\n /**\n * Per-criterion coverage for this eval run — one row per static\n * criterion, ALWAYS all of them when present. Stamped by\n * `runLLMEvaluation` (`ran` / `skipped`) and by the harness on\n * evaluator-bypass exits (`not-applicable` + reason). The harness\n * carries it unchanged through every later re-stamp of this result.\n * Absent = coverage UNKNOWN (paths that predate the instrument, e.g.\n * `parseEvalResponse` replays) — never assume `ran`, never assume\n * bypass.\n */\n criteriaCoverage?: CriterionCoverage[];\n /**\n * Runtime-render probe execution meta. Stamped by the exit-decision\n * probe runner; absent on eval paths that never invoke the probe.\n */\n runtimeProbe?: RuntimeProbeMeta;\n /**\n * The probe-only round's repair record (ggui#1380) — present only when a\n * recoverable render crash bought the one repair turn. See\n * {@link RuntimeProbeRepair}. `runtimeProbe` beside it is the re-probe's\n * verdict when the repair compiled, else the pre-repair probe's.\n */\n runtimeProbeRepair?: RuntimeProbeRepair;\n /**\n * The contract-feedback round, when one fired this generation (ggui#1261):\n * which exit-probe findings bought it and the source as it stood when the\n * model was told. `runtimeProbe` and the `runtime:*` issues on this result\n * are the probe's verdict AFTER that round; `sourceBefore` beside the final\n * source is the round's before/after. Absent when no such round fired.\n */\n contractFeedback?: ContractFeedbackRecord;\n /**\n * Per-canvas visual verdicts. Stamped by the harness ONLY when the\n * visual leg ran with `visualEvaluation.canvases` set (arm-neutral —\n * the same judge in every design mode); absent on the single-shot\n * visual path and whenever the visual leg did not run. PNGs stay on\n * `runVisualEvaluation`'s own result (`VisualEvaluationResult.canvases[*].screenshotPng`),\n * never here — this object is serialized into reports.\n */\n visual?: VisualEvalSummary;\n /**\n * Whether the screenshot judge leg ran, was skipped (with the reason) or\n * was not configured — ALWAYS stamped by the harness's eval round\n * (ggui#1221), so a consumer can tell a clean visual run from a leg\n * that silently could not run. See {@link VisualCoverage}.\n */\n visualCoverage?: VisualCoverage;\n}\n\n/** One canvas's visual verdict, PNG-free — see `EvalResult.visual`. */\n/**\n * How one canvas's `score` was reached (ggui#1072): `k` vision calls on the\n * SAME captured frame, aggregated by `rule`. Always present — `k: 1` ⇒\n * `samples: [score]`, `sigma: 0`, `notes: [critique]` — so one shape serves\n * a single judgement and a median of many. `samples`/`notes` carry only the\n * calls the judge could parse (in call order); `k` stays the requested count,\n * so a short `samples` is visible on the row rather than filled in.\n */\nexport interface CanvasJudgeRecord {\n readonly k: number;\n readonly rule: 'median';\n readonly samples: number[];\n /** Population σ of `samples` (0 when one sample). */\n readonly sigma: number;\n /** The judge's per-canvas critique per sample — the words beside a swing. */\n readonly notes: string[];\n /**\n * ggui#1127 — the cause of each scoring sample whose answer failed to parse and was SALVAGED: its four dimensions\n * were recovered from the closed prefix, its issues kept only as far as they closed, its critique lost. One entry\n * per salvaged sample; absent when every sample parsed. The salvaged sample's score still counts.\n */\n readonly salvaged?: readonly JudgeSalvageCause[];\n /**\n * ggui#1127 — the criteria call's answer was salvaged. A salvage keeps no criteria, so that frame's judge rows read\n * \"not answered\" with this cause rather than a clean `n/a`. Absent when the call parsed or was not asked.\n */\n readonly criteriaSalvaged?: JudgeSalvageCause;\n /**\n * ggui#1687 — the model asked for, and every model the provider said answered this canvas's calls (scoring and\n * criteria), deduplicated. `served` is empty when no provider named one: unknown, never \"the requested model\".\n */\n readonly models?: { readonly requested: string; readonly served: readonly string[] };\n}\n\n/**\n * ggui#1687 — what the criteria call's answer held, before resolution. A row the judge left unanswered reads `n/a`\n * either way; this says whether the call came back empty, cut, or with entries the parser had to drop.\n */\nexport interface CriteriaAnswerCounts {\n /** The answer carried a `criteria` array. `false`: absent or not an array, so no row was read from it. */\n readonly array: boolean;\n /** Entries in the array. */\n readonly received: number;\n /** Entries kept: an object with a string id and a verdict of pass, fail or n/a. */\n readonly kept: number;\n /** Entries dropped, by why. */\n readonly dropped: { readonly notObject: number; readonly badId: number; readonly badVerdict: number };\n}\n\n/**\n * ggui#1127 — why a judge answer that failed to parse had to be salvaged. `output-cap`: the provider reported it\n * stopped at the output cap. `malformed`: the provider reported a normal stop, so the answer ended but did not\n * parse. `stopped`: the provider stopped it for another reason it named (a safety stop, or one it reports as\n * other), so it is cut, not malformed. `unknown`: the provider or route reported no stop reason. Never inferred\n * from the answer's length.\n */\nexport type JudgeSalvageCause = \"output-cap\" | \"malformed\" | \"stopped\" | \"unknown\";\n\n/** ggui#1127 — salvaged judge answers across a canvas run, per leg, as N of M. */\nexport interface JudgeSalvageCounts {\n /** Scoring answers: `answers` = samples that parsed or were salvaged, `salvaged` = those salvaged. */\n readonly scoring: { readonly salvaged: number; readonly answers: number };\n /** Criteria calls: `answered` = calls that parsed or were salvaged, `salvaged` = those salvaged (criteria lost). */\n readonly criteria: { readonly salvaged: number; readonly answered: number };\n}\n\n// ─── Visual criteria (ggui#1436) ──────────────────────────────────────────\n// The judge's typed criteria block per canvas — report-only beside the score\n// until a later word flips a gate to it. Every field below is optional on the\n// stamps so yesterday's `eval.json` and an old judge answer still parse (N−1).\nimport type { FetchShape, LayoutShape, RenderShape, RiskTier, StateShape, WriteShape } from \"../classifier/axes.js\";\n\nexport type CriteriaSeverity = \"must\" | \"should\";\nexport type CriteriaVerdict = \"pass\" | \"fail\" | \"n/a\";\n/** The method that produces a verdict: an instrument's measurement, the vision judge off the frame, or a person's eye. */\nexport type CriteriaMethod = \"instrument\" | \"judge\" | \"human\";\n/** The method's readiness, as the bank's author wrote it — the only source of an `n/a` that is not the judge's own. */\nexport type CriteriaStatus = \"live\" | \"reference\" | \"planned\" | \"manual\";\n/**\n * How a criterion entered the selection: bank-level (`static`, an empty scope) or by the selector's\n * rules for this card (`context`). A model PROPOSING a criterion at judge time is RESERVED and not a\n * member until a consumer exists — it would be `should`-only, recorded verbatim, never a gate.\n */\nexport type CriteriaSource = \"static\" | \"context\";\nexport type CriteriaChroma = \"achromatic\" | \"chromatic\" | \"unknown\";\n/** The classifier's shape axes, as hashed into the set id. */\nexport interface CriteriaAxes {\n render: RenderShape;\n state: StateShape;\n writes: WriteShape;\n fetch: FetchShape;\n layout: LayoutShape;\n}\n/** The selector's inputs, stored with the verdict so a reader recomputes `criteriaSetId` from the record alone. */\nexport interface CriteriaContext {\n canvas: CanvasClass;\n hasActions: boolean;\n riskTier: RiskTier;\n axes: CriteriaAxes;\n chroma: CriteriaChroma;\n profilePresent: boolean;\n /** The harness's shell as named; `unknown` when the round carries none. */\n shell: string;\n /** The caller's item kind (a bootstrap mint's `hello`); hashed when present. */\n kind?: string;\n /** The styling preset in force (the profile's aesthetic id); a recipe is selected only under its preset. */\n preset?: string;\n}\n/** What was asked and why — recorded BEFORE the judge runs. Omission is the selector's decision. */\nexport interface CriteriaSelection {\n id: string;\n source: CriteriaSource;\n reason: string;\n}\n/** One criterion's verdict; `n/a` is the judge's answer (\"cannot read this off the frame\"), an unanswered id, a tie, or a method whose `status` is not live. */\nexport interface CriterionVerdict {\n id: string;\n severity: CriteriaSeverity;\n method: CriteriaMethod;\n status: CriteriaStatus;\n source: CriteriaSource;\n verdict: CriteriaVerdict;\n evidence: string;\n /**\n * ggui#1663 — a measured reading beside a judge row, REPORT-ONLY: the row's `verdict` stays the judge's, so this\n * changes no verdict, score or bar. Present only on rows an instrument answers beside the judge (`space.edge`).\n */\n instrument?: { verdict: CriteriaVerdict; evidence: string };\n}\n/** ggui#1687 — the criteria call as it came back: its answer's counts, ids it answered outside the bank, its stop. */\nexport interface CriteriaCallRecord {\n readonly answer: CriteriaAnswerCounts;\n /** Kept entries whose id names no row of the bank. */\n readonly unknownIds: number;\n /** The provider's normalized stop reason (`length` = the output cap); absent when it reported none. */\n readonly finishReason?: VisionFinishReason;\n}\nexport interface CriteriaBlock {\n /** sha256(bank version | selector version | canonical context), 16 hex — the block's own digest. */\n criteriaSetId: string;\n bankVersion: string;\n selectorVersion: string;\n context: CriteriaContext;\n selection: CriteriaSelection[];\n verdicts: CriterionVerdict[];\n /** ggui#1687 — the call that answered this block, when one did. Absent for a block resolved with no call. */\n call?: CriteriaCallRecord;\n}\n/** The roll-up across canvases; a `must` at `n/a` is listed, never counted as a pass. */\nexport interface CriteriaRollup {\n mustFailed: string[];\n shouldFailed: string[];\n mustNa: string[];\n}\n\n/** ggui#1492 — a host\"s frame round the inline card, as data. Colours are `#rrggbb`; the ring\"s `alpha` is 0..1. */\nexport interface HostInlineFrame {\n /** The frame\"s surface — what shows behind a transparent card, and under the floor\"s residual. */\n readonly surface: string;\n /** The room the frame sits in (the page ground round it). */\n readonly ground: string;\n readonly ring: { readonly widthPx: number; readonly color: string; readonly alpha: number };\n readonly radiusPx: number;\n /** The host\"s minimum frame height: a card shorter than it sits in a frame this tall, and the visitor sees the rest as void. */\n readonly minHeightPx?: number;\n}\n/** ggui#1492 — how a host presents one canvas: the label the judge is told, the page ground, and (the inline card only) its frame. */\nexport interface CanvasHostPresentation {\n readonly label: string;\n /** The page ground under a fill canvas\"s panel; the inline card\"s ground lives on its {@link HostInlineFrame}. */\n readonly ground?: string;\n readonly frame?: HostInlineFrame;\n}\n/** ggui#1492 — why the judge did not draw a canvas's host presentation. The codes are the lane reader's own. */\nexport type HostPresentationIgnoredReason = \"label_missing\" | \"color_not_hex\" | \"frame_off_inline\" | \"frame_malformed\" | \"ground_on_inline\";\n/**\n * ggui#1492 — what the judge DID with a canvas's host presentation, read from the judge itself: `applied` carries\n * the presentation it drew, `ignored` the reason it drew none. Absent when the caller supplied no presentation.\n */\nexport type CanvasPresentationOutcome =\n | { readonly status: \"applied\"; readonly applied: CanvasHostPresentation }\n | { readonly status: \"ignored\"; readonly reason: HostPresentationIgnoredReason };\n\nexport interface CanvasVisualSummary {\n canvas: CanvasClass;\n viewport: { width: number; height: number };\n /** The judge's weighted score at this canvas (0-100). */\n score: number;\n /** `score >= passThreshold`, and on the inline card: no overflow (ggui#1027). */\n passed: boolean;\n /** The document's scroll height at this canvas, CSS px; `null` when unmeasurable (ggui#1027). */\n contentHeight: number | null;\n /** `contentHeight > viewport.height` — measured on every canvas, judged per `canvasFitPolicy`. */\n overflow: boolean;\n /**\n * ggui#1120 — how far down the capture anything was painted: the last inked row over the measured\n * region's height (inside a drawn host panel's chrome on md/lg/xl), read from the screenshot's\n * pixels against their dominant colour. `0` is the blank the judge fails (`canvas-blank`); every\n * other value is reported, never scored. `null` when the capture could not be read.\n */\n inkRatio: number | null;\n /** How `score` was reached — always present (ggui#1072). */\n judge: CanvasJudgeRecord;\n /** ggui#1436 — the typed criteria block, when a bank was configured; report-only. */\n criteria?: CriteriaBlock;\n /** ggui#1492 — what the judge did with this canvas's host presentation, when one was supplied. */\n presentation?: CanvasPresentationOutcome;\n /**\n * How the judge composed the mount (ggui#1100): `'fill'` on every\n * fullscreen canvas — the served runtime's fit, the root stretched to\n * the frame; absent on the inline card, which keeps its natural height.\n */\n fit?: 'fill';\n}\n\n/**\n * ggui#1195 — the fit reading on the canvas whose policy FAILS an overflow\n * (the inline chat card): the box it was judged at (`ceiling` — the order's\n * declared viewport when one was carried, else the class box), whether that\n * box was declared, and how many px of content sit below it (0 = fits).\n * Present only when such a canvas was judged with a measurable height, so\n * the bar and the ledger read one number for \"does the hello fit\".\n */\nexport interface VisualFitStamp {\n readonly canvas: CanvasClass;\n readonly ceiling: { readonly width: number; readonly height: number };\n readonly declared: boolean;\n readonly overflowPx: number;\n}\n\n/** The visual leg's per-canvas summary — see `EvalResult.visual`. */\nexport interface VisualEvalSummary {\n /** Mean of the canvas scores (rounded). */\n score: number;\n /** Every canvas passed. */\n passed: boolean;\n canvases: CanvasVisualSummary[];\n /** ggui#1195 — see {@link VisualFitStamp}; absent when no fail-policy canvas was judged. */\n fit?: VisualFitStamp;\n /** The design tree the judge painted with (ggui#1042): `src` + `srcSha256` — `design@judge`. */\n design?: { readonly src: string; readonly srcSha256: string };\n /** The mode the judge's tokens were composed in, when the caller said (ggui#1076). */\n themeMode?: 'light' | 'dark';\n /** ggui#1436 — the criteria roll-up across canvases, when any canvas carries a block; report-only. */\n criteria?: CriteriaRollup;\n}\n\n// ─── Quality mode ──────────────────────────────────────────────────────────\n\nexport type QualityMode = \"fast\" | \"auto-improve\" | \"high-quality\";\n\nexport interface QualityConfig {\n quality: QualityMode;\n visualEval: boolean;\n maxCostPerGeneration: number;\n model?: { provider?: string; model?: string };\n}\n\nexport const DEFAULT_QUALITY_CONFIG: QualityConfig = {\n quality: \"fast\",\n visualEval: false,\n maxCostPerGeneration: 3,\n};\n\n// ─── Axis-check types ──────────────────────────────────────────────────────\n// The `AxisCheck` type vocabulary lives here. The check bodies\n// themselves (REGISTRY, per-axis implementations) live under\n// `./axis-checks/`.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { JsonObject } from \"@ggui-ai/protocol\";\nimport type { AxisVector, Classification } from \"../classifier/axes.js\";\nimport type { AxisKey } from \"../fragments/index.js\";\n\nexport interface AxisCheckInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n /** Full classification — checks may read sibling axes. */\n classification: Classification;\n /**\n * Which triad produced the source. Checks that assert a design-package\n * component (e.g. `layout.multi_step.stepper_adopted`) read it and\n * stand down in `free` mode, where the primitive is optional. Absent\n * means `constrained`.\n */\n designMode?: DesignMode;\n /**\n * The rendering canvas the source is judged FOR (ggui#1117). A width cap on\n * the outermost element is a defect on a fullscreen canvas and a no-op in a\n * chat bubble, so a check that reads width must know the surface. Populated\n * where the harness is built (`Harness.canvas`); ABSENT for callers with no\n * rendering context — a check handles `undefined`, it never assumes a\n * default (a silent `lg` would be the same guess with a nicer face).\n */\n canvas?: CanvasClass;\n /**\n * The props the probe and the judge RENDERED the source with (ggui#1285) — a bootstrap order's\n * `sampleProps`, the bench commit's fixture. They are judging data, not the request: a literal in\n * the source that equals one of these values, and that the request never stated, is baked copy a\n * visitor sees whenever the agent leaves the prop out. Populated on the served loop and at\n * auto-commit; ABSENT where the caller has none — the check stands down, it never guesses.\n */\n fixtureProps?: JsonObject;\n}\n\n/**\n * A gated check. Runs only when the classification's axis value matches\n * one of the gate's accepted values. Multiple gates (implicit AND) support\n * cross-axis combinations.\n */\nexport interface AxisCheck {\n /** Stable id used in issue subcategories. */\n id: string;\n /** Primary axis this check gates on. */\n axis: AxisKey;\n /** Which values of that axis activate the check. */\n values: readonly string[];\n /** Optional extra gate on a sibling axis (e.g., only when state=merge AND writes=per-item). */\n and?: { axis: AxisKey; values: readonly string[] };\n /** Execute the check and emit zero or more issues. */\n run(input: AxisCheckInput): EvalIssue[];\n}\n\n/**\n * Whether a check's gate(s) match the given axis vector. Pure function,\n * no issue emission.\n */\nexport function matches(vector: AxisVector, check: AxisCheck): boolean {\n const primary = vector[check.axis] as string;\n if (!check.values.includes(primary)) return false;\n if (check.and) {\n const sibling = vector[check.and.axis] as string;\n if (!check.and.values.includes(sibling)) return false;\n }\n return true;\n}\n\n// ─── Purely-typed helpers ──────────────────────────────────────────────────\n\n/**\n * Map a tier-0 issue category to the canonical P0/P1/P2 priority.\n *\n * Sourced from the criteria priority assignments:\n * - P0 (must): compile, security, imports, contract, types, mode\n * - P1 (safety): tokens, crash, functionality\n * - P2 (quality): interactivity, accessibility, layout, loading, visual\n */\nexport function priorityForIssue(category: EvalCategory): Priority {\n if (\n category === \"interactivity\" ||\n category === \"accessibility\" ||\n category === \"layout\" ||\n category === \"loading\" ||\n category === \"visual\"\n ) {\n return \"P2\";\n }\n if (category === \"tokens\" || category === \"crash\" || category === \"functionality\") {\n return \"P1\";\n }\n // compile, security, imports, contract, types, mode → P0.\n return \"P0\";\n}\n\n/** Whether any issue blocks shipping (has result = 'fail'). */\nexport function isBlocked(result: EvalResult): boolean {\n return result.issues.some((i) => i.result === \"fail\");\n}\n\n/**\n * Return the issues the agent should act on, depending on quality mode.\n * - fast: only fails (blocking issues)\n * - auto-improve / high-quality: fails + warns\n */\nexport function getActionableIssues(result: EvalResult, mode: QualityMode): EvalIssue[] {\n if (mode === \"fast\") {\n return result.issues.filter((i) => i.result === \"fail\");\n }\n return result.issues.filter((i) => i.result === \"fail\" || i.result === \"warn\");\n}\n\n// ─── Criteria (single source of truth for coding + eval sides) ─────────────\n//\n// Each criterion is defined ONCE with both sides of the contract:\n// - codingGuidance: what the coding agent should DO\n// - evalInstruction: what the eval agent should CHECK\n// They must be compatible — changing one means reviewing the other.\n//\n// This is *validated* shipping content: it's what the hosted runtime sends\n// to every generation today. External OSS implementers building their own\n// prompts should be able to use the same rubric — hence it's open.\n\nexport interface EvalCriterion {\n /** Unique identifier matching the eval tool name (e.g., 'functionality') */\n id: string;\n /** Human-readable name shown to both agents */\n name: string;\n /** Priority tier — P0 must, P1 should, P2 nice */\n priority: Priority;\n /** What the coding agent should DO to satisfy this criterion */\n codingGuidance: string;\n /** What the eval agent should CHECK — the evaluation prompt */\n evalInstruction: string;\n /** Tier 0 = programmatic, Tier 1 = LLM critical, Tier 2 = LLM quality */\n tier: 0 | 1 | 2;\n /** Eval outcome when this criterion fails */\n failOutcome: \"fail\" | \"warn\";\n}\n\nexport const CRITERIA: readonly EvalCriterion[] = [\n // ── P0: Correctness (must satisfy — failure = broken component) ──\n\n {\n id: \"compile\",\n name: \"Compile & type-check\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance:\n \"Code must compile. The typed Props and wire hook generics are enforced by the compiler.\",\n evalInstruction: \"Checked automatically by esbuild + TypeScript. No LLM evaluation needed.\",\n },\n {\n id: \"render-props\",\n name: \"Render all Props fields\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance: \"Render every Props field in JSX. Access via props.fieldName.\",\n evalInstruction:\n \"Check that every field from interface Props appears as props.fieldName in the function body.\",\n },\n {\n id: \"wire-hooks\",\n name: \"Wire all contract hooks\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Wire every useAction/useStream and every clientCapabilities.gadgets hook (e.g., useGeolocation) to a UI element. `agentCapabilities.tools` is a catalog the AGENT invokes — NOT a component hook surface.\",\n evalInstruction:\n \"Check that every hook variable from the boilerplate appears in the JSX or an effect.\",\n },\n {\n id: \"imports\",\n name: \"Valid imports only\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Only import from react, @ggui-ai/design/*, and @ggui-ai/wire.\",\n evalInstruction: \"Flag any import from a package not in the allowlist.\",\n },\n {\n id: \"security\",\n name: \"No eval/fetch/window\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Never use eval(), fetch(), or window. Data comes from props and hooks.\",\n evalInstruction: \"Flag any call to eval(), fetch(), or window access.\",\n },\n\n // ── P1: Safety (should satisfy — failure = crash or bad UX) ──\n\n {\n id: \"functionality\",\n name: \"All features implemented\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance: \"Implement ALL features from the request AND the data contract.\",\n evalInstruction: `Evaluate FUNCTIONALITY: Does this component implement ALL features from the request AND the data contract?\n\nCheck against BOTH sources:\n1. Original request — each feature must be coded AND rendered in JSX\n2. Data contract (if present) — verify:\n - Props fields are rendered in the UI. EXCEPTION: pure identifier fields (\\`id\\`, \\`*Id\\`, keys) that exist only to be echoed back inside an action payload do NOT need to be visibly rendered.\n - ALL useAction hooks are wired to clickable UI elements\n - ALL useStream hooks are consumed — the streamed data must reach the UI. Merging stream events into rendered state (a list, a counter, the displayed records) COUNTS as consuming the stream; it need not be a literal \\`.latest\\` render.\n - ALL clientCapabilities gadgets are used. \\`clientCapabilities.gadgets\\` is keyed by npm package: built-in browser capabilities (useGeolocation / useCamera / …) import from @ggui-ai/gadgets; registered third-party gadgets (e.g. useChartTheme) import from their OWN package. Any gadget the contract declares IS a contract feature — NEVER flag it as \"not part of the contract\".\n - \\`agentCapabilities.tools\\` is a catalog declaration only; do NOT flag missing component-side calls for it\n\nA contract hook that is declared but never used at all is a MISSING feature.\n\nCRITICAL: The \"issues\" array must ONLY contain features you are CERTAIN are missing or broken — never an implemented feature. (See \"Issue-array discipline\" above: no speculative, self-negating, or \"verify that…\" entries.)`,\n },\n {\n id: \"crash\",\n name: \"No crash scenarios\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance:\n \"Guard optional props (props.field?.x). stream.latest is T|null — always null-guard. .all is always an array.\",\n evalInstruction: `Evaluate CRASH SAFETY: Are there ACTUAL runtime crash scenarios?\n\nWILL crash (include in issues):\n- .map()/.filter()/.length on an uninitialized variable\n- Accessing property of undefined without guard\n- useStream().latest.field WITHOUT null guard — .latest is T | null\n- Optional Props field accessed as props.field.x without guard\n- Array item optional field: items.map(item => item.priority.toUpperCase()) when priority is optional\n\nSAFE (do NOT include):\n- Optional chaining: props.items?.map() — SAFE\n- Fallback: items || [] — SAFE\n- useState initializer: useState([]) — SAFE\n- Null check: items && items.map() — SAFE\n- stream.latest && stream.latest.field — SAFE, guarded\n- stream.all.map(...) — SAFE, .all is always an array\n- stream.all.length — SAFE, always a number\n\nThe \"issues\" array is ONLY for a specific line that WILL throw at runtime. NEVER put a line you have determined is safe into the issues array — not even to note that it is safe (\"…so this is safely guarded\", \"…so there is no crash\"). If you cannot name a concrete line that will throw, the answer is {\"pass\": true} — return that and an empty issues array.`,\n },\n {\n id: \"tokens\",\n name: \"Design system tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Use CSS variables for colors (var(--ggui-color-*)); use the spacing scale for gap/padding/margin (gap=\\\"md\\\", padding=\\\"lg\\\").\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, and numeric or raw-CSS-length spacing props. A t-shirt-scale spacing name (gap=\\\"md\\\") IS a token — never flag it.\",\n },\n\n // ── P2: Quality (nice to have — failure = lower score, not broken) ──\n\n {\n id: \"interactivity\",\n name: \"Sufficient interactive elements\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Add appropriate interactive elements for the component purpose.\",\n evalInstruction: `Evaluate INTERACTIVITY: Does this component have sufficient interactive elements?\n\nConsider: forms need submit buttons, lists need selection, editable content needs save/cancel.\nContract actions (if present): every useAction hook should be triggered by a visible UI element.\n\nOnly list MISSING interactive elements. Use 'fail' only for issues blocking core purpose.`,\n },\n {\n id: \"accessibility\",\n name: \"Accessible markup\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance:\n \"Add labels on form inputs, alt text on images, semantic HTML, and state ARIA (aria-checked/pressed/selected/expanded) on hand-rolled interactive controls.\",\n evalInstruction: `Evaluate ACCESSIBILITY: missing labels, alt text, semantic HTML, keyboard support, ARIA state.\n\nggui primitives bake in their own ARIA — see \"Primitive Accessibility\" in the Design System context above. NEVER flag a ggui primitive (Input/Select/TextArea, RadioGroup, Checkbox, Toggle, Progress, Slider, Spinner, Skeleton, Tabs, Accordion, Alert, Toast, Tooltip, Clickable, Icon) for a missing role / aria-* / label / keyboard handler — it is already there and not visible in the source you are reading.\n\nFlag ONLY real gaps: a raw div/span used as an interactive control; a hand-rolled control whose checked/selected/expanded/pressed state is conveyed only by styling (strikethrough, color, a check icon) with no \\`aria-checked\\` / \\`aria-pressed\\` / \\`aria-selected\\` / \\`aria-expanded\\`; an image with no alt text; an Input/Select/TextArea with no \\`label\\` prop; an icon-only Button with no aria-label; live/streaming data not wrapped in an aria-live region; inverted heading hierarchy.\n\nOnly list MISSING accessibility features. Use 'fail' only if it blocks delivery.`,\n },\n {\n id: \"layout\",\n name: \"Clean layout\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use proper spacing and visual grouping.\",\n evalInstruction: `Evaluate LAYOUT: Check spacing, alignment, visual grouping, and composition.\n\nOnly list ACTUAL layout problems. Use 'fail' only for fundamentally broken layouts.`,\n },\n {\n id: \"loading\",\n name: \"Loading/empty/error states\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Handle async data, empty collections, and error cases.\",\n evalInstruction: `Evaluate LOADING/EMPTY/ERROR STATES: Does the component handle async data and edge cases?\n\nContract-specific: useStream should handle pre-data state. clientCapabilities hooks may return undefined / permission-denied — defensive guards expected before threading values into JSX.\nProps-only components (no async, no streams, no client capabilities) do NOT need loading states — return pass.\n\nOnly list MISSING states.`,\n },\n {\n id: \"visual\",\n name: \"Design system consistency\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use design system tokens consistently.\",\n evalInstruction: `Evaluate VISUAL CONSISTENCY: Is the component using the design system correctly?\n\nFlag: hardcoded colors instead of CSS variables, numeric or raw-CSS-length spacing instead of the t-shirt scale, style objects bypassing design system.\nA t-shirt-scale spacing name (gap=\"md\", padding=\"lg\") IS correct token usage — never flag it.\nIntentional custom colors (status indicators) are acceptable when no semantic token fits.\n\nOnly list ACTUAL violations. Use 'fail' only for pervasive violations.`,\n },\n] as const;\n\n/**\n * `designMode: 'free'` overrides — ONLY the two criteria whose text\n * encodes the design vocabulary. `tokens` narrows to COLOR (the free arm\n * relaxes spacing / typography / radius / shadow to literals but keeps\n * brand-bearing color on the closed `--ggui-color-*` manifest, no\n * fallbacks); `visual` becomes arm-neutral (composition, hierarchy,\n * consistency, fit to canvas — no reward or penalty for design-system\n * usage). Every other criterion is shared verbatim between the modes.\n * Constraint alignment: what the free prompt says, the free evaluator\n * checks — and nothing more.\n */\nconst FREE_DESIGN_CRITERIA_OVERRIDES: readonly EvalCriterion[] = [\n {\n id: \"tokens\",\n name: \"Color tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Every color is a bare var(--ggui-color-*) from the token manifest — no hex, rgb()/hsl(), CSS named colors or literal fallbacks, in style props and <style> blocks alike. Spacing, typography, radius and shadow geometry may be literals.\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, CSS named colors, and literal fallbacks inside var(--ggui-*) references. Do NOT flag literal spacing, font sizes, radii or pixel values — they are allowed in this mode.\",\n },\n {\n id: \"visual\",\n name: \"Visual composition\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance:\n \"Compose deliberately: one clear focal point, consistent spacing rhythm, a coherent theme-token palette, a fit to the rendering canvas.\",\n evalInstruction: `Evaluate VISUAL COMPOSITION: Is the component composed deliberately for its canvas?\n\nJudge: visual hierarchy (one clear focal point, headings distinct from body text), consistent spacing rhythm and alignment, a coherent palette drawn from the theme tokens, fit to the canvas (fluid width, no fixed widths, nothing cramped or stretched).\nDo NOT reward or penalise the use of design-system primitives — raw HTML with inline CSS is a first-class choice here. Literal spacing / typography / radius values are fine.\n\nOnly list ACTUAL composition problems. Use 'fail' only for a fundamentally incoherent composition.`,\n },\n];\n\n/**\n * The criteria registry for a design mode. `constrained` IS `CRITERIA`\n * (same array, byte-identical summary); `free` swaps in the two\n * overrides above by id, preserving order.\n */\nexport function criteriaFor(designMode: DesignMode = \"constrained\"): readonly EvalCriterion[] {\n if (designMode === \"constrained\") return CRITERIA;\n return CRITERIA.map(\n (c) => FREE_DESIGN_CRITERIA_OVERRIDES.find((o) => o.id === c.id) ?? c,\n );\n}\n\n/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(\n priority: Priority,\n designMode: DesignMode = \"constrained\",\n): EvalCriterion[] {\n return criteriaFor(designMode).filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(\n id: string,\n designMode: DesignMode = \"constrained\",\n): EvalCriterion | undefined {\n return criteriaFor(designMode).find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(designMode: DesignMode = \"constrained\"): EvalCriterion[] {\n return criteriaFor(designMode).filter((c) => c.tier > 0);\n}\n\n/**\n * Build the coding agent's criteria summary from the single source of truth.\n * Grouped by priority for the P0→P1→P2 hierarchy.\n */\nexport function buildCodingCriteriaSummary(designMode: DesignMode = \"constrained\"): string {\n const lines: string[] = [\"## Priority (P0 first, then P1, then P2)\", \"\"];\n\n for (const priority of [\"P0\", \"P1\", \"P2\"] as Priority[]) {\n const label =\n priority === \"P0\"\n ? \"Must (compile + complete)\"\n : priority === \"P1\"\n ? \"Should (safety)\"\n : \"Nice (quality)\";\n const criteria = getCriteriaByPriority(priority, designMode);\n lines.push(`**${priority} — ${label}:**`);\n for (const c of criteria) {\n lines.push(`- ${c.codingGuidance}`);\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","// packages/ui-gen/src/check/run-tier0.ts\n//\n// Tier-0 deterministic CHECK orchestrator — the programmatic half of\n// the three-tier evaluation system:\n// Tier 0 — programmatic (deterministic, no LLM) ← this file\n// Tier 1 — LLM critical checks (functionality, crash)\n// Tier 2 — LLM quality checks (interactivity, accessibility, layout, etc.)\n//\n// Composes the deterministic helpers (`extract-wire-calls`,\n// `react-linter`, `contract-validation`, `type-checker`) from the\n// `@ggui-ai/ui-gen/check` subpath. The purely-typed evaluation surface\n// (`EvalTier` / `EvalOutcome` / `priorityForIssue` / …) is imported\n// directly from `@ggui-ai/ui-gen/evaluation` — its canonical home.\n\nimport ts from 'typescript';\nimport type { DataContract } from '@ggui-ai/protocol';\nimport { HOOK_NAME_RE, listContractGadgets } from '@ggui-ai/protocol';\nimport { consumedTokenManifest } from '@ggui-ai/design/themes';\nimport { DEFAULT_DESIGN_MODE, type DesignMode } from '../design-mode.js';\nimport { taughtTokenManifest } from '../taught-tokens.js';\nimport { validateAllContracts, type ContractIssue } from './contract-validation.js';\nimport { typecheck } from './type-checker.js';\nimport { lintReactHooks, type ReactLintDiagnostic } from './react-linter.js';\nimport { isAllowedImport, describeAllowedImports } from '../validation/allowed-imports.js';\nimport {\n checkWireImports,\n checkWirePreservation,\n type WireKind,\n} from './extract-wire-calls.js';\nimport {\n priorityForIssue,\n type EvalCategory,\n type EvalIssue,\n type EvalResult,\n} from '../evaluation/types-public.js';\n\n/**\n * Strip line + block comments from source, leaving all other text in\n * place. Uses the TS scanner so a `//` or block-comment sequence inside\n * a string / template / regex literal is NOT mistaken for a comment.\n * Comment characters are replaced with spaces (newlines kept) so byte\n * offsets and line numbers are unchanged.\n *\n * Used by regex-based CHECK rules that must not be satisfied by\n * commented-out code (e.g. `gadget_preservation`).\n */\nfunction stripComments(code: string): string {\n const scanner = ts.createScanner(\n ts.ScriptTarget.Latest,\n /* skipTrivia */ false,\n ts.LanguageVariant.JSX,\n code,\n );\n let out = '';\n for (\n let token = scanner.scan();\n token !== ts.SyntaxKind.EndOfFileToken;\n token = scanner.scan()\n ) {\n const text = scanner.getTokenText();\n out +=\n token === ts.SyntaxKind.SingleLineCommentTrivia ||\n token === ts.SyntaxKind.MultiLineCommentTrivia\n ? text.replace(/[^\\n]/g, ' ')\n : text;\n }\n return out;\n}\n\n/**\n * AST-precise detector for the unambiguous nested-interactive\n * double-wire pattern. See the call-site comment in `runTier0Checks` +\n * the `double-wired-action:certain` block for the rationale.\n *\n * The detector accepts a JSX element as the outer host when:\n * - tagName ∈ {Card, Box, Stack, Row}\n * - has `as={Clickable | Pressable}` (`Hoverable` doesn't fire click)\n * - has `onClick` (or `onPress`) whose handler calls one of the\n * known `useAction` bindings.\n *\n * Then it walks descendants of that outer element and matches an inner\n * interactive primitive when:\n * - tagName ∈ {Button, Checkbox, Input, Toggle, Slider, RadioGroup,\n * Select, TextArea, Link}\n * - has any of {onClick, onChange, onPress, onSelect} whose handler\n * calls the SAME useAction binding as the outer.\n *\n * Patterns it INTENTIONALLY does not catch:\n * - helper-function indirection (`const fire = () => toggle({id})`\n * in both handlers) — the AST sees two distinct callees, not the\n * same binding. The runtime dedup in `useAction` still catches the\n * symptom; the static-time catch is a teaching aid, not a safety\n * net.\n * - cross-component prop drilling — same reason.\n * - imperative DOM addEventListener — out of scope for JSX walking.\n */\nfunction detectCertainDoubleWiredActions(\n sourceCode: string,\n actionBindings: readonly string[],\n /**\n * `constrained` keeps the design-package tag sets above. `free`\n * retargets the SAME invariant (\"one useAction binding → exactly one\n * gesture surface\") at raw elements: the outer host is ANY JSX element\n * whose onClick/onPress calls a binding (`<div onClick>`, `<li>`,\n * `<tr>`, `<button>`, `<a>`, `[role=button]`, a design primitive…),\n * and the inner match is ANY descendant whose handler attribute calls\n * the same binding. Tag names stop mattering because in free mode a\n * raw element is a first-class gesture surface.\n */\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n): EvalIssue[] {\n const issues: EvalIssue[] = [];\n if (actionBindings.length === 0) return issues;\n const bindings = new Set(actionBindings);\n const anyElementIsInteractive = designMode === 'free';\n const TRAIT_HOST_TAGS = new Set(['Card', 'Box', 'Stack', 'Row']);\n const TRAITS_THAT_FIRE = new Set(['Clickable', 'Pressable']);\n const INTERACTIVE_DESCENDANTS = new Set([\n 'Button',\n 'Checkbox',\n 'Input',\n 'Toggle',\n 'Slider',\n 'RadioGroup',\n 'Select',\n 'TextArea',\n 'Link',\n ]);\n const HANDLER_ATTRS = ['onClick', 'onChange', 'onPress', 'onSelect'] as const;\n\n const sf = ts.createSourceFile(\n 'source.tsx',\n sourceCode,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n ts.ScriptKind.TSX,\n );\n\n function tagNameText(\n node: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n ): string | undefined {\n return ts.isIdentifier(node.tagName) ? node.tagName.text : undefined;\n }\n\n function attrExpression(\n node: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n attrName: string,\n ): ts.Expression | undefined {\n for (const attr of node.attributes.properties) {\n if (\n ts.isJsxAttribute(attr) &&\n ts.isIdentifier(attr.name) &&\n attr.name.text === attrName &&\n attr.initializer !== undefined &&\n ts.isJsxExpression(attr.initializer)\n ) {\n return attr.initializer.expression;\n }\n }\n return undefined;\n }\n\n function isTraitHostWithFiringAs(node: ts.JsxOpeningElement): boolean {\n const tag = tagNameText(node);\n if (tag === undefined) return false;\n // Free mode: every element with a handler is a gesture surface —\n // the callee check in `visit` decides whether it fires a binding.\n if (anyElementIsInteractive) return true;\n if (!TRAIT_HOST_TAGS.has(tag)) return false;\n const asExpr = attrExpression(node, 'as');\n return (\n asExpr !== undefined &&\n ts.isIdentifier(asExpr) &&\n TRAITS_THAT_FIRE.has(asExpr.text)\n );\n }\n\n // Best-effort callee extraction from event-handler expression shapes\n // the LLM actually emits. Forms covered:\n // {handler} → 'handler'\n // {() => callee(arg)} → 'callee'\n // {(e) => callee(e)} → 'callee'\n // {() => { callee(arg); }} → 'callee'\n // {function () { callee(arg); }} → 'callee'\n // Forms intentionally not covered: chained calls, conditional\n // expressions, calls inside if-branches. Those are rare in\n // LLM-generated JSX and would expand the FP surface.\n function extractCalleeName(\n expr: ts.Expression | undefined,\n ): string | undefined {\n if (expr === undefined) return undefined;\n if (ts.isIdentifier(expr)) return expr.text;\n if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {\n const body = expr.body;\n if (ts.isCallExpression(body) && ts.isIdentifier(body.expression)) {\n return body.expression.text;\n }\n if (ts.isBlock(body)) {\n for (const stmt of body.statements) {\n if (\n ts.isExpressionStatement(stmt) &&\n ts.isCallExpression(stmt.expression) &&\n ts.isIdentifier(stmt.expression.expression)\n ) {\n return stmt.expression.expression.text;\n }\n }\n }\n }\n return undefined;\n }\n\n function findMatchingInteractiveDescendant(\n outer: ts.JsxElement,\n expectedBinding: string,\n ): { tag: string; line: number } | undefined {\n let found: { tag: string; line: number } | undefined;\n function walk(node: ts.Node): void {\n if (found !== undefined) return;\n const opening = ts.isJsxElement(node)\n ? node.openingElement\n : ts.isJsxSelfClosingElement(node)\n ? node\n : undefined;\n if (opening !== undefined) {\n const tag = tagNameText(opening);\n if (\n tag !== undefined &&\n (anyElementIsInteractive || INTERACTIVE_DESCENDANTS.has(tag))\n ) {\n for (const attrName of HANDLER_ATTRS) {\n const callee = extractCalleeName(attrExpression(opening, attrName));\n if (callee === expectedBinding) {\n found = {\n tag,\n line:\n sf.getLineAndCharacterOfPosition(opening.getStart()).line + 1,\n };\n return;\n }\n }\n }\n }\n ts.forEachChild(node, walk);\n }\n // Walk only the outer element's children, not the outer itself.\n ts.forEachChild(outer, walk);\n return found;\n }\n\n function visit(node: ts.Node): void {\n if (ts.isJsxElement(node) && isTraitHostWithFiringAs(node.openingElement)) {\n const outerCallee =\n extractCalleeName(attrExpression(node.openingElement, 'onClick')) ??\n extractCalleeName(attrExpression(node.openingElement, 'onPress'));\n if (outerCallee !== undefined && bindings.has(outerCallee)) {\n const match = findMatchingInteractiveDescendant(node, outerCallee);\n if (match !== undefined) {\n const outerTag = tagNameText(node.openingElement);\n const outerLine =\n sf.getLineAndCharacterOfPosition(node.openingElement.getStart())\n .line + 1;\n const outerLabel = anyElementIsInteractive\n ? `<${outerTag}>`\n : `<${outerTag} as={...}>`;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'interactivity',\n subcategory: 'double-wired-action:certain',\n severity: 'critical',\n description:\n `Nested-interactive double-wire: outer ${outerLabel} at line ${outerLine} and inner <${match.tag}> at line ${match.line} both dispatch the same useAction binding '${outerCallee}'. ` +\n `One user click on the inner control fires its handler AND bubbles to the outer handler — '${outerCallee}' dispatches TWICE, the action runs back-to-back, and a toggle-style action silently reverts the user's change.`,\n fix: anyElementIsInteractive\n ? `Pick ONE gesture surface for '${outerCallee}': either remove the onClick from the outer <${outerTag}> and let the inner <${match.tag}> own the gesture, OR drop the inner <${match.tag}>'s handler and let the outer <${outerTag}> own it. Never wire both to the same useAction binding — stopPropagation is not a fix.`\n : `Pick ONE surface for the gesture: either drop \\`as={...}\\` + onClick on the outer <${outerTag}> and let the inner <${match.tag}> own the gesture, OR remove the inner <${match.tag}> and let the outer <${outerTag} as={...}> own it. Don't wire both to the same useAction binding.`,\n line: outerLine,\n });\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return issues;\n}\n\n/**\n * The consumed-token manifest as a closed set (ggui#613 residual 3 —\n * the generation-time closure leg of the #598 record). Every theme\n * MUST define exactly these names (the coverage gate); a generated\n * component may therefore consume ONLY these names. Anything else\n * is a reference no theme is obligated to define, and under the s4\n * fallback ban it paints nothing.\n */\nconst MANIFEST_TOKENS: ReadonlySet<string> = new Set(consumedTokenManifest);\n\n/**\n * Role names retired by ggui#987 that generated code still invents, each\n * with the manifest name that replaced it (ggui#1325). The self-check names\n * the successor, so the model does not spend a turn guessing another name.\n */\nconst RETIRED_TOKEN_SUCCESSORS: ReadonlyMap<string, string> = new Map([\n ['--ggui-color-surface', '--ggui-color-container'],\n ['--ggui-color-onSurface', '--ggui-color-onContainer'],\n ['--ggui-color-surfaceVariant', '--ggui-color-sunken'],\n ['--ggui-color-onSurfaceVariant', '--ggui-color-onSunken'],\n]);\n\n/**\n * The manifest names nearest an invented one (ggui#1325): a retired role's\n * successor when there is one; otherwise the names sharing the invented\n * name's longest family prefix at a segment boundary\n * (`--ggui-motion-duration-normal` → fast, base, slow); otherwise the names\n * sharing any of its segments of four letters or more\n * (`--ggui-duration-slow` → the motion durations). Empty when nothing is\n * near, so the hint falls back to the manifest's general shape. A hint\n * teaches, so it draws only on the names the model may be taught\n * (`taughtTokenManifest`); the closed-set check above admits the full manifest.\n */\nexport function suggestManifestTokens(name: string): readonly string[] {\n const successor = RETIRED_TOKEN_SUCCESSORS.get(name);\n if (successor !== undefined) return [successor];\n // Family prefixes at the name's own segment boundaries, longest first: for\n // `--ggui-motion-duration-normal` that is `--ggui-motion-duration-`, then\n // `--ggui-motion-`; an empty-suffix name such as `--ggui-color-` (the model\n // stopped mid-name) is its own longest prefix, so it gets the colour family.\n const segments = name.split('-').filter((segment) => segment.length > 0);\n const own = name.endsWith('-') ? segments.length : segments.length - 1;\n for (let n = own; n >= 2; n--) {\n const prefix = `--${segments.slice(0, n).join('-')}-`;\n const family = taughtTokenManifest.filter((token) => token.startsWith(prefix));\n if (family.length > 0) return wordHitsFirst(name, rolesFirst(family));\n }\n const words = new Set(\n segments\n .slice(1)\n .filter((segment) => segment.length >= 4)\n .map((segment) => segment.toLowerCase()),\n );\n return rolesFirst(\n taughtTokenManifest.filter((token) =>\n token.split('-').some((segment) => words.has(segment.toLowerCase())),\n ),\n );\n}\n\n/**\n * Names that carry the invented name's last word lead the list: `--ggui-color-inverse` names `inverseLink` and\n * `inverseOutline` before the rest of the colour family, since those are what the model was reaching for. The word is\n * the last segment when it has four letters or more; shorter or empty suffixes leave the order alone.\n */\nfunction wordHitsFirst(name: string, family: readonly string[]): readonly string[] {\n const word = name.slice(name.lastIndexOf('-') + 1).toLowerCase();\n if (word.length < 4) return family;\n const hit = (token: string): boolean => token.slice(token.lastIndexOf('-') + 1).toLowerCase().includes(word);\n return [...family.filter(hit), ...family.filter((token) => !hit(token))];\n}\n\n/** Role names (a non-numeric last segment) before ramp steps, so the taught vocabulary leads a long family. */\nfunction rolesFirst(tokens: readonly string[]): readonly string[] {\n const isRole = (token: string): boolean => !/^\\d+$/.test(token.slice(token.lastIndexOf('-') + 1));\n return [...tokens.filter(isRole), ...tokens.filter((token) => !isRole(token))];\n}\n\n/** The sentence that names the real token first (ggui#1325); empty when nothing in the manifest is near. */\nfunction offManifestHint(name: string): string {\n const successor = RETIRED_TOKEN_SUCCESSORS.get(name);\n if (successor !== undefined) {\n return `\"${name}\" was retired (ggui#987); the current name is var(${successor}). `;\n }\n const near = suggestManifestTokens(name);\n if (near.length === 0) return '';\n const shown = near.slice(0, 8).map((token) => `var(${token})`).join(', ');\n const more = near.length > 8 ? ` (and ${near.length - 8} more in that family)` : '';\n return `Nearest names in the manifest: ${shown}${more}. `;\n}\nconst TOKEN_REF_RE = /var\\(\\s*(--ggui-[a-zA-Z0-9-]+)/g;\n\n/** Map wire kind to the matching `@ggui-ai/wire` hook name. */\nconst HOOK_NAME_FOR: Readonly<Record<WireKind, string>> = {\n action: 'useAction',\n stream: 'useStream',\n context: 'useGguiContext',\n};\n\n/**\n * Map wire kind to the contract field the agent must declare on the\n * `contract` input to `ggui_render` (post-Phase-2 flat handshake input)\n * to make the `useX('<name>')` call legal.\n *\n * Drives the remediation message on the `wire_undeclared` fail.\n * Telling the LLM \"declare it on contextSpec.<slotName>\" with the\n * JSON-Schema starter is concretely actionable; \"declare a contract\"\n * alone is not.\n */\nconst CONTRACT_FIELD_FOR: Readonly<Record<WireKind, string>> = {\n action: 'actionSpec',\n stream: 'streamSpec',\n context: 'contextSpec',\n};\n\n// =============================================================================\n// Tier 0: Programmatic Hard Checks\n// =============================================================================\n\n/**\n * Whether comment-free `source` imports the named gadget `exportName`\n * from `pkg` — `import { …, exportName, … } from '<pkg>'` (the source\n * name, left of any `as`). Kind-agnostic — hook and component exports\n * are both direct-imported the same way. The `gadget_preservation`\n * anchor: generated code direct-imports each gadget export, and the\n * import is what the iframe rewriter binds to the per-package runtime\n * shim.\n */\nfunction isGadgetExportImported(\n source: string,\n pkg: string,\n exportName: string,\n): boolean {\n const esc = pkg.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const re = new RegExp(\n `import\\\\s*(?:[A-Za-z_$][\\\\w$]*\\\\s*,\\\\s*)?\\\\{([^}]*)\\\\}\\\\s*from\\\\s*['\"]${esc}['\"]`,\n 'g',\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(source)) !== null) {\n for (const raw of m[1].split(',')) {\n if (raw.trim().split(/\\s+as\\s+/)[0]?.trim() === exportName) return true;\n }\n }\n return false;\n}\n\n/**\n * AST-precise detector for the compiles-but-renders-nothing class: the\n * default-exported component's body never returns a tree.\n *\n * The boilerplate HANDS the model the wrapper — `base.tsx.tmpl` and\n * `base-free.tsx.tmpl` both emit `return (` … `);` around `{{LAYOUT}}`.\n * A model rewriting the root block can delete those two lines with it,\n * leaving the JSX as a bare expression statement. That is legal TSX: it\n * parses, esbuild compiles it, `typecheck()` passes it, and the\n * component renders a blank frame. Seen once in twenty takes of the\n * ggui#1113 A/B (`xs-chat-card`, run 2 — the judge spent a screenshot\n * and an LLM call to report \"completely blank\").\n *\n * `compile/default-export` already guards the scaffold's\n * `export default function` line and `types/props-interface` its\n * `interface Props` line. The `return (` was the third scaffold line\n * with nothing watching it.\n *\n * Conservative by construction — it reports ONLY when it positively\n * identified a block-bodied default-export component:\n * - a concise arrow body (`export default () => <X/>`) returns by\n * construction → silent\n * - `export default memo(Component)` or any other expression it\n * cannot resolve to a function → silent\n * - a `return` inside a nested helper is not the component's own (the\n * walk stops at every nested function boundary), but ONE own-level\n * `return <value>` anywhere — an early `return null` included —\n * satisfies it.\n *\n * Returns `null` when the component returns (or could not be\n * identified), else the 1-based line of the first bare JSX expression\n * statement in its body — the line the fix belongs on — or `undefined`\n * when the body has no JSX statement to point at either.\n */\nfunction detectComponentNeverReturns(\n sourceCode: string,\n): { jsxStatementLine: number | undefined } | null {\n const sf = ts.createSourceFile(\n 'source.tsx',\n sourceCode,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n ts.ScriptKind.TSX,\n );\n\n const isFunctionLike = (n: ts.Node): boolean =>\n ts.isFunctionDeclaration(n) ||\n ts.isFunctionExpression(n) ||\n ts.isArrowFunction(n) ||\n ts.isMethodDeclaration(n) ||\n ts.isClassDeclaration(n) ||\n ts.isClassExpression(n);\n\n /** The top-level declaration `name` binds to, when it is a function. */\n function resolveTopLevel(\n name: string,\n ): ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction | undefined {\n for (const st of sf.statements) {\n if (ts.isFunctionDeclaration(st) && st.name?.text === name) return st;\n if (ts.isVariableStatement(st)) {\n for (const decl of st.declarationList.declarations) {\n if (\n ts.isIdentifier(decl.name) &&\n decl.name.text === name &&\n decl.initializer !== undefined &&\n (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))\n ) {\n return decl.initializer;\n }\n }\n }\n }\n return undefined;\n }\n\n let component:\n | ts.FunctionDeclaration\n | ts.FunctionExpression\n | ts.ArrowFunction\n | undefined;\n for (const st of sf.statements) {\n if (\n ts.isFunctionDeclaration(st) &&\n st.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)\n ) {\n component = st;\n break;\n }\n if (ts.isExportAssignment(st) && st.isExportEquals !== true) {\n const expr = st.expression;\n if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) component = expr;\n else if (ts.isIdentifier(expr)) component = resolveTopLevel(expr.text);\n break;\n }\n }\n // No default export at all, or one this detector cannot resolve to a\n // function — `compile/default-export` owns the first case and the\n // second is not ours to guess at.\n if (component === undefined) return null;\n\n const body = component.body;\n // A concise arrow body IS the returned value.\n if (body === undefined || !ts.isBlock(body)) return null;\n\n let returnsValue = false;\n let jsxStatementLine: number | undefined;\n const visit = (node: ts.Node): void => {\n if (returnsValue) return;\n if (ts.isReturnStatement(node)) {\n if (node.expression !== undefined) returnsValue = true;\n return;\n }\n if (\n jsxStatementLine === undefined &&\n ts.isExpressionStatement(node) &&\n (ts.isJsxElement(node.expression) ||\n ts.isJsxFragment(node.expression) ||\n ts.isJsxSelfClosingElement(node.expression))\n ) {\n jsxStatementLine = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n }\n node.forEachChild((child) => {\n // A helper component's own `return` is not this component's.\n if (!isFunctionLike(child)) visit(child);\n });\n };\n for (const st of body.statements) if (!isFunctionLike(st)) visit(st);\n\n return returnsValue ? null : { jsxStatementLine };\n}\n\n/**\n * Run all tier 0 (deterministic, no-LLM) checks against component source.\n *\n * Wraps the same logic as runSelfChecks (adapters/tools.ts) but emits EvalIssue[].\n * Also runs contract validation when contract are provided.\n */\nexport async function runTier0Checks(\n sourceCode: string,\n contract?: DataContract,\n buildErrors?: string[],\n /**\n * A `package -> .d.ts content` map for third-party gadget wrappers.\n * Threaded verbatim into `typecheck()` so the in-memory TS sandbox\n * overlays each wrapper `.d.ts` at `node_modules/<package>/index.d.ts`\n * — a generated direct import `import { useX } from '<package>'`\n * resolves against the real declaration (strict option/return\n * narrowing). Standard-library-only callers omit it.\n */\n gadgetTypes?: Readonly<Record<string, string>>,\n /**\n * Which triad produced the source. `constrained` (default) runs every\n * leg exactly as before. `free` gates OFF the design-VOCABULARY legs —\n * `raw-spacing`, `raw-pixels`, `numeric-spacing-prop`, the\n * `stack-row-*` prop checks and `clickable-wrapper` — because raw\n * elements, inline CSS and literal spacing are first-class there. It\n * KEEPS every contract leg: `hex-color`, `hardcoded-color-fn`,\n * `named-color`, `token-fallback`, `off-manifest-token`,\n * `asset-color-pair` (color stays on the closed token manifest),\n * imports, security, Props / default-export, wire_* and gadget checks,\n * and the double-wired-action detector (retargeted at raw elements).\n */\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n): Promise<EvalIssue[]> {\n const issues: EvalIssue[] = [];\n const lines = sourceCode.split('\\n');\n // Design-vocabulary legs fire only when the prompt taught the\n // vocabulary — see `designMode` above.\n const enforceDesignVocabulary = designMode === 'constrained';\n\n // ── Compile check ─────────────────────────────────────────\n //\n // Fail only when the caller ATTEMPTED compile and captured errors.\n // Absent `buildErrors` means the caller hasn't run esbuild at all\n // (e.g. OSS `createUiGenerator` which is sometimes wrapped by\n // `withBrowserCompile` and sometimes not); degrade gracefully —\n // downstream checks (security, forbidden imports, wire-import\n // presence, react-linter, Props-interface, default-export) still\n // fire on sourceCode alone.\n if (buildErrors && buildErrors.length > 0) {\n const errorDetail = buildErrors\n .map((e) => {\n // Extract key info from esbuild error (e.g., line number, error type)\n const match = e.match(/<stdin>:(\\d+):\\d+: ERROR: (.+)/);\n return match ? `Line ${match[1]}: ${match[2]}` : e.slice(0, 200);\n })\n .join('\\n');\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'compile',\n subcategory: 'build-error',\n severity: 'critical',\n description: `Component failed to compile:\\n${errorDetail}`,\n fix: 'Fix the JSX/TypeScript syntax errors listed above',\n });\n }\n\n // ── assetColor allow-list ─────────────────────────────────\n //\n // T-4: Box gains a typed brand-color escape pair —\n // <Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">\n // The static hex / rgba checks below allow a hex/rgba/hsl whose\n // `JSXAttribute` parent is `assetColor`, but only when a sibling\n // `assetSemantic` attribute carries a non-empty string value on the\n // same JSX opening tag. Both pieces are required: an `assetColor`\n // alone, or `assetSemantic=\"\"`, fails.\n //\n // Implementation: collect the (1-based) line numbers of every line\n // whose JSX opening tag legitimately satisfies this pair. The\n // hex/colorFn/named-color checks below skip emitting a failure\n // when the matching line is in this allow-list.\n const assetEscapedLines = new Set<number>();\n // Match each JSX opening tag (allowing multiline attribute lists).\n // The regex captures the tag's attribute span; we then check it for\n // the required `assetColor` + non-empty `assetSemantic` pair, and\n // record every source line that the tag spans.\n const jsxOpenRegex = /<([A-Z][A-Za-z0-9]*)\\b([^>]*)>/gs;\n for (const match of sourceCode.matchAll(jsxOpenRegex)) {\n const tagAttrs = match[2];\n const assetColorAttr = tagAttrs.match(/\\bassetColor\\s*=\\s*(?:[\"']([^\"']*)[\"']|\\{[^}]*\\})/);\n if (!assetColorAttr) continue;\n const assetSemanticAttr = tagAttrs.match(/\\bassetSemantic\\s*=\\s*[\"']([^\"']*)[\"']/);\n const startLine = sourceCode.slice(0, match.index ?? 0).split('\\n').length;\n const tagLineCount = match[0].split('\\n').length;\n // Both attributes must be present, AND assetSemantic must be a\n // non-empty string literal. A `{expr}` value for assetSemantic is\n // treated as not-statically-verifiable; the escape is opt-in\n // documentation, not a runtime expression. Failing pairs emit a\n // dedicated `tokens:asset-color-pair` failure AND do NOT enter\n // the allow-list — so the embedded hex still fires its own\n // `tokens:hex-color` failure (two issues, one per axis).\n if (!assetSemanticAttr || assetSemanticAttr[1].length === 0) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'asset-color-pair',\n severity: 'critical',\n description:\n 'Box `assetColor` set without a non-empty `assetSemantic` — the typed brand-color escape requires both. ' +\n '`assetSemantic` is a human-readable label that documents why this color bypasses the theme.',\n fix:\n 'Pair the `assetColor` with a non-empty `assetSemantic` literal, e.g. ' +\n '`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">`. Reach for `surface=\"...\"` first ' +\n 'whenever the color SHOULD track the operator\\'s theme.',\n line: startLine,\n });\n continue;\n }\n for (let l = 0; l < tagLineCount; l++) {\n assetEscapedLines.add(startLine + l);\n }\n }\n\n // Gadget packages the contract declares are import-\n // allowlisted. Generated code direct-imports gadget exports from\n // their package. `clientCapabilities.gadgets` is\n // package-keyed, so the map's own keys ARE the permitted import\n // sources, alongside the STDLIB `@ggui-ai/gadgets`.\n const allowedGadgetPackages = new Set<string>(\n Object.keys(contract?.clientCapabilities?.gadgets ?? {}),\n );\n\n // ── Line-by-line checks ───────────────────────────────────\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNum = i + 1;\n\n // Security: eval()\n if (/\\beval\\s*\\(/.test(line)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'security',\n subcategory: 'eval',\n severity: 'critical',\n description: 'eval() is forbidden',\n fix: 'Remove eval() call entirely',\n line: lineNum,\n });\n }\n\n // Security: fetch()\n if (/\\bfetch\\s*\\(/.test(line)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'security',\n subcategory: 'fetch',\n severity: 'critical',\n description: 'fetch() is forbidden — use props for data',\n fix: 'Remove fetch() and pass data via props',\n line: lineNum,\n });\n }\n\n // Forbidden imports (skip commented-out imports)\n const trimmedLine = line.trim();\n if (trimmedLine.startsWith('//') || trimmedLine.startsWith('*')) continue;\n const importMatch = trimmedLine.match(/import\\s+.*from\\s+['\"]([^'\"]+)['\"]/);\n if (importMatch) {\n const pkg = importMatch[1];\n // Allowlist mirrors `validation/component-detailed.ts` ALLOWED_IMPORTS —\n // these two must stay in sync. Generated code direct-imports\n // gadget exports, so every gadget package the contract declares\n // (`clientCapabilities.gadgets[*].package`) is allowlisted alongside\n // the STDLIB `@ggui-ai/gadgets`. Rejecting a declared gadget package\n // would contradict the `gadget_preservation` check (which REQUIRES\n // the direct import).\n if (!isAllowedImport(pkg, allowedGadgetPackages)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: 'disallowed-package',\n severity: 'critical',\n description: `Import from \"${pkg}\" is not allowed`,\n fix: `Only import from: ${describeAllowedImports()}`,\n line: lineNum,\n });\n }\n }\n\n // Hardcoded hex colors (not inside CSS variable fallbacks).\n //\n // Empirical (warn → fail rationale): when the\n // operator's prompt evoked a strong aesthetic (\"garden / living\n // ecosystem\"), the LLM emitted hex literals (`#B8FF3A` lime,\n // `#0a0a0a` near-black) inline on `color`/`background` style\n // overrides — completely overriding the operator's selected theme.\n // The warn-level rule was advisory and got ignored. As a `fail`\n // it forces the LLM to remediate before passing self-check.\n //\n // Generation contract this enforces (per the contract bar): the\n // LLM describes structure + intent; the theme + primitive variants\n // describe visuals. Hardcoded hex is a contract violation. The\n // existing `var(--ggui-*, #fallback)` exception keeps legit token\n // patterns flowing untouched. Asset-fixed brand colors get a\n // typed escape on Box (`assetColor` + `assetSemantic`) — see\n // T-4 follow-up.\n // Literal fallback inside ANY token reference (ggui#598 slice 4\n // origin-kill, generalized by ggui#613 residual 4 from color to\n // every token): the runtime injects every token — colors, spacing,\n // typography, radius, shadows — so a literal fallback can only\n // ever paint default-brand pixels under a failed injection, which\n // must be visible (unset) rather than silently default. The old\n // hex-only exemption plus a remediation that suggested\n // `var(--x, ${hex})` actively taught the model to launder invented\n // values INTO fallbacks (adversarial-cycle find). A token-to-token\n // fallback (`var(--a, var(--b))`) is not a literal — it stays on\n // the manifest check alone.\n const literalFallbackMatch = line.match(\n /var\\(\\s*(--ggui-[a-zA-Z0-9-]+)\\s*,\\s*([^)]+)\\)/,\n );\n const literalFallback =\n literalFallbackMatch !== null &&\n !literalFallbackMatch[2]!.trim().startsWith('var(')\n ? { token: literalFallbackMatch[1]!, literal: literalFallbackMatch[2]!.trim() }\n : null;\n if (literalFallback !== null && !assetEscapedLines.has(lineNum)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'token-fallback',\n severity: 'critical',\n description: `Literal fallback \"${literalFallback.literal}\" inside a token reference — the runtime injects every token, and the fallback paints the wrong value exactly when the theme matters most.`,\n fix: `Drop the fallback: write var(${literalFallback.token}) bare. If the token might not exist, that is a vocabulary problem to fix by choosing a token from the design-system docs, never by a literal.`,\n line: lineNum,\n });\n }\n\n const hexMatch = line.match(/#[0-9a-fA-F]{3,8}\\b/);\n if (hexMatch && !assetEscapedLines.has(lineNum)) {\n // A hex that lives inside a token fallback is already reported\n // above as `token-fallback` — don't double-report it as\n // `hex-color`.\n if (literalFallback !== null && literalFallback.literal.includes(hexMatch[0])) {\n // reported above\n } else if (!line.includes('// fallback')) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'hex-color',\n severity: 'critical',\n description: `Hardcoded color \"${hexMatch[0]}\" breaks theme switching — use design tokens.`,\n fix: `Replace with a primitive variant (Button variant=\"primary\"|Badge variant=\"success\"|...) OR a bare token reference like var(--ggui-color-primary-500) — never a literal fallback. Hardcoded colors mean the operator's theme has no effect on this surface.`,\n line: lineNum,\n });\n }\n }\n\n // Hardcoded rgba()/hsl() color functions — same reasoning as above.\n // Treated as `fail` for symmetry — a hardcoded `rgba(184, 255, 58, 1)`\n // is functionally identical to `#B8FF3A` from a theme-override\n // standpoint.\n const colorFnMatch = line.match(/\\b(rgba?|hsla?)\\s*\\(/);\n if (\n colorFnMatch &&\n !line.includes('var(--ggui-') &&\n !line.includes('// fallback') &&\n !line.includes('$value') &&\n !assetEscapedLines.has(lineNum)\n ) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'hardcoded-color-fn',\n severity: 'critical',\n description: `Hardcoded ${colorFnMatch[1]}() breaks theme switching — use design tokens.`,\n fix: 'Replace with a primitive variant OR a layering role: var(--ggui-color-container), var(--ggui-color-onContainer), var(--ggui-color-outline), etc.',\n line: lineNum,\n });\n }\n\n // Off-manifest token references (ggui#613 residual 3): a\n // `var(--ggui-*)` whose name is outside the consumed-token\n // manifest. The manifest is the closed vocabulary the prompt\n // teaches AND the set every theme must define — so a name outside\n // it is invented, and with literal fallbacks banned it renders\n // UNSET. Fail, like the other token-contract violations; one issue\n // per distinct name per line.\n const offManifest = new Set<string>();\n for (const m of line.matchAll(TOKEN_REF_RE)) {\n const name = m[1]!;\n if (!MANIFEST_TOKENS.has(name)) offManifest.add(name);\n }\n for (const name of offManifest) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'off-manifest-token',\n severity: 'critical',\n description: `Token \"${name}\" is not in the design system's token manifest — no theme defines it, so it renders unset.`,\n fix: `${offManifestHint(name)}Choose a token that exists: the closed vocabulary is the manifest the design-system docs list (colors: var(--ggui-color-primary-500), var(--ggui-color-onContainer), …; spacing: var(--ggui-spacing-4); type: var(--ggui-font-size-sm)). Never invent a name and never add a literal fallback.`,\n line: lineNum,\n });\n }\n\n // Raw CSS length on a spacing / radius prop — bypasses the design\n // scale. Same reasoning as the hardcoded-color checks above: a\n // literal `gap=\"8px\"` defeats the theme's spacing scale exactly as\n // `#fff` defeats its colors. Only the STRING-literal form fails;\n // the numeric escape (`gap={12}`) is untouched, so a genuine\n // off-scale pixel value still has a path.\n const rawSpacingMatch = enforceDesignVocabulary\n ? line.match(\n /\\b(gap|padding|paddingX|paddingY|margin|radius)\\s*=\\s*[\"'][\\d.]+(?:px|rem|em)[\"']/,\n )\n : null;\n if (rawSpacingMatch) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'raw-spacing',\n severity: 'critical',\n description: `\\`${rawSpacingMatch[1]}\\` uses a raw CSS length — bypasses the design spacing/radius scale.`,\n fix: `Use a scale name: ${rawSpacingMatch[1]}=\"xs|sm|md|lg|xl\" (spacing also has none|2xl; radius none|sm|md|lg|xl). For an exact off-scale pixel value pass a number — ${rawSpacingMatch[1]}={12}.`,\n line: lineNum,\n });\n }\n\n // CSS named-color literals on color/background sinks. Closes the\n // residual escape after the hex/rgb checks: `style={{ color:\n // 'lime' }}` or `style={{ background: 'royalblue' }}`. The hex\n // check doesn't match these because they're keyword identifiers,\n // not `#`-prefixed hex. CSS-spec named colors are a finite set;\n // we match the obvious ones the LLM reaches for.\n //\n // Allowed keywords (no fail): `inherit`, `currentColor`,\n // `transparent`, `unset`, `initial`, `revert`, `none`. These have\n // legitimate semantic uses (inherit for nested rendering, none\n // for explicit empty fill).\n //\n // Out-of-scope by design: token-name strings like `color:\n // 'primary'` — those would render as invalid CSS and a separate\n // self-check (the existing prop-value validator) catches them.\n const namedColorMatch = line.match(\n /(?:^|[^a-zA-Z-])(?:color|background|backgroundColor|borderColor)\\s*:\\s*['\"]([a-z][a-zA-Z]+)['\"]/,\n );\n if (namedColorMatch) {\n const named = namedColorMatch[1].toLowerCase();\n const allowed = new Set([\n 'inherit', 'currentcolor', 'transparent',\n 'unset', 'initial', 'revert', 'none',\n ]);\n // Heuristic for the named-color lexicon. Covers every CSS-spec\n // color the LLM has empirically reached for; new keywords can\n // be added as they surface in benchmarks. Token-name strings\n // (`'primary'`) bypass this check because they're not in the\n // lexicon — the prop-value validator catches them as invalid\n // enum values.\n const namedCssColors = new Set([\n 'red', 'green', 'blue', 'yellow', 'orange', 'purple', 'pink',\n 'cyan', 'magenta', 'lime', 'teal', 'navy', 'maroon', 'olive',\n 'aqua', 'fuchsia', 'silver', 'gray', 'grey', 'white', 'black',\n 'brown', 'gold', 'indigo', 'violet', 'crimson', 'tomato',\n 'coral', 'salmon', 'orchid', 'plum', 'tan', 'khaki', 'beige',\n 'ivory', 'lavender', 'mint', 'turquoise', 'azure',\n 'royalblue', 'darkblue', 'lightblue', 'skyblue', 'steelblue',\n 'darkred', 'lightgreen', 'darkgreen', 'forestgreen',\n 'darkorange', 'lightgray', 'lightgrey', 'darkgray', 'darkgrey',\n 'hotpink', 'deeppink', 'lightpink', 'lightyellow',\n ]);\n if (!allowed.has(named) && namedCssColors.has(named)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'named-color',\n severity: 'critical',\n description: `Hardcoded CSS named color \"${named}\" breaks theme switching — use design tokens.`,\n fix: `Replace with a typed slot (Text tone=\"muted\" / Box surface=\"accent\" / Badge variant=\"success\") OR a semantic token: var(--ggui-color-onSunken), var(--ggui-color-primary-500), etc. The keyword \"${named}\" maps to a fixed RGB; the operator's theme has no effect on it.`,\n line: lineNum,\n });\n }\n }\n\n // Raw pixel values in spacing CSS properties\n const pxMatch = enforceDesignVocabulary\n ? line.match(/(?:padding|margin|gap|borderRadius)\\s*:\\s*['\"]?\\d+px/)\n : null;\n if (pxMatch && !line.includes('var(--ggui-')) {\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'tokens',\n subcategory: 'raw-pixels',\n description: 'Raw pixel value in spacing — must use design tokens',\n fix: 'Replace with a bare var(--ggui-spacing-*) token — no literal fallback (the runtime injects every token) — or the scale name on the primitive prop (gap=\"md\", padding=\"lg\")',\n line: lineNum,\n });\n }\n\n // Numeric spacing props on components (e.g., padding={24}, gap={8})\n // These bypass the design system — should use var(--ggui-spacing-*)\n const numericSpacingMatch = enforceDesignVocabulary\n ? line.match(/\\b(padding|paddingX|paddingY|gap|margin)\\s*=\\s*\\{?\\s*(\\d+)\\s*\\}?/)\n : null;\n if (numericSpacingMatch && !line.includes('var(--ggui-')) {\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'tokens',\n subcategory: 'numeric-spacing-prop',\n description: `Numeric spacing prop ${numericSpacingMatch[1]}={${numericSpacingMatch[2]}} — use design tokens instead`,\n fix: `Replace with ${numericSpacingMatch[1]}=\"var(--ggui-spacing-*)\"`,\n line: lineNum,\n });\n }\n }\n\n // ── Clickable trait check — onClick on a structural primitive needs as={Clickable} ──\n // Only the four trait-host primitives (typed `WithTrait<…>`) accept\n // `as={Clickable}`. Text/Heading/Badge/Avatar/Image are NOT hosts, so an\n // onClick on them is a plain type error the type-checker catches — don't\n // steer those toward `as={Clickable}` (it won't compile on them).\n const clickablePattern = /<(?:Card|Box|Stack|Row)\\s[^>]*onClick/;\n for (let i = 0; enforceDesignVocabulary && i < lines.length; i++) {\n if (clickablePattern.test(lines[i]) && !lines[i].includes('as={Clickable}') && !lines[i].includes('as={Pressable}')) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: 'clickable-wrapper',\n description: `onClick on a structural primitive without as={Clickable} — the bare primitive has no click or keyboard handling`,\n fix: `Add as={Clickable} to the element, e.g., <Card as={Clickable} onClick={handler}>`,\n line: i + 1,\n });\n }\n }\n\n // ── Double-wired action check (warn — broad regex) ──────────\n // A useAction callback dispatched from 2+ call sites fires the action\n // more than once per gesture when an interactive element nests inside\n // another (the inner gesture bubbles to the outer handler). Captured\n // in scenario-07: a `Card as={Clickable} onClick` row containing a\n // `Checkbox onChange`, both calling the same action → double-toggle.\n //\n // Binding extraction. The constrained regex is the pre-`designMode`\n // one, kept verbatim: it matches `useAction(` only, so a binding\n // declared with the generic the boilerplate itself emits —\n // `useAction<ActionXPayload>('x')` — is NOT collected there (a\n // pre-existing gap, left in place because the constrained gate must\n // stay byte-identical for the A/B; collapse the two regexes once that\n // pin is lifted). `free` mode accepts the optional generic so the\n // one-gesture-surface invariant actually fires on boilerplate-shaped\n // hook lines.\n const bindingRe =\n designMode === 'free'\n ? /(?:const|let)\\s+(\\w+)\\s*=\\s*useAction\\s*(?:<[^>]*>)?\\s*\\(/g\n : /(?:const|let)\\s+(\\w+)\\s*=\\s*useAction\\s*\\(/g;\n const actionBindings = [...sourceCode.matchAll(bindingRe)]\n .map((m) => m[1])\n .filter((name): name is string => typeof name === 'string');\n for (const binding of actionBindings) {\n const callSites = (\n sourceCode.match(new RegExp(`\\\\b${binding}\\\\s*\\\\(`, 'g')) ?? []\n ).length;\n if (callSites >= 2) {\n // Kept at WARN — too many legit patterns (confirm/cancel, branched\n // dispatch, sibling buttons in a list) match this generic shape. The\n // structural correctness backstop lives at runtime in `useAction`'s\n // task-scoped dedup; this check is a quality nudge for the LLM, not a\n // load-bearing safety gate. See `docs/principles/no-silent-block.md`\n // — three-pattern FP test fails for this detector → severity = warn.\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'interactivity',\n subcategory: 'double-wired-action',\n description: `Action '${binding}' is dispatched from ${callSites} call sites — if an interactive element nests inside another, one gesture fires the action twice (the inner gesture bubbles to the outer handler).`,\n fix: `Wire each useAction callback to exactly ONE interactive surface; never nest interactive elements (e.g. a Checkbox inside a Card as={Clickable}).`,\n });\n }\n }\n\n // ── Double-wired action check (fail — narrow AST) ────────────\n // Precise detector for the unambiguous shape: an outer trait-host JSX\n // element (Card/Box/Stack/Row with `as={Clickable|Pressable}`) wired\n // via onClick/onPress to useAction binding X, with a descendant\n // interactive primitive (Checkbox/Button/Input/Toggle/Slider/\n // RadioGroup/Select/TextArea/Link) wired via on* to the SAME X.\n //\n // Near-zero FP: the only patterns matching `<Card as={Clickable}\n // onClick={X}> ... <Checkbox onChange={X}>` are bugs. Three-pattern\n // FP test passes → severity earns 'fail' per no-silent-block\n // principle Rule 1. The runtime dedup in @ggui-ai/wire's useAction\n // catches the SYMPTOM regardless of shape; this check catches the\n // CAUSE one turn earlier and prevents shipping the broken a11y nest.\n if (actionBindings.length > 0) {\n issues.push(\n ...detectCertainDoubleWiredActions(sourceCode, actionBindings, designMode),\n );\n }\n\n // ── Connection suppression (ggui#670 Phase 2) ────────────────\n // `useRender().isConnected` is a LIVE read of the relay latch, and\n // the ATTEMPT is the runtime's self-heal sensor (#440/#443\n // attempt-always): a dispatch fired while the latch stands is how the\n // runtime discovers the host can relay again. Binding `disabled` to\n // the connection state strips the handler and blinds that sensor —\n // the control stays dead after recovery. The runtime owns the dead\n // zone's presentation (ggui#670 Phase 3: standing notice, then a\n // per-gesture cue) — generated code never suppresses on it. Direct\n // binding only, and only when the source reads\n // `useRender` at all — a same-named `props.isConnected` (a device-\n // status card) is not the connection state. Whole-source scan so a\n // multi-line attribute is caught; the issue reports the attribute's\n // line. The lookbehind keeps `aria-disabled={…}` (the idiom) out.\n if (/\\buseRender\\s*\\(/.test(sourceCode)) {\n const suppressionRe = /(?<![\\w-])disabled\\s*=\\s*\\{([^}]*)\\}/gs;\n for (const m of sourceCode.matchAll(suppressionRe)) {\n const expr = m[1]!;\n if (!/\\bisConnected\\b/.test(expr)) continue;\n const attrLine = sourceCode.slice(0, m.index ?? 0).split('\\n').length;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'interactivity',\n subcategory: 'connection-suppression',\n severity: 'critical',\n description:\n `\\`disabled\\` is bound to the connection state (\\`${expr.trim().replace(/\\s+/g, ' ')}\\`) — that strips the click handler, and the click is how the runtime detects that the host can relay actions again. The control stays dead after recovery.`,\n fix:\n 'Leave the control enabled — never bind `disabled` to the connection state. The runtime presents the dead zone itself (a standing notice, then a per-gesture cue) and the attempt is how it detects recovery; a suppressed control stays dead after the host recovers.',\n line: attrLine,\n });\n }\n }\n\n // ── Optional props accessed without guard ──────────────────\n // Check if Props interface has optional fields that are accessed without ?. or ?? or &&\n const propsInterfaceMatch = sourceCode.match(/interface Props\\s*\\{([^}]+)\\}/);\n if (propsInterfaceMatch) {\n const propsBody = propsInterfaceMatch[1];\n const optionalProps = [...propsBody.matchAll(/(\\w+)\\?:/g)].map(m => m[1]);\n for (const prop of optionalProps) {\n // Check for unguarded access: props.field. (dot access) or props.field[ (bracket access)\n // without being preceded by props.field?. or props.field ?? or props.field &&\n const accessPattern = new RegExp(`props\\\\.${prop}[.\\\\[]`, 'g');\n const guardPattern = new RegExp(`props\\\\.${prop}(\\\\?[.[]|\\\\s*&&|\\\\s*\\\\?\\\\?)`, 'g');\n const accesses = (sourceCode.match(accessPattern) || []).length;\n const guards = (sourceCode.match(guardPattern) || []).length;\n if (accesses > 0 && guards === 0) {\n issues.push({\n tier: 0, result: 'warn', category: 'crash', subcategory: `optional-prop:${prop}`,\n description: `Optional prop 'props.${prop}' accessed without null guard — will crash if undefined`,\n fix: `Use props.${prop}?.field or props.${prop} ?? fallback or {props.${prop} && ...}`,\n });\n }\n }\n }\n\n // ── Common pitfalls (recurring LLM mistakes that cost a turn) ─\n // Scan whole source so multiline opening tags (attrs split across lines) are caught.\n // Each match's line number = the line where the tag opens.\n const ALIGN_VALUES = new Set(['start', 'center', 'end', 'stretch']);\n const JUSTIFY_VALUES = new Set(['start', 'center', 'end', 'between', 'around', 'evenly']);\n const tagRegex = /<(Stack|Row)\\b([^>]*)>/gs;\n for (const tag of enforceDesignVocabulary ? sourceCode.matchAll(tagRegex) : []) {\n const tagName = tag[1];\n const attrs = tag[2];\n const tagLine = sourceCode.slice(0, tag.index).split('\\n').length;\n\n if (/\\bpadding=/.test(attrs)) {\n issues.push({\n tier: 0, result: 'fail', category: 'types', subcategory: 'stack-row-padding',\n description: `<${tagName}> does not accept a 'padding' prop`,\n fix: `Wrap the children in <Box padding=\"...\"> or use the parent <Card padding=\"...\">`,\n line: tagLine,\n });\n }\n const alignAttr = attrs.match(/\\balign=[\"']([^\"']+)[\"']/);\n if (alignAttr && !ALIGN_VALUES.has(alignAttr[1])) {\n issues.push({\n tier: 0, result: 'fail', category: 'types', subcategory: 'stack-row-align',\n description: `align=\"${alignAttr[1]}\" is invalid on <${tagName}>`,\n fix: `Use align=\"start\" | \"center\" | \"end\" | \"stretch\" (NOT flex-start/flex-end/space-between)`,\n line: tagLine,\n });\n }\n const justifyAttr = attrs.match(/\\bjustify=[\"']([^\"']+)[\"']/);\n if (justifyAttr && !JUSTIFY_VALUES.has(justifyAttr[1])) {\n issues.push({\n tier: 0, result: 'fail', category: 'types', subcategory: 'stack-row-justify',\n description: `justify=\"${justifyAttr[1]}\" is invalid on <${tagName}>`,\n fix: `Use justify=\"start\" | \"center\" | \"end\" | \"between\" | \"around\" | \"evenly\"`,\n line: tagLine,\n });\n }\n }\n\n // ── Missing Props interface ───────────────────────────────\n if (!sourceCode.includes('interface Props') && !sourceCode.includes('type Props')) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'types',\n subcategory: 'props-interface',\n severity: 'critical',\n description: 'No Props interface found — data is likely hardcoded',\n fix: 'Add interface Props { ... } with typed fields and default values in the function signature',\n });\n }\n\n // ── Missing default export ────────────────────────────────\n if (!sourceCode.includes('export default function')) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'compile',\n subcategory: 'default-export',\n severity: 'critical',\n description: 'Missing default export function',\n fix: 'Add export default function Component(props: Props) { ... }',\n });\n }\n\n // ── Component never returns its tree ──────────────────────\n // The scaffold hands the model `return (` … `);` around the layout.\n // A root-block rewrite can delete them with it, and bare JSX at\n // statement position compiles, type-checks and renders NOTHING.\n const neverReturns = detectComponentNeverReturns(sourceCode);\n if (neverReturns !== null) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'compile',\n subcategory: 'renders-nothing',\n severity: 'critical',\n description:\n neverReturns.jsxStatementLine === undefined\n ? 'The component never returns its tree — it renders a blank frame'\n : `The component never returns its tree: the JSX at line ${neverReturns.jsxStatementLine} sits at statement position, so it is built and thrown away and the frame renders blank`,\n fix: 'Wrap the tree in the return the boilerplate gave you: `return (` before the root element and `);` after it.',\n ...(neverReturns.jsxStatementLine === undefined ? {} : { line: neverReturns.jsxStatementLine }),\n });\n }\n\n // (Controller-View checks removed — generated components use a\n // single-function pattern.)\n\n // ── Contract validation ───────────────────────────────────\n if (contract) {\n try {\n const contractIssues: ContractIssue[] = validateAllContracts(sourceCode, contract);\n for (const ci of contractIssues) {\n issues.push({\n tier: 0,\n result: ci.severity === 'error' ? 'fail' as const : 'warn' as const,\n category: 'contract' as const,\n subcategory: ci.field,\n severity: ci.severity === 'error' ? 'critical' as const : 'major' as const,\n description: ci.message,\n fix: ci.fix,\n });\n }\n } catch {\n // Contract validation may fail on malformed code — non-blocking\n }\n\n // ── Wire hook usage — every contract hook must be used in the component body ──\n //\n // `actionSpec` / `streamSpec` are flat `Record<name, Entry>` maps.\n // See `@ggui-ai/protocol` DataContract.\n const fnBody = sourceCode.slice(sourceCode.indexOf('export default function'));\n if (contract.actionSpec) {\n for (const actionName of Object.keys(contract.actionSpec)) {\n if (!fnBody.includes(actionName)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `action:${actionName}`,\n description: `Action hook '${actionName}' from contract is declared but never used in the component`,\n fix: `Wire ${actionName}() to a Button onClick, form onSubmit, or other user interaction`,\n });\n }\n }\n }\n if (contract.streamSpec) {\n for (const channelName of Object.keys(contract.streamSpec)) {\n if (!fnBody.includes(channelName)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `stream:${channelName}`,\n description: `Stream hook '${channelName}' from contract is declared but never rendered in the component`,\n fix: `Render ${channelName}.latest data in the JSX (with null guard: ${channelName}.latest && ...)`,\n });\n }\n }\n }\n // agentCapabilities.tools is intentionally NOT checked here — it\n // is a catalog the AGENT invokes, not a component hook surface.\n // Cross-refs surface via actionSpec[*].nextStep and\n // streamSpec[*].source.tool, which the action/stream loops above\n // already cover.\n if (contract.clientCapabilities) {\n // Iterate the flattened `GadgetUse[]` — the export name\n // (`use.name`) is the identity the generated code references.\n for (const use of listContractGadgets(contract)) {\n if (!fnBody.includes(use.name)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `clientCapability:${use.name}`,\n description: `Client capability '${use.name}' from contract is declared but the export is never used`,\n fix: HOOK_NAME_RE.test(use.name)\n ? `Import \\`${use.name}\\` from \\`${use.package}\\` and call it inside the component — bind the return value and surface its \\`.value\\` / \\`.status\\` in JSX.`\n : `Import \\`${use.name}\\` from \\`${use.package}\\` and render it as a JSX element (\\`<${use.name} … />\\`).`,\n });\n }\n }\n }\n\n // ── Wire preservation ─────────────────────────────────────────────────\n // The substring checks above (`fnBody.includes(name)`) are permissive —\n // they pass if the name appears ANYWHERE in the function body, including\n // a comment or unrelated identifier. The AST-backed `checkWirePreservation`\n // is the strict seal: it verifies that the boilerplate-emitted\n // `useAction('<name>')` / `useStream('<name>')` / `useGguiContext('<name>')`\n // hook call ACTUALLY exists, keyed on the string-literal first argument.\n //\n // Catches the abandonment/deletion case: LLM's apply_changes drops the\n // hook call entirely, so the wire never fires at runtime. `pnpm\n // typecheck` can't catch this (a missing call is a missing side effect,\n // not a type error). Seal B fires as `fail` — deterministic, retriable\n // feedback.\n //\n // The runtime auto-commit path (`coding-agent/tools.ts::autoCommit`)\n // calls `runTier0Checks`, which is where this rule lives so it\n // fires on the live generation path.\n try {\n const report = checkWirePreservation(sourceCode, contract);\n for (const site of report.missing) {\n const hook = HOOK_NAME_FOR[site.kind];\n const fix =\n site.kind === 'context'\n ? `Restore \\`const [${site.name}, set${site.name.charAt(0).toUpperCase() + site.name.slice(1)}] = ${hook}('${site.name}')\\` ` +\n `at the top of the component body. The boilerplate auto-emits this destructure for every declared ` +\n `contextSpec slot — do not delete it.`\n : `Restore \\`const ${site.name} = ${hook}('${site.name}')\\` at the top of the ` +\n `component body and consume the returned binding (in JSX, a callback, or an effect).`;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'contract',\n subcategory: `wire_preservation:${site.kind}:${site.name}`,\n severity: 'critical',\n description:\n `Contract declares ${site.kind} '${site.name}' but no ${hook}('${site.name}') ` +\n `call exists in the component. The boilerplate placed this hook for you — ` +\n `do not delete it.`,\n fix,\n });\n }\n } catch {\n // Malformed code surfaces as a primary error elsewhere — don't mask\n // it with a wire-preservation noise-violation here.\n }\n\n // ── Props field rendering — verify each prop is actually used in the component ──\n if (contract.propsSpec) {\n const propsProperties = contract.propsSpec.properties ?? {};\n for (const propName of Object.keys(propsProperties)) {\n // Check if prop is referenced in the function body (via props.fieldName)\n if (!fnBody.includes(`props.${propName}`) && !fnBody.includes(`{props.${propName}}`)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `prop:${propName}`,\n description: `Props field '${propName}' from contract is never rendered — data is wasted`,\n fix: `Render props.${propName} in the JSX (e.g., <Text>{props.${propName}}</Text>)`,\n });\n }\n }\n }\n }\n\n // ── Wire_undeclared (UNCONDITIONAL) ──────────────────────────────────\n //\n // Every wire-call site in the emitted code MUST correspond to a\n // declared entry on the agent-authored `contract`, regardless of\n // whether the contract is partially or wholly absent. Empty contract\n // → ALL wire calls are \"extra\" → all fail with `wire_undeclared`.\n // Failure mode this guards against: agent describes contextSpec in\n // plain prompt text but doesn't author `contract`; the LLM emits\n // `useGguiContext('foo')` / `useAction('foo')` with no slot\n // registration; the iframe crashes at first paint with\n // `[ggui] useGguiContext('foo'): no Context registered`. The\n // remediation message names the exact contract field to declare on,\n // so the agent's next turn can fix structurally.\n try {\n const contractsForExtraCheck: DataContract = contract ?? {};\n const extras = checkWirePreservation(sourceCode, contractsForExtraCheck).extra;\n for (const site of extras) {\n const hook = HOOK_NAME_FOR[site.kind];\n const field = CONTRACT_FIELD_FOR[site.kind];\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'contract',\n subcategory: `wire_undeclared:${site.kind}:${site.name}`,\n severity: 'critical',\n description:\n `Component calls ${hook}('${site.name}') but the contract does not declare ` +\n `${site.kind} '${site.name}'. Every wire reference in the generated code MUST ` +\n `correspond to a declared entry on the agent-authored contract — the runtime ` +\n `mounts/registers wire surfaces from the contract, not from the code. ` +\n (contract === undefined\n ? 'No contract authored at all — describing the contract in the prompt text is NOT enough; ' +\n 'the agent MUST pass a structured `contract` field on the ggui_render call.'\n : ''),\n fix:\n `Either (a) declare \\`${field}.${site.name}\\` on the \\`contract\\` input so the ` +\n `runtime registers the surface for this UI, or (b) remove the ${hook}('${site.name}') ` +\n `call from the component if it isn't part of the intended wire surface.`,\n });\n }\n } catch {\n // Malformed code surfaces elsewhere; don't mask with noise.\n }\n\n // ── Wire-hook import presence ────────────────────────────────────────\n //\n // `rewriteImports` (packages/design/src/rendering/rewrite-imports.ts) only\n // substitutes `from '@ggui-ai/wire'` specifiers that already exist in the\n // compiled code; a hook call like `useAction('X')` without the paired\n // `import { useAction } from '@ggui-ai/wire'` line leaves no specifier\n // for the shim to attach, so the hook is undeclared at eval time and the\n // browser throws `ReferenceError: useAction is not defined`. This check\n // runs unconditionally (no contract needed) — for every wire hook the\n // component CALLS at least once, the matching named import must be\n // present at top level. Independent of `wire_preservation` which checks\n // that contract-declared hooks are called.\n try {\n const importReport = checkWireImports(sourceCode);\n for (const miss of importReport.missing) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: `wire_import_missing:${miss.hook}`,\n severity: 'critical',\n description:\n `Component calls ${miss.hook}(...) but does not import it from ` +\n `'@ggui-ai/wire'. Without the import, rewriteImports has no ` +\n `specifier to attach the data-URL shim to, so the hook is ` +\n `undeclared at browser eval time and the component crashes on ` +\n `mount with \\`ReferenceError: ${miss.hook} is not defined\\`.`,\n fix:\n `Add \\`import { ${miss.hook} } from '@ggui-ai/wire';\\` at the ` +\n `top of the file alongside the other imports.`,\n });\n }\n } catch {\n // Malformed code surfaces as a primary error elsewhere — don't mask it.\n }\n\n // ── No-require pattern for @-scoped packages ─────────────────────────\n //\n // A repeating LLM failure mode: when the boilerplate emits a static\n // `import { useLeafletMap } from '@ggui-samples/gadget-leaflet'`, the\n // model sometimes removes the import and substitutes\n // `const { useLeafletMap } = require('@ggui-samples/gadget-leaflet')`\n // (or `require('@ggui-ai/gadgets')`) inline. That FAILS in a real\n // browser ESM iframe: `require` is not defined, and `rewriteImports`\n // never sees a static `from '<pkg>'` specifier to attach the data-URL\n // shim to.\n //\n // This check rejects any `require('@...')` call expression on an\n // @-scoped package. The fix is always the same — convert to a\n // top-level static `import { … } from '<pkg>'`. Targeted at @-scoped\n // packages because that's the LLM's typical hedge specifier shape\n // (CJS bare `require('react')` etc. don't appear in our generated\n // code path).\n {\n // Match `require('@scope/pkg')` and `require(\"@scope/pkg\")` with a\n // simple regex. The LLM only emits this pattern as call\n // expressions, so the false-positive rate is negligible in\n // practice; an AST walk would be more rigorous but unnecessary.\n const requireRe = /require\\s*\\(\\s*['\"](@[^'\"]+)['\"]\\s*\\)/g;\n const seen = new Set<string>();\n let m: RegExpExecArray | null;\n while ((m = requireRe.exec(sourceCode)) !== null) {\n const pkg = m[1];\n if (pkg === undefined || seen.has(pkg)) continue;\n seen.add(pkg);\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: `require_disallowed:${pkg}`,\n severity: 'critical',\n description:\n `Component uses \\`require('${pkg}')\\` — CommonJS require is ` +\n `not available in the iframe's browser ESM runtime, and the ` +\n `import-rewriter only attaches data-URL shims to STATIC import ` +\n `specifiers. The component will fail to mount with ` +\n `\\`ReferenceError: require is not defined\\` at the first call.`,\n fix:\n `Replace with a top-level static \\`import { … } from '${pkg}'\\` ` +\n `at the top of the file. The boilerplate emits this import for ` +\n `you when the contract declares a matching ` +\n `\\`clientCapabilities.gadgets[*]\\` entry — restore the line ` +\n `instead of inlining a require() call.`,\n });\n }\n }\n\n // ── gadget import preservation ───────────────────────────────────────\n //\n // Gadgets are DIRECT-imported. The boilerplate emits, per\n // registered gadget package, one combined import:\n // `import { useLeafletMap } from '@scope/leaflet';`\n // The LLM (correctly) intuits the hook is runtime-resolved and tends\n // to delete the import — but the import IS the resolution anchor: the\n // iframe rewriter rewrites the package specifier to a per-package\n // shim, and without the import the hook is unbound (ReferenceError).\n //\n // This check verifies, for every contract-declared gadget export,\n // that it is still imported from its package. The export NAME\n // appearing alone is not enough — the `import { … }` statement must\n // carry it. Hooks AND components are both direct-imported and\n // both checked here; the fix hint adapts to the export kind (hooks\n // are CALLED, components are RENDERED as JSX).\n {\n // Scan comment-free source — a commented-out import must NOT\n // satisfy the preservation check.\n const gadgetScanSource = stripComments(sourceCode);\n // Iterate the flattened `GadgetUse[]`. Kind is discriminated\n // by the export-name grammar — `use`-prefixed → hook, else component.\n for (const use of contract ? listContractGadgets(contract) : []) {\n const exportName = use.name;\n if (isGadgetExportImported(gadgetScanSource, use.package, exportName)) {\n continue;\n }\n const isComponent = !HOOK_NAME_RE.test(exportName);\n const kind = isComponent ? 'component' : 'hook';\n // Local binding name for the hook worked example (mirrors the\n // boilerplate's derivation: strip `use`, lowercase first char).\n const bindingName =\n exportName.length > 3\n ? exportName.charAt(3).toLowerCase() + exportName.slice(4)\n : exportName;\n const fix = isComponent\n ? `The component \\`${exportName}\\` is REAL and CORRECT — do NOT remove it. ` +\n `Restore the gadget plumbing in 2 steps:\\n` +\n `(1) Keep \\`import { ${exportName} } from '${use.package}';\\` at the top of the file.\\n` +\n `(2) RENDER \\`<${exportName} … />\\` as a JSX element in the tree you return — pass its props from the contract. Do NOT call it like a hook.\\n` +\n `Import \\`${exportName}\\` ONLY from '${use.package}' — that is the package it is registered under. If you remove the import again, this check will fail again — \\`${exportName}\\` is not optional.`\n : `The hook \\`${exportName}\\` is REAL and CORRECT — do NOT remove it. ` +\n `Restore the gadget plumbing in 2 steps:\\n` +\n `(1) Keep \\`import { ${exportName} } from '${use.package}';\\` at the top of the file.\\n` +\n `(2) CALL \\`${exportName}(...)\\` inside the component body and render its return value. Example:\\n` +\n ` \\`const ${bindingName} = ${exportName}({ /* props from contract */ });\\`\\n` +\n ` \\`return <div>{/* render ${bindingName} */}</div>;\\`\\n` +\n `Import \\`${exportName}\\` ONLY from '${use.package}' — that is the package it is registered under. If you remove the import again, this check will fail again — \\`${exportName}\\` is not optional.`;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: `gadget_preservation:${exportName}`,\n severity: 'critical',\n description:\n `Contract declares \\`clientCapabilities.gadgets['${use.package}']['${exportName}']\\` ` +\n `(a ${kind}) but the ` +\n `component does not import \\`${exportName}\\` from \\`${use.package}\\`. ` +\n `The boilerplate emits \\`import { ${exportName} } from '${use.package}';\\` ` +\n `— keep it. Without the import the iframe runtime cannot resolve the ` +\n `${kind} and the registered gadget is unreachable.`,\n fix,\n });\n }\n }\n\n // ── TypeScript type checking + React hooks linting ──────────\n const [typeResult, reactResult] = await Promise.all([\n typecheck(sourceCode, gadgetTypes).catch((err) => {\n console.warn('[runTier0Checks] TypeChecker failed:', err instanceof Error ? err.message : String(err));\n return null;\n }),\n lintReactHooks(sourceCode).catch((err) => {\n console.warn('[runTier0Checks] React linter failed:', err instanceof Error ? err.message : String(err));\n return [] as ReactLintDiagnostic[];\n }),\n ]);\n\n // TS type errors → fail, warnings → warn\n if (typeResult) {\n for (const error of typeResult.errors) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'types',\n subcategory: `ts${error.code}`,\n description: error.message,\n fix: error.fix,\n line: error.line,\n });\n }\n for (const warning of typeResult.warnings) {\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'types',\n subcategory: `ts${warning.code}`,\n description: warning.message,\n fix: warning.fix,\n line: warning.line,\n });\n }\n }\n\n // React hooks violations — errors → fail, warnings → warn\n for (const diag of reactResult) {\n issues.push({\n tier: 0,\n result: diag.severity === 'error' ? 'fail' : 'warn',\n category: 'types',\n subcategory: diag.rule,\n description: diag.message,\n fix: diag.fix,\n line: diag.line,\n });\n }\n\n // Populate priority on every tier-0 issue. No current code path reads\n // `.priority` — it is reserved for future eval-policy consumption.\n for (const issue of issues) {\n if (!issue.priority) issue.priority = priorityForIssue(issue.category);\n }\n\n return issues;\n}\n\n/**\n * Run tier 0 checks and return a full EvalResult with pass list.\n */\nexport async function runTier0(\n sourceCode: string,\n contract?: DataContract,\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n): Promise<EvalResult> {\n const issues = await runTier0Checks(sourceCode, contract, undefined, undefined, designMode);\n const pass: string[] = [];\n\n // Build pass list from categories that had no issues\n const failedCategories = new Set(issues.map(i => i.category));\n const tier0Categories: EvalCategory[] = ['compile', 'security', 'contract', 'types', 'imports', 'tokens'];\n\n for (const cat of tier0Categories) {\n if (!failedCategories.has(cat)) {\n pass.push(cat);\n }\n }\n\n return { issues, pass };\n}\n\n// Tier-0 deterministic checks are run above. Axis-gated mode checks are\n// dispatched from `evaluation/axis-checks/` — see `runAxisChecks`.\n","// Sample props from a PropsSpec — `example` first, then `default`, then a type-driven fill from the JSON\n// Schema. Pure: protocol types only, no sandbox, no node modules, so `@ggui-ai/ui-gen/check` can export it and a\n// caller outside the harness (an experiment's judge input, ggui#1386) synthesizes the SAME props the coding\n// agent's own render check falls back to. Moved verbatim out of `tools/render-check.ts` (2026-09-26).\nimport type { JsonObject, JsonSchema, JsonValue, PropsSpec } from '@ggui-ai/protocol';\n\n/**\n * Generate sample props from a PropsSpec contract.\n * Uses `example` values from each PropEntry when available,\n * otherwise synthesizes plausible defaults from the JSON Schema.\n */\nexport function generateSampleProps(spec: PropsSpec): JsonObject {\n const props: JsonObject = {};\n\n for (const [name, entry] of Object.entries(spec.properties)) {\n // Prefer explicit example value\n if (entry.example !== undefined) {\n props[name] = entry.example;\n continue;\n }\n\n // Prefer explicit default value\n if (entry.default !== undefined) {\n props[name] = entry.default;\n continue;\n }\n\n // Synthesize from JSON Schema\n props[name] = synthesizeFromSchema(entry.schema);\n }\n\n return props;\n}\n\nfunction synthesizeFromSchema(schema: JsonSchema): JsonValue | undefined {\n // Draft-07 type arrays (`['string','null']`) synthesize from the\n // first non-null member — the canonical nullability form the\n // enforced-props-schema emission produces.\n const declared = Array.isArray(schema.type)\n ? schema.type.find((t) => t !== 'null')\n : schema.type;\n switch (declared) {\n case 'string': return 'sample';\n case 'number':\n case 'integer': return 0;\n case 'boolean': return false;\n case 'null': return null;\n case 'array': {\n if (schema.items) return [synthesizeFromSchema(schema.items) ?? null];\n return [];\n }\n case 'object': {\n const obj: JsonObject = {};\n if (schema.properties) {\n for (const [k, v] of Object.entries(schema.properties)) {\n obj[k] = synthesizeFromSchema(v);\n }\n }\n return obj;\n }\n default: return undefined;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/check/extract-wire-calls.ts","../../src/boilerplate/json-schema-ts.ts","../../src/check/contract-validation.ts","../../src/validation/allowed-imports.ts","../../src/check/type-checker.ts","../../src/check/react-linter.ts","../../src/design-mode.ts","../../src/taught-tokens.ts","../../src/evaluation/types-public.ts","../../src/check/run-tier0.ts","../../src/check/sample-props.ts"],"names":["ts","resolved","consumedTokenManifest","hit"],"mappings":";;;;;;;;;;AAuGA,IAAM,YAAA,GAAmD;AAAA,EACvD,SAAA,EAAW,QAAA;AAAA,EACX,SAAA,EAAW,QAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMX,cAAA,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAMlB,CAAA;AAGA,IAAM,cAAA,GAAiB,MAAA,CAAO,IAAA,CAAK,YAAY,CAAA;AAYxC,SAAS,qBAAqB,IAAA,EAA8B;AACjE,EAAA,MAAM,KAAKA,GAAA,CAAG,gBAAA;AAAA,IACZ,eAAA;AAAA,IACA,IAAA;AAAA,IACAA,IAAG,YAAA,CAAa,MAAA;AAAA;AAAA,IACG,IAAA;AAAA,IACnBA,IAAG,UAAA,CAAW;AAAA,GAChB;AACA,EAAA,MAAM,QAAwB,EAAC;AAE/B,EAAA,SAAS,MAAM,IAAA,EAAqB;AAClC,IAAA,IAAIA,GAAA,CAAG,gBAAA,CAAiB,IAAI,CAAA,EAAG;AAC7B,MAAA,MAAM,SAAS,IAAA,CAAK,UAAA;AAIpB,MAAA,IAAIA,GAAA,CAAG,YAAA,CAAa,MAAM,CAAA,EAAG;AAC3B,QAAA,MAAM,IAAA,GAAO,YAAA,CAAa,MAAA,CAAO,IAAI,CAAA;AACrC,QAAA,IAAI,IAAA,EAAM;AACR,UAAA,MAAM,QAAA,GAAW,IAAA,CAAK,S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AC,CAAA,GAAI,oBAAA,CAAqB,CAAC,CAAA;AAAA,QACjC;AAAA,MACF;AACA,MAAA,OAAO,GAAA;AAAA,IACT;AAAA,IACA;AAAS,MAAA,OAAO,MAAA;AAAA;AAEpB","file":"index.js","sourcesContent":["// packages/ui-gen/src/check/extract-wire-calls.ts\n//\n// AST helper for wire-call-site extraction + sibling `checkWireImports`\n// for OSS tier-0 gate coverage.\n//\n// Used by:\n// (1) Tier-0 `wire_preservation` check — verifies the LLM hasn't\n// deleted a boilerplate-emitted hook call via `apply_patch`.\n// Deletion cannot be caught by `pnpm typecheck` alone because a\n// hook that is never called simply doesn't fire; the TypeScript\n// checker has no opinion on absence.\n// (2) Tier-0 `wire_import` check — verifies every\n// wire hook the component calls also appears as a named import\n// from `@ggui-ai/wire` at top level. Missing imports turn into\n// `ReferenceError` at mount because `rewriteImports` only\n// activates the data-URL shim for specifiers that already exist\n// in the code.\n// (3) Axis check (future) — same report shape, surfaced at eval tier\n// alongside the other deterministic axes.\n//\n// Keying is on the STRING-LITERAL first argument of the hook call, NOT\n// the variable name bound to its result. An LLM that renames\n// `const submit = useAction('submit')` to `const onSubmit =\n// useAction('submit')` is authoring the SAME wire — the identifier is\n// ergonomic sugar, the wire contract is the string. This matches the\n// `@ggui-ai/wire` hook semantics: the dispatcher routes by name.\n//\n// Regex was deliberately rejected for the call-site walk. Hook calls\n// inside callbacks, behind variable aliases, or wrapped in `useMemo`/\n// `useCallback` dependency arrays would fool a regex scan. The TS\n// compiler API walks the real AST and never confuses `useAction`\n// identifier references (e.g. in a dependency array) with actual\n// `useAction(...)` call expressions.\n\nimport ts from \"typescript\";\nimport type { DataContract } from \"@ggui-ai/protocol\";\n\n/**\n * The four contract-declared wire kinds, matching `@ggui-ai/wire` hooks.\n *\n * `'context'` covers `useGguiContext` calls. The iframe-runtime mounts\n * Contexts only when the bootstrap envelope carries `contextSlots`,\n * which fires only when the persisted GguiSession has `contextSpec`,\n * which happens only when the agent authored\n * `story.contract.contextSpec` AND render.ts plumbed it to the\n * generator. The symptom of a missing slot is a blank `/r/<id>` direct\n * preview when the LLM emitted `useGguiContext('X')` without a\n * declared slot. The undeclared-wire-call check (tier-0\n * `wire_undeclared`) catches the drift fail-loud at gen time so the\n * agent gets a remediation message instead of a silent blank page.\n *\n * `'clientTool'` retired 2026-05-11 alongside `useClientTool` +\n * `clientTools` → `clientCapabilities` reframe. Capability hooks\n * import from `@ggui-ai/gadgets` (or other vendor packages),\n * not from `@ggui-ai/wire`, so they fall outside the wire-import\n * tier-0 gate by construction.\n */\nexport type WireKind =\n | \"action\"\n | \"stream\"\n | \"context\";\n\n/** A single extracted wire reference — either from code or from the contract. */\nexport interface WireCallSite {\n readonly kind: WireKind;\n /** The string-literal argument to the hook, matching the contract key. */\n readonly name: string;\n}\n\n/**\n * Bidirectional completeness report between a contract and a component's\n * hook call sites. `missing` = contract-declared but absent from code;\n * `extra` = present in code but not declared on the contract. Item 3b\n * compile narrowing (`InferActionNames<T>` / `InferStreamNames<T>`)\n * already rejects `extra` at typecheck time — this report is primarily\n * consumed by the `wire_preservation` tier-0 check for the `missing`\n * direction.\n */\nexport interface WirePreservationReport {\n readonly missing: WireCallSite[];\n readonly extra: WireCallSite[];\n}\n\n/**\n * Report from `checkWireImports`. Each entry names a wire hook the\n * component CALLS at least once but does NOT import from\n * `@ggui-ai/wire` at the top level. Hook-name collisions (e.g. a\n * user-defined `useAction` in the same scope) are out of scope —\n * generated code lives inside the boilerplate frame, which declares\n * the hooks as imports and nothing else by that name.\n */\nexport interface WireImportReport {\n /** Hooks the component calls but does not import. */\n readonly missing: readonly WireImportSite[];\n}\n\nexport interface WireImportSite {\n /** The hook function name — `useAction` / `useStream` / etc. */\n readonly hook: string;\n /** The matching `WireKind` for reporting symmetry. */\n readonly kind: WireKind;\n}\n\nconst HOOK_TO_KIND: Readonly<Record<string, WireKind>> = {\n useAction: \"action\",\n useStream: \"stream\",\n // `useGguiContext('slot')` is the client→agent observable-state\n // hook. Treated as a wire call site for tier-0 preservation +\n // undeclared detection because the runtime registers one\n // React.Context per declared contextSpec slot at boot — referencing\n // an undeclared slot throws synchronously at first paint.\n useGguiContext: \"context\",\n // Pre-rename component-side tool hooks are retired. The contract's\n // `agentCapabilities.tools` catalog is agent-side declaration only —\n // no component hook surface. Cross-refs surface via\n // `actionSpec[*].nextStep` (already covered by the `action` kind)\n // and `streamSpec[*].source.tool` (covered by `stream`).\n};\n\n/** All known wire hook names — iteration source for `checkWireImports`. */\nconst ALL_WIRE_HOOKS = Object.keys(HOOK_TO_KIND) as ReadonlyArray<\n keyof typeof HOOK_TO_KIND\n>;\n\n/**\n * Walk the TSX AST and collect every call expression whose callee is one\n * of the four wire hooks AND whose first argument is a string literal.\n * Non-literal first arguments (e.g. `useAction(dynamicName)`) are\n * intentionally ignored — the generator always emits string literals,\n * and the contract keys by literal, so an indirection through a\n * variable can't carry the wiring.\n */\nexport function extractWireCallSites(code: string): WireCallSite[] {\n const sf = ts.createSourceFile(\n \"component.tsx\",\n code,\n ts.ScriptTarget.Latest,\n /*setParentNodes*/ true,\n ts.ScriptKind.TSX,\n );\n const sites: WireCallSite[] = [];\n\n function visit(node: ts.Node): void {\n if (ts.isCallExpression(node)) {\n const callee = node.expression;\n // Match bare hook identifiers. We do NOT match\n // `React.useAction(...)` or other member-accessed forms — wire\n // hooks are always imported by name from `@ggui-ai/wire`.\n if (ts.isIdentifier(callee)) {\n const kind = HOOK_TO_KIND[callee.text];\n if (kind) {\n const firstArg = node.arguments[0];\n if (firstArg && ts.isStringLiteral(firstArg)) {\n sites.push({ kind, name: firstArg.text });\n }\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return sites;\n}\n\n/**\n * Walk top-level `import` statements and collect named specifiers\n * imported from `@ggui-ai/wire`. Returns the set of local-binding\n * names (not aliased source names) because the checker compares\n * against identifiers USED by call expressions in the body.\n *\n * Default imports and namespace imports (`import * as w from ...`) are\n * ignored — the `@ggui-ai/wire` shim exports named members only, and\n * generated code always reaches for them by name.\n */\nexport function extractWireImports(code: string): ReadonlySet<string> {\n const sf = ts.createSourceFile(\n \"component.tsx\",\n code,\n ts.ScriptTarget.Latest,\n /*setParentNodes*/ true,\n ts.ScriptKind.TSX,\n );\n const imported = new Set<string>();\n\n for (const stmt of sf.statements) {\n if (!ts.isImportDeclaration(stmt)) continue;\n const moduleSpecifier = stmt.moduleSpecifier;\n if (!ts.isStringLiteral(moduleSpecifier)) continue;\n if (moduleSpecifier.text !== \"@ggui-ai/wire\") continue;\n\n const clause = stmt.importClause;\n if (!clause) continue;\n const bindings = clause.namedBindings;\n if (!bindings) continue;\n if (!ts.isNamedImports(bindings)) continue;\n for (const el of bindings.elements) {\n // `import { useAction as a }` — the LOCAL name is what the body\n // references. But generated code never aliases wire hooks, so\n // reading `el.name.text` for both aliased and bare forms stays\n // correct either way (local = bare when no alias).\n imported.add(el.name.text);\n }\n }\n\n return imported;\n}\n\n/**\n * Enumerate every wire a contract declares. Parallels the generator's\n * emission order in `generateBoilerplate` — actions, streams, context\n * slots. Contract-key typing matches the `@ggui-ai/protocol` canonical\n * flat-map shape.\n *\n * `agentCapabilities.tools` and `clientCapabilities` are NOT enumerated:\n * - `agentCapabilities.tools` is a catalog the AGENT invokes (no component hook).\n * Cross-references surface via `actionSpec[*].nextStep` and\n * `streamSpec[*].source.tool`, already covered by `action` / `stream`.\n * - `clientCapabilities` are declarations of browser-capability hooks\n * imported from `@ggui-ai/gadgets` (or another vendor package).\n * They are NOT `@ggui-ai/wire` hooks and do NOT participate in the\n * wire-import tier-0 gate.\n */\nexport function collectExpectedWires(contract: DataContract): WireCallSite[] {\n const expected: WireCallSite[] = [];\n\n const actionsMap = contract.actionSpec ?? {};\n for (const name of Object.keys(actionsMap)) {\n expected.push({ kind: \"action\", name });\n }\n\n const streamsMap = contract.streamSpec ?? {};\n for (const name of Object.keys(streamsMap)) {\n expected.push({ kind: \"stream\", name });\n }\n\n // contextSpec slots. Each declared slot becomes one\n // `useGguiContext('<slot>')` call site the boilerplate auto-emits\n // at the top of the component body. Without this in the expected\n // set, an LLM emitting an undeclared useGguiContext call slips\n // through and the runtime throws on mount (no Context registered\n // for that slot), blanking the iframe.\n const contextMap = contract.contextSpec ?? {};\n for (const name of Object.keys(contextMap)) {\n expected.push({ kind: \"context\", name });\n }\n\n return expected;\n}\n\n/**\n * Diff the component's observed wire call sites against the contract's\n * expected wires. Symmetric set difference by `(kind, name)` pair.\n */\nexport function checkWirePreservation(\n code: string,\n contract: DataContract,\n): WirePreservationReport {\n const expected = collectExpectedWires(contract);\n const actual = extractWireCallSites(code);\n\n const actualKeys = new Set(actual.map((s) => `${s.kind}:${s.name}`));\n const expectedKeys = new Set(expected.map((s) => `${s.kind}:${s.name}`));\n\n const missing = expected.filter((s) => !actualKeys.has(`${s.kind}:${s.name}`));\n const extra = actual.filter((s) => !expectedKeys.has(`${s.kind}:${s.name}`));\n\n return { missing, extra };\n}\n\n/**\n * Guards against this failure class: componentCode calls a wire hook\n * but doesn't import it, so the data-URL shim rewrite has no\n * specifier to attach to and the hook is undeclared at eval time. Run\n * `extractWireCallSites` for the used set, `extractWireImports` for\n * the imported set, and emit the setwise difference.\n *\n * This is purely a STATIC check — it doesn't care whether the contract\n * declares each hook (that's `checkWirePreservation`'s job). Its only\n * question is: every hook the generated code CALLS, is it imported?\n * Yes → silent. No → report. A hook that is imported but unused is\n * caught by the existing `no-unused-vars` lint, not by this check.\n */\nexport function checkWireImports(code: string): WireImportReport {\n const used = extractWireCallSites(code);\n const imports = extractWireImports(code);\n const usedHookSet = new Set(\n used.map(\n (s) =>\n // Reverse the kind → hook-name lookup. Closed set of 5 —\n // hardcoded to stay cheap and explicit.\n ({\n action: \"useAction\",\n stream: \"useStream\",\n context: \"useGguiContext\",\n })[s.kind],\n ),\n );\n\n const missing: WireImportSite[] = [];\n for (const hook of ALL_WIRE_HOOKS) {\n if (!usedHookSet.has(hook)) continue;\n if (imports.has(hook)) continue;\n missing.push({ hook, kind: HOOK_TO_KIND[hook] });\n }\n\n return { missing };\n}\n","// packages/ui-gen/src/boilerplate/json-schema-ts.ts\n//\n// JSON Schema → TypeScript type string converter.\n//\n// Pure, self-contained, no env reads, no framework deps. Exposed\n// publicly on `@ggui-ai/ui-gen/boilerplate` because it's the primitive\n// that turns a contract's JSON Schema into the `interface Props { ... }`\n// block the boilerplate generator writes.\n\nimport type { JsonSchema } from '@ggui-ai/protocol';\n\n/**\n * Convert a JsonSchema to a TypeScript type string — recursive.\n *\n * Handles: string, number, integer, boolean, null, array (+ tuples), object,\n * enum, oneOf/anyOf (unions), nullable, const, additionalProperties.\n */\nexport function jsonSchemaTypeToTs(schema: JsonSchema): string {\n // ── Union types (oneOf / anyOf) ──\n const unionMembers = schema.oneOf ?? schema.anyOf;\n if (unionMembers?.length) {\n const types = [...new Set(unionMembers.map(s => jsonSchemaTypeToTs(s)))];\n return types.length === 1 ? types[0] : types.join(' | ');\n }\n\n // ── Const (literal type) ──\n if (schema.const !== undefined) {\n return typeof schema.const === 'string' ? `'${schema.const}'` : String(schema.const);\n }\n\n // ── Enum (union of literals) ──\n if (schema.enum?.length) {\n return schema.enum\n .map(v => typeof v === 'string' ? `'${v}'` : String(v))\n .join(' | ');\n }\n\n // ── Draft-07 type array (`['string','null']` — the canonical\n // nullable form since draft-2026-08-19): members' TS union. Each\n // member re-enters with the single type so object/array members\n // keep their properties/items; `nullable` is folded in here (not in\n // the recursion) so it can't double-append. ──\n if (Array.isArray(schema.type)) {\n const { nullable: _nullable, ...rest } = schema;\n const members = [...new Set(schema.type)].map((member) =>\n jsonSchemaTypeToTs({ ...rest, type: member }),\n );\n const unique = [...new Set(members)];\n if (schema.nullable && !unique.includes('null')) unique.push('null');\n return unique.join(' | ');\n }\n\n let result: string;\n\n switch (schema.type) {\n case 'string':\n result = 'string';\n break;\n case 'number':\n case 'integer':\n result = 'number';\n break;\n case 'boolean':\n result = 'boolean';\n break;\n case 'null':\n return 'null';\n\n case 'array': {\n if (schema.items) {\n const itemType = jsonSchemaTypeToTs(schema.items);\n // Use Array<T> for complex object types, T[] for simple.\n // `items.type` may be a type SET — treat any set containing\n // 'object' like the single-string form.\n const itemsDeclareObject = Array.isArray(schema.items.type)\n ? schema.items.type.includes('object')\n : schema.items.type === 'object';\n result = (itemsDeclareObject && schema.items.properties)\n ? `Array<${itemType}>`\n : (itemType.includes('|') ? `(${itemType})[]` : `${itemType}[]`);\n } else {\n result = 'unknown[]';\n }\n break;\n }\n\n case 'object': {\n if (schema.properties) {\n const required = schema.required ?? [];\n const fields = Object.entries(schema.properties)\n .map(([key, prop]) => {\n const opt = !required.includes(key);\n return `${key}${opt ? '?' : ''}: ${jsonSchemaTypeToTs(prop)}`;\n })\n .join('; ');\n result = `{ ${fields} }`;\n } else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {\n result = `Record<string, ${jsonSchemaTypeToTs(schema.additionalProperties)}>`;\n } else {\n result = 'Record<string, unknown>';\n }\n break;\n }\n\n default:\n result = 'unknown';\n }\n\n // Apply nullable (OpenAPI 3.0 shorthand)\n if (schema.nullable && result !== 'unknown') {\n return `${result} | null`;\n }\n\n return result;\n}\n","// packages/ui-gen/src/check/contract-validation.ts\n//\n// Shared validation utilities for data-contract conformance —\n// deterministic tier-0 gate for `PropsSpec` / `StreamSpec` / `ActionSpec`\n// agreement between the LLM-emitted componentCode and the contract the\n// agent handed to `ggui_render`.\n//\n// Used by:\n// (1) Self-check soft gate in the coding agent\n// (`coding-agent/self-check.ts`) — surfaces mismatches as\n// structured violations for the LLM retry loop.\n// (2) Tier-0 hard gate in the evaluation pipeline — errors (severity\n// `error`) are blocking; warnings surface as advisory.\n// (3) Adapter tool-family wiring for multi-SDK generation runs.\n// (4) Benchmarks + LLM prompt construction — `jsonSchemaTypeToTs` +\n// `propsSpecToTypeScript` + `inferPropsSpecFromSampleData` are\n// pure helpers reused outside the check path. Re-exported here so\n// those callers don't need a separate import for the subpath.\n//\n// Deps are pure: `@ggui-ai/protocol` (public types) + `typescript`\n// (compiler API) + the in-package `jsonSchemaTypeToTs` primitive from\n// `../boilerplate/json-schema-ts.js`.\n\nimport type {\n PropsSpec,\n StreamSpec,\n ActionSpec,\n DataContract,\n JsonSchema,\n JsonValue,\n PropEntry,\n JsonObject,\n} from \"@ggui-ai/protocol\";\nimport ts from \"typescript\";\n\n// Re-export the pure JSON-Schema → TypeScript-type converter from the\n// in-package `boilerplate/` primitive, so consumers of the tier-0 check\n// surface (self-check, tiers, benchmarks, prompts, adapters) import a\n// single symbol from a single subpath.\nexport { jsonSchemaTypeToTs } from \"../boilerplate/json-schema-ts.js\";\nimport { jsonSchemaTypeToTs } from \"../boilerplate/json-schema-ts.js\";\n\n// =============================================================================\n// Contract Issue\n// =============================================================================\n\nexport interface ContractIssue {\n severity: \"error\" | \"warning\";\n field: string;\n message: string;\n fix: string;\n}\n\n// =============================================================================\n// Props Interface Extraction (AST-based)\n// =============================================================================\n\ninterface ExtractedProp {\n name: string;\n type: string;\n optional: boolean;\n}\n\n/**\n * Extract field names and types from a TypeScript Props interface in source code.\n * Uses the TypeScript compiler API — handles nested types, generics, unions correctly.\n */\nexport function extractPropsInterface(code: string): ExtractedProp[] | null {\n const sf = ts.createSourceFile(\"component.tsx\", code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);\n const props: ExtractedProp[] = [];\n\n function visitMembers(members: ts.NodeArray<ts.TypeElement>): void {\n for (const member of members) {\n if (ts.isPropertySignature(member) && member.name) {\n const name = member.name.getText(sf);\n const type = member.type ? member.type.getText(sf) : \"unknown\";\n const optional = !!member.questionToken;\n props.push({ name, type, optional });\n }\n }\n }\n\n function visit(node: ts.Node): void {\n // interface Props { ... }\n if (ts.isInterfaceDeclaration(node) && node.name.text === \"Props\") {\n visitMembers(node.members);\n return;\n }\n // type Props = { ... }\n if (ts.isTypeAliasDeclaration(node) && node.name.text === \"Props\") {\n if (ts.isTypeLiteralNode(node.type)) {\n visitMembers(node.type.members);\n }\n return;\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return props.length > 0 ? props : null;\n}\n\n// =============================================================================\n// Contract Validation\n// =============================================================================\n\n/**\n * Compare extracted Props interface against a PropsSpec contract.\n * Returns issues: errors for missing required fields, warnings for type mismatches.\n */\nexport function validatePropsAgainstSchema(\n code: string,\n spec: PropsSpec,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n const extracted = extractPropsInterface(code);\n\n if (!extracted) {\n // Can't extract — not necessarily an error (might use inline types)\n return [];\n }\n\n const extractedMap = new Map(extracted.map((p) => [p.name, p]));\n\n for (const [propName, entry] of Object.entries(spec.properties)) {\n const extractedProp = extractedMap.get(propName);\n\n if (!extractedProp) {\n if (entry.required) {\n issues.push({\n severity: \"error\",\n field: propName,\n message: `Props interface is missing required field '${propName}' from the data contract`,\n fix: `Add \\`${propName}${entry.required ? \"\" : \"?\"}: ${jsonSchemaTypeToTs(entry.schema)}\\` to your Props interface`,\n });\n } else {\n issues.push({\n severity: \"warning\",\n field: propName,\n message: `Props interface is missing optional field '${propName}' from the data contract`,\n fix: `Consider adding \\`${propName}?: ${jsonSchemaTypeToTs(entry.schema)}\\` to your Props interface`,\n });\n }\n continue;\n }\n\n // Basic type compatibility check (only if we have type info)\n if (extractedProp.type !== \"unknown\") {\n const expectedTsType = jsonSchemaTypeToTs(entry.schema);\n if (!isTypeCompatible(extractedProp.type, expectedTsType, entry.schema)) {\n issues.push({\n severity: \"warning\",\n field: propName,\n message: `Field '${propName}' has type '${extractedProp.type}' but contract expects '${expectedTsType}'`,\n fix: `Change \\`${propName}\\` type to \\`${expectedTsType}\\``,\n });\n }\n }\n }\n\n return issues;\n}\n\n/**\n * Check if a TypeScript type string is compatible with a JSON Schema type.\n * Loose comparison — we only check the base type, not full structural equality.\n */\nfunction isTypeCompatible(tsType: string, expectedTsType: string, schema: JsonSchema): boolean {\n const normalized = tsType.replace(/\\s/g, \"\").toLowerCase();\n\n switch (schema.type) {\n case \"string\":\n return normalized.includes(\"string\");\n case \"number\":\n case \"integer\":\n return normalized.includes(\"number\");\n case \"boolean\":\n return normalized.includes(\"boolean\");\n case \"array\":\n return normalized.includes(\"[]\") || normalized.includes(\"array\");\n case \"object\":\n return ![\"string\", \"number\", \"boolean\"].some((t) => normalized === t);\n default:\n return true;\n }\n}\n\n// =============================================================================\n// JSON Schema → TypeScript Conversion (for LLM prompts)\n// =============================================================================\n\n// `jsonSchemaTypeToTs` lives in `@ggui-ai/ui-gen/boilerplate` and is\n// re-exported at the top of this file.\n\n/**\n * Convert a full PropsSpec to a TypeScript interface string for LLM prompt injection.\n * Includes required/optional markers and descriptions as comments.\n */\nexport function propsSpecToTypeScript(spec: PropsSpec, indent = 2): string {\n const pad = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const [propName, entry] of Object.entries(spec.properties)) {\n if (entry.description) {\n lines.push(`${pad}/** ${entry.description} */`);\n }\n const optional = !entry.required;\n const tsType = jsonSchemaTypeToTs(entry.schema);\n const defaultStr = entry.default !== undefined ? ` // default: ${JSON.stringify(entry.default)}` : \"\";\n lines.push(`${pad}${propName}${optional ? \"?\" : \"\"}: ${tsType};${defaultStr}`);\n // Include example as a comment so the LLM sees the exact data shape\n if (entry.example !== undefined) {\n const exampleStr = JSON.stringify(entry.example, null, 2)\n .split(\"\\n\")\n .map((l, i) => (i === 0 ? `${pad}// Example: ${l}` : `${pad}// ${l}`))\n .join(\"\\n\");\n lines.push(exampleStr);\n }\n }\n\n return `{\\n${lines.join(\"\\n\")}\\n}`;\n}\n\n// =============================================================================\n// StreamSpec Validation\n// =============================================================================\n\n/**\n * Validate that the generated source code properly handles stream events.\n * Requires useStream() wire hooks — legacy DOM event patterns are no longer accepted.\n */\nexport function validateStreamSpecConformance(\n code: string,\n spec: StreamSpec,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n\n const usesWireStream = code.includes(\"useStream\");\n\n if (!usesWireStream) {\n issues.push({\n severity: \"error\",\n field: \"__streamSpec__\",\n message: \"Component does not handle stream events — use useStream() from the boilerplate wire hooks\",\n fix: \"Use the useStream('eventName') hook from the boilerplate to receive real-time data from the agent\",\n });\n return issues;\n }\n\n // Check each declared channel is referenced in the code. `spec` is a\n // flat `Record<channelName, StreamChannelEntry>` — iterate directly.\n for (const [channelName, entry] of Object.entries(spec)) {\n if (!code.includes(`'${channelName}'`) && !code.includes(`\"${channelName}\"`)) {\n issues.push({\n severity: \"warning\",\n field: channelName,\n message: `StreamSpec declares channel '${channelName}' but component doesn't reference it`,\n fix: `Add useStream('${channelName}') to receive ${entry.description || channelName} events`,\n });\n }\n }\n\n return issues;\n}\n\n// =============================================================================\n// ActionSpec Validation\n// =============================================================================\n\n/**\n * Validate that the generated source code wires the declared actions.\n * Checks that action IDs are referenced via useAction() wire hooks, string literals, or prop callbacks.\n */\nexport function validateActionSpecConformance(\n code: string,\n spec: ActionSpec,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n\n // `spec` is a flat `Record<actionId, ActionEntry>` — iterate directly.\n for (const [actionId, entry] of Object.entries(spec)) {\n // Check the action ID or its label is referenced in the code\n const idReferenced = code.includes(`'${actionId}'`) || code.includes(`\"${actionId}\"`);\n const labelReferenced = code.includes(entry.label);\n const callbackName = `on${actionId.charAt(0).toUpperCase()}${actionId.slice(1)}`;\n const callbackReferenced = code.includes(callbackName);\n\n if (!idReferenced && !labelReferenced && !callbackReferenced) {\n issues.push({\n severity: \"error\",\n field: actionId,\n message: `ActionSpec declares action '${actionId}' (\"${entry.label}\") but component doesn't wire it`,\n fix: `Use the useAction('${actionId}') hook from the boilerplate and wire it to a button or form submit`,\n });\n }\n }\n\n return issues;\n}\n\n// =============================================================================\n// Unified Contract Validation\n// =============================================================================\n\n/**\n * Validate all contract (props, stream, actions) against the source code.\n * Returns combined issues from all three validations.\n */\nexport function validateAllContracts(\n code: string,\n contract: DataContract,\n): ContractIssue[] {\n const issues: ContractIssue[] = [];\n\n if (contract.propsSpec) {\n issues.push(...validatePropsAgainstSchema(code, contract.propsSpec));\n }\n\n if (contract.streamSpec) {\n issues.push(...validateStreamSpecConformance(code, contract.streamSpec));\n }\n\n if (contract.actionSpec) {\n issues.push(...validateActionSpecConformance(code, contract.actionSpec));\n }\n\n return issues;\n}\n\n// =============================================================================\n// Sample Data → PropsSpec Inference (backward compat)\n// =============================================================================\n\n/**\n * Infer a PropsSpec from sample data.\n * Convenience utility for migration and for agents that pass sample data instead of schemas.\n * All fields are marked as required (can't distinguish required/optional from data alone).\n */\nexport function inferPropsSpecFromSampleData(data: JsonObject): PropsSpec {\n const properties: Record<string, PropEntry> = {};\n\n for (const [key, value] of Object.entries(data)) {\n properties[key] = {\n schema: inferJsonSchema(value),\n required: true,\n example: value as JsonValue,\n };\n }\n\n return { properties };\n}\n\nfunction inferJsonSchema(value: unknown): JsonSchema {\n if (value === null || value === undefined) return { type: \"null\" };\n if (typeof value === \"string\") return { type: \"string\" };\n if (typeof value === \"number\") return { type: \"number\" };\n if (typeof value === \"boolean\") return { type: \"boolean\" };\n\n if (Array.isArray(value)) {\n if (value.length === 0) return { type: \"array\" };\n return {\n type: \"array\",\n items: inferJsonSchema(value[0]),\n };\n }\n\n if (typeof value === \"object\") {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n for (const [k, v] of Object.entries(value as JsonObject)) {\n properties[k] = inferJsonSchema(v);\n required.push(k);\n }\n return { type: \"object\", properties, required };\n }\n\n return { type: \"string\" };\n}\n","/**\n * The single source of truth for which packages LLM-generated\n * component code may import.\n *\n * Before this module the allowlist was duplicated — as `startsWith`\n * chains, as literal arrays, as hand-written error strings — across\n * `adapters/tools.ts`, `check/run-tier0.ts`, `check/type-checker.ts`\n * and `validation/component-detailed.ts`. The copies had already\n * drifted (one rejected `react-dom`, others allowed it). Every\n * import-validation site now derives from {@link isAllowedImport}.\n *\n * The design system is imported through ONE specifier — `@ggui-ai/design`\n * — never the `/primitives`, `/components`, `/compositions`, `/interact`\n * subpaths. The barrel re-exports every layer, so the generation LLM\n * never has to predict which subpath a component lives in. Subpaths\n * still resolve (the predicate allows any `@ggui-ai/design/...`), but\n * the prompt and catalog teach the barrel exclusively.\n */\n\n/**\n * Static package specifiers generated code may import. A subpath of\n * any base (`<base>/...`) is allowed too. Per-contract gadget packages\n * are dynamic — pass them to {@link isAllowedImport}.\n */\nimport { FORBIDDEN_IMPORT_SPECIFIERS } from '@ggui-ai/design/rendering';\n\nexport const ALLOWED_IMPORT_BASES = [\n 'react',\n 'react-dom',\n '@ggui-ai/design',\n '@ggui-ai/wire',\n '@ggui-ai/gadgets',\n] as const;\n\n/**\n * True if `specifier` is a package generated component code may import:\n * one of {@link ALLOWED_IMPORT_BASES} (or a subpath of one), or a\n * contract-declared gadget package — and never one of the design package's\n * `FORBIDDEN_IMPORT_SPECIFIERS` (ggui#843: `@ggui-ai/wire/internal` is the\n * writer side of the wire; the load-time rewriter refuses it from the same\n * list, so the two gates cannot drift apart).\n */\nexport function isAllowedImport(\n specifier: string,\n gadgetPackages?: ReadonlySet<string>,\n): boolean {\n if (FORBIDDEN_IMPORT_SPECIFIERS.includes(specifier)) return false;\n for (const base of ALLOWED_IMPORT_BASES) {\n if (specifier === base || specifier.startsWith(`${base}/`)) return true;\n }\n return gadgetPackages?.has(specifier) ?? false;\n}\n\n/**\n * Human-readable allowed-import list for error messages shown to the\n * generation LLM.\n */\nexport function describeAllowedImports(): string {\n return 'react, @ggui-ai/design, @ggui-ai/wire, @ggui-ai/gadgets, or a gadget package declared on the contract — never @ggui-ai/wire/internal (the writer side of the wire; components read useRender().isConnected)';\n}\n","// packages/ui-gen/src/check/type-checker.ts\n//\n// TypeScript type-checker for LLM-generated UI components. Uses the\n// TypeScript compiler API with a virtual filesystem to type-check TSX\n// code against React types and `@ggui-ai/design` primitives, giving\n// the LLM familiar TS error feedback without writing anything to disk.\n//\n// The checker builds a virtual filesystem seeded with `typescript/lib`,\n// `@types/react`, `@ggui-ai/design/dist`, and `@ggui-ai/wire/dist`\n// `.d.ts` content, then drives `ts.createProgram` against a synthetic\n// `Component.tsx`. Exposed on `@ggui-ai/ui-gen/check` so\n// `createUiGenerator` runs the same tier-0 gate as the hosted\n// generation path.\n//\n// Path-resolution note: the three workspace-rooted lookups —\n// `.pnpm/@types+react@*`, `packages/design/dist`, and\n// `packages/wire/dist` — are anchored relative to this file. tsup\n// bundles `src/check/index.ts` (splitting: false) into a flat\n// `dist/check/index.js`, so the src and dist locations sit at the same\n// depth and both resolve correctly. `typescript/lib/typescript.js`\n// keeps using `createRequire(import.meta.url).resolve` —\n// position-independent, so no change.\n//\n// Used by:\n// (1) Tier-0 `type_check` — blocking errors (see BLOCKING_CODES)\n// map to PRODUCTION_FAILED; non-blocking TS diagnostics surface\n// as warnings so the LLM can iterate on non-crash-risk findings\n// without stalling the harness.\n// (2) The `self_check` tool — called from generator SDKs (Anthropic /\n// OpenAI / Google) to give the LLM TS feedback mid-generation.\n// (3) The tier-0 orchestrator `runTier0Checks` — runs in parallel\n// with the wire-preservation + lint checks under the same tier\n// budget.\n//\n// Design notes that motivate non-obvious choices:\n// - Classic React JSX mode (`ts.JsxEmit.React`). The synthetic\n// prefix (see SYNTHETIC_PREFIX) supplies `import React from\n// 'react'` for the classic JSX factory PLUS a self-contained\n// global `JSX` namespace. `@types/react` v19 removed the global\n// `JSX` namespace that classic mode resolves intrinsic elements +\n// the `key`/`ref` carve-out through; without the shim, `<div>`\n// degrades to `any` and every typed component falsely rejects the\n// intrinsic `key` prop. Automatic mode was tried but its\n// `react/jsx-runtime` resolution does not survive the VFS.\n// - `strict: false` + `strictNullChecks: true`: we want the runtime\n// crash classes (`undefined.foo()`, `null.bar`) to surface as\n// blocking, but not the optional-chaining / exhaustive-check\n// noise that full `strict` would emit on LLM code.\n// - `types: []`: prevents the VFS from auto-pulling every\n// `@types/*` package that happens to be hoisted — only react and\n// the design/wire dist types should be reachable, matching the\n// forbidden-import policy enforced by `react-linter` elsewhere.\n// - TS2307 (\"Cannot find module\") is deliberately NOT blocking —\n// Lambda bundles code without type declarations, so the VFS can't\n// see every package that may exist at runtime. Forbidden imports\n// are caught by `runSelfChecks` regex instead.\n\nimport ts from 'typescript';\nimport fs from 'fs';\nimport path from 'path';\nimport { createRequire } from 'module';\nimport { describeAllowedImports } from '../validation/allowed-imports.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TypeCheckDiagnostic {\n code: number;\n line: number;\n message: string;\n fix: string;\n}\n\nexport interface TypeCheckResult {\n errors: TypeCheckDiagnostic[]; // Blocking\n warnings: TypeCheckDiagnostic[]; // Non-blocking\n}\n\n// ---------------------------------------------------------------------------\n// Blocking error codes — these would break at runtime\n// ---------------------------------------------------------------------------\n\nconst BLOCKING_CODES = new Set([\n 2304, // Cannot find name\n // 2307 (Cannot find module) is NOT blocking — Lambda bundles code without\n // type declarations, so the VFS can't resolve react/@ggui-ai/design.\n // Forbidden imports are caught by runSelfChecks regex instead.\n 2305, // Module has no exported member\n 2322, // Type not assignable\n 2339, // Property does not exist on type\n 2741, // Missing required property\n 2769, // No overload matches this call\n 17004, // Cannot use JSX unless '--jsx' flag\n 18047, // 'X' is possibly 'null' — causes runtime crash\n 18048, // 'X' is possibly 'undefined' — causes runtime crash\n]);\n\n// ---------------------------------------------------------------------------\n// Fix suggestions per error code\n// ---------------------------------------------------------------------------\n\nfunction generateFix(code: number, message?: string, sourceLine?: string): string {\n // Source-line hint: when the failing line is short and self-contained,\n // appending it gives the LLM a precise target. Skip for very long lines\n // (>140 chars — usually multi-prop JSX where the line itself is the\n // diagnostic) since they bloat the violation envelope without helping.\n const sourceHint =\n sourceLine && sourceLine.length > 0 && sourceLine.length <= 140\n ? ` Offending line: \\`${sourceLine}\\``\n : '';\n\n // Detect event handler on non-interactive primitive\n if ((code === 2322 || code === 2339) && message && /onClick|onDoubleClick|onMouseEnter|onMouseLeave|onPress/.test(message)) {\n return `This structural primitive has no event handlers of its own — add the trait as a PROP: as={Clickable} (then onClick works), imported from @ggui-ai/design. Do NOT wrap it in <Clickable>…</Clickable>; as is a prop, not a wrapper element.${sourceHint}`;\n }\n\n // Detect underscore-prefix-on-prop trap: `Property '_X' does not exist`.\n // LLM saw an unused-var warning on `X` and tried to silence it by renaming\n // the destructure to `_X`, breaking prop access. Steer back.\n if (code === 2339 && message && /Property '_[a-zA-Z]/.test(message)) {\n return `You renamed a prop with a leading underscore to silence \\`no-unused-vars\\`, but the prop on \\`Props\\` doesn't have that prefix. Restore the original name; better, don't destructure props you won't render — access them via \\`props.fieldName\\` only when needed.${sourceHint}`;\n }\n\n // Detect \"Cannot find name\" for destructured props\n if (code === 2304 && message && !message.includes('module') && !message.includes('import')) {\n return `This name is not defined in scope. Either you destructured props (use \\`props.fieldName\\` directly instead) OR you removed a helper declaration in this patch but kept a JSX/expression reference to it. Read your full patch and either restore the declaration or remove the reference.${sourceHint}`;\n }\n\n // Detect \"unknown is not assignable to ReactNode\"\n if ((code === 2322 || code === 2769) && message && /unknown.*ReactNode|ReactNode.*unknown/.test(message)) {\n return `This value has type 'unknown' and cannot be rendered in JSX. Cast it: String(value) or add a type annotation.${sourceHint}`;\n }\n\n switch (code) {\n case 2307:\n return `Only these imports are allowed: ${describeAllowedImports()}${sourceHint}`;\n case 2322:\n case 2769:\n return `Type mismatch on this expression. Check the offending line below — the prop name in JSX is what TypeScript is rejecting; the message tells you the expected type.${sourceHint}`;\n case 2339:\n return `This prop doesn't exist on this component — check the available props on the component's interface (visible at the top of the file, or in the design-system reference).${sourceHint}`;\n case 2305:\n return `This name is not defined. Check your imports and variable declarations.${sourceHint}`;\n case 2741:\n return `A required prop is missing. Check the component's Props interface.${sourceHint}`;\n case 18047:\n case 18048:\n return `This value might be null/undefined. Every dereference on the same nullable still needs \\`?.\\` — \\`x?.foo && x?.bar\\`, NOT \\`x?.foo && x.bar\\`. Or hoist: \\`const v = x; if (!v) return null;\\` then access \\`v.foo\\`/\\`v.bar\\` unguarded.${sourceHint}`;\n default:\n return `Review the TypeScript error and fix the type issue.${sourceHint}`;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Virtual Filesystem — lazy singleton\n// ---------------------------------------------------------------------------\n\ninterface VfsEntry {\n content: string;\n sourceFile: ts.SourceFile;\n}\n\nlet vfsCache: Map<string, VfsEntry> | null = null;\n\nfunction parseAndStore(\n vfs: Map<string, VfsEntry>,\n virtualPath: string,\n content: string,\n): void {\n const sourceFile = ts.createSourceFile(\n virtualPath,\n content,\n ts.ScriptTarget.ES2020,\n true,\n virtualPath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,\n );\n vfs.set(virtualPath, { content, sourceFile });\n}\n\n/**\n * Recursively walk a directory and return all file paths matching a filter.\n */\nfunction walkDir(dir: string, filter: (f: string) => boolean): string[] {\n const results: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n results.push(...walkDir(full, filter));\n } else if (filter(full)) {\n results.push(full);\n }\n }\n return results;\n}\n\n/**\n * Resolve `@types/react`'s root directory through Node's module\n * resolution. Position-independent — walks the consumer's node_modules\n * chain. Works in monorepo (where the type package is hoisted under\n * `<root>/node_modules/.pnpm/@types+react@*`) and in standalone\n * `packages/`-only installs (e.g. the projected public OSS repo where\n * the `packages/` prefix is stripped, so a hardcoded `../../../..`\n * walk lands in the wrong place).\n */\nfunction findReactTypesDir(): string | null {\n try {\n // `@types/react` doesn't expose `package.json` as a public subpath,\n // so resolve via the always-present `index.d.ts`.\n const indexDts = createRequire(import.meta.url).resolve('@types/react/index.d.ts');\n return path.dirname(indexDts);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a workspace package's `dist/` directory through Node's\n * module resolution. Like `findReactTypesDir`, this works in both\n * monorepo (where the package is hoisted/symlinked) and standalone\n * installs — no relative-path math required.\n */\nfunction findPackageDistDir(pkg: string): string | null {\n try {\n const pkgJson = createRequire(import.meta.url).resolve(`${pkg}/package.json`);\n const dist = path.join(path.dirname(pkgJson), 'dist');\n return fs.existsSync(dist) ? dist : null;\n } catch {\n return null;\n }\n}\n\nasync function loadVfs(): Promise<Map<string, VfsEntry>> {\n if (vfsCache) return vfsCache;\n\n const vfs = new Map<string, VfsEntry>();\n\n // ---- 1. TypeScript lib files ----\n // `createRequire(import.meta.url).resolve('typescript/lib/typescript.js')`\n // is position-independent — it walks the consumer's node_modules chain,\n // so this lookup works identically from core/, packages/ui-gen/, and any\n // future host package.\n const require_ = createRequire(import.meta.url);\n const tsDir = path.dirname(require_.resolve('typescript/lib/typescript.js'));\n const libFiles = fs.readdirSync(tsDir).filter((f) => /^lib\\..*\\.d\\.ts$/.test(f));\n for (const file of libFiles) {\n const content = fs.readFileSync(path.join(tsDir, file), 'utf-8');\n parseAndStore(vfs, file, content);\n }\n\n // ---- 2. React types ----\n // Resolved through `createRequire(import.meta.url).resolve('@types/\n // react/index.d.ts')` — position-independent. Works the same in\n // monorepo (hoisted to root) and in standalone `packages/`-only\n // installs (the projected public OSS repo strips the `packages/`\n // prefix, so a hardcoded `../../../..` walk would miss).\n const reactDir = findReactTypesDir();\n if (reactDir) {\n const reactDts = fs.readdirSync(reactDir).filter((f) => f.endsWith('.d.ts'));\n for (const file of reactDts) {\n const content = fs.readFileSync(path.join(reactDir, file), 'utf-8');\n parseAndStore(vfs, `node_modules/@types/react/${file}`, content);\n }\n }\n\n // ---- 3. Design system types ----\n const designDist = findPackageDistDir('@ggui-ai/design');\n if (designDist) {\n const dtsFiles = walkDir(designDist, (f) => f.endsWith('.d.ts') && !f.endsWith('.d.ts.map'));\n for (const file of dtsFiles) {\n const rel = path.relative(designDist, file);\n const content = fs.readFileSync(file, 'utf-8');\n parseAndStore(vfs, `node_modules/@ggui-ai/design/${rel}`, content);\n }\n }\n\n // ---- 4. Wire module types ----\n const wireDist = findPackageDistDir('@ggui-ai/wire');\n if (wireDist) {\n const dtsFiles = walkDir(wireDist, (f) => f.endsWith('.d.ts') && !f.endsWith('.d.ts.map'));\n for (const file of dtsFiles) {\n const rel = path.relative(wireDist, file);\n const content = fs.readFileSync(file, 'utf-8');\n parseAndStore(vfs, `node_modules/@ggui-ai/wire/${rel}`, content);\n }\n }\n\n // ---- 5. Gadgets types ----\n // Generated component code direct-imports standard-library gadget\n // hooks — `import { useGeolocation } from '@ggui-ai/gadgets'`.\n // Loading the `@ggui-ai/gadgets` package's shipped `.d.ts` into the\n // VFS makes those bare-named imports resolve against the real hook\n // declarations (named option/return types preserved). The standard\n // gadget hooks are plain named exports the resolver finds directly.\n const clientLibsDist = findPackageDistDir('@ggui-ai/gadgets');\n if (clientLibsDist) {\n const dtsFiles = walkDir(\n clientLibsDist,\n (f) => f.endsWith('.d.ts') && !f.endsWith('.d.ts.map'),\n );\n for (const file of dtsFiles) {\n const rel = path.relative(clientLibsDist, file);\n const content = fs.readFileSync(file, 'utf-8');\n parseAndStore(vfs, `node_modules/@ggui-ai/gadgets/${rel}`, content);\n }\n }\n\n vfsCache = vfs;\n return vfs;\n}\n\n// ---------------------------------------------------------------------------\n// Module resolution helper\n// ---------------------------------------------------------------------------\n\n/**\n * Try to resolve a relative import within the VFS.\n * Given `containingFile` (e.g. `node_modules/@ggui-ai/design/primitives/index.d.ts`)\n * and `importPath` (e.g. `./Card` or, as every published declaration says\n * since 0.15.0, `./Card.js`), try:\n * - <resolved>.d.ts\n * - <resolved>/index.d.ts\n * - <resolved>.ts\n * A `.js` / `.mjs` / `.cjs` extension on the specifier is the ESM\n * convention for \"the module that compiles to this file\" — TypeScript's\n * NodeNext maps `./Card.js` to `./Card.d.ts`, and so does this: the\n * extension is stripped before the candidates are tried. Without that, a\n * `.js`-suffixed re-export resolved to nothing, the imported names typed\n * as `any`, and the checker reported zero errors on code it must reject\n * (ggui 0.15.0 publish-gate, type-checker.test.ts).\n */\nfunction resolveRelativeInVfs(\n vfs: Map<string, VfsEntry>,\n containingFile: string,\n importPath: string,\n): string | undefined {\n // Strip leading '/' from containingFile — TS may prepend getCurrentDirectory()\n const normalized = containingFile.startsWith('/') ? containingFile.slice(1) : containingFile;\n const dir = path.posix.dirname(normalized);\n // `./x.js` (`.mjs`, `.cjs`) names the declaration `./x.d.ts` — strip it.\n const specifier = importPath.replace(/\\.(?:m|c)?js$/, '');\n const resolved = path.posix.normalize(`${dir}/${specifier}`);\n\n // Try .d.ts extension\n const withDts = `${resolved}.d.ts`;\n if (vfs.has(withDts)) return withDts;\n\n // Try /index.d.ts\n const withIndexDts = `${resolved}/index.d.ts`;\n if (vfs.has(withIndexDts)) return withIndexDts;\n\n // Try .ts extension\n const withTs = `${resolved}.ts`;\n if (vfs.has(withTs)) return withTs;\n\n // Might already be the exact path\n if (vfs.has(resolved)) return resolved;\n\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// CompilerHost factory\n// ---------------------------------------------------------------------------\n\nconst COMPILER_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ES2020,\n module: ts.ModuleKind.ESNext,\n // Classic React JSX mode. The synthetic prefix (SYNTHETIC_PREFIX)\n // supplies `import React from 'react'` plus a `declare global` JSX\n // namespace shim: `@types/react` v19 removed the *global* `JSX`\n // namespace (it lives at `React.JSX` now), which classic mode needs\n // for `JSX.IntrinsicElements` and the `key`/`ref` carve-out. Without\n // the shim, `<div>` degrades to `any` and every typed component\n // falsely rejects the intrinsic `key` prop.\n jsx: ts.JsxEmit.React,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n strict: false,\n strictNullChecks: true, // Catch undefined.foo() errors that cause runtime crashes\n noEmit: true,\n skipLibCheck: true,\n noImplicitAny: true,\n types: [],\n esModuleInterop: true,\n};\n\n/**\n * Normalize a path that TS's internal module resolution might generate.\n * Since getCurrentDirectory() returns '/', TS will probe paths like\n * '/node_modules/@types/react/jsx-runtime.d.ts'. We strip the leading\n * '/' to match our VFS keys.\n */\nfunction normalizeVfsPath(f: string): string | null {\n if (f.startsWith('/')) {\n return f.slice(1);\n }\n return null;\n}\n\n/**\n * Core module resolution logic shared between resolveModuleNameLiterals\n * (for user imports) and resolveModuleNames (for TS-internal imports\n * like jsxImportSource).\n */\nfunction resolveModuleName(\n vfs: Map<string, VfsEntry>,\n name: string,\n containingFile: string,\n): ts.ResolvedModuleWithFailedLookupLocations {\n // React core\n if (name === 'react') {\n return resolved('node_modules/@types/react/index.d.ts');\n }\n if (name === 'react/jsx-runtime') {\n return resolved('node_modules/@types/react/jsx-runtime.d.ts');\n }\n if (name === 'react/jsx-dev-runtime') {\n const p = 'node_modules/@types/react/jsx-dev-runtime.d.ts';\n if (vfs.has(p)) return resolved(p);\n return resolved('node_modules/@types/react/jsx-runtime.d.ts');\n }\n\n // @ggui-ai/design sub-paths\n const designPrefix = '@ggui-ai/design/';\n if (name.startsWith(designPrefix)) {\n const subpath = name.slice(designPrefix.length);\n const indexPath = `node_modules/@ggui-ai/design/${subpath}/index.d.ts`;\n if (vfs.has(indexPath)) return resolved(indexPath);\n const directPath = `node_modules/@ggui-ai/design/${subpath}.d.ts`;\n if (vfs.has(directPath)) return resolved(directPath);\n }\n\n // @ggui-ai/design root\n if (name === '@ggui-ai/design') {\n return resolved('node_modules/@ggui-ai/design/index.d.ts');\n }\n\n // @ggui-ai/wire\n if (name === '@ggui-ai/wire') {\n return resolved('node_modules/@ggui-ai/wire/index.d.ts');\n }\n\n // @ggui-ai/gadgets — the STDLIB gadget package. Generated\n // code direct-imports the seven STDLIB hooks (`useGeolocation`, …)\n // as plain named exports from this specifier. The shipped `.d.ts`\n // (loaded into the VFS above) carries their real declarations.\n if (name === '@ggui-ai/gadgets') {\n return resolved('node_modules/@ggui-ai/gadgets/index.d.ts');\n }\n\n // Relative imports — resolve within VFS\n if (name.startsWith('./') || name.startsWith('../')) {\n const resolvedPath = resolveRelativeInVfs(vfs, containingFile, name);\n if (resolvedPath) return resolved(resolvedPath);\n }\n\n // Third-party gadget wrapper packages. The render handler fetches each\n // non-stdlib gadget's `.d.ts` and `typecheck` overlays it at\n // `node_modules/<package>/index.d.ts`. A generated direct import\n // `import { useX } from '<package>'` resolves through this\n // bare-specifier branch against the overlaid `.d.ts` — named\n // option/return types preserved instead of collapsing to `any`.\n // Generic VFS lookup — no per-package allow-list.\n const bareIndex = `node_modules/${name}/index.d.ts`;\n if (vfs.has(bareIndex)) return resolved(bareIndex);\n\n // Unknown module\n return { resolvedModule: undefined };\n}\n\nfunction createVfsHost(\n vfs: Map<string, VfsEntry>,\n componentCode: string,\n): ts.CompilerHost {\n // Create fresh source file for the user component\n const componentFile = ts.createSourceFile(\n 'Component.tsx',\n componentCode,\n ts.ScriptTarget.ES2020,\n true,\n ts.ScriptKind.TSX,\n );\n\n const host: ts.CompilerHost = {\n getSourceFile(fileName: string) {\n if (fileName === 'Component.tsx') return componentFile;\n const entry = vfs.get(fileName);\n if (entry) return entry.sourceFile;\n // Try normalized path (strip leading '/')\n const normalized = normalizeVfsPath(fileName);\n if (normalized) return vfs.get(normalized)?.sourceFile;\n return undefined;\n },\n getDefaultLibFileName() {\n return 'lib.es2020.full.d.ts';\n },\n writeFile() {\n // no-op\n },\n getCurrentDirectory() {\n return '/';\n },\n getCanonicalFileName(f: string) {\n return f;\n },\n useCaseSensitiveFileNames() {\n return true;\n },\n getNewLine() {\n return '\\n';\n },\n fileExists(f: string) {\n if (f === 'Component.tsx' || vfs.has(f)) return true;\n // Normalize bare-specifier lookups that TS's internal resolver\n // turns into relative-looking paths from getCurrentDirectory '/'.\n const normalized = normalizeVfsPath(f);\n if (normalized && vfs.has(normalized)) return true;\n return false;\n },\n readFile(f: string) {\n if (f === 'Component.tsx') return componentCode;\n const direct = vfs.get(f);\n if (direct) return direct.content;\n const normalized = normalizeVfsPath(f);\n if (normalized) return vfs.get(normalized)?.content;\n return undefined;\n },\n resolveModuleNameLiterals(\n moduleLiterals: readonly ts.StringLiteralLike[],\n containingFile: string,\n ): readonly ts.ResolvedModuleWithFailedLookupLocations[] {\n return moduleLiterals.map((literal) =>\n resolveModuleName(vfs, literal.text, containingFile),\n );\n },\n };\n\n return host;\n}\n\nfunction resolved(resolvedFileName: string): ts.ResolvedModuleWithFailedLookupLocations {\n return {\n resolvedModule: {\n resolvedFileName,\n isExternalLibraryImport: true,\n extension: ts.Extension.Dts,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport async function typecheck(\n code: string,\n /**\n * A `package -> .d.ts content` map for third-party gadget wrappers.\n * The render handler parallel-fetches each non-stdlib gadget's `.d.ts`\n * (via `GadgetDescriptor.typesUrl` + SRI) and threads the result\n * here. Each entry is overlaid into the per-call VFS at\n * `node_modules/<package>/index.d.ts`. A generated direct import\n * `import { useX } from '<package>'` resolves through the\n * bare-specifier branch in `resolveModuleName` directly against this\n * overlaid entry — named option/return types preserved, so a\n * wrong-typed hook call surfaces a blocking TS error instead of\n * collapsing to `any`.\n *\n * Stdlib gadgets (`package: '@ggui-ai/gadgets'`) need no entry —\n * `@ggui-ai/gadgets` ships its `.d.ts` into the VFS unconditionally.\n * Omit for standard-library-only callers.\n */\n dtsMap?: Readonly<Record<string, string>>,\n): Promise<TypeCheckResult> {\n const vfs = await loadVfs();\n\n // Overlay each third-party gadget wrapper's `.d.ts` per-call without\n // mutating the cached VFS. The bare-specifier branch in\n // `resolveModuleName` resolves a generated `import { useX } from\n // '<package>'` against the overlaid entry, so the LLM sandbox sees\n // the wrapper's strict hook/component types (named option/return\n // shapes) rather than `any`. A third-party wrapper with no `dtsMap`\n // entry collapses to `any` (TS2307 is non-blocking) — degraded UX,\n // not a generation blocker; the fix is to thread `gadgetTypes`.\n // Stdlib (`@ggui-ai/gadgets`) ships its `.d.ts` unconditionally.\n const effectiveVfs = (() => {\n const dtsEntries = dtsMap !== undefined ? Object.entries(dtsMap) : [];\n if (dtsEntries.length === 0) {\n return vfs;\n }\n const overlay = new Map(vfs);\n for (const [pkg, content] of dtsEntries) {\n parseAndStore(overlay, `node_modules/${pkg}/index.d.ts`, content);\n }\n return overlay;\n })();\n\n // Prepend a synthetic prefix for classic JSX mode:\n // - `import React from 'react'` — the classic-mode JSX factory\n // (`React.createElement`) needs the React namespace in scope.\n // - a `declare global` JSX shim — `@types/react` v19 dropped the\n // GLOBAL `JSX` namespace (it is `React.JSX` now); classic mode\n // resolves intrinsic elements + the `key`/`ref` carve-out through\n // the global `JSX`, so without this `<div>` degrades to `any` and\n // every typed component falsely rejects the intrinsic `key` prop.\n // Mirrors `react/jsx-runtime`'s own JSX namespace, hoisted global.\n // All prefix lines are skipped from diagnostics via `lineOffset`.\n // `@types/react` v19 removed the GLOBAL `JSX` namespace (it lives at\n // `React.JSX` now — un-exported, not reliably reachable through the\n // VFS). Classic JSX mode resolves intrinsic elements + the `key`\n // carve-out through the global `JSX`, so declare a self-contained\n // one. Intrinsic elements are permissive (`[elem]: any`): the\n // type-checker's value is on the design components — which keep\n // their real prop types regardless of this namespace — and on\n // runtime-crash detection, not on deep typing of raw HTML (which the\n // generation prompt discourages anyway).\n const globalJsxShim =\n 'declare global { namespace JSX {' +\n ' type ElementType = string | ((props: any) => any) | (new (props: any) => any);' +\n ' interface Element { type: any; props: any; key: string | number | null; }' +\n ' interface ElementClass { render(): any; }' +\n ' interface ElementAttributesProperty { props: object; }' +\n ' interface ElementChildrenAttribute { children: object; }' +\n ' interface IntrinsicAttributes { key?: string | number | bigint | null; }' +\n ' interface IntrinsicClassAttributes<T> { ref?: any; }' +\n ' interface IntrinsicElements { [elem: string]: any; }' +\n ' } }\\n';\n const SYNTHETIC_PREFIX = \"import React from 'react';\\n\" + globalJsxShim;\n const prefixedCode = SYNTHETIC_PREFIX + code;\n const lineOffset = SYNTHETIC_PREFIX.split('\\n').length - 1;\n\n const host = createVfsHost(effectiveVfs, prefixedCode);\n\n const program = ts.createProgram(['Component.tsx'], COMPILER_OPTIONS, host);\n const diagnostics = ts.getPreEmitDiagnostics(program);\n\n const errors: TypeCheckDiagnostic[] = [];\n const warnings: TypeCheckDiagnostic[] = [];\n\n for (const diag of diagnostics) {\n // Only report diagnostics from the user's component file\n if (diag.file && diag.file.fileName !== 'Component.tsx') continue;\n // Global diagnostics (no file) — skip as they come from config\n if (!diag.file) continue;\n // Skip diagnostics on the synthetic import prefix line\n const diagLine = ts.getLineAndCharacterOfPosition(diag.file, diag.start ?? 0).line;\n if (diagLine < lineOffset) continue;\n\n const rawLine = diag.file\n ? ts.getLineAndCharacterOfPosition(diag.file, diag.start ?? 0).line + 1\n : 0;\n // Subtract the synthetic import line to get the user's original line number\n const line = Math.max(1, rawLine - lineOffset);\n const message = ts.flattenDiagnosticMessageText(diag.messageText, '\\n');\n const code_ = diag.code;\n\n // Extract the offending source line for the fix hint — without it\n // \"Type 'string' is not assignable to type 'number'\" is unactionable\n // because the LLM doesn't know which prop on which primitive. With\n // the line (\"<Icon size=\\\"md\\\" ...>\"), the LLM can target precisely.\n const sourceLines = diag.file.text.split('\\n');\n const sourceLine =\n rawLine >= 1 && rawLine <= sourceLines.length\n ? sourceLines[rawLine - 1]?.trim() ?? ''\n : '';\n\n const entry: TypeCheckDiagnostic = {\n code: code_,\n line,\n message,\n fix: generateFix(code_, message, sourceLine),\n };\n\n if (BLOCKING_CODES.has(code_)) {\n errors.push(entry);\n } else {\n warnings.push(entry);\n }\n }\n\n return { errors, warnings };\n}\n","// packages/ui-gen/src/check/react-linter.ts\n//\n// React linter — runs eslint-plugin-react-hooks via ESLint's Linter API.\n//\n// Exposed on `@ggui-ai/ui-gen/check` so `createUiGenerator` can invoke\n// the same lint gate as the hosted generation path.\n//\n// Dep surface: the linter imports the `Linter` / `Rule` types from\n// `eslint` at module load and lazily imports `@typescript-eslint/parser`,\n// `eslint-plugin-react-hooks`, and `eslint-plugin-react` inside\n// `getLinter()` — those four packages are runtime deps of this package.\n//\n// Catches Rules of Hooks violations that the TS type-checker misses:\n// - Hooks inside conditionals, loops, nested functions\n// - Hooks after early returns\n// - Missing/extra dependencies in useEffect/useMemo/useCallback\n//\n// Also carries the core ESLint `no-unused-vars` rule to\n// catch wire hooks the LLM declared but never consumed — an unused\n// `const submit = useAction('submit')` ships a subscription with no\n// render/callback wiring and will not actually drive the UI. Rule 14\n// (`wire_preservation`) in self-check.ts catches the DELETION case;\n// this lint pass catches the ABANDONMENT case. Together they seal\n// bidirectional contract completeness: contract -> code.\n//\n// Uses the lightweight Linter API (no file system, no config resolution).\n// Runs in parallel with the TS type-checker during self-check.\n\nimport { Linter, type Rule } from 'eslint';\n\nexport interface ReactLintDiagnostic {\n rule: string;\n line: number;\n message: string;\n fix: string;\n severity: 'error' | 'warning';\n}\n\n// Singleton Linter instance — reused across calls.\nlet linterInstance: Linter | null = null;\n\nasync function getLinter(): Promise<Linter> {\n if (!linterInstance) {\n linterInstance = new Linter();\n\n // Register @typescript-eslint/parser so ESLint can parse TS/TSX\n const tsParser = await import('@typescript-eslint/parser');\n linterInstance.defineParser('@typescript-eslint/parser', tsParser as Linter.Parser);\n\n // Register react-hooks plugin rules\n const reactHooksPlugin = await import('eslint-plugin-react-hooks');\n const hooksRules = reactHooksPlugin.default?.rules ?? reactHooksPlugin.rules;\n for (const [name, rule] of Object.entries(hooksRules)) {\n linterInstance.defineRule(`react-hooks/${name}`, rule as Rule.RuleModule);\n }\n\n // Register eslint-plugin-react rules\n const reactPlugin = await import('eslint-plugin-react');\n const reactRules = reactPlugin.default?.rules ?? reactPlugin.rules;\n for (const [name, rule] of Object.entries(reactRules)) {\n linterInstance.defineRule(`react/${name}`, rule as Rule.RuleModule);\n }\n }\n return linterInstance;\n}\n\n/**\n * Lint TSX code for React hooks violations.\n * Returns diagnostics with line numbers and fix suggestions.\n */\nexport async function lintReactHooks(code: string): Promise<ReactLintDiagnostic[]> {\n const linter = await getLinter();\n\n let messages: Linter.LintMessage[];\n try {\n const config: Linter.LegacyConfig = {\n parser: '@typescript-eslint/parser',\n parserOptions: {\n ecmaVersion: 2022,\n sourceType: 'module',\n ecmaFeatures: { jsx: true },\n },\n rules: {\n 'react-hooks/rules-of-hooks': 2,\n 'react-hooks/exhaustive-deps': 1,\n // React rules\n 'react/jsx-no-undef': 2, // undefined JSX components\n 'react/jsx-key': 1, // missing key in lists\n 'react/no-direct-mutation-state': 2, // direct state mutation\n // An unused `const submit = useAction('submit')` is a\n // dead contract wire. Narrow the rule to variable bindings we\n // care about: skip function args (LLMs legitimately omit unused\n // params), skip destructured `rest` collectors, respect a `_`-\n // prefix escape hatch for intentionally-ignored declarations,\n // and silence the caught-error slot (async error handling can\n // leave `catch (err)` unused at a boundary).\n 'no-unused-vars': [2, {\n vars: 'all',\n args: 'none',\n ignoreRestSiblings: true,\n varsIgnorePattern: '^_',\n caughtErrors: 'none',\n }],\n },\n settings: {\n react: { version: '19.0' },\n },\n };\n messages = linter.verify(code, config, { filename: 'component.tsx' });\n } catch {\n // Parser not available or code too malformed — skip\n return [];\n }\n\n const diagnostics: ReactLintDiagnostic[] = [];\n\n // Rules surfaced from the Linter run. `no-unused-vars` is the core\n // ESLint rule (no plugin prefix) — admitted alongside react-hooks/\n // and react/ rules so the no-unused-vars diagnostic reaches self_check.\n const ADMITTED_RULES = (id: string): boolean =>\n id.startsWith('react-hooks/') ||\n id.startsWith('react/') ||\n id === 'no-unused-vars';\n\n for (const msg of messages) {\n // Skip parser errors — caught by TS type-checker\n if (!msg.ruleId) continue;\n if (!ADMITTED_RULES(msg.ruleId)) continue;\n\n diagnostics.push({\n rule: msg.ruleId,\n line: msg.line,\n message: msg.message,\n fix: generateReactFix(msg.ruleId, msg.message),\n severity: resolveSeverity(msg, code),\n });\n }\n\n return diagnostics;\n}\n\n/**\n * Resolve the self-check severity of a lint diagnostic.\n *\n * Most rules map straight from ESLint severity (2 → error, 1 → warning).\n * `no-unused-vars` is special-cased: it stays a hard `error` ONLY when\n * the unused binding is a CONTRACT WIRE — `const x = useAction(...)` /\n * `useStream(...)` / `useGguiContext(...)` — because an abandoned wire\n * ships a dead subscription. For every other unused binding (a local\n * helper the LLM declared mid-generation, a `useMemo` result, a state-\n * read gadget binding) it is downgraded to `warning`.\n *\n * Rationale: a half-wired local helper is transient coding state, not a\n * defect — blocking tier-0 self-check on it forces a whole coding-turn\n * round-trip and is the single largest turn-thrash driver on the\n * benchmark (kanban/chat hit the turn cap oscillating on `'handleNext'\n * is assigned a value but never used`). The dead-CONTRACT-wire case it\n * was built to catch is independently enforced at\n * `error` severity by `validateActionSpecConformance` /\n * `validateStreamSpecConformance` in contract-validation.ts, so the\n * downgrade loses no correctness coverage. The diagnostic still surfaces\n * as a `warn` and is fed back to the LLM during eval rounds.\n */\nfunction resolveSeverity(\n msg: Linter.LintMessage,\n code: string,\n): 'error' | 'warning' {\n const base: 'error' | 'warning' = msg.severity === 2 ? 'error' : 'warning';\n if (msg.ruleId !== 'no-unused-vars' || base !== 'error') return base;\n const name = msg.message.match(/'([^']+)'/)?.[1];\n if (name === undefined) return 'warning';\n // Escape regex metacharacters in the identifier (defensive — JS\n // identifiers can't contain them, but the message text is untrusted).\n const safe = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Contract-wire binding. Two declaration shapes:\n // - direct: `const submit = useAction('submit')`\n // - destructured: `const [step, setStep] = useGguiContext<number>('step')`\n // The destructured form covers `useGguiContext` (and a defensive\n // `useStream`), where the unused name is one tuple slot.\n const directRe = new RegExp(\n `\\\\bconst\\\\s+${safe}\\\\s*=\\\\s*use(Action|Stream|GguiContext)\\\\s*[<(]`,\n );\n const destructuredRe = new RegExp(\n `\\\\bconst\\\\s+\\\\[[^\\\\]]*\\\\b${safe}\\\\b[^\\\\]]*\\\\]\\\\s*=\\\\s*use(Action|Stream|GguiContext)\\\\s*[<(]`,\n );\n return directRe.test(code) || destructuredRe.test(code)\n ? 'error'\n : 'warning';\n}\n\nfunction generateReactFix(ruleId: string, message: string): string {\n if (ruleId === 'react-hooks/rules-of-hooks') {\n if (message.includes('called conditionally')) {\n return 'Move this hook to the top level of the component, before any early returns or conditionals. Hooks must run in the same order every render.';\n }\n return 'Hooks can only be called at the top level of a React function component or custom hook. Move it out of any conditional, loop, nested function, or callback.';\n }\n if (ruleId === 'react-hooks/exhaustive-deps') {\n return 'Add the missing dependencies to the dependency array, or remove the array to run on every render.';\n }\n if (ruleId === 'react/jsx-no-undef') {\n const match = message.match(/'(\\w+)'/);\n const name = match?.[1] ?? 'Component';\n return `'${name}' is not defined. Import it from the design system or define it in the file.`;\n }\n if (ruleId === 'react/jsx-key') {\n return 'Add a unique \"key\" prop to each element rendered inside a .map() or iterator.';\n }\n if (ruleId === 'react/no-direct-mutation-state') {\n return 'Do not mutate state directly. Use setState or the setter from useState instead.';\n }\n if (ruleId === 'no-unused-vars') {\n // Extract the identifier name from the ESLint message shape:\n // \"'submit' is assigned a value but never used.\" (varsIgnorePattern also referenced)\n const match = message.match(/'([^']+)'/);\n const name = match?.[1] ?? 'variable';\n // Wire-hook shape — if the binding is an obvious contract wire, route\n // the LLM to the right remediation. Heuristic lives on the message\n // text because we only see the rule output here, not the AST.\n const isLikelyWireBinding = /\\bconst\\s+[A-Za-z_$][\\w$]*\\s*=\\s*use(Action|Stream)\\s*\\(/.test(message);\n if (isLikelyWireBinding || /^(submit|cancel|search|progress|snapshot)$/.test(name)) {\n return `'${name}' is declared but never used. If this binding came from a wire hook (useAction / useStream) or a clientCapabilities hook (useGeolocation / useCamera / etc. from @ggui-ai/gadgets), consume it somewhere in the component — render its value in JSX, bind it to a callback prop, or use it in an effect. A contract-declared hook without consumption is a dead wire.`;\n }\n return `'${name}' is declared but never used. Remove the declaration, or consume it somewhere in the component. Prefix with '_' (e.g. '_${name}') to mark it intentionally unused.`;\n }\n return 'Fix the React violation.';\n}\n","// packages/ui-gen/src/design-mode.ts\n//\n// The ONE definition of the `designMode` option and the rendering-canvas\n// vocabulary. Every triad surface (system prompt, boilerplate, tier-0\n// gate, axis checks, evaluator criteria) AND the visual evaluator import\n// these types from here — nothing re-declares the unions.\n//\n// - `constrained` (default) — today's triad: the component composes\n// from the `@ggui-ai/design` primitives, prop enums and spacing\n// scale, and tier-0 enforces the design vocabulary. Byte-identical\n// to the pre-`designMode` behaviour (pinned by\n// `design-mode.pin.test.ts`).\n// - `free` — the design vocabulary is relaxed: raw HTML elements,\n// inline styles and `<style>` blocks are allowed; the design package\n// is importable but optional. Every HARD contract stays: the data\n// contract via the boilerplate-typed wire hooks, the import\n// allowlist + security bans, the host envelope, the budgets, the\n// blueprint-reuse shape, and brand-bearing color via the closed\n// `--ggui-color-*` token manifest (no literals, no fallbacks).\n\nexport const DESIGN_MODES = [\"constrained\", \"free\"] as const;\n\nexport type DesignMode = (typeof DESIGN_MODES)[number];\n\nexport const DEFAULT_DESIGN_MODE: DesignMode = \"constrained\";\n\n// ─── Rendering canvas ───────────────────────────────────────────────────────\n//\n// ONE canvas vocabulary shared by the prompt input (the `free` prompt\n// TELLS the agent its canvas; the `constrained` prompt keeps its\n// shell/screen descriptors byte-for-byte) and the visual evaluator (one\n// screenshot + judge score per class at `CANVAS_VIEWPORTS[class]`).\n//\n// A class is derived from DISPLAY MODE + width, never from width alone:\n// an inline chat card is `xs-chat-card` whatever the host window\n// measures (the bubble, not the window, bounds the component); a\n// fullscreen-class surface follows its width through the three\n// breakpoints. `canvasForViewportWidth` is monotonic in width per\n// display mode (pinned by `design-mode.test.ts`).\n\nexport const CANVAS_CLASSES = [\n \"xs-chat-card\",\n \"mobile-fullscreen-small\",\n \"md\",\n \"lg\",\n \"xl\",\n] as const;\n\nexport type CanvasClass = (typeof CANVAS_CLASSES)[number];\n\nexport interface CanvasViewport {\n readonly width: number;\n readonly height: number;\n}\n\n/** The viewport (CSS px) each class is rendered + judged at. */\nexport const CANVAS_VIEWPORTS: Readonly<Record<CanvasClass, CanvasViewport>> = {\n \"xs-chat-card\": { width: 400, height: 640 },\n \"mobile-fullscreen-small\": { width: 390, height: 844 },\n md: { width: 768, height: 1024 },\n lg: { width: 1024, height: 768 },\n xl: { width: 1440, height: 900 },\n};\n\n/**\n * The two display modes the canvas derivation distinguishes. `inline`\n * is the chat card (MCP Apps `inline` display mode / the `chat` shell);\n * `fullscreen` is every surface the component owns edge to edge or as\n * a panel (`fullscreen`, `pip`, the `spatial` and `partial` shells) —\n * there the width decides the class.\n */\nexport type CanvasDisplayMode = \"inline\" | \"fullscreen\";\n\n/**\n * Map a shell name (`chat` / `fullscreen` / `spatial` / `partial`) or an\n * MCP Apps display mode (`inline` / `fullscreen` / `pip`) onto the\n * canvas display mode. Only `chat` and `inline` are the inline card;\n * everything else is width-governed.\n */\n/**\n * The display mode a JUDGE canvas stands for (ggui#1100): the inline chat\n * card is `xs-chat-card`; every other canvas is a surface the component\n * owns edge to edge, which the served runtime composes with `fit: 'fill'`\n * — so the judge must too, or it scores a picture the user never sees.\n */\nexport function displayModeForCanvas(canvas: CanvasClass): CanvasDisplayMode {\n return canvas === \"xs-chat-card\" ? \"inline\" : \"fullscreen\";\n}\n\nexport function canvasDisplayModeForShell(shell: string | undefined): CanvasDisplayMode {\n return shell === \"chat\" || shell === \"inline\" ? \"inline\" : \"fullscreen\";\n}\n\n/** Fullscreen-class breakpoints (inclusive lower bounds), CSS px. */\nexport const CANVAS_BREAKPOINTS = { md: 600, lg: 1024, xl: 1440 } as const;\n\n/**\n * Derive the canvas class from display mode + container width.\n *\n * inline → `xs-chat-card` at every width\n * fullscreen → width < 600 → `mobile-fullscreen-small`\n * 600 – 1023 → `md`\n * 1024 – 1439 → `lg`\n * ≥ 1440 → `xl`\n */\nexport function canvasForViewportWidth(mode: CanvasDisplayMode, width: number): CanvasClass {\n if (mode === \"inline\") return \"xs-chat-card\";\n if (width < CANVAS_BREAKPOINTS.md) return \"mobile-fullscreen-small\";\n if (width < CANVAS_BREAKPOINTS.lg) return \"md\";\n if (width < CANVAS_BREAKPOINTS.xl) return \"lg\";\n return \"xl\";\n}\n\n/**\n * Map today's shell × screen descriptors onto a canvas class when no\n * width is known. `chat` is always the inline card; `spatial` is a\n * ~600px floating panel (`md`); `fullscreen` follows the screen. Unknown\n * values fall back to `lg` (the widest common fullscreen), matching the\n * skeleton's `fullscreen` / `universal` defaults.\n */\nexport function canvasForRendering(\n shellType: string | undefined,\n screen: string | undefined,\n): CanvasClass {\n const shell = shellType ?? \"fullscreen\";\n if (canvasDisplayModeForShell(shell) === \"inline\") return \"xs-chat-card\";\n if (shell === \"spatial\") return \"md\";\n switch (screen ?? \"universal\") {\n case \"mobile\":\n return \"mobile-fullscreen-small\";\n case \"tablet\":\n return \"md\";\n default:\n return \"lg\";\n }\n}\n\nexport interface CanvasDescriptor {\n /** Short human label. */\n readonly label: string;\n /** Inclusive width range the component must look right across, CSS px. */\n readonly minWidthPx: number;\n readonly maxWidthPx: number;\n /** What the host draws around the component at this canvas. */\n readonly host: string;\n}\n\nexport const CANVAS_DESCRIPTORS: Readonly<Record<CanvasClass, CanvasDescriptor>> = {\n \"xs-chat-card\": {\n label: \"extra-small chat card\",\n minWidthPx: 320,\n maxWidthPx: 480,\n host: \"an inline card inside a chat message bubble — the host draws the card border, shadow and rounded corners; the component fills the bubble width and takes its natural height\",\n },\n \"mobile-fullscreen-small\": {\n label: \"small mobile fullscreen\",\n minWidthPx: 320,\n maxWidthPx: 599,\n host: \"a phone-sized viewport the component owns edge to edge — single column, touch targets at least 44px, the component manages its own scroll\",\n },\n md: {\n label: \"medium panel\",\n minWidthPx: 600,\n maxWidthPx: 1023,\n host: \"a tablet viewport or a floating panel (spatial / picture-in-picture) — one or two columns, medium density\",\n },\n lg: {\n label: \"large fullscreen\",\n minWidthPx: 1024,\n maxWidthPx: 1439,\n host: \"a desktop viewport the component owns edge to edge — multi-column layouts, hover states and pointer interactions are available\",\n },\n xl: {\n label: \"extra-large fullscreen\",\n minWidthPx: 1440,\n maxWidthPx: 1920,\n host: \"a wide desktop viewport the component owns edge to edge — cap content width or use the extra room deliberately; never stretch a single column across the whole width\",\n },\n};\n\n/**\n * The explicit sentence the `free` prompt renders for a canvas — the\n * agent is TOLD the canvas, it never guesses it.\n */\nexport function describeCanvas(canvas: CanvasClass): string {\n const d = CANVAS_DESCRIPTORS[canvas];\n return (\n `This component renders on the \\`${canvas}\\` canvas (${d.label}): ` +\n `${d.minWidthPx}–${d.maxWidthPx}px wide, ${d.host}. ` +\n `Design for the whole range — the host may size the iframe anywhere inside it, and the host owns the height: size to your content, never to the viewport.`\n );\n}\n","// The consumed-token names the generator may TEACH — the manifest minus the names a card may not\n// reference yet.\n//\n// A card is minted by one release and rendered by whichever runtime serves it: during a rolling\n// deploy, or after a rollback, that runtime can be the previous release, which neither declares\n// nor completes a key derived for the first time in this one. A bare `var(--new-key)` then\n// resolves to nothing — a `border` shorthand drops whole — and the no-fallback rule leaves the\n// card nothing to fall back on. So a new derived key ships in two steps: the renderers that\n// declare and complete it serve first (the design package's own primitives read it behind a\n// fallback), and the release AFTER takes it out of this set, in the same change as the prompt\n// guidance that teaches it.\n\nimport { consumedTokenManifest } from \"@ggui-ai/design/themes\";\n\n/**\n * Manifest names held back from every surface that teaches the model a name — the free prompt's\n * colour vocabulary and token reference, and the self-check's nearest-name suggestions. The\n * closed-set check still admits them: a card that references one is valid wherever this release\n * renders it.\n *\n * Empty today. The control edges (`controlOutline`, `controlAccentOutline`, ggui#1494) were held here\n * until every serving and rollback runtime declared them; the derivation (`10a0c00f2`) is in every\n * release from tag 17 on, so they are taught from ggui#1697, in the same change as the prompt rule that\n * teaches a control's edge.\n */\nexport const NOT_YET_TAUGHT_TOKENS: ReadonlySet<string> = new Set<string>([]);\n\n/** The manifest as the model is taught it. */\nexport const taughtTokenManifest: readonly string[] = consumedTokenManifest.filter(\n (token) => !NOT_YET_TAUGHT_TOKENS.has(token),\n);\n","// Evaluation type vocabulary shared between the harness runtime and its\n// check/evaluator surfaces. This is the narrow contract layer — the\n// type language every harness leg is written against:\n//\n// - `EvalIssue` — the single issue shape everything produces.\n// - `EvalTier` / `EvalOutcome` / `EvalCategory` — the issue's axes.\n// - `Priority` — P0/P1/P2 ranking referenced by the retry formatter.\n// - `EvalResult` — aggregate shape a runner returns.\n// - `QualityMode` / `QualityConfig` / `DEFAULT_QUALITY_CONFIG` —\n// the quality-mode knob the adapter surface consumes.\n// - `priorityForIssue` / `isBlocked` / `getActionableIssues` — the\n// purely-typed helpers over the vocabulary.\n//\n// `EvalIssue` is referenced by `PatchFn`, `TierCheck`, `LLMEvaluator`,\n// and `RuntimeRenderCheck` in the harness types hub.\n\n// ─── Priority ──────────────────────────────────────────────────────────────\n// P0 = must (compile + complete), P1 = should (safety), P2 = nice (quality).\n// Single source of truth for the retry-formatter ranking.\n\nexport type Priority = \"P0\" | \"P1\" | \"P2\";\n\nimport type { VisionFinishReason } from '../harness/llm-router.js';\nimport type { GenerationRuntimeProbeOutcome, GenerationRuntimeProbeStatus } from \"@ggui-ai/mcp-server-core\";\nimport type { CanvasClass, DesignMode } from \"../design-mode.js\";\n\n// ─── Issue shape ───────────────────────────────────────────────────────────\n\nexport type EvalTier = 0 | 1 | 2;\nexport type EvalOutcome = \"fail\" | \"warn\" | \"pass\";\n\nexport type EvalCategory =\n | \"compile\"\n | \"security\"\n | \"contract\"\n | \"types\"\n | \"imports\"\n | \"tokens\" // tier 0\n | \"mode\" // tier 0 — per-mode deterministic\n | \"functionality\"\n | \"crash\" // tier 1\n | \"interactivity\"\n | \"accessibility\"\n | \"layout\"\n | \"loading\"\n | \"visual\"; // tier 2\n\nexport interface EvalIssue {\n tier: EvalTier;\n result: EvalOutcome;\n category: EvalCategory;\n /**\n * Priority tier — threaded through to the retry formatter so the LLM can\n * rank its next patch against the prompt's P0/P1/P2 priority schema.\n * Derived from (category, result) via {@link priorityForIssue} when not\n * explicitly set. Optional on construction; check-runners typically\n * populate it before returning.\n */\n priority?: Priority;\n subcategory?: string;\n severity?: \"critical\" | \"major\";\n description: string;\n fix: string;\n line?: number;\n /**\n * The visual leg's provenance (ggui#1545): `judge` (the model's finding) or `instrument` (a deterministic\n * measurement). Absent on every other leg's issues. `visualEvaluation.actOn` acts on `judge` only.\n */\n origin?: \"judge\" | \"instrument\";\n}\n\n/**\n * Runtime-render probe execution status — four-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\". ONE union: the\n * same values a generation's metadata reports (`GenerationRuntimeProbeStatus`\n * in `@ggui-ai/mcp-server-core`), declared there and named here.\n *\n * - `ran` — probe executed; its findings (possibly none) are\n * in the issue stream under `runtime:*` subcategories.\n * - `infra-skipped` — probe could NOT execute (environment failure:\n * happy-dom load, user-event document capture,\n * ESM/CJS interop). Carries ZERO probe evidence;\n * consumers MUST NOT count it as a pass.\n * - `not-applicable`— nothing to probe (no compiled code, no contract\n * surface, or no runtimeRender check configured).\n * - `timed-out` — probe started but did not finish inside its\n * wall-clock bound (ggui#1299). Carries ZERO\n * evidence about the component: on a contended\n * host an ordinary component crosses the bound.\n * Consumers MUST NOT count it as a pass, and MUST\n * NOT count it as a crash either. `elapsedMs` and\n * `hostLoad` say how long it ran and how busy the\n * host was, so a reader can tell the two cases apart.\n */\nexport type RuntimeProbeStatus = GenerationRuntimeProbeStatus;\n\n/**\n * The host's 1-minute load average at a probe's start and end, beside the\n * number of CPUs the process can use (ggui#1299). A load well above\n * `cores` means the probe competed for CPU; a wall-clock bound crossed\n * there says more about the host than about the component.\n */\nexport interface ProbeHostLoad {\n readonly start: number;\n readonly end: number;\n readonly cores: number;\n}\n\n/**\n * ggui#1398 — whether the controls the probe clicked showed they were\n * working once their action was pending. Report-only: it is read by the\n * benchmark and never counted into the probe's warnings or fed back to\n * the coding loop.\n */\nexport interface ProbePendingAffordance {\n /** Controls the pending phase marked pending: those whose click dispatched their action (click or submit wiring) and that were still in the page. `visible + missing.length === dispatched`. */\n readonly dispatched: number;\n /** Of those, how many visibly changed while pending (disabled, busy, text, or replaced). */\n readonly visible: number;\n /** The actions whose control did not visibly change, including one whose card threw while pending. */\n readonly missing: readonly string[];\n /** Actions whose control was no longer in the page when its turn came (the card replaced it, or blanked after a throw): never marked, not counted as dispatched. */\n readonly gone: readonly string[];\n}\n\n/**\n * The engine's own fields on a probe's meta, beside the outcome a\n * generation's metadata reports: why a probe did not finish, its render\n * time, the host's load around it. Present on every arm of\n * {@link RuntimeProbeMeta}; each is absent when the probe had nothing to\n * say about it.\n */\nexport interface RuntimeProbeMetaDetail {\n /** Populated for `infra-skipped` / `not-applicable` / `timed-out` — why the probe didn't finish. */\n readonly reason?: string;\n /** `ran` only: the check's own render time, inside `elapsedMs`. */\n readonly renderMs?: number;\n /** Host load around the probe, when it ran isolated (absent for an in-process probe). */\n readonly hostLoad?: ProbeHostLoad;\n /** Time the check waited for a probe slot before it started, ms; present only when > 0 (ggui#1380 C2b). */\n readonly queuedMs?: number;\n /**\n * `ran` only: the pending-affordance walk (ggui#1398). Absent when no\n * action walk ran, so \"no data\" and \"0 of 0\" read differently.\n */\n readonly pendingAffordance?: ProbePendingAffordance;\n}\n\n/**\n * Probe execution meta stamped onto an `EvalResult` at the exit-decision\n * points that invoke the probe. Absence of this field means the eval\n * path never reached a probe invocation at all — consumers treat that\n * the same as not-run, never as a pass.\n *\n * ONE union with the generation metadata's probe outcome\n * (`GenerationRuntimeProbeOutcome` in `@ggui-ai/mcp-server-core`, declared\n * there and carried here with {@link RuntimeProbeMetaDetail} on every arm),\n * so the round's stamp and the metadata's record cannot say different\n * things (ggui#1380):\n *\n * - `ran` + `verdict: 'pass'` — the probe executed and no check failed;\n * - `ran` + `verdict: 'fail'` — ANY check failed; `failChecks` lists the\n * distinct check kinds that did (`RenderCheckKind`, the engine's name\n * for the same union), never empty, in the order `RENDER_CHECK_KINDS`\n * declares them, parsed from the probe's own\n * `runtime:<check>[:<subject>]` issues;\n * - `timed-out` / `infra-skipped` / `not-applicable` — no verdict, and the\n * type carries none. `elapsedMs` (on every status that reached the\n * check) and `hostLoad` say how long it ran and how busy the host was.\n *\n * The verdict and the repair trigger are two different questions. The\n * verdict is `fail` on any failing check. The one repair turn a probe-only\n * round buys fires on a `render-no-throw` fail the engine recognises\n * (`isRecoverableRenderCrash`) and on nothing else: on the PROBE-ONLY round a\n * `fail` verdict whose checks are `prop-sensitivity`, `action-wiring` or any\n * other kind is recorded here and never fed back. The same meta is stamped on\n * the EVALUATION lane, where a `prop-sensitivity` fail buys that lane's own\n * contract-feedback round (ggui#1261, `FEEDBACK_PROBE_CHECKS`) — a different\n * turn under a different rule, not the repair turn.\n */\nexport type RuntimeProbeMeta = GenerationRuntimeProbeOutcome & RuntimeProbeMetaDetail;\n\n/**\n * The one repair turn a probe-only round buys (ggui#1380). A serving\n * deployment that wires the runtime probe and configures no evaluator runs\n * the probe once after the coding turns; a render crash the engine\n * recognises buys exactly one repair turn, then one re-probe. This records\n * what came of it:\n * - `compiled: false` — the repair turn's code did not pass self-check, so\n * no re-probe ran (there is no `after`) and the pre-repair card is the\n * one served;\n * - `compiled: true` — the re-probe ran and `after` is its whole meta:\n * its status, its verdict when it ran, and the checks that still fail.\n * Whether the crash class the turn was bought for is still there is\n * `after.verdict === 'fail' && after.failChecks.includes('render-no-throw')`.\n * The two arms are exclusive by type.\n */\nexport type RuntimeProbeRepair =\n | { readonly attempted: true; readonly compiled: false; readonly trigger?: never }\n | { readonly attempted: true; readonly compiled: true; readonly trigger: RuntimeProbeMeta };\n\n/**\n * Per-criterion execution status — three-valued so \"the criterion\n * silently produced no verdict\" is never conflated with \"the criterion\n * ran clean\", and neither is conflated with \"not evaluated by design\".\n * Same doctrine and vocabulary family as `RuntimeProbeStatus` above.\n *\n * - `ran` — the LLM call completed and returned a verdict\n * for this criterion; its findings (possibly\n * none) are in `issues`.\n * - `skipped` — the call errored or returned no tool call. The\n * criterion carries ZERO evidence; the evaluator\n * fail-opens it into `pass` to avoid blocking\n * generation on flaky LLM calls, so consumers\n * MUST consult this field before treating `pass`\n * membership as a verdict. Counts AGAINST\n * coverage.\n * - `not-applicable` — the evaluator was bypassed by design for this\n * cell (e.g. the same-image low-risk bypass:\n * axis checks clean, tier-1/2 never invoked).\n * `reason` names the bypass. Excluded from\n * coverage denominators — it is neither evidence\n * nor a silent absence.\n */\nexport type CriterionRunStatus = \"ran\" | \"skipped\" | \"not-applicable\";\n\n/** Coverage row for one evaluation criterion of one eval run. */\nexport interface CriterionCoverage {\n readonly criterion: string;\n readonly tier: 1 | 2;\n readonly status: CriterionRunStatus;\n /** Populated for `skipped` / `not-applicable` — why no verdict. */\n readonly reason?: string;\n}\n\n/**\n * Coverage of the screenshot JUDGE leg for one eval round (ggui#1221) — a\n * different surface from the `visual` CRITERION in `criteriaCoverage` (the\n * LLM evaluator's read of the source). `ran` = a frame was captured and\n * judged; `skipped` = the leg was configured but produced no verdict\n * (no browser, a launch or in-page failure, an unbundlable component, an\n * unparsable judge answer) with `reason` naming why; `not-applicable` =\n * the round had no visual leg configured. Before this row a skipped leg\n * left NO trace on the result — `{ issues: [] }` read exactly like a\n * clean run, and every bootstrap mint on a browserless runtime \"passed\"\n * its visual round that way.\n */\nexport interface VisualCoverage {\n readonly status: CriterionRunStatus;\n /** Populated for `skipped` / `not-applicable` — why no verdict. */\n readonly reason?: string;\n}\n\n/**\n * The static criteria `runLLMEvaluation` runs, in stamp order — the\n * ONE list both the evaluator's coverage stamp and the harness's\n * bypass stamp derive from, so the two can never disagree on the set.\n * Tier 1 = binary pass/fail gates; tier 2 = fail/warn/pass quality.\n */\nexport const LLM_EVAL_STATIC_CRITERIA: ReadonlyArray<{ readonly criterion: string; readonly tier: 1 | 2 }> = [\n { criterion: \"functionality\", tier: 1 },\n { criterion: \"crash\", tier: 1 },\n { criterion: \"interactivity\", tier: 2 },\n { criterion: \"accessibility\", tier: 2 },\n { criterion: \"layout\", tier: 2 },\n { criterion: \"loading\", tier: 2 },\n { criterion: \"visual\", tier: 2 },\n];\n\n/**\n * Coverage rows for a cell where the evaluator was BYPASSED BY DESIGN\n * (never invoked) — one `not-applicable` row per static criterion, all\n * carrying `reason`. Harness exits that skip tier-1/2 evaluation stamp\n * this so the cell is neither a silent absence (field missing) nor\n * evidence. Same shape contract as `runLLMEvaluation`'s stamp: always\n * every criterion. Lives here (not in llm-evaluator) because the bypass\n * exit runs before the evaluator module is lazily loaded.\n */\nexport function notApplicableCoverage(reason: string): CriterionCoverage[] {\n return LLM_EVAL_STATIC_CRITERIA.map(({ criterion, tier }) => ({\n criterion,\n tier,\n status: \"not-applicable\",\n reason,\n }));\n}\n\n/** One contract-feedback round (ggui#1261): what bought it, and the source it was fed back on. */\nexport interface ContractFeedbackRecord {\n /** The exit-probe issue subcategories that bought the round, e.g. `runtime:prop-sensitivity:currentUser`. */\n readonly firedOn: readonly string[];\n /** The component source as it stood when the model was told — the round's BEFORE. */\n readonly sourceBefore: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\n /**\n * Per-criterion coverage for this eval run — one row per static\n * criterion, ALWAYS all of them when present. Stamped by\n * `runLLMEvaluation` (`ran` / `skipped`) and by the harness on\n * evaluator-bypass exits (`not-applicable` + reason). The harness\n * carries it unchanged through every later re-stamp of this result.\n * Absent = coverage UNKNOWN (paths that predate the instrument, e.g.\n * `parseEvalResponse` replays) — never assume `ran`, never assume\n * bypass.\n */\n criteriaCoverage?: CriterionCoverage[];\n /**\n * Runtime-render probe execution meta. Stamped by the exit-decision\n * probe runner; absent on eval paths that never invoke the probe.\n */\n runtimeProbe?: RuntimeProbeMeta;\n /**\n * The probe-only round's repair record (ggui#1380) — present only when a\n * recoverable render crash bought the one repair turn. See\n * {@link RuntimeProbeRepair}. `runtimeProbe` beside it is the re-probe's\n * verdict when the repair compiled, else the pre-repair probe's.\n */\n runtimeProbeRepair?: RuntimeProbeRepair;\n /**\n * The contract-feedback round, when one fired this generation (ggui#1261):\n * which exit-probe findings bought it and the source as it stood when the\n * model was told. `runtimeProbe` and the `runtime:*` issues on this result\n * are the probe's verdict AFTER that round; `sourceBefore` beside the final\n * source is the round's before/after. Absent when no such round fired.\n */\n contractFeedback?: ContractFeedbackRecord;\n /**\n * Per-canvas visual verdicts. Stamped by the harness ONLY when the\n * visual leg ran with `visualEvaluation.canvases` set (arm-neutral —\n * the same judge in every design mode); absent on the single-shot\n * visual path and whenever the visual leg did not run. PNGs stay on\n * `runVisualEvaluation`'s own result (`VisualEvaluationResult.canvases[*].screenshotPng`),\n * never here — this object is serialized into reports.\n */\n visual?: VisualEvalSummary;\n /**\n * Whether the screenshot judge leg ran, was skipped (with the reason) or\n * was not configured — ALWAYS stamped by the harness's eval round\n * (ggui#1221), so a consumer can tell a clean visual run from a leg\n * that silently could not run. See {@link VisualCoverage}.\n */\n visualCoverage?: VisualCoverage;\n}\n\n/** One canvas's visual verdict, PNG-free — see `EvalResult.visual`. */\n/**\n * How one canvas's `score` was reached (ggui#1072): `k` vision calls on the\n * SAME captured frame, aggregated by `rule`. Always present — `k: 1` ⇒\n * `samples: [score]`, `sigma: 0`, `notes: [critique]` — so one shape serves\n * a single judgement and a median of many. `samples`/`notes` carry only the\n * calls the judge could parse (in call order); `k` stays the requested count,\n * so a short `samples` is visible on the row rather than filled in.\n */\nexport interface CanvasJudgeRecord {\n readonly k: number;\n readonly rule: 'median';\n readonly samples: number[];\n /** Population σ of `samples` (0 when one sample). */\n readonly sigma: number;\n /** The judge's per-canvas critique per sample — the words beside a swing. */\n readonly notes: string[];\n /**\n * ggui#1127 — the cause of each scoring sample whose answer failed to parse and was SALVAGED: its four dimensions\n * were recovered from the closed prefix, its issues kept only as far as they closed, its critique lost. One entry\n * per salvaged sample; absent when every sample parsed. The salvaged sample's score still counts.\n */\n readonly salvaged?: readonly JudgeSalvageCause[];\n /**\n * ggui#1127 — the criteria call's answer was salvaged. A salvage keeps no criteria, so that frame's judge rows read\n * \"not answered\" with this cause rather than a clean `n/a`. Absent when the call parsed or was not asked.\n */\n readonly criteriaSalvaged?: JudgeSalvageCause;\n /**\n * ggui#1687 — the model asked for, and every model the provider said answered this canvas's calls (scoring and\n * criteria), deduplicated. `served` is empty when no provider named one: unknown, never \"the requested model\".\n * When the request names an alias and the provider echoes the alias (measured on a hosted route, 125 of 125\n * canvases), `served` confirms the alias was honoured but cannot tell two snapshots behind it apart. A judge that\n * must is pinned to a dated snapshot id instead. With the alias, a snapshot change shows only as a step on a date in\n * the judge's pooled within-call spread, read by week. That is a read someone runs, not a monitor.\n */\n readonly models?: { readonly requested: string; readonly served: readonly string[] };\n}\n\n/**\n * ggui#1687 — what the criteria call's answer held, before resolution. A row the judge left unanswered reads `n/a`\n * either way; this says whether the call came back empty, cut, or with entries the parser had to drop.\n */\nexport interface CriteriaAnswerCounts {\n /** The answer carried a `criteria` array. `false`: absent or not an array, so no row was read from it. */\n readonly array: boolean;\n /** Entries in the array. */\n readonly received: number;\n /** Entries kept: an object with a string id and a verdict of pass, fail or n/a. */\n readonly kept: number;\n /** Entries dropped, by why. */\n readonly dropped: { readonly notObject: number; readonly badId: number; readonly badVerdict: number };\n}\n\n/**\n * ggui#1127 — why a judge answer that failed to parse had to be salvaged. `output-cap`: the provider reported it\n * stopped at the output cap. `malformed`: the provider reported a normal stop, so the answer ended but did not\n * parse. `stopped`: the provider stopped it for another reason it named (a safety stop, or one it reports as\n * other), so it is cut, not malformed. `unknown`: the provider or route reported no stop reason. Never inferred\n * from the answer's length.\n */\nexport type JudgeSalvageCause = \"output-cap\" | \"malformed\" | \"stopped\" | \"unknown\";\n\n/** ggui#1127 — salvaged judge answers across a canvas run, per leg, as N of M. */\nexport interface JudgeSalvageCounts {\n /** Scoring answers: `answers` = samples that parsed or were salvaged, `salvaged` = those salvaged. */\n readonly scoring: { readonly salvaged: number; readonly answers: number };\n /** Criteria calls: `answered` = calls that parsed or were salvaged, `salvaged` = those salvaged (criteria lost). */\n readonly criteria: { readonly salvaged: number; readonly answered: number };\n}\n\n// ─── Visual criteria (ggui#1436) ──────────────────────────────────────────\n// The judge's typed criteria block per canvas — report-only beside the score\n// until a later word flips a gate to it. Every field below is optional on the\n// stamps so yesterday's `eval.json` and an old judge answer still parse (N−1).\nimport type { FetchShape, LayoutShape, RenderShape, RiskTier, StateShape, WriteShape } from \"../classifier/axes.js\";\n\nexport type CriteriaSeverity = \"must\" | \"should\";\nexport type CriteriaVerdict = \"pass\" | \"fail\" | \"n/a\";\n/** The method that produces a verdict: an instrument's measurement, the vision judge off the frame, or a person's eye. */\nexport type CriteriaMethod = \"instrument\" | \"judge\" | \"human\";\n/** The method's readiness, as the bank's author wrote it — the only source of an `n/a` that is not the judge's own. */\nexport type CriteriaStatus = \"live\" | \"reference\" | \"planned\" | \"manual\";\n/**\n * How a criterion entered the selection: bank-level (`static`, an empty scope) or by the selector's\n * rules for this card (`context`). A model PROPOSING a criterion at judge time is RESERVED and not a\n * member until a consumer exists — it would be `should`-only, recorded verbatim, never a gate.\n */\nexport type CriteriaSource = \"static\" | \"context\";\nexport type CriteriaChroma = \"achromatic\" | \"chromatic\" | \"unknown\";\n/** The classifier's shape axes, as hashed into the set id. */\nexport interface CriteriaAxes {\n render: RenderShape;\n state: StateShape;\n writes: WriteShape;\n fetch: FetchShape;\n layout: LayoutShape;\n}\n/** The selector's inputs, stored with the verdict so a reader recomputes `criteriaSetId` from the record alone. */\nexport interface CriteriaContext {\n canvas: CanvasClass;\n hasActions: boolean;\n riskTier: RiskTier;\n axes: CriteriaAxes;\n chroma: CriteriaChroma;\n profilePresent: boolean;\n /** The harness's shell as named; `unknown` when the round carries none. */\n shell: string;\n /** The caller's item kind (a bootstrap mint's `hello`); hashed when present. */\n kind?: string;\n /** The styling preset in force (the profile's aesthetic id); a recipe is selected only under its preset. */\n preset?: string;\n}\n/** What was asked and why — recorded BEFORE the judge runs. Omission is the selector's decision. */\nexport interface CriteriaSelection {\n id: string;\n source: CriteriaSource;\n reason: string;\n}\n/** One criterion's verdict; `n/a` is the judge's answer (\"cannot read this off the frame\"), an unanswered id, a tie, or a method whose `status` is not live. */\nexport interface CriterionVerdict {\n id: string;\n severity: CriteriaSeverity;\n method: CriteriaMethod;\n status: CriteriaStatus;\n source: CriteriaSource;\n verdict: CriteriaVerdict;\n evidence: string;\n /**\n * ggui#1663 — a measured reading beside a judge row, REPORT-ONLY: the row's `verdict` stays the judge's, so this\n * changes no verdict, score or bar. Present only on rows an instrument answers beside the judge (`space.edge`).\n */\n instrument?: { verdict: CriteriaVerdict; evidence: string };\n}\n/** ggui#1687 — the criteria call as it came back: its answer's counts, ids it answered outside the bank, its stop. */\nexport interface CriteriaCallRecord {\n readonly answer: CriteriaAnswerCounts;\n /** Kept entries whose id names no row of the bank. */\n readonly unknownIds: number;\n /** The provider's normalized stop reason (`length` = the output cap); absent when it reported none. */\n readonly finishReason?: VisionFinishReason;\n}\nexport interface CriteriaBlock {\n /** sha256(bank version | selector version | canonical context), 16 hex — the block's own digest. */\n criteriaSetId: string;\n bankVersion: string;\n selectorVersion: string;\n context: CriteriaContext;\n selection: CriteriaSelection[];\n verdicts: CriterionVerdict[];\n /** ggui#1687 — the call that answered this block, when one did. Absent for a block resolved with no call. */\n call?: CriteriaCallRecord;\n}\n/** The roll-up across canvases; a `must` at `n/a` is listed, never counted as a pass. */\nexport interface CriteriaRollup {\n mustFailed: string[];\n shouldFailed: string[];\n mustNa: string[];\n}\n\n/** ggui#1492 — a host\"s frame round the inline card, as data. Colours are `#rrggbb`; the ring\"s `alpha` is 0..1. */\nexport interface HostInlineFrame {\n /** The frame\"s surface — what shows behind a transparent card, and under the floor\"s residual. */\n readonly surface: string;\n /** The room the frame sits in (the page ground round it). */\n readonly ground: string;\n readonly ring: { readonly widthPx: number; readonly color: string; readonly alpha: number };\n readonly radiusPx: number;\n /** The host\"s minimum frame height: a card shorter than it sits in a frame this tall, and the visitor sees the rest as void. */\n readonly minHeightPx?: number;\n}\n/** ggui#1492 — how a host presents one canvas: the label the judge is told, the page ground, and (the inline card only) its frame. */\nexport interface CanvasHostPresentation {\n readonly label: string;\n /** The page ground under a fill canvas\"s panel; the inline card\"s ground lives on its {@link HostInlineFrame}. */\n readonly ground?: string;\n readonly frame?: HostInlineFrame;\n}\n/** ggui#1492 — why the judge did not draw a canvas's host presentation. The codes are the lane reader's own. */\nexport type HostPresentationIgnoredReason = \"label_missing\" | \"color_not_hex\" | \"frame_off_inline\" | \"frame_malformed\" | \"ground_on_inline\";\n/**\n * ggui#1492 — what the judge DID with a canvas's host presentation, read from the judge itself: `applied` carries\n * the presentation it drew, `ignored` the reason it drew none. Absent when the caller supplied no presentation.\n */\nexport type CanvasPresentationOutcome =\n | { readonly status: \"applied\"; readonly applied: CanvasHostPresentation }\n | { readonly status: \"ignored\"; readonly reason: HostPresentationIgnoredReason };\n\nexport interface CanvasVisualSummary {\n canvas: CanvasClass;\n viewport: { width: number; height: number };\n /** The judge's weighted score at this canvas (0-100). */\n score: number;\n /** `score >= passThreshold`, and on the inline card: no overflow (ggui#1027). */\n passed: boolean;\n /** The document's scroll height at this canvas, CSS px; `null` when unmeasurable (ggui#1027). */\n contentHeight: number | null;\n /** `contentHeight > viewport.height` — measured on every canvas, judged per `canvasFitPolicy`. */\n overflow: boolean;\n /**\n * ggui#1120 — how far down the capture anything was painted: the last inked row over the measured\n * region's height (inside a drawn host panel's chrome on md/lg/xl), read from the screenshot's\n * pixels against their dominant colour. `0` is the blank the judge fails (`canvas-blank`); every\n * other value is reported, never scored. `null` when the capture could not be read.\n */\n inkRatio: number | null;\n /** How `score` was reached — always present (ggui#1072). */\n judge: CanvasJudgeRecord;\n /** ggui#1436 — the typed criteria block, when a bank was configured; report-only. */\n criteria?: CriteriaBlock;\n /** ggui#1492 — what the judge did with this canvas's host presentation, when one was supplied. */\n presentation?: CanvasPresentationOutcome;\n /**\n * How the judge composed the mount (ggui#1100): `'fill'` on every\n * fullscreen canvas — the served runtime's fit, the root stretched to\n * the frame; absent on the inline card, which keeps its natural height.\n */\n fit?: 'fill';\n}\n\n/**\n * ggui#1195 — the fit reading on the canvas whose policy FAILS an overflow\n * (the inline chat card): the box it was judged at (`ceiling` — the order's\n * declared viewport when one was carried, else the class box), whether that\n * box was declared, and how many px of content sit below it (0 = fits).\n * Present only when such a canvas was judged with a measurable height, so\n * the bar and the ledger read one number for \"does the hello fit\".\n */\nexport interface VisualFitStamp {\n readonly canvas: CanvasClass;\n readonly ceiling: { readonly width: number; readonly height: number };\n readonly declared: boolean;\n readonly overflowPx: number;\n}\n\n/** The visual leg's per-canvas summary — see `EvalResult.visual`. */\nexport interface VisualEvalSummary {\n /** Mean of the canvas scores (rounded). */\n score: number;\n /** Every canvas passed. */\n passed: boolean;\n canvases: CanvasVisualSummary[];\n /** ggui#1195 — see {@link VisualFitStamp}; absent when no fail-policy canvas was judged. */\n fit?: VisualFitStamp;\n /** The design tree the judge painted with (ggui#1042): `src` + `srcSha256` — `design@judge`. */\n design?: { readonly src: string; readonly srcSha256: string };\n /** The mode the judge's tokens were composed in, when the caller said (ggui#1076). */\n themeMode?: 'light' | 'dark';\n /** ggui#1436 — the criteria roll-up across canvases, when any canvas carries a block; report-only. */\n criteria?: CriteriaRollup;\n}\n\n// ─── Quality mode ──────────────────────────────────────────────────────────\n\nexport type QualityMode = \"fast\" | \"auto-improve\" | \"high-quality\";\n\nexport interface QualityConfig {\n quality: QualityMode;\n visualEval: boolean;\n maxCostPerGeneration: number;\n model?: { provider?: string; model?: string };\n}\n\nexport const DEFAULT_QUALITY_CONFIG: QualityConfig = {\n quality: \"fast\",\n visualEval: false,\n maxCostPerGeneration: 3,\n};\n\n// ─── Axis-check types ──────────────────────────────────────────────────────\n// The `AxisCheck` type vocabulary lives here. The check bodies\n// themselves (REGISTRY, per-axis implementations) live under\n// `./axis-checks/`.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { JsonObject } from \"@ggui-ai/protocol\";\nimport type { AxisVector, Classification } from \"../classifier/axes.js\";\nimport type { AxisKey } from \"../fragments/index.js\";\n\nexport interface AxisCheckInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n /** Full classification — checks may read sibling axes. */\n classification: Classification;\n /**\n * Which triad produced the source. Checks that assert a design-package\n * component (e.g. `layout.multi_step.stepper_adopted`) read it and\n * stand down in `free` mode, where the primitive is optional. Absent\n * means `constrained`.\n */\n designMode?: DesignMode;\n /**\n * The rendering canvas the source is judged FOR (ggui#1117). A width cap on\n * the outermost element is a defect on a fullscreen canvas and a no-op in a\n * chat bubble, so a check that reads width must know the surface. Populated\n * where the harness is built (`Harness.canvas`); ABSENT for callers with no\n * rendering context — a check handles `undefined`, it never assumes a\n * default (a silent `lg` would be the same guess with a nicer face).\n */\n canvas?: CanvasClass;\n /**\n * The props the probe and the judge RENDERED the source with (ggui#1285) — a bootstrap order's\n * `sampleProps`, the bench commit's fixture. They are judging data, not the request: a literal in\n * the source that equals one of these values, and that the request never stated, is baked copy a\n * visitor sees whenever the agent leaves the prop out. Populated on the served loop and at\n * auto-commit; ABSENT where the caller has none — the check stands down, it never guesses.\n */\n fixtureProps?: JsonObject;\n}\n\n/**\n * A gated check. Runs only when the classification's axis value matches\n * one of the gate's accepted values. Multiple gates (implicit AND) support\n * cross-axis combinations.\n */\nexport interface AxisCheck {\n /** Stable id used in issue subcategories. */\n id: string;\n /** Primary axis this check gates on. */\n axis: AxisKey;\n /** Which values of that axis activate the check. */\n values: readonly string[];\n /** Optional extra gate on a sibling axis (e.g., only when state=merge AND writes=per-item). */\n and?: { axis: AxisKey; values: readonly string[] };\n /** Execute the check and emit zero or more issues. */\n run(input: AxisCheckInput): EvalIssue[];\n}\n\n/**\n * Whether a check's gate(s) match the given axis vector. Pure function,\n * no issue emission.\n */\nexport function matches(vector: AxisVector, check: AxisCheck): boolean {\n const primary = vector[check.axis] as string;\n if (!check.values.includes(primary)) return false;\n if (check.and) {\n const sibling = vector[check.and.axis] as string;\n if (!check.and.values.includes(sibling)) return false;\n }\n return true;\n}\n\n// ─── Purely-typed helpers ──────────────────────────────────────────────────\n\n/**\n * Map a tier-0 issue category to the canonical P0/P1/P2 priority.\n *\n * Sourced from the criteria priority assignments:\n * - P0 (must): compile, security, imports, contract, types, mode\n * - P1 (safety): tokens, crash, functionality\n * - P2 (quality): interactivity, accessibility, layout, loading, visual\n */\nexport function priorityForIssue(category: EvalCategory): Priority {\n if (\n category === \"interactivity\" ||\n category === \"accessibility\" ||\n category === \"layout\" ||\n category === \"loading\" ||\n category === \"visual\"\n ) {\n return \"P2\";\n }\n if (category === \"tokens\" || category === \"crash\" || category === \"functionality\") {\n return \"P1\";\n }\n // compile, security, imports, contract, types, mode → P0.\n return \"P0\";\n}\n\n/** Whether any issue blocks shipping (has result = 'fail'). */\nexport function isBlocked(result: EvalResult): boolean {\n return result.issues.some((i) => i.result === \"fail\");\n}\n\n/**\n * Return the issues the agent should act on, depending on quality mode.\n * - fast: only fails (blocking issues)\n * - auto-improve / high-quality: fails + warns\n */\nexport function getActionableIssues(result: EvalResult, mode: QualityMode): EvalIssue[] {\n if (mode === \"fast\") {\n return result.issues.filter((i) => i.result === \"fail\");\n }\n return result.issues.filter((i) => i.result === \"fail\" || i.result === \"warn\");\n}\n\n// ─── Criteria (single source of truth for coding + eval sides) ─────────────\n//\n// Each criterion is defined ONCE with both sides of the contract:\n// - codingGuidance: what the coding agent should DO\n// - evalInstruction: what the eval agent should CHECK\n// They must be compatible — changing one means reviewing the other.\n//\n// This is *validated* shipping content: it's what the hosted runtime sends\n// to every generation today. External OSS implementers building their own\n// prompts should be able to use the same rubric — hence it's open.\n\nexport interface EvalCriterion {\n /** Unique identifier matching the eval tool name (e.g., 'functionality') */\n id: string;\n /** Human-readable name shown to both agents */\n name: string;\n /** Priority tier — P0 must, P1 should, P2 nice */\n priority: Priority;\n /** What the coding agent should DO to satisfy this criterion */\n codingGuidance: string;\n /** What the eval agent should CHECK — the evaluation prompt */\n evalInstruction: string;\n /** Tier 0 = programmatic, Tier 1 = LLM critical, Tier 2 = LLM quality */\n tier: 0 | 1 | 2;\n /** Eval outcome when this criterion fails */\n failOutcome: \"fail\" | \"warn\";\n}\n\nexport const CRITERIA: readonly EvalCriterion[] = [\n // ── P0: Correctness (must satisfy — failure = broken component) ──\n\n {\n id: \"compile\",\n name: \"Compile & type-check\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance:\n \"Code must compile. The typed Props and wire hook generics are enforced by the compiler.\",\n evalInstruction: \"Checked automatically by esbuild + TypeScript. No LLM evaluation needed.\",\n },\n {\n id: \"render-props\",\n name: \"Render all Props fields\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance: \"Render every Props field in JSX. Access via props.fieldName.\",\n evalInstruction:\n \"Check that every field from interface Props appears as props.fieldName in the function body.\",\n },\n {\n id: \"wire-hooks\",\n name: \"Wire all contract hooks\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Wire every useAction/useStream and every clientCapabilities.gadgets hook (e.g., useGeolocation) to a UI element. `agentCapabilities.tools` is a catalog the AGENT invokes — NOT a component hook surface.\",\n evalInstruction:\n \"Check that every hook variable from the boilerplate appears in the JSX or an effect.\",\n },\n {\n id: \"imports\",\n name: \"Valid imports only\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Only import from react, @ggui-ai/design/*, and @ggui-ai/wire.\",\n evalInstruction: \"Flag any import from a package not in the allowlist.\",\n },\n {\n id: \"security\",\n name: \"No eval/fetch/window\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Never use eval(), fetch(), or window. Data comes from props and hooks.\",\n evalInstruction: \"Flag any call to eval(), fetch(), or window access.\",\n },\n\n // ── P1: Safety (should satisfy — failure = crash or bad UX) ──\n\n {\n id: \"functionality\",\n name: \"All features implemented\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance: \"Implement ALL features from the request AND the data contract.\",\n evalInstruction: `Evaluate FUNCTIONALITY: Does this component implement ALL features from the request AND the data contract?\n\nCheck against BOTH sources:\n1. Original request — each feature must be coded AND rendered in JSX\n2. Data contract (if present) — verify:\n - Props fields are rendered in the UI. EXCEPTION: pure identifier fields (\\`id\\`, \\`*Id\\`, keys) that exist only to be echoed back inside an action payload do NOT need to be visibly rendered.\n - ALL useAction hooks are wired to clickable UI elements\n - ALL useStream hooks are consumed — the streamed data must reach the UI. Merging stream events into rendered state (a list, a counter, the displayed records) COUNTS as consuming the stream; it need not be a literal \\`.latest\\` render.\n - ALL clientCapabilities gadgets are used. \\`clientCapabilities.gadgets\\` is keyed by npm package: built-in browser capabilities (useGeolocation / useCamera / …) import from @ggui-ai/gadgets; registered third-party gadgets (e.g. useChartTheme) import from their OWN package. Any gadget the contract declares IS a contract feature — NEVER flag it as \"not part of the contract\".\n - \\`agentCapabilities.tools\\` is a catalog declaration only; do NOT flag missing component-side calls for it\n\nA contract hook that is declared but never used at all is a MISSING feature.\n\nCRITICAL: The \"issues\" array must ONLY contain features you are CERTAIN are missing or broken — never an implemented feature. (See \"Issue-array discipline\" above: no speculative, self-negating, or \"verify that…\" entries.)`,\n },\n {\n id: \"crash\",\n name: \"No crash scenarios\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance:\n \"Guard optional props (props.field?.x). stream.latest is T|null — always null-guard. .all is always an array.\",\n evalInstruction: `Evaluate CRASH SAFETY: Are there ACTUAL runtime crash scenarios?\n\nWILL crash (include in issues):\n- .map()/.filter()/.length on an uninitialized variable\n- Accessing property of undefined without guard\n- useStream().latest.field WITHOUT null guard — .latest is T | null\n- Optional Props field accessed as props.field.x without guard\n- Array item optional field: items.map(item => item.priority.toUpperCase()) when priority is optional\n\nSAFE (do NOT include):\n- Optional chaining: props.items?.map() — SAFE\n- Fallback: items || [] — SAFE\n- useState initializer: useState([]) — SAFE\n- Null check: items && items.map() — SAFE\n- stream.latest && stream.latest.field — SAFE, guarded\n- stream.all.map(...) — SAFE, .all is always an array\n- stream.all.length — SAFE, always a number\n\nThe \"issues\" array is ONLY for a specific line that WILL throw at runtime. NEVER put a line you have determined is safe into the issues array — not even to note that it is safe (\"…so this is safely guarded\", \"…so there is no crash\"). If you cannot name a concrete line that will throw, the answer is {\"pass\": true} — return that and an empty issues array.`,\n },\n {\n id: \"tokens\",\n name: \"Design system tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Use CSS variables for colors (var(--ggui-color-*)); use the spacing scale for gap/padding/margin (gap=\\\"md\\\", padding=\\\"lg\\\").\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, and numeric or raw-CSS-length spacing props. A t-shirt-scale spacing name (gap=\\\"md\\\") IS a token — never flag it.\",\n },\n\n // ── P2: Quality (nice to have — failure = lower score, not broken) ──\n\n {\n id: \"interactivity\",\n name: \"Sufficient interactive elements\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Add appropriate interactive elements for the component purpose.\",\n evalInstruction: `Evaluate INTERACTIVITY: Does this component have sufficient interactive elements?\n\nConsider: forms need submit buttons, lists need selection, editable content needs save/cancel.\nContract actions (if present): every useAction hook should be triggered by a visible UI element.\n\nOnly list MISSING interactive elements. Use 'fail' only for issues blocking core purpose.`,\n },\n {\n id: \"accessibility\",\n name: \"Accessible markup\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance:\n \"Add labels on form inputs, alt text on images, semantic HTML, and state ARIA (aria-checked/pressed/selected/expanded) on hand-rolled interactive controls.\",\n evalInstruction: `Evaluate ACCESSIBILITY: missing labels, alt text, semantic HTML, keyboard support, ARIA state.\n\nggui primitives bake in their own ARIA — see \"Primitive Accessibility\" in the Design System context above. NEVER flag a ggui primitive (Input/Select/TextArea, RadioGroup, Checkbox, Toggle, Progress, Slider, Spinner, Skeleton, Tabs, Accordion, Alert, Toast, Tooltip, Clickable, Icon) for a missing role / aria-* / label / keyboard handler — it is already there and not visible in the source you are reading.\n\nFlag ONLY real gaps: a raw div/span used as an interactive control; a hand-rolled control whose checked/selected/expanded/pressed state is conveyed only by styling (strikethrough, color, a check icon) with no \\`aria-checked\\` / \\`aria-pressed\\` / \\`aria-selected\\` / \\`aria-expanded\\`; an image with no alt text; an Input/Select/TextArea with no \\`label\\` prop; an icon-only Button with no aria-label; live/streaming data not wrapped in an aria-live region; inverted heading hierarchy.\n\nOnly list MISSING accessibility features. Use 'fail' only if it blocks delivery.`,\n },\n {\n id: \"layout\",\n name: \"Clean layout\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use proper spacing and visual grouping.\",\n evalInstruction: `Evaluate LAYOUT: Check spacing, alignment, visual grouping, and composition.\n\nOnly list ACTUAL layout problems. Use 'fail' only for fundamentally broken layouts.`,\n },\n {\n id: \"loading\",\n name: \"Loading/empty/error states\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Handle async data, empty collections, and error cases.\",\n evalInstruction: `Evaluate LOADING/EMPTY/ERROR STATES: Does the component handle async data and edge cases?\n\nContract-specific: useStream should handle pre-data state. clientCapabilities hooks may return undefined / permission-denied — defensive guards expected before threading values into JSX.\nProps-only components (no async, no streams, no client capabilities) do NOT need loading states — return pass.\n\nOnly list MISSING states.`,\n },\n {\n id: \"visual\",\n name: \"Design system consistency\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use design system tokens consistently.\",\n evalInstruction: `Evaluate VISUAL CONSISTENCY: Is the component using the design system correctly?\n\nFlag: hardcoded colors instead of CSS variables, numeric or raw-CSS-length spacing instead of the t-shirt scale, style objects bypassing design system.\nA t-shirt-scale spacing name (gap=\"md\", padding=\"lg\") IS correct token usage — never flag it.\nIntentional custom colors (status indicators) are acceptable when no semantic token fits.\n\nOnly list ACTUAL violations. Use 'fail' only for pervasive violations.`,\n },\n] as const;\n\n/**\n * `designMode: 'free'` overrides — ONLY the two criteria whose text\n * encodes the design vocabulary. `tokens` narrows to COLOR (the free arm\n * relaxes spacing / typography / radius / shadow to literals but keeps\n * brand-bearing color on the closed `--ggui-color-*` manifest, no\n * fallbacks); `visual` becomes arm-neutral (composition, hierarchy,\n * consistency, fit to canvas — no reward or penalty for design-system\n * usage). Every other criterion is shared verbatim between the modes.\n * Constraint alignment: what the free prompt says, the free evaluator\n * checks — and nothing more.\n */\nconst FREE_DESIGN_CRITERIA_OVERRIDES: readonly EvalCriterion[] = [\n {\n id: \"tokens\",\n name: \"Color tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Every color is a bare var(--ggui-color-*) from the token manifest — no hex, rgb()/hsl(), CSS named colors or literal fallbacks, in style props and <style> blocks alike. Spacing, typography, radius and shadow geometry may be literals.\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, CSS named colors, and literal fallbacks inside var(--ggui-*) references. Do NOT flag literal spacing, font sizes, radii or pixel values — they are allowed in this mode.\",\n },\n {\n id: \"visual\",\n name: \"Visual composition\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance:\n \"Compose deliberately: one clear focal point, consistent spacing rhythm, a coherent theme-token palette, a fit to the rendering canvas.\",\n evalInstruction: `Evaluate VISUAL COMPOSITION: Is the component composed deliberately for its canvas?\n\nJudge: visual hierarchy (one clear focal point, headings distinct from body text), consistent spacing rhythm and alignment, a coherent palette drawn from the theme tokens, fit to the canvas (fluid width, no fixed widths, nothing cramped or stretched).\nDo NOT reward or penalise the use of design-system primitives — raw HTML with inline CSS is a first-class choice here. Literal spacing / typography / radius values are fine.\n\nOnly list ACTUAL composition problems. Use 'fail' only for a fundamentally incoherent composition.`,\n },\n];\n\n/**\n * The criteria registry for a design mode. `constrained` IS `CRITERIA`\n * (same array, byte-identical summary); `free` swaps in the two\n * overrides above by id, preserving order.\n */\nexport function criteriaFor(designMode: DesignMode = \"constrained\"): readonly EvalCriterion[] {\n if (designMode === \"constrained\") return CRITERIA;\n return CRITERIA.map(\n (c) => FREE_DESIGN_CRITERIA_OVERRIDES.find((o) => o.id === c.id) ?? c,\n );\n}\n\n/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(\n priority: Priority,\n designMode: DesignMode = \"constrained\",\n): EvalCriterion[] {\n return criteriaFor(designMode).filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(\n id: string,\n designMode: DesignMode = \"constrained\",\n): EvalCriterion | undefined {\n return criteriaFor(designMode).find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(designMode: DesignMode = \"constrained\"): EvalCriterion[] {\n return criteriaFor(designMode).filter((c) => c.tier > 0);\n}\n\n/**\n * Build the coding agent's criteria summary from the single source of truth.\n * Grouped by priority for the P0→P1→P2 hierarchy.\n */\nexport function buildCodingCriteriaSummary(designMode: DesignMode = \"constrained\"): string {\n const lines: string[] = [\"## Priority (P0 first, then P1, then P2)\", \"\"];\n\n for (const priority of [\"P0\", \"P1\", \"P2\"] as Priority[]) {\n const label =\n priority === \"P0\"\n ? \"Must (compile + complete)\"\n : priority === \"P1\"\n ? \"Should (safety)\"\n : \"Nice (quality)\";\n const criteria = getCriteriaByPriority(priority, designMode);\n lines.push(`**${priority} — ${label}:**`);\n for (const c of criteria) {\n lines.push(`- ${c.codingGuidance}`);\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","// packages/ui-gen/src/check/run-tier0.ts\n//\n// Tier-0 deterministic CHECK orchestrator — the programmatic half of\n// the three-tier evaluation system:\n// Tier 0 — programmatic (deterministic, no LLM) ← this file\n// Tier 1 — LLM critical checks (functionality, crash)\n// Tier 2 — LLM quality checks (interactivity, accessibility, layout, etc.)\n//\n// Composes the deterministic helpers (`extract-wire-calls`,\n// `react-linter`, `contract-validation`, `type-checker`) from the\n// `@ggui-ai/ui-gen/check` subpath. The purely-typed evaluation surface\n// (`EvalTier` / `EvalOutcome` / `priorityForIssue` / …) is imported\n// directly from `@ggui-ai/ui-gen/evaluation` — its canonical home.\n\nimport ts from 'typescript';\nimport type { DataContract } from '@ggui-ai/protocol';\nimport { HOOK_NAME_RE, listContractGadgets } from '@ggui-ai/protocol';\nimport { consumedTokenManifest } from '@ggui-ai/design/themes';\nimport { DEFAULT_DESIGN_MODE, type DesignMode } from '../design-mode.js';\nimport { taughtTokenManifest } from '../taught-tokens.js';\nimport { validateAllContracts, type ContractIssue } from './contract-validation.js';\nimport { typecheck } from './type-checker.js';\nimport { lintReactHooks, type ReactLintDiagnostic } from './react-linter.js';\nimport { isAllowedImport, describeAllowedImports } from '../validation/allowed-imports.js';\nimport {\n checkWireImports,\n checkWirePreservation,\n type WireKind,\n} from './extract-wire-calls.js';\nimport {\n priorityForIssue,\n type EvalCategory,\n type EvalIssue,\n type EvalResult,\n} from '../evaluation/types-public.js';\n\n/**\n * Strip line + block comments from source, leaving all other text in\n * place. Uses the TS scanner so a `//` or block-comment sequence inside\n * a string / template / regex literal is NOT mistaken for a comment.\n * Comment characters are replaced with spaces (newlines kept) so byte\n * offsets and line numbers are unchanged.\n *\n * Used by regex-based CHECK rules that must not be satisfied by\n * commented-out code (e.g. `gadget_preservation`).\n */\nfunction stripComments(code: string): string {\n const scanner = ts.createScanner(\n ts.ScriptTarget.Latest,\n /* skipTrivia */ false,\n ts.LanguageVariant.JSX,\n code,\n );\n let out = '';\n for (\n let token = scanner.scan();\n token !== ts.SyntaxKind.EndOfFileToken;\n token = scanner.scan()\n ) {\n const text = scanner.getTokenText();\n out +=\n token === ts.SyntaxKind.SingleLineCommentTrivia ||\n token === ts.SyntaxKind.MultiLineCommentTrivia\n ? text.replace(/[^\\n]/g, ' ')\n : text;\n }\n return out;\n}\n\n/**\n * AST-precise detector for the unambiguous nested-interactive\n * double-wire pattern. See the call-site comment in `runTier0Checks` +\n * the `double-wired-action:certain` block for the rationale.\n *\n * The detector accepts a JSX element as the outer host when:\n * - tagName ∈ {Card, Box, Stack, Row}\n * - has `as={Clickable | Pressable}` (`Hoverable` doesn't fire click)\n * - has `onClick` (or `onPress`) whose handler calls one of the\n * known `useAction` bindings.\n *\n * Then it walks descendants of that outer element and matches an inner\n * interactive primitive when:\n * - tagName ∈ {Button, Checkbox, Input, Toggle, Slider, RadioGroup,\n * Select, TextArea, Link}\n * - has any of {onClick, onChange, onPress, onSelect} whose handler\n * calls the SAME useAction binding as the outer.\n *\n * Patterns it INTENTIONALLY does not catch:\n * - helper-function indirection (`const fire = () => toggle({id})`\n * in both handlers) — the AST sees two distinct callees, not the\n * same binding. The runtime dedup in `useAction` still catches the\n * symptom; the static-time catch is a teaching aid, not a safety\n * net.\n * - cross-component prop drilling — same reason.\n * - imperative DOM addEventListener — out of scope for JSX walking.\n */\nfunction detectCertainDoubleWiredActions(\n sourceCode: string,\n actionBindings: readonly string[],\n /**\n * `constrained` keeps the design-package tag sets above. `free`\n * retargets the SAME invariant (\"one useAction binding → exactly one\n * gesture surface\") at raw elements: the outer host is ANY JSX element\n * whose onClick/onPress calls a binding (`<div onClick>`, `<li>`,\n * `<tr>`, `<button>`, `<a>`, `[role=button]`, a design primitive…),\n * and the inner match is ANY descendant whose handler attribute calls\n * the same binding. Tag names stop mattering because in free mode a\n * raw element is a first-class gesture surface.\n */\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n): EvalIssue[] {\n const issues: EvalIssue[] = [];\n if (actionBindings.length === 0) return issues;\n const bindings = new Set(actionBindings);\n const anyElementIsInteractive = designMode === 'free';\n const TRAIT_HOST_TAGS = new Set(['Card', 'Box', 'Stack', 'Row']);\n const TRAITS_THAT_FIRE = new Set(['Clickable', 'Pressable']);\n const INTERACTIVE_DESCENDANTS = new Set([\n 'Button',\n 'Checkbox',\n 'Input',\n 'Toggle',\n 'Slider',\n 'RadioGroup',\n 'Select',\n 'TextArea',\n 'Link',\n ]);\n const HANDLER_ATTRS = ['onClick', 'onChange', 'onPress', 'onSelect'] as const;\n\n const sf = ts.createSourceFile(\n 'source.tsx',\n sourceCode,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n ts.ScriptKind.TSX,\n );\n\n function tagNameText(\n node: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n ): string | undefined {\n return ts.isIdentifier(node.tagName) ? node.tagName.text : undefined;\n }\n\n function attrExpression(\n node: ts.JsxOpeningElement | ts.JsxSelfClosingElement,\n attrName: string,\n ): ts.Expression | undefined {\n for (const attr of node.attributes.properties) {\n if (\n ts.isJsxAttribute(attr) &&\n ts.isIdentifier(attr.name) &&\n attr.name.text === attrName &&\n attr.initializer !== undefined &&\n ts.isJsxExpression(attr.initializer)\n ) {\n return attr.initializer.expression;\n }\n }\n return undefined;\n }\n\n function isTraitHostWithFiringAs(node: ts.JsxOpeningElement): boolean {\n const tag = tagNameText(node);\n if (tag === undefined) return false;\n // Free mode: every element with a handler is a gesture surface —\n // the callee check in `visit` decides whether it fires a binding.\n if (anyElementIsInteractive) return true;\n if (!TRAIT_HOST_TAGS.has(tag)) return false;\n const asExpr = attrExpression(node, 'as');\n return (\n asExpr !== undefined &&\n ts.isIdentifier(asExpr) &&\n TRAITS_THAT_FIRE.has(asExpr.text)\n );\n }\n\n // Best-effort callee extraction from event-handler expression shapes\n // the LLM actually emits. Forms covered:\n // {handler} → 'handler'\n // {() => callee(arg)} → 'callee'\n // {(e) => callee(e)} → 'callee'\n // {() => { callee(arg); }} → 'callee'\n // {function () { callee(arg); }} → 'callee'\n // Forms intentionally not covered: chained calls, conditional\n // expressions, calls inside if-branches. Those are rare in\n // LLM-generated JSX and would expand the FP surface.\n function extractCalleeName(\n expr: ts.Expression | undefined,\n ): string | undefined {\n if (expr === undefined) return undefined;\n if (ts.isIdentifier(expr)) return expr.text;\n if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {\n const body = expr.body;\n if (ts.isCallExpression(body) && ts.isIdentifier(body.expression)) {\n return body.expression.text;\n }\n if (ts.isBlock(body)) {\n for (const stmt of body.statements) {\n if (\n ts.isExpressionStatement(stmt) &&\n ts.isCallExpression(stmt.expression) &&\n ts.isIdentifier(stmt.expression.expression)\n ) {\n return stmt.expression.expression.text;\n }\n }\n }\n }\n return undefined;\n }\n\n function findMatchingInteractiveDescendant(\n outer: ts.JsxElement,\n expectedBinding: string,\n ): { tag: string; line: number } | undefined {\n let found: { tag: string; line: number } | undefined;\n function walk(node: ts.Node): void {\n if (found !== undefined) return;\n const opening = ts.isJsxElement(node)\n ? node.openingElement\n : ts.isJsxSelfClosingElement(node)\n ? node\n : undefined;\n if (opening !== undefined) {\n const tag = tagNameText(opening);\n if (\n tag !== undefined &&\n (anyElementIsInteractive || INTERACTIVE_DESCENDANTS.has(tag))\n ) {\n for (const attrName of HANDLER_ATTRS) {\n const callee = extractCalleeName(attrExpression(opening, attrName));\n if (callee === expectedBinding) {\n found = {\n tag,\n line:\n sf.getLineAndCharacterOfPosition(opening.getStart()).line + 1,\n };\n return;\n }\n }\n }\n }\n ts.forEachChild(node, walk);\n }\n // Walk only the outer element's children, not the outer itself.\n ts.forEachChild(outer, walk);\n return found;\n }\n\n function visit(node: ts.Node): void {\n if (ts.isJsxElement(node) && isTraitHostWithFiringAs(node.openingElement)) {\n const outerCallee =\n extractCalleeName(attrExpression(node.openingElement, 'onClick')) ??\n extractCalleeName(attrExpression(node.openingElement, 'onPress'));\n if (outerCallee !== undefined && bindings.has(outerCallee)) {\n const match = findMatchingInteractiveDescendant(node, outerCallee);\n if (match !== undefined) {\n const outerTag = tagNameText(node.openingElement);\n const outerLine =\n sf.getLineAndCharacterOfPosition(node.openingElement.getStart())\n .line + 1;\n const outerLabel = anyElementIsInteractive\n ? `<${outerTag}>`\n : `<${outerTag} as={...}>`;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'interactivity',\n subcategory: 'double-wired-action:certain',\n severity: 'critical',\n description:\n `Nested-interactive double-wire: outer ${outerLabel} at line ${outerLine} and inner <${match.tag}> at line ${match.line} both dispatch the same useAction binding '${outerCallee}'. ` +\n `One user click on the inner control fires its handler AND bubbles to the outer handler — '${outerCallee}' dispatches TWICE, the action runs back-to-back, and a toggle-style action silently reverts the user's change.`,\n fix: anyElementIsInteractive\n ? `Pick ONE gesture surface for '${outerCallee}': either remove the onClick from the outer <${outerTag}> and let the inner <${match.tag}> own the gesture, OR drop the inner <${match.tag}>'s handler and let the outer <${outerTag}> own it. Never wire both to the same useAction binding — stopPropagation is not a fix.`\n : `Pick ONE surface for the gesture: either drop \\`as={...}\\` + onClick on the outer <${outerTag}> and let the inner <${match.tag}> own the gesture, OR remove the inner <${match.tag}> and let the outer <${outerTag} as={...}> own it. Don't wire both to the same useAction binding.`,\n line: outerLine,\n });\n }\n }\n }\n ts.forEachChild(node, visit);\n }\n\n visit(sf);\n return issues;\n}\n\n/**\n * The consumed-token manifest as a closed set (ggui#613 residual 3 —\n * the generation-time closure leg of the #598 record). Every theme\n * MUST define exactly these names (the coverage gate); a generated\n * component may therefore consume ONLY these names. Anything else\n * is a reference no theme is obligated to define, and under the s4\n * fallback ban it paints nothing.\n */\nconst MANIFEST_TOKENS: ReadonlySet<string> = new Set(consumedTokenManifest);\n\n/**\n * Role names retired by ggui#987 that generated code still invents, each\n * with the manifest name that replaced it (ggui#1325). The self-check names\n * the successor, so the model does not spend a turn guessing another name.\n */\nconst RETIRED_TOKEN_SUCCESSORS: ReadonlyMap<string, string> = new Map([\n ['--ggui-color-surface', '--ggui-color-container'],\n ['--ggui-color-onSurface', '--ggui-color-onContainer'],\n ['--ggui-color-surfaceVariant', '--ggui-color-sunken'],\n ['--ggui-color-onSurfaceVariant', '--ggui-color-onSunken'],\n]);\n\n/**\n * The manifest names nearest an invented one (ggui#1325): a retired role's\n * successor when there is one; otherwise the names sharing the invented\n * name's longest family prefix at a segment boundary\n * (`--ggui-motion-duration-normal` → fast, base, slow); otherwise the names\n * sharing any of its segments of four letters or more\n * (`--ggui-duration-slow` → the motion durations). Empty when nothing is\n * near, so the hint falls back to the manifest's general shape. A hint\n * teaches, so it draws only on the names the model may be taught\n * (`taughtTokenManifest`); the closed-set check above admits the full manifest.\n */\nexport function suggestManifestTokens(name: string): readonly string[] {\n const successor = RETIRED_TOKEN_SUCCESSORS.get(name);\n if (successor !== undefined) return [successor];\n // Family prefixes at the name's own segment boundaries, longest first: for\n // `--ggui-motion-duration-normal` that is `--ggui-motion-duration-`, then\n // `--ggui-motion-`; an empty-suffix name such as `--ggui-color-` (the model\n // stopped mid-name) is its own longest prefix, so it gets the colour family.\n const segments = name.split('-').filter((segment) => segment.length > 0);\n const own = name.endsWith('-') ? segments.length : segments.length - 1;\n for (let n = own; n >= 2; n--) {\n const prefix = `--${segments.slice(0, n).join('-')}-`;\n const family = taughtTokenManifest.filter((token) => token.startsWith(prefix));\n if (family.length > 0) return wordHitsFirst(name, rolesFirst(family));\n }\n const words = new Set(\n segments\n .slice(1)\n .filter((segment) => segment.length >= 4)\n .map((segment) => segment.toLowerCase()),\n );\n return rolesFirst(\n taughtTokenManifest.filter((token) =>\n token.split('-').some((segment) => words.has(segment.toLowerCase())),\n ),\n );\n}\n\n/**\n * Names that carry the invented name's last word lead the list: `--ggui-color-inverse` names `inverseLink` and\n * `inverseOutline` before the rest of the colour family, since those are what the model was reaching for. The word is\n * the last segment when it has four letters or more; shorter or empty suffixes leave the order alone.\n */\nfunction wordHitsFirst(name: string, family: readonly string[]): readonly string[] {\n const word = name.slice(name.lastIndexOf('-') + 1).toLowerCase();\n if (word.length < 4) return family;\n const hit = (token: string): boolean => token.slice(token.lastIndexOf('-') + 1).toLowerCase().includes(word);\n return [...family.filter(hit), ...family.filter((token) => !hit(token))];\n}\n\n/** Role names (a non-numeric last segment) before ramp steps, so the taught vocabulary leads a long family. */\nfunction rolesFirst(tokens: readonly string[]): readonly string[] {\n const isRole = (token: string): boolean => !/^\\d+$/.test(token.slice(token.lastIndexOf('-') + 1));\n return [...tokens.filter(isRole), ...tokens.filter((token) => !isRole(token))];\n}\n\n/** The sentence that names the real token first (ggui#1325); empty when nothing in the manifest is near. */\nfunction offManifestHint(name: string): string {\n const successor = RETIRED_TOKEN_SUCCESSORS.get(name);\n if (successor !== undefined) {\n return `\"${name}\" was retired (ggui#987); the current name is var(${successor}). `;\n }\n const near = suggestManifestTokens(name);\n if (near.length === 0) return '';\n const shown = near.slice(0, 8).map((token) => `var(${token})`).join(', ');\n const more = near.length > 8 ? ` (and ${near.length - 8} more in that family)` : '';\n return `Nearest names in the manifest: ${shown}${more}. `;\n}\nconst TOKEN_REF_RE = /var\\(\\s*(--ggui-[a-zA-Z0-9-]+)/g;\n\n/** Map wire kind to the matching `@ggui-ai/wire` hook name. */\nconst HOOK_NAME_FOR: Readonly<Record<WireKind, string>> = {\n action: 'useAction',\n stream: 'useStream',\n context: 'useGguiContext',\n};\n\n/**\n * Map wire kind to the contract field the agent must declare on the\n * `contract` input to `ggui_render` (post-Phase-2 flat handshake input)\n * to make the `useX('<name>')` call legal.\n *\n * Drives the remediation message on the `wire_undeclared` fail.\n * Telling the LLM \"declare it on contextSpec.<slotName>\" with the\n * JSON-Schema starter is concretely actionable; \"declare a contract\"\n * alone is not.\n */\nconst CONTRACT_FIELD_FOR: Readonly<Record<WireKind, string>> = {\n action: 'actionSpec',\n stream: 'streamSpec',\n context: 'contextSpec',\n};\n\n// =============================================================================\n// Tier 0: Programmatic Hard Checks\n// =============================================================================\n\n/**\n * Whether comment-free `source` imports the named gadget `exportName`\n * from `pkg` — `import { …, exportName, … } from '<pkg>'` (the source\n * name, left of any `as`). Kind-agnostic — hook and component exports\n * are both direct-imported the same way. The `gadget_preservation`\n * anchor: generated code direct-imports each gadget export, and the\n * import is what the iframe rewriter binds to the per-package runtime\n * shim.\n */\nfunction isGadgetExportImported(\n source: string,\n pkg: string,\n exportName: string,\n): boolean {\n const esc = pkg.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const re = new RegExp(\n `import\\\\s*(?:[A-Za-z_$][\\\\w$]*\\\\s*,\\\\s*)?\\\\{([^}]*)\\\\}\\\\s*from\\\\s*['\"]${esc}['\"]`,\n 'g',\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(source)) !== null) {\n for (const raw of m[1].split(',')) {\n if (raw.trim().split(/\\s+as\\s+/)[0]?.trim() === exportName) return true;\n }\n }\n return false;\n}\n\n/**\n * AST-precise detector for the compiles-but-renders-nothing class: the\n * default-exported component's body never returns a tree.\n *\n * The boilerplate HANDS the model the wrapper — `base.tsx.tmpl` and\n * `base-free.tsx.tmpl` both emit `return (` … `);` around `{{LAYOUT}}`.\n * A model rewriting the root block can delete those two lines with it,\n * leaving the JSX as a bare expression statement. That is legal TSX: it\n * parses, esbuild compiles it, `typecheck()` passes it, and the\n * component renders a blank frame. Seen once in twenty takes of the\n * ggui#1113 A/B (`xs-chat-card`, run 2 — the judge spent a screenshot\n * and an LLM call to report \"completely blank\").\n *\n * `compile/default-export` already guards the scaffold's\n * `export default function` line and `types/props-interface` its\n * `interface Props` line. The `return (` was the third scaffold line\n * with nothing watching it.\n *\n * Conservative by construction — it reports ONLY when it positively\n * identified a block-bodied default-export component:\n * - a concise arrow body (`export default () => <X/>`) returns by\n * construction → silent\n * - `export default memo(Component)` or any other expression it\n * cannot resolve to a function → silent\n * - a `return` inside a nested helper is not the component's own (the\n * walk stops at every nested function boundary), but ONE own-level\n * `return <value>` anywhere — an early `return null` included —\n * satisfies it.\n *\n * Returns `null` when the component returns (or could not be\n * identified), else the 1-based line of the first bare JSX expression\n * statement in its body — the line the fix belongs on — or `undefined`\n * when the body has no JSX statement to point at either.\n */\nfunction detectComponentNeverReturns(\n sourceCode: string,\n): { jsxStatementLine: number | undefined } | null {\n const sf = ts.createSourceFile(\n 'source.tsx',\n sourceCode,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n ts.ScriptKind.TSX,\n );\n\n const isFunctionLike = (n: ts.Node): boolean =>\n ts.isFunctionDeclaration(n) ||\n ts.isFunctionExpression(n) ||\n ts.isArrowFunction(n) ||\n ts.isMethodDeclaration(n) ||\n ts.isClassDeclaration(n) ||\n ts.isClassExpression(n);\n\n /** The top-level declaration `name` binds to, when it is a function. */\n function resolveTopLevel(\n name: string,\n ): ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction | undefined {\n for (const st of sf.statements) {\n if (ts.isFunctionDeclaration(st) && st.name?.text === name) return st;\n if (ts.isVariableStatement(st)) {\n for (const decl of st.declarationList.declarations) {\n if (\n ts.isIdentifier(decl.name) &&\n decl.name.text === name &&\n decl.initializer !== undefined &&\n (ts.isArrowFunction(decl.initializer) || ts.isFunctionExpression(decl.initializer))\n ) {\n return decl.initializer;\n }\n }\n }\n }\n return undefined;\n }\n\n let component:\n | ts.FunctionDeclaration\n | ts.FunctionExpression\n | ts.ArrowFunction\n | undefined;\n for (const st of sf.statements) {\n if (\n ts.isFunctionDeclaration(st) &&\n st.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)\n ) {\n component = st;\n break;\n }\n if (ts.isExportAssignment(st) && st.isExportEquals !== true) {\n const expr = st.expression;\n if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) component = expr;\n else if (ts.isIdentifier(expr)) component = resolveTopLevel(expr.text);\n break;\n }\n }\n // No default export at all, or one this detector cannot resolve to a\n // function — `compile/default-export` owns the first case and the\n // second is not ours to guess at.\n if (component === undefined) return null;\n\n const body = component.body;\n // A concise arrow body IS the returned value.\n if (body === undefined || !ts.isBlock(body)) return null;\n\n let returnsValue = false;\n let jsxStatementLine: number | undefined;\n const visit = (node: ts.Node): void => {\n if (returnsValue) return;\n if (ts.isReturnStatement(node)) {\n if (node.expression !== undefined) returnsValue = true;\n return;\n }\n if (\n jsxStatementLine === undefined &&\n ts.isExpressionStatement(node) &&\n (ts.isJsxElement(node.expression) ||\n ts.isJsxFragment(node.expression) ||\n ts.isJsxSelfClosingElement(node.expression))\n ) {\n jsxStatementLine = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n }\n node.forEachChild((child) => {\n // A helper component's own `return` is not this component's.\n if (!isFunctionLike(child)) visit(child);\n });\n };\n for (const st of body.statements) if (!isFunctionLike(st)) visit(st);\n\n return returnsValue ? null : { jsxStatementLine };\n}\n\n/**\n * Run all tier 0 (deterministic, no-LLM) checks against component source.\n *\n * Wraps the same logic as runSelfChecks (adapters/tools.ts) but emits EvalIssue[].\n * Also runs contract validation when contract are provided.\n */\n/** The kit controls whose boundary the design system draws (ggui#1697). */\nconst KIT_CONTROLS = ['Button', 'Input', 'Select', 'TextArea', 'Checkbox', 'RadioGroup', 'Toggle', 'SearchField'] as const;\n\n/**\n * Opening tags of kit controls, read brace- and quote-aware: an attribute like `onClick={() => x}` holds a `>` that a\n * plain `[^>]*` pattern stops at, which would hide every attribute after it.\n */\nfunction kitControlTags(source: string): { name: string; attrs: string; line: number }[] {\n const out: { name: string; attrs: string; line: number }[] = [];\n const open = new RegExp(`<(${KIT_CONTROLS.join('|')})\\\\b`, 'g');\n for (const m of source.matchAll(open)) {\n const start = (m.index ?? 0) + m[0].length;\n let depth = 0;\n let quote: string | null = null;\n let i = start;\n for (; i < source.length; i += 1) {\n const c = source[i];\n if (quote !== null) {\n if (c === quote && source[i - 1] !== '\\\\') quote = null;\n } else if (c === '\"' || c === \"'\" || c === '`') quote = c;\n else if (c === '{') depth += 1;\n else if (c === '}') depth -= 1;\n else if (c === '>' && depth === 0) break;\n }\n out.push({ name: m[1] ?? '', attrs: source.slice(start, i), line: source.slice(0, m.index ?? 0).split('\\n').length });\n }\n return out;\n}\n\n/** A border key (not a radius) in the tag's inline style, or in a same-file object its `style={name}` points at. */\nfunction inlineBorderKey(attrs: string, source: string): string | null {\n const BORDER = /\\b(border(?:Top|Right|Bottom|Left)?(?:Color|Width|Style)?)\\s*:/;\n const style = attrs.match(/\\bstyle=\\{\\{([\\s\\S]*)\\}\\}/);\n if (style !== null) {\n const hit = (style[1] ?? '').match(BORDER);\n if (hit !== null) return hit[1] ?? null;\n }\n const named = attrs.match(/\\bstyle=\\{\\s*([A-Za-z_$][\\w$]*)\\s*\\}/);\n if (named === null) return null;\n const decl = source.match(new RegExp(`\\\\b(?:const|let)\\\\s+${named[1]}\\\\b[^=]*=\\\\s*\\\\{([^{}]*)\\\\}`));\n const hit = decl !== null ? (decl[1] ?? '').match(BORDER) : null;\n return hit !== null ? hit[1] ?? null : null;\n}\n\nexport async function runTier0Checks(\n sourceCode: string,\n contract?: DataContract,\n buildErrors?: string[],\n /**\n * A `package -> .d.ts content` map for third-party gadget wrappers.\n * Threaded verbatim into `typecheck()` so the in-memory TS sandbox\n * overlays each wrapper `.d.ts` at `node_modules/<package>/index.d.ts`\n * — a generated direct import `import { useX } from '<package>'`\n * resolves against the real declaration (strict option/return\n * narrowing). Standard-library-only callers omit it.\n */\n gadgetTypes?: Readonly<Record<string, string>>,\n /**\n * Which triad produced the source. `constrained` (default) runs every\n * leg exactly as before. `free` gates OFF the design-VOCABULARY legs —\n * `raw-spacing`, `raw-pixels`, `numeric-spacing-prop`, the\n * `stack-row-*` prop checks and `clickable-wrapper` — because raw\n * elements, inline CSS and literal spacing are first-class there. It\n * KEEPS every contract leg: `hex-color`, `hardcoded-color-fn`,\n * `named-color`, `token-fallback`, `off-manifest-token`,\n * `asset-color-pair` (color stays on the closed token manifest),\n * imports, security, Props / default-export, wire_* and gadget checks,\n * and the double-wired-action detector (retargeted at raw elements).\n */\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n): Promise<EvalIssue[]> {\n const issues: EvalIssue[] = [];\n const lines = sourceCode.split('\\n');\n // Design-vocabulary legs fire only when the prompt taught the\n // vocabulary — see `designMode` above.\n const enforceDesignVocabulary = designMode === 'constrained';\n\n // ── Compile check ─────────────────────────────────────────\n //\n // Fail only when the caller ATTEMPTED compile and captured errors.\n // Absent `buildErrors` means the caller hasn't run esbuild at all\n // (e.g. OSS `createUiGenerator` which is sometimes wrapped by\n // `withBrowserCompile` and sometimes not); degrade gracefully —\n // downstream checks (security, forbidden imports, wire-import\n // presence, react-linter, Props-interface, default-export) still\n // fire on sourceCode alone.\n if (buildErrors && buildErrors.length > 0) {\n const errorDetail = buildErrors\n .map((e) => {\n // Extract key info from esbuild error (e.g., line number, error type)\n const match = e.match(/<stdin>:(\\d+):\\d+: ERROR: (.+)/);\n return match ? `Line ${match[1]}: ${match[2]}` : e.slice(0, 200);\n })\n .join('\\n');\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'compile',\n subcategory: 'build-error',\n severity: 'critical',\n description: `Component failed to compile:\\n${errorDetail}`,\n fix: 'Fix the JSX/TypeScript syntax errors listed above',\n });\n }\n\n // ── assetColor allow-list ─────────────────────────────────\n //\n // T-4: Box gains a typed brand-color escape pair —\n // <Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">\n // The static hex / rgba checks below allow a hex/rgba/hsl whose\n // `JSXAttribute` parent is `assetColor`, but only when a sibling\n // `assetSemantic` attribute carries a non-empty string value on the\n // same JSX opening tag. Both pieces are required: an `assetColor`\n // alone, or `assetSemantic=\"\"`, fails.\n //\n // Implementation: collect the (1-based) line numbers of every line\n // whose JSX opening tag legitimately satisfies this pair. The\n // hex/colorFn/named-color checks below skip emitting a failure\n // when the matching line is in this allow-list.\n const assetEscapedLines = new Set<number>();\n // Match each JSX opening tag (allowing multiline attribute lists).\n // The regex captures the tag's attribute span; we then check it for\n // the required `assetColor` + non-empty `assetSemantic` pair, and\n // record every source line that the tag spans.\n const jsxOpenRegex = /<([A-Z][A-Za-z0-9]*)\\b([^>]*)>/gs;\n for (const match of sourceCode.matchAll(jsxOpenRegex)) {\n const tagAttrs = match[2];\n const assetColorAttr = tagAttrs.match(/\\bassetColor\\s*=\\s*(?:[\"']([^\"']*)[\"']|\\{[^}]*\\})/);\n if (!assetColorAttr) continue;\n const assetSemanticAttr = tagAttrs.match(/\\bassetSemantic\\s*=\\s*[\"']([^\"']*)[\"']/);\n const startLine = sourceCode.slice(0, match.index ?? 0).split('\\n').length;\n const tagLineCount = match[0].split('\\n').length;\n // Both attributes must be present, AND assetSemantic must be a\n // non-empty string literal. A `{expr}` value for assetSemantic is\n // treated as not-statically-verifiable; the escape is opt-in\n // documentation, not a runtime expression. Failing pairs emit a\n // dedicated `tokens:asset-color-pair` failure AND do NOT enter\n // the allow-list — so the embedded hex still fires its own\n // `tokens:hex-color` failure (two issues, one per axis).\n if (!assetSemanticAttr || assetSemanticAttr[1].length === 0) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'asset-color-pair',\n severity: 'critical',\n description:\n 'Box `assetColor` set without a non-empty `assetSemantic` — the typed brand-color escape requires both. ' +\n '`assetSemantic` is a human-readable label that documents why this color bypasses the theme.',\n fix:\n 'Pair the `assetColor` with a non-empty `assetSemantic` literal, e.g. ' +\n '`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">`. Reach for `surface=\"...\"` first ' +\n 'whenever the color SHOULD track the operator\\'s theme.',\n line: startLine,\n });\n continue;\n }\n for (let l = 0; l < tagLineCount; l++) {\n assetEscapedLines.add(startLine + l);\n }\n }\n\n // Gadget packages the contract declares are import-\n // allowlisted. Generated code direct-imports gadget exports from\n // their package. `clientCapabilities.gadgets` is\n // package-keyed, so the map's own keys ARE the permitted import\n // sources, alongside the STDLIB `@ggui-ai/gadgets`.\n const allowedGadgetPackages = new Set<string>(\n Object.keys(contract?.clientCapabilities?.gadgets ?? {}),\n );\n\n // ── Line-by-line checks ───────────────────────────────────\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const lineNum = i + 1;\n\n // Security: eval()\n if (/\\beval\\s*\\(/.test(line)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'security',\n subcategory: 'eval',\n severity: 'critical',\n description: 'eval() is forbidden',\n fix: 'Remove eval() call entirely',\n line: lineNum,\n });\n }\n\n // Security: fetch()\n if (/\\bfetch\\s*\\(/.test(line)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'security',\n subcategory: 'fetch',\n severity: 'critical',\n description: 'fetch() is forbidden — use props for data',\n fix: 'Remove fetch() and pass data via props',\n line: lineNum,\n });\n }\n\n // Forbidden imports (skip commented-out imports)\n const trimmedLine = line.trim();\n if (trimmedLine.startsWith('//') || trimmedLine.startsWith('*')) continue;\n const importMatch = trimmedLine.match(/import\\s+.*from\\s+['\"]([^'\"]+)['\"]/);\n if (importMatch) {\n const pkg = importMatch[1];\n // Allowlist mirrors `validation/component-detailed.ts` ALLOWED_IMPORTS —\n // these two must stay in sync. Generated code direct-imports\n // gadget exports, so every gadget package the contract declares\n // (`clientCapabilities.gadgets[*].package`) is allowlisted alongside\n // the STDLIB `@ggui-ai/gadgets`. Rejecting a declared gadget package\n // would contradict the `gadget_preservation` check (which REQUIRES\n // the direct import).\n if (!isAllowedImport(pkg, allowedGadgetPackages)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: 'disallowed-package',\n severity: 'critical',\n description: `Import from \"${pkg}\" is not allowed`,\n fix: `Only import from: ${describeAllowedImports()}`,\n line: lineNum,\n });\n }\n }\n\n // Hardcoded hex colors (not inside CSS variable fallbacks).\n //\n // Empirical (warn → fail rationale): when the\n // operator's prompt evoked a strong aesthetic (\"garden / living\n // ecosystem\"), the LLM emitted hex literals (`#B8FF3A` lime,\n // `#0a0a0a` near-black) inline on `color`/`background` style\n // overrides — completely overriding the operator's selected theme.\n // The warn-level rule was advisory and got ignored. As a `fail`\n // it forces the LLM to remediate before passing self-check.\n //\n // Generation contract this enforces (per the contract bar): the\n // LLM describes structure + intent; the theme + primitive variants\n // describe visuals. Hardcoded hex is a contract violation. The\n // existing `var(--ggui-*, #fallback)` exception keeps legit token\n // patterns flowing untouched. Asset-fixed brand colors get a\n // typed escape on Box (`assetColor` + `assetSemantic`) — see\n // T-4 follow-up.\n // Literal fallback inside ANY token reference (ggui#598 slice 4\n // origin-kill, generalized by ggui#613 residual 4 from color to\n // every token): the runtime injects every token — colors, spacing,\n // typography, radius, shadows — so a literal fallback can only\n // ever paint default-brand pixels under a failed injection, which\n // must be visible (unset) rather than silently default. The old\n // hex-only exemption plus a remediation that suggested\n // `var(--x, ${hex})` actively taught the model to launder invented\n // values INTO fallbacks (adversarial-cycle find). A token-to-token\n // fallback (`var(--a, var(--b))`) is not a literal — it stays on\n // the manifest check alone.\n const literalFallbackMatch = line.match(\n /var\\(\\s*(--ggui-[a-zA-Z0-9-]+)\\s*,\\s*([^)]+)\\)/,\n );\n const literalFallback =\n literalFallbackMatch !== null &&\n !literalFallbackMatch[2]!.trim().startsWith('var(')\n ? { token: literalFallbackMatch[1]!, literal: literalFallbackMatch[2]!.trim() }\n : null;\n if (literalFallback !== null && !assetEscapedLines.has(lineNum)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'token-fallback',\n severity: 'critical',\n description: `Literal fallback \"${literalFallback.literal}\" inside a token reference — the runtime injects every token, and the fallback paints the wrong value exactly when the theme matters most.`,\n fix: `Drop the fallback: write var(${literalFallback.token}) bare. If the token might not exist, that is a vocabulary problem to fix by choosing a token from the design-system docs, never by a literal.`,\n line: lineNum,\n });\n }\n\n const hexMatch = line.match(/#[0-9a-fA-F]{3,8}\\b/);\n if (hexMatch && !assetEscapedLines.has(lineNum)) {\n // A hex that lives inside a token fallback is already reported\n // above as `token-fallback` — don't double-report it as\n // `hex-color`.\n if (literalFallback !== null && literalFallback.literal.includes(hexMatch[0])) {\n // reported above\n } else if (!line.includes('// fallback')) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'hex-color',\n severity: 'critical',\n description: `Hardcoded color \"${hexMatch[0]}\" breaks theme switching — use design tokens.`,\n fix: `Replace with a primitive variant (Button variant=\"primary\"|Badge variant=\"success\"|...) OR a bare token reference like var(--ggui-color-primary-500) — never a literal fallback. Hardcoded colors mean the operator's theme has no effect on this surface.`,\n line: lineNum,\n });\n }\n }\n\n // Hardcoded rgba()/hsl() color functions — same reasoning as above.\n // Treated as `fail` for symmetry — a hardcoded `rgba(184, 255, 58, 1)`\n // is functionally identical to `#B8FF3A` from a theme-override\n // standpoint.\n const colorFnMatch = line.match(/\\b(rgba?|hsla?)\\s*\\(/);\n if (\n colorFnMatch &&\n !line.includes('var(--ggui-') &&\n !line.includes('// fallback') &&\n !line.includes('$value') &&\n !assetEscapedLines.has(lineNum)\n ) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'hardcoded-color-fn',\n severity: 'critical',\n description: `Hardcoded ${colorFnMatch[1]}() breaks theme switching — use design tokens.`,\n fix: 'Replace with a primitive variant OR a layering role: var(--ggui-color-container), var(--ggui-color-onContainer), var(--ggui-color-outline), etc.',\n line: lineNum,\n });\n }\n\n // Off-manifest token references (ggui#613 residual 3): a\n // `var(--ggui-*)` whose name is outside the consumed-token\n // manifest. The manifest is the closed vocabulary the prompt\n // teaches AND the set every theme must define — so a name outside\n // it is invented, and with literal fallbacks banned it renders\n // UNSET. Fail, like the other token-contract violations; one issue\n // per distinct name per line.\n const offManifest = new Set<string>();\n for (const m of line.matchAll(TOKEN_REF_RE)) {\n const name = m[1]!;\n if (!MANIFEST_TOKENS.has(name)) offManifest.add(name);\n }\n for (const name of offManifest) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'off-manifest-token',\n severity: 'critical',\n description: `Token \"${name}\" is not in the design system's token manifest — no theme defines it, so it renders unset.`,\n fix: `${offManifestHint(name)}Choose a token that exists: the closed vocabulary is the manifest the design-system docs list (colors: var(--ggui-color-primary-500), var(--ggui-color-onContainer), …; spacing: var(--ggui-spacing-4); type: var(--ggui-font-size-sm)). Never invent a name and never add a literal fallback.`,\n line: lineNum,\n });\n }\n\n // Raw CSS length on a spacing / radius prop — bypasses the design\n // scale. Same reasoning as the hardcoded-color checks above: a\n // literal `gap=\"8px\"` defeats the theme's spacing scale exactly as\n // `#fff` defeats its colors. Only the STRING-literal form fails;\n // the numeric escape (`gap={12}`) is untouched, so a genuine\n // off-scale pixel value still has a path.\n const rawSpacingMatch = enforceDesignVocabulary\n ? line.match(\n /\\b(gap|padding|paddingX|paddingY|margin|radius)\\s*=\\s*[\"'][\\d.]+(?:px|rem|em)[\"']/,\n )\n : null;\n if (rawSpacingMatch) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'raw-spacing',\n severity: 'critical',\n description: `\\`${rawSpacingMatch[1]}\\` uses a raw CSS length — bypasses the design spacing/radius scale.`,\n fix: `Use a scale name: ${rawSpacingMatch[1]}=\"xs|sm|md|lg|xl\" (spacing also has none|2xl; radius none|sm|md|lg|xl). For an exact off-scale pixel value pass a number — ${rawSpacingMatch[1]}={12}.`,\n line: lineNum,\n });\n }\n\n // CSS named-color literals on color/background sinks. Closes the\n // residual escape after the hex/rgb checks: `style={{ color:\n // 'lime' }}` or `style={{ background: 'royalblue' }}`. The hex\n // check doesn't match these because they're keyword identifiers,\n // not `#`-prefixed hex. CSS-spec named colors are a finite set;\n // we match the obvious ones the LLM reaches for.\n //\n // Allowed keywords (no fail): `inherit`, `currentColor`,\n // `transparent`, `unset`, `initial`, `revert`, `none`. These have\n // legitimate semantic uses (inherit for nested rendering, none\n // for explicit empty fill).\n //\n // Out-of-scope by design: token-name strings like `color:\n // 'primary'` — those would render as invalid CSS and a separate\n // self-check (the existing prop-value validator) catches them.\n const namedColorMatch = line.match(\n /(?:^|[^a-zA-Z-])(?:color|background|backgroundColor|borderColor)\\s*:\\s*['\"]([a-z][a-zA-Z]+)['\"]/,\n );\n if (namedColorMatch) {\n const named = namedColorMatch[1].toLowerCase();\n const allowed = new Set([\n 'inherit', 'currentcolor', 'transparent',\n 'unset', 'initial', 'revert', 'none',\n ]);\n // Heuristic for the named-color lexicon. Covers every CSS-spec\n // color the LLM has empirically reached for; new keywords can\n // be added as they surface in benchmarks. Token-name strings\n // (`'primary'`) bypass this check because they're not in the\n // lexicon — the prop-value validator catches them as invalid\n // enum values.\n const namedCssColors = new Set([\n 'red', 'green', 'blue', 'yellow', 'orange', 'purple', 'pink',\n 'cyan', 'magenta', 'lime', 'teal', 'navy', 'maroon', 'olive',\n 'aqua', 'fuchsia', 'silver', 'gray', 'grey', 'white', 'black',\n 'brown', 'gold', 'indigo', 'violet', 'crimson', 'tomato',\n 'coral', 'salmon', 'orchid', 'plum', 'tan', 'khaki', 'beige',\n 'ivory', 'lavender', 'mint', 'turquoise', 'azure',\n 'royalblue', 'darkblue', 'lightblue', 'skyblue', 'steelblue',\n 'darkred', 'lightgreen', 'darkgreen', 'forestgreen',\n 'darkorange', 'lightgray', 'lightgrey', 'darkgray', 'darkgrey',\n 'hotpink', 'deeppink', 'lightpink', 'lightyellow',\n ]);\n if (!allowed.has(named) && namedCssColors.has(named)) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'tokens',\n subcategory: 'named-color',\n severity: 'critical',\n description: `Hardcoded CSS named color \"${named}\" breaks theme switching — use design tokens.`,\n fix: `Replace with a typed slot (Text tone=\"muted\" / Box surface=\"accent\" / Badge variant=\"success\") OR a semantic token: var(--ggui-color-onSunken), var(--ggui-color-primary-500), etc. The keyword \"${named}\" maps to a fixed RGB; the operator's theme has no effect on it.`,\n line: lineNum,\n });\n }\n }\n\n // Raw pixel values in spacing CSS properties\n const pxMatch = enforceDesignVocabulary\n ? line.match(/(?:padding|margin|gap|borderRadius)\\s*:\\s*['\"]?\\d+px/)\n : null;\n if (pxMatch && !line.includes('var(--ggui-')) {\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'tokens',\n subcategory: 'raw-pixels',\n description: 'Raw pixel value in spacing — must use design tokens',\n fix: 'Replace with a bare var(--ggui-spacing-*) token — no literal fallback (the runtime injects every token) — or the scale name on the primitive prop (gap=\"md\", padding=\"lg\")',\n line: lineNum,\n });\n }\n\n // Numeric spacing props on components (e.g., padding={24}, gap={8})\n // These bypass the design system — should use var(--ggui-spacing-*)\n const numericSpacingMatch = enforceDesignVocabulary\n ? line.match(/\\b(padding|paddingX|paddingY|gap|margin)\\s*=\\s*\\{?\\s*(\\d+)\\s*\\}?/)\n : null;\n if (numericSpacingMatch && !line.includes('var(--ggui-')) {\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'tokens',\n subcategory: 'numeric-spacing-prop',\n description: `Numeric spacing prop ${numericSpacingMatch[1]}={${numericSpacingMatch[2]}} — use design tokens instead`,\n fix: `Replace with ${numericSpacingMatch[1]}=\"var(--ggui-spacing-*)\"`,\n line: lineNum,\n });\n }\n }\n\n // ── Clickable trait check — onClick on a structural primitive needs as={Clickable} ──\n // Only the four trait-host primitives (typed `WithTrait<…>`) accept\n // `as={Clickable}`. Text/Heading/Badge/Avatar/Image are NOT hosts, so an\n // onClick on them is a plain type error the type-checker catches — don't\n // steer those toward `as={Clickable}` (it won't compile on them).\n const clickablePattern = /<(?:Card|Box|Stack|Row)\\s[^>]*onClick/;\n for (let i = 0; enforceDesignVocabulary && i < lines.length; i++) {\n if (clickablePattern.test(lines[i]) && !lines[i].includes('as={Clickable}') && !lines[i].includes('as={Pressable}')) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: 'clickable-wrapper',\n description: `onClick on a structural primitive without as={Clickable} — the bare primitive has no click or keyboard handling`,\n fix: `Add as={Clickable} to the element, e.g., <Card as={Clickable} onClick={handler}>`,\n line: i + 1,\n });\n }\n }\n\n // ── Double-wired action check (warn — broad regex) ──────────\n // A useAction callback dispatched from 2+ call sites fires the action\n // more than once per gesture when an interactive element nests inside\n // another (the inner gesture bubbles to the outer handler). Captured\n // in scenario-07: a `Card as={Clickable} onClick` row containing a\n // `Checkbox onChange`, both calling the same action → double-toggle.\n //\n // Binding extraction. The constrained regex is the pre-`designMode`\n // one, kept verbatim: it matches `useAction(` only, so a binding\n // declared with the generic the boilerplate itself emits —\n // `useAction<ActionXPayload>('x')` — is NOT collected there (a\n // pre-existing gap, left in place because the constrained gate must\n // stay byte-identical for the A/B; collapse the two regexes once that\n // pin is lifted). `free` mode accepts the optional generic so the\n // one-gesture-surface invariant actually fires on boilerplate-shaped\n // hook lines.\n const bindingRe =\n designMode === 'free'\n ? /(?:const|let)\\s+(\\w+)\\s*=\\s*useAction\\s*(?:<[^>]*>)?\\s*\\(/g\n : /(?:const|let)\\s+(\\w+)\\s*=\\s*useAction\\s*\\(/g;\n const actionBindings = [...sourceCode.matchAll(bindingRe)]\n .map((m) => m[1])\n .filter((name): name is string => typeof name === 'string');\n for (const binding of actionBindings) {\n const callSites = (\n sourceCode.match(new RegExp(`\\\\b${binding}\\\\s*\\\\(`, 'g')) ?? []\n ).length;\n if (callSites >= 2) {\n // Kept at WARN — too many legit patterns (confirm/cancel, branched\n // dispatch, sibling buttons in a list) match this generic shape. The\n // structural correctness backstop lives at runtime in `useAction`'s\n // task-scoped dedup; this check is a quality nudge for the LLM, not a\n // load-bearing safety gate. See `docs/principles/no-silent-block.md`\n // — three-pattern FP test fails for this detector → severity = warn.\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'interactivity',\n subcategory: 'double-wired-action',\n description: `Action '${binding}' is dispatched from ${callSites} call sites — if an interactive element nests inside another, one gesture fires the action twice (the inner gesture bubbles to the outer handler).`,\n fix: `Wire each useAction callback to exactly ONE interactive surface; never nest interactive elements (e.g. a Checkbox inside a Card as={Clickable}).`,\n });\n }\n }\n\n // ── Double-wired action check (fail — narrow AST) ────────────\n // Precise detector for the unambiguous shape: an outer trait-host JSX\n // element (Card/Box/Stack/Row with `as={Clickable|Pressable}`) wired\n // via onClick/onPress to useAction binding X, with a descendant\n // interactive primitive (Checkbox/Button/Input/Toggle/Slider/\n // RadioGroup/Select/TextArea/Link) wired via on* to the SAME X.\n //\n // Near-zero FP: the only patterns matching `<Card as={Clickable}\n // onClick={X}> ... <Checkbox onChange={X}>` are bugs. Three-pattern\n // FP test passes → severity earns 'fail' per no-silent-block\n // principle Rule 1. The runtime dedup in @ggui-ai/wire's useAction\n // catches the SYMPTOM regardless of shape; this check catches the\n // CAUSE one turn earlier and prevents shipping the broken a11y nest.\n if (actionBindings.length > 0) {\n issues.push(\n ...detectCertainDoubleWiredActions(sourceCode, actionBindings, designMode),\n );\n }\n\n // ── Connection suppression (ggui#670 Phase 2) ────────────────\n // `useRender().isConnected` is a LIVE read of the relay latch, and\n // the ATTEMPT is the runtime's self-heal sensor (#440/#443\n // attempt-always): a dispatch fired while the latch stands is how the\n // runtime discovers the host can relay again. Binding `disabled` to\n // the connection state strips the handler and blinds that sensor —\n // the control stays dead after recovery. The runtime owns the dead\n // zone's presentation (ggui#670 Phase 3: standing notice, then a\n // per-gesture cue) — generated code never suppresses on it. Direct\n // binding only, and only when the source reads\n // `useRender` at all — a same-named `props.isConnected` (a device-\n // status card) is not the connection state. Whole-source scan so a\n // multi-line attribute is caught; the issue reports the attribute's\n // line. The lookbehind keeps `aria-disabled={…}` (the idiom) out.\n if (/\\buseRender\\s*\\(/.test(sourceCode)) {\n const suppressionRe = /(?<![\\w-])disabled\\s*=\\s*\\{([^}]*)\\}/gs;\n for (const m of sourceCode.matchAll(suppressionRe)) {\n const expr = m[1]!;\n if (!/\\bisConnected\\b/.test(expr)) continue;\n const attrLine = sourceCode.slice(0, m.index ?? 0).split('\\n').length;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'interactivity',\n subcategory: 'connection-suppression',\n severity: 'critical',\n description:\n `\\`disabled\\` is bound to the connection state (\\`${expr.trim().replace(/\\s+/g, ' ')}\\`) — that strips the click handler, and the click is how the runtime detects that the host can relay actions again. The control stays dead after recovery.`,\n fix:\n 'Leave the control enabled — never bind `disabled` to the connection state. The runtime presents the dead zone itself (a standing notice, then a per-gesture cue) and the attempt is how it detects recovery; a suppressed control stays dead after the host recovers.',\n line: attrLine,\n });\n }\n }\n\n // ── Optional props accessed without guard ──────────────────\n // Check if Props interface has optional fields that are accessed without ?. or ?? or &&\n const propsInterfaceMatch = sourceCode.match(/interface Props\\s*\\{([^}]+)\\}/);\n if (propsInterfaceMatch) {\n const propsBody = propsInterfaceMatch[1];\n const optionalProps = [...propsBody.matchAll(/(\\w+)\\?:/g)].map(m => m[1]);\n for (const prop of optionalProps) {\n // Check for unguarded access: props.field. (dot access) or props.field[ (bracket access)\n // without being preceded by props.field?. or props.field ?? or props.field &&\n const accessPattern = new RegExp(`props\\\\.${prop}[.\\\\[]`, 'g');\n const guardPattern = new RegExp(`props\\\\.${prop}(\\\\?[.[]|\\\\s*&&|\\\\s*\\\\?\\\\?)`, 'g');\n const accesses = (sourceCode.match(accessPattern) || []).length;\n const guards = (sourceCode.match(guardPattern) || []).length;\n if (accesses > 0 && guards === 0) {\n issues.push({\n tier: 0, result: 'warn', category: 'crash', subcategory: `optional-prop:${prop}`,\n description: `Optional prop 'props.${prop}' accessed without null guard — will crash if undefined`,\n fix: `Use props.${prop}?.field or props.${prop} ?? fallback or {props.${prop} && ...}`,\n });\n }\n }\n }\n\n // ── Common pitfalls (recurring LLM mistakes that cost a turn) ─\n // Scan whole source so multiline opening tags (attrs split across lines) are caught.\n // Each match's line number = the line where the tag opens.\n const ALIGN_VALUES = new Set(['start', 'center', 'end', 'stretch']);\n const JUSTIFY_VALUES = new Set(['start', 'center', 'end', 'between', 'around', 'evenly']);\n const tagRegex = /<(Stack|Row)\\b([^>]*)>/gs;\n for (const tag of enforceDesignVocabulary ? sourceCode.matchAll(tagRegex) : []) {\n const tagName = tag[1];\n const attrs = tag[2];\n const tagLine = sourceCode.slice(0, tag.index).split('\\n').length;\n\n if (/\\bpadding=/.test(attrs)) {\n issues.push({\n tier: 0, result: 'fail', category: 'types', subcategory: 'stack-row-padding',\n description: `<${tagName}> does not accept a 'padding' prop`,\n fix: `Wrap the children in <Box padding=\"...\"> or use the parent <Card padding=\"...\">`,\n line: tagLine,\n });\n }\n const alignAttr = attrs.match(/\\balign=[\"']([^\"']+)[\"']/);\n if (alignAttr && !ALIGN_VALUES.has(alignAttr[1])) {\n issues.push({\n tier: 0, result: 'fail', category: 'types', subcategory: 'stack-row-align',\n description: `align=\"${alignAttr[1]}\" is invalid on <${tagName}>`,\n fix: `Use align=\"start\" | \"center\" | \"end\" | \"stretch\" (NOT flex-start/flex-end/space-between)`,\n line: tagLine,\n });\n }\n const justifyAttr = attrs.match(/\\bjustify=[\"']([^\"']+)[\"']/);\n if (justifyAttr && !JUSTIFY_VALUES.has(justifyAttr[1])) {\n issues.push({\n tier: 0, result: 'fail', category: 'types', subcategory: 'stack-row-justify',\n description: `justify=\"${justifyAttr[1]}\" is invalid on <${tagName}>`,\n fix: `Use justify=\"start\" | \"center\" | \"end\" | \"between\" | \"around\" | \"evenly\"`,\n line: tagLine,\n });\n }\n }\n\n // ── A kit control's boundary is the kit's (ggui#1697) ──────\n // A control draws its own edge, derived to clear 3:1 on its surface (`controlOutline`, or\n // `controlAccentOutline` on an outline Button); an inline border paints over it, and the ramp step\n // the model reached for (`primary-200`) measured about 1.1:1. The prompt's rule 5 says the same, so\n // this check enforces what the model was told. The description starts with the check's id so the\n // generator's logged violation lines (`✗ …`) count its fires per generation, in-turn repairs included.\n for (const tag of enforceDesignVocabulary ? kitControlTags(sourceCode) : []) {\n const key = inlineBorderKey(tag.attrs, sourceCode);\n if (key === null) continue;\n issues.push({\n tier: 0, result: 'fail', category: 'tokens', subcategory: 'control-inline-border', severity: 'critical',\n description: `control-inline-border: <${tag.name}> sets an inline \\`${key}\\` — a kit control draws its own boundary, and an inline border paints over it`,\n fix: `Remove the border from <${tag.name}>'s style (keep borderRadius if you need it). An outline chip is <Button variant=\"outline\"> exactly as it comes; a control-like edge on your own element uses var(--ggui-color-controlOutline).`,\n line: tag.line,\n });\n }\n\n // ── Missing Props interface ───────────────────────────────\n if (!sourceCode.includes('interface Props') && !sourceCode.includes('type Props')) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'types',\n subcategory: 'props-interface',\n severity: 'critical',\n description: 'No Props interface found — data is likely hardcoded',\n fix: 'Add interface Props { ... } with typed fields and default values in the function signature',\n });\n }\n\n // ── Missing default export ────────────────────────────────\n if (!sourceCode.includes('export default function')) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'compile',\n subcategory: 'default-export',\n severity: 'critical',\n description: 'Missing default export function',\n fix: 'Add export default function Component(props: Props) { ... }',\n });\n }\n\n // ── Component never returns its tree ──────────────────────\n // The scaffold hands the model `return (` … `);` around the layout.\n // A root-block rewrite can delete them with it, and bare JSX at\n // statement position compiles, type-checks and renders NOTHING.\n const neverReturns = detectComponentNeverReturns(sourceCode);\n if (neverReturns !== null) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'compile',\n subcategory: 'renders-nothing',\n severity: 'critical',\n description:\n neverReturns.jsxStatementLine === undefined\n ? 'The component never returns its tree — it renders a blank frame'\n : `The component never returns its tree: the JSX at line ${neverReturns.jsxStatementLine} sits at statement position, so it is built and thrown away and the frame renders blank`,\n fix: 'Wrap the tree in the return the boilerplate gave you: `return (` before the root element and `);` after it.',\n ...(neverReturns.jsxStatementLine === undefined ? {} : { line: neverReturns.jsxStatementLine }),\n });\n }\n\n // (Controller-View checks removed — generated components use a\n // single-function pattern.)\n\n // ── Contract validation ───────────────────────────────────\n if (contract) {\n try {\n const contractIssues: ContractIssue[] = validateAllContracts(sourceCode, contract);\n for (const ci of contractIssues) {\n issues.push({\n tier: 0,\n result: ci.severity === 'error' ? 'fail' as const : 'warn' as const,\n category: 'contract' as const,\n subcategory: ci.field,\n severity: ci.severity === 'error' ? 'critical' as const : 'major' as const,\n description: ci.message,\n fix: ci.fix,\n });\n }\n } catch {\n // Contract validation may fail on malformed code — non-blocking\n }\n\n // ── Wire hook usage — every contract hook must be used in the component body ──\n //\n // `actionSpec` / `streamSpec` are flat `Record<name, Entry>` maps.\n // See `@ggui-ai/protocol` DataContract.\n const fnBody = sourceCode.slice(sourceCode.indexOf('export default function'));\n if (contract.actionSpec) {\n for (const actionName of Object.keys(contract.actionSpec)) {\n if (!fnBody.includes(actionName)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `action:${actionName}`,\n description: `Action hook '${actionName}' from contract is declared but never used in the component`,\n fix: `Wire ${actionName}() to a Button onClick, form onSubmit, or other user interaction`,\n });\n }\n }\n }\n if (contract.streamSpec) {\n for (const channelName of Object.keys(contract.streamSpec)) {\n if (!fnBody.includes(channelName)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `stream:${channelName}`,\n description: `Stream hook '${channelName}' from contract is declared but never rendered in the component`,\n fix: `Render ${channelName}.latest data in the JSX (with null guard: ${channelName}.latest && ...)`,\n });\n }\n }\n }\n // agentCapabilities.tools is intentionally NOT checked here — it\n // is a catalog the AGENT invokes, not a component hook surface.\n // Cross-refs surface via actionSpec[*].nextStep and\n // streamSpec[*].source.tool, which the action/stream loops above\n // already cover.\n if (contract.clientCapabilities) {\n // Iterate the flattened `GadgetUse[]` — the export name\n // (`use.name`) is the identity the generated code references.\n for (const use of listContractGadgets(contract)) {\n if (!fnBody.includes(use.name)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `clientCapability:${use.name}`,\n description: `Client capability '${use.name}' from contract is declared but the export is never used`,\n fix: HOOK_NAME_RE.test(use.name)\n ? `Import \\`${use.name}\\` from \\`${use.package}\\` and call it inside the component — bind the return value and surface its \\`.value\\` / \\`.status\\` in JSX.`\n : `Import \\`${use.name}\\` from \\`${use.package}\\` and render it as a JSX element (\\`<${use.name} … />\\`).`,\n });\n }\n }\n }\n\n // ── Wire preservation ─────────────────────────────────────────────────\n // The substring checks above (`fnBody.includes(name)`) are permissive —\n // they pass if the name appears ANYWHERE in the function body, including\n // a comment or unrelated identifier. The AST-backed `checkWirePreservation`\n // is the strict seal: it verifies that the boilerplate-emitted\n // `useAction('<name>')` / `useStream('<name>')` / `useGguiContext('<name>')`\n // hook call ACTUALLY exists, keyed on the string-literal first argument.\n //\n // Catches the abandonment/deletion case: LLM's apply_changes drops the\n // hook call entirely, so the wire never fires at runtime. `pnpm\n // typecheck` can't catch this (a missing call is a missing side effect,\n // not a type error). Seal B fires as `fail` — deterministic, retriable\n // feedback.\n //\n // The runtime auto-commit path (`coding-agent/tools.ts::autoCommit`)\n // calls `runTier0Checks`, which is where this rule lives so it\n // fires on the live generation path.\n try {\n const report = checkWirePreservation(sourceCode, contract);\n for (const site of report.missing) {\n const hook = HOOK_NAME_FOR[site.kind];\n const fix =\n site.kind === 'context'\n ? `Restore \\`const [${site.name}, set${site.name.charAt(0).toUpperCase() + site.name.slice(1)}] = ${hook}('${site.name}')\\` ` +\n `at the top of the component body. The boilerplate auto-emits this destructure for every declared ` +\n `contextSpec slot — do not delete it.`\n : `Restore \\`const ${site.name} = ${hook}('${site.name}')\\` at the top of the ` +\n `component body and consume the returned binding (in JSX, a callback, or an effect).`;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'contract',\n subcategory: `wire_preservation:${site.kind}:${site.name}`,\n severity: 'critical',\n description:\n `Contract declares ${site.kind} '${site.name}' but no ${hook}('${site.name}') ` +\n `call exists in the component. The boilerplate placed this hook for you — ` +\n `do not delete it.`,\n fix,\n });\n }\n } catch {\n // Malformed code surfaces as a primary error elsewhere — don't mask\n // it with a wire-preservation noise-violation here.\n }\n\n // ── Props field rendering — verify each prop is actually used in the component ──\n if (contract.propsSpec) {\n const propsProperties = contract.propsSpec.properties ?? {};\n for (const propName of Object.keys(propsProperties)) {\n // Check if prop is referenced in the function body (via props.fieldName)\n if (!fnBody.includes(`props.${propName}`) && !fnBody.includes(`{props.${propName}}`)) {\n issues.push({\n tier: 0, result: 'warn', category: 'contract', subcategory: `prop:${propName}`,\n description: `Props field '${propName}' from contract is never rendered — data is wasted`,\n fix: `Render props.${propName} in the JSX (e.g., <Text>{props.${propName}}</Text>)`,\n });\n }\n }\n }\n }\n\n // ── Wire_undeclared (UNCONDITIONAL) ──────────────────────────────────\n //\n // Every wire-call site in the emitted code MUST correspond to a\n // declared entry on the agent-authored `contract`, regardless of\n // whether the contract is partially or wholly absent. Empty contract\n // → ALL wire calls are \"extra\" → all fail with `wire_undeclared`.\n // Failure mode this guards against: agent describes contextSpec in\n // plain prompt text but doesn't author `contract`; the LLM emits\n // `useGguiContext('foo')` / `useAction('foo')` with no slot\n // registration; the iframe crashes at first paint with\n // `[ggui] useGguiContext('foo'): no Context registered`. The\n // remediation message names the exact contract field to declare on,\n // so the agent's next turn can fix structurally.\n try {\n const contractsForExtraCheck: DataContract = contract ?? {};\n const extras = checkWirePreservation(sourceCode, contractsForExtraCheck).extra;\n for (const site of extras) {\n const hook = HOOK_NAME_FOR[site.kind];\n const field = CONTRACT_FIELD_FOR[site.kind];\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'contract',\n subcategory: `wire_undeclared:${site.kind}:${site.name}`,\n severity: 'critical',\n description:\n `Component calls ${hook}('${site.name}') but the contract does not declare ` +\n `${site.kind} '${site.name}'. Every wire reference in the generated code MUST ` +\n `correspond to a declared entry on the agent-authored contract — the runtime ` +\n `mounts/registers wire surfaces from the contract, not from the code. ` +\n (contract === undefined\n ? 'No contract authored at all — describing the contract in the prompt text is NOT enough; ' +\n 'the agent MUST pass a structured `contract` field on the ggui_render call.'\n : ''),\n fix:\n `Either (a) declare \\`${field}.${site.name}\\` on the \\`contract\\` input so the ` +\n `runtime registers the surface for this UI, or (b) remove the ${hook}('${site.name}') ` +\n `call from the component if it isn't part of the intended wire surface.`,\n });\n }\n } catch {\n // Malformed code surfaces elsewhere; don't mask with noise.\n }\n\n // ── Wire-hook import presence ────────────────────────────────────────\n //\n // `rewriteImports` (packages/design/src/rendering/rewrite-imports.ts) only\n // substitutes `from '@ggui-ai/wire'` specifiers that already exist in the\n // compiled code; a hook call like `useAction('X')` without the paired\n // `import { useAction } from '@ggui-ai/wire'` line leaves no specifier\n // for the shim to attach, so the hook is undeclared at eval time and the\n // browser throws `ReferenceError: useAction is not defined`. This check\n // runs unconditionally (no contract needed) — for every wire hook the\n // component CALLS at least once, the matching named import must be\n // present at top level. Independent of `wire_preservation` which checks\n // that contract-declared hooks are called.\n try {\n const importReport = checkWireImports(sourceCode);\n for (const miss of importReport.missing) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: `wire_import_missing:${miss.hook}`,\n severity: 'critical',\n description:\n `Component calls ${miss.hook}(...) but does not import it from ` +\n `'@ggui-ai/wire'. Without the import, rewriteImports has no ` +\n `specifier to attach the data-URL shim to, so the hook is ` +\n `undeclared at browser eval time and the component crashes on ` +\n `mount with \\`ReferenceError: ${miss.hook} is not defined\\`.`,\n fix:\n `Add \\`import { ${miss.hook} } from '@ggui-ai/wire';\\` at the ` +\n `top of the file alongside the other imports.`,\n });\n }\n } catch {\n // Malformed code surfaces as a primary error elsewhere — don't mask it.\n }\n\n // ── No-require pattern for @-scoped packages ─────────────────────────\n //\n // A repeating LLM failure mode: when the boilerplate emits a static\n // `import { useLeafletMap } from '@ggui-samples/gadget-leaflet'`, the\n // model sometimes removes the import and substitutes\n // `const { useLeafletMap } = require('@ggui-samples/gadget-leaflet')`\n // (or `require('@ggui-ai/gadgets')`) inline. That FAILS in a real\n // browser ESM iframe: `require` is not defined, and `rewriteImports`\n // never sees a static `from '<pkg>'` specifier to attach the data-URL\n // shim to.\n //\n // This check rejects any `require('@...')` call expression on an\n // @-scoped package. The fix is always the same — convert to a\n // top-level static `import { … } from '<pkg>'`. Targeted at @-scoped\n // packages because that's the LLM's typical hedge specifier shape\n // (CJS bare `require('react')` etc. don't appear in our generated\n // code path).\n {\n // Match `require('@scope/pkg')` and `require(\"@scope/pkg\")` with a\n // simple regex. The LLM only emits this pattern as call\n // expressions, so the false-positive rate is negligible in\n // practice; an AST walk would be more rigorous but unnecessary.\n const requireRe = /require\\s*\\(\\s*['\"](@[^'\"]+)['\"]\\s*\\)/g;\n const seen = new Set<string>();\n let m: RegExpExecArray | null;\n while ((m = requireRe.exec(sourceCode)) !== null) {\n const pkg = m[1];\n if (pkg === undefined || seen.has(pkg)) continue;\n seen.add(pkg);\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: `require_disallowed:${pkg}`,\n severity: 'critical',\n description:\n `Component uses \\`require('${pkg}')\\` — CommonJS require is ` +\n `not available in the iframe's browser ESM runtime, and the ` +\n `import-rewriter only attaches data-URL shims to STATIC import ` +\n `specifiers. The component will fail to mount with ` +\n `\\`ReferenceError: require is not defined\\` at the first call.`,\n fix:\n `Replace with a top-level static \\`import { … } from '${pkg}'\\` ` +\n `at the top of the file. The boilerplate emits this import for ` +\n `you when the contract declares a matching ` +\n `\\`clientCapabilities.gadgets[*]\\` entry — restore the line ` +\n `instead of inlining a require() call.`,\n });\n }\n }\n\n // ── gadget import preservation ───────────────────────────────────────\n //\n // Gadgets are DIRECT-imported. The boilerplate emits, per\n // registered gadget package, one combined import:\n // `import { useLeafletMap } from '@scope/leaflet';`\n // The LLM (correctly) intuits the hook is runtime-resolved and tends\n // to delete the import — but the import IS the resolution anchor: the\n // iframe rewriter rewrites the package specifier to a per-package\n // shim, and without the import the hook is unbound (ReferenceError).\n //\n // This check verifies, for every contract-declared gadget export,\n // that it is still imported from its package. The export NAME\n // appearing alone is not enough — the `import { … }` statement must\n // carry it. Hooks AND components are both direct-imported and\n // both checked here; the fix hint adapts to the export kind (hooks\n // are CALLED, components are RENDERED as JSX).\n {\n // Scan comment-free source — a commented-out import must NOT\n // satisfy the preservation check.\n const gadgetScanSource = stripComments(sourceCode);\n // Iterate the flattened `GadgetUse[]`. Kind is discriminated\n // by the export-name grammar — `use`-prefixed → hook, else component.\n for (const use of contract ? listContractGadgets(contract) : []) {\n const exportName = use.name;\n if (isGadgetExportImported(gadgetScanSource, use.package, exportName)) {\n continue;\n }\n const isComponent = !HOOK_NAME_RE.test(exportName);\n const kind = isComponent ? 'component' : 'hook';\n // Local binding name for the hook worked example (mirrors the\n // boilerplate's derivation: strip `use`, lowercase first char).\n const bindingName =\n exportName.length > 3\n ? exportName.charAt(3).toLowerCase() + exportName.slice(4)\n : exportName;\n const fix = isComponent\n ? `The component \\`${exportName}\\` is REAL and CORRECT — do NOT remove it. ` +\n `Restore the gadget plumbing in 2 steps:\\n` +\n `(1) Keep \\`import { ${exportName} } from '${use.package}';\\` at the top of the file.\\n` +\n `(2) RENDER \\`<${exportName} … />\\` as a JSX element in the tree you return — pass its props from the contract. Do NOT call it like a hook.\\n` +\n `Import \\`${exportName}\\` ONLY from '${use.package}' — that is the package it is registered under. If you remove the import again, this check will fail again — \\`${exportName}\\` is not optional.`\n : `The hook \\`${exportName}\\` is REAL and CORRECT — do NOT remove it. ` +\n `Restore the gadget plumbing in 2 steps:\\n` +\n `(1) Keep \\`import { ${exportName} } from '${use.package}';\\` at the top of the file.\\n` +\n `(2) CALL \\`${exportName}(...)\\` inside the component body and render its return value. Example:\\n` +\n ` \\`const ${bindingName} = ${exportName}({ /* props from contract */ });\\`\\n` +\n ` \\`return <div>{/* render ${bindingName} */}</div>;\\`\\n` +\n `Import \\`${exportName}\\` ONLY from '${use.package}' — that is the package it is registered under. If you remove the import again, this check will fail again — \\`${exportName}\\` is not optional.`;\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'imports',\n subcategory: `gadget_preservation:${exportName}`,\n severity: 'critical',\n description:\n `Contract declares \\`clientCapabilities.gadgets['${use.package}']['${exportName}']\\` ` +\n `(a ${kind}) but the ` +\n `component does not import \\`${exportName}\\` from \\`${use.package}\\`. ` +\n `The boilerplate emits \\`import { ${exportName} } from '${use.package}';\\` ` +\n `— keep it. Without the import the iframe runtime cannot resolve the ` +\n `${kind} and the registered gadget is unreachable.`,\n fix,\n });\n }\n }\n\n // ── TypeScript type checking + React hooks linting ──────────\n const [typeResult, reactResult] = await Promise.all([\n typecheck(sourceCode, gadgetTypes).catch((err) => {\n console.warn('[runTier0Checks] TypeChecker failed:', err instanceof Error ? err.message : String(err));\n return null;\n }),\n lintReactHooks(sourceCode).catch((err) => {\n console.warn('[runTier0Checks] React linter failed:', err instanceof Error ? err.message : String(err));\n return [] as ReactLintDiagnostic[];\n }),\n ]);\n\n // TS type errors → fail, warnings → warn\n if (typeResult) {\n for (const error of typeResult.errors) {\n issues.push({\n tier: 0,\n result: 'fail',\n category: 'types',\n subcategory: `ts${error.code}`,\n description: error.message,\n fix: error.fix,\n line: error.line,\n });\n }\n for (const warning of typeResult.warnings) {\n issues.push({\n tier: 0,\n result: 'warn',\n category: 'types',\n subcategory: `ts${warning.code}`,\n description: warning.message,\n fix: warning.fix,\n line: warning.line,\n });\n }\n }\n\n // React hooks violations — errors → fail, warnings → warn\n for (const diag of reactResult) {\n issues.push({\n tier: 0,\n result: diag.severity === 'error' ? 'fail' : 'warn',\n category: 'types',\n subcategory: diag.rule,\n description: diag.message,\n fix: diag.fix,\n line: diag.line,\n });\n }\n\n // Populate priority on every tier-0 issue. No current code path reads\n // `.priority` — it is reserved for future eval-policy consumption.\n for (const issue of issues) {\n if (!issue.priority) issue.priority = priorityForIssue(issue.category);\n }\n\n return issues;\n}\n\n/**\n * Run tier 0 checks and return a full EvalResult with pass list.\n */\nexport async function runTier0(\n sourceCode: string,\n contract?: DataContract,\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n): Promise<EvalResult> {\n const issues = await runTier0Checks(sourceCode, contract, undefined, undefined, designMode);\n const pass: string[] = [];\n\n // Build pass list from categories that had no issues\n const failedCategories = new Set(issues.map(i => i.category));\n const tier0Categories: EvalCategory[] = ['compile', 'security', 'contract', 'types', 'imports', 'tokens'];\n\n for (const cat of tier0Categories) {\n if (!failedCategories.has(cat)) {\n pass.push(cat);\n }\n }\n\n return { issues, pass };\n}\n\n// Tier-0 deterministic checks are run above. Axis-gated mode checks are\n// dispatched from `evaluation/axis-checks/` — see `runAxisChecks`.\n","// Sample props from a PropsSpec — `example` first, then `default`, then a type-driven fill from the JSON\n// Schema. Pure: protocol types only, no sandbox, no node modules, so `@ggui-ai/ui-gen/check` can export it and a\n// caller outside the harness (an experiment's judge input, ggui#1386) synthesizes the SAME props the coding\n// agent's own render check falls back to. Moved verbatim out of `tools/render-check.ts` (2026-09-26).\nimport type { JsonObject, JsonSchema, JsonValue, PropsSpec } from '@ggui-ai/protocol';\n\n/**\n * Generate sample props from a PropsSpec contract.\n * Uses `example` values from each PropEntry when available,\n * otherwise synthesizes plausible defaults from the JSON Schema.\n */\nexport function generateSampleProps(spec: PropsSpec): JsonObject {\n const props: JsonObject = {};\n\n for (const [name, entry] of Object.entries(spec.properties)) {\n // Prefer explicit example value\n if (entry.example !== undefined) {\n props[name] = entry.example;\n continue;\n }\n\n // Prefer explicit default value\n if (entry.default !== undefined) {\n props[name] = entry.default;\n continue;\n }\n\n // Synthesize from JSON Schema\n props[name] = synthesizeFromSchema(entry.schema);\n }\n\n return props;\n}\n\nfunction synthesizeFromSchema(schema: JsonSchema): JsonValue | undefined {\n // Draft-07 type arrays (`['string','null']`) synthesize from the\n // first non-null member — the canonical nullability form the\n // enforced-props-schema emission produces.\n const declared = Array.isArray(schema.type)\n ? schema.type.find((t) => t !== 'null')\n : schema.type;\n switch (declared) {\n case 'string': return 'sample';\n case 'number':\n case 'integer': return 0;\n case 'boolean': return false;\n case 'null': return null;\n case 'array': {\n if (schema.items) return [synthesizeFromSchema(schema.items) ?? null];\n return [];\n }\n case 'object': {\n const obj: JsonObject = {};\n if (schema.properties) {\n for (const [k, v] of Object.entries(schema.properties)) {\n obj[k] = synthesizeFromSchema(v);\n }\n }\n return obj;\n }\n default: return undefined;\n }\n}\n"]}