@ggui-ai/ui-gen 0.6.2 → 0.7.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 (35) hide show
  1. package/dist/adapters/generation-dispatch.js +21 -8
  2. package/dist/adapters/generation-dispatch.js.map +1 -1
  3. package/dist/adapters/index.js +1 -1
  4. package/dist/adapters/index.js.map +1 -1
  5. package/dist/advanced/index.js +21 -8
  6. package/dist/advanced/index.js.map +1 -1
  7. package/dist/boilerplate.js +9 -5
  8. package/dist/boilerplate.js.map +1 -1
  9. package/dist/check/index.js.map +1 -1
  10. package/dist/evaluation/axis-checks/index.js.map +1 -1
  11. package/dist/evaluation/index.js +3 -3
  12. package/dist/evaluation/index.js.map +1 -1
  13. package/dist/harness/index.js +9 -5
  14. package/dist/harness/index.js.map +1 -1
  15. package/dist/harness/runtime.js +10 -6
  16. package/dist/harness/runtime.js.map +1 -1
  17. package/dist/harness/types-public.js +9 -5
  18. package/dist/harness/types-public.js.map +1 -1
  19. package/dist/index.js +21 -8
  20. package/dist/index.js.map +1 -1
  21. package/dist/tools/get-primitives-ts.d.ts +1 -1
  22. package/dist/tools/get-primitives-ts.js +1 -1
  23. package/dist/tools/get-primitives-ts.js.map +1 -1
  24. package/dist/validation/index.d.ts +1 -1
  25. package/dist/validation/index.js +1 -1
  26. package/dist/validation/index.js.map +1 -1
  27. package/package.json +12 -12
  28. package/src/boilerplate/generate.ts +2 -0
  29. package/src/boilerplate/system-prompt.ts +3 -1
  30. package/src/boilerplate/templates/base.tsx.tmpl +1 -1
  31. package/src/evaluation/llm-evaluator.ts +8 -1
  32. package/src/evaluation/types-public.ts +4 -3
  33. package/src/harness/primitive-slice.ts +1 -1
  34. package/src/tools/get-primitives-ts.ts +1 -1
  35. package/src/validation/primitives.ts +1 -1
@@ -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/evaluation/types-public.ts","../../src/check/run-tier0.ts"],"names":["ts","resolved"],"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,SAAA,CAAU,CAAC,CAAA;AACjC,UAAA,IAAI,QAAA,IAAYA,GAAA,CAAG,eAAA,CAAgB,QAAQ,CAAA,EAAG;AAC5C,YAAA,KAAA,CAAM,KAAK,EAAE,IAAA,EAAM,IAAA,EAAM,QAAA,CAAS,MAAM,CAAA;AAAA,UAC1C;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,IAAAA,GAAA,CAAG,YAAA,CAAa,MAAM,KAAK,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,GAAA,CAAI,GAAG,CAAA,EAAG;AAC9B,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AAAA,IACf;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,QAAQ,IAAA,EAAK;AACxB","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 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 result = (schema.items.type === 'object' && 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 */\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.\n */\nexport function isAllowedImport(\n specifier: string,\n gadgetPackages?: ReadonlySet<string>,\n): boolean {\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';\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`), try:\n * - <resolved>.d.ts\n * - <resolved>/index.d.ts\n * - <resolved>.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 const resolved = path.posix.normalize(`${dir}/${importPath}`);\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","// 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\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\n/**\n * Runtime-render probe execution status — three-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\".\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 */\nexport type RuntimeProbeStatus = \"ran\" | \"infra-skipped\" | \"not-applicable\";\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 */\nexport interface RuntimeProbeMeta {\n readonly status: RuntimeProbeStatus;\n /** Populated for `infra-skipped` / `not-applicable` — why the probe didn't run. */\n readonly reason?: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\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\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 { 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\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: \"Add labels on form inputs, alt text on images, semantic HTML.\",\n evalInstruction: `Evaluate ACCESSIBILITY: missing labels, alt text, semantic HTML, keyboard support.\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; 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/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(priority: Priority): EvalCriterion[] {\n return CRITERIA.filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(id: string): EvalCriterion | undefined {\n return CRITERIA.find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(): EvalCriterion[] {\n return CRITERIA.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(): 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);\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 { 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): EvalIssue[] {\n const issues: EvalIssue[] = [];\n if (actionBindings.length === 0) return issues;\n const bindings = new Set(actionBindings);\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 || !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 (tag !== undefined && INTERACTIVE_DESCENDANTS.has(tag)) {\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 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 <${outerTag} as={...}> 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: `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/** 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 * 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): Promise<EvalIssue[]> {\n const issues: EvalIssue[] = [];\n const lines = sourceCode.split('\\n');\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 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 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 const hexMatch = line.match(/#[0-9a-fA-F]{3,8}\\b/);\n if (\n hexMatch &&\n !line.includes('var(--ggui-') &&\n !line.includes('// fallback') &&\n !assetEscapedLines.has(lineNum)\n ) {\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 token reference like var(--ggui-color-primary-500, ${hexMatch[0]}). Hardcoded colors mean the operator's theme has no effect on this surface.`,\n line: lineNum,\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 semantic token: var(--ggui-color-surface), var(--ggui-color-onSurface), var(--ggui-color-outline), etc.',\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 = line.match(\n /\\b(gap|padding|paddingX|paddingY|margin|radius)\\s*=\\s*[\"'][\\d.]+(?:px|rem|em)[\"']/,\n );\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-onSurfaceVariant), 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 = line.match(/(?:padding|margin|gap|borderRadius)\\s*:\\s*['\"]?\\d+px/);\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 var(--ggui-spacing-*, fallback)',\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 = line.match(/\\b(padding|paddingX|paddingY|gap|margin)\\s*=\\s*\\{?\\s*(\\d+)\\s*\\}?/);\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; 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 const actionBindings = [\n ...sourceCode.matchAll(/(?:const|let)\\s+(\\w+)\\s*=\\s*useAction\\s*\\(/g),\n ]\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),\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 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 // (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): Promise<EvalResult> {\n const issues = await runTier0Checks(sourceCode, contract);\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"]}
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/evaluation/types-public.ts","../../src/check/run-tier0.ts"],"names":["ts","resolved"],"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,GAA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AAI,CAAC,KAAA,CAAM,QAAA,QAAgB,QAAA,GAAW,gBAAA,CAAiB,MAAM,QAAQ,CAAA;AAAA,EACvE;AAEA,EAAA,OAAO,MAAA;AACT;AAKA,eAAsB,QAAA,CACpB,YACA,QAAA,EACqB;AACrB,EAAA,MAAM,MAAA,GAAS,MAAM,cAAA,CAAe,UAAA,EAAY,QAAQ,CAAA;AACxD,EAAA,MAAM,OAAiB,EAAC;AAGxB,EAAA,MAAM,gBAAA,GAAmB,IAAI,GAAA,CAAI,MAAA,CAAO,IAAI,CAAA,CAAA,KAAK,CAAA,CAAE,QAAQ,CAAC,CAAA;AAC5D,EAAA,MAAM,kBAAkC,CAAC,SAAA,EAAW,YAAY,UAAA,EAAY,OAAA,EAAS,WAAW,QAAQ,CAAA;AAExG,EAAA,KAAA,MAAW,OAAO,eAAA,EAAiB;AACjC,IAAA,IAAI,CAAC,gBAAA,CAAiB,GAAA,CAAI,GAAG,CAAA,EAAG;AAC9B,MAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AAAA,IACf;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,QAAQ,IAAA,EAAK;AACxB","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 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 result = (schema.items.type === 'object' && 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 */\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.\n */\nexport function isAllowedImport(\n specifier: string,\n gadgetPackages?: ReadonlySet<string>,\n): boolean {\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';\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`), try:\n * - <resolved>.d.ts\n * - <resolved>/index.d.ts\n * - <resolved>.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 const resolved = path.posix.normalize(`${dir}/${importPath}`);\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","// 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\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\n/**\n * Runtime-render probe execution status — three-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\".\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 */\nexport type RuntimeProbeStatus = \"ran\" | \"infra-skipped\" | \"not-applicable\";\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 */\nexport interface RuntimeProbeMeta {\n readonly status: RuntimeProbeStatus;\n /** Populated for `infra-skipped` / `not-applicable` — why the probe didn't run. */\n readonly reason?: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\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\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 { 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\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/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(priority: Priority): EvalCriterion[] {\n return CRITERIA.filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(id: string): EvalCriterion | undefined {\n return CRITERIA.find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(): EvalCriterion[] {\n return CRITERIA.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(): 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);\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 { 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): EvalIssue[] {\n const issues: EvalIssue[] = [];\n if (actionBindings.length === 0) return issues;\n const bindings = new Set(actionBindings);\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 || !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 (tag !== undefined && INTERACTIVE_DESCENDANTS.has(tag)) {\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 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 <${outerTag} as={...}> 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: `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/** 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 * 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): Promise<EvalIssue[]> {\n const issues: EvalIssue[] = [];\n const lines = sourceCode.split('\\n');\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 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 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 const hexMatch = line.match(/#[0-9a-fA-F]{3,8}\\b/);\n if (\n hexMatch &&\n !line.includes('var(--ggui-') &&\n !line.includes('// fallback') &&\n !assetEscapedLines.has(lineNum)\n ) {\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 token reference like var(--ggui-color-primary-500, ${hexMatch[0]}). Hardcoded colors mean the operator's theme has no effect on this surface.`,\n line: lineNum,\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 semantic token: var(--ggui-color-surface), var(--ggui-color-onSurface), var(--ggui-color-outline), etc.',\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 = line.match(\n /\\b(gap|padding|paddingX|paddingY|margin|radius)\\s*=\\s*[\"'][\\d.]+(?:px|rem|em)[\"']/,\n );\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-onSurfaceVariant), 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 = line.match(/(?:padding|margin|gap|borderRadius)\\s*:\\s*['\"]?\\d+px/);\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 var(--ggui-spacing-*, fallback)',\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 = line.match(/\\b(padding|paddingX|paddingY|gap|margin)\\s*=\\s*\\{?\\s*(\\d+)\\s*\\}?/);\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; 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 const actionBindings = [\n ...sourceCode.matchAll(/(?:const|let)\\s+(\\w+)\\s*=\\s*useAction\\s*\\(/g),\n ]\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),\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 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 // (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): Promise<EvalResult> {\n const issues = await runTier0Checks(sourceCode, contract);\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"]}