{"version":3,"file":"index.mjs","names":["#contracts","sensitivityRank","isCompilerArtifactPart","reference"],"sources":["../src/canonical.ts","../src/contract-version.ts","../src/diagnostics.ts","../src/catalog.ts","../src/information-flow.ts","../src/part.ts","../src/commit.ts","../src/normalize.ts","../src/prompt.ts","../src/repair.ts","../src/surface.ts","../src/turn.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { JsonValue } from \"./types\";\n\nconst forbiddenObjectKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function assertJsonValue(value: unknown, path = \"$\"): asserts value is JsonValue {\n  const ancestors = new Set<object>();\n\n  const visit = (current: unknown, currentPath: string): void => {\n    if (\n      current === null\n      || typeof current === \"string\"\n      || typeof current === \"boolean\"\n    ) return;\n    if (typeof current === \"number\") {\n      if (!Number.isFinite(current)) {\n        throw new TypeError(`Expected a finite number at ${currentPath}.`);\n      }\n      return;\n    }\n    if (typeof current !== \"object\") {\n      throw new TypeError(`Expected JSON data at ${currentPath}.`);\n    }\n    if (ancestors.has(current)) {\n      throw new TypeError(`Cyclic JSON data at ${currentPath}.`);\n    }\n\n    ancestors.add(current);\n    if (Array.isArray(current)) {\n      for (const [index, item] of current.entries()) {\n        visit(item, `${currentPath}/${index}`);\n      }\n    } else {\n      const prototype = Object.getPrototypeOf(current);\n      if (prototype !== Object.prototype && prototype !== null) {\n        throw new TypeError(`Expected a plain JSON object at ${currentPath}.`);\n      }\n      for (const [key, item] of Object.entries(current)) {\n        if (forbiddenObjectKeys.has(key)) {\n          throw new TypeError(`Forbidden object key at ${currentPath}/${key}.`);\n        }\n        visit(item, `${currentPath}/${escapeJsonPointer(key)}`);\n      }\n    }\n    ancestors.delete(current);\n  };\n\n  visit(value, path);\n}\n\nexport function canonicalize(value: JsonValue): string {\n  if (value === null || typeof value !== \"object\") return JSON.stringify(value);\n  if (Array.isArray(value)) {\n    return `[${value.map((item) => canonicalize(item)).join(\",\")}]`;\n  }\n  return `{${Object.keys(value)\n    .sort()\n    .map((key) => `${JSON.stringify(key)}:${canonicalize(value[key]!)}`)\n    .join(\",\")}}`;\n}\n\nexport function hashJson(value: JsonValue): string {\n  return createHash(\"sha256\").update(canonicalize(value)).digest(\"hex\");\n}\n\nexport function utf8Bytes(value: string): number {\n  return Buffer.byteLength(value, \"utf8\");\n}\n\nexport function escapeJsonPointer(value: string): string {\n  return value.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n}\n\nexport function deepFreeze<T>(value: T): Readonly<T> {\n  if (value && typeof value === \"object\" && !Object.isFrozen(value)) {\n    Object.freeze(value);\n    for (const child of Object.values(value)) deepFreeze(child);\n  }\n  return value;\n}\n","const exactVersionPattern = /^([1-9][0-9]*)$/;\nconst compatibleVersionPattern = /^\\^([1-9][0-9]*)$/;\nconst boundedVersionPattern = /^>=([1-9][0-9]*) <([1-9][0-9]*)$/;\nconst MAX_VERSION_SPAN = 32;\n\n/**\n * Action contracts use integer protocol versions. Ranges stay deliberately\n * finite so provider schemas and validators can share an exact version set.\n */\nexport function actionContractVersions(range: string): readonly number[] | undefined {\n  const exact = exactVersionPattern.exec(range);\n  if (exact) return [Number(exact[1])];\n\n  const compatible = compatibleVersionPattern.exec(range);\n  if (compatible) return [Number(compatible[1])];\n\n  const bounded = boundedVersionPattern.exec(range);\n  if (!bounded) return undefined;\n  const minimum = Number(bounded[1]);\n  const maximum = Number(bounded[2]);\n  if (maximum <= minimum || maximum - minimum > MAX_VERSION_SPAN) return undefined;\n  return Array.from({ length: maximum - minimum }, (_, index) => minimum + index);\n}\n\nexport function matchesActionContractVersion(version: number, range: string): boolean {\n  return actionContractVersions(range)?.includes(version) ?? false;\n}\n","import type { Diagnostic, DiagnosticPhase, JsonValue } from \"./types\";\n\nexport class CompilerDiagnosticError extends Error {\n  readonly diagnostics: readonly Diagnostic[];\n\n  constructor(diagnostics: readonly Diagnostic[]) {\n    super(diagnostics.map(({ code, message }) => `${code}: ${message}`).join(\"\\n\"));\n    this.name = \"CompilerDiagnosticError\";\n    this.diagnostics = diagnostics;\n  }\n}\n\nexport function compilerDiagnostic(input: {\n  phase: DiagnosticPhase;\n  code: string;\n  message: string;\n  path?: string;\n  severity?: Diagnostic[\"severity\"];\n  recoverable?: boolean;\n  modelCorrectable?: boolean;\n  expected?: JsonValue;\n  actualSummary?: string;\n  hint?: string;\n}): Diagnostic {\n  return {\n    phase: input.phase,\n    code: input.code,\n    severity: input.severity ?? \"error\",\n    recoverable: input.recoverable ?? true,\n    modelCorrectable: input.modelCorrectable ?? true,\n    message: input.message,\n    ...(input.path ? { location: { path: input.path } } : {}),\n    ...(input.expected === undefined ? {} : { expected: input.expected }),\n    ...(input.actualSummary ? { actualSummary: input.actualSummary } : {}),\n    ...(input.hint ? { hint: input.hint } : {}),\n  };\n}\n\nexport function throwDiagnostic(input: Parameters<typeof compilerDiagnostic>[0]): never {\n  throw new CompilerDiagnosticError([compilerDiagnostic(input)]);\n}\n\nexport function diagnosticsFromUnknown(error: unknown): readonly Diagnostic[] {\n  if (error instanceof CompilerDiagnosticError) return error.diagnostics;\n  return [compilerDiagnostic({\n    phase: \"validate\",\n    code: \"compiler.validation_failed\",\n    message: \"The artifact did not satisfy the active contract.\",\n    severity: \"error\",\n    recoverable: false,\n    modelCorrectable: false,\n    actualSummary: error instanceof Error ? error.name : typeof error,\n  })];\n}\n","import { artifactContracts, type ArtifactContract } from \"@data-elements/core\";\nimport type { Artifact, ArtifactKind } from \"@data-elements/schema\";\nimport { z, type ZodType } from \"zod\";\nimport { assertJsonValue, deepFreeze, hashJson } from \"./canonical\";\nimport { actionContractVersions } from \"./contract-version\";\nimport { compilerDiagnostic, CompilerDiagnosticError } from \"./diagnostics\";\nimport type {\n  CatalogIdentity,\n  CatalogSlice,\n  CompilerExample,\n  JSONSchema,\n  JsonValue,\n  NodeContract,\n  SurfaceProfile,\n} from \"./types\";\n\nconst nodeTypePattern = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)+$/;\nconst contractPathSegmentPattern = /^(?:[^~]|~[01])+$/;\nconst gapSchema = z.enum([\"none\", \"xs\", \"sm\", \"md\", \"lg\", \"xl\"]);\nconst alignSchema = z.enum([\"start\", \"center\", \"end\", \"stretch\"]);\nconst formInputValueSchema = z.union([\n  z.string().max(8_000),\n  z.number().finite(),\n]);\nconst formOptionSchema = z.object({\n  value: z.string().min(1).max(512),\n  label: z.string().min(1).max(512),\n  disabled: z.boolean().optional(),\n}).strict();\n\nfunction propsSchema<T extends z.ZodRawShape>(shape: T) {\n  return z.object(shape).strict() as unknown as ZodType<Record<string, unknown>>;\n}\n\nexport function defineNodeContract<const T extends NodeContract>(contract: T): T {\n  if (!nodeTypePattern.test(contract.type)) {\n    throw new TypeError(\n      `Node type \"${contract.type}\" must be a lowercase namespaced identifier.`,\n    );\n  }\n  if (!Number.isSafeInteger(contract.version) || contract.version < 1) {\n    throw new TypeError(`Node contract \"${contract.type}\" must have a positive version.`);\n  }\n  if (!contract.prompt.summary.trim()) {\n    throw new TypeError(`Node contract \"${contract.type}\" needs a prompt summary.`);\n  }\n  if (contract.prompt.useWhen.length === 0 || contract.prompt.avoidWhen.length === 0) {\n    throw new TypeError(\n      `Node contract \"${contract.type}\" needs positive and negative selection guidance.`,\n    );\n  }\n  for (const [name, slot] of Object.entries(contract.slots)) {\n    if (!name || (slot.min ?? 0) < 0 || (slot.max ?? Number.MAX_SAFE_INTEGER) < (slot.min ?? 0)) {\n      throw new TypeError(`Node contract \"${contract.type}\" has an invalid \"${name}\" slot.`);\n    }\n    if (!slot.accepts?.length && !slot.categories?.length) {\n      throw new TypeError(\n        `Node contract \"${contract.type}\" slot \"${name}\" must constrain accepted children.`,\n      );\n    }\n  }\n  for (const [kind, paths] of Object.entries(contract.bindings ?? {})) {\n    if (new Set(paths).size !== paths.length || paths.some((path) => !isContractPath(path))) {\n      throw new TypeError(`Node contract \"${contract.type}\" has invalid ${kind}.`);\n    }\n    Object.freeze(paths);\n  }\n  for (const [name, event] of Object.entries(contract.events ?? {})) {\n    if (!/^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/.test(name)) {\n      throw new TypeError(`Node contract \"${contract.type}\" has an invalid event port.`);\n    }\n    if (Object.keys(event.actionContracts).length === 0) {\n      throw new TypeError(`Node contract \"${contract.type}\" event \"${name}\" needs an action contract.`);\n    }\n    for (const [contractId, versionRange] of Object.entries(event.actionContracts)) {\n      if (!/^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/.test(contractId)) {\n        throw new TypeError(`Node contract \"${contract.type}\" event \"${name}\" has an invalid action contract id.`);\n      }\n      if (!actionContractVersions(versionRange)) {\n        throw new TypeError(\n          `Node contract \"${contract.type}\" event \"${name}\" has an unsupported action contract range.`,\n        );\n      }\n    }\n    Object.freeze(event.actionContracts);\n    Object.freeze(event);\n  }\n  if (contract.events) Object.freeze(contract.events);\n  if (contract.bindings) Object.freeze(contract.bindings);\n  Object.freeze(contract.prompt);\n  Object.freeze(contract.slots);\n  Object.freeze(contract);\n  return contract;\n}\n\nfunction isContractPath(path: string): boolean {\n  if (!path.startsWith(\"/\")) return false;\n  return path.slice(1).split(\"/\").every((segment) => (\n    segment.length > 0 && contractPathSegmentPattern.test(segment)\n  ));\n}\n\nfunction contractProjection(contract: NodeContract): JsonValue {\n  const props = contract.providerSchema ?? z.toJSONSchema(contract.propsSchema, {\n    target: \"draft-2020-12\", reused: \"inline\",\n  });\n  assertJsonValue(props);\n  const events = Object.fromEntries(\n    Object.entries(contract.events ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(\n      ([name, event]) => {\n        const payload = z.toJSONSchema(event.payloadSchema, {\n          target: \"draft-2020-12\",\n          reused: \"inline\",\n        });\n        assertJsonValue(payload);\n        return [name, {\n          payload,\n          actionContracts: Object.fromEntries(\n            Object.entries(event.actionContracts).sort(([left], [right]) => left.localeCompare(right)),\n          ),\n        }];\n      },\n    ),\n  );\n\n  return {\n    type: contract.type,\n    version: contract.version,\n    category: contract.category,\n    props,\n    slots: contract.slots as unknown as JsonValue,\n    trust: contract.trust,\n    commitPolicy: contract.commitPolicy,\n    prompt: contract.prompt as unknown as JsonValue,\n    profiles: [...contract.profiles].sort(),\n    dependencies: [...(contract.dependencies ?? [])].sort(),\n    maxInstances: contract.maxInstances ?? null,\n    events: events as JsonValue,\n    bindings: (contract.bindings ?? {}) as JsonValue,\n  };\n}\n\nexport class CompilerCatalog {\n  readonly identity: Readonly<CatalogIdentity>;\n  readonly contractFingerprint: string;\n  readonly #contracts: ReadonlyMap<string, NodeContract>;\n\n  constructor(identity: CatalogIdentity, contracts: readonly NodeContract[]) {\n    if (!identity.id.trim() || !identity.version.trim()) {\n      throw new TypeError(\"A compiler catalog needs a stable id and version.\");\n    }\n    const entries = new Map<string, NodeContract>();\n    for (const contract of contracts) {\n      if (entries.has(contract.type)) {\n        throw new TypeError(`Node type \"${contract.type}\" is already registered.`);\n      }\n      entries.set(contract.type, defineNodeContract(contract));\n    }\n    for (const contract of entries.values()) {\n      for (const dependency of contract.dependencies ?? []) {\n        if (!entries.has(dependency)) {\n          throw new TypeError(\n            `Node contract \"${contract.type}\" depends on missing type \"${dependency}\".`,\n          );\n        }\n      }\n    }\n\n    this.identity = deepFreeze({ ...identity });\n    this.#contracts = entries;\n    this.contractFingerprint = hashJson({\n      catalog: this.identity as unknown as JsonValue,\n      contracts: [...entries.values()]\n        .sort((left, right) => left.type.localeCompare(right.type))\n        .map(contractProjection),\n    });\n    Object.freeze(this);\n  }\n\n  has(type: string): boolean {\n    return this.#contracts.has(type);\n  }\n\n  get(type: string): NodeContract | undefined {\n    return this.#contracts.get(type);\n  }\n\n  contracts(): readonly NodeContract[] {\n    return [...this.#contracts.values()].sort((left, right) => left.type.localeCompare(right.type));\n  }\n\n  extend(\n    contracts: readonly NodeContract[],\n    identity: CatalogIdentity = this.identity,\n  ): CompilerCatalog {\n    return new CompilerCatalog(identity, [...this.#contracts.values(), ...contracts]);\n  }\n}\n\nexport function createCompilerCatalog(\n  contracts: readonly NodeContract[],\n  identity: CatalogIdentity = { id: \"data-elements.custom\", version: \"1\" },\n): CompilerCatalog {\n  return new CompilerCatalog(identity, contracts);\n}\n\nconst composableCategories = [\n  \"surface-layout\",\n  \"surface-content\",\n  \"surface-form\",\n  \"semantic-artifact\",\n  \"extension:*\",\n] as const;\n\nexport const surfaceNodeContracts = [\n  defineNodeContract({\n    type: \"layout.stack\",\n    version: 1,\n    category: \"surface-layout\",\n    propsSchema: propsSchema({\n      gap: gapSchema.default(\"md\"),\n      align: alignSchema.default(\"stretch\"),\n    }),\n    slots: {\n      children: {\n        categories: composableCategories,\n        min: 1,\n        max: 32,\n        fallback: \"placeholder\",\n      },\n    },\n    trust: \"safe\",\n    commitPolicy: \"progressive\",\n    prompt: {\n      summary: \"Arrange related nodes vertically with semantic spacing.\",\n      useWhen: [\"The result contains more than one related block.\"],\n      avoidWhen: [\"A single semantic artifact can be the root.\"],\n    },\n    profiles: [\"analysis\", \"report\", \"form\", \"operations\"],\n    searchTerms: [\"stack\", \"layout\", \"section\", \"纵向\", \"布局\"],\n    maxInstances: 16,\n  }),\n  defineNodeContract({\n    type: \"layout.grid\",\n    version: 1,\n    category: \"surface-layout\",\n    propsSchema: propsSchema({\n      columns: z.number().int().min(1).max(4).default(2),\n      gap: gapSchema.default(\"md\"),\n      align: alignSchema.default(\"stretch\"),\n    }),\n    slots: {\n      children: {\n        categories: composableCategories,\n        min: 1,\n        max: 16,\n        fallback: \"placeholder\",\n      },\n    },\n    trust: \"safe\",\n    commitPolicy: \"progressive\",\n    prompt: {\n      summary: \"Arrange comparable nodes in a responsive grid.\",\n      useWhen: [\"Several peers benefit from side-by-side comparison.\"],\n      avoidWhen: [\"Reading order or narrow-screen density would be unclear.\"],\n    },\n    profiles: [\"analysis\", \"report\", \"operations\"],\n    searchTerms: [\"grid\", \"compare\", \"dashboard\", \"网格\", \"对比\"],\n    maxInstances: 8,\n  }),\n  defineNodeContract({\n    type: \"layout.section\",\n    version: 1,\n    category: \"surface-layout\",\n    propsSchema: propsSchema({\n      title: z.string().min(1).max(160).optional(),\n      description: z.string().max(1_000).optional(),\n    }),\n    slots: {\n      children: {\n        categories: composableCategories,\n        min: 1,\n        max: 24,\n        fallback: \"placeholder\",\n      },\n    },\n    trust: \"safe\",\n    commitPolicy: \"progressive\",\n    prompt: {\n      summary: \"Group a named part of a report without controlling visual styling.\",\n      useWhen: [\"A document needs a clear semantic subsection.\"],\n      avoidWhen: [\"The section would contain no meaningful child.\"],\n    },\n    profiles: [\"analysis\", \"report\", \"form\", \"operations\"],\n    searchTerms: [\"section\", \"group\", \"章节\", \"分组\"],\n    maxInstances: 16,\n  }),\n  defineNodeContract({\n    type: \"content.text\",\n    version: 1,\n    category: \"surface-content\",\n    propsSchema: propsSchema({\n      text: z.string().min(1).max(8_000),\n      role: z.enum([\"heading\", \"paragraph\", \"caption\"]).default(\"paragraph\"),\n      tone: z.enum([\"default\", \"muted\", \"positive\", \"warning\", \"critical\"]).default(\"default\"),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"progressive\",\n    prompt: {\n      summary: \"Render bounded plain text with a semantic role.\",\n      useWhen: [\"A short heading, explanation, or caption improves comprehension.\"],\n      avoidWhen: [\"Structured data belongs in a semantic artifact node.\"],\n    },\n    profiles: [\"analysis\", \"report\", \"form\", \"operations\"],\n    searchTerms: [\"text\", \"summary\", \"explain\", \"文本\", \"说明\"],\n    maxInstances: 32,\n  }),\n  defineNodeContract({\n    type: \"content.callout\",\n    version: 1,\n    category: \"surface-content\",\n    propsSchema: propsSchema({\n      title: z.string().min(1).max(160).optional(),\n      body: z.string().min(1).max(2_000),\n      tone: z.enum([\"info\", \"success\", \"warning\", \"critical\"]).default(\"info\"),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"progressive\",\n    prompt: {\n      summary: \"Emphasize a bounded status, warning, or conclusion.\",\n      useWhen: [\"One short message needs distinct semantic emphasis.\"],\n      avoidWhen: [\"The content is ordinary narrative or unsupported alarm.\"],\n    },\n    profiles: [\"analysis\", \"report\", \"form\", \"operations\"],\n    searchTerms: [\"warning\", \"notice\", \"status\", \"提醒\", \"警告\"],\n    maxInstances: 12,\n  }),\n  defineNodeContract({\n    type: \"content.progress\",\n    version: 1,\n    category: \"surface-content\",\n    propsSchema: propsSchema({\n      label: z.string().min(1).max(160),\n      value: z.number().min(0).max(100),\n      detail: z.string().max(500).optional(),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"progressive\",\n    prompt: {\n      summary: \"Show validated completion against a zero-to-one-hundred scale.\",\n      useWhen: [\"A real process or target has a validated completion percentage.\"],\n      avoidWhen: [\"The percentage is an unsupported estimate.\"],\n    },\n    profiles: [\"report\", \"operations\"],\n    searchTerms: [\"progress\", \"completion\", \"进度\", \"完成率\"],\n    maxInstances: 12,\n  }),\n  defineNodeContract({\n    type: \"content.empty\",\n    version: 1,\n    category: \"surface-content\",\n    propsSchema: propsSchema({\n      title: z.string().min(1).max(160),\n      description: z.string().max(1_000).optional(),\n      reason: z.enum([\"no-data\", \"filtered\", \"unavailable\", \"not-applicable\"]).default(\"no-data\"),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"progressive\",\n    prompt: {\n      summary: \"Represent a valid empty or unavailable result explicitly.\",\n      useWhen: [\"A trusted query produced no data or a resource is unavailable.\"],\n      avoidWhen: [\"Generation failed or validation is incomplete.\"],\n    },\n    profiles: [\"analysis\", \"report\", \"form\", \"operations\"],\n    searchTerms: [\"empty\", \"no data\", \"unavailable\", \"空\", \"无数据\"],\n    maxInstances: 8,\n  }),\n  defineNodeContract({\n    type: \"form.root\",\n    version: 1,\n    category: \"surface-form\",\n    propsSchema: propsSchema({\n      title: z.string().min(1).max(160).optional(),\n      description: z.string().max(1_000).optional(),\n    }),\n    slots: {\n      fields: {\n        accepts: [\"form.input\", \"form.select\", \"form.toggle\", \"form.button\"],\n        min: 1,\n        max: 32,\n        fallback: \"placeholder\",\n      },\n    },\n    trust: \"safe\",\n    commitPolicy: \"atomic\",\n    prompt: {\n      summary: \"Collect typed local state through a bounded declarative form.\",\n      useWhen: [\"The user needs to review or change a small set of typed values.\"],\n      avoidWhen: [\"The interaction can execute without explicit user review.\"],\n    },\n    profiles: [\"form\", \"operations\"],\n    searchTerms: [\"form\", \"input\", \"edit\", \"表单\", \"填写\"],\n    dependencies: [\"form.input\", \"form.select\", \"form.toggle\", \"form.button\"],\n    maxInstances: 4,\n    events: {\n      submit: {\n        payloadSchema: z.object({}).strict(),\n        actionContracts: { \"form.submit\": \"^1\" },\n      },\n      reset: {\n        payloadSchema: z.object({}).strict(),\n        actionContracts: { \"form.reset\": \"^1\" },\n      },\n    },\n  }),\n  defineNodeContract({\n    type: \"form.input\",\n    version: 1,\n    category: \"surface-form\",\n    propsSchema: propsSchema({\n      label: z.string().min(1).max(160),\n      inputType: z.enum([\"text\", \"email\", \"number\", \"date\"]).default(\"text\"),\n      value: formInputValueSchema.default(\"\"),\n      placeholder: z.string().max(500).optional(),\n      description: z.string().max(1_000).optional(),\n      required: z.boolean().default(false),\n      disabled: z.boolean().default(false),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"atomic\",\n    prompt: {\n      summary: \"Edit one bounded string or numeric state value.\",\n      useWhen: [\"A form needs a short text, email, number, or date value.\"],\n      avoidWhen: [\"The field is a fixed option set or boolean choice.\"],\n    },\n    profiles: [\"form\", \"operations\"],\n    searchTerms: [\"input\", \"field\", \"text field\", \"输入\", \"字段\"],\n    maxInstances: 24,\n    events: {\n      change: {\n        payloadSchema: z.object({ value: formInputValueSchema }).strict(),\n        actionContracts: { \"form.change\": \"^1\" },\n      },\n    },\n    bindings: {\n      referencePaths: [\"/value\", \"/disabled\"],\n      conditionPaths: [\"/disabled\"],\n    },\n  }),\n  defineNodeContract({\n    type: \"form.select\",\n    version: 1,\n    category: \"surface-form\",\n    propsSchema: propsSchema({\n      label: z.string().min(1).max(160),\n      value: z.string().max(512).default(\"\"),\n      options: z.array(formOptionSchema).max(100).default([]),\n      placeholder: z.string().max(500).optional(),\n      description: z.string().max(1_000).optional(),\n      required: z.boolean().default(false),\n      disabled: z.boolean().default(false),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"atomic\",\n    prompt: {\n      summary: \"Choose one value from a bounded option set.\",\n      useWhen: [\"A typed form value must come from known options.\"],\n      avoidWhen: [\"The option set is unbounded or free-form text is required.\"],\n    },\n    profiles: [\"form\", \"operations\"],\n    searchTerms: [\"select\", \"options\", \"choice\", \"选择\", \"选项\"],\n    maxInstances: 16,\n    events: {\n      change: {\n        payloadSchema: z.object({ value: z.string().max(512) }).strict(),\n        actionContracts: { \"form.change\": \"^1\" },\n      },\n    },\n    bindings: {\n      referencePaths: [\"/value\", \"/options\", \"/disabled\"],\n      conditionPaths: [\"/disabled\"],\n    },\n  }),\n  defineNodeContract({\n    type: \"form.toggle\",\n    version: 1,\n    category: \"surface-form\",\n    propsSchema: propsSchema({\n      label: z.string().min(1).max(160),\n      description: z.string().max(1_000).optional(),\n      checked: z.boolean().default(false),\n      disabled: z.boolean().default(false),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"atomic\",\n    prompt: {\n      summary: \"Edit one explicit boolean state value.\",\n      useWhen: [\"A form needs a binary on or off choice.\"],\n      avoidWhen: [\"The choice has more than two meaningful values.\"],\n    },\n    profiles: [\"form\", \"operations\"],\n    searchTerms: [\"toggle\", \"boolean\", \"switch\", \"开关\", \"布尔\"],\n    maxInstances: 16,\n    events: {\n      change: {\n        payloadSchema: z.object({ checked: z.boolean() }).strict(),\n        actionContracts: { \"form.change\": \"^1\" },\n      },\n    },\n    bindings: {\n      referencePaths: [\"/checked\", \"/disabled\"],\n      conditionPaths: [\"/disabled\"],\n    },\n  }),\n  defineNodeContract({\n    type: \"form.button\",\n    version: 1,\n    category: \"surface-form\",\n    propsSchema: propsSchema({\n      label: z.string().min(1).max(160),\n      type: z.enum([\"button\", \"submit\", \"reset\"]).default(\"button\"),\n      variant: z.enum([\"default\", \"secondary\", \"destructive\"]).default(\"default\"),\n      disabled: z.boolean().default(false),\n    }),\n    slots: {},\n    trust: \"safe\",\n    commitPolicy: \"atomic\",\n    prompt: {\n      summary: \"Trigger a declared form action with an explicit command button.\",\n      useWhen: [\"A form needs an explicit submit, reset, or local action command.\"],\n      avoidWhen: [\"The action is not declared or requires hidden executable behavior.\"],\n    },\n    profiles: [\"form\", \"operations\"],\n    searchTerms: [\"button\", \"submit\", \"reset\", \"按钮\", \"提交\"],\n    maxInstances: 8,\n    events: {\n      press: {\n        payloadSchema: z.object({}).strict(),\n        actionContracts: { \"form.press\": \"^1\" },\n      },\n    },\n    bindings: {\n      referencePaths: [\"/disabled\"],\n      conditionPaths: [\"/disabled\"],\n    },\n  }),\n] as const;\n\nconst artifactProfiles: Record<ArtifactKind, readonly SurfaceProfile[]> = {\n  query: [\"analysis\"],\n  calculator: [\"analysis\"],\n  metric: [\"analysis\", \"report\", \"operations\"],\n  comparison: [\"analysis\", \"report\"],\n  trend: [\"analysis\", \"report\", \"operations\"],\n  anomaly: [\"analysis\", \"operations\"],\n  forecast: [\"analysis\", \"report\", \"operations\"],\n  funnel: [\"analysis\", \"report\", \"operations\"],\n  \"data-quality\": [\"analysis\", \"report\", \"operations\"],\n  insight: [\"analysis\", \"report\", \"operations\"],\n  breakdown: [\"analysis\", \"report\"],\n  distribution: [\"analysis\", \"report\"],\n  cohort: [\"analysis\", \"report\"],\n  experiment: [\"analysis\", \"report\"],\n  driver: [\"analysis\", \"report\"],\n  ranking: [\"analysis\", \"report\"],\n  target: [\"analysis\", \"report\", \"operations\"],\n  timeline: [\"analysis\", \"report\", \"operations\"],\n};\n\nconst artifactSearchTerms: Record<ArtifactKind, readonly string[]> = {\n  query: [\"query\", \"rows\", \"table\", \"sql\", \"查询\", \"明细\"],\n  calculator: [\"calculator\", \"what if\", \"scenario\", \"计算器\", \"假设\"],\n  metric: [\"metric\", \"kpi\", \"number\", \"指标\"],\n  comparison: [\"compare\", \"comparison\", \"versus\", \"比较\", \"对比\"],\n  trend: [\"trend\", \"over time\", \"time series\", \"趋势\", \"变化\"],\n  anomaly: [\"anomaly\", \"unusual\", \"spike\", \"异常\", \"突增\"],\n  forecast: [\"forecast\", \"predict\", \"future\", \"预测\", \"未来\"],\n  funnel: [\"funnel\", \"conversion\", \"drop off\", \"漏斗\", \"转化\"],\n  \"data-quality\": [\"quality\", \"freshness\", \"validity\", \"质量\", \"新鲜度\"],\n  insight: [\"insight\", \"finding\", \"结论\", \"洞察\"],\n  breakdown: [\"breakdown\", \"contribution\", \"segment\", \"构成\", \"贡献\"],\n  distribution: [\"distribution\", \"histogram\", \"spread\", \"分布\", \"直方图\"],\n  cohort: [\"cohort\", \"retention\", \"留存\", \"同期群\"],\n  experiment: [\"experiment\", \"ab test\", \"significance\", \"实验\", \"显著性\"],\n  driver: [\"driver\", \"decomposition\", \"cause\", \"驱动\", \"归因\"],\n  ranking: [\"ranking\", \"leaderboard\", \"top\", \"bottom\", \"排名\", \"排行\"],\n  target: [\"target\", \"goal\", \"progress\", \"on track\", \"目标\", \"进度\"],\n  timeline: [\"timeline\", \"event\", \"milestone\", \"history\", \"时间线\", \"里程碑\"],\n};\n\nfunction semanticProviderSchema(contract: ArtifactContract<Artifact>): JsonValue {\n  const generated = z.toJSONSchema(contract.schema, {\n    target: \"draft-2020-12\",\n    io: \"input\",\n    reused: \"inline\",\n  });\n  assertJsonValue(generated);\n  if (!generated || typeof generated !== \"object\" || Array.isArray(generated)) {\n    throw new TypeError(`Artifact contract \"${contract.kind}\" did not produce an object schema.`);\n  }\n  const schema = JSON.parse(JSON.stringify(generated)) as Record<string, JsonValue>;\n  delete schema.$schema;\n  const properties = schema.properties;\n  if (properties && typeof properties === \"object\" && !Array.isArray(properties)) {\n    delete properties.protocolVersion;\n    delete properties.kind;\n    delete properties.id;\n  }\n  if (Array.isArray(schema.required)) {\n    schema.required = schema.required.filter((key) => (\n      key !== \"protocolVersion\" && key !== \"kind\" && key !== \"id\"\n    ));\n  }\n  schema.additionalProperties = false;\n  schema.description = `Semantic props for artifact.${contract.kind}@${contract.version}. Envelope identity is supplied by the host.`;\n  return schema;\n}\n\nfunction semanticPropsSchema(\n  contract: ArtifactContract<Artifact>,\n): ZodType<Record<string, unknown>> {\n  return z.record(z.string(), z.unknown()).refine(\n    (input) => !(\"protocolVersion\" in input) && !(\"kind\" in input) && !(\"id\" in input),\n    { message: \"Semantic node props must not contain v1 envelope identity fields.\" },\n  ).transform((input) => contract.schema.parse({\n    ...input,\n    protocolVersion: \"1.0\",\n    kind: contract.kind,\n    id: \"semantic-node\",\n  })).transform((artifact) => {\n    const {\n      protocolVersion: _protocolVersion,\n      kind: _kind,\n      id: _id,\n      ...props\n    } = artifact;\n    return props;\n  }) as unknown as ZodType<Record<string, unknown>>;\n}\n\nexport const semanticArtifactContracts: readonly NodeContract[] = artifactContracts.map(\n  (contract) => defineNodeContract({\n    type: `artifact.${contract.kind}`,\n    version: contract.version,\n    category: \"semantic-artifact\",\n    propsSchema: semanticPropsSchema(contract),\n    providerSchema: semanticProviderSchema(contract) as JSONSchema,\n    slots: {},\n    trust: \"governed\",\n    commitPolicy: contract.commitPolicy,\n    prompt: contract.prompt,\n    profiles: artifactProfiles[contract.kind as ArtifactKind],\n    searchTerms: artifactSearchTerms[contract.kind as ArtifactKind],\n    maxInstances: contract.kind === \"metric\" ? 12 : 4,\n    events: Object.fromEntries(Object.entries(contract.eventPorts).map(([name, payloadSchema]) => [\n      name,\n      { payloadSchema, actionContracts: { [name]: \"^1\" } },\n    ])),\n  }),\n);\n\nconst defaultExamples: readonly CompilerExample[] = [\n  {\n    id: \"surface-summary\",\n    profiles: [\"analysis\", \"report\", \"operations\"],\n    nodeTypes: [\"layout.stack\", \"content.text\"],\n    user: \"Summarize the validated result.\",\n    proposal: {\n      root: {\n        id: \"root\",\n        type: \"layout.stack\",\n        props: { gap: \"md\", align: \"stretch\" },\n        slots: {\n          children: [{\n            id: \"summary\",\n            type: \"content.text\",\n            props: { text: \"The validated result is ready.\", role: \"paragraph\", tone: \"default\" },\n          }],\n        },\n      },\n    },\n  },\n  {\n    id: \"metric-report\",\n    profiles: [\"analysis\", \"report\"],\n    nodeTypes: [\"artifact.metric\"],\n    user: \"Show the validated revenue metric.\",\n    proposal: {\n      root: {\n        id: \"revenue\",\n        type: \"artifact.metric\",\n        props: {\n          title: \"Revenue\",\n          description: \"Validated revenue\",\n          metrics: [{ id: \"mrr\", label: \"MRR\", value: 461400, format: \"currency\", currency: \"USD\" }],\n        },\n      },\n    },\n  },\n  {\n    id: \"typed-contact-form\",\n    profiles: [\"form\"],\n    nodeTypes: [\"form.root\", \"form.input\", \"form.button\"],\n    user: \"Let me edit and confirm a contact name.\",\n    proposal: {\n      root: {\n        id: \"contact-form\",\n        type: \"form.root\",\n        props: { title: \"Contact\" },\n        slots: {\n          fields: [\n            {\n              id: \"contact-name\",\n              type: \"form.input\",\n              props: {\n                label: \"Name\",\n                value: { $ref: \"state\", id: \"name\" },\n              },\n              events: { change: \"set-name\" },\n            },\n            {\n              id: \"confirm\",\n              type: \"form.button\",\n              props: { label: \"Confirm\", type: \"submit\" },\n            },\n          ],\n        },\n      },\n      state: {\n        name: { schema: { type: \"string\", maxLength: 160 }, initial: \"\" },\n      },\n      actions: {\n        \"set-name\": {\n          contractId: \"form.change\",\n          steps: [{\n            stepId: \"apply-name\",\n            type: \"state.set\",\n            stateId: \"name\",\n            value: { $ref: \"event\", port: \"change\", path: [\"value\"] },\n          }],\n        },\n      },\n    },\n  },\n];\n\nconst contractsWithExamples = [...surfaceNodeContracts, ...semanticArtifactContracts].map(\n  (contract) => ({\n    ...contract,\n    examples: defaultExamples.filter((example) => example.nodeTypes.includes(contract.type)),\n  }),\n);\n\nexport const defaultCompilerCatalog = new CompilerCatalog(\n  { id: \"data-elements.default\", version: \"2.0\" },\n  contractsWithExamples,\n);\n\nexport type CatalogSliceInput = {\n  catalog?: CompilerCatalog;\n  profile?: SurfaceProfile;\n  requestedNodeTypes?: readonly string[];\n  task?: string;\n  maxNodeTypes?: number;\n};\n\nconst foundationTypes = new Set([\"layout.stack\", \"content.text\", \"content.callout\", \"content.empty\"]);\n\nexport function sliceCatalog(input: CatalogSliceInput = {}): CatalogSlice {\n  const catalog = input.catalog ?? defaultCompilerCatalog;\n  const profile = input.profile ?? \"analysis\";\n  const maxNodeTypes = input.maxNodeTypes ?? 12;\n  if (!Number.isSafeInteger(maxNodeTypes) || maxNodeTypes < 1) {\n    throw new TypeError(\"maxNodeTypes must be a positive integer.\");\n  }\n  const requested = [...new Set(input.requestedNodeTypes ?? [])].sort();\n  const missing = requested.filter((type) => !catalog.has(type));\n  if (missing.length) {\n    throw new CompilerDiagnosticError(missing.map((type) => compilerDiagnostic({\n      phase: \"validate\",\n      code: \"catalog.unknown_node_type\",\n      message: `Node type \"${type}\" is not in the active catalog.`,\n      path: \"/requestedNodeTypes\",\n      hint: \"Choose a node type from the active catalog slice.\",\n    })));\n  }\n\n  const task = (input.task ?? \"\").normalize(\"NFKC\").toLocaleLowerCase(\"en-US\");\n  const scores = new Map<string, number>();\n  const taskScores = new Map<string, number>();\n  for (const contract of catalog.contracts()) {\n    let taskScore = 0;\n    for (const term of contract.searchTerms ?? []) {\n      if (task.includes(term.toLocaleLowerCase(\"en-US\"))) taskScore += 200 + term.length;\n    }\n    if (task.includes(contract.type.toLocaleLowerCase(\"en-US\"))) taskScore += 500;\n    if (taskScore > 0) taskScores.set(contract.type, taskScore);\n  }\n  const hasTaskMatch = taskScores.size > 0;\n  for (const contract of catalog.contracts()) {\n    let score = 0;\n    if (foundationTypes.has(contract.type)) score += 40;\n    if (requested.length) {\n      if (requested.includes(contract.type)) score += 10_000;\n    } else if (hasTaskMatch) {\n      score += taskScores.get(contract.type) ?? 0;\n    } else if (contract.profiles.includes(profile)) {\n      score += 20;\n    }\n    if (score > 0) scores.set(contract.type, score);\n  }\n\n  const selected = new Set<string>();\n  const ranked = catalog.contracts().filter((contract) => scores.has(contract.type)).sort(\n    (left, right) => (scores.get(right.type)! - scores.get(left.type)!) || left.type.localeCompare(right.type),\n  );\n  for (const contract of ranked) {\n    if (selected.size >= maxNodeTypes) break;\n    selected.add(contract.type);\n  }\n\n  const addDependencies = (type: string): void => {\n    const contract = catalog.get(type)!;\n    for (const dependency of [...(contract.dependencies ?? [])].sort()) {\n      if (!selected.has(dependency)) {\n        selected.add(dependency);\n        addDependencies(dependency);\n      }\n    }\n  };\n  for (const type of [...selected]) addDependencies(type);\n\n  if (selected.size > maxNodeTypes || requested.some((type) => !selected.has(type))) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"validate\",\n      code: \"catalog.slice_limit_exceeded\",\n      message: \"The requested node types and their dependencies exceed the catalog slice limit.\",\n      path: \"/requestedNodeTypes\",\n      expected: maxNodeTypes,\n      hint: \"Increase maxNodeTypes or request a smaller surface.\",\n    })]);\n  }\n\n  const contracts = catalog.contracts().filter(({ type }) => selected.has(type));\n  const sliceHash = hashJson({\n    catalog: catalog.identity as unknown as JsonValue,\n    contractFingerprint: catalog.contractFingerprint,\n    nodeTypes: contracts.map(({ type, version }) => `${type}@${version}`),\n  });\n  return Object.freeze({\n    catalog: catalog.identity,\n    contractFingerprint: catalog.contractFingerprint,\n    sliceHash,\n    contracts: Object.freeze([...contracts]),\n  });\n}\n","import { deepFreeze, hashJson } from \"./canonical\";\nimport { compilerDiagnostic, CompilerDiagnosticError } from \"./diagnostics\";\nimport type {\n  DocumentPolicy,\n  InformationFlowLabel,\n  JsonValue,\n  LabeledModelInput,\n  PolicySink,\n} from \"./types\";\n\nconst sensitivityRank = { public: 0, private: 1, sensitive: 2 } as const;\nconst persistenceStrictness = { host: 0, session: 1, none: 2 } as const;\nconst sinkOrder: readonly PolicySink[] = [\n  \"model-generation\",\n  \"renderer\",\n  \"model-repair\",\n  \"export\",\n  \"share\",\n  \"telemetry\",\n];\n\nexport type DocumentPolicyInput = InformationFlowLabel & {\n  policyId: string;\n  policyVersion?: number;\n};\n\nfunction staticPolicyProjection(\n  policy: Omit<DocumentPolicy, \"policyHash\"> | DocumentPolicyInput,\n): JsonValue {\n  return {\n    policyId: policy.policyId,\n    policyVersion: policy.policyVersion ?? 1,\n    scopeRef: policy.scopeRef,\n    sensitivity: policy.sensitivity,\n    persistence: policy.persistence,\n    allowedSinks: [...new Set(policy.allowedSinks)].sort(\n      (left, right) => sinkOrder.indexOf(left) - sinkOrder.indexOf(right),\n    ),\n    ...(policy.expiresAt ? { expiresAt: policy.expiresAt } : {}),\n  };\n}\n\nexport function computeDocumentPolicyHash(\n  policy: Omit<DocumentPolicy, \"policyHash\"> | DocumentPolicyInput,\n): string {\n  return hashJson(staticPolicyProjection(policy));\n}\n\nexport function createDocumentPolicy(input: DocumentPolicyInput): Readonly<DocumentPolicy> {\n  validateLabel(input, \"/documentPolicy\");\n  const policy: DocumentPolicy = {\n    ...input,\n    policyVersion: input.policyVersion ?? 1,\n    allowedSinks: [...new Set(input.allowedSinks)].sort(\n      (left, right) => sinkOrder.indexOf(left) - sinkOrder.indexOf(right),\n    ),\n    policyHash: computeDocumentPolicyHash(input),\n  };\n  return deepFreeze(policy);\n}\n\nexport const DEFAULT_DOCUMENT_POLICY = createDocumentPolicy({\n  policyId: \"data-elements.public-session\",\n  policyVersion: 1,\n  scopeRef: \"public\",\n  sensitivity: \"public\",\n  persistence: \"session\",\n  allowedSinks: [\"model-generation\", \"renderer\", \"model-repair\"],\n});\n\nfunction validateLabel(label: InformationFlowLabel, path: string): void {\n  if (!label.scopeRef.trim()) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"information_flow.empty_scope\",\n      message: \"An information-flow label needs a scope reference.\",\n      path: `${path}/scopeRef`,\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  if (!sinkOrder.includes(label.allowedSinks[0]!) && label.allowedSinks.length > 0) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"information_flow.invalid_sink\",\n      message: \"An information-flow label contains an unknown sink.\",\n      path: `${path}/allowedSinks`,\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  if (label.allowedSinks.some((sink) => !sinkOrder.includes(sink))) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"information_flow.invalid_sink\",\n      message: \"An information-flow label contains an unknown sink.\",\n      path: `${path}/allowedSinks`,\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  if (label.expiresAt !== undefined && !Number.isFinite(Date.parse(label.expiresAt))) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"information_flow.invalid_expiry\",\n      message: \"Information-flow expiry must be an ISO date-time.\",\n      path: `${path}/expiresAt`,\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n}\n\nfunction earliestExpiry(labels: readonly InformationFlowLabel[]): string | undefined {\n  const expiries = labels.flatMap(({ expiresAt }) => expiresAt ? [expiresAt] : []);\n  return expiries.sort((left, right) => Date.parse(left) - Date.parse(right))[0];\n}\n\nexport function joinInformationFlow(\n  labels: readonly InformationFlowLabel[],\n): Readonly<InformationFlowLabel> {\n  if (labels.length === 0) return DEFAULT_DOCUMENT_POLICY;\n  labels.forEach((label, index) => validateLabel(label, `/modelInputs/${index}/label`));\n  const scopes = [...new Set(labels.map(({ scopeRef }) => scopeRef))];\n  if (scopes.length !== 1) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"information_flow.empty_scope_intersection\",\n      message: \"The model inputs do not share an authorized scope.\",\n      path: \"/modelInputs\",\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  const allowedSinks = sinkOrder.filter((sink) => labels.every(\n    (label) => label.allowedSinks.includes(sink),\n  ));\n  if (allowedSinks.length === 0) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"information_flow.empty_sink_intersection\",\n      message: \"The model inputs do not share an allowed information sink.\",\n      path: \"/modelInputs\",\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  const sensitivity = labels.reduce<InformationFlowLabel[\"sensitivity\"]>(\n    (current, label) => sensitivityRank[label.sensitivity] > sensitivityRank[current]\n      ? label.sensitivity\n      : current,\n    \"public\",\n  );\n  const persistence = labels.reduce<InformationFlowLabel[\"persistence\"]>(\n    (current, label) => persistenceStrictness[label.persistence] > persistenceStrictness[current]\n      ? label.persistence\n      : current,\n    \"host\",\n  );\n  const expiresAt = earliestExpiry(labels);\n  return deepFreeze({\n    scopeRef: scopes[0]!,\n    sensitivity,\n    persistence,\n    allowedSinks,\n    ...(expiresAt ? { expiresAt } : {}),\n  });\n}\n\nfunction assertPolicyCanContain(\n  policy: DocumentPolicy,\n  joined: InformationFlowLabel,\n): void {\n  if (policy.policyHash !== computeDocumentPolicyHash(policy)) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"document_policy.hash_mismatch\",\n      message: \"The document policy hash does not match its static policy fields.\",\n      path: \"/documentPolicy/policyHash\",\n      severity: \"fatal\",\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  const expiryTooWide = joined.expiresAt !== undefined\n    && (policy.expiresAt === undefined || Date.parse(policy.expiresAt) > Date.parse(joined.expiresAt));\n  const invalid = policy.scopeRef !== joined.scopeRef\n    || sensitivityRank[policy.sensitivity] < sensitivityRank[joined.sensitivity]\n    || persistenceStrictness[policy.persistence] < persistenceStrictness[joined.persistence]\n    || policy.allowedSinks.some((sink) => !joined.allowedSinks.includes(sink))\n    || expiryTooWide;\n  if (invalid) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"document_policy.weaker_than_inputs\",\n      message: \"The document policy is less restrictive than the joined model inputs.\",\n      path: \"/documentPolicy\",\n      severity: \"fatal\",\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  if (!policy.allowedSinks.includes(\"model-generation\")) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"document_policy.model_generation_denied\",\n      message: \"The document policy does not allow model generation.\",\n      path: \"/documentPolicy/allowedSinks\",\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  if (policy.expiresAt && Date.parse(policy.expiresAt) <= Date.now()) {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"policy\",\n      code: \"document_policy.expired\",\n      message: \"The document policy has expired.\",\n      path: \"/documentPolicy/expiresAt\",\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n}\n\nexport type PreparedInformationFlow = {\n  included: readonly LabeledModelInput[];\n  excluded: readonly LabeledModelInput[];\n  joinedLabel: Readonly<InformationFlowLabel>;\n  generationTaintHash: string;\n};\n\nexport function prepareInformationFlow(\n  inputs: readonly LabeledModelInput[],\n  documentPolicy: DocumentPolicy,\n): Readonly<PreparedInformationFlow> {\n  const provenance = new Set<string>();\n  for (const [index, input] of inputs.entries()) {\n    if (!input.provenanceRef.trim() || provenance.has(input.provenanceRef)) {\n      throw new CompilerDiagnosticError([compilerDiagnostic({\n        phase: \"policy\",\n        code: \"information_flow.invalid_provenance\",\n        message: \"Every labeled model input needs a unique provenance reference.\",\n        path: `/modelInputs/${index}/provenanceRef`,\n        recoverable: false,\n        modelCorrectable: false,\n      })]);\n    }\n    provenance.add(input.provenanceRef);\n    validateLabel(input.label, `/modelInputs/${index}/label`);\n  }\n  const included = inputs.filter(({ label }) => label.allowedSinks.includes(\"model-generation\"));\n  const excluded = inputs.filter(({ label }) => !label.allowedSinks.includes(\"model-generation\"));\n  const joinedLabel = included.length\n    ? joinInformationFlow(included.map(({ label }) => label))\n    : documentPolicy;\n  assertPolicyCanContain(documentPolicy, joinedLabel);\n  const generationTaintHash = hashJson(included\n    .map((input) => ({\n      provenanceRef: input.provenanceRef,\n      kind: input.kind,\n      content: input.content,\n      label: input.label,\n    }))\n    .sort((left, right) => left.provenanceRef.localeCompare(right.provenanceRef)) as JsonValue);\n  return Object.freeze({\n    included: Object.freeze([...included]),\n    excluded: Object.freeze([...excluded]),\n    joinedLabel,\n    generationTaintHash,\n  });\n}\n","import type { AdapterContext, ArtifactPart, NormalizedArtifactProposal } from \"./types\";\n\nconst artifactPartBrand = Symbol(\"data-elements.validated-artifact-part\");\nconst brandedParts = new WeakSet<object>();\n\nexport function createValidatedArtifactPart(\n  snapshot: Readonly<NormalizedArtifactProposal>,\n  context: AdapterContext,\n): ArtifactPart<Readonly<NormalizedArtifactProposal>> {\n  const part = {\n    kind: \"artifact-snapshot\" as const,\n    snapshot,\n    contractFingerprint: context.contractFingerprint,\n    promptBundleHash: context.promptBundleHash,\n    generationTaintHash: context.generationTaintHash,\n  };\n  Object.defineProperty(part, artifactPartBrand, {\n    value: true,\n    enumerable: false,\n    configurable: false,\n    writable: false,\n  });\n  brandedParts.add(part);\n  return Object.freeze(part) as unknown as ArtifactPart<Readonly<NormalizedArtifactProposal>>;\n}\n\nexport function isArtifactPart(value: unknown): value is ArtifactPart {\n  return Boolean(value && typeof value === \"object\" && brandedParts.has(value));\n}\n","import {\n  parseJsonWithSchema,\n  prepareJsonSchema,\n} from \"@data-elements/capability-broker\";\nimport {\n  ARTIFACT_PROTOCOL,\n  ARTIFACT_PROTOCOL_VERSION,\n  artifactDocumentSchema,\n  canonicalHash,\n  claimBindingSchema,\n  decodeArtifactPart,\n  documentPolicySchema,\n  evidenceReferenceSchema,\n  hashArtifactSemanticContent,\n  projectArtifactSemanticContent,\n  resourceReferenceSchema,\n  stateDefinitionSchema,\n  type ArtifactDocument,\n  type ArtifactPart as RuntimeArtifactPart,\n  type ClaimBinding,\n  type EvidenceReference,\n  type ResourceReference,\n  type RuntimeSnapshot,\n  type StateDefinition,\n} from \"@data-elements/runtime\";\nimport { computeDocumentPolicyHash, DEFAULT_DOCUMENT_POLICY } from \"./information-flow\";\nimport { isArtifactPart as isCompilerArtifactPart } from \"./part\";\nimport type {\n  ArtifactPart as CompilerArtifactPart,\n  DocumentPolicy,\n  MaybePromise,\n  NormalizedArtifactProposal,\n  PromptBundle,\n} from \"./types\";\n\nconst DEFAULT_BRANCH_ID = \"main\";\nconst sensitivityRank = { public: 0, private: 1, sensitive: 2 } as const;\nconst persistenceRank = { none: 0, session: 1, host: 2 } as const;\n\nexport type ArtifactUIIdKind =\n  | \"document\"\n  | \"revision\"\n  | \"head-token\"\n  | \"state-revision\"\n  | \"ui-part\";\n\nexport type ArtifactUIHostContext = {\n  branchId?: string;\n  resources?: Readonly<Record<string, ResourceReference>>;\n  evidence?: Readonly<Record<string, EvidenceReference>>;\n};\n\nexport type ArtifactCommitHostContext = ArtifactUIHostContext;\nexport type ArtifactCommitIdKind = ArtifactUIIdKind;\n\ntype CommitBundle = Pick<\n  PromptBundle,\n  \"catalogSlice\" | \"contractFingerprint\" | \"generationTaintHash\" | \"promptBundleHash\" | \"renderMode\"\n>;\n\nexport type ArtifactCommitOptions = ArtifactCommitHostContext & {\n  documentPolicy?: DocumentPolicy;\n  now?: () => string;\n  idFactory?: (kind: ArtifactCommitIdKind, hint?: string) => string;\n  stateDefinition?: (\n    stateId: string,\n    authoring: NormalizedArtifactProposal[\"state\"][string],\n    policy: DocumentPolicy,\n  ) => MaybePromise<StateDefinition>;\n};\n\nexport type MaterializeArtifactPartOptions = ArtifactCommitOptions & {\n  bundle: CommitBundle;\n  documentPolicy: DocumentPolicy;\n};\n\nexport class ArtifactCommitError extends TypeError {\n  readonly code: string;\n\n  constructor(code: string, message: string) {\n    super(message);\n    this.name = \"ArtifactCommitError\";\n    this.code = code;\n  }\n}\n\n/**\n * Crosses the only trusted boundary from a compiler-branded proposal into the\n * runtime document protocol. Transport adapters should never construct runtime\n * snapshots independently.\n */\nexport async function materializeArtifactPart(\n  proposalPart: CompilerArtifactPart,\n  options: MaterializeArtifactPartOptions,\n): Promise<RuntimeArtifactPart> {\n  const { bundle, ...commitOptions } = options;\n  return commitValidatedArtifactProposal(proposalPart, bundle, commitOptions);\n}\n\nexport async function commitValidatedArtifactProposal(\n  proposalPart: CompilerArtifactPart,\n  bundle: CommitBundle,\n  options: ArtifactCommitOptions = {},\n): Promise<RuntimeArtifactPart> {\n  assertMatchingCompilerPart(proposalPart, bundle);\n  const proposal = proposalPart.snapshot;\n  const now = options.now?.() ?? new Date().toISOString();\n  if (!Number.isFinite(Date.parse(now))) {\n    throw new ArtifactCommitError(\"commit.invalid-now\", \"Commit time must be an ISO date-time.\");\n  }\n  const nowMs = Date.parse(now);\n  const documentPolicy = validateDocumentPolicy(options.documentPolicy ?? DEFAULT_DOCUMENT_POLICY, nowMs);\n  const idFactory = options.idFactory ?? defaultArtifactIdFactory;\n  const documentId = idFactory(\"document\", proposal.root);\n  const revisionId = idFactory(\"revision\", documentId);\n  const branchId = options.branchId ?? DEFAULT_BRANCH_ID;\n  const state: Record<string, StateDefinition> = {};\n\n  for (const [stateId, authoring] of Object.entries(proposal.state)) {\n    const resolved = options.stateDefinition\n      ? await options.stateDefinition(stateId, authoring, documentPolicy)\n      : await createLocalStateDefinition(stateId, authoring, documentPolicy);\n    state[stateId] = await validateStateDefinition(stateId, resolved, documentPolicy, nowMs);\n  }\n\n  const resources = selectResources(proposal.resourceIds, options.resources ?? {}, documentPolicy, nowMs);\n  const evidence = selectEvidence(proposal, options.evidence ?? {}, documentPolicy, nowMs);\n  const claims = parseClaims(proposal.claims);\n  const documentBase: ArtifactDocument = artifactDocumentSchema.parse({\n    protocol: ARTIFACT_PROTOCOL,\n    protocolVersion: ARTIFACT_PROTOCOL_VERSION,\n    documentId,\n    revision: {\n      revisionId,\n      parentRevisionIds: [],\n      branchId,\n      sequence: 0,\n      contentHash: \"pending\",\n      contractFingerprint: bundle.contractFingerprint,\n      migrationReceiptIds: [],\n      stateTransitionReceiptIds: [],\n    },\n    policy: documentPolicy,\n    catalog: {\n      ...bundle.catalogSlice.catalog,\n      contractFingerprint: bundle.contractFingerprint,\n    },\n    renderMode: bundle.renderMode,\n    root: proposal.root,\n    nodes: proposal.nodes,\n    state,\n    actions: proposal.actions,\n    resources,\n    evidence,\n    claims,\n    meta: { ...proposal.meta, createdAt: now, updatedAt: now },\n  });\n  const contentHash = await hashArtifactSemanticContent(projectArtifactSemanticContent(documentBase));\n  const document = artifactDocumentSchema.parse({\n    ...documentBase,\n    revision: { ...documentBase.revision, contentHash },\n  });\n  const snapshot: RuntimeSnapshot = {\n    document,\n    branchHead: {\n      branchId,\n      revisionId,\n      headToken: idFactory(\"head-token\", revisionId),\n    },\n    state: await Promise.all(Object.entries(state).map(async ([stateId, definition]) => ({\n      documentId,\n      branchId,\n      stateId,\n      stateRevision: idFactory(\"state-revision\", stateId),\n      schemaId: definition.schemaId,\n      schemaVersion: definition.schemaVersion,\n      schemaHash: definition.schemaHash,\n      policyHash: definition.policy.policyHash,\n      value: definition.initial,\n    }))),\n    pendingActions: [],\n    pendingEffects: [],\n    activeApprovals: [],\n    stateMigrationReceipts: [],\n    stateTransitionReceipts: [],\n  };\n  const decoded = await decodeArtifactPart(\n    { kind: \"artifact-snapshot\", snapshot },\n    { contractFingerprint: bundle.contractFingerprint },\n  );\n  if (!decoded.success) {\n    throw new ArtifactCommitError(\n      \"commit.runtime-validation-failed\",\n      `Runtime artifact validation failed: ${decoded.diagnostics.map(({ code }) => code).join(\", \")}`,\n    );\n  }\n  return decoded.part;\n}\n\nfunction assertMatchingCompilerPart(\n  part: CompilerArtifactPart,\n  bundle: CommitBundle,\n): asserts part is CompilerArtifactPart<Readonly<NormalizedArtifactProposal>> {\n  if (!isCompilerArtifactPart(part)) {\n    throw new ArtifactCommitError(\n      \"commit.untrusted-proposal\",\n      \"Only a locally validated compiler artifact part can be materialized.\",\n    );\n  }\n  if (\n    part.contractFingerprint !== bundle.contractFingerprint\n    || part.promptBundleHash !== bundle.promptBundleHash\n    || part.generationTaintHash !== bundle.generationTaintHash\n  ) {\n    throw new ArtifactCommitError(\n      \"commit.bundle-identity-mismatch\",\n      \"Compiler artifact identity does not match the active prompt bundle.\",\n    );\n  }\n}\n\nasync function createLocalStateDefinition(\n  stateId: string,\n  authoring: NormalizedArtifactProposal[\"state\"][string],\n  documentPolicy: DocumentPolicy,\n): Promise<StateDefinition> {\n  const schemaHash = await canonicalHash(authoring.schema);\n  const policy = {\n    policyId: `data-elements.local-state.${stateId}`,\n    policyVersion: 1,\n    policyHash: \"pending\",\n    scope: \"document\" as const,\n    persistence: documentPolicy.persistence,\n    sensitivity: documentPolicy.sensitivity,\n    modelAccess: \"none\" as const,\n    lifecycle: \"retain\" as const,\n    ...(documentPolicy.expiresAt ? { expiresAt: documentPolicy.expiresAt } : {}),\n  };\n  policy.policyHash = await canonicalHash({\n    policyId: policy.policyId,\n    policyVersion: policy.policyVersion,\n    scope: policy.scope,\n    persistence: policy.persistence,\n    sensitivity: policy.sensitivity,\n    modelAccess: policy.modelAccess,\n    lifecycle: policy.lifecycle,\n    ...(policy.expiresAt ? { expiresAt: policy.expiresAt } : {}),\n  });\n  return stateDefinitionSchema.parse({\n    schemaId: `data-elements.state.${stateId}`,\n    schema: authoring.schema,\n    schemaVersion: 1,\n    schemaHash,\n    initial: authoring.initial,\n    policy,\n  });\n}\n\nasync function validateStateDefinition(\n  stateId: string,\n  input: StateDefinition,\n  documentPolicy: DocumentPolicy,\n  nowMs: number,\n): Promise<StateDefinition> {\n  const definition = stateDefinitionSchema.parse(input);\n  const actualPolicyHash = await canonicalHash({\n    policyId: definition.policy.policyId,\n    policyVersion: definition.policy.policyVersion,\n    scope: definition.policy.scope,\n    persistence: definition.policy.persistence,\n    sensitivity: definition.policy.sensitivity,\n    modelAccess: definition.policy.modelAccess,\n    lifecycle: definition.policy.lifecycle,\n    ...(definition.policy.expiresAt ? { expiresAt: definition.policy.expiresAt } : {}),\n  });\n  if (definition.policy.policyHash !== actualPolicyHash) {\n    throw new ArtifactCommitError(\n      \"commit.state-policy-hash-mismatch\",\n      `State ${stateId} policy hash does not match its static fields.`,\n    );\n  }\n  assertPolicyBoundary(\n    stateId,\n    definition.policy.persistence,\n    definition.policy.sensitivity,\n    definition.policy.expiresAt,\n    documentPolicy,\n    nowMs,\n  );\n  if (definition.policy.modelAccess !== \"none\"\n    && !documentPolicy.allowedSinks.includes(\"model-generation\")) {\n    throw new ArtifactCommitError(\n      \"commit.state-model-access-denied\",\n      `State ${stateId} requests model access outside the document policy.`,\n    );\n  }\n  const prepared = await prepareJsonSchema(definition.schema, definition.schemaHash);\n  return stateDefinitionSchema.parse({\n    ...definition,\n    initial: parseJsonWithSchema(prepared.validator, definition.initial),\n  });\n}\n\nfunction selectResources(\n  ids: readonly string[],\n  available: Readonly<Record<string, ResourceReference>>,\n  documentPolicy: DocumentPolicy,\n  nowMs: number,\n): Record<string, ResourceReference> {\n  return Object.fromEntries([...new Set(ids)].sort().map((id) => {\n    const resource = available[id];\n    if (!resource) {\n      throw new ArtifactCommitError(\"commit.resource-not-granted\", `Resource ${id} is not host-granted.`);\n    }\n    const parsed = resourceReferenceSchema.parse(resource);\n    if (parsed.resourceId !== id) {\n      throw new ArtifactCommitError(\n        \"commit.resource-identity-mismatch\",\n        `Resource ${id} does not match its grant identity.`,\n      );\n    }\n    assertReferenceBoundary(id, parsed, documentPolicy, nowMs, \"resource\");\n    return [id, parsed];\n  }));\n}\n\nfunction selectEvidence(\n  proposal: Readonly<NormalizedArtifactProposal>,\n  available: Readonly<Record<string, EvidenceReference>>,\n  documentPolicy: DocumentPolicy,\n  nowMs: number,\n): Record<string, EvidenceReference> {\n  const ids = new Set(Object.values(proposal.nodes).flatMap((node) => node.evidence ?? []));\n  for (const claim of Object.values(proposal.claims)) {\n    const evidenceIds = isRecord(claim) ? claim.evidenceIds : undefined;\n    if (Array.isArray(evidenceIds)) {\n      for (const id of evidenceIds) if (typeof id === \"string\") ids.add(id);\n    }\n  }\n  return Object.fromEntries([...ids].sort().map((id) => {\n    const evidence = available[id];\n    if (!evidence) {\n      throw new ArtifactCommitError(\"commit.evidence-not-granted\", `Evidence ${id} is not host-granted.`);\n    }\n    const parsed = evidenceReferenceSchema.parse(evidence);\n    if (parsed.evidenceId !== id) {\n      throw new ArtifactCommitError(\n        \"commit.evidence-identity-mismatch\",\n        `Evidence ${id} does not match its grant identity.`,\n      );\n    }\n    assertReferenceBoundary(id, parsed, documentPolicy, nowMs, \"evidence\");\n    return [id, parsed];\n  }));\n}\n\nfunction parseClaims(input: Readonly<Record<string, unknown>>): Record<string, ClaimBinding> {\n  return Object.fromEntries(Object.entries(input).map(([id, claim]) => [\n    id,\n    claimBindingSchema.parse(claim),\n  ]));\n}\n\nexport function toArtifactPartWire(part: RuntimeArtifactPart): import(\"@data-elements/runtime\").ArtifactPartWire {\n  return part.kind === \"artifact-snapshot\"\n    ? { kind: part.kind, snapshot: part.snapshot }\n    : { kind: part.kind, ...(part.base ? { base: part.base } : {}), events: part.events };\n}\n\nexport function mergeArtifactCommitHostContext(\n  base: ArtifactCommitHostContext,\n  turn: ArtifactCommitHostContext,\n): Required<ArtifactCommitHostContext> {\n  return {\n    branchId: turn.branchId ?? base.branchId ?? DEFAULT_BRANCH_ID,\n    resources: { ...base.resources, ...turn.resources },\n    evidence: { ...base.evidence, ...turn.evidence },\n  };\n}\n\nexport function defaultArtifactIdFactory(kind: ArtifactCommitIdKind, hint = \"artifact\"): string {\n  const uuid = globalThis.crypto?.randomUUID?.();\n  if (!uuid) {\n    throw new ArtifactCommitError(\n      \"commit.secure-id-factory-required\",\n      \"A secure idFactory is required when crypto.randomUUID is unavailable.\",\n    );\n  }\n  return `${kind}:${hint.slice(0, 48)}:${uuid}`;\n}\n\nfunction validateDocumentPolicy(input: DocumentPolicy, nowMs: number): DocumentPolicy {\n  const policy = documentPolicySchema.parse(input) as DocumentPolicy;\n  if (policy.policyHash !== computeDocumentPolicyHash(policy)) {\n    throw new ArtifactCommitError(\n      \"commit.document-policy-hash-mismatch\",\n      \"Document policy hash does not match its static fields.\",\n    );\n  }\n  assertNotExpired(policy.expiresAt, nowMs, \"commit.document-policy-expired\", \"Document policy\");\n  return policy;\n}\n\nfunction assertReferenceBoundary(\n  id: string,\n  reference: ResourceReference | EvidenceReference,\n  documentPolicy: DocumentPolicy,\n  nowMs: number,\n  kind: \"resource\" | \"evidence\",\n): void {\n  if (reference.scopeRef !== documentPolicy.scopeRef) {\n    throw new ArtifactCommitError(\n      `commit.${kind}-scope-mismatch`,\n      `${capitalize(kind)} ${id} is outside the document policy scope.`,\n    );\n  }\n  if (sensitivityRank[reference.sensitivity] < sensitivityRank[documentPolicy.sensitivity]) {\n    throw new ArtifactCommitError(\n      `commit.${kind}-sensitivity-lowered`,\n      `${capitalize(kind)} ${id} lowers the document policy sensitivity.`,\n    );\n  }\n  assertExpiryBoundary(id, reference.expiresAt, documentPolicy.expiresAt, nowMs, kind);\n}\n\nfunction assertPolicyBoundary(\n  id: string,\n  persistence: keyof typeof persistenceRank,\n  sensitivity: keyof typeof sensitivityRank,\n  expiresAt: string | undefined,\n  documentPolicy: DocumentPolicy,\n  nowMs: number,\n): void {\n  if (persistenceRank[persistence] > persistenceRank[documentPolicy.persistence]) {\n    throw new ArtifactCommitError(\n      \"commit.state-persistence-broadened\",\n      `State ${id} persists longer than the document policy allows.`,\n    );\n  }\n  if (sensitivityRank[sensitivity] < sensitivityRank[documentPolicy.sensitivity]) {\n    throw new ArtifactCommitError(\n      \"commit.state-sensitivity-lowered\",\n      `State ${id} lowers the document policy sensitivity.`,\n    );\n  }\n  assertExpiryBoundary(id, expiresAt, documentPolicy.expiresAt, nowMs, \"state\");\n}\n\nfunction assertExpiryBoundary(\n  id: string,\n  expiresAt: string | undefined,\n  documentExpiresAt: string | undefined,\n  nowMs: number,\n  kind: \"state\" | \"resource\" | \"evidence\",\n): void {\n  assertNotExpired(expiresAt, nowMs, `commit.${kind}-expired`, `${capitalize(kind)} ${id}`);\n  if (documentExpiresAt !== undefined\n    && (expiresAt === undefined || Date.parse(expiresAt) > Date.parse(documentExpiresAt))) {\n    throw new ArtifactCommitError(\n      `commit.${kind}-expiry-broadened`,\n      `${capitalize(kind)} ${id} outlives the document policy.`,\n    );\n  }\n}\n\nfunction assertNotExpired(\n  expiresAt: string | undefined,\n  nowMs: number,\n  code: string,\n  label: string,\n): void {\n  if (expiresAt !== undefined && Date.parse(expiresAt) <= nowMs) {\n    throw new ArtifactCommitError(code, `${label} has expired.`);\n  }\n}\n\nfunction capitalize(value: string): string {\n  return `${value[0]?.toUpperCase() ?? \"\"}${value.slice(1)}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { z, ZodError, type ZodType } from \"zod\";\nimport { canonicalize, deepFreeze, escapeJsonPointer, utf8Bytes } from \"./canonical\";\nimport { CompilerCatalog } from \"./catalog\";\nimport { matchesActionContractVersion } from \"./contract-version\";\nimport {\n  compilerDiagnostic,\n  CompilerDiagnosticError,\n  diagnosticsFromUnknown,\n} from \"./diagnostics\";\nimport type {\n  ArtifactMeta,\n  ArtifactProposal,\n  ArtifactValue,\n  AuthoringActionPlan,\n  AuthoringActionStep,\n  AuthoringNavigationTarget,\n  AuthoringStateDefinition,\n  AuthoringValue,\n  CatalogSlice,\n  Diagnostic,\n  GenerationLimits,\n  JSONSchema,\n  JsonValue,\n  NodeContract,\n  NormalizedActionPlan,\n  NormalizedActionStep,\n  NormalizedArtifactNode,\n  NormalizedArtifactProposal,\n} from \"./types\";\n\nexport const DEFAULT_GENERATION_LIMITS: Readonly<GenerationLimits> = Object.freeze({\n  maxDocumentBytes: 256_000,\n  maxNodes: 64,\n  maxDepth: 12,\n  maxStringBytes: 16_000,\n  maxCollectionItems: 2_000,\n  maxObjectKeys: 256,\n  maxTotalValues: 20_000,\n  maxNodeTypes: 12,\n  maxExamples: 2,\n  maxRepairFragmentBytes: 32_000,\n  maxRepairAttempts: 1,\n});\n\nconst absoluteLimitCeilings: Readonly<GenerationLimits> = Object.freeze({\n  maxDocumentBytes: 4_000_000,\n  maxNodes: 1_000,\n  maxDepth: 64,\n  maxStringBytes: 1_000_000,\n  maxCollectionItems: 20_000,\n  maxObjectKeys: 4_096,\n  maxTotalValues: 1_000_000,\n  maxNodeTypes: 256,\n  maxExamples: 8,\n  maxRepairFragmentBytes: 128_000,\n  maxRepairAttempts: 3,\n});\n\nconst identifierPattern = /^[A-Za-z][A-Za-z0-9_.:-]{0,127}$/;\nconst forbiddenKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nconst authoringPathSchema = z.array(z.union([\n  z.string().min(1).refine((value) => !forbiddenKeys.has(value)),\n  z.number().int().nonnegative(),\n])).max(64);\nconst propsReferenceSchema = z.union([\n  z.object({\n    $ref: z.enum([\"state\", \"resource\"]),\n    id: z.string().regex(identifierPattern),\n    path: authoringPathSchema.optional(),\n  }).strict(),\n  z.object({\n    $ref: z.literal(\"context\"),\n    key: z.enum([\"locale\", \"timezone\"]),\n  }).strict(),\n]);\nconst presentationConditionSchema = z.object({\n  $condition: z.object({\n    op: z.enum([\"eq\", \"neq\", \"lt\", \"lte\", \"gt\", \"gte\", \"and\", \"or\", \"not\"]),\n    args: z.array(z.unknown()).min(1),\n  }).strict(),\n}).strict();\nconst bindingSchemaCache = new WeakMap<NodeContract, ZodType<Record<string, unknown>>>();\n\nexport function resolveGenerationLimits(\n  overrides: Partial<GenerationLimits> = {},\n): Readonly<GenerationLimits> {\n  const limits = { ...DEFAULT_GENERATION_LIMITS, ...overrides };\n  for (const [name, value] of Object.entries(limits) as [keyof GenerationLimits, number][]) {\n    if (!Number.isSafeInteger(value) || value < 0 || value > absoluteLimitCeilings[name]) {\n      throw new TypeError(\n        `${name} must be an integer between 0 and ${absoluteLimitCeilings[name]}.`,\n      );\n    }\n  }\n  if (limits.maxNodes < 1 || limits.maxDepth < 1 || limits.maxNodeTypes < 1) {\n    throw new TypeError(\"Node, depth, and node-type limits must be positive.\");\n  }\n  return Object.freeze(limits);\n}\n\nexport type NormalizeSurfaceOptions = {\n  catalog?: CompilerCatalog | CatalogSlice;\n  limits?: Partial<GenerationLimits>;\n  allowedResourceIds?: readonly string[];\n  capabilityIds?: readonly string[];\n  messageTemplateIds?: readonly string[];\n};\n\ntype NormalizeContext = {\n  contracts: ReadonlyMap<string, NodeContract>;\n  limits: Readonly<GenerationLimits>;\n  nodes: Record<string, NormalizedArtifactNode>;\n  instanceCounts: Map<string, number>;\n  stateIds: ReadonlySet<string>;\n  resourceIds: ReadonlySet<string>;\n  capabilityIds: ReadonlySet<string>;\n  messageTemplateIds: ReadonlySet<string>;\n};\n\nfunction fail(input: Parameters<typeof compilerDiagnostic>[0]): never {\n  throw new CompilerDiagnosticError([compilerDiagnostic(input)]);\n}\n\nfunction summarize(value: unknown): string {\n  if (value === null) return \"null\";\n  if (Array.isArray(value)) return \"array\";\n  return typeof value;\n}\n\nfunction recordAt(value: unknown, path: string): Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    return fail({\n      phase: \"decode\",\n      code: \"authoring.expected_object\",\n      message: \"Expected an object.\",\n      path,\n      actualSummary: summarize(value),\n    });\n  }\n  const prototype = Object.getPrototypeOf(value);\n  if (prototype !== Object.prototype && prototype !== null) {\n    return fail({\n      phase: \"decode\",\n      code: \"authoring.non_plain_object\",\n      message: \"Authoring input must contain only plain JSON objects.\",\n      path,\n      modelCorrectable: false,\n      actualSummary: Object.prototype.toString.call(value),\n    });\n  }\n  return value as Record<string, unknown>;\n}\n\nfunction rejectUnknownKeys(\n  value: Record<string, unknown>,\n  allowed: ReadonlySet<string>,\n  path: string,\n): void {\n  const unknown = Object.keys(value).filter((key) => !allowed.has(key));\n  if (unknown.length) {\n    fail({\n      phase: \"validate\",\n      code: \"authoring.unknown_field\",\n      message: `Unknown field \"${unknown.sort()[0]}\".`,\n      path: `${path}/${escapeJsonPointer(unknown.sort()[0]!)}`,\n      hint: \"Remove fields that are not declared by the authoring schema.\",\n    });\n  }\n}\n\nfunction stringAt(value: unknown, path: string): string {\n  if (typeof value !== \"string\" || value.length === 0) {\n    return fail({\n      phase: \"decode\",\n      code: \"authoring.expected_string\",\n      message: \"Expected a non-empty string.\",\n      path,\n      actualSummary: summarize(value),\n    });\n  }\n  return value;\n}\n\nfunction identifierAt(value: unknown, path: string): string {\n  const id = stringAt(value, path);\n  if (!identifierPattern.test(id)) {\n    return fail({\n      phase: \"validate\",\n      code: \"authoring.invalid_identifier\",\n      message: \"Identifiers must be stable ASCII names of at most 128 characters.\",\n      path,\n      hint: \"Start with a letter and use letters, numbers, dot, colon, underscore, or hyphen.\",\n    });\n  }\n  return id;\n}\n\nfunction inspectJson(value: unknown, limits: GenerationLimits): asserts value is JsonValue {\n  let totalValues = 0;\n  const ancestors = new Set<object>();\n\n  const visit = (current: unknown, path: string): void => {\n    totalValues += 1;\n    if (totalValues > limits.maxTotalValues) {\n      fail({\n        phase: \"decode\",\n        code: \"limit.total_values_exceeded\",\n        message: \"The artifact contains too many values.\",\n        path,\n        expected: limits.maxTotalValues,\n      });\n    }\n    if (current === null || typeof current === \"boolean\") return;\n    if (typeof current === \"string\") {\n      if (utf8Bytes(current) > limits.maxStringBytes) {\n        fail({\n          phase: \"decode\",\n          code: \"limit.string_bytes_exceeded\",\n          message: \"A string exceeds the configured UTF-8 byte limit.\",\n          path,\n          expected: limits.maxStringBytes,\n        });\n      }\n      return;\n    }\n    if (typeof current === \"number\") {\n      if (!Number.isFinite(current)) {\n        fail({\n          phase: \"decode\",\n          code: \"authoring.non_finite_number\",\n          message: \"Numbers must be finite.\",\n          path,\n        });\n      }\n      return;\n    }\n    if (!current || typeof current !== \"object\") {\n      fail({\n        phase: \"decode\",\n        code: \"authoring.non_json_value\",\n        message: \"The authoring document must contain only JSON values.\",\n        path,\n        modelCorrectable: false,\n        actualSummary: summarize(current),\n      });\n    }\n    if (ancestors.has(current)) {\n      fail({\n        phase: \"decode\",\n        code: \"authoring.cyclic_value\",\n        message: \"The authoring document cannot contain cyclic values.\",\n        path,\n        modelCorrectable: false,\n      });\n    }\n    ancestors.add(current);\n    if (Array.isArray(current)) {\n      if (current.length > limits.maxCollectionItems) {\n        fail({\n          phase: \"decode\",\n          code: \"limit.collection_items_exceeded\",\n          message: \"An array exceeds the configured item limit.\",\n          path,\n          expected: limits.maxCollectionItems,\n        });\n      }\n      current.forEach((item, index) => visit(item, `${path}/${index}`));\n    } else {\n      const object = recordAt(current, path);\n      const keys = Object.keys(object);\n      if (keys.length > limits.maxObjectKeys) {\n        fail({\n          phase: \"decode\",\n          code: \"limit.object_keys_exceeded\",\n          message: \"An object exceeds the configured key limit.\",\n          path,\n          expected: limits.maxObjectKeys,\n        });\n      }\n      for (const key of keys) {\n        if (forbiddenKeys.has(key)) {\n          fail({\n            phase: \"decode\",\n            code: \"authoring.forbidden_object_key\",\n            message: \"The authoring document contains a forbidden object key.\",\n            path: `${path}/${escapeJsonPointer(key)}`,\n            modelCorrectable: false,\n          });\n        }\n        visit(object[key], `${path}/${escapeJsonPointer(key)}`);\n      }\n    }\n    ancestors.delete(current);\n  };\n\n  visit(value, \"\");\n  const bytes = utf8Bytes(canonicalize(value as JsonValue));\n  if (bytes > limits.maxDocumentBytes) {\n    fail({\n      phase: \"decode\",\n      code: \"limit.document_bytes_exceeded\",\n      message: \"The artifact exceeds the configured document byte limit.\",\n      path: \"\",\n      expected: limits.maxDocumentBytes,\n      actualSummary: `${bytes} UTF-8 bytes`,\n    });\n  }\n}\n\nfunction matchesPath(path: string, patterns: readonly string[] | undefined): boolean {\n  return (patterns ?? []).some((pattern) => {\n    const expected = pattern.split(\"/\");\n    const actual = path.split(\"/\");\n    return expected.length === actual.length && expected.every(\n      (segment, index) => segment === \"*\" || segment === actual[index],\n    );\n  });\n}\n\nfunction pathSegments(value: unknown, path: string): (string | number)[] | undefined {\n  if (value === undefined) return undefined;\n  if (!Array.isArray(value)) {\n    return fail({\n      phase: \"normalize\",\n      code: \"reference.invalid_path\",\n      message: \"A reference path must be an array.\",\n      path,\n    });\n  }\n  return value.map((segment, index) => {\n    if (typeof segment === \"string\" && segment.length > 0 && !forbiddenKeys.has(segment)) {\n      return segment;\n    }\n    if (typeof segment === \"number\" && Number.isSafeInteger(segment) && segment >= 0) {\n      return segment;\n    }\n    return fail({\n      phase: \"normalize\",\n      code: \"reference.invalid_path_segment\",\n      message: \"Reference paths accept non-empty property names and non-negative integer indexes.\",\n      path: `${path}/${index}`,\n    });\n  });\n}\n\ntype LowerOptions = {\n  context: NormalizeContext;\n  path: string;\n  bindingPath: string;\n  contract?: NodeContract;\n  allowEventReference: boolean;\n};\n\nfunction lowerValue(value: AuthoringValue, options: LowerOptions): ArtifactValue {\n  if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n    return { kind: \"literal\", value };\n  }\n  if (typeof value === \"number\") {\n    if (!Number.isFinite(value)) {\n      return fail({\n        phase: \"normalize\",\n        code: \"authoring.non_finite_number\",\n        message: \"Numbers must be finite.\",\n        path: options.path,\n      });\n    }\n    return { kind: \"literal\", value };\n  }\n  if (Array.isArray(value)) {\n    return {\n      kind: \"array\",\n      items: value.map((item, index) => lowerValue(item, {\n        ...options,\n        path: `${options.path}/${index}`,\n        bindingPath: `${options.bindingPath}/*`,\n      })),\n    };\n  }\n\n  const object = recordAt(value, options.path);\n  const dollarKeys = Object.keys(object).filter((key) => key.startsWith(\"$\"));\n  if (\"$ref\" in object) {\n    if (\n      dollarKeys.length !== 1\n      || (!options.allowEventReference && !matchesPath(\n        options.bindingPath,\n        options.contract?.bindings?.referencePaths,\n      ))\n    ) {\n      return fail({\n        phase: \"normalize\",\n        code: \"binding.reference_not_allowed\",\n        message: \"This contract field does not allow references.\",\n        path: options.path,\n      });\n    }\n    const ref = stringAt(object.$ref, `${options.path}/$ref`);\n    const path = pathSegments(object.path, `${options.path}/path`);\n    if (ref === \"state\" || ref === \"resource\") {\n      rejectUnknownKeys(object, new Set([\"$ref\", \"id\", \"path\"]), options.path);\n      const id = identifierAt(object.id, `${options.path}/id`);\n      if (ref === \"state\" && !options.context.stateIds.has(id)) {\n        return fail({\n          phase: \"validate\",\n          code: \"reference.unknown_state\",\n          message: `State \"${id}\" is not declared by this proposal.`,\n          path: `${options.path}/id`,\n        });\n      }\n      if (ref === \"resource\" && !options.context.resourceIds.has(id)) {\n        return fail({\n          phase: \"policy\",\n          code: \"reference.resource_not_granted\",\n          message: `Resource \"${id}\" is not in the sealed proposal context.`,\n          path: `${options.path}/id`,\n          recoverable: false,\n          modelCorrectable: false,\n        });\n      }\n      return ref === \"state\"\n        ? { kind: \"state-ref\", stateId: id, ...(path ? { path } : {}) }\n        : { kind: \"resource-ref\", resourceId: id, ...(path ? { path } : {}) };\n    }\n    if (ref === \"event\") {\n      if (!options.allowEventReference) {\n        return fail({\n          phase: \"validate\",\n          code: \"reference.event_outside_action\",\n          message: \"Event references are allowed only inside action plans.\",\n          path: options.path,\n        });\n      }\n      rejectUnknownKeys(object, new Set([\"$ref\", \"port\", \"path\"]), options.path);\n      const port = identifierAt(object.port, `${options.path}/port`);\n      return { kind: \"event-ref\", port, ...(path ? { path } : {}) };\n    }\n    if (ref === \"context\") {\n      rejectUnknownKeys(object, new Set([\"$ref\", \"key\"]), options.path);\n      if (object.key !== \"locale\" && object.key !== \"timezone\") {\n        return fail({\n          phase: \"normalize\",\n          code: \"reference.invalid_context_key\",\n          message: \"Context references are limited to locale and timezone.\",\n          path: `${options.path}/key`,\n        });\n      }\n      return { kind: \"context-ref\", key: object.key };\n    }\n    return fail({\n      phase: \"normalize\",\n      code: \"reference.invalid_kind\",\n      message: `Unknown reference kind \"${ref}\".`,\n      path: `${options.path}/$ref`,\n    });\n  }\n\n  if (\"$condition\" in object) {\n    if (\n      dollarKeys.length !== 1\n      || (!options.allowEventReference && !matchesPath(\n        options.bindingPath,\n        options.contract?.bindings?.conditionPaths,\n      ))\n    ) {\n      return fail({\n        phase: \"normalize\",\n        code: \"binding.condition_not_allowed\",\n        message: \"This contract field does not allow conditions.\",\n        path: options.path,\n      });\n    }\n    rejectUnknownKeys(object, new Set([\"$condition\"]), options.path);\n    const condition = recordAt(object.$condition, `${options.path}/$condition`);\n    rejectUnknownKeys(condition, new Set([\"op\", \"args\"]), `${options.path}/$condition`);\n    const operator = stringAt(condition.op, `${options.path}/$condition/op`);\n    const operators = new Set([\"eq\", \"neq\", \"lt\", \"lte\", \"gt\", \"gte\", \"and\", \"or\", \"not\"]);\n    if (!operators.has(operator) || !Array.isArray(condition.args)) {\n      return fail({\n        phase: \"normalize\",\n        code: \"condition.invalid_shape\",\n        message: \"The condition operator or argument list is invalid.\",\n        path: `${options.path}/$condition`,\n      });\n    }\n    const count = condition.args.length;\n    const validArity = operator === \"not\" ? count === 1\n      : operator === \"and\" || operator === \"or\" ? count >= 2\n      : count === 2;\n    if (!validArity) {\n      return fail({\n        phase: \"validate\",\n        code: \"condition.invalid_arity\",\n        message: `Condition operator \"${operator}\" received the wrong number of arguments.`,\n        path: `${options.path}/$condition/args`,\n      });\n    }\n    if ([\"lt\", \"lte\", \"gt\", \"gte\"].includes(operator)) {\n      for (const [index, item] of condition.args.entries()) {\n        if (typeof item !== \"object\" && typeof item !== \"number\") {\n          return fail({\n            phase: \"validate\",\n            code: \"condition.expected_number\",\n            message: \"Ordered comparisons accept only numbers or numeric references.\",\n            path: `${options.path}/$condition/args/${index}`,\n          });\n        }\n      }\n    }\n    return {\n      kind: \"condition\",\n      op: operator as \"eq\",\n      args: (condition.args as AuthoringValue[]).map((item, index) => lowerValue(item, {\n        ...options,\n        path: `${options.path}/$condition/args/${index}`,\n      })),\n    };\n  }\n\n  if (dollarKeys.length) {\n    return fail({\n      phase: \"normalize\",\n      code: \"authoring.reserved_key\",\n      message: `Unknown reserved authoring key \"${dollarKeys.sort()[0]}\".`,\n      path: `${options.path}/${escapeJsonPointer(dollarKeys.sort()[0]!)}`,\n    });\n  }\n\n  return {\n    kind: \"object\",\n    entries: Object.fromEntries(Object.keys(object).sort().map((key) => [\n      key,\n      lowerValue(object[key] as AuthoringValue, {\n        ...options,\n        path: `${options.path}/${escapeJsonPointer(key)}`,\n        bindingPath: `${options.bindingPath}/${escapeJsonPointer(key)}`,\n      }),\n    ])),\n  };\n}\n\nfunction lowerRecord(\n  value: Record<string, unknown>,\n  context: NormalizeContext,\n  path: string,\n  contract?: NodeContract,\n  allowEventReference = false,\n): Record<string, ArtifactValue> {\n  return Object.fromEntries(Object.keys(value).sort().map((key) => [\n    key,\n    lowerValue(value[key] as AuthoringValue, {\n      context,\n      contract,\n      allowEventReference,\n      path: `${path}/${escapeJsonPointer(key)}`,\n      bindingPath: `/${escapeJsonPointer(key)}`,\n    }),\n  ]));\n}\n\ntype CloneableZod = ZodType & {\n  readonly def: Record<string, unknown> & { type?: string };\n  readonly shape?: Readonly<Record<string, ZodType>>;\n  readonly element?: ZodType;\n  clone(def: Record<string, unknown>): ZodType;\n};\n\nfunction decodeBindingPath(path: string): string[] {\n  return path.slice(1).split(\"/\").map((segment) => (\n    segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\")\n  ));\n}\n\nfunction patchZodBindingPath(\n  schema: ZodType,\n  segments: readonly string[],\n  bindingSchema: ZodType,\n  index = 0,\n): ZodType | undefined {\n  if (index === segments.length) return z.union([schema, bindingSchema]);\n\n  const candidate = schema as CloneableZod;\n  const type = candidate.def.type;\n  if (type === \"object\") {\n    const segment = segments[index]!;\n    if (segment === \"*\") return undefined;\n    const shape = candidate.shape;\n    const property = shape?.[segment];\n    if (!shape || !property) return undefined;\n    const patched = patchZodBindingPath(property, segments, bindingSchema, index + 1);\n    if (!patched) return undefined;\n    return candidate.clone({ ...candidate.def, shape: { ...shape, [segment]: patched } });\n  }\n  if (type === \"array\") {\n    if (segments[index] !== \"*\" || !candidate.element) return undefined;\n    const patched = patchZodBindingPath(candidate.element, segments, bindingSchema, index + 1);\n    if (!patched) return undefined;\n    return candidate.clone({ ...candidate.def, element: patched });\n  }\n  if ([\"optional\", \"nullable\", \"default\", \"prefault\", \"catch\", \"readonly\", \"nonoptional\"].includes(type ?? \"\")) {\n    const innerType = candidate.def.innerType;\n    if (!innerType || typeof innerType !== \"object\") return undefined;\n    const patched = patchZodBindingPath(innerType as ZodType, segments, bindingSchema, index);\n    if (!patched) return undefined;\n    return candidate.clone({ ...candidate.def, innerType: patched });\n  }\n  return undefined;\n}\n\nfunction bindingAwarePropsSchema(contract: NodeContract): ZodType<Record<string, unknown>> {\n  const cached = bindingSchemaCache.get(contract);\n  if (cached) return cached;\n\n  let schema = contract.propsSchema;\n  const bindings = [\n    ...(contract.bindings?.referencePaths ?? []).map((path) => ({ path, schema: propsReferenceSchema })),\n    ...(contract.bindings?.conditionPaths ?? []).map((path) => ({ path, schema: presentationConditionSchema })),\n  ].sort((left, right) => left.path.localeCompare(right.path));\n  for (const binding of bindings) {\n    const patched = patchZodBindingPath(schema, decodeBindingPath(binding.path), binding.schema);\n    if (!patched) {\n      throw new TypeError(\n        `Node contract \"${contract.type}\" binding path \"${binding.path}\" is not present in its props schema.`,\n      );\n    }\n    schema = patched as ZodType<Record<string, unknown>>;\n  }\n  bindingSchemaCache.set(contract, schema);\n  return schema;\n}\n\nfunction assertContractBindingsAllowed(\n  value: unknown,\n  contract: NodeContract,\n  path: string,\n  bindingPath = \"\",\n): void {\n  if (Array.isArray(value)) {\n    value.forEach((item, index) => assertContractBindingsAllowed(\n      item,\n      contract,\n      `${path}/${index}`,\n      `${bindingPath}/*`,\n    ));\n    return;\n  }\n  if (value === null || typeof value !== \"object\") return;\n  const object = value as Record<string, unknown>;\n  if (\"$ref\" in object) {\n    if (!matchesPath(bindingPath, contract.bindings?.referencePaths)) {\n      fail({\n        phase: \"normalize\",\n        code: \"binding.reference_not_allowed\",\n        message: \"This contract field does not allow references.\",\n        path,\n      });\n    }\n    return;\n  }\n  if (\"$condition\" in object) {\n    if (!matchesPath(bindingPath, contract.bindings?.conditionPaths)) {\n      fail({\n        phase: \"normalize\",\n        code: \"binding.condition_not_allowed\",\n        message: \"This contract field does not allow conditions.\",\n        path,\n      });\n    }\n    return;\n  }\n  for (const [key, child] of Object.entries(object)) {\n    assertContractBindingsAllowed(\n      child,\n      contract,\n      `${path}/${escapeJsonPointer(key)}`,\n      `${bindingPath}/${escapeJsonPointer(key)}`,\n    );\n  }\n}\n\nfunction parseContractProps(\n  contract: NodeContract,\n  value: unknown,\n  path: string,\n): Record<string, unknown> {\n  assertContractBindingsAllowed(value, contract, path);\n  try {\n    return bindingAwarePropsSchema(contract).parse(value);\n  } catch (error) {\n    if (!(error instanceof ZodError)) throw error;\n    const diagnostics = error.issues.slice(0, 20).map((issue) => compilerDiagnostic({\n      phase: \"validate\",\n      code: \"node.invalid_props\",\n      message: issue.message,\n      path: `${path}${issue.path.map((segment) => `/${escapeJsonPointer(String(segment))}`).join(\"\")}`,\n      actualSummary: issue.code,\n      hint: `Use the generated props schema for \"${contract.type}@${contract.version}\".`,\n    }));\n    throw new CompilerDiagnosticError(diagnostics);\n  }\n}\n\nfunction contractMap(catalog: CompilerCatalog | CatalogSlice | undefined): ReadonlyMap<string, NodeContract> {\n  const contracts = catalog instanceof CompilerCatalog\n    ? catalog.contracts()\n    : catalog?.contracts ?? [];\n  return new Map(contracts.map((contract) => [contract.type, contract]));\n}\n\nfunction normalizeStates(\n  raw: unknown,\n): Record<string, AuthoringStateDefinition> {\n  if (raw === undefined) return {};\n  const states = recordAt(raw, \"/state\");\n  return Object.fromEntries(Object.keys(states).sort().map((stateId) => {\n    identifierAt(stateId, `/state/${escapeJsonPointer(stateId)}`);\n    const state = recordAt(states[stateId], `/state/${escapeJsonPointer(stateId)}`);\n    rejectUnknownKeys(state, new Set([\"schema\", \"initial\"]), `/state/${escapeJsonPointer(stateId)}`);\n    const schema = recordAt(state.schema, `/state/${escapeJsonPointer(stateId)}/schema`);\n    const initial = state.initial as JsonValue;\n    rejectReservedPlainKeys(initial, `/state/${escapeJsonPointer(stateId)}/initial`);\n    return [stateId, {\n      schema: cloneJson(schema as unknown as JsonValue) as AuthoringStateDefinition[\"schema\"],\n      initial: cloneJson(initial),\n    }];\n  }));\n}\n\nfunction rejectReservedPlainKeys(value: JsonValue, path: string): void {\n  if (!value || typeof value !== \"object\") return;\n  if (Array.isArray(value)) {\n    value.forEach((item, index) => rejectReservedPlainKeys(item, `${path}/${index}`));\n    return;\n  }\n  for (const [key, child] of Object.entries(value)) {\n    if (key.startsWith(\"$\")) {\n      fail({\n        phase: \"normalize\",\n        code: \"authoring.reserved_key\",\n        message: `Reserved key \"${key}\" is not allowed in a literal value.`,\n        path: `${path}/${escapeJsonPointer(key)}`,\n      });\n    }\n    rejectReservedPlainKeys(child, `${path}/${escapeJsonPointer(key)}`);\n  }\n}\n\nfunction cloneJson<T extends JsonValue>(value: T): T {\n  return JSON.parse(canonicalize(value)) as T;\n}\n\nfunction normalizeActionStep(\n  raw: unknown,\n  path: string,\n  context: NormalizeContext,\n): NormalizedActionStep {\n  const step = recordAt(raw, path);\n  const stepId = identifierAt(step.stepId, `${path}/stepId`);\n  const type = stringAt(step.type, `${path}/type`) as AuthoringActionStep[\"type\"];\n  const common = { stepId, type };\n\n  if (type === \"state.set\") {\n    rejectUnknownKeys(step, new Set([\"stepId\", \"type\", \"stateId\", \"value\"]), path);\n    const stateId = identifierAt(step.stateId, `${path}/stateId`);\n    if (!context.stateIds.has(stateId)) {\n      return fail({\n        phase: \"validate\",\n        code: \"action.unknown_state\",\n        message: `State \"${stateId}\" is not declared.`,\n        path: `${path}/stateId`,\n      });\n    }\n    return {\n      ...common,\n      type,\n      stateId,\n      value: lowerValue(step.value as AuthoringValue, {\n        context,\n        allowEventReference: true,\n        path: `${path}/value`,\n        bindingPath: \"/value\",\n      }),\n    };\n  }\n  if (type === \"state.reset\") {\n    rejectUnknownKeys(step, new Set([\"stepId\", \"type\", \"stateIds\"]), path);\n    if (!Array.isArray(step.stateIds) || step.stateIds.length === 0) {\n      return fail({\n        phase: \"validate\",\n        code: \"action.invalid_state_reset\",\n        message: \"state.reset requires at least one state id.\",\n        path: `${path}/stateIds`,\n      });\n    }\n    const stateIds = step.stateIds.map((id, index) => identifierAt(id, `${path}/stateIds/${index}`));\n    if (stateIds.some((id) => !context.stateIds.has(id))) {\n      return fail({\n        phase: \"validate\",\n        code: \"action.unknown_state\",\n        message: \"state.reset references an undeclared state.\",\n        path: `${path}/stateIds`,\n      });\n    }\n    return { ...common, type, stateIds };\n  }\n  if (type === \"node.focus\") {\n    rejectUnknownKeys(step, new Set([\"stepId\", \"type\", \"nodeId\"]), path);\n    return { ...common, type, nodeId: identifierAt(step.nodeId, `${path}/nodeId`) };\n  }\n  if (type === \"agent.message\") {\n    rejectUnknownKeys(step, new Set([\"stepId\", \"type\", \"templateGrantId\", \"values\"]), path);\n    const templateGrantId = identifierAt(step.templateGrantId, `${path}/templateGrantId`);\n    if (!context.messageTemplateIds.has(templateGrantId)) {\n      return fail({\n        phase: \"policy\",\n        code: \"action.message_template_not_granted\",\n        message: \"The message template is not in the sealed proposal context.\",\n        path: `${path}/templateGrantId`,\n        recoverable: false,\n        modelCorrectable: false,\n      });\n    }\n    return {\n      ...common,\n      type,\n      templateGrantId,\n      values: lowerRecord(recordAt(step.values ?? {}, `${path}/values`), context, `${path}/values`, undefined, true),\n    };\n  }\n  if (type === \"capability.request\") {\n    rejectUnknownKeys(step, new Set([\"stepId\", \"type\", \"capabilityId\", \"input\"]), path);\n    const capabilityId = identifierAt(step.capabilityId, `${path}/capabilityId`);\n    assertCapability(context, capabilityId, `${path}/capabilityId`);\n    return {\n      ...common,\n      type,\n      capabilityId,\n      input: lowerRecord(recordAt(step.input, `${path}/input`), context, `${path}/input`, undefined, true),\n    };\n  }\n  if (type === \"navigation.request\") {\n    rejectUnknownKeys(step, new Set([\"stepId\", \"type\", \"target\"]), path);\n    return {\n      ...common,\n      type,\n      target: normalizeNavigationTarget(step.target as AuthoringNavigationTarget, `${path}/target`, context),\n    };\n  }\n  return fail({\n    phase: \"validate\",\n    code: \"action.unknown_step_type\",\n    message: `Unknown action step type \"${String(type)}\".`,\n    path: `${path}/type`,\n  });\n}\n\nfunction assertCapability(context: NormalizeContext, id: string, path: string): void {\n  if (!context.capabilityIds.has(id)) {\n    fail({\n      phase: \"policy\",\n      code: \"action.capability_not_granted\",\n      message: \"The capability is not in the sealed proposal context.\",\n      path,\n      recoverable: false,\n      modelCorrectable: false,\n    });\n  }\n}\n\nfunction normalizeNavigationTarget(\n  raw: AuthoringNavigationTarget,\n  path: string,\n  context: NormalizeContext,\n): Extract<NormalizedActionStep, { type: \"navigation.request\" }>[\"target\"] {\n  const target = recordAt(raw, path);\n  const kind = stringAt(target.kind, `${path}/kind`);\n  const capabilityId = identifierAt(target.capabilityId, `${path}/capabilityId`);\n  assertCapability(context, capabilityId, `${path}/capabilityId`);\n  if (kind === \"route\") {\n    rejectUnknownKeys(target, new Set([\"kind\", \"capabilityId\", \"routeId\", \"params\"]), path);\n    return {\n      kind,\n      capabilityId,\n      routeId: identifierAt(target.routeId, `${path}/routeId`),\n      params: lowerRecord(recordAt(target.params ?? {}, `${path}/params`), context, `${path}/params`, undefined, true),\n    };\n  }\n  if (kind === \"resource\") {\n    rejectUnknownKeys(target, new Set([\"kind\", \"capabilityId\", \"resourceId\"]), path);\n    const resourceId = identifierAt(target.resourceId, `${path}/resourceId`);\n    if (!context.resourceIds.has(resourceId)) {\n      return fail({\n        phase: \"policy\",\n        code: \"reference.resource_not_granted\",\n        message: \"The navigation target resource is not in the sealed context.\",\n        path: `${path}/resourceId`,\n        recoverable: false,\n        modelCorrectable: false,\n      });\n    }\n    return { kind, capabilityId, resourceId };\n  }\n  if (kind === \"external\") {\n    rejectUnknownKeys(target, new Set([\"kind\", \"capabilityId\", \"input\"]), path);\n    return {\n      kind,\n      capabilityId,\n      input: lowerRecord(recordAt(target.input, `${path}/input`), context, `${path}/input`, undefined, true),\n    };\n  }\n  return fail({\n    phase: \"validate\",\n    code: \"action.invalid_navigation_target\",\n    message: \"Unknown navigation target kind.\",\n    path: `${path}/kind`,\n  });\n}\n\nfunction normalizeActions(raw: unknown, context: NormalizeContext): Record<string, NormalizedActionPlan> {\n  if (raw === undefined) return {};\n  const actions = recordAt(raw, \"/actions\");\n  return Object.fromEntries(Object.keys(actions).sort().map((actionId) => {\n    identifierAt(actionId, `/actions/${escapeJsonPointer(actionId)}`);\n    const path = `/actions/${escapeJsonPointer(actionId)}`;\n    const action = recordAt(actions[actionId], path) as AuthoringActionPlan & Record<string, unknown>;\n    rejectUnknownKeys(action, new Set([\"contractId\", \"contractVersion\", \"steps\", \"onError\"]), path);\n    const contractId = identifierAt(action.contractId, `${path}/contractId`);\n    const contractVersion = action.contractVersion ?? 1;\n    if (!Number.isSafeInteger(contractVersion) || contractVersion < 1) {\n      return fail({\n        phase: \"validate\",\n        code: \"action.invalid_contract_version\",\n        message: \"Action contract versions must be positive integers.\",\n        path: `${path}/contractVersion`,\n      });\n    }\n    if (!Array.isArray(action.steps) || action.steps.length === 0) {\n      return fail({\n        phase: \"validate\",\n        code: \"action.empty_plan\",\n        message: \"An action plan needs at least one step.\",\n        path: `${path}/steps`,\n      });\n    }\n    const steps = action.steps.map((step, index) => normalizeActionStep(step, `${path}/steps/${index}`, context));\n    const stepIds = new Set<string>();\n    for (const step of steps) {\n      if (stepIds.has(step.stepId)) {\n        return fail({\n          phase: \"validate\",\n          code: \"action.duplicate_step_id\",\n          message: `Step id \"${step.stepId}\" is duplicated in one action plan.`,\n          path: `${path}/steps`,\n        });\n      }\n      stepIds.add(step.stepId);\n    }\n    if (action.onError !== undefined && action.onError !== \"halt\" && action.onError !== \"continue\") {\n      return fail({\n        phase: \"validate\",\n        code: \"action.invalid_error_policy\",\n        message: \"onError must be halt or continue.\",\n        path: `${path}/onError`,\n      });\n    }\n    return [actionId, {\n      contractId,\n      contractVersion,\n      steps,\n      onError: action.onError ?? \"halt\",\n    }];\n  }));\n}\n\nfunction slotAccepts(parent: NodeContract, slotName: string, child: NodeContract): boolean {\n  const slot = parent.slots[slotName]!;\n  return Boolean(\n    slot.accepts?.includes(child.type)\n    || slot.categories?.includes(child.category)\n    || (child.category.startsWith(\"extension:\") && slot.categories?.includes(\"extension:*\")),\n  );\n}\n\nfunction normalizeNode(\n  raw: unknown,\n  path: string,\n  depth: number,\n  context: NormalizeContext,\n): string {\n  if (depth > context.limits.maxDepth) {\n    return fail({\n      phase: \"normalize\",\n      code: \"limit.node_depth_exceeded\",\n      message: \"The nested surface exceeds the configured depth limit.\",\n      path,\n      expected: context.limits.maxDepth,\n    });\n  }\n  const node = recordAt(raw, path);\n  rejectUnknownKeys(node, new Set([\"id\", \"type\", \"typeVersion\", \"props\", \"slots\", \"events\", \"evidence\"]), path);\n  const id = identifierAt(node.id, `${path}/id`);\n  if (context.nodes[id]) {\n    return fail({\n      phase: \"normalize\",\n      code: \"node.duplicate_id\",\n      message: `Node id \"${id}\" is duplicated.`,\n      path: `${path}/id`,\n    });\n  }\n  if (Object.keys(context.nodes).length >= context.limits.maxNodes) {\n    return fail({\n      phase: \"normalize\",\n      code: \"limit.node_count_exceeded\",\n      message: \"The surface exceeds the configured node limit.\",\n      path,\n      expected: context.limits.maxNodes,\n    });\n  }\n  const type = stringAt(node.type, `${path}/type`);\n  const contract = context.contracts.get(type);\n  if (!contract) {\n    return fail({\n      phase: \"validate\",\n      code: \"catalog.node_not_in_slice\",\n      message: `Node type \"${type}\" is not in the active catalog slice.`,\n      path: `${path}/type`,\n      hint: \"Choose a type from the provider schema for this turn.\",\n    });\n  }\n  const typeVersion = node.typeVersion ?? contract.version;\n  if (typeVersion !== contract.version) {\n    return fail({\n      phase: \"validate\",\n      code: \"catalog.node_version_mismatch\",\n      message: `Node type \"${type}\" requires version ${contract.version}.`,\n      path: `${path}/typeVersion`,\n      expected: contract.version,\n    });\n  }\n  const count = (context.instanceCounts.get(type) ?? 0) + 1;\n  if (contract.maxInstances !== undefined && count > contract.maxInstances) {\n    return fail({\n      phase: \"validate\",\n      code: \"limit.node_instances_exceeded\",\n      message: `Node type \"${type}\" exceeds its instance limit.`,\n      path,\n      expected: contract.maxInstances,\n    });\n  }\n  context.instanceCounts.set(type, count);\n\n  const parsedProps = parseContractProps(contract, node.props ?? {}, `${path}/props`);\n  const normalized: NormalizedArtifactNode = {\n    type,\n    typeVersion,\n    props: lowerRecord(parsedProps, context, `${path}/props`, contract),\n  };\n  context.nodes[id] = normalized;\n\n  const rawSlots = node.slots === undefined ? {} : recordAt(node.slots, `${path}/slots`);\n  const unknownSlots = Object.keys(rawSlots).filter((name) => !contract.slots[name]);\n  if (unknownSlots.length) {\n    return fail({\n      phase: \"validate\",\n      code: \"slot.unknown\",\n      message: `Slot \"${unknownSlots.sort()[0]}\" is not declared by \"${type}\".`,\n      path: `${path}/slots/${escapeJsonPointer(unknownSlots.sort()[0]!)}`,\n    });\n  }\n  const slots: Record<string, string[]> = {};\n  for (const [slotName, slotContract] of Object.entries(contract.slots).sort(([left], [right]) => left.localeCompare(right))) {\n    const children = rawSlots[slotName] ?? [];\n    if (!Array.isArray(children)) {\n      return fail({\n        phase: \"validate\",\n        code: \"slot.expected_array\",\n        message: `Slot \"${slotName}\" must be an array of nested nodes.`,\n        path: `${path}/slots/${escapeJsonPointer(slotName)}`,\n      });\n    }\n    if (children.length < (slotContract.min ?? 0) || children.length > (slotContract.max ?? Number.MAX_SAFE_INTEGER)) {\n      return fail({\n        phase: \"validate\",\n        code: \"slot.cardinality\",\n        message: `Slot \"${slotName}\" has an invalid number of children.`,\n        path: `${path}/slots/${escapeJsonPointer(slotName)}`,\n        expected: { min: slotContract.min ?? 0, max: slotContract.max ?? null },\n      });\n    }\n    const childIds = children.map((child, index) => {\n      const childPath = `${path}/slots/${escapeJsonPointer(slotName)}/${index}`;\n      const childRecord = recordAt(child, childPath);\n      const childType = stringAt(childRecord.type, `${childPath}/type`);\n      const childContract = context.contracts.get(childType);\n      if (!childContract || !slotAccepts(contract, slotName, childContract)) {\n        return fail({\n          phase: \"validate\",\n          code: \"slot.child_not_allowed\",\n          message: `Node type \"${childType}\" is not allowed in \"${type}.${slotName}\".`,\n          path: `${childPath}/type`,\n        });\n      }\n      return normalizeNode(child, childPath, depth + 1, context);\n    });\n    if (childIds.length) slots[slotName] = childIds;\n  }\n  if (Object.keys(slots).length) normalized.slots = slots;\n\n  if (node.events !== undefined) {\n    const events = recordAt(node.events, `${path}/events`);\n    const normalizedEvents: Record<string, string> = {};\n    for (const port of Object.keys(events).sort()) {\n      if (!contract.events?.[port]) {\n        return fail({\n          phase: \"validate\",\n          code: \"event.unknown_port\",\n          message: `Event port \"${port}\" is not declared by \"${type}\".`,\n          path: `${path}/events/${escapeJsonPointer(port)}`,\n        });\n      }\n      normalizedEvents[port] = identifierAt(events[port], `${path}/events/${escapeJsonPointer(port)}`);\n    }\n    if (Object.keys(normalizedEvents).length) normalized.events = normalizedEvents;\n  }\n\n  if (node.evidence !== undefined) {\n    if (!Array.isArray(node.evidence)) {\n      return fail({\n        phase: \"validate\",\n        code: \"evidence.expected_array\",\n        message: \"Evidence bindings must be an array of ids.\",\n        path: `${path}/evidence`,\n      });\n    }\n    const evidence = node.evidence.map((value, index) => identifierAt(value, `${path}/evidence/${index}`));\n    if (new Set(evidence).size !== evidence.length) {\n      return fail({\n        phase: \"validate\",\n        code: \"evidence.duplicate_id\",\n        message: \"A node cannot bind the same evidence more than once.\",\n        path: `${path}/evidence`,\n      });\n    }\n    if (evidence.length) normalized.evidence = evidence;\n  }\n  return id;\n}\n\nfunction validateActionReferences(\n  nodes: Record<string, NormalizedArtifactNode>,\n  actions: Record<string, NormalizedActionPlan>,\n  contracts: ReadonlyMap<string, NodeContract>,\n): void {\n  const boundActions = new Set<string>();\n  for (const [nodeId, node] of Object.entries(nodes)) {\n    for (const [port, actionId] of Object.entries(node.events ?? {})) {\n      const action = actions[actionId];\n      if (!action) {\n        fail({\n          phase: \"validate\",\n          code: \"event.unknown_action\",\n          message: `Event \"${nodeId}.${port}\" references undeclared action \"${actionId}\".`,\n          path: `/nodes/${escapeJsonPointer(nodeId)}/events/${escapeJsonPointer(port)}`,\n        });\n      }\n      boundActions.add(actionId);\n      const eventContract = contracts.get(node.type)?.events?.[port];\n      if (!eventContract) {\n        fail({\n          phase: \"validate\",\n          code: \"event.unknown_port\",\n          message: `Event port \"${port}\" is not declared by \"${node.type}\".`,\n          path: `/nodes/${escapeJsonPointer(nodeId)}/events/${escapeJsonPointer(port)}`,\n        });\n      }\n      const versionRange = eventContract.actionContracts[action.contractId];\n      if (!versionRange) {\n        fail({\n          phase: \"validate\",\n          code: \"event.action_contract_not_allowed\",\n          message: `Event \"${nodeId}.${port}\" does not accept action contract \"${action.contractId}\".`,\n          path: `/actions/${escapeJsonPointer(actionId)}/contractId`,\n        });\n      }\n      if (!matchesActionContractVersion(action.contractVersion, versionRange)) {\n        fail({\n          phase: \"validate\",\n          code: \"event.action_contract_version_mismatch\",\n          message: `Event \"${nodeId}.${port}\" does not accept action contract version ${action.contractVersion}.`,\n          path: `/actions/${escapeJsonPointer(actionId)}/contractVersion`,\n        });\n      }\n      visitActionEventReferences(actionId, action, (reference, path) => {\n        if (reference.port !== port) {\n          fail({\n            phase: \"validate\",\n            code: \"event.reference_port_mismatch\",\n            message: `Action \"${actionId}\" must reference its bound event port \"${port}\".`,\n            path: `${path}/port`,\n          });\n        }\n        if (!eventPayloadPathExists(eventContract.payloadSchema, reference.path ?? [])) {\n          fail({\n            phase: \"validate\",\n            code: \"event.reference_path_not_found\",\n            message: `Event payload path is not declared by \"${node.type}.${port}\".`,\n            path: `${path}/path`,\n          });\n        }\n      });\n    }\n  }\n  for (const [actionId, action] of Object.entries(actions)) {\n    for (const [index, step] of action.steps.entries()) {\n      if (step.type === \"node.focus\" && !nodes[step.nodeId]) {\n        fail({\n          phase: \"validate\",\n          code: \"action.unknown_node\",\n          message: `Action \"${actionId}\" focuses undeclared node \"${step.nodeId}\".`,\n          path: `/actions/${escapeJsonPointer(actionId)}/steps/${index}/nodeId`,\n        });\n      }\n    }\n    if (!boundActions.has(actionId)) {\n      visitActionEventReferences(actionId, action, (_reference, path) => {\n        fail({\n          phase: \"validate\",\n          code: \"event.reference_unbound_action\",\n          message: `Action \"${actionId}\" cannot read an event payload unless a node binds it.`,\n          path,\n        });\n      });\n    }\n  }\n}\n\nfunction visitActionEventReferences(\n  actionId: string,\n  action: NormalizedActionPlan,\n  visit: (reference: Extract<ArtifactValue, { kind: \"event-ref\" }>, path: string) => void,\n): void {\n  const actionPath = `/actions/${escapeJsonPointer(actionId)}`;\n  for (const [index, step] of action.steps.entries()) {\n    const path = `${actionPath}/steps/${index}`;\n    if (step.type === \"state.set\") {\n      visitEventReferences(step.value, `${path}/value`, visit);\n    } else if (step.type === \"agent.message\") {\n      for (const [key, value] of Object.entries(step.values)) {\n        visitEventReferences(value, `${path}/values/${escapeJsonPointer(key)}`, visit);\n      }\n    } else if (step.type === \"capability.request\") {\n      for (const [key, value] of Object.entries(step.input)) {\n        visitEventReferences(value, `${path}/input/${escapeJsonPointer(key)}`, visit);\n      }\n    } else if (step.type === \"navigation.request\") {\n      const values = step.target.kind === \"route\"\n        ? step.target.params\n        : step.target.kind === \"external\" ? step.target.input : undefined;\n      for (const [key, value] of Object.entries(values ?? {})) {\n        visitEventReferences(value, `${path}/target/${step.target.kind === \"route\" ? \"params\" : \"input\"}/${escapeJsonPointer(key)}`, visit);\n      }\n    }\n  }\n}\n\nfunction visitEventReferences(\n  value: ArtifactValue,\n  path: string,\n  visit: (reference: Extract<ArtifactValue, { kind: \"event-ref\" }>, path: string) => void,\n): void {\n  if (value.kind === \"event-ref\") {\n    visit(value, path);\n  } else if (value.kind === \"array\") {\n    value.items.forEach((item, index) => visitEventReferences(item, `${path}/${index}`, visit));\n  } else if (value.kind === \"object\") {\n    for (const [key, item] of Object.entries(value.entries)) {\n      visitEventReferences(item, `${path}/${escapeJsonPointer(key)}`, visit);\n    }\n  } else if (value.kind === \"condition\") {\n    value.args.forEach((item, index) => visitEventReferences(item, `${path}/args/${index}`, visit));\n  }\n}\n\nfunction eventPayloadPathExists(payloadSchema: ZodType<unknown>, path: readonly (string | number)[]): boolean {\n  const schema = z.toJSONSchema(payloadSchema, {\n    target: \"draft-2020-12\",\n    reused: \"inline\",\n  }) as unknown as JSONSchema;\n  return jsonSchemaPathExists(schema, path, schema, new Set());\n}\n\nfunction jsonSchemaPathExists(\n  schema: JSONSchema,\n  path: readonly (string | number)[],\n  root: JSONSchema,\n  seenRefs: Set<string>,\n): boolean {\n  if (path.length === 0) return true;\n  if (typeof schema.$ref === \"string\" && schema.$ref.startsWith(\"#/$defs/\")) {\n    if (seenRefs.has(schema.$ref)) return false;\n    const key = schema.$ref.slice(\"#/$defs/\".length).replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\");\n    const definitions = root.$defs;\n    if (!definitions || typeof definitions !== \"object\" || Array.isArray(definitions)) return false;\n    const target = definitions[key];\n    if (!target || typeof target !== \"object\" || Array.isArray(target)) return false;\n    const nextSeen = new Set(seenRefs);\n    nextSeen.add(schema.$ref);\n    return jsonSchemaPathExists(target as JSONSchema, path, root, nextSeen);\n  }\n\n  for (const keyword of [\"oneOf\", \"anyOf\"] as const) {\n    const branches = schema[keyword];\n    if (Array.isArray(branches) && branches.length > 0) {\n      return branches.every((branch) => (\n        branch !== null && typeof branch === \"object\" && !Array.isArray(branch)\n          && jsonSchemaPathExists(branch as JSONSchema, path, root, new Set(seenRefs))\n      ));\n    }\n  }\n  if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n    return schema.allOf.some((branch) => (\n      branch !== null && typeof branch === \"object\" && !Array.isArray(branch)\n        && jsonSchemaPathExists(branch as JSONSchema, path, root, new Set(seenRefs))\n    ));\n  }\n\n  const [segment, ...remaining] = path;\n  if (typeof segment === \"string\") {\n    const properties = schema.properties;\n    if (properties && typeof properties === \"object\" && !Array.isArray(properties)) {\n      const property = properties[segment];\n      if (property && typeof property === \"object\" && !Array.isArray(property)) {\n        return jsonSchemaPathExists(property as JSONSchema, remaining, root, seenRefs);\n      }\n    }\n    const additional = schema.additionalProperties;\n    return additional !== null && typeof additional === \"object\" && !Array.isArray(additional)\n      ? jsonSchemaPathExists(additional as JSONSchema, remaining, root, seenRefs)\n      : false;\n  }\n  const items = schema.items;\n  return items !== null && typeof items === \"object\" && !Array.isArray(items)\n    ? jsonSchemaPathExists(items as JSONSchema, remaining, root, seenRefs)\n    : false;\n}\n\nfunction normalizeStringArray(raw: unknown, path: string): string[] {\n  if (raw === undefined) return [];\n  if (!Array.isArray(raw)) {\n    return fail({\n      phase: \"validate\",\n      code: \"authoring.expected_array\",\n      message: \"Expected an array of identifiers.\",\n      path,\n    });\n  }\n  const result = raw.map((item, index) => identifierAt(item, `${path}/${index}`));\n  if (new Set(result).size !== result.length) {\n    return fail({\n      phase: \"validate\",\n      code: \"authoring.duplicate_identifier\",\n      message: \"Identifier arrays cannot contain duplicates.\",\n      path,\n    });\n  }\n  return result.sort();\n}\n\nfunction normalizeMeta(raw: unknown): ArtifactMeta {\n  if (raw === undefined) return {};\n  const meta = recordAt(raw, \"/meta\");\n  rejectUnknownKeys(meta, new Set([\"title\", \"description\", \"locale\", \"tags\"]), \"/meta\");\n  const output: ArtifactMeta = {};\n  if (meta.title !== undefined) output.title = stringAt(meta.title, \"/meta/title\");\n  if (meta.description !== undefined) output.description = stringAt(meta.description, \"/meta/description\");\n  if (meta.locale !== undefined) output.locale = stringAt(meta.locale, \"/meta/locale\");\n  if (meta.tags !== undefined) output.tags = normalizeStringArray(meta.tags, \"/meta/tags\");\n  return output;\n}\n\nexport function normalizeSurface(\n  input: unknown,\n  options: NormalizeSurfaceOptions = {},\n): Readonly<NormalizedArtifactProposal> {\n  const limits = resolveGenerationLimits(options.limits);\n  inspectJson(input, limits);\n  const proposal = recordAt(input, \"\") as ArtifactProposal & Record<string, unknown>;\n  rejectUnknownKeys(proposal, new Set([\"root\", \"state\", \"actions\", \"claims\", \"resourceIds\", \"meta\"]), \"\");\n\n  const contracts = contractMap(options.catalog);\n  if (contracts.size === 0) {\n    return fail({\n      phase: \"validate\",\n      code: \"catalog.empty\",\n      message: \"Normalization requires a non-empty compiler catalog or catalog slice.\",\n      path: \"/root/type\",\n      modelCorrectable: false,\n    });\n  }\n  const state = normalizeStates(proposal.state);\n  const declaredResources = normalizeStringArray(proposal.resourceIds, \"/resourceIds\");\n  const grantedResources = options.allowedResourceIds\n    ? new Set(options.allowedResourceIds)\n    : new Set(declaredResources);\n  for (const resourceId of declaredResources) {\n    if (!grantedResources.has(resourceId)) {\n      return fail({\n        phase: \"policy\",\n        code: \"reference.resource_not_granted\",\n        message: `Resource \"${resourceId}\" is not in the sealed proposal context.`,\n        path: \"/resourceIds\",\n        recoverable: false,\n        modelCorrectable: false,\n      });\n    }\n  }\n\n  const context: NormalizeContext = {\n    contracts,\n    limits,\n    nodes: {},\n    instanceCounts: new Map(),\n    stateIds: new Set(Object.keys(state)),\n    resourceIds: new Set(declaredResources),\n    capabilityIds: new Set(options.capabilityIds ?? []),\n    messageTemplateIds: new Set(options.messageTemplateIds ?? []),\n  };\n  const root = normalizeNode(proposal.root, \"/root\", 1, context);\n  const actions = normalizeActions(proposal.actions, context);\n  validateActionReferences(context.nodes, actions, context.contracts);\n\n  const claims = proposal.claims === undefined\n    ? {}\n    : cloneJson(recordAt(proposal.claims, \"/claims\") as unknown as JsonValue) as Record<string, JsonValue>;\n  const result: NormalizedArtifactProposal = {\n    root,\n    nodes: context.nodes,\n    state,\n    actions,\n    claims,\n    resourceIds: declaredResources,\n    meta: normalizeMeta(proposal.meta),\n  };\n  return deepFreeze(result);\n}\n\nexport function safeNormalizeSurface(\n  input: unknown,\n  options: NormalizeSurfaceOptions = {},\n):\n  | { success: true; data: Readonly<NormalizedArtifactProposal> }\n  | { success: false; diagnostics: readonly Diagnostic[] } {\n  try {\n    return { success: true, data: normalizeSurface(input, options) };\n  } catch (error) {\n    return { success: false, diagnostics: diagnosticsFromUnknown(error) };\n  }\n}\n","import { z } from \"zod\";\nimport { assertJsonValue, canonicalize, hashJson } from \"./canonical\";\nimport {\n  CompilerCatalog,\n  defaultCompilerCatalog,\n  sliceCatalog,\n} from \"./catalog\";\nimport { compilerDiagnostic, CompilerDiagnosticError } from \"./diagnostics\";\nimport { actionContractVersions } from \"./contract-version\";\nimport { DEFAULT_DOCUMENT_POLICY } from \"./information-flow\";\nimport { resolveGenerationLimits } from \"./normalize\";\nimport type {\n  AuthoringCodec,\n  CatalogSlice,\n  CompilerExample,\n  CompilerPreset,\n  DocumentPolicy,\n  DocumentSummary,\n  GenerationLimits,\n  JSONSchema,\n  JsonValue,\n  ModelVisibleCapability,\n  ModelVisibleMessageTemplate,\n  NodeContract,\n  PromptBundle,\n  RenderMode,\n  SurfaceProfile,\n} from \"./types\";\n\nconst schemaProfile = {\n  profileId: \"data-elements.schema-core\",\n  profileVersion: 1,\n  profileHash: hashJson({ id: \"data-elements.schema-core\", version: 1 }),\n} as const;\n\nconst PROVIDER_SCHEMA_CACHE_LIMIT = 128;\nconst providerSchemaCache = new Map<string, string>();\n\nfunction nodeDefinitionKey(contract: NodeContract): string {\n  return `node_${contract.type.replaceAll(/[^a-zA-Z0-9_]/g, \"_\")}_${hashJson(contract.type).slice(0, 8)}`;\n}\n\nfunction jsonSchemaFor(contract: NodeContract): JSONSchema {\n  if (contract.providerSchema) return applyContractBindings(contract.providerSchema, contract);\n  const schema = contract.propsSchema;\n  const generated: unknown = z.toJSONSchema(schema, {\n    target: \"draft-2020-12\",\n    reused: \"inline\",\n  });\n  assertJsonValue(generated);\n  if (!generated || typeof generated !== \"object\" || Array.isArray(generated)) {\n    throw new TypeError(\"A node props schema must compile to an object JSON Schema.\");\n  }\n  const embedded = { ...generated };\n  delete embedded.$schema;\n  return applyContractBindings(embedded, contract);\n}\n\nfunction applyContractBindings(schema: JSONSchema, contract: NodeContract): JSONSchema {\n  const paths = new Map<string, { reference: boolean; condition: boolean }>();\n  for (const path of contract.bindings?.referencePaths ?? []) {\n    paths.set(path, { reference: true, condition: paths.get(path)?.condition ?? false });\n  }\n  for (const path of contract.bindings?.conditionPaths ?? []) {\n    paths.set(path, { reference: paths.get(path)?.reference ?? false, condition: true });\n  }\n  let output = JSON.parse(JSON.stringify(schema)) as JSONSchema;\n  for (const [path, allowed] of [...paths.entries()].sort(([left], [right]) => left.localeCompare(right))) {\n    const result = wrapBindingPath(output, decodeContractPath(path), 0, allowed);\n    if (!result.found) {\n      throw new TypeError(`Node contract \"${contract.type}\" binding path \"${path}\" is not present in its props schema.`);\n    }\n    output = result.schema;\n  }\n  return output;\n}\n\nfunction decodeContractPath(path: string): string[] {\n  return path.slice(1).split(\"/\").map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"));\n}\n\nfunction wrapBindingPath(\n  schema: JSONSchema,\n  segments: readonly string[],\n  index: number,\n  allowed: { reference: boolean; condition: boolean },\n): { schema: JSONSchema; found: boolean } {\n  if (index === segments.length) {\n    return {\n      schema: {\n        oneOf: [\n          schema,\n          ...(allowed.reference ? [reference(\"#/$defs/propsReference\")] : []),\n          ...(allowed.condition ? [reference(\"#/$defs/presentationCondition\")] : []),\n        ],\n      },\n      found: true,\n    };\n  }\n  const segment = segments[index]!;\n  if (segment === \"*\") {\n    const items = schema.items;\n    if (!items || typeof items !== \"object\" || Array.isArray(items)) return { schema, found: false };\n    const nested = wrapBindingPath(items as JSONSchema, segments, index + 1, allowed);\n    return nested.found ? { schema: { ...schema, items: nested.schema }, found: true } : { schema, found: false };\n  }\n  const properties = schema.properties;\n  if (!properties || typeof properties !== \"object\" || Array.isArray(properties)) {\n    return { schema, found: false };\n  }\n  const property = properties[segment];\n  if (!property || typeof property !== \"object\" || Array.isArray(property)) {\n    return { schema, found: false };\n  }\n  const nested = wrapBindingPath(property as JSONSchema, segments, index + 1, allowed);\n  if (!nested.found) return { schema, found: false };\n  return {\n    schema: { ...schema, properties: { ...properties, [segment]: nested.schema } },\n    found: true,\n  };\n}\n\nfunction reference(ref: string): JSONSchema {\n  return { $ref: ref };\n}\n\nfunction buildValueDefinitions(): Record<string, JSONSchema> {\n  const path = {\n    type: \"array\",\n    items: {\n      anyOf: [\n        { type: \"string\", minLength: 1, not: { enum: [\"__proto__\", \"constructor\", \"prototype\"] } },\n        { type: \"integer\", minimum: 0 },\n      ],\n    },\n  } as unknown as JSONSchema;\n  const closed = (properties: JSONSchema, required: string[]): JSONSchema => ({\n    type: \"object\",\n    properties,\n    required,\n    additionalProperties: false,\n  });\n  const stateOrResourceReference = closed({\n    $ref: { enum: [\"state\", \"resource\"] },\n    id: { type: \"string\", minLength: 1 },\n    path,\n  }, [\"$ref\", \"id\"]);\n  const contextReference = closed({\n    $ref: { const: \"context\" },\n    key: { enum: [\"locale\", \"timezone\"] },\n  }, [\"$ref\", \"key\"]);\n  const eventReference = closed({\n    $ref: { const: \"event\" },\n    port: { type: \"string\", minLength: 1 },\n    path,\n  }, [\"$ref\", \"port\"]);\n  const presentationCondition = closed({\n    $condition: closed({\n      op: { enum: [\"eq\", \"neq\", \"lt\", \"lte\", \"gt\", \"gte\", \"and\", \"or\", \"not\"] },\n      args: { type: \"array\", minItems: 1, items: reference(\"#/$defs/authoringValue\") },\n    }, [\"op\", \"args\"]),\n  }, [\"$condition\"]);\n  return {\n    jsonValue: {\n      anyOf: [\n        { type: \"null\" },\n        { type: \"boolean\" },\n        { type: \"string\" },\n        { type: \"number\" },\n        { type: \"array\", items: reference(\"#/$defs/jsonValue\") },\n        {\n          type: \"object\",\n          propertyNames: { not: { enum: [\"__proto__\", \"constructor\", \"prototype\"] } },\n          additionalProperties: reference(\"#/$defs/jsonValue\"),\n        },\n      ],\n    },\n    authoringValue: {\n      anyOf: [\n        { type: \"null\" },\n        { type: \"boolean\" },\n        { type: \"string\" },\n        { type: \"number\" },\n        { type: \"array\", items: reference(\"#/$defs/authoringValue\") },\n        {\n          type: \"object\",\n          propertyNames: {\n            allOf: [\n              { not: { pattern: \"^\\\\$\" } },\n              { not: { enum: [\"__proto__\", \"constructor\", \"prototype\"] } },\n            ],\n          },\n          additionalProperties: reference(\"#/$defs/authoringValue\"),\n        },\n        reference(\"#/$defs/propsReference\"),\n        reference(\"#/$defs/eventReference\"),\n        reference(\"#/$defs/presentationCondition\"),\n      ],\n    },\n    propsReference: { oneOf: [stateOrResourceReference, contextReference] },\n    eventReference,\n    presentationCondition,\n  };\n}\n\nfunction actionDefinitions(\n  capabilities: readonly ModelVisibleCapability[],\n  templates: readonly ModelVisibleMessageTemplate[],\n  actionContracts: ReadonlyMap<string, readonly number[]>,\n): Record<string, JSONSchema> {\n  const valueRecord: JSONSchema = {\n    type: \"object\",\n    propertyNames: { not: { pattern: \"^\\\\$\" } },\n    additionalProperties: reference(\"#/$defs/authoringValue\"),\n  };\n  const stepBase = (properties: JSONSchema, required: string[]): JSONSchema => ({\n    type: \"object\",\n    properties: { stepId: { type: \"string\", minLength: 1 }, ...properties },\n    required: [\"stepId\", ...required],\n    additionalProperties: false,\n  });\n  const steps: JSONSchema[] = [\n    stepBase({ type: { const: \"state.set\" }, stateId: { type: \"string\" }, value: reference(\"#/$defs/authoringValue\") }, [\"type\", \"stateId\", \"value\"]),\n    stepBase({ type: { const: \"state.reset\" }, stateIds: { type: \"array\", minItems: 1, uniqueItems: true, items: { type: \"string\" } } }, [\"type\", \"stateIds\"]),\n    stepBase({ type: { const: \"node.focus\" }, nodeId: { type: \"string\" } }, [\"type\", \"nodeId\"]),\n  ];\n  if (templates.length) {\n    steps.push(stepBase({\n      type: { const: \"agent.message\" },\n      templateGrantId: { enum: templates.map(({ templateGrantId }) => templateGrantId) },\n      values: valueRecord,\n    }, [\"type\", \"templateGrantId\"]));\n  }\n  if (capabilities.length) {\n    const capabilityIds = capabilities.map(({ capabilityId }) => capabilityId);\n    steps.push(stepBase({\n      type: { const: \"capability.request\" },\n      capabilityId: { enum: capabilityIds },\n      input: valueRecord,\n    }, [\"type\", \"capabilityId\", \"input\"]));\n    steps.push(stepBase({\n      type: { const: \"navigation.request\" },\n      target: {\n        oneOf: [\n          {\n            type: \"object\",\n            properties: {\n              kind: { const: \"route\" }, capabilityId: { enum: capabilityIds },\n              routeId: { type: \"string\" }, params: valueRecord,\n            },\n            required: [\"kind\", \"capabilityId\", \"routeId\"], additionalProperties: false,\n          },\n          {\n            type: \"object\",\n            properties: {\n              kind: { const: \"resource\" }, capabilityId: { enum: capabilityIds },\n              resourceId: { type: \"string\" },\n            },\n            required: [\"kind\", \"capabilityId\", \"resourceId\"], additionalProperties: false,\n          },\n          {\n            type: \"object\",\n            properties: {\n              kind: { const: \"external\" }, capabilityId: { enum: capabilityIds }, input: valueRecord,\n            },\n            required: [\"kind\", \"capabilityId\", \"input\"], additionalProperties: false,\n          },\n        ],\n      },\n    }, [\"type\", \"target\"]));\n  }\n  let actionPlan: JSONSchema;\n  if (actionContracts.size === 0) {\n    actionPlan = { not: {} };\n  } else {\n    actionPlan = {\n      oneOf: [...actionContracts.entries()].map(([contractId, versions]) => ({\n          type: \"object\",\n          properties: {\n            contractId: { const: contractId },\n            contractVersion: {\n              enum: [...versions],\n              ...(versions.includes(1) ? { default: 1 } : {}),\n            },\n            steps: { type: \"array\", minItems: 1, items: reference(\"#/$defs/actionStep\") },\n            onError: { enum: [\"halt\", \"continue\"], default: \"halt\" },\n          },\n          required: [\"contractId\", \"steps\", ...(versions.includes(1) ? [] : [\"contractVersion\"])],\n          additionalProperties: false,\n      })),\n    };\n  }\n  return {\n    actionStep: { oneOf: steps },\n    actionPlan,\n    stateDefinition: {\n      type: \"object\",\n      properties: {\n        schema: { type: \"object\" },\n        initial: reference(\"#/$defs/jsonValue\"),\n      },\n      required: [\"schema\", \"initial\"],\n      additionalProperties: false,\n    },\n  };\n}\n\nfunction collectActionContracts(slice: CatalogSlice): ReadonlyMap<string, readonly number[]> {\n  const versions = new Map<string, Set<number>>();\n  for (const contract of slice.contracts) {\n    for (const event of Object.values(contract.events ?? {})) {\n      for (const [contractId, range] of Object.entries(event.actionContracts)) {\n        const supported = actionContractVersions(range);\n        if (!supported) {\n          throw new TypeError(`Unsupported action contract range \"${range}\" in \"${contract.type}\".`);\n        }\n        const existing = versions.get(contractId) ?? new Set<number>();\n        supported.forEach((version) => existing.add(version));\n        versions.set(contractId, existing);\n      }\n    }\n  }\n  return new Map([...versions.entries()]\n    .sort(([left], [right]) => left.localeCompare(right))\n    .map(([contractId, supported]) => [contractId, [...supported].sort((left, right) => left - right)]));\n}\n\nexport function createProviderSchema(\n  slice: CatalogSlice,\n  options: {\n    capabilities?: readonly ModelVisibleCapability[];\n    messageTemplates?: readonly ModelVisibleMessageTemplate[];\n  } = {},\n): JSONSchema {\n  const capabilities = [...(options.capabilities ?? [])].sort(\n    (left, right) => left.capabilityId.localeCompare(right.capabilityId),\n  );\n  const templates = [...(options.messageTemplates ?? [])].sort(\n    (left, right) => left.templateGrantId.localeCompare(right.templateGrantId),\n  );\n  const cacheIdentity = {\n    version: 1,\n    sliceHash: slice.sliceHash,\n    capabilities,\n    templates,\n  };\n  assertJsonValue(cacheIdentity);\n  const cacheKey = hashJson(cacheIdentity);\n  const cached = providerSchemaCache.get(cacheKey);\n  if (cached !== undefined) {\n    // Refresh insertion order so frequently used catalog slices remain hot.\n    providerSchemaCache.delete(cacheKey);\n    providerSchemaCache.set(cacheKey, cached);\n    return JSON.parse(cached) as JSONSchema;\n  }\n\n  const definitions: Record<string, JSONSchema> = {\n    ...buildValueDefinitions(),\n    ...actionDefinitions(capabilities, templates, collectActionContracts(slice)),\n  };\n  const keyByType = new Map(slice.contracts.map((contract) => [contract.type, nodeDefinitionKey(contract)]));\n\n  for (const contract of slice.contracts) {\n    const properties: JSONSchema = {\n      id: { type: \"string\", pattern: \"^[A-Za-z][A-Za-z0-9_.:-]{0,127}$\" },\n      type: { const: contract.type },\n      typeVersion: { const: contract.version },\n      props: jsonSchemaFor(contract),\n    };\n    const required = [\"id\", \"type\"];\n    const slotEntries = Object.entries(contract.slots).sort(([left], [right]) => left.localeCompare(right));\n    if (slotEntries.length) {\n      const slotProperties: JSONSchema = {};\n      const requiredSlots: string[] = [];\n      for (const [slotName, slot] of slotEntries) {\n        const accepted = slice.contracts.filter((candidate) => (\n          slot.accepts?.includes(candidate.type)\n          || slot.categories?.includes(candidate.category)\n          || (candidate.category.startsWith(\"extension:\") && slot.categories?.includes(\"extension:*\"))\n        ));\n        slotProperties[slotName] = {\n          type: \"array\",\n          minItems: slot.min ?? 0,\n          maxItems: slot.max ?? 2_000,\n          items: accepted.length\n            ? { oneOf: accepted.map((candidate) => reference(`#/$defs/${keyByType.get(candidate.type)!}`)) }\n            : { not: {} },\n        };\n        if ((slot.min ?? 0) > 0) requiredSlots.push(slotName);\n      }\n      properties.slots = {\n        type: \"object\",\n        properties: slotProperties,\n        ...(requiredSlots.length ? { required: requiredSlots } : {}),\n        additionalProperties: false,\n      };\n      if (requiredSlots.length) required.push(\"slots\");\n    }\n    if (contract.events && Object.keys(contract.events).length) {\n      properties.events = {\n        type: \"object\",\n        properties: Object.fromEntries(Object.keys(contract.events).sort().map((port) => [\n          port,\n          { type: \"string\", minLength: 1 },\n        ])),\n        additionalProperties: false,\n      };\n    }\n    properties.evidence = {\n      type: \"array\",\n      uniqueItems: true,\n      items: { type: \"string\", minLength: 1 },\n    };\n    definitions[keyByType.get(contract.type)!] = {\n      type: \"object\",\n      properties,\n      required,\n      additionalProperties: false,\n    };\n  }\n\n  const rootRefs = slice.contracts.map((contract) => reference(`#/$defs/${keyByType.get(contract.type)!}`));\n  const schema: JSONSchema = {\n    $schema: \"https://json-schema.org/draft/2020-12/schema\",\n    $id: `urn:data-elements:authoring:${slice.sliceHash}`,\n    title: \"Data Elements Artifact Proposal\",\n    description: \"Nested authoring input. The trusted compiler normalizes and validates it before rendering.\",\n    type: \"object\",\n    properties: {\n      root: { oneOf: rootRefs },\n      state: { type: \"object\", additionalProperties: reference(\"#/$defs/stateDefinition\") },\n      actions: { type: \"object\", additionalProperties: reference(\"#/$defs/actionPlan\") },\n      claims: { type: \"object\", additionalProperties: reference(\"#/$defs/jsonValue\") },\n      resourceIds: { type: \"array\", uniqueItems: true, items: { type: \"string\", minLength: 1 } },\n      meta: {\n        type: \"object\",\n        properties: {\n          title: { type: \"string\" }, description: { type: \"string\" }, locale: { type: \"string\" },\n          tags: { type: \"array\", uniqueItems: true, items: { type: \"string\" } },\n        },\n        additionalProperties: false,\n      },\n    },\n    required: [\"root\"],\n    additionalProperties: false,\n    $defs: definitions,\n  };\n  providerSchemaCache.set(cacheKey, JSON.stringify(schema));\n  if (providerSchemaCache.size > PROVIDER_SCHEMA_CACHE_LIMIT) {\n    const oldest = providerSchemaCache.keys().next().value;\n    if (oldest !== undefined) providerSchemaCache.delete(oldest);\n  }\n  return schema;\n}\n\nfunction validateDescriptorSets(\n  capabilities: readonly ModelVisibleCapability[],\n  templates: readonly ModelVisibleMessageTemplate[],\n): void {\n  const assertUnique = (values: readonly string[], path: string): void => {\n    if (new Set(values).size !== values.length) {\n      throw new CompilerDiagnosticError([compilerDiagnostic({\n        phase: \"policy\",\n        code: \"prompt.duplicate_descriptor\",\n        message: \"Model-visible descriptor ids must be unique within a turn.\",\n        path,\n        recoverable: false,\n        modelCorrectable: false,\n      })]);\n    }\n  };\n  assertUnique(capabilities.map(({ capabilityId }) => capabilityId), \"/capabilityDescriptors\");\n  assertUnique(templates.map(({ templateGrantId }) => templateGrantId), \"/messageTemplateDescriptors\");\n  for (const [index, descriptor] of [...capabilities, ...templates].entries()) {\n    if (\n      descriptor.schemaProfile.profileId !== schemaProfile.profileId\n      || descriptor.schemaProfile.profileVersion !== schemaProfile.profileVersion\n      || descriptor.schemaProfile.profileHash !== schemaProfile.profileHash\n    ) {\n      throw new CompilerDiagnosticError([compilerDiagnostic({\n        phase: \"policy\",\n        code: \"prompt.schema_profile_mismatch\",\n        message: \"A model-visible descriptor uses a different schema profile.\",\n        path: `/descriptors/${index}/schemaProfile`,\n        recoverable: false,\n        modelCorrectable: false,\n      })]);\n    }\n  }\n}\n\nfunction selectExamples(\n  slice: CatalogSlice,\n  profile: SurfaceProfile,\n  maxExamples: number,\n): readonly CompilerExample[] {\n  const available = new Set(slice.contracts.map(({ type }) => type));\n  const unique = new Map<string, CompilerExample>();\n  for (const contract of slice.contracts) {\n    for (const example of contract.examples ?? []) unique.set(example.id, example);\n  }\n  return [...unique.values()]\n    .filter((example) => example.profiles.includes(profile) && example.nodeTypes.every((type) => available.has(type)))\n    .sort((left, right) => left.id.localeCompare(right.id))\n    .slice(0, maxExamples);\n}\n\nfunction contractInstructions(contract: NodeContract): string {\n  const slots = Object.entries(contract.slots).sort(([left], [right]) => left.localeCompare(right)).map(\n    ([name, slot]) => `${name}[${slot.min ?? 0}..${slot.max ?? \"n\"}]`,\n  ).join(\", \") || \"none\";\n  return [\n    `- ${contract.type}@${contract.version} (${contract.category}, ${contract.commitPolicy})`,\n    `  ${contract.prompt.summary}`,\n    `  Use when: ${contract.prompt.useWhen.join(\" \")}`,\n    `  Avoid when: ${contract.prompt.avoidWhen.join(\" \")}`,\n    `  Slots: ${slots}`,\n  ].join(\"\\n\");\n}\n\nfunction buildSystem(input: {\n  slice: CatalogSlice;\n  profile: SurfaceProfile;\n  preset: CompilerPreset;\n  codec: AuthoringCodec;\n  renderMode: RenderMode;\n  locale: string;\n  limits: GenerationLimits;\n  examples: readonly CompilerExample[];\n  capabilities: readonly ModelVisibleCapability[];\n  templates: readonly ModelVisibleMessageTemplate[];\n  summaries: readonly DocumentSummary[];\n}): string {\n  const sections = [\n    \"You produce Data Elements Artifact Authoring DSL only through the renderArtifact tool.\",\n    \"Never emit JSX, JavaScript, HTML, CSS, SQL, executable formulas, credentials, endpoints, or arbitrary component names.\",\n    `Protocol 2.0; codec ${input.codec}; profile ${input.profile}; preset ${input.preset}; render mode ${input.renderMode}; locale ${input.locale}.`,\n    `Limits: at most ${input.limits.maxNodes} nodes, depth ${input.limits.maxDepth}, ${input.limits.maxDocumentBytes} UTF-8 bytes, and ${input.limits.maxTotalValues} values.`,\n    \"Use stable unique ids. Nest nodes only in declared slots. Props must match the generated closed schema. Treat semantic artifact nodes as atomic.\",\n    \"Only cite evidence and resources already provided by the host. Descriptors name possible requests, not authorization to invent new ids.\",\n    \"Active node contracts:\\n\" + input.slice.contracts.map(contractInstructions).join(\"\\n\"),\n  ];\n  if (input.capabilities.length) {\n    sections.push(\"Model-visible capabilities:\\n\" + input.capabilities.map((capability) => (\n      `- ${capability.capabilityId}@${capability.grantVersion}: ${capability.summary}; approval=${capability.requiresApproval}`\n    )).join(\"\\n\"));\n  }\n  if (input.templates.length) {\n    sections.push(\"Model-visible message templates:\\n\" + input.templates.map((template) => (\n      `- ${template.templateGrantId}@${template.templateGrantVersion}: ${template.summary}`\n    )).join(\"\\n\"));\n  }\n  if (input.summaries.length) {\n    sections.push(\"Authorized parent document summaries:\\n\" + input.summaries.map((summary) => (\n      `- ${summary.documentId}@${summary.revisionId}${summary.title ? ` (${summary.title})` : \"\"}: ${summary.summary}`\n    )).join(\"\\n\"));\n  }\n  if (input.examples.length) {\n    sections.push(\"Validated examples:\\n\" + input.examples.map((example) => (\n      `User: ${example.user}\\nTool input: ${canonicalize(example.proposal as unknown as JsonValue)}`\n    )).join(\"\\n\\n\"));\n  }\n  return sections.join(\"\\n\\n\");\n}\n\nexport type PromptCompileInput = {\n  catalog?: CompilerCatalog | CatalogSlice;\n  preset?: CompilerPreset;\n  profile?: SurfaceProfile;\n  documentPolicy?: DocumentPolicy;\n  generationTaintHash: string;\n  requestedNodeTypes?: readonly string[];\n  task?: string;\n  codec?: AuthoringCodec;\n  renderMode?: RenderMode;\n  capabilityDescriptors?: readonly ModelVisibleCapability[];\n  messageTemplateDescriptors?: readonly ModelVisibleMessageTemplate[];\n  locale?: string;\n  limits?: Partial<GenerationLimits>;\n  parentDocumentSummaries?: readonly DocumentSummary[];\n};\n\nexport function compilePrompt(input: PromptCompileInput): Readonly<PromptBundle> {\n  const preset = input.preset ?? \"standard\";\n  const profile = input.profile ?? \"analysis\";\n  const codec = input.codec ?? \"snapshot-json\";\n  const renderMode = preset === \"governed\" ? \"strict\" : input.renderMode ?? \"progressive\";\n  const locale = input.locale ?? \"en-US\";\n  const limits = resolveGenerationLimits(input.limits);\n  const capabilities = [...(input.capabilityDescriptors ?? [])].sort(\n    (left, right) => left.capabilityId.localeCompare(right.capabilityId),\n  );\n  const templates = [...(input.messageTemplateDescriptors ?? [])].sort(\n    (left, right) => left.templateGrantId.localeCompare(right.templateGrantId),\n  );\n  validateDescriptorSets(capabilities, templates);\n  const catalog = input.catalog ?? defaultCompilerCatalog;\n  const catalogSlice = catalog instanceof CompilerCatalog\n    ? sliceCatalog({\n        catalog,\n        profile,\n        requestedNodeTypes: input.requestedNodeTypes,\n        task: input.task,\n        maxNodeTypes: limits.maxNodeTypes,\n      })\n    : catalog;\n  const examples = selectExamples(catalogSlice, profile, limits.maxExamples);\n  const providerSchema = createProviderSchema(catalogSlice, {\n    capabilities,\n    messageTemplates: templates,\n  });\n  const summaries = [...(input.parentDocumentSummaries ?? [])].sort(\n    (left, right) => left.documentId.localeCompare(right.documentId) || left.revisionId.localeCompare(right.revisionId),\n  );\n  const system = buildSystem({\n    slice: catalogSlice,\n    profile,\n    preset,\n    codec,\n    renderMode,\n    locale,\n    limits,\n    examples,\n    capabilities,\n    templates,\n    summaries,\n  });\n  const documentPolicy = input.documentPolicy ?? DEFAULT_DOCUMENT_POLICY;\n  const hashInput: JsonValue = {\n    protocolVersion: \"2.0\",\n    system,\n    providerSchema,\n    catalog: catalogSlice.catalog as unknown as JsonValue,\n    contractFingerprint: catalogSlice.contractFingerprint,\n    sliceHash: catalogSlice.sliceHash,\n    profile,\n    preset,\n    codec,\n    renderMode,\n    locale,\n    limits,\n    documentPolicy,\n    generationTaintHash: input.generationTaintHash,\n    capabilities: capabilities as unknown as JsonValue,\n    messageTemplates: templates as unknown as JsonValue,\n    parentDocumentSummaries: summaries as unknown as JsonValue,\n    examples: examples as unknown as JsonValue,\n  };\n  const promptBundleHash = hashJson(hashInput);\n  const bundle: PromptBundle = {\n    protocolVersion: \"2.0\",\n    system,\n    providerSchema,\n    tool: {\n      name: \"renderArtifact\",\n      description: \"Submit one validated, declarative Data Elements artifact proposal.\",\n      inputSchema: providerSchema,\n    },\n    catalogSlice,\n    contractFingerprint: catalogSlice.contractFingerprint,\n    promptBundleHash,\n    generationTaintHash: input.generationTaintHash,\n    profile,\n    preset,\n    codec,\n    renderMode,\n    locale,\n    limits,\n    examples,\n    repair: {\n      maxAttempts: limits.maxRepairAttempts,\n      redactedFields: [\"actualSummary\", \"expected\", \"rawException\", \"credentials\", \"hiddenPolicy\", \"sql\"],\n    },\n  };\n  Object.freeze(bundle.tool);\n  Object.freeze(bundle.repair);\n  return Object.freeze(bundle);\n}\n\nexport { schemaProfile as compilerSchemaProfile };\n","import { canonicalize, hashJson, utf8Bytes } from \"./canonical\";\nimport {\n  compilerDiagnostic,\n  CompilerDiagnosticError,\n  diagnosticsFromUnknown,\n} from \"./diagnostics\";\nimport type {\n  Diagnostic,\n  InformationFlowLabel,\n  JsonValue,\n  PromptBundle,\n  RepairDiagnostic,\n  RepairProvider,\n  RepairRequest,\n} from \"./types\";\n\nconst repairablePhases = new Set<Diagnostic[\"phase\"]>([\"decode\", \"normalize\", \"validate\"]);\n\nconst safeRepairMessages: Readonly<Record<string, string>> = Object.freeze({\n  \"authoring.expected_object\": \"Replace this value with the required object shape.\",\n  \"authoring.expected_string\": \"Provide the required non-empty string.\",\n  \"authoring.unknown_field\": \"Remove the undeclared field.\",\n  \"authoring.reserved_key\": \"Remove the unknown reserved key.\",\n  \"catalog.node_not_in_slice\": \"Choose a node type from the active provider schema.\",\n  \"catalog.node_version_mismatch\": \"Use the active node contract version.\",\n  \"node.invalid_props\": \"Make the node props satisfy its generated closed schema.\",\n  \"node.duplicate_id\": \"Give every node a unique stable id.\",\n  \"slot.unknown\": \"Use only slots declared by the node contract.\",\n  \"slot.expected_array\": \"Represent slot children as an array.\",\n  \"slot.cardinality\": \"Adjust the number of children to the declared slot bounds.\",\n  \"slot.child_not_allowed\": \"Use a child type accepted by this slot.\",\n  \"condition.invalid_shape\": \"Use a supported condition operator and argument list.\",\n  \"condition.invalid_arity\": \"Use the required number of condition arguments.\",\n  \"action.duplicate_step_id\": \"Give every step in the action plan a unique id.\",\n});\n\nexport function sanitizeRepairDiagnostics(\n  diagnostics: readonly Diagnostic[],\n): readonly RepairDiagnostic[] {\n  return diagnostics.filter((diagnostic) => (\n    diagnostic.modelCorrectable\n    && diagnostic.recoverable\n    && repairablePhases.has(diagnostic.phase)\n  )).map((diagnostic) => ({\n    phase: diagnostic.phase,\n    code: diagnostic.code.replaceAll(/[^a-zA-Z0-9_.-]/g, \"_\").slice(0, 120),\n    severity: diagnostic.severity,\n    message: safeRepairMessages[diagnostic.code] ?? \"Correct this field using the active provider schema.\",\n    ...(diagnostic.location?.path ? { path: diagnostic.location.path.slice(0, 500) } : {}),\n    ...(safeRepairMessages[diagnostic.code]\n      ? { hint: safeRepairMessages[diagnostic.code] }\n      : {}),\n  }));\n}\n\nfunction repairFragment(value: unknown, maxBytes: number): JsonValue {\n  try {\n    const serialized = JSON.stringify(value);\n    if (serialized === undefined) throw new TypeError(\"not JSON\");\n    const parsed = redactRepairValue(JSON.parse(serialized) as JsonValue);\n    const canonical = canonicalize(parsed);\n    if (utf8Bytes(canonical) <= maxBytes) return parsed;\n    return {\n      omitted: true,\n      reason: \"fragment-too-large\",\n      contentHash: hashJson(parsed),\n      byteLength: utf8Bytes(canonical),\n    };\n  } catch {\n    return { omitted: true, reason: \"fragment-not-json\" };\n  }\n}\n\nconst secretKeyPattern = /(?:api[-_]?key|authorization|credential|password|secret|token|rawexception|hiddenpolicy|sql)/i;\nconst secretValuePattern = /(?:bearer\\s+[a-z0-9._~+/-]+=*|\\bsk-[a-z0-9_-]{12,}|\\b(?:select|insert|update|delete|drop|alter)\\s+.+\\b(?:from|into|table|set)\\b)/i;\n\nfunction redactRepairValue(value: JsonValue): JsonValue {\n  if (typeof value === \"string\") {\n    return secretValuePattern.test(value) ? \"[REDACTED]\" : value;\n  }\n  if (value === null || typeof value !== \"object\") return value;\n  if (Array.isArray(value)) return value.map(redactRepairValue);\n  return Object.fromEntries(Object.entries(value).map(([key, child]) => [\n    key,\n    secretKeyPattern.test(key) ? \"[REDACTED]\" : redactRepairValue(child),\n  ]));\n}\n\nfunction createRepairRequest(input: {\n  attempt: number;\n  bundle: PromptBundle;\n  diagnostics: readonly RepairDiagnostic[];\n  invalidValue: unknown;\n  parentRevisionId?: string;\n  headPreconditions?: Readonly<Record<string, string>>;\n  statePreconditions?: Readonly<Record<string, string>>;\n}): RepairRequest {\n  const fragment = repairFragment(input.invalidValue, input.bundle.limits.maxRepairFragmentBytes);\n  const requestWithoutPrompt = {\n    attempt: input.attempt,\n    maxAttempts: input.bundle.repair.maxAttempts,\n    contractFingerprint: input.bundle.contractFingerprint,\n    promptBundleHash: input.bundle.promptBundleHash,\n    ...(input.parentRevisionId ? { parentRevisionId: input.parentRevisionId } : {}),\n    ...(input.headPreconditions ? { headPreconditions: input.headPreconditions } : {}),\n    ...(input.statePreconditions ? { statePreconditions: input.statePreconditions } : {}),\n    allowedOperations: [\"replace-snapshot\"] as const,\n    diagnostics: input.diagnostics,\n    fragment,\n  };\n  const prompt = [\n    \"Repair the Artifact Authoring snapshot using only the active provider schema.\",\n    \"Return one complete replacement snapshot. Do not add prose, patches, credentials, SQL, policy details, or executable content.\",\n    \"Active authoring instructions:\\n\" + input.bundle.system,\n    \"Active provider JSON Schema:\\n\" + canonicalize(input.bundle.providerSchema),\n    canonicalize(requestWithoutPrompt as unknown as JsonValue),\n  ].join(\"\\n\\n\");\n  return {\n    ...requestWithoutPrompt,\n    system: input.bundle.system,\n    providerSchema: input.bundle.providerSchema,\n    prompt,\n  };\n}\n\nexport type BoundedRepairOptions<T> = {\n  initialValue: unknown;\n  bundle: PromptBundle;\n  informationFlow: InformationFlowLabel;\n  validate(value: unknown): T;\n  provider?: RepairProvider;\n  parentRevisionId?: string;\n  headPreconditions?: Readonly<Record<string, string>>;\n  statePreconditions?: Readonly<Record<string, string>>;\n};\n\nexport async function runBoundedRepair<T>(\n  options: BoundedRepairOptions<T>,\n): Promise<T> {\n  let value = options.initialValue;\n  let lastDiagnostics: readonly Diagnostic[] = [];\n  for (let attempt = 0; attempt <= options.bundle.repair.maxAttempts; attempt += 1) {\n    try {\n      return options.validate(value);\n    } catch (error) {\n      lastDiagnostics = diagnosticsFromUnknown(error);\n    }\n\n    const diagnostics = sanitizeRepairDiagnostics(lastDiagnostics);\n    const canRepair = attempt < options.bundle.repair.maxAttempts\n      && options.provider !== undefined\n      && options.informationFlow.allowedSinks.includes(\"model-repair\")\n      && diagnostics.length > 0;\n    if (!canRepair) throw new CompilerDiagnosticError(lastDiagnostics);\n\n    const request = createRepairRequest({\n      attempt: attempt + 1,\n      bundle: options.bundle,\n      diagnostics,\n      invalidValue: value,\n      parentRevisionId: options.parentRevisionId,\n      headPreconditions: options.headPreconditions,\n      statePreconditions: options.statePreconditions,\n    });\n    try {\n      value = await options.provider!.repair(request);\n    } catch {\n      throw new CompilerDiagnosticError([compilerDiagnostic({\n        phase: \"transport\",\n        code: \"repair.provider_failed\",\n        message: \"The repair provider failed before returning a replacement snapshot.\",\n        recoverable: true,\n        modelCorrectable: false,\n      })]);\n    }\n  }\n  throw new CompilerDiagnosticError(lastDiagnostics);\n}\n","import type { Artifact } from \"@data-elements/schema\";\nimport type {\n  ArtifactProposal,\n  AuthoringNode,\n  AuthoringValue,\n  ConditionOperator,\n  PathSegment,\n} from \"./types\";\n\ntype NodeBase = {\n  id: string;\n  events?: Record<string, string>;\n  evidence?: string[];\n};\n\nfunction authoringProps(\n  value: Record<string, AuthoringValue | undefined>,\n): Record<string, AuthoringValue> {\n  return Object.fromEntries(\n    Object.entries(value).filter(([, item]) => item !== undefined),\n  ) as Record<string, AuthoringValue>;\n}\n\nfunction attachBase(\n  node: AuthoringNode,\n  input: Pick<NodeBase, \"events\" | \"evidence\">,\n): AuthoringNode {\n  if (input.events) node.events = input.events;\n  if (input.evidence) node.evidence = input.evidence;\n  return node;\n}\n\nfunction leaf(\n  type: string,\n  input: NodeBase,\n  props: Record<string, AuthoringValue>,\n): AuthoringNode {\n  return attachBase({\n    id: input.id,\n    type,\n    props,\n  }, input);\n}\n\nexport const reference = Object.freeze({\n  state(id: string, path?: PathSegment[]): AuthoringValue {\n    return path ? { $ref: \"state\", id, path } : { $ref: \"state\", id };\n  },\n  resource(id: string, path?: PathSegment[]): AuthoringValue {\n    return path ? { $ref: \"resource\", id, path } : { $ref: \"resource\", id };\n  },\n  event(port: string, path?: PathSegment[]): AuthoringValue {\n    return path ? { $ref: \"event\", port, path } : { $ref: \"event\", port };\n  },\n  context(key: \"locale\" | \"timezone\"): AuthoringValue {\n    return { $ref: \"context\", key };\n  },\n});\n\nexport function condition(\n  op: ConditionOperator,\n  ...args: AuthoringValue[]\n): AuthoringValue {\n  return { $condition: { op, args } };\n}\n\nexport const surface = Object.freeze({\n  node(input: AuthoringNode): AuthoringNode {\n    return input;\n  },\n\n  stack(input: NodeBase & {\n    children: AuthoringNode[];\n    gap?: \"none\" | \"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\";\n    align?: \"start\" | \"center\" | \"end\" | \"stretch\";\n  }): AuthoringNode {\n    return attachBase({\n      id: input.id,\n      type: \"layout.stack\",\n      props: authoringProps({ gap: input.gap, align: input.align }),\n      slots: { children: input.children },\n    }, input);\n  },\n\n  grid(input: NodeBase & {\n    children: AuthoringNode[];\n    columns?: 1 | 2 | 3 | 4;\n    gap?: \"none\" | \"xs\" | \"sm\" | \"md\" | \"lg\" | \"xl\";\n    align?: \"start\" | \"center\" | \"end\" | \"stretch\";\n  }): AuthoringNode {\n    return attachBase({\n      id: input.id,\n      type: \"layout.grid\",\n      props: authoringProps({ columns: input.columns, gap: input.gap, align: input.align }),\n      slots: { children: input.children },\n    }, input);\n  },\n\n  section(input: NodeBase & {\n    children: AuthoringNode[];\n    title?: string;\n    description?: string;\n  }): AuthoringNode {\n    return attachBase({\n      id: input.id,\n      type: \"layout.section\",\n      props: authoringProps({ title: input.title, description: input.description }),\n      slots: { children: input.children },\n    }, input);\n  },\n\n  text(input: NodeBase & {\n    text: string;\n    role?: \"heading\" | \"paragraph\" | \"caption\";\n    tone?: \"default\" | \"muted\" | \"positive\" | \"warning\" | \"critical\";\n  }): AuthoringNode {\n    return leaf(\"content.text\", input, {\n      text: input.text,\n      ...(input.role ? { role: input.role } : {}),\n      ...(input.tone ? { tone: input.tone } : {}),\n    });\n  },\n\n  callout(input: NodeBase & {\n    body: string;\n    title?: string;\n    tone?: \"info\" | \"success\" | \"warning\" | \"critical\";\n  }): AuthoringNode {\n    return leaf(\"content.callout\", input, {\n      body: input.body,\n      ...(input.title ? { title: input.title } : {}),\n      ...(input.tone ? { tone: input.tone } : {}),\n    });\n  },\n\n  progress(input: NodeBase & { label: string; value: number; detail?: string }): AuthoringNode {\n    return leaf(\"content.progress\", input, {\n      label: input.label,\n      value: input.value,\n      ...(input.detail ? { detail: input.detail } : {}),\n    });\n  },\n\n  empty(input: NodeBase & {\n    title: string;\n    description?: string;\n    reason?: \"no-data\" | \"filtered\" | \"unavailable\" | \"not-applicable\";\n  }): AuthoringNode {\n    return leaf(\"content.empty\", input, {\n      title: input.title,\n      ...(input.description ? { description: input.description } : {}),\n      ...(input.reason ? { reason: input.reason } : {}),\n    });\n  },\n\n  form(input: NodeBase & {\n    fields: AuthoringNode[];\n    title?: string;\n    description?: string;\n  }): AuthoringNode {\n    return attachBase({\n      id: input.id,\n      type: \"form.root\",\n      props: authoringProps({ title: input.title, description: input.description }),\n      slots: { fields: input.fields },\n    }, input);\n  },\n\n  input(input: NodeBase & {\n    label: string;\n    inputType?: \"text\" | \"email\" | \"number\" | \"date\";\n    value?: AuthoringValue;\n    placeholder?: string;\n    description?: string;\n    required?: boolean;\n    disabled?: AuthoringValue;\n  }): AuthoringNode {\n    return leaf(\"form.input\", input, authoringProps({\n      label: input.label,\n      inputType: input.inputType,\n      value: input.value,\n      placeholder: input.placeholder,\n      description: input.description,\n      required: input.required,\n      disabled: input.disabled,\n    }));\n  },\n\n  select(input: NodeBase & {\n    label: string;\n    options?: AuthoringValue;\n    value?: AuthoringValue;\n    placeholder?: string;\n    description?: string;\n    required?: boolean;\n    disabled?: AuthoringValue;\n  }): AuthoringNode {\n    return leaf(\"form.select\", input, authoringProps({\n      label: input.label,\n      options: input.options,\n      value: input.value,\n      placeholder: input.placeholder,\n      description: input.description,\n      required: input.required,\n      disabled: input.disabled,\n    }));\n  },\n\n  toggle(input: NodeBase & {\n    label: string;\n    description?: string;\n    checked?: AuthoringValue;\n    disabled?: AuthoringValue;\n  }): AuthoringNode {\n    return leaf(\"form.toggle\", input, authoringProps({\n      label: input.label,\n      description: input.description,\n      checked: input.checked,\n      disabled: input.disabled,\n    }));\n  },\n\n  button(input: NodeBase & {\n    label: string;\n    type?: \"button\" | \"submit\" | \"reset\";\n    variant?: \"default\" | \"secondary\" | \"destructive\";\n    disabled?: AuthoringValue;\n  }): AuthoringNode {\n    return leaf(\"form.button\", input, authoringProps({\n      label: input.label,\n      type: input.type,\n      variant: input.variant,\n      disabled: input.disabled,\n    }));\n  },\n\n  artifact(artifact: Artifact, options: {\n    id?: string;\n    events?: Record<string, string>;\n    evidence?: string[];\n  } = {}): AuthoringNode {\n    return attachBase({\n      id: options.id ?? artifact.id,\n      type: `artifact.${artifact.kind}`,\n      props: projectArtifactToNodeProps(artifact),\n    }, options);\n  },\n});\n\nexport function projectArtifactToNodeProps(\n  artifact: Artifact,\n): Record<string, AuthoringValue> {\n  const {\n    protocolVersion: _protocolVersion,\n    kind: _kind,\n    id: _id,\n    ...props\n  } = artifact;\n  return props as unknown as Record<string, AuthoringValue>;\n}\n\nexport function defineSurface(\n  input: AuthoringNode | ArtifactProposal,\n): ArtifactProposal {\n  if (\"root\" in input) return input;\n  return { root: input };\n}\n","import { assertJsonValue } from \"./canonical\";\nimport { CompilerCatalog, defaultCompilerCatalog } from \"./catalog\";\nimport { compilerDiagnostic, CompilerDiagnosticError } from \"./diagnostics\";\nimport {\n  createDocumentPolicy,\n  DEFAULT_DOCUMENT_POLICY,\n  prepareInformationFlow,\n} from \"./information-flow\";\nimport { normalizeSurface } from \"./normalize\";\nimport { createValidatedArtifactPart, isArtifactPart } from \"./part\";\nimport { compilePrompt } from \"./prompt\";\nimport { runBoundedRepair } from \"./repair\";\nimport type {\n  AdapterContext,\n  ArtifactPart,\n  ArtifactTransportAdapter,\n  AuthoringCodec,\n  CompilerPreset,\n  DocumentPolicy,\n  DocumentSummary,\n  GenerationLimits,\n  InformationFlowLabel,\n  JsonValue,\n  LabeledModelInput,\n  ModelVisibleCapability,\n  ModelVisibleMessageTemplate,\n  PromptBundle,\n  RenderMode,\n  RepairProvider,\n  SurfaceProfile,\n} from \"./types\";\n\nexport type TurnMessage = {\n  role: \"system\" | \"user\" | \"assistant\" | \"tool\" | string;\n  content: JsonValue;\n  provenanceRef?: string;\n  label?: InformationFlowLabel;\n};\n\nexport type LabeledDocumentSummary = {\n  value: DocumentSummary;\n  provenanceRef: string;\n  label: InformationFlowLabel;\n};\n\nexport type PrepareTurnInput<TMessage extends TurnMessage = TurnMessage> = {\n  messages: readonly TMessage[];\n  profile?: SurfaceProfile;\n  preset?: CompilerPreset;\n  catalog?: CompilerCatalog;\n  documentPolicy?: DocumentPolicy;\n  modelInputs?: readonly LabeledModelInput[];\n  requestedNodeTypes?: readonly string[];\n  task?: string;\n  codec?: AuthoringCodec;\n  renderMode?: RenderMode;\n  capabilityDescriptors?: readonly ModelVisibleCapability[];\n  messageTemplateDescriptors?: readonly ModelVisibleMessageTemplate[];\n  parentDocumentSummaries?: readonly LabeledDocumentSummary[];\n  resourceIds?: readonly string[];\n  locale?: string;\n  limits?: Partial<GenerationLimits>;\n};\n\nexport type AcceptArtifactOptions = {\n  repairProvider?: RepairProvider;\n  parentRevisionId?: string;\n  headPreconditions?: Readonly<Record<string, string>>;\n  statePreconditions?: Readonly<Record<string, string>>;\n};\n\nexport type PreparedTurn<TMessage extends TurnMessage = TurnMessage> = {\n  readonly system: string;\n  readonly messages: readonly TMessage[];\n  readonly modelInputs: readonly LabeledModelInput[];\n  readonly tools: Readonly<{ renderArtifact: PromptBundle[\"tool\"] }>;\n  readonly providerSchema: PromptBundle[\"providerSchema\"];\n  readonly bundle: Readonly<PromptBundle>;\n  readonly context: Readonly<AdapterContext>;\n  accept<TProviderOutput>(\n    output: TProviderOutput,\n    adapter: ArtifactTransportAdapter<TProviderOutput, unknown>,\n    options?: AcceptArtifactOptions,\n  ): Promise<ArtifactPart>;\n  respond<TResponse>(\n    part: ArtifactPart,\n    adapter: ArtifactTransportAdapter<unknown, TResponse>,\n  ): Promise<TResponse>;\n};\n\nfunction labelFromPolicy(policy: DocumentPolicy): InformationFlowLabel {\n  return {\n    scopeRef: policy.scopeRef,\n    sensitivity: policy.sensitivity,\n    persistence: policy.persistence,\n    allowedSinks: [...policy.allowedSinks],\n    ...(policy.expiresAt ? { expiresAt: policy.expiresAt } : {}),\n  };\n}\n\nfunction messageInput(\n  message: TurnMessage,\n  index: number,\n  defaultLabel: InformationFlowLabel,\n): LabeledModelInput {\n  try {\n    assertJsonValue(message.content, `/messages/${index}/content`);\n  } catch {\n    throw new CompilerDiagnosticError([compilerDiagnostic({\n      phase: \"decode\",\n      code: \"message.non_json_content\",\n      message: \"Provider-neutral messages must contain JSON-compatible content.\",\n      path: `/messages/${index}/content`,\n      recoverable: false,\n      modelCorrectable: false,\n    })]);\n  }\n  return {\n    provenanceRef: message.provenanceRef ?? `message:${index}`,\n    kind: \"message\",\n    content: { role: message.role, content: message.content },\n    label: message.label ?? defaultLabel,\n  };\n}\n\nfunction descriptorInput(\n  id: string,\n  kind: LabeledModelInput[\"kind\"],\n  content: unknown,\n  label: InformationFlowLabel,\n): LabeledModelInput {\n  assertJsonValue(content);\n  return { provenanceRef: id, kind, content, label };\n}\n\nfunction taskText(messages: readonly TurnMessage[], explicit?: string): string {\n  if (explicit) return explicit.slice(0, 32_000);\n  let output = \"\";\n  const collect = (value: JsonValue): void => {\n    if (output.length >= 32_000) return;\n    if (typeof value === \"string\") {\n      output += ` ${value}`;\n    } else if (Array.isArray(value)) {\n      value.forEach(collect);\n    } else if (value && typeof value === \"object\") {\n      Object.values(value).forEach(collect);\n    }\n  };\n  messages.forEach(({ content }) => collect(content));\n  return output.slice(0, 32_000);\n}\n\nfunction transportFailure(): CompilerDiagnosticError {\n  return new CompilerDiagnosticError([compilerDiagnostic({\n    phase: \"transport\",\n    code: \"adapter.extraction_failed\",\n    message: \"The provider adapter did not produce an artifact proposal.\",\n    recoverable: true,\n    modelCorrectable: false,\n  })]);\n}\n\nexport async function prepareTurn<TMessage extends TurnMessage>(\n  input: PrepareTurnInput<TMessage>,\n): Promise<PreparedTurn<TMessage>> {\n  const catalog = input.catalog ?? defaultCompilerCatalog;\n  const policy = input.documentPolicy ?? DEFAULT_DOCUMENT_POLICY;\n  const defaultLabel = labelFromPolicy(policy);\n  const messageInputs = input.messages.map((message, index) => messageInput(message, index, defaultLabel));\n  const capabilities = [...(input.capabilityDescriptors ?? [])];\n  const templates = [...(input.messageTemplateDescriptors ?? [])];\n  const summaries = [...(input.parentDocumentSummaries ?? [])];\n  const descriptorInputs = [\n    ...capabilities.map((descriptor) => descriptorInput(\n      `capability:${descriptor.capabilityId}@${descriptor.grantVersion}`,\n      \"tool-result\",\n      descriptor,\n      defaultLabel,\n    )),\n    ...templates.map((descriptor) => descriptorInput(\n      `message-template:${descriptor.templateGrantId}@${descriptor.templateGrantVersion}`,\n      \"tool-result\",\n      descriptor,\n      defaultLabel,\n    )),\n    ...summaries.map(({ value, provenanceRef, label }) => descriptorInput(\n      provenanceRef,\n      \"parent-summary\",\n      value,\n      label,\n    )),\n  ];\n  const baseInputs = [...messageInputs, ...(input.modelInputs ?? []), ...descriptorInputs];\n  const baseFlow = prepareInformationFlow(baseInputs, policy);\n  const includedMessageRefs = new Set(baseFlow.included\n    .filter(({ kind }) => kind === \"message\")\n    .map(({ provenanceRef }) => provenanceRef));\n  const messages = input.messages.filter((message, index) => includedMessageRefs.has(\n    message.provenanceRef ?? `message:${index}`,\n  ));\n  const authorizedSummaries = summaries.filter(({ provenanceRef }) => baseFlow.included.some(\n    (modelInput) => modelInput.provenanceRef === provenanceRef,\n  )).map(({ value }) => value);\n\n  const compile = (generationTaintHash: string) => compilePrompt({\n    catalog,\n    preset: input.preset,\n    profile: input.profile,\n    documentPolicy: policy,\n    generationTaintHash,\n    requestedNodeTypes: input.requestedNodeTypes,\n    task: taskText(messages, input.task),\n    codec: input.codec,\n    renderMode: input.renderMode,\n    capabilityDescriptors: capabilities,\n    messageTemplateDescriptors: templates,\n    locale: input.locale,\n    limits: input.limits,\n    parentDocumentSummaries: authorizedSummaries,\n  });\n\n  const preliminary = compile(baseFlow.generationTaintHash);\n  const exampleInputs = preliminary.examples.map((example) => descriptorInput(\n    `compiler-example:${preliminary.catalogSlice.sliceHash}:${example.id}`,\n    \"example\",\n    example as unknown as JsonValue,\n    defaultLabel,\n  ));\n  const flow = prepareInformationFlow([...baseInputs, ...exampleInputs], policy);\n  const bundle = compile(flow.generationTaintHash);\n  const context: AdapterContext = Object.freeze({\n    protocolVersion: \"2.0\",\n    contractFingerprint: bundle.contractFingerprint,\n    promptBundleHash: bundle.promptBundleHash,\n    generationTaintHash: bundle.generationTaintHash,\n    codec: bundle.codec,\n    renderMode: bundle.renderMode,\n  });\n  const resourceIds = [...new Set(input.resourceIds ?? [])];\n  const capabilityIds = capabilities.map(({ capabilityId }) => capabilityId);\n  const messageTemplateIds = templates.map(({ templateGrantId }) => templateGrantId);\n\n  const turn: PreparedTurn<TMessage> = {\n    system: bundle.system,\n    messages: Object.freeze([...messages]),\n    modelInputs: Object.freeze([...flow.included]),\n    tools: Object.freeze({ renderArtifact: bundle.tool }),\n    providerSchema: bundle.providerSchema,\n    bundle,\n    context,\n    async accept<TProviderOutput>(\n      output: TProviderOutput,\n      adapter: ArtifactTransportAdapter<TProviderOutput, unknown>,\n      options: AcceptArtifactOptions = {},\n    ): Promise<ArtifactPart> {\n      if (!adapter.id.trim()) throw transportFailure();\n      let proposal: unknown;\n      try {\n        proposal = await adapter.extractProposal(output, context);\n      } catch {\n        throw transportFailure();\n      }\n      if (proposal === undefined) throw transportFailure();\n      const snapshot = await runBoundedRepair({\n        initialValue: proposal,\n        bundle,\n        informationFlow: flow.joinedLabel,\n        provider: options.repairProvider,\n        parentRevisionId: options.parentRevisionId,\n        headPreconditions: options.headPreconditions,\n        statePreconditions: options.statePreconditions,\n        validate: (candidate) => normalizeSurface(candidate, {\n          catalog: bundle.catalogSlice,\n          limits: bundle.limits,\n          allowedResourceIds: resourceIds,\n          capabilityIds,\n          messageTemplateIds,\n        }),\n      });\n      return createValidatedArtifactPart(snapshot, context);\n    },\n    async respond<TResponse>(\n      part: ArtifactPart,\n      adapter: ArtifactTransportAdapter<unknown, TResponse>,\n    ): Promise<TResponse> {\n      if (!isArtifactPart(part) || !adapter.encodePart) {\n        throw new CompilerDiagnosticError([compilerDiagnostic({\n          phase: \"transport\",\n          code: \"adapter.invalid_artifact_part\",\n          message: \"The transport can encode only a locally validated ArtifactPart.\",\n          severity: \"fatal\",\n          recoverable: false,\n          modelCorrectable: false,\n        })]);\n      }\n      try {\n        return await adapter.encodePart(part, context);\n      } catch {\n        throw new CompilerDiagnosticError([compilerDiagnostic({\n          phase: \"transport\",\n          code: \"adapter.encoding_failed\",\n          message: \"The provider adapter failed to encode the validated ArtifactPart.\",\n          recoverable: true,\n          modelCorrectable: false,\n        })]);\n      }\n    },\n  };\n  return Object.freeze(turn);\n}\n\nexport type ArtifactCompilerOptions = {\n  catalog?: CompilerCatalog;\n  preset?: CompilerPreset;\n  documentPolicy?: DocumentPolicy;\n  codec?: AuthoringCodec;\n  renderMode?: RenderMode;\n  limits?: Partial<GenerationLimits>;\n};\n\nexport function createArtifactCompiler(options: ArtifactCompilerOptions = {}) {\n  const catalog = options.catalog ?? defaultCompilerCatalog;\n  const policy = options.documentPolicy ?? DEFAULT_DOCUMENT_POLICY;\n  return Object.freeze({\n    catalog,\n    prepareTurn<TMessage extends TurnMessage>(input: PrepareTurnInput<TMessage>) {\n      return prepareTurn({\n        ...input,\n        catalog: input.catalog ?? catalog,\n        preset: input.preset ?? options.preset,\n        documentPolicy: input.documentPolicy ?? policy,\n        codec: input.codec ?? options.codec,\n        renderMode: input.renderMode ?? options.renderMode,\n        limits: { ...options.limits, ...input.limits },\n      });\n    },\n  });\n}\n\nexport { createDocumentPolicy };\n"],"mappings":";;;;;;AAGA,MAAM,sCAAsB,IAAI,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