@ggui-ai/ui-gen 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/generation-dispatch.d.ts +9 -2
- package/dist/adapters/generation-dispatch.js +547 -85
- package/dist/adapters/generation-dispatch.js.map +1 -1
- package/dist/adapters/index.js +28 -11
- package/dist/adapters/index.js.map +1 -1
- package/dist/advanced/index.d.ts +5 -3
- package/dist/advanced/index.js +563 -92
- package/dist/advanced/index.js.map +1 -1
- package/dist/blueprint-validator.js +109 -3
- package/dist/blueprint-validator.js.map +1 -1
- package/dist/boilerplate.js +14 -2
- package/dist/boilerplate.js.map +1 -1
- package/dist/check/index.d.ts +1 -1
- package/dist/check/index.js +11 -1
- package/dist/check/index.js.map +1 -1
- package/dist/{create-ui-generator-B9kV4U9h.d.ts → create-ui-generator-CF0EL0Li.d.ts} +13 -1
- package/dist/{dispatch-Deo9qzrG.d.ts → dispatch-D75M-OfZ.d.ts} +1 -1
- package/dist/evaluation/axis-checks/index.d.ts +3 -3
- package/dist/evaluation/axis-checks/index.js +101 -0
- package/dist/evaluation/axis-checks/index.js.map +1 -1
- package/dist/evaluation/axis-checks/registry.d.ts +1 -1
- package/dist/evaluation/axis-checks/registry.js +101 -0
- package/dist/evaluation/axis-checks/registry.js.map +1 -1
- package/dist/evaluation/index.d.ts +46 -3
- package/dist/evaluation/index.js +358 -17
- package/dist/evaluation/index.js.map +1 -1
- package/dist/harness/check/runtime-render/index.d.ts +2 -2
- package/dist/harness/check/runtime-render/index.js +110 -3
- package/dist/harness/check/runtime-render/index.js.map +1 -1
- package/dist/harness/index.d.ts +2 -2
- package/dist/harness/index.js +263 -18
- package/dist/harness/index.js.map +1 -1
- package/dist/harness/llm-trace-sink.d.ts +1 -1
- package/dist/harness/llm-trace-sink.js.map +1 -1
- package/dist/harness/prompts.js +17 -3
- package/dist/harness/prompts.js.map +1 -1
- package/dist/harness/result-types.d.ts +1 -1
- package/dist/harness/runtime.d.ts +9 -2
- package/dist/harness/runtime.js +20 -6
- package/dist/harness/runtime.js.map +1 -1
- package/dist/harness/types-public.d.ts +1 -1
- package/dist/harness/types-public.js +14 -2
- package/dist/harness/types-public.js.map +1 -1
- package/dist/harness/validator-trace-sink.d.ts +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.js +563 -92
- package/dist/index.js.map +1 -1
- package/dist/{llm-router-1TyI0_TV.d.ts → llm-router-BEVtbAb9.d.ts} +61 -4
- package/dist/patch.d.ts +1 -1
- package/dist/provider-adapter.d.ts +16 -6
- package/dist/provider-adapter.js.map +1 -1
- package/dist/providers/index.d.ts +19 -6
- package/dist/providers/index.js.map +1 -1
- package/dist/{render-check-CNZjHD5g.d.ts → render-check-BNYGVDJd.d.ts} +1 -1
- package/dist/{types-public-C36k1q6s.d.ts → types-public-DIpjC-OA.d.ts} +1 -1
- package/dist/workflows.d.ts +1 -1
- package/package.json +12 -12
- package/src/adapters/generation-dispatch.ts +9 -0
- package/src/adapters/openrouter/client.ts +2 -2
- package/src/adapters/openrouter/types.ts +10 -0
- package/src/boilerplate/generate.ts +10 -2
- package/src/boilerplate/json-schema-ts.ts +22 -2
- package/src/boilerplate/system-prompt.ts +1 -0
- package/src/compile.ts +1 -1
- package/src/contract-context.ts +10 -2
- package/src/create-ui-generator.ts +14 -0
- package/src/design-system-docs.ts +6 -4
- package/src/evaluation/axis-checks/checks/state-ui-affordance.ts +162 -0
- package/src/evaluation/axis-checks/registry.ts +2 -0
- package/src/evaluation/index.ts +11 -0
- package/src/evaluation/llm-evaluator.ts +14 -1
- package/src/evaluation/visual-evaluator.ts +44 -65
- package/src/harness/check/runtime-render/adapter.ts +18 -0
- package/src/harness/check/runtime-render/index.ts +8 -0
- package/src/harness/check/runtime-render/prepare-mockup.ts +14 -0
- package/src/harness/check/runtime-render/production-act-shim.ts +158 -0
- package/src/harness/check/runtime-render/render-check.ts +72 -1
- package/src/harness/coding/run-eval-round.ts +61 -5
- package/src/harness/index.ts +1 -1
- package/src/harness/llm-router.ts +397 -18
- package/src/harness/llm-trace-sink.ts +2 -1
- package/src/harness/runtime.ts +7 -0
- package/src/index.ts +5 -5
- package/src/provider-adapter.ts +16 -6
- package/src/providers/bedrock.ts +5 -4
- package/src/providers/index.ts +16 -4
- package/src/tools/render-check.ts +19 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/run-workflow.ts","../../src/harness/validator-trace-sink.ts","../../src/run-check.ts","../../src/run-harness.ts","../../src/fragments/render.ts","../../src/fragments/state.ts","../../src/fragments/writes.ts","../../src/fragments/realtime.ts","../../src/fragments/fetch.ts","../../src/fragments/layout.ts","../../src/fragments/tooling.ts","../../src/fragments/index.ts","../../src/compose.ts","../../src/boilerplate/render.ts","../../src/boilerplate/json-schema-ts.ts","../../src/boilerplate/generate.ts","../../src/evaluation/types-public.ts","../../src/internal/extract-call-signatures.ts","../../src/boilerplate/system-prompt.ts","../../src/tools.ts","../../src/patch.ts","../../src/hash.ts","../../src/workflows.ts","../../src/policy.ts","../../src/create-harness.ts"],"names":["result","__dirname"],"mappings":";;;;;;;;AAiEA,IAAM,iBAAA,GAAuC,OAAO,IAAA,KAAS,IAAA,CAAK,EAAA;AAOlE,eAAsB,YAAY,KAAA,EAAqD;AACrF,EAAA,MAAM,EAAE,OAAA,EAAS,MAAA,EAAQ,UAAU,WAAA,EAAa,aAAA,EAAe,gBAAe,GAAI,KAAA;AAClF,EAAA,MAAM,QAAA,GAAqB,QAAQ,OAAA,CAAQ,QAAA;AAE3C,EAAA,MAAM,UAAA,GAAa,KAAK,GAAA,EAAI;AAC5B,EAAA,MAAM,YAAA,GAA0C,EAAE,GAAI,cAAA,IAAkB,EAAC,EAAG;AAC5E,EAAA,MAAM,eAAiC,EAAC;AACxC,EAAA,MAAM,OAAA,GAAU,eAAe,EAAC;AAChC,EAAA,MAAM,WAAW,aAAA,IAAiB,iBAAA;AAElC,EAAA,KAAA,MAAW,KAAA,IAAS,SA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AAA,EAAY;AAAA,EAC5D;AAEA,EAAA,OAAO,aAAA,CAAc;AAAA,IACnB,GAAG,aAAA;AAAA,IACH,cAAA,EAAgB,QAAA,CAAS,cAAA,IAAkB,IAAA,CAAK,cAAA;AAAA,IAChD,SAAA,EAAW;AAAA,GACZ,CAAA;AACH","file":"types-public.js","sourcesContent":["// packages/ui-gen/src/run-workflow.ts\n//\n// Workflow executor. Runs phases sequentially; within a phase, tasks run in\n// parallel (Promise.all). Each task produces a named output that downstream\n// tasks can read from context.priorResults.\n//\n// Generic DAG executor — zero LLM coupling, zero environment/profile\n// gating. Re-exported via `@ggui-ai/ui-gen/harness` alongside the\n// Harness type vocabulary.\n//\n// Scope:\n// - Generic execution machinery — drives the DAG, doesn't know how to\n// run individual tasks. Task handlers are pluggable via the taskRunners\n// parameter, keyed by task.id (or a fallback).\n// - Single-pass / staged / staged-concurrent all work under one executor.\n// - No LLM coupling here — that belongs to the specific task runners the\n// caller registers.\n//\n// Failure semantics:\n// - If any task in a phase throws, the phase is aborted and the error\n// propagates out of runWorkflow. The caller owns the retry policy.\n// - If any task returns { error }, the phase completes but the workflow\n// result carries the error; the caller decides whether to continue.\n\nimport type { DataContract, JsonValue } from \"@ggui-ai/protocol\";\nimport type { Harness, Task, TaskContext, Workflow } from \"./harness/types-public.js\";\n\n/** Called by the executor to run a single task. One of these per task.id. */\nexport type TaskRunner = (task: Task, ctx: TaskContext) => Promise<JsonValue>;\n\n/** Fallback runner used when no task-specific runner is registered. */\nexport type DefaultTaskRunner = (task: Task, ctx: TaskContext) => Promise<JsonValue>;\n\nexport interface RunWorkflowInput {\n readonly harness: Harness;\n readonly prompt: string;\n readonly contract: DataContract;\n /** Task runners by task.id. Fallback to defaultRunner for unregistered ids. */\n readonly taskRunners?: Readonly<Record<string, TaskRunner>>;\n /** Runner invoked when no task.id-specific runner is registered. */\n readonly defaultRunner?: DefaultTaskRunner;\n /** Initial context (rarely used — mostly for resume/recovery). */\n readonly initialResults?: Readonly<Record<string, JsonValue>>;\n}\n\nexport interface PhaseRunResult {\n readonly phaseId: string;\n readonly taskResults: ReadonlyArray<{\n readonly taskId: string;\n readonly outputName: string;\n readonly output: JsonValue;\n readonly durationMs: number;\n }>;\n readonly durationMs: number;\n}\n\nexport interface WorkflowRunResult {\n readonly workflowId: string;\n readonly phases: readonly PhaseRunResult[];\n /** Final merged results map — task outputs keyed by outputName. */\n readonly results: Readonly<Record<string, JsonValue>>;\n readonly durationMs: number;\n}\n\n/** No-op default runner — returns the task id as its output. Tests can swap. */\nconst noopDefaultRunner: DefaultTaskRunner = async (task) => task.id;\n\n/**\n * Execute a workflow. Phases run sequentially; tasks within a phase run in\n * parallel via Promise.all. Task outputs accumulate into priorResults and\n * are passed to subsequent phases via the TaskContext.\n */\nexport async function runWorkflow(input: RunWorkflowInput): Promise<WorkflowRunResult> {\n const { harness, prompt, contract, taskRunners, defaultRunner, initialResults } = input;\n const workflow: Workflow = harness.process.workflow;\n\n const startTotal = Date.now();\n const priorResults: Record<string, JsonValue> = { ...(initialResults ?? {}) };\n const phaseResults: PhaseRunResult[] = [];\n const runners = taskRunners ?? {};\n const fallback = defaultRunner ?? noopDefaultRunner;\n\n for (const phase of workflow.phases) {\n const phaseStart = Date.now();\n\n const ctx: TaskContext = {\n harness,\n priorResults: { ...priorResults },\n classification: harness.classification,\n prompt,\n contract,\n };\n\n const taskPromises = phase.tasks.map(async (task) => {\n const taskStart = Date.now();\n const runner = runners[task.id] ?? fallback;\n const output = await runner(task, ctx);\n return {\n taskId: task.id,\n outputName: task.outputName,\n output,\n durationMs: Date.now() - taskStart,\n };\n });\n\n const taskResults = await Promise.all(taskPromises);\n\n // Merge outputs into priorResults for the next phase.\n for (const tr of taskResults) {\n priorResults[tr.outputName] = tr.output;\n }\n\n phaseResults.push({\n phaseId: phase.id,\n taskResults,\n durationMs: Date.now() - phaseStart,\n });\n }\n\n return {\n workflowId: workflow.id,\n phases: phaseResults,\n results: { ...priorResults },\n durationMs: Date.now() - startTotal,\n };\n}\n","/**\n * Live validator-tier trace sink — devtools introspection of every\n * `runCheck()` invocation the harness performs.\n *\n * **Distinct from {@link LlmTraceSink}, {@link TelemetrySink}, and\n * {@link AuditSink}.**\n * - **LLM trace** (sibling) = devtools-only ring buffer of LLM call\n * payloads (system + user prompt, tools, completion, tokens).\n * Answers \"what did the LLM see / say?\".\n * - **Telemetry** (mcp-server-core) = ops signals (`pair.completed`,\n * `render.duration_ms`). Lossy. Flat scalars.\n * - **Audit** (mcp-server-core) = compliance log of privileged\n * mutations. Durable.\n * - **Validator trace** (this) = devtools-only ring buffer of every\n * `runCheck()` call's full validator-tier breakdown — which axis /\n * tier / runtime-render / LLM checks fired, what each returned\n * (pass/fail/warn issues with description, fix, line, severity).\n * Answers \"which check failed, and what did the LLM emit?\".\n *\n * **Why module-level registry instead of constructor injection.** Same\n * argument as the LLM trace sink — `runCheck()` is called from multiple\n * orchestrator entrypoints (`runHarness`, `run-eval-round`) across the\n * harness package; threading a sink through every call site for a\n * devtools-only surface isn't worth the churn. The ggui server is\n * single-process per CLI invocation; a hosted runtime isolates per\n * request via a process pool.\n *\n * **Default = no sink.** When unset, `runCheck` emits nothing and spends\n * no CPU formatting events. Passing `null` removes a previously\n * registered sink.\n */\nimport type { Classification } from \"../classifier/axes.js\";\nimport type { EvalIssue } from \"../evaluation/types-public.js\";\n\n/**\n * One `runCheck()` invocation. Emitted **after** all tiers complete\n * (success or partial — even when one tier throws, the others ran and\n * we surface what we have). Single event per call.\n */\nexport interface ValidatorTraceEvent {\n /** Random per-event ID. */\n readonly id: string;\n /** Epoch ms when `runCheck` was entered. */\n readonly at: number;\n /** Epoch ms when `runCheck` returned. */\n readonly endedAt: number;\n /** `endedAt - at` — convenience. */\n readonly durationMs: number;\n /** Harness fingerprint that drove these checks. */\n readonly harnessId: string;\n /** Classification axes that produced the harness — useful when the\n * operator asks \"why did this axis-check fire?\". */\n readonly classification: Classification;\n /** Workflow that produced the source-under-check. */\n readonly workflowId: string;\n /** Was a non-null compiledCode fed in? When false, runCheck short-\n * circuits to an empty result — surfaced for transparency. */\n readonly hadCompiledCode: boolean;\n /** Was the runtime-render probe deliberately skipped? Mirrors the\n * `skipRuntimeRender` input flag. */\n readonly skippedRuntimeRender: boolean;\n /** Per-tier issue counts and which check ids fired. */\n readonly summary: {\n readonly totalIssues: number;\n readonly axisIssues: number;\n readonly tierIssues: number;\n readonly llmIssues: number;\n readonly runtimeRenderIssues: number;\n readonly firedCheckIds: readonly string[];\n };\n /** Every issue emitted across all tiers. Carries description + fix +\n * line + severity + tier + category — the full per-issue payload the\n * validator UI renders into a per-tier breakdown. */\n readonly issues: readonly EvalIssue[];\n /** Source under check — capped at ~16KB. Operators expanding a card\n * want to see what failed; longer sources are truncated with a\n * trailing marker so the UI shows the truncation honestly. */\n readonly sourceCode?: string;\n /** Original prompt — useful when \"this passed eval but doesn't match\n * the request\" comes up in operator triage. */\n readonly prompt?: string;\n /** Set when `runCheck` itself threw before completing. The event is\n * still emitted (devtools want to see partial / failed runs). */\n readonly error?: { readonly message: string };\n}\n\n/**\n * Sink that receives one event per `runCheck()` invocation. Same\n * contract as {@link LlmTraceSink} — implementations MUST be sync +\n * non-throwing. Buffer + drop or fan out to a queue inside the\n * implementation.\n */\nexport interface ValidatorTraceSink {\n emit(event: ValidatorTraceEvent): void;\n}\n\nlet activeSink: ValidatorTraceSink | null = null;\n\n/**\n * Register the active sink. Pass `null` to remove. Subsequent\n * {@link emitValidatorTraceEvent} calls dispatch to this sink.\n */\nexport function setValidatorTraceSink(sink: ValidatorTraceSink | null): void {\n activeSink = sink;\n}\n\n/** Read the active sink. Mostly for tests. */\nexport function getValidatorTraceSink(): ValidatorTraceSink | null {\n return activeSink;\n}\n\n/**\n * Internal — used by `runCheck`. No-op when no sink is registered.\n * Swallows sink-thrown errors (a broken devtools sink must not break\n * generation).\n */\nexport function emitValidatorTraceEvent(event: ValidatorTraceEvent): void {\n const sink = activeSink;\n if (!sink) return;\n try {\n sink.emit(event);\n } catch {\n // Devtools sink is allowed to be buggy — generation must not die.\n }\n}\n\n/**\n * Truncate a source string to ~16KB so a runaway component doesn't\n * blow the per-event memory budget. Adds a visible truncation marker.\n */\nexport function truncateSourceForTrace(source: string): string {\n const cap = 16 * 1024;\n if (source.length <= cap) return source;\n return source.slice(0, cap) + \"\\n\\n/* … truncated for devtools trace … */\";\n}\n\n/**\n * Crockford-style random ID. Same approach as the LLM trace sink —\n * dep-free for any runtime the harness might run in.\n */\nexport function newValidatorTraceId(): string {\n return (\n Date.now().toString(36) +\n Math.random().toString(36).slice(2, 10)\n );\n}\n","// packages/ui-gen/src/run-check.ts\n//\n// Post-workflow evaluation stage. Runs every check registered on a harness's\n// CheckLeg against produced source and returns a flat issue list.\n//\n// Pure orchestration — iterates the harness's CheckLeg and runs each\n// check. Check BODIES (axis-check registry entries, tier-0 checks, LLM\n// evaluator, runtime-render adapter) are injected at harness\n// construction.\n//\n// Scope:\n// - Runs axisChecks (already-filtered at createHarness time).\n// - Runs tierChecks (deterministic, no LLM).\n// - Delegates LLM evaluation to harness.check.llmEvaluator when present.\n// - Delegates runtime-render to harness.check.runtimeRender when present.\n\nimport type { DataContract, JsonObject } from \"@ggui-ai/protocol\";\nimport type { EvalIssue, AxisCheckInput } from \"./evaluation/types-public.js\";\nimport type { CheckLeg, Harness } from \"./harness/types-public.js\";\nimport {\n emitValidatorTraceEvent,\n newValidatorTraceId,\n truncateSourceForTrace,\n} from \"./harness/validator-trace-sink.js\";\n\nexport interface RunCheckInput {\n readonly sourceCode: string;\n readonly compiledCode: string | null;\n readonly contract?: DataContract;\n readonly prompt: string;\n readonly harness: Harness;\n /**\n * Optional fixture props (e.g., from a benchmark commit's `props` field).\n * Forwarded to runtimeRender for schema-first mockup synthesis.\n */\n readonly fixtureProps?: JsonObject;\n /**\n * When true, skip the runtime-render probe even if the harness has one.\n * Used by the eval-round runner to keep the probe (~500ms-2s) off the\n * per-turn hot path; the runner runs the probe ONCE at exit-decision\n * time via `harness.check.runtimeRender.run` directly.\n */\n readonly skipRuntimeRender?: boolean;\n}\n\nexport interface CheckResult {\n readonly issues: readonly EvalIssue[];\n readonly axisIssueCount: number;\n readonly tierIssueCount: number;\n readonly llmIssueCount: number;\n readonly runtimeRenderIssueCount: number;\n readonly firedCheckIds: readonly string[];\n}\n\n/**\n * Run every check on a CheckLeg against produced source. Returns all issues\n * with per-source counts for telemetry.\n *\n * Pre-filtering invariant: `check.axisChecks` already only contains checks\n * whose `matches()` gate passed at createHarness time, so this function\n * does no re-matching — it just iterates and runs.\n */\nexport async function runCheck(input: RunCheckInput): Promise<CheckResult> {\n const { harness, sourceCode, compiledCode, contract, prompt } = input;\n const check: CheckLeg = harness.check;\n const startedAt = Date.now();\n\n if (compiledCode === null) {\n const result: CheckResult = {\n issues: [],\n axisIssueCount: 0,\n tierIssueCount: 0,\n llmIssueCount: 0,\n runtimeRenderIssueCount: 0,\n firedCheckIds: [],\n };\n // Emit a trace event even for the no-compile short-circuit so the\n // devtools UI sees the call ran (and can show \"compile failed →\n // checks skipped\").\n const endedAt = Date.now();\n emitValidatorTraceEvent({\n id: newValidatorTraceId(),\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n harnessId: harness.id,\n classification: harness.classification,\n workflowId: harness.process.workflow.id,\n hadCompiledCode: false,\n skippedRuntimeRender: input.skipRuntimeRender ?? false,\n summary: {\n totalIssues: 0,\n axisIssues: 0,\n tierIssues: 0,\n llmIssues: 0,\n runtimeRenderIssues: 0,\n firedCheckIds: [],\n },\n issues: [],\n sourceCode: truncateSourceForTrace(sourceCode),\n prompt,\n });\n return result;\n }\n\n const issues: EvalIssue[] = [];\n const firedIds: string[] = [];\n\n // ── Axis checks (deterministic, pre-gated on harness) ─────────────────\n const axisInput: AxisCheckInput = {\n sourceCode,\n compiledCode,\n contract: contract,\n originalPrompt: prompt,\n classification: harness.classification,\n };\n let axisIssueCount = 0;\n const seenAxisIds = new Set<string>();\n for (const axisCheck of check.axisChecks) {\n if (seenAxisIds.has(axisCheck.id)) continue;\n seenAxisIds.add(axisCheck.id);\n firedIds.push(axisCheck.id);\n const axisIssues = axisCheck.run(axisInput);\n issues.push(...axisIssues);\n axisIssueCount += axisIssues.length;\n }\n\n // ── Tier checks (deterministic, harness-owned) ────────────────────────\n let tierIssueCount = 0;\n for (const tierCheck of check.tierChecks) {\n firedIds.push(tierCheck.id);\n const tierIssues = await tierCheck.run({ sourceCode, compiledCode });\n issues.push(...tierIssues);\n tierIssueCount += tierIssues.length;\n }\n\n // ── Runtime render check (deterministic, ~50-1000ms warm/cold) ────────\n // 2026-04-27: probe runs ONLY when prior cheap checks (axis + tier)\n // produced no tier-0 failures. Rationale: probe is the \"does this\n // actually work at runtime\" gate — wasting ~50-1000ms probing a\n // component the deterministic checks already rejected adds latency\n // with no signal (the LLM is going to fix self-check first anyway,\n // and probe issues on broken-self-check code are noise, not\n // actionable feedback).\n //\n // When axis/tier are clean and probe finds wiring bugs (action not\n // wired, useStream subscribed but never read, prop never rendered),\n // those issues feed back through the same `issues` channel as\n // self-check failures — coding agent gets one more turn with the\n // probe diagnostic. Goal: 0 probe failures on success path.\n let runtimeRenderIssueCount = 0;\n if (check.runtimeRender && !input.skipRuntimeRender) {\n const cheapTier0Failures = issues.filter(\n i => i.result === \"fail\" && (i.tier === 0 || i.tier === undefined),\n ).length;\n if (cheapTier0Failures === 0) {\n const outcome = await check.runtimeRender.run({\n sourceCode,\n compiledCode,\n contract,\n fixtureProps: input.fixtureProps,\n });\n // Only a probe that actually executed counts as a fired check —\n // an infra-skipped / not-applicable outcome carries no evidence\n // and must not appear in `firedCheckIds` as if it gated anything.\n if (outcome.status === \"ran\") {\n firedIds.push(check.runtimeRender.id);\n issues.push(...outcome.issues);\n runtimeRenderIssueCount = outcome.issues.length;\n }\n }\n }\n\n // ── LLM evaluator (optional, async) ───────────────────────────────────\n let llmIssueCount = 0;\n if (check.llmEvaluator && contract) {\n firedIds.push(check.llmEvaluator.id);\n const llmIssues = await check.llmEvaluator.run({\n sourceCode,\n compiledCode,\n contract,\n prompt,\n });\n issues.push(...llmIssues);\n llmIssueCount = llmIssues.length;\n }\n\n const result: CheckResult = {\n issues,\n axisIssueCount,\n tierIssueCount,\n llmIssueCount,\n runtimeRenderIssueCount,\n firedCheckIds: firedIds,\n };\n\n // Emit one validator-trace event capturing the full per-tier\n // breakdown. Devtools-only — no-op when no sink registered (see\n // validator-trace-sink.ts).\n const endedAt = Date.now();\n emitValidatorTraceEvent({\n id: newValidatorTraceId(),\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n harnessId: harness.id,\n classification: harness.classification,\n workflowId: harness.process.workflow.id,\n hadCompiledCode: true,\n skippedRuntimeRender: input.skipRuntimeRender ?? false,\n summary: {\n totalIssues: issues.length,\n axisIssues: axisIssueCount,\n tierIssues: tierIssueCount,\n llmIssues: llmIssueCount,\n runtimeRenderIssues: runtimeRenderIssueCount,\n firedCheckIds: firedIds,\n },\n issues,\n sourceCode: truncateSourceForTrace(sourceCode),\n prompt,\n });\n\n return result;\n}\n","// packages/ui-gen/src/run-harness.ts\n//\n// End-to-end orchestration: run a harness's workflow to produce source,\n// then run the check leg on the result. Owns retry policy (derive new\n// harness + re-run on failure, up to harness.process.retry.maxIterations).\n//\n// Combines runWorkflow + runCheck + the derive loop — the top of the\n// orchestration spine. Re-exported via `@ggui-ai/ui-gen/harness`\n// alongside runWorkflow + runCheck.\n//\n// Shape:\n// for iteration in 1..maxIterations:\n// workflowResult = await runWorkflow(harness, ctx, taskRunners)\n// source = workflowResult.results.source\n// if !source: return { ok: false, reason: \"no source produced\" }\n// checkResult = await runCheck(harness, source)\n// if passingThreshold(checkResult): return { ok: true, source, ... }\n// harness = harness.derive(decideRevision(harness, checkResult))\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { Harness } from \"./harness/types-public.js\";\nimport { runWorkflow, type TaskRunner, type WorkflowRunResult } from \"./run-workflow.js\";\nimport { runCheck, type CheckResult } from \"./run-check.js\";\n\nexport interface RunHarnessInput {\n readonly harness: Harness;\n readonly prompt: string;\n readonly contract: DataContract;\n readonly taskRunners: Readonly<Record<string, TaskRunner>>;\n readonly compile?: (source: string) => Promise<string | null>;\n readonly passes?: (result: CheckResult) => boolean;\n readonly maxIterations?: number;\n /**\n * Skip runCheck() entirely — for callers that have already evaluated\n * the source themselves and don't want the duplicate work. When true,\n * the iteration record's checkResult is empty and `passes` is not\n * consulted; the iteration is treated as passed unconditionally.\n *\n * Used by dispatchGeneration during the runHarness migration: the\n * closure-based generate runner does its own multi-round eval inside\n * the workflow, so re-running runCheck here would re-fire LLM + visual\n * eval needlessly (~5s wasted per generation).\n */\n readonly skipCheck?: boolean;\n}\n\nexport type RunHarnessReason =\n | \"passed\"\n | \"no-source\"\n | \"compile-failed\"\n | \"max-iterations\";\n\nexport interface IterationRecord {\n readonly iteration: number;\n readonly harnessId: string;\n readonly workflowId: string;\n readonly source: string | null;\n readonly compiled: string | null;\n readonly workflowDurationMs: number;\n readonly checkDurationMs: number;\n readonly issueCount: number;\n readonly firedCheckIds: readonly string[];\n}\n\nexport interface RunHarnessResult {\n readonly ok: boolean;\n readonly reason: RunHarnessReason;\n readonly finalHarness: Harness;\n readonly finalSource: string | null;\n readonly finalCompiled: string | null;\n readonly finalCheck: CheckResult | null;\n readonly iterations: readonly IterationRecord[];\n readonly durationMs: number;\n}\n\nconst defaultPasses = (r: CheckResult): boolean =>\n r.issues.every((i) => i.result !== \"fail\");\n\n/**\n * Run harness end-to-end: workflow → compile → check → derive-on-fail.\n *\n * Caller must supply taskRunners — at minimum, a runner for each task in\n * the workflow's phases. The `generate` task (single_pass) should return\n * the produced source as a string.\n */\nexport async function runHarness(input: RunHarnessInput): Promise<RunHarnessResult> {\n const {\n harness: initialHarness,\n prompt,\n contract,\n taskRunners,\n compile,\n passes = defaultPasses,\n maxIterations: explicitMax,\n skipCheck = false,\n } = input;\n\n const maxIterations = explicitMax ?? initialHarness.process.retry.maxIterations;\n const start = Date.now();\n const iterations: IterationRecord[] = [];\n\n let harness = initialHarness;\n let lastSource: string | null = null;\n let lastCompiled: string | null = null;\n let lastCheck: CheckResult | null = null;\n\n for (let i = 1; i <= maxIterations; i++) {\n const workflowResult: WorkflowRunResult = await runWorkflow({\n harness,\n prompt,\n contract,\n taskRunners,\n });\n\n const source = (workflowResult.results.source ?? null) as string | null;\n let compiled: string | null = null;\n if (source && compile) {\n compiled = await compile(source);\n } else if (source && !compile) {\n compiled = source;\n }\n\n // Compile failure is a hard fail. We must NOT fall through to runCheck()\n // — its compile-null branch returns an empty issue set, which the default\n // pass predicate would happily accept as \"no failures = passed\". Bail out\n // explicitly so the iteration record reflects the actual failure mode.\n const compileFailed = source !== null && compile !== undefined && compiled === null;\n\n const checkStart = Date.now();\n const checkResult = source && !compileFailed && !skipCheck\n ? await runCheck({ harness, sourceCode: source, compiledCode: compiled, contract, prompt })\n : { issues: [], axisIssueCount: 0, tierIssueCount: 0, llmIssueCount: 0, runtimeRenderIssueCount: 0, firedCheckIds: [] };\n const checkDurationMs = Date.now() - checkStart;\n\n iterations.push({\n iteration: i,\n harnessId: harness.id,\n workflowId: harness.process.workflow.id,\n source,\n compiled,\n workflowDurationMs: workflowResult.durationMs,\n checkDurationMs,\n issueCount: checkResult.issues.length,\n firedCheckIds: checkResult.firedCheckIds,\n });\n\n lastSource = source;\n lastCompiled = compiled;\n lastCheck = checkResult;\n\n if (!source) {\n return buildResult({\n ok: false,\n reason: \"no-source\",\n finalHarness: harness,\n finalSource: null,\n finalCompiled: null,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (compileFailed) {\n // Don't keep iterating on a compile failure unless the harness has a\n // derive policy that would change codegen — for now, treat it as a\n // terminal signal, the same way no-source is terminal. A future PR can\n // make this iteration-aware once derive policies exist that target it.\n return buildResult({\n ok: false,\n reason: \"compile-failed\",\n finalHarness: harness,\n finalSource: source,\n finalCompiled: null,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (passes(checkResult)) {\n return buildResult({\n ok: true,\n reason: \"passed\",\n finalHarness: harness,\n finalSource: source,\n finalCompiled: compiled,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (i < maxIterations) {\n // Default revision: re-run same harness. Real deriders (planner,\n // runtime fallback, classification swap) plug in via harness.process.retry\n // or an explicit revision function (future API).\n harness = harness.derive({});\n }\n }\n\n return buildResult({\n ok: false,\n reason: \"max-iterations\",\n finalHarness: harness,\n finalSource: lastSource,\n finalCompiled: lastCompiled,\n finalCheck: lastCheck,\n iterations,\n start,\n });\n}\n\nfunction buildResult(args: {\n ok: boolean;\n reason: RunHarnessReason;\n finalHarness: Harness;\n finalSource: string | null;\n finalCompiled: string | null;\n finalCheck: CheckResult | null;\n iterations: IterationRecord[];\n start: number;\n}): RunHarnessResult {\n return {\n ok: args.ok,\n reason: args.reason,\n finalHarness: args.finalHarness,\n finalSource: args.finalSource,\n finalCompiled: args.finalCompiled,\n finalCheck: args.finalCheck,\n iterations: args.iterations,\n durationMs: Date.now() - args.start,\n };\n}\n","// packages/ui-gen/src/fragments/render.ts\n//\n// Render-axis fragments. One per RenderShape. Kept minimal — the stable\n// prefix already covers primitives + design tokens. These only add the\n// per-shape layout pattern the LLM needs to commit to up front.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const renderFragments: Record<string, HarnessFragment> = {\n static: {\n axis: \"render\",\n value: \"static\",\n cacheTier: \"axisDelta\",\n // Static = single entity detail. Stable prefix already covers the\n // obvious pattern (Card + Stack + Heading + fields). No prompt text\n // here keeps low-risk fixtures fast.\n },\n list: {\n axis: \"render\",\n value: \"list\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: list\\nVertical column of items. Each item is a <Card> with <Row> + <Text>. Use key={item.id} on each item. Do not paginate unless the contract has a fetch tool with cursor/offset.\",\n },\n grid: {\n axis: \"render\",\n value: \"grid\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: grid\\n2D tile layout. Use <CardGrid> or CSS `display: grid` with `grid-template-columns: repeat(N, 1fr)`. If items carry row/col fields, position each tile at (row, col). Do not scroll horizontally.\",\n },\n spatial: {\n axis: \"render\",\n value: \"spatial\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: spatial\\nGeo/coord-positioned items. Use absolute positioning inside a relative container, or a map primitive if available. Normalize coords to the container's bounds. Treat lat/lng as y/x, not strings.\",\n },\n timeline: {\n axis: \"render\",\n value: \"timeline\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: timeline\\nGroup items by day (or other temporal bucket). Render a sticky date header per group, then the grouped items. Sort newest-first unless the contract says otherwise. Memoize the grouping with useMemo.\",\n },\n chart: {\n axis: \"render\",\n value: \"chart\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: chart\\nNumeric → visual. Render with inline SVG (no chart library). Compute the viewBox from data min/max. Add axis labels and one value label on the latest/peak point. Keep it readable on a 400px container.\",\n },\n \"master-detail\": {\n axis: \"render\",\n value: \"master-detail\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: master-detail\\nSplit view: list on one side, detail panel on the other. Track `selectedId` in useState, default to the first item's id. Desktop = side-by-side; mobile/chat shell = stacked with back button.\",\n },\n};\n","// packages/ui-gen/src/fragments/state.ts\n//\n// State-axis fragments. This is the most error-prone axis — \"merge\" in\n// particular collapses into append-only bugs without explicit guidance.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const stateFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"state\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n // Pure props → JSX. Stable prefix is enough — no useState call at all.\n },\n \"ui-affordance\": {\n axis: \"state\",\n value: \"ui-affordance\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: ui-affordance\\nLocal UI state for filter text / selected id / active tab / quantity. Use useState with a sensible default. Do NOT mirror props into state — read props directly and track only the affordance value.\",\n },\n merge: {\n axis: \"state\",\n value: \"merge\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: merge (live entity reconciliation)\\n1. Seed `const [items, setItems] = useState(props.items ?? [])` AND re-seed on prop change: `useEffect(() => setItems(props.items ?? []), [props.items])` — a `ggui_amend` repaint must move the list.\\n2. On stream updates: `setItems(prev => prev.map(it => it.id === event.id ? { ...it, ...event } : it))` — merge by id, do NOT append.\\n3. Memoize derived views (grouping/sorting/filtering) with useMemo.\\n4. Per-item actions pass `{ id, ... }` in the payload.\\n5. Never push the stream payload into an append-only list unless realtime=append.\",\n boilerplateMarker: [\n \"\",\n \" // ── Live entity state (merge-by-id) ──\",\n \" // useState(props.items ?? []); re-seed via useEffect on [props.items]; merge stream events by item.id; never append.\",\n \"\",\n ].join(\"\\n\"),\n },\n payload: {\n axis: \"state\",\n value: \"payload\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: payload (form assembly)\\nAccumulate form fields in a single state object. Validate on blur or on submit — do NOT block keystrokes. The submit action fires once, with the assembled payload.\",\n boilerplateMarker: [\n \"\",\n \" // ── Form payload ──\",\n \" // useState<FormData> seeded with defaults from props or empty; validate on submit.\",\n \"\",\n ].join(\"\\n\"),\n },\n draft: {\n axis: \"state\",\n value: \"draft\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: draft (in-place editor)\\nEdit one item at a time. Track `draft` as a separate useState (not mutating the source). Support cancel (discard draft) and save (commit draft → fire action).\",\n },\n};\n","// packages/ui-gen/src/fragments/writes.ts\n//\n// Writes-axis fragments. Covers both WriteShape (what) and WriteTrigger (how).\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const writeFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"writes\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n },\n commit: {\n axis: \"writes\",\n value: \"commit\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: commit\\nOne action with a small payload (e.g., addToCart). Wire useAction on a single Button. Do not block the UI on completion — this is fire-and-forget.\",\n },\n \"multi-commit\": {\n axis: \"writes\",\n value: \"multi-commit\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: multi-commit\\nMultiple unrelated single-commit actions (e.g., cancel / change destination / contact driver). Each action has its own Button. No shared payload assembly.\",\n },\n \"per-item\": {\n axis: \"writes\",\n value: \"per-item\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: per-item\\nEach item in the entity list has its own action button(s). The payload must include the item's id. Example: `onClick={() => toggle({ id: item.id, completed: !item.completed })}`.\",\n boilerplateMarker: [\n \"\",\n \" // ── Per-item actions ──\",\n \" // Pass {id, ...} in the payload; wire to a Button inside each item's card.\",\n \"\",\n ].join(\"\\n\"),\n },\n submit: {\n axis: \"writes\",\n value: \"submit\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: submit\\nTerminal form submit. One action fires with the full assembled payload at the end. Disable the submit button while pending and after success.\",\n },\n compose: {\n axis: \"writes\",\n value: \"compose\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: compose (cross-entity action)\\nOne trigger references ids from two or more entity lists (e.g., {eventId, calendarId}). Track both selections in local state. Only enable the trigger once both are chosen.\",\n },\n};\n\n// WriteTrigger is a separate axis but lives in the same file for locality.\nexport const writeTriggerFragments: Record<string, HarnessFragment> = {\n click: {\n axis: \"writeTrigger\",\n value: \"click\",\n cacheTier: \"axisDelta\",\n // Default case — covered by stable prefix.\n },\n drag: {\n axis: \"writeTrigger\",\n value: \"drag\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: drag\\nDrag-drop interaction. Use HTML5 drag events (onDragStart, onDragOver, onDrop) on the item and drop zones. Track the dragged item id in useState. Set data-ggui-draggable on draggable elements. Do NOT pull in an external dnd library.\",\n boilerplateMarker: [\n \"\",\n \" // ── Drag state ──\",\n \" // Track the dragged item id; fire the action on drop with {id, destination}.\",\n \"\",\n ].join(\"\\n\"),\n },\n swipe: {\n axis: \"writeTrigger\",\n value: \"swipe\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: swipe\\nTouch gesture → one of N actions. Use onTouchStart/onTouchMove/onTouchEnd. Also expose fallback Buttons so desktop users can trigger the same actions by click.\",\n },\n keystroke: {\n axis: \"writeTrigger\",\n value: \"keystroke\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: keystroke\\nKeyboard shortcut. Attach onKeyDown to the container (with tabIndex={0}) or use a window listener inside useEffect with cleanup. Document visible shortcuts in the UI.\",\n },\n auto: {\n axis: \"writeTrigger\",\n value: \"auto\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: auto\\nEffect-driven. Use useEffect with a debounce (setTimeout + clearTimeout). Do not fire the action on every keystroke.\",\n },\n};\n","// packages/ui-gen/src/fragments/realtime.ts\n//\n// Realtime-axis fragments. Stream semantics drive whether you merge,\n// append, replace, or do nothing. \"mixed\" needs per-event kind dispatch.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const realtimeFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"realtime\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n },\n merge: {\n axis: \"realtime\",\n value: \"merge\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: merge\\nStream events carry an id; merge into LOCAL STATE. Subscribing alone is not enough — the local list must update on each event for the DOM to re-render.\\n\\n```tsx\\nconst stream = useStream<UpdateT>('streamName');\\nconst [items, setItems] = useState(props.items);\\nuseEffect(() => setItems(props.items), [props.items]); // re-seed on ggui_amend repaint — props stay the source of truth\\nuseEffect(() => {\\n if (!stream.latest) return;\\n setItems((prev) => prev.map((it) => it.id === stream.latest!.id ? { ...it, ...stream.latest } : it));\\n}, [stream.latest]);\\n// Render `items.map(...)` — NOT props.items, NOT stream.all.\\n```\\n\\nNever append — stream=merge means the entity already exists locally.\",\n },\n append: {\n axis: \"realtime\",\n value: \"append\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: append\\nStream events are new entities; APPEND to local state. Subscribing alone is not enough — the local list must update for the DOM to re-render.\\n\\n```tsx\\nconst stream = useStream<EventT>('streamName');\\nconst [items, setItems] = useState(props.items);\\nuseEffect(() => setItems(props.items), [props.items]); // re-seed on ggui_amend repaint — props stay the source of truth\\nuseEffect(() => {\\n if (!stream.latest) return;\\n setItems((prev) => [...prev, stream.latest!]);\\n}, [stream.latest]);\\n// Render `items.map(...)` — NOT props.items, NOT stream.all (which accumulates only post-mount).\\n```\\n\\nUse head for newest-first, tail for chat-style. Cap list length if needed. Do not dedupe unless the contract guarantees at-most-once.\",\n },\n status: {\n axis: \"realtime\",\n value: \"status\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: status\\nStream replaces a singleton (e.g., marketStatus, rideStatus). `stream.latest` is the current value — bind directly into JSX, no local state needed for the singleton itself:\\n\\n```tsx\\nconst statusStream = useStream<StatusT>('streamName');\\nconst status = statusStream.latest;\\n// Render `<Badge>{status?.state ?? 'loading'}</Badge>`.\\n```\\n\\nIf you also need the timestamp of the last update, derive it from `useEffect` on `statusStream.latest`.\",\n },\n presence: {\n axis: \"realtime\",\n value: \"presence\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: presence\\nEphemeral per-user state (typing, cursors, online). Do NOT persist to a list. Sync into a `Set` and clear entries based on the active flag or a timeout:\\n\\n```tsx\\nconst stream = useStream<{ sender: string; active: boolean }>('streamName');\\nconst [active, setActive] = useState<Set<string>>(new Set());\\nuseEffect(() => {\\n if (!stream.latest) return;\\n setActive((prev) => {\\n const next = new Set(prev);\\n if (stream.latest!.active) next.add(stream.latest!.sender);\\n else next.delete(stream.latest!.sender);\\n return next;\\n });\\n}, [stream.latest]);\\n```\",\n },\n mixed: {\n axis: \"realtime\",\n value: \"mixed\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: mixed\\nMultiple stream channels with DIFFERENT semantics. Each `streamKinds` entry in the contract maps to one of: merge, append, status, presence. Subscribe + sync to local state PER CHANNEL — subscribing alone never re-renders the DOM.\\n\\nExample (chat-interface — message=append, typing=presence):\\n\\n```tsx\\nconst messages = useStream<MessageT>('message');\\nconst typing = useStream<TypingT>('typing');\\nconst [messageList, setMessageList] = useState(props.messages);\\nconst [typingUsers, setTypingUsers] = useState<Set<string>>(new Set());\\n\\nuseEffect(() => setMessageList(props.messages), [props.messages]); // re-seed on ggui_amend repaint\\n\\nuseEffect(() => {\\n if (!messages.latest) return;\\n setMessageList((prev) => [...prev, messages.latest!]);\\n}, [messages.latest]);\\n\\nuseEffect(() => {\\n if (!typing.latest) return;\\n setTypingUsers((prev) => {\\n const next = new Set(prev);\\n if (typing.latest!.active) next.add(typing.latest!.sender);\\n else next.delete(typing.latest!.sender);\\n return next;\\n });\\n}, [typing.latest]);\\n```\\n\\nDo NOT treat all events the same. Do NOT skip the local-state sync — `useStream` alone won't trigger DOM updates of your derived view.\",\n boilerplateMarker: [\n \"\",\n \" // ── Mixed stream handlers ──\",\n \" // One useStream + useEffect+setState per channel — see realtime fragment.\",\n \"\",\n ].join(\"\\n\"),\n },\n};\n","// packages/ui-gen/src/fragments/fetch.ts\n//\n// Fetch-axis fragments. Covers how the component reacts to agent-fetched\n// data — agent-side tools live in `agentCapabilities.tools` (catalog\n// only); the component itself never invokes them directly.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const fetchFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"fetch\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n },\n pagination: {\n axis: \"fetch\",\n value: \"pagination\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: pagination\\nTrack `cursor` (or offset/page) in useState. Expose a 'Load more' Button that calls the tool with the next cursor and appends results. Show a spinner while tool.isPending.\",\n },\n search: {\n axis: \"fetch\",\n value: \"search\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: search\\nDebounced query → tool call. Track `query` in useState; fire the tool inside useEffect after a 300ms debounce. Replace (don't append) results on each call. Guard against stale responses.\",\n },\n \"drill-down\": {\n axis: \"fetch\",\n value: \"drill-down\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: drill-down\\nOn item click, call the tool with the item's id and show the detail. Track `selectedId` and `detail` separately; render a loading placeholder while tool.isPending.\",\n },\n refresh: {\n axis: \"fetch\",\n value: \"refresh\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: refresh\\nUser-triggered re-fetch (e.g., pull-to-refresh or a Refresh button). Re-call the tool with the same args; show a small spinner while pending.\",\n },\n};\n","// packages/ui-gen/src/fragments/layout.ts\n//\n// Layout-axis fragments. Structural composition — how the screen is split.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const layoutFragments: Record<string, HarnessFragment> = {\n single: {\n axis: \"layout\",\n value: \"single\",\n cacheTier: \"axisDelta\",\n },\n \"multi-step\": {\n axis: \"layout\",\n value: \"multi-step\",\n cacheTier: \"axisDelta\",\n // 2026-04-27: anti-pattern warnings added after 6× n=3 benches showed\n // survey-form + onboarding-wizard accounted for 9 of 11 probe FAILs\n // (\"Too many re-renders\" 6×, \"function is not iterable\" 2×, TDZ 1×).\n // All 3 classes trace to the same multi-step-specific anti-patterns\n // below; non-multi-step fixtures had 0 fails across the same benches.\n promptText:\n \"## Layout: multi-step\\n\" +\n \"Wizard. Track `step` in useState (0-indexed). Render \" +\n \"`<Stepper steps={STEPS} current={step} />` as the progress \" +\n \"indicator — do NOT hand-roll a '2 of 4' counter, and do NOT \" +\n \"reach for Tabs/Progress/Breadcrumb. Stepper is display-only: \" +\n \"your Next/Back buttons move `step`. Keep all step state in a \" +\n \"single payload object; do NOT reset previous-step data on \" +\n \"navigation.\\n\\n\" +\n \"### Anti-patterns that crash at runtime — DO NOT do these:\\n\\n\" +\n \"1. **No setState in render body** — causes 'Too many re-renders'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — fires every render, infinite loop\\n\" +\n \"const Form = () => {\\n\" +\n \" const [errors, setErrors] = useState({});\\n\" +\n \" setErrors(validate(values)); // setState in render → loop\\n\" +\n \"};\\n\" +\n \"// ✅ RIGHT — derive with useMemo (no state)\\n\" +\n \"const Form = () => {\\n\" +\n \" const errors = useMemo(() => validate(values), [values]);\\n\" +\n \"};\\n\" +\n \"```\\n\\n\" +\n \"2. **No setState in useEffect with state-derived deps** — also \" +\n \"causes 'Too many re-renders'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — payload identity changes → setIsValid → re-render → ...\\n\" +\n \"useEffect(() => { setIsValid(check(payload)); }, [payload]);\\n\" +\n \"// ✅ RIGHT — useMemo, no setState\\n\" +\n \"const isValid = useMemo(() => check(payload), [payload]);\\n\" +\n \"```\\n\\n\" +\n \"3. **Declare `steps` array as a top-level `const`, NEVER state.** \" +\n \"Default arrays (`fields`, `options`) the same way. Iterating over \" +\n \"an undefined or unstable array throws 'function is not iterable'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — useState('steps array...') is a string, .map crashes\\n\" +\n \"const [steps] = useState('Welcome,Profile,Done');\\n\" +\n \"// ✅ RIGHT — top-level const\\n\" +\n \"const STEPS = ['Welcome', 'Profile', 'Done'] as const;\\n\" +\n \"```\\n\\n\" +\n \"4. **Hooks/`const` declarations come BEFORE any useEffect/\" +\n \"useMemo/useCallback that reads them.** Otherwise: TDZ 'Cannot \" +\n \"access X before initialization'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — useEffect reads `total` before its `const` line\\n\" +\n \"useEffect(() => log(total), [total]);\\n\" +\n \"const total = items.reduce(sum, 0);\\n\" +\n \"// ✅ RIGHT — declare first, read after\\n\" +\n \"const total = items.reduce(sum, 0);\\n\" +\n \"useEffect(() => log(total), [total]);\\n\" +\n \"```\",\n },\n \"master-detail\": {\n axis: \"layout\",\n value: \"master-detail\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Layout: master-detail\\nSplit container: master list on the left/top, detail panel on the right/bottom. Track `selectedId` and show a 'select an item' placeholder in the detail panel when null.\",\n },\n overlay: {\n axis: \"layout\",\n value: \"overlay\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Layout: overlay\\nFloating controls layered on top of content. Use position: absolute with explicit insets. Ensure the overlay does not block critical content (leave a safe area).\",\n },\n modal: {\n axis: \"layout\",\n value: \"modal\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Layout: modal\\nUse the <Modal> primitive. Track `isOpen` in useState. Provide a clear close affordance (X button + clicking backdrop). Trap focus inside the modal.\",\n },\n};\n","// packages/ui-gen/src/fragments/tooling.ts\n//\n// tooling-axis fragments. The contract carries two tooling surfaces:\n//\n// - `agentCapabilities.tools` — catalog of agent-invoked tools the\n// contract references via `actionSpec[*].nextStep` and\n// `streamSpec[*].source.tool`. NO component-side hook surface.\n// - `clientCapabilities.gadgets` — catalog of browser-capability\n// gadget hooks (geolocation, mic, camera, clipboard, file picker,\n// notifications). The component imports + calls these hooks\n// from `@ggui-ai/gadgets` (or the third-party package named in\n// `entry.package`).\n//\n// The `wired` / `client` / `both` axis values map onto these surfaces\n// by what the contract carries; the prompt text steers the LLM toward\n// the correct patterns.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const toolingFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"tooling\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n // Nothing to say — contract carries no agentCapabilities.tools /\n // clientCapabilities.gadgets.\n },\n wired: {\n axis: \"tooling\",\n value: \"wired\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Tooling: agent-side tools (catalog only)\\nThe contract declares `agentCapabilities.tools[X]` for tools the AGENT invokes — the component never calls these directly. References surface via `actionSpec[Y].nextStep = 'X'` (the agent's next-turn hint forwarded on action events) and `streamSpec[Z].source.tool = 'X'` (the runtime polls / subscribes the tool, deliveries land on the stream channel). Author UI controls fire actions via `useAction`; data feeds appear via `useStream`. The `useWiredTool` hook from before 2026-05-11 is RETIRED.\",\n },\n client: {\n axis: \"tooling\",\n value: \"client\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Tooling: gadgets (browser-capability hooks)\\nThe contract declares `clientCapabilities.gadgets[X]` for browser-capability gadget hooks the UI mounts. The boilerplate has pre-emitted a direct import per gadget package — `import { useFoo, useBar } from '<package>';` — above a `// DO NOT EDIT` banner (STDLIB hooks come from `@ggui-ai/gadgets`, third-party hooks from the package on `clientCapabilities.gadgets[*].package`). Call the imported hook inside the component (`const loc = useGeolocation();`) and trigger via `.start()` from a UI control. Read `.value` / `.status` to render. If the agent needs to observe the result, thread `.value` into a `contextSpec` slot or an `actionSpec` payload. Library hooks are UI-owned lifecycle; the agent never invokes them. **KEEP every pre-emitted gadget import — do NOT delete it and do NOT change its package**; self_check rejects the code with `gadget_preservation:<hook>` if a gadget import disappears. The pre-2026-05-11 `useClientTool(name, handler)` shape is RETIRED, as is the `@ggui-ai/client-tools` package name (renamed to `@ggui-ai/gadgets`).\",\n },\n both: {\n axis: \"tooling\",\n value: \"both\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Tooling: both surfaces present\\nThe contract declares BOTH `agentCapabilities.tools` (agent-invoked catalog; referenced via `actionSpec.nextStep` / `streamSpec.source.tool` — NO component hook) AND `clientCapabilities.gadgets` (browser-capability gadget hooks the component direct-imports — the boilerplate pre-emits `import { useCamera } from '@ggui-ai/gadgets';` (STDLIB) or `import { useFoo } from '<package>';` (third-party) above a `// DO NOT EDIT` banner). Don't conflate: agentCapabilities entries are catalog declarations the agent uses, NOT component hooks. clientCapabilities entries DO emit component-side hook calls (e.g., `const cam = useCamera();`).\",\n },\n};\n","// packages/ui-gen/src/fragments/index.ts\n//\n// Public barrel for the `@ggui-ai/ui-gen/fragments` subpath.\n//\n// Stable public surface (what external consumers should build against):\n// - `FRAGMENT_REGISTRY` — the axis-keyed registry\n// - `lookupFragment` — the one-call lookup helper\n// - fragment types — HarnessFragment, ComposedHarness, CacheTier, AxisKey\n//\n// Per-axis fragment records (renderFragments, stateFragments, etc.) are\n// intentionally NOT re-exported here — consumers who genuinely need one\n// can read `FRAGMENT_REGISTRY.render` / `.state` / etc. Keeping the public\n// surface to a single entry point preserves our freedom to reshape the\n// per-axis files without breaking semver.\n\nimport type { AxisKey, HarnessFragment } from \"./types.js\";\nimport { renderFragments } from \"./render.js\";\nimport { stateFragments } from \"./state.js\";\nimport { writeFragments, writeTriggerFragments } from \"./writes.js\";\nimport { realtimeFragments } from \"./realtime.js\";\nimport { fetchFragments } from \"./fetch.js\";\nimport { layoutFragments } from \"./layout.js\";\nimport { toolingFragments } from \"./tooling.js\";\n\nexport type { HarnessFragment, ComposedHarness, CacheTier, AxisKey } from \"./types.js\";\n\nexport const FRAGMENT_REGISTRY: Record<AxisKey, Record<string, HarnessFragment>> = {\n render: renderFragments,\n state: stateFragments,\n writes: writeFragments,\n writeTrigger: writeTriggerFragments,\n realtime: realtimeFragments,\n fetch: fetchFragments,\n layout: layoutFragments,\n tooling: toolingFragments,\n};\n\nexport function lookupFragment(axis: AxisKey, value: string): HarnessFragment | undefined {\n return FRAGMENT_REGISTRY[axis]?.[value];\n}\n","// packages/ui-gen/src/compose.ts\n//\n// Materializes a Classification into prompt sections + boilerplate markers.\n// Sits between the stable prefix (design system docs, pitfalls) and the\n// volatile feedback (eval issues) in the system prompt's cache tiering.\n//\n// Consumes the `./classifier` and `./fragments` subpaths — it's the\n// bridge between an axis vector and the prompt/boilerplate the LLM\n// actually sees.\n\nimport type { Classification } from \"./classifier/axes.js\";\nimport {\n lookupFragment,\n type AxisKey,\n type ComposedHarness,\n type HarnessFragment,\n} from \"./fragments/index.js\";\n\n// Axis processing order inside axisDelta. Puts the most behaviourally\n// consequential axes first so the LLM reads them before scanning details.\nconst AXIS_ORDER: AxisKey[] = [\n \"render\",\n \"layout\",\n \"state\",\n \"writes\",\n \"writeTrigger\",\n \"realtime\",\n \"fetch\",\n \"tooling\",\n];\n\nexport function compose(classification: Classification): ComposedHarness {\n const v = classification.vector;\n const matched: HarnessFragment[] = [];\n\n for (const axis of AXIS_ORDER) {\n const value = v[axis] as string | undefined;\n if (!value) continue;\n const frag = lookupFragment(axis, value);\n if (frag) matched.push(frag);\n }\n\n const promptParts = matched\n .filter((f) => f.promptText && f.promptText.trim().length > 0)\n .map((f) => f.promptText!.trim());\n\n const boilerplateParts = matched\n .filter((f) => f.boilerplateMarker && f.boilerplateMarker.trim().length > 0)\n .map((f) => f.boilerplateMarker!);\n\n return {\n promptText: promptParts.join(\"\\n\\n\"),\n boilerplateSections: boilerplateParts.join(\"\"),\n fragments: matched,\n };\n}\n\nexport type { ComposedHarness };\n","// packages/ui-gen/src/boilerplate/render.ts\n//\n// Loads base.tsx.tmpl + layout files from disk, caches them in memory,\n// and replaces {{MARKER}} placeholders with generated content.\n//\n// Package-private — consumers use `generateBoilerplate()` from\n// `@ggui-ai/ui-gen/boilerplate`; this file is not re-exported.\n\nimport { readFileSync } from 'node:fs';\nimport { resolve, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// `@ggui-ai/ui-gen` ships both `src/` and `dist/` (see package.json `files`).\n// Templates always live at `<pkg-root>/src/boilerplate/templates/` (kept in\n// the published tarball via `files: ['src', 'dist', ...]`). Render.ts gets\n// inlined into multiple dist entrypoints by tsup (`boilerplate.js`,\n// `harness/runtime.js`, `harness/index.js`, …), so `__dirname` varies. We\n// enumerate every reasonable location:\n//\n// - From tsx (`src/boilerplate/render.ts`): `./templates`\n// - Bundled into `dist/boilerplate.js`: `../src/boilerplate/templates`\n// - Bundled into `dist/harness/runtime.js`: `../../src/boilerplate/templates`\n// - Bundled into `dist/harness/coding/X.js`: `../../../src/boilerplate/templates`\n//\n// Step 3 (2026-04-27): the harness cluster ported in from cloud added the\n// `dist/harness/` and `dist/harness/coding/` entrypoints — needed deeper\n// upward walks than the pre-step-3 single-level `dist/`.\nconst TEMPLATE_DIRS = [\n resolve(__dirname, 'templates'),\n resolve(__dirname, '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', '..', 'src', 'boilerplate', 'templates'),\n];\n\nlet baseCache: string | null = null;\nconst layoutCache = new Map<string, string>();\n\nfunction loadBase(): string {\n if (baseCache) return baseCache;\n\n for (const dir of TEMPLATE_DIRS) {\n try {\n baseCache = readFileSync(resolve(dir, 'base.tsx.tmpl'), 'utf-8');\n return baseCache;\n } catch { continue; }\n }\n\n throw new Error('No base.tsx.tmpl found');\n}\n\nfunction loadLayout(shellType: string, screen: string): string {\n const key = `${shellType}-${screen}`;\n if (layoutCache.has(key)) return layoutCache.get(key)!;\n\n // Try exact match, then fallback to universal, then fullscreen-universal\n const candidates = [\n `${shellType}-${screen}.tsx.tmpl`,\n `${shellType}-universal.tsx.tmpl`,\n `fullscreen-universal.tsx.tmpl`, // final fallback\n ];\n\n for (const filename of candidates) {\n for (const dir of TEMPLATE_DIRS) {\n try {\n const content = readFileSync(resolve(dir, 'layouts', filename), 'utf-8');\n layoutCache.set(key, content);\n return content;\n } catch { continue; }\n }\n }\n\n throw new Error(`No layout found for ${key}`);\n}\n\nexport interface BoilerplateMarkers {\n REACT_IMPORT: string;\n ALL_DESIGN: string;\n WIRE_IMPORT: string;\n PROPS_INTERFACE: string;\n ACTION_TYPES: string;\n STREAM_TYPES: string;\n /** `useGguiContext` destructure lines, one per declared `contextSpec`\n * slot. Emitted at the top of the user component body. The runtime\n * owns useState + Provider per slot; the LLM only reads `<slotKey>`\n * and writes via `set<SlotKey>`. Empty when contextSpec is absent or\n * empty. */\n CONTEXT_HOOKS: string;\n WIRE_HOOKS: string;\n AXIS_SECTIONS: string;\n}\n\nexport function renderBoilerplate(\n shellType: string,\n screen: string,\n markers: BoilerplateMarkers,\n): string {\n let template = loadBase();\n const layout = loadLayout(shellType, screen);\n template = template.replace('{{LAYOUT}}', layout);\n\n for (const [key, value] of Object.entries(markers)) {\n template = template.replaceAll(`{{${key}}}`, value);\n }\n\n return template;\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/boilerplate/generate.ts\n//\n// Typed boilerplate generator. Takes a data contract (propsSpec /\n// actionSpec / streamSpec / contextSpec + agentCapabilities.tools +\n// clientCapabilities.gadgets catalogs) and a rendering context\n// (shell + screen) and produces the starting `.tsx` boilerplate the\n// coding agent fills in via apply_changes.\n//\n// `agentCapabilities.tools` entries do NOT emit component hooks. They\n// are catalog declarations the AGENT invokes; component code references\n// them indirectly via `actionSpec.nextStep` (advisory hint surfacing on\n// action events) and `streamSpec.source.tool` (transport-negotiated\n// source).\n//\n// `clientCapabilities.gadgets` entries DO emit component-side gadget\n// plumbing. Gadgets are direct-imported: the generator emits one\n// combined `import { … } from '<package>'` per registered gadget\n// package, above a `// DO NOT EDIT` banner. Hook exports additionally\n// get a pre-emitted `const binding = hook();` call site; component\n// exports are import-only — the LLM renders `<X … />` in the JSX tree\n// itself. The deterministic `gadget_preservation` check rejects the\n// code if a gadget import disappears.\n//\n// Pure function — deterministic, no env reads, no I/O other than\n// `renderBoilerplate` reading the template files.\n\nimport type {\n ActionSpec,\n GadgetDescriptor,\n ContextSpec,\n DataContract,\n JsonObject,\n JsonValue,\n StreamSpec,\n} from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport { renderBoilerplate } from \"./render.js\";\nimport { jsonSchemaTypeToTs } from \"./json-schema-ts.js\";\n\n/** Shell layout modes supported by the boilerplate templates. */\nexport type ShellType = \"chat\" | \"fullscreen\" | \"spatial\";\n\n/** Target screen size. */\nexport type ScreenSize = \"mobile\" | \"tablet\" | \"desktop\" | \"universal\";\n\n// =============================================================================\n// Design-system surface (pre-imported in every boilerplate)\n// =============================================================================\n\nconst ALL_PRIMITIVES = [\n \"Container\",\n \"Card\",\n \"Stack\",\n \"Row\",\n \"Grid\",\n \"Box\",\n \"Divider\",\n \"Spacer\",\n \"Text\",\n \"Heading\",\n \"Button\",\n \"Input\",\n \"TextArea\",\n \"Select\",\n \"Checkbox\",\n \"Toggle\",\n \"RadioGroup\",\n \"Slider\",\n \"Badge\",\n \"Spinner\",\n \"Skeleton\",\n \"Avatar\",\n \"Alert\",\n \"Progress\",\n \"Image\",\n \"Icon\",\n \"Link\",\n \"Tooltip\",\n \"Table\",\n \"Tabs\",\n \"Toast\",\n \"Accordion\",\n \"MotionKeyframes\",\n \"useMotion\",\n \"useAnimationKey\",\n].join(\", \");\n\nconst ALL_COMPONENTS = [\n \"SearchField\",\n \"FormField\",\n \"MenuItem\",\n \"Tag\",\n \"Dropdown\",\n \"Autocomplete\",\n \"Breadcrumb\",\n \"Pagination\",\n \"EmptyState\",\n \"Stat\",\n \"Stepper\",\n \"Markdown\",\n \"MarkdownInline\",\n].join(\", \");\n\n// Mirrors the actual @ggui-ai/design compositions exports. The 2026-07-29\n// composite-roster wave (#306) deleted the six zero-consumer composites\n// (MakeTabLayout, MarketingHero/CTA/Features, IncidentTimeline,\n// UserProfileCard) from the design package; this list shrank with it.\n// The data-URL shim's allowlist must mirror this list (enforced by\n// verify-shim-allowlists.test.ts).\nconst ALL_COMPOSITIONS = [\n \"Header\",\n \"Sidebar\",\n \"CardGrid\",\n \"CommentThread\",\n \"DataTable\",\n \"ChatWindow\",\n \"NavigationBar\",\n \"FileUploader\",\n \"NotificationCenter\",\n \"Modal\",\n \"CommandPalette\",\n \"Footer\",\n \"Hero\",\n].join(\", \");\n\nconst ALL_INTERACT = [\"Clickable\", \"Hoverable\", \"Pressable\"].join(\", \");\n\n// D1: the whole design system is imported through one specifier\n// (`@ggui-ai/design`), so the boilerplate emits a single import line.\nconst ALL_DESIGN = [\n ALL_PRIMITIVES,\n ALL_COMPONENTS,\n ALL_COMPOSITIONS,\n ALL_INTERACT,\n].join(\", \");\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/** Infer a TypeScript type string from an example value (when no JSON Schema is available). */\nfunction inferTypeFromExample(example: JsonObject): string {\n const fields: string[] = [];\n for (const [k, v] of Object.entries(example)) {\n let t: string;\n if (v === null || v === undefined) t = \"unknown\";\n else if (typeof v === \"string\") t = \"string\";\n else if (typeof v === \"number\") t = \"number\";\n else if (typeof v === \"boolean\") t = \"boolean\";\n else if (Array.isArray(v)) {\n if (v.length === 0) t = \"unknown[]\";\n else if (typeof v[0] === \"string\") t = \"string[]\";\n else if (typeof v[0] === \"number\") t = \"number[]\";\n else if (typeof v[0] === \"object\" && v[0] !== null)\n t = `Array<${inferTypeFromExample(v[0] as JsonObject)}>`;\n else t = \"unknown[]\";\n } else if (typeof v === \"object\") {\n t = inferTypeFromExample(v as JsonObject);\n } else {\n t = \"unknown\";\n }\n fields.push(`${k}: ${t}`);\n }\n return `{ ${fields.join(\"; \")} }`;\n}\n\n// =============================================================================\n// Boilerplate generator\n// =============================================================================\n\nexport function generateBoilerplate(\n _userPrompt: string,\n contract?: DataContract,\n shellType?: ShellType,\n screen?: ScreenSize,\n /** Axis-composed boilerplate sections — fragments produced by `compose()`. */\n composedSections?: string,\n /**\n * Registered gadget catalog. The boilerplate emits a direct\n * `import { … } from '<package>'` per gadget package from the\n * contract's declarations; this catalog supplies the descriptor\n * metadata (`description` / `usage` / `example`) used to prime each\n * pre-emitted gadget call site so the LLM has a working starting\n * point rather than an empty `useFoo()` it might delete.\n */\n appGadgets?: readonly GadgetDescriptor[],\n): string {\n // ── Props interface from data contract (data only — NO action callbacks) ──\n // Contract shape (PropsSpec is ALWAYS the wrapper — never flat):\n // { properties: { fieldName: { schema, required, description } } }\n const propsFields: string[] = [];\n const propsProperties = contract?.propsSpec?.properties ?? {};\n for (const [key, entry] of Object.entries(propsProperties)) {\n const required = entry.required !== false;\n const nullable = entry.schema.nullable === true;\n const tsType = jsonSchemaTypeToTs(entry.schema);\n const fullType = nullable ? `${tsType} | null` : tsType;\n // Build comment: description + default value hint\n const parts: string[] = [];\n if (entry.description) parts.push(entry.description);\n if (entry.default !== undefined) parts.push(`(default: ${JSON.stringify(entry.default)})`);\n const desc = parts.length > 0 ? ` // ${parts.join(' ')}` : \"\";\n propsFields.push(` ${key}${required ? \"\" : \"?\"}: ${fullType};${desc}`);\n }\n\n // ── Actions (useAction hooks — fire-and-forget to agent) ──\n // Contract shape: { actionSpec: { actionName: { label, description, schema?, example?, nextStep? } } }\n // ActionEntry.nextStep: optional hint naming the MCP tool the AGENT\n // should invoke on its next turn after this action fires. Actions have\n // exactly one routing target — the agent; there is NO synchronous\n // server-side dispatch. The name is informational here (use it for\n // button labels, icons, copy).\n const actionTypeAliases: string[] = [];\n const actionHookCalls: string[] = [];\n const actionReturnFields: string[] = [];\n const actionsMap: ActionSpec = contract?.actionSpec ?? {};\n for (const [key, entry] of Object.entries(actionsMap)) {\n const label = entry.label ?? key;\n const desc = entry.description ?? \"\";\n const tool = entry.nextStep ?? \"\";\n const typeName = `Action${key.charAt(0).toUpperCase()}${key.slice(1)}Payload`;\n\n // Derive TypeScript type: schema > example > void (fire-and-forget)\n let tsType = \"void\";\n if (entry.schema) {\n tsType = jsonSchemaTypeToTs(entry.schema);\n } else if (entry.example && typeof entry.example === \"object\" && !Array.isArray(entry.example)) {\n tsType = inferTypeFromExample(entry.example as JsonObject);\n }\n\n const toolNote = tool ? ` (label \"${label}\", nextStep hint → ${tool})` : \"\";\n actionTypeAliases.push(\n `/** Action payload: ${desc || label}${toolNote} */\\ntype ${typeName} = ${tsType};`\n );\n // Inline signature tells the LLM exactly how to call this action\n const callSig = tsType === \"void\" ? \"() => void — fire and forget\" : `(data: ${tsType}) => void`;\n const toolHint = tool ? ` → nextStep: ${tool}` : \"\";\n actionHookCalls.push(` const ${key} = useAction<${typeName}>('${key}'); // ${callSig}${toolHint}`);\n actionReturnFields.push(key);\n }\n\n // ── Stream channels (useStream hooks — real-time from agent) ──\n // Stream spec: flat map { channelName: { schema, description, example } }\n const streamChannels: StreamSpec = contract?.streamSpec ?? {};\n const streamChannelEntries = Object.entries(streamChannels);\n\n const streamTypeAliases: string[] = [];\n const streamHookCalls: string[] = [];\n const streamReturnFields: string[] = [];\n for (const [channelName, entry] of streamChannelEntries) {\n const desc = entry.description ?? \"\";\n const typeName = `Stream${channelName.charAt(0).toUpperCase()}${channelName.slice(1)}`;\n const tsType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n streamTypeAliases.push(`/** Stream channel: ${desc} */\\ntype ${typeName} = ${tsType};`);\n // Show .latest/.all types so the LLM knows how to access stream data\n streamHookCalls.push(\n ` const ${channelName} = useStream<${typeName}>('${channelName}'); // .latest: ${typeName} | null, .all: ${typeName}[]`\n );\n streamReturnFields.push(channelName);\n }\n\n // ── agentCapabilities.tools catalog (NO component-side hook emission) ──\n // `agentCapabilities.tools[*]` declares tools the AGENT invokes —\n // referenced from the contract via `actionSpec[*].nextStep` (advisory\n // hint forwarded on action events) and `streamSpec[*].source.tool`\n // (channel data source). The component never calls these tools\n // directly; there is no `useWiredTool(name)` hook. The boilerplate\n // therefore emits no per-tool hook line, no request/response type\n // aliases, and no useWiredTool import.\n\n // ── Client capabilities (browser-capability gadget hooks declared in contract) ──\n // Contract shape: { gadgets: { '<package>': { '<exportName>': { description?, usage? } } } }\n // package-keyed two-level map. `listContractGadgets` flattens it to\n // `GadgetUse[]` — one record per used export with `package`, `name`,\n // and optional `description` / `usage` overrides. The export NAME\n // grammar discriminates kind (`use`-prefixed → hook, PascalCase →\n // component).\n // No type aliases — gadget hooks own their typed return shape.\n // No wire-import side effect — gadgets are imported from `package`\n // (default `@ggui-ai/gadgets`), not from `@ggui-ai/wire`.\n //\n // Group-by-package — emit ONE combined `import { hookA, hookB } from '<pkg>'`\n // per declared package, NOT one import per hook. Hooks ordered\n // alphabetically within each package for stable diffs across same-\n // contract regens.\n const gadgetUses = contract ? listContractGadgets(contract) : [];\n\n // Gadgets are DIRECT-imported from their package, grouped\n // per package below. Build a hook-name → registry export lookup so\n // each contract-declared gadget binding can be enriched with the\n // catalog's description / usage / example fields. Mirrors how wire\n // boilerplate emits typed action signatures + nextStep hints —\n // gadgets get the same priming so the LLM has a working call site to\n // start from rather than an empty `useFoo()` it might delete.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports, keyed by hook name.\n const gadgetCatalog = new Map<\n string,\n {\n readonly description?: string;\n readonly usage?: string;\n readonly example?: JsonValue;\n }\n >();\n for (const descriptor of appGadgets ?? []) {\n for (const exp of descriptor.exports) {\n // `GadgetExport` is a type-exclusive union (`hook?: never` on the\n // component member); discriminate by VALUE presence — `\"hook\" in\n // exp` no longer narrows now that `hook` is an optional key of\n // both members.\n if (exp.hook === undefined) continue;\n gadgetCatalog.set(exp.hook, {\n description: exp.description,\n usage: exp.usage,\n example: exp.example,\n });\n }\n }\n // Gadget imports grouped by package: `package → set of export names`\n // (hook AND component exports). One combined\n // `import { … } from '<pkg>'` is emitted per package.\n const gadgetImportsByPackage = new Map<string, Set<string>>();\n const gadgetHookCalls: string[] = [];\n for (const use of gadgetUses) {\n const exportName = use.name;\n // Both hooks and components are DIRECT-imported from their\n // package — add every contract-declared export to the per-package\n // import group.\n const pkgExports = gadgetImportsByPackage.get(use.package);\n if (pkgExports !== undefined) pkgExports.add(exportName);\n else gadgetImportsByPackage.set(use.package, new Set([exportName]));\n\n // Kind discrimination is by the export-name grammar.\n // A component name (PascalCase) is import-only — the LLM renders\n // `<X … />` in the JSX tree itself, so there is no pre-emitted call\n // site. Hook names (`use`-prefixed) additionally get a pre-emitted\n // call line below so the LLM has a working invocation.\n if (!HOOK_NAME_RE.test(exportName)) continue;\n const hook = exportName;\n // Contract entry's local override wins; registry catalog is the\n // fallback (most plugin descriptors live on the registry side).\n // The wire `GadgetUse` carries only `description` / `usage`\n // overrides — `example` lives solely on the registered export.\n const contractDesc = use.description;\n const contractUsage = use.usage;\n const catalog = gadgetCatalog.get(hook) ?? {};\n const desc = contractDesc ?? catalog.description ?? hook;\n const usage = contractUsage ?? catalog.usage;\n const example = catalog.example;\n\n // Pre-emit the hook call so the LLM sees a working invocation\n // (and doesn't delete it as \"unused\"). Mirrors wire's typed-\n // signature pattern. Two example shapes in the wild:\n // (a) plain literal — `{ center: [0,0], zoom: 12 }` — the\n // descriptor IS the call args; inline as the call arg.\n // (b) shaped object — `{ call: '<full TS expression>',\n // returns: <typed return shape> }` — the canonical\n // sample/leaflet descriptor shape; emit the `call` as a\n // separate EXAMPLE comment so the LLM sees the literal TS\n // it should produce.\n let callArgs = '';\n let exampleComment = '';\n if (example !== undefined && example !== null) {\n const callLine =\n typeof example === 'object' &&\n !Array.isArray(example) &&\n typeof example.call === 'string'\n ? example.call\n : undefined;\n if (callLine !== undefined) {\n exampleComment = `\\n // EXAMPLE: ${callLine.trim()}`;\n } else {\n callArgs = JSON.stringify(example);\n }\n }\n const usageNote = usage ? ` USE: ${usage}` : '';\n // Local binding name: strip the `use` prefix + lowercase the first\n // char so `useGeolocation` → `geolocation`. The wire no longer\n // carries an explicit binding name (the export name IS the inner\n // key), so the boilerplate derives a stable, readable one.\n const bindingName =\n hook.length > 3\n ? hook.charAt(3).toLowerCase() + hook.slice(4)\n : hook;\n gadgetHookCalls.push(\n ` const ${bindingName} = ${hook}(${callArgs}); // ${desc}${usageNote}${exampleComment}`,\n );\n }\n // Gadgets are DIRECT-imported, one combined\n // `import { hookA, hookB } from '<pkg>'` per registered package\n // (packages + hooks sorted for stable diffs across same-contract\n // regens). The `DO NOT EDIT` banner + tier-0 `gadget_preservation`\n // keep the LLM from deleting an import it (correctly) intuits is\n // runtime-resolved — the banner alone makes direct imports survive\n // multi-turn generation. Tier-0 verifies each registered hook is\n // still imported from its package.\n const gadgetImportLine =\n gadgetImportsByPackage.size > 0\n ? \"// DO NOT EDIT — gadget imports. Each export is resolved by the iframe \" +\n \"runtime; keep every import line and export name. self_check fails with \" +\n \"gadget_preservation:<export> if a gadget import is removed.\\n\" +\n Array.from(gadgetImportsByPackage.entries())\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([pkg, hooks]) =>\n `import { ${Array.from(hooks).sort().join(\", \")} } from '${pkg}';`,\n )\n .join(\"\\n\")\n : \"\";\n // ── Props interface (data only — no action callbacks) ──\n const propsInterface =\n propsFields.length > 0\n ? `// DO NOT EDIT — generated from data contract. Changing this will fail validation.\\ninterface Props {\\n${propsFields.join(\"\\n\")}\\n}`\n : `// DO NOT EDIT — generated from data contract.\\ninterface Props {\\n [key: string]: string | number | boolean | null | object;\\n}`;\n\n // ── Context slots — `useGguiContext` hook ──\n // For each declared `contextSpec` slot, emit ONE destructure line\n // at the top of the user component:\n // const [<slotKey>, set<PascalSlotKey>] =\n // useGguiContext<TS>('<slotKey>');\n // The runtime owns useState per slot and wraps the user component\n // in nested SingleSlotProvider components — the user only reads\n // the live tuple via the hook. There must be NO `useState` and NO\n // `<Provider>` wrap anywhere in the LLM-authored JSX.\n const contextSpec: ContextSpec = contract?.contextSpec ?? {};\n const contextSpecEntries = Object.entries(contextSpec);\n let contextHooks = \"\";\n if (contextSpecEntries.length > 0) {\n const hookLines: string[] = [];\n for (const [slotKey, entry] of contextSpecEntries) {\n const valueType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n const setterName = `set${slotKey.charAt(0).toUpperCase()}${slotKey.slice(1)}`;\n hookLines.push(\n ` const [${slotKey}, ${setterName}] = useGguiContext<${valueType}>('${slotKey}');`,\n );\n }\n contextHooks =\n ` // DO NOT EDIT — auto-generated per contextSpec slot.\\n` +\n ` // Read \\`<slotKey>\\` to render, write via \\`set<SlotKey>\\` to\\n` +\n ` // surface the change to the agent's LLM context (debounced).\\n` +\n ` // The runtime owns the underlying useState + Provider; you\\n` +\n ` // write plain JSX, no wrap.\\n` +\n `${hookLines.join(\"\\n\")}\\n`;\n }\n\n // ── Determine which wire hooks are needed ──\n const hasActions = actionHookCalls.length > 0;\n const hasStream = streamHookCalls.length > 0;\n // Gates the gadget hook-CALL body section. A component gadget\n // contributes an import but no call site, so this is false for a\n // component-only contract — the import line is gated separately on\n // `gadgetImportLine` below.\n const hasGadgetHookCalls = gadgetHookCalls.length > 0;\n const hasContext = contextSpecEntries.length > 0;\n // `hasAnyHook` gates the \"DO NOT EDIT wire hooks\" header + body.\n // Client gadget HOOKS contribute call sites alongside the\n // @ggui-ai/wire hooks — their declaration needs the same emitted\n // header so the LLM sees the binding lines pre-declared and doesn't\n // strip / duplicate them. (Component gadgets add no body line.)\n const hasAnyHook =\n hasActions || hasStream || hasContext || hasGadgetHookCalls;\n const hasAnyWireFromWire = hasActions || hasStream || hasContext;\n\n const wireHooks: string[] = [];\n if (hasActions) wireHooks.push(\"useAction\");\n if (hasStream) wireHooks.push(\"useStream\");\n if (hasContext) wireHooks.push(\"useGguiContext\");\n const wireImport = hasAnyWireFromWire\n ? `import { ${wireHooks.join(\", \")} } from '@ggui-ai/wire';\\n`\n : \"\";\n // The gadget import line is emitted whenever ANY gadget export is\n // declared — hook OR component. (`gadgetImportLine` is non-empty iff\n // `gadgetImportsByPackage` has an entry; component-only contracts\n // have an import but no `hasGadgetHookCalls`.)\n const gadgetImport =\n gadgetImportLine.length > 0 ? `${gadgetImportLine}\\n` : \"\";\n\n // ── React import — only include hooks that are actually needed ──\n const reactHooks = [\"useState\", \"useCallback\", \"useMemo\", \"useEffect\", \"useRef\"];\n const reactImport = `import React, { ${reactHooks.join(\", \")} } from 'react';`;\n\n // ── Hook body ──────────────────────────────────────────\n // Wire hooks are placed inside render(), before the return statement.\n const hookParts: string[] = [];\n if (hasActions) {\n hookParts.push(\" // ── Actions (contract-typed, fire-and-forget to agent) ──\");\n hookParts.push(\" // Call these to send user interactions to the agent. Types are enforced by the compiler.\");\n hookParts.push(...actionHookCalls);\n }\n if (hasStream) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Streams (contract-typed, real-time from agent) ──\");\n hookParts.push(\" // .latest is the most recent event (or null). .all is the full history array.\");\n hookParts.push(...streamHookCalls);\n }\n if (hasGadgetHookCalls) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Gadgets (browser-capability hooks; UI-owned lifecycle) ──\");\n hookParts.push(\" // Read .value / .status; call .start() to invoke. Surface .value through\");\n hookParts.push(\" // an actionSpec payload or contextSpec slot if the agent needs to observe it.\");\n hookParts.push(...gadgetHookCalls);\n }\n\n // Only emit the \"DO NOT EDIT wire hooks\" header when there ARE wire-side\n // OR gadget-side hook bindings to surface. An orphaned header on\n // no-wire fixtures (e.g. weather-card) makes the LLM hallucinate\n // hooks for an empty section and burn turns on missing imports.\n const hookBody = hasAnyHook\n ? ` // DO NOT EDIT wire hooks — auto-generated from the data contract\\n${hookParts.join(\"\\n\")}\\n`\n : \"\";\n\n // ── Type alias blocks ───────────────────────────────────\n // Auto-generated type aliases serve as documentation for the LLM. Some are\n // referenced by the wire-hook calls below (e.g. `useAction<ActionXPayload>`)\n // but request types are typically only mentioned in trailing comments —\n // ESLint flags them as unused. Without `eslint-disable` here, the LLM\n // enters a fix-rename oscillation loop (prefix `_`, break prop access,\n // revert, retry…) that drives up to 27% of cap-hit selfCheckFails on\n // wire-bearing fixtures. Suppress no-unused-vars for the generated\n // type-alias block; \"DO NOT EDIT\" comments + tier-0 wire-preservation\n // already prevent the LLM from removing them.\n const wrapTypes = (label: string, body: string): string =>\n `\\n/* eslint-disable no-unused-vars */\\n// DO NOT EDIT — ${label}\\n${body}\\n/* eslint-enable no-unused-vars */\\n`;\n\n const actionTypesBlock =\n actionTypeAliases.length > 0\n ? wrapTypes(\"action payload types generated from action contract.\", actionTypeAliases.join(\"\\n\\n\"))\n : \"\";\n const streamTypesBlock =\n streamTypeAliases.length > 0\n ? wrapTypes(\"stream event types generated from stream contract.\", streamTypeAliases.join(\"\\n\\n\"))\n : \"\";\n // `clientCapabilities.gadgets` ship NO type-alias block — gadget\n // hooks own their typed return shape internally; the contract surface\n // is pure declaration.\n\n return renderBoilerplate(shellType ?? \"fullscreen\", screen ?? \"universal\", {\n REACT_IMPORT: reactImport,\n ALL_DESIGN,\n WIRE_IMPORT: wireImport + gadgetImport,\n PROPS_INTERFACE: propsInterface,\n ACTION_TYPES: actionTypesBlock,\n STREAM_TYPES: streamTypesBlock,\n CONTEXT_HOOKS: contextHooks,\n WIRE_HOOKS: hookBody,\n AXIS_SECTIONS: composedSections ?? \"\",\n });\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/internal/extract-call-signatures.ts\n//\n// Internal gadget-signature extractor.\n//\n// Uses the TypeScript Compiler API to parse an in-memory wrapper `.d.ts`\n// STRING and, for each requested export, print a prompt-ready type:\n//\n// - `extractCallSignaturesFromDts` — for HOOK exports, prints the\n// callable signature as a self-contained TS function-type\n// expression (`(options?: { center: [number, number]; zoom: number })\n// => GadgetHookResult<...>`).\n// - `extractComponentPropsFromDts` (GG.8.5) — for COMPONENT exports,\n// prints the props-object shape (the first parameter's type,\n// structurally expanded) so the prompt can teach the LLM the JSX\n// props of `<Chart data={…} height={…} />`.\n//\n// Both take the wrapper's already-built `.d.ts` content AS A STRING —\n// the render handler fetches each non-stdlib gadget's `.d.ts` over HTTPS\n// and threads a `package -> dtsContent` map into the generator\n// (`UiGenerateInput.gadgetTypes`). The code-gen prompt builder calls\n// these helpers to render a `Type:` / `Props:` line per third-party\n// gadget so the LLM sees the real shape it otherwise can't know.\n//\n// Internal only — NOT re-exported from any public package entry. Lives\n// under `src/internal/` deliberately.\n\nimport ts from 'typescript';\n\n/**\n * Map of `hookName → call-signature string` produced by\n * {@link extractCallSignaturesFromDts}. Each value is a printed\n * function-type expression suitable for verbatim interpolation into a\n * prompt `Type:` line.\n *\n * Hooks whose signature could not be resolved are omitted — the caller\n * renders a `Type:` line only for hooks that appear here.\n */\nexport type CallSignatureMap = Record<string, string>;\n\n/**\n * Map of `componentName → props-object type string` produced by\n * {@link extractComponentPropsFromDts}. Each value is a printed object\n * type (`{ data: …; height?: number }`) suitable for a prompt `Props:`\n * line. Components whose props could not be resolved are omitted.\n */\nexport type ComponentPropsMap = Record<string, string>;\n\n// In-memory `.d.ts` is parsed under a synthetic file name. The leading\n// `/` matches the convention `getCurrentDirectory()` (also `/`) so the\n// compiler host's path probes line up.\nconst VIRTUAL_DTS_PATH = '/__gadget__.d.ts';\n\nconst EXTRACTOR_COMPILER_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n allowJs: false,\n jsx: ts.JsxEmit.ReactJSX,\n noEmit: true,\n esModuleInterop: true,\n // skipLibCheck so an unresolvable wrapper-internal import (the\n // sandbox doesn't carry the wrapper's transitive deps) doesn't abort\n // the program before we can read the symbol's callable signature.\n skipLibCheck: true,\n strict: true,\n};\n\n/**\n * Process-lifetime memos. Building a `ts.Program` — including\n * default-lib reads — on every call is expensive, and each extractor is\n * invoked once per coding-agent turn while the `.d.ts` content + name\n * set stay constant across a generation. Keying on `(dtsContent, names)`\n * collapses the repeated work. The key set is tiny in practice (a\n * handful of gadgets per process).\n */\nconst callSignatureCache = new Map<string, CallSignatureMap>();\nconst componentPropsCache = new Map<string, ComponentPropsMap>();\n\n/**\n * One-shot extractor program for a wrapper `.d.ts`, with the resolved\n * call signatures of every requested export. Shared by both public\n * extractors — they differ only in how they format the result.\n */\ninterface ExtractorContext {\n readonly checker: ts.TypeChecker;\n /** Render a `ts.Type` as a self-contained, prompt-ready expression. */\n readonly renderType: (t: ts.Type, depth: number) => string;\n /**\n * Requested export name → its resolved call signatures, in\n * declaration order. Only exports that are callable (a hook or a\n * function component) appear; non-callable exports are omitted.\n */\n readonly signaturesByName: ReadonlyMap<string, readonly ts.Signature[]>;\n}\n\n/**\n * Build a single-file TS Program over `dtsContent`, resolve the call\n * signatures of every requested export name, and expose the checker +\n * a structural type renderer. Returns `undefined` when the `.d.ts`\n * cannot be parsed.\n */\nfunction buildExtractorContext(\n dtsContent: string,\n names: readonly string[],\n): ExtractorContext | undefined {\n // Build a fresh `.d.ts` source file. `setParentNodes: true` is\n // required so the checker can walk the AST.\n const sourceFile = ts.createSourceFile(\n VIRTUAL_DTS_PATH,\n dtsContent,\n ts.ScriptTarget.ESNext,\n /* setParentNodes */ true,\n ts.ScriptKind.TS,\n );\n\n // Minimal in-memory compiler host. Only the synthetic `.d.ts` plus\n // the TS default lib files are resolvable; everything else is absent\n // (skipLibCheck keeps that from aborting the program). The checker\n // still resolves intra-file named types, which is all structural\n // fallback needs to inline a self-contained signature.\n const defaultLibName = ts.getDefaultLibFileName(EXTRACTOR_COMPILER_OPTIONS);\n const host: ts.CompilerHost = {\n getSourceFile(fileName) {\n if (fileName === VIRTUAL_DTS_PATH) return sourceFile;\n // Default lib(s) — load from the real `typescript` install so the\n // checker has `lib.d.ts` ambient types. The dts may not need\n // them, but the program won't run without a default lib.\n const libContent = ts.sys.readFile(\n ts.getDefaultLibFilePath(EXTRACTOR_COMPILER_OPTIONS).replace(\n /[^/\\\\]+$/,\n fileName,\n ),\n );\n if (libContent !== undefined) {\n return ts.createSourceFile(\n fileName,\n libContent,\n ts.ScriptTarget.ESNext,\n true,\n ts.ScriptKind.TS,\n );\n }\n return undefined;\n },\n getDefaultLibFileName() {\n return defaultLibName;\n },\n writeFile() {\n // no-op — noEmit\n },\n getCurrentDirectory() {\n return '/';\n },\n getCanonicalFileName(f) {\n return f;\n },\n useCaseSensitiveFileNames() {\n return true;\n },\n getNewLine() {\n return '\\n';\n },\n fileExists(f) {\n if (f === VIRTUAL_DTS_PATH) return true;\n return ts.sys.fileExists(f);\n },\n readFile(f) {\n if (f === VIRTUAL_DTS_PATH) return dtsContent;\n return ts.sys.readFile(f);\n },\n };\n\n const program = ts.createProgram(\n [VIRTUAL_DTS_PATH],\n EXTRACTOR_COMPILER_OPTIONS,\n host,\n );\n const checker = program.getTypeChecker();\n const parsed = program.getSourceFile(VIRTUAL_DTS_PATH);\n if (parsed === undefined) {\n return undefined;\n }\n\n const requested = new Set(names);\n\n // True when a symbol's declaration originates from the wrapper's own\n // `.d.ts`. Only THESE named types get structurally expanded — types\n // from the TS DOM lib (`HTMLDivElement`), `@ggui-ai/gadgets`\n // (`GadgetHookResult`), or any external package keep their name,\n // because (a) the LLM already knows DOM / ggui types and (b)\n // expanding `HTMLDivElement` would dump hundreds of DOM members into\n // the prompt.\n function isWrapperLocal(symbol: ts.Symbol | undefined): boolean {\n const decls = symbol?.getDeclarations();\n if (decls === undefined) return false;\n return decls.some((d) => d.getSourceFile().fileName === VIRTUAL_DTS_PATH);\n }\n\n // Render a single `ts.Type` as a self-contained TS type expression.\n //\n // The TS node builder keeps a type's NAME whenever that name is\n // reachable in the program — for a `.d.ts` whose option/value types\n // are `export interface`s, that means the printed signature ends up\n // full of `LeafletMapOptions` references the LLM cannot resolve. To\n // produce a prompt-ready, self-contained signature we structurally\n // expand WRAPPER-LOCAL named object types one level: enumerate the\n // apparent properties and render each property's type (recursively,\n // depth-bounded). Non-local named types, primitives, unions, arrays,\n // tuples, and anonymous objects keep `typeToString`'s rendering.\n const MAX_DEPTH = 4;\n function renderType(t: ts.Type, depth: number): string {\n const plain = (): string =>\n checker.typeToString(t, undefined, ts.TypeFormatFlags.NoTruncation);\n\n // Bail to the plain stringifier once we hit the depth cap so a\n // cyclic / deeply-nested type can't blow the stack.\n if (depth >= MAX_DEPTH) return plain();\n\n // `boolean` is internally `true | false` — `isUnion()` is true for\n // it. Catch it before union-splitting so it prints as `boolean`.\n if ((t.getFlags() & ts.TypeFlags.Boolean) !== 0) return 'boolean';\n\n // Union types (e.g. `LeafletMapOptions | undefined` from an\n // optional param) — recurse into each constituent so a wrapper-\n // local named object member still expands structurally.\n if (t.isUnion()) {\n return t.types.map((member) => renderType(member, depth)).join(' | ');\n }\n // Intersections — same treatment.\n if (t.isIntersection()) {\n return t.types.map((member) => renderType(member, depth)).join(' & ');\n }\n\n const symbol = t.getSymbol() ?? t.aliasSymbol;\n\n // Callable types (e.g. `containerRef: (el) => void`) — render the\n // first call signature inline.\n const callSigs = t.getCallSignatures();\n if (callSigs.length > 0) {\n const cs = callSigs[0]!;\n const params = cs\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined ||\n decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join(', ');\n const ret = renderType(cs.getReturnType(), depth + 1);\n return `(${params}) => ${ret}`;\n }\n\n const isObject = (t.getFlags() & ts.TypeFlags.Object) !== 0;\n const isArrayOrTuple =\n checker.isArrayType(t) || checker.isTupleType(t);\n\n // Generic instantiation of a non-local type (e.g.\n // `GadgetHookResult<LeafletMapValue>`) — keep the outer name (the\n // LLM knows the ggui types) but recurse into the type arguments so\n // a nested wrapper-local type still expands.\n const typeArgs = (t as ts.TypeReference).typeArguments;\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n !isWrapperLocal(symbol) &&\n typeArgs !== undefined &&\n typeArgs.length > 0\n ) {\n const args = typeArgs.map((a) => renderType(a, depth + 1)).join(', ');\n return `${symbol.getName()}<${args}>`;\n }\n\n // Wrapper-local named object — expand its property shape inline.\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n isWrapperLocal(symbol)\n ) {\n const props = checker.getPropertiesOfType(t);\n if (props.length > 0) {\n const body = props\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional = (p.getFlags() & ts.SymbolFlags.Optional) !== 0;\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join('; ');\n return `{ ${body} }`;\n }\n }\n\n return plain();\n }\n\n // The exported binding may surface as either:\n // - `export declare const useLeafletMap: GguiGadget<...>` — a\n // variable statement, or\n // - `export declare function useLeafletMap(...): ...` — a function\n // declaration, or\n // - `export { useLeafletMap } from '...'` — a re-export.\n // The module-symbol export table covers all three uniformly, so we\n // walk the module symbol's exports rather than top-level statements.\n const moduleSymbol = checker.getSymbolAtLocation(parsed);\n const exportSymbols: ts.Symbol[] =\n moduleSymbol !== undefined ? checker.getExportsOfModule(moduleSymbol) : [];\n\n const signaturesByName = new Map<string, readonly ts.Signature[]>();\n for (const symbol of exportSymbols) {\n const name = symbol.getName();\n if (!requested.has(name)) continue;\n if (signaturesByName.has(name)) continue;\n\n // Resolve aliases (re-exports) so we read the real declaration.\n const resolved =\n (symbol.flags & ts.SymbolFlags.Alias) !== 0\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n\n const declarations = resolved.getDeclarations();\n if (declarations === undefined || declarations.length === 0) continue;\n const declaration = declarations[0]!;\n\n const type = checker.getTypeOfSymbolAtLocation(resolved, declaration);\n const callSignatures = type.getCallSignatures();\n if (callSignatures.length === 0) continue;\n\n signaturesByName.set(name, callSignatures);\n }\n\n return { checker, renderType, signaturesByName };\n}\n\n/**\n * Print one call signature as a self-contained `(params) => ret`\n * expression.\n */\nfunction printCallSignature(sig: ts.Signature, ctx: ExtractorContext): string {\n const params = sig\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(p, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined || decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${ctx.renderType(pType, 0)}`;\n })\n .join(', ');\n const ret = ctx.renderType(sig.getReturnType(), 0);\n return `(${params}) => ${ret}`.trim();\n}\n\n/**\n * Render a function component's props — the first parameter's type,\n * structurally expanded into a self-contained object type. A\n * zero-parameter component yields `{}`. Returns `undefined` when the\n * expander bottoms out on an unresolvable token.\n */\nfunction printComponentProps(\n sig: ts.Signature,\n ctx: ExtractorContext,\n): string | undefined {\n const params = sig.getParameters();\n // A zero-parameter component takes no props.\n if (params.length === 0) return '{}';\n const propsParam = params[0]!;\n const decl = propsParam.valueDeclaration ?? propsParam.declarations?.[0];\n const propsType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(propsParam, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(propsParam);\n const rendered = ctx.renderType(propsType, 0);\n // A surviving virtual-file qualifier means the structural expander\n // bottomed out on something it couldn't inline — drop it rather than\n // feed the LLM an unresolvable `import(\"/__gadget__\")` token.\n if (rendered.length === 0 || rendered.includes('import(\"')) return undefined;\n return rendered;\n}\n\n/**\n * Print the inferred call signature of every requested HOOK found in\n * the supplied wrapper `.d.ts` string.\n *\n * For each exported declaration whose name matches a requested hook,\n * the checker's callable signature is printed with structural-fallback\n * so wrapper-specific named types expand to their structural form — the\n * resulting string is self-contained and safe to drop into a prompt. A\n * hook declared with multiple overloads renders each, joined with ` | `.\n *\n * Hooks that aren't found, or that resolve to a value with no callable\n * signature, are omitted from the result (no throw) — the caller is\n * expected to render a `Type:` line only for hooks that resolved.\n *\n * Memoized on `(dtsContent, hookNames)`.\n */\nexport function extractCallSignaturesFromDts(\n dtsContent: string,\n hookNames: readonly string[],\n): CallSignatureMap {\n if (hookNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...hookNames].sort().join(',')}`;\n const cached = callSignatureCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: CallSignatureMap = {};\n const ctx = buildExtractorContext(dtsContent, hookNames);\n if (ctx === undefined) {\n callSignatureCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A hook declared with multiple overloads renders ALL of them,\n // joined as a union of function types. A surviving virtual-file\n // qualifier means the structural expander bottomed out on something\n // it couldn't inline — drop that overload rather than feed the LLM\n // an unresolvable `import(\"/__gadget__\")` token.\n const printed = signatures\n .map((sig) => printCallSignature(sig, ctx))\n .filter((s) => s.length > 0 && !s.includes('import(\"'))\n .join(' | ');\n if (printed.length > 0) {\n result[name] = printed;\n }\n }\n\n callSignatureCache.set(cacheKey, result);\n return result;\n}\n\n/**\n * Print the props-object shape of every requested COMPONENT found in\n * the supplied wrapper `.d.ts` string (GG.8.5).\n *\n * A function component's props are its first parameter's type. The\n * type is structurally expanded the same way hook signatures are, so\n * the printed value (`{ data: …; height?: number }`) is self-contained\n * and prompt-ready — the code-gen prompt renders it as a `Props:` line\n * so the LLM knows the JSX attributes of `<Component … />`.\n *\n * Components not found, or that resolve to a non-callable value, are\n * omitted (no throw). Memoized on `(dtsContent, componentNames)`.\n */\nexport function extractComponentPropsFromDts(\n dtsContent: string,\n componentNames: readonly string[],\n): ComponentPropsMap {\n if (componentNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...componentNames].sort().join(',')}`;\n const cached = componentPropsCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: ComponentPropsMap = {};\n const ctx = buildExtractorContext(dtsContent, componentNames);\n if (ctx === undefined) {\n componentPropsCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A component is single-signature by convention — use the first.\n const first = signatures[0];\n if (first === undefined) continue;\n const props = printComponentProps(first, ctx);\n if (props !== undefined) {\n result[name] = props;\n }\n }\n\n componentPropsCache.set(cacheKey, result);\n return result;\n}\n","// packages/ui-gen/src/boilerplate/system-prompt.ts\n//\n// System-prompt skeleton for the coding agent. Deterministic assembly;\n// injection points for funnel content (pitfalls) and for large content\n// blocks that are OWNED BY OTHER PACKAGES (design-system docs,\n// primitives doc, wire doc). Those blocks travel as strings so ui-gen\n// doesn't silently pull in megabytes of auto-generated content from\n// `@ggui-ai/design` / `@ggui-ai/wire` that those packages authoritatively\n// own.\n//\n// The only content this skeleton carries by default is the coding-\n// criteria summary (`buildCodingCriteriaSummary()` over the open\n// `CRITERIA` single-source-of-truth). Everything else defaults to empty\n// string — the skeleton still renders cleanly for OSS callers who don't\n// pass doc blocks.\n\nimport { resolveAppGadgets } from \"@ggui-ai/protocol\";\nimport type {\n GadgetDescriptor,\n GadgetExport,\n GadgetHookExport,\n GadgetComponentExport,\n} from \"@ggui-ai/protocol\";\nimport { buildCodingCriteriaSummary } from \"../evaluation/types-public.js\";\nimport {\n extractCallSignaturesFromDts,\n extractComponentPropsFromDts,\n} from \"../internal/extract-call-signatures.js\";\n\n/** Narrow a {@link GadgetExport} to its hook variant by field presence. */\nfunction isHookExport(exp: GadgetExport): exp is GadgetHookExport {\n return \"hook\" in exp;\n}\n\n/** Narrow a {@link GadgetExport} to its component variant by field presence. */\nfunction isComponentExport(exp: GadgetExport): exp is GadgetComponentExport {\n return \"component\" in exp;\n}\n\nexport interface SystemPromptInputs {\n /** The user's original request. */\n userRequest: string;\n /** Shell layout mode. */\n shellType?: string;\n /** Target screen size. */\n screen?: string;\n /** Axis-conditioned prompt fragments (from `compose()`). */\n axisDelta?: string;\n /**\n * Funnel content injection — env-gated pitfalls block rendered by the\n * caller. OSS default: `\"\"`. The hosted runtime's core wrapper passes\n * `renderPitfallsBlock()` which honors `GGUI_PITFALLS` /\n * `GGUI_NEW_PITFALLS` env vars.\n */\n pitfallsBlock?: string;\n /**\n * Pre-rendered criteria block. Defaults to\n * `buildCodingCriteriaSummary()` over the open CRITERIA registry.\n * Callers that want to override (e.g. a trimmed summary for fast mode)\n * pass their own string.\n */\n criteriaBlock?: string;\n /** Hand-written design-token reference. Owned by `@ggui-ai/design`. */\n designSystemDocs?: string;\n /** Auto-generated primitives reference. Owned by `@ggui-ai/design`. */\n primitivesDoc?: string;\n /** Auto-generated wire-hooks reference. Owned by `@ggui-ai/wire`. */\n wireDoc?: string;\n /**\n * Per-app gadget catalog. When provided, replaces the default\n * `STDLIB_GADGETS`-only table in the\n * `clientCapabilities — registered catalog` section so registered\n * third-party gadgets (Leaflet, Mapbox, Stripe, …) instruct the\n * code-gen LLM with the same teaching text the synth + decision LLMs\n * see.\n *\n * When omitted, the section renders the standard-library seed (the\n * first-party browser-capability hooks).\n */\n appGadgets?: readonly GadgetDescriptor[];\n /**\n * A `package -> .d.ts content` map for THIRD-PARTY gadget wrappers\n * (the render handler parallel-fetches each non-stdlib gadget's\n * `.d.ts`). When a gadget's `package` has an entry here,\n * `formatGadgetsSection` renders a `**Type**:` line carrying the\n * hook's extracted call signature — the LLM sees the real call shape\n * of a wrapper it cannot otherwise know.\n *\n * Stdlib gadgets (`@ggui-ai/gadgets`) get NO `Type:` line — they\n * already carry an `example` and are well-known; extracting stdlib\n * signatures is deliberately out of scope. Omit for STDLIB-only\n * callers (the section stays byte-identical).\n */\n gadgetTypes?: Readonly<Record<string, string>>;\n}\n\nconst SHELL_DESCRIPTIONS: Record<string, string> = {\n chat: \"inline component inside ChatShell message bubble (~400px wide, compact)\",\n fullscreen: \"full viewport, responsive layout\",\n spatial: \"floating AR/VR panel (~600px, touch-friendly)\",\n};\n\nconst SCREEN_DESCRIPTIONS: Record<string, string> = {\n mobile: \"single column, large touch targets\",\n tablet: \"flexible columns, medium spacing\",\n desktop: \"multi-column, dense layout\",\n universal: \"responsive across all breakpoints\",\n};\n\n/**\n * Render the `clientCapabilities — registered catalog` table from the\n * per-app gadget catalog. Each registered gadget renders one row\n * with hook + permission + the `description`-or-`usage` field as the\n * \"what it does\" column. Permission falls back to `(none)` when the\n * descriptor doesn't declare one.\n *\n * The table is built dynamically from the catalog so all three triad\n * surfaces (synth contract authoring, decision LLM, code-gen system\n * prompt) instruct the model uniformly about which gadgets are\n * available.\n *\n * Rows are emitted in catalog order. An empty catalog produces a hint\n * to seed it via `app.gadgets` rather than an empty table.\n *\n * When `gadgetTypes` carries a `.d.ts` for a gadget's `package`, a\n * `**Type**:` block is appended after the table with one line per\n * THIRD-PARTY gadget: `\\`<hook>\\`: <extracted call signature>`. The\n * signature is extracted from the wrapper's `.d.ts` via\n * `extractCallSignaturesFromDts`. Stdlib gadgets (`@ggui-ai/gadgets`)\n * get NO `Type:` line — they already carry an `example` and are\n * well-known. A hook whose signature can't be extracted is silently\n * skipped.\n *\n * Pure helper. Exported for unit testing.\n */\nexport function formatGadgetsSection(\n appGadgets: readonly GadgetDescriptor[],\n gadgetTypes?: Readonly<Record<string, string>>,\n): string {\n if (appGadgets.length === 0) {\n return [\n \"When the contract declares a `clientCapabilities.gadgets` entry,\",\n \"the hook MUST be one the operator has registered on\",\n \"`App.gadgets`. The default ggui server seeds the 7\",\n \"first-party STDLIB hooks; this server has none registered (the\",\n \"operator's `ggui.json#app.gadgets` is empty). Don't\",\n \"declare `clientCapabilities.gadgets` until a hook is registered.\",\n ].join(\" \");\n }\n // The LLM DIRECT-IMPORTS gadget hooks. The boilerplate emits\n // one combined `import { hookA, hookB } from '<package>'` line per\n // registered gadget package, above a `DO NOT EDIT` banner. The\n // `Package` column below IS the import specifier — it is load-bearing.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports (one table row per hook), carrying\n // package identity through for the Package column.\n const hookExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isHookExport)\n .map((exp) => ({ exp, descriptor })),\n );\n // Component exports get their own table + render teaching.\n const componentExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isComponentExport)\n .map((exp) => ({ exp, descriptor })),\n );\n const header =\n \"When the contract declares a hook gadget on `clientCapabilities.gadgets`, the hook MUST be one of the registered hooks below. The boilerplate has already emitted a direct import per gadget package — `import { <hook>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each STDLIB hook from `@ggui-ai/gadgets`; import each third-party hook from the package named in the `Package` column. DO NOT invent your own import paths. Available registered hooks:\";\n const tableHead = [\n \"| Hook | Package (import from here) | Permission | What it does |\",\n \"| --------------------- | ---------------------------------- | ------------------ | ------------------------------------------- |\",\n ];\n const rows = hookExports.map(({ exp, descriptor }) => {\n const hookCol = `\\`${exp.hook}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const permCol = exp.permission\n ? `\\`${exp.permission}\\``.padEnd(18, \" \")\n : \"(none)\".padEnd(18, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${hookCol} | ${pkgCol} | ${permCol} | ${what.padEnd(43, \" \")} |`;\n });\n\n // `**Type**:` lines for THIRD-PARTY gadgets. A gadget is third-party\n // when its `package` has a `.d.ts` entry in `gadgetTypes` (stdlib\n // `@ggui-ai/gadgets` is never in the map). The LLM can't know a\n // third-party wrapper's call shape; the extracted signature gives it\n // the exact param/return type to code against.\n // Stdlib gadgets get nothing here by design — `example` covers them.\n const typeLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of hookExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const signatures = extractCallSignaturesFromDts(dts, [exp.hook]);\n const sig = signatures[exp.hook];\n if (sig === undefined) continue; // graceful — couldn't extract.\n typeLines.push(`- \\`${exp.hook}\\`: \\`${sig}\\``);\n }\n }\n const typeBlock =\n typeLines.length > 0\n ? [\n \"\",\n \"**Type** (third-party gadgets — call signature from the wrapper's published `.d.ts`):\",\n \"\",\n ...typeLines,\n ]\n : [];\n\n const hookSection =\n hookExports.length > 0\n ? [header, \"\", ...tableHead, ...rows, ...typeBlock].join(\"\\n\")\n : \"\";\n\n // Component gadgets: their own table + RENDER (not call)\n // teaching. A component export is mounted as a JSX element; the LLM\n // never invokes it like a hook.\n const componentRows = componentExports.map(({ exp, descriptor }) => {\n const compCol = `\\`${exp.component}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${compCol} | ${pkgCol} | ${what.padEnd(53, \" \")} |`;\n });\n\n // `**Props**:` lines for THIRD-PARTY component gadgets. The\n // props-object shape is extracted from the wrapper's published\n // `.d.ts` so the LLM knows the exact JSX attributes of `<X … />`. A\n // component whose `package` has no `.d.ts` entry is skipped\n // (graceful — the `example` still covers it).\n const componentPropsLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of componentExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const propsMap = extractComponentPropsFromDts(dts, [exp.component]);\n const props = propsMap[exp.component];\n if (props === undefined) continue; // graceful — couldn't extract.\n componentPropsLines.push(`- \\`${exp.component}\\`: \\`${props}\\``);\n }\n }\n const componentPropsBlock =\n componentPropsLines.length > 0\n ? [\n \"\",\n \"**Props** (third-party component gadgets — prop shape from the wrapper's published `.d.ts`):\",\n \"\",\n ...componentPropsLines,\n ]\n : [];\n\n const componentSection =\n componentExports.length > 0\n ? [\n \"When the contract declares a component gadget on `clientCapabilities.gadgets`, the export is a COMPONENT — RENDER it as a JSX element (`<X … />`) in the tree you return. Do NOT call it like a hook. The boilerplate has already emitted a direct import per gadget package — `import { <Component>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each component from the package named in the `Package` column. Available registered components:\",\n \"\",\n \"| Component | Package (import from here) | What it does |\",\n \"| --------------------- | ---------------------------------- | ----------------------------------------------------- |\",\n ...componentRows,\n ...componentPropsBlock,\n ].join(\"\\n\")\n : \"\";\n\n return [hookSection, componentSection]\n .filter((section) => section.length > 0)\n .join(\"\\n\\n\");\n}\n\n/**\n * Assemble the coding-agent system prompt. Deterministic — the only\n * variable content comes from the caller-supplied injection fields.\n */\nexport function buildSystemPrompt(inputs: SystemPromptInputs): string {\n const shell = inputs.shellType ?? \"fullscreen\";\n const scr = inputs.screen ?? \"universal\";\n const shellDesc = SHELL_DESCRIPTIONS[shell] ?? SHELL_DESCRIPTIONS.fullscreen;\n const screenDesc = SCREEN_DESCRIPTIONS[scr] ?? SCREEN_DESCRIPTIONS.universal;\n\n const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary();\n const pitfallsBlock = inputs.pitfallsBlock ?? \"\";\n const designSystemDocs = inputs.designSystemDocs ?? \"\";\n const primitivesDoc = inputs.primitivesDoc ?? \"\";\n const wireDoc = inputs.wireDoc ?? \"\";\n // Default to the standard-library seed when no per-app catalog is\n // supplied. Callers that resolve `App.gadgets` thread it through here.\n //\n // `gadgetTypes` carries third-party wrapper `.d.ts` content;\n // `formatGadgetsSection` renders a `Type:` line per third-party\n // gadget from it. When omitted, no `Type:` lines are rendered.\n const gadgetsSection = formatGadgetsSection(\n resolveAppGadgets(inputs.appGadgets),\n inputs.gadgetTypes,\n );\n\n const axisSection =\n inputs.axisDelta && inputs.axisDelta.trim().length > 0\n ? `\\n## Shape Guidance\\n${inputs.axisDelta}\\n`\n : \"\";\n\n return `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.\n\n## Your Task\n${inputs.userRequest}\n\n## Rendering Context\n- **Shell**: \\`${shell}\\` — ${shellDesc}\n- **Screen**: \\`${scr}\\` — ${screenDesc}\n\n## How It Works\n1. Read the boilerplate — typed Props, wire hooks, and layout container are pre-configured\n2. Respond with one apply_changes call — add state, helpers, and JSX\n3. If compilation or evaluation fails, you'll get errors to fix in the next turn\n\n${criteriaBlock}\n${axisSection}\n## Protocol Notes\nThe boilerplate pre-declares every wire hook the contract requires (\\`useAction\\`, \\`useStream\\`, \\`useGguiContext\\`, plus capability hooks from \\`@ggui-ai/gadgets\\` when the contract declares \\`clientCapabilities\\`). Three rules:\n1. **Do NOT delete any pre-declared hook.** \\`self_check\\` fails with \\`wire_preservation:<kind>:<name>\\` if you remove one.\n2. **Consume every hook binding** somewhere in the component — in JSX, a callback, or an effect. Unused bindings fail lint with \\`no-unused-vars\\`.\n3. **Do NOT invent new wire calls.** Every \\`useAction('X')\\`, \\`useStream('X')\\`, \\`useGguiContext('X')\\` etc. MUST correspond to a declared entry on the contract. Calling one that isn't declared fails \\`self_check\\` with \\`wire_undeclared:<kind>:<name>\\` because the runtime has no Context/registration for it and would throw at first paint. If you need a new wire surface, that's a contract authoring step the agent owns — your job is to honor what's declared.\n\nRenaming a binding is fine — the wiring is the string-literal argument, not the identifier.\n\n## Contract surface — four specs + two catalogs\n\nA \\`DataContract\\` declares everything a GguiSession exchanges with the outside world. **Four typed specs** for the four data-flow directions, **two reference catalogs** for tool / hook lookups:\n\n| Surface | Direction | Role |\n| -------------------- | -------------------------- | -------------------------------------------------------------------- |\n| \\`propsSpec\\` | server → UI (one-shot) | Initial render values delivered once at \\`ggui_render\\` |\n| \\`streamSpec\\` | agent → UI (many) | Typed channels for live updates via \\`ggui_emit\\` |\n| \\`actionSpec\\` | UI → agent (events) | Discrete events driving the agent's next turn (consumed via \\`ggui_consume\\`) |\n| \\`contextSpec\\` | UI → server (state mirror) | UI state the agent observes between turns |\n| \\`agentCapabilities.tools\\` | catalog | Tools the contract references via \\`actionSpec[*].nextStep\\` and \\`streamSpec[*].source.tool\\` |\n| \\`clientCapabilities.gadgets\\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \\`useGeolocation\\`) |\n\n**Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.\n\n**Data vs behavior**: the contract describes data flow; the component code describes behavior. Scroll, focus, toast, animation, clipboard write — all component code, never contract fields.\n\n## Defensive coding for absent / late-arriving data\n\nProps arrive at mount and may be partial on first render; later prop changes reach the SAME mounted component via \\`ggui_amend\\` (in-place repaint) on the live channel. Stream channels start empty and fill over time. Context slots start at their declared default (often \\`null\\`). **Never assume a field exists before you read it.**\n\n- **Array iteration**: always default to \\`[]\\` before \\`.map\\`/\\`.filter\\`/\\`.length\\`. Use \\`(props.items ?? []).map(...)\\` not \\`props.items.map(...)\\`. Same for stream.all, stream.latest, etc.\n- **Object access**: optional-chain through nested fields. \\`props.user?.name ?? 'Anonymous'\\` not \\`props.user.name\\`.\n- **Number ops**: default before arithmetic. \\`(props.count ?? 0) + 1\\` not \\`props.count + 1\\`.\n- **Stream latest**: \\`useStream\\` returns \\`{latest: T | null, all: T[], isComplete: boolean}\\`. The default \\`all\\` is \\`[]\\` so it's safe to map; \\`latest\\` is null until the first frame arrives — guard before reading \\`.foo\\`.\n- **Stream reconciliation**: when a stream event carries an \\`action\\` discriminant (e.g. \\`create | move | edit | delete\\`), the channel is a CRUD feed — your handler MUST branch on EVERY value: append on \\`create\\`, drop on \\`delete\\`, replace-by-id on \\`move\\` / \\`edit\\`. Merging only the \"edit\" case silently loses created and deleted items. Reconcile into the SAME state that seeds from \\`props\\` (e.g. \\`useState(() => props.tasks ?? [])\\`) so the seed data and the live feed render as one list — and handle an event whose id is not yet present (a \\`create\\` for an unknown item) by inserting it, not ignoring it.\n- **Props re-sync on repaint**: props the agent owns are the source of truth for display — prefer rendering DIRECTLY from \\`props\\` (controlled, no local copy). When local optimistic state genuinely needs a prop seed (a click bumps a count before the agent confirms), it MUST re-sync on prop change — \\`useEffect(() => setCount(props.count ?? 0), [props.count])\\` — or a \\`ggui_amend\\` repaint applies the new props while the display keeps the stale local value. BAD: \\`const [count, setCount] = useState(props.count ?? 0)\\` alone. GOOD: the same seed + the one-line re-sync effect.\n- **Loading state**: while data is still absent, render \\`<Skeleton>\\` placeholders — never a blank screen. \\`<Skeleton variant=\"text\" />\\` for a text line, \\`variant=\"circle\"\\` for an avatar slot, default \\`rect\\` for a block.\n- **Empty state**: when a list or results array is empty, render \\`<EmptyState title=\"…\" description=\"…\" />\\` — a region that renders nothing when empty looks broken to the user.\n\nUnhandled \\`Cannot read properties of undefined\\` errors trip the iframe error boundary and the user sees \"Something went wrong\" — a regression class the runtime can't recover from.\n\n## Picking the right primitive for user gestures\n\nChoose by what the user is DOING, not where the result goes — the runtime handles the routing.\n\n| Gesture intent | LLM writes | Notes |\n| -------------- | ---------- | ----- |\n| Fire a server-side action | \\`useAction(name)\\` + call \\`dispatch(name, payload)\\` | Every action is agent-routed. The runtime emits an event on \\`ggui_consume\\`; the agent reacts on its next turn. If the contract entry declares \\`nextStep: 'X'\\`, that names the tool the agent SHOULD call next — advisory hint forwarded as event metadata. |\n| Surface state to the agent's context | the auto-generated \\`setSlotName\\` setter (from the boilerplate's \\`useGguiContext\\` line) | The runtime owns useState + Provider; the boilerplate emits one \\`const [slot, setSlot] = useGguiContext<T>('slot')\\` line per declared \\`contextSpec\\` slot. Write plain JSX, no \\`useState\\`, no Provider wrap. Every value change auto-flows to the host LLM (debounced). One-way client → agent — see \"Observable state via \\`contextSpec\\`\" below. |\n| Use a browser capability (camera, mic, geolocation, clipboard, file picker, notifications) | call the hook the contract declared, e.g., \\`const loc = useGeolocation();\\` and \\`await loc.start()\\` | The contract's \\`clientCapabilities.gadgets\\` declares which gadget exports the UI uses. The hook implementations live in \\`@ggui-ai/gadgets\\` (or a third-party package named in the \\`Package\\` column). Read \\`status\\` (\"idle\" / \"prompting\" / \"active\" / \"completed\" / \"denied\" / \"error\") to gate UI, and thread the resolved \\`value\\` into a contextSpec slot or actionSpec payload if the agent needs to see it. |\n| Open external link | Plain \\`<a href=\"https://...\">\\` (or \\`target=\"_blank\"\\`) | External cross-origin clicks are intercepted and routed through the host (security warnings, app-internal navigation, audit). Same-origin links and \\`#fragment\\` jumps stay native. |\n| Toggle fullscreen / chrome | Plain \\`el.requestFullscreen()\\` / \\`document.exitFullscreen()\\` | The native browser API is intercepted; the host adjusts iframe chrome accordingly. Returns a resolved promise so \\`.then()\\` / \\`await\\` chains don't break. |\n\nEvery gesture fires a uniform server-side audit envelope (\\`ggui_runtime_submit_action\\`) so operators see all three patterns in RenderInspector with the same shape.\n\n**Don't import wire hooks for link / display-mode.** \\`useAction\\` is the only wire hook for user gestures; links and fullscreen use plain HTML / browser APIs.\n\n**All actions are agent-routed.** Every action emits an event the agent reacts to on its next turn via \\`ggui_consume\\`. The optional \\`nextStep: '<tool>'\\` field on an \\`actionSpec\\` entry is a HINT naming the tool the agent SHOULD call next — the contract author's recommendation, NOT a binding directive. The agent decides whether to honor it. If you want to declare a tool catalog entry the contract references, add it to \\`agentCapabilities.tools[<name>]\\` with input/output schemas; the cross-ref linter rejects dangling \\`nextStep\\` values that don't resolve to a declared catalog entry.\n\n## Making a primitive interactive — \\`as={Trait}\\`\n\nStructural primitives (\\`Box\\`, \\`Stack\\`, \\`Row\\`, \\`Card\\`) have NO \\`onClick\\` by default. Add interactivity with the \\`as\\` prop — a trait, not a wrapper:\n\n\\`\\`\\`tsx\n<Card as={Clickable} onClick={() => dispatch('select', { id })}\n hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>…</Card>\n\\`\\`\\`\n\n- \\`as={Clickable}\\` → \\`onClick\\` + keyboard activation (Enter/Space) + \\`role=\"button\"\\` + \\`hoverStyle\\`/\\`activeStyle\\`/\\`cursor\\`.\n- \\`as={Hoverable}\\` → \\`hoverStyle\\` only (no click). \\`as={Pressable}\\` → \\`onPress\\` + \\`pressStyle\\`.\n\n\\`as={Trait}\\` is a PROP — it does NOT re-nest the JSX. Never write \\`<Clickable>…</Clickable>\\` around a primitive; put \\`as={Clickable}\\` on the primitive itself. The trait carries the keyboard + ARIA wiring, so don't hand-write \\`onKeyDown\\` / \\`role\\`. Trait components (\\`Clickable\\`, \\`Hoverable\\`, \\`Pressable\\`) import from \\`@ggui-ai/design\\` like everything else — the boilerplate already imports them.\n\n**Semantic components are already interactive** — \\`Button\\` (\\`onClick\\`), \\`Link\\` (\\`href\\`), \\`Input\\` / \\`Select\\` (\\`onChange\\`). Use their own props; never put \\`as\\` on them. \\`Text\\` picks its element with \\`is\\` (\\`<Text is=\"label\">\\`), not \\`as\\`.\n\n**Never nest two interactive elements.** Interactive content MUST NOT contain other interactive content — a gesture on the inner control bubbles to the outer one and fires BOTH handlers (one user click → the action dispatched twice). Do NOT put a \\`Button\\`, \\`Checkbox\\`, \\`Input\\`, \\`Select\\`, \\`Link\\`, or another \\`as={Clickable}\\` primitive inside a \\`Card\\` / \\`Box\\` / \\`Row\\` / \\`Stack\\` that is itself \\`as={Clickable}\\`. Wire each \\`useAction\\` callback to exactly ONE surface: EITHER the whole card is the trigger (interactive container, no interactive children) OR an inner control is the trigger (plain container, no \\`as={Clickable}\\`) — never both. A row with a checkbox: put the action on the \\`Checkbox onChange\\` and leave the row plain.\n\n**\\`Text\\` / \\`Heading\\` accept NO event handlers and NO \\`as\\` — only \\`style\\` / \\`className\\` plus their own typed props.** \\`onClick\\`, \\`onDoubleClick\\`, \\`as={Clickable}\\`, \\`color\\` are all type errors on \\`Text\\`. When the request says a label is \"clickable\", \"editable\", \"edit on click / double-click\", or \"tap to …\", do ONE of these — never put the handler on \\`Text\\`:\n\n\\`\\`\\`tsx\n// Click-to-edit a label: wrap the Text in a Clickable structural primitive.\n<Box as={Clickable} onClick={() => setEditingId(task.id)}\n style={{ cursor: 'pointer' }}>\n <Text weight=\"semibold\">{task.title}</Text>\n</Box>\n\n// Or pair the label with an explicit edit Button (clearer affordance).\n<Row gap=\"xs\" align=\"center\">\n <Text weight=\"semibold\">{task.title}</Text>\n <Button variant=\"ghost\" size=\"xs\" aria-label=\"Edit title\"\n onClick={() => setEditingId(task.id)}>Edit</Button>\n</Row>\n\n// In edit mode, swap the Text for an Input.\n{editingId === task.id\n ? <Input value={draftTitle} onChange={setDraftTitle} label=\"Task title\" />\n : <Text weight=\"semibold\">{task.title}</Text>}\n\\`\\`\\`\n\n## Anti-patterns — DO NOT WRITE\n\nThe following identifiers / shapes are RETIRED from the contract surface as of 2026-05-11. Pre-2026-05-11 examples in your training data may include them; do not reproduce. The linter / CI grep gate rejects:\n\n- \\`useWiredTool\\`, \\`useClientTool\\` — retired hooks. Replace with \\`useAction\\` (events) and the named hook from \\`@ggui-ai/gadgets\\` (browser capabilities).\n- \\`dispatch: { kind: 'tool', tool: '...' }\\` / \\`dispatch: { kind: 'agent', intendedTool: '...' }\\` — retired discriminated-union. Use the flat optional \\`nextStep?: '<tool>'\\` instead.\n- \\`mode: 'host-routed'\\` / \\`mode: 'tool'\\` — retired \\`mode\\` field. Same fix: flat \\`nextStep?\\`.\n- \\`broadcast: {...}\\` on the contract — retired top-level field. Use \\`streamSpec[channel].source: {tool, args?}\\` to declare a tool-fed channel.\n- \\`wiredTools\\` / \\`agentTools\\` (top-level) — retired catalog names. Use \\`agentCapabilities.tools\\`.\n- \\`clientTools\\` / \\`clientCapabilities.capabilities\\` — retired catalog shapes. Use \\`clientCapabilities.gadgets\\` (entries declare hooks, not RPC).\n- \\`@ggui-ai/client-tools\\` — retired package name. Import gadget hooks from \\`@ggui-ai/gadgets\\`.\n- \\`intendedTool\\` — retired. Use \\`nextStep\\` (flat).\n- \\`props: { properties: {...} }\\` as a CONTRACT field — retired. The contract field is \\`propsSpec\\` (the wire \\`props\\` field on render / update still carries VALUES).\n\n## Cross-reference rules\n\nWhen you declare a reference, also declare the catalog entry it points at:\n\n- \\`actionSpec[X].nextStep = 'fetch_inbox'\\` → \\`agentCapabilities.tools.fetch_inbox = { toolInfo: { inputSchema, description?, outputSchema? }, usage?, example? }\\` MUST exist. Cross-ref code: \\`CTR_REF_NEXT_STEP\\`.\n- \\`streamSpec[X].source.tool = 'list_messages'\\` → \\`agentCapabilities.tools.list_messages\\` MUST exist. Cross-ref code: \\`CTR_REF_STREAM_SOURCE\\`.\n- The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \\`CTR_SCHEMA_INCOMPAT\\`.\n\n## clientCapabilities — registered catalog\n\n${gadgetsSection}\n\nEach hook conforms to \\`GadgetHook<TOutput, TOptions>\\`: call \\`start(opts?)\\` to fire, read \\`{value, status, error, stop?}\\`. \\`status\\` walks through \\`idle → prompting → active|completed\\` or routes to \\`denied\\` / \\`error\\` on failure.\n\n3rd-party plugins (Leaflet maps, Mapbox, Stripe, Chart.js, …) are registered via \\`createGguiGadget\\` from \\`@ggui-ai/gadgets\\` and surface in this same table when the operator has added them to \\`App.gadgets\\`. Reference any registered hook by name — render validation rejects hooks not in this catalog with \\`gadget_not_registered\\`.\n\n## Observable state via \\`contextSpec\\`\n\nWhen the contract declares \\`contextSpec\\`, the boilerplate auto-generates one \\`useGguiContext\\` call per slot at the top of your component. The runtime owns the underlying \\`useState\\` and the Provider tree — **you do NOT write \\`useState\\` or any \\`<Provider>\\` wrap yourself**:\n\n\\`\\`\\`tsx\nimport { useGguiContext } from '@ggui-ai/wire';\n\nexport default function Component(props: Props) {\n // AUTO-GENERATED — do not remove or rename:\n const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');\n const [draftText, setDraftText] = useGguiContext<string>('draftText');\n\n // Plain JSX. No Provider wrap. The runtime already wrapped your\n // component in nested SingleSlotProviders before this code ran.\n return (\n <Container>\n <Text>Step {currentStep}</Text>\n <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />\n <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>\n </Container>\n );\n}\n\\`\\`\\`\n\nFor every declared slot you have **\\`slotName\\` + \\`setSlotName\\`** in scope:\n- **Read** the value to render: \\`<Text>Step {currentStep}</Text>\\`\n- **Write** via the setter: \\`setCurrentStep(s => s + 1)\\` (in callbacks, effects, anywhere)\n\nEvery value change is mirrored to the host LLM's context automatically (debounced, default 300ms — adjustable per-slot via \\`entry.debounceMs\\` in the contract). The agent sees the user's interaction state — drafts, current step, hover, selection — without you calling any API.\n\n**When to use the auto-generated state.** Any slot the contract declared. If \\`contextSpec.draftText\\` exists, bind \\`<Input value={draftText} onChange={e => setDraftText(e.target.value)}>\\` so the agent sees the typing live. If \\`contextSpec.currentStep\\` exists, render the step indicator from \\`currentStep\\` and bump it via \\`setCurrentStep\\` in your \"next\" callback.\n\n**When NOT to use it.** Local UI state the contract did NOT declare — \\`isDropdownOpen\\`, hover flags, animation phase, ephemeral toggles. For those, use a plain \\`useState\\` directly. The runtime ignores undeclared state.\n\n**\\`contextSpec\\` direction is one-way: client → agent.** The agent uses \\`propsSpec\\` (via \\`ggui_amend\\` for in-place repaints of this mount, or \\`ggui_update\\` when it mints a new history card) and \\`streamSpec\\` (via the live channel) to push state TO the client. Don't try to write to the agent via \\`contextSpec\\` — there is no return path.\n\n**Schema mismatches drop silently.** If you set a value that doesn't match the slot's schema (e.g. a string into a \\`{type: 'number'}\\` slot), the runtime logs a dev \\`console.warn\\` and skips the post. Make sure your setter calls produce values that match the declared shape.\n\n${pitfallsBlock}\n\n## Reference: Wire Hooks\n${wireDoc}\n\n${DESIGN_SYSTEM_GUIDANCE}\n\n### CSS Token Documentation\n${designSystemDocs}\n\n### Component Reference\n${primitivesDoc}\n`;\n}\n\n/**\n * Hand-written design-system guidance embedded in every coding-agent\n * system prompt. Lists prop-value enums, branded color strategy, and\n * responsive/parameterization rules that make a generated component\n * feel polished — the system prompt without it would only list\n * primitive *names*. Exported so `prompt-type-drift.test.ts` can\n * verify its enum claims against the auto-generated primitive catalog.\n */\nexport const DESIGN_SYSTEM_GUIDANCE = `## Imports & Component Surface\n\nImport ONLY from: \\`react\\`, \\`@ggui-ai/design\\`, \\`@ggui-ai/wire\\`. The ENTIRE design system — every primitive, component, composition and trait — is exported from the single \\`@ggui-ai/design\\` entry: \\`import { Card, Grid, Stack, Modal, Clickable } from '@ggui-ai/design'\\`. There are NO subpaths (\\`/primitives\\`, \\`/components\\`, …) — never import from them. Use the design components — DO NOT use raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) or Tailwind classes; those render unstyled in the iframe runtime.\n\nAvailable primitives (all from \\`@ggui-ai/design\\`):\n- Layout: Box, Container, Stack, Row, Grid, Spacer, Divider\n- Typography: Heading, Text, Link\n- Form: Button, Input, TextArea, Checkbox, Toggle, RadioGroup, Select, Slider\n- Display: Card, Alert, Badge, Avatar, Image, Icon, Progress, Spinner, Skeleton, Tooltip\n- Composite: Accordion, Tabs, Table, Toast\n\nAvailable compound components (all from \\`@ggui-ai/design\\`):\n- Autocomplete, Breadcrumb, Dropdown, EmptyState, FormField, Markdown, MarkdownInline, MenuItem, Pagination, SearchField, Stat, Stepper, Tag\n\n**Choosing between similar components** — pick by intent, don't guess:\n- **Pick from options**: one value from a short fixed list (a form field) → \\`Select\\`. Type-to-filter a long list, then pick → \\`Autocomplete\\`. A menu of actions off a button (edit / delete / …) → \\`Dropdown\\`. A search box that filters displayed content → \\`SearchField\\`.\n- **Tabular data** → \\`Table\\`. Reach for \\`DataTable\\` ONLY when you need built-in sorting / pagination / row-selection.\n- **Messaging**: an inline message in the layout flow → \\`Alert\\`. A transient popup → \\`Toast\\`. A panel listing many notifications → \\`NotificationCenter\\`.\n- **Step progress**: a wizard's step indicator → \\`Stepper\\`. NOT \\`Tabs\\` (implies free navigation), NOT \\`Progress\\` (continuous bar), NOT \\`Breadcrumb\\` (hierarchy).\n- **Containers**: width-constrain a page region → \\`Container\\`. A visually-contained surface (background + shadow + border) → \\`Card\\`. Plain grouping / spacing with no chrome → \\`Box\\`.\n\nEXACT primitive prop values (other values are silently ignored — the design system maps them to defaults):\n- \\`<Text size=\"...\">\\` — ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\`. For a HUGE number/temperature, use \\`<Text size=\"4xl\" weight=\"bold\">\\`. \\`caps\\` uppercases with letter-spacing — the eyebrow/overline label look is \\`<Text size=\"xs\" weight=\"semibold\" caps tone=\"muted\">\\`.\n- \\`<Text weight=\"...\">\\` — \\`normal | medium | semibold | bold\\`.\n- \\`<Text tone=\"...\">\\` — typed semantic slot. \\`default | muted | subtle | emphasized | loud | success | warning | error | info | inverse | inherit\\`. The theme decides what each tone LOOKS like — \\`muted\\` is a quiet warm grey on Claudic, a cool slate on Indigo. \\`tone\\` is the ONLY way to set Text color; the legacy \\`color=\"...\"\\` prop has been removed.\n- \\`<Heading level={1|2|3|4|5|6}>\\` — sizes are preset by level (h1 = 4xl bold, h2 = 3xl bold, h3 = 2xl semibold). Pass a number, not \\`level=\"h1\"\\`. Heading uses the same \\`tone\\` slot vocabulary as Text.\n- \\`<Icon name=\"...\" tone=\"...\">\\` / \\`<Spinner tone=\"...\">\\` / \\`<Link href=\"...\" tone=\"...\">\\` / \\`<Divider tone=\"...\">\\` — same \\`tone\\` vocabulary as Text. Default = \\`currentColor\\` (Icon), primary-tinted (Spinner / Link), outlineVariant (Divider). Use \\`tone=\"inherit\"\\` when you want the element to track the parent's foreground color (e.g. an Icon next to muted text).\n- \\`<Button variant=\"...\">\\` — \\`primary | secondary | outline | ghost | danger\\`. Sizes \\`xs | sm | md | lg\\`. Use \\`primary\\` for the main action — renders in the brand color automatically.\n- \\`<Card padding=\"lg\" shadow=\"md\" radius=\"lg\" surface=\"default\">\\` — shadow \\`none|sm|md|lg|xl\\`, radius \\`none|sm|md|lg|xl\\`. \\`surface\\` slot picks the fill: \\`default | elevated | sunken | accent | inverted | transparent\\`. Use \\`inverted\\` for dark testimonial-style cards on a light theme; \\`accent\\` for branded fills.\n- \\`<Box surface=\"...\">\\` — same surface slots as Card. \\`surface\\` is the ONLY theme-tracking background prop; the legacy \\`background=\"...\"\\` prop has been removed. For non-theme-mapped brand colors (a partner's exact brand hex like Stripe purple), use the typed escape \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">\\` — both props are required, and \\`assetSemantic\\` MUST be a non-empty human-readable label. Tier-0 self-check rejects every other hex / rgba on Box.\n- \\`<Stack gap=\"...\">\\` / \\`<Row gap=\"...\">\\` — \\`gap\\` takes the **spacing scale** (next bullet). \\`align\\` (cross-axis) is ONLY \\`start | center | end | stretch\\` and \\`justify\\` (main-axis) is ONLY \\`start | center | end | between | around | evenly\\` — NEVER the raw CSS values \\`flex-start\\` / \\`flex-end\\` / \\`space-between\\`, which are type errors.\n- **Spacing scale** — \\`gap\\` (Stack / Row / Grid) and \\`padding\\` (Card / Box / Container) take a t-shirt size: \\`none | xs | sm | md | lg | xl | 2xl\\`. Each resolves to a \\`--ggui-spacing-*\\` token (xs≈4px, sm≈8px, md≈16px, lg≈24px, xl≈32px, 2xl≈48px). A bare number is treated as pixels. NEVER pass a raw CSS length such as \\`gap=\"8px\"\\` — it is silently dropped by the browser and the gap collapses to 0; use the scale name (\\`gap=\"sm\"\\`).\n- \\`<Grid columns={N} gap=\"md\">\\` — 2-D layout (rows AND columns). Reach for it for card galleries, stat grids and dashboards — NEVER hand-roll \\`style={{ display: 'grid' }}\\`. When the request names exact per-breakpoint counts (\"3 per row on desktop, 1 on mobile\"), pass a map: \\`<Grid columns={{ base: 1, md: 3 }}>\\` (breakpoints \\`sm\\`/\\`md\\`/\\`lg\\`/\\`xl\\`; the design system emits the media queries). For an open-ended gallery where any column count is fine, use \\`<Grid minColumnWidth={220}>\\` — it fits as many equal columns as the width allows. \\`radius\\` (Card / Box / Image) takes the scale \\`none | sm | md | lg | xl\\`.\n- \\`<Stat label=\"…\" value=\"…\" delta=\"+12%\" trend=\"up\">\\` — KPI display (label + big value + trend-coloured delta + optional \\`icon\\`). \\`trend\\` is \\`up | down | neutral\\` (delta renders green / red / muted). Reach for it for any \"show a number\" UI; drop several into a \\`<Grid>\\` for a stat grid instead of hand-building label+value pairs.\n- \\`<Stepper steps={STEPS} current={step} />\\` — display-only step indicator for wizards/checkouts. \\`steps\\` is a top-level \\`const\\` array of labels; \\`current\\` is YOUR zero-indexed \\`useState\\` value; \\`orientation\\` is \\`horizontal | vertical\\`; optional \\`onStepClick={(i) => …}\\` makes steps clickable. Stepper never owns navigation state — your Next/Back handlers move \\`current\\`.\n- \\`<Badge variant=\"...\">\\` — \\`default | primary | secondary | success | warning | error | info\\` for colored pills. Great for status/condition labels. There is NO \\`neutral\\` variant — use \\`default\\` (or \\`secondary\\`) for an un-tinted pill.\n\n**Color choice rule of thumb.** Reach for typed slots first: Button \\`variant\\`, Badge \\`variant\\`, Alert \\`variant\\`, Text/Heading/Icon/Spinner/Link/Divider \\`tone\\`, Box/Card \\`surface\\`. NEVER hardcode hex \\`#XXXXXX\\`, rgba, or hsl — tier-0 self-check rejects them with \\`tokens:hex-color\\` / \\`tokens:hardcoded-color-fn\\` and the LLM must remediate. Hardcoded colors break the operator's theme switch (Indigo → Claudic → Cyberpunk preset has zero effect on a card hardcoded with \\`background: '#000'\\`).\n\n**Asset-color escape (Box only).** When you genuinely need a non-theme color — a partner's exact brand hex (Stripe purple \\`#635BFF\\`, Slack aubergine \\`#4A154B\\`), a fixed product surface — use \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">…</Box>\\`. The \\`assetSemantic\\` is REQUIRED and MUST be a non-empty human-readable label that documents intent. Tier-0 allows hex inside this typed pair; one without the other fails the check. Reach for \\`surface\\` first — \\`assetColor\\` is rare.\n\n## Accessibility (REQUIRED)\n\nThe design-system primitives are accessible by construction — they emit their own roles, labels, keyboard handlers, and error wiring. Your job is to USE them correctly, NOT to re-declare ARIA on top of them.\n\n1. **Form inputs** — give every \\`Input\\` / \\`TextArea\\` / \\`Select\\` a \\`label\\` prop. The primitive renders its own \\`<label htmlFor>\\`, and exposes \\`aria-invalid\\` + \\`aria-describedby\\` for errors. Do NOT add a separate \\`<Text>\\` label or your own \\`htmlFor\\` — that double-labels the field.\n \\`\\`\\`tsx\n <Input label=\"Email\" value={email} onChange={setEmail} type=\"email\" />\n \\`\\`\\`\n2. **Don't re-declare built-in ARIA.** \\`Progress\\`, \\`RadioGroup\\`, \\`Tabs\\`, \\`Toggle\\`, \\`Slider\\`, \\`Spinner\\`, \\`Alert\\`, \\`Accordion\\` already carry the correct \\`role\\` / \\`aria-*\\`. \\`Card as={Clickable}\\` already adds \\`role=\"button\"\\` + keyboard activation. Adding your own is redundant and often wrong.\n3. **Icons are decorative by default** — \\`<Icon name=\"check\" />\\` is hidden from screen readers, which is correct for an icon sitting next to text. Add \\`aria-label\\` ONLY for a standalone, meaning-bearing icon with no adjacent text. Icon-only \\`Button\\`s still need \\`aria-label\\` on the **Button** itself.\n4. **Live & streaming data** — wrap any region whose content updates on its own (a \\`useStream\\` \\`.latest\\` value, a live clock, an \"N new\" counter, a flashing price) in an element with \\`aria-live=\"polite\"\\` so screen readers announce the change.\n5. **Headings nest** — one \\`<Heading level={1}>\\` per screen, \\`level={2}\\` for sections, \\`level={3}\\` for subsections. Never skip or invert levels.\n6. **Buttons** — descriptive text content; icon-only buttons need \\`aria-label\\`. Announce busy state: \\`<Button disabled={isLoading} aria-busy={isLoading}>{isLoading ? 'Submitting…' : 'Submit'}</Button>\\`.\n7. **Stateful controls announce their state.** Toggleable / selectable / expandable things use the primitive that carries the semantics (\\`Checkbox\\`, \\`Toggle\\`, \\`Tabs\\`, \\`Accordion\\`) — never a styled \\`Box\\`/\\`Icon\\` that only *looks* checked. When you hand-roll one with \\`as={Clickable}\\`, \\`Clickable\\` adds button + keyboard semantics but NOT state — add it yourself: \\`role=\"checkbox\"\\` + \\`aria-checked={done}\\` on a toggleable row, \\`aria-pressed\\` on a toggle button, \\`aria-selected\\` on the chosen item, \\`aria-expanded\\` on an open/close affordance. Styling (strikethrough, color, a check icon) must never be the only carrier of state.\n\n## Design System Usage (CRITICAL)\n\nEVERY color, spacing, typography, shadow, and radius value MUST come from design-system CSS variables. The runtime injects them on \\`:root\\`.\n\nMANDATORY:\n1. NEVER use hardcoded hex colors like \\`#7c3aed\\` — ONLY \\`var(--ggui-color-*)\\` tokens.\n2. NEVER use CSS gradients with custom colors. If you need a gradient: \\`linear-gradient(to bottom, var(--ggui-color-primary-500, #0ea5e9), var(--ggui-color-primary-700, #0369a1))\\`.\n3. NEVER invent your own palette. The system provides primary, neutral, success, warning, error, and info — use ONLY these.\n4. ALWAYS include fallback values: \\`var(--ggui-color-primary-600, #0284c7)\\`.\n\nToken categories:\n- Brand: \\`var(--ggui-color-primary-600, #0284c7)\\`, \\`var(--ggui-color-primary-50, #f0f9ff)\\`\n- Text: \\`var(--ggui-color-onSurface, #18181b)\\`, \\`var(--ggui-color-onSurfaceVariant, #52525b)\\`\n- Backgrounds: \\`var(--ggui-color-surface, #fafafa)\\`, \\`var(--ggui-color-surfaceVariant, #f4f4f5)\\`\n- Borders: \\`var(--ggui-color-outline, #d4d4d8)\\`\n- Spacing: \\`var(--ggui-spacing-4, 16px)\\`, \\`var(--ggui-spacing-6, 24px)\\`\n- Typography: \\`var(--ggui-font-size-sm, 14px)\\`, \\`var(--ggui-font-weight-semibold, 600)\\`\n- Shadows: \\`var(--ggui-shape-shadow-sm)\\`, \\`var(--ggui-shape-shadow-md)\\`, \\`var(--ggui-shape-shadow-lg)\\`\n- Radius: \\`var(--ggui-shape-radius-md, 8px)\\`, \\`var(--ggui-shape-radius-lg, 12px)\\`\n\nPrefer primitives' built-in styling props over inline styles when possible.\n\n### Branded Color Strategy\n\nUse the FULL primary palette throughout the component — NOT only on submit buttons. A well-themed component feels distinctly branded, not gray-with-one-colored-button.\n\n| Element | Token | Purpose |\n|---------|-------|---------|\n| Section headers, hero areas, highlight strips | \\`primary-50\\` / \\`primary-100\\` | Subtle branded backgrounds |\n| Borders, dividers, focus rings, input focus | \\`primary-200\\` / \\`primary-300\\` | Branded structure |\n| Icons, links, labels, active indicators | \\`primary-500\\` / \\`primary-600\\` | Core accent color |\n| Buttons, CTAs, filled interactive elements | \\`primary-600\\` / \\`primary-700\\` | Primary actions |\n| Headings on light primary backgrounds | \\`primary-800\\` / \\`primary-900\\` | High-contrast branded text |\n\nUse semantic tokens (\\`onSurface\\`, \\`onSurfaceVariant\\`) for body text and secondary info. NEVER use raw \\`neutral-*\\` or \\`gray-*\\` for body text — they break in dark themes.\n\n### Theme-Agnostic Design\n\nComponents MUST be theme-agnostic — they reference CSS variables but NEVER assume a specific style. The theme decides what \\`primary-600\\` looks like.\n\nDO:\n- Use \\`var(--ggui-color-primary-*)\\` for brand elements — the theme controls what \"primary\" means\n- Use \\`var(--ggui-shape-shadow-*)\\` for depth, \\`var(--ggui-shape-radius-*)\\` for corners\n- Use semantic color roles: primary for brand, surface/onSurface for structure, success/error/warning for state\n\nDON'T:\n- Don't assume primary is blue — could be red, green, purple\n- Don't hardcode gradients tuned for a specific theme\n- Don't use fixed shadow values\n\nVisual hierarchy via tokens:\n- Elevated sections: \\`var(--ggui-shape-shadow-md)\\` + \\`var(--ggui-shape-radius-lg)\\`\n- Highlighted regions: \\`var(--ggui-color-primary-50)\\` background\n- Active/selected: \\`var(--ggui-color-primary-100)\\` background\n- Section headers: \\`var(--ggui-color-primary-600)\\` text or border-bottom\n\n## Responsive Design (CRITICAL)\n\nGenerated components become reusable blueprints — the same blueprint serves phones, tablets, desktops, spatial headsets. Design for ALL screen sizes:\n\n1. Design tokens for ALL spacing — never hardcode pixel values for padding/margins/gaps. Use the named spacing scale on props (\\`gap=\"md\"\\`, \\`padding=\"lg\"\\`); for inline \\`style\\` use \\`var(--ggui-spacing-*, …)\\`.\n2. Relative/fluid units — prefer \\`%\\`, \\`em\\`, \\`rem\\`, \\`min()\\`, \\`max()\\`, \\`clamp()\\` over fixed \\`px\\`.\n3. Fluid widths — \\`max-width\\` with \\`width: 100%\\`. Never set a fixed width.\n4. Compact padding — components are embedded in containers that provide their own chrome.\n5. No raw \\`@media\\` queries in component code — for a layout that must change by breakpoint, use \\`<Grid columns={{ base: 1, md: 3 }}>\\` (the design system emits the media queries for you) or a fluid \\`minColumnWidth\\` grid.\n\n## Data Parameterization (CRITICAL)\n\nGenerated components are CACHED blueprints reused across requests. NEVER hardcode request-specific data (names, cities, numbers, dates) into the component body. Define data as default prop values so the blueprint works for ANY similar request:\n\n\\`\\`\\`tsx\n// BAD — hardcoded, only works for Tokyo\nconst city = \"Tokyo\";\nconst temp = 18;\n\n// GOOD — parameterized via props with defaults from the request\ninterface Props {\n city?: string;\n temperature?: number;\n}\nexport default function WeatherCard({ city = \"Tokyo\", temperature = 18 }: Props) {\n // A controller can override for Seoul, Paris, etc.\n}\n\\`\\`\\`\n\nRules:\n1. All request-specific data → props with defaults. City names, tickers, user names, dates, counts.\n2. Layout and styling are universal. Colors, spacing, structure — these are the reusable part.\n3. Default values come from the current request — so the component renders correctly standalone.\n4. Props interface must be typed and exported.\n\n## Component Structure\n\nKeep JSX nesting depth to 3–5 levels. When deeper, extract repeated/complex sections into helper components — named functions defined above the main Component in the same file. Helpers take data + callbacks via props; they don't own state.\n\n\\`\\`\\`tsx\nimport { useState } from 'react';\nimport { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';\n\ninterface Props {\n onSubmit?: (data: unknown) => void;\n}\n\nfunction ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {\n return <Card padding=\"md\">…</Card>;\n}\n\nexport default function GeneratedComponent({ onSubmit }: Props) {\n return (\n <Container>\n {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}\n </Container>\n );\n}\n\\`\\`\\`\n\n## Aesthetic Guidance (READ CAREFULLY — this is what separates \"polished\" from \"ok\")\n\n### Visual hierarchy — the SCALE GAP rule\n\nA polished UI has ONE hero that dominates. Everything else supports it. Bad layouts have everything at similar sizes — the eye has nowhere to land. The rule:\n\n**Hero metric vs supporting text must have a 2–3× size gap.** If the hero is the temperature, score, count, status, price — it's ENORMOUS. Use \\`<Text size=\"4xl\" weight=\"bold\">\\` — the largest \\`size\\` the type allows (\\`4xl\\` = 36px). Pair it with a small supporting label (\\`size=\"sm\"\\`, ~14px) so the gap reads as 2–3×. The hero number should feel oversized compared to the location/title around it. \\`size\\` accepts ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\` — \\`5xl\\` / \\`6xl\\` are NOT valid and fail tier-0 type-check.\n\n\\`\\`\\`tsx\n// BAD — temperature is the same size as the location heading\n<Heading level={1}>Seoul, South Korea</Heading>\n<Text size=\"lg\" weight=\"bold\">18°C</Text>\n\n// GOOD — temperature dominates (4xl), location supports it (sm)\n<Text size=\"sm\" tone=\"muted\">Seoul, South Korea</Text>\n<Text size=\"4xl\" weight=\"bold\">18°C</Text>\n<Text size=\"lg\" tone=\"muted\">Partly Cloudy · Feels like 16°C</Text>\n\\`\\`\\`\n\n### Color discipline — the 60/30/10 rule\n\nDon't paint everything in primary. Use:\n- **60% surface** (\\`var(--ggui-color-surface)\\` / \\`onSurface\\`) — body text, default backgrounds, structure\n- **30% surfaceVariant + onSurfaceVariant** — secondary text, captions, labels, dividers\n- **10% primary** — hero number, ONE highlight element, CTAs, brand accent\n\nIf your component is 100% purple text on purple backgrounds, you've lost the eye. Headings can be \\`onSurface\\` (dark neutral) — they'll still feel weighty. Save the primary palette for one or two STAR moments.\n\n\\`\\`\\`tsx\n// BAD — everything purple, eye has no anchor\n<Heading tone=\"emphasized\">Title</Heading>\n<Text tone=\"emphasized\">42</Text>\n<Text tone=\"emphasized\">all body text</Text>\n\n// GOOD — hero pops, body is neutral, primary is reserved\n<Heading>Title</Heading> {/* defaults to onSurface */}\n<Text size=\"4xl\" weight=\"bold\" tone=\"emphasized\">42</Text>\n<Text tone=\"muted\">all body text</Text>\n\\`\\`\\`\n\n### Visual rhythm — vary your card treatments\n\nA row of identical flat tiles feels monotone. Use card-treatment variation to create rhythm:\n- **Hero card**: \\`<Card padding=\"xl\" shadow=\"lg\" radius=\"xl\">\\` with branded gradient background — anchors the eye\n- **Stat tiles**: \\`<Card padding=\"md\" shadow=\"sm\" radius=\"md\">\\` with surface bg — secondary\n- **Inline rows / list items**: no card chrome at all, just \\`<Stack gap=\"sm\">\\` with dividers — tertiary\n\nThe hero should literally have higher elevation than the supporting tiles. If everything has \\`shadow=\"md\"\\`, nothing does.\n\n### Iconography — emoji + Icon are visual weight on the cheap\n\nDon't render text-only metrics. A weather widget without a sun/cloud, a stock card without an arrow, a status panel without a colored dot — all feel undersold. Pair every hero metric with an icon or emoji at large size:\n\n\\`\\`\\`tsx\n<Row gap=\"md\" align=\"center\">\n <Text size=\"3xl\">☀️</Text>\n <Stack gap=\"xs\">\n <Text size=\"4xl\" weight=\"bold\">18°C</Text>\n <Text size=\"sm\" tone=\"muted\">Sunny · feels like 16°</Text>\n </Stack>\n</Row>\n\\`\\`\\`\n\nUse \\`<Icon name=\"...\" />\\` (Lucide icon names in kebab-case) for line icons; emoji directly for status/weather/mood. Both are valid. For per-stat tiny accents, use a small icon next to the label.\n\n### Spacing — generosity beats compactness\n\nHero sections should feel airy. Use \\`padding=\"xl\"\\` (32px) on the main card, not \\`padding=\"md\"\\`. Whitespace IS design. A cramped polished card looks worse than a roomy plain one.\n\n### Concrete recipes\n\n- **Hero metric card** (weather, stock, score): hero number at \\`size=\"4xl\"\\` (the max), icon/emoji at \\`size=\"3xl\"\\` next to it (use \\`<Row gap=\"md\">\\`), supporting label at \\`size=\"sm\"\\` muted, branded gradient bg, \\`shadow=\"lg\"\\`, \\`padding=\"xl\"\\`.\n- **Stat grid** (3–6 quick metrics): \\`<Grid columns={3} gap=\"md\">\\` of \\`<Stat>\\` — each \\`<Stat label=\"…\" value=\"…\" delta=\"…\" trend=\"…\" />\\` handles the label-on-top / value-below / trend-coloured-delta layout for you. Wrap each in a \\`<Card padding=\"md\" shadow=\"sm\">\\` if you want tile chrome.\n- **List item** (forecast day, todo, message): no card per item, use \\`<Stack gap=\"md\">\\` with each row as \\`<Row gap=\"md\">\\` of icon + content + meta. Add \\`<Divider>\\` between rows.\n- **Multi-step wizard** (survey, onboarding, checkout): \\`<Stepper steps={STEPS} current={step} />\\` at the top, the current step's fields below, Next/Back buttons that move \\`step\\`. Don't hand-roll a \"2 of 4\" indicator.\n- **Key-value rows** (specs, order summary, flight details): \\`<Stack gap=\"sm\">\\` of \\`<Row justify=\"between\">\\` — label as \\`<Text size=\"sm\" tone=\"muted\">\\`, value as \\`<Text size=\"sm\" weight=\"medium\">\\`.\n- **Section header**: \\`<Heading level={2}>\\` left-aligned, optional \\`<Badge>\\` to its right for count/status, optional muted caption below.\n- **CTA section**: ONE primary button. Other actions as ghost/outline. Don't stack three primary buttons.\n\n## Quality Checklist (verify before returning)\n\n- [ ] Imports ONLY from: react, @ggui-ai/design, @ggui-ai/wire\n- [ ] No raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) — uses primitives\n- [ ] ZERO hardcoded hex colors — every color is \\`var(--ggui-color-*, fallback)\\`\n- [ ] No raw pixel values for spacing — all via \\`var(--ggui-spacing-*)\\` tokens\n- [ ] Primary palette used throughout (headers, borders, icons) — not just buttons\n- [ ] Typed Props interface exported; request-specific data is a prop with default\n- [ ] Every Input/TextArea/Select has a \\`label\\` prop (no separate \\`<Text>\\` label)\n- [ ] Icon-only buttons have \\`aria-label\\`; no redundant \\`role\\`/\\`aria-*\\` on primitives\n- [ ] Toggleable/selected/expanded state is ARIA-expressed (\\`aria-checked\\`/\\`aria-pressed\\`/\\`aria-selected\\`/\\`aria-expanded\\`) — never style-only\n- [ ] Live/streaming regions wrapped in \\`aria-live=\"polite\"\\`\n- [ ] Headings nest — one \\`level={1}\\`, then \\`level={2}\\`/\\`{3}\\` — never skipped or inverted\n- [ ] Wire hooks (\\`useAction\\`, \\`useStream\\`) imported from \\`@ggui-ai/wire\\` and consumed`;\n","// packages/ui-gen/src/tools.ts\n//\n// LLM tool grammars used by the generation stage. Primary tool =\n// `apply_changes` (multi-range patch). Scoped fallback =\n// `apply_changes` with `maxItems=1` for transport-error recovery\n// (malformed_tool_call retries). Plus:\n// - hashline variants (`APPLY_CHANGES_HASHLINE_TOOL[_FLAT]`) used\n// when the `hashline: \"v2\"` policy profile selects them;\n// - flat-code variant (`APPLY_CHANGES_TOOL_FLAT`) — the shipped\n// default;\n// - helper tools (`GET_ICONS_TOOL`, `GET_COMPONENTS_INFO_TOOL`,\n// `WRITE_PLAN_TOOL`, `REWRITE_TOOL`) wired into the\n// `selectTurnTools` path.\n//\n// Harness `what.codingTools` can override with any subset; alternate\n// patch grammars swap in by replacing the tool list + a matching\n// `applyPatch` implementation.\n//\n// The tool definitions in this file are static JSON schemas + prompt\n// text. The decision logic (which profile picks which tool,\n// model-registry overrides, environment gating) lives in\n// `./harness/policy.ts` + `run-coding-turn.ts::selectTurnTools` —\n// nothing in this file reads a profile or an env var; these are data.\n\nimport type { LLMToolDef } from \"./llm.js\";\nexport type { LLMToolDef };\n\n/** Standard multi-range patch tool — surgical edits. */\nexport const APPLY_CHANGES_TOOL: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit: replace line ranges in ui.tsx with new code. Use line numbers from the Current File (shown as N│). Preferred for targeted changes — fixing one hook, renaming a prop, swapping a component, closing a missing tag. The patch is ALWAYS applied to the workspace even if the resulting file has syntax errors — the error location is returned as guidance so you can iterate. If the file is in a tangled state and patches aren't converging cleanly, use `write` to rewrite from scratch.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces lines startLine through endLine (inclusive) with the new code lines. Applied bottom-to-top to preserve line numbers.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"number\",\n description: \"First line to replace (from the N│ numbers in Current File)\",\n },\n endLine: { type: \"number\", description: \"Last line to replace (inclusive)\" },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines. One source line per array element. Avoid embedding newlines inside an element. For long JSX blocks, split at statement boundaries across multiple changes.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n allowBroken: {\n type: \"boolean\",\n description:\n \"Opt-in: commit the patch even if the resulting file fails syntax preflight. Use when you want to iterate across multiple turns and accept a broken intermediate state (e.g., split a big JSX refactor into 2 patches). Default false (strict preflight).\",\n },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Scoped fallback variant for transport-error retries. Used by the LLM\n * router when `malformed_tool_call` exhausts the standard retry budget —\n * forces a single small change (≤20 lines) so the payload fits within the\n * provider's JSON-emission ceiling. Universal signal; only Gemini hits this\n * path today, but the handler is not provider-gated.\n */\nexport const APPLY_CHANGES_TOOL_SCOPED: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Replace ONE small line range in ui.tsx. Narrow schema for transport-error recovery: emit a single change covering at most 20 lines.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n minItems: 1,\n maxItems: 1,\n description: \"Single change. endLine - startLine ≤ 20.\",\n items: {\n type: \"object\",\n properties: {\n startLine: { type: \"number\", description: \"First line to replace\" },\n endLine: {\n type: \"number\",\n description: \"Last line (inclusive). Keep endLine - startLine ≤ 20.\",\n },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines (one source line per element, no embedded newlines). ≤ 20 elements.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/** Hashline variant of APPLY_CHANGES_TOOL.\n * When the `hashline-v2` policy profile is active, this tool is\n * advertised in place of the standard numeric-line APPLY_CHANGES_TOOL.\n * The `startLine` and `endLine` fields are STRINGS in `\"N:hh\"` format\n * (e.g., `\"47:a3\"`) — where `hh` is the 2-char content hash shown in\n * the `## Current File` block. The handler validates the hash against\n * the current file; if it mismatches, the edit is rejected with\n * HASHLINE_STALE so the LLM re-reads before patching. */\nexport const APPLY_CHANGES_HASHLINE_TOOL: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit with line-hash verification. Replace line ranges in ui.tsx. Line refs use the format `N:hh` from the Current File block (e.g., `47:a3`) — the 2-char hash anchors your view so the edit is rejected if the file drifted under you. Always use the exact hashes shown in the latest Current File view. The patch is applied even if the resulting file has syntax errors (the error location is returned as guidance); but edits with mismatched hashes are rejected BEFORE apply.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces `startLine` through `endLine` (inclusive) with the new code lines. Line refs use the `N:hh` format.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"First line to replace, as `N:hh` (e.g., `47:a3`). The hash MUST match the line's hash in the latest Current File view. Format is line-number, colon, 2 lowercase hex chars — enforced by JSON schema pattern.\",\n },\n endLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"Last line to replace, as `N:hh` (e.g., `83:b1`). Hash MUST match. Format: line-number, colon, 2 lowercase hex chars.\",\n },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines. One source line per array element. No embedded newlines.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Flat-code variant of APPLY_CHANGES_TOOL.\n *\n * Identical to APPLY_CHANGES_TOOL except `code` is a single string with\n * `\\n`-separated lines instead of an array. One level of JSON nesting\n * shallower — a deeply-nested schema can trip some model decoders. The\n * handler in `coding-agent/tools.ts` accepts both shapes.\n */\nexport const APPLY_CHANGES_TOOL_FLAT: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit: replace line ranges in ui.tsx with new code. Use line numbers from the Current File (shown as N│). Preferred for targeted changes. The `code` field is a single string with newlines (`\\\\n`) between lines. The patch is ALWAYS applied even if the resulting file has syntax errors — the error is returned as guidance. For a full rewrite, use `rewrite`.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces lines startLine through endLine (inclusive). Applied bottom-to-top.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"number\",\n description: \"First line to replace (from the N│ numbers in Current File)\",\n },\n endLine: { type: \"number\", description: \"Last line to replace (inclusive)\" },\n code: {\n type: \"string\",\n description:\n \"New code as a single string. Separate lines with `\\\\n`. Preserve leading indentation inside the string.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n allowBroken: {\n type: \"boolean\",\n description:\n \"Opt-in: commit the patch even if the resulting file fails syntax preflight.\",\n },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Flat-code + hashline variant.\n * Combines `code: string` flatness with `N:hh` hash-verified line refs\n * from hashline-v2.\n */\nexport const APPLY_CHANGES_HASHLINE_TOOL_FLAT: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit with line-hash verification. Replace line ranges in ui.tsx using `N:hh` references from the Current File (e.g. `47:a3`). The `code` field is a single string with newlines between lines. Edits with mismatched hashes are rejected before apply.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description: \"Array of changes. Line refs use `N:hh` format.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"First line to replace, as `N:hh` (e.g., `47:a3`). Hash MUST match the latest Current File view. Format: line-number, colon, 2 lowercase hex chars.\",\n },\n endLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"Last line to replace, as `N:hh` (e.g., `83:b1`). Hash MUST match.\",\n },\n code: {\n type: \"string\",\n description:\n \"New code as a single string. Separate lines with `\\\\n`. Preserve leading indentation.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/** Helper icon-lookup tool — not a patch grammar, attached to the same LLM turn. */\nexport const GET_ICONS_TOOL: LLMToolDef = {\n name: \"get_available_icons\",\n description: 'List all 185 available Lucide icon names for the <Icon name=\"...\"> component.',\n parameters: { type: \"object\", properties: {} },\n};\n\n/**\n * Component-docs fetch tool (tool-driven primitive docs). Advertised\n * alongside `apply_changes` when `ContextPolicy.primitiveIndex` is\n * active (a compact name+description index replaces the full ~130KB\n * primitives doc in the system prompt; the LLM fetches the full\n * per-component API on demand).\n *\n * The handler lives in `coding-agent/tools.ts` under the\n * `get_components_info` case.\n */\nexport const GET_COMPONENTS_INFO_TOOL: LLMToolDef = {\n name: \"get_components_info\",\n description:\n \"Fetch full prop API + example + variant mappings for one or more design-system components. Use when the compact index doesn't give you enough detail to write correct JSX (e.g., you need to know the exact prop values for `variant` or the shape of an options array). Batch names in one call — cheaper than multiple fetches.\",\n parameters: {\n type: \"object\",\n properties: {\n names: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Component names to fetch (e.g., ['Card', 'Stack', 'Input']). Names must match the index entries exactly.\",\n },\n },\n required: [\"names\"],\n },\n};\n\n/**\n * Plan-commitment tool.\n *\n * Forced on turn 2 when the harness runs the `fetch → plan → write`\n * pipeline. After turn-1 fetching, the LLM must produce a short\n * structured plan before any apply_changes is allowed. The plan\n * echoes back in the tool result so turn 3+ patches can reference it —\n * this breaks fetch-loops where the model over-fetches without\n * committing to a structure.\n */\nexport const WRITE_PLAN_TOOL: LLMToolDef = {\n name: \"write_plan\",\n description:\n \"Commit to a concrete plan before writing code. Produce a short structured outline: which components you'll use, rough JSX structure, and wiring (state/actions/streams). After this call, on the next turn you'll be able to write code with `apply_changes`. Keep it brief — this is a commitment, not a design doc.\",\n parameters: {\n type: \"object\",\n properties: {\n components: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Primitive/component names you'll use in the final JSX (e.g., ['Card', 'Stack', 'Input', 'Button']).\",\n },\n structure: {\n type: \"string\",\n description:\n \"Brief JSX structure outline — a few lines of pseudocode showing nesting. Example: 'Card > Stack > [Heading, Input x3, Button].'\",\n },\n wiring: {\n type: \"string\",\n description:\n \"Brief note on state/actions/streams you'll wire. Example: 'useState for form payload; invokeAction(submit) on Button click.'\",\n },\n },\n required: [\"components\", \"structure\", \"wiring\"],\n },\n};\n\n/**\n * Full-file write tool. Flat JSON payload (two top-level strings) — much\n * easier for brittle tool-call serializers (e.g., Google Gemini Flash-Lite)\n * than `apply_changes`' nested array-of-objects-of-arrays-of-strings.\n *\n * Offered alongside `apply_changes` on turn 1 so the LLM can pick whichever\n * shape it emits more reliably. On patch-repair turns, `apply_changes` is\n * preferred (minimal diff, preserves session), but turn-1 has no existing\n * scaffold state to preserve — write is equivalent semantically.\n *\n * Implementation note: `executeTool` in `coding-agent/tools.ts`\n * already handles the `write` case; the harness just needs to\n * advertise it to the LLM.\n */\nexport const REWRITE_TOOL: LLMToolDef = {\n name: \"rewrite\",\n description:\n \"Escape hatch: rewrite the entire ui.tsx file in one call. Use only when surgical `apply_changes` patches have accumulated into a tangled broken state and you need to reset the file to a clean implementation. Single-string payload; auto-compiles + validates. Prefer `apply_changes` for normal edits.\",\n parameters: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"Complete TSX component source — the whole file.\",\n },\n commit_message: {\n type: \"string\",\n description: \"Short description (< 10 words)\",\n },\n },\n required: [\"code\", \"commit_message\"],\n },\n};\n","// packages/ui-gen/src/patch.ts\n//\n// Pure line-range patch implementation. Mirrors the `apply_changes` tool\n// logic (from coding-agent/tools.ts) without workspace / git / preflight\n// coupling — the harness exposes this as the default `PatchFn` so\n// variants can override with alternative patch grammars (diff3,\n// atomic-write, inline-markup, etc.) while reusing the orchestration\n// around them.\n//\n// Invariants:\n// - Changes sorted ascending by startLine.\n// - No overlapping ranges.\n// - All line numbers within [1, fileLines].\n// - Applied in reverse order to preserve upstream line numbers.\n//\n// This is the default patch function — every production harness uses it\n// unless a variant overrides `what.applyPatch`.\n\nimport type { PatchFn } from \"./harness/types-public.js\";\n\n/** Core pure logic — exported separately for tests + alternative wrappers. */\nexport function applyLineRanges(\n sourceBefore: string,\n rawChanges: ReadonlyArray<{\n startLine: number;\n endLine: number;\n code: readonly string[];\n description?: string;\n }>,\n): { ok: true; sourceAfter: string } | { ok: false; error: string } {\n if (rawChanges.length === 0) {\n return { ok: false, error: \"No changes provided.\" };\n }\n\n // Normalize — stable copy, sort ascending by startLine\n const changes = rawChanges\n .map((c, i) => ({\n startLine: c.startLine,\n endLine: c.endLine,\n code: [...c.code],\n description: c.description ?? `change ${i + 1}`,\n }))\n .sort((a, b) => a.startLine - b.startLine);\n\n // Required fields + non-empty code\n for (const c of changes) {\n if (typeof c.startLine !== \"number\" || typeof c.endLine !== \"number\") {\n return { ok: false, error: `Change \"${c.description}\" missing startLine or endLine.` };\n }\n if (c.code.length === 0) {\n return {\n ok: false,\n error: `Change \"${c.description}\" has empty code. Use [\"\"] to delete lines.`,\n };\n }\n }\n\n // Overlaps\n for (let i = 1; i < changes.length; i++) {\n if (changes[i].startLine <= changes[i - 1].endLine) {\n return {\n ok: false,\n error:\n `Changes overlap — \"${changes[i - 1].description}\" (lines ` +\n `${changes[i - 1].startLine}-${changes[i - 1].endLine}) overlaps with ` +\n `\"${changes[i].description}\" (lines ${changes[i].startLine}-${changes[i].endLine}).`,\n };\n }\n }\n\n // Line-number bounds\n const fileLines = sourceBefore.split(\"\\n\");\n for (const c of changes) {\n if (c.startLine < 1 || c.endLine < c.startLine || c.startLine > fileLines.length) {\n return {\n ok: false,\n error:\n `Invalid line range ${c.startLine}-${c.endLine} for \"${c.description}\". ` +\n `File has ${fileLines.length} lines.`,\n };\n }\n }\n\n // Apply in reverse to preserve line numbers\n const resultLines = [...fileLines];\n for (let i = changes.length - 1; i >= 0; i--) {\n const c = changes[i];\n const deleteCount = c.endLine - c.startLine + 1;\n resultLines.splice(c.startLine - 1, deleteCount, ...c.code);\n }\n\n return { ok: true, sourceAfter: resultLines.join(\"\\n\") };\n}\n\n/**\n * Harness-compatible wrapper around `applyLineRanges`. The default\n * patch function attached to every new harness's `what.applyPatch`.\n * Variants can override with alternative implementations (e.g., diff3\n * merge, atomic file write, etc.) to test different patch grammars\n * end-to-end.\n */\nexport const defaultApplyPatch: PatchFn = async ({ sourceBefore, changes }) => {\n const result = applyLineRanges(sourceBefore, changes);\n if (result.ok) {\n return { ok: true, sourceAfter: result.sourceAfter };\n }\n return { ok: false, error: result.error };\n};\n","// packages/ui-gen/src/hash.ts\n//\n// Deterministic fingerprint helpers for harness composition. Two inputs\n// that are structurally equivalent hash to the same 12-char prefix; two\n// different inputs hash to different prefixes.\n//\n// Used for:\n// - Harness id attribution (log + benchmark cell tagging)\n// - Prompt-cache key reuse\n// - Comparison-validity checks when benchmarking harness variants\n//\n// The `stableStringify` + `shortHash` primitives are private\n// implementation detail of this module.\n\nimport { createHash } from \"node:crypto\";\nimport type { Classification } from \"./classifier/axes.js\";\n\n// ─── Private primitives ────────────────────────────────────────────────────\n// Not exported — these are implementation detail. If an external consumer\n// needs a stable hash of arbitrary data, they should do it themselves.\n\nfunction stableStringify(value: unknown): string {\n if (value === null) return \"null\";\n if (typeof value === \"number\") return Number.isFinite(value) ? JSON.stringify(value) : \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (typeof value === \"object\") {\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const parts = keys.map(\n (k) =>\n `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`,\n );\n return `{${parts.join(\",\")}}`;\n }\n return \"null\";\n}\n\nfunction shortHash(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\").slice(0, 12);\n}\n\n// ─── Public surface ────────────────────────────────────────────────────────\n\n/** Hash a classification — used as a sub-component of the harness id. */\nexport function hashClassification(c: Classification): string {\n return shortHash(stableStringify({ vector: c.vector, riskTier: c.riskTier }));\n}\n\n/**\n * Compute a harness id from the materialized pieces. Called by `createHarness`\n * after all legs are built.\n *\n * Hashes only the stable content — not function references (applyPatch,\n * planner, etc.) because function identity isn't serializable. Instead,\n * version tags bump when semantics change.\n */\nexport function computeHarnessId(input: {\n classificationHash: string;\n howVersion: string;\n whatVersion: string;\n checkVersion: string;\n processVersion: string;\n workflowId: string;\n fragmentIds: readonly string[];\n overrides: readonly string[];\n}): string {\n return shortHash(stableStringify(input));\n}\n\n/**\n * Human-readable harness name. Deterministic but informative — derives from\n * classification + workflow without needing to look up the id.\n */\nexport function computeHarnessName(input: {\n classification: Classification;\n workflowName: string;\n version: string;\n}): string {\n const v = input.classification.vector;\n const dominantAxes: string[] = [];\n if (v.state !== \"none\") dominantAxes.push(`state=${v.state}`);\n if (v.writes !== \"none\") dominantAxes.push(`writes=${v.writes}`);\n if (v.realtime !== \"none\") dominantAxes.push(`realtime=${v.realtime}`);\n if (v.tooling !== \"none\") dominantAxes.push(`tooling=${v.tooling}`);\n const axesPart = dominantAxes.length > 0 ? dominantAxes.join(\"+\") : \"passive\";\n return `${input.version}/${axesPart}/${input.workflowName}`;\n}\n","// packages/ui-gen/src/workflows.ts\n//\n// Workflow registry + classification-driven picker. Each workflow\n// describes an execution topology (phases × tasks) for producing source\n// from a contract + prompt; the harness runtime owns actual LLM calls.\n//\n// Workflow shapes are validated shipping defaults — even `staged` /\n// `staged-concurrent` are reserved-but-registered topologies the picker\n// may route to in future risk-tier routing. Classification-driven\n// routing itself is deliberately conservative today (always\n// `single_pass`); changing the picker is a behavior change that should\n// be validated against the generation benchmark suite.\n//\n// Public surface is intentionally minimal: consumers import `WORKFLOWS`\n// (the map) + `pickWorkflow` (the router) + `WorkflowId` (the key\n// type). Individual topology constants (SINGLE_PASS, STAGED,\n// STAGED_CONCURRENT) are internal — access them via\n// `WORKFLOWS.single_pass` etc.\n\nimport type { Classification } from \"./classifier/axes.js\";\nimport type { Workflow } from \"./harness/types-public.js\";\n\n/** Identity parser — used for tasks whose output is already a string. */\nconst identityParser = (raw: unknown): string => raw as string;\n\n/**\n * single_pass — one phase, one task. The current default. The task runs\n * the existing impl/patch/eval-fix loop as a single atomic block.\n */\nconst SINGLE_PASS: Workflow = {\n id: \"single_pass@1\",\n name: \"single_pass\",\n description: \"One LLM-driven impl loop. Used for risk:low + risk:medium contract.\",\n phases: [\n {\n id: \"impl\",\n tasks: [\n {\n id: \"generate\",\n systemPrompt: (ctx) => ctx.harness.how.systemPrompt,\n contextBuilder: (ctx) =>\n `User prompt: ${ctx.prompt}\\n\\nBoilerplate is pre-written. Fill it in with apply_changes.`,\n outputFormat: \"tool-call\",\n outputParser: identityParser,\n outputName: \"source\",\n },\n ],\n },\n ],\n};\n\n/**\n * staged — plan phase then execute phase. For risk:high contract where\n * decomposing planning from authoring reduces light-model cognitive load.\n *\n * Registered but not yet routed by `pickWorkflow` — the executor wires\n * architect/coder TaskRunners through a separate dispatch path in core/.\n */\nconst STAGED: Workflow = {\n id: \"staged@1\",\n name: \"staged\",\n description: \"plan → execute. One architect task then one coder task.\",\n phases: [\n {\n id: \"plan\",\n tasks: [\n {\n id: \"architect\",\n systemPrompt: \"You are a UI architect. Produce a plan, no code.\",\n contextBuilder: (ctx) => `Plan the UI for: ${ctx.prompt}`,\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"plan\",\n maxTokens: 800,\n },\n ],\n },\n {\n id: \"execute\",\n tasks: [\n {\n id: \"coder\",\n systemPrompt: (ctx) => ctx.harness.how.systemPrompt,\n contextBuilder: (ctx) =>\n `User prompt: ${ctx.prompt}\\n\\nPlan:\\n${ctx.priorResults.plan ?? \"(no plan)\"}\\n\\nImplement per plan with apply_changes.`,\n inputs: [\"plan\"],\n outputFormat: \"tool-call\",\n outputParser: identityParser,\n outputName: \"source\",\n },\n ],\n },\n ],\n};\n\n/**\n * staged-concurrent — plan, then parallel skeleton tasks, then integrate.\n * Reserved shape for risk:high + multi-axis contract where the LLM\n * benefits from breaking structural concerns apart.\n */\nconst STAGED_CONCURRENT: Workflow = {\n id: \"staged_concurrent@1\",\n name: \"staged-concurrent\",\n description: \"plan → [types ∥ hooks ∥ jsx] → integrate. DAG with parallel skeleton phase.\",\n phases: [\n {\n id: \"plan\",\n tasks: [\n {\n id: \"architect\",\n systemPrompt: \"Plan the UI. No code.\",\n contextBuilder: (ctx) => `Plan the UI for: ${ctx.prompt}`,\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"plan\",\n maxTokens: 600,\n },\n ],\n },\n {\n id: \"skeleton\",\n tasks: [\n {\n id: \"types\",\n systemPrompt: \"Emit only type declarations for the contract.\",\n contextBuilder: (ctx) =>\n `Emit TypeScript types for: ${ctx.prompt}. Plan: ${ctx.priorResults.plan ?? \"(n/a)\"}`,\n inputs: [\"plan\"],\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"types\",\n maxTokens: 400,\n },\n {\n id: \"hooks\",\n systemPrompt: \"Emit only hook declarations (useState/useEffect/useStream).\",\n contextBuilder: (ctx) =>\n `Emit hooks for: ${ctx.prompt}. Plan: ${ctx.priorResults.plan ?? \"(n/a)\"}`,\n inputs: [\"plan\"],\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"hooks\",\n maxTokens: 400,\n },\n {\n id: \"jsx\",\n systemPrompt: \"Emit only the render JSX tree skeleton.\",\n contextBuilder: (ctx) =>\n `Emit JSX for: ${ctx.prompt}. Plan: ${ctx.priorResults.plan ?? \"(n/a)\"}`,\n inputs: [\"plan\"],\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"jsx\",\n maxTokens: 400,\n },\n ],\n },\n {\n id: \"integrate\",\n tasks: [\n {\n id: \"glue\",\n systemPrompt: (ctx) => ctx.harness.how.systemPrompt,\n contextBuilder: (ctx) =>\n `Combine into one component. Types:\\n${ctx.priorResults.types}\\n\\nHooks:\\n${ctx.priorResults.hooks}\\n\\nJSX:\\n${ctx.priorResults.jsx}`,\n inputs: [\"types\", \"hooks\", \"jsx\"],\n outputFormat: \"tool-call\",\n outputParser: identityParser,\n outputName: \"source\",\n },\n ],\n },\n ],\n};\n\nexport const WORKFLOWS = {\n single_pass: SINGLE_PASS,\n staged: STAGED,\n staged_concurrent: STAGED_CONCURRENT,\n} as const;\n\nexport type WorkflowId = keyof typeof WORKFLOWS;\n\n/**\n * Pick a workflow based on classification shape. One dispatch rule —\n * kept small on purpose. Changing this mapping is a first-class\n * experiment.\n *\n * Deliberately conservative — always `single_pass`. Classification-\n * driven routing to `staged` / `staged-concurrent` will follow once\n * the workflow executor can actually run non-single_pass shapes end-\n * to-end on the dispatch path.\n */\nexport function pickWorkflow(_classification: Classification): Workflow {\n return WORKFLOWS.single_pass;\n}\n","// packages/ui-gen/src/policy.ts\n//\n// Harness policy — validated defaults + identity resolvers.\n//\n// What lives here is the CONTRACT layer + the SHIPPING DEFAULTS:\n// - Type vocabulary every harness is built against\n// (ContextPolicy, HarnessPolicy, RuntimeCtx, ResolvedRunPolicy,\n// ProcessMode).\n// - The default values that reflect the current best-known harness\n// (DEFAULT_CONTEXT_POLICY, DEFAULT_HARNESS_POLICY), updated as new\n// configurations ship as new defaults.\n// - The structural-equality check `isDefaultHarnessPolicy`, used by\n// createHarness to decide whether policy participates in the\n// harness id (a harness running the vanilla default policy gets a\n// byte-identical id regardless of how the policy was constructed).\n// - The default `resolveHarnessPolicy(classification)` (returns\n// `DEFAULT_HARNESS_POLICY` for every classification — no ENV\n// profile branches here).\n// - The identity `resolveRunPolicy(harness, runtimeCtx)` (returns\n// `harness.policy` unchanged — no per-model registry lookup here).\n//\n// What does NOT live here (it lives in `./harness/policy.ts`, the\n// experiment layer that wraps this module):\n// - `GGUI_POLICY_PROFILE` environment-variable reading.\n// - The named experimental profile branches\n// (narrow-merge-v1, hashline-v2, tool-driven-primitives-*,\n// primitives-ts-format, tsformat-plan-impl, numberline-flat,\n// legacy-code-array, hashline-v2-flat).\n// - `resolveRunPolicyForProfile`.\n// - The per-model `MODEL_HARNESS_REGISTRY` consultation in\n// `resolveRunPolicy`.\n// Those are experiment plumbing — a new arm lives in the wrapper layer\n// until it is validated, then graduates into the defaults here.\n\nimport type { Classification } from \"./classifier/axes.js\";\n\n// ─── Execution topology ────────────────────────────────────────────────────\n\n/**\n * Coarse execution-topology label attached to `ProcessLeg`. The workflow\n * DAG itself is the source of truth; this is a label on it, used by filters\n * and by `HarnessPolicy.processMode` to override the default `\"single_pass\"`.\n */\nexport type ProcessMode = \"single_pass\" | \"staged\" | \"staged-concurrent\";\n\n// ─── ContextPolicy ─────────────────────────────────────────────────────────\n\n/**\n * Context-leg policy. Controls the SHAPE of feedback the LLM sees on retry /\n * patch surfaces, the format of the primitives reference, and the tool-grammar\n * schema of `apply_changes`. Does NOT change what errors get caught or how\n * the code executes — only how errors get rendered back to the LLM and how\n * the primitive documentation is staged on turn 1.\n *\n * Every field is documented against the experiment that justified it. The\n * defaults in `DEFAULT_CONTEXT_POLICY` reflect the current best-known\n * harness; changing a default here is a semver-major-level event for\n * a hosted closed runtime (which shifts every benchmark cell) and\n * deserves its own commit with bench evidence.\n */\nexport interface ContextPolicy {\n /**\n * Prefix the preflight `PATCH_INVALID` retry message with `[P0-compile]`\n * so the LLM can rank it against the prompt's P0/P1/P2 priority schema.\n * Default `false`.\n */\n readonly labeledPreflight: boolean;\n /**\n * Reserved for future plumbing. When true, would prefix tier-0 self-check\n * retry violations with `[P0-*]` / `[P1-*]` priority tags. Default false.\n */\n readonly labeledTier0: boolean;\n /**\n * When true, the coding loop detects duplicate patch/error-class\n * fingerprints across consecutive patch turns and, on match, runs the\n * action chosen by {@link dupeBreakAction}. Default false.\n */\n readonly breakDuplicatePatch: boolean;\n /**\n * When `breakDuplicatePatch` fires, choose the intervention. Default\n * `\"escape\"` for back-compat with the dormant scoped-escape plumbing —\n * has no effect unless `breakDuplicatePatch` is also true.\n */\n readonly dupeBreakAction?: \"escape\" | \"diagnostic\" | \"diagnostic-noforce\";\n /**\n * Axis-keyed primitives doc slice. When `\"axis-keyed\"`, the first-turn\n * system prompt injects only the allowlisted primitives derived from\n * the classification, shrinking the ~130 KB monolith to ~30–50 KB.\n * Default `\"full\"`.\n */\n readonly primitiveDocSlice?: \"full\" | \"axis-keyed\";\n /**\n * Primitives to exclude from the axis-keyed slice. Only meaningful\n * when `primitiveDocSlice === \"axis-keyed\"`.\n */\n readonly primitiveDocExcludes?: readonly string[];\n /**\n * Hashline view format on `## Current File` + hash-verified\n * apply_changes line refs. Default `\"off\"`.\n */\n readonly hashline?: \"off\" | \"v2\";\n /**\n * Tool-driven primitive docs. When `\"names-only\"` or `\"with-props\"`,\n * the ~130 KB primitives doc is replaced with a compact ~7–9 KB index\n * and `get_components_info` is advertised alongside the authoring tool.\n * Default `\"off\"`.\n */\n readonly primitiveIndex?: \"off\" | \"names-only\" | \"with-props\";\n /**\n * Force turn 1 to advertise ONLY `get_components_info`. Requires\n * `primitiveIndex !== \"off\"`. Default `false`.\n */\n readonly primitiveIndexForceFetch?: boolean;\n /**\n * Force turn 2 to advertise ONLY `write_plan`. Requires\n * `primitiveIndex !== \"off\"` and typically `primitiveIndexForceFetch`.\n * Default `false`.\n */\n readonly primitiveIndexPlanTurn?: boolean;\n /**\n * Format of the primitive component reference. `\"markdown\"` = verbose\n * markdown tables (~128 KB); `\"ts\"` = compact TS-interface format\n * (~59 KB, same enum coverage). The TS format is the shipped default.\n */\n readonly primitiveDocFormat?: \"markdown\" | \"ts\";\n /**\n * Force turn 1 to advertise ONLY `write_plan`. Orthogonal to\n * `primitiveIndex`. Default `false`.\n */\n readonly planFirstTurn?: boolean;\n /**\n * apply_changes `code` field schema. `\"array\"` = `string[]` (one line\n * per element); `\"flat\"` = single string with `\\n` separators (3 JSON\n * nesting levels instead of 4). The flat format is the shipped\n * default.\n */\n readonly codeFormat?: \"array\" | \"flat\";\n}\n\n// ─── HarnessPolicy + runtime context ───────────────────────────────────────\n\n/**\n * Top-level policy attached to a harness. v1 defines only the context\n * sub-policy + an optional process-mode override. More sub-policies\n * (eval, retry, process-specific) will land when they have a first real\n * field with clean semantics.\n */\nexport interface HarnessPolicy {\n readonly context: ContextPolicy;\n /**\n * Process-leg mode override. When set, `createHarness` uses this value\n * instead of the default `\"single_pass\"`. Null/undefined → default.\n */\n readonly processMode?: ProcessMode;\n}\n\n/**\n * Runtime context visible at dispatch time. v1 carries `provider` +\n * optional `modelId`. Future fields (observed axis values, capability\n * flags) may appear as warranted.\n */\nexport interface RuntimeCtx {\n readonly provider: \"anthropic\" | \"openai\" | \"google\" | \"openrouter\";\n /**\n * Model id as passed to the provider SDK. Optional — when absent,\n * runtime policy resolution falls through to provider-level and\n * default resolution only.\n */\n readonly modelId?: string;\n}\n\n/**\n * Runtime-resolved policy. Identical shape to {@link HarnessPolicy} for\n * v1 — the default {@link resolveRunPolicy} is an identity. The separate\n * type exists as a parking spot for future provider-aware overrides so\n * callers can start typing `ResolvedRunPolicy` today and get new fields\n * automatically when they land.\n */\nexport type ResolvedRunPolicy = HarnessPolicy;\n\n// ─── Defaults ──────────────────────────────────────────────────────────────\n\n/** Validated shipping defaults for the generation harness. */\nexport const DEFAULT_CONTEXT_POLICY: ContextPolicy = Object.freeze({\n labeledPreflight: false,\n labeledTier0: false,\n breakDuplicatePatch: false,\n dupeBreakAction: \"escape\",\n primitiveDocSlice: \"full\",\n hashline: \"off\",\n primitiveIndex: \"off\",\n primitiveIndexForceFetch: false,\n primitiveIndexPlanTurn: false,\n // A processed TypeScript-interface format for the primitive docs,\n // chosen over verbose markdown tables: roughly half the size with no\n // loss of enum-value information.\n primitiveDocFormat: \"ts\",\n planFirstTurn: false,\n // A flat `code: string` patch payload instead of `code: string[]`.\n // The shallower JSON nesting is more reliably decoded by tool-calling\n // models.\n codeFormat: \"flat\",\n});\n\nexport const DEFAULT_HARNESS_POLICY: HarnessPolicy = Object.freeze({\n context: DEFAULT_CONTEXT_POLICY,\n});\n\n// ─── Resolvers (defaults + identity) ───────────────────────────────────────\n\n/**\n * Default harness-policy resolver — v1 returns `DEFAULT_HARNESS_POLICY`\n * for every classification. A hosted closed runtime can overlay its own\n * funnel profile-branching wrapper around this; OSS consumers get this\n * single default path and can wrap it themselves if they need\n * classification-aware overrides.\n *\n * Preserves reference equality: every call on every classification\n * returns the same frozen singleton object, so callers can use\n * `resolved === DEFAULT_HARNESS_POLICY` to detect the vanilla path\n * (used by `createHarness` via `isDefaultHarnessPolicy` to keep\n * `harness.id` byte-identical on the default path).\n */\nexport function resolveHarnessPolicy(_classification: Classification): HarnessPolicy {\n return DEFAULT_HARNESS_POLICY;\n}\n\n/**\n * Identity run-time resolver — returns `harness.policy` unchanged for\n * any runtime context. A hosted closed runtime can overlay a per-model\n * registry lookup on top (graduating bench-validated overrides per\n * model id); OSS consumers get the identity, preserving reference\n * equality so `resolved === harness.policy` detects \"no override\n * applied.\"\n */\nexport function resolveRunPolicy(\n harness: { readonly policy: HarnessPolicy },\n _runtimeCtx: RuntimeCtx,\n): ResolvedRunPolicy {\n return harness.policy;\n}\n\n// ─── Structural-equality check ─────────────────────────────────────────────\n\n/**\n * Structural equality against `DEFAULT_HARNESS_POLICY`. Used by\n * `createHarness` to skip hashing the policy for the vanilla case —\n * keeps `harness.id` byte-identical for every harness running the\n * default policy.\n *\n * Checks each field explicitly (including the unset-means-default\n * shorthand) instead of `policy === DEFAULT_HARNESS_POLICY` so callers\n * can pass a structurally-equivalent object they built themselves.\n */\nexport function isDefaultHarnessPolicy(policy: HarnessPolicy): boolean {\n return (\n policy.context.labeledPreflight === DEFAULT_CONTEXT_POLICY.labeledPreflight &&\n policy.context.labeledTier0 === DEFAULT_CONTEXT_POLICY.labeledTier0 &&\n policy.context.breakDuplicatePatch === DEFAULT_CONTEXT_POLICY.breakDuplicatePatch &&\n (policy.context.dupeBreakAction ?? \"escape\") ===\n (DEFAULT_CONTEXT_POLICY.dupeBreakAction ?? \"escape\") &&\n (policy.context.primitiveDocSlice ?? \"full\") ===\n (DEFAULT_CONTEXT_POLICY.primitiveDocSlice ?? \"full\") &&\n (policy.context.primitiveDocExcludes?.length ?? 0) === 0 &&\n (policy.context.hashline ?? \"off\") === (DEFAULT_CONTEXT_POLICY.hashline ?? \"off\") &&\n (policy.context.primitiveIndex ?? \"off\") ===\n (DEFAULT_CONTEXT_POLICY.primitiveIndex ?? \"off\") &&\n (policy.context.primitiveIndexForceFetch ?? false) ===\n (DEFAULT_CONTEXT_POLICY.primitiveIndexForceFetch ?? false) &&\n (policy.context.primitiveIndexPlanTurn ?? false) ===\n (DEFAULT_CONTEXT_POLICY.primitiveIndexPlanTurn ?? false) &&\n (policy.context.primitiveDocFormat ?? \"markdown\") ===\n (DEFAULT_CONTEXT_POLICY.primitiveDocFormat ?? \"markdown\") &&\n (policy.context.planFirstTurn ?? false) ===\n (DEFAULT_CONTEXT_POLICY.planFirstTurn ?? false) &&\n (policy.context.codeFormat ?? \"array\") ===\n (DEFAULT_CONTEXT_POLICY.codeFormat ?? \"array\") &&\n policy.processMode === undefined\n );\n}\n","// packages/ui-gen/src/create-harness.ts\n//\n// Deterministic Harness factory — the skeleton constructor. Given a\n// classification + contract + prompt (+ optional caller-injected\n// defaults for policy / system-prompt builder / axis-checks /\n// runtime-render / overrides), assemble all four legs and return an\n// immutable Harness object ready to drive generation.\n//\n// This is a SKELETON: it has four injection seams (policy,\n// systemPromptBuilder, axisChecks, runtimeRender). The hosted runtime\n// supplies the production content for those seams from\n// `adapters/generation-dispatch.ts` at the dispatch boundary; callers\n// that omit them get minimal defaults.\n\nimport type { CacheTier } from \"./fragments/index.js\";\nimport { compose } from \"./compose.js\";\nimport { buildSystemPrompt, generateBoilerplate } from \"./boilerplate.js\";\nimport { APPLY_CHANGES_TOOL, APPLY_CHANGES_TOOL_SCOPED } from \"./tools.js\";\nimport { defaultApplyPatch } from \"./patch.js\";\nimport { computeHarnessId, computeHarnessName, hashClassification } from \"./hash.js\";\nimport { pickWorkflow } from \"./workflows.js\";\nimport { DEFAULT_HARNESS_POLICY, isDefaultHarnessPolicy } from \"./policy.js\";\nimport type {\n CreateHarnessInput,\n Harness,\n HarnessConstructionContext,\n HarnessOverrides,\n HarnessRevision,\n HowLeg,\n WhatLeg,\n CheckLeg,\n ProcessLeg,\n HarnessMeta,\n PatchFn,\n SystemPromptBuilder,\n} from \"./harness/types-public.js\";\n\n// Version tags — bump when semantics change.\nconst HARNESS_VERSION = \"harness@1\";\nconst HOW_VERSION = \"how@1\";\nconst WHAT_VERSION = \"what@1\";\nconst CHECK_VERSION = \"check@1\";\nconst PROCESS_VERSION = \"process@1\";\n\n// Default patch function — pure line-range application (mirrors apply_changes).\n// Variants can override via HarnessOverrides.what.\nconst defaultPatchFn: PatchFn = defaultApplyPatch;\n\nfunction applyLegOverride<L>(\n base: L,\n ovr: Partial<L> | ((base: L, ctx: HarnessConstructionContext) => L) | undefined,\n ctx: HarnessConstructionContext,\n): L {\n if (!ovr) return base;\n if (typeof ovr === \"function\") return (ovr as (b: L, c: HarnessConstructionContext) => L)(base, ctx);\n return { ...base, ...ovr };\n}\n\nfunction countCacheTiers(fragments: readonly { cacheTier: CacheTier }[]): Record<CacheTier, number> {\n const counts: Record<CacheTier, number> = { stable: 0, axisDelta: 0, volatile: 0 };\n for (const f of fragments) counts[f.cacheTier]++;\n return counts;\n}\n\n/**\n * Build a Harness from classification + inputs. Idempotent: same inputs\n * produce a Harness with the same id.\n */\nexport function createHarness(input: CreateHarnessInput): Harness {\n const { classification, contract, prompt, shellType, screen, overrides } = input;\n const ctx: HarnessConstructionContext = { classification, contract, prompt };\n\n // ── Compose fragments from classification ────────────────────────────────\n const composed = compose(classification);\n\n // ── HOW leg ──────────────────────────────────────────────────────────────\n // System-prompt builder seam. The default is the skeleton builder\n // with empty content blocks; callers inject a fully-populated builder\n // to add pitfalls + design-system docs + primitives + wire content.\n const systemPromptBuilder: SystemPromptBuilder =\n input.systemPromptBuilder ?? buildSystemPrompt;\n const systemPrompt = systemPromptBuilder({\n userRequest: prompt,\n shellType,\n screen,\n axisDelta: composed.promptText,\n });\n const howFragments = composed.fragments.filter(\n (f) => f.promptText && f.promptText.trim().length > 0,\n );\n const baseHow: HowLeg = {\n systemPrompt,\n implPrompt: \"\",\n fragments: howFragments,\n version: HOW_VERSION,\n };\n const how = applyLegOverride(baseHow, overrides?.how, ctx);\n\n // ── WHAT leg ─────────────────────────────────────────────────────────────\n // `appGadgets` reaches the boilerplate generator so thin contract\n // refs (`{hook: 'useLeafletMap'}` without a per-binding `package`)\n // resolve their import specifier from the operator-registered\n // descriptor's `package` field. Without this thread, the LLM's\n // starter file shows\n // `import { useLeafletMap } from '@ggui-ai/gadgets'` —\n // which doesn't export operator-registered wrapper hooks — and the\n // LLM removes the hook with a \"not available\" comment.\n const boilerplate = generateBoilerplate(\n prompt,\n contract as Parameters<typeof generateBoilerplate>[1],\n shellType,\n screen,\n composed.boilerplateSections,\n input.appGadgets,\n );\n const whatFragments = composed.fragments.filter(\n (f) => f.boilerplateMarker && f.boilerplateMarker.trim().length > 0,\n );\n const baseWhat: WhatLeg = {\n boilerplate,\n fragments: whatFragments,\n codingTools: [APPLY_CHANGES_TOOL],\n scopedTools: [APPLY_CHANGES_TOOL_SCOPED],\n applyPatch: defaultPatchFn,\n // Registered gadget catalog — drives the system prompt's gadget\n // table + the boilerplate's direct-import emission. Omitted when no\n // gadgets registered.\n ...(input.appGadgets !== undefined ? { appGadgets: input.appGadgets } : {}),\n // Third-party wrapper `.d.ts` map — autoCommit's typecheck overlays\n // the real wrapper declarations so a generated direct gadget import\n // gets strict hook types.\n ...(input.gadgetTypes !== undefined\n ? { gadgetTypes: input.gadgetTypes }\n : {}),\n version: WHAT_VERSION,\n };\n const what = applyLegOverride(baseWhat, overrides?.what, ctx);\n\n // ── CHECK leg ────────────────────────────────────────────────────────────\n // Axis-check registry seam. The caller supplies pre-filtered\n // axisChecks; the skeleton default is [].\n // Runtime-render seam. The skeleton default is undefined.\n const axisChecks = input.axisChecks ?? [];\n const baseCheck: CheckLeg = {\n axisChecks,\n tierChecks: [],\n runtimeRender: input.runtimeRender,\n llmEvaluator: undefined,\n version: CHECK_VERSION,\n };\n const check = applyLegOverride(baseCheck, overrides?.check, ctx);\n\n // ── Policy ───────────────────────────────────────────────────────────────\n // Policy injection seam. The caller pre-resolves; the skeleton\n // default is DEFAULT_HARNESS_POLICY.\n const policy = input.policy ?? DEFAULT_HARNESS_POLICY;\n\n // ── Process leg ──────────────────────────────────────────────────────────\n const workflow = pickWorkflow(classification);\n const baseProcess: ProcessLeg = {\n mode: policy.processMode ?? \"single_pass\",\n workflow,\n planner: undefined,\n retry: { maxIterations: 30 },\n version: PROCESS_VERSION,\n };\n const processLeg = applyLegOverride(baseProcess, overrides?.process, ctx);\n\n // ── Meta + id ────────────────────────────────────────────────────────────\n const classificationHash = hashClassification(classification);\n const fragmentIds = composed.fragments.map((f) => `${f.axis}=${f.value}`);\n const cacheTierBreakdown = countCacheTiers(composed.fragments);\n const overrideLabels: string[] = [];\n if (overrides?.how) overrideLabels.push(\"how\");\n if (overrides?.what) overrideLabels.push(\"what\");\n if (overrides?.check) overrideLabels.push(\"check\");\n if (overrides?.process) overrideLabels.push(\"process\");\n if (overrides?.label) overrideLabels.push(`label:${overrides.label}`);\n // Only non-default policies contribute to the harness id — preserves\n // byte-identical id across default-policy runs.\n if (!isDefaultHarnessPolicy(policy)) overrideLabels.push(\"policy\");\n\n const id = computeHarnessId({\n classificationHash,\n howVersion: how.version,\n whatVersion: what.version,\n checkVersion: check.version,\n processVersion: processLeg.version,\n workflowId: workflow.id,\n fragmentIds,\n overrides: overrideLabels,\n });\n\n const name = computeHarnessName({\n classification,\n workflowName: workflow.name,\n version: HARNESS_VERSION,\n });\n\n const meta: HarnessMeta = {\n classificationHash,\n fragmentIds,\n cacheTierBreakdown,\n overrides: overrideLabels,\n createdAt: new Date().toISOString(),\n harnessVersion: HARNESS_VERSION,\n };\n\n const harness: Harness = {\n id,\n name,\n classification,\n how,\n what,\n check,\n process: processLeg,\n policy,\n meta,\n derive(revision: HarnessRevision): Harness {\n return deriveHarness(this, revision, input);\n },\n };\n\n return harness;\n}\n\n/**\n * Produce a derived Harness for a subsequent iteration. Called when the\n * planner reclassifies or a runtime signal demands a topology swap.\n */\nfunction deriveHarness(\n base: Harness,\n revision: HarnessRevision,\n originalInput: CreateHarnessInput,\n): Harness {\n let mergedOverrides: HarnessOverrides = {\n ...originalInput.overrides,\n ...(revision.overrides ?? {}),\n };\n\n // If the revision names a new workflow explicitly, override the process leg.\n if (revision.workflow) {\n const currentProcessOverride = mergedOverrides.process;\n const processBuilder = (baseProcess: ProcessLeg, ctx: HarnessConstructionContext): ProcessLeg => {\n const withOverride =\n typeof currentProcessOverride === \"function\"\n ? currentProcessOverride(baseProcess, ctx)\n : { ...baseProcess, ...(currentProcessOverride ?? {}) };\n return { ...withOverride, workflow: revision.workflow! };\n };\n mergedOverrides = { ...mergedOverrides, process: processBuilder };\n }\n\n // Runtime fallback: promote scopedTools → codingTools.\n if (revision.useFallbackTools) {\n const currentWhatOverride = mergedOverrides.what;\n const whatBuilder = (baseWhat: WhatLeg, ctx: HarnessConstructionContext): WhatLeg => {\n const withOverride =\n typeof currentWhatOverride === \"function\"\n ? currentWhatOverride(baseWhat, ctx)\n : { ...baseWhat, ...(currentWhatOverride ?? {}) };\n if (withOverride.scopedTools && withOverride.scopedTools.length > 0) {\n return { ...withOverride, codingTools: withOverride.scopedTools };\n }\n return withOverride;\n };\n mergedOverrides = { ...mergedOverrides, what: whatBuilder };\n }\n\n return createHarness({\n ...originalInput,\n classification: revision.classification ?? base.classification,\n overrides: mergedOverrides,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/run-workflow.ts","../../src/harness/validator-trace-sink.ts","../../src/run-check.ts","../../src/run-harness.ts","../../src/fragments/render.ts","../../src/fragments/state.ts","../../src/fragments/writes.ts","../../src/fragments/realtime.ts","../../src/fragments/fetch.ts","../../src/fragments/layout.ts","../../src/fragments/tooling.ts","../../src/fragments/index.ts","../../src/compose.ts","../../src/boilerplate/render.ts","../../src/boilerplate/json-schema-ts.ts","../../src/boilerplate/generate.ts","../../src/evaluation/types-public.ts","../../src/internal/extract-call-signatures.ts","../../src/boilerplate/system-prompt.ts","../../src/tools.ts","../../src/patch.ts","../../src/hash.ts","../../src/workflows.ts","../../src/policy.ts","../../src/create-harness.ts"],"names":["result","__dirname"],"mappings":";;;;;;;;AAiEA,IAAM,iBAAA,GAAuC,OAAO,IAAA,KAAS,IAAA,CAAK,EAAA;AAOlE,eAAsB,YAAY,KAAA,EAAqD;AACrF,EAAA,MAAM,EAAE,OAAA,EAAS,MAAA,EAAQ,UAAU,WAAA,EAAa,aAAA,EAAe,gBAAe,GAAI,KAAA;AAClF,EAAA,MAAM,QAAA,GAAqB,QAAQ,OAAA,CA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,EAAgB,QAAA,CAAS,cAAA,IAAkB,IAAA,CAAK,cAAA;AAAA,IAChD,SAAA,EAAW;AAAA,GACZ,CAAA;AACH","file":"types-public.js","sourcesContent":["// packages/ui-gen/src/run-workflow.ts\n//\n// Workflow executor. Runs phases sequentially; within a phase, tasks run in\n// parallel (Promise.all). Each task produces a named output that downstream\n// tasks can read from context.priorResults.\n//\n// Generic DAG executor — zero LLM coupling, zero environment/profile\n// gating. Re-exported via `@ggui-ai/ui-gen/harness` alongside the\n// Harness type vocabulary.\n//\n// Scope:\n// - Generic execution machinery — drives the DAG, doesn't know how to\n// run individual tasks. Task handlers are pluggable via the taskRunners\n// parameter, keyed by task.id (or a fallback).\n// - Single-pass / staged / staged-concurrent all work under one executor.\n// - No LLM coupling here — that belongs to the specific task runners the\n// caller registers.\n//\n// Failure semantics:\n// - If any task in a phase throws, the phase is aborted and the error\n// propagates out of runWorkflow. The caller owns the retry policy.\n// - If any task returns { error }, the phase completes but the workflow\n// result carries the error; the caller decides whether to continue.\n\nimport type { DataContract, JsonValue } from \"@ggui-ai/protocol\";\nimport type { Harness, Task, TaskContext, Workflow } from \"./harness/types-public.js\";\n\n/** Called by the executor to run a single task. One of these per task.id. */\nexport type TaskRunner = (task: Task, ctx: TaskContext) => Promise<JsonValue>;\n\n/** Fallback runner used when no task-specific runner is registered. */\nexport type DefaultTaskRunner = (task: Task, ctx: TaskContext) => Promise<JsonValue>;\n\nexport interface RunWorkflowInput {\n readonly harness: Harness;\n readonly prompt: string;\n readonly contract: DataContract;\n /** Task runners by task.id. Fallback to defaultRunner for unregistered ids. */\n readonly taskRunners?: Readonly<Record<string, TaskRunner>>;\n /** Runner invoked when no task.id-specific runner is registered. */\n readonly defaultRunner?: DefaultTaskRunner;\n /** Initial context (rarely used — mostly for resume/recovery). */\n readonly initialResults?: Readonly<Record<string, JsonValue>>;\n}\n\nexport interface PhaseRunResult {\n readonly phaseId: string;\n readonly taskResults: ReadonlyArray<{\n readonly taskId: string;\n readonly outputName: string;\n readonly output: JsonValue;\n readonly durationMs: number;\n }>;\n readonly durationMs: number;\n}\n\nexport interface WorkflowRunResult {\n readonly workflowId: string;\n readonly phases: readonly PhaseRunResult[];\n /** Final merged results map — task outputs keyed by outputName. */\n readonly results: Readonly<Record<string, JsonValue>>;\n readonly durationMs: number;\n}\n\n/** No-op default runner — returns the task id as its output. Tests can swap. */\nconst noopDefaultRunner: DefaultTaskRunner = async (task) => task.id;\n\n/**\n * Execute a workflow. Phases run sequentially; tasks within a phase run in\n * parallel via Promise.all. Task outputs accumulate into priorResults and\n * are passed to subsequent phases via the TaskContext.\n */\nexport async function runWorkflow(input: RunWorkflowInput): Promise<WorkflowRunResult> {\n const { harness, prompt, contract, taskRunners, defaultRunner, initialResults } = input;\n const workflow: Workflow = harness.process.workflow;\n\n const startTotal = Date.now();\n const priorResults: Record<string, JsonValue> = { ...(initialResults ?? {}) };\n const phaseResults: PhaseRunResult[] = [];\n const runners = taskRunners ?? {};\n const fallback = defaultRunner ?? noopDefaultRunner;\n\n for (const phase of workflow.phases) {\n const phaseStart = Date.now();\n\n const ctx: TaskContext = {\n harness,\n priorResults: { ...priorResults },\n classification: harness.classification,\n prompt,\n contract,\n };\n\n const taskPromises = phase.tasks.map(async (task) => {\n const taskStart = Date.now();\n const runner = runners[task.id] ?? fallback;\n const output = await runner(task, ctx);\n return {\n taskId: task.id,\n outputName: task.outputName,\n output,\n durationMs: Date.now() - taskStart,\n };\n });\n\n const taskResults = await Promise.all(taskPromises);\n\n // Merge outputs into priorResults for the next phase.\n for (const tr of taskResults) {\n priorResults[tr.outputName] = tr.output;\n }\n\n phaseResults.push({\n phaseId: phase.id,\n taskResults,\n durationMs: Date.now() - phaseStart,\n });\n }\n\n return {\n workflowId: workflow.id,\n phases: phaseResults,\n results: { ...priorResults },\n durationMs: Date.now() - startTotal,\n };\n}\n","/**\n * Live validator-tier trace sink — devtools introspection of every\n * `runCheck()` invocation the harness performs.\n *\n * **Distinct from {@link LlmTraceSink}, {@link TelemetrySink}, and\n * {@link AuditSink}.**\n * - **LLM trace** (sibling) = devtools-only ring buffer of LLM call\n * payloads (system + user prompt, tools, completion, tokens).\n * Answers \"what did the LLM see / say?\".\n * - **Telemetry** (mcp-server-core) = ops signals (`pair.completed`,\n * `render.duration_ms`). Lossy. Flat scalars.\n * - **Audit** (mcp-server-core) = compliance log of privileged\n * mutations. Durable.\n * - **Validator trace** (this) = devtools-only ring buffer of every\n * `runCheck()` call's full validator-tier breakdown — which axis /\n * tier / runtime-render / LLM checks fired, what each returned\n * (pass/fail/warn issues with description, fix, line, severity).\n * Answers \"which check failed, and what did the LLM emit?\".\n *\n * **Why module-level registry instead of constructor injection.** Same\n * argument as the LLM trace sink — `runCheck()` is called from multiple\n * orchestrator entrypoints (`runHarness`, `run-eval-round`) across the\n * harness package; threading a sink through every call site for a\n * devtools-only surface isn't worth the churn. The ggui server is\n * single-process per CLI invocation; a hosted runtime isolates per\n * request via a process pool.\n *\n * **Default = no sink.** When unset, `runCheck` emits nothing and spends\n * no CPU formatting events. Passing `null` removes a previously\n * registered sink.\n */\nimport type { Classification } from \"../classifier/axes.js\";\nimport type { EvalIssue } from \"../evaluation/types-public.js\";\n\n/**\n * One `runCheck()` invocation. Emitted **after** all tiers complete\n * (success or partial — even when one tier throws, the others ran and\n * we surface what we have). Single event per call.\n */\nexport interface ValidatorTraceEvent {\n /** Random per-event ID. */\n readonly id: string;\n /** Epoch ms when `runCheck` was entered. */\n readonly at: number;\n /** Epoch ms when `runCheck` returned. */\n readonly endedAt: number;\n /** `endedAt - at` — convenience. */\n readonly durationMs: number;\n /** Harness fingerprint that drove these checks. */\n readonly harnessId: string;\n /** Classification axes that produced the harness — useful when the\n * operator asks \"why did this axis-check fire?\". */\n readonly classification: Classification;\n /** Workflow that produced the source-under-check. */\n readonly workflowId: string;\n /** Was a non-null compiledCode fed in? When false, runCheck short-\n * circuits to an empty result — surfaced for transparency. */\n readonly hadCompiledCode: boolean;\n /** Was the runtime-render probe deliberately skipped? Mirrors the\n * `skipRuntimeRender` input flag. */\n readonly skippedRuntimeRender: boolean;\n /** Per-tier issue counts and which check ids fired. */\n readonly summary: {\n readonly totalIssues: number;\n readonly axisIssues: number;\n readonly tierIssues: number;\n readonly llmIssues: number;\n readonly runtimeRenderIssues: number;\n readonly firedCheckIds: readonly string[];\n };\n /** Every issue emitted across all tiers. Carries description + fix +\n * line + severity + tier + category — the full per-issue payload the\n * validator UI renders into a per-tier breakdown. */\n readonly issues: readonly EvalIssue[];\n /** Source under check — capped at ~16KB. Operators expanding a card\n * want to see what failed; longer sources are truncated with a\n * trailing marker so the UI shows the truncation honestly. */\n readonly sourceCode?: string;\n /** Original prompt — useful when \"this passed eval but doesn't match\n * the request\" comes up in operator triage. */\n readonly prompt?: string;\n /** Set when `runCheck` itself threw before completing. The event is\n * still emitted (devtools want to see partial / failed runs). */\n readonly error?: { readonly message: string };\n}\n\n/**\n * Sink that receives one event per `runCheck()` invocation. Same\n * contract as {@link LlmTraceSink} — implementations MUST be sync +\n * non-throwing. Buffer + drop or fan out to a queue inside the\n * implementation.\n */\nexport interface ValidatorTraceSink {\n emit(event: ValidatorTraceEvent): void;\n}\n\nlet activeSink: ValidatorTraceSink | null = null;\n\n/**\n * Register the active sink. Pass `null` to remove. Subsequent\n * {@link emitValidatorTraceEvent} calls dispatch to this sink.\n */\nexport function setValidatorTraceSink(sink: ValidatorTraceSink | null): void {\n activeSink = sink;\n}\n\n/** Read the active sink. Mostly for tests. */\nexport function getValidatorTraceSink(): ValidatorTraceSink | null {\n return activeSink;\n}\n\n/**\n * Internal — used by `runCheck`. No-op when no sink is registered.\n * Swallows sink-thrown errors (a broken devtools sink must not break\n * generation).\n */\nexport function emitValidatorTraceEvent(event: ValidatorTraceEvent): void {\n const sink = activeSink;\n if (!sink) return;\n try {\n sink.emit(event);\n } catch {\n // Devtools sink is allowed to be buggy — generation must not die.\n }\n}\n\n/**\n * Truncate a source string to ~16KB so a runaway component doesn't\n * blow the per-event memory budget. Adds a visible truncation marker.\n */\nexport function truncateSourceForTrace(source: string): string {\n const cap = 16 * 1024;\n if (source.length <= cap) return source;\n return source.slice(0, cap) + \"\\n\\n/* … truncated for devtools trace … */\";\n}\n\n/**\n * Crockford-style random ID. Same approach as the LLM trace sink —\n * dep-free for any runtime the harness might run in.\n */\nexport function newValidatorTraceId(): string {\n return (\n Date.now().toString(36) +\n Math.random().toString(36).slice(2, 10)\n );\n}\n","// packages/ui-gen/src/run-check.ts\n//\n// Post-workflow evaluation stage. Runs every check registered on a harness's\n// CheckLeg against produced source and returns a flat issue list.\n//\n// Pure orchestration — iterates the harness's CheckLeg and runs each\n// check. Check BODIES (axis-check registry entries, tier-0 checks, LLM\n// evaluator, runtime-render adapter) are injected at harness\n// construction.\n//\n// Scope:\n// - Runs axisChecks (already-filtered at createHarness time).\n// - Runs tierChecks (deterministic, no LLM).\n// - Delegates LLM evaluation to harness.check.llmEvaluator when present.\n// - Delegates runtime-render to harness.check.runtimeRender when present.\n\nimport type { DataContract, JsonObject } from \"@ggui-ai/protocol\";\nimport type { EvalIssue, AxisCheckInput } from \"./evaluation/types-public.js\";\nimport type { CheckLeg, Harness } from \"./harness/types-public.js\";\nimport {\n emitValidatorTraceEvent,\n newValidatorTraceId,\n truncateSourceForTrace,\n} from \"./harness/validator-trace-sink.js\";\n\nexport interface RunCheckInput {\n readonly sourceCode: string;\n readonly compiledCode: string | null;\n readonly contract?: DataContract;\n readonly prompt: string;\n readonly harness: Harness;\n /**\n * Optional fixture props (e.g., from a benchmark commit's `props` field).\n * Forwarded to runtimeRender for schema-first mockup synthesis.\n */\n readonly fixtureProps?: JsonObject;\n /**\n * When true, skip the runtime-render probe even if the harness has one.\n * Used by the eval-round runner to keep the probe (~500ms-2s) off the\n * per-turn hot path; the runner runs the probe ONCE at exit-decision\n * time via `harness.check.runtimeRender.run` directly.\n */\n readonly skipRuntimeRender?: boolean;\n}\n\nexport interface CheckResult {\n readonly issues: readonly EvalIssue[];\n readonly axisIssueCount: number;\n readonly tierIssueCount: number;\n readonly llmIssueCount: number;\n readonly runtimeRenderIssueCount: number;\n readonly firedCheckIds: readonly string[];\n}\n\n/**\n * Run every check on a CheckLeg against produced source. Returns all issues\n * with per-source counts for telemetry.\n *\n * Pre-filtering invariant: `check.axisChecks` already only contains checks\n * whose `matches()` gate passed at createHarness time, so this function\n * does no re-matching — it just iterates and runs.\n */\nexport async function runCheck(input: RunCheckInput): Promise<CheckResult> {\n const { harness, sourceCode, compiledCode, contract, prompt } = input;\n const check: CheckLeg = harness.check;\n const startedAt = Date.now();\n\n if (compiledCode === null) {\n const result: CheckResult = {\n issues: [],\n axisIssueCount: 0,\n tierIssueCount: 0,\n llmIssueCount: 0,\n runtimeRenderIssueCount: 0,\n firedCheckIds: [],\n };\n // Emit a trace event even for the no-compile short-circuit so the\n // devtools UI sees the call ran (and can show \"compile failed →\n // checks skipped\").\n const endedAt = Date.now();\n emitValidatorTraceEvent({\n id: newValidatorTraceId(),\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n harnessId: harness.id,\n classification: harness.classification,\n workflowId: harness.process.workflow.id,\n hadCompiledCode: false,\n skippedRuntimeRender: input.skipRuntimeRender ?? false,\n summary: {\n totalIssues: 0,\n axisIssues: 0,\n tierIssues: 0,\n llmIssues: 0,\n runtimeRenderIssues: 0,\n firedCheckIds: [],\n },\n issues: [],\n sourceCode: truncateSourceForTrace(sourceCode),\n prompt,\n });\n return result;\n }\n\n const issues: EvalIssue[] = [];\n const firedIds: string[] = [];\n\n // ── Axis checks (deterministic, pre-gated on harness) ─────────────────\n const axisInput: AxisCheckInput = {\n sourceCode,\n compiledCode,\n contract: contract,\n originalPrompt: prompt,\n classification: harness.classification,\n };\n let axisIssueCount = 0;\n const seenAxisIds = new Set<string>();\n for (const axisCheck of check.axisChecks) {\n if (seenAxisIds.has(axisCheck.id)) continue;\n seenAxisIds.add(axisCheck.id);\n firedIds.push(axisCheck.id);\n const axisIssues = axisCheck.run(axisInput);\n issues.push(...axisIssues);\n axisIssueCount += axisIssues.length;\n }\n\n // ── Tier checks (deterministic, harness-owned) ────────────────────────\n let tierIssueCount = 0;\n for (const tierCheck of check.tierChecks) {\n firedIds.push(tierCheck.id);\n const tierIssues = await tierCheck.run({ sourceCode, compiledCode });\n issues.push(...tierIssues);\n tierIssueCount += tierIssues.length;\n }\n\n // ── Runtime render check (deterministic, ~50-1000ms warm/cold) ────────\n // 2026-04-27: probe runs ONLY when prior cheap checks (axis + tier)\n // produced no tier-0 failures. Rationale: probe is the \"does this\n // actually work at runtime\" gate — wasting ~50-1000ms probing a\n // component the deterministic checks already rejected adds latency\n // with no signal (the LLM is going to fix self-check first anyway,\n // and probe issues on broken-self-check code are noise, not\n // actionable feedback).\n //\n // When axis/tier are clean and probe finds wiring bugs (action not\n // wired, useStream subscribed but never read, prop never rendered),\n // those issues feed back through the same `issues` channel as\n // self-check failures — coding agent gets one more turn with the\n // probe diagnostic. Goal: 0 probe failures on success path.\n let runtimeRenderIssueCount = 0;\n if (check.runtimeRender && !input.skipRuntimeRender) {\n const cheapTier0Failures = issues.filter(\n i => i.result === \"fail\" && (i.tier === 0 || i.tier === undefined),\n ).length;\n if (cheapTier0Failures === 0) {\n const outcome = await check.runtimeRender.run({\n sourceCode,\n compiledCode,\n contract,\n fixtureProps: input.fixtureProps,\n });\n // Only a probe that actually executed counts as a fired check —\n // an infra-skipped / not-applicable outcome carries no evidence\n // and must not appear in `firedCheckIds` as if it gated anything.\n if (outcome.status === \"ran\") {\n firedIds.push(check.runtimeRender.id);\n issues.push(...outcome.issues);\n runtimeRenderIssueCount = outcome.issues.length;\n }\n }\n }\n\n // ── LLM evaluator (optional, async) ───────────────────────────────────\n let llmIssueCount = 0;\n if (check.llmEvaluator && contract) {\n firedIds.push(check.llmEvaluator.id);\n const llmIssues = await check.llmEvaluator.run({\n sourceCode,\n compiledCode,\n contract,\n prompt,\n });\n issues.push(...llmIssues);\n llmIssueCount = llmIssues.length;\n }\n\n const result: CheckResult = {\n issues,\n axisIssueCount,\n tierIssueCount,\n llmIssueCount,\n runtimeRenderIssueCount,\n firedCheckIds: firedIds,\n };\n\n // Emit one validator-trace event capturing the full per-tier\n // breakdown. Devtools-only — no-op when no sink registered (see\n // validator-trace-sink.ts).\n const endedAt = Date.now();\n emitValidatorTraceEvent({\n id: newValidatorTraceId(),\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n harnessId: harness.id,\n classification: harness.classification,\n workflowId: harness.process.workflow.id,\n hadCompiledCode: true,\n skippedRuntimeRender: input.skipRuntimeRender ?? false,\n summary: {\n totalIssues: issues.length,\n axisIssues: axisIssueCount,\n tierIssues: tierIssueCount,\n llmIssues: llmIssueCount,\n runtimeRenderIssues: runtimeRenderIssueCount,\n firedCheckIds: firedIds,\n },\n issues,\n sourceCode: truncateSourceForTrace(sourceCode),\n prompt,\n });\n\n return result;\n}\n","// packages/ui-gen/src/run-harness.ts\n//\n// End-to-end orchestration: run a harness's workflow to produce source,\n// then run the check leg on the result. Owns retry policy (derive new\n// harness + re-run on failure, up to harness.process.retry.maxIterations).\n//\n// Combines runWorkflow + runCheck + the derive loop — the top of the\n// orchestration spine. Re-exported via `@ggui-ai/ui-gen/harness`\n// alongside runWorkflow + runCheck.\n//\n// Shape:\n// for iteration in 1..maxIterations:\n// workflowResult = await runWorkflow(harness, ctx, taskRunners)\n// source = workflowResult.results.source\n// if !source: return { ok: false, reason: \"no source produced\" }\n// checkResult = await runCheck(harness, source)\n// if passingThreshold(checkResult): return { ok: true, source, ... }\n// harness = harness.derive(decideRevision(harness, checkResult))\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { Harness } from \"./harness/types-public.js\";\nimport { runWorkflow, type TaskRunner, type WorkflowRunResult } from \"./run-workflow.js\";\nimport { runCheck, type CheckResult } from \"./run-check.js\";\n\nexport interface RunHarnessInput {\n readonly harness: Harness;\n readonly prompt: string;\n readonly contract: DataContract;\n readonly taskRunners: Readonly<Record<string, TaskRunner>>;\n readonly compile?: (source: string) => Promise<string | null>;\n readonly passes?: (result: CheckResult) => boolean;\n readonly maxIterations?: number;\n /**\n * Skip runCheck() entirely — for callers that have already evaluated\n * the source themselves and don't want the duplicate work. When true,\n * the iteration record's checkResult is empty and `passes` is not\n * consulted; the iteration is treated as passed unconditionally.\n *\n * Used by dispatchGeneration during the runHarness migration: the\n * closure-based generate runner does its own multi-round eval inside\n * the workflow, so re-running runCheck here would re-fire LLM + visual\n * eval needlessly (~5s wasted per generation).\n */\n readonly skipCheck?: boolean;\n}\n\nexport type RunHarnessReason =\n | \"passed\"\n | \"no-source\"\n | \"compile-failed\"\n | \"max-iterations\";\n\nexport interface IterationRecord {\n readonly iteration: number;\n readonly harnessId: string;\n readonly workflowId: string;\n readonly source: string | null;\n readonly compiled: string | null;\n readonly workflowDurationMs: number;\n readonly checkDurationMs: number;\n readonly issueCount: number;\n readonly firedCheckIds: readonly string[];\n}\n\nexport interface RunHarnessResult {\n readonly ok: boolean;\n readonly reason: RunHarnessReason;\n readonly finalHarness: Harness;\n readonly finalSource: string | null;\n readonly finalCompiled: string | null;\n readonly finalCheck: CheckResult | null;\n readonly iterations: readonly IterationRecord[];\n readonly durationMs: number;\n}\n\nconst defaultPasses = (r: CheckResult): boolean =>\n r.issues.every((i) => i.result !== \"fail\");\n\n/**\n * Run harness end-to-end: workflow → compile → check → derive-on-fail.\n *\n * Caller must supply taskRunners — at minimum, a runner for each task in\n * the workflow's phases. The `generate` task (single_pass) should return\n * the produced source as a string.\n */\nexport async function runHarness(input: RunHarnessInput): Promise<RunHarnessResult> {\n const {\n harness: initialHarness,\n prompt,\n contract,\n taskRunners,\n compile,\n passes = defaultPasses,\n maxIterations: explicitMax,\n skipCheck = false,\n } = input;\n\n const maxIterations = explicitMax ?? initialHarness.process.retry.maxIterations;\n const start = Date.now();\n const iterations: IterationRecord[] = [];\n\n let harness = initialHarness;\n let lastSource: string | null = null;\n let lastCompiled: string | null = null;\n let lastCheck: CheckResult | null = null;\n\n for (let i = 1; i <= maxIterations; i++) {\n const workflowResult: WorkflowRunResult = await runWorkflow({\n harness,\n prompt,\n contract,\n taskRunners,\n });\n\n const source = (workflowResult.results.source ?? null) as string | null;\n let compiled: string | null = null;\n if (source && compile) {\n compiled = await compile(source);\n } else if (source && !compile) {\n compiled = source;\n }\n\n // Compile failure is a hard fail. We must NOT fall through to runCheck()\n // — its compile-null branch returns an empty issue set, which the default\n // pass predicate would happily accept as \"no failures = passed\". Bail out\n // explicitly so the iteration record reflects the actual failure mode.\n const compileFailed = source !== null && compile !== undefined && compiled === null;\n\n const checkStart = Date.now();\n const checkResult = source && !compileFailed && !skipCheck\n ? await runCheck({ harness, sourceCode: source, compiledCode: compiled, contract, prompt })\n : { issues: [], axisIssueCount: 0, tierIssueCount: 0, llmIssueCount: 0, runtimeRenderIssueCount: 0, firedCheckIds: [] };\n const checkDurationMs = Date.now() - checkStart;\n\n iterations.push({\n iteration: i,\n harnessId: harness.id,\n workflowId: harness.process.workflow.id,\n source,\n compiled,\n workflowDurationMs: workflowResult.durationMs,\n checkDurationMs,\n issueCount: checkResult.issues.length,\n firedCheckIds: checkResult.firedCheckIds,\n });\n\n lastSource = source;\n lastCompiled = compiled;\n lastCheck = checkResult;\n\n if (!source) {\n return buildResult({\n ok: false,\n reason: \"no-source\",\n finalHarness: harness,\n finalSource: null,\n finalCompiled: null,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (compileFailed) {\n // Don't keep iterating on a compile failure unless the harness has a\n // derive policy that would change codegen — for now, treat it as a\n // terminal signal, the same way no-source is terminal. A future PR can\n // make this iteration-aware once derive policies exist that target it.\n return buildResult({\n ok: false,\n reason: \"compile-failed\",\n finalHarness: harness,\n finalSource: source,\n finalCompiled: null,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (passes(checkResult)) {\n return buildResult({\n ok: true,\n reason: \"passed\",\n finalHarness: harness,\n finalSource: source,\n finalCompiled: compiled,\n finalCheck: checkResult,\n iterations,\n start,\n });\n }\n\n if (i < maxIterations) {\n // Default revision: re-run same harness. Real deriders (planner,\n // runtime fallback, classification swap) plug in via harness.process.retry\n // or an explicit revision function (future API).\n harness = harness.derive({});\n }\n }\n\n return buildResult({\n ok: false,\n reason: \"max-iterations\",\n finalHarness: harness,\n finalSource: lastSource,\n finalCompiled: lastCompiled,\n finalCheck: lastCheck,\n iterations,\n start,\n });\n}\n\nfunction buildResult(args: {\n ok: boolean;\n reason: RunHarnessReason;\n finalHarness: Harness;\n finalSource: string | null;\n finalCompiled: string | null;\n finalCheck: CheckResult | null;\n iterations: IterationRecord[];\n start: number;\n}): RunHarnessResult {\n return {\n ok: args.ok,\n reason: args.reason,\n finalHarness: args.finalHarness,\n finalSource: args.finalSource,\n finalCompiled: args.finalCompiled,\n finalCheck: args.finalCheck,\n iterations: args.iterations,\n durationMs: Date.now() - args.start,\n };\n}\n","// packages/ui-gen/src/fragments/render.ts\n//\n// Render-axis fragments. One per RenderShape. Kept minimal — the stable\n// prefix already covers primitives + design tokens. These only add the\n// per-shape layout pattern the LLM needs to commit to up front.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const renderFragments: Record<string, HarnessFragment> = {\n static: {\n axis: \"render\",\n value: \"static\",\n cacheTier: \"axisDelta\",\n // Static = single entity detail. Stable prefix already covers the\n // obvious pattern (Card + Stack + Heading + fields). No prompt text\n // here keeps low-risk fixtures fast.\n },\n list: {\n axis: \"render\",\n value: \"list\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: list\\nVertical column of items. Each item is a <Card> with <Row> + <Text>. Use key={item.id} on each item. Do not paginate unless the contract has a fetch tool with cursor/offset.\",\n },\n grid: {\n axis: \"render\",\n value: \"grid\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: grid\\n2D tile layout. Use <CardGrid> or CSS `display: grid` with `grid-template-columns: repeat(N, 1fr)`. If items carry row/col fields, position each tile at (row, col). Do not scroll horizontally.\",\n },\n spatial: {\n axis: \"render\",\n value: \"spatial\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: spatial\\nGeo/coord-positioned items. Use absolute positioning inside a relative container, or a map primitive if available. Normalize coords to the container's bounds. Treat lat/lng as y/x, not strings.\",\n },\n timeline: {\n axis: \"render\",\n value: \"timeline\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: timeline\\nGroup items by day (or other temporal bucket). Render a sticky date header per group, then the grouped items. Sort newest-first unless the contract says otherwise. Memoize the grouping with useMemo.\",\n },\n chart: {\n axis: \"render\",\n value: \"chart\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: chart\\nNumeric → visual. Render with inline SVG (no chart library). Compute the viewBox from data min/max. Add axis labels and one value label on the latest/peak point. Keep it readable on a 400px container.\",\n },\n \"master-detail\": {\n axis: \"render\",\n value: \"master-detail\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Render: master-detail\\nSplit view: list on one side, detail panel on the other. Track `selectedId` in useState, default to the first item's id. Desktop = side-by-side; mobile/chat shell = stacked with back button.\",\n },\n};\n","// packages/ui-gen/src/fragments/state.ts\n//\n// State-axis fragments. This is the most error-prone axis — \"merge\" in\n// particular collapses into append-only bugs without explicit guidance.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const stateFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"state\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n // Pure props → JSX. Stable prefix is enough — no useState call at all.\n },\n \"ui-affordance\": {\n axis: \"state\",\n value: \"ui-affordance\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: ui-affordance\\nLocal UI state for filter text / selected id / active tab / quantity. Use useState with a sensible default. Do NOT mirror props into state — read props directly and track only the affordance value.\",\n },\n merge: {\n axis: \"state\",\n value: \"merge\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: merge (live entity reconciliation)\\n1. Seed `const [items, setItems] = useState(props.items ?? [])` AND re-seed on prop change: `useEffect(() => setItems(props.items ?? []), [props.items])` — a `ggui_amend` repaint must move the list.\\n2. On stream updates: `setItems(prev => prev.map(it => it.id === event.id ? { ...it, ...event } : it))` — merge by id, do NOT append.\\n3. Memoize derived views (grouping/sorting/filtering) with useMemo.\\n4. Per-item actions pass `{ id, ... }` in the payload.\\n5. Never push the stream payload into an append-only list unless realtime=append.\",\n boilerplateMarker: [\n \"\",\n \" // ── Live entity state (merge-by-id) ──\",\n \" // useState(props.items ?? []); re-seed via useEffect on [props.items]; merge stream events by item.id; never append.\",\n \"\",\n ].join(\"\\n\"),\n },\n payload: {\n axis: \"state\",\n value: \"payload\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: payload (form assembly)\\nAccumulate form fields in a single state object. Validate on blur or on submit — do NOT block keystrokes. The submit action fires once, with the assembled payload.\",\n boilerplateMarker: [\n \"\",\n \" // ── Form payload ──\",\n \" // useState<FormData> seeded with defaults from props or empty; validate on submit.\",\n \"\",\n ].join(\"\\n\"),\n },\n draft: {\n axis: \"state\",\n value: \"draft\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## State: draft (in-place editor)\\nEdit one item at a time. Track `draft` as a separate useState (not mutating the source). Support cancel (discard draft) and save (commit draft → fire action).\",\n },\n};\n","// packages/ui-gen/src/fragments/writes.ts\n//\n// Writes-axis fragments. Covers both WriteShape (what) and WriteTrigger (how).\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const writeFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"writes\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n },\n commit: {\n axis: \"writes\",\n value: \"commit\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: commit\\nOne action with a small payload (e.g., addToCart). Wire useAction on a single Button. Do not block the UI on completion — this is fire-and-forget.\",\n },\n \"multi-commit\": {\n axis: \"writes\",\n value: \"multi-commit\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: multi-commit\\nMultiple unrelated single-commit actions (e.g., cancel / change destination / contact driver). Each action has its own Button. No shared payload assembly.\",\n },\n \"per-item\": {\n axis: \"writes\",\n value: \"per-item\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: per-item\\nEach item in the entity list has its own action button(s). The payload must include the item's id. Example: `onClick={() => toggle({ id: item.id, completed: !item.completed })}`.\",\n boilerplateMarker: [\n \"\",\n \" // ── Per-item actions ──\",\n \" // Pass {id, ...} in the payload; wire to a Button inside each item's card.\",\n \"\",\n ].join(\"\\n\"),\n },\n submit: {\n axis: \"writes\",\n value: \"submit\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: submit\\nTerminal form submit. One action fires with the full assembled payload at the end. Disable the submit button while pending and after success.\",\n },\n compose: {\n axis: \"writes\",\n value: \"compose\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Writes: compose (cross-entity action)\\nOne trigger references ids from two or more entity lists (e.g., {eventId, calendarId}). Track both selections in local state. Only enable the trigger once both are chosen.\",\n },\n};\n\n// WriteTrigger is a separate axis but lives in the same file for locality.\nexport const writeTriggerFragments: Record<string, HarnessFragment> = {\n click: {\n axis: \"writeTrigger\",\n value: \"click\",\n cacheTier: \"axisDelta\",\n // Default case — covered by stable prefix.\n },\n drag: {\n axis: \"writeTrigger\",\n value: \"drag\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: drag\\nDrag-drop interaction. Use HTML5 drag events (onDragStart, onDragOver, onDrop) on the item and drop zones. Track the dragged item id in useState. Set data-ggui-draggable on draggable elements. Do NOT pull in an external dnd library.\",\n boilerplateMarker: [\n \"\",\n \" // ── Drag state ──\",\n \" // Track the dragged item id; fire the action on drop with {id, destination}.\",\n \"\",\n ].join(\"\\n\"),\n },\n swipe: {\n axis: \"writeTrigger\",\n value: \"swipe\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: swipe\\nTouch gesture → one of N actions. Use onTouchStart/onTouchMove/onTouchEnd. Also expose fallback Buttons so desktop users can trigger the same actions by click.\",\n },\n keystroke: {\n axis: \"writeTrigger\",\n value: \"keystroke\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: keystroke\\nKeyboard shortcut. Attach onKeyDown to the container (with tabIndex={0}) or use a window listener inside useEffect with cleanup. Document visible shortcuts in the UI.\",\n },\n auto: {\n axis: \"writeTrigger\",\n value: \"auto\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Trigger: auto\\nEffect-driven. Use useEffect with a debounce (setTimeout + clearTimeout). Do not fire the action on every keystroke.\",\n },\n};\n","// packages/ui-gen/src/fragments/realtime.ts\n//\n// Realtime-axis fragments. Stream semantics drive whether you merge,\n// append, replace, or do nothing. \"mixed\" needs per-event kind dispatch.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const realtimeFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"realtime\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n },\n merge: {\n axis: \"realtime\",\n value: \"merge\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: merge\\nStream events carry an id; merge into LOCAL STATE. Subscribing alone is not enough — the local list must update on each event for the DOM to re-render.\\n\\n```tsx\\nconst stream = useStream<UpdateT>('streamName');\\nconst [items, setItems] = useState(props.items);\\nuseEffect(() => setItems(props.items), [props.items]); // re-seed on ggui_amend repaint — props stay the source of truth\\nuseEffect(() => {\\n if (!stream.latest) return;\\n setItems((prev) => prev.map((it) => it.id === stream.latest!.id ? { ...it, ...stream.latest } : it));\\n}, [stream.latest]);\\n// Render `items.map(...)` — NOT props.items, NOT stream.all.\\n```\\n\\nNever append — stream=merge means the entity already exists locally.\",\n },\n append: {\n axis: \"realtime\",\n value: \"append\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: append\\nStream events are new entities; APPEND to local state. Subscribing alone is not enough — the local list must update for the DOM to re-render.\\n\\n```tsx\\nconst stream = useStream<EventT>('streamName');\\nconst [items, setItems] = useState(props.items);\\nuseEffect(() => setItems(props.items), [props.items]); // re-seed on ggui_amend repaint — props stay the source of truth\\nuseEffect(() => {\\n if (!stream.latest) return;\\n setItems((prev) => [...prev, stream.latest!]);\\n}, [stream.latest]);\\n// Render `items.map(...)` — NOT props.items, NOT stream.all (which accumulates only post-mount).\\n```\\n\\nUse head for newest-first, tail for chat-style. Cap list length if needed. Do not dedupe unless the contract guarantees at-most-once.\",\n },\n status: {\n axis: \"realtime\",\n value: \"status\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: status\\nStream replaces a singleton (e.g., marketStatus, rideStatus). `stream.latest` is the current value — bind directly into JSX, no local state needed for the singleton itself:\\n\\n```tsx\\nconst statusStream = useStream<StatusT>('streamName');\\nconst status = statusStream.latest;\\n// Render `<Badge>{status?.state ?? 'loading'}</Badge>`.\\n```\\n\\nIf you also need the timestamp of the last update, derive it from `useEffect` on `statusStream.latest`.\",\n },\n presence: {\n axis: \"realtime\",\n value: \"presence\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: presence\\nEphemeral per-user state (typing, cursors, online). Do NOT persist to a list. Sync into a `Set` and clear entries based on the active flag or a timeout:\\n\\n```tsx\\nconst stream = useStream<{ sender: string; active: boolean }>('streamName');\\nconst [active, setActive] = useState<Set<string>>(new Set());\\nuseEffect(() => {\\n if (!stream.latest) return;\\n setActive((prev) => {\\n const next = new Set(prev);\\n if (stream.latest!.active) next.add(stream.latest!.sender);\\n else next.delete(stream.latest!.sender);\\n return next;\\n });\\n}, [stream.latest]);\\n```\",\n },\n mixed: {\n axis: \"realtime\",\n value: \"mixed\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Realtime: mixed\\nMultiple stream channels with DIFFERENT semantics. Each `streamKinds` entry in the contract maps to one of: merge, append, status, presence. Subscribe + sync to local state PER CHANNEL — subscribing alone never re-renders the DOM.\\n\\nExample (chat-interface — message=append, typing=presence):\\n\\n```tsx\\nconst messages = useStream<MessageT>('message');\\nconst typing = useStream<TypingT>('typing');\\nconst [messageList, setMessageList] = useState(props.messages);\\nconst [typingUsers, setTypingUsers] = useState<Set<string>>(new Set());\\n\\nuseEffect(() => setMessageList(props.messages), [props.messages]); // re-seed on ggui_amend repaint\\n\\nuseEffect(() => {\\n if (!messages.latest) return;\\n setMessageList((prev) => [...prev, messages.latest!]);\\n}, [messages.latest]);\\n\\nuseEffect(() => {\\n if (!typing.latest) return;\\n setTypingUsers((prev) => {\\n const next = new Set(prev);\\n if (typing.latest!.active) next.add(typing.latest!.sender);\\n else next.delete(typing.latest!.sender);\\n return next;\\n });\\n}, [typing.latest]);\\n```\\n\\nDo NOT treat all events the same. Do NOT skip the local-state sync — `useStream` alone won't trigger DOM updates of your derived view.\",\n boilerplateMarker: [\n \"\",\n \" // ── Mixed stream handlers ──\",\n \" // One useStream + useEffect+setState per channel — see realtime fragment.\",\n \"\",\n ].join(\"\\n\"),\n },\n};\n","// packages/ui-gen/src/fragments/fetch.ts\n//\n// Fetch-axis fragments. Covers how the component reacts to agent-fetched\n// data — agent-side tools live in `agentCapabilities.tools` (catalog\n// only); the component itself never invokes them directly.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const fetchFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"fetch\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n },\n pagination: {\n axis: \"fetch\",\n value: \"pagination\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: pagination\\nTrack `cursor` (or offset/page) in useState. Expose a 'Load more' Button that calls the tool with the next cursor and appends results. Show a spinner while tool.isPending.\",\n },\n search: {\n axis: \"fetch\",\n value: \"search\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: search\\nDebounced query → tool call. Track `query` in useState; fire the tool inside useEffect after a 300ms debounce. Replace (don't append) results on each call. Guard against stale responses.\",\n },\n \"drill-down\": {\n axis: \"fetch\",\n value: \"drill-down\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: drill-down\\nOn item click, call the tool with the item's id and show the detail. Track `selectedId` and `detail` separately; render a loading placeholder while tool.isPending.\",\n },\n refresh: {\n axis: \"fetch\",\n value: \"refresh\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Fetch: refresh\\nUser-triggered re-fetch (e.g., pull-to-refresh or a Refresh button). Re-call the tool with the same args; show a small spinner while pending.\",\n },\n};\n","// packages/ui-gen/src/fragments/layout.ts\n//\n// Layout-axis fragments. Structural composition — how the screen is split.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const layoutFragments: Record<string, HarnessFragment> = {\n single: {\n axis: \"layout\",\n value: \"single\",\n cacheTier: \"axisDelta\",\n },\n \"multi-step\": {\n axis: \"layout\",\n value: \"multi-step\",\n cacheTier: \"axisDelta\",\n // 2026-04-27: anti-pattern warnings added after 6× n=3 benches showed\n // survey-form + onboarding-wizard accounted for 9 of 11 probe FAILs\n // (\"Too many re-renders\" 6×, \"function is not iterable\" 2×, TDZ 1×).\n // All 3 classes trace to the same multi-step-specific anti-patterns\n // below; non-multi-step fixtures had 0 fails across the same benches.\n promptText:\n \"## Layout: multi-step\\n\" +\n \"Wizard. Track `step` in useState (0-indexed). Render \" +\n \"`<Stepper steps={STEPS} current={step} />` as the progress \" +\n \"indicator — do NOT hand-roll a '2 of 4' counter, and do NOT \" +\n \"reach for Tabs/Progress/Breadcrumb. Stepper is display-only: \" +\n \"your Next/Back buttons move `step`. Keep all step state in a \" +\n \"single payload object; do NOT reset previous-step data on \" +\n \"navigation.\\n\\n\" +\n \"### Anti-patterns that crash at runtime — DO NOT do these:\\n\\n\" +\n \"1. **No setState in render body** — causes 'Too many re-renders'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — fires every render, infinite loop\\n\" +\n \"const Form = () => {\\n\" +\n \" const [errors, setErrors] = useState({});\\n\" +\n \" setErrors(validate(values)); // setState in render → loop\\n\" +\n \"};\\n\" +\n \"// ✅ RIGHT — derive with useMemo (no state)\\n\" +\n \"const Form = () => {\\n\" +\n \" const errors = useMemo(() => validate(values), [values]);\\n\" +\n \"};\\n\" +\n \"```\\n\\n\" +\n \"2. **No setState in useEffect with state-derived deps** — also \" +\n \"causes 'Too many re-renders'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — payload identity changes → setIsValid → re-render → ...\\n\" +\n \"useEffect(() => { setIsValid(check(payload)); }, [payload]);\\n\" +\n \"// ✅ RIGHT — useMemo, no setState\\n\" +\n \"const isValid = useMemo(() => check(payload), [payload]);\\n\" +\n \"```\\n\\n\" +\n \"3. **Declare `steps` array as a top-level `const`, NEVER state.** \" +\n \"Default arrays (`fields`, `options`) the same way. Iterating over \" +\n \"an undefined or unstable array throws 'function is not iterable'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — useState('steps array...') is a string, .map crashes\\n\" +\n \"const [steps] = useState('Welcome,Profile,Done');\\n\" +\n \"// ✅ RIGHT — top-level const\\n\" +\n \"const STEPS = ['Welcome', 'Profile', 'Done'] as const;\\n\" +\n \"```\\n\\n\" +\n \"4. **Hooks/`const` declarations come BEFORE any useEffect/\" +\n \"useMemo/useCallback that reads them.** Otherwise: TDZ 'Cannot \" +\n \"access X before initialization'.\\n\" +\n \"```tsx\\n\" +\n \"// ❌ WRONG — useEffect reads `total` before its `const` line\\n\" +\n \"useEffect(() => log(total), [total]);\\n\" +\n \"const total = items.reduce(sum, 0);\\n\" +\n \"// ✅ RIGHT — declare first, read after\\n\" +\n \"const total = items.reduce(sum, 0);\\n\" +\n \"useEffect(() => log(total), [total]);\\n\" +\n \"```\",\n },\n \"master-detail\": {\n axis: \"layout\",\n value: \"master-detail\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Layout: master-detail\\nSplit container: master list on the left/top, detail panel on the right/bottom. Track `selectedId` and show a 'select an item' placeholder in the detail panel when null.\",\n },\n overlay: {\n axis: \"layout\",\n value: \"overlay\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Layout: overlay\\nFloating controls layered on top of content. Use position: absolute with explicit insets. Ensure the overlay does not block critical content (leave a safe area).\",\n },\n modal: {\n axis: \"layout\",\n value: \"modal\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Layout: modal\\nUse the <Modal> primitive. Track `isOpen` in useState. Provide a clear close affordance (X button + clicking backdrop). Trap focus inside the modal.\",\n },\n};\n","// packages/ui-gen/src/fragments/tooling.ts\n//\n// tooling-axis fragments. The contract carries two tooling surfaces:\n//\n// - `agentCapabilities.tools` — catalog of agent-invoked tools the\n// contract references via `actionSpec[*].nextStep` and\n// `streamSpec[*].source.tool`. NO component-side hook surface.\n// - `clientCapabilities.gadgets` — catalog of browser-capability\n// gadget hooks (geolocation, mic, camera, clipboard, file picker,\n// notifications). The component imports + calls these hooks\n// from `@ggui-ai/gadgets` (or the third-party package named in\n// `entry.package`).\n//\n// The `wired` / `client` / `both` axis values map onto these surfaces\n// by what the contract carries; the prompt text steers the LLM toward\n// the correct patterns.\n\nimport type { HarnessFragment } from \"./types.js\";\n\nexport const toolingFragments: Record<string, HarnessFragment> = {\n none: {\n axis: \"tooling\",\n value: \"none\",\n cacheTier: \"axisDelta\",\n // Nothing to say — contract carries no agentCapabilities.tools /\n // clientCapabilities.gadgets.\n },\n wired: {\n axis: \"tooling\",\n value: \"wired\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Tooling: agent-side tools (catalog only)\\nThe contract declares `agentCapabilities.tools[X]` for tools the AGENT invokes — the component never calls these directly. References surface via `actionSpec[Y].nextStep = 'X'` (the agent's next-turn hint forwarded on action events) and `streamSpec[Z].source.tool = 'X'` (the runtime polls / subscribes the tool, deliveries land on the stream channel). Author UI controls fire actions via `useAction`; data feeds appear via `useStream`. The `useWiredTool` hook from before 2026-05-11 is RETIRED.\",\n },\n client: {\n axis: \"tooling\",\n value: \"client\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Tooling: gadgets (browser-capability hooks)\\nThe contract declares `clientCapabilities.gadgets[X]` for browser-capability gadget hooks the UI mounts. The boilerplate has pre-emitted a direct import per gadget package — `import { useFoo, useBar } from '<package>';` — above a `// DO NOT EDIT` banner (STDLIB hooks come from `@ggui-ai/gadgets`, third-party hooks from the package on `clientCapabilities.gadgets[*].package`). Call the imported hook inside the component (`const loc = useGeolocation();`) and trigger via `.start()` from a UI control. Read `.value` / `.status` to render. If the agent needs to observe the result, thread `.value` into a `contextSpec` slot or an `actionSpec` payload. Library hooks are UI-owned lifecycle; the agent never invokes them. **KEEP every pre-emitted gadget import — do NOT delete it and do NOT change its package**; self_check rejects the code with `gadget_preservation:<hook>` if a gadget import disappears. The pre-2026-05-11 `useClientTool(name, handler)` shape is RETIRED, as is the `@ggui-ai/client-tools` package name (renamed to `@ggui-ai/gadgets`).\",\n },\n both: {\n axis: \"tooling\",\n value: \"both\",\n cacheTier: \"axisDelta\",\n promptText:\n \"## Tooling: both surfaces present\\nThe contract declares BOTH `agentCapabilities.tools` (agent-invoked catalog; referenced via `actionSpec.nextStep` / `streamSpec.source.tool` — NO component hook) AND `clientCapabilities.gadgets` (browser-capability gadget hooks the component direct-imports — the boilerplate pre-emits `import { useCamera } from '@ggui-ai/gadgets';` (STDLIB) or `import { useFoo } from '<package>';` (third-party) above a `// DO NOT EDIT` banner). Don't conflate: agentCapabilities entries are catalog declarations the agent uses, NOT component hooks. clientCapabilities entries DO emit component-side hook calls (e.g., `const cam = useCamera();`).\",\n },\n};\n","// packages/ui-gen/src/fragments/index.ts\n//\n// Public barrel for the `@ggui-ai/ui-gen/fragments` subpath.\n//\n// Stable public surface (what external consumers should build against):\n// - `FRAGMENT_REGISTRY` — the axis-keyed registry\n// - `lookupFragment` — the one-call lookup helper\n// - fragment types — HarnessFragment, ComposedHarness, CacheTier, AxisKey\n//\n// Per-axis fragment records (renderFragments, stateFragments, etc.) are\n// intentionally NOT re-exported here — consumers who genuinely need one\n// can read `FRAGMENT_REGISTRY.render` / `.state` / etc. Keeping the public\n// surface to a single entry point preserves our freedom to reshape the\n// per-axis files without breaking semver.\n\nimport type { AxisKey, HarnessFragment } from \"./types.js\";\nimport { renderFragments } from \"./render.js\";\nimport { stateFragments } from \"./state.js\";\nimport { writeFragments, writeTriggerFragments } from \"./writes.js\";\nimport { realtimeFragments } from \"./realtime.js\";\nimport { fetchFragments } from \"./fetch.js\";\nimport { layoutFragments } from \"./layout.js\";\nimport { toolingFragments } from \"./tooling.js\";\n\nexport type { HarnessFragment, ComposedHarness, CacheTier, AxisKey } from \"./types.js\";\n\nexport const FRAGMENT_REGISTRY: Record<AxisKey, Record<string, HarnessFragment>> = {\n render: renderFragments,\n state: stateFragments,\n writes: writeFragments,\n writeTrigger: writeTriggerFragments,\n realtime: realtimeFragments,\n fetch: fetchFragments,\n layout: layoutFragments,\n tooling: toolingFragments,\n};\n\nexport function lookupFragment(axis: AxisKey, value: string): HarnessFragment | undefined {\n return FRAGMENT_REGISTRY[axis]?.[value];\n}\n","// packages/ui-gen/src/compose.ts\n//\n// Materializes a Classification into prompt sections + boilerplate markers.\n// Sits between the stable prefix (design system docs, pitfalls) and the\n// volatile feedback (eval issues) in the system prompt's cache tiering.\n//\n// Consumes the `./classifier` and `./fragments` subpaths — it's the\n// bridge between an axis vector and the prompt/boilerplate the LLM\n// actually sees.\n\nimport type { Classification } from \"./classifier/axes.js\";\nimport {\n lookupFragment,\n type AxisKey,\n type ComposedHarness,\n type HarnessFragment,\n} from \"./fragments/index.js\";\n\n// Axis processing order inside axisDelta. Puts the most behaviourally\n// consequential axes first so the LLM reads them before scanning details.\nconst AXIS_ORDER: AxisKey[] = [\n \"render\",\n \"layout\",\n \"state\",\n \"writes\",\n \"writeTrigger\",\n \"realtime\",\n \"fetch\",\n \"tooling\",\n];\n\nexport function compose(classification: Classification): ComposedHarness {\n const v = classification.vector;\n const matched: HarnessFragment[] = [];\n\n for (const axis of AXIS_ORDER) {\n const value = v[axis] as string | undefined;\n if (!value) continue;\n const frag = lookupFragment(axis, value);\n if (frag) matched.push(frag);\n }\n\n const promptParts = matched\n .filter((f) => f.promptText && f.promptText.trim().length > 0)\n .map((f) => f.promptText!.trim());\n\n const boilerplateParts = matched\n .filter((f) => f.boilerplateMarker && f.boilerplateMarker.trim().length > 0)\n .map((f) => f.boilerplateMarker!);\n\n return {\n promptText: promptParts.join(\"\\n\\n\"),\n boilerplateSections: boilerplateParts.join(\"\"),\n fragments: matched,\n };\n}\n\nexport type { ComposedHarness };\n","// packages/ui-gen/src/boilerplate/render.ts\n//\n// Loads base.tsx.tmpl + layout files from disk, caches them in memory,\n// and replaces {{MARKER}} placeholders with generated content.\n//\n// Package-private — consumers use `generateBoilerplate()` from\n// `@ggui-ai/ui-gen/boilerplate`; this file is not re-exported.\n\nimport { readFileSync } from 'node:fs';\nimport { resolve, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// `@ggui-ai/ui-gen` ships both `src/` and `dist/` (see package.json `files`).\n// Templates always live at `<pkg-root>/src/boilerplate/templates/` (kept in\n// the published tarball via `files: ['src', 'dist', ...]`). Render.ts gets\n// inlined into multiple dist entrypoints by tsup (`boilerplate.js`,\n// `harness/runtime.js`, `harness/index.js`, …), so `__dirname` varies. We\n// enumerate every reasonable location:\n//\n// - From tsx (`src/boilerplate/render.ts`): `./templates`\n// - Bundled into `dist/boilerplate.js`: `../src/boilerplate/templates`\n// - Bundled into `dist/harness/runtime.js`: `../../src/boilerplate/templates`\n// - Bundled into `dist/harness/coding/X.js`: `../../../src/boilerplate/templates`\n//\n// Step 3 (2026-04-27): the harness cluster ported in from cloud added the\n// `dist/harness/` and `dist/harness/coding/` entrypoints — needed deeper\n// upward walks than the pre-step-3 single-level `dist/`.\nconst TEMPLATE_DIRS = [\n resolve(__dirname, 'templates'),\n resolve(__dirname, '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', '..', 'src', 'boilerplate', 'templates'),\n];\n\nlet baseCache: string | null = null;\nconst layoutCache = new Map<string, string>();\n\nfunction loadBase(): string {\n if (baseCache) return baseCache;\n\n for (const dir of TEMPLATE_DIRS) {\n try {\n baseCache = readFileSync(resolve(dir, 'base.tsx.tmpl'), 'utf-8');\n return baseCache;\n } catch { continue; }\n }\n\n throw new Error('No base.tsx.tmpl found');\n}\n\nfunction loadLayout(shellType: string, screen: string): string {\n const key = `${shellType}-${screen}`;\n if (layoutCache.has(key)) return layoutCache.get(key)!;\n\n // Try exact match, then fallback to universal, then fullscreen-universal\n const candidates = [\n `${shellType}-${screen}.tsx.tmpl`,\n `${shellType}-universal.tsx.tmpl`,\n `fullscreen-universal.tsx.tmpl`, // final fallback\n ];\n\n for (const filename of candidates) {\n for (const dir of TEMPLATE_DIRS) {\n try {\n const content = readFileSync(resolve(dir, 'layouts', filename), 'utf-8');\n layoutCache.set(key, content);\n return content;\n } catch { continue; }\n }\n }\n\n throw new Error(`No layout found for ${key}`);\n}\n\nexport interface BoilerplateMarkers {\n REACT_IMPORT: string;\n ALL_DESIGN: string;\n WIRE_IMPORT: string;\n PROPS_INTERFACE: string;\n ACTION_TYPES: string;\n STREAM_TYPES: string;\n /** `useGguiContext` destructure lines, one per declared `contextSpec`\n * slot. Emitted at the top of the user component body. The runtime\n * owns useState + Provider per slot; the LLM only reads `<slotKey>`\n * and writes via `set<SlotKey>`. Empty when contextSpec is absent or\n * empty. */\n CONTEXT_HOOKS: string;\n WIRE_HOOKS: string;\n AXIS_SECTIONS: string;\n}\n\nexport function renderBoilerplate(\n shellType: string,\n screen: string,\n markers: BoilerplateMarkers,\n): string {\n let template = loadBase();\n const layout = loadLayout(shellType, screen);\n template = template.replace('{{LAYOUT}}', layout);\n\n for (const [key, value] of Object.entries(markers)) {\n template = template.replaceAll(`{{${key}}}`, value);\n }\n\n return template;\n}\n","// packages/ui-gen/src/boilerplate/json-schema-ts.ts\n//\n// JSON Schema → TypeScript type string converter.\n//\n// Pure, self-contained, no env reads, no framework deps. Exposed\n// publicly on `@ggui-ai/ui-gen/boilerplate` because it's the primitive\n// that turns a contract's JSON Schema into the `interface Props { ... }`\n// block the boilerplate generator writes.\n\nimport type { JsonSchema } from '@ggui-ai/protocol';\n\n/**\n * Convert a JsonSchema to a TypeScript type string — recursive.\n *\n * Handles: string, number, integer, boolean, null, array (+ tuples), object,\n * enum, oneOf/anyOf (unions), nullable, const, additionalProperties.\n */\nexport function jsonSchemaTypeToTs(schema: JsonSchema): string {\n // ── Union types (oneOf / anyOf) ──\n const unionMembers = schema.oneOf ?? schema.anyOf;\n if (unionMembers?.length) {\n const types = [...new Set(unionMembers.map(s => jsonSchemaTypeToTs(s)))];\n return types.length === 1 ? types[0] : types.join(' | ');\n }\n\n // ── Const (literal type) ──\n if (schema.const !== undefined) {\n return typeof schema.const === 'string' ? `'${schema.const}'` : String(schema.const);\n }\n\n // ── Enum (union of literals) ──\n if (schema.enum?.length) {\n return schema.enum\n .map(v => typeof v === 'string' ? `'${v}'` : String(v))\n .join(' | ');\n }\n\n // ── Draft-07 type array (`['string','null']` — the canonical\n // nullable form since draft-2026-08-19): members' TS union. Each\n // member re-enters with the single type so object/array members\n // keep their properties/items; `nullable` is folded in here (not in\n // the recursion) so it can't double-append. ──\n if (Array.isArray(schema.type)) {\n const { nullable: _nullable, ...rest } = schema;\n const members = [...new Set(schema.type)].map((member) =>\n jsonSchemaTypeToTs({ ...rest, type: member }),\n );\n const unique = [...new Set(members)];\n if (schema.nullable && !unique.includes('null')) unique.push('null');\n return unique.join(' | ');\n }\n\n let result: string;\n\n switch (schema.type) {\n case 'string':\n result = 'string';\n break;\n case 'number':\n case 'integer':\n result = 'number';\n break;\n case 'boolean':\n result = 'boolean';\n break;\n case 'null':\n return 'null';\n\n case 'array': {\n if (schema.items) {\n const itemType = jsonSchemaTypeToTs(schema.items);\n // Use Array<T> for complex object types, T[] for simple.\n // `items.type` may be a type SET — treat any set containing\n // 'object' like the single-string form.\n const itemsDeclareObject = Array.isArray(schema.items.type)\n ? schema.items.type.includes('object')\n : schema.items.type === 'object';\n result = (itemsDeclareObject && schema.items.properties)\n ? `Array<${itemType}>`\n : (itemType.includes('|') ? `(${itemType})[]` : `${itemType}[]`);\n } else {\n result = 'unknown[]';\n }\n break;\n }\n\n case 'object': {\n if (schema.properties) {\n const required = schema.required ?? [];\n const fields = Object.entries(schema.properties)\n .map(([key, prop]) => {\n const opt = !required.includes(key);\n return `${key}${opt ? '?' : ''}: ${jsonSchemaTypeToTs(prop)}`;\n })\n .join('; ');\n result = `{ ${fields} }`;\n } else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {\n result = `Record<string, ${jsonSchemaTypeToTs(schema.additionalProperties)}>`;\n } else {\n result = 'Record<string, unknown>';\n }\n break;\n }\n\n default:\n result = 'unknown';\n }\n\n // Apply nullable (OpenAPI 3.0 shorthand)\n if (schema.nullable && result !== 'unknown') {\n return `${result} | null`;\n }\n\n return result;\n}\n","// packages/ui-gen/src/boilerplate/generate.ts\n//\n// Typed boilerplate generator. Takes a data contract (propsSpec /\n// actionSpec / streamSpec / contextSpec + agentCapabilities.tools +\n// clientCapabilities.gadgets catalogs) and a rendering context\n// (shell + screen) and produces the starting `.tsx` boilerplate the\n// coding agent fills in via apply_changes.\n//\n// `agentCapabilities.tools` entries do NOT emit component hooks. They\n// are catalog declarations the AGENT invokes; component code references\n// them indirectly via `actionSpec.nextStep` (advisory hint surfacing on\n// action events) and `streamSpec.source.tool` (transport-negotiated\n// source).\n//\n// `clientCapabilities.gadgets` entries DO emit component-side gadget\n// plumbing. Gadgets are direct-imported: the generator emits one\n// combined `import { … } from '<package>'` per registered gadget\n// package, above a `// DO NOT EDIT` banner. Hook exports additionally\n// get a pre-emitted `const binding = hook();` call site; component\n// exports are import-only — the LLM renders `<X … />` in the JSX tree\n// itself. The deterministic `gadget_preservation` check rejects the\n// code if a gadget import disappears.\n//\n// Pure function — deterministic, no env reads, no I/O other than\n// `renderBoilerplate` reading the template files.\n\nimport type {\n ActionSpec,\n GadgetDescriptor,\n ContextSpec,\n DataContract,\n JsonObject,\n JsonValue,\n StreamSpec,\n} from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport { renderBoilerplate } from \"./render.js\";\nimport { jsonSchemaTypeToTs } from \"./json-schema-ts.js\";\n\n/** Shell layout modes supported by the boilerplate templates. */\nexport type ShellType = \"chat\" | \"fullscreen\" | \"spatial\";\n\n/** Target screen size. */\nexport type ScreenSize = \"mobile\" | \"tablet\" | \"desktop\" | \"universal\";\n\n// =============================================================================\n// Design-system surface (pre-imported in every boilerplate)\n// =============================================================================\n\nconst ALL_PRIMITIVES = [\n \"Container\",\n \"Card\",\n \"Stack\",\n \"Row\",\n \"Grid\",\n \"Box\",\n \"Divider\",\n \"Spacer\",\n \"Text\",\n \"Heading\",\n \"Button\",\n \"Input\",\n \"TextArea\",\n \"Select\",\n \"Checkbox\",\n \"Toggle\",\n \"RadioGroup\",\n \"Slider\",\n \"Badge\",\n \"Spinner\",\n \"Skeleton\",\n \"Avatar\",\n \"Alert\",\n \"Progress\",\n \"Image\",\n \"Icon\",\n \"Link\",\n \"Tooltip\",\n \"Table\",\n \"Tabs\",\n \"Toast\",\n \"Accordion\",\n \"MotionKeyframes\",\n \"useMotion\",\n \"useAnimationKey\",\n].join(\", \");\n\nconst ALL_COMPONENTS = [\n \"SearchField\",\n \"FormField\",\n \"MenuItem\",\n \"Tag\",\n \"Dropdown\",\n \"Autocomplete\",\n \"Breadcrumb\",\n \"Pagination\",\n \"EmptyState\",\n \"Stat\",\n \"Stepper\",\n \"Markdown\",\n \"MarkdownInline\",\n].join(\", \");\n\n// Mirrors the actual @ggui-ai/design compositions exports. The 2026-07-29\n// composite-roster wave (#306) deleted the six zero-consumer composites\n// (MakeTabLayout, MarketingHero/CTA/Features, IncidentTimeline,\n// UserProfileCard) from the design package; this list shrank with it.\n// The data-URL shim's allowlist must mirror this list (enforced by\n// verify-shim-allowlists.test.ts).\nconst ALL_COMPOSITIONS = [\n \"Header\",\n \"Sidebar\",\n \"CardGrid\",\n \"CommentThread\",\n \"DataTable\",\n \"ChatWindow\",\n \"NavigationBar\",\n \"FileUploader\",\n \"NotificationCenter\",\n \"Modal\",\n \"CommandPalette\",\n \"Footer\",\n \"Hero\",\n].join(\", \");\n\nconst ALL_INTERACT = [\"Clickable\", \"Hoverable\", \"Pressable\"].join(\", \");\n\n// D1: the whole design system is imported through one specifier\n// (`@ggui-ai/design`), so the boilerplate emits a single import line.\nconst ALL_DESIGN = [\n ALL_PRIMITIVES,\n ALL_COMPONENTS,\n ALL_COMPOSITIONS,\n ALL_INTERACT,\n].join(\", \");\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/** Infer a TypeScript type string from an example value (when no JSON Schema is available). */\nfunction inferTypeFromExample(example: JsonObject): string {\n const fields: string[] = [];\n for (const [k, v] of Object.entries(example)) {\n let t: string;\n if (v === null || v === undefined) t = \"unknown\";\n else if (typeof v === \"string\") t = \"string\";\n else if (typeof v === \"number\") t = \"number\";\n else if (typeof v === \"boolean\") t = \"boolean\";\n else if (Array.isArray(v)) {\n if (v.length === 0) t = \"unknown[]\";\n else if (typeof v[0] === \"string\") t = \"string[]\";\n else if (typeof v[0] === \"number\") t = \"number[]\";\n else if (typeof v[0] === \"object\" && v[0] !== null)\n t = `Array<${inferTypeFromExample(v[0] as JsonObject)}>`;\n else t = \"unknown[]\";\n } else if (typeof v === \"object\") {\n t = inferTypeFromExample(v as JsonObject);\n } else {\n t = \"unknown\";\n }\n fields.push(`${k}: ${t}`);\n }\n return `{ ${fields.join(\"; \")} }`;\n}\n\n// =============================================================================\n// Boilerplate generator\n// =============================================================================\n\nexport function generateBoilerplate(\n _userPrompt: string,\n contract?: DataContract,\n shellType?: ShellType,\n screen?: ScreenSize,\n /** Axis-composed boilerplate sections — fragments produced by `compose()`. */\n composedSections?: string,\n /**\n * Registered gadget catalog. The boilerplate emits a direct\n * `import { … } from '<package>'` per gadget package from the\n * contract's declarations; this catalog supplies the descriptor\n * metadata (`description` / `usage` / `example`) used to prime each\n * pre-emitted gadget call site so the LLM has a working starting\n * point rather than an empty `useFoo()` it might delete.\n */\n appGadgets?: readonly GadgetDescriptor[],\n): string {\n // ── Props interface from data contract (data only — NO action callbacks) ──\n // Contract shape (PropsSpec is ALWAYS the wrapper — never flat):\n // { properties: { fieldName: { schema, required, description } } }\n const propsFields: string[] = [];\n const propsProperties = contract?.propsSpec?.properties ?? {};\n for (const [key, entry] of Object.entries(propsProperties)) {\n // Required is OPT-IN (`required === true`) — the same reading the\n // wire gate applies (`contract-validator.ts` builds the JSON-Schema\n // `required` list from `=== true`), the contract summary's `!`\n // marker uses, and coverage annotates with. The old `!== false`\n // reading typed omitted-`required` props as always-present, so a\n // render the gate legitimately accepts (agent omits an optional\n // prop) crashed on `props.x.map(...)` — ggui#528.\n const required = entry.required === true;\n const nullable = entry.schema.nullable === true;\n const tsType = jsonSchemaTypeToTs(entry.schema);\n const fullType = nullable ? `${tsType} | null` : tsType;\n // Build comment: description + default hint + optionality contract\n const parts: string[] = [];\n if (entry.description) parts.push(entry.description);\n if (entry.default !== undefined) parts.push(`(default: ${JSON.stringify(entry.default)})`);\n if (!required) parts.push(\"(optional — the agent may omit it; guard or fall back)\");\n const desc = parts.length > 0 ? ` // ${parts.join(' ')}` : \"\";\n propsFields.push(` ${key}${required ? \"\" : \"?\"}: ${fullType};${desc}`);\n }\n\n // ── Actions (useAction hooks — fire-and-forget to agent) ──\n // Contract shape: { actionSpec: { actionName: { label, description, schema?, example?, nextStep? } } }\n // ActionEntry.nextStep: optional hint naming the MCP tool the AGENT\n // should invoke on its next turn after this action fires. Actions have\n // exactly one routing target — the agent; there is NO synchronous\n // server-side dispatch. The name is informational here (use it for\n // button labels, icons, copy).\n const actionTypeAliases: string[] = [];\n const actionHookCalls: string[] = [];\n const actionReturnFields: string[] = [];\n const actionsMap: ActionSpec = contract?.actionSpec ?? {};\n for (const [key, entry] of Object.entries(actionsMap)) {\n const label = entry.label ?? key;\n const desc = entry.description ?? \"\";\n const tool = entry.nextStep ?? \"\";\n const typeName = `Action${key.charAt(0).toUpperCase()}${key.slice(1)}Payload`;\n\n // Derive TypeScript type: schema > example > void (fire-and-forget)\n let tsType = \"void\";\n if (entry.schema) {\n tsType = jsonSchemaTypeToTs(entry.schema);\n } else if (entry.example && typeof entry.example === \"object\" && !Array.isArray(entry.example)) {\n tsType = inferTypeFromExample(entry.example as JsonObject);\n }\n\n const toolNote = tool ? ` (label \"${label}\", nextStep hint → ${tool})` : \"\";\n actionTypeAliases.push(\n `/** Action payload: ${desc || label}${toolNote} */\\ntype ${typeName} = ${tsType};`\n );\n // Inline signature tells the LLM exactly how to call this action\n const callSig = tsType === \"void\" ? \"() => void — fire and forget\" : `(data: ${tsType}) => void`;\n const toolHint = tool ? ` → nextStep: ${tool}` : \"\";\n actionHookCalls.push(` const ${key} = useAction<${typeName}>('${key}'); // ${callSig}${toolHint}`);\n actionReturnFields.push(key);\n }\n\n // ── Stream channels (useStream hooks — real-time from agent) ──\n // Stream spec: flat map { channelName: { schema, description, example } }\n const streamChannels: StreamSpec = contract?.streamSpec ?? {};\n const streamChannelEntries = Object.entries(streamChannels);\n\n const streamTypeAliases: string[] = [];\n const streamHookCalls: string[] = [];\n const streamReturnFields: string[] = [];\n for (const [channelName, entry] of streamChannelEntries) {\n const desc = entry.description ?? \"\";\n const typeName = `Stream${channelName.charAt(0).toUpperCase()}${channelName.slice(1)}`;\n const tsType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n streamTypeAliases.push(`/** Stream channel: ${desc} */\\ntype ${typeName} = ${tsType};`);\n // Show .latest/.all types so the LLM knows how to access stream data\n streamHookCalls.push(\n ` const ${channelName} = useStream<${typeName}>('${channelName}'); // .latest: ${typeName} | null, .all: ${typeName}[]`\n );\n streamReturnFields.push(channelName);\n }\n\n // ── agentCapabilities.tools catalog (NO component-side hook emission) ──\n // `agentCapabilities.tools[*]` declares tools the AGENT invokes —\n // referenced from the contract via `actionSpec[*].nextStep` (advisory\n // hint forwarded on action events) and `streamSpec[*].source.tool`\n // (channel data source). The component never calls these tools\n // directly; there is no `useWiredTool(name)` hook. The boilerplate\n // therefore emits no per-tool hook line, no request/response type\n // aliases, and no useWiredTool import.\n\n // ── Client capabilities (browser-capability gadget hooks declared in contract) ──\n // Contract shape: { gadgets: { '<package>': { '<exportName>': { description?, usage? } } } }\n // package-keyed two-level map. `listContractGadgets` flattens it to\n // `GadgetUse[]` — one record per used export with `package`, `name`,\n // and optional `description` / `usage` overrides. The export NAME\n // grammar discriminates kind (`use`-prefixed → hook, PascalCase →\n // component).\n // No type aliases — gadget hooks own their typed return shape.\n // No wire-import side effect — gadgets are imported from `package`\n // (default `@ggui-ai/gadgets`), not from `@ggui-ai/wire`.\n //\n // Group-by-package — emit ONE combined `import { hookA, hookB } from '<pkg>'`\n // per declared package, NOT one import per hook. Hooks ordered\n // alphabetically within each package for stable diffs across same-\n // contract regens.\n const gadgetUses = contract ? listContractGadgets(contract) : [];\n\n // Gadgets are DIRECT-imported from their package, grouped\n // per package below. Build a hook-name → registry export lookup so\n // each contract-declared gadget binding can be enriched with the\n // catalog's description / usage / example fields. Mirrors how wire\n // boilerplate emits typed action signatures + nextStep hints —\n // gadgets get the same priming so the LLM has a working call site to\n // start from rather than an empty `useFoo()` it might delete.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports, keyed by hook name.\n const gadgetCatalog = new Map<\n string,\n {\n readonly description?: string;\n readonly usage?: string;\n readonly example?: JsonValue;\n }\n >();\n for (const descriptor of appGadgets ?? []) {\n for (const exp of descriptor.exports) {\n // `GadgetExport` is a type-exclusive union (`hook?: never` on the\n // component member); discriminate by VALUE presence — `\"hook\" in\n // exp` no longer narrows now that `hook` is an optional key of\n // both members.\n if (exp.hook === undefined) continue;\n gadgetCatalog.set(exp.hook, {\n description: exp.description,\n usage: exp.usage,\n example: exp.example,\n });\n }\n }\n // Gadget imports grouped by package: `package → set of export names`\n // (hook AND component exports). One combined\n // `import { … } from '<pkg>'` is emitted per package.\n const gadgetImportsByPackage = new Map<string, Set<string>>();\n const gadgetHookCalls: string[] = [];\n for (const use of gadgetUses) {\n const exportName = use.name;\n // Both hooks and components are DIRECT-imported from their\n // package — add every contract-declared export to the per-package\n // import group.\n const pkgExports = gadgetImportsByPackage.get(use.package);\n if (pkgExports !== undefined) pkgExports.add(exportName);\n else gadgetImportsByPackage.set(use.package, new Set([exportName]));\n\n // Kind discrimination is by the export-name grammar.\n // A component name (PascalCase) is import-only — the LLM renders\n // `<X … />` in the JSX tree itself, so there is no pre-emitted call\n // site. Hook names (`use`-prefixed) additionally get a pre-emitted\n // call line below so the LLM has a working invocation.\n if (!HOOK_NAME_RE.test(exportName)) continue;\n const hook = exportName;\n // Contract entry's local override wins; registry catalog is the\n // fallback (most plugin descriptors live on the registry side).\n // The wire `GadgetUse` carries only `description` / `usage`\n // overrides — `example` lives solely on the registered export.\n const contractDesc = use.description;\n const contractUsage = use.usage;\n const catalog = gadgetCatalog.get(hook) ?? {};\n const desc = contractDesc ?? catalog.description ?? hook;\n const usage = contractUsage ?? catalog.usage;\n const example = catalog.example;\n\n // Pre-emit the hook call so the LLM sees a working invocation\n // (and doesn't delete it as \"unused\"). Mirrors wire's typed-\n // signature pattern. Two example shapes in the wild:\n // (a) plain literal — `{ center: [0,0], zoom: 12 }` — the\n // descriptor IS the call args; inline as the call arg.\n // (b) shaped object — `{ call: '<full TS expression>',\n // returns: <typed return shape> }` — the canonical\n // sample/leaflet descriptor shape; emit the `call` as a\n // separate EXAMPLE comment so the LLM sees the literal TS\n // it should produce.\n let callArgs = '';\n let exampleComment = '';\n if (example !== undefined && example !== null) {\n const callLine =\n typeof example === 'object' &&\n !Array.isArray(example) &&\n typeof example.call === 'string'\n ? example.call\n : undefined;\n if (callLine !== undefined) {\n exampleComment = `\\n // EXAMPLE: ${callLine.trim()}`;\n } else {\n callArgs = JSON.stringify(example);\n }\n }\n const usageNote = usage ? ` USE: ${usage}` : '';\n // Local binding name: strip the `use` prefix + lowercase the first\n // char so `useGeolocation` → `geolocation`. The wire no longer\n // carries an explicit binding name (the export name IS the inner\n // key), so the boilerplate derives a stable, readable one.\n const bindingName =\n hook.length > 3\n ? hook.charAt(3).toLowerCase() + hook.slice(4)\n : hook;\n gadgetHookCalls.push(\n ` const ${bindingName} = ${hook}(${callArgs}); // ${desc}${usageNote}${exampleComment}`,\n );\n }\n // Gadgets are DIRECT-imported, one combined\n // `import { hookA, hookB } from '<pkg>'` per registered package\n // (packages + hooks sorted for stable diffs across same-contract\n // regens). The `DO NOT EDIT` banner + tier-0 `gadget_preservation`\n // keep the LLM from deleting an import it (correctly) intuits is\n // runtime-resolved — the banner alone makes direct imports survive\n // multi-turn generation. Tier-0 verifies each registered hook is\n // still imported from its package.\n const gadgetImportLine =\n gadgetImportsByPackage.size > 0\n ? \"// DO NOT EDIT — gadget imports. Each export is resolved by the iframe \" +\n \"runtime; keep every import line and export name. self_check fails with \" +\n \"gadget_preservation:<export> if a gadget import is removed.\\n\" +\n Array.from(gadgetImportsByPackage.entries())\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([pkg, hooks]) =>\n `import { ${Array.from(hooks).sort().join(\", \")} } from '${pkg}';`,\n )\n .join(\"\\n\")\n : \"\";\n // ── Props interface (data only — no action callbacks) ──\n const propsInterface =\n propsFields.length > 0\n ? `// DO NOT EDIT — generated from data contract. Changing this will fail validation.\\ninterface Props {\\n${propsFields.join(\"\\n\")}\\n}`\n : `// DO NOT EDIT — generated from data contract.\\ninterface Props {\\n [key: string]: string | number | boolean | null | object;\\n}`;\n\n // ── Context slots — `useGguiContext` hook ──\n // For each declared `contextSpec` slot, emit ONE destructure line\n // at the top of the user component:\n // const [<slotKey>, set<PascalSlotKey>] =\n // useGguiContext<TS>('<slotKey>');\n // The runtime owns useState per slot and wraps the user component\n // in nested SingleSlotProvider components — the user only reads\n // the live tuple via the hook. There must be NO `useState` and NO\n // `<Provider>` wrap anywhere in the LLM-authored JSX.\n const contextSpec: ContextSpec = contract?.contextSpec ?? {};\n const contextSpecEntries = Object.entries(contextSpec);\n let contextHooks = \"\";\n if (contextSpecEntries.length > 0) {\n const hookLines: string[] = [];\n for (const [slotKey, entry] of contextSpecEntries) {\n const valueType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n const setterName = `set${slotKey.charAt(0).toUpperCase()}${slotKey.slice(1)}`;\n hookLines.push(\n ` const [${slotKey}, ${setterName}] = useGguiContext<${valueType}>('${slotKey}');`,\n );\n }\n contextHooks =\n ` // DO NOT EDIT — auto-generated per contextSpec slot.\\n` +\n ` // Read \\`<slotKey>\\` to render, write via \\`set<SlotKey>\\` to\\n` +\n ` // surface the change to the agent's LLM context (debounced).\\n` +\n ` // The runtime owns the underlying useState + Provider; you\\n` +\n ` // write plain JSX, no wrap.\\n` +\n `${hookLines.join(\"\\n\")}\\n`;\n }\n\n // ── Determine which wire hooks are needed ──\n const hasActions = actionHookCalls.length > 0;\n const hasStream = streamHookCalls.length > 0;\n // Gates the gadget hook-CALL body section. A component gadget\n // contributes an import but no call site, so this is false for a\n // component-only contract — the import line is gated separately on\n // `gadgetImportLine` below.\n const hasGadgetHookCalls = gadgetHookCalls.length > 0;\n const hasContext = contextSpecEntries.length > 0;\n // `hasAnyHook` gates the \"DO NOT EDIT wire hooks\" header + body.\n // Client gadget HOOKS contribute call sites alongside the\n // @ggui-ai/wire hooks — their declaration needs the same emitted\n // header so the LLM sees the binding lines pre-declared and doesn't\n // strip / duplicate them. (Component gadgets add no body line.)\n const hasAnyHook =\n hasActions || hasStream || hasContext || hasGadgetHookCalls;\n const hasAnyWireFromWire = hasActions || hasStream || hasContext;\n\n const wireHooks: string[] = [];\n if (hasActions) wireHooks.push(\"useAction\");\n if (hasStream) wireHooks.push(\"useStream\");\n if (hasContext) wireHooks.push(\"useGguiContext\");\n const wireImport = hasAnyWireFromWire\n ? `import { ${wireHooks.join(\", \")} } from '@ggui-ai/wire';\\n`\n : \"\";\n // The gadget import line is emitted whenever ANY gadget export is\n // declared — hook OR component. (`gadgetImportLine` is non-empty iff\n // `gadgetImportsByPackage` has an entry; component-only contracts\n // have an import but no `hasGadgetHookCalls`.)\n const gadgetImport =\n gadgetImportLine.length > 0 ? `${gadgetImportLine}\\n` : \"\";\n\n // ── React import — only include hooks that are actually needed ──\n const reactHooks = [\"useState\", \"useCallback\", \"useMemo\", \"useEffect\", \"useRef\"];\n const reactImport = `import React, { ${reactHooks.join(\", \")} } from 'react';`;\n\n // ── Hook body ──────────────────────────────────────────\n // Wire hooks are placed inside render(), before the return statement.\n const hookParts: string[] = [];\n if (hasActions) {\n hookParts.push(\" // ── Actions (contract-typed, fire-and-forget to agent) ──\");\n hookParts.push(\" // Call these to send user interactions to the agent. Types are enforced by the compiler.\");\n hookParts.push(...actionHookCalls);\n }\n if (hasStream) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Streams (contract-typed, real-time from agent) ──\");\n hookParts.push(\" // .latest is the most recent event (or null). .all is the full history array.\");\n hookParts.push(...streamHookCalls);\n }\n if (hasGadgetHookCalls) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Gadgets (browser-capability hooks; UI-owned lifecycle) ──\");\n hookParts.push(\" // Read .value / .status; call .start() to invoke. Surface .value through\");\n hookParts.push(\" // an actionSpec payload or contextSpec slot if the agent needs to observe it.\");\n hookParts.push(...gadgetHookCalls);\n }\n\n // Only emit the \"DO NOT EDIT wire hooks\" header when there ARE wire-side\n // OR gadget-side hook bindings to surface. An orphaned header on\n // no-wire fixtures (e.g. weather-card) makes the LLM hallucinate\n // hooks for an empty section and burn turns on missing imports.\n const hookBody = hasAnyHook\n ? ` // DO NOT EDIT wire hooks — auto-generated from the data contract\\n${hookParts.join(\"\\n\")}\\n`\n : \"\";\n\n // ── Type alias blocks ───────────────────────────────────\n // Auto-generated type aliases serve as documentation for the LLM. Some are\n // referenced by the wire-hook calls below (e.g. `useAction<ActionXPayload>`)\n // but request types are typically only mentioned in trailing comments —\n // ESLint flags them as unused. Without `eslint-disable` here, the LLM\n // enters a fix-rename oscillation loop (prefix `_`, break prop access,\n // revert, retry…) that drives up to 27% of cap-hit selfCheckFails on\n // wire-bearing fixtures. Suppress no-unused-vars for the generated\n // type-alias block; \"DO NOT EDIT\" comments + tier-0 wire-preservation\n // already prevent the LLM from removing them.\n const wrapTypes = (label: string, body: string): string =>\n `\\n/* eslint-disable no-unused-vars */\\n// DO NOT EDIT — ${label}\\n${body}\\n/* eslint-enable no-unused-vars */\\n`;\n\n const actionTypesBlock =\n actionTypeAliases.length > 0\n ? wrapTypes(\"action payload types generated from action contract.\", actionTypeAliases.join(\"\\n\\n\"))\n : \"\";\n const streamTypesBlock =\n streamTypeAliases.length > 0\n ? wrapTypes(\"stream event types generated from stream contract.\", streamTypeAliases.join(\"\\n\\n\"))\n : \"\";\n // `clientCapabilities.gadgets` ship NO type-alias block — gadget\n // hooks own their typed return shape internally; the contract surface\n // is pure declaration.\n\n return renderBoilerplate(shellType ?? \"fullscreen\", screen ?? \"universal\", {\n REACT_IMPORT: reactImport,\n ALL_DESIGN,\n WIRE_IMPORT: wireImport + gadgetImport,\n PROPS_INTERFACE: propsInterface,\n ACTION_TYPES: actionTypesBlock,\n STREAM_TYPES: streamTypesBlock,\n CONTEXT_HOOKS: contextHooks,\n WIRE_HOOKS: hookBody,\n AXIS_SECTIONS: composedSections ?? \"\",\n });\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/internal/extract-call-signatures.ts\n//\n// Internal gadget-signature extractor.\n//\n// Uses the TypeScript Compiler API to parse an in-memory wrapper `.d.ts`\n// STRING and, for each requested export, print a prompt-ready type:\n//\n// - `extractCallSignaturesFromDts` — for HOOK exports, prints the\n// callable signature as a self-contained TS function-type\n// expression (`(options?: { center: [number, number]; zoom: number })\n// => GadgetHookResult<...>`).\n// - `extractComponentPropsFromDts` (GG.8.5) — for COMPONENT exports,\n// prints the props-object shape (the first parameter's type,\n// structurally expanded) so the prompt can teach the LLM the JSX\n// props of `<Chart data={…} height={…} />`.\n//\n// Both take the wrapper's already-built `.d.ts` content AS A STRING —\n// the render handler fetches each non-stdlib gadget's `.d.ts` over HTTPS\n// and threads a `package -> dtsContent` map into the generator\n// (`UiGenerateInput.gadgetTypes`). The code-gen prompt builder calls\n// these helpers to render a `Type:` / `Props:` line per third-party\n// gadget so the LLM sees the real shape it otherwise can't know.\n//\n// Internal only — NOT re-exported from any public package entry. Lives\n// under `src/internal/` deliberately.\n\nimport ts from 'typescript';\n\n/**\n * Map of `hookName → call-signature string` produced by\n * {@link extractCallSignaturesFromDts}. Each value is a printed\n * function-type expression suitable for verbatim interpolation into a\n * prompt `Type:` line.\n *\n * Hooks whose signature could not be resolved are omitted — the caller\n * renders a `Type:` line only for hooks that appear here.\n */\nexport type CallSignatureMap = Record<string, string>;\n\n/**\n * Map of `componentName → props-object type string` produced by\n * {@link extractComponentPropsFromDts}. Each value is a printed object\n * type (`{ data: …; height?: number }`) suitable for a prompt `Props:`\n * line. Components whose props could not be resolved are omitted.\n */\nexport type ComponentPropsMap = Record<string, string>;\n\n// In-memory `.d.ts` is parsed under a synthetic file name. The leading\n// `/` matches the convention `getCurrentDirectory()` (also `/`) so the\n// compiler host's path probes line up.\nconst VIRTUAL_DTS_PATH = '/__gadget__.d.ts';\n\nconst EXTRACTOR_COMPILER_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n allowJs: false,\n jsx: ts.JsxEmit.ReactJSX,\n noEmit: true,\n esModuleInterop: true,\n // skipLibCheck so an unresolvable wrapper-internal import (the\n // sandbox doesn't carry the wrapper's transitive deps) doesn't abort\n // the program before we can read the symbol's callable signature.\n skipLibCheck: true,\n strict: true,\n};\n\n/**\n * Process-lifetime memos. Building a `ts.Program` — including\n * default-lib reads — on every call is expensive, and each extractor is\n * invoked once per coding-agent turn while the `.d.ts` content + name\n * set stay constant across a generation. Keying on `(dtsContent, names)`\n * collapses the repeated work. The key set is tiny in practice (a\n * handful of gadgets per process).\n */\nconst callSignatureCache = new Map<string, CallSignatureMap>();\nconst componentPropsCache = new Map<string, ComponentPropsMap>();\n\n/**\n * One-shot extractor program for a wrapper `.d.ts`, with the resolved\n * call signatures of every requested export. Shared by both public\n * extractors — they differ only in how they format the result.\n */\ninterface ExtractorContext {\n readonly checker: ts.TypeChecker;\n /** Render a `ts.Type` as a self-contained, prompt-ready expression. */\n readonly renderType: (t: ts.Type, depth: number) => string;\n /**\n * Requested export name → its resolved call signatures, in\n * declaration order. Only exports that are callable (a hook or a\n * function component) appear; non-callable exports are omitted.\n */\n readonly signaturesByName: ReadonlyMap<string, readonly ts.Signature[]>;\n}\n\n/**\n * Build a single-file TS Program over `dtsContent`, resolve the call\n * signatures of every requested export name, and expose the checker +\n * a structural type renderer. Returns `undefined` when the `.d.ts`\n * cannot be parsed.\n */\nfunction buildExtractorContext(\n dtsContent: string,\n names: readonly string[],\n): ExtractorContext | undefined {\n // Build a fresh `.d.ts` source file. `setParentNodes: true` is\n // required so the checker can walk the AST.\n const sourceFile = ts.createSourceFile(\n VIRTUAL_DTS_PATH,\n dtsContent,\n ts.ScriptTarget.ESNext,\n /* setParentNodes */ true,\n ts.ScriptKind.TS,\n );\n\n // Minimal in-memory compiler host. Only the synthetic `.d.ts` plus\n // the TS default lib files are resolvable; everything else is absent\n // (skipLibCheck keeps that from aborting the program). The checker\n // still resolves intra-file named types, which is all structural\n // fallback needs to inline a self-contained signature.\n const defaultLibName = ts.getDefaultLibFileName(EXTRACTOR_COMPILER_OPTIONS);\n const host: ts.CompilerHost = {\n getSourceFile(fileName) {\n if (fileName === VIRTUAL_DTS_PATH) return sourceFile;\n // Default lib(s) — load from the real `typescript` install so the\n // checker has `lib.d.ts` ambient types. The dts may not need\n // them, but the program won't run without a default lib.\n const libContent = ts.sys.readFile(\n ts.getDefaultLibFilePath(EXTRACTOR_COMPILER_OPTIONS).replace(\n /[^/\\\\]+$/,\n fileName,\n ),\n );\n if (libContent !== undefined) {\n return ts.createSourceFile(\n fileName,\n libContent,\n ts.ScriptTarget.ESNext,\n true,\n ts.ScriptKind.TS,\n );\n }\n return undefined;\n },\n getDefaultLibFileName() {\n return defaultLibName;\n },\n writeFile() {\n // no-op — noEmit\n },\n getCurrentDirectory() {\n return '/';\n },\n getCanonicalFileName(f) {\n return f;\n },\n useCaseSensitiveFileNames() {\n return true;\n },\n getNewLine() {\n return '\\n';\n },\n fileExists(f) {\n if (f === VIRTUAL_DTS_PATH) return true;\n return ts.sys.fileExists(f);\n },\n readFile(f) {\n if (f === VIRTUAL_DTS_PATH) return dtsContent;\n return ts.sys.readFile(f);\n },\n };\n\n const program = ts.createProgram(\n [VIRTUAL_DTS_PATH],\n EXTRACTOR_COMPILER_OPTIONS,\n host,\n );\n const checker = program.getTypeChecker();\n const parsed = program.getSourceFile(VIRTUAL_DTS_PATH);\n if (parsed === undefined) {\n return undefined;\n }\n\n const requested = new Set(names);\n\n // True when a symbol's declaration originates from the wrapper's own\n // `.d.ts`. Only THESE named types get structurally expanded — types\n // from the TS DOM lib (`HTMLDivElement`), `@ggui-ai/gadgets`\n // (`GadgetHookResult`), or any external package keep their name,\n // because (a) the LLM already knows DOM / ggui types and (b)\n // expanding `HTMLDivElement` would dump hundreds of DOM members into\n // the prompt.\n function isWrapperLocal(symbol: ts.Symbol | undefined): boolean {\n const decls = symbol?.getDeclarations();\n if (decls === undefined) return false;\n return decls.some((d) => d.getSourceFile().fileName === VIRTUAL_DTS_PATH);\n }\n\n // Render a single `ts.Type` as a self-contained TS type expression.\n //\n // The TS node builder keeps a type's NAME whenever that name is\n // reachable in the program — for a `.d.ts` whose option/value types\n // are `export interface`s, that means the printed signature ends up\n // full of `LeafletMapOptions` references the LLM cannot resolve. To\n // produce a prompt-ready, self-contained signature we structurally\n // expand WRAPPER-LOCAL named object types one level: enumerate the\n // apparent properties and render each property's type (recursively,\n // depth-bounded). Non-local named types, primitives, unions, arrays,\n // tuples, and anonymous objects keep `typeToString`'s rendering.\n const MAX_DEPTH = 4;\n function renderType(t: ts.Type, depth: number): string {\n const plain = (): string =>\n checker.typeToString(t, undefined, ts.TypeFormatFlags.NoTruncation);\n\n // Bail to the plain stringifier once we hit the depth cap so a\n // cyclic / deeply-nested type can't blow the stack.\n if (depth >= MAX_DEPTH) return plain();\n\n // `boolean` is internally `true | false` — `isUnion()` is true for\n // it. Catch it before union-splitting so it prints as `boolean`.\n if ((t.getFlags() & ts.TypeFlags.Boolean) !== 0) return 'boolean';\n\n // Union types (e.g. `LeafletMapOptions | undefined` from an\n // optional param) — recurse into each constituent so a wrapper-\n // local named object member still expands structurally.\n if (t.isUnion()) {\n return t.types.map((member) => renderType(member, depth)).join(' | ');\n }\n // Intersections — same treatment.\n if (t.isIntersection()) {\n return t.types.map((member) => renderType(member, depth)).join(' & ');\n }\n\n const symbol = t.getSymbol() ?? t.aliasSymbol;\n\n // Callable types (e.g. `containerRef: (el) => void`) — render the\n // first call signature inline.\n const callSigs = t.getCallSignatures();\n if (callSigs.length > 0) {\n const cs = callSigs[0]!;\n const params = cs\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined ||\n decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join(', ');\n const ret = renderType(cs.getReturnType(), depth + 1);\n return `(${params}) => ${ret}`;\n }\n\n const isObject = (t.getFlags() & ts.TypeFlags.Object) !== 0;\n const isArrayOrTuple =\n checker.isArrayType(t) || checker.isTupleType(t);\n\n // Generic instantiation of a non-local type (e.g.\n // `GadgetHookResult<LeafletMapValue>`) — keep the outer name (the\n // LLM knows the ggui types) but recurse into the type arguments so\n // a nested wrapper-local type still expands.\n const typeArgs = (t as ts.TypeReference).typeArguments;\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n !isWrapperLocal(symbol) &&\n typeArgs !== undefined &&\n typeArgs.length > 0\n ) {\n const args = typeArgs.map((a) => renderType(a, depth + 1)).join(', ');\n return `${symbol.getName()}<${args}>`;\n }\n\n // Wrapper-local named object — expand its property shape inline.\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n isWrapperLocal(symbol)\n ) {\n const props = checker.getPropertiesOfType(t);\n if (props.length > 0) {\n const body = props\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional = (p.getFlags() & ts.SymbolFlags.Optional) !== 0;\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join('; ');\n return `{ ${body} }`;\n }\n }\n\n return plain();\n }\n\n // The exported binding may surface as either:\n // - `export declare const useLeafletMap: GguiGadget<...>` — a\n // variable statement, or\n // - `export declare function useLeafletMap(...): ...` — a function\n // declaration, or\n // - `export { useLeafletMap } from '...'` — a re-export.\n // The module-symbol export table covers all three uniformly, so we\n // walk the module symbol's exports rather than top-level statements.\n const moduleSymbol = checker.getSymbolAtLocation(parsed);\n const exportSymbols: ts.Symbol[] =\n moduleSymbol !== undefined ? checker.getExportsOfModule(moduleSymbol) : [];\n\n const signaturesByName = new Map<string, readonly ts.Signature[]>();\n for (const symbol of exportSymbols) {\n const name = symbol.getName();\n if (!requested.has(name)) continue;\n if (signaturesByName.has(name)) continue;\n\n // Resolve aliases (re-exports) so we read the real declaration.\n const resolved =\n (symbol.flags & ts.SymbolFlags.Alias) !== 0\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n\n const declarations = resolved.getDeclarations();\n if (declarations === undefined || declarations.length === 0) continue;\n const declaration = declarations[0]!;\n\n const type = checker.getTypeOfSymbolAtLocation(resolved, declaration);\n const callSignatures = type.getCallSignatures();\n if (callSignatures.length === 0) continue;\n\n signaturesByName.set(name, callSignatures);\n }\n\n return { checker, renderType, signaturesByName };\n}\n\n/**\n * Print one call signature as a self-contained `(params) => ret`\n * expression.\n */\nfunction printCallSignature(sig: ts.Signature, ctx: ExtractorContext): string {\n const params = sig\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(p, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined || decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${ctx.renderType(pType, 0)}`;\n })\n .join(', ');\n const ret = ctx.renderType(sig.getReturnType(), 0);\n return `(${params}) => ${ret}`.trim();\n}\n\n/**\n * Render a function component's props — the first parameter's type,\n * structurally expanded into a self-contained object type. A\n * zero-parameter component yields `{}`. Returns `undefined` when the\n * expander bottoms out on an unresolvable token.\n */\nfunction printComponentProps(\n sig: ts.Signature,\n ctx: ExtractorContext,\n): string | undefined {\n const params = sig.getParameters();\n // A zero-parameter component takes no props.\n if (params.length === 0) return '{}';\n const propsParam = params[0]!;\n const decl = propsParam.valueDeclaration ?? propsParam.declarations?.[0];\n const propsType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(propsParam, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(propsParam);\n const rendered = ctx.renderType(propsType, 0);\n // A surviving virtual-file qualifier means the structural expander\n // bottomed out on something it couldn't inline — drop it rather than\n // feed the LLM an unresolvable `import(\"/__gadget__\")` token.\n if (rendered.length === 0 || rendered.includes('import(\"')) return undefined;\n return rendered;\n}\n\n/**\n * Print the inferred call signature of every requested HOOK found in\n * the supplied wrapper `.d.ts` string.\n *\n * For each exported declaration whose name matches a requested hook,\n * the checker's callable signature is printed with structural-fallback\n * so wrapper-specific named types expand to their structural form — the\n * resulting string is self-contained and safe to drop into a prompt. A\n * hook declared with multiple overloads renders each, joined with ` | `.\n *\n * Hooks that aren't found, or that resolve to a value with no callable\n * signature, are omitted from the result (no throw) — the caller is\n * expected to render a `Type:` line only for hooks that resolved.\n *\n * Memoized on `(dtsContent, hookNames)`.\n */\nexport function extractCallSignaturesFromDts(\n dtsContent: string,\n hookNames: readonly string[],\n): CallSignatureMap {\n if (hookNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...hookNames].sort().join(',')}`;\n const cached = callSignatureCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: CallSignatureMap = {};\n const ctx = buildExtractorContext(dtsContent, hookNames);\n if (ctx === undefined) {\n callSignatureCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A hook declared with multiple overloads renders ALL of them,\n // joined as a union of function types. A surviving virtual-file\n // qualifier means the structural expander bottomed out on something\n // it couldn't inline — drop that overload rather than feed the LLM\n // an unresolvable `import(\"/__gadget__\")` token.\n const printed = signatures\n .map((sig) => printCallSignature(sig, ctx))\n .filter((s) => s.length > 0 && !s.includes('import(\"'))\n .join(' | ');\n if (printed.length > 0) {\n result[name] = printed;\n }\n }\n\n callSignatureCache.set(cacheKey, result);\n return result;\n}\n\n/**\n * Print the props-object shape of every requested COMPONENT found in\n * the supplied wrapper `.d.ts` string (GG.8.5).\n *\n * A function component's props are its first parameter's type. The\n * type is structurally expanded the same way hook signatures are, so\n * the printed value (`{ data: …; height?: number }`) is self-contained\n * and prompt-ready — the code-gen prompt renders it as a `Props:` line\n * so the LLM knows the JSX attributes of `<Component … />`.\n *\n * Components not found, or that resolve to a non-callable value, are\n * omitted (no throw). Memoized on `(dtsContent, componentNames)`.\n */\nexport function extractComponentPropsFromDts(\n dtsContent: string,\n componentNames: readonly string[],\n): ComponentPropsMap {\n if (componentNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...componentNames].sort().join(',')}`;\n const cached = componentPropsCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: ComponentPropsMap = {};\n const ctx = buildExtractorContext(dtsContent, componentNames);\n if (ctx === undefined) {\n componentPropsCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A component is single-signature by convention — use the first.\n const first = signatures[0];\n if (first === undefined) continue;\n const props = printComponentProps(first, ctx);\n if (props !== undefined) {\n result[name] = props;\n }\n }\n\n componentPropsCache.set(cacheKey, result);\n return result;\n}\n","// packages/ui-gen/src/boilerplate/system-prompt.ts\n//\n// System-prompt skeleton for the coding agent. Deterministic assembly;\n// injection points for funnel content (pitfalls) and for large content\n// blocks that are OWNED BY OTHER PACKAGES (design-system docs,\n// primitives doc, wire doc). Those blocks travel as strings so ui-gen\n// doesn't silently pull in megabytes of auto-generated content from\n// `@ggui-ai/design` / `@ggui-ai/wire` that those packages authoritatively\n// own.\n//\n// The only content this skeleton carries by default is the coding-\n// criteria summary (`buildCodingCriteriaSummary()` over the open\n// `CRITERIA` single-source-of-truth). Everything else defaults to empty\n// string — the skeleton still renders cleanly for OSS callers who don't\n// pass doc blocks.\n\nimport { resolveAppGadgets } from \"@ggui-ai/protocol\";\nimport type {\n GadgetDescriptor,\n GadgetExport,\n GadgetHookExport,\n GadgetComponentExport,\n} from \"@ggui-ai/protocol\";\nimport { buildCodingCriteriaSummary } from \"../evaluation/types-public.js\";\nimport {\n extractCallSignaturesFromDts,\n extractComponentPropsFromDts,\n} from \"../internal/extract-call-signatures.js\";\n\n/** Narrow a {@link GadgetExport} to its hook variant by field presence. */\nfunction isHookExport(exp: GadgetExport): exp is GadgetHookExport {\n return \"hook\" in exp;\n}\n\n/** Narrow a {@link GadgetExport} to its component variant by field presence. */\nfunction isComponentExport(exp: GadgetExport): exp is GadgetComponentExport {\n return \"component\" in exp;\n}\n\nexport interface SystemPromptInputs {\n /** The user's original request. */\n userRequest: string;\n /** Shell layout mode. */\n shellType?: string;\n /** Target screen size. */\n screen?: string;\n /** Axis-conditioned prompt fragments (from `compose()`). */\n axisDelta?: string;\n /**\n * Funnel content injection — env-gated pitfalls block rendered by the\n * caller. OSS default: `\"\"`. The hosted runtime's core wrapper passes\n * `renderPitfallsBlock()` which honors `GGUI_PITFALLS` /\n * `GGUI_NEW_PITFALLS` env vars.\n */\n pitfallsBlock?: string;\n /**\n * Pre-rendered criteria block. Defaults to\n * `buildCodingCriteriaSummary()` over the open CRITERIA registry.\n * Callers that want to override (e.g. a trimmed summary for fast mode)\n * pass their own string.\n */\n criteriaBlock?: string;\n /** Hand-written design-token reference. Owned by `@ggui-ai/design`. */\n designSystemDocs?: string;\n /** Auto-generated primitives reference. Owned by `@ggui-ai/design`. */\n primitivesDoc?: string;\n /** Auto-generated wire-hooks reference. Owned by `@ggui-ai/wire`. */\n wireDoc?: string;\n /**\n * Per-app gadget catalog. When provided, replaces the default\n * `STDLIB_GADGETS`-only table in the\n * `clientCapabilities — registered catalog` section so registered\n * third-party gadgets (Leaflet, Mapbox, Stripe, …) instruct the\n * code-gen LLM with the same teaching text the synth + decision LLMs\n * see.\n *\n * When omitted, the section renders the standard-library seed (the\n * first-party browser-capability hooks).\n */\n appGadgets?: readonly GadgetDescriptor[];\n /**\n * A `package -> .d.ts content` map for THIRD-PARTY gadget wrappers\n * (the render handler parallel-fetches each non-stdlib gadget's\n * `.d.ts`). When a gadget's `package` has an entry here,\n * `formatGadgetsSection` renders a `**Type**:` line carrying the\n * hook's extracted call signature — the LLM sees the real call shape\n * of a wrapper it cannot otherwise know.\n *\n * Stdlib gadgets (`@ggui-ai/gadgets`) get NO `Type:` line — they\n * already carry an `example` and are well-known; extracting stdlib\n * signatures is deliberately out of scope. Omit for STDLIB-only\n * callers (the section stays byte-identical).\n */\n gadgetTypes?: Readonly<Record<string, string>>;\n}\n\nconst SHELL_DESCRIPTIONS: Record<string, string> = {\n chat: \"inline component inside ChatShell message bubble (~400px wide, compact)\",\n fullscreen: \"full viewport, responsive layout\",\n spatial: \"floating AR/VR panel (~600px, touch-friendly)\",\n};\n\nconst SCREEN_DESCRIPTIONS: Record<string, string> = {\n mobile: \"single column, large touch targets\",\n tablet: \"flexible columns, medium spacing\",\n desktop: \"multi-column, dense layout\",\n universal: \"responsive across all breakpoints\",\n};\n\n/**\n * Render the `clientCapabilities — registered catalog` table from the\n * per-app gadget catalog. Each registered gadget renders one row\n * with hook + permission + the `description`-or-`usage` field as the\n * \"what it does\" column. Permission falls back to `(none)` when the\n * descriptor doesn't declare one.\n *\n * The table is built dynamically from the catalog so all three triad\n * surfaces (synth contract authoring, decision LLM, code-gen system\n * prompt) instruct the model uniformly about which gadgets are\n * available.\n *\n * Rows are emitted in catalog order. An empty catalog produces a hint\n * to seed it via `app.gadgets` rather than an empty table.\n *\n * When `gadgetTypes` carries a `.d.ts` for a gadget's `package`, a\n * `**Type**:` block is appended after the table with one line per\n * THIRD-PARTY gadget: `\\`<hook>\\`: <extracted call signature>`. The\n * signature is extracted from the wrapper's `.d.ts` via\n * `extractCallSignaturesFromDts`. Stdlib gadgets (`@ggui-ai/gadgets`)\n * get NO `Type:` line — they already carry an `example` and are\n * well-known. A hook whose signature can't be extracted is silently\n * skipped.\n *\n * Pure helper. Exported for unit testing.\n */\nexport function formatGadgetsSection(\n appGadgets: readonly GadgetDescriptor[],\n gadgetTypes?: Readonly<Record<string, string>>,\n): string {\n if (appGadgets.length === 0) {\n return [\n \"When the contract declares a `clientCapabilities.gadgets` entry,\",\n \"the hook MUST be one the operator has registered on\",\n \"`App.gadgets`. The default ggui server seeds the 7\",\n \"first-party STDLIB hooks; this server has none registered (the\",\n \"operator's `ggui.json#app.gadgets` is empty). Don't\",\n \"declare `clientCapabilities.gadgets` until a hook is registered.\",\n ].join(\" \");\n }\n // The LLM DIRECT-IMPORTS gadget hooks. The boilerplate emits\n // one combined `import { hookA, hookB } from '<package>'` line per\n // registered gadget package, above a `DO NOT EDIT` banner. The\n // `Package` column below IS the import specifier — it is load-bearing.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports (one table row per hook), carrying\n // package identity through for the Package column.\n const hookExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isHookExport)\n .map((exp) => ({ exp, descriptor })),\n );\n // Component exports get their own table + render teaching.\n const componentExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isComponentExport)\n .map((exp) => ({ exp, descriptor })),\n );\n const header =\n \"When the contract declares a hook gadget on `clientCapabilities.gadgets`, the hook MUST be one of the registered hooks below. The boilerplate has already emitted a direct import per gadget package — `import { <hook>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each STDLIB hook from `@ggui-ai/gadgets`; import each third-party hook from the package named in the `Package` column. DO NOT invent your own import paths. Available registered hooks:\";\n const tableHead = [\n \"| Hook | Package (import from here) | Permission | What it does |\",\n \"| --------------------- | ---------------------------------- | ------------------ | ------------------------------------------- |\",\n ];\n const rows = hookExports.map(({ exp, descriptor }) => {\n const hookCol = `\\`${exp.hook}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const permCol = exp.permission\n ? `\\`${exp.permission}\\``.padEnd(18, \" \")\n : \"(none)\".padEnd(18, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${hookCol} | ${pkgCol} | ${permCol} | ${what.padEnd(43, \" \")} |`;\n });\n\n // `**Type**:` lines for THIRD-PARTY gadgets. A gadget is third-party\n // when its `package` has a `.d.ts` entry in `gadgetTypes` (stdlib\n // `@ggui-ai/gadgets` is never in the map). The LLM can't know a\n // third-party wrapper's call shape; the extracted signature gives it\n // the exact param/return type to code against.\n // Stdlib gadgets get nothing here by design — `example` covers them.\n const typeLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of hookExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const signatures = extractCallSignaturesFromDts(dts, [exp.hook]);\n const sig = signatures[exp.hook];\n if (sig === undefined) continue; // graceful — couldn't extract.\n typeLines.push(`- \\`${exp.hook}\\`: \\`${sig}\\``);\n }\n }\n const typeBlock =\n typeLines.length > 0\n ? [\n \"\",\n \"**Type** (third-party gadgets — call signature from the wrapper's published `.d.ts`):\",\n \"\",\n ...typeLines,\n ]\n : [];\n\n const hookSection =\n hookExports.length > 0\n ? [header, \"\", ...tableHead, ...rows, ...typeBlock].join(\"\\n\")\n : \"\";\n\n // Component gadgets: their own table + RENDER (not call)\n // teaching. A component export is mounted as a JSX element; the LLM\n // never invokes it like a hook.\n const componentRows = componentExports.map(({ exp, descriptor }) => {\n const compCol = `\\`${exp.component}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${compCol} | ${pkgCol} | ${what.padEnd(53, \" \")} |`;\n });\n\n // `**Props**:` lines for THIRD-PARTY component gadgets. The\n // props-object shape is extracted from the wrapper's published\n // `.d.ts` so the LLM knows the exact JSX attributes of `<X … />`. A\n // component whose `package` has no `.d.ts` entry is skipped\n // (graceful — the `example` still covers it).\n const componentPropsLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of componentExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const propsMap = extractComponentPropsFromDts(dts, [exp.component]);\n const props = propsMap[exp.component];\n if (props === undefined) continue; // graceful — couldn't extract.\n componentPropsLines.push(`- \\`${exp.component}\\`: \\`${props}\\``);\n }\n }\n const componentPropsBlock =\n componentPropsLines.length > 0\n ? [\n \"\",\n \"**Props** (third-party component gadgets — prop shape from the wrapper's published `.d.ts`):\",\n \"\",\n ...componentPropsLines,\n ]\n : [];\n\n const componentSection =\n componentExports.length > 0\n ? [\n \"When the contract declares a component gadget on `clientCapabilities.gadgets`, the export is a COMPONENT — RENDER it as a JSX element (`<X … />`) in the tree you return. Do NOT call it like a hook. The boilerplate has already emitted a direct import per gadget package — `import { <Component>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each component from the package named in the `Package` column. Available registered components:\",\n \"\",\n \"| Component | Package (import from here) | What it does |\",\n \"| --------------------- | ---------------------------------- | ----------------------------------------------------- |\",\n ...componentRows,\n ...componentPropsBlock,\n ].join(\"\\n\")\n : \"\";\n\n return [hookSection, componentSection]\n .filter((section) => section.length > 0)\n .join(\"\\n\\n\");\n}\n\n/**\n * Assemble the coding-agent system prompt. Deterministic — the only\n * variable content comes from the caller-supplied injection fields.\n */\nexport function buildSystemPrompt(inputs: SystemPromptInputs): string {\n const shell = inputs.shellType ?? \"fullscreen\";\n const scr = inputs.screen ?? \"universal\";\n const shellDesc = SHELL_DESCRIPTIONS[shell] ?? SHELL_DESCRIPTIONS.fullscreen;\n const screenDesc = SCREEN_DESCRIPTIONS[scr] ?? SCREEN_DESCRIPTIONS.universal;\n\n const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary();\n const pitfallsBlock = inputs.pitfallsBlock ?? \"\";\n const designSystemDocs = inputs.designSystemDocs ?? \"\";\n const primitivesDoc = inputs.primitivesDoc ?? \"\";\n const wireDoc = inputs.wireDoc ?? \"\";\n // Default to the standard-library seed when no per-app catalog is\n // supplied. Callers that resolve `App.gadgets` thread it through here.\n //\n // `gadgetTypes` carries third-party wrapper `.d.ts` content;\n // `formatGadgetsSection` renders a `Type:` line per third-party\n // gadget from it. When omitted, no `Type:` lines are rendered.\n const gadgetsSection = formatGadgetsSection(\n resolveAppGadgets(inputs.appGadgets),\n inputs.gadgetTypes,\n );\n\n const axisSection =\n inputs.axisDelta && inputs.axisDelta.trim().length > 0\n ? `\\n## Shape Guidance\\n${inputs.axisDelta}\\n`\n : \"\";\n\n return `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.\n\n## Your Task\n${inputs.userRequest}\n\n## Rendering Context\n- **Shell**: \\`${shell}\\` — ${shellDesc}\n- **Screen**: \\`${scr}\\` — ${screenDesc}\n\n## How It Works\n1. Read the boilerplate — typed Props, wire hooks, and layout container are pre-configured\n2. Respond with one apply_changes call — add state, helpers, and JSX\n3. If compilation or evaluation fails, you'll get errors to fix in the next turn\n\n${criteriaBlock}\n${axisSection}\n## Protocol Notes\nThe boilerplate pre-declares every wire hook the contract requires (\\`useAction\\`, \\`useStream\\`, \\`useGguiContext\\`, plus capability hooks from \\`@ggui-ai/gadgets\\` when the contract declares \\`clientCapabilities\\`). Three rules:\n1. **Do NOT delete any pre-declared hook.** \\`self_check\\` fails with \\`wire_preservation:<kind>:<name>\\` if you remove one.\n2. **Consume every hook binding** somewhere in the component — in JSX, a callback, or an effect. Unused bindings fail lint with \\`no-unused-vars\\`.\n3. **Do NOT invent new wire calls.** Every \\`useAction('X')\\`, \\`useStream('X')\\`, \\`useGguiContext('X')\\` etc. MUST correspond to a declared entry on the contract. Calling one that isn't declared fails \\`self_check\\` with \\`wire_undeclared:<kind>:<name>\\` because the runtime has no Context/registration for it and would throw at first paint. If you need a new wire surface, that's a contract authoring step the agent owns — your job is to honor what's declared.\n\nRenaming a binding is fine — the wiring is the string-literal argument, not the identifier.\n\n## Contract surface — four specs + two catalogs\n\nA \\`DataContract\\` declares everything a GguiSession exchanges with the outside world. **Four typed specs** for the four data-flow directions, **two reference catalogs** for tool / hook lookups:\n\n| Surface | Direction | Role |\n| -------------------- | -------------------------- | -------------------------------------------------------------------- |\n| \\`propsSpec\\` | server → UI (one-shot) | Initial render values delivered once at \\`ggui_render\\` |\n| \\`streamSpec\\` | agent → UI (many) | Typed channels for live updates via \\`ggui_emit\\` |\n| \\`actionSpec\\` | UI → agent (events) | Discrete events driving the agent's next turn (consumed via \\`ggui_consume\\`) |\n| \\`contextSpec\\` | UI → server (state mirror) | UI state the agent observes between turns |\n| \\`agentCapabilities.tools\\` | catalog | Tools the contract references via \\`actionSpec[*].nextStep\\` and \\`streamSpec[*].source.tool\\` |\n| \\`clientCapabilities.gadgets\\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \\`useGeolocation\\`) |\n\n**Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.\n\n**Data vs behavior**: the contract describes data flow; the component code describes behavior. Scroll, focus, toast, animation, clipboard write — all component code, never contract fields.\n\n## Defensive coding for absent / late-arriving data\n\nProps arrive at mount and may be partial on first render; later prop changes reach the SAME mounted component via \\`ggui_amend\\` (in-place repaint) on the live channel. Stream channels start empty and fill over time. Context slots start at their declared default (often \\`null\\`). **Never assume a field exists before you read it.**\n\n- **Optional contract props**: a \\`Props\\` field marked \\`?\\` in the boilerplate may be omitted by the agent ENTIRELY — the wire gate only enforces \\`required: true\\` entries, and the harness verifies your component with those props stripped. Guard them (\\`?? default\\`, \\`?.\\`, or an empty-state branch) from the FIRST render.\n- **Array iteration**: always default to \\`[]\\` before \\`.map\\`/\\`.filter\\`/\\`.length\\`. Use \\`(props.items ?? []).map(...)\\` not \\`props.items.map(...)\\`. Same for stream.all, stream.latest, etc.\n- **Object access**: optional-chain through nested fields. \\`props.user?.name ?? 'Anonymous'\\` not \\`props.user.name\\`.\n- **Number ops**: default before arithmetic. \\`(props.count ?? 0) + 1\\` not \\`props.count + 1\\`.\n- **Stream latest**: \\`useStream\\` returns \\`{latest: T | null, all: T[], isComplete: boolean}\\`. The default \\`all\\` is \\`[]\\` so it's safe to map; \\`latest\\` is null until the first frame arrives — guard before reading \\`.foo\\`.\n- **Stream reconciliation**: when a stream event carries an \\`action\\` discriminant (e.g. \\`create | move | edit | delete\\`), the channel is a CRUD feed — your handler MUST branch on EVERY value: append on \\`create\\`, drop on \\`delete\\`, replace-by-id on \\`move\\` / \\`edit\\`. Merging only the \"edit\" case silently loses created and deleted items. Reconcile into the SAME state that seeds from \\`props\\` (e.g. \\`useState(() => props.tasks ?? [])\\`) so the seed data and the live feed render as one list — and handle an event whose id is not yet present (a \\`create\\` for an unknown item) by inserting it, not ignoring it.\n- **Props re-sync on repaint**: props the agent owns are the source of truth for display — prefer rendering DIRECTLY from \\`props\\` (controlled, no local copy). When local optimistic state genuinely needs a prop seed (a click bumps a count before the agent confirms), it MUST re-sync on prop change — \\`useEffect(() => setCount(props.count ?? 0), [props.count])\\` — or a \\`ggui_amend\\` repaint applies the new props while the display keeps the stale local value. BAD: \\`const [count, setCount] = useState(props.count ?? 0)\\` alone. GOOD: the same seed + the one-line re-sync effect.\n- **Loading state**: while data is still absent, render \\`<Skeleton>\\` placeholders — never a blank screen. \\`<Skeleton variant=\"text\" />\\` for a text line, \\`variant=\"circle\"\\` for an avatar slot, default \\`rect\\` for a block.\n- **Empty state**: when a list or results array is empty, render \\`<EmptyState title=\"…\" description=\"…\" />\\` — a region that renders nothing when empty looks broken to the user.\n\nUnhandled \\`Cannot read properties of undefined\\` errors trip the iframe error boundary and the user sees \"Something went wrong\" — a regression class the runtime can't recover from.\n\n## Picking the right primitive for user gestures\n\nChoose by what the user is DOING, not where the result goes — the runtime handles the routing.\n\n| Gesture intent | LLM writes | Notes |\n| -------------- | ---------- | ----- |\n| Fire a server-side action | \\`useAction(name)\\` + call \\`dispatch(name, payload)\\` | Every action is agent-routed. The runtime emits an event on \\`ggui_consume\\`; the agent reacts on its next turn. If the contract entry declares \\`nextStep: 'X'\\`, that names the tool the agent SHOULD call next — advisory hint forwarded as event metadata. |\n| Surface state to the agent's context | the auto-generated \\`setSlotName\\` setter (from the boilerplate's \\`useGguiContext\\` line) | The runtime owns useState + Provider; the boilerplate emits one \\`const [slot, setSlot] = useGguiContext<T>('slot')\\` line per declared \\`contextSpec\\` slot. Write plain JSX, no \\`useState\\`, no Provider wrap. Every value change auto-flows to the host LLM (debounced). One-way client → agent — see \"Observable state via \\`contextSpec\\`\" below. |\n| Use a browser capability (camera, mic, geolocation, clipboard, file picker, notifications) | call the hook the contract declared, e.g., \\`const loc = useGeolocation();\\` and \\`await loc.start()\\` | The contract's \\`clientCapabilities.gadgets\\` declares which gadget exports the UI uses. The hook implementations live in \\`@ggui-ai/gadgets\\` (or a third-party package named in the \\`Package\\` column). Read \\`status\\` (\"idle\" / \"prompting\" / \"active\" / \"completed\" / \"denied\" / \"error\") to gate UI, and thread the resolved \\`value\\` into a contextSpec slot or actionSpec payload if the agent needs to see it. |\n| Open external link | Plain \\`<a href=\"https://...\">\\` (or \\`target=\"_blank\"\\`) | External cross-origin clicks are intercepted and routed through the host (security warnings, app-internal navigation, audit). Same-origin links and \\`#fragment\\` jumps stay native. |\n| Toggle fullscreen / chrome | Plain \\`el.requestFullscreen()\\` / \\`document.exitFullscreen()\\` | The native browser API is intercepted; the host adjusts iframe chrome accordingly. Returns a resolved promise so \\`.then()\\` / \\`await\\` chains don't break. |\n\nEvery gesture fires a uniform server-side audit envelope (\\`ggui_runtime_submit_action\\`) so operators see all three patterns in RenderInspector with the same shape.\n\n**Don't import wire hooks for link / display-mode.** \\`useAction\\` is the only wire hook for user gestures; links and fullscreen use plain HTML / browser APIs.\n\n**All actions are agent-routed.** Every action emits an event the agent reacts to on its next turn via \\`ggui_consume\\`. The optional \\`nextStep: '<tool>'\\` field on an \\`actionSpec\\` entry is a HINT naming the tool the agent SHOULD call next — the contract author's recommendation, NOT a binding directive. The agent decides whether to honor it. If you want to declare a tool catalog entry the contract references, add it to \\`agentCapabilities.tools[<name>]\\` with input/output schemas; the cross-ref linter rejects dangling \\`nextStep\\` values that don't resolve to a declared catalog entry.\n\n## Making a primitive interactive — \\`as={Trait}\\`\n\nStructural primitives (\\`Box\\`, \\`Stack\\`, \\`Row\\`, \\`Card\\`) have NO \\`onClick\\` by default. Add interactivity with the \\`as\\` prop — a trait, not a wrapper:\n\n\\`\\`\\`tsx\n<Card as={Clickable} onClick={() => dispatch('select', { id })}\n hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>…</Card>\n\\`\\`\\`\n\n- \\`as={Clickable}\\` → \\`onClick\\` + keyboard activation (Enter/Space) + \\`role=\"button\"\\` + \\`hoverStyle\\`/\\`activeStyle\\`/\\`cursor\\`.\n- \\`as={Hoverable}\\` → \\`hoverStyle\\` only (no click). \\`as={Pressable}\\` → \\`onPress\\` + \\`pressStyle\\`.\n\n\\`as={Trait}\\` is a PROP — it does NOT re-nest the JSX. Never write \\`<Clickable>…</Clickable>\\` around a primitive; put \\`as={Clickable}\\` on the primitive itself. The trait carries the keyboard + ARIA wiring, so don't hand-write \\`onKeyDown\\` / \\`role\\`. Trait components (\\`Clickable\\`, \\`Hoverable\\`, \\`Pressable\\`) import from \\`@ggui-ai/design\\` like everything else — the boilerplate already imports them.\n\n**Semantic components are already interactive** — \\`Button\\` (\\`onClick\\`), \\`Link\\` (\\`href\\`), \\`Input\\` / \\`Select\\` (\\`onChange\\`). Use their own props; never put \\`as\\` on them. \\`Text\\` picks its element with \\`is\\` (\\`<Text is=\"label\">\\`), not \\`as\\`.\n\n**Never nest two interactive elements.** Interactive content MUST NOT contain other interactive content — a gesture on the inner control bubbles to the outer one and fires BOTH handlers (one user click → the action dispatched twice). Do NOT put a \\`Button\\`, \\`Checkbox\\`, \\`Input\\`, \\`Select\\`, \\`Link\\`, or another \\`as={Clickable}\\` primitive inside a \\`Card\\` / \\`Box\\` / \\`Row\\` / \\`Stack\\` that is itself \\`as={Clickable}\\`. Wire each \\`useAction\\` callback to exactly ONE surface: EITHER the whole card is the trigger (interactive container, no interactive children) OR an inner control is the trigger (plain container, no \\`as={Clickable}\\`) — never both. A row with a checkbox: put the action on the \\`Checkbox onChange\\` and leave the row plain.\n\n**\\`Text\\` / \\`Heading\\` accept NO event handlers and NO \\`as\\` — only \\`style\\` / \\`className\\` plus their own typed props.** \\`onClick\\`, \\`onDoubleClick\\`, \\`as={Clickable}\\`, \\`color\\` are all type errors on \\`Text\\`. When the request says a label is \"clickable\", \"editable\", \"edit on click / double-click\", or \"tap to …\", do ONE of these — never put the handler on \\`Text\\`:\n\n\\`\\`\\`tsx\n// Click-to-edit a label: wrap the Text in a Clickable structural primitive.\n<Box as={Clickable} onClick={() => setEditingId(task.id)}\n style={{ cursor: 'pointer' }}>\n <Text weight=\"semibold\">{task.title}</Text>\n</Box>\n\n// Or pair the label with an explicit edit Button (clearer affordance).\n<Row gap=\"xs\" align=\"center\">\n <Text weight=\"semibold\">{task.title}</Text>\n <Button variant=\"ghost\" size=\"xs\" aria-label=\"Edit title\"\n onClick={() => setEditingId(task.id)}>Edit</Button>\n</Row>\n\n// In edit mode, swap the Text for an Input.\n{editingId === task.id\n ? <Input value={draftTitle} onChange={setDraftTitle} label=\"Task title\" />\n : <Text weight=\"semibold\">{task.title}</Text>}\n\\`\\`\\`\n\n## Anti-patterns — DO NOT WRITE\n\nThe following identifiers / shapes are RETIRED from the contract surface as of 2026-05-11. Pre-2026-05-11 examples in your training data may include them; do not reproduce. The linter / CI grep gate rejects:\n\n- \\`useWiredTool\\`, \\`useClientTool\\` — retired hooks. Replace with \\`useAction\\` (events) and the named hook from \\`@ggui-ai/gadgets\\` (browser capabilities).\n- \\`dispatch: { kind: 'tool', tool: '...' }\\` / \\`dispatch: { kind: 'agent', intendedTool: '...' }\\` — retired discriminated-union. Use the flat optional \\`nextStep?: '<tool>'\\` instead.\n- \\`mode: 'host-routed'\\` / \\`mode: 'tool'\\` — retired \\`mode\\` field. Same fix: flat \\`nextStep?\\`.\n- \\`broadcast: {...}\\` on the contract — retired top-level field. Use \\`streamSpec[channel].source: {tool, args?}\\` to declare a tool-fed channel.\n- \\`wiredTools\\` / \\`agentTools\\` (top-level) — retired catalog names. Use \\`agentCapabilities.tools\\`.\n- \\`clientTools\\` / \\`clientCapabilities.capabilities\\` — retired catalog shapes. Use \\`clientCapabilities.gadgets\\` (entries declare hooks, not RPC).\n- \\`@ggui-ai/client-tools\\` — retired package name. Import gadget hooks from \\`@ggui-ai/gadgets\\`.\n- \\`intendedTool\\` — retired. Use \\`nextStep\\` (flat).\n- \\`props: { properties: {...} }\\` as a CONTRACT field — retired. The contract field is \\`propsSpec\\` (the wire \\`props\\` field on render / update still carries VALUES).\n\n## Cross-reference rules\n\nWhen you declare a reference, also declare the catalog entry it points at:\n\n- \\`actionSpec[X].nextStep = 'fetch_inbox'\\` → \\`agentCapabilities.tools.fetch_inbox = { toolInfo: { inputSchema, description?, outputSchema? }, usage?, example? }\\` MUST exist. Cross-ref code: \\`CTR_REF_NEXT_STEP\\`.\n- \\`streamSpec[X].source.tool = 'list_messages'\\` → \\`agentCapabilities.tools.list_messages\\` MUST exist. Cross-ref code: \\`CTR_REF_STREAM_SOURCE\\`.\n- The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \\`CTR_SCHEMA_INCOMPAT\\`.\n\n## clientCapabilities — registered catalog\n\n${gadgetsSection}\n\nEach hook conforms to \\`GadgetHook<TOutput, TOptions>\\`: call \\`start(opts?)\\` to fire, read \\`{value, status, error, stop?}\\`. \\`status\\` walks through \\`idle → prompting → active|completed\\` or routes to \\`denied\\` / \\`error\\` on failure.\n\n3rd-party plugins (Leaflet maps, Mapbox, Stripe, Chart.js, …) are registered via \\`createGguiGadget\\` from \\`@ggui-ai/gadgets\\` and surface in this same table when the operator has added them to \\`App.gadgets\\`. Reference any registered hook by name — render validation rejects hooks not in this catalog with \\`gadget_not_registered\\`.\n\n## Observable state via \\`contextSpec\\`\n\nWhen the contract declares \\`contextSpec\\`, the boilerplate auto-generates one \\`useGguiContext\\` call per slot at the top of your component. The runtime owns the underlying \\`useState\\` and the Provider tree — **you do NOT write \\`useState\\` or any \\`<Provider>\\` wrap yourself**:\n\n\\`\\`\\`tsx\nimport { useGguiContext } from '@ggui-ai/wire';\n\nexport default function Component(props: Props) {\n // AUTO-GENERATED — do not remove or rename:\n const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');\n const [draftText, setDraftText] = useGguiContext<string>('draftText');\n\n // Plain JSX. No Provider wrap. The runtime already wrapped your\n // component in nested SingleSlotProviders before this code ran.\n return (\n <Container>\n <Text>Step {currentStep}</Text>\n <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />\n <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>\n </Container>\n );\n}\n\\`\\`\\`\n\nFor every declared slot you have **\\`slotName\\` + \\`setSlotName\\`** in scope:\n- **Read** the value to render: \\`<Text>Step {currentStep}</Text>\\`\n- **Write** via the setter: \\`setCurrentStep(s => s + 1)\\` (in callbacks, effects, anywhere)\n\nEvery value change is mirrored to the host LLM's context automatically (debounced, default 300ms — adjustable per-slot via \\`entry.debounceMs\\` in the contract). The agent sees the user's interaction state — drafts, current step, hover, selection — without you calling any API.\n\n**When to use the auto-generated state.** Any slot the contract declared. If \\`contextSpec.draftText\\` exists, bind \\`<Input value={draftText} onChange={e => setDraftText(e.target.value)}>\\` so the agent sees the typing live. If \\`contextSpec.currentStep\\` exists, render the step indicator from \\`currentStep\\` and bump it via \\`setCurrentStep\\` in your \"next\" callback.\n\n**When NOT to use it.** Local UI state the contract did NOT declare — \\`isDropdownOpen\\`, hover flags, animation phase, ephemeral toggles. For those, use a plain \\`useState\\` directly. The runtime ignores undeclared state.\n\n**\\`contextSpec\\` direction is one-way: client → agent.** The agent uses \\`propsSpec\\` (via \\`ggui_amend\\` for in-place repaints of this mount, or \\`ggui_update\\` when it mints a new history card) and \\`streamSpec\\` (via the live channel) to push state TO the client. Don't try to write to the agent via \\`contextSpec\\` — there is no return path.\n\n**Schema mismatches drop silently.** If you set a value that doesn't match the slot's schema (e.g. a string into a \\`{type: 'number'}\\` slot), the runtime logs a dev \\`console.warn\\` and skips the post. Make sure your setter calls produce values that match the declared shape.\n\n${pitfallsBlock}\n\n## Reference: Wire Hooks\n${wireDoc}\n\n${DESIGN_SYSTEM_GUIDANCE}\n\n### CSS Token Documentation\n${designSystemDocs}\n\n### Component Reference\n${primitivesDoc}\n`;\n}\n\n/**\n * Hand-written design-system guidance embedded in every coding-agent\n * system prompt. Lists prop-value enums, branded color strategy, and\n * responsive/parameterization rules that make a generated component\n * feel polished — the system prompt without it would only list\n * primitive *names*. Exported so `prompt-type-drift.test.ts` can\n * verify its enum claims against the auto-generated primitive catalog.\n */\nexport const DESIGN_SYSTEM_GUIDANCE = `## Imports & Component Surface\n\nImport ONLY from: \\`react\\`, \\`@ggui-ai/design\\`, \\`@ggui-ai/wire\\`. The ENTIRE design system — every primitive, component, composition and trait — is exported from the single \\`@ggui-ai/design\\` entry: \\`import { Card, Grid, Stack, Modal, Clickable } from '@ggui-ai/design'\\`. There are NO subpaths (\\`/primitives\\`, \\`/components\\`, …) — never import from them. Use the design components — DO NOT use raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) or Tailwind classes; those render unstyled in the iframe runtime.\n\nAvailable primitives (all from \\`@ggui-ai/design\\`):\n- Layout: Box, Container, Stack, Row, Grid, Spacer, Divider\n- Typography: Heading, Text, Link\n- Form: Button, Input, TextArea, Checkbox, Toggle, RadioGroup, Select, Slider\n- Display: Card, Alert, Badge, Avatar, Image, Icon, Progress, Spinner, Skeleton, Tooltip\n- Composite: Accordion, Tabs, Table, Toast\n\nAvailable compound components (all from \\`@ggui-ai/design\\`):\n- Autocomplete, Breadcrumb, Dropdown, EmptyState, FormField, Markdown, MarkdownInline, MenuItem, Pagination, SearchField, Stat, Stepper, Tag\n\n**Choosing between similar components** — pick by intent, don't guess:\n- **Pick from options**: one value from a short fixed list (a form field) → \\`Select\\`. Type-to-filter a long list, then pick → \\`Autocomplete\\`. A menu of actions off a button (edit / delete / …) → \\`Dropdown\\`. A search box that filters displayed content → \\`SearchField\\`.\n- **Tabular data** → \\`Table\\`. Reach for \\`DataTable\\` ONLY when you need built-in sorting / pagination / row-selection.\n- **Messaging**: an inline message in the layout flow → \\`Alert\\`. A transient popup → \\`Toast\\`. A panel listing many notifications → \\`NotificationCenter\\`.\n- **Step progress**: a wizard's step indicator → \\`Stepper\\`. NOT \\`Tabs\\` (implies free navigation), NOT \\`Progress\\` (continuous bar), NOT \\`Breadcrumb\\` (hierarchy).\n- **Containers**: width-constrain a page region → \\`Container\\`. A visually-contained surface (background + shadow + border) → \\`Card\\`. Plain grouping / spacing with no chrome → \\`Box\\`.\n\nEXACT primitive prop values (other values are silently ignored — the design system maps them to defaults):\n- \\`<Text size=\"...\">\\` — ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\`. For a HUGE number/temperature, use \\`<Text size=\"4xl\" weight=\"bold\">\\`. \\`caps\\` uppercases with letter-spacing — the eyebrow/overline label look is \\`<Text size=\"xs\" weight=\"semibold\" caps tone=\"muted\">\\`.\n- \\`<Text weight=\"...\">\\` — \\`normal | medium | semibold | bold\\`.\n- \\`<Text tone=\"...\">\\` — typed semantic slot. \\`default | muted | subtle | emphasized | loud | success | warning | error | info | inverse | inherit\\`. The theme decides what each tone LOOKS like — \\`muted\\` is a quiet warm grey on Claudic, a cool slate on Indigo. \\`tone\\` is the ONLY way to set Text color; the legacy \\`color=\"...\"\\` prop has been removed.\n- \\`<Heading level={1|2|3|4|5|6}>\\` — sizes are preset by level (h1 = 4xl bold, h2 = 3xl bold, h3 = 2xl semibold). Pass a number, not \\`level=\"h1\"\\`. Heading uses the same \\`tone\\` slot vocabulary as Text.\n- \\`<Icon name=\"...\" tone=\"...\">\\` / \\`<Spinner tone=\"...\">\\` / \\`<Link href=\"...\" tone=\"...\">\\` / \\`<Divider tone=\"...\">\\` — same \\`tone\\` vocabulary as Text. Default = \\`currentColor\\` (Icon), primary-tinted (Spinner / Link), outlineVariant (Divider). Use \\`tone=\"inherit\"\\` when you want the element to track the parent's foreground color (e.g. an Icon next to muted text).\n- \\`<Button variant=\"...\">\\` — \\`primary | secondary | outline | ghost | danger\\`. Sizes \\`xs | sm | md | lg\\`. Use \\`primary\\` for the main action — renders in the brand color automatically.\n- \\`<Card padding=\"lg\" shadow=\"md\" radius=\"lg\" surface=\"default\">\\` — shadow \\`none|sm|md|lg|xl\\`, radius \\`none|sm|md|lg|xl\\`. \\`surface\\` slot picks the fill: \\`default | elevated | sunken | accent | inverted | transparent\\`. Use \\`inverted\\` for dark testimonial-style cards on a light theme; \\`accent\\` for branded fills.\n- \\`<Box surface=\"...\">\\` — same surface slots as Card. \\`surface\\` is the ONLY theme-tracking background prop; the legacy \\`background=\"...\"\\` prop has been removed. For non-theme-mapped brand colors (a partner's exact brand hex like Stripe purple), use the typed escape \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">\\` — both props are required, and \\`assetSemantic\\` MUST be a non-empty human-readable label. Tier-0 self-check rejects every other hex / rgba on Box.\n- \\`<Stack gap=\"...\">\\` / \\`<Row gap=\"...\">\\` — \\`gap\\` takes the **spacing scale** (next bullet). \\`align\\` (cross-axis) is ONLY \\`start | center | end | stretch\\` and \\`justify\\` (main-axis) is ONLY \\`start | center | end | between | around | evenly\\` — NEVER the raw CSS values \\`flex-start\\` / \\`flex-end\\` / \\`space-between\\`, which are type errors.\n- **Spacing scale** — \\`gap\\` (Stack / Row / Grid) and \\`padding\\` (Card / Box / Container) take a t-shirt size: \\`none | xs | sm | md | lg | xl | 2xl\\`. Each resolves to a \\`--ggui-spacing-*\\` token (xs≈4px, sm≈8px, md≈16px, lg≈24px, xl≈32px, 2xl≈48px). A bare number is treated as pixels. NEVER pass a raw CSS length such as \\`gap=\"8px\"\\` — it is silently dropped by the browser and the gap collapses to 0; use the scale name (\\`gap=\"sm\"\\`).\n- \\`<Grid columns={N} gap=\"md\">\\` — 2-D layout (rows AND columns). Reach for it for card galleries, stat grids and dashboards — NEVER hand-roll \\`style={{ display: 'grid' }}\\`. When the request names exact per-breakpoint counts (\"3 per row on desktop, 1 on mobile\"), pass a map: \\`<Grid columns={{ base: 1, md: 3 }}>\\` (breakpoints \\`sm\\`/\\`md\\`/\\`lg\\`/\\`xl\\`; the design system emits the media queries). For an open-ended gallery where any column count is fine, use \\`<Grid minColumnWidth={220}>\\` — it fits as many equal columns as the width allows. \\`radius\\` (Card / Box / Image) takes the scale \\`none | sm | md | lg | xl\\`.\n- \\`<Stat label=\"…\" value=\"…\" delta=\"+12%\" trend=\"up\">\\` — KPI display (label + big value + trend-coloured delta + optional \\`icon\\`). \\`trend\\` is \\`up | down | neutral\\` (delta renders green / red / muted). Reach for it for any \"show a number\" UI; drop several into a \\`<Grid>\\` for a stat grid instead of hand-building label+value pairs.\n- \\`<Stepper steps={STEPS} current={step} />\\` — display-only step indicator for wizards/checkouts. \\`steps\\` is a top-level \\`const\\` array of labels; \\`current\\` is YOUR zero-indexed \\`useState\\` value; \\`orientation\\` is \\`horizontal | vertical\\`; optional \\`onStepClick={(i) => …}\\` makes steps clickable. Stepper never owns navigation state — your Next/Back handlers move \\`current\\`.\n- \\`<Badge variant=\"...\">\\` — \\`default | primary | secondary | success | warning | error | info\\` for colored pills. Great for status/condition labels. There is NO \\`neutral\\` variant — use \\`default\\` (or \\`secondary\\`) for an un-tinted pill.\n\n**Color choice rule of thumb.** Reach for typed slots first: Button \\`variant\\`, Badge \\`variant\\`, Alert \\`variant\\`, Text/Heading/Icon/Spinner/Link/Divider \\`tone\\`, Box/Card \\`surface\\`. NEVER hardcode hex \\`#XXXXXX\\`, rgba, or hsl — tier-0 self-check rejects them with \\`tokens:hex-color\\` / \\`tokens:hardcoded-color-fn\\` and the LLM must remediate. Hardcoded colors break the operator's theme switch (Indigo → Claudic → Cyberpunk preset has zero effect on a card hardcoded with \\`background: '#000'\\`).\n\n**Asset-color escape (Box only).** When you genuinely need a non-theme color — a partner's exact brand hex (Stripe purple \\`#635BFF\\`, Slack aubergine \\`#4A154B\\`), a fixed product surface — use \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">…</Box>\\`. The \\`assetSemantic\\` is REQUIRED and MUST be a non-empty human-readable label that documents intent. Tier-0 allows hex inside this typed pair; one without the other fails the check. Reach for \\`surface\\` first — \\`assetColor\\` is rare.\n\n## Accessibility (REQUIRED)\n\nThe design-system primitives are accessible by construction — they emit their own roles, labels, keyboard handlers, and error wiring. Your job is to USE them correctly, NOT to re-declare ARIA on top of them.\n\n1. **Form inputs** — give every \\`Input\\` / \\`TextArea\\` / \\`Select\\` a \\`label\\` prop. The primitive renders its own \\`<label htmlFor>\\`, and exposes \\`aria-invalid\\` + \\`aria-describedby\\` for errors. Do NOT add a separate \\`<Text>\\` label or your own \\`htmlFor\\` — that double-labels the field.\n \\`\\`\\`tsx\n <Input label=\"Email\" value={email} onChange={setEmail} type=\"email\" />\n \\`\\`\\`\n2. **Don't re-declare built-in ARIA.** \\`Progress\\`, \\`RadioGroup\\`, \\`Tabs\\`, \\`Toggle\\`, \\`Slider\\`, \\`Spinner\\`, \\`Alert\\`, \\`Accordion\\` already carry the correct \\`role\\` / \\`aria-*\\`. \\`Card as={Clickable}\\` already adds \\`role=\"button\"\\` + keyboard activation. Adding your own is redundant and often wrong.\n3. **Icons are decorative by default** — \\`<Icon name=\"check\" />\\` is hidden from screen readers, which is correct for an icon sitting next to text. Add \\`aria-label\\` ONLY for a standalone, meaning-bearing icon with no adjacent text. Icon-only \\`Button\\`s still need \\`aria-label\\` on the **Button** itself.\n4. **Live & streaming data** — wrap any region whose content updates on its own (a \\`useStream\\` \\`.latest\\` value, a live clock, an \"N new\" counter, a flashing price) in an element with \\`aria-live=\"polite\"\\` so screen readers announce the change.\n5. **Headings nest** — one \\`<Heading level={1}>\\` per screen, \\`level={2}\\` for sections, \\`level={3}\\` for subsections. Never skip or invert levels.\n6. **Buttons** — descriptive text content; icon-only buttons need \\`aria-label\\`. Announce busy state: \\`<Button disabled={isLoading} aria-busy={isLoading}>{isLoading ? 'Submitting…' : 'Submit'}</Button>\\`.\n7. **Stateful controls announce their state.** Toggleable / selectable / expandable things use the primitive that carries the semantics (\\`Checkbox\\`, \\`Toggle\\`, \\`Tabs\\`, \\`Accordion\\`) — never a styled \\`Box\\`/\\`Icon\\` that only *looks* checked. When you hand-roll one with \\`as={Clickable}\\`, \\`Clickable\\` adds button + keyboard semantics but NOT state — add it yourself: \\`role=\"checkbox\"\\` + \\`aria-checked={done}\\` on a toggleable row, \\`aria-pressed\\` on a toggle button, \\`aria-selected\\` on the chosen item, \\`aria-expanded\\` on an open/close affordance. Styling (strikethrough, color, a check icon) must never be the only carrier of state.\n\n## Design System Usage (CRITICAL)\n\nEVERY color, spacing, typography, shadow, and radius value MUST come from design-system CSS variables. The runtime injects them on \\`:root\\`.\n\nMANDATORY:\n1. NEVER use hardcoded hex colors like \\`#7c3aed\\` — ONLY \\`var(--ggui-color-*)\\` tokens.\n2. NEVER use CSS gradients with custom colors. If you need a gradient: \\`linear-gradient(to bottom, var(--ggui-color-primary-500, #0ea5e9), var(--ggui-color-primary-700, #0369a1))\\`.\n3. NEVER invent your own palette. The system provides primary, neutral, success, warning, error, and info — use ONLY these.\n4. ALWAYS include fallback values: \\`var(--ggui-color-primary-600, #0284c7)\\`.\n\nToken categories:\n- Brand: \\`var(--ggui-color-primary-600, #0284c7)\\`, \\`var(--ggui-color-primary-50, #f0f9ff)\\`\n- Text: \\`var(--ggui-color-onSurface, #18181b)\\`, \\`var(--ggui-color-onSurfaceVariant, #52525b)\\`\n- Backgrounds: \\`var(--ggui-color-surface, #fafafa)\\`, \\`var(--ggui-color-surfaceVariant, #f4f4f5)\\`\n- Borders: \\`var(--ggui-color-outline, #d4d4d8)\\`\n- Spacing: \\`var(--ggui-spacing-4, 16px)\\`, \\`var(--ggui-spacing-6, 24px)\\`\n- Typography: \\`var(--ggui-font-size-sm, 14px)\\`, \\`var(--ggui-font-weight-semibold, 600)\\`\n- Shadows: \\`var(--ggui-shape-shadow-sm)\\`, \\`var(--ggui-shape-shadow-md)\\`, \\`var(--ggui-shape-shadow-lg)\\`\n- Radius: \\`var(--ggui-shape-radius-md, 8px)\\`, \\`var(--ggui-shape-radius-lg, 12px)\\`\n\nPrefer primitives' built-in styling props over inline styles when possible.\n\n### Branded Color Strategy\n\nUse the FULL primary palette throughout the component — NOT only on submit buttons. A well-themed component feels distinctly branded, not gray-with-one-colored-button.\n\n| Element | Token | Purpose |\n|---------|-------|---------|\n| Section headers, hero areas, highlight strips | \\`primary-50\\` / \\`primary-100\\` | Subtle branded backgrounds |\n| Borders, dividers, focus rings, input focus | \\`primary-200\\` / \\`primary-300\\` | Branded structure |\n| Icons, links, labels, active indicators | \\`primary-500\\` / \\`primary-600\\` | Core accent color |\n| Buttons, CTAs, filled interactive elements | \\`primary-600\\` / \\`primary-700\\` | Primary actions |\n| Headings on light primary backgrounds | \\`primary-800\\` / \\`primary-900\\` | High-contrast branded text |\n\nUse semantic tokens (\\`onSurface\\`, \\`onSurfaceVariant\\`) for body text and secondary info. NEVER use raw \\`neutral-*\\` or \\`gray-*\\` for body text — they break in dark themes.\n\n### Theme-Agnostic Design\n\nComponents MUST be theme-agnostic — they reference CSS variables but NEVER assume a specific style. The theme decides what \\`primary-600\\` looks like.\n\nDO:\n- Use \\`var(--ggui-color-primary-*)\\` for brand elements — the theme controls what \"primary\" means\n- Use \\`var(--ggui-shape-shadow-*)\\` for depth, \\`var(--ggui-shape-radius-*)\\` for corners\n- Use semantic color roles: primary for brand, surface/onSurface for structure, success/error/warning for state\n\nDON'T:\n- Don't assume primary is blue — could be red, green, purple\n- Don't hardcode gradients tuned for a specific theme\n- Don't use fixed shadow values\n\nVisual hierarchy via tokens:\n- Elevated sections: \\`var(--ggui-shape-shadow-md)\\` + \\`var(--ggui-shape-radius-lg)\\`\n- Highlighted regions: \\`var(--ggui-color-primary-50)\\` background\n- Active/selected: \\`var(--ggui-color-primary-100)\\` background\n- Section headers: \\`var(--ggui-color-primary-600)\\` text or border-bottom\n\n## Responsive Design (CRITICAL)\n\nGenerated components become reusable blueprints — the same blueprint serves phones, tablets, desktops, spatial headsets. Design for ALL screen sizes:\n\n1. Design tokens for ALL spacing — never hardcode pixel values for padding/margins/gaps. Use the named spacing scale on props (\\`gap=\"md\"\\`, \\`padding=\"lg\"\\`); for inline \\`style\\` use \\`var(--ggui-spacing-*, …)\\`.\n2. Relative/fluid units — prefer \\`%\\`, \\`em\\`, \\`rem\\`, \\`min()\\`, \\`max()\\`, \\`clamp()\\` over fixed \\`px\\`.\n3. Fluid widths — \\`max-width\\` with \\`width: 100%\\`. Never set a fixed width.\n4. Compact padding — components are embedded in containers that provide their own chrome.\n5. No raw \\`@media\\` queries in component code — for a layout that must change by breakpoint, use \\`<Grid columns={{ base: 1, md: 3 }}>\\` (the design system emits the media queries for you) or a fluid \\`minColumnWidth\\` grid.\n\n## Data Parameterization (CRITICAL)\n\nGenerated components are CACHED blueprints reused across requests. NEVER hardcode request-specific data (names, cities, numbers, dates) into the component body. Define data as default prop values so the blueprint works for ANY similar request:\n\n\\`\\`\\`tsx\n// BAD — hardcoded, only works for Tokyo\nconst city = \"Tokyo\";\nconst temp = 18;\n\n// GOOD — parameterized via props with defaults from the request\ninterface Props {\n city?: string;\n temperature?: number;\n}\nexport default function WeatherCard({ city = \"Tokyo\", temperature = 18 }: Props) {\n // A controller can override for Seoul, Paris, etc.\n}\n\\`\\`\\`\n\nRules:\n1. All request-specific data → props with defaults. City names, tickers, user names, dates, counts.\n2. Layout and styling are universal. Colors, spacing, structure — these are the reusable part.\n3. Default values come from the current request — so the component renders correctly standalone.\n4. Props interface must be typed and exported.\n\n## Component Structure\n\nKeep JSX nesting depth to 3–5 levels. When deeper, extract repeated/complex sections into helper components — named functions defined above the main Component in the same file. Helpers take data + callbacks via props; they don't own state.\n\n\\`\\`\\`tsx\nimport { useState } from 'react';\nimport { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';\n\ninterface Props {\n onSubmit?: (data: unknown) => void;\n}\n\nfunction ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {\n return <Card padding=\"md\">…</Card>;\n}\n\nexport default function GeneratedComponent({ onSubmit }: Props) {\n return (\n <Container>\n {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}\n </Container>\n );\n}\n\\`\\`\\`\n\n## Aesthetic Guidance (READ CAREFULLY — this is what separates \"polished\" from \"ok\")\n\n### Visual hierarchy — the SCALE GAP rule\n\nA polished UI has ONE hero that dominates. Everything else supports it. Bad layouts have everything at similar sizes — the eye has nowhere to land. The rule:\n\n**Hero metric vs supporting text must have a 2–3× size gap.** If the hero is the temperature, score, count, status, price — it's ENORMOUS. Use \\`<Text size=\"4xl\" weight=\"bold\">\\` — the largest \\`size\\` the type allows (\\`4xl\\` = 36px). Pair it with a small supporting label (\\`size=\"sm\"\\`, ~14px) so the gap reads as 2–3×. The hero number should feel oversized compared to the location/title around it. \\`size\\` accepts ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\` — \\`5xl\\` / \\`6xl\\` are NOT valid and fail tier-0 type-check.\n\n\\`\\`\\`tsx\n// BAD — temperature is the same size as the location heading\n<Heading level={1}>Seoul, South Korea</Heading>\n<Text size=\"lg\" weight=\"bold\">18°C</Text>\n\n// GOOD — temperature dominates (4xl), location supports it (sm)\n<Text size=\"sm\" tone=\"muted\">Seoul, South Korea</Text>\n<Text size=\"4xl\" weight=\"bold\">18°C</Text>\n<Text size=\"lg\" tone=\"muted\">Partly Cloudy · Feels like 16°C</Text>\n\\`\\`\\`\n\n### Color discipline — the 60/30/10 rule\n\nDon't paint everything in primary. Use:\n- **60% surface** (\\`var(--ggui-color-surface)\\` / \\`onSurface\\`) — body text, default backgrounds, structure\n- **30% surfaceVariant + onSurfaceVariant** — secondary text, captions, labels, dividers\n- **10% primary** — hero number, ONE highlight element, CTAs, brand accent\n\nIf your component is 100% purple text on purple backgrounds, you've lost the eye. Headings can be \\`onSurface\\` (dark neutral) — they'll still feel weighty. Save the primary palette for one or two STAR moments.\n\n\\`\\`\\`tsx\n// BAD — everything purple, eye has no anchor\n<Heading tone=\"emphasized\">Title</Heading>\n<Text tone=\"emphasized\">42</Text>\n<Text tone=\"emphasized\">all body text</Text>\n\n// GOOD — hero pops, body is neutral, primary is reserved\n<Heading>Title</Heading> {/* defaults to onSurface */}\n<Text size=\"4xl\" weight=\"bold\" tone=\"emphasized\">42</Text>\n<Text tone=\"muted\">all body text</Text>\n\\`\\`\\`\n\n### Visual rhythm — vary your card treatments\n\nA row of identical flat tiles feels monotone. Use card-treatment variation to create rhythm:\n- **Hero card**: \\`<Card padding=\"xl\" shadow=\"lg\" radius=\"xl\">\\` with branded gradient background — anchors the eye\n- **Stat tiles**: \\`<Card padding=\"md\" shadow=\"sm\" radius=\"md\">\\` with surface bg — secondary\n- **Inline rows / list items**: no card chrome at all, just \\`<Stack gap=\"sm\">\\` with dividers — tertiary\n\nThe hero should literally have higher elevation than the supporting tiles. If everything has \\`shadow=\"md\"\\`, nothing does.\n\n### Iconography — emoji + Icon are visual weight on the cheap\n\nDon't render text-only metrics. A weather widget without a sun/cloud, a stock card without an arrow, a status panel without a colored dot — all feel undersold. Pair every hero metric with an icon or emoji at large size:\n\n\\`\\`\\`tsx\n<Row gap=\"md\" align=\"center\">\n <Text size=\"3xl\">☀️</Text>\n <Stack gap=\"xs\">\n <Text size=\"4xl\" weight=\"bold\">18°C</Text>\n <Text size=\"sm\" tone=\"muted\">Sunny · feels like 16°</Text>\n </Stack>\n</Row>\n\\`\\`\\`\n\nUse \\`<Icon name=\"...\" />\\` (Lucide icon names in kebab-case) for line icons; emoji directly for status/weather/mood. Both are valid. For per-stat tiny accents, use a small icon next to the label.\n\n### Spacing — generosity beats compactness\n\nHero sections should feel airy. Use \\`padding=\"xl\"\\` (32px) on the main card, not \\`padding=\"md\"\\`. Whitespace IS design. A cramped polished card looks worse than a roomy plain one.\n\n### Concrete recipes\n\n- **Hero metric card** (weather, stock, score): hero number at \\`size=\"4xl\"\\` (the max), icon/emoji at \\`size=\"3xl\"\\` next to it (use \\`<Row gap=\"md\">\\`), supporting label at \\`size=\"sm\"\\` muted, branded gradient bg, \\`shadow=\"lg\"\\`, \\`padding=\"xl\"\\`.\n- **Stat grid** (3–6 quick metrics): \\`<Grid columns={3} gap=\"md\">\\` of \\`<Stat>\\` — each \\`<Stat label=\"…\" value=\"…\" delta=\"…\" trend=\"…\" />\\` handles the label-on-top / value-below / trend-coloured-delta layout for you. Wrap each in a \\`<Card padding=\"md\" shadow=\"sm\">\\` if you want tile chrome.\n- **List item** (forecast day, todo, message): no card per item, use \\`<Stack gap=\"md\">\\` with each row as \\`<Row gap=\"md\">\\` of icon + content + meta. Add \\`<Divider>\\` between rows.\n- **Multi-step wizard** (survey, onboarding, checkout): \\`<Stepper steps={STEPS} current={step} />\\` at the top, the current step's fields below, Next/Back buttons that move \\`step\\`. Don't hand-roll a \"2 of 4\" indicator.\n- **Key-value rows** (specs, order summary, flight details): \\`<Stack gap=\"sm\">\\` of \\`<Row justify=\"between\">\\` — label as \\`<Text size=\"sm\" tone=\"muted\">\\`, value as \\`<Text size=\"sm\" weight=\"medium\">\\`.\n- **Section header**: \\`<Heading level={2}>\\` left-aligned, optional \\`<Badge>\\` to its right for count/status, optional muted caption below.\n- **CTA section**: ONE primary button. Other actions as ghost/outline. Don't stack three primary buttons.\n\n## Quality Checklist (verify before returning)\n\n- [ ] Imports ONLY from: react, @ggui-ai/design, @ggui-ai/wire\n- [ ] No raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) — uses primitives\n- [ ] ZERO hardcoded hex colors — every color is \\`var(--ggui-color-*, fallback)\\`\n- [ ] No raw pixel values for spacing — all via \\`var(--ggui-spacing-*)\\` tokens\n- [ ] Primary palette used throughout (headers, borders, icons) — not just buttons\n- [ ] Typed Props interface exported; request-specific data is a prop with default\n- [ ] Every Input/TextArea/Select has a \\`label\\` prop (no separate \\`<Text>\\` label)\n- [ ] Icon-only buttons have \\`aria-label\\`; no redundant \\`role\\`/\\`aria-*\\` on primitives\n- [ ] Toggleable/selected/expanded state is ARIA-expressed (\\`aria-checked\\`/\\`aria-pressed\\`/\\`aria-selected\\`/\\`aria-expanded\\`) — never style-only\n- [ ] Live/streaming regions wrapped in \\`aria-live=\"polite\"\\`\n- [ ] Headings nest — one \\`level={1}\\`, then \\`level={2}\\`/\\`{3}\\` — never skipped or inverted\n- [ ] Wire hooks (\\`useAction\\`, \\`useStream\\`) imported from \\`@ggui-ai/wire\\` and consumed`;\n","// packages/ui-gen/src/tools.ts\n//\n// LLM tool grammars used by the generation stage. Primary tool =\n// `apply_changes` (multi-range patch). Scoped fallback =\n// `apply_changes` with `maxItems=1` for transport-error recovery\n// (malformed_tool_call retries). Plus:\n// - hashline variants (`APPLY_CHANGES_HASHLINE_TOOL[_FLAT]`) used\n// when the `hashline: \"v2\"` policy profile selects them;\n// - flat-code variant (`APPLY_CHANGES_TOOL_FLAT`) — the shipped\n// default;\n// - helper tools (`GET_ICONS_TOOL`, `GET_COMPONENTS_INFO_TOOL`,\n// `WRITE_PLAN_TOOL`, `REWRITE_TOOL`) wired into the\n// `selectTurnTools` path.\n//\n// Harness `what.codingTools` can override with any subset; alternate\n// patch grammars swap in by replacing the tool list + a matching\n// `applyPatch` implementation.\n//\n// The tool definitions in this file are static JSON schemas + prompt\n// text. The decision logic (which profile picks which tool,\n// model-registry overrides, environment gating) lives in\n// `./harness/policy.ts` + `run-coding-turn.ts::selectTurnTools` —\n// nothing in this file reads a profile or an env var; these are data.\n\nimport type { LLMToolDef } from \"./llm.js\";\nexport type { LLMToolDef };\n\n/** Standard multi-range patch tool — surgical edits. */\nexport const APPLY_CHANGES_TOOL: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit: replace line ranges in ui.tsx with new code. Use line numbers from the Current File (shown as N│). Preferred for targeted changes — fixing one hook, renaming a prop, swapping a component, closing a missing tag. The patch is ALWAYS applied to the workspace even if the resulting file has syntax errors — the error location is returned as guidance so you can iterate. If the file is in a tangled state and patches aren't converging cleanly, use `write` to rewrite from scratch.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces lines startLine through endLine (inclusive) with the new code lines. Applied bottom-to-top to preserve line numbers.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"number\",\n description: \"First line to replace (from the N│ numbers in Current File)\",\n },\n endLine: { type: \"number\", description: \"Last line to replace (inclusive)\" },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines. One source line per array element. Avoid embedding newlines inside an element. For long JSX blocks, split at statement boundaries across multiple changes.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n allowBroken: {\n type: \"boolean\",\n description:\n \"Opt-in: commit the patch even if the resulting file fails syntax preflight. Use when you want to iterate across multiple turns and accept a broken intermediate state (e.g., split a big JSX refactor into 2 patches). Default false (strict preflight).\",\n },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Scoped fallback variant for transport-error retries. Used by the LLM\n * router when `malformed_tool_call` exhausts the standard retry budget —\n * forces a single small change (≤20 lines) so the payload fits within the\n * provider's JSON-emission ceiling. Universal signal; only Gemini hits this\n * path today, but the handler is not provider-gated.\n */\nexport const APPLY_CHANGES_TOOL_SCOPED: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Replace ONE small line range in ui.tsx. Narrow schema for transport-error recovery: emit a single change covering at most 20 lines.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n minItems: 1,\n maxItems: 1,\n description: \"Single change. endLine - startLine ≤ 20.\",\n items: {\n type: \"object\",\n properties: {\n startLine: { type: \"number\", description: \"First line to replace\" },\n endLine: {\n type: \"number\",\n description: \"Last line (inclusive). Keep endLine - startLine ≤ 20.\",\n },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines (one source line per element, no embedded newlines). ≤ 20 elements.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/** Hashline variant of APPLY_CHANGES_TOOL.\n * When the `hashline-v2` policy profile is active, this tool is\n * advertised in place of the standard numeric-line APPLY_CHANGES_TOOL.\n * The `startLine` and `endLine` fields are STRINGS in `\"N:hh\"` format\n * (e.g., `\"47:a3\"`) — where `hh` is the 2-char content hash shown in\n * the `## Current File` block. The handler validates the hash against\n * the current file; if it mismatches, the edit is rejected with\n * HASHLINE_STALE so the LLM re-reads before patching. */\nexport const APPLY_CHANGES_HASHLINE_TOOL: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit with line-hash verification. Replace line ranges in ui.tsx. Line refs use the format `N:hh` from the Current File block (e.g., `47:a3`) — the 2-char hash anchors your view so the edit is rejected if the file drifted under you. Always use the exact hashes shown in the latest Current File view. The patch is applied even if the resulting file has syntax errors (the error location is returned as guidance); but edits with mismatched hashes are rejected BEFORE apply.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces `startLine` through `endLine` (inclusive) with the new code lines. Line refs use the `N:hh` format.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"First line to replace, as `N:hh` (e.g., `47:a3`). The hash MUST match the line's hash in the latest Current File view. Format is line-number, colon, 2 lowercase hex chars — enforced by JSON schema pattern.\",\n },\n endLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"Last line to replace, as `N:hh` (e.g., `83:b1`). Hash MUST match. Format: line-number, colon, 2 lowercase hex chars.\",\n },\n code: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"New code lines. One source line per array element. No embedded newlines.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Flat-code variant of APPLY_CHANGES_TOOL.\n *\n * Identical to APPLY_CHANGES_TOOL except `code` is a single string with\n * `\\n`-separated lines instead of an array. One level of JSON nesting\n * shallower — a deeply-nested schema can trip some model decoders. The\n * handler in `coding-agent/tools.ts` accepts both shapes.\n */\nexport const APPLY_CHANGES_TOOL_FLAT: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit: replace line ranges in ui.tsx with new code. Use line numbers from the Current File (shown as N│). Preferred for targeted changes. The `code` field is a single string with newlines (`\\\\n`) between lines. The patch is ALWAYS applied even if the resulting file has syntax errors — the error is returned as guidance. For a full rewrite, use `rewrite`.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description:\n \"Array of changes. Each replaces lines startLine through endLine (inclusive). Applied bottom-to-top.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"number\",\n description: \"First line to replace (from the N│ numbers in Current File)\",\n },\n endLine: { type: \"number\", description: \"Last line to replace (inclusive)\" },\n code: {\n type: \"string\",\n description:\n \"New code as a single string. Separate lines with `\\\\n`. Preserve leading indentation inside the string.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n allowBroken: {\n type: \"boolean\",\n description:\n \"Opt-in: commit the patch even if the resulting file fails syntax preflight.\",\n },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/**\n * Flat-code + hashline variant.\n * Combines `code: string` flatness with `N:hh` hash-verified line refs\n * from hashline-v2.\n */\nexport const APPLY_CHANGES_HASHLINE_TOOL_FLAT: LLMToolDef = {\n name: \"apply_changes\",\n description:\n \"Surgical edit with line-hash verification. Replace line ranges in ui.tsx using `N:hh` references from the Current File (e.g. `47:a3`). The `code` field is a single string with newlines between lines. Edits with mismatched hashes are rejected before apply.\",\n parameters: {\n type: \"object\",\n properties: {\n changes: {\n type: \"array\",\n description: \"Array of changes. Line refs use `N:hh` format.\",\n items: {\n type: \"object\",\n properties: {\n startLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"First line to replace, as `N:hh` (e.g., `47:a3`). Hash MUST match the latest Current File view. Format: line-number, colon, 2 lowercase hex chars.\",\n },\n endLine: {\n type: \"string\",\n pattern: \"^\\\\d+:[0-9a-f]{2}$\",\n description:\n \"Last line to replace, as `N:hh` (e.g., `83:b1`). Hash MUST match.\",\n },\n code: {\n type: \"string\",\n description:\n \"New code as a single string. Separate lines with `\\\\n`. Preserve leading indentation.\",\n },\n description: { type: \"string\", description: \"What this change does (< 10 words)\" },\n },\n required: [\"startLine\", \"endLine\", \"code\", \"description\"],\n },\n },\n commit_message: { type: \"string\", description: \"Short summary of all changes\" },\n },\n required: [\"changes\", \"commit_message\"],\n },\n};\n\n/** Helper icon-lookup tool — not a patch grammar, attached to the same LLM turn. */\nexport const GET_ICONS_TOOL: LLMToolDef = {\n name: \"get_available_icons\",\n description: 'List all 185 available Lucide icon names for the <Icon name=\"...\"> component.',\n parameters: { type: \"object\", properties: {} },\n};\n\n/**\n * Component-docs fetch tool (tool-driven primitive docs). Advertised\n * alongside `apply_changes` when `ContextPolicy.primitiveIndex` is\n * active (a compact name+description index replaces the full ~130KB\n * primitives doc in the system prompt; the LLM fetches the full\n * per-component API on demand).\n *\n * The handler lives in `coding-agent/tools.ts` under the\n * `get_components_info` case.\n */\nexport const GET_COMPONENTS_INFO_TOOL: LLMToolDef = {\n name: \"get_components_info\",\n description:\n \"Fetch full prop API + example + variant mappings for one or more design-system components. Use when the compact index doesn't give you enough detail to write correct JSX (e.g., you need to know the exact prop values for `variant` or the shape of an options array). Batch names in one call — cheaper than multiple fetches.\",\n parameters: {\n type: \"object\",\n properties: {\n names: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Component names to fetch (e.g., ['Card', 'Stack', 'Input']). Names must match the index entries exactly.\",\n },\n },\n required: [\"names\"],\n },\n};\n\n/**\n * Plan-commitment tool.\n *\n * Forced on turn 2 when the harness runs the `fetch → plan → write`\n * pipeline. After turn-1 fetching, the LLM must produce a short\n * structured plan before any apply_changes is allowed. The plan\n * echoes back in the tool result so turn 3+ patches can reference it —\n * this breaks fetch-loops where the model over-fetches without\n * committing to a structure.\n */\nexport const WRITE_PLAN_TOOL: LLMToolDef = {\n name: \"write_plan\",\n description:\n \"Commit to a concrete plan before writing code. Produce a short structured outline: which components you'll use, rough JSX structure, and wiring (state/actions/streams). After this call, on the next turn you'll be able to write code with `apply_changes`. Keep it brief — this is a commitment, not a design doc.\",\n parameters: {\n type: \"object\",\n properties: {\n components: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"Primitive/component names you'll use in the final JSX (e.g., ['Card', 'Stack', 'Input', 'Button']).\",\n },\n structure: {\n type: \"string\",\n description:\n \"Brief JSX structure outline — a few lines of pseudocode showing nesting. Example: 'Card > Stack > [Heading, Input x3, Button].'\",\n },\n wiring: {\n type: \"string\",\n description:\n \"Brief note on state/actions/streams you'll wire. Example: 'useState for form payload; invokeAction(submit) on Button click.'\",\n },\n },\n required: [\"components\", \"structure\", \"wiring\"],\n },\n};\n\n/**\n * Full-file write tool. Flat JSON payload (two top-level strings) — much\n * easier for brittle tool-call serializers (e.g., Google Gemini Flash-Lite)\n * than `apply_changes`' nested array-of-objects-of-arrays-of-strings.\n *\n * Offered alongside `apply_changes` on turn 1 so the LLM can pick whichever\n * shape it emits more reliably. On patch-repair turns, `apply_changes` is\n * preferred (minimal diff, preserves session), but turn-1 has no existing\n * scaffold state to preserve — write is equivalent semantically.\n *\n * Implementation note: `executeTool` in `coding-agent/tools.ts`\n * already handles the `write` case; the harness just needs to\n * advertise it to the LLM.\n */\nexport const REWRITE_TOOL: LLMToolDef = {\n name: \"rewrite\",\n description:\n \"Escape hatch: rewrite the entire ui.tsx file in one call. Use only when surgical `apply_changes` patches have accumulated into a tangled broken state and you need to reset the file to a clean implementation. Single-string payload; auto-compiles + validates. Prefer `apply_changes` for normal edits.\",\n parameters: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"Complete TSX component source — the whole file.\",\n },\n commit_message: {\n type: \"string\",\n description: \"Short description (< 10 words)\",\n },\n },\n required: [\"code\", \"commit_message\"],\n },\n};\n","// packages/ui-gen/src/patch.ts\n//\n// Pure line-range patch implementation. Mirrors the `apply_changes` tool\n// logic (from coding-agent/tools.ts) without workspace / git / preflight\n// coupling — the harness exposes this as the default `PatchFn` so\n// variants can override with alternative patch grammars (diff3,\n// atomic-write, inline-markup, etc.) while reusing the orchestration\n// around them.\n//\n// Invariants:\n// - Changes sorted ascending by startLine.\n// - No overlapping ranges.\n// - All line numbers within [1, fileLines].\n// - Applied in reverse order to preserve upstream line numbers.\n//\n// This is the default patch function — every production harness uses it\n// unless a variant overrides `what.applyPatch`.\n\nimport type { PatchFn } from \"./harness/types-public.js\";\n\n/** Core pure logic — exported separately for tests + alternative wrappers. */\nexport function applyLineRanges(\n sourceBefore: string,\n rawChanges: ReadonlyArray<{\n startLine: number;\n endLine: number;\n code: readonly string[];\n description?: string;\n }>,\n): { ok: true; sourceAfter: string } | { ok: false; error: string } {\n if (rawChanges.length === 0) {\n return { ok: false, error: \"No changes provided.\" };\n }\n\n // Normalize — stable copy, sort ascending by startLine\n const changes = rawChanges\n .map((c, i) => ({\n startLine: c.startLine,\n endLine: c.endLine,\n code: [...c.code],\n description: c.description ?? `change ${i + 1}`,\n }))\n .sort((a, b) => a.startLine - b.startLine);\n\n // Required fields + non-empty code\n for (const c of changes) {\n if (typeof c.startLine !== \"number\" || typeof c.endLine !== \"number\") {\n return { ok: false, error: `Change \"${c.description}\" missing startLine or endLine.` };\n }\n if (c.code.length === 0) {\n return {\n ok: false,\n error: `Change \"${c.description}\" has empty code. Use [\"\"] to delete lines.`,\n };\n }\n }\n\n // Overlaps\n for (let i = 1; i < changes.length; i++) {\n if (changes[i].startLine <= changes[i - 1].endLine) {\n return {\n ok: false,\n error:\n `Changes overlap — \"${changes[i - 1].description}\" (lines ` +\n `${changes[i - 1].startLine}-${changes[i - 1].endLine}) overlaps with ` +\n `\"${changes[i].description}\" (lines ${changes[i].startLine}-${changes[i].endLine}).`,\n };\n }\n }\n\n // Line-number bounds\n const fileLines = sourceBefore.split(\"\\n\");\n for (const c of changes) {\n if (c.startLine < 1 || c.endLine < c.startLine || c.startLine > fileLines.length) {\n return {\n ok: false,\n error:\n `Invalid line range ${c.startLine}-${c.endLine} for \"${c.description}\". ` +\n `File has ${fileLines.length} lines.`,\n };\n }\n }\n\n // Apply in reverse to preserve line numbers\n const resultLines = [...fileLines];\n for (let i = changes.length - 1; i >= 0; i--) {\n const c = changes[i];\n const deleteCount = c.endLine - c.startLine + 1;\n resultLines.splice(c.startLine - 1, deleteCount, ...c.code);\n }\n\n return { ok: true, sourceAfter: resultLines.join(\"\\n\") };\n}\n\n/**\n * Harness-compatible wrapper around `applyLineRanges`. The default\n * patch function attached to every new harness's `what.applyPatch`.\n * Variants can override with alternative implementations (e.g., diff3\n * merge, atomic file write, etc.) to test different patch grammars\n * end-to-end.\n */\nexport const defaultApplyPatch: PatchFn = async ({ sourceBefore, changes }) => {\n const result = applyLineRanges(sourceBefore, changes);\n if (result.ok) {\n return { ok: true, sourceAfter: result.sourceAfter };\n }\n return { ok: false, error: result.error };\n};\n","// packages/ui-gen/src/hash.ts\n//\n// Deterministic fingerprint helpers for harness composition. Two inputs\n// that are structurally equivalent hash to the same 12-char prefix; two\n// different inputs hash to different prefixes.\n//\n// Used for:\n// - Harness id attribution (log + benchmark cell tagging)\n// - Prompt-cache key reuse\n// - Comparison-validity checks when benchmarking harness variants\n//\n// The `stableStringify` + `shortHash` primitives are private\n// implementation detail of this module.\n\nimport { createHash } from \"node:crypto\";\nimport type { Classification } from \"./classifier/axes.js\";\n\n// ─── Private primitives ────────────────────────────────────────────────────\n// Not exported — these are implementation detail. If an external consumer\n// needs a stable hash of arbitrary data, they should do it themselves.\n\nfunction stableStringify(value: unknown): string {\n if (value === null) return \"null\";\n if (typeof value === \"number\") return Number.isFinite(value) ? JSON.stringify(value) : \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (typeof value === \"object\") {\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const parts = keys.map(\n (k) =>\n `${JSON.stringify(k)}:${stableStringify((value as Record<string, unknown>)[k])}`,\n );\n return `{${parts.join(\",\")}}`;\n }\n return \"null\";\n}\n\nfunction shortHash(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\").slice(0, 12);\n}\n\n// ─── Public surface ────────────────────────────────────────────────────────\n\n/** Hash a classification — used as a sub-component of the harness id. */\nexport function hashClassification(c: Classification): string {\n return shortHash(stableStringify({ vector: c.vector, riskTier: c.riskTier }));\n}\n\n/**\n * Compute a harness id from the materialized pieces. Called by `createHarness`\n * after all legs are built.\n *\n * Hashes only the stable content — not function references (applyPatch,\n * planner, etc.) because function identity isn't serializable. Instead,\n * version tags bump when semantics change.\n */\nexport function computeHarnessId(input: {\n classificationHash: string;\n howVersion: string;\n whatVersion: string;\n checkVersion: string;\n processVersion: string;\n workflowId: string;\n fragmentIds: readonly string[];\n overrides: readonly string[];\n}): string {\n return shortHash(stableStringify(input));\n}\n\n/**\n * Human-readable harness name. Deterministic but informative — derives from\n * classification + workflow without needing to look up the id.\n */\nexport function computeHarnessName(input: {\n classification: Classification;\n workflowName: string;\n version: string;\n}): string {\n const v = input.classification.vector;\n const dominantAxes: string[] = [];\n if (v.state !== \"none\") dominantAxes.push(`state=${v.state}`);\n if (v.writes !== \"none\") dominantAxes.push(`writes=${v.writes}`);\n if (v.realtime !== \"none\") dominantAxes.push(`realtime=${v.realtime}`);\n if (v.tooling !== \"none\") dominantAxes.push(`tooling=${v.tooling}`);\n const axesPart = dominantAxes.length > 0 ? dominantAxes.join(\"+\") : \"passive\";\n return `${input.version}/${axesPart}/${input.workflowName}`;\n}\n","// packages/ui-gen/src/workflows.ts\n//\n// Workflow registry + classification-driven picker. Each workflow\n// describes an execution topology (phases × tasks) for producing source\n// from a contract + prompt; the harness runtime owns actual LLM calls.\n//\n// Workflow shapes are validated shipping defaults — even `staged` /\n// `staged-concurrent` are reserved-but-registered topologies the picker\n// may route to in future risk-tier routing. Classification-driven\n// routing itself is deliberately conservative today (always\n// `single_pass`); changing the picker is a behavior change that should\n// be validated against the generation benchmark suite.\n//\n// Public surface is intentionally minimal: consumers import `WORKFLOWS`\n// (the map) + `pickWorkflow` (the router) + `WorkflowId` (the key\n// type). Individual topology constants (SINGLE_PASS, STAGED,\n// STAGED_CONCURRENT) are internal — access them via\n// `WORKFLOWS.single_pass` etc.\n\nimport type { Classification } from \"./classifier/axes.js\";\nimport type { Workflow } from \"./harness/types-public.js\";\n\n/** Identity parser — used for tasks whose output is already a string. */\nconst identityParser = (raw: unknown): string => raw as string;\n\n/**\n * single_pass — one phase, one task. The current default. The task runs\n * the existing impl/patch/eval-fix loop as a single atomic block.\n */\nconst SINGLE_PASS: Workflow = {\n id: \"single_pass@1\",\n name: \"single_pass\",\n description: \"One LLM-driven impl loop. Used for risk:low + risk:medium contract.\",\n phases: [\n {\n id: \"impl\",\n tasks: [\n {\n id: \"generate\",\n systemPrompt: (ctx) => ctx.harness.how.systemPrompt,\n contextBuilder: (ctx) =>\n `User prompt: ${ctx.prompt}\\n\\nBoilerplate is pre-written. Fill it in with apply_changes.`,\n outputFormat: \"tool-call\",\n outputParser: identityParser,\n outputName: \"source\",\n },\n ],\n },\n ],\n};\n\n/**\n * staged — plan phase then execute phase. For risk:high contract where\n * decomposing planning from authoring reduces light-model cognitive load.\n *\n * Registered but not yet routed by `pickWorkflow` — the executor wires\n * architect/coder TaskRunners through a separate dispatch path in core/.\n */\nconst STAGED: Workflow = {\n id: \"staged@1\",\n name: \"staged\",\n description: \"plan → execute. One architect task then one coder task.\",\n phases: [\n {\n id: \"plan\",\n tasks: [\n {\n id: \"architect\",\n systemPrompt: \"You are a UI architect. Produce a plan, no code.\",\n contextBuilder: (ctx) => `Plan the UI for: ${ctx.prompt}`,\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"plan\",\n maxTokens: 800,\n },\n ],\n },\n {\n id: \"execute\",\n tasks: [\n {\n id: \"coder\",\n systemPrompt: (ctx) => ctx.harness.how.systemPrompt,\n contextBuilder: (ctx) =>\n `User prompt: ${ctx.prompt}\\n\\nPlan:\\n${ctx.priorResults.plan ?? \"(no plan)\"}\\n\\nImplement per plan with apply_changes.`,\n inputs: [\"plan\"],\n outputFormat: \"tool-call\",\n outputParser: identityParser,\n outputName: \"source\",\n },\n ],\n },\n ],\n};\n\n/**\n * staged-concurrent — plan, then parallel skeleton tasks, then integrate.\n * Reserved shape for risk:high + multi-axis contract where the LLM\n * benefits from breaking structural concerns apart.\n */\nconst STAGED_CONCURRENT: Workflow = {\n id: \"staged_concurrent@1\",\n name: \"staged-concurrent\",\n description: \"plan → [types ∥ hooks ∥ jsx] → integrate. DAG with parallel skeleton phase.\",\n phases: [\n {\n id: \"plan\",\n tasks: [\n {\n id: \"architect\",\n systemPrompt: \"Plan the UI. No code.\",\n contextBuilder: (ctx) => `Plan the UI for: ${ctx.prompt}`,\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"plan\",\n maxTokens: 600,\n },\n ],\n },\n {\n id: \"skeleton\",\n tasks: [\n {\n id: \"types\",\n systemPrompt: \"Emit only type declarations for the contract.\",\n contextBuilder: (ctx) =>\n `Emit TypeScript types for: ${ctx.prompt}. Plan: ${ctx.priorResults.plan ?? \"(n/a)\"}`,\n inputs: [\"plan\"],\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"types\",\n maxTokens: 400,\n },\n {\n id: \"hooks\",\n systemPrompt: \"Emit only hook declarations (useState/useEffect/useStream).\",\n contextBuilder: (ctx) =>\n `Emit hooks for: ${ctx.prompt}. Plan: ${ctx.priorResults.plan ?? \"(n/a)\"}`,\n inputs: [\"plan\"],\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"hooks\",\n maxTokens: 400,\n },\n {\n id: \"jsx\",\n systemPrompt: \"Emit only the render JSX tree skeleton.\",\n contextBuilder: (ctx) =>\n `Emit JSX for: ${ctx.prompt}. Plan: ${ctx.priorResults.plan ?? \"(n/a)\"}`,\n inputs: [\"plan\"],\n outputFormat: \"structured\",\n outputParser: identityParser,\n outputName: \"jsx\",\n maxTokens: 400,\n },\n ],\n },\n {\n id: \"integrate\",\n tasks: [\n {\n id: \"glue\",\n systemPrompt: (ctx) => ctx.harness.how.systemPrompt,\n contextBuilder: (ctx) =>\n `Combine into one component. Types:\\n${ctx.priorResults.types}\\n\\nHooks:\\n${ctx.priorResults.hooks}\\n\\nJSX:\\n${ctx.priorResults.jsx}`,\n inputs: [\"types\", \"hooks\", \"jsx\"],\n outputFormat: \"tool-call\",\n outputParser: identityParser,\n outputName: \"source\",\n },\n ],\n },\n ],\n};\n\nexport const WORKFLOWS = {\n single_pass: SINGLE_PASS,\n staged: STAGED,\n staged_concurrent: STAGED_CONCURRENT,\n} as const;\n\nexport type WorkflowId = keyof typeof WORKFLOWS;\n\n/**\n * Pick a workflow based on classification shape. One dispatch rule —\n * kept small on purpose. Changing this mapping is a first-class\n * experiment.\n *\n * Deliberately conservative — always `single_pass`. Classification-\n * driven routing to `staged` / `staged-concurrent` will follow once\n * the workflow executor can actually run non-single_pass shapes end-\n * to-end on the dispatch path.\n */\nexport function pickWorkflow(_classification: Classification): Workflow {\n return WORKFLOWS.single_pass;\n}\n","// packages/ui-gen/src/policy.ts\n//\n// Harness policy — validated defaults + identity resolvers.\n//\n// What lives here is the CONTRACT layer + the SHIPPING DEFAULTS:\n// - Type vocabulary every harness is built against\n// (ContextPolicy, HarnessPolicy, RuntimeCtx, ResolvedRunPolicy,\n// ProcessMode).\n// - The default values that reflect the current best-known harness\n// (DEFAULT_CONTEXT_POLICY, DEFAULT_HARNESS_POLICY), updated as new\n// configurations ship as new defaults.\n// - The structural-equality check `isDefaultHarnessPolicy`, used by\n// createHarness to decide whether policy participates in the\n// harness id (a harness running the vanilla default policy gets a\n// byte-identical id regardless of how the policy was constructed).\n// - The default `resolveHarnessPolicy(classification)` (returns\n// `DEFAULT_HARNESS_POLICY` for every classification — no ENV\n// profile branches here).\n// - The identity `resolveRunPolicy(harness, runtimeCtx)` (returns\n// `harness.policy` unchanged — no per-model registry lookup here).\n//\n// What does NOT live here (it lives in `./harness/policy.ts`, the\n// experiment layer that wraps this module):\n// - `GGUI_POLICY_PROFILE` environment-variable reading.\n// - The named experimental profile branches\n// (narrow-merge-v1, hashline-v2, tool-driven-primitives-*,\n// primitives-ts-format, tsformat-plan-impl, numberline-flat,\n// legacy-code-array, hashline-v2-flat).\n// - `resolveRunPolicyForProfile`.\n// - The per-model `MODEL_HARNESS_REGISTRY` consultation in\n// `resolveRunPolicy`.\n// Those are experiment plumbing — a new arm lives in the wrapper layer\n// until it is validated, then graduates into the defaults here.\n\nimport type { Classification } from \"./classifier/axes.js\";\n\n// ─── Execution topology ────────────────────────────────────────────────────\n\n/**\n * Coarse execution-topology label attached to `ProcessLeg`. The workflow\n * DAG itself is the source of truth; this is a label on it, used by filters\n * and by `HarnessPolicy.processMode` to override the default `\"single_pass\"`.\n */\nexport type ProcessMode = \"single_pass\" | \"staged\" | \"staged-concurrent\";\n\n// ─── ContextPolicy ─────────────────────────────────────────────────────────\n\n/**\n * Context-leg policy. Controls the SHAPE of feedback the LLM sees on retry /\n * patch surfaces, the format of the primitives reference, and the tool-grammar\n * schema of `apply_changes`. Does NOT change what errors get caught or how\n * the code executes — only how errors get rendered back to the LLM and how\n * the primitive documentation is staged on turn 1.\n *\n * Every field is documented against the experiment that justified it. The\n * defaults in `DEFAULT_CONTEXT_POLICY` reflect the current best-known\n * harness; changing a default here is a semver-major-level event for\n * a hosted closed runtime (which shifts every benchmark cell) and\n * deserves its own commit with bench evidence.\n */\nexport interface ContextPolicy {\n /**\n * Prefix the preflight `PATCH_INVALID` retry message with `[P0-compile]`\n * so the LLM can rank it against the prompt's P0/P1/P2 priority schema.\n * Default `false`.\n */\n readonly labeledPreflight: boolean;\n /**\n * Reserved for future plumbing. When true, would prefix tier-0 self-check\n * retry violations with `[P0-*]` / `[P1-*]` priority tags. Default false.\n */\n readonly labeledTier0: boolean;\n /**\n * When true, the coding loop detects duplicate patch/error-class\n * fingerprints across consecutive patch turns and, on match, runs the\n * action chosen by {@link dupeBreakAction}. Default false.\n */\n readonly breakDuplicatePatch: boolean;\n /**\n * When `breakDuplicatePatch` fires, choose the intervention. Default\n * `\"escape\"` for back-compat with the dormant scoped-escape plumbing —\n * has no effect unless `breakDuplicatePatch` is also true.\n */\n readonly dupeBreakAction?: \"escape\" | \"diagnostic\" | \"diagnostic-noforce\";\n /**\n * Axis-keyed primitives doc slice. When `\"axis-keyed\"`, the first-turn\n * system prompt injects only the allowlisted primitives derived from\n * the classification, shrinking the ~130 KB monolith to ~30–50 KB.\n * Default `\"full\"`.\n */\n readonly primitiveDocSlice?: \"full\" | \"axis-keyed\";\n /**\n * Primitives to exclude from the axis-keyed slice. Only meaningful\n * when `primitiveDocSlice === \"axis-keyed\"`.\n */\n readonly primitiveDocExcludes?: readonly string[];\n /**\n * Hashline view format on `## Current File` + hash-verified\n * apply_changes line refs. Default `\"off\"`.\n */\n readonly hashline?: \"off\" | \"v2\";\n /**\n * Tool-driven primitive docs. When `\"names-only\"` or `\"with-props\"`,\n * the ~130 KB primitives doc is replaced with a compact ~7–9 KB index\n * and `get_components_info` is advertised alongside the authoring tool.\n * Default `\"off\"`.\n */\n readonly primitiveIndex?: \"off\" | \"names-only\" | \"with-props\";\n /**\n * Force turn 1 to advertise ONLY `get_components_info`. Requires\n * `primitiveIndex !== \"off\"`. Default `false`.\n */\n readonly primitiveIndexForceFetch?: boolean;\n /**\n * Force turn 2 to advertise ONLY `write_plan`. Requires\n * `primitiveIndex !== \"off\"` and typically `primitiveIndexForceFetch`.\n * Default `false`.\n */\n readonly primitiveIndexPlanTurn?: boolean;\n /**\n * Format of the primitive component reference. `\"markdown\"` = verbose\n * markdown tables (~128 KB); `\"ts\"` = compact TS-interface format\n * (~59 KB, same enum coverage). The TS format is the shipped default.\n */\n readonly primitiveDocFormat?: \"markdown\" | \"ts\";\n /**\n * Force turn 1 to advertise ONLY `write_plan`. Orthogonal to\n * `primitiveIndex`. Default `false`.\n */\n readonly planFirstTurn?: boolean;\n /**\n * apply_changes `code` field schema. `\"array\"` = `string[]` (one line\n * per element); `\"flat\"` = single string with `\\n` separators (3 JSON\n * nesting levels instead of 4). The flat format is the shipped\n * default.\n */\n readonly codeFormat?: \"array\" | \"flat\";\n}\n\n// ─── HarnessPolicy + runtime context ───────────────────────────────────────\n\n/**\n * Top-level policy attached to a harness. v1 defines only the context\n * sub-policy + an optional process-mode override. More sub-policies\n * (eval, retry, process-specific) will land when they have a first real\n * field with clean semantics.\n */\nexport interface HarnessPolicy {\n readonly context: ContextPolicy;\n /**\n * Process-leg mode override. When set, `createHarness` uses this value\n * instead of the default `\"single_pass\"`. Null/undefined → default.\n */\n readonly processMode?: ProcessMode;\n}\n\n/**\n * Runtime context visible at dispatch time. v1 carries `provider` +\n * optional `modelId`. Future fields (observed axis values, capability\n * flags) may appear as warranted.\n */\nexport interface RuntimeCtx {\n readonly provider: \"anthropic\" | \"openai\" | \"google\" | \"openrouter\";\n /**\n * Model id as passed to the provider SDK. Optional — when absent,\n * runtime policy resolution falls through to provider-level and\n * default resolution only.\n */\n readonly modelId?: string;\n}\n\n/**\n * Runtime-resolved policy. Identical shape to {@link HarnessPolicy} for\n * v1 — the default {@link resolveRunPolicy} is an identity. The separate\n * type exists as a parking spot for future provider-aware overrides so\n * callers can start typing `ResolvedRunPolicy` today and get new fields\n * automatically when they land.\n */\nexport type ResolvedRunPolicy = HarnessPolicy;\n\n// ─── Defaults ──────────────────────────────────────────────────────────────\n\n/** Validated shipping defaults for the generation harness. */\nexport const DEFAULT_CONTEXT_POLICY: ContextPolicy = Object.freeze({\n labeledPreflight: false,\n labeledTier0: false,\n breakDuplicatePatch: false,\n dupeBreakAction: \"escape\",\n primitiveDocSlice: \"full\",\n hashline: \"off\",\n primitiveIndex: \"off\",\n primitiveIndexForceFetch: false,\n primitiveIndexPlanTurn: false,\n // A processed TypeScript-interface format for the primitive docs,\n // chosen over verbose markdown tables: roughly half the size with no\n // loss of enum-value information.\n primitiveDocFormat: \"ts\",\n planFirstTurn: false,\n // A flat `code: string` patch payload instead of `code: string[]`.\n // The shallower JSON nesting is more reliably decoded by tool-calling\n // models.\n codeFormat: \"flat\",\n});\n\nexport const DEFAULT_HARNESS_POLICY: HarnessPolicy = Object.freeze({\n context: DEFAULT_CONTEXT_POLICY,\n});\n\n// ─── Resolvers (defaults + identity) ───────────────────────────────────────\n\n/**\n * Default harness-policy resolver — v1 returns `DEFAULT_HARNESS_POLICY`\n * for every classification. A hosted closed runtime can overlay its own\n * funnel profile-branching wrapper around this; OSS consumers get this\n * single default path and can wrap it themselves if they need\n * classification-aware overrides.\n *\n * Preserves reference equality: every call on every classification\n * returns the same frozen singleton object, so callers can use\n * `resolved === DEFAULT_HARNESS_POLICY` to detect the vanilla path\n * (used by `createHarness` via `isDefaultHarnessPolicy` to keep\n * `harness.id` byte-identical on the default path).\n */\nexport function resolveHarnessPolicy(_classification: Classification): HarnessPolicy {\n return DEFAULT_HARNESS_POLICY;\n}\n\n/**\n * Identity run-time resolver — returns `harness.policy` unchanged for\n * any runtime context. A hosted closed runtime can overlay a per-model\n * registry lookup on top (graduating bench-validated overrides per\n * model id); OSS consumers get the identity, preserving reference\n * equality so `resolved === harness.policy` detects \"no override\n * applied.\"\n */\nexport function resolveRunPolicy(\n harness: { readonly policy: HarnessPolicy },\n _runtimeCtx: RuntimeCtx,\n): ResolvedRunPolicy {\n return harness.policy;\n}\n\n// ─── Structural-equality check ─────────────────────────────────────────────\n\n/**\n * Structural equality against `DEFAULT_HARNESS_POLICY`. Used by\n * `createHarness` to skip hashing the policy for the vanilla case —\n * keeps `harness.id` byte-identical for every harness running the\n * default policy.\n *\n * Checks each field explicitly (including the unset-means-default\n * shorthand) instead of `policy === DEFAULT_HARNESS_POLICY` so callers\n * can pass a structurally-equivalent object they built themselves.\n */\nexport function isDefaultHarnessPolicy(policy: HarnessPolicy): boolean {\n return (\n policy.context.labeledPreflight === DEFAULT_CONTEXT_POLICY.labeledPreflight &&\n policy.context.labeledTier0 === DEFAULT_CONTEXT_POLICY.labeledTier0 &&\n policy.context.breakDuplicatePatch === DEFAULT_CONTEXT_POLICY.breakDuplicatePatch &&\n (policy.context.dupeBreakAction ?? \"escape\") ===\n (DEFAULT_CONTEXT_POLICY.dupeBreakAction ?? \"escape\") &&\n (policy.context.primitiveDocSlice ?? \"full\") ===\n (DEFAULT_CONTEXT_POLICY.primitiveDocSlice ?? \"full\") &&\n (policy.context.primitiveDocExcludes?.length ?? 0) === 0 &&\n (policy.context.hashline ?? \"off\") === (DEFAULT_CONTEXT_POLICY.hashline ?? \"off\") &&\n (policy.context.primitiveIndex ?? \"off\") ===\n (DEFAULT_CONTEXT_POLICY.primitiveIndex ?? \"off\") &&\n (policy.context.primitiveIndexForceFetch ?? false) ===\n (DEFAULT_CONTEXT_POLICY.primitiveIndexForceFetch ?? false) &&\n (policy.context.primitiveIndexPlanTurn ?? false) ===\n (DEFAULT_CONTEXT_POLICY.primitiveIndexPlanTurn ?? false) &&\n (policy.context.primitiveDocFormat ?? \"markdown\") ===\n (DEFAULT_CONTEXT_POLICY.primitiveDocFormat ?? \"markdown\") &&\n (policy.context.planFirstTurn ?? false) ===\n (DEFAULT_CONTEXT_POLICY.planFirstTurn ?? false) &&\n (policy.context.codeFormat ?? \"array\") ===\n (DEFAULT_CONTEXT_POLICY.codeFormat ?? \"array\") &&\n policy.processMode === undefined\n );\n}\n","// packages/ui-gen/src/create-harness.ts\n//\n// Deterministic Harness factory — the skeleton constructor. Given a\n// classification + contract + prompt (+ optional caller-injected\n// defaults for policy / system-prompt builder / axis-checks /\n// runtime-render / overrides), assemble all four legs and return an\n// immutable Harness object ready to drive generation.\n//\n// This is a SKELETON: it has four injection seams (policy,\n// systemPromptBuilder, axisChecks, runtimeRender). The hosted runtime\n// supplies the production content for those seams from\n// `adapters/generation-dispatch.ts` at the dispatch boundary; callers\n// that omit them get minimal defaults.\n\nimport type { CacheTier } from \"./fragments/index.js\";\nimport { compose } from \"./compose.js\";\nimport { buildSystemPrompt, generateBoilerplate } from \"./boilerplate.js\";\nimport { APPLY_CHANGES_TOOL, APPLY_CHANGES_TOOL_SCOPED } from \"./tools.js\";\nimport { defaultApplyPatch } from \"./patch.js\";\nimport { computeHarnessId, computeHarnessName, hashClassification } from \"./hash.js\";\nimport { pickWorkflow } from \"./workflows.js\";\nimport { DEFAULT_HARNESS_POLICY, isDefaultHarnessPolicy } from \"./policy.js\";\nimport type {\n CreateHarnessInput,\n Harness,\n HarnessConstructionContext,\n HarnessOverrides,\n HarnessRevision,\n HowLeg,\n WhatLeg,\n CheckLeg,\n ProcessLeg,\n HarnessMeta,\n PatchFn,\n SystemPromptBuilder,\n} from \"./harness/types-public.js\";\n\n// Version tags — bump when semantics change.\nconst HARNESS_VERSION = \"harness@1\";\nconst HOW_VERSION = \"how@1\";\nconst WHAT_VERSION = \"what@1\";\nconst CHECK_VERSION = \"check@1\";\nconst PROCESS_VERSION = \"process@1\";\n\n// Default patch function — pure line-range application (mirrors apply_changes).\n// Variants can override via HarnessOverrides.what.\nconst defaultPatchFn: PatchFn = defaultApplyPatch;\n\nfunction applyLegOverride<L>(\n base: L,\n ovr: Partial<L> | ((base: L, ctx: HarnessConstructionContext) => L) | undefined,\n ctx: HarnessConstructionContext,\n): L {\n if (!ovr) return base;\n if (typeof ovr === \"function\") return (ovr as (b: L, c: HarnessConstructionContext) => L)(base, ctx);\n return { ...base, ...ovr };\n}\n\nfunction countCacheTiers(fragments: readonly { cacheTier: CacheTier }[]): Record<CacheTier, number> {\n const counts: Record<CacheTier, number> = { stable: 0, axisDelta: 0, volatile: 0 };\n for (const f of fragments) counts[f.cacheTier]++;\n return counts;\n}\n\n/**\n * Build a Harness from classification + inputs. Idempotent: same inputs\n * produce a Harness with the same id.\n */\nexport function createHarness(input: CreateHarnessInput): Harness {\n const { classification, contract, prompt, shellType, screen, overrides } = input;\n const ctx: HarnessConstructionContext = { classification, contract, prompt };\n\n // ── Compose fragments from classification ────────────────────────────────\n const composed = compose(classification);\n\n // ── HOW leg ──────────────────────────────────────────────────────────────\n // System-prompt builder seam. The default is the skeleton builder\n // with empty content blocks; callers inject a fully-populated builder\n // to add pitfalls + design-system docs + primitives + wire content.\n const systemPromptBuilder: SystemPromptBuilder =\n input.systemPromptBuilder ?? buildSystemPrompt;\n const systemPrompt = systemPromptBuilder({\n userRequest: prompt,\n shellType,\n screen,\n axisDelta: composed.promptText,\n });\n const howFragments = composed.fragments.filter(\n (f) => f.promptText && f.promptText.trim().length > 0,\n );\n const baseHow: HowLeg = {\n systemPrompt,\n implPrompt: \"\",\n fragments: howFragments,\n version: HOW_VERSION,\n };\n const how = applyLegOverride(baseHow, overrides?.how, ctx);\n\n // ── WHAT leg ─────────────────────────────────────────────────────────────\n // `appGadgets` reaches the boilerplate generator so thin contract\n // refs (`{hook: 'useLeafletMap'}` without a per-binding `package`)\n // resolve their import specifier from the operator-registered\n // descriptor's `package` field. Without this thread, the LLM's\n // starter file shows\n // `import { useLeafletMap } from '@ggui-ai/gadgets'` —\n // which doesn't export operator-registered wrapper hooks — and the\n // LLM removes the hook with a \"not available\" comment.\n const boilerplate = generateBoilerplate(\n prompt,\n contract as Parameters<typeof generateBoilerplate>[1],\n shellType,\n screen,\n composed.boilerplateSections,\n input.appGadgets,\n );\n const whatFragments = composed.fragments.filter(\n (f) => f.boilerplateMarker && f.boilerplateMarker.trim().length > 0,\n );\n const baseWhat: WhatLeg = {\n boilerplate,\n fragments: whatFragments,\n codingTools: [APPLY_CHANGES_TOOL],\n scopedTools: [APPLY_CHANGES_TOOL_SCOPED],\n applyPatch: defaultPatchFn,\n // Registered gadget catalog — drives the system prompt's gadget\n // table + the boilerplate's direct-import emission. Omitted when no\n // gadgets registered.\n ...(input.appGadgets !== undefined ? { appGadgets: input.appGadgets } : {}),\n // Third-party wrapper `.d.ts` map — autoCommit's typecheck overlays\n // the real wrapper declarations so a generated direct gadget import\n // gets strict hook types.\n ...(input.gadgetTypes !== undefined\n ? { gadgetTypes: input.gadgetTypes }\n : {}),\n version: WHAT_VERSION,\n };\n const what = applyLegOverride(baseWhat, overrides?.what, ctx);\n\n // ── CHECK leg ────────────────────────────────────────────────────────────\n // Axis-check registry seam. The caller supplies pre-filtered\n // axisChecks; the skeleton default is [].\n // Runtime-render seam. The skeleton default is undefined.\n const axisChecks = input.axisChecks ?? [];\n const baseCheck: CheckLeg = {\n axisChecks,\n tierChecks: [],\n runtimeRender: input.runtimeRender,\n llmEvaluator: undefined,\n version: CHECK_VERSION,\n };\n const check = applyLegOverride(baseCheck, overrides?.check, ctx);\n\n // ── Policy ───────────────────────────────────────────────────────────────\n // Policy injection seam. The caller pre-resolves; the skeleton\n // default is DEFAULT_HARNESS_POLICY.\n const policy = input.policy ?? DEFAULT_HARNESS_POLICY;\n\n // ── Process leg ──────────────────────────────────────────────────────────\n const workflow = pickWorkflow(classification);\n const baseProcess: ProcessLeg = {\n mode: policy.processMode ?? \"single_pass\",\n workflow,\n planner: undefined,\n retry: { maxIterations: 30 },\n version: PROCESS_VERSION,\n };\n const processLeg = applyLegOverride(baseProcess, overrides?.process, ctx);\n\n // ── Meta + id ────────────────────────────────────────────────────────────\n const classificationHash = hashClassification(classification);\n const fragmentIds = composed.fragments.map((f) => `${f.axis}=${f.value}`);\n const cacheTierBreakdown = countCacheTiers(composed.fragments);\n const overrideLabels: string[] = [];\n if (overrides?.how) overrideLabels.push(\"how\");\n if (overrides?.what) overrideLabels.push(\"what\");\n if (overrides?.check) overrideLabels.push(\"check\");\n if (overrides?.process) overrideLabels.push(\"process\");\n if (overrides?.label) overrideLabels.push(`label:${overrides.label}`);\n // Only non-default policies contribute to the harness id — preserves\n // byte-identical id across default-policy runs.\n if (!isDefaultHarnessPolicy(policy)) overrideLabels.push(\"policy\");\n\n const id = computeHarnessId({\n classificationHash,\n howVersion: how.version,\n whatVersion: what.version,\n checkVersion: check.version,\n processVersion: processLeg.version,\n workflowId: workflow.id,\n fragmentIds,\n overrides: overrideLabels,\n });\n\n const name = computeHarnessName({\n classification,\n workflowName: workflow.name,\n version: HARNESS_VERSION,\n });\n\n const meta: HarnessMeta = {\n classificationHash,\n fragmentIds,\n cacheTierBreakdown,\n overrides: overrideLabels,\n createdAt: new Date().toISOString(),\n harnessVersion: HARNESS_VERSION,\n };\n\n const harness: Harness = {\n id,\n name,\n classification,\n how,\n what,\n check,\n process: processLeg,\n policy,\n meta,\n derive(revision: HarnessRevision): Harness {\n return deriveHarness(this, revision, input);\n },\n };\n\n return harness;\n}\n\n/**\n * Produce a derived Harness for a subsequent iteration. Called when the\n * planner reclassifies or a runtime signal demands a topology swap.\n */\nfunction deriveHarness(\n base: Harness,\n revision: HarnessRevision,\n originalInput: CreateHarnessInput,\n): Harness {\n let mergedOverrides: HarnessOverrides = {\n ...originalInput.overrides,\n ...(revision.overrides ?? {}),\n };\n\n // If the revision names a new workflow explicitly, override the process leg.\n if (revision.workflow) {\n const currentProcessOverride = mergedOverrides.process;\n const processBuilder = (baseProcess: ProcessLeg, ctx: HarnessConstructionContext): ProcessLeg => {\n const withOverride =\n typeof currentProcessOverride === \"function\"\n ? currentProcessOverride(baseProcess, ctx)\n : { ...baseProcess, ...(currentProcessOverride ?? {}) };\n return { ...withOverride, workflow: revision.workflow! };\n };\n mergedOverrides = { ...mergedOverrides, process: processBuilder };\n }\n\n // Runtime fallback: promote scopedTools → codingTools.\n if (revision.useFallbackTools) {\n const currentWhatOverride = mergedOverrides.what;\n const whatBuilder = (baseWhat: WhatLeg, ctx: HarnessConstructionContext): WhatLeg => {\n const withOverride =\n typeof currentWhatOverride === \"function\"\n ? currentWhatOverride(baseWhat, ctx)\n : { ...baseWhat, ...(currentWhatOverride ?? {}) };\n if (withOverride.scopedTools && withOverride.scopedTools.length > 0) {\n return { ...withOverride, codingTools: withOverride.scopedTools };\n }\n return withOverride;\n };\n mergedOverrides = { ...mergedOverrides, what: whatBuilder };\n }\n\n return createHarness({\n ...originalInput,\n classification: revision.classification ?? base.classification,\n overrides: mergedOverrides,\n });\n}\n"]}
|