{"version":3,"sources":["../route.ts","../core/ir-types.ts","../core/kind-schema.types.ts","../core/fingerprint.ts","../core/normalize.ts","../core/envelope-read.ts","../directives/grammar.ts","../route/kind-route.ts","../wire/partial-kind.ts","../route/partial-kind-route.ts","../route/route-binding.ts"],"sourcesContent":["/**\n * `@ai-matrx/content-ir/route` — the pure render decisions, callable\n * outside React (reducers, stream accumulators, server-side shape doctors,\n * tests): THE KIND ROUTE, the provisional (streaming partial kinds) route,\n * and the per-host binding factory. Pure TS — deliberately unstamped.\n */\nexport * from \"./route/kind-route\";\nexport * from \"./route/partial-kind-route\";\nexport * from \"./route/route-binding\";\n","/**\n * The canonical IR contract for structured content.\n *\n * Every source (live agent stream, DB reload, Python-preprocessed results,\n * notes, any future surface) is normalized into these shapes exactly once.\n * Anything already carrying this IR passes through downstream layers by\n * reference — see `core/normalize.ts` for the idempotence law.\n *\n * This file is pure types + path helpers. No React, no Redux, no IO.\n */\n\n/** Path of a value inside a parsed region (object keys + array indices). */\nexport type IrPath = Array<string | number>;\n\n/**\n * How a node's kind was (or wasn't) established.\n *\n * 🚨 `unverified` IS NOT `raw`, AND THE DIFFERENCE IS LOAD-BEARING (Arman's\n * ruling, 2026-08-29). \"We checked it and it is wrong\" and \"we had nothing to\n * check it with\" are opposite facts about a payload, and collapsing them cost\n * ~221 live kinds their component overnight: a kind whose schema never loaded\n * degraded to `raw`, the render route read `raw` as \"broken instance\", and\n * perfectly valid payloads were dumped as key/value lists instead of reaching\n * the component the user built. A consumer that treats `unverified` as a\n * failure is reintroducing that outage — the data is intact and MAY be\n * entirely valid; all that is missing is the schema that would prove it.\n */\nexport type IrKindState =\n  | \"resolved\" // __kind seen + schema validated\n  | \"speculative\" // committed from parent itemKinds before __kind arrived\n  | \"pending_kind\" // object open, no __kind yet, no speculation possible\n  | \"pending_schema\" // kind known, registry cold-fetch in flight\n  | \"unverified\" // kind known, NO schema was ever available — never checked\n  | \"raw\"; // checked and FAILED, or structurally broken\n\n/**\n * System-level zero-data-loss channel. Unknown keys are NEVER merged into a\n * node's `value` (they'd be indistinguishable from schema fields); they are\n * carried here verbatim — Protobuf unknown-fields discipline. Distinct from\n * any domain-level `additionalDetails` field, which is an ordinary schema\n * field inside `value`.\n */\nexport interface IrResidue {\n  /** Keys present in the source object but absent from the kind schema. */\n  extra: Record<string, unknown> | null;\n  /** Optional schema fields the source never provided. */\n  optionalMissing: string[] | null;\n  /** Structured warnings attached during parsing (speculation backtracks, truncation, …). */\n  notices: Array<{ code: string; message: string; at?: number }> | null;\n}\n\n/** Which wire syntax carried the kind discriminator for a node. */\nexport type IrDiscriminator =\n  | { format: \"json\"; key: \"__kind\" }\n  | { format: \"xml\"; tag: string }\n  | { format: \"fence\"; language: string };\n\n/** A schema-shaped structured node. Children live inside `value` (and carry their own metadata via `nodeIndex`). */\nexport interface IrStructuredNode {\n  role: \"structured\";\n  /** Canonical kind slug. Empty string while pending. */\n  kind: string;\n  kindState: IrKindState;\n  discriminator: IrDiscriminator;\n  /** Region-relative path ([] = region root). */\n  path: IrPath;\n  status: \"streaming\" | \"complete\" | \"error\";\n  /** Compliant snapshot: schema fields + __kind ONLY. Unknown keys → residue. */\n  value: Record<string, unknown>;\n  residue: IrResidue | null;\n}\n\n/** Envelope version. Bump = migration point for persisted envelopes. */\nexport const IR_VERSION = 1 as const;\n\n/** Reserved key carrying the envelope inside RenderBlockPayload.data. */\nexport const IR_ENVELOPE_KEY = \"__ir\" as const;\n\n/**\n * One parsed region's canonical form. Serializable (plain JSON), carried on\n * render blocks (`data.__ir`), persisted on artifacts and message metadata,\n * and — with `engine: \"py-block-detector\"` — accepted pre-built from Python.\n */\nexport interface CanonicalBlockIR {\n  v: typeof IR_VERSION;\n  /** Provenance: which implementation produced this envelope. */\n  engine: \"fe-kind-parser\" | \"py-block-detector\";\n  /** Stable hash of the region source text — the idempotence / cache key. */\n  fingerprint: string;\n  root: IrStructuredNode;\n  /**\n   * pathKey → node metadata for per-path readers (child kinds under root).\n   * Carries each child node's residue — child snapshot values inside\n   * `root.value` hold schema fields only, so WITHOUT this the envelope would\n   * silently drop nested unknown keys (zero-data-loss violation).\n   */\n  nodeIndex?: Record<\n    string,\n    Pick<IrStructuredNode, \"kind\" | \"kindState\" | \"status\"> & {\n      residue?: IrResidue | null;\n    }\n  >;\n}\n\n/** Normalizer output segment: prose stays raw text; structured regions carry IR. */\nexport type CanonicalSegment =\n  | { role: \"text\"; content: string }\n  | {\n      role: \"block\";\n      blockType: string;\n      content: string;\n      ir: CanonicalBlockIR | null;\n    };\n\nexport interface CanonicalContent {\n  v: typeof IR_VERSION;\n  segments: CanonicalSegment[];\n}\n\n// ---------------------------------------------------------------------------\n// Path helpers — the ONE implementation. Consumers must not roll their own.\n// ---------------------------------------------------------------------------\n\nexport function irPathKey(path: IrPath): string {\n  return path.map((segment) => String(segment)).join(\".\");\n}\n\nexport function irPathsEqual(left: IrPath, right: IrPath): boolean {\n  if (left.length !== right.length) return false;\n  for (let i = 0; i < left.length; i++) {\n    if (left[i] !== right[i]) return false;\n  }\n  return true;\n}\n\nexport function irPathIsUnderOrEqual(path: IrPath, prefix: IrPath): boolean {\n  if (path.length < prefix.length) return false;\n  for (let i = 0; i < prefix.length; i++) {\n    if (path[i] !== prefix[i]) return false;\n  }\n  return true;\n}\n\n/** Human label for a path (\"root\", \"cards[2].front\"). */\nexport function irPathLabel(path: IrPath): string {\n  if (path.length === 0) return \"root\";\n\n  const parts: string[] = [];\n  for (const segment of path) {\n    if (typeof segment === \"number\") {\n      parts[parts.length - 1] += `[${segment}]`;\n    } else {\n      parts.push(String(segment));\n    }\n  }\n  return parts.join(\".\");\n}\n\n/** True when every residue channel is empty — normalize to null instead. */\nexport function isEmptyResidue(residue: IrResidue): boolean {\n  return (\n    (residue.extra === null || Object.keys(residue.extra).length === 0) &&\n    (residue.optionalMissing === null ||\n      residue.optionalMissing.length === 0) &&\n    (residue.notices === null || residue.notices.length === 0)\n  );\n}\n","/**\n * KindSchema — the data-defined field model for a registered kind.\n *\n * `__kind` (KIND_KEY) is the carried discriminator: it is NOT part of a\n * kind's field map; the parser enforces it via `KindSchema.kind` and stamps\n * it onto every compliant snapshot.\n *\n * Moved from app/(dev)/demos/json-block-detector/kind-schemas.ts.\n *\n * 2026-07-15 expressivity extension (A2) — four constructs the Python-owned\n * pydantic schemas need that the v1 vocabulary could not express:\n *   - `{type:\"json\"}` / `{type:\"json[]\"}` — any JSON value / array of any\n *     JSON values (pydantic bare `Any` fields, `items: {}` arrays, `{}`\n *     schemas). A `json` value is implicitly nullable — `null` IS a JSON\n *     value — so `nullable` is meaningless (and ignored) on it.\n *   - `record` values widened to `\"json\"` (pydantic `dict[str, Any]` /\n *     `additionalProperties: true`).\n *   - `union` may now carry `kinds` (object unions — anyOf over kind refs,\n *     optionally mixed with scalars). Refs externalize to `kind_edge` rows\n *     exactly like `array.itemKinds`.\n *   - `KindSchema.root` — a NON-OBJECT root form: the kind's VALUE is the\n *     root field itself (scalar / array / json / open object), not a `__kind`\n *     object with fields. Root-form kinds are data-only: the streaming\n *     `__kind` parser cannot type them (a scalar cannot carry a\n *     discriminator) and refuses them loudly; validation goes through the\n *     emitted JSON Schema (ajv / Pydantic). `root` and a non-empty `fields`\n *     are mutually exclusive.\n *   - `inline_object.open` — `additionalProperties: true`; fixes the\n *     open-empty-object defect where an open `inline_object{fields:{}}`\n *     materialized as CLOSED (schema_proposal / item_presentation class).\n *\n * 2026-07-15 input-semantics extension (W3-A, agent-input bridge) — the\n * constructs the Wave-1 sufficiency survey of all 1,529 live agent variables\n * showed FieldSchema could not carry, added so `AgentVariable` ⇄ kind\n * conversion is faithful:\n *   - `FieldBase.description` — human guidance; round-trips JSON Schema\n *     `description` and VariableDefinition `helpText`.\n *   - `FieldBase.default` — the field's default VALUE (JSON Schema `default`,\n *     VariableDefinition `defaultValue`). Annotation-level: validators never\n *     apply it; emitters carry it verbatim.\n *   - `enum.open` — \"one of these options OR any string\" (the FE's\n *     `allowOther`). Emits as `anyOf: [{type:\"string\", enum}, {type:\"string\"}]`\n *     so the option set survives instead of widening to bare `string`.\n *   - `number` bounds `min`/`max`/`step` — JSON Schema\n *     `minimum`/`maximum`/`multipleOf` (number/slider components).\n *   - `string[].values` (+ `open`) — an items-enum: array of strings drawn\n *     from an option set (checkbox components), `open` meaning the set is\n *     advisory (`allowOther` on a multi-select).\n * Picklist bindings, scope bindings, and media component identity are\n * PROVENANCE, not structure — they never enter FieldSchema; the bridge\n * carries them out-of-band (see convert/kind-variable-bridge.ts sidecar).\n */\n\n/** System discriminator — hardcoded, not part of per-kind field schemas. */\nexport const KIND_KEY = \"__kind\";\n\nexport type ScalarFieldType = \"string\" | \"number\" | \"boolean\";\n\nexport type ArrayItemScalarType = \"string\" | \"number\" | \"boolean\";\n\n/** Value domain of a `record` field — typed scalars, or any JSON value. */\nexport type RecordValueType = ArrayItemScalarType | \"json\";\n\ntype FieldBase = {\n  required?: boolean;\n  nullable?: boolean;\n  /** Human guidance — JSON Schema `description` / variable `helpText`. */\n  description?: string;\n  /**\n   * Default VALUE (JSON Schema `default` / variable `defaultValue`).\n   * Annotation-level: validators never apply it; emitters carry it verbatim.\n   */\n  default?: unknown;\n};\n\nexport type FieldSchema =\n  | (FieldBase & { type: \"string\" | \"boolean\" })\n  | (FieldBase & {\n      type: \"number\";\n      /** Inclusive lower bound — JSON Schema `minimum`. */\n      min?: number;\n      /** Inclusive upper bound — JSON Schema `maximum`. */\n      max?: number;\n      /** Increment — JSON Schema `multipleOf`. Annotation-level in the parser. */\n      step?: number;\n    })\n  | (FieldBase & {\n      type: \"string[]\";\n      /** Items-enum: each item must be one of these values (checkbox option sets). */\n      values?: string[];\n      /** With `values`: the set is advisory — any string item is also legal (`allowOther`). */\n      open?: boolean;\n    })\n  | (FieldBase & { type: \"number[]\" | \"boolean[]\" })\n  | (FieldBase & { type: \"json\" })\n  | (FieldBase & { type: \"json[]\" })\n  | (FieldBase & { type: \"array\"; itemKinds: string[] })\n  | (FieldBase & { type: \"object\"; kind: string })\n  | (FieldBase & {\n      type: \"inline_object\";\n      fields: Record<string, FieldSchema>;\n      /** additionalProperties: true — unknown keys are legal, not residue-only. */\n      open?: boolean;\n    })\n  | (FieldBase & { type: \"record\"; values: RecordValueType })\n  | (FieldBase & {\n      type: \"enum\";\n      values: string[];\n      /** \"One of these OR any string\" — the option set is advisory (`allowOther`). */\n      open?: boolean;\n    })\n  | (FieldBase & {\n      type: \"union\";\n      scalars: Array<\"string\" | \"number\" | \"boolean\">;\n      /** Object union members — kind refs (anyOf of $refs), may mix with scalars. */\n      kinds?: string[];\n    });\n\n/**\n * Domain fields only — __kind is enforced by the parser via KindSchema.kind\n * (block slug). A kind with `root` set has NO field map (fields stays `{}`):\n * its value is the root field's type at the top level. See the module header.\n */\nexport type KindSchema = {\n  kind: string;\n  fields: Record<string, FieldSchema>;\n  /** Non-object root form — mutually exclusive with a non-empty `fields`. */\n  root?: FieldSchema;\n};\n\nexport function readObjectKind(value: Record<string, unknown>): string | null {\n  const kind = value[KIND_KEY];\n  return typeof kind === \"string\" ? kind : null;\n}\n\nexport function isScalarArrayType(\n  type: FieldSchema[\"type\"],\n): type is \"string[]\" | \"number[]\" | \"boolean[]\" {\n  return type === \"string[]\" || type === \"number[]\" || type === \"boolean[]\";\n}\n\nexport function scalarArrayItemType(\n  type: \"string[]\" | \"number[]\" | \"boolean[]\",\n): ArrayItemScalarType {\n  if (type === \"number[]\") return \"number\";\n  if (type === \"boolean[]\") return \"boolean\";\n  return \"string\";\n}\n\n/**\n * Does this field's value domain accept ANY JSON shape (object/array/scalar/\n * null alike)? True for `json` and `json[]` ITEMS — the parser treats the\n * subtree under such a field as opaque (no kind identification, no raw_object\n * degradation: unknown structure is the declared contract, not a failure).\n */\nexport function isJsonAnyField(field: FieldSchema): boolean {\n  return field.type === \"json\" || field.type === \"json[]\";\n}\n","/**\n * Stable, fast content fingerprint for IR envelopes.\n *\n * Used as the idempotence / cache key: a persisted CanonicalBlockIR is only\n * reused when its fingerprint matches the region source text it claims to\n * represent. Not cryptographic — collision resistance at the \"same message,\n * same block\" scale is all that's required, and it must be synchronous and\n * dependency-free (runs per region on the hot streaming path).\n *\n * FNV-1a 32-bit, applied twice with different seeds and concatenated, so a\n * single 32-bit collision doesn't alias two regions.\n *\n * `createFingerprinter` is the incremental form for live streams: feeding\n * chunks one at a time yields EXACTLY the same fingerprint as\n * `fingerprintText` over the concatenation — sessions never re-hash the\n * whole source per flush.\n */\n\nconst SEED_A = 0x811c9dc5;\nconst SEED_B = 0x01000193;\n\nfunction fnv1aStep(hash: number, input: string): number {\n  let h = hash >>> 0;\n  for (let i = 0; i < input.length; i++) {\n    h ^= input.charCodeAt(i);\n    // h *= 16777619 (FNV prime), in 32-bit space without BigInt.\n    h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;\n  }\n  return h >>> 0;\n}\n\nexport interface Fingerprinter {\n  push(chunk: string): void;\n  /** Fingerprint of everything pushed so far. */\n  current(): string;\n}\n\nexport function createFingerprinter(): Fingerprinter {\n  let a = SEED_A;\n  let b = SEED_B;\n  let length = 0;\n\n  return {\n    push(chunk: string): void {\n      a = fnv1aStep(a, chunk);\n      b = fnv1aStep(b, chunk);\n      length += chunk.length;\n    },\n    current(): string {\n      return `${length.toString(36)}-${a.toString(36)}${b.toString(36)}`;\n    },\n  };\n}\n\nexport function fingerprintText(source: string): string {\n  const hasher = createFingerprinter();\n  hasher.push(source);\n  return hasher.current();\n}\n","/**\n * Idempotent normalizer — the \"recognizes its own work\" property.\n *\n * THE LAW: anything already carrying a current CanonicalBlockIR envelope is\n * returned BY REFERENCE — zero reprocessing, reference equality holds, React\n * bails out. Only raw text (a detected region's source) is ever parsed, and\n * it is parsed exactly once per fingerprint.\n *\n * `normalizeJsonRegion` is the one-shot mode: the same KindStreamParser that\n * powers live streams, run over a complete region string (DB reloads,\n * reconcile passes), assembled through the same IrTree the live session uses\n * — stream and static output are structurally identical by construction.\n */\n\nimport { fingerprintText } from \"./fingerprint\";\nimport {\n  IR_VERSION,\n  type CanonicalBlockIR,\n  type IrDiscriminator,\n  type IrStructuredNode,\n} from \"./ir-types\";\nimport { KIND_KEY, type KindSchema } from \"./kind-schema.types\";\nimport { IrTree } from \"./ir-tree\";\nimport {\n  createKindStreamParser,\n  type SchemaResolver,\n} from \"./kind-parser\";\n\nexport function isCanonicalBlockIR(value: unknown): value is CanonicalBlockIR {\n  if (typeof value !== \"object\" || value === null) return false;\n  const candidate = value as Partial<CanonicalBlockIR>;\n  return (\n    candidate.v === IR_VERSION &&\n    typeof candidate.fingerprint === \"string\" &&\n    typeof candidate.engine === \"string\" &&\n    typeof candidate.root === \"object\" &&\n    candidate.root !== null &&\n    (candidate.root as IrStructuredNode).role === \"structured\"\n  );\n}\n\n/**\n * The idempotence fast path: return the existing envelope by reference when\n * it still describes this source text; null means \"parse needed\".\n */\nexport function reuseEnvelopeIfCurrent(\n  source: string,\n  candidate: unknown,\n): CanonicalBlockIR | null {\n  if (!isCanonicalBlockIR(candidate)) return null;\n  return candidate.fingerprint === fingerprintText(source) ? candidate : null;\n}\n\nexport interface NormalizeJsonRegionOptions {\n  schemas: Record<string, KindSchema> | SchemaResolver;\n  /** Known-context root prediction (agent output schema, fence hint). */\n  expectedRootKind?: string;\n  /**\n   * Pass a previously persisted envelope (message metadata, artifact row);\n   * when its fingerprint matches, it is returned as-is and nothing parses.\n   */\n  existing?: unknown;\n}\n\nexport interface CompleteValueEnvelopeOptions {\n  /**\n   * Wire discriminator recorded on the root node — which syntax established\n   * the kind. Defaults to the JSON `__kind` key; XML surfaces converging at\n   * region finalize pass `xmlDiscriminator(tag)` so round-trip serializers\n   * know the original arrival format.\n   */\n  discriminator?: IrDiscriminator;\n}\n\n/**\n * Build a resolved, complete envelope directly from an already-structured\n * value (a persisted artifact's `content.data` object, or a completed XML\n * region's strategy output). This is the zero-reprocessing rehydration path:\n * the value IS the reconstructed region value (schema fields + residue extras\n * merged at persist time), so no tokenizer/parser run is needed — the\n * envelope wraps it verbatim. The fingerprint hashes the canonical value\n * serialization, so any two paths producing the same value produce the SAME\n * envelope (stream ≡ static by construction).\n */\nexport function envelopeFromCompleteValue(\n  value: Record<string, unknown>,\n  kind: string,\n  options?: CompleteValueEnvelopeOptions,\n): CanonicalBlockIR {\n  return {\n    v: IR_VERSION,\n    engine: \"fe-kind-parser\",\n    fingerprint: fingerprintText(JSON.stringify(value)),\n    root: {\n      role: \"structured\",\n      kind,\n      kindState: \"resolved\",\n      discriminator: options?.discriminator ?? { format: \"json\", key: KIND_KEY },\n      path: [],\n      status: \"complete\",\n      value,\n      residue: null,\n    },\n  };\n}\n\n/** One-shot: complete region text in → canonical envelope out. */\nexport function normalizeJsonRegion(\n  source: string,\n  options: NormalizeJsonRegionOptions,\n): CanonicalBlockIR {\n  const reused = reuseEnvelopeIfCurrent(source, options.existing);\n  if (reused) return reused;\n\n  const tree = new IrTree();\n  const parser = createKindStreamParser({\n    schemas: options.schemas,\n    ...(options.expectedRootKind !== undefined && {\n      expectedRootKind: options.expectedRootKind,\n    }),\n    onEvent(event) {\n      tree.applyEvent(event);\n    },\n  });\n  parser.push(source);\n  parser.end();\n\n  return tree.buildEnvelope(fingerprintText(source));\n}\n","/**\n * PURE envelope ingestion — reading `metadata.__ir` off a block's metadata\n * and gating SERVER-BUILT envelopes at the wire boundary. Twin-safe: no\n * React / Redux / Supabase / host diagnostics — side effects (seeding the\n * region-envelope memo, screaming to the Error Inspector) are injected by\n * the host through `InboundEnvelopeHooks`.\n *\n * The frontend host shell is `redux/render-block-envelope.ts` (binds the\n * hooks to `seedEnvelope` + `captureError`); aidream's Workflow Studio binds\n * its own. Contract: /Users/armanisadeghi/code/common-docs/systems/architecture/content-ir/FEATURE.md.\n */\n\nimport { IR_ENVELOPE_KEY, type CanonicalBlockIR } from \"./ir-types\";\nimport { isCanonicalBlockIR } from \"./normalize\";\n\n/** Read a CanonicalBlockIR envelope off a block's metadata (or anything). */\nexport function readEnvelope(\n  metadata: Record<string, unknown> | null | undefined,\n): CanonicalBlockIR | null {\n  const candidate = metadata?.[IR_ENVELOPE_KEY];\n  return isCanonicalBlockIR(candidate) ? candidate : null;\n}\n\n/** Pure classification of inbound metadata carrying (or not) an envelope. */\nexport type InboundEnvelopeVerdict =\n  | {\n      /** No `__ir` key — zero-touch pass, same reference back. */\n      outcome: \"absent\";\n      metadata: Record<string, unknown> | undefined;\n    }\n  | {\n      /** Valid CanonicalBlockIR — same reference back (idempotence law). */\n      outcome: \"valid\";\n      metadata: Record<string, unknown>;\n      envelope: CanonicalBlockIR;\n    }\n  | {\n      /** Malformed/foreign `__ir` — a COPY with `__ir` stripped. */\n      outcome: \"malformed\";\n      metadata: Record<string, unknown>;\n      engine: string;\n      raw: unknown;\n    };\n\nexport function classifyInboundEnvelopeMetadata(\n  metadata: Record<string, unknown> | null | undefined,\n): InboundEnvelopeVerdict {\n  if (!metadata || !(IR_ENVELOPE_KEY in metadata)) {\n    return { outcome: \"absent\", metadata: metadata ?? undefined };\n  }\n\n  const candidate = metadata[IR_ENVELOPE_KEY];\n  if (isCanonicalBlockIR(candidate)) {\n    return { outcome: \"valid\", metadata, envelope: candidate };\n  }\n\n  const engine =\n    typeof candidate === \"object\" &&\n    candidate !== null &&\n    typeof (candidate as { engine?: unknown }).engine === \"string\"\n      ? (candidate as { engine: string }).engine\n      : \"unknown\";\n\n  const { [IR_ENVELOPE_KEY]: _dropped, ...rest } = metadata;\n  void _dropped;\n  return { outcome: \"malformed\", metadata: rest, engine, raw: candidate };\n}\n\n/** Host-injected side effects for the inbound gate. */\nexport interface InboundEnvelopeHooks {\n  /** Called with every VALID envelope so later re-splits reuse it by reference. */\n  seedEnvelope?: (envelope: CanonicalBlockIR) => void;\n  /** Called LOUDLY for every malformed envelope — a bad envelope is a defect. */\n  reportMalformed?: (info: {\n    blockId: string;\n    engine: string;\n    raw: unknown;\n  }) => void;\n}\n\n/**\n * Ingest guard for SERVER-BUILT envelopes riding `metadata.__ir` on a\n * `render_block` event.\n *\n * - No `__ir` key → the SAME metadata reference back (zero-touch pass).\n * - Valid CanonicalBlockIR → the SAME metadata reference back (reuse-by-\n *   reference — the idempotence law) AND `hooks.seedEnvelope` fires so any\n *   later re-split of the same region source reuses it instead of parsing.\n * - Malformed/foreign `__ir` → a COPY with `__ir` stripped, plus a loud\n *   `hooks.reportMalformed`. A bad envelope must never poison kind routing\n *   or the persistence cache; dropping it degrades that block to the\n *   ordinary content-driven path, nothing more.\n */\nexport function sanitizeInboundEnvelopeMetadata(\n  metadata: Record<string, unknown> | null | undefined,\n  context: { blockId: string },\n  hooks: InboundEnvelopeHooks = {},\n): Record<string, unknown> | undefined {\n  const verdict = classifyInboundEnvelopeMetadata(metadata);\n  if (verdict.outcome === \"valid\") {\n    hooks.seedEnvelope?.(verdict.envelope);\n    return verdict.metadata;\n  }\n  if (verdict.outcome === \"malformed\") {\n    hooks.reportMalformed?.({\n      blockId: context.blockId,\n      engine: verdict.engine,\n      raw: verdict.raw,\n    });\n    return verdict.metadata;\n  }\n  return verdict.metadata;\n}\n","/**\n * Kind Directives — the grammar, the shell, and the position law (kernel edition).\n *\n * ONE system (Arman, 2026-08-23): the Matrx Envelope/Directive protocol and the\n * Content IR kind system are one system. A directive is an ordinary kind\n * instance — `{ \"__kind\": \"directive_v1_<class>_<noun>\", \"items\": [...] }` —\n * whose registered shape additionally carries execution semantics on the\n * server. This module is the PURE half, ported verbatim from the aidream source\n * of record (`packages/matrx-graph/matrx_graph/content_ir/directives.py`) so\n * every UI parses the grammar identically. It lives in the KERNEL because a\n * host that can parse a kind must be able to recognize a directive without a\n * second copy of these rules (matrx-frontend carried the only copy until\n * 2026-09-08; Workflow Studio had none and rendered directives as raw text).\n *\n * THE SLUG GRAMMAR — `directive_v<version>_<class>_<noun>`:\n *  - `directive_v` is a RESERVED prefix; a hand-authored kind may never claim it.\n *  - `<class>` comes from a CLOSED vocabulary, so parsing is unambiguous even\n *    though nouns contain underscores: `directive_v1_reference_create_task` is\n *    `(reference, \"create_task\")`.\n *  - capability is DERIVED from the class, never stored twice.\n */\n\nimport { KIND_KEY } from \"../core/kind-schema.types\";\n\nexport { KIND_KEY };\n\n/** The reserved slug prefix. ANY kind slug starting with this belongs to the Kind Directives protocol. */\nexport const RESERVED_PREFIX = \"directive_v\" as const;\n\n/** Current directive grammar version. */\nexport const DIRECTIVE_VERSION = 1 as const;\n\n/** The full prefix of a v1 directive slug. */\nexport const SLUG_PREFIX = `${RESERVED_PREFIX}${DIRECTIVE_VERSION}_` as const;\n\n/** The CLOSED class vocabulary. Closed is what makes the grammar parseable. */\nexport const CLASSES = [\n  \"reference\",\n  \"view\",\n  \"create\",\n  \"update\",\n  \"delete\",\n  \"action\",\n  \"validation\",\n  \"secret\",\n] as const;\n\nexport type DirectiveClass = (typeof CLASSES)[number];\n\nexport type DirectiveCapability = \"pure\" | \"sensitive\" | \"side_effect\";\n\n/** class → capability. DERIVED, never stored on a shape. */\nexport const CAPABILITY_BY_CLASS: Readonly<Record<DirectiveClass, DirectiveCapability>> = {\n  reference: \"pure\",\n  view: \"pure\",\n  validation: \"pure\",\n  secret: \"sensitive\",\n  create: \"side_effect\",\n  update: \"side_effect\",\n  delete: \"side_effect\",\n  action: \"side_effect\",\n};\n\n/** The classes that EXECUTE at an agent's output root — a durable side effect. */\nexport const SIDE_EFFECT_CLASSES: ReadonlySet<DirectiveClass> = new Set(\n  CLASSES.filter((c) => CAPABILITY_BY_CLASS[c] === \"side_effect\"),\n);\n\n/**\n * The classes that resolve to a LIVE VALUE inside content. STRICT BY CHOICE,\n * mirroring the server: exactly `reference` + `secret`.\n */\nexport const IN_CONTENT_CLASSES: ReadonlySet<DirectiveClass> = new Set<DirectiveClass>([\n  \"reference\",\n  \"secret\",\n]);\n\n/** A parsed directive slug. `slug` round-trips through `buildDirectiveSlug`. */\nexport interface DirectiveSlug {\n  slug: string;\n  version: number;\n  directiveClass: DirectiveClass;\n  noun: string;\n  capability: DirectiveCapability;\n  /** Executes at an agent's output root (THE position law, half one). */\n  executes: boolean;\n  /** Resolves to a live value inside content (THE position law, half two). */\n  inContent: boolean;\n}\n\nexport function isDirectiveClass(value: unknown): value is DirectiveClass {\n  return (\n    typeof value === \"string\" &&\n    Object.prototype.hasOwnProperty.call(CAPABILITY_BY_CLASS, value)\n  );\n}\n\n/**\n * Whether `slug` sits in the reserved Kind Directives namespace. Deliberately\n * broader than {@link parseDirectiveSlug}: a MALFORMED `directive_v…` slug is\n * still reserved, so authoring gates reject it instead of letting a near-miss\n * through as an ordinary kind.\n */\nexport function isReservedDirectiveSlug(slug: unknown): slug is string {\n  return typeof slug === \"string\" && slug.startsWith(RESERVED_PREFIX);\n}\n\n/** A noun/token: starts with a lowercase letter, then `[a-z0-9_]`. */\nfunction isToken(value: string): boolean {\n  return /^[a-z][a-z0-9_]*$/.test(value);\n}\n\n/**\n * `(\"create\", \"task\") → \"directive_v1_create_task\"`. THROWS on a class outside\n * the closed vocabulary or an ill-formed noun — a slug that cannot be parsed\n * back must never be mintable.\n */\nexport function buildDirectiveSlug(\n  directiveClass: string,\n  noun: string,\n  version: number = DIRECTIVE_VERSION,\n): string {\n  if (!isDirectiveClass(directiveClass)) {\n    throw new Error(\n      `unknown directive class ${JSON.stringify(directiveClass)}; the vocabulary is CLOSED: ${CLASSES.join(\", \")}.`,\n    );\n  }\n  if (typeof noun !== \"string\" || !isToken(noun)) {\n    throw new Error(\n      `invalid directive noun ${JSON.stringify(noun)} for class ${JSON.stringify(directiveClass)}: a noun is lowercase [a-z0-9_], starts with a letter, and is non-empty.`,\n    );\n  }\n  return `${RESERVED_PREFIX}${version}_${directiveClass}_${noun}`;\n}\n\n/**\n * Parse a directive slug, or `null` when `slug` is not one. A slug that IS in\n * the reserved namespace but does not parse returns `null` too — pair with\n * {@link isReservedDirectiveSlug} to tell \"ordinary kind\" from \"malformed\n * directive\"; every such caller treats the malformed case as an ERROR.\n */\nexport function parseDirectiveSlug(slug: unknown): DirectiveSlug | null {\n  if (!isReservedDirectiveSlug(slug)) return null;\n  const rest = slug.slice(RESERVED_PREFIX.length);\n  const firstSep = rest.indexOf(\"_\");\n  if (firstSep <= 0) return null;\n  const versionDigits = rest.slice(0, firstSep);\n  if (!/^[0-9]+$/.test(versionDigits)) return null;\n  const remainder = rest.slice(firstSep + 1);\n  const classSep = remainder.indexOf(\"_\");\n  if (classSep <= 0) return null;\n  const directiveClass = remainder.slice(0, classSep);\n  const noun = remainder.slice(classSep + 1);\n  if (!isDirectiveClass(directiveClass) || !isToken(noun)) return null;\n  return {\n    slug,\n    version: Number.parseInt(versionDigits, 10),\n    directiveClass,\n    noun,\n    capability: CAPABILITY_BY_CLASS[directiveClass],\n    executes: executesAtOutputRoot(directiveClass),\n    inContent: resolvesInContent(directiveClass),\n  };\n}\n\nexport function capabilityOf(directiveClass: DirectiveClass): DirectiveCapability {\n  return CAPABILITY_BY_CLASS[directiveClass];\n}\n\n/** THE position law, half one: only a side-effect class executes at an agent's output root. */\nexport function executesAtOutputRoot(directiveClass: string): boolean {\n  return isDirectiveClass(directiveClass) && SIDE_EFFECT_CLASSES.has(directiveClass);\n}\n\n/** THE position law, half two: only a pointer or a sensitive value resolves to a live value inside content. */\nexport function resolvesInContent(directiveClass: string): boolean {\n  return isDirectiveClass(directiveClass) && IN_CONTENT_CLASSES.has(directiveClass);\n}\n\n/**\n * The `__kind` of `obj` when it is in the reserved namespace, else null. Reads\n * the RESERVED namespace, not the parsed grammar, so a malformed directive is\n * still recognized as a directive (and rejected downstream with a real message).\n */\nexport function directiveSlugOf(obj: unknown): string | null {\n  if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return null;\n  const slug = (obj as Record<string, unknown>)[KIND_KEY];\n  return isReservedDirectiveSlug(slug) ? slug : null;\n}\n\n/** THE detector — a dict whose `__kind` is in the reserved namespace. */\nexport function isKindDirective(obj: unknown): boolean {\n  return directiveSlugOf(obj) !== null;\n}\n\n/**\n * The two-key shell, as it travels on the wire. A TYPE alias, not an interface,\n * so a shell is structurally assignable to `Record<string, unknown>`.\n */\nexport type KindDirectiveShell<Item = Record<string, unknown>> = {\n  /** The slug. Serialized FIRST — see the module doc. */\n  [KIND_KEY]: string;\n  items: Item[];\n};\n\n/**\n * Build the two-key shell with `__kind` FIRST. Never hand-assemble the object\n * literal elsewhere: JS preserves insertion order for string keys, and the\n * first-key rule is what lets the streaming detector type a directive early.\n */\nexport function buildKindDirective<Item>(slug: string, items: Item[]): KindDirectiveShell<Item> {\n  return { [KIND_KEY]: slug, items };\n}\n\n/**\n * Mid-stream recognition: the opening of a document whose FIRST key is a\n * reserved directive slug, before the closing brace has arrived. Used by\n * content splitters so a streaming envelope is typed early.\n */\nexport function looksLikeDirectiveHead(content: string): boolean {\n  const match = content.trimStart().match(/^\\{\\s*\"__kind\"\\s*:\\s*\"([^\"]*)/);\n  return !!match && isReservedDirectiveSlug(match[1]);\n}\n","/**\n * THE KIND ROUTE — the render flip, as a pure block transform.\n *\n * A block whose `metadata.__ir` envelope resolved a REGISTERED kind is routed\n * to that kind's component: via the legacy-bridge facet (`legacyBlockType` +\n * `toLegacyServerData`) when the kind has one, so the block enters the host's\n * existing renderer as its real type with envelope-derived serverData;\n * otherwise via the component resolver. Blocks with no envelope, an\n * unregistered kind, or no bridge facet pass through UNTOUCHED — the strangler\n * seam.\n *\n * This is where a bare/fenced JSON flashcard_set — which a text detector could\n * only ever call \"code\" — becomes real flashcards, live while streaming.\n *\n * PORTABILITY. This function was matrx-frontend's `react/kind-route.ts` and is\n * the single most-copied thing in the system: every UI that renders a kind has\n * to make exactly these decisions in exactly this order, and a second\n * implementation of them is a guaranteed divergence. It takes its registries,\n * its platform, and its error sink as an {@link KindRouteEnv} argument rather\n * than importing them, so it is callable from a reducer, a stream accumulator,\n * a test, or a React render — in any app.\n *\n * Semantics: `matrx-frontend/features/content-ir/docs/SHAPE_SYSTEM.md`\n * (registry, dual gate, `kind_component` resolution, rulings R1 + R6).\n */\n\nimport { envelopeFromCompleteValue, isJsonAnyField, readEnvelope, readObjectKind } from \"../core\";\nimport { isReservedDirectiveSlug } from \"../directives\";\nimport type { ComponentResolution } from \"../resolver/component-resolution.types\";\nimport type { IrRoutableBlock, KindRouteEnv } from \"../host/host-types\";\n\n/**\n * Runtime routing marker (the Shape System's verification hook): stamped on\n * `metadata.__ir_route` whenever a block routes AND the component resolver\n * produced the decision. `by` says which resolver tier answered (\"compiled\"\n * floor vs a warm `content_ir.kind_component` row) — the live proof of\n * registry-resolution vs hard-coded fallback. Metadata-only, non-breaking.\n */\nexport const IR_ROUTE_KEY = \"__ir_route\" as const;\n\n/**\n * The component key the R6 generic fallback routes to — the official renderer\n * for a KNOWN shape that nothing render-trusted claims. Hosts map this key to\n * their generic structured view (the package ships one: `GenericStructuredView`).\n */\nexport const GENERIC_STRUCTURED_COMPONENT_KEY = \"generic_structured\" as const;\n\n/**\n * The block type a DB-sourced (user-authored) kind component renders as.\n * FE-synthesized: produced ONLY here, never emitted upstream. A host that has\n * no sandbox for user components simply does not map this key — the block then\n * falls to that host's unknown-type handling, which is honest.\n */\nexport const DB_KIND_COMPONENT_KEY = \"db_kind_component\" as const;\n\n/**\n * THE DIRECTIVE TIER. A block whose root `__kind` is a reserved directive\n * slug (`directive_v…`) is typed to this block type and drawn by\n * `DirectiveRender` (`@ai-matrx/content-ir/react-directives`) — BEFORE the\n * component resolver is consulted. A directive is a kind whose display is the\n * directive card (the item inside it renders through the item's own kind —\n * THE DIRECTIVE⇄KIND SEAM), so no `kind_component` row exists or is needed,\n * and the \"unregistered\" / \"no-component\" floors must never claim one.\n * `\"matrx\"` is the block type matrx-frontend has dispatched directive fences\n * to since the envelope era; every host's dispatch table maps it to\n * `DirectiveRender`.\n */\nexport const DIRECTIVE_BLOCK_TYPE = \"matrx\" as const;\n\n/**\n * A DB row is render-trusted as a USER component when it is active, declares\n * `source='db'` (R1: db = web sandbox only), and actually carries a component\n * body. An active db-source row WITHOUT a body is a data defect — reported\n * loudly, and the route then falls through to the bundled behavior (never\n * un-render).\n */\nfunction isDbSourceResolution(\n  resolution: ComponentResolution | null,\n): resolution is ComponentResolution {\n  return (\n    resolution !== null &&\n    resolution.resolvedBy === \"db\" &&\n    resolution.source === \"db\" &&\n    resolution.isActive\n  );\n}\n\n// SESSION LATCH ON A globalThis SLOT — never a module-level variable. With the\n// package built `splitting: false` in dual ESM/CJS and multiple subpath\n// entries, this module is duplicated into the root bundle and the `./route`\n// bundle, and CJS/ESM each instantiate their own graph — a module-level Set\n// would silently split the latch (the kit confirm-opener precedent). Never\n// \"clean this up\" into a module local.\nconst SOURCELESS_DB_ROW_SLOT = Symbol.for(\n  \"ai-matrx.content-ir.sourceless-db-row-reports\",\n);\ntype SourcelessSlotHolder = typeof globalThis & {\n  [SOURCELESS_DB_ROW_SLOT]?: Set<string>;\n};\nconst reportedSourcelessDbRows: Set<string> = ((globalThis as SourcelessSlotHolder)[\n  SOURCELESS_DB_ROW_SLOT\n] ??= new Set<string>());\n\n/** Loud recovery: an active source='db' row with no component_source. */\nfunction reportDbRowWithoutSource(kind: string, env: KindRouteEnv): void {\n  const message = `[content-ir] kind_component for \"${kind}\" declares source='db' + is_active but has NO component_source — data defect; falling through to bundled rendering.`;\n  if (!reportedSourcelessDbRows.has(kind)) {\n    reportedSourcelessDbRows.add(kind);\n    console.error(message);\n  }\n  env.reportError({ source: \"content-ir\", message, raw: { kind } });\n}\n\n/** Test-only reset of the once-per-kind console latch. */\nexport function resetSourcelessDbRowReports(): void {\n  reportedSourcelessDbRows.clear();\n}\n\n/**\n * The db-override flip (R6: db overrides bundled): an ACTIVE `source='db'` row\n * carrying a component body wins over BOTH the compiled bridge and any bundled\n * resolution. The block re-types to `db_kind_component`; the host re-resolves\n * the row and compiles/sandboxes it. Returns null when the flip does not apply.\n */\nfunction routeToDbComponent<T extends IrRoutableBlock>(\n  block: T,\n  kind: string,\n  resolution: ComponentResolution | null,\n  env: KindRouteEnv,\n): T | null {\n  if (!isDbSourceResolution(resolution)) return null;\n  // Gate on the FLAG, not body presence: a lazy host's warm list is\n  // body-less (metadata only) and the body arrives per kind via the cold\n  // fetch — the row still routes, and the renderer compiles the body once it\n  // lands. A row whose flag says it truly has no body screams and falls\n  // through, exactly as before.\n  if (!resolution.hasComponentSource) {\n    reportDbRowWithoutSource(kind, env);\n    return null;\n  }\n  if (block.type === DB_KIND_COMPONENT_KEY) return block;\n  return {\n    ...block,\n    type: DB_KIND_COMPONENT_KEY,\n    // The compiled/sandboxed component reads the envelope, never the raw\n    // region's annotation serverData (same poison rule as bridged kinds).\n    serverData: undefined,\n    metadata: withRouteMarker(block.metadata, resolution),\n  };\n}\n\n/** A kind whose root form is opaque JSON: no value can fail its schema. */\nfunction acceptsAnyValue(\n  def: ReturnType<KindRouteEnv[\"kinds\"][\"getDefinition\"]>,\n): boolean {\n  const schema = def?.schema;\n  if (!schema?.root) return false;\n  return Object.keys(schema.fields ?? {}).length === 0 && isJsonAnyField(schema.root);\n}\n\n/** Why a block landed on the generic viewer instead of a real renderer. */\nexport type GenericFallbackReason =\n  /** No compiled bridge and no `content_ir.kind_component` row at all. */\n  | \"no-component\"\n  /** A component row exists but is held `is_active = false`. */\n  | \"inactive\"\n  /**\n   * An ACTIVE component row exists and names `generic_structured` — i.e. the\n   * fallback, registered under a component's name. This reads as coverage to\n   * every count-the-rows check on the platform and is not: the reader still\n   * gets a key/value dump. Kept as its own reason because the repair differs\n   * (author a component AND retire the decoy row), and because a page that\n   * silently marked itself `by: \"bundled\"` here is how 226 of 428 active\n   * kinds came to be certified as renderable while rendering generically\n   * (found 2026-08-23).\n   */\n  | \"generic-row\"\n  /**\n   * The envelope carries a kind-preserved RAW: the payload identified a\n   * registered kind and its value FAILED a check — a schema violation, an\n   * array-item kind mismatch, a duplicate key, a contradicted speculation.\n   * The instance is BROKEN, not component-less — the repair is fixing the\n   * payload or the schema, and the generic floor must acknowledge the kind and\n   * surface the recorded problems.\n   *\n   * NOT this: a kind whose schema was never available (`kindState:\n   * \"unverified\"`). Nothing checked that value, so calling it broken is a\n   * false accusation — it routes to its component. The two were one state\n   * until 2026-08-29 and conflating them was a platform-wide outage.\n   */\n  | \"broken-instance\";\n\nexport interface IrRouteMarker {\n  by: ComponentResolution[\"resolvedBy\"] | \"generic\" | \"directive\";\n  key: string;\n  /**\n   * Only on the generic fallback: the shape is NOT render-trusted, so the\n   * viewer must say so out loud (R6 — never an error, never hidden content).\n   */\n  unverified?: true;\n  reason?: GenericFallbackReason;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isRouteMarker(value: unknown): value is IrRouteMarker {\n  return (\n    isRecord(value) &&\n    typeof value.by === \"string\" &&\n    typeof value.key === \"string\"\n  );\n}\n\n/** Read the routing marker a block picked up at the seam (or null). */\nexport function readIrRouteMarker(\n  metadata: Record<string, unknown> | null | undefined,\n): IrRouteMarker | null {\n  const candidate = metadata?.[IR_ROUTE_KEY];\n  return isRouteMarker(candidate) ? candidate : null;\n}\n\nfunction withRouteMarker(\n  metadata: Record<string, unknown> | undefined,\n  resolution: ComponentResolution,\n): Record<string, unknown> {\n  return {\n    ...metadata,\n    [IR_ROUTE_KEY]: {\n      by: resolution.resolvedBy,\n      key: resolution.componentKey,\n    } satisfies IrRouteMarker,\n  };\n}\n\n/**\n * R6's sanctioned disposition for a shape the platform KNOWS (a kind\n * definition supplied its schema) but nothing render-trusted claims: the\n * generic structured viewer, carrying an honest \"unverified shape\" affordance\n * — never an error, never a raw code block, never hidden content.\n *\n * `serverData` is CLEARED for the same reason the resolver-only path clears\n * it: a raw region's annotation (`{ language: \"json\" }`) is not kind data, and\n * the generic viewer reads the envelope, not serverData.\n */\nfunction routeToGeneric<T extends IrRoutableBlock>(\n  block: T,\n  reason: GenericFallbackReason,\n): T {\n  if (block.type === GENERIC_STRUCTURED_COMPONENT_KEY) return block;\n\n  return {\n    ...block,\n    type: GENERIC_STRUCTURED_COMPONENT_KEY,\n    serverData: undefined,\n    metadata: {\n      ...block.metadata,\n      [IR_ROUTE_KEY]: {\n        by: \"generic\",\n        key: GENERIC_STRUCTURED_COMPONENT_KEY,\n        unverified: true,\n        reason,\n      } satisfies IrRouteMarker,\n    },\n  };\n}\n\nexport interface KindRouteOptions {\n  /**\n   * Block types this host OWNS and the route must never re-type, however good\n   * the envelope on them looks.\n   *\n   * matrx-frontend passes `[\"artifact\"]`: an artifact block has an identity, a\n   * version, and a Canvas to open in, and since 2026-08-18 it carries\n   * `metadata.__ir` so SELECTORS can read the envelope. That envelope is DATA\n   * there, not a route — re-typing it to the bare kind component would strip\n   * the artifact chrome and lose the door to the Canvas.\n   */\n  ownedTypes?: readonly string[];\n}\n\nexport function applyIrKindRoute<T extends IrRoutableBlock>(\n  block: T,\n  env: KindRouteEnv,\n  options?: KindRouteOptions,\n): T {\n  if (options?.ownedTypes?.includes(block.type)) return block;\n\n  const envelope = readEnvelope(block.metadata);\n  if (!envelope) return block;\n\n  const kind = envelope.root.kind;\n  if (!kind) return block; // raw / pending — the host's own rendering stands\n\n  // An identified kind whose SCHEMA is still cold-fetching (pending_schema) has\n  // no compliant value yet — routing now would hand a component early scalars\n  // at best. The host's loading layer owns this window; the parser upgrades in\n  // place the moment the schema lands, and end() converts a lost race to a\n  // kind-preserving raw — both of which route normally.\n  if (envelope.root.kindState === \"pending_schema\") return block;\n\n  // ── THE DIRECTIVE TIER ────────────────────────────────────────────────────\n  // A reserved slug is a directive; the directive tier owns its display, in\n  // every kind state (a kind-preserved raw is still a directive the card can\n  // name and the reader can apply — the server re-validates on confirm).\n  if (isReservedDirectiveSlug(kind)) {\n    if (block.type === DIRECTIVE_BLOCK_TYPE) return block;\n    return {\n      ...block,\n      type: DIRECTIVE_BLOCK_TYPE,\n      serverData: undefined,\n      metadata: {\n        ...(block.metadata ?? {}),\n        [IR_ROUTE_KEY]: { by: \"directive\", key: DIRECTIVE_BLOCK_TYPE } satisfies IrRouteMarker,\n      },\n    };\n  }\n\n  const def = env.kinds.getDefinition(kind);\n  const resolution = env.components.resolve(kind, env.platform, \"output\");\n\n  // 🚨 THE COLD-VERDICT RULE (Arman, 2026-08-31). A registry that has not\n  // loaded yet must never be allowed to publish a NEGATIVE verdict. Every\n  // \"this shape isn't registered\" / \"no component\" answer below is a durable,\n  // user-visible claim written into the block's metadata — and on the first\n  // paint of a fresh tab the resolver has fetched nothing, so those claims\n  // were being produced by a registry whose honest answer is \"I haven't\n  // looked\". The reader saw a key/value dump captioned \"this shape isn't\n  // registered on this platform\" for a shape that was registered, active, and\n  // had a component the whole time.\n  //\n  // Holding the block (exactly as `pending_schema` does) hands the window to\n  // the host's loading layer; `useEnsureKindRenderable` fetches, the per-kind\n  // repaint fires, and this function re-runs with a settled registry. A\n  // POSITIVE answer is never suppressed — if the compiled floor or an already\n  // ingested row can name a component, the paths below run immediately.\n  // PER KIND (2026-10-17): the verdict waits until THIS kind's lookups have answered — its\n  // component read (`hasSettledFor`, else the tier's `hasSettled`) and its definition read\n  // (`schemaState` not \"pending\"). A tier that \"settled\" because another kind's row landed, or a\n  // definition still in flight, is \"I haven't looked\", never \"unregistered\".\n  if (!resolution && !def && !kindLookupSettled(env, kind)) return block;\n\n  // A kind-preserved `raw` is a BROKEN instance: something CHECKED this value\n  // and it failed — a schema violation, an array-item kind mismatch, a\n  // duplicate key, a contradicted speculation. No component (bridge or db) may\n  // claim a non-compliant value; the generic floor acknowledges the kind and\n  // the envelope's recorded problems (residue notices, the raw_fallback\n  // reason) are the host's to show. An UNREGISTERED slug routes here too —\n  // Arman's 2026-08-29 ruling: a root `__kind` key means the kind system owns\n  // the render, NO exceptions. Repaint upgrades it the moment the registries\n  // learn more.\n  //\n  // 🚨 `unverified` DELIBERATELY DOES NOT MATCH HERE, AND MUST NEVER BE ADDED.\n  // That state means no schema was ever available, so nothing was checked —\n  // the value is intact and quite possibly perfect. It falls through to the\n  // component paths below exactly as it did before 2026-08-28, when this gate\n  // read the old undifferentiated `raw` and took ~221 live kinds' components\n  // away overnight: every kind whose schema cannot be reconstructed (nested\n  // objects, arrays of children, loose fields) degrades this way, and each one\n  // rendered as a key/value dump while its purpose-built component sat one\n  // line below, never asked for. Widening this condition re-opens that outage.\n  // See `IrKindState` in @ai-matrx/content-ir.\n  //\n  // A shape whose root accepts ANY JSON value (`json`, emitted schema `{}`)\n  // cannot be violated: the kernel marks a tagged object of a non-object-root\n  // kind `raw` (\"cannot be a __kind object\"), but every value — that object\n  // included — is inside the declared contract. Calling it broken put \"did\n  // not match the shape's schema\" under a passing example; it falls through\n  // to the component paths instead (shapes audit 3.2, 2026-10-14).\n  // 🚨 RULE 28 (Arman, 2026-10-25): a `__kind` KEY IS NOT A KIND. A slug the\n  // registry has settled on knowing nothing about — no definition, no component\n  // row — is plain JSON: the host's own rendering stands. It is never dressed\n  // as a kind instance on the generic floor (that supersedes the 2026-08-29\n  // \"a root __kind key means the kind system owns the render\" ruling).\n  if (!def && !resolution) return block;\n\n  if (envelope.root.kindState === \"raw\" && !acceptsAnyValue(def)) {\n    return routeToGeneric(block, \"broken-instance\");\n  }\n\n  // ── DB user-component path — db overrides bundled (ruling R6) ─────────────\n  // Checked FIRST so a user's registered component actually renders; a\n  // defective row (no source) screams and falls through to bundled behavior —\n  // never un-renders.\n  const dbRouted = routeToDbComponent(block, kind, resolution, env);\n  if (dbRouted) return dbRouted;\n\n  // ── Compiled-bridge path — trusted at bootstrap (ruling R6) ───────────────\n  // A kind carrying a legacyBlockType facet ALWAYS routes: the host's existing\n  // behavior for every registered kind, and the production floor a DB row can\n  // refine (the marker records which tier resolved) but never un-render.\n  if (def?.legacyBlockType) {\n    // A block ALREADY emitted as the legacy type carrying its own serverData is\n    // authoritative — the server typed it AND provided the component's data.\n    if (block.type === def.legacyBlockType && block.serverData) return block;\n\n    // ROUTING a raw region (e.g. \"code\" → \"flashcards\"): the envelope is the\n    // single source of truth. The block's own serverData here is NOT kind data\n    // — it is the raw region's annotation (`{ language: \"json\" }`). Preferring\n    // that junk handed the legacy component `{ language: \"json\" }` instead of\n    // cards/questions/slides — the 2026-07-04 \"No flashcards available yet\"\n    // bug — so it is REPLACED (bridge output) or CLEARED (bridgeless kinds\n    // parse `content` themselves), never forwarded.\n    const serverData = def.toLegacyServerData?.(envelope);\n\n    if (block.type === def.legacyBlockType && serverData === undefined) {\n      return block; // nothing to change — keep reference stability\n    }\n\n    return {\n      ...block,\n      type: def.legacyBlockType,\n      serverData,\n      ...(resolution\n        ? { metadata: withRouteMarker(block.metadata, resolution) }\n        : null),\n    };\n  }\n\n  // ── Resolver-only path (no compiled bridge): the registry decides ─────────\n  // R6: only an ACTIVE resolution is render-trusted. An inactive row means\n  // \"held\", not \"route it anyway\".\n  if (resolution?.isActive) {\n    // A row naming the fallback is NOT a resolution. Routing it as one stamped\n    // `by: \"bundled\"` on the block and told every reader the shape had a\n    // renderer — the platform's own generic viewer, wearing a component's\n    // clothes. It goes to the honest generic path with its own reason instead.\n    if (resolution.componentKey === GENERIC_STRUCTURED_COMPONENT_KEY) {\n      return routeToGeneric(block, \"generic-row\");\n    }\n    if (block.type === resolution.componentKey) return block;\n\n    return {\n      ...block,\n      type: resolution.componentKey,\n      // No compiled bridge exists — the routed component parses `content`\n      // itself; the raw region's annotation serverData is CLEARED.\n      serverData: undefined,\n      metadata: withRouteMarker(block.metadata, resolution),\n    };\n  }\n\n  // ── R6 generic fallback: a KNOWN shape that nothing render-trusted claims ─\n  // `def` exists ⇒ a kind definition supplied this kind's schema: the platform\n  // knows the shape. It has no compiled bridge, and either no `kind_component`\n  // row at all (`no-component`) or one held inactive (`inactive`). R6 sends\n  // exactly this case to the generic structured viewer with an \"unverified\n  // shape\" affordance — the disposition that retires permanently-red\n  // \"no-component root\" kinds without pretending they have renderers.\n  if (def) {\n    return routeToGeneric(block, resolution ? \"inactive\" : \"no-component\");\n  }\n\n  // No definition and no ACTIVE component row: nothing designed claims this\n  // slug, so the host's own rendering stands (rule 28).\n  return block;\n}\n\n/**\n * THE COLD-VERDICT RULE, per kind: have this kind's own lookups answered? Only then may the route\n * publish a negative verdict (that a slug names no kind). Exported so a host's loading layer holds its loader\n * on exactly the same predicate the route holds its verdict on.\n */\nexport function kindLookupSettled(env: Pick<KindRouteEnv, \"kinds\" | \"components\" | \"platform\">, kind: string): boolean {\n  const componentsSettled =\n    env.components.hasSettledFor?.(kind, env.platform) ?? env.components.hasSettled?.() ?? true;\n  if (!componentsSettled) return false;\n  return (env.kinds.schemaState?.(kind) ?? \"loaded\") !== \"pending\";\n}\n\n/**\n * Rehydration route for STRUCTURED persisted artifacts.\n *\n * A materialized kind artifact stores its zero-loss value object (carrying\n * `__kind`) alongside its row. Given that stored value, derive the registered\n * kind's legacy `serverData` WITHOUT re-parsing any text: the value wraps into\n * a complete envelope and runs through the same `toLegacyServerData` bridge the\n * live stream uses. Returns null for non-objects, unregistered kinds, or kinds\n * without a legacy bridge — callers fall back to their string-payload path.\n */\nexport function kindServerDataFromStoredValue(\n  value: unknown,\n  env: Pick<KindRouteEnv, \"kinds\">,\n): Record<string, unknown> | null {\n  if (!isRecord(value)) return null;\n  const kind = readObjectKind(value);\n  if (!kind) return null;\n\n  const def = env.kinds.getDefinition(kind);\n  if (!def?.toLegacyServerData) return null;\n\n  return def.toLegacyServerData(envelopeFromCompleteValue(value, kind)) ?? null;\n}\n","/**\n * Streaming partial kinds — the TS twin of the Python producer's contract.\n *\n * Cross-repo system-of-record (read it before changing anything here):\n * `common-docs/systems/architecture/content-ir/FEATURE.md`.\n * Python twin: `aidream/packages/matrx-graph/matrx_graph/content_ir/partial.py`.\n *\n * WHAT THIS IS\n * ------------\n * While a structured region streams, the server announces what it thinks the\n * region IS and what has arrived so far, so the UI fills in progressively\n * instead of showing a spinner until the closing brace. Three events, a CLOSED\n * union on `state`, all riding `metadata.__ir_partial` on the `render_block`\n * events this app already receives:\n *\n *   partial     — repeatable. A provisional instance whose `root.value` is\n *                 VALID, CLOSED JSON (the server truncates and closes it, so\n *                 this side never repairs or guesses). `kindState` is\n *                 \"speculative\": it MAY still turn out to be something else.\n *   superseded  — TERMINAL. The region completed as the announced kind; drop\n *                 the provisional render, the block's own content/`__ir` is the\n *                 truth.\n *   retracted   — TERMINAL escape hatch. Detection was wrong; `becameKind` /\n *                 `becameBlockType` name what it actually is. Never a silent\n *                 swap.\n *\n * WHY IT IS NOT ON `__ir`\n * -----------------------\n * `__ir` means \"validated against the registered schema\", and a valid `__ir`\n * is SEEDED into the fingerprint-keyed envelope memo. A provisional value\n * there would poison every later read of that region. The two channels never\n * touch: `classifyInboundEnvelopeMetadata` sees `absent` for a partial and\n * passes the metadata through by reference.\n *\n * Pure kernel module: types + validators only. No React, no Redux, no IO.\n * Lives in @ai-matrx/content-ir `wire/` so EVERY UI (Matrix, Workflow Studio,\n * the dashboard, the Chrome extension, the desktop app) reads the channel\n * through the same reader.\n */\n\nimport { IR_VERSION } from \"../core/ir-types\";\nimport type { IrDiscriminator, IrPath, IrResidue } from \"../core/ir-types\";\n\n/** The reserved metadata key carrying every event of this contract. */\nexport const IR_PARTIAL_KEY = \"__ir_partial\" as const;\n\nexport type PartialKindState = \"partial\" | \"superseded\" | \"retracted\";\n\nconst PARTIAL_STATES: readonly PartialKindState[] = [\n  \"partial\",\n  \"superseded\",\n  \"retracted\",\n];\n\n/** The provisional node. Deliberately `IrStructuredNode`-shaped so existing IR readers work. */\nexport interface PartialKindNode {\n  role: \"structured\";\n  /** The server's DETECTION GUESS for this region. */\n  kind: string;\n  /** Always \"speculative\" on a partial — pre-recognition, not a resolved kind. */\n  kindState: \"speculative\";\n  discriminator: IrDiscriminator;\n  path: IrPath;\n  status: \"streaming\";\n  /**\n   * Valid, closed JSON carrying its own `__kind`. MAY be missing required\n   * schema fields — that is what `partial_unvalidated` in `residue.notices`\n   * says. A renderer that throws on an absent field is not partial-ready and\n   * must not be routed a provisional value.\n   */\n  value: Record<string, unknown>;\n  residue: IrResidue | null;\n}\n\nexport interface PartialKindEvent {\n  v: typeof IR_VERSION;\n  engine: string;\n  state: \"partial\";\n  /** Monotonic PER BLOCK — the ordering / staleness key. Keep the highest. */\n  seq: number;\n  fingerprint: string;\n  root: PartialKindNode;\n}\n\nexport interface SupersededKindEvent {\n  v: typeof IR_VERSION;\n  engine: string;\n  state: \"superseded\";\n  seq: number;\n  kind: string;\n}\n\nexport interface RetractedKindEvent {\n  v: typeof IR_VERSION;\n  engine: string;\n  state: \"retracted\";\n  seq: number;\n  /** The kind that was WRONGLY announced. */\n  kind: string;\n  reason: string;\n  /** What it actually is — null when it resolved to no registered kind. */\n  becameKind: string | null;\n  /** The detector's final block type, so a consumer re-routes without guessing. */\n  becameBlockType: string | null;\n}\n\nexport type AnyPartialKindEvent =\n  | PartialKindEvent\n  | SupersededKindEvent\n  | RetractedKindEvent;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction readPath(value: unknown): IrPath | null {\n  if (!Array.isArray(value)) return null;\n  return value.every(\n    (segment) => typeof segment === \"string\" || typeof segment === \"number\",\n  )\n    ? value\n    : null;\n}\n\nfunction readDiscriminator(value: unknown): IrDiscriminator | null {\n  if (!isRecord(value)) return null;\n  if (value.format === \"json\" && value.key === \"__kind\") {\n    return { format: \"json\", key: \"__kind\" };\n  }\n  if (value.format === \"xml\" && typeof value.tag === \"string\") {\n    return { format: \"xml\", tag: value.tag };\n  }\n  if (value.format === \"fence\" && typeof value.language === \"string\") {\n    return { format: \"fence\", language: value.language };\n  }\n  return null;\n}\n\nfunction readResidue(value: unknown): IrResidue | null | undefined {\n  if (value === null) return null;\n  if (!isRecord(value)) return undefined;\n  const extra = value.extra;\n  const optionalMissing = value.optionalMissing;\n  const notices = value.notices;\n  if (extra !== null && !isRecord(extra)) return undefined;\n  if (\n    optionalMissing !== null &&\n    (!Array.isArray(optionalMissing) ||\n      !optionalMissing.every((item) => typeof item === \"string\"))\n  ) {\n    return undefined;\n  }\n  if (\n    notices !== null &&\n    (!Array.isArray(notices) ||\n      !notices.every(\n        (notice) =>\n          isRecord(notice) &&\n          typeof notice.code === \"string\" &&\n          typeof notice.message === \"string\" &&\n          (notice.at === undefined || typeof notice.at === \"number\"),\n      ))\n  ) {\n    return undefined;\n  }\n  return { extra, optionalMissing, notices };\n}\n\n/**\n * Read + validate a partial-channel event off a block's metadata.\n *\n * Returns null for anything malformed, foreign, or of an unknown `state`. A\n * malformed partial degrades to \"no live rendering\" — never to a wrong render,\n * and never to a thrown error inside a stream handler.\n */\nexport function readPartialKindEvent(\n  metadata: Record<string, unknown> | null | undefined,\n): AnyPartialKindEvent | null {\n  if (!isRecord(metadata)) return null;\n  const candidate = metadata[IR_PARTIAL_KEY];\n  if (!isRecord(candidate)) return null;\n  if (candidate.v !== IR_VERSION) return null;\n  if (typeof candidate.engine !== \"string\") return null;\n  if (typeof candidate.seq !== \"number\" || !Number.isFinite(candidate.seq)) {\n    return null;\n  }\n\n  const state = candidate.state;\n  if (typeof state !== \"string\") return null;\n  if (!PARTIAL_STATES.includes(state as PartialKindState)) return null;\n\n  if (state === \"partial\") {\n    const root = candidate.root;\n    if (!isRecord(root)) return null;\n    if (root.role !== \"structured\") return null;\n    if (root.status !== \"streaming\") return null;\n    if (root.kindState !== \"speculative\") return null;\n    if (typeof root.kind !== \"string\" || !root.kind) return null;\n    if (!isRecord(root.value)) return null;\n    const discriminator = readDiscriminator(root.discriminator);\n    const path = readPath(root.path);\n    const residue = readResidue(root.residue);\n    if (discriminator === null || path === null || residue === undefined) {\n      return null;\n    }\n    return {\n      v: IR_VERSION,\n      engine: candidate.engine,\n      state: \"partial\",\n      seq: candidate.seq,\n      fingerprint:\n        typeof candidate.fingerprint === \"string\" ? candidate.fingerprint : \"\",\n      root: {\n        role: \"structured\",\n        kind: root.kind,\n        kindState: \"speculative\",\n        discriminator,\n        path,\n        status: \"streaming\",\n        value: root.value,\n        residue,\n      },\n    };\n  }\n\n  if (typeof candidate.kind !== \"string\" || !candidate.kind) return null;\n\n  if (state === \"superseded\") {\n    return {\n      v: IR_VERSION,\n      engine: candidate.engine,\n      state: \"superseded\",\n      seq: candidate.seq,\n      kind: candidate.kind,\n    };\n  }\n\n  if (typeof candidate.reason !== \"string\" || !candidate.reason) return null;\n  if (\n    candidate.becameKind !== null &&\n    typeof candidate.becameKind !== \"string\"\n  ) {\n    return null;\n  }\n  if (\n    candidate.becameBlockType !== null &&\n    typeof candidate.becameBlockType !== \"string\"\n  ) {\n    return null;\n  }\n  return {\n    v: IR_VERSION,\n    engine: candidate.engine,\n    state: \"retracted\",\n    seq: candidate.seq,\n    kind: candidate.kind,\n    reason: candidate.reason,\n    becameKind: candidate.becameKind,\n    becameBlockType: candidate.becameBlockType,\n  };\n}\n\n/**\n * Ingest guard for the partial channel on a `render_block` event — the twin of\n * `sanitizeInboundEnvelopeMetadata` for `__ir`, and it exists for the same\n * reason: a malformed server event must be stripped at the wire boundary, not\n * carried into Redux where every later reader has to re-decide whether to\n * trust it.\n *\n * - no `__ir_partial` key → the SAME metadata reference back (zero-touch).\n * - valid event → the SAME metadata reference back (idempotence law).\n * - malformed → a COPY with the key stripped, plus a loud `reportMalformed`.\n *   Dropping it degrades that block to \"no live rendering\" and nothing more.\n *\n * Pure: the host injects the reporter, exactly like the envelope gate, so\n * aidream's Workflow Studio can bind its own.\n */\nexport function sanitizeInboundPartialKindMetadata(\n  metadata: Record<string, unknown> | null | undefined,\n  context: { blockId: string },\n  hooks: {\n    reportMalformed?: (info: { blockId: string; raw: unknown }) => void;\n  } = {},\n): Record<string, unknown> | undefined {\n  if (!isRecord(metadata) || !(IR_PARTIAL_KEY in metadata)) {\n    return metadata ?? undefined;\n  }\n  if (readPartialKindEvent(metadata) !== null) return metadata;\n\n  const { [IR_PARTIAL_KEY]: raw, ...rest } = metadata;\n  hooks.reportMalformed?.({ blockId: context.blockId, raw });\n  return rest;\n}\n\n/** Narrowing helper: is this the repeatable provisional event? */\nexport function isProvisionalKind(\n  event: AnyPartialKindEvent | null,\n): event is PartialKindEvent {\n  return event !== null && event.state === \"partial\";\n}\n\n/**\n * Narrowing helper: is this a TERMINAL event? Every partial ends in exactly\n * one of these — that law is what makes a stuck skeleton impossible, so a\n * consumer clears its provisional render here and nowhere else.\n */\nexport function isTerminalKindEvent(\n  event: AnyPartialKindEvent | null,\n): event is SupersededKindEvent | RetractedKindEvent {\n  return (\n    event !== null && (event.state === \"superseded\" || event.state === \"retracted\")\n  );\n}\n\n/**\n * Per-block staleness gate. Events can be re-dispatched, replayed on reconnect,\n * or arrive out of order; only a strictly higher `seq` advances a block.\n * Returns null when the event should be ignored.\n *\n * Pure: the caller owns the `seen` map, so this composes into a reducer\n * without hiding module state.\n */\nexport function advancePartialKind(\n  seen: Record<string, number>,\n  blockId: string,\n  event: AnyPartialKindEvent | null,\n): AnyPartialKindEvent | null {\n  if (event === null) return null;\n  const last = seen[blockId];\n  if (last !== undefined && event.seq <= last) return null;\n  return event;\n}\n\n/**\n * The per-block staleness GATE, as a stateful closure over `advancePartialKind`\n * — one per stream.\n *\n * `upsertRenderBlock` REPLACES the stored block, so an event landing on a block\n * would regress what the user is looking at (a filled-in quiz snapping back to\n * two questions, or a terminal being undone by a late `partial`). The highest\n * accepted event is CARRIED FORWARD rather than dropped, so it is a no-op on\n * screen instead of a flicker back to the skeleton.\n *\n * 🚨 TWO arrivals must be carried, and the second one is the common case:\n *\n *  1. A STALE key — a replay or an out-of-order event (`seq <= last`).\n *  2. **NO key at all.** The producer clears `__ir_partial` at the top of every\n *     stamp and re-adds it only when the value genuinely advanced\n *     (`stream_processor.py::_stamp_partial` → `_partials.advanced(...)`), so\n *     it is CORRECT for it to omit the key — re-shipping an identical payload\n *     every token is pure wire cost. But the block still ships whole, and\n *     replacing the stored block with one that has no partial metadata is what\n *     made the provisional render vanish between advances: every non-advancing\n *     token dropped the user back to the pending skeleton.\n *\n * Carrying stops at the TERMINAL, and only there. After `superseded` /\n * `retracted` the region's truth is its own content or `__ir`, so resurrecting\n * a provisional value would be a lie that outlives its own contract.\n *\n * Returns the metadata to store: the same reference when nothing changed, a\n * copy with the carried-forward event otherwise.\n */\nexport function makePartialKindStalenessGate(): (\n  blockId: string,\n  metadata: Record<string, unknown> | undefined,\n) => Record<string, unknown> | undefined {\n  const seen: Record<string, number> = {};\n  const lastAccepted: Record<string, unknown> = {};\n  const terminated: Record<string, true> = {};\n\n  return (blockId, metadata) => {\n    if (!isRecord(metadata)) return metadata;\n\n    if (!(IR_PARTIAL_KEY in metadata)) {\n      // The producer omitted the key because nothing advanced. Keep showing the\n      // last provisional value — unless this block already terminated, in which\n      // case its own content/`__ir` is the truth and the partial must stay gone.\n      const open = lastAccepted[blockId];\n      if (terminated[blockId] || open === undefined) return metadata;\n      return { ...metadata, [IR_PARTIAL_KEY]: open };\n    }\n    // Anything malformed was stripped by `sanitizeInboundPartialKindMetadata`\n    // at the same boundary, so a key still present here reads as valid.\n    const parsed = readPartialKindEvent(metadata);\n    if (parsed === null) return metadata;\n\n    if (advancePartialKind(seen, blockId, parsed) !== null) {\n      seen[blockId] = parsed.seq;\n      // The highest accepted event is always retained — including a TERMINAL,\n      // so a replayed `partial` arriving after it is suppressed by the terminal\n      // rather than re-opening a closed region.\n      lastAccepted[blockId] = metadata[IR_PARTIAL_KEY];\n      if (isTerminalKindEvent(parsed)) terminated[blockId] = true;\n      return metadata;\n    }\n\n    const carried = lastAccepted[blockId];\n    if (carried === undefined || carried === metadata[IR_PARTIAL_KEY]) {\n      return metadata;\n    }\n    return { ...metadata, [IR_PARTIAL_KEY]: carried };\n  };\n}\n","/**\n * Routing the PROVISIONAL half of the streaming partial-kinds contract.\n *\n * Cross-repo system-of-record (read it before changing anything here):\n * `common-docs/systems/architecture/content-ir/FEATURE.md` §8.\n * The reader/validator half lives in `@ai-matrx/content-ir` (`wire/partial-kind`);\n * the wire gate runs in each host's stream ingest.\n *\n * WHAT THIS DOES\n * --------------\n * While a structured region streams, the server announces what it thinks the\n * region IS and what has arrived so far (`metadata.__ir_partial`). This module\n * turns that provisional event into a routed block that renders through the\n * EXACT SAME component the final value renders in — which is the entire point:\n * a bespoke skeleton renderer would be a second render path and is banned.\n *\n * HOW, without touching the verified channel\n * ------------------------------------------\n * `root` is deliberately `IrStructuredNode`-shaped, so the event wraps into a\n * `CanonicalBlockIR` and every existing reader — the compiled bridge, the\n * component resolver, the db-component flip, the generic viewer — works\n * unchanged. That provisional envelope is placed on a RENDER-LOCAL COPY of the\n * block's metadata under `__ir`, never on the wire and never in host state. The\n * block also carries `__ir_provisional: true` so any downstream reader can tell\n * a provisional render from a verified one.\n *\n * THE POSTURE: PROGRESSIVE BY DEFAULT, OPT OUT PER KIND (Arman, 2026-10-14)\n * ------------------------------------------------------------------------\n * A provisional value MAY be missing required fields — that is what the\n * `partial_unvalidated` notice declares. It used to be WITHHELD unless a kind\n * opted in with `partialReady: true`, so a run page showed a loader until the\n * end for components that render partial values perfectly well (the same\n * component fills in live on a chat stream, which never consulted this flag).\n * Now every kind with a real component is handed the provisional value — and\n * since Arman, 2026-10-26 (\"Kind components get partial values immediately\n * everywhere … Remove the hold-back\") there is no opt-out: `partialReady` is no\n * longer read. The safety net is unchanged and is what makes the\n * open default safe: a component that throws is caught by\n * `ProvisionalKindBoundary`, which screams and calls `markKindPartialUnsafe`,\n * dropping that kind back to withhold for the session; a bridged kind whose\n * bridge declines a thin value stays on its loader for that frame.\n *\n * TERMINALS\n * ---------\n * `superseded` and `retracted` produce NO provisional render, so the swap to\n * the final value happens in the same frame the terminal arrives — never a\n * flicker through an empty state. Both are explicit EVENTS: the terminal is\n * never inferred from the arrival of `__ir`, because a completed block often\n * has no `__ir` at all (unregistered kind, schema drift, cold catalog) and\n * inferring it would leave the skeleton up forever in exactly those cases.\n */\n\nimport { envelopeFromCompleteValue, IR_ENVELOPE_KEY, IR_VERSION, readEnvelope, readObjectKind } from \"../core\";\nimport { IR_PARTIAL_KEY, isProvisionalKind, readPartialKindEvent } from \"../wire\";\nimport type { CanonicalBlockIR } from \"../core\";\nimport type { PartialKindEvent } from \"../wire\";\nimport type { IrRoutableBlock, KindRouteEnv } from \"../host/host-types\";\nimport { applyIrKindRoute, type KindRouteOptions } from \"./kind-route\";\n\n/**\n * Marker stamped on a render-local block whose `__ir` is PROVISIONAL. Never\n * emitted by a producer, never persisted, never on the wire.\n */\nexport const IR_PROVISIONAL_KEY = \"__ir_provisional\" as const;\n\n/** True when this block's metadata carries a provisional (not verified) envelope. */\nexport function isProvisionalBlock(\n  metadata: Record<string, unknown> | null | undefined,\n): boolean {\n  return metadata?.[IR_PROVISIONAL_KEY] === true;\n}\n\n/** Wrap a validated `partial` event into the envelope shape every IR reader consumes. */\nexport function envelopeFromPartialKind(\n  event: PartialKindEvent,\n): CanonicalBlockIR {\n  return {\n    v: IR_VERSION,\n    // The partial channel is only ever produced by the Python detector; the\n    // envelope's `engine` union has no third member and inventing one would\n    // break every existing reader.\n    engine: \"py-block-detector\",\n    fingerprint: event.fingerprint,\n    root: event.root,\n  };\n}\n\n/**\n * Kinds whose component threw while rendering a provisional value. Session-\n * scoped: the kind falls back to withhold (its loading skeleton) until a\n * reload, so one bad component cannot keep re-throwing on every block.\n */\n// SESSION LATCH ON A globalThis SLOT — never a module-level variable. This\n// latch is WRITTEN from the `./react` bundle (ProvisionalKindBoundary calls\n// markKindPartialUnsafe) and READ from the `./route` bundle\n// (isPartialReadyKind); with `splitting: false` dual ESM/CJS output those are\n// different module instantiations, and a module-level Set would silently split\n// the writer from the reader (the kit confirm-opener precedent). Never \"clean\n// this up\" into a module local.\nconst PARTIAL_UNSAFE_SLOT = Symbol.for(\n  \"ai-matrx.content-ir.partial-unsafe-kinds\",\n);\ntype PartialUnsafeSlotHolder = typeof globalThis & {\n  [PARTIAL_UNSAFE_SLOT]?: Set<string>;\n};\nconst partialUnsafeKinds: Set<string> = ((globalThis as PartialUnsafeSlotHolder)[\n  PARTIAL_UNSAFE_SLOT\n] ??= new Set<string>());\n\n/** Loud recovery hook — called by ProvisionalKindBoundary when a render throws. */\nexport function markKindPartialUnsafe(kind: string): void {\n  partialUnsafeKinds.add(kind);\n}\n\n/** Test-only reset of the session latch. */\nexport function resetPartialUnsafeKinds(): void {\n  partialUnsafeKinds.clear();\n}\n\n/**\n * May this kind be handed a provisional value? Always — unless its component\n * already threw on one this session; see the module doc.\n */\nexport function isPartialReadyKind(\n  kind: string,\n  _env: Pick<KindRouteEnv, \"kinds\">,\n): boolean {\n  return Boolean(kind) && !partialUnsafeKinds.has(kind);\n}\n\nexport interface PartialRenderOptions extends KindRouteOptions {\n  /**\n   * Is the STREAM still running? Message-wide, deliberately — not this block's\n   * own completion.\n   *\n   * 🚨 THE ANTI-STUCK-SKELETON BACKSTOP. Law 1 of the contract says every\n   * partial ends in exactly one terminal, and that law is the ONLY thing\n   * standing between a user and a \"Still arriving\" skeleton that never\n   * resolves. It is a producer guarantee with at least three ways to not fire:\n   * the drain skips a block missing from the final block list, the emitter\n   * early-returns once the stream ended or was canceled (so a client abort\n   * drops every retraction), and a flush failure is swallowed so it never kills\n   * a run.\n   *\n   * Once the stream is over, no terminal can ever arrive, so a still-open\n   * provisional is stuck by definition — drop it and let the block's own\n   * content and `__ir` be the truth. Correct to be message-wide: a terminal for\n   * THIS block may still be in flight while the block itself looks finished.\n   *\n   * `undefined` reads as active, so a caller that does not thread stream state\n   * keeps live rendering rather than silently losing it.\n   */\n  streamActive?: boolean;\n}\n\n/**\n * The ANNOUNCED-but-not-yet-renderable state: the server has said what this\n * region is, and the region cannot render its real component yet.\n *\n * WHY THIS EXISTS SEPARATELY FROM THE VERIFIED CHANNEL. On a chat stream the\n * host's own accumulator fills `__ir` in as it parses. A WORKFLOW run's lane\n * does not: when the server opens the block scope it marks the text channel\n * `block_shadowed` and the lane stops feeding its accumulator, precisely so one\n * region is never rendered twice under two sets of block ids\n * (STREAMING_PARTIAL_KINDS.md §7b rule 4). So on a run page there is NO\n * streaming `__ir` — the ONLY thing that knows what the region is, is the\n * partial channel. Without this, a workflow node's structured answer fell\n * through to the raw-text renderer: a generic loader, then raw JSON\n * accumulating, then a swap at the end.\n *\n * Returns the provisional envelope to feed the kind's loading component, or\n * null when there is nothing announced (no event, a terminal, a dead stream).\n * Deliberately independent of `partialReady`: withholding a VALUE from a\n * component that might throw on it is a real decision, but withholding the\n * kind's own loading state is not — a skeleton cannot throw, and the reader\n * seeing what is coming is the whole point.\n */\nexport function resolveAnnouncedKindLoading(\n  block: { metadata?: Record<string, unknown> },\n  options?: Pick<PartialRenderOptions, \"streamActive\">,\n): { kind: string; envelope: CanonicalBlockIR } | null {\n  // Same anti-stuck-skeleton backstop as resolveProvisionalKindRender: once the\n  // stream is over no terminal can arrive, so a still-open announcement is\n  // stuck by definition and must not hold a loader on screen forever.\n  if (options?.streamActive === false) return null;\n\n  const event = readPartialKindEvent(block.metadata);\n  if (!isProvisionalKind(event)) return null;\n  const kind = event.root.kind;\n  if (!kind) return null;\n\n  // A region that already VERIFIED is the truth; never cover it with a loader.\n  const verified = readEnvelope(block.metadata);\n  if (verified && verified.root.status === \"complete\") return null;\n\n  return { kind, envelope: envelopeFromPartialKind(event) };\n}\n\nexport interface ProvisionalKindRender<T> {\n  /** The routed block — same type/serverData shape the final value produces. */\n  block: T;\n  /** The announced (speculative) kind. */\n  kind: string;\n  /** Per-block ordering key, for diagnostics. */\n  seq: number;\n  /** The provisional envelope — feeds the loading skeleton used as the throw fallback. */\n  envelope: CanonicalBlockIR;\n}\n\nexport interface SupersededKindRender<T> {\n  /** The completed block routed through the announced kind's normal component. */\n  block: T;\n  /** The kind the producer announced and then confirmed at terminal. */\n  kind: string;\n  /** Per-block ordering key, for diagnostics. */\n  seq: number;\n  /** Render-local complete envelope reconstructed from the block's own content. */\n  envelope: CanonicalBlockIR;\n}\n\nfunction parseCompletedJsonObject(content: string): Record<string, unknown> | null {\n  let source = content.trim();\n  const fenced = source.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```$/i);\n  if (fenced?.[1]) source = fenced[1].trim();\n\n  try {\n    const value = JSON.parse(source) as unknown;\n    return typeof value === \"object\" && value !== null && !Array.isArray(value)\n      ? (value as Record<string, unknown>)\n      : null;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Finish the partial-kind handoff for a `superseded` terminal.\n *\n * A workflow run deliberately shadows its text channel while server-built\n * render blocks stream, so the browser never builds a verified `__ir`\n * envelope for that region. The terminal still proves that the announced kind\n * completed, and the block's own content is now closed JSON. Reconstruct a\n * render-local COMPLETE envelope from that content and route it through the\n * same component path as persisted/reloaded data. `retracted` is never\n * eligible, and a malformed or mismatched payload stays on the host's honest\n * raw fallback.\n */\nexport function resolveSupersededKindRender<\n  T extends IrRoutableBlock & {\n    content: string;\n    metadata?: Record<string, unknown>;\n  },\n>(\n  block: T,\n  env: KindRouteEnv,\n  options?: KindRouteOptions,\n): SupersededKindRender<T> | null {\n  const event = readPartialKindEvent(block.metadata);\n  if (event?.state !== \"superseded\") return null;\n\n  // A verified envelope is already the higher-fidelity truth and the ordinary\n  // kind route owns it.\n  if (readEnvelope(block.metadata)?.root.status === \"complete\") return null;\n\n  const value = parseCompletedJsonObject(block.content);\n  if (!value || readObjectKind(value) !== event.kind) return null;\n\n  const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n  void _partial;\n  const envelope = envelopeFromCompleteValue(value, event.kind);\n  const terminalBlock = {\n    ...block,\n    // A code/json block's serverData is an annotation, not kind data.\n    serverData: undefined,\n    metadata: { ...rest, [IR_ENVELOPE_KEY]: envelope },\n  } as T;\n  const routed = applyIrKindRoute(terminalBlock, env, options);\n  if (routed === terminalBlock) return null;\n\n  return { block: routed, kind: event.kind, seq: event.seq, envelope };\n}\n\n/**\n * Resolve a block's provisional render, or null when there is nothing to show\n * provisionally (no event, a terminal event, a withheld kind, a kind nothing\n * can route, or a verified envelope that already won).\n *\n * Pure: no React, no host state, no side effects beyond the registry reads.\n */\nexport function resolveProvisionalKindRender<\n  T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n>(\n  block: T,\n  env: KindRouteEnv,\n  options?: PartialRenderOptions,\n): ProvisionalKindRender<T> | null {\n  if (options?.streamActive === false) return null;\n\n  const event = readPartialKindEvent(block.metadata);\n  // Terminal (superseded / retracted) → no provisional render, in this frame.\n  if (!isProvisionalKind(event)) return null;\n\n  const kind = event.root.kind;\n  if (!isPartialReadyKind(kind, env)) return null;\n\n  // A verified envelope that has already completed is the truth — a late or\n  // duplicated partial must never displace it.\n  const verified = readEnvelope(block.metadata);\n  if (verified && verified.root.status === \"complete\") return null;\n\n  const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n  void _partial;\n\n  const envelope = envelopeFromPartialKind(event);\n\n  const provisionalBlock = {\n    ...block,\n    // The raw region annotation (`{ language: \"json\" }`) is not kind data —\n    // same poison rule the verified route follows.\n    serverData: undefined,\n    metadata: {\n      ...rest,\n      [IR_ENVELOPE_KEY]: envelope,\n      [IR_PROVISIONAL_KEY]: true,\n    },\n  } as T;\n\n  const routed = applyIrKindRoute(provisionalBlock, env, options);\n  // Nothing claimed it (unknown kind, no component) — `applyIrKindRoute`\n  // returns the SAME reference. Withhold rather than render raw partial JSON.\n  if (routed === provisionalBlock) return null;\n  // A bridged kind whose bridge DECLINED this value (too thin to render — a\n  // quiz with no answerable question yet) routed on type alone, which would\n  // hand the component the partial JSON text to parse. Withhold: the loading\n  // skeleton stays up for this frame and the next `seq` tries again.\n  if (\n    env.kinds.getDefinition(kind)?.toLegacyServerData &&\n    !(routed as { serverData?: unknown }).serverData\n  ) {\n    return null;\n  }\n\n  return { block: routed, kind, seq: event.seq, envelope };\n}\n","/**\n * THE BOUND ROUTE — the pure route functions with a host's env and owned\n * types partially applied, built ONCE in a host wiring module.\n *\n * Every host was writing the same wrapper file by hand: one function per pure\n * route, each forwarding `matrx…Env` + `ownedTypes` (matrx-frontend carried\n * two such modules; the dashboard a third). Per C22 that repeated delta is\n * package-provided: a host module now only INJECTS (its env, its owned block\n * types) and re-exports what this factory returns.\n *\n * The functions are the exact pure routes — read `kind-route.ts` /\n * `partial-kind-route.ts` for semantics; nothing behavioral lives here.\n */\n\nimport type { IrRoutableBlock, KindRouteEnv } from \"../host/host-types\";\nimport {\n  applyIrKindRoute,\n  kindServerDataFromStoredValue,\n  type KindRouteOptions,\n} from \"./kind-route\";\nimport {\n  isPartialReadyKind,\n  resolveProvisionalKindRender,\n  resolveSupersededKindRender,\n  type PartialRenderOptions,\n  type ProvisionalKindRender,\n  type SupersededKindRender,\n} from \"./partial-kind-route\";\n\nexport interface KindRouteBinding {\n  /** Route one block through the bound registries. */\n  applyIrKindRoute<T extends IrRoutableBlock>(block: T): T;\n  /**\n   * Rehydration route for STRUCTURED persisted artifacts: given a stored\n   * zero-loss value object, derive the registered kind's legacy `serverData`\n   * with no re-parse. Null for non-objects, unregistered kinds, or kinds\n   * without a legacy bridge.\n   */\n  kindServerDataFromStoredValue(value: unknown): Record<string, unknown> | null;\n  /** Has this kind opted in to being handed a provisional value? */\n  isPartialReadyKind(kind: string): boolean;\n  /**\n   * Resolve a block's provisional render, or null when there is nothing to\n   * show provisionally (no event, a terminal event, a withheld kind, a kind\n   * nothing can route, or a verified envelope that already won).\n   */\n  resolveProvisionalKindRender<\n    T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n  >(\n    block: T,\n    options?: Pick<PartialRenderOptions, \"streamActive\">,\n  ): ProvisionalKindRender<T> | null;\n  /**\n   * Route a completed workflow block whose `superseded` terminal confirms the\n   * kind but whose shadowed lane never built a verified envelope.\n   */\n  resolveSupersededKindRender<\n    T extends IrRoutableBlock & {\n      content: string;\n      metadata?: Record<string, unknown>;\n    },\n  >(block: T): SupersededKindRender<T> | null;\n}\n\n/** Bind the pure routes to one host's env + owned block types. */\nexport function createKindRouteBinding(\n  env: KindRouteEnv,\n  options?: KindRouteOptions,\n): KindRouteBinding {\n  const ownedTypes = options?.ownedTypes;\n  return {\n    applyIrKindRoute: (block) =>\n      applyIrKindRoute(block, env, ownedTypes ? { ownedTypes } : undefined),\n    kindServerDataFromStoredValue: (value) =>\n      kindServerDataFromStoredValue(value, env),\n    isPartialReadyKind: (kind) => isPartialReadyKind(kind, env),\n    resolveProvisionalKindRender: (block, streamOptions) =>\n      resolveProvisionalKindRender(block, env, {\n        ...streamOptions,\n        ...(ownedTypes ? { ownedTypes } : null),\n      }),\n    resolveSupersededKindRender: (block) =>\n      resolveSupersededKindRender(\n        block,\n        env,\n        ownedTypes ? { ownedTypes } : undefined,\n      ),\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACyEO,IAAM,aAAa;AAGnB,IAAM,kBAAkB;;;ACtBxB,IAAM,WAAW;AA4EjB,SAAS,eAAe,OAA+C;AAC5E,QAAM,OAAO,MAAM,QAAQ;AAC3B,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAsBO,SAAS,eAAe,OAA6B;AAC1D,SAAO,MAAM,SAAS,UAAU,MAAM,SAAS;AACjD;;;AC3IA,IAAM,SAAS;AACf,IAAM,SAAS;AAEf,SAAS,UAAU,MAAc,OAAuB;AACtD,MAAI,IAAI,SAAS;AACjB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,SAAK,MAAM,WAAW,CAAC;AAEvB,QAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,MAAM,KAAK,SAAU;AAAA,EACxE;AACA,SAAO,MAAM;AACf;AAQO,SAAS,sBAAqC;AACnD,MAAI,IAAI;AACR,MAAI,IAAI;AACR,MAAI,SAAS;AAEb,SAAO;AAAA,IACL,KAAK,OAAqB;AACxB,UAAI,UAAU,GAAG,KAAK;AACtB,UAAI,UAAU,GAAG,KAAK;AACtB,gBAAU,MAAM;AAAA,IAClB;AAAA,IACA,UAAkB;AAChB,aAAO,GAAG,OAAO,SAAS,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,SAAS,EAAE,CAAC;AAAA,IAClE;AAAA,EACF;AACF;AAEO,SAAS,gBAAgB,QAAwB;AACtD,QAAM,SAAS,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