{"version":3,"sources":["../react-views.ts","../react/use-kind-version.ts","../react/KindInstanceRender.tsx","../core/ir-types.ts","../core/kind-schema.types.ts","../core/fingerprint.ts","../core/normalize.ts","../core/envelope-read.ts","../core/envelope-value.ts","../directives/grammar.ts","../directives/legacy-shell.ts","../directives/decode.ts","../directives/display.ts","../directives/item-summary.ts","../directives/item-kind.ts","../react-directives/DirectiveRender.tsx","../react-directives/ApplyDirectiveButton.tsx","../react-directives/item-changes.ts","../react-directives/record-values.ts","../react-directives/failure-words.ts","../react-directives/icons.tsx","../react-directives/DirectiveFallbackCard.tsx","../react-directives/DirectiveProvisionalCard.tsx","../react-directives/registry.ts","../react-directives/SideEffectDirectiveCard.tsx","../route/kind-route.ts","../react/ProvisionalKindBoundary.tsx","../wire/runtime-wrapper.ts","../route/partial-kind-route.ts","../react/GenericStructuredView.tsx","../react/RuntimeWrapperViews.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * `@ai-matrx/content-ir/react-views` — the components every UI shares:\n * `KindInstanceRender`, the generic structured floor, the runtime-wrapper\n * chrome, the provisional boundary/frame, and the per-kind repaint hook.\n * Client-only; the entry is stamped \"use client\".\n */\nexport * from \"./react/use-kind-version\";\nexport * from \"./react/KindInstanceRender\";\nexport * from \"./react/ProvisionalKindBoundary\";\nexport * from \"./react/GenericStructuredView\";\nexport * from \"./react/RuntimeWrapperViews\";\n","\"use client\";\n\n/**\n * Late-arrival repaint for the streaming render path — GRANULAR.\n *\n * `applyIrKindRoute` is a pure, synchronous read of two registries. When a\n * schema or component row lands AFTER a block rendered — a cold fetch losing\n * the race with the region end, the warm list resolving mid-conversation —\n * nothing in React state changes, so the block would stay stuck on its\n * pre-arrival rendering (raw JSON / generic) forever.\n *\n * Granularity contract: each consumer subscribes to ONE kind's version\n * (per-kind counters in both registries, plus a rare wholesale epoch). A\n * cold/warm arrival for kind X re-renders only mounted blocks of kind X —\n * never every block in every conversation. In a host WITHOUT the React\n * Compiler, pair this with an explicit `useMemo` on (block, version) so the\n * route itself does not re-execute on unrelated renders.\n */\n\nimport { useCallback, useSyncExternalStore } from \"react\";\nimport { useContentIrHostOrNull } from \"../host/ContentIrProvider\";\nimport type {\n  ContentIrHost,\n  KindDefinitionSource,\n} from \"../host/host-types\";\nimport type { ComponentResolutionSource } from \"../resolver/component-resolution.types\";\n\n/**\n * The two registries this hook watches. Passed explicitly by a host whose\n * render path sits BELOW no provider — matrx-frontend's block renderer runs\n * deep inside chat, workflow, and canvas trees that predate this package, and\n * threading a provider through all of them to read two counters would be the\n * tail wagging the dog.\n */\nexport interface KindVersionSources {\n  kinds: Pick<KindDefinitionSource, \"getKindVersion\" | \"subscribeKind\">;\n  components: Pick<ComponentResolutionSource, \"getKindVersion\" | \"subscribeKind\">;\n}\n\nconst noopSubscribe = () => () => {};\nconst zero = () => 0;\n\n/**\n * Subscribes the caller to registry changes FOR ONE KIND and returns that\n * kind's combined version. Pass null for blocks with no envelope kind — they\n * never repaint from registries (nothing to learn about them).\n *\n * `sources` defaults to the provider's host. Passing them explicitly is the\n * supported way to use this hook outside a provider.\n */\nexport function useContentIrKindVersion(\n  kind: string | null,\n  sources?: KindVersionSources,\n): number {\n  const host: ContentIrHost | null = useContentIrHostOrNull();\n  const resolved: KindVersionSources | null = sources ?? host;\n\n  if (kind && !resolved) {\n    throw new Error(\n      \"[content-ir/react] useContentIrKindVersion needs either a \" +\n        \"ContentIrRenderProvider above it or explicit `sources`.\",\n    );\n  }\n\n  const subscribe = useCallback(\n    (onStoreChange: () => void) => {\n      if (!kind || !resolved) return noopSubscribe();\n      const unsubKinds = resolved.kinds.subscribeKind(kind, onStoreChange);\n      const unsubComponents = resolved.components.subscribeKind(\n        kind,\n        onStoreChange,\n      );\n      return () => {\n        unsubKinds();\n        unsubComponents();\n      };\n    },\n    [resolved, kind],\n  );\n\n  const getSnapshot = useCallback(\n    () =>\n      kind && resolved\n        ? // Both counters are monotonic, so the sum is monotonic — a change in\n          // either registry produces a new snapshot value for this kind.\n          resolved.kinds.getKindVersion(kind) +\n          resolved.components.getKindVersion(kind)\n        : 0,\n    [resolved, kind],\n  );\n\n  return useSyncExternalStore(subscribe, getSnapshot, zero);\n}\n","\"use client\";\n\n/**\n * KindInstanceRender — render ONE canonical kind instance through the REAL\n * production path, never a lookalike.\n *\n * The value object is wrapped by the kernel's complete-envelope assembler\n * (`envelopeFromCompleteValue`), placed on a raw render block's\n * `metadata.__ir`, and handed to the host's block renderer — which runs\n * `applyIrKindRoute` exactly as it does for streamed content (db-sourced\n * `kind_component` renderers resolve through the same route automatically).\n *\n * If the kind has no registered component/bridge, the value renders through\n * the host's structured-value FLOOR (`renderValue`) — the platform seam that\n * turns any JSON value into a human document. It used to become a ```json code\n * block instead, which is what put 19 of 23 Study Pack steps in front of a\n * non-technical reader as a JSON dump (2026-08-18). A curated `kind_component`\n * is an UPGRADE over a good default, never the prerequisite for one.\n *\n * THIS IS THE COMPONENT EVERY UI NEEDS. It is the door between \"I am holding a\n * kind-shaped value\" and \"the reader sees it drawn properly\", and it was the\n * single biggest reason a second UI could not render a kind: the routing\n * three-state lifecycle, the eager targeted resolve, the warm-then-refresh\n * order, and the \"checking is not the same as missing\" rule are all subtle and\n * were all trapped inside matrx-frontend.\n */\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { envelopeFromCompleteValue, IR_ENVELOPE_KEY } from \"../core\";\nimport { isReservedDirectiveSlug } from \"../directives\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport { DirectiveRender } from \"../react-directives/DirectiveRender\";\nimport type { ContentIrHost } from \"../host/host-types\";\nimport { GENERIC_STRUCTURED_COMPONENT_KEY } from \"../route/kind-route\";\n\nexport function isRecordValue(\n  value: unknown,\n): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * True when `applyIrKindRoute` has a registered render path for this kind — a\n * compiled legacy bridge OR any ACTIVE resolver row (including db-sourced user\n * components, which route to `db_kind_component`). Mirrors the route's own\n * decision order; requires the resolver warm tier for db rows (see the warm\n * tick in {@link KindInstanceRender}).\n */\n/**\n * Is there a render path for this kind that is NOT the generic key/value floor?\n *\n * 🚨 READ THIS BEFORE USING IT AS A HEALTH SIGNAL. It answers a narrow\n * question — \"will a direct-object render mount something other than the\n * generic view?\" — and it is the right question for the fallback decision it\n * was written for. It is the WRONG question for \"does this kind work\".\n *\n * It cannot see any of: whether the kind's schema loads, whether a streamed\n * payload is recognized from text, or what `applyIrKindRoute` returns for a\n * real envelope. On 2026-08-29 every one of ~221 kinds that had stopped\n * rendering in chat still answered `true` here, because their component rows\n * were fine — the recognition step ahead of the component was not.\n *\n * For \"does this kind work\", run the render paths\n * (`features/content-ir/render-paths`) and read the route's actual answer.\n */\nexport function kindIsRoutable(kind: string, host: ContentIrHost): boolean {\n  // A directive's display is the directive tier — always routable.\n  if (isReservedDirectiveSlug(kind)) return true;\n  if (host.kinds.getDefinition(kind)?.legacyBlockType) return true;\n  const resolution = host.components.resolve(kind, host.platform, \"output\");\n  if (!resolution?.isActive) return false;\n  // A row naming the generic fallback is coverage on paper only — the reader\n  // still gets a key/value dump, so this must not read as \"routable\".\n  return resolution.componentKey !== GENERIC_STRUCTURED_COMPONENT_KEY;\n}\n\nexport interface KindInstanceRenderProps {\n  kind: string;\n  /** The canonical instance value (a `kind_example.data` row, a form-emitted instance, a node output). */\n  value: unknown;\n  /** Show the honest \"no component registered\" notice when unroutable. Default true. */\n  showRoutingNote?: boolean;\n  /**\n   * What to render when the routing decision lands on \"no component exists for\n   * this kind\". The universal document view is the right answer almost\n   * everywhere — it reads well and hides nothing. It is still the wrong answer\n   * when the raw value is an internal ENVELOPE rather than content: an\n   * `agent_result` dumped the verbatim prompt, the model id and the token bill\n   * into the box a learner was waiting on. Passing a fallback lets that caller\n   * show what the reader actually wants WITHOUT anyone second-guessing the\n   * routing decision — this component stays the ONE place that decides whether\n   * a kind has a component.\n   *\n   * Omitted → the host's floor, exactly as before.\n   */\n  unroutableFallback?: ReactNode;\n  /**\n   * Chrome, per THE WRAPPER LAW and the owner's no-cards ruling (2026-10-24:\n   * \"Avoid cards at all costs. Especially cards within other cards.\"): a shape\n   * is never boxed by default.\n   * - \"flat\" (default): normal padding only (`px-3 py-2`) — no border, no\n   *   background. The shape sits on the host surface, full width, off the walls.\n   * - \"bare\": no padding either — for a host that already pads (a titled panel,\n   *   a dialog body, a chat message).\n   * - \"card\": the deliberate opt-in bordered surface. Never inside another card.\n   */\n  variant?: KindInstanceFrameVariant;\n  className?: string;\n}\n\ntype RoutingStatus = \"checking\" | \"routable\" | \"unroutable\";\n\nexport type KindInstanceFrameVariant = \"flat\" | \"card\" | \"bare\";\n\n/**\n * The frame classes per variant — exported so a guard can prove the DEFAULT\n * frame carries no border and no card background.\n */\nexport const KIND_INSTANCE_FRAME_CLASS: Record<KindInstanceFrameVariant, string | undefined> = {\n  flat: \"px-3 py-2\",\n  card: \"rounded-md border border-border bg-card p-3\",\n  bare: undefined,\n};\n\nexport const DEFAULT_KIND_INSTANCE_FRAME: KindInstanceFrameVariant = \"flat\";\n\nexport function KindInstanceRender(props: KindInstanceRenderProps) {\n  // THE DIRECTIVE TIER: a reserved slug never consults the component resolver.\n  if (isReservedDirectiveSlug(props.kind)) {\n    return (\n      <DirectiveRender\n        content={props.value}\n        {...(props.className === undefined ? {} : { className: props.className })}\n      />\n    );\n  }\n  return <KindInstanceRenderInner {...props} />;\n}\n\nfunction KindInstanceRenderInner({\n  kind,\n  value,\n  showRoutingNote = true,\n  unroutableFallback,\n  variant = DEFAULT_KIND_INSTANCE_FRAME,\n  className,\n}: KindInstanceRenderProps) {\n  const host = useContentIrHost();\n\n  // Routing must be judged with the WARM tiers in (user kind definitions +\n  // `kind_component` resolver rows — including source='db' user components).\n  // Keep the note in an explicit three-state lifecycle: a cold registry is\n  // \"checking\", not proof that a component is missing. This prevents the false\n  // warning from flashing or sticking while the host's renderer independently\n  // upgrades to a newly arrived db component.\n  const [routingStatus, setRoutingStatus] = useState<RoutingStatus>(() =>\n    kindIsRoutable(kind, host) ? \"routable\" : \"checking\",\n  );\n\n  useEffect(() => {\n    let cancelled = false;\n    let warmed = false;\n    const syncRoutingStatus = () => {\n      if (cancelled) return;\n      setRoutingStatus(\n        kindIsRoutable(kind, host)\n          ? \"routable\"\n          : warmed\n            ? \"unroutable\"\n            : \"checking\",\n      );\n    };\n\n    const unsubscribe = host.components.subscribe(syncRoutingStatus);\n    syncRoutingStatus();\n\n    // Eager targeted resolve FIRST — the same seam the streaming path uses: two\n    // indexed single-kind reads land this kind's own resolver row in ~100ms, so\n    // first paint shows the real component instead of the floor. The warm sweep\n    // below (megabytes, several round trips) is the backstop, never the gate —\n    // before this, the component only appeared after the full sweep landed,\n    // which users experienced as \"it renders after I switch tabs\" (2026-08-22).\n    host.components.requestComponent(kind, host.platform, \"output\");\n\n    // Sampled BEFORE the warm: refresh-on-view only earns its keep when the\n    // registry was already warm from an earlier mount; on a cold mount it would\n    // re-download the identical list ensureWarm is about to fetch.\n    const wasAlreadyWarm = host.components.getVersion() > 0;\n    void Promise.allSettled([\n      host.kinds.ensureWarm(),\n      host.components.ensureWarm(),\n    ]).then(async () => {\n      warmed = true;\n      syncRoutingStatus();\n      if (wasAlreadyWarm) await host.components.refresh();\n      syncRoutingStatus();\n    });\n\n    return () => {\n      cancelled = true;\n      unsubscribe();\n    };\n  }, [host, kind]);\n\n  const block = isRecordValue(value)\n    ? {\n        type: \"code\",\n        content: JSON.stringify(value, null, 2),\n        language: \"json\",\n        metadata: {\n          [IR_ENVELOPE_KEY]: envelopeFromCompleteValue(value, kind),\n        },\n      }\n    : null;\n\n  const frameClass = KIND_INSTANCE_FRAME_CLASS[variant];\n\n  // A caller that supplied a fallback gets it the moment routing SETTLES on \"no\n  // component\" — never during \"checking\", so a warm-up tick cannot flash the\n  // fallback over a component that is about to resolve.\n  if (routingStatus === \"unroutable\" && unroutableFallback !== undefined) {\n    return <>{unroutableFallback}</>;\n  }\n\n  // The floor. Two ways to land here, and the answer is the same document\n  // either way: the kind settled on \"no component\", or the value is not an\n  // object at all (a scalar / array workflow I/O shape), for which there has\n  // never been a block render path.\n  const onTheFloor = block === null || routingStatus === \"unroutable\";\n\n  const notice =\n    \"This shape has no custom component yet, so it renders through the universal viewer — exactly what production shows today.\";\n\n  return (\n    <div className={className ? `space-y-3 ${className}` : \"space-y-3\"}>\n      {showRoutingNote && routingStatus === \"unroutable\"\n        ? (host.renderNotice?.(notice) ?? (\n            <div className=\"rounded-md border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-800 dark:text-amber-200\">\n              {notice}\n            </div>\n          ))\n        : null}\n      <div className={frameClass}>\n        {onTheFloor\n          ? host.renderValue({ value, kind })\n          : host.renderBlock(block)}\n      </div>\n    </div>\n  );\n}\n\nexport default KindInstanceRender;\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 * Pure envelope→value functions (the zero-data-loss wire round-trip).\n *\n * These live in core/ (the pure kernel) because every layer needs them —\n * including kinds/legacy-bridge-utils, whose bridges are built at MODULE\n * SCOPE inside kinds/<slug>.ts files that system-kinds.ts imports. When these\n * functions lived in redux/render-block-envelope.ts, that file's memo/capture\n * imports closed a module cycle (kinds → bridge-utils → render-block-envelope\n * → region-envelope-memo → kind-registry → system-kinds → kinds), which made\n * SYSTEM_KIND_DEFINITIONS entry-point-fragile (undefined defs when a kinds\n * module was the import entry). Keeping them here makes every kinds module\n * cycle-free BY CONSTRUCTION. redux/render-block-envelope re-exports them for\n * its existing consumers.\n */\n\nimport { isEmptyResidue, type CanonicalBlockIR } from \"./ir-types\";\nimport { KIND_KEY } from \"./kind-schema.types\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Rebuild the region's full data: walk the root value and merge each node's\n * residue extras back in (root residue + nodeIndex residues). This is the\n * zero-data-loss read: nothing the model emitted is missing, whether or not\n * a schema knew about it.\n */\nexport function reconstructRegionValue(\n  envelope: CanonicalBlockIR,\n): Record<string, unknown> {\n  const cloned = structuredClone(envelope.root.value);\n\n  const applyExtras = (\n    target: Record<string, unknown>,\n    extras: Record<string, unknown> | null | undefined,\n  ) => {\n    if (!extras) return;\n    for (const [key, value] of Object.entries(extras)) {\n      target[key] = structuredClone(value);\n    }\n  };\n\n  applyExtras(cloned, envelope.root.residue?.extra);\n\n  for (const [pathKey, meta] of Object.entries(envelope.nodeIndex ?? {})) {\n    const residue = meta.residue;\n    if (!residue || isEmptyResidue(residue) || !residue.extra) continue;\n\n    const segments = pathKey.split(\".\");\n    let cursor: unknown = cloned;\n    for (const segment of segments) {\n      if (Array.isArray(cursor)) {\n        cursor = cursor[Number(segment)];\n      } else if (isRecord(cursor)) {\n        cursor = cursor[segment];\n      } else {\n        cursor = undefined;\n        break;\n      }\n    }\n    if (isRecord(cursor)) {\n      applyExtras(cursor, residue.extra);\n    }\n  }\n\n  return cloned;\n}\n\n/**\n * Deep-remove the `__kind` discriminator.\n *\n * 🚨 NOT A TRANSFORM FOR PLATFORM DATA. `__kind` is part of the data\n * (KINDS_EVERYWHERE_PLAN §4.2) and stripping it from anything stored, passed or\n * rendered was annihilated on 2026-08-23. This helper survives for exactly two\n * shapes of caller, both of which are guarded:\n *   - a SYMMETRIC COMPARISON that reduces both sides and returns a boolean;\n *   - legacy validation TOLERANCE against a pre-2026-08-23 schema version.\n * Guards: aidream `scripts/check_kind_marker_law.py`,\n * matrx-frontend `pnpm check:kind-marker-law`.\n */\nexport function stripKindDeep(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map(stripKindDeep);\n  }\n  if (isRecord(value)) {\n    const out: Record<string, unknown> = {};\n    for (const [key, child] of Object.entries(value)) {\n      if (key === KIND_KEY) continue;\n      out[key] = stripKindDeep(child);\n    }\n    return out;\n  }\n  return value;\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 ONE LEGACY SURFACE of the Kind Directives protocol — read-only.\n *\n * Stored content written before 2026-08-23 carries the retired 4-key shell\n * (`matrx_version` / `kind` / `type` / `items`). This module translates it into\n * the current two-key shell so `decodeDirective` sees one shape, forever. It\n * never emits, never registers a shape, has no fallback branch, and every use\n * is counted so the containment can be measured. Only `decode.ts` may import\n * it (matrx-frontend's `check-legacy-shim-containment` and aidream's\n * `test_legacy_shim_containment.py` enforce the mirror).\n */\n\nimport { KIND_KEY, buildDirectiveSlug } from \"./grammar\";\n\nconst LEGACY_SENTINEL = \"matrx_version\";\n\nconst CLASS_BY_LEGACY_KIND: Readonly<Record<string, string>> = {\n  reference: \"reference\",\n  secret: \"secret\",\n  validation: \"validation\",\n};\n\nconst LEGACY_SIDE_EFFECT_KINDS: ReadonlySet<string> = new Set([\"output_directive\", \"function\"]);\n\nconst VERB_NOUN_RE = /^(create|update|delete):([a-z][a-z0-9_]*)$/;\n\n// USE COUNTER ON A globalThis SLOT — never a module-level variable. With\n// `splitting: false` dual ESM/CJS output this module is duplicated into the\n// root bundle and the `./directives` bundle; a module local would count per\n// graph and under-report. Never \"clean this up\" into a module local.\nconst USES_SLOT = Symbol.for(\"ai-matrx.content-ir.legacy-shell-uses\");\ntype UsesHolder = typeof globalThis & { [USES_SLOT]?: { count: number } };\nconst uses: { count: number } = ((globalThis as UsesHolder)[USES_SLOT] ??= { count: 0 });\n\nexport function legacyShellUses(): number {\n  return uses.count;\n}\n\nexport function resetLegacyShellUses(): void {\n  uses.count = 0;\n}\n\n/** True ONLY for a genuine retired-shell directive claim (sentinel + a retired kind token). */\nexport function isLegacyShell(obj: unknown): boolean {\n  if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return false;\n  const record = obj as Record<string, unknown>;\n  if (!(LEGACY_SENTINEL in record)) return false;\n  const kind = record.kind;\n  return (\n    typeof kind === \"string\" &&\n    (kind in CLASS_BY_LEGACY_KIND || LEGACY_SIDE_EFFECT_KINDS.has(kind))\n  );\n}\n\nfunction slugForLegacy(kind: string, type: string): string | null {\n  let directiveClass: string;\n  let noun: string;\n  if (LEGACY_SIDE_EFFECT_KINDS.has(kind)) {\n    const match = VERB_NOUN_RE.exec(type);\n    if (match) {\n      directiveClass = match[1]!;\n      noun = match[2]!;\n    } else {\n      directiveClass = \"action\";\n      noun = type;\n    }\n  } else {\n    const mapped = CLASS_BY_LEGACY_KIND[kind];\n    if (!mapped) return null;\n    directiveClass = mapped;\n    noun = type;\n  }\n  try {\n    return buildDirectiveSlug(directiveClass, noun);\n  } catch {\n    return null;\n  }\n}\n\n/** The current two-key shell for a retired one, or null when it cannot be honored. */\nexport function translateLegacyShell(\n  obj: Record<string, unknown>,\n): Record<string, unknown> | null {\n  const kind = obj.kind;\n  const type = obj.type;\n  if (typeof kind !== \"string\" || typeof type !== \"string\") return null;\n  const slug = slugForLegacy(kind, type);\n  if (slug === null) return null;\n  const items = obj.items;\n  uses.count += 1;\n  return { [KIND_KEY]: slug, items: Array.isArray(items) ? [...items] : [] };\n}\n","/**\n * Decode a Kind Directive — THE one entry point on every client.\n *\n * `decodeDirective()` recognizes the shell (current OR, for stored content\n * only, the retired 4-key one), reads the slug, and derives class + noun. A\n * caller only ever sees a parsed {@link DecodedDirective}; nothing downstream\n * inspects a raw shell again.\n *\n * ITEM VALIDATION IS THE SERVER'S. The registered item models live in aidream\n * (`services/content_ir_directives/registry.py`) and validate on apply; a\n * client-side copy of ~120 item models is exactly the drift the merge exists\n * to kill. The client parses identity, routes, and renders. Mirror of aidream\n * `services/content_ir_directives/decode.py`.\n */\n\nimport {\n  type DirectiveClass,\n  type DirectiveSlug,\n  KIND_KEY,\n  isReservedDirectiveSlug,\n  parseDirectiveSlug,\n} from \"./grammar\";\nimport { isLegacyShell, translateLegacyShell } from \"./legacy-shell\";\n\n/**\n * A well-formed-looking directive that cannot be honored (a malformed slug, or\n * a retired shell that does not map onto the grammar). Never thrown for \"this\n * isn't a directive\" — that is `null`.\n */\nexport class DirectiveDecodeError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"DirectiveDecodeError\";\n  }\n}\n\nexport interface DecodedDirective {\n  /** The parsed slug — class, noun, capability and the position law. */\n  readonly parsed: DirectiveSlug;\n  readonly slug: string;\n  readonly directiveClass: DirectiveClass;\n  readonly noun: string;\n  readonly items: Record<string, unknown>[];\n  /** The two-key shell, normalized — what a confirm POST round-trips. */\n  readonly shell: Record<string, unknown>;\n  /** True when this arrived in the retired 4-key shell and was translated. */\n  readonly legacyShell: boolean;\n}\n\nfunction asObject(value: unknown): Record<string, unknown> | null {\n  if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n  return value as Record<string, unknown>;\n}\n\n/**\n * A typed directive, or `null` when `value` is not a directive at all. Throws\n * {@link DirectiveDecodeError} when it IS one but cannot be honored.\n */\nexport function decodeDirective(value: unknown): DecodedDirective | null {\n  let obj = asObject(value);\n  if (obj === null) return null;\n\n  let legacy = false;\n  if (isLegacyShell(obj)) {\n    const translated = translateLegacyShell(obj);\n    if (translated === null) {\n      throw new DirectiveDecodeError(\n        `a retired 4-key shell with kind=${JSON.stringify(obj.kind)} type=${JSON.stringify(obj.type)} does not map onto the Kind Directives grammar. Emit the current shell: {\"${KIND_KEY}\": \"directive_v1_<class>_<noun>\", \"items\": [...]}.`,\n      );\n    }\n    obj = translated;\n    legacy = true;\n  }\n\n  const rawSlug = obj[KIND_KEY];\n  if (!isReservedDirectiveSlug(rawSlug)) return null;\n\n  const parsed = parseDirectiveSlug(rawSlug);\n  if (parsed === null) {\n    throw new DirectiveDecodeError(\n      `malformed directive slug ${JSON.stringify(rawSlug)} — it claims the reserved \"directive_v\" namespace but does not parse as directive_v<version>_<class>_<noun>.`,\n    );\n  }\n\n  const rawItems = obj.items;\n  const items = Array.isArray(rawItems)\n    ? rawItems.filter((i): i is Record<string, unknown> => asObject(i) !== null)\n    : [];\n\n  return {\n    parsed,\n    slug: parsed.slug,\n    directiveClass: parsed.directiveClass,\n    noun: parsed.noun,\n    items,\n    shell: { [KIND_KEY]: parsed.slug, items },\n    legacyShell: legacy,\n  };\n}\n\n/**\n * The forgiving read used at render seams: `decodeDirective`, but a directive\n * that cannot be honored comes back as `null` after the reason is handed to\n * `onError`. A render seam must never take a whole message block down over one\n * bad fence — but it must never swallow the reason either.\n */\nexport function tryDecodeDirective(\n  value: unknown,\n  onError?: (message: string) => void,\n): DecodedDirective | null {\n  try {\n    return decodeDirective(value);\n  } catch (error) {\n    onError?.(error instanceof Error ? error.message : \"directive decode failed\");\n    return null;\n  }\n}\n\n/** `decodeDirective` over a JSON string or an already-parsed value. Non-JSON text is `null`. */\nexport function tryDecodeDirectiveContent(\n  content: unknown,\n  onError?: (message: string) => void,\n): DecodedDirective | null {\n  if (typeof content !== \"string\") return tryDecodeDirective(content, onError);\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(content);\n  } catch {\n    return null;\n  }\n  return tryDecodeDirective(parsed, onError);\n}\n","/**\n * THE AUTO-VIEW's naming half: every enrolled noun \"instantly has a view\" —\n * the prefix rule gives it a renderer, and this gives it a NAME. A shape the\n * client has never heard of must still read as \"Create Agent · Agents\", never\n * as the raw `agent` token and never as a slug.\n *\n * The catalog (`platform.entity_types` → the server's directive catalog) is the\n * authority for `label` / `family` / `title_column`; a host that mirrors it\n * passes a {@link DirectiveNounCatalog}. Without one — or for a noun the\n * catalog does not carry (a Kind Action like `plan_tree`) — the name degrades\n * to a title-cased token: legible, honestly derived, never blank.\n */\n\nimport type { DirectiveClass } from \"./grammar\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\n\nexport interface DirectiveNounEntry {\n  /** The noun's human name — \"Agent\", \"Plan tree\". */\n  label?: string | null;\n  /** The catalog family (\"Agents\"). */\n  family?: string | null;\n  /** Which field of a row names it (`name`, `title`, …). */\n  titleColumn?: string | null;\n}\n\n/** A host-supplied lookup over the mirrored catalog. `undefined` = not carried. */\nexport type DirectiveNounCatalog = (noun: string) => DirectiveNounEntry | undefined;\n\nexport interface DirectiveDisplay {\n  /** The noun's human name — \"Agent\", \"Plan tree\". */\n  noun: string;\n  /** The catalog family (\"Agents\"), or \"\" when the catalog has none. */\n  family: string;\n  /** What this directive DOES, in the user's words — \"Create\", \"Reference\". */\n  action: string;\n  /** One line: \"Create Agent\". */\n  title: string;\n}\n\n/** `plan_node_patch` → `Plan Node Patch` — THE humanizer, the honest last resort. */\nexport function titleCaseToken(token: string): string {\n  return humanizeIdentifier(token) || token;\n}\n\n/**\n * How a class reads to a human. `action` is deliberately \"Run\": a Kind Action\n * is a named procedure, and \"Action Plan tree\" reads like a noun phrase where a\n * verb belongs. Mirrored by the server's kind-catalog label.\n */\nexport const ACTION_BY_CLASS: Readonly<Record<DirectiveClass, string>> = {\n  reference: \"Reference\",\n  view: \"View\",\n  create: \"Create\",\n  update: \"Update\",\n  delete: \"Delete\",\n  action: \"Run\",\n  validation: \"Validate\",\n  secret: \"Secret\",\n};\n\nexport function nounLabel(noun: string, catalog?: DirectiveNounCatalog): string {\n  const label = catalog?.(noun)?.label;\n  return label && label.length > 0 ? label : titleCaseToken(noun);\n}\n\nexport function nounFamily(noun: string, catalog?: DirectiveNounCatalog): string {\n  return catalog?.(noun)?.family ?? \"\";\n}\n\nexport function nounTitleColumn(noun: string, catalog?: DirectiveNounCatalog): string | null {\n  return catalog?.(noun)?.titleColumn ?? null;\n}\n\n/** Everything a generic card needs to name a directive it cannot render. */\nexport function directiveDisplay(\n  directiveClass: DirectiveClass,\n  noun: string,\n  catalog?: DirectiveNounCatalog,\n): DirectiveDisplay {\n  const label = nounLabel(noun, catalog);\n  const action = ACTION_BY_CLASS[directiveClass];\n  return {\n    noun: label,\n    family: nounFamily(noun, catalog),\n    action,\n    title: `${action} ${label}`,\n  };\n}\n","/**\n * Naming and summarizing ONE item of a directive, for the compact card.\n *\n * THE RULE: a user is never asked to approve a write they cannot identify. The\n * card must say WHAT is about to be created/updated/deleted, derived from\n * authority rather than guesswork, in this order:\n *   1. the noun's catalog `title_column` — the server's own answer to \"what\n *      names a row of this table\";\n *   2. the conventional identity fields, in a fixed order;\n *   3. the honest last resort — \"Item 2 of 3\", never a blank chip and never a\n *      slug pretending to be a name.\n *\n * Facts are scalars ONLY. Nesting goes to the panel, never into the row.\n */\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\n\n/** Identity fields, in the order a human would reach for them. */\nconst NAME_KEYS = [\"name\", \"title\", \"label\", \"heading\", \"slug\", \"key\", \"question\", \"summary\"] as const;\n\n/** Never shown as a fact chip — identity, plumbing, or already in the title. */\nconst FACT_EXCLUDE = new Set<string>([\n  \"__kind\",\n  ...NAME_KEYS,\n  \"id\",\n  \"description\",\n  \"about\",\n  \"notes\",\n  \"content\",\n  \"text\",\n  \"body\",\n  \"organization_id\",\n  \"user_id\",\n  \"created_by\",\n  \"resource_type\",\n]);\n\nfunction firstString(item: Record<string, unknown>, keys: readonly string[]): string | null {\n  for (const key of keys) {\n    const value = item[key];\n    if (typeof value === \"string\" && value.trim()) return value.trim();\n  }\n  return null;\n}\n\n/**\n * What to call this item. `titleColumn` is the noun's catalog title column\n * (consulted first); null when the catalog carries none.\n */\nexport function catalogItemTitle(\n  item: Record<string, unknown>,\n  titleColumn: string | null,\n  index: number,\n  total: number,\n): string {\n  const fromCatalog = titleColumn ? firstString(item, [titleColumn]) : null;\n  const name = fromCatalog ?? firstString(item, NAME_KEYS);\n  if (name) return name;\n  return total > 1 ? `Item ${index + 1} of ${total}` : \"Item\";\n}\n\n/** A one-line subtitle when the item carries prose about itself. */\nexport function itemSubtitle(item: Record<string, unknown>): string | null {\n  return firstString(item, [\"description\", \"about\", \"summary\", \"doc\"]);\n}\n\nexport interface ItemFact {\n  key: string;\n  label: string;\n  value: string;\n}\n\n/**\n * A UUID is never a fact. THE UUID RULE: an id is shown as its first segment\n * with a copy control and the full value on hover — which a dense fact chip\n * cannot do. Found in production 2026-09-08: `model_id` rendered as a chip.\n */\n\n/** `variable_definitions` → \"variables\". Underscores read as developer output. */\nconst FACT_LABEL_OVERRIDES: Readonly<Record<string, string>> = {\n  variable_definitions: \"variables\",\n  context_policies: \"context\",\n  custom_tools: \"custom tools\",\n};\n\nfunction factLabel(key: string): string {\n  return FACT_LABEL_OVERRIDES[key] ?? key.replace(/_/g, \" \");\n}\n\n/**\n * Up to `limit` scalar facts about the item — counts for collections, values\n * for scalars. Nested objects are deliberately absent (they belong in the\n * panel), and so is anything already carried by the title/subtitle.\n */\nexport function itemFacts(item: Record<string, unknown>, limit = 4): ItemFact[] {\n  const facts: ItemFact[] = [];\n  for (const [key, value] of Object.entries(item)) {\n    if (facts.length >= limit) break;\n    if (FACT_EXCLUDE.has(key)) continue;\n    if (Array.isArray(value)) {\n      if (value.length === 0) continue;\n      facts.push({ key, label: factLabel(key), value: String(value.length) });\n      continue;\n    }\n    if (typeof value === \"string\") {\n      const trimmed = value.trim();\n      if (!trimmed || trimmed.length > 40) continue;\n      if (isUuidShape(trimmed)) continue;\n      facts.push({ key, label: factLabel(key), value: trimmed });\n      continue;\n    }\n    if (typeof value === \"number\" || typeof value === \"boolean\") {\n      facts.push({ key, label: factLabel(key), value: String(value) });\n    }\n  }\n  return facts;\n}\n","/**\n * THE DIRECTIVE⇄KIND SEAM, client side.\n *\n * Arman, 2026-08-26: the envelope / Matrx-Actions system and the Shape (kind)\n * system are ONE system with several methods inside it. They meet at the ITEM.\n * A directive is a CONTAINER; its items are the payload, and when the server's\n * item model is already a `KindModel`, that payload IS a registered kind\n * instance — so the kind system already knows how to validate, render and copy\n * it.\n *\n * The seam is SERVER-DERIVED (`ShapeSpec.item_kind`). Since 2026-09-08 the ONE\n * kind endpoint publishes every directive shape as a KindDescriptor whose\n * `items` EDGE names the item kind, so a client reads it from the same\n * catalog it already holds — {@link directiveItemKindFromEdges}. A host that\n * mirrors the directive catalog manifest instead passes its map as a\n * {@link DirectiveItemKindLookup}. `null` is HONEST, never a gap-filler.\n */\n\nimport { KIND_KEY } from \"./grammar\";\n\n/** A host-supplied lookup: slug → the kind ONE item is, or null. */\nexport type DirectiveItemKindLookup = (slug: string) => string | null;\n\n/** The `items` edge of a directive KindDescriptor, as the kind catalog serves it. */\nexport interface DirectiveItemsEdge {\n  field_name?: string;\n  fieldPath?: string;\n  child_kind?: string;\n  childKind?: string;\n}\n\n/** The item kind named by a directive descriptor's `items` edge, or null. */\nexport function directiveItemKindFromEdges(\n  edges: readonly DirectiveItemsEdge[] | null | undefined,\n): string | null {\n  for (const edge of edges ?? []) {\n    const field = edge.field_name ?? edge.fieldPath;\n    const child = edge.child_kind ?? edge.childKind;\n    if (field === \"items\" && typeof child === \"string\" && child) return child;\n  }\n  return null;\n}\n\n/**\n * The item, presented the way the kind pipeline expects it: `__kind` FIRST so a\n * consumer types the object from its own first key. `__kind` is ADDED, never\n * overwritten: an item that already carries its marker keeps the value it was\n * emitted with. Null when no kind is known — the caller owns the generic floor.\n */\nexport function asKindInstance(\n  item: Record<string, unknown>,\n  kind: string | null,\n): Record<string, unknown> | null {\n  const existing = item[KIND_KEY];\n  const resolved = typeof existing === \"string\" && existing ? existing : kind;\n  if (!resolved) return null;\n  return { [KIND_KEY]: resolved, ...item };\n}\n","\"use client\";\n\n/**\n * DirectiveRender — THE renderer for anything whose `__kind` is a reserved\n * directive slug, on every AI Matrx UI.\n *\n * Pipeline (one pipeline, mirroring the backend):\n *   0. THE PROVISIONAL TIER — a head that names a directive but does not\n *      decode yet renders `DirectiveProvisionalCard` (\"writing…\" while\n *      streaming, \"cut off\" once the host says the stream ended).\n *   1. `tryDecodeDirectiveContent` → the two-key shell (a stored 4-key fence is\n *      translated inside the decoder). Not a directive (bad JSON / no reserved\n *      `__kind`) → raw <pre>, never throws. An unhonourable shell is REPORTED\n *      through the host and falls to raw — a render seam must not take a whole\n *      message block down over one fence, and must never go silent.\n *   2. `getDirectiveRenderer` → exact slug, else the CLASS prefix rule (the\n *      host's registrations). Found → render it.\n *   3. THE SIDE-EFFECT TIER — every create / update / delete / action shape\n *      renders the side-effect card, so a person is never asked to approve a\n *      write they cannot identify.\n *   4. THE FLOOR — a class nothing registers still shows the fallback card.\n *      Never null, never silent.\n *\n * Position decides capability: in content only `reference`/`secret` resolve;\n * a side-effect directive in prose is a card with an explicit Apply, never\n * executed on sight.\n */\n\nimport { looksLikeDirectiveHead, tryDecodeDirectiveContent } from \"../directives\";\nimport { DirectiveScopeProvider, useDirectiveHost } from \"./directive-host\";\nimport { DirectiveFallbackCard } from \"./DirectiveFallbackCard\";\nimport { DirectiveProvisionalCard } from \"./DirectiveProvisionalCard\";\nimport { getDirectiveRenderer } from \"./registry\";\nimport { SideEffectDirectiveCard } from \"./SideEffectDirectiveCard\";\n\nexport interface DirectiveRenderProps {\n  /** The fence body (JSON string) or an already-parsed shell / value. */\n  content: unknown;\n  className?: string;\n  /**\n   * Whether the document may still be arriving. A host that knows its stream\n   * has ended passes `false`, so an undecodable directive head is shown as CUT\n   * OFF rather than \"writing…\" forever. Omitted = it may still be arriving.\n   */\n  streaming?: boolean;\n  /**\n   * The conversation this directive renders in (a chat message). Applies and\n   * ledger reads key on it — the same namespace an agent proposal's Approve\n   * uses — so one action can never apply twice through two doors. Omit in a\n   * person's own content. Overrides any enclosing `DirectiveScopeProvider`.\n   */\n  conversationId?: string | null;\n}\n\n/**\n * A document that parses is WHOLE: if it still does not decode, it is a\n * malformed directive (already reported by the decoder), never one \"still\n * arriving\" — only a genuinely unfinished document gets the provisional tier.\n */\nfunction isWholeJson(content: string): boolean {\n  try {\n    JSON.parse(content);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport function DirectiveRender({ conversationId, ...props }: DirectiveRenderProps) {\n  if (conversationId === undefined) return <DirectiveRenderInner {...props} />;\n  return (\n    <DirectiveScopeProvider conversationId={conversationId}>\n      <DirectiveRenderInner {...props} />\n    </DirectiveScopeProvider>\n  );\n}\n\nfunction DirectiveRenderInner({ content, className, streaming }: Omit<DirectiveRenderProps, \"conversationId\">) {\n  const host = useDirectiveHost();\n  const directive = tryDecodeDirectiveContent(content, (message) => {\n    const line = `[kind-directives] ${message}`;\n    if (host.reportError) host.reportError(line);\n    else console.error(line);\n  });\n\n  if (!directive) {\n    // THE PROVISIONAL TIER: the head already names a directive but the shell is\n    // not whole yet (mid-stream) or never became whole (cut off). The class and\n    // noun are known from the first bytes — say what it is, never show the\n    // growing JSON as if it were the answer.\n    if (typeof content === \"string\" && looksLikeDirectiveHead(content) && !isWholeJson(content)) {\n      return (\n        <DirectiveProvisionalCard content={content} streaming={streaming !== false} className={className} />\n      );\n    }\n    const raw = typeof content === \"string\" ? content : JSON.stringify(content, null, 2);\n    return (\n      <pre\n        className={`my-3 overflow-x-auto rounded-md border border-border bg-muted px-3 py-2 text-xs text-muted-foreground${className ? ` ${className}` : \"\"}`}\n      >\n        {raw}\n      </pre>\n    );\n  }\n\n  const Renderer = getDirectiveRenderer(directive);\n  if (Renderer) return <Renderer directive={directive} />;\n  if (directive.parsed.executes) return <SideEffectDirectiveCard directive={directive} />;\n  return <DirectiveFallbackCard directive={directive} />;\n}\n\nexport default DirectiveRender;\n","\"use client\";\n\n/**\n * \"Apply\" for a side-effect Kind Directive that arrived as CONTENT.\n *\n * THE POSITION RULE, honored exactly: a directive inside content NEVER\n * auto-executes — that is the guard against untrusted content mutating things.\n * But \"does not auto-execute\" was never \"is inert\": the user seeing it must be\n * able to say yes. This button IS that yes, through the host's `confirm` seam\n * (`POST /directives/confirm`, re-validated server-side, run as the user).\n *\n * No `confirm` seam → NO button. A control that cannot do its job is absent,\n * never dead. Only a side-effect class is applicable at all (`parsed.executes`).\n */\n\nimport { useEffect, useRef, useState, useSyncExternalStore } from \"react\";\nimport { nounLabel, type DecodedDirective } from \"../directives\";\nimport {\n  useDirectiveHost,\n  useDirectiveScope,\n  type DirectiveRecordRef,\n  type DirectiveShell,\n} from \"./directive-host\";\nimport { TARGETING_CLASSES, itemRecordId, recordFallbackName } from \"./item-changes\";\nimport { noteRecordChanged } from \"./record-values\";\nimport { failureWords } from \"./failure-words\";\nimport { AlertIcon, CheckCircleIcon, LoaderIcon, PlayIcon, RotateCcwIcon } from \"./icons\";\n\n/** The records an update/delete names — re-read wherever they are shown once it ran. */\nfunction announceChangedRecords(directive: DecodedDirective, items: Record<string, unknown>[]): void {\n  if (!TARGETING_CLASSES.has(directive.directiveClass)) return;\n  for (const item of items) {\n    const id = itemRecordId(item);\n    if (id) noteRecordChanged(id);\n  }\n}\n\ntype ApplyState =\n  // Reading the server ledger on mount: has this block already run? Nothing\n  // offers a write until it answers (reviewer defect 5, 2026-10-02).\n  | { status: \"checking\" }\n  // The ledger has a claim but no result: another request is applying it now.\n  | { status: \"finishing\" }\n  | { status: \"idle\" }\n  // The host's `ask` dialog is up. NOTHING is applying yet, so nothing says so.\n  | { status: \"asking\" }\n  | { status: \"applying\"; startedAt: number }\n  | {\n      status: \"applied\";\n      applied: number;\n      failed: number;\n      message: string | null;\n      /** The LATEST apply's records — after \"Run again\", the newest copy. */\n      records: DirectiveRecordRef[];\n      /** How many times this block has applied (1 + every \"Run again\"). */\n      copies: number;\n      /** An update's replaced values, by item index — the record of the change. */\n      before: ReadonlyArray<Record<string, unknown> | null> | null;\n    }\n  | { status: \"error\"; message: string };\n\n/**\n * 🚨 AN APPLY BELONGS TO THE BLOCK, NOT TO THE COMPONENT (G6A review,\n * 2026-10-02). A note re-renders its blocks while a confirm dialog is open, so\n * the card that asked was unmounted and a fresh one mounted in its place. The\n * apply still ran — but its result was handed to the card that was gone, and\n * the new card, which had read the ledger BEFORE the write landed, offered\n * \"Apply\" for an update that had already run.\n *\n * So once a person says yes, the apply's progress and outcome are kept HERE,\n * per apply authority — the host's `confirm` function, which ran it (a host\n * object may be rebuilt on every render; its `confirm` is the stable seam) — keyed by the block's identity (slug + items + where it renders — the\n * same namespace the ledger keys in), and every card drawing that block shows\n * them, whenever it mounted. Component state keeps only what is the instance's own:\n * the ledger read and the open question.\n */\ntype ApplyOutcome = Extract<ApplyState, { status: \"applying\" | \"applied\" | \"error\" }>;\nconst applyOutcomes = new WeakMap<object, Map<string, ApplyOutcome>>();\n/** The key when a host has no `confirm`: nothing can apply, so nothing is ever held. */\nconst EMPTY_AUTHORITY = {};\nconst outcomeListeners = new Set<() => void>();\n\nfunction outcomesOf(host: object): Map<string, ApplyOutcome> {\n  let held = applyOutcomes.get(host);\n  if (!held) {\n    held = new Map();\n    applyOutcomes.set(host, held);\n  }\n  return held;\n}\n\nfunction publishOutcome(host: object, identity: string, outcome: ApplyOutcome): void {\n  outcomesOf(host).set(identity, outcome);\n  for (const listener of outcomeListeners) listener();\n}\n\nfunction subscribeOutcomes(listener: () => void): () => void {\n  outcomeListeners.add(listener);\n  return () => {\n    outcomeListeners.delete(listener);\n  };\n}\n\n/** The outcome this page holds for a block, or null. */\nfunction useApplyOutcome(host: object, identity: string): ApplyOutcome | null {\n  return useSyncExternalStore(\n    subscribeOutcomes,\n    () => applyOutcomes.get(host)?.get(identity) ?? null,\n    () => null,\n  );\n}\n\n/** How often a card re-reads a block another request is mid-applying. */\nconst FINISH_POLL_MS = 2_000;\n/** ~1 minute (the server's own claim wait is 45 s), then Apply is offered — idempotent. */\nconst FINISH_POLLS_MAX = 30;\n\n/**\n * What the Apply control knows about its block, for the rest of the card:\n *  - `pending` — the ledger has not answered yet;\n *  - `open`    — nothing applied: rows compare against the record as it is now;\n *  - `applied` — the change happened: rows draw it from `before` (the server's\n *                record of what it replaced), never from a live re-read, which\n *                now holds the NEW value.\n */\nexport type DirectiveApplyPhase =\n  | { phase: \"pending\" }\n  | { phase: \"open\" }\n  | { phase: \"applied\"; before: ReadonlyArray<Record<string, unknown> | null> | null };\n\n/** Does this card read the ledger before offering Apply? (One rule, card and control.) */\nexport function readsApplyLedger(\n  host: { applyState?: unknown; confirm?: unknown },\n  directive: DecodedDirective,\n): boolean {\n  return !!host.applyState && !!host.confirm && directive.parsed.executes && directive.items.length > 0;\n}\n\nexport interface ApplyDirectiveButtonProps {\n  directive: DecodedDirective;\n  label?: string;\n  /** How many things this will write — shown during the wait so a long apply reads as work, not a frozen spinner. */\n  itemCount?: number;\n  onApplied?: () => void;\n  /** Told whenever what the control knows about its block changes. */\n  onPhase?: (phase: DirectiveApplyPhase) => void;\n  /**\n   * The block would change nothing (an update that sets no field). Apply stays\n   * — validation offers, never blocks — but muted, with the reason beside it.\n   */\n  nothingToChange?: boolean;\n}\n\nexport function ApplyDirectiveButton({\n  directive,\n  label = \"Apply\",\n  itemCount,\n  onApplied,\n  onPhase,\n  nothingToChange = false,\n}: ApplyDirectiveButtonProps) {\n  const host = useDirectiveHost();\n  const scope = useDirectiveScope();\n  // WHERE the card sits is the namespace its apply keys in: a chat message's\n  // conversation (the SAME key the agent proposal's Approve uses — never two\n  // applies of one action), else the person's own content.\n  const conversationId = scope.conversationId || undefined;\n  const items = directive.items;\n  // The ledger read runs only where an apply could: a side effect, a confirm\n  // seam, something to write. Everything else starts (and stays) where it was.\n  const readsLedger = readsApplyLedger(host, directive);\n  const initial: ApplyState = readsLedger ? { status: \"checking\" } : { status: \"idle\" };\n  const [state, setState] = useState<ApplyState>(initial);\n  const [elapsed, setElapsed] = useState(0);\n  // \"Run again\" asks from the tally; the tally stays on screen while it asks\n  // (only its own button goes quiet), never swapped for a disabled Apply.\n  const [askingAgain, setAskingAgain] = useState(false);\n  const startedAt = useRef<number | null>(null);\n\n  // 🚨 THE STATE BELONGS TO THE BLOCK, NOT TO THE SLOT (reviewer, 2026-10-02).\n  // A host that keys its blocks by POSITION hands this same instance a\n  // DIFFERENT directive when a block is inserted above it. The state used to\n  // stay: an applied Update card flipped back to \"Apply\" (the instance that\n  // had been an idle card now held the Update, and the ledger's \"applied\"\n  // answer was ignored because the state was not \"checking\"), and the\n  // opposite — one card's tally drawn on another block — was one insert away.\n  // When the block this instance draws changes, everything it knew resets and\n  // the ledger is asked again about the block it now holds.\n  const identity = JSON.stringify([directive.slug, items, conversationId ?? null]);\n  const [stateFor, setStateFor] = useState(identity);\n  if (stateFor !== identity) {\n    setStateFor(identity);\n    setState(initial);\n    setAskingAgain(false);\n    setElapsed(0);\n  }\n  // What this page knows about the block's apply wins over this instance's own\n  // ledger read — except while this instance is asking its own question.\n  const shared = useApplyOutcome(host.confirm ?? EMPTY_AUTHORITY, identity);\n  const view: ApplyState = state.status === \"asking\" || !shared ? state : shared;\n  // An apply that finishes after its block left this slot must not land here.\n  const currentIdentity = useRef(identity);\n  useEffect(() => {\n    currentIdentity.current = identity;\n  }, [identity]);\n  const nounText = nounLabel(directive.noun, host.nouns);\n\n  // THE CARD SURVIVES A RELOAD. Component state dies with the page; the\n  // server's action ledger does not. Ask it once on mount — and every\n  // FINISH_POLL_MS while another request is mid-apply — and render exactly\n  // what a fresh apply would have left on screen.\n  const shellKey = readsLedger ? JSON.stringify([directive.slug, items, conversationId ?? null]) : \"\";\n  const read = host.applyState;\n  const report = host.reportError;\n  useEffect(() => {\n    if (!shellKey || !read) return;\n    // Parsed back from the key so the effect depends on the shell's CONTENT,\n    // never on the per-render identity of `directive.items`.\n    const [slug, shellItems, inConversation] = JSON.parse(shellKey) as [\n      string,\n      Record<string, unknown>[],\n      string | null,\n    ];\n    const shell: DirectiveShell = { __kind: slug, items: shellItems };\n    if (inConversation) shell.conversationId = inConversation;\n    let live = true;\n    let polls = 0;\n    let timer: ReturnType<typeof setTimeout> | null = null;\n    const ask = () => {\n      read(shell)\n        .then((answer) => {\n          if (!live) return;\n          if (answer.state === \"applied\") {\n            setState((prev) =>\n              prev.status === \"checking\" || prev.status === \"finishing\"\n                ? {\n                    status: \"applied\",\n                    applied: shellItems.length,\n                    failed: 0,\n                    message: answer.message?.trim() ? answer.message.trim() : null,\n                    records: answer.records ?? [],\n                    copies: Math.max(1, answer.copies ?? 1),\n                    before: answer.before ?? null,\n                  }\n                : prev,\n            );\n          } else if (answer.state === \"in_flight\" && polls < FINISH_POLLS_MAX) {\n            polls += 1;\n            setState((prev) => (prev.status === \"checking\" || prev.status === \"finishing\" ? { status: \"finishing\" } : prev));\n            timer = setTimeout(ask, FINISH_POLL_MS);\n          } else {\n            // Not applied — or still \"in flight\" after a minute, when Apply is\n            // the honest offer: confirm is idempotent and replays the receipt.\n            setState((prev) => (prev.status === \"checking\" || prev.status === \"finishing\" ? { status: \"idle\" } : prev));\n          }\n        })\n        .catch((error: unknown) => {\n          if (!live) return;\n          const why = error instanceof Error && error.message ? error.message : String(error);\n          (report ?? console.error)(\n            `[kind-directives] Could not read whether ${slug} was already applied: ${why}`,\n          );\n          setState((prev) => (prev.status === \"checking\" || prev.status === \"finishing\" ? { status: \"idle\" } : prev));\n        });\n    };\n    ask();\n    return () => {\n      live = false;\n      if (timer) clearTimeout(timer);\n    };\n  }, [shellKey, read, report]);\n\n  // The rest of the card draws its rows from what this control knows.\n  const appliedClean = view.status === \"applied\" && view.failed === 0 ? view : null;\n  const appliedBefore = appliedClean ? appliedClean.before : null;\n  const phaseKey =\n    view.status === \"checking\" || view.status === \"finishing\"\n      ? \"pending\"\n      : appliedClean\n        ? `applied:${JSON.stringify(appliedBefore)}`\n        : \"open\";\n  useEffect(() => {\n    if (!onPhase) return;\n    if (phaseKey === \"pending\") onPhase({ phase: \"pending\" });\n    else if (phaseKey === \"open\") onPhase({ phase: \"open\" });\n    else onPhase({ phase: \"applied\", before: appliedBefore });\n  }, [phaseKey, onPhase, appliedBefore]);\n\n  // An honest clock beats a fake progress bar — counted from when the apply\n  // started, so a card mounted mid-apply shows the true elapsed time.\n  const applyingSince = view.status === \"applying\" ? view.startedAt : null;\n  useEffect(() => {\n    if (applyingSince === null) return;\n    startedAt.current = applyingSince;\n    const id = setInterval(\n      () => setElapsed(Math.round((Date.now() - (startedAt.current ?? 0)) / 1000)),\n      1000,\n    );\n    return () => clearInterval(id);\n  }, [applyingSince]);\n\n  if (!directive.parsed.executes) return null;\n  const confirm = host.confirm;\n  if (!confirm) return null;\n\n  /**\n   * `again` = \"Run again\": the ledger already holds this block, so a plain\n   * confirm would only replay its receipt. The person is asked in words that\n   * say it runs a SECOND time, and a yes sends `force`.\n   */\n  async function handleApply(again = false) {\n    if (!confirm) return;\n    // A \"no\" to Run again leaves the tally exactly where it was.\n    const prior = view;\n    const askedFor = identity;\n    const stillHere = () => currentIdentity.current === askedFor;\n    const priorCopies = view.status === \"applied\" ? view.copies : 0;\n    // THE STATUS TELLS THE TRUTH (reviewer, 2026-09-30): the card used to read\n    // \"Applying 1 item…\" while the confirm dialog was still asking. Ask first,\n    // idle; only a yes moves the control to \"applying\".\n    if (host.ask) {\n      if (again) setAskingAgain(true);\n      else setState({ status: \"asking\" });\n      let ok = false;\n      try {\n        ok = await host.ask({\n          directive,\n          items,\n          nounLabel: nounText,\n          ...(again ? { again: true } : {}),\n        });\n      } catch (error) {\n        if (!stillHere()) return;\n        setAskingAgain(false);\n        setState({\n          status: \"error\",\n          message:\n            error instanceof Error && error.message\n              ? error.message\n              : \"We could not ask you to confirm this, so nothing was done.\",\n        });\n        return;\n      }\n      if (!stillHere()) return;\n      setAskingAgain(false);\n      if (!ok) {\n        // Declining is not an error: the card is exactly as it was.\n        setState(again ? prior : { status: \"idle\" });\n        return;\n      }\n    }\n    setElapsed(0);\n    // The question is answered: this instance stops asking.\n    setState((prev) => (prev.status === \"asking\" ? { status: \"idle\" } : prev));\n    // From the yes on, the apply is the BLOCK's: published by identity, so a\n    // card that re-mounts mid-apply (or after it) shows the true outcome.\n    publishOutcome(confirm, askedFor, { status: \"applying\", startedAt: Date.now() });\n    try {\n      const shell: DirectiveShell = { __kind: directive.slug, items };\n      if (conversationId) shell.conversationId = conversationId;\n      if (again) shell.force = true;\n      let result: Awaited<ReturnType<typeof confirm>>;\n      try {\n        result = await confirm(shell);\n      } finally {\n        // Every record this apply may have touched is re-read wherever it is\n        // shown — even a failed apply may have written some items.\n        announceChangedRecords(directive, items);\n      }\n      for (const record of result.records ?? []) noteRecordChanged(record.id);\n      publishOutcome(confirm, askedFor, {\n        status: \"applied\",\n        applied: result.applied,\n        failed: result.failed,\n        message: result.message?.trim() ? result.message.trim() : null,\n        records: result.records ?? [],\n        // \"Run again\" made one more; a first apply (or a replay of one) is one.\n        copies: again ? Math.max(1, priorCopies) + 1 : Math.max(1, priorCopies),\n        // \"Run again\" wrote the same values over themselves; what the FIRST\n        // apply replaced is still the change this block made.\n        before:\n          again && prior.status === \"applied\" && prior.before\n            ? prior.before\n            : (result.before ?? null),\n      });\n      if (stillHere()) onApplied?.();\n    } catch (error) {\n      publishOutcome(confirm, askedFor, {\n        status: \"error\",\n        message:\n          error instanceof Error && error.message\n            ? error.message\n            : \"That couldn't be applied just now. Please try again.\",\n      });\n    }\n  }\n\n  if (view.status === \"applied\") {\n    const bad = view.failed > 0;\n    const trashed = directive.directiveClass === \"delete\";\n    const label = nounText;\n    // THE TALLY IS A DOOR (no dead ends): the records the apply wrote, each by\n    // name and each opening, beside the server's own sentence when it sent one.\n    const records = host.renderRecord ? view.records : [];\n    return (\n      <span\n        className={`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs ${bad ? \"text-destructive\" : \"text-primary\"}`}\n        data-apply-state=\"applied\"\n      >\n        {/* The glyph rides WITH the sentence: a long server sentence wraps\n            beside it, never leaving the icon alone on a line (phone width). */}\n        <span className=\"inline-flex min-w-0 items-start gap-1\">\n          {bad ? (\n            <AlertIcon className=\"matrx-line-icon-sm\" />\n          ) : (\n            <CheckCircleIcon className=\"matrx-line-icon-sm\" />\n          )}\n          {bad ? (\n            <FailureNotice\n              words={failureWords(\n                {\n                  raw: view.message ?? `${view.failed} failed`,\n                  directiveClass: directive.directiveClass,\n                  noun: directive.noun,\n                  nounLabel: nounText,\n                  failed: view.failed,\n                  total: view.applied + view.failed,\n                },\n                host.explainFailure,\n              )}\n              raw={view.message}\n            />\n          ) : (\n            <span className=\"min-w-0\">{view.message ?? `Applied ${view.applied}`}</span>\n          )}\n        </span>\n        {view.copies > 1 ? (\n          <span\n            className=\"shrink-0 text-muted-foreground\"\n            data-apply-copies={view.copies}\n            title={\n              records.length > 0\n                ? directive.directiveClass === \"create\"\n                  ? \"Links to the latest copy.\"\n                  : \"Links to the latest run.\"\n                : undefined\n            }\n          >\n            {directive.directiveClass === \"create\" ? `${view.copies} copies` : `Ran ${view.copies} times`}\n          </span>\n        ) : null}\n        {records.map((record) => (\n          <span key={`${record.noun}:${record.id}`} className=\"inline-flex min-w-0 items-center\">\n            {host.renderRecord?.({\n              ...record,\n              fallback: recordFallbackName(label),\n              context: \"applied\",\n              trashed,\n            })}\n          </span>\n        ))}\n        {/* A failed item was never ledgered, so a plain re-apply retries only\n            it. A clean tally offers \"Run again\" — the one way past the\n            ledger's dedup, asked in words that say it runs a second time. */}\n        <button\n          type=\"button\"\n          disabled={askingAgain}\n          onClick={() => void handleApply(!bad)}\n          className=\"inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded px-1 py-0.5 text-muted-foreground hover:bg-accent hover:text-accent-foreground disabled:opacity-50\"\n          data-apply-action={bad ? \"retry\" : \"run-again\"}\n        >\n          <RotateCcwIcon className=\"h-3 w-3\" />\n          {bad ? \"Retry\" : \"Run again\"}\n        </button>\n      </span>\n    );\n  }\n\n  if (view.status === \"checking\") {\n    return (\n      <span\n        className=\"inline-flex h-6 w-6 items-center justify-center text-muted-foreground\"\n        role=\"status\"\n        aria-label=\"Checking whether this already ran\"\n        data-apply-state=\"checking\"\n      >\n        <LoaderIcon className=\"h-3.5 w-3.5 animate-spin\" />\n      </span>\n    );\n  }\n\n  if (view.status === \"finishing\") {\n    return (\n      <span\n        className=\"inline-flex items-center gap-1 text-xs text-muted-foreground\"\n        role=\"status\"\n        data-apply-state=\"finishing\"\n      >\n        <LoaderIcon className=\"h-3.5 w-3.5 animate-spin\" />\n        Finishing…\n      </span>\n    );\n  }\n\n  // THE CONFIRM OPENS WITH THE RECORD IN HAND (G10B review, 2026-10-02: the\n  // first update confirm of a session took ~2 s). An update/delete's confirm\n  // reads the records it names; pointing at (or focusing) Apply starts that\n  // read through the host's `readRecord`, so a host that keeps a recent read\n  // hands the confirm the record instead of a second round trip.\n  const warm = () => {\n    const read = host.readRecord;\n    if (!read || !TARGETING_CLASSES.has(directive.directiveClass)) return;\n    for (const item of items) {\n      const id = itemRecordId(item);\n      if (id) void read({ noun: directive.noun, id }).catch(() => null);\n    }\n  };\n\n  // A delete LOOKS like one before the click, not only inside the confirm\n  // (reviewer, 2026-10-02: the Delete card's Apply was the same neutral gray\n  // as a create's).\n  const destructive = directive.directiveClass === \"delete\";\n  // NOTHING TO CHANGE, SHOWN BEFORE THE CLICK (G6A review, 2026-10-02): an\n  // update that sets no field still offered a full-weight \"Update\". The control\n  // stays live — validation offers, never blocks — but reads muted, with why.\n  const muted = nothingToChange && view.status === \"idle\";\n  return (\n    <span className=\"flex min-w-0 flex-wrap items-center justify-end gap-x-2 gap-y-1\">\n      {/* A button never wraps its label: the REASON wraps, the button holds. */}\n      {muted ? (\n        <span className=\"min-w-0 text-xs text-muted-foreground\" data-apply-nothing=\"\">\n          Nothing to change\n        </span>\n      ) : null}\n      <button\n        type=\"button\"\n        onClick={() => void handleApply()}\n        onPointerEnter={warm}\n        onFocus={warm}\n        disabled={view.status === \"applying\" || view.status === \"asking\" || items.length === 0}\n        data-apply-tone={muted ? \"muted\" : destructive ? \"destructive\" : \"default\"}\n        title={muted ? \"Applying it changes nothing.\" : undefined}\n        className={`inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 py-1 text-xs font-medium disabled:opacity-50 ${\n          muted\n            ? \"border-border/60 bg-background text-muted-foreground hover:bg-accent\"\n            : destructive\n            ? \"border-destructive/50 bg-background text-destructive hover:bg-destructive/10\"\n            : \"border-border bg-background hover:bg-accent\"\n        }`}\n      >\n        {view.status === \"applying\" ? (\n          <LoaderIcon className=\"h-3.5 w-3.5 animate-spin\" />\n        ) : (\n          <PlayIcon className=\"h-3.5 w-3.5\" />\n        )}\n        {view.status === \"applying\"\n          ? `Applying${itemCount ? ` ${itemCount} ${itemCount === 1 ? \"item\" : \"items\"}` : \"\"}…${elapsed ? ` ${elapsed}s` : \"\"}`\n          : label}\n      </button>\n      {view.status === \"error\" ? (\n        <span\n          className=\"inline-flex max-w-sm items-start gap-1 text-xs text-destructive\"\n          data-apply-state=\"error\"\n        >\n          <AlertIcon className=\"matrx-line-icon-sm\" />\n          <FailureNotice\n            words={failureWords(\n              {\n                raw: view.message,\n                directiveClass: directive.directiveClass,\n                noun: directive.noun,\n                nounLabel: nounText,\n              },\n              host.explainFailure,\n            )}\n            raw={view.message}\n          />\n        </span>\n      ) : null}\n    </span>\n  );\n}\n\n/**\n * What failed and what to do, in plain words — and the technical text behind\n * \"Details\" for whoever debugs it. Never the raw text as the sentence.\n */\nfunction FailureNotice({\n  words,\n  raw,\n}: {\n  words: { what: string; next: string; details?: string };\n  raw: string | null;\n}) {\n  const [open, setOpen] = useState(false);\n  // The host's worded details replace the raw text only when there IS raw text.\n  const detail = raw?.trim() ? (words.details?.trim() || raw.trim()) : \"\";\n  return (\n    <span className=\"flex min-w-0 flex-col gap-0.5\" data-apply-failure>\n      <span className=\"min-w-0\">\n        {words.what} {words.next}\n        {detail ? (\n          <button\n            type=\"button\"\n            onClick={() => setOpen((v) => !v)}\n            aria-expanded={open}\n            className=\"ml-1 whitespace-nowrap underline underline-offset-2 hover:no-underline\"\n            data-apply-failure-details-toggle\n          >\n            {open ? \"Hide details\" : \"Details\"}\n          </button>\n        ) : null}\n      </span>\n      {open && detail ? (\n        <span\n          className=\"block max-w-sm select-text break-words font-mono text-[11px] text-muted-foreground\"\n          data-apply-failure-details\n        >\n          {detail}\n        </span>\n      ) : null}\n    </span>\n  );\n}\n\nexport default ApplyDirectiveButton;\n","/**\n * WHAT A DIRECTIVE ITEM WILL DO TO AN EXISTING RECORD — for the card, the\n * confirm dialog, and anything else that must say it before the click.\n *\n * WHY (reviewer, 2026-09-30): an Update card and a Delete card showed each item\n * as \"Item\" — they never named the record they would change, and an Update card\n * never said what it would change. The item-summary helpers name a thing to be\n * CREATED from its own fields; an update or delete item carries the TARGET's id\n * and, for an update, the NEW values — so its \"title\" field is the new title,\n * not the name of the record being changed. Naming the target is the host's\n * live lookup (`DirectiveHost.renderRecord`); what changes is right here.\n *\n * Law: common-docs/policies/no-dead-ends.md — the sentence\n * names what changes.\n */\n\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\nimport { catalogItemTitle } from \"../directives\";\n\n/** Classes whose items point at an EXISTING record by `id`. */\nexport const TARGETING_CLASSES: ReadonlySet<string> = new Set([\"update\", \"delete\"]);\n\n/** Never a change: identity and plumbing. */\nconst NOT_A_CHANGE = new Set<string>([\"__kind\", \"id\"]);\n\n/**\n * How long a changed value may read before it is shortened. A value someone\n * must judge — a title, a status, a date — is always whole (G8A review: a 60\n * cap plus CSS truncation cut \"Review4 tasks…\" on a phone); only a body of\n * prose longer than this is shortened, whole on hover and in View/Copy.\n */\nexport const CHANGE_VALUE_MAX = 280;\n\n/** The id of the existing record an update/delete item targets, or null. */\nexport function itemRecordId(item: Record<string, unknown>): string | null {\n  const id = item.id;\n  if (typeof id === \"string\" && id.trim()) return id.trim();\n  if (typeof id === \"number\") return String(id);\n  return null;\n}\n\n/** \"due_date\" → \"Due Date\" — THE humanizer; underscores read as developer output. */\nexport function fieldLabel(key: string): string {\n  return humanizeIdentifier(key) || key;\n}\n\n/**\n * THE ONE FIELD-LABEL RULE for a directive — card rows, card facts and the\n * host's confirm: the noun's title column reads \"Title\" whatever it is stored\n * as (a workbook's `workbook_name`, a note's `label`), every other field reads\n * through THE humanizer. A new workbook card said \"workbook name\" while its\n * confirm said \"Title\" (G8A review, 2026-10-02).\n */\nexport function directiveFieldLabel(key: string, titleColumn: string | null | undefined): string {\n  return titleColumn && key === titleColumn ? \"Title\" : fieldLabel(key);\n}\n\n/**\n * The app's word for ONE stored value of ONE field — \"incomplete\" on a task\n * reads \"Inbox\", \"high\" reads \"High\". The host answers it for its pick-list\n * fields; null → the value as stored.\n */\nexport type DirectiveValueWord = (field: string, value: string) => string | null;\n\n/**\n * The name a NEW item carries, or null when it has none — the one rule the card\n * and a host's confirm share. `catalogItemTitle`'s last resort (\"Item\", \"Item 2 of 3\")\n * is a placeholder, never a name: a create with an empty title used to ask\n * \"Create project Item?\" and its card row read \"Item\" (G10B review, 2026-10-02).\n */\nexport function itemOwnName(item: Record<string, unknown>, titleColumn: string | null): string | null {\n  // With two items the last resort is exactly \"Item 1 of 2\"; a real name wins first.\n  const probe = catalogItemTitle(item, titleColumn, 0, 2);\n  return probe === \"Item 1 of 2\" ? null : probe;\n}\n\n/** What a nameless new item is called — said as such, never a placeholder name. */\nexport const NO_TITLE_WORD = \"No title\";\n\n/** How an empty value reads — before or after, on the card and in the confirm. */\nexport const EMPTY_VALUE_WORD = \"None\";\n\n\n/**\n * What a record is called when its name cannot be read: its TYPE (\"Task\").\n * Never its id, in any slot — text, tooltip or screen-reader label. It used to\n * be \"Task a8a00001\", and a link to a record that no longer exists hovered\n * \"Open Task a8a00001\" (G10B review, 2026-10-02). The host says WHY the name is\n * missing (not found, no access) beside it.\n */\nexport function recordFallbackName(nounLabel: string): string {\n  return nounLabel.trim() || \"Record\";\n}\n\n/** One value as a row reads it: shortened, the whole of it, and whether it is empty. */\nexport interface ChangeValue {\n  value: string;\n  full: string;\n  clears: boolean;\n}\n\nexport interface ItemChange extends ChangeValue {\n  key: string;\n  /** \"Due date\". */\n  label: string;\n  /**\n   * What the field holds NOW, when the host could read the record — so an\n   * update reads \"old → new\", never just the new value (reviewer, 2026-10-02).\n   * Absent when the current record is unknown.\n   */\n  before?: ChangeValue;\n  /** True when the record already holds exactly this value — nothing changes. */\n  same?: boolean;\n}\n\n/** One value, described for a change row (`value` shortened, `full` whole). */\nexport function describeChangeValue(value: unknown, word?: (value: string) => string | null): ChangeValue {\n  return describeValue(value, word);\n}\n\nconst EMPTY: ChangeValue = { value: EMPTY_VALUE_WORD, full: EMPTY_VALUE_WORD, clears: true };\n\nfunction describeValue(value: unknown, word?: (value: string) => string | null): ChangeValue {\n  if (value === null || value === undefined) return EMPTY;\n  if (typeof value === \"string\") {\n    const trimmed = value.trim();\n    if (!trimmed) return EMPTY;\n    // ONE VALUE, ONE WORD (G8A review, 2026-10-02: \"Status incomplete →\n    // completed\"). A value of a pick-list field reads as the app's word for it\n    // — the host knows which fields are pick-lists and their words; anything\n    // else (free text, a slug) is shown exactly as written.\n    const named = word?.(trimmed) ?? null;\n    if (named) return { value: named, full: named, clears: false };\n    const oneLine = trimmed.replace(/\\s+/g, \" \");\n    const shown = oneLine.length > CHANGE_VALUE_MAX ? `${oneLine.slice(0, CHANGE_VALUE_MAX - 1)}…` : oneLine;\n    return { value: shown, full: trimmed, clears: false };\n  }\n  if (typeof value === \"number\" || typeof value === \"boolean\") {\n    return { value: String(value), full: String(value), clears: false };\n  }\n  if (Array.isArray(value)) {\n    const n = value.length;\n    const text = n === 0 ? EMPTY_VALUE_WORD : `${n} ${n === 1 ? \"entry\" : \"entries\"}`;\n    return { value: text, full: safeJson(value), clears: n === 0 };\n  }\n  const n = Object.keys(value as object).length;\n  const text = n === 0 ? EMPTY_VALUE_WORD : `${n} ${n === 1 ? \"field\" : \"fields\"}`;\n  return { value: text, full: safeJson(value), clears: n === 0 };\n}\n\nfunction safeJson(value: unknown): string {\n  try {\n    return JSON.stringify(value, null, 2);\n  } catch {\n    return String(value);\n  }\n}\n\nfunction sameValue(a: unknown, b: unknown): boolean {\n  if (a === b) return true;\n  if (a === null || a === undefined || b === null || b === undefined) {\n    // An empty string and a missing value both read \"None\".\n    const emptyA = a === null || a === undefined || a === \"\";\n    const emptyB = b === null || b === undefined || b === \"\";\n    return emptyA && emptyB;\n  }\n  if (typeof a === \"object\" || typeof b === \"object\") return safeJson(a) === safeJson(b);\n  return false;\n}\n\n/**\n * Every field an UPDATE item sets, in the order the item carries them — ALL of\n * them, never a sample: a person approving an overwrite sees the whole of it.\n *\n * Pass `current` — the record as it is now (`DirectiveHost.readRecord`) — and\n * each change also carries what it REPLACES (`before`) and whether it changes\n * anything at all (`same`). A field the record does not carry gets no `before`.\n */\nexport interface ItemChangesOptions {\n  /**\n   * The noun's title column (catalog `title_column` — `nounTitleColumn`). It is\n   * labeled \"Title\" whatever it is called: a note's title is stored in\n   * `label`, and the confirm said \"Label\" while the form said \"Title\"\n   * (reviewer, 2026-10-02). The same rule the directive builder's form uses.\n   */\n  titleColumn?: string | null;\n  /** The app's word for a stored value (`DirectiveHost.valueLabel`, bound to the noun). */\n  valueWord?: DirectiveValueWord | null;\n}\n\nexport function itemChanges(\n  item: Record<string, unknown>,\n  current?: Record<string, unknown> | null,\n  options: ItemChangesOptions = {},\n): ItemChange[] {\n  const out: ItemChange[] = [];\n  const titleColumn = options.titleColumn ?? null;\n  for (const [key, raw] of Object.entries(item)) {\n    if (NOT_A_CHANGE.has(key)) continue;\n    const label = directiveFieldLabel(key, titleColumn);\n    // The title is a name, never a token to translate.\n    const valueWord = options.valueWord;\n    const word =\n      key === titleColumn || !valueWord ? undefined : (v: string) => valueWord(key, v);\n    const change: ItemChange = { key, label, ...describeValue(raw, word) };\n    if (current && Object.prototype.hasOwnProperty.call(current, key)) {\n      change.before = describeValue(current[key], word);\n      change.same = sameValue(current[key], raw);\n    }\n    out.push(change);\n  }\n  return out;\n}\n\n/**\n * 🚨 AN UPDATE THAT WOULD CHANGE NOTHING SAYS SO (G11B review, 2026-10-07: the\n * confirm listed every field \"(no change)\", Apply stayed full-weight, and the\n * run ended \"Updated task. Ran 2 times\"). True when the item sets no field, or\n * when the record was read and EVERY field already holds its new value. A field\n * whose current value is unknown counts as a change — doubt never mutes Apply.\n * ONE rule for the card and the host's confirm.\n */\nexport function changesNothing(changes: ReadonlyArray<ItemChange>): boolean {\n  return changes.every((change) => change.same === true);\n}\n","\"use client\";\n\n/**\n * THE RECORD AS IT IS NOW — read through the host's `readRecord` seam, so an\n * update row (and the host's own confirm) can say what each field REPLACES.\n *\n * 🚨 RE-READ WHENEVER THE RECORD CHANGES (G7, 2026-10-02). It used to be read\n * ONCE per `noun:id`: after Update card A applied, Update card B naming the same\n * record — its row, and a confirm whose body stayed mounted between questions —\n * still said A's OLD value was the old value (\"G6A renamed target\" while the\n * database held \"G6A second rename\"). Every apply now announces the records it\n * touched (`noteRecordChanged`, also the host's door for its own writers) and\n * every read keyed on that record's revision runs again. A host reader that\n * shares in-flight reads keys them by `recordRevision(id)` too, so a read\n * started before the write is never handed to a reader asking after it.\n *\n * A pure hook over a reader FUNCTION rather than the directive-host context:\n * the confirm dialog renders in the host's global dialog layer, outside every\n * `DirectiveHostProvider`, and must read the same values the card does.\n */\n\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport type { DirectiveRecordRef } from \"./directive-host\";\n\nexport type RecordValuesStatus = \"idle\" | \"loading\" | \"ready\" | \"unavailable\";\n\nexport interface RecordValues {\n  /** The record's fields now, or null until (or unless) they are read. */\n  values: Record<string, unknown> | null;\n  status: RecordValuesStatus;\n}\n\nexport type RecordReader = (ref: DirectiveRecordRef) => Promise<Record<string, unknown> | null>;\n\n/**\n * One change counter per record id — bumped by every write this page makes.\n * ONE store per page, not per bundle: every entry of this package (`.`,\n * `./directives`, …) is built self-contained, so module state would be a\n * SEPARATE counter per entry — an apply announced through one entry was never\n * seen by a reader imported through another (found adopting 0.19.0). The store\n * lives in a `Symbol.for` slot on `globalThis`, shared by every copy.\n */\ninterface RevisionStore {\n  revisions: Map<string, number>;\n  listeners: Set<() => void>;\n}\nconst STORE_SLOT = Symbol.for(\"ai-matrx.content-ir.record-revisions\");\nfunction revisionStore(): RevisionStore {\n  const slots = globalThis as unknown as Record<symbol, RevisionStore | undefined>;\n  let store = slots[STORE_SLOT];\n  if (!store) {\n    store = { revisions: new Map(), listeners: new Set() };\n    slots[STORE_SLOT] = store;\n  }\n  return store;\n}\nconst { revisions, listeners } = revisionStore();\n\n/** How many times this page has changed record `id` (0 = never). */\nexport function recordRevision(id: string): number {\n  return revisions.get(id) ?? 0;\n}\n\n/**\n * Record `id` just changed (an apply wrote it, or any other writer on the page).\n * Every `useRecordValues` naming it reads it again.\n */\nexport function noteRecordChanged(id: string): void {\n  if (!id) return;\n  revisions.set(id, recordRevision(id) + 1);\n  for (const listener of listeners) listener();\n}\n\nfunction subscribeRevisions(listener: () => void): () => void {\n  listeners.add(listener);\n  return () => {\n    listeners.delete(listener);\n  };\n}\n\n/** The live revision of record `id`, re-rendering when it changes. */\nexport function useRecordRevision(id: string): number {\n  return useSyncExternalStore(\n    subscribeRevisions,\n    () => recordRevision(id),\n    () => 0,\n  );\n}\n\nexport function useRecordValues(\n  read: RecordReader | undefined,\n  ref: DirectiveRecordRef | null,\n): RecordValues {\n  const revision = useRecordRevision(ref?.id ?? \"\");\n  // The revision is part of the key: a change to the record is a fresh read,\n  // and nothing read before it is shown as \"now\" while the new read runs.\n  const key = ref && read ? `${ref.noun}:${ref.id}#${revision}` : \"\";\n  const [result, setResult] = useState<{ key: string } & RecordValues>({\n    key: \"\",\n    values: null,\n    status: \"idle\",\n  });\n\n  useEffect(() => {\n    if (!key || !read) return;\n    const split = key.indexOf(\":\");\n    const target: DirectiveRecordRef = {\n      noun: key.slice(0, split),\n      id: key.slice(split + 1, key.lastIndexOf(\"#\")),\n    };\n    let live = true;\n    setResult({ key, values: null, status: \"loading\" });\n    read(target)\n      .then((values) => {\n        if (!live) return;\n        setResult({ key, values, status: values ? \"ready\" : \"unavailable\" });\n      })\n      .catch(() => {\n        if (!live) return;\n        // Not knowing the old value is not an error the person must handle:\n        // the row says only what changes, exactly as it did before this seam.\n        setResult({ key, values: null, status: \"unavailable\" });\n      });\n    return () => {\n      live = false;\n    };\n  }, [key, read]);\n\n  if (!key) return { values: null, status: \"idle\" };\n  if (result.key !== key) return { values: null, status: \"loading\" };\n  return { values: result.values, status: result.status };\n}\n","/**\n * THE WORDS A FAILED APPLY SHOWS A PERSON.\n *\n * A card used to print the server's text as its sentence — e.g.\n * \"unknown / non-writable noun 'task'. Writable: [...]\" (G5 review,\n * 2026-10-02). A person needs WHAT failed and WHAT TO DO, in plain words; the\n * technical text is for whoever debugs it, behind a Details toggle. The host\n * may name a failure it recognizes (`DirectiveHost.explainFailure`); otherwise\n * these verb-aware defaults answer.\n */\nimport type { DirectiveFailure, DirectiveFailureWords } from \"./directive-host\";\n\nconst PAST: Record<string, string> = {\n  create: \"created\",\n  update: \"updated\",\n  delete: \"deleted\",\n};\n\n/** The card's own words for a failure the host did not name. */\nexport function defaultFailureWords(failure: DirectiveFailure): DirectiveFailureWords {\n  const verbed = PAST[failure.directiveClass] ?? \"applied\";\n  const noun = failure.nounLabel.trim().toLowerCase() || \"item\";\n  if (failure.failed && failure.total && failure.total > 1) {\n    return {\n      what: `${failure.failed} of ${failure.total} weren't ${verbed}.`,\n      next: \"Retry to try those again.\",\n    };\n  }\n  return {\n    what: `The ${noun} wasn't ${verbed}.`,\n    next: \"Try again in a moment.\",\n  };\n}\n\n/** The host's words when it names this failure, else the default. */\nexport function failureWords(\n  failure: DirectiveFailure,\n  explain?: (failure: DirectiveFailure) => DirectiveFailureWords | null,\n): DirectiveFailureWords {\n  return explain?.(failure) ?? defaultFailureWords(failure);\n}\n","/**\n * content-ir-core/react-directives/icons.tsx — this package's glyph names, as aliases of the ONE glyph home,\n * `@ai-matrx/design-system/icons`. No path data lives here (policy C19: no icon library, and one drawing per\n * glyph); the alias only fixes this package's historical size and stroke. Exports are unchanged.\n */\n\nimport {\n  AlertTriangleIcon as GAlertTriangleIcon,\n  BoxesIcon as GBoxesIcon,\n  ChevronDownIcon as GChevronDownIcon,\n  ChevronRightIcon as GChevronRightIcon,\n  CircleCheckIcon as GCircleCheckIcon,\n  FilePlusIcon as GFilePlusIcon,\n  Loader2Icon as GLoader2Icon,\n  MaximizeIcon as GMaximizeIcon,\n  PencilIcon as GPencilIcon,\n  PlayIcon as GPlayIcon,\n  RotateCcwIcon as GRotateCcwIcon,\n  Trash2Icon as GTrash2Icon,\n  WebhookIcon as GWebhookIcon,\n  type GlyphComponent,\n} from \"@ai-matrx/design-system/icons\";\n\nimport type { ReactElement, SVGProps } from \"react\";\n\ntype IconProps = SVGProps<SVGSVGElement>;\n\nconst sized = (Glyph: GlyphComponent): GlyphComponent => Glyph;\n\nconst FilePlusIcon = sized(GFilePlusIcon);\nconst PencilIcon = sized(GPencilIcon);\nconst TrashIcon = sized(GTrash2Icon);\nconst PlayIcon = sized(GPlayIcon);\nconst WebhookIcon = sized(GWebhookIcon);\nconst BoxesIcon = sized(GBoxesIcon);\nconst ChevronDownIcon = sized(GChevronDownIcon);\nconst ChevronRightIcon = sized(GChevronRightIcon);\nconst MaximizeIcon = sized(GMaximizeIcon);\nconst LoaderIcon = sized(GLoader2Icon);\nconst RotateCcwIcon = sized(GRotateCcwIcon);\nconst CheckCircleIcon = sized(GCircleCheckIcon);\nconst AlertIcon = sized(GAlertTriangleIcon);\n\nexport {\n  FilePlusIcon,\n  PencilIcon,\n  TrashIcon,\n  PlayIcon,\n  WebhookIcon,\n  BoxesIcon,\n  ChevronDownIcon,\n  ChevronRightIcon,\n  MaximizeIcon,\n  LoaderIcon,\n  RotateCcwIcon,\n  CheckCircleIcon,\n  AlertIcon,\n};\n\n/**\n * The icon for a side-effect directive card. THE CLASS LEADS: on a card whose\n * job is \"authorize this write\", the first thing to see is whether this\n * CREATES, CHANGES, or DELETES. A noun override exists only where the platform\n * has a settled visual identity for the thing — agents are a Webhook.\n */\nconst AGENT_NOUNS = new Set([\"create_agent\", \"create_agent_definition\", \"agent\"]);\n\nexport function classIcon(directiveClass: string, noun: string): (p: IconProps) => ReactElement {\n  if (directiveClass === \"action\" && AGENT_NOUNS.has(noun)) return WebhookIcon;\n  switch (directiveClass) {\n    case \"create\":\n      return FilePlusIcon;\n    case \"update\":\n      return PencilIcon;\n    case \"delete\":\n      return TrashIcon;\n    default:\n      return PlayIcon;\n  }\n}\n","\"use client\";\n\n/**\n * The neutral \"we could not render this, but we will NEVER hide it\" card —\n * THE PREFIX FLOOR of the Kind Directives route.\n *\n * THE RULE THIS ENFORCES: a registered directive renderer must never return\n * `null`. `DirectiveRender` renders a renderer's output verbatim, so a `null`\n * deletes the assistant's whole message block (2026-07-26: a 70KB content plan\n * vanished exactly that way). When a renderer cannot draw its rich view, it\n * renders THIS instead: named by class and noun, itemised by count, with Apply\n * when the class is a side effect and the host can apply.\n */\n\nimport { directiveDisplay, type DecodedDirective } from \"../directives\";\nimport { ApplyDirectiveButton } from \"./ApplyDirectiveButton\";\nimport { useDirectiveHost } from \"./directive-host\";\nimport { BoxesIcon } from \"./icons\";\n\nexport interface DirectiveFallbackCardProps {\n  directive: DecodedDirective;\n  /** Short, human explanation of why the rich renderer degraded. */\n  reason?: string;\n}\n\nexport function DirectiveFallbackCard({ directive, reason }: DirectiveFallbackCardProps) {\n  const host = useDirectiveHost();\n  const count = directive.items.length;\n  const display = directiveDisplay(directive.directiveClass, directive.noun, host.nouns);\n  return (\n    <div className=\"my-3 inline-flex flex-wrap items-center gap-2 rounded-md border border-border bg-muted px-2.5 py-1 text-sm\">\n      <BoxesIcon className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n      <span className=\"text-foreground\">{display.title}</span>\n      {display.family ? <span className=\"text-muted-foreground\">· {display.family}</span> : null}\n      <span className=\"text-muted-foreground\">\n        · {count} {count === 1 ? \"item\" : \"items\"}\n      </span>\n      {reason ? <span className=\"text-muted-foreground\">· {reason}</span> : null}\n      <ApplyDirectiveButton directive={directive} />\n    </div>\n  );\n}\n\nexport default DirectiveFallbackCard;\n","\"use client\";\n\n/**\n * The card for a directive whose JSON has NOT finished arriving — the\n * provisional tier of `DirectiveRender`.\n *\n * WHY IT EXISTS (found live 2026-09-25, the agent builder's\n * `directive_v1_action_create_agent_definition` in the agent run window): an\n * agent streams a directive as one JSON document, `__kind` first. Every splitter\n * already types the block as a directive from its first bytes\n * (`looksLikeDirectiveHead`), but the decoder can only honor a COMPLETE shell,\n * so for the whole stream `DirectiveRender` fell to its raw `<pre>` — the person\n * watched a wall of JSON grow and then snap into a card at the last byte.\n *\n * The head already says what this is (class + noun), so the card says it from\n * the first bytes, from the same catalog words the finished card uses:\n *\n *  - STREAMING — \"Create agent definition · writing…\". No Apply: nothing is\n *    applicable until the shell is whole.\n *  - NOT STREAMING, still undecodable — the document was cut off (a model hit\n *    its output limit, a stream died). Said plainly, never dressed as\n *    \"writing…\" forever, with what did arrive one click away.\n *\n * NEVER RETURNS NULL.\n */\n\nimport { directiveDisplay, parseDirectiveSlug } from \"../directives\";\nimport { useDirectiveHost } from \"./directive-host\";\nimport { BoxesIcon, classIcon } from \"./icons\";\n\n/** A head whose slug has fully arrived: `{\"__kind\":\"directive_v1_…\"` + closing quote. */\nconst COMPLETE_SLUG_RE = /^\\{\\s*\"__kind\"\\s*:\\s*\"([^\"]+)\"/;\n\n/** The directive slug of a partial document, once its closing quote has arrived. */\nexport function provisionalDirectiveSlug(content: string): string | null {\n  const match = content.trimStart().match(COMPLETE_SLUG_RE);\n  return match?.[1] ?? null;\n}\n\nexport interface DirectiveProvisionalCardProps {\n  /** The partial fence body as received so far. */\n  content: string;\n  /**\n   * Whether the document may still be arriving. `false` means the stream is\n   * over and the document never completed — the card says it was cut off.\n   */\n  streaming: boolean;\n  className?: string | undefined;\n}\n\nexport function DirectiveProvisionalCard({ content, streaming, className }: DirectiveProvisionalCardProps) {\n  const host = useDirectiveHost();\n  const slug = provisionalDirectiveSlug(content);\n  const known = slug ? parseDirectiveSlug(slug) : null;\n  const display = known ? directiveDisplay(known.directiveClass, known.noun, host.nouns) : null;\n  const Icon = known ? classIcon(known.directiveClass, known.noun) : BoxesIcon;\n  const title = display?.title ?? \"Structured action\";\n\n  return (\n    <div\n      className={`my-3 rounded-md border border-border bg-card px-2.5 py-1.5${className ? ` ${className}` : \"\"}`}\n      data-directive={slug ?? undefined}\n      data-directive-state={streaming ? \"streaming\" : \"incomplete\"}\n    >\n      <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n        <Icon className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n        <span className=\"text-sm font-medium text-foreground\">{title}</span>\n        {display?.family ? <span className=\"text-xs text-muted-foreground\">{display.family}</span> : null}\n        {streaming ? (\n          <span className=\"inline-flex items-center gap-1.5 text-xs text-muted-foreground\" role=\"status\">\n            <span className=\"h-1.5 w-1.5 animate-pulse rounded-full bg-primary\" aria-hidden />\n            Writing…\n          </span>\n        ) : (\n          <span className=\"text-xs text-destructive\" role=\"status\">\n            Cut off before it finished — nothing can be applied.\n          </span>\n        )}\n      </div>\n      {streaming ? null : (\n        <details className=\"mt-1 text-xs text-muted-foreground\">\n          <summary className=\"cursor-pointer select-none hover:text-foreground\">Show what arrived</summary>\n          <pre className=\"mt-1 max-h-64 overflow-auto whitespace-pre-wrap break-all rounded bg-muted px-2 py-1 text-[11px]\">\n            {content}\n          </pre>\n        </details>\n      )}\n    </div>\n  );\n}\n\nexport default DirectiveProvisionalCard;\n","/**\n * Kind Directives — the renderer registry, and THE PREFIX TIER.\n *\n * A directive IS a kind instance, so the renderer for one is resolved from its\n * SLUG, in the same shape the kind component resolver uses:\n *\n *   getDirectiveRenderer(directive)\n *     → an exact-slug renderer            (directive_v1_action_plan_tree)\n *     → else the CLASS prefix rule        (every directive_v1_reference_*)\n *     → else null                         (DirectiveRender's own tier: the\n *                                          side-effect card, then the floor)\n *\n * THE PREFIX RULE is Arman's routing-language ruling made real: registering\n * `reference` once gives EVERY enrolled noun a renderer for free; a custom\n * renderer for one slug overrides it; a brand-new server noun renders with\n * ZERO client edits. Hosts register their bespoke renderers (reference chips,\n * plan trees) here; the package supplies the side-effect card and the floor.\n */\n\nimport type { ComponentType } from \"react\";\nimport { type DecodedDirective, type DirectiveClass, buildDirectiveSlug } from \"../directives\";\n\nexport interface DirectiveRendererProps {\n  /** The decoded two-key shell — slug, class, noun, items, position law. */\n  directive: DecodedDirective;\n}\n\nexport type DirectiveRenderer = ComponentType<DirectiveRendererProps>;\n\n// REGISTRY ON A globalThis SLOT — never module-level Maps. With `splitting:\n// false` dual ESM/CJS output this module is duplicated into the root bundle and\n// the `./directives` bundle, and a host registering a renderer through one\n// graph must be visible to a card rendering through the other.\nconst REGISTRY_SLOT = Symbol.for(\"ai-matrx.content-ir.directive-renderers\");\ninterface Registry {\n  bySlug: Map<string, DirectiveRenderer>;\n  byClass: Map<DirectiveClass, DirectiveRenderer>;\n}\ntype RegistryHolder = typeof globalThis & { [REGISTRY_SLOT]?: Registry };\nconst registry: Registry = ((globalThis as RegistryHolder)[REGISTRY_SLOT] ??= {\n  bySlug: new Map(),\n  byClass: new Map(),\n});\n\n/**\n * Register a renderer for a whole CLASS (the prefix rule), or for one exact\n * `(class, noun)` pair, which wins. `noun` is passed as a noun, never a\n * hand-typed slug: the slug is BUILT by the grammar, so a registration whose\n * slug could not be parsed back is unconstructable rather than unreachable.\n */\nexport function registerDirectiveRenderer(\n  directiveClass: DirectiveClass,\n  renderer: DirectiveRenderer,\n  noun?: string,\n): void {\n  if (noun) registry.bySlug.set(buildDirectiveSlug(directiveClass, noun), renderer);\n  else registry.byClass.set(directiveClass, renderer);\n}\n\n/** The renderer for a slug: exact → class prefix rule → null. */\nexport function getDirectiveRenderer(\n  directive: Pick<DecodedDirective, \"slug\" | \"directiveClass\">,\n): DirectiveRenderer | null {\n  return (\n    registry.bySlug.get(directive.slug) ?? registry.byClass.get(directive.directiveClass) ?? null\n  );\n}\n\n/** Tests only. */\nexport function resetDirectiveRenderers(): void {\n  registry.bySlug.clear();\n  registry.byClass.clear();\n}\n","\"use client\";\n\n/**\n * The card for a SIDE-EFFECT directive in content — create / update / delete /\n * action. One card for every shape the server can register, so a person is\n * never asked to approve a write they cannot identify.\n *\n * WHY IT EXISTS (Arman, 2026-08-26): the floor it replaced gave \"a name and\n * then an apply button, which essentially tells the user to click apply and\n * conduct a potentially destructive action without any clue as to what this\n * thing is.\"\n *\n * THE DESIGN:\n *  - Say what it IS, from authority — the catalog's own words for the title,\n *    the noun's title column for each item, never a guess.\n *  - Facts, not prose — a few scalar chips; nesting goes to the panel.\n *  - Read before you approve — `View` opens the item through the host's seam,\n *    which wraps the item's OWN kind component (THE DIRECTIVE⇄KIND SEAM).\n *  - Copy is table stakes, at the batch and at the item (host chrome).\n *  - Apply stays exactly where it was — the host's confirm seam.\n *\n * NEVER RETURNS NULL — a shape with no items degrades to a stated line.\n */\n\nimport { useEffect, useState } from \"react\";\nimport { asKindInstance, directiveDisplay, itemFacts, itemSubtitle, nounLabel, nounTitleColumn, type DecodedDirective } from \"../directives\";\nimport {\n  ApplyDirectiveButton,\n  readsApplyLedger,\n  type DirectiveApplyPhase,\n} from \"./ApplyDirectiveButton\";\nimport {\n  TARGETING_CLASSES,\n  changesNothing,\n  directiveFieldLabel,\n  itemChanges,\n  itemOwnName,\n  itemRecordId,\n  NO_TITLE_WORD,\n  recordFallbackName,\n  type DirectiveValueWord,\n  type ItemChange,\n} from \"./item-changes\";\nimport { useRecordValues } from \"./record-values\";\nimport { useDirectiveHost, type DirectiveHost } from \"./directive-host\";\nimport { ChevronDownIcon, ChevronRightIcon, MaximizeIcon, classIcon } from \"./icons\";\n\nexport interface SideEffectDirectiveCardProps {\n  directive: DecodedDirective;\n}\n\n/** The host's value words for one record type, or null when it has none. */\nexport function directiveValueWord(\n  host: Pick<DirectiveHost, \"valueLabel\">,\n  noun: string,\n): DirectiveValueWord | null {\n  const valueLabel = host.valueLabel;\n  return valueLabel ? (field, value) => valueLabel({ noun, field, value }) : null;\n}\n\nfunction omitKey(item: Record<string, unknown>, key: string): Record<string, unknown> {\n  const { [key]: _omitted, ...rest } = item;\n  return rest;\n}\n\n/** How many items render as rows before the rest collapse behind a toggle. */\nconst ROWS_BEFORE_FOLD = 3;\n\nfunction ItemRow({\n  directive,\n  item,\n  index,\n  total,\n  phase,\n  onNothing,\n}: {\n  directive: DecodedDirective;\n  item: Record<string, unknown>;\n  index: number;\n  total: number;\n  phase: DirectiveApplyPhase;\n  onNothing?: ((index: number, nothing: boolean) => void) | undefined;\n}) {\n  const host = useDirectiveHost();\n  // An update/delete item points at a record that ALREADY EXISTS: name THAT\n  // record (its live name, through the host), never the item's own fields —\n  // an update's `title` is the NEW title — and never \"Item\".\n  const recordId = TARGETING_CLASSES.has(directive.directiveClass) ? itemRecordId(item) : null;\n  if (recordId) {\n    return (\n      <TargetRow\n        directive={directive}\n        item={item}\n        recordId={recordId}\n        index={index}\n        phase={phase}\n        onNothing={onNothing}\n      />\n    );\n  }\n  const titleColumn = nounTitleColumn(directive.noun, host.nouns);\n  // A nameless item SAYS it has no title — never \"Item\" posing as its name.\n  const ownName = itemOwnName(item, titleColumn);\n  const title = ownName ?? NO_TITLE_WORD;\n  const subtitle = itemSubtitle(item);\n  // The title column IS the title — never repeated as a fact — and every\n  // fact is labeled and worded exactly as the confirm and the forms do.\n  const valueWord = directiveValueWord(host, directive.noun);\n  const facts = itemFacts(titleColumn ? omitKey(item, titleColumn) : item).map((fact) => ({\n    ...fact,\n    label: directiveFieldLabel(fact.key, titleColumn),\n    value: valueWord?.(fact.key, fact.value) ?? fact.value,\n  }));\n  const kind = host.itemKind?.(directive.slug) ?? null;\n  const display = directiveDisplay(directive.directiveClass, directive.noun, host.nouns);\n  const openItem = host.openItem;\n\n  const body = (\n    <>\n      {/* THE IDENTITY WINS THE SPACE: the title keeps its intrinsic width and the facts give way; on a phone (no facts) it wraps to two lines, never cut to one (G11B). */}\n      <span\n        className={`min-w-0 line-clamp-2 font-medium [overflow-wrap:anywhere] sm:shrink-0 sm:truncate ${ownName ? \"text-foreground\" : \"italic text-muted-foreground\"}`}\n        data-item-name=\"\"\n        data-item-untitled={ownName ? undefined : \"\"}\n      >\n        {title}\n      </span>\n      <span className=\"hidden min-w-0 flex-1 items-baseline gap-2 overflow-hidden sm:flex\">\n        {facts.map((fact) => (\n          <span key={fact.key} className=\"truncate text-[11px] text-muted-foreground\" data-item-fact={fact.key}>\n            {fact.label} <span className=\"text-foreground/80\">{fact.value}</span>\n          </span>\n        ))}\n      </span>\n      {subtitle && facts.length === 0 ? (\n        <span className=\"hidden truncate text-[11px] text-muted-foreground sm:inline\">{subtitle}</span>\n      ) : null}\n      {openItem ? (\n        <MaximizeIcon className=\"ml-auto h-3 w-3 shrink-0 text-muted-foreground\" />\n      ) : null}\n    </>\n  );\n\n  return (\n    <div className=\"flex items-center gap-2 py-1 text-xs\">\n      {openItem ? (\n        <button\n          type=\"button\"\n          onClick={() =>\n            openItem({\n              // Stamped so the panel's kind pipeline types it from its own first key.\n              item: asKindInstance(item, kind) ?? item,\n              itemKind: kind,\n              title,\n              subtitle: `${display.title} · item ${index + 1} of ${total}`,\n              directive,\n              index,\n              total,\n            })\n          }\n          className=\"flex min-w-0 flex-1 items-center gap-2 rounded px-1 py-0.5 text-left hover:bg-accent hover:text-accent-foreground\"\n          title=\"Open to read it\"\n        >\n          {body}\n        </button>\n      ) : (\n        <span className=\"flex min-w-0 flex-1 items-center gap-2 px-1 py-0.5\">{body}</span>\n      )}\n      {host.renderCopy?.({\n        label: ownName ?? `this ${nounLabel(directive.noun, host.nouns)}`,\n        value: item,\n        kind,\n        size: \"xs\",\n      })}\n    </div>\n  );\n}\n\n/**\n * THE CHANGE LIST — every field an update sets, as \"Label  old → new\" when the\n * record's current value is known, \"Label → new\" when it is not. ONE component\n * for the card row and the host's confirm dialog, so the two can never read\n * differently (reviewer, 2026-10-02: the confirm showed only the new value).\n *\n * 🚨 A VALUE SOMEONE MUST JUDGE IS NEVER CUT (G8A review, 2026-10-02): on a\n * phone the card is ~230px and the row read \"Title Review… → Review4 tas…\".\n * Values wrap; below a 20rem container the label, the old value and the new\n * value stack, one per line. Measured on the list's own width (a container\n * query), so a narrow window panel on a desktop gets the same stacking.\n */\nexport function DirectiveChangeList({\n  changes,\n  className,\n}: {\n  changes: ItemChange[];\n  className?: string;\n}) {\n  if (changes.length === 0) {\n    return (\n      <p className={`text-[11px] text-muted-foreground${className ? ` ${className}` : \"\"}`}>\n        Sets no fields — nothing would change.\n      </p>\n    );\n  }\n  return (\n    <ul className={`@container space-y-1${className ? ` ${className}` : \"\"}`} data-directive-changes=\"\">\n      {changes.map((change) => {\n        const before = change.before && !change.same ? change.before : null;\n        return (\n          <li\n            key={change.key}\n            className=\"flex min-w-0 flex-col text-[11px] @xs:flex-row @xs:flex-wrap @xs:items-baseline @xs:gap-x-1.5\"\n            title={\n              before\n                ? `${change.label}: ${before.full} → ${change.full}`\n                : `${change.label} → ${change.full}`\n            }\n            data-change-key={change.key}\n          >\n            <span className=\"shrink-0 text-muted-foreground\">{change.label}</span>\n            {before ? (\n              <span\n                className=\"min-w-0 text-muted-foreground line-through [overflow-wrap:anywhere]\"\n                data-change-before=\"\"\n              >\n                {before.value}\n              </span>\n            ) : null}\n            <span className=\"flex min-w-0 items-baseline gap-1.5\">\n              <span aria-hidden className=\"shrink-0 text-muted-foreground\">\n                →\n              </span>\n              <span\n                className={`min-w-0 [overflow-wrap:anywhere] ${change.clears ? \"italic text-muted-foreground\" : \"text-foreground\"}`}\n                data-change-after=\"\"\n              >\n                {change.value}\n              </span>\n              {change.same ? <span className=\"shrink-0 text-muted-foreground\">(no change)</span> : null}\n            </span>\n          </li>\n        );\n      })}\n    </ul>\n  );\n}\n\n/**\n * ONE row for an item that changes an EXISTING record: the record by its live\n * name (a way to open it, through `renderRecord`), then — for an update —\n * every field it sets, \"Due date 2026-10-01 → 2026-10-15\" (the old value read\n * through `readRecord` when the host can).\n */\nfunction TargetRow({\n  directive,\n  item,\n  recordId,\n  index,\n  phase,\n  onNothing,\n}: {\n  directive: DecodedDirective;\n  item: Record<string, unknown>;\n  recordId: string;\n  index: number;\n  phase: DirectiveApplyPhase;\n  onNothing?: ((index: number, nothing: boolean) => void) | undefined;\n}) {\n  const host = useDirectiveHost();\n  const fallback = recordFallbackName(nounLabel(directive.noun, host.nouns));\n  const isUpdate = directive.directiveClass === \"update\";\n  // 🚨 THE OLD VALUE OF A CHANGE THAT HAPPENED COMES FROM THE RECORD OF THE\n  // CHANGE (G6A review, 2026-10-02). A live read after the apply answers the NEW\n  // value, so an applied card said \"Title → X (no change)\". Live values are read\n  // only while the block is still open; once applied, the server's `before` is\n  // the old value — and without it the row says only what each field was set to.\n  // Until the ledger answers, neither: no comparison is better than a wrong one.\n  const readsLive = isUpdate && phase.phase === \"open\";\n  const live = useRecordValues(\n    readsLive ? host.readRecord : undefined,\n    readsLive ? { noun: directive.noun, id: recordId } : null,\n  );\n  const compareTo =\n    phase.phase === \"applied\" ? (phase.before?.[index] ?? null) : readsLive ? live.values : null;\n  const changes = isUpdate\n    ? itemChanges(item, compareTo, {\n        titleColumn: nounTitleColumn(directive.noun, host.nouns),\n        valueWord: directiveValueWord(host, directive.noun),\n      })\n    : [];\n  // The card mutes Apply when every row would change nothing — known only once\n  // the record is read and the block is still open.\n  const nothing = readsLive && live.values !== null && changesNothing(changes);\n  useEffect(() => {\n    onNothing?.(index, nothing);\n  }, [onNothing, index, nothing]);\n  const name = host.renderRecord ? (\n    host.renderRecord({ noun: directive.noun, id: recordId, fallback, context: \"row\" })\n  ) : (\n    <span className=\"line-clamp-2 min-w-0 font-medium text-foreground [overflow-wrap:anywhere]\">{fallback}</span>\n  );\n\n  return (\n    <div className=\"py-1 text-xs\" data-directive-target={recordId}>\n      <div className=\"flex min-w-0 items-center gap-2\">\n        <span className=\"flex min-w-0 flex-1 items-center gap-1 px-1\">{name}</span>\n        {/* THE LABEL NEVER NAMES AN ID (G9): \"this task\" until the host reads the name. */}\n        {host.renderCopy?.({\n          label: `this ${nounLabel(directive.noun, host.nouns).toLowerCase()}`,\n          value: item,\n          size: \"xs\",\n          record: { noun: directive.noun, id: recordId },\n        })}\n      </div>\n      {isUpdate ? <DirectiveChangeList changes={changes} className=\"mt-0.5 px-1\" /> : null}\n    </div>\n  );\n}\n\nexport function SideEffectDirectiveCard({ directive }: SideEffectDirectiveCardProps) {\n  const host = useDirectiveHost();\n  const [expanded, setExpanded] = useState(false);\n  const items = directive.items;\n  const total = items.length;\n  const display = directiveDisplay(directive.directiveClass, directive.noun, host.nouns);\n  const Icon = classIcon(directive.directiveClass, directive.noun);\n\n  // What the Apply control knows about this block — the rows draw an applied\n  // change from its record, never from a live re-read.\n  const [phase, setPhase] = useState<DirectiveApplyPhase>(() =>\n    readsApplyLedger(host, directive) ? { phase: \"pending\" } : { phase: \"open\" },\n  );\n  // An update that changes nothing — it sets no field, or the record already\n  // holds every value (read by its row) — says so before the click (G11B).\n  const [nothingAt, setNothingAt] = useState<Readonly<Record<number, boolean>>>({});\n  const noteNothing = (index: number, nothing: boolean) =>\n    setNothingAt((prev) => (prev[index] === nothing ? prev : { ...prev, [index]: nothing }));\n  const nothingToChange =\n    directive.directiveClass === \"update\" &&\n    total > 0 &&\n    items.every((item, index) => itemChanges(item).length === 0 || nothingAt[index] === true);\n\n  const shown = expanded ? items : items.slice(0, ROWS_BEFORE_FOLD);\n  const hidden = total - shown.length;\n\n  return (\n    <div className=\"my-3 rounded-md border border-border bg-card px-2.5 py-1.5\" data-directive={directive.slug}>\n      <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n        <Icon className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground\" />\n        <span className=\"text-sm font-medium text-foreground\">{display.title}</span>\n        {display.family ? <span className=\"text-xs text-muted-foreground\">{display.family}</span> : null}\n        <span className=\"text-xs tabular-nums text-muted-foreground\">\n          {total} {total === 1 ? \"item\" : \"items\"}\n        </span>\n        {/* Copy and Apply share ONE row that never wraps: after a run the tally\n            wraps inside itself, so the copy icon never sits alone (G18). */}\n        <div className=\"ml-auto flex min-w-0 max-w-full items-start justify-end gap-1\" data-directive-actions=\"\">\n          {host.renderCopy?.({ label: display.title, value: directive.shell, size: \"icon\" })}\n          <ApplyDirectiveButton\n            directive={directive}\n            itemCount={total}\n            onPhase={setPhase}\n            nothingToChange={nothingToChange}\n          />\n        </div>\n      </div>\n\n      {total === 0 ? (\n        // Stated, never silent: an empty batch is a real (and suspicious) state.\n        <p className=\"mt-1 text-xs text-muted-foreground\">No items — nothing would be written.</p>\n      ) : (\n        <div className=\"mt-0.5 divide-y divide-border/60\">\n          {shown.map((item, i) => (\n            <ItemRow\n              key={i}\n              directive={directive}\n              item={item}\n              index={i}\n              total={total}\n              phase={phase}\n              onNothing={noteNothing}\n            />\n          ))}\n        </div>\n      )}\n\n      {hidden > 0 || expanded ? (\n        <button\n          type=\"button\"\n          onClick={() => setExpanded((v) => !v)}\n          className=\"mt-0.5 inline-flex items-center gap-1 whitespace-nowrap rounded px-1 py-0.5 text-[11px] text-muted-foreground hover:text-foreground\"\n        >\n          {expanded ? <ChevronDownIcon className=\"h-3 w-3\" /> : <ChevronRightIcon className=\"h-3 w-3\" />}\n          {expanded ? \"Show less\" : `Show ${hidden} more`}\n        </button>\n      ) : null}\n    </div>\n  );\n}\n\nexport default SideEffectDirectiveCard;\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","\"use client\";\n\n/**\n * The safety net + the \"still arriving\" affordance for a provisional kind\n * render (streaming partial kinds — see `route/partial-kind-route.ts` and\n * `common-docs/systems/architecture/content-ir/FEATURE.md`).\n *\n * TWO JOBS\n * --------\n * 1. **Never let a component throw mid-stream.** A provisional value may be\n *    missing required fields. The routed kind opted in to tolerating that\n *    (every kind does — there is no opt-out), but that is a claim, not a proof — so a throw is\n *    caught here, SCREAMS through the host's error reporter, drops the kind\n *    back to withhold for the session (`markKindPartialUnsafe`), and falls back\n *    to the kind's own loading skeleton. The user sees the pre-partial\n *    behavior, not a broken message.\n * 2. **Say it is still arriving.** The user must be able to tell a live fill-in\n *    from a finished render, and it must not read as an error. A quiet chip\n *    rides the block's top edge — absolutely positioned and\n *    `pointer-events-none`, so it costs the content no layout and cannot shift\n *    the page when it disappears. It sits ON the border rather than inside the\n *    block: a routed kind often renders its own chrome, and a chip inside the\n *    box lands on top of those controls.\n *\n * No wrapper chrome: no border, no background, no padding. The kind component\n * already carries its own (THE WRAPPER LAW).\n */\n\nimport React, { type ReactNode } from \"react\";\nimport type { ContentIrErrorReporter } from \"../host/error-report\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport { markKindPartialUnsafe } from \"../route/partial-kind-route\";\n\ninterface ProvisionalKindBoundaryOwnProps {\n  kind: string;\n  /** Rendered instead of the children when the provisional render throws. */\n  fallback: ReactNode;\n  children: ReactNode;\n  /**\n   * The value is FINAL (the block that streamed provisionally has settled). The host keeps this\n   * boundary in place so the drawn component is the same element from its first provisional\n   * frame through its final render (a streamed shape mounts once); a throw on a final value is not\n   * a provisional failure, so it passes up to the host's own error boundary untouched.\n   */\n  final?: boolean;\n}\n\ninterface ProvisionalKindBoundaryProps extends ProvisionalKindBoundaryOwnProps {\n  reportError: ContentIrErrorReporter;\n}\n\ninterface ProvisionalKindBoundaryState {\n  failed: boolean;\n  error?: unknown;\n}\n\n/**\n * The class half. React error boundaries must be classes and classes cannot\n * use hooks, so the reporter is threaded in by the exported wrapper below.\n */\nclass ProvisionalKindBoundaryInner extends React.Component<\n  ProvisionalKindBoundaryProps,\n  ProvisionalKindBoundaryState\n> {\n  override state: ProvisionalKindBoundaryState = { failed: false };\n\n  static getDerivedStateFromError(error: unknown): ProvisionalKindBoundaryState {\n    return { failed: true, error };\n  }\n\n  override componentDidCatch(error: Error, info: React.ErrorInfo): void {\n    const { kind, reportError, final } = this.props;\n    // A final value's throw is the host boundary's to report (it is re-thrown from render).\n    if (final) return;\n    // Loud recovery: the kind CLAIMED partial-readiness and its component threw\n    // on a provisional value. Stop handing it one — for every block, for the\n    // rest of the session — and report it as the defect it is.\n    markKindPartialUnsafe(kind);\n    reportError({\n      source: \"content-ir\",\n      message: `kind \"${kind}\": its component threw on a provisional value — provisional rendering disabled for this kind for the session (falling back to its loading skeleton). Make the component null-safe on every field — it is handed partial values as they stream.`,\n      name: error.name,\n      ...(error.stack === undefined ? {} : { stack: error.stack }),\n      relation: \"partial-kind\",\n      raw: { kind, componentStack: info.componentStack },\n    });\n  }\n\n  override render(): ReactNode {\n    if (this.state.failed) {\n      if (this.props.final) throw this.state.error;\n      return this.props.fallback;\n    }\n    return this.props.children;\n  }\n}\n\nexport function ProvisionalKindBoundary(props: ProvisionalKindBoundaryOwnProps) {\n  const host = useContentIrHost();\n  return (\n    <ProvisionalKindBoundaryInner {...props} reportError={host.reportError} />\n  );\n}\n\n/**\n * The \"still arriving\" frame. `aria-busy` carries the same fact to assistive\n * tech that the chip carries visually. The chip's own rendering is a host seam\n * (`renderShimmer`) so an app with a shimmer primitive uses it and one without\n * still says the true thing, plainly.\n */\nexport function ProvisionalKindFrame({\n  children,\n  arriving = true,\n}: {\n  children: ReactNode;\n  /**\n   * False once the value is final: the SAME frame element stays (so its child is never\n   * re-parented — a streamed shape mounts once), it just stops saying \"still arriving\".\n   */\n  arriving?: boolean;\n}) {\n  const host = useContentIrHost();\n  const label = \"Still arriving\";\n  return (\n    <div className=\"relative\" aria-busy={arriving ? \"true\" : undefined}>\n      {children}\n      {arriving ? (\n        <span className=\"pointer-events-none absolute -top-2 right-4 z-10 select-none rounded-full bg-background px-1.5 leading-4\">\n          {host.renderShimmer?.(label) ?? (\n            <span className=\"text-[10px] text-muted-foreground\">{label}</span>\n          )}\n        </span>\n      ) : null}\n    </div>\n  );\n}\n","/**\n * Runtime wrapper kinds — the reader, and THE elision gate.\n *\n * Cross-repo contract (system of record):\n * `common-docs/systems/architecture/content-ir/FEATURE.md`.\n *\n * A runtime wrapper is the CLOSED set of envelopes that carry instance\n * context with a data kind NESTED inside: `node_outcome` (one settled node\n * invocation) and `run_result` (one terminated run, nesting one\n * `node_outcome` per terminal node). `tool_result` is registered server-side\n * but nothing emits it yet, so nothing here reads it.\n *\n * ## THE ELISION RULE — do it ONCE, here\n *\n * The payload is NEVER sent twice. On the wire `output` is `null` and\n * `output_ref` names the FRAME field that already holds the value:\n *\n *  - `\"output\"`              → the frame's own `output` (`node_completed.output`,\n *                              the run row's `output`).\n *  - `\"output.<node_id>\"`    → that key of the frame's terminal output map.\n *\n * PRESENCE OF `output_ref` IS THE MARKER. A bare `output: null` with NO ref is\n * a legitimately empty payload — never an elision, never something to go\n * looking for. This is the same rule the `__ir` envelope follows with\n * `value_ref`, for the same reason: otherwise every payload is serialized\n * twice per streamed event, twice per durable row and twice per run read.\n *\n * Rehydration happens at the single INGEST GATE (each host's one ingest point —\n * Matrix's workflow-runs reducer, the Studio's inbound-envelope gate),\n * before anything reads the wrapper. No renderer, selector or component ever\n * sees an un-rehydrated wrapper, so none of them may re-implement this.\n *\n * ## Never load-bearing\n *\n * Assembly is a pure read. A malformed wrapper yields `null` and the frame's\n * own fields carry the surface exactly as they did before the wrapper\n * existed — additive on the wire, additive here.\n */\n\nimport { KIND_KEY } from \"../core/kind-schema.types\";\n\n/** The registered slugs — named once, never spelled by hand elsewhere. */\nexport const NODE_OUTCOME_KIND = \"node_outcome\";\nexport const RUN_RESULT_KIND = \"run_result\";\n\n/** One settled node invocation, with its data kind nested in `output`. */\nexport interface NodeOutcomeWrapper {\n  __kind: typeof NODE_OUTCOME_KIND;\n  run_id: string;\n  node_id: string;\n  workflow_id: string | null;\n  step: number | null;\n  attempt: number;\n  status: string;\n  started_at: string | null;\n  ended_at: string | null;\n  /** `0` is a REAL duration, not \"unknown\"; `null` is unknown. */\n  duration_ms: number | null;\n  /** null = the node declared no kind (a loud defect, never a pass). */\n  output_kind: string | null;\n  /** null = never checked / degraded — NEVER renderable as a pass. */\n  output_kind_ok: boolean | null;\n  output_kind_errors: string[] | null;\n  /** Rehydrated by {@link rehydrateNodeOutcome}; null = genuinely empty. */\n  output: unknown;\n}\n\n/** One terminated run. `outputs` is one wrapper per TERMINAL node. */\nexport interface RunResultWrapper {\n  __kind: typeof RUN_RESULT_KIND;\n  run_id: string;\n  workflow_id: string | null;\n  status: string;\n  started_at: string | null;\n  ended_at: string | null;\n  duration_ms: number | null;\n  output_kind: string | null;\n  output: unknown;\n  outputs: NodeOutcomeWrapper[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction str(source: Record<string, unknown>, key: string): string | null {\n  const value = source[key];\n  return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction num(source: Record<string, unknown>, key: string): number | null {\n  const value = source[key];\n  return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction bool(source: Record<string, unknown>, key: string): boolean | null {\n  const value = source[key];\n  return typeof value === \"boolean\" ? value : null;\n}\n\nfunction strings(\n  source: Record<string, unknown>,\n  key: string,\n): string[] | null {\n  const value = source[key];\n  if (!Array.isArray(value)) return null;\n  const out = value.filter((item): item is string => typeof item === \"string\");\n  return out.length > 0 ? out : null;\n}\n\n/**\n * Resolve a dotted `output_ref` against the frame that carries the payload.\n * Returns `undefined` when the path does not resolve — the caller keeps\n * `output: null` rather than inventing a value.\n */\nexport function readOutputRef(frame: unknown, ref: string): unknown {\n  let cursor: unknown = frame;\n  for (const segment of ref.split(\".\")) {\n    if (!isRecord(cursor)) return undefined;\n    if (!(segment in cursor)) return undefined;\n    cursor = cursor[segment];\n  }\n  return cursor;\n}\n\n/**\n * Read a `node_outcome` off a frame and rehydrate its elided payload.\n *\n * `frame` is the object the wrapper traveled ON — the `node_completed` event,\n * or the run read response for a `run_result`'s children. Returns null for\n * anything that is not a node_outcome (including a missing wrapper: the\n * producer fails OPEN, so an absent wrapper is a normal, non-fatal state).\n */\nexport function rehydrateNodeOutcome(\n  raw: unknown,\n  frame: unknown,\n): NodeOutcomeWrapper | null {\n  if (!isRecord(raw)) return null;\n  if (raw[KIND_KEY] !== NODE_OUTCOME_KIND) return null;\n  // THE ELISION RULE. Presence of the ref is the marker; a bare null is empty.\n  const ref = str(raw, \"output_ref\");\n  const resolved = ref === null ? undefined : readOutputRef(frame, ref);\n  return readNodeOutcomeValue(\n    resolved === undefined ? raw : { ...raw, output: resolved },\n  );\n}\n\n/**\n * Read an ALREADY-REHYDRATED node_outcome value into its typed form.\n *\n * Deliberately does NOT require `__kind`: the render bridge strips the root\n * discriminator before the component sees the value, and it does NOT touch\n * `output_ref` — by the time anything renders, the ingest gate has already\n * resolved the elision, and a second resolution attempt against a frame that\n * is no longer there is how a payload goes missing.\n */\nexport function readNodeOutcomeValue(\n  raw: unknown,\n): NodeOutcomeWrapper | null {\n  if (!isRecord(raw)) return null;\n  const runId = str(raw, \"run_id\");\n  const nodeId = str(raw, \"node_id\");\n  if (!runId || !nodeId) return null;\n  const output = raw.output ?? null;\n\n  return {\n    __kind: NODE_OUTCOME_KIND,\n    run_id: runId,\n    node_id: nodeId,\n    workflow_id: str(raw, \"workflow_id\"),\n    step: num(raw, \"step\"),\n    attempt: num(raw, \"attempt\") ?? 1,\n    status: str(raw, \"status\") ?? \"completed\",\n    started_at: str(raw, \"started_at\"),\n    ended_at: str(raw, \"ended_at\"),\n    duration_ms: num(raw, \"duration_ms\"),\n    output_kind: str(raw, \"output_kind\"),\n    output_kind_ok: bool(raw, \"output_kind_ok\"),\n    output_kind_errors: strings(raw, \"output_kind_errors\"),\n    output,\n  };\n}\n\n/**\n * Read a `run_result` off the run read response and rehydrate every elided\n * payload — its own, and each terminal node's. Both resolve against the SAME\n * frame (the run read response), which is what `\"output.<node_id>\"` addresses.\n */\nexport function rehydrateRunResult(\n  raw: unknown,\n  frame: unknown,\n): RunResultWrapper | null {\n  if (!isRecord(raw)) return null;\n  if (raw[KIND_KEY] !== RUN_RESULT_KIND) return null;\n  const ref = str(raw, \"output_ref\");\n  const resolved = ref === null ? undefined : readOutputRef(frame, ref);\n  const outputs = Array.isArray(raw.outputs)\n    ? raw.outputs\n        .map((child) => rehydrateNodeOutcome(child, frame))\n        .filter((child): child is NodeOutcomeWrapper => child !== null)\n    : [];\n  return readRunResultValue({\n    ...raw,\n    ...(resolved === undefined ? {} : { output: resolved }),\n    outputs,\n  });\n}\n\n/**\n * Read an ALREADY-REHYDRATED run_result value into its typed form. Same\n * contract as {@link readNodeOutcomeValue}: no `__kind` requirement, no\n * second elision pass.\n */\nexport function readRunResultValue(raw: unknown): RunResultWrapper | null {\n  if (!isRecord(raw)) return null;\n  const runId = str(raw, \"run_id\");\n  if (!runId) return null;\n  const output = raw.output ?? null;\n  const outputs = Array.isArray(raw.outputs)\n    ? raw.outputs\n        .map((child) => readNodeOutcomeValue(child))\n        .filter((child): child is NodeOutcomeWrapper => child !== null)\n    : [];\n\n  return {\n    __kind: RUN_RESULT_KIND,\n    run_id: runId,\n    workflow_id: str(raw, \"workflow_id\"),\n    status: str(raw, \"status\") ?? \"completed\",\n    started_at: str(raw, \"started_at\"),\n    ended_at: str(raw, \"ended_at\"),\n    duration_ms: num(raw, \"duration_ms\"),\n    output_kind: str(raw, \"output_kind\"),\n    output,\n    outputs,\n  };\n}\n\n/**\n * The kind verdict, as three states the UI must keep distinct.\n *\n * `unchecked` is NEVER a pass: the engine either did not check (no declared\n * kind) or checked and could not conclude. Collapsing it into \"ok\" is how a\n * confidently-rendered document gets shown for a shape nobody verified.\n */\nexport type KindVerdict = \"passed\" | \"failed\" | \"unchecked\";\n\nexport function kindVerdictOf(wrapper: {\n  output_kind: string | null;\n  output_kind_ok: boolean | null;\n}): KindVerdict {\n  if (wrapper.output_kind_ok === true) return \"passed\";\n  if (wrapper.output_kind_ok === false) return \"failed\";\n  return \"unchecked\";\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","\"use client\";\n\n/**\n * The OFFICIAL fallback renderer for a resolved `__kind` block that has no\n * registered component (Shape System ruling R6).\n *\n * Before this existed, a kind the platform fully understood — schema in\n * `content_ir.kind_definition`, envelope parsed, fields validated — but which\n * no component claimed would fall through the host's renderer switch and land\n * on a raw code block.\n *\n * R6's disposition, implemented here: render the shape READABLY, and say —\n * quietly, in human words — that no custom view is registered for it yet. Never\n * an error. Never hidden content. The user always sees their data.\n *\n * 🚨 **What \"readably\" means changed on 2026-08-18.** This block used to show a\n * JSON tree under a warning-tinted \"Unverified shape\" banner. That is a\n * developer artifact, and our reader is a non-technical Subject Matter Expert:\n * on one real Study Pack run, 19 of 23 steps rendered exactly like that. The\n * body is now the host's structured-value FLOOR — the seam that renders any\n * JSON value as a human document. The honesty did not go away; it moved into\n * that view's muted footer, beside the raw-data escape hatch — which is where\n * WE read it and where the SME does not have to.\n *\n * Naming a component is still not the same as having one: the note appears\n * whether R6 fired (`marker.by === \"generic\"`) or a `kind_component` row names\n * `generic_structured` as the kind's web output component (`marker.by === \"db\"`),\n * because both mean \"no custom view\".\n *\n * ## Bare by construction (THE WRAPPER LAW)\n *\n * Every host that routes a block here already draws chrome — a chat message\n * surface, a workflow readout step box, a preview card. This view contributes\n * flow spacing and nothing else; the host owns the frame.\n */\n\nimport { type ReactNode } from \"react\";\nimport { readEnvelope, readObjectKind, reconstructRegionValue } from \"../core\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport { readIrRouteMarker } from \"../route/kind-route\";\n\nexport interface GenericStructuredViewProps {\n  /** The raw region source — the zero-loss floor when no envelope survived. */\n  content: string;\n  /** Carries `__ir` (the parsed envelope) and `__ir_route` (the seam marker). */\n  metadata?: Record<string, unknown>;\n  /**\n   * What to show while the region is still streaming. Hosts with a shimmer or\n   * an icon set pass theirs; the default is the same sentence, plainly.\n   */\n  streamingIndicator?: ReactNode;\n  className?: string;\n}\n\n/**\n * Best-effort value recovery, in descending fidelity. The envelope is the\n * source of truth (it merges residues back, so unknown keys survive); a bare\n * `JSON.parse` is the floor; the raw text is the never-lose-content backstop.\n */\nfunction readStructuredValue(\n  content: string,\n  metadata: Record<string, unknown> | undefined,\n): { value: unknown; recovered: boolean } {\n  const envelope = readEnvelope(metadata);\n  if (envelope) {\n    return { value: reconstructRegionValue(envelope), recovered: true };\n  }\n\n  try {\n    return { value: JSON.parse(content) as unknown, recovered: true };\n  } catch {\n    return { value: null, recovered: false };\n  }\n}\n\nexport function GenericStructuredView({\n  content,\n  metadata,\n  streamingIndicator,\n  className,\n}: GenericStructuredViewProps) {\n  const host = useContentIrHost();\n  const envelope = readEnvelope(metadata);\n  const status = envelope?.root.status ?? \"complete\";\n  const { value, recovered } = readStructuredValue(content, metadata);\n  // The envelope is the authority; a block that arrived without one still names\n  // its own kind inside the payload.\n  const kind =\n    envelope?.root.kind ??\n    (typeof value === \"object\" && value !== null && !Array.isArray(value)\n      ? readObjectKind(value as Record<string, unknown>)\n      : null) ??\n    \"\";\n  const marker = readIrRouteMarker(metadata);\n  const note =\n    marker?.reason === \"inactive\"\n      ? \"a custom view is registered but held inactive\"\n      : marker?.reason === \"broken-instance\"\n        ? \"this instance did not match the shape's schema\"\n        : \"no custom view yet\";\n\n  return (\n    <div className={className ? `my-2 min-w-0 ${className}` : \"my-2 min-w-0\"}>\n      {status === \"streaming\"\n        ? (streamingIndicator ?? (\n            <div className=\"mb-2 text-xs text-muted-foreground\">\n              Still arriving…\n            </div>\n          ))\n        : null}\n\n      {recovered ? (\n        host.renderValue({ value, ...(kind ? { kind } : {}), note })\n      ) : (\n        // Zero-data-loss backstop: the region never parsed, so show the source\n        // verbatim rather than swallowing it.\n        <pre className=\"max-h-96 overflow-auto font-mono text-xs leading-relaxed text-muted-foreground\">\n          {content}\n        </pre>\n      )}\n    </div>\n  );\n}\n\nexport default GenericStructuredView;\n","\"use client\";\n\n/**\n * The runtime-wrapper CHROME — `node_outcome` and `run_result`.\n *\n * Contract: `common-docs/systems/architecture/content-ir/FEATURE.md`.\n * The readers live in `@ai-matrx/content-ir` (`wire/runtime-wrapper`); this is\n * the render half, and it is deliberately almost nothing.\n *\n * The packet, verbatim: \"the front end would know which workflow it came from,\n * which node it came from, and then inside of it, it would see that it's a\n * Brave search results, and inside of that, ten websites.\"\n *\n * 🚨 **DELEGATE, NEVER REIMPLEMENT.** These components are TRANSPARENT ROUTERS.\n * They hand `output` straight back to the kind registry\n * ({@link KindInstanceRender}), so the nested data kind's own component draws\n * it, recursing all the way down. Runtime provenance stays in the wrapper data\n * for diagnostics; it is not reader-facing UI. The moment one of these files\n * renders a payload itself, the layer model is dead.\n *\n * The nested payload is ALREADY rehydrated: the elision (`output_ref`) is\n * resolved ONCE at the host's ingest gate through the kernel's\n * `wire/runtime-wrapper` readers, before anything reads the wrapper. Nothing\n * here goes looking for a frame.\n *\n * Bare by construction: the host (a readout step box, a deliverable card, a\n * chat message) already draws chrome; these add no card of their own.\n */\n\nimport type { ReactNode } from \"react\";\nimport { readNodeOutcomeValue, readRunResultValue } from \"../wire\";\nimport { readObjectKind } from \"../core\";\nimport type { NodeOutcomeWrapper, RunResultWrapper } from \"../wire\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport { KindInstanceRender } from \"./KindInstanceRender\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The bridge builds `{ wrapper }`; anything else is not ours to render. */\nfunction readWrapperFrom<T>(\n  serverData: unknown,\n  read: (value: unknown) => T | null,\n): T | null {\n  if (!isRecord(serverData)) return null;\n  return read(serverData.wrapper);\n}\n\nexport interface DelegatedOutputProps {\n  output: unknown;\n  /** The wrapper's `output_kind` — the node's DECLARATION, the fallback. */\n  declaredKind: string | null;\n  /**\n   * What to draw for a value with no kind at all, and as the unroutable\n   * fallback. Hosts with a settled-output body (the same one their readout\n   * uses — never a second reader) pass it; otherwise the floor draws it.\n   *\n   * A RENDER FUNCTION, not a node: the fallback needs the payload, and the only\n   * component that has read it is this one. Handing back a static node would\n   * force every host to re-read the wrapper itself — a second reader, which is\n   * exactly what this family exists to prevent.\n   */\n  fallback?: (output: unknown) => ReactNode;\n  /** What to say when the step produced nothing. */\n  emptyLabel?: string;\n}\n\n/**\n * The delegation seam — the ONLY thing these components do with a payload.\n *\n * In-band `__kind` wins over the node's DECLARATION, the same law a run reducer\n * follows: the discriminator inside the value describes what we are actually\n * holding, so it is what routes. With no kind at all there is nothing to route\n * to, and the host's fallback (or the floor) shows what the step produced.\n */\nexport function DelegatedOutput({\n  output,\n  declaredKind,\n  fallback,\n  emptyLabel = \"This step ran, and handed its result to the next one.\",\n}: DelegatedOutputProps) {\n  const host = useContentIrHost();\n\n  if (output === null || output === undefined) {\n    return <p className=\"text-xs text-muted-foreground\">{emptyLabel}</p>;\n  }\n  if (!isRecord(output)) {\n    return <>{host.renderValue({ value: output })}</>;\n  }\n\n  const kind = readObjectKind(output) ?? declaredKind;\n  if (!kind) {\n    return <>{fallback?.(output) ?? host.renderValue({ value: output })}</>;\n  }\n\n  return (\n    <KindInstanceRender\n      kind={kind}\n      value={output}\n      showRoutingNote={false}\n      variant=\"bare\"\n      {...(fallback === undefined\n        ? {}\n        : { unroutableFallback: fallback(output) })}\n    />\n  );\n}\n\nexport interface NodeOutcomeViewProps {\n  serverData?: unknown;\n  /** Passed through to {@link DelegatedOutput}. */\n  fallback?: (output: unknown) => ReactNode;\n}\n\n/** THE renderer for the `node_outcome` runtime wrapper kind. */\nexport function NodeOutcomeView({ serverData, fallback }: NodeOutcomeViewProps) {\n  const wrapper = readWrapperFrom<NodeOutcomeWrapper>(\n    serverData,\n    readNodeOutcomeValue,\n  );\n  if (!wrapper) return null;\n\n  return (\n    <DelegatedOutput\n      output={wrapper.output}\n      declaredKind={wrapper.output_kind}\n      {...(fallback === undefined ? {} : { fallback })}\n    />\n  );\n}\n\nexport interface RunResultViewProps {\n  serverData?: unknown;\n  fallback?: (output: unknown) => ReactNode;\n}\n\n/**\n * THE renderer for the `run_result` runtime wrapper kind.\n *\n * One finished run: one `node_outcome` per TERMINAL node — each delegated to\n * {@link NodeOutcomeView}, which delegates the payload inside it to the data\n * kind's own component. Recursion all the way down; no payload is rendered\n * here, and no `final_text` is read here.\n *\n * The run's own `output` is rendered ONLY when the run declared no terminal\n * outcomes — otherwise it is the same content the outcomes already carry, and\n * showing both is the duplication the wrapper exists to prevent.\n */\nexport function RunResultView({ serverData, fallback }: RunResultViewProps) {\n  const wrapper = readWrapperFrom<RunResultWrapper>(\n    serverData,\n    readRunResultValue,\n  );\n  if (!wrapper) return null;\n\n  return (\n    <div className=\"space-y-2\">\n      {wrapper.outputs.length > 0 ? (\n        wrapper.outputs.map((outcome) => (\n          <NodeOutcomeView\n            key={`${outcome.node_id}:${outcome.attempt}`}\n            serverData={{ wrapper: outcome }}\n            {...(fallback === undefined ? {} : { fallback })}\n          />\n        ))\n      ) : (\n        <DelegatedOutput\n          output={wrapper.output}\n          declaredKind={wrapper.output_kind}\n          {...(fallback === undefined ? {} : { fallback })}\n        />\n      )}\n    </div>\n  );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBA,mBAAkD;AAClD,+BAAuC;AAmBvC,IAAM,gBAAgB,MAAM,MAAM;AAAC;AACnC,IAAM,OAAO,MAAM;AAUZ,SAAS,wBACd,MACA,SACQ;AACR,QAAM,WAA6B,iDAAuB;AAC1D,QAAM,WAAsC,WAAW;AAEvD,MAAI,QAAQ,CAAC,UAAU;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AAEA,QAAM,gBAAY;AAAA,IAChB,CAAC,kBAA8B;AAC7B,UAAI,CAAC,QAAQ,CAAC,SAAU,QAAO,cAAc;AAC7C,YAAM,aAAa,SAAS,MAAM,cAAc,MAAM,aAAa;AACnE,YAAM,kBAAkB,SAAS,WAAW;AAAA,QAC1C;AAAA,QACA;AAAA,MACF;AACA,aAAO,MAAM;AACX,mBAAW;AACX,wBAAgB;AAAA,MAClB;AAAA,IACF;AAAA,IACA,CAAC,UAAU,IAAI;AAAA,EACjB;AAEA,QAAM,kBAAc;AAAA,IAClB,MACE,QAAQ;AAAA;AAAA;AAAA,MAGJ,SAAS,MAAM,eAAe,IAAI,IAClC,SAAS,WAAW,eAAe,IAAI;AAAA,QACvC;AAAA,IACN,CAAC,UAAU,IAAI;AAAA,EACjB;AAEA,aAAO,mCAAqB,WAAW,aAAa,IAAI;AAC1D;;;ACjEA,IAAAA,gBAAoD;;;AC8C7C,IAAM,aAAa;AAGnB,IAAM,kBAAkB;AAmFxB,SAAS,eAAe,SAA6B;AAC1D,UACG,QAAQ,UAAU,QAAQ,OAAO,KAAK,QAAQ,KAAK,EAAE,WAAW,OAChE,QAAQ,oBAAoB,QAC3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host","import_react","import_text_case","nounLabel","n","text","import_react","GFilePlusIcon","GPencilIcon","GTrash2Icon","GPlayIcon","GWebhookIcon","GBoxesIcon","GChevronDownIcon","GChevronRightIcon","GMaximizeIcon","GLoader2Icon","GRotateCcwIcon","GCircleCheckIcon","GAlertTriangleIcon","label","read","import_directive_host","import_jsx_runtime","import_directive_host","import_jsx_runtime","import_react","import_directive_host","import_jsx_runtime","import_jsx_runtime","isRecord","import_jsx_runtime","import_react","import_ContentIrProvider","isRecord","isRecord","isRecord","import_jsx_runtime","React","import_react","import_ContentIrProvider","import_jsx_runtime","import_ContentIrProvider","import_jsx_runtime","isRecord"]}