@ai-matrx/content-ir-react 0.25.2 → 0.25.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../host/error-report.ts","../host/host-types.ts","../host/ContentIrProvider.tsx","../directives/directive-host.tsx","../resolver/component-resolver.ts","../route/kind-route.ts","../route/partial-kind-route.ts","../route/route-binding.ts","../react/use-kind-version.ts","../react/KindInstanceRender.tsx","../directives/DirectiveRender.tsx","../directives/DirectiveFallbackCard.tsx","../directives/ApplyDirectiveButton.tsx","../directives/item-changes.ts","../directives/record-values.ts","../directives/failure-words.ts","../directives/icons.tsx","../directives/DirectiveProvisionalCard.tsx","../directives/registry.ts","../directives/SideEffectDirectiveCard.tsx","../react/ProvisionalKindBoundary.tsx","../react/GenericStructuredView.tsx","../react/RuntimeWrapperViews.tsx","../db-component/db-kind-component-cache.ts","../db-component/DbKindComponentErrorBoundary.tsx"],"sourcesContent":["/**\n * THE SCREAM SEAM.\n *\n * Every recovery path in this package is loud: a defective component row, a\n * failed resolver load, a kind whose component throws on a provisional value.\n * The package refuses to own where those screams land — matrx-frontend routes\n * them to the Error Inspector, the dashboard to its own log, the extension to\n * its background page. Each host binds one function.\n *\n * A host that binds a no-op has chosen silence, which is a defect in itself;\n * {@link consoleErrorReporter} is the honest default.\n */\n\nexport interface ContentIrErrorReport {\n /** Always `\"content-ir\"` — hosts key their capture stores on it. */\n source: \"content-ir\";\n message: string;\n name?: string;\n stack?: string;\n /** Free-form grouping key (the host's `relation`), e.g. `\"partial-kind\"`. */\n relation?: string;\n raw?: unknown;\n}\n\nexport type ContentIrErrorReporter = (report: ContentIrErrorReport) => void;\n\n/** The default when a host binds nothing: never silent. */\nexport const consoleErrorReporter: ContentIrErrorReporter = (report) => {\n console.error(`[content-ir] ${report.message}`, report.raw ?? \"\");\n};\n","/**\n * THE HOST CONTRACT — everything this package refuses to decide.\n *\n * The kernel (`@ai-matrx/content-ir`) proved the shape: extract the portable\n * part, let host capability enter through explicit named seams. The render\n * layer needs four things it must never own:\n *\n * 1. WHERE KIND DEFINITIONS COME FROM (a bundled table, `content_ir`, a REST\n * call). The route only asks \"is this kind registered, and does it carry a\n * legacy bridge / a partial-ready opt-in\".\n * 2. WHERE COMPONENT ROWS COME FROM — {@link ComponentResolutionSource}. The\n * package ships `ComponentResolver`, which any host can construct with its\n * own loaders; a host with its own resolver only has to satisfy the type.\n * 3. HOW A ROUTED BLOCK ACTUALLY DRAWS. `applyIrKindRoute` decides a block's\n * TYPE; turning that type into pixels is the host's dispatch table\n * (matrx-frontend's `BlockRenderer`, the dashboard's small map). The\n * package never imports a component library.\n * 4. WHERE SCREAMS LAND — {@link ContentIrErrorReporter}.\n *\n * No Next.js, no Redux, no Supabase, no router, no host error capture. If a\n * seam is missing, ADD A SEAM — never an import.\n */\n\nimport type { ReactNode } from \"react\";\nimport type { KindDefinition } from \"@ai-matrx/content-ir\";\nimport type { ContentIrErrorReporter } from \"./error-report\";\nimport type { ComponentResolutionSource } from \"../resolver/component-resolution.types\";\nimport type { DirectiveHost } from \"../directives/directive-host\";\n\n/**\n * The minimum a render block must expose for the kind route to work. Hosts\n * pass their own richer block type through; the route is generic over `T` and\n * preserves every extra field.\n */\nexport interface IrRoutableBlock {\n type: string;\n serverData?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n/** A routable block that also carries its source text (the raw region). */\nexport interface IrRenderBlock extends IrRoutableBlock {\n content: string;\n language?: string;\n}\n\n/**\n * Where registered kinds come from. `getDefinition` is the only method the\n * pure route needs; the rest drive the granular repaint and the warm-up tick\n * that keeps a cold registry from being mistaken for \"this kind has no\n * component\".\n */\nexport interface KindDefinitionSource {\n getDefinition(kind: string): KindDefinition | undefined;\n /** Monotonic per-kind version — the repaint snapshot key. */\n getKindVersion(kind: string): number;\n subscribeKind(kind: string, listener: () => void): () => void;\n /** One definition load per app session. */\n ensureWarm(): Promise<void>;\n}\n\n/**\n * The rendering seams. Everything here returns host UI; the package supplies\n * the DECISIONS and the chrome-free structure around them.\n */\nexport interface ContentIrRenderSeams {\n /**\n * Draw a block the kind route has already typed. This is the host's dispatch\n * table — the single place a component key becomes a component.\n */\n renderBlock(block: IrRenderBlock): ReactNode;\n /**\n * THE FLOOR: render ANY JSON value as a human document. Reached when a kind\n * has no render-trusted component, when the value is not an object at all,\n * and by the generic structured view.\n *\n * This is deliberately a seam and not a bundled component. Rendering a value\n * WELL means prose through the host's markdown renderer, media through the\n * host's file handler, and uniform arrays through the host's data table —\n * all of which are host property. A host that has none of those can pass a\n * `<pre>`; it will be honest, just plain.\n */\n renderValue(props: StructuredValueRenderProps): ReactNode;\n /**\n * The \"still arriving\" indicator used by the provisional frame. Optional —\n * hosts without a shimmer get plain text.\n */\n renderShimmer?(text: string): ReactNode;\n /**\n * The honest \"this shape has no custom component yet\" notice. Optional: the\n * package draws a plain amber line when a host supplies nothing, and a host\n * with an icon set or its own callout component supplies that instead. It is\n * a seam and not a bundled component because this package depends on no icon\n * library.\n */\n renderNotice?(text: string): ReactNode;\n}\n\nexport interface StructuredValueRenderProps {\n value: unknown;\n /** The kind slug this value claims, when known. Honesty line only — never a renderer choice. */\n kind?: string;\n /** Why this shape has no custom view, in human words. */\n note?: string;\n /** Show the \"what this is / raw data\" footer. Default true. */\n footer?: boolean;\n}\n\n/**\n * One host, wired once, read by every component in this package through\n * {@link ContentIrRenderProvider}.\n */\nexport interface ContentIrHost extends ContentIrRenderSeams {\n kinds: KindDefinitionSource;\n components: ComponentResolutionSource;\n reportError: ContentIrErrorReporter;\n /**\n * The `kind_component.platform` this host resolves as. \"web\" for every\n * browser UI; the column already models \"react-native\" and friends, and a\n * host that lies here renders the wrong component everywhere.\n */\n platform: string;\n /**\n * The Kind Directives seams (apply / open item / copy / noun catalog / item\n * kind). Optional: a host without them still renders every directive card,\n * apply-less and copy-less — honest chrome, never hidden content. Provided\n * to the directive tier by `ContentIrRenderProvider`; a host that has not\n * adopted the render provider mounts `DirectiveHostProvider` directly.\n */\n directives?: DirectiveHost;\n}\n\n/**\n * The pure route's dependencies — a strict subset of {@link ContentIrHost},\n * because `applyIrKindRoute` is called OUTSIDE React (reducers, stream\n * accumulators, tests) where there is no provider to read.\n */\nexport interface KindRouteEnv {\n kinds: Pick<KindDefinitionSource, \"getDefinition\">;\n /**\n * `hasSettled` is optional and read ONLY to suppress a negative verdict from\n * a registry that has not loaded yet — see THE COLD-VERDICT RULE on\n * `ComponentResolutionSource`.\n */\n components: Pick<ComponentResolutionSource, \"resolve\"> &\n Partial<Pick<ComponentResolutionSource, \"hasSettled\">>;\n reportError: ContentIrErrorReporter;\n platform: string;\n}\n\n/** Narrow a host (or anything host-shaped) to what the pure route needs. */\nexport function routeEnvOf(host: ContentIrHost): KindRouteEnv {\n return {\n kinds: host.kinds,\n components: host.components,\n reportError: host.reportError,\n platform: host.platform,\n };\n}\n","\"use client\";\n\n/**\n * The one place a host is wired in. Everything React in this package reads its\n * capability from here — no module singleton, no import into an app.\n *\n * A host mounts this ONCE, high enough that every kind-rendering surface is\n * inside it:\n *\n * ```tsx\n * <ContentIrRenderProvider host={matrxContentIrHost}>\n * <App />\n * </ContentIrRenderProvider>\n * ```\n *\n * Reading it outside a provider THROWS rather than falling back to a default.\n * A silent default would render the wrong component for every kind in the app\n * and look like a data problem for weeks.\n */\n\nimport { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type { ContentIrHost, KindRouteEnv } from \"./host-types\";\nimport { routeEnvOf } from \"./host-types\";\nimport { DirectiveHostProvider } from \"../directives/directive-host\";\n\nconst ContentIrHostContext = createContext<ContentIrHost | null>(null);\n\nexport interface ContentIrRenderProviderProps {\n host: ContentIrHost;\n children: ReactNode;\n}\n\nexport function ContentIrRenderProvider({\n host,\n children,\n}: ContentIrRenderProviderProps) {\n return (\n <ContentIrHostContext.Provider value={host}>\n <DirectiveHostProvider host={host.directives ?? {}}>{children}</DirectiveHostProvider>\n </ContentIrHostContext.Provider>\n );\n}\n\n/**\n * The wired host, or null. For the rare consumer that can legitimately run\n * without a provider because it was handed its sources explicitly (see\n * `useContentIrKindVersion`). Everything else uses {@link useContentIrHost}.\n */\nexport function useContentIrHostOrNull(): ContentIrHost | null {\n return useContext(ContentIrHostContext);\n}\n\n/** The wired host. Throws outside a provider — see the module doc. */\nexport function useContentIrHost(): ContentIrHost {\n const host = useContentIrHostOrNull();\n if (!host) {\n throw new Error(\n \"[content-ir-react] No ContentIrRenderProvider above this component. \" +\n \"Mount one at the app root with your host adapter (kind definitions, \" +\n \"component resolver, renderBlock, renderValue, reportError).\",\n );\n }\n return host;\n}\n\n/** The wired host narrowed to what the pure route functions take. */\nexport function useKindRouteEnv(): KindRouteEnv {\n const host = useContentIrHost();\n return useMemo(() => routeEnvOf(host), [host]);\n}\n","\"use client\";\n\n/**\n * THE DIRECTIVE HOST CONTRACT — what the directive tier refuses to decide.\n *\n * The package owns the DECISIONS (decode → renderer → card → floor, the\n * position law, never-null rendering) and the card itself. Four things stay\n * host property and enter through named seams:\n *\n * 1. APPLYING a side-effect directive — `POST /directives/confirm` as the\n * user, with the host's auth and base URL. Absent → the Apply control is\n * ABSENT (honest), never a dead button.\n * 2. OPENING an item to read it before approving — a window panel, a dialog,\n * a route. Absent → items are not clickable.\n * 3. COPY controls — host chrome (matrx-frontend's CopyButtons). Absent → none.\n * 4. The NOUN catalog + item-kind lookup — server-derived tables the host\n * mirrors (or reads from its kind catalog's `items` edges).\n * 5. ASKING (`ask`), NAMING a record (`renderRecord`), and READING the ledger\n * (`applyState`) — the consequence before the click, the doors, and the\n * state that survives a reload.\n *\n * A host that has adopted `ContentIrRenderProvider` passes `directives` on its\n * ContentIrHost; a host that has NOT (Workflow Studio, 2026-09-08) mounts\n * `DirectiveHostProvider` alone — the directive tier never requires the full\n * render host, because a chat bubble must be able to draw a directive card\n * identically everywhere, today.\n */\n\nimport { createContext, useContext, type ReactNode } from \"react\";\nimport type {\n DecodedDirective,\n DirectiveItemKindLookup,\n DirectiveNounCatalog,\n} from \"@ai-matrx/content-ir\";\n\nexport interface DirectiveApplyResult {\n applied: number;\n failed: number;\n /**\n * The server's own receipt sentence (\"Deleted task “Ship it”.\"), shown in\n * place of a bare count. Never composed client-side.\n */\n message?: string | null;\n /**\n * The records the apply created or changed, so the tally is a way IN to them\n * (no dead ends). Rendered through `renderRecord`; absent → the sentence alone.\n */\n records?: DirectiveRecordRef[];\n /**\n * For an UPDATE: what each item's fields held just BEFORE the write, by item\n * index (`null` for an item the server did not record). The card draws the\n * applied change from this record — never from a live re-read, which after the\n * apply answers the NEW value (G6A review, 2026-10-02: \"(no change)\" for a\n * change that happened).\n */\n before?: ReadonlyArray<Record<string, unknown> | null>;\n}\n\n/**\n * What the server's action ledger says about ONE block, read on mount so a\n * reloaded page never offers \"Apply\" for work that already ran (reviewer\n * defect 5, 2026-10-02).\n *\n * - `not_applied` — still to do (or partly done: the batch re-applies, and the\n * server replays the members it already holds). The card offers Apply.\n * - `in_flight` — another request is applying it right now. The card says it\n * is finishing and asks again shortly; it offers neither Apply nor a tally.\n * - `applied` — the ledger holds every item. The card shows the tally exactly\n * as a fresh apply would: the ledger's own sentence and the records, as doors.\n */\nexport interface DirectiveApplyState {\n state: \"not_applied\" | \"in_flight\" | \"applied\";\n /** The ledger row's sentence (\"Created task.\"), never composed client-side. */\n message?: string | null;\n /**\n * The records the LATEST apply wrote — the tally's doors. After \"Run again\"\n * that is the newest copy, never the first.\n */\n records?: DirectiveRecordRef[];\n /**\n * How many times the ledger holds this block as applied: 1 for the original,\n * one more for every \"Run again\". Absent → 1. A create that ran twice made\n * two records, and the card says so (reviewer, 2026-10-02).\n */\n copies?: number;\n /**\n * For an applied UPDATE: each item's replaced values, by item index, from the\n * ledger row (`null` where the ledger has none — a row from before 2026-10-02).\n * Absent → the card says only what each field was set to.\n */\n before?: ReadonlyArray<Record<string, unknown> | null>;\n}\n\n/** One record a directive names: the noun it is, and its id. */\nexport interface DirectiveRecordRef {\n noun: string;\n id: string;\n}\n\nexport interface DirectiveRecordProps extends DirectiveRecordRef {\n /**\n * What to show until (or unless) the host resolves the live name —\n * \"Task 1a2b3c4d\". Never blank, never \"Item\".\n */\n fallback: string;\n /** Where it is drawn: an item row, the confirm dialog, or the applied tally. */\n context: \"row\" | \"dialog\" | \"applied\";\n /**\n * True when the record is (about to be) in the trash — the host may still\n * name it but should not promise it opens as a live record.\n */\n trashed?: boolean;\n}\n\n/** What the person is being asked to approve — everything the card knows. */\nexport interface DirectiveAskRequest {\n directive: DecodedDirective;\n /** The items, exactly as they will be sent. */\n items: Record<string, unknown>[];\n /** The noun's human label (\"Task\"), from the host's catalog when it has one. */\n nounLabel: string;\n /**\n * True for \"Run again\": the ledger already holds this block, and a yes runs\n * it a SECOND time (`force`) — another copy for a create, the same fields\n * written again for an update, another delete for a restored record. The\n * question must say so.\n */\n again?: boolean;\n}\n\n/**\n * The shell a card hands its host — the two keys, plus WHERE it sits.\n *\n * `conversationId` is the conversation the card renders in (a chat message),\n * absent in a person's own content (a note). It is the idempotency NAMESPACE:\n * a card in an agent's message must apply under the SAME key as that\n * proposal's Approve button, or the one action could run twice.\n */\nexport interface DirectiveShell {\n __kind: string;\n items: Record<string, unknown>[];\n conversationId?: string;\n /** \"Run again\": skip the ledger's dedup and apply a second time. */\n force?: boolean;\n}\n\nexport interface DirectiveOpenItemOptions {\n /** The item, `__kind`-stamped when the shape has an item kind. */\n item: Record<string, unknown>;\n /** The content-IR kind this item IS, or null when the shape has none. */\n itemKind: string | null;\n /** What the item is called — the same title the card shows. */\n title: string;\n /** \"Run Create agent definition · item 1 of 1\". */\n subtitle: string | null;\n directive: DecodedDirective;\n index: number;\n total: number;\n}\n\nexport interface DirectiveCopyProps {\n /**\n * What the control is called to a screen reader. Never an id: for a record it\n * is type-generic (\"this task\"); a host with the record's live name replaces\n * it through `record`.\n */\n label: string;\n /** The existing record this control copies, when it copies one — to name it. */\n record?: DirectiveRecordRef;\n /** The value to copy — the whole shell or one item. */\n value: unknown;\n /** The item's kind, when copying an item. */\n kind?: string | null;\n size: \"icon\" | \"xs\";\n}\n\nexport interface DirectiveHost {\n /**\n * Apply a side-effect directive as the user (the server re-validates every\n * item against the registered model and runs the ONE handler; idempotent).\n * Reject with an Error whose message is safe to show.\n */\n confirm?: (shell: DirectiveShell) => Promise<DirectiveApplyResult>;\n /**\n * Ask the person BEFORE anything runs, naming the consequence (the records,\n * what changes). Resolve `true` to go ahead, `false` to leave the card as it\n * was. The Apply control stays idle while this is open — nothing reads as\n * \"applying\" until the person has said yes. Absent → `confirm` is called\n * directly (a host that asks inside `confirm` keeps working, but its card\n * will read \"Applying…\" while its dialog is up).\n */\n ask?: (request: DirectiveAskRequest) => Promise<boolean>;\n /**\n * Has this exact block already been applied? Read ONCE when the card mounts\n * (and again while the answer is `in_flight`), so the card survives a reload:\n * the server ledger, not component state, is what knows. The identity is the\n * server's (it hashes the validated items in the same namespace `confirm`\n * applies in), so a host asks — it never computes. Batch on the host side if\n * a page carries many cards. Reject with an Error when the ledger cannot be\n * read: the card reports it and offers Apply, which is safe because `confirm`\n * is idempotent. Absent → the card starts at Apply, as before.\n */\n applyState?: (shell: DirectiveShell) => Promise<DirectiveApplyState>;\n /**\n * Read the CURRENT values of ONE existing record, so an update says what it\n * replaces — \"Status open → done\", never just \"→ done\" (reviewer,\n * 2026-10-02). Resolve `null` when the record cannot be read (no access, no\n * such record, a noun the host cannot read); reject only for a real failure.\n * Absent → an update row shows the new values alone, as before.\n */\n readRecord?: (ref: DirectiveRecordRef) => Promise<Record<string, unknown> | null>;\n /**\n * Draw ONE existing record by its live name, as a way to open it. Used on\n * update/delete rows (the record that will change), in the host's own ask\n * dialog if it likes, and on the applied tally (what was written). Absent →\n * the fallback text, unlinked.\n */\n renderRecord?: (props: DirectiveRecordProps) => ReactNode;\n /** Open ONE item to read it properly before approving the write. */\n openItem?: (options: DirectiveOpenItemOptions) => void;\n /** Host copy controls. */\n renderCopy?: (props: DirectiveCopyProps) => ReactNode;\n /**\n * The app's word for one stored value of one pick-list field — the SAME word\n * the record's own screens and the write forms show (\"incomplete\" on a task\n * reads \"Inbox\"). One value, one display word everywhere (G8A review,\n * 2026-10-02: the card said \"Status incomplete → completed\"). Return null for\n * a field that is not a pick-list: its value is shown as written. Absent →\n * every value is shown as stored.\n */\n valueLabel?: (ref: DirectiveValueRef) => string | null;\n /** The mirrored noun catalog (label / family / title column). */\n nouns?: DirectiveNounCatalog;\n /** slug → the kind ONE item is (THE DIRECTIVE⇄KIND SEAM), or null. */\n itemKind?: DirectiveItemKindLookup;\n /** Where a decode failure or an unhonourable shell is reported. Default: console.error. */\n reportError?: (message: string) => void;\n /**\n * Plain words for a failed apply the host recognises (\"This button can't\n * create a task yet.\" + \"Create it from Tasks instead.\"). The card never shows\n * the server's raw text as its sentence: it shows these words — or its own\n * verb-aware default — and keeps the raw text behind \"Details\". Return null\n * to use the default.\n */\n explainFailure?: (failure: DirectiveFailure) => DirectiveFailureWords | null;\n}\n\n/** One stored value of one field of one record type. */\nexport interface DirectiveValueRef {\n noun: string;\n field: string;\n value: string;\n}\n\n/** One failed apply, as the card knows it. */\nexport interface DirectiveFailure {\n /** The server's / host's own text — technical; shown only behind Details. */\n raw: string;\n directiveClass: string;\n noun: string;\n /** The noun's display label (\"Task\"). */\n nounLabel: string;\n /** Items that failed, when some applied and some did not. */\n failed?: number;\n /** Items in the block. */\n total?: number;\n}\n\n/** What failed and what to do — each one short sentence. */\nexport interface DirectiveFailureWords {\n what: string;\n next: string;\n /**\n * The text behind \"Details\", when the host words it (e.g. the server's field\n * names read as the form labels them — \"Title is required\", never\n * \"name is required\"). Absent → the raw text.\n */\n details?: string;\n}\n\nconst DirectiveHostContext = createContext<DirectiveHost | null>(null);\n\n/** Where a directive renders — today, the conversation it sits in (if any). */\nexport interface DirectiveScope {\n conversationId?: string | null;\n}\n\nconst DirectiveScopeContext = createContext<DirectiveScope>({});\n\n/**\n * Tell every card below WHERE it renders. A host draws a chat message's\n * directives inside one of these (or passes `conversationId` to\n * `DirectiveRender`), so the card applies in that conversation's namespace —\n * the same key the agent's proposal approves under. A note mounts none.\n */\nexport function DirectiveScopeProvider({\n conversationId,\n children,\n}: DirectiveScope & { children: ReactNode }) {\n return (\n <DirectiveScopeContext.Provider value={{ conversationId: conversationId ?? null }}>\n {children}\n </DirectiveScopeContext.Provider>\n );\n}\n\nexport function useDirectiveScope(): DirectiveScope {\n return useContext(DirectiveScopeContext);\n}\n\nexport interface DirectiveHostProviderProps {\n host: DirectiveHost;\n children: ReactNode;\n}\n\nexport function DirectiveHostProvider({ host, children }: DirectiveHostProviderProps) {\n return <DirectiveHostContext.Provider value={host}>{children}</DirectiveHostContext.Provider>;\n}\n\nconst EMPTY_HOST: DirectiveHost = {};\n\n/**\n * The wired directive host. Unlike the render host this does NOT throw when\n * unwired: a directive still renders (named, itemised, copy-less, apply-less)\n * — degrading the chrome is honest, hiding the content is not.\n */\nexport function useDirectiveHost(): DirectiveHost {\n return useContext(DirectiveHostContext) ?? EMPTY_HOST;\n}\n","/**\n * The Shape System component RESOLVER (rulings R1 + R6): (kind, platform,\n * role) → component, with two tiers:\n *\n * - eager: a COMPILED bootstrap the host ships in its bundle — the\n * trusted-at-boot floor, available at import so the render seam can gate\n * synchronously from the first streamed byte.\n * - warm: one `content_ir.kind_component` list fetch per app session\n * (`ensureWarm`). A DB row for a (kind, platform, role) OVERRIDES the\n * compiled entry once warm; the compiled floor keeps answering until then\n * (and forever, on DB failure).\n *\n * Resolution is SYNCHRONOUS (the render seam calls it per block); the only\n * async work is the loading, off the render path.\n *\n * WHAT MOVED AND WHY. This class was matrx-frontend's `ComponentRegistry`. It\n * is a large part of why a second UI could not render a kind: every tier rule,\n * every repaint counter, every dedupe latch lived in one app. Nothing about it\n * is Next.js, Redux, or Supabase — the only host-specific parts were the two\n * loaders and the error sink, which are now constructor arguments.\n */\n\nimport type { ContentIrErrorReporter } from \"../host/error-report\";\nimport { consoleErrorReporter } from \"../host/error-report\";\nimport type {\n ComponentResolution,\n ComponentResolutionSource,\n ComponentRole,\n KindComponentRow,\n SystemComponentEntry,\n} from \"./component-resolution.types\";\n\nexport interface ComponentResolverOptions {\n /**\n * The compiled bootstrap, as a THUNK resolved on first use: a host's system\n * component table is often mid-initialization when this module evaluates\n * (matrx-frontend's registry cluster has a deliberate import cycle).\n */\n compiledEntries?: () => SystemComponentEntry[];\n /** The warm/refresh list load — every `kind_component` row the user may see. */\n loadAll?: () => Promise<KindComponentRow[]>;\n /** The eager single-kind load fired the moment a kind is identified mid-stream. */\n loadForKind?: (kind: string, platform: string) => Promise<KindComponentRow[]>;\n /** Where recovery screams land. Defaults to `console.error`, never silence. */\n reportError?: ContentIrErrorReporter;\n /** Clock seam — the refresh rate limiter. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/** Unit separator — a character no kind slug, platform, or role can contain. */\nconst KEY_SEPARATOR = String.fromCharCode(1);\n\nfunction keyOf(kind: string, platform: string, role: string): string {\n return `${kind}${KEY_SEPARATOR}${platform}${KEY_SEPARATOR}${role}`;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Error-shaped fields, spread-safe under `exactOptionalPropertyTypes`. */\nfunction errorFields(error: unknown): { name?: string; stack?: string } {\n if (!(error instanceof Error)) return {};\n return {\n name: error.name,\n ...(error.stack === undefined ? {} : { stack: error.stack }),\n };\n}\n\n/**\n * Warm-load retry backoff. Sized for the auth-hydration race: a fresh tab's\n * first list load can run before the Supabase session restores and fail with\n * a permission error; the session is typically live within a second or two,\n * so the first retry usually completes the load. After the last delay the\n * resolver settles on whatever it has — see the failure branch in ensureWarm.\n */\nconst WARM_RETRY_DELAYS_MS: readonly number[] = [1_000, 5_000, 15_000];\n\nexport class ComponentResolver implements ComponentResolutionSource {\n private compiled: Map<string, SystemComponentEntry> | null = null;\n private readonly db = new Map<string, KindComponentRow>();\n private warmPromise: Promise<void> | null = null;\n /** Consecutive warm-load failures — indexes WARM_RETRY_DELAYS_MS. */\n private warmFailures = 0;\n private warmRetryTimer: ReturnType<typeof setTimeout> | null = null;\n /**\n * True once a list load has RUN TO COMPLETION (success or failure), or once\n * any rows have been ingested by any tier. Until then `resolve()` answering\n * null means \"I have not looked yet\" — never \"no such component\". See THE\n * COLD-VERDICT RULE on `ComponentResolutionSource.hasSettled`.\n */\n private settled = false;\n /**\n * When the last successful wholesale refresh landed, or null for \"never\".\n * Explicitly nullable rather than 0: with a host-supplied clock that starts\n * near zero, a `0` sentinel makes the FIRST refresh look rate-limited and\n * silently skip.\n */\n private lastRefreshAt: number | null = null;\n private refreshPromise: Promise<void> | null = null;\n private readonly listeners = new Set<() => void>();\n /**\n * Cold single-kind fetch dedupe (streaming eager path). In-flight is keyed\n * by (kind, platform) — the fetch unit; misses are keyed by (kind, platform,\n * role) so a miss on web/output never suppresses other roles, and CLEARED on\n * every wholesale refresh (a component created mid-session becomes eagerly\n * fetchable again — misses are cheap to re-verify).\n */\n private readonly coldInFlight = new Set<string>();\n private readonly coldMisses = new Set<string>();\n /** Monotonic db-tier version — the repaint hook's snapshot key. */\n private version = 0;\n /** Per-kind versions + listeners (granular repaint) + wholesale epoch. */\n private readonly kindVersions = new Map<string, number>();\n private readonly kindListeners = new Map<string, Set<() => void>>();\n private epoch = 0;\n\n private readonly reportError: ContentIrErrorReporter;\n private readonly now: () => number;\n\n private readonly options: ComponentResolverOptions;\n\n // Explicit field, not a parameter property: consumers compile this source\n // directly, and a strict host (the dashboard) sets `erasableSyntaxOnly`,\n // under which parameter properties are a hard error.\n constructor(options: ComponentResolverOptions = {}) {\n this.options = options;\n this.reportError = options.reportError ?? consoleErrorReporter;\n this.now = options.now ?? (() => Date.now());\n }\n\n private compiledMap(): Map<string, SystemComponentEntry> {\n if (!this.compiled) {\n this.compiled = new Map();\n for (const entry of this.options.compiledEntries?.() ?? []) {\n this.compiled.set(keyOf(entry.kind, entry.platform, entry.role), entry);\n }\n }\n return this.compiled;\n }\n\n /**\n * Synchronous resolve — the render seam's per-block call. DB override first\n * (once warm), compiled floor second, null for unknown.\n */\n resolve(\n kind: string,\n platform: string,\n role: ComponentRole,\n ): ComponentResolution | null {\n const key = keyOf(kind, platform, role);\n\n const dbRow = this.db.get(key);\n if (dbRow) {\n return {\n componentKey: dbRow.componentKey,\n source: dbRow.source,\n config: dbRow.config,\n isActive: dbRow.isActive,\n resolvedBy: \"db\",\n componentSource: dbRow.componentSource,\n propsTransform: dbRow.propsTransform,\n hasComponentSource:\n dbRow.hasComponentSource ??\n Boolean(dbRow.componentSource && dbRow.componentSource.trim()),\n pinnedKindVersion: dbRow.pinnedKindVersion,\n updatedAt: dbRow.updatedAt,\n createdBy: dbRow.createdBy,\n };\n }\n\n const compiledEntry = this.compiledMap().get(key);\n if (compiledEntry) {\n return {\n componentKey: compiledEntry.componentKey,\n source: compiledEntry.source,\n config: compiledEntry.config,\n isActive: true, // trusted at bootstrap (R6)\n resolvedBy: \"compiled\",\n componentSource: null,\n propsTransform: null,\n hasComponentSource: false,\n pinnedKindVersion: null,\n updatedAt: null,\n createdBy: null,\n };\n }\n\n return null;\n }\n\n /** R6 floor check: compiled-bootstrap membership = always render-trusted. */\n hasCompiled(kind: string, platform: string, role: ComponentRole): boolean {\n return this.compiledMap().has(keyOf(kind, platform, role));\n }\n\n /**\n * Pure ingest — the warm landing point and the unit-test seam. First row per\n * key wins: rows arrive is_default-first / sort_order-asc from the source.\n */\n ingestDbRows(rows: readonly KindComponentRow[]): void {\n const wasSettled = this.hasSettled();\n const changedKinds = new Set<string>();\n for (const row of rows) {\n const key = keyOf(row.kind, row.platform, row.role);\n if (!this.db.has(key)) {\n this.db.set(key, row);\n changedKinds.add(row.kind);\n }\n }\n // Warm/cold ingest is a resolver-tier change the render seam must see — a\n // db component landing AFTER a region finalized re-runs the route via the\n // repaint hook. Per-kind bumps keep the repaint granular.\n // The first rows settle the tier (hasSettled): every waiting kind hears it,\n // ONCE — the epoch covers the ingested kinds too.\n if (!wasSettled && this.hasSettled()) {\n this.notifySettled();\n return;\n }\n if (changedKinds.size > 0) {\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\n }\n\n /**\n * Mark the tier settled. THE COLD-VERDICT RULE held every block whose kind\n * the tier could not answer; settling changes that verdict for ALL of them,\n * so the flip bumps the epoch and calls every per-kind listener (as a\n * wholesale replace does). Before 0.13.0 a settle notified only kinds that\n * gained rows, and a waiting block for any other kind kept its pre-settle\n * rendering until something unrelated re-rendered it.\n */\n private markSettled(): void {\n const wasSettled = this.hasSettled();\n this.settled = true;\n if (!wasSettled) this.notifySettled();\n }\n\n private notifySettled(): void {\n this.epoch += 1;\n for (const set of this.kindListeners.values()) {\n for (const listener of set) listener();\n }\n this.notifyChanged();\n }\n\n /**\n * Refresh landing point: REPLACE the db tier wholesale (same\n * first-row-per-key contract as {@link ingestDbRows}) so edits, deletions,\n * and is_active flips all take effect. Always notifies.\n */\n replaceDbRows(rows: readonly KindComponentRow[]): void {\n // A wholesale replace IS a completed list load — the refresh landing\n // point, and the seam tests use to declare \"the list loaded\". Settling\n // here keeps THE COLD-VERDICT RULE from holding blocks forever in any\n // host that warms through refresh() rather than ensureWarm().\n this.settled = true;\n this.db.clear();\n // Wholesale invalidation: every recorded miss is stale (a component\n // created mid-session must become eagerly fetchable again).\n this.coldMisses.clear();\n for (const row of rows) {\n const key = keyOf(row.kind, row.platform, row.role);\n if (!this.db.has(key)) this.db.set(key, row);\n }\n // A wholesale replace ALWAYS notifies (deletions/flips count too), and\n // bumps the epoch so EVERY per-kind subscriber re-snapshots.\n this.epoch += 1;\n for (const set of this.kindListeners.values()) {\n for (const listener of set) listener();\n }\n this.notifyChanged();\n }\n\n getVersion(): number {\n return this.version;\n }\n\n getKindVersion(kind: string): number {\n return this.epoch + (this.kindVersions.get(kind) ?? 0);\n }\n\n subscribeKind(kind: string, listener: () => void): () => void {\n const set = this.kindListeners.get(kind) ?? new Set<() => void>();\n set.add(listener);\n this.kindListeners.set(kind, set);\n return () => {\n set.delete(listener);\n if (set.size === 0) this.kindListeners.delete(kind);\n };\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n private bumpKind(kind: string): void {\n this.kindVersions.set(kind, (this.kindVersions.get(kind) ?? 0) + 1);\n const listeners = this.kindListeners.get(kind);\n if (listeners) for (const listener of listeners) listener();\n }\n\n private notifyChanged(): void {\n this.version += 1;\n for (const listener of this.listeners) listener();\n }\n\n /**\n * A warm metadata shell is resolved enough for routing, but not for the\n * host's db-component renderer. Its body must still come from the cold\n * single-kind loader.\n */\n private needsColdFetch(\n kind: string,\n platform: string,\n role: ComponentRole,\n ): boolean {\n const resolution = this.resolve(kind, platform, role);\n return (\n resolution === null ||\n (resolution.resolvedBy === \"db\" &&\n resolution.hasComponentSource &&\n resolution.componentSource === null)\n );\n }\n\n /**\n * Cold rows are the authoritative heavy form of warm metadata shells. Keep\n * the same first-row-per-key winner contract, but replace an existing shell\n * so `componentSource` / `propsTransform` can land and repaint the kind.\n */\n private ingestColdRows(rows: readonly KindComponentRow[]): void {\n const winners = new Map<string, KindComponentRow>();\n for (const row of rows) {\n const key = keyOf(row.kind, row.platform, row.role);\n if (!winners.has(key)) winners.set(key, row);\n }\n if (winners.size === 0) return;\n\n const changedKinds = new Set<string>();\n for (const [key, row] of winners) {\n this.db.set(key, row);\n changedKinds.add(row.kind);\n }\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\n\n /**\n * The eager lightweight single-kind fetch (streaming path): the moment a\n * cloud kind is identified mid-stream, pull ONLY that kind's resolver rows\n * and ingest them so {@link resolve} can answer before — or shortly after —\n * the region completes. Deduped in-flight and by known-miss. Fire-and-forget;\n * failures are loud (the warm list remains the backstop).\n */\n requestComponent(kind: string, platform: string, role: ComponentRole): void {\n const loadForKind = this.options.loadForKind;\n if (!loadForKind) return;\n if (!this.needsColdFetch(kind, platform, role)) return;\n const missKey = keyOf(kind, platform, role);\n const flightKey = `${kind}${KEY_SEPARATOR}${platform}`;\n if (this.coldInFlight.has(flightKey) || this.coldMisses.has(missKey)) {\n return;\n }\n this.coldInFlight.add(flightKey);\n const versionBefore = this.kindVersions.get(kind) ?? 0;\n\n void (async () => {\n try {\n this.ingestColdRows(await loadForKind(kind, platform));\n // Record the miss for exactly the requested (kind, platform, role) —\n // rows may exist for OTHER roles on this platform; those must not be\n // suppressed, and this one must not be re-fetched until a refresh.\n if (this.needsColdFetch(kind, platform, role)) {\n this.coldMisses.add(missKey);\n }\n } catch (error) {\n this.reportError({\n source: \"content-ir\",\n message: `component-resolver cold fetch failed for \"${kind}\": ${describe(error)}`,\n ...errorFields(error),\n raw: error,\n });\n } finally {\n this.coldInFlight.delete(flightKey);\n // The kind's single-kind fetch answered (rows, a miss, or a failure):\n // a block waiting on THIS kind re-routes now. A landing already bumped\n // inside ingestColdRows; a miss or failure changed nothing in the\n // tier, but the waiting block must still be told to re-ask.\n if ((this.kindVersions.get(kind) ?? 0) === versionBefore) {\n this.bumpKind(kind);\n }\n }\n })();\n }\n\n /**\n * Refresh-on-view: re-fetch the warm list and REPLACE the db tier, so an\n * edited `source='db'` component (its `updated_at` bump re-keys the host's\n * compile cache) renders fresh on the next view. Deduped in-flight and\n * rate-limited by `maxAgeMs` (default 10s) — mounting several previews costs\n * one fetch. Server-side edits do NOT push to open clients; the contract is\n * refresh-on-view via this call.\n */\n refresh(maxAgeMs = 10_000): Promise<void> {\n const loadAll = this.options.loadAll;\n if (!loadAll) return Promise.resolve();\n if (this.refreshPromise) return this.refreshPromise;\n if (\n this.lastRefreshAt !== null &&\n this.now() - this.lastRefreshAt < maxAgeMs\n ) {\n return Promise.resolve();\n }\n // Any refresh intent invalidates recorded misses immediately (also cleared\n // in replaceDbRows when the fetch lands) — cheap to re-verify.\n this.coldMisses.clear();\n\n this.refreshPromise = loadAll()\n .then((rows) => {\n this.lastRefreshAt = this.now();\n this.replaceDbRows(rows);\n })\n .catch((error: unknown) => {\n // Loud recovery: the current tier keeps answering; a refresh failure is\n // a real defect (same posture as the warm loader).\n this.reportError({\n source: \"content-ir\",\n message: `component-resolver refresh failed (current resolver tier still serving): ${describe(error)}`,\n ...errorFields(error),\n raw: error,\n });\n })\n .finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** One list fetch per app session; failed loads retry on the next call. */\n ensureWarm(): Promise<void> {\n const loadAll = this.options.loadAll;\n if (!loadAll) return Promise.resolve();\n if (!this.warmPromise) {\n this.warmPromise = loadAll()\n .then((rows) => {\n this.ingestDbRows(rows);\n this.markSettled();\n this.warmFailures = 0;\n if (this.warmRetryTimer) {\n clearTimeout(this.warmRetryTimer);\n this.warmRetryTimer = null;\n }\n })\n .catch((error: unknown) => {\n // The host owns presentation and severity through reportError. A\n // direct console.error here duplicates that report and prevents a\n // host from classifying a still-serving compiled fallback as a\n // recoverable warning.\n const message = `component-resolver warm load failed (compiled bootstrap still serving): ${describe(error)}`;\n this.reportError({\n source: \"content-ir\",\n message,\n ...errorFields(error),\n raw: error,\n });\n this.warmPromise = null;\n // 🚨 A FAILED load is NOT truth (2026-08-31). The 0.9.0 posture —\n // \"a failed load still settles\" — turned the auth-hydration race\n // into a lie: a fresh tab fires this load BEFORE the Supabase\n // session hydrates, the read runs as `anon`, RLS answers\n // 42501 permission denied, and settling on that failure declared an\n // EMPTY resolver to be the loaded state of the world. Every kind on\n // the page then routed to the generic floor as \"unregistered\" —\n // while the same rows were one authenticated retry away. So: retry\n // with backoff, and settle only when retries are exhausted (the\n // backend really is down; the generic floor + the per-attempt\n // scream above are then the honest, announced stand-in).\n this.warmFailures += 1;\n const delay =\n WARM_RETRY_DELAYS_MS[this.warmFailures - 1] ?? null;\n if (delay === null) {\n this.markSettled();\n } else if (!this.warmRetryTimer) {\n this.warmRetryTimer = setTimeout(() => {\n this.warmRetryTimer = null;\n void this.ensureWarm();\n }, delay);\n }\n });\n }\n return this.warmPromise;\n }\n\n /** @see ComponentResolutionSource.hasSettled */\n hasSettled(): boolean {\n // No list loader configured = nothing to wait for: the compiled floor IS\n // the complete truth for this resolver, so it is settled from birth. (A\n // host that never wired a loader must not have every block held forever.)\n if (!this.options.loadAll) return true;\n return this.settled || this.db.size > 0;\n }\n}\n","/**\n * THE KIND ROUTE — the render flip, as a pure block transform.\n *\n * A block whose `metadata.__ir` envelope resolved a REGISTERED kind is routed\n * to that kind's component: via the legacy-bridge facet (`legacyBlockType` +\n * `toLegacyServerData`) when the kind has one, so the block enters the host's\n * existing renderer as its real type with envelope-derived serverData;\n * otherwise via the component resolver. Blocks with no envelope, an\n * unregistered kind, or no bridge facet pass through UNTOUCHED — the strangler\n * seam.\n *\n * This is where a bare/fenced JSON flashcard_set — which a text detector could\n * only ever call \"code\" — becomes real flashcards, live while streaming.\n *\n * PORTABILITY. This function was matrx-frontend's `react/kind-route.ts` and is\n * the single most-copied thing in the system: every UI that renders a kind has\n * to make exactly these decisions in exactly this order, and a second\n * implementation of them is a guaranteed divergence. It takes its registries,\n * its platform, and its error sink as an {@link KindRouteEnv} argument rather\n * than importing them, so it is callable from a reducer, a stream accumulator,\n * a test, or a React render — in any app.\n *\n * Semantics: `matrx-frontend/features/content-ir/docs/SHAPE_SYSTEM.md`\n * (registry, dual gate, `kind_component` resolution, rulings R1 + R6).\n */\n\nimport {\n envelopeFromCompleteValue,\n isReservedDirectiveSlug,\n readEnvelope,\n readObjectKind,\n} from \"@ai-matrx/content-ir\";\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-react.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/** 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 /**\n * The slug is not in the registry at all (typo, foreign emitter, a shape\n * not yet created). Routed anyway — Arman's 2026-08-29 ruling: a root\n * `__kind` key means the kind system owns the render, no exceptions. The\n * repair is creating/registering the shape (or fixing the slug).\n */\n | \"unregistered\";\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 const componentsSettled = env.components.hasSettled?.() ?? true;\n if (!componentsSettled && !resolution && !def) 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 if (envelope.root.kindState === \"raw\") {\n return routeToGeneric(\n block,\n def || resolution ? \"broken-instance\" : \"unregistered\",\n );\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 // A kind slug the platform has NO definition for (a typo, a foreign\n // emitter, a not-yet-created shape). 🚨 Arman's ruling, 2026-08-29: a root\n // `__kind` key means the kind system owns the render — NO exceptions. The\n // old strangler carve-out (\"not ours to claim\", teaching content stayed a\n // raw code block) is retired: an unregistered kind renders through the\n // generic floor with `reason: \"unregistered\"`, so the reader always sees\n // the payload acknowledged AS a kind instance with what is known about it.\n // A repaint hook upgrades this block the moment the registries learn the\n // kind.\n return routeToGeneric(block, \"unregistered\");\n}\n\n/**\n * Rehydration route for STRUCTURED persisted artifacts.\n *\n * A materialized kind artifact stores its zero-loss value object (carrying\n * `__kind`) alongside its row. Given that stored value, derive the registered\n * kind's legacy `serverData` WITHOUT re-parsing any text: the value wraps into\n * a complete envelope and runs through the same `toLegacyServerData` bridge the\n * live stream uses. Returns null for non-objects, unregistered kinds, or kinds\n * without a legacy bridge — callers fall back to their string-payload path.\n */\nexport function kindServerDataFromStoredValue(\n value: unknown,\n env: Pick<KindRouteEnv, \"kinds\">,\n): Record<string, unknown> | null {\n if (!isRecord(value)) return null;\n const kind = readObjectKind(value);\n if (!kind) return null;\n\n const def = env.kinds.getDefinition(kind);\n if (!def?.toLegacyServerData) return null;\n\n return def.toLegacyServerData(envelopeFromCompleteValue(value, kind)) ?? null;\n}\n","/**\n * 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: WITHHOLD BY DEFAULT, OPT IN PER KIND\n * -------------------------------------------------\n * A provisional value MAY be missing required fields — that is what the\n * `partial_unvalidated` notice declares — and §8 of the contract requires that\n * a component which throws on an absent field is not routed one. Rather than\n * audit every component, the default is WITHHOLD: nothing changes and the block\n * keeps its loading skeleton. A kind opts in with `partialReady: true` on its\n * registry definition. If an opted-in component throws anyway,\n * `ProvisionalKindBoundary` screams and calls `markKindPartialUnsafe`, which\n * drops that kind back to withhold for the rest of the session — loud recovery,\n * never a broken surface.\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 {\n envelopeFromCompleteValue,\n IR_ENVELOPE_KEY,\n IR_PARTIAL_KEY,\n IR_VERSION,\n isProvisionalKind,\n readEnvelope,\n readObjectKind,\n readPartialKindEvent,\n} from \"@ai-matrx/content-ir\";\nimport type { CanonicalBlockIR, PartialKindEvent } from \"@ai-matrx/content-ir\";\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-react.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 * Has this kind opted in to being handed a provisional value? Withhold is the\n * default; see the module doc.\n */\nexport function isPartialReadyKind(\n kind: string,\n env: Pick<KindRouteEnv, \"kinds\">,\n): boolean {\n if (!kind || partialUnsafeKinds.has(kind)) return false;\n return env.kinds.getDefinition(kind)?.partialReady === true;\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 cancelled (so a client abort\n * drops every retraction), and a flush failure is swallowed so it never kills\n * a run.\n *\n * Once the stream is over, no terminal can ever arrive, so a still-open\n * provisional is stuck by definition — drop it and let the block's own\n * content and `__ir` be the truth. Correct to be message-wide: a terminal for\n * THIS block may still be in flight while the block itself looks finished.\n *\n * `undefined` reads as active, so a caller that does not thread stream state\n * keeps live rendering rather than silently losing it.\n */\n streamActive?: boolean;\n}\n\n/**\n * The ANNOUNCED-but-not-yet-renderable state: the server has said what this\n * region is, and the region cannot render its real component yet.\n *\n * WHY THIS EXISTS SEPARATELY FROM THE VERIFIED CHANNEL. On a chat stream the\n * host's own accumulator fills `__ir` in as it parses. A WORKFLOW run's lane\n * does not: when the server opens the block scope it marks the text channel\n * `block_shadowed` and the lane stops feeding its accumulator, precisely so one\n * region is never rendered twice under two sets of block ids\n * (STREAMING_PARTIAL_KINDS.md §7b rule 4). So on a run page there is NO\n * streaming `__ir` — the ONLY thing that knows what the region is, is the\n * partial channel. Without this, a workflow node's structured answer fell\n * through to the raw-text renderer: a generic loader, then raw JSON\n * accumulating, then a swap at the end.\n *\n * Returns the provisional envelope to feed the kind's loading component, or\n * null when there is nothing announced (no event, a terminal, a dead stream).\n * Deliberately independent of `partialReady`: withholding a VALUE from a\n * component that might throw on it is a real decision, but withholding the\n * kind's own loading state is not — a skeleton cannot throw, and the reader\n * seeing what is coming is the whole point.\n */\nexport function resolveAnnouncedKindLoading(\n block: { metadata?: Record<string, unknown> },\n options?: Pick<PartialRenderOptions, \"streamActive\">,\n): { kind: string; envelope: CanonicalBlockIR } | null {\n // Same anti-stuck-skeleton backstop as resolveProvisionalKindRender: once the\n // stream is over no terminal can arrive, so a still-open announcement is\n // stuck by definition and must not hold a loader on screen forever.\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n if (!isProvisionalKind(event)) return null;\n const kind = event.root.kind;\n if (!kind) return null;\n\n // A region that already VERIFIED is the truth; never cover it with a loader.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n return { kind, envelope: envelopeFromPartialKind(event) };\n}\n\nexport interface ProvisionalKindRender<T> {\n /** The routed block — same type/serverData shape the final value produces. */\n block: T;\n /** The announced (speculative) kind. */\n kind: string;\n /** Per-block ordering key, for diagnostics. */\n seq: number;\n /** The provisional envelope — feeds the loading skeleton used as the throw fallback. */\n envelope: CanonicalBlockIR;\n}\n\nexport interface SupersededKindRender<T> {\n /** The completed block routed through the announced kind's normal component. */\n block: T;\n /** The kind the producer announced and then confirmed at terminal. */\n kind: string;\n /** Per-block ordering key, for diagnostics. */\n seq: number;\n /** Render-local complete envelope reconstructed from the block's own content. */\n envelope: CanonicalBlockIR;\n}\n\nfunction parseCompletedJsonObject(content: string): Record<string, unknown> | null {\n let source = content.trim();\n const fenced = source.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```$/i);\n if (fenced?.[1]) source = fenced[1].trim();\n\n try {\n const value = JSON.parse(source) as unknown;\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Finish the partial-kind handoff for a `superseded` terminal.\n *\n * A workflow run deliberately shadows its text channel while server-built\n * render blocks stream, so the browser never builds a verified `__ir`\n * envelope for that region. The terminal still proves that the announced kind\n * completed, and the block's own content is now closed JSON. Reconstruct a\n * render-local COMPLETE envelope from that content and route it through the\n * same component path as persisted/reloaded data. `retracted` is never\n * eligible, and a malformed or mismatched payload stays on the host's honest\n * raw fallback.\n */\nexport function resolveSupersededKindRender<\n T extends IrRoutableBlock & {\n content: string;\n metadata?: Record<string, unknown>;\n },\n>(\n block: T,\n env: KindRouteEnv,\n options?: KindRouteOptions,\n): SupersededKindRender<T> | null {\n const event = readPartialKindEvent(block.metadata);\n if (event?.state !== \"superseded\") return null;\n\n // A verified envelope is already the higher-fidelity truth and the ordinary\n // kind route owns it.\n if (readEnvelope(block.metadata)?.root.status === \"complete\") return null;\n\n const value = parseCompletedJsonObject(block.content);\n if (!value || readObjectKind(value) !== event.kind) return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n const envelope = envelopeFromCompleteValue(value, event.kind);\n const terminalBlock = {\n ...block,\n // A code/json block's serverData is an annotation, not kind data.\n serverData: undefined,\n metadata: { ...rest, [IR_ENVELOPE_KEY]: envelope },\n } as T;\n const routed = applyIrKindRoute(terminalBlock, env, options);\n if (routed === terminalBlock) return null;\n\n return { block: routed, kind: event.kind, seq: event.seq, envelope };\n}\n\n/**\n * Resolve a block's provisional render, or null when there is nothing to show\n * provisionally (no event, a terminal event, a withheld kind, a kind nothing\n * can route, or a verified envelope that already won).\n *\n * Pure: no React, no host state, no side effects beyond the registry reads.\n */\nexport function resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n>(\n block: T,\n env: KindRouteEnv,\n options?: PartialRenderOptions,\n): ProvisionalKindRender<T> | null {\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n // Terminal (superseded / retracted) → no provisional render, in this frame.\n if (!isProvisionalKind(event)) return null;\n\n const kind = event.root.kind;\n if (!isPartialReadyKind(kind, env)) return null;\n\n // A verified envelope that has already completed is the truth — a late or\n // duplicated partial must never displace it.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n\n const envelope = envelopeFromPartialKind(event);\n\n const provisionalBlock = {\n ...block,\n // The raw region annotation (`{ language: \"json\" }`) is not kind data —\n // same poison rule the verified route follows.\n serverData: undefined,\n metadata: {\n ...rest,\n [IR_ENVELOPE_KEY]: envelope,\n [IR_PROVISIONAL_KEY]: true,\n },\n } as T;\n\n const routed = applyIrKindRoute(provisionalBlock, env, options);\n // Nothing claimed it (unknown kind, no component) — `applyIrKindRoute`\n // returns the SAME reference. Withhold rather than render raw partial JSON.\n if (routed === provisionalBlock) return null;\n // A bridged kind whose bridge DECLINED this value (too thin to render — a\n // quiz with no answerable question yet) routed on type alone, which would\n // hand the component the partial JSON text to parse. Withhold: the loading\n // skeleton stays up for this frame and the next `seq` tries again.\n if (\n env.kinds.getDefinition(kind)?.toLegacyServerData &&\n !(routed as { serverData?: unknown }).serverData\n ) {\n return null;\n }\n\n return { block: routed, kind, seq: event.seq, envelope };\n}\n","/**\n * THE BOUND ROUTE — the pure route functions with a host's env and owned\n * types partially applied, built ONCE in a host wiring module.\n *\n * Every host was writing the same wrapper file by hand: one function per pure\n * route, each forwarding `matrx…Env` + `ownedTypes` (matrx-frontend carried\n * two such modules; the dashboard a third). Per C22 that repeated delta is\n * package-provided: a host module now only INJECTS (its env, its owned block\n * types) and re-exports what this factory returns.\n *\n * The functions are the exact pure routes — read `kind-route.ts` /\n * `partial-kind-route.ts` for semantics; nothing behavioral lives here.\n */\n\nimport type { IrRoutableBlock, KindRouteEnv } from \"../host/host-types\";\nimport {\n applyIrKindRoute,\n kindServerDataFromStoredValue,\n type KindRouteOptions,\n} from \"./kind-route\";\nimport {\n isPartialReadyKind,\n resolveProvisionalKindRender,\n resolveSupersededKindRender,\n type PartialRenderOptions,\n type ProvisionalKindRender,\n type SupersededKindRender,\n} from \"./partial-kind-route\";\n\nexport interface KindRouteBinding {\n /** Route one block through the bound registries. */\n applyIrKindRoute<T extends IrRoutableBlock>(block: T): T;\n /**\n * Rehydration route for STRUCTURED persisted artifacts: given a stored\n * zero-loss value object, derive the registered kind's legacy `serverData`\n * with no re-parse. Null for non-objects, unregistered kinds, or kinds\n * without a legacy bridge.\n */\n kindServerDataFromStoredValue(value: unknown): Record<string, unknown> | null;\n /** Has this kind opted in to being handed a provisional value? */\n isPartialReadyKind(kind: string): boolean;\n /**\n * Resolve a block's provisional render, or null when there is nothing to\n * show provisionally (no event, a terminal event, a withheld kind, a kind\n * nothing can route, or a verified envelope that already won).\n */\n resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n >(\n block: T,\n options?: Pick<PartialRenderOptions, \"streamActive\">,\n ): ProvisionalKindRender<T> | null;\n /**\n * Route a completed workflow block whose `superseded` terminal confirms the\n * kind but whose shadowed lane never built a verified envelope.\n */\n resolveSupersededKindRender<\n T extends IrRoutableBlock & {\n content: string;\n metadata?: Record<string, unknown>;\n },\n >(block: T): SupersededKindRender<T> | null;\n}\n\n/** Bind the pure routes to one host's env + owned block types. */\nexport function createKindRouteBinding(\n env: KindRouteEnv,\n options?: KindRouteOptions,\n): KindRouteBinding {\n const ownedTypes = options?.ownedTypes;\n return {\n applyIrKindRoute: (block) =>\n applyIrKindRoute(block, env, ownedTypes ? { ownedTypes } : undefined),\n kindServerDataFromStoredValue: (value) =>\n kindServerDataFromStoredValue(value, env),\n isPartialReadyKind: (kind) => isPartialReadyKind(kind, env),\n resolveProvisionalKindRender: (block, streamOptions) =>\n resolveProvisionalKindRender(block, env, {\n ...streamOptions,\n ...(ownedTypes ? { ownedTypes } : null),\n }),\n resolveSupersededKindRender: (block) =>\n resolveSupersededKindRender(\n block,\n env,\n ownedTypes ? { ownedTypes } : undefined,\n ),\n };\n}\n","\"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 {\n envelopeFromCompleteValue,\n IR_ENVELOPE_KEY,\n isReservedDirectiveSlug,\n} from \"@ai-matrx/content-ir\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport { DirectiveRender } from \"../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: a host frame either IS the chrome or has none.\n * \"card\" (default) keeps a bordered surface for preview surfaces. \"bare\"\n * renders with NO border/background/pad — for a host that already draws a\n * titled card, where the default produced a two-tone box-in-a-box with a dead\n * band around it.\n */\n variant?: \"card\" | \"bare\";\n className?: string;\n}\n\ntype RoutingStatus = \"checking\" | \"routable\" | \"unroutable\";\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 = \"card\",\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 =\n variant === \"bare\" ? undefined : \"rounded-md border border-border bg-card p-3\";\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","\"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 \"@ai-matrx/content-ir\";\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 * 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 \"@ai-matrx/content-ir\";\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 * \"Apply\" for a side-effect Kind Directive that arrived as CONTENT.\n *\n * THE POSITION RULE, honoured 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 \"@ai-matrx/content-ir\";\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=\"mt-px h-3.5 w-3.5 shrink-0\" />\n ) : (\n <CheckCircleIcon className=\"mt-px h-3.5 w-3.5 shrink-0\" />\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 grey\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=\"mt-0.5 h-3.5 w-3.5 shrink-0\" />\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 { itemTitle } from \"@ai-matrx/content-ir\";\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. `itemTitle`'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 = itemTitle(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 * labelled \"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-react/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 recognises (`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 * The handful of glyphs the directive cards need, as inline SVG. This package\n * depends on no icon library (see the FEATURE boundary); the paths are the\n * Lucide set's (ISC), so the cards look identical to a Lucide-using host.\n */\n\nimport type { ReactElement, SVGProps } from \"react\";\n\ntype IconProps = SVGProps<SVGSVGElement>;\n\nfunction Svg({ children, ...props }: IconProps) {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n {...props}\n >\n {children}\n </svg>\n );\n}\n\nexport const FilePlusIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4\" />\n <path d=\"M14 2v4a2 2 0 0 0 2 2h4\" />\n <path d=\"M3 15h6\" />\n <path d=\"M6 12v6\" />\n </Svg>\n);\nexport const PencilIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M12 20h9\" />\n <path d=\"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z\" />\n </Svg>\n);\nexport const TrashIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M3 6h18\" />\n <path d=\"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6\" />\n <path d=\"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2\" />\n <line x1=\"10\" x2=\"10\" y1=\"11\" y2=\"17\" />\n <line x1=\"14\" x2=\"14\" y1=\"11\" y2=\"17\" />\n </Svg>\n);\nexport const PlayIcon = (p: IconProps) => (\n <Svg {...p}>\n <polygon points=\"6 3 20 12 6 21 6 3\" />\n </Svg>\n);\nexport const WebhookIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2\" />\n <path d=\"m6 17 3.13-5.78c.53-.97.1-2.01-.4-2.96A4 4 0 0 1 14 5.5c.63.42 1.13 1 1.44 1.66\" />\n <path d=\"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8\" />\n </Svg>\n);\nexport const BoxesIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z\" />\n <path d=\"m7 16.5-4.74-2.85\" />\n <path d=\"m7 16.5 5-3\" />\n <path d=\"M7 16.5v5.17\" />\n <path d=\"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z\" />\n <path d=\"m17 16.5-5-3\" />\n <path d=\"m17 16.5 4.74-2.85\" />\n <path d=\"M17 16.5v5.17\" />\n <path d=\"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z\" />\n <path d=\"M12 8 7.26 5.15\" />\n <path d=\"m12 8 4.74-2.85\" />\n <path d=\"M12 13.5V8\" />\n </Svg>\n);\nexport const ChevronDownIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m6 9 6 6 6-6\" />\n </Svg>\n);\nexport const ChevronRightIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m9 18 6-6-6-6\" />\n </Svg>\n);\nexport const MaximizeIcon = (p: IconProps) => (\n <Svg {...p}>\n <polyline points=\"15 3 21 3 21 9\" />\n <polyline points=\"9 21 3 21 3 15\" />\n <line x1=\"21\" x2=\"14\" y1=\"3\" y2=\"10\" />\n <line x1=\"3\" x2=\"10\" y1=\"21\" y2=\"14\" />\n </Svg>\n);\nexport const LoaderIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </Svg>\n);\n/** Lucide `rotate-ccw` — \"Run again\". */\nexport const RotateCcwIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n <path d=\"M3 3v5h5\" />\n </Svg>\n);\nexport const CheckCircleIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m9 12 2 2 4-4\" />\n </Svg>\n);\nexport const AlertIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </Svg>\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 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 honour 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 \"@ai-matrx/content-ir\";\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 {\n type DecodedDirective,\n type DirectiveClass,\n buildDirectiveSlug,\n} from \"@ai-matrx/content-ir\";\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-react.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 {\n asKindInstance,\n directiveDisplay,\n itemFacts,\n itemSubtitle,\n nounLabel,\n nounTitleColumn,\n type DecodedDirective,\n} from \"@ai-matrx/content-ir\";\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 labelled 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 <div className=\"ml-auto flex min-w-0 flex-wrap items-center justify-end gap-1\">\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","\"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 * (`partialReady`), but an opt-in 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\ninterface ProvisionalKindBoundaryProps extends ProvisionalKindBoundaryOwnProps {\n reportError: ContentIrErrorReporter;\n}\n\ninterface ProvisionalKindBoundaryState {\n failed: boolean;\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(): ProvisionalKindBoundaryState {\n return { failed: true };\n }\n\n override componentDidCatch(error: Error, info: React.ErrorInfo): void {\n const { kind, reportError } = this.props;\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}\" declares partialReady but its component threw on a provisional value — provisional rendering disabled for this kind (falling back to its loading skeleton). Fix the component or drop partialReady.`,\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) return this.props.fallback;\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({ children }: { children: ReactNode }) {\n const host = useContentIrHost();\n const label = \"Still arriving\";\n return (\n <div className=\"relative\" aria-busy=\"true\">\n {children}\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 </div>\n );\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 {\n readEnvelope,\n readObjectKind,\n reconstructRegionValue,\n} from \"@ai-matrx/content-ir\";\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 : marker?.reason === \"unregistered\"\n ? \"this shape isn't registered on this platform\"\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, readObjectKind, readRunResultValue } from \"@ai-matrx/content-ir\";\nimport type { NodeOutcomeWrapper, RunResultWrapper } from \"@ai-matrx/content-ir\";\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","/**\n * The DB-component COMPILE CACHE — session-scoped, keyed per winning row\n * VERSION, with the loud-recovery policy built in.\n *\n * This was matrx-frontend's `dbKindComponentCache.ts` (316 lines of compile\n * caching + invalidation living in one host), absorbed per C22: cache\n * mechanics, key derivation, the scream-once latch, transform recovery, and\n * config narrowing are PACKAGE policy — every host was going to need exactly\n * these lines, bug for bug. What stays host-injected is exactly what is\n * host-shaped:\n *\n * - THE COMPILER ({@link DbKindComponentCompiler}). Compiling or sandboxing\n * user-authored component source is a security-shaped host decision — the\n * package never bundles Babel or an allowlist scope. matrx-frontend\n * injects its shared allowlist compiler (`compileSlotComponent`); a host\n * with no sandbox simply never constructs a cache.\n * - The default allowed-imports list (host scope registry).\n * - Where screams land ({@link ContentIrErrorReporter}) and where durable\n * incidents go ({@link DbKindComponentIncidentSink}).\n * - Invalidation TRIGGERS ({@link DbKindComponentCachePorts.registerInvalidation}):\n * the host wires its invalidation-registry keys (e.g.\n * `@ai-matrx/kit/invalidation` fired by name when an agent edits a\n * component row); the cache owns what invalidation MEANS.\n *\n * Contract (the db-row component contract, SHAPE_SYSTEM.md):\n * - `component_source` compiles to a React component receiving\n * `{ data, kind, config, runAction, itemState?, onResolve?, uiOptions? }`\n * where `data` is the kind instance value and `itemState` what actions\n * saved onto this item.\n * - `props_transform` (optional) compiles to a `(data) => data` function\n * applied to the value BEFORE it reaches the component. A throwing or\n * non-compiling transform screams and the untransformed value is used\n * (never a blank hole).\n * - `config.allowed_imports` (string[]) narrows the compile scope; absent,\n * the row gets the host's FULL registered allowlist.\n *\n * Cache key: (kind, platform, role, row.updated_at) — one compile per winning\n * row VERSION. A resolver refresh delivering an edited row (bumped\n * `updated_at`) re-keys and recompiles naturally; `invalidate` /\n * `invalidateAll` force-drop keys. Server edits never push to open clients —\n * the contract is refresh-on-view.\n */\n\nimport type * as React from \"react\";\n\nimport type { ContentIrErrorReporter } from \"../host/error-report\";\nimport type { ComponentResolution } from \"../resolver/component-resolution.types\";\n\n/**\n * Settings the MOUNTING UI dictates to a kind component — the standard,\n * growing arg list every component honors (Arman, 2026-07-23). `selectionMode`\n * is the first: it tells a component whether the surface wants the user to\n * pick one value, many, or none (pure display). A component reads what it\n * understands and ignores the rest; absent = its own default (usually display).\n */\nexport interface KindComponentUiOptions {\n selectionMode?: \"single\" | \"multiple\" | \"none\";\n [key: string]: unknown;\n}\n\n/**\n * The return channel: how a kind component hands a chosen value back to the\n * surface that mounted it (a Kind Request). The mirror of `runAction`\n * (surface → agent); this is component → surface. Undefined in normal render\n * (chat/notes) — the component simply doesn't offer selection there.\n */\nexport type ResolveKindValue = (value: unknown) => void;\n\n/** The envelope every kind action resolves to — a skip/failure is never a silent pass. */\nexport type DbKindActionResult =\n | { ok: true; result: unknown }\n | { ok: false; error: string };\n\n/**\n * The action seam a compiled component receives: `runAction(key, input)`\n * triggers a registered platform capability (e.g. \"trigger_agent\"). Always\n * resolves to an `{ ok }` envelope, never throws — safe to call from imperfect\n * component code. This is the ONLY side-effect channel a sandboxed component\n * gets; it reaches no data directly.\n */\nexport type RunDbKindAction = (\n key: string,\n input: unknown,\n) => Promise<DbKindActionResult>;\n\n/** Props every compiled DB kind component receives. */\nexport interface DbKindComponentRenderProps {\n /** The kind instance value — post-`props_transform` when one exists. */\n data: unknown;\n /** The kind slug the value belongs to. */\n kind: string;\n /** The resolver row's `config` object, verbatim (narrowed — see {@link DbKindComponentCache.config}). */\n config: Record<string, unknown>;\n /** The action seam — see {@link RunDbKindAction}. */\n runAction: RunDbKindAction;\n /**\n * Present only when the component is mounted inside a Kind Request. Call it\n * with the user's chosen value to hand that value back to the requesting\n * surface (which resolves its promise). Undefined in normal render.\n */\n onResolve?: ResolveKindValue;\n /** Settings the mounting surface dictates (e.g. `{ selectionMode: \"single\" }`). */\n uiOptions?: KindComponentUiOptions;\n /**\n * This item's durable state: what `save_item_state` / `run_shortcut` with\n * `saveAs` wrote onto it (`{}` when nothing yet; survives reload). The host\n * adds `src` to every saved image ref (`{ file_id, mime_type, width, height }`)\n * so the component renders `<img src={itemState.key.src}>`.\n */\n itemState?: Record<string, unknown>;\n}\n\nexport interface CompiledDbKindComponent {\n Component: React.ComponentType<DbKindComponentRenderProps>;\n /** Compiled `props_transform`, or null when the row declares none. */\n transform: ((data: unknown) => unknown) | null;\n}\n\nexport type DbKindCompileResult =\n | { ok: true; compiled: CompiledDbKindComponent }\n | { ok: false; error: string };\n\n/** The failure modes a browser can observe on a DB kind component. */\nexport type DbKindComponentIncidentType =\n /** `component_source` did not compile (or produced no component). */\n | \"compile_error\"\n /** The compiled component threw during render (error boundary caught it). */\n | \"render_throw\"\n /** `props_transform` failed to compile or threw. */\n | \"transform_error\";\n\n/**\n * One durable render incident — the payload for whoever can actually FIX the\n * component. A host sink typically files it on the kind's own incident queue\n * (matrx-frontend: `content_ir.kind_component_incident` via RPC); without a\n * sink, a broken component seen only by ordinary users is invisible to its\n * author forever. `data` is the kind instance value — a privacy-conscious sink\n * reduces it to keys + types before it leaves the browser.\n */\nexport interface DbKindComponentIncident {\n kind: string;\n errorType: DbKindComponentIncidentType;\n message: string;\n platform?: string;\n role?: string;\n componentKey?: string | null;\n componentUpdatedAt?: string | null;\n stack?: string | null;\n data?: unknown;\n}\n\nexport type DbKindComponentIncidentSink = (\n incident: DbKindComponentIncident,\n) => void;\n\n/**\n * THE COMPILER PORT. Matches matrx-frontend's shared allowlist compiler\n * (`compileSlotComponent`) structurally: source in, `{ Component | error }`\n * out, never throws. The compiled component is generically typed — the cache\n * performs the single deliberate narrowing where the generic compiler meets\n * the kind prop contract.\n */\nexport type DbKindComponentCompiler = (args: {\n code: string;\n allowedImports: string[];\n}) => {\n Component: React.ComponentType<Record<string, unknown>> | null;\n error: string | null;\n};\n\nexport interface DbKindComponentCachePorts {\n /** The host's sandbox compiler — see {@link DbKindComponentCompiler}. */\n compile: DbKindComponentCompiler;\n /** The FULL registered allowlist a row without `config.allowed_imports` gets. */\n defaultAllowedImports: () => string[];\n /** Where screams land (every recovery path is loud). */\n reportError: ContentIrErrorReporter;\n /** Durable incident sink — optional, but a host without one blinds authors. */\n reportIncident?: DbKindComponentIncidentSink;\n /** Default `kind_component.platform` for this host (default \"web\"). */\n platform?: string;\n /**\n * THE INVALIDATION REGISTRATION PORT. Called once at construction with the\n * cache's `invalidateAll`; the host registers it under its own invalidation\n * keys (e.g. `@ai-matrx/kit/invalidation`'s name-keyed registry, fired when\n * an agent's component write completes). The cache owns the mechanics —\n * what gets dropped, the scream-latch reset; the host owns only WHEN.\n */\n registerInvalidation?: (invalidateAll: () => void) => void;\n}\n\nexport interface DbKindComponentCache {\n /**\n * Compile (once per resolver key per row version) a db-source resolution's\n * `component_source` + optional `props_transform`. Synchronous — the caller\n * (a lazily-loaded Impl) already paid the compiler chunk.\n */\n getOrCompile(\n kind: string,\n resolution: ComponentResolution,\n platform?: string,\n role?: string,\n ): DbKindCompileResult;\n /**\n * Apply the row's transform to the kind value. Loud on throw, never fatal —\n * the untransformed value comes back so content is never hidden.\n */\n applyPropsTransform(\n kind: string,\n compiled: CompiledDbKindComponent,\n value: unknown,\n ): unknown;\n /**\n * THE CONFIG BOUNDARY. `ComponentResolution.config` is typed\n * `Record<string, unknown>` — deliberately agnostic about a host's JSONB\n * interior. This narrows at runtime (plain object → itself; anything else →\n * scream + empty config) rather than asserting: a row whose `config` is not\n * an object is a malformed `kind_component` row, and the component still\n * renders rather than crashing.\n */\n config(config: unknown, kind: string): Record<string, unknown>;\n /** Drop a (kind, platform, role) key family (authoring surfaces call after editing a row). */\n invalidate(kind: string, platform?: string, role?: string): void;\n /** Drop everything — the invalidation-port payload. */\n invalidateAll(): void;\n}\n\n/**\n * A routed lazy warm row owns a real body, but the per-kind cold fetch has not\n * landed it yet. This is loading, not a compile failure.\n */\nexport function isDbKindComponentBodyPending(\n resolution: ComponentResolution,\n): boolean {\n return resolution.hasComponentSource && resolution.componentSource === null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Build the session cache. One per host app — construct it in the wiring module. */\nexport function createDbKindComponentCache(\n ports: DbKindComponentCachePorts,\n): DbKindComponentCache {\n const cache = new Map<string, DbKindCompileResult>();\n const screamedKeys = new Set<string>();\n const defaultPlatform = ports.platform ?? \"web\";\n\n function cacheKey(\n kind: string,\n platform: string,\n role: string,\n updatedAt: string | null,\n ): string {\n // `updatedAt` (the winning row's freshness) is part of the key: a refresh\n // that delivers an edited row (bumped updated_at) recompiles automatically\n // instead of serving the stale compile for the rest of the session.\n return `${kind}${platform}${role}${updatedAt ?? \"\"}`;\n }\n\n /**\n * Loud recovery: one console scream per key + a structured report on every\n * attempt + a durable incident for whoever can fix the component.\n */\n function screamCompileFailure(\n key: string,\n kind: string,\n error: string,\n resolution: ComponentResolution,\n platform: string,\n role: string,\n ): void {\n const message = `[content-ir] DB kind component for \"${kind}\" failed to compile — rendering the generic structured viewer instead: ${error}`;\n if (!screamedKeys.has(key)) {\n screamedKeys.add(key);\n console.error(message);\n }\n ports.reportError({ source: \"content-ir\", message, raw: { kind, error } });\n ports.reportIncident?.({\n kind,\n errorType: \"compile_error\",\n message,\n platform,\n role,\n componentKey: resolution.componentKey,\n componentUpdatedAt: resolution.updatedAt,\n });\n }\n\n function config(value: unknown, kind: string): Record<string, unknown> {\n if (isPlainObject(value)) return value;\n if (value === null || value === undefined) return {};\n const message = `[content-ir] kind_component.config for \"${kind}\" is not a JSON object (${typeof value}) — rendering with an empty config.`;\n console.error(message);\n ports.reportError({ source: \"content-ir\", message, raw: { kind } });\n return {};\n }\n\n function resolveAllowedImports(rowConfig: Record<string, unknown>): string[] {\n const declared = rowConfig.allowed_imports;\n if (\n Array.isArray(declared) &&\n declared.every((entry): entry is string => typeof entry === \"string\")\n ) {\n return declared;\n }\n return ports.defaultAllowedImports();\n }\n\n function getOrCompile(\n kind: string,\n resolution: ComponentResolution,\n platform: string = defaultPlatform,\n role = \"output\",\n ): DbKindCompileResult {\n const key = cacheKey(kind, platform, role, resolution.updatedAt);\n const cached = cache.get(key);\n if (cached) return cached;\n\n const source = resolution.componentSource;\n if (!source || !source.trim()) {\n const result: DbKindCompileResult = {\n ok: false,\n error: \"db-source resolution has no component_source\",\n };\n screamCompileFailure(key, kind, result.error, resolution, platform, role);\n cache.set(key, result);\n return result;\n }\n\n const allowedImports = resolveAllowedImports(\n config(resolution.config, kind),\n );\n\n const { Component, error } = ports.compile({ code: source, allowedImports });\n if (!Component || error) {\n const result: DbKindCompileResult = {\n ok: false,\n error: error ?? \"compile produced no component\",\n };\n screamCompileFailure(key, kind, result.error, resolution, platform, role);\n cache.set(key, result);\n return result;\n }\n\n // The optional props transform is its own tiny compile — a `(data) => data`\n // function (mirroring tool_ui's header_subtitle_code pattern). A broken\n // transform is LOUD but never fatal: the component still renders, fed the\n // untransformed value.\n let transform: ((data: unknown) => unknown) | null = null;\n if (resolution.propsTransform && resolution.propsTransform.trim()) {\n const { Component: transformFn, error: transformError } = ports.compile({\n code: resolution.propsTransform,\n allowedImports: [],\n });\n if (typeof transformFn === \"function\" && !transformError) {\n transform = transformFn as unknown as (data: unknown) => unknown;\n } else {\n const message = `[content-ir] props_transform for kind \"${kind}\" failed to compile — value passes through untransformed: ${transformError ?? \"no function produced\"}`;\n console.error(message);\n ports.reportError({\n source: \"content-ir\",\n message,\n raw: { kind, error: transformError },\n });\n ports.reportIncident?.({\n kind,\n errorType: \"transform_error\",\n message,\n platform,\n role,\n componentKey: resolution.componentKey,\n componentUpdatedAt: resolution.updatedAt,\n });\n }\n }\n\n const result: DbKindCompileResult = {\n ok: true,\n compiled: {\n // The injected compiler types components as\n // ComponentType<Record<string, unknown>>; the callsite always passes\n // DbKindComponentRenderProps — the single deliberate narrowing where\n // the generic compiler meets the kind contract.\n Component:\n Component as unknown as React.ComponentType<DbKindComponentRenderProps>,\n transform,\n },\n };\n cache.set(key, result);\n return result;\n }\n\n function applyPropsTransform(\n kind: string,\n compiled: CompiledDbKindComponent,\n value: unknown,\n ): unknown {\n if (!compiled.transform) return value;\n try {\n return compiled.transform(value);\n } catch (error) {\n const message = `[content-ir] props_transform for kind \"${kind}\" threw — using the untransformed value: ${\n error instanceof Error ? error.message : String(error)\n }`;\n console.error(message);\n ports.reportError({ source: \"content-ir\", message, raw: { kind } });\n ports.reportIncident?.({\n kind,\n errorType: \"transform_error\",\n message,\n stack: error instanceof Error ? (error.stack ?? null) : null,\n data: value,\n });\n return value;\n }\n }\n\n function invalidate(\n kind: string,\n platform: string = defaultPlatform,\n role = \"output\",\n ): void {\n const prefix = `${kind}${platform}${role}`;\n for (const key of [...cache.keys()]) {\n if (key.startsWith(prefix)) cache.delete(key);\n }\n for (const key of [...screamedKeys]) {\n if (key.startsWith(prefix)) screamedKeys.delete(key);\n }\n }\n\n function invalidateAll(): void {\n cache.clear();\n screamedKeys.clear();\n }\n\n const api: DbKindComponentCache = {\n getOrCompile,\n applyPropsTransform,\n config,\n invalidate,\n invalidateAll,\n };\n\n ports.registerInvalidation?.(() => invalidateAll());\n\n return api;\n}\n","\"use client\";\n\n/**\n * DbKindComponentErrorBoundary — the DEFAULT error boundary around a compiled\n * DB kind component (absorbed from matrx-frontend per the C23 retrofit; the\n * package previously shipped \"no error capture by design\", which left every\n * host to rebuild this class).\n *\n * A user-authored component that throws during render must never crash the\n * surface (chat, notes, admin preview). The boundary catches, renders the\n * fallback (the kind's generic structured viewer — the R6 disposition, never\n * a blank hole), and SCREAMS: a recovery firing means a real bug got past\n * authoring.\n *\n * `resetSignal` (the component's `updated_at`) un-latches the boundary when a\n * NEW component version arrives: an author who fixes a throwing component must\n * see the fix on the next re-render, not stay stuck on the fallback until a\n * full unmount. Without this the error state is sticky for the whole session —\n * the \"broke, then magically fixed itself minutes later\" class. React error\n * boundaries never self-clear, so a version change is the only safe signal\n * (`hasError` alone can't tell a fixed version from the same broken one).\n *\n * `onCaught` is the scream seam: a host binds its structured render-error\n * capture + durable incident filing (matrx-frontend files a `render_throw`\n * incident so the component's author learns). Bound to nothing, the default is\n * an honest console scream — never silence.\n */\nimport * as React from \"react\";\n\nexport interface DbKindComponentErrorBoundaryProps {\n kind: string;\n /** The resolved component's `updated_at`; a change means a new version. */\n resetSignal: string | null;\n fallback: React.ReactNode;\n children: React.ReactNode;\n /**\n * Where the catch lands. A host binds structured capture + incident filing\n * here; the default screams to the console. NOTE for hosts whose console\n * adapter persists `console.error`: bind this (which replaces the default)\n * rather than mirroring the capture through the console twice.\n */\n onCaught?: (\n error: Error,\n info: { componentStack: string | null },\n ) => void;\n}\n\ninterface State {\n hasError: boolean;\n /**\n * The `resetSignal` seen on the LAST render — tracked every render (not just\n * on error) so that at throw time it already holds the version that threw.\n * `getDerivedStateFromError` cannot read props, so this is how the boundary\n * knows which version to un-latch away from.\n */\n signalAtLastRender: string | null;\n}\n\nexport class DbKindComponentErrorBoundary extends React.Component<\n DbKindComponentErrorBoundaryProps,\n State\n> {\n constructor(props: DbKindComponentErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false, signalAtLastRender: props.resetSignal };\n }\n\n static getDerivedStateFromError(): Partial<State> {\n return { hasError: true };\n }\n\n static getDerivedStateFromProps(\n props: DbKindComponentErrorBoundaryProps,\n state: State,\n ): State | null {\n if (props.resetSignal === state.signalAtLastRender) return null;\n // The version changed. If we were latched on the old version, un-latch so\n // the new (hopefully fixed) component gets a fresh render attempt; either\n // way, record the new signal as the one now rendering.\n return { hasError: false, signalAtLastRender: props.resetSignal };\n }\n\n override componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {\n const info = { componentStack: errorInfo.componentStack ?? null };\n if (this.props.onCaught) {\n this.props.onCaught(error, info);\n return;\n }\n // The honest default when a host binds nothing: never silent.\n console.error(\n `[content-ir] DB kind component for \"${this.props.kind}\" threw during render — showing the fallback:`,\n error,\n );\n }\n\n override render(): React.ReactNode {\n if (this.state.hasError) return this.props.fallback;\n return this.props.children;\n }\n}\n"],"mappings":";AA2BO,IAAM,uBAA+C,CAAC,WAAW;AACtE,UAAQ,MAAM,gBAAgB,OAAO,OAAO,IAAI,OAAO,OAAO,EAAE;AAClE;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BhB,IAAM,+BAAN,cAAiD,iBAGtD;AAAA,EACA,YAAY,OAA0C;AACpD,UAAM,KAAK;AACX,SAAK,QAAQ,EAAE,UAAU,OAAO,oBAAoB,MAAM,YAAY;AAAA,EACxE;AAAA,EAEA,OAAO,2BAA2C;AAChD,WAAO,EAAE,UAAU,KAAK;AAAA,EAC1B;AAAA,EAEA,OAAO,yBACL,OACA,OACc;AACd,QAAI,MAAM,gBAAgB,MAAM,mBAAoB,QAAO;AAI3D,WAAO,EAAE,UAAU,OAAO,oBAAoB,MAAM,YAAY;AAAA,EAClE;AAAA,EAES,kBAAkB,OAAc,WAAkC;AACzE,UAAM,OAAO,EAAE,gBAAgB,UAAU,kBAAkB,KAAK;AAChE,QAAI,KAAK,MAAM,UAAU;AACvB,WAAK,MAAM,SAAS,OAAO,IAAI;AAC/B;AAAA,IACF;AAEA,YAAQ;AAAA,MACN,uCAAuC,KAAK,MAAM,IAAI;AAAA,MACtD;AAAA,IACF;AAAA,EACF;AAAA,EAES,SAA0B;AACjC,QAAI,KAAK,MAAM,SAAU,QAAO,KAAK,MAAM;AAC3C,WAAO,KAAK,MAAM;AAAA,EACpB;AACF;","names":["createContext","useContext","jsx","createContext","useContext","listeners","envelopeFromCompleteValue","readEnvelope","readObjectKind","readEnvelope","readObjectKind","envelopeFromCompleteValue","useEffect","useState","envelopeFromCompleteValue","IR_ENVELOPE_KEY","isReservedDirectiveSlug","useEffect","useState","useSyncExternalStore","nounLabel","n","text","useSyncExternalStore","jsx","jsx","jsxs","useSyncExternalStore","useState","useEffect","label","read","jsx","jsxs","directiveDisplay","jsx","jsxs","directiveDisplay","useEffect","useState","directiveDisplay","nounLabel","jsx","jsxs","directiveDisplay","nounLabel","useEffect","useState","jsx","Fragment","jsx","jsxs","isReservedDirectiveSlug","useState","useEffect","IR_ENVELOPE_KEY","envelopeFromCompleteValue","jsx","jsxs","readEnvelope","readObjectKind","jsx","jsxs","readEnvelope","readObjectKind","readObjectKind","Fragment","jsx","isRecord","readObjectKind","result","Component","React"]}
1
+ {"version":3,"sources":["../host/error-report.ts","../host/host-types.ts","../host/ContentIrProvider.tsx","../directives/directive-host.tsx","../resolver/component-resolver.ts","../route/kind-route.ts","../route/partial-kind-route.ts","../route/route-binding.ts","../react/use-kind-version.ts","../react/KindInstanceRender.tsx","../directives/DirectiveRender.tsx","../directives/DirectiveFallbackCard.tsx","../directives/ApplyDirectiveButton.tsx","../directives/item-changes.ts","../directives/record-values.ts","../directives/failure-words.ts","../directives/icons.tsx","../directives/DirectiveProvisionalCard.tsx","../directives/registry.ts","../directives/SideEffectDirectiveCard.tsx","../react/ProvisionalKindBoundary.tsx","../react/GenericStructuredView.tsx","../react/RuntimeWrapperViews.tsx","../db-component/db-kind-component-cache.ts","../db-component/DbKindComponentErrorBoundary.tsx"],"sourcesContent":["/**\n * THE SCREAM SEAM.\n *\n * Every recovery path in this package is loud: a defective component row, a\n * failed resolver load, a kind whose component throws on a provisional value.\n * The package refuses to own where those screams land — matrx-frontend routes\n * them to the Error Inspector, the dashboard to its own log, the extension to\n * its background page. Each host binds one function.\n *\n * A host that binds a no-op has chosen silence, which is a defect in itself;\n * {@link consoleErrorReporter} is the honest default.\n */\n\nexport interface ContentIrErrorReport {\n /** Always `\"content-ir\"` — hosts key their capture stores on it. */\n source: \"content-ir\";\n message: string;\n name?: string;\n stack?: string;\n /** Free-form grouping key (the host's `relation`), e.g. `\"partial-kind\"`. */\n relation?: string;\n raw?: unknown;\n}\n\nexport type ContentIrErrorReporter = (report: ContentIrErrorReport) => void;\n\n/** The default when a host binds nothing: never silent. */\nexport const consoleErrorReporter: ContentIrErrorReporter = (report) => {\n console.error(`[content-ir] ${report.message}`, report.raw ?? \"\");\n};\n","/**\n * THE HOST CONTRACT — everything this package refuses to decide.\n *\n * The kernel (`@ai-matrx/content-ir`) proved the shape: extract the portable\n * part, let host capability enter through explicit named seams. The render\n * layer needs four things it must never own:\n *\n * 1. WHERE KIND DEFINITIONS COME FROM (a bundled table, `content_ir`, a REST\n * call). The route only asks \"is this kind registered, and does it carry a\n * legacy bridge / a partial-ready opt-in\".\n * 2. WHERE COMPONENT ROWS COME FROM — {@link ComponentResolutionSource}. The\n * package ships `ComponentResolver`, which any host can construct with its\n * own loaders; a host with its own resolver only has to satisfy the type.\n * 3. HOW A ROUTED BLOCK ACTUALLY DRAWS. `applyIrKindRoute` decides a block's\n * TYPE; turning that type into pixels is the host's dispatch table\n * (matrx-frontend's `BlockRenderer`, the dashboard's small map). The\n * package never imports a component library.\n * 4. WHERE SCREAMS LAND — {@link ContentIrErrorReporter}.\n *\n * No Next.js, no Redux, no Supabase, no router, no host error capture. If a\n * seam is missing, ADD A SEAM — never an import.\n */\n\nimport type { ReactNode } from \"react\";\nimport type { KindDefinition } from \"@ai-matrx/content-ir\";\nimport type { ContentIrErrorReporter } from \"./error-report\";\nimport type { ComponentResolutionSource } from \"../resolver/component-resolution.types\";\nimport type { DirectiveHost } from \"../directives/directive-host\";\n\n/**\n * The minimum a render block must expose for the kind route to work. Hosts\n * pass their own richer block type through; the route is generic over `T` and\n * preserves every extra field.\n */\nexport interface IrRoutableBlock {\n type: string;\n serverData?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n}\n\n/** A routable block that also carries its source text (the raw region). */\nexport interface IrRenderBlock extends IrRoutableBlock {\n content: string;\n language?: string;\n}\n\n/**\n * Where registered kinds come from. `getDefinition` is the only method the\n * pure route needs; the rest drive the granular repaint and the warm-up tick\n * that keeps a cold registry from being mistaken for \"this kind has no\n * component\".\n */\nexport interface KindDefinitionSource {\n getDefinition(kind: string): KindDefinition | undefined;\n /** Monotonic per-kind version — the repaint snapshot key. */\n getKindVersion(kind: string): number;\n subscribeKind(kind: string, listener: () => void): () => void;\n /** One definition load per app session. */\n ensureWarm(): Promise<void>;\n}\n\n/**\n * The rendering seams. Everything here returns host UI; the package supplies\n * the DECISIONS and the chrome-free structure around them.\n */\nexport interface ContentIrRenderSeams {\n /**\n * Draw a block the kind route has already typed. This is the host's dispatch\n * table — the single place a component key becomes a component.\n */\n renderBlock(block: IrRenderBlock): ReactNode;\n /**\n * THE FLOOR: render ANY JSON value as a human document. Reached when a kind\n * has no render-trusted component, when the value is not an object at all,\n * and by the generic structured view.\n *\n * This is deliberately a seam and not a bundled component. Rendering a value\n * WELL means prose through the host's markdown renderer, media through the\n * host's file handler, and uniform arrays through the host's data table —\n * all of which are host property. A host that has none of those can pass a\n * `<pre>`; it will be honest, just plain.\n */\n renderValue(props: StructuredValueRenderProps): ReactNode;\n /**\n * The \"still arriving\" indicator used by the provisional frame. Optional —\n * hosts without a shimmer get plain text.\n */\n renderShimmer?(text: string): ReactNode;\n /**\n * The honest \"this shape has no custom component yet\" notice. Optional: the\n * package draws a plain amber line when a host supplies nothing, and a host\n * with an icon set or its own callout component supplies that instead. It is\n * a seam and not a bundled component because this package depends on no icon\n * library.\n */\n renderNotice?(text: string): ReactNode;\n}\n\nexport interface StructuredValueRenderProps {\n value: unknown;\n /** The kind slug this value claims, when known. Honesty line only — never a renderer choice. */\n kind?: string;\n /** Why this shape has no custom view, in human words. */\n note?: string;\n /** Show the \"what this is / raw data\" footer. Default true. */\n footer?: boolean;\n}\n\n/**\n * One host, wired once, read by every component in this package through\n * {@link ContentIrRenderProvider}.\n */\nexport interface ContentIrHost extends ContentIrRenderSeams {\n kinds: KindDefinitionSource;\n components: ComponentResolutionSource;\n reportError: ContentIrErrorReporter;\n /**\n * The `kind_component.platform` this host resolves as. \"web\" for every\n * browser UI; the column already models \"react-native\" and friends, and a\n * host that lies here renders the wrong component everywhere.\n */\n platform: string;\n /**\n * The Kind Directives seams (apply / open item / copy / noun catalog / item\n * kind). Optional: a host without them still renders every directive card,\n * apply-less and copy-less — honest chrome, never hidden content. Provided\n * to the directive tier by `ContentIrRenderProvider`; a host that has not\n * adopted the render provider mounts `DirectiveHostProvider` directly.\n */\n directives?: DirectiveHost;\n}\n\n/**\n * The pure route's dependencies — a strict subset of {@link ContentIrHost},\n * because `applyIrKindRoute` is called OUTSIDE React (reducers, stream\n * accumulators, tests) where there is no provider to read.\n */\nexport interface KindRouteEnv {\n kinds: Pick<KindDefinitionSource, \"getDefinition\">;\n /**\n * `hasSettled` is optional and read ONLY to suppress a negative verdict from\n * a registry that has not loaded yet — see THE COLD-VERDICT RULE on\n * `ComponentResolutionSource`.\n */\n components: Pick<ComponentResolutionSource, \"resolve\"> &\n Partial<Pick<ComponentResolutionSource, \"hasSettled\">>;\n reportError: ContentIrErrorReporter;\n platform: string;\n}\n\n/** Narrow a host (or anything host-shaped) to what the pure route needs. */\nexport function routeEnvOf(host: ContentIrHost): KindRouteEnv {\n return {\n kinds: host.kinds,\n components: host.components,\n reportError: host.reportError,\n platform: host.platform,\n };\n}\n","\"use client\";\n\n/**\n * The one place a host is wired in. Everything React in this package reads its\n * capability from here — no module singleton, no import into an app.\n *\n * A host mounts this ONCE, high enough that every kind-rendering surface is\n * inside it:\n *\n * ```tsx\n * <ContentIrRenderProvider host={matrxContentIrHost}>\n * <App />\n * </ContentIrRenderProvider>\n * ```\n *\n * Reading it outside a provider THROWS rather than falling back to a default.\n * A silent default would render the wrong component for every kind in the app\n * and look like a data problem for weeks.\n */\n\nimport { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type { ContentIrHost, KindRouteEnv } from \"./host-types\";\nimport { routeEnvOf } from \"./host-types\";\nimport { DirectiveHostProvider } from \"../directives/directive-host\";\n\nconst ContentIrHostContext = createContext<ContentIrHost | null>(null);\n\nexport interface ContentIrRenderProviderProps {\n host: ContentIrHost;\n children: ReactNode;\n}\n\nexport function ContentIrRenderProvider({\n host,\n children,\n}: ContentIrRenderProviderProps) {\n return (\n <ContentIrHostContext.Provider value={host}>\n <DirectiveHostProvider host={host.directives ?? {}}>{children}</DirectiveHostProvider>\n </ContentIrHostContext.Provider>\n );\n}\n\n/**\n * The wired host, or null. For the rare consumer that can legitimately run\n * without a provider because it was handed its sources explicitly (see\n * `useContentIrKindVersion`). Everything else uses {@link useContentIrHost}.\n */\nexport function useContentIrHostOrNull(): ContentIrHost | null {\n return useContext(ContentIrHostContext);\n}\n\n/** The wired host. Throws outside a provider — see the module doc. */\nexport function useContentIrHost(): ContentIrHost {\n const host = useContentIrHostOrNull();\n if (!host) {\n throw new Error(\n \"[content-ir-react] No ContentIrRenderProvider above this component. \" +\n \"Mount one at the app root with your host adapter (kind definitions, \" +\n \"component resolver, renderBlock, renderValue, reportError).\",\n );\n }\n return host;\n}\n\n/** The wired host narrowed to what the pure route functions take. */\nexport function useKindRouteEnv(): KindRouteEnv {\n const host = useContentIrHost();\n return useMemo(() => routeEnvOf(host), [host]);\n}\n","\"use client\";\n\n/**\n * THE DIRECTIVE HOST CONTRACT — what the directive tier refuses to decide.\n *\n * The package owns the DECISIONS (decode → renderer → card → floor, the\n * position law, never-null rendering) and the card itself. Four things stay\n * host property and enter through named seams:\n *\n * 1. APPLYING a side-effect directive — `POST /directives/confirm` as the\n * user, with the host's auth and base URL. Absent → the Apply control is\n * ABSENT (honest), never a dead button.\n * 2. OPENING an item to read it before approving — a window panel, a dialog,\n * a route. Absent → items are not clickable.\n * 3. COPY controls — host chrome (matrx-frontend's CopyButtons). Absent → none.\n * 4. The NOUN catalog + item-kind lookup — server-derived tables the host\n * mirrors (or reads from its kind catalog's `items` edges).\n * 5. ASKING (`ask`), NAMING a record (`renderRecord`), and READING the ledger\n * (`applyState`) — the consequence before the click, the doors, and the\n * state that survives a reload.\n *\n * A host that has adopted `ContentIrRenderProvider` passes `directives` on its\n * ContentIrHost; a host that has NOT (Workflow Studio, 2026-09-08) mounts\n * `DirectiveHostProvider` alone — the directive tier never requires the full\n * render host, because a chat bubble must be able to draw a directive card\n * identically everywhere, today.\n */\n\nimport { createContext, useContext, type ReactNode } from \"react\";\nimport type {\n DecodedDirective,\n DirectiveItemKindLookup,\n DirectiveNounCatalog,\n} from \"@ai-matrx/content-ir\";\n\nexport interface DirectiveApplyResult {\n applied: number;\n failed: number;\n /**\n * The server's own receipt sentence (\"Deleted task “Ship it”.\"), shown in\n * place of a bare count. Never composed client-side.\n */\n message?: string | null;\n /**\n * The records the apply created or changed, so the tally is a way IN to them\n * (no dead ends). Rendered through `renderRecord`; absent → the sentence alone.\n */\n records?: DirectiveRecordRef[];\n /**\n * For an UPDATE: what each item's fields held just BEFORE the write, by item\n * index (`null` for an item the server did not record). The card draws the\n * applied change from this record — never from a live re-read, which after the\n * apply answers the NEW value (G6A review, 2026-10-02: \"(no change)\" for a\n * change that happened).\n */\n before?: ReadonlyArray<Record<string, unknown> | null>;\n}\n\n/**\n * What the server's action ledger says about ONE block, read on mount so a\n * reloaded page never offers \"Apply\" for work that already ran (reviewer\n * defect 5, 2026-10-02).\n *\n * - `not_applied` — still to do (or partly done: the batch re-applies, and the\n * server replays the members it already holds). The card offers Apply.\n * - `in_flight` — another request is applying it right now. The card says it\n * is finishing and asks again shortly; it offers neither Apply nor a tally.\n * - `applied` — the ledger holds every item. The card shows the tally exactly\n * as a fresh apply would: the ledger's own sentence and the records, as doors.\n */\nexport interface DirectiveApplyState {\n state: \"not_applied\" | \"in_flight\" | \"applied\";\n /** The ledger row's sentence (\"Created task.\"), never composed client-side. */\n message?: string | null;\n /**\n * The records the LATEST apply wrote — the tally's doors. After \"Run again\"\n * that is the newest copy, never the first.\n */\n records?: DirectiveRecordRef[];\n /**\n * How many times the ledger holds this block as applied: 1 for the original,\n * one more for every \"Run again\". Absent → 1. A create that ran twice made\n * two records, and the card says so (reviewer, 2026-10-02).\n */\n copies?: number;\n /**\n * For an applied UPDATE: each item's replaced values, by item index, from the\n * ledger row (`null` where the ledger has none — a row from before 2026-10-02).\n * Absent → the card says only what each field was set to.\n */\n before?: ReadonlyArray<Record<string, unknown> | null>;\n}\n\n/** One record a directive names: the noun it is, and its id. */\nexport interface DirectiveRecordRef {\n noun: string;\n id: string;\n}\n\nexport interface DirectiveRecordProps extends DirectiveRecordRef {\n /**\n * What to show until (or unless) the host resolves the live name —\n * \"Task 1a2b3c4d\". Never blank, never \"Item\".\n */\n fallback: string;\n /** Where it is drawn: an item row, the confirm dialog, or the applied tally. */\n context: \"row\" | \"dialog\" | \"applied\";\n /**\n * True when the record is (about to be) in the trash — the host may still\n * name it but should not promise it opens as a live record.\n */\n trashed?: boolean;\n}\n\n/** What the person is being asked to approve — everything the card knows. */\nexport interface DirectiveAskRequest {\n directive: DecodedDirective;\n /** The items, exactly as they will be sent. */\n items: Record<string, unknown>[];\n /** The noun's human label (\"Task\"), from the host's catalog when it has one. */\n nounLabel: string;\n /**\n * True for \"Run again\": the ledger already holds this block, and a yes runs\n * it a SECOND time (`force`) — another copy for a create, the same fields\n * written again for an update, another delete for a restored record. The\n * question must say so.\n */\n again?: boolean;\n}\n\n/**\n * The shell a card hands its host — the two keys, plus WHERE it sits.\n *\n * `conversationId` is the conversation the card renders in (a chat message),\n * absent in a person's own content (a note). It is the idempotency NAMESPACE:\n * a card in an agent's message must apply under the SAME key as that\n * proposal's Approve button, or the one action could run twice.\n */\nexport interface DirectiveShell {\n __kind: string;\n items: Record<string, unknown>[];\n conversationId?: string;\n /** \"Run again\": skip the ledger's dedup and apply a second time. */\n force?: boolean;\n}\n\nexport interface DirectiveOpenItemOptions {\n /** The item, `__kind`-stamped when the shape has an item kind. */\n item: Record<string, unknown>;\n /** The content-IR kind this item IS, or null when the shape has none. */\n itemKind: string | null;\n /** What the item is called — the same title the card shows. */\n title: string;\n /** \"Run Create agent definition · item 1 of 1\". */\n subtitle: string | null;\n directive: DecodedDirective;\n index: number;\n total: number;\n}\n\nexport interface DirectiveCopyProps {\n /**\n * What the control is called to a screen reader. Never an id: for a record it\n * is type-generic (\"this task\"); a host with the record's live name replaces\n * it through `record`.\n */\n label: string;\n /** The existing record this control copies, when it copies one — to name it. */\n record?: DirectiveRecordRef;\n /** The value to copy — the whole shell or one item. */\n value: unknown;\n /** The item's kind, when copying an item. */\n kind?: string | null;\n size: \"icon\" | \"xs\";\n}\n\nexport interface DirectiveHost {\n /**\n * Apply a side-effect directive as the user (the server re-validates every\n * item against the registered model and runs the ONE handler; idempotent).\n * Reject with an Error whose message is safe to show.\n */\n confirm?: (shell: DirectiveShell) => Promise<DirectiveApplyResult>;\n /**\n * Ask the person BEFORE anything runs, naming the consequence (the records,\n * what changes). Resolve `true` to go ahead, `false` to leave the card as it\n * was. The Apply control stays idle while this is open — nothing reads as\n * \"applying\" until the person has said yes. Absent → `confirm` is called\n * directly (a host that asks inside `confirm` keeps working, but its card\n * will read \"Applying…\" while its dialog is up).\n */\n ask?: (request: DirectiveAskRequest) => Promise<boolean>;\n /**\n * Has this exact block already been applied? Read ONCE when the card mounts\n * (and again while the answer is `in_flight`), so the card survives a reload:\n * the server ledger, not component state, is what knows. The identity is the\n * server's (it hashes the validated items in the same namespace `confirm`\n * applies in), so a host asks — it never computes. Batch on the host side if\n * a page carries many cards. Reject with an Error when the ledger cannot be\n * read: the card reports it and offers Apply, which is safe because `confirm`\n * is idempotent. Absent → the card starts at Apply, as before.\n */\n applyState?: (shell: DirectiveShell) => Promise<DirectiveApplyState>;\n /**\n * Read the CURRENT values of ONE existing record, so an update says what it\n * replaces — \"Status open → done\", never just \"→ done\" (reviewer,\n * 2026-10-02). Resolve `null` when the record cannot be read (no access, no\n * such record, a noun the host cannot read); reject only for a real failure.\n * Absent → an update row shows the new values alone, as before.\n */\n readRecord?: (ref: DirectiveRecordRef) => Promise<Record<string, unknown> | null>;\n /**\n * Draw ONE existing record by its live name, as a way to open it. Used on\n * update/delete rows (the record that will change), in the host's own ask\n * dialog if it likes, and on the applied tally (what was written). Absent →\n * the fallback text, unlinked.\n */\n renderRecord?: (props: DirectiveRecordProps) => ReactNode;\n /** Open ONE item to read it properly before approving the write. */\n openItem?: (options: DirectiveOpenItemOptions) => void;\n /** Host copy controls. */\n renderCopy?: (props: DirectiveCopyProps) => ReactNode;\n /**\n * The app's word for one stored value of one pick-list field — the SAME word\n * the record's own screens and the write forms show (\"incomplete\" on a task\n * reads \"Inbox\"). One value, one display word everywhere (G8A review,\n * 2026-10-02: the card said \"Status incomplete → completed\"). Return null for\n * a field that is not a pick-list: its value is shown as written. Absent →\n * every value is shown as stored.\n */\n valueLabel?: (ref: DirectiveValueRef) => string | null;\n /** The mirrored noun catalog (label / family / title column). */\n nouns?: DirectiveNounCatalog;\n /** slug → the kind ONE item is (THE DIRECTIVE⇄KIND SEAM), or null. */\n itemKind?: DirectiveItemKindLookup;\n /** Where a decode failure or an unhonourable shell is reported. Default: console.error. */\n reportError?: (message: string) => void;\n /**\n * Plain words for a failed apply the host recognises (\"This button can't\n * create a task yet.\" + \"Create it from Tasks instead.\"). The card never shows\n * the server's raw text as its sentence: it shows these words — or its own\n * verb-aware default — and keeps the raw text behind \"Details\". Return null\n * to use the default.\n */\n explainFailure?: (failure: DirectiveFailure) => DirectiveFailureWords | null;\n}\n\n/** One stored value of one field of one record type. */\nexport interface DirectiveValueRef {\n noun: string;\n field: string;\n value: string;\n}\n\n/** One failed apply, as the card knows it. */\nexport interface DirectiveFailure {\n /** The server's / host's own text — technical; shown only behind Details. */\n raw: string;\n directiveClass: string;\n noun: string;\n /** The noun's display label (\"Task\"). */\n nounLabel: string;\n /** Items that failed, when some applied and some did not. */\n failed?: number;\n /** Items in the block. */\n total?: number;\n}\n\n/** What failed and what to do — each one short sentence. */\nexport interface DirectiveFailureWords {\n what: string;\n next: string;\n /**\n * The text behind \"Details\", when the host words it (e.g. the server's field\n * names read as the form labels them — \"Title is required\", never\n * \"name is required\"). Absent → the raw text.\n */\n details?: string;\n}\n\nconst DirectiveHostContext = createContext<DirectiveHost | null>(null);\n\n/** Where a directive renders — today, the conversation it sits in (if any). */\nexport interface DirectiveScope {\n conversationId?: string | null;\n}\n\nconst DirectiveScopeContext = createContext<DirectiveScope>({});\n\n/**\n * Tell every card below WHERE it renders. A host draws a chat message's\n * directives inside one of these (or passes `conversationId` to\n * `DirectiveRender`), so the card applies in that conversation's namespace —\n * the same key the agent's proposal approves under. A note mounts none.\n */\nexport function DirectiveScopeProvider({\n conversationId,\n children,\n}: DirectiveScope & { children: ReactNode }) {\n return (\n <DirectiveScopeContext.Provider value={{ conversationId: conversationId ?? null }}>\n {children}\n </DirectiveScopeContext.Provider>\n );\n}\n\nexport function useDirectiveScope(): DirectiveScope {\n return useContext(DirectiveScopeContext);\n}\n\nexport interface DirectiveHostProviderProps {\n host: DirectiveHost;\n children: ReactNode;\n}\n\nexport function DirectiveHostProvider({ host, children }: DirectiveHostProviderProps) {\n return <DirectiveHostContext.Provider value={host}>{children}</DirectiveHostContext.Provider>;\n}\n\nconst EMPTY_HOST: DirectiveHost = {};\n\n/**\n * The wired directive host. Unlike the render host this does NOT throw when\n * unwired: a directive still renders (named, itemised, copy-less, apply-less)\n * — degrading the chrome is honest, hiding the content is not.\n */\nexport function useDirectiveHost(): DirectiveHost {\n return useContext(DirectiveHostContext) ?? EMPTY_HOST;\n}\n","/**\n * The Shape System component RESOLVER (rulings R1 + R6): (kind, platform,\n * role) → component, with two tiers:\n *\n * - eager: a COMPILED bootstrap the host ships in its bundle — the\n * trusted-at-boot floor, available at import so the render seam can gate\n * synchronously from the first streamed byte.\n * - warm: one `content_ir.kind_component` list fetch per app session\n * (`ensureWarm`). A DB row for a (kind, platform, role) OVERRIDES the\n * compiled entry once warm; the compiled floor keeps answering until then\n * (and forever, on DB failure).\n *\n * Resolution is SYNCHRONOUS (the render seam calls it per block); the only\n * async work is the loading, off the render path.\n *\n * WHAT MOVED AND WHY. This class was matrx-frontend's `ComponentRegistry`. It\n * is a large part of why a second UI could not render a kind: every tier rule,\n * every repaint counter, every dedupe latch lived in one app. Nothing about it\n * is Next.js, Redux, or Supabase — the only host-specific parts were the two\n * loaders and the error sink, which are now constructor arguments.\n */\n\nimport type { ContentIrErrorReporter } from \"../host/error-report\";\nimport { consoleErrorReporter } from \"../host/error-report\";\nimport type {\n ComponentResolution,\n ComponentResolutionSource,\n ComponentRole,\n KindComponentRow,\n SystemComponentEntry,\n} from \"./component-resolution.types\";\n\nexport interface ComponentResolverOptions {\n /**\n * The compiled bootstrap, as a THUNK resolved on first use: a host's system\n * component table is often mid-initialization when this module evaluates\n * (matrx-frontend's registry cluster has a deliberate import cycle).\n */\n compiledEntries?: () => SystemComponentEntry[];\n /** The warm/refresh list load — every `kind_component` row the user may see. */\n loadAll?: () => Promise<KindComponentRow[]>;\n /** The eager single-kind load fired the moment a kind is identified mid-stream. */\n loadForKind?: (kind: string, platform: string) => Promise<KindComponentRow[]>;\n /** Where recovery screams land. Defaults to `console.error`, never silence. */\n reportError?: ContentIrErrorReporter;\n /** Clock seam — the refresh rate limiter. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/** Unit separator — a character no kind slug, platform, or role can contain. */\nconst KEY_SEPARATOR = String.fromCharCode(1);\n\nfunction keyOf(kind: string, platform: string, role: string): string {\n return `${kind}${KEY_SEPARATOR}${platform}${KEY_SEPARATOR}${role}`;\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Error-shaped fields, spread-safe under `exactOptionalPropertyTypes`. */\nfunction errorFields(error: unknown): { name?: string; stack?: string } {\n if (!(error instanceof Error)) return {};\n return {\n name: error.name,\n ...(error.stack === undefined ? {} : { stack: error.stack }),\n };\n}\n\n/**\n * Warm-load retry backoff. Sized for the auth-hydration race: a fresh tab's\n * first list load can run before the Supabase session restores and fail with\n * a permission error; the session is typically live within a second or two,\n * so the first retry usually completes the load. After the last delay the\n * resolver settles on whatever it has — see the failure branch in ensureWarm.\n */\nconst WARM_RETRY_DELAYS_MS: readonly number[] = [1_000, 5_000, 15_000];\n\nexport class ComponentResolver implements ComponentResolutionSource {\n private compiled: Map<string, SystemComponentEntry> | null = null;\n private readonly db = new Map<string, KindComponentRow>();\n private warmPromise: Promise<void> | null = null;\n /** Consecutive warm-load failures — indexes WARM_RETRY_DELAYS_MS. */\n private warmFailures = 0;\n private warmRetryTimer: ReturnType<typeof setTimeout> | null = null;\n /**\n * True once a list load has RUN TO COMPLETION (success or failure), or once\n * any rows have been ingested by any tier. Until then `resolve()` answering\n * null means \"I have not looked yet\" — never \"no such component\". See THE\n * COLD-VERDICT RULE on `ComponentResolutionSource.hasSettled`.\n */\n private settled = false;\n /**\n * When the last successful wholesale refresh landed, or null for \"never\".\n * Explicitly nullable rather than 0: with a host-supplied clock that starts\n * near zero, a `0` sentinel makes the FIRST refresh look rate-limited and\n * silently skip.\n */\n private lastRefreshAt: number | null = null;\n private refreshPromise: Promise<void> | null = null;\n private readonly listeners = new Set<() => void>();\n /**\n * Cold single-kind fetch dedupe (streaming eager path). In-flight is keyed\n * by (kind, platform) — the fetch unit; misses are keyed by (kind, platform,\n * role) so a miss on web/output never suppresses other roles, and CLEARED on\n * every wholesale refresh (a component created mid-session becomes eagerly\n * fetchable again — misses are cheap to re-verify).\n */\n private readonly coldInFlight = new Set<string>();\n private readonly coldMisses = new Set<string>();\n /** Monotonic db-tier version — the repaint hook's snapshot key. */\n private version = 0;\n /** Per-kind versions + listeners (granular repaint) + wholesale epoch. */\n private readonly kindVersions = new Map<string, number>();\n private readonly kindListeners = new Map<string, Set<() => void>>();\n private epoch = 0;\n\n private readonly reportError: ContentIrErrorReporter;\n private readonly now: () => number;\n\n private readonly options: ComponentResolverOptions;\n\n // Explicit field, not a parameter property: consumers compile this source\n // directly, and a strict host (the dashboard) sets `erasableSyntaxOnly`,\n // under which parameter properties are a hard error.\n constructor(options: ComponentResolverOptions = {}) {\n this.options = options;\n this.reportError = options.reportError ?? consoleErrorReporter;\n this.now = options.now ?? (() => Date.now());\n }\n\n private compiledMap(): Map<string, SystemComponentEntry> {\n if (!this.compiled) {\n this.compiled = new Map();\n for (const entry of this.options.compiledEntries?.() ?? []) {\n this.compiled.set(keyOf(entry.kind, entry.platform, entry.role), entry);\n }\n }\n return this.compiled;\n }\n\n /**\n * Synchronous resolve — the render seam's per-block call. DB override first\n * (once warm), compiled floor second, null for unknown.\n */\n resolve(\n kind: string,\n platform: string,\n role: ComponentRole,\n ): ComponentResolution | null {\n const key = keyOf(kind, platform, role);\n\n const dbRow = this.db.get(key);\n if (dbRow) {\n return {\n componentKey: dbRow.componentKey,\n source: dbRow.source,\n config: dbRow.config,\n isActive: dbRow.isActive,\n resolvedBy: \"db\",\n componentSource: dbRow.componentSource,\n propsTransform: dbRow.propsTransform,\n hasComponentSource:\n dbRow.hasComponentSource ??\n Boolean(dbRow.componentSource && dbRow.componentSource.trim()),\n pinnedKindVersion: dbRow.pinnedKindVersion,\n updatedAt: dbRow.updatedAt,\n createdBy: dbRow.createdBy,\n };\n }\n\n const compiledEntry = this.compiledMap().get(key);\n if (compiledEntry) {\n return {\n componentKey: compiledEntry.componentKey,\n source: compiledEntry.source,\n config: compiledEntry.config,\n isActive: true, // trusted at bootstrap (R6)\n resolvedBy: \"compiled\",\n componentSource: null,\n propsTransform: null,\n hasComponentSource: false,\n pinnedKindVersion: null,\n updatedAt: null,\n createdBy: null,\n };\n }\n\n return null;\n }\n\n /** R6 floor check: compiled-bootstrap membership = always render-trusted. */\n hasCompiled(kind: string, platform: string, role: ComponentRole): boolean {\n return this.compiledMap().has(keyOf(kind, platform, role));\n }\n\n /**\n * Pure ingest — the warm landing point and the unit-test seam. First row per\n * key wins: rows arrive is_default-first / sort_order-asc from the source.\n */\n ingestDbRows(rows: readonly KindComponentRow[]): void {\n const wasSettled = this.hasSettled();\n const changedKinds = new Set<string>();\n for (const row of rows) {\n const key = keyOf(row.kind, row.platform, row.role);\n if (!this.db.has(key)) {\n this.db.set(key, row);\n changedKinds.add(row.kind);\n }\n }\n // Warm/cold ingest is a resolver-tier change the render seam must see — a\n // db component landing AFTER a region finalized re-runs the route via the\n // repaint hook. Per-kind bumps keep the repaint granular.\n // The first rows settle the tier (hasSettled): every waiting kind hears it,\n // ONCE — the epoch covers the ingested kinds too.\n if (!wasSettled && this.hasSettled()) {\n this.notifySettled();\n return;\n }\n if (changedKinds.size > 0) {\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\n }\n\n /**\n * Mark the tier settled. THE COLD-VERDICT RULE held every block whose kind\n * the tier could not answer; settling changes that verdict for ALL of them,\n * so the flip bumps the epoch and calls every per-kind listener (as a\n * wholesale replace does). Before 0.13.0 a settle notified only kinds that\n * gained rows, and a waiting block for any other kind kept its pre-settle\n * rendering until something unrelated re-rendered it.\n */\n private markSettled(): void {\n const wasSettled = this.hasSettled();\n this.settled = true;\n if (!wasSettled) this.notifySettled();\n }\n\n private notifySettled(): void {\n this.epoch += 1;\n for (const set of this.kindListeners.values()) {\n for (const listener of set) listener();\n }\n this.notifyChanged();\n }\n\n /**\n * Refresh landing point: REPLACE the db tier wholesale (same\n * first-row-per-key contract as {@link ingestDbRows}) so edits, deletions,\n * and is_active flips all take effect. Always notifies.\n */\n replaceDbRows(rows: readonly KindComponentRow[]): void {\n // A wholesale replace IS a completed list load — the refresh landing\n // point, and the seam tests use to declare \"the list loaded\". Settling\n // here keeps THE COLD-VERDICT RULE from holding blocks forever in any\n // host that warms through refresh() rather than ensureWarm().\n this.settled = true;\n this.db.clear();\n // Wholesale invalidation: every recorded miss is stale (a component\n // created mid-session must become eagerly fetchable again).\n this.coldMisses.clear();\n for (const row of rows) {\n const key = keyOf(row.kind, row.platform, row.role);\n if (!this.db.has(key)) this.db.set(key, row);\n }\n // A wholesale replace ALWAYS notifies (deletions/flips count too), and\n // bumps the epoch so EVERY per-kind subscriber re-snapshots.\n this.epoch += 1;\n for (const set of this.kindListeners.values()) {\n for (const listener of set) listener();\n }\n this.notifyChanged();\n }\n\n getVersion(): number {\n return this.version;\n }\n\n getKindVersion(kind: string): number {\n return this.epoch + (this.kindVersions.get(kind) ?? 0);\n }\n\n subscribeKind(kind: string, listener: () => void): () => void {\n const set = this.kindListeners.get(kind) ?? new Set<() => void>();\n set.add(listener);\n this.kindListeners.set(kind, set);\n return () => {\n set.delete(listener);\n if (set.size === 0) this.kindListeners.delete(kind);\n };\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n private bumpKind(kind: string): void {\n this.kindVersions.set(kind, (this.kindVersions.get(kind) ?? 0) + 1);\n const listeners = this.kindListeners.get(kind);\n if (listeners) for (const listener of listeners) listener();\n }\n\n private notifyChanged(): void {\n this.version += 1;\n for (const listener of this.listeners) listener();\n }\n\n /**\n * A warm metadata shell is resolved enough for routing, but not for the\n * host's db-component renderer. Its body must still come from the cold\n * single-kind loader.\n */\n private needsColdFetch(\n kind: string,\n platform: string,\n role: ComponentRole,\n ): boolean {\n const resolution = this.resolve(kind, platform, role);\n return (\n resolution === null ||\n (resolution.resolvedBy === \"db\" &&\n resolution.hasComponentSource &&\n resolution.componentSource === null)\n );\n }\n\n /**\n * Cold rows are the authoritative heavy form of warm metadata shells. Keep\n * the same first-row-per-key winner contract, but replace an existing shell\n * so `componentSource` / `propsTransform` can land and repaint the kind.\n */\n private ingestColdRows(rows: readonly KindComponentRow[]): void {\n const winners = new Map<string, KindComponentRow>();\n for (const row of rows) {\n const key = keyOf(row.kind, row.platform, row.role);\n if (!winners.has(key)) winners.set(key, row);\n }\n if (winners.size === 0) return;\n\n const changedKinds = new Set<string>();\n for (const [key, row] of winners) {\n this.db.set(key, row);\n changedKinds.add(row.kind);\n }\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\n\n /**\n * The eager lightweight single-kind fetch (streaming path): the moment a\n * cloud kind is identified mid-stream, pull ONLY that kind's resolver rows\n * and ingest them so {@link resolve} can answer before — or shortly after —\n * the region completes. Deduped in-flight and by known-miss. Fire-and-forget;\n * failures are loud (the warm list remains the backstop).\n */\n requestComponent(kind: string, platform: string, role: ComponentRole): void {\n const loadForKind = this.options.loadForKind;\n if (!loadForKind) return;\n if (!this.needsColdFetch(kind, platform, role)) return;\n const missKey = keyOf(kind, platform, role);\n const flightKey = `${kind}${KEY_SEPARATOR}${platform}`;\n if (this.coldInFlight.has(flightKey) || this.coldMisses.has(missKey)) {\n return;\n }\n this.coldInFlight.add(flightKey);\n const versionBefore = this.kindVersions.get(kind) ?? 0;\n\n void (async () => {\n try {\n this.ingestColdRows(await loadForKind(kind, platform));\n // Record the miss for exactly the requested (kind, platform, role) —\n // rows may exist for OTHER roles on this platform; those must not be\n // suppressed, and this one must not be re-fetched until a refresh.\n if (this.needsColdFetch(kind, platform, role)) {\n this.coldMisses.add(missKey);\n }\n } catch (error) {\n this.reportError({\n source: \"content-ir\",\n message: `component-resolver cold fetch failed for \"${kind}\": ${describe(error)}`,\n ...errorFields(error),\n raw: error,\n });\n } finally {\n this.coldInFlight.delete(flightKey);\n // The kind's single-kind fetch answered (rows, a miss, or a failure):\n // a block waiting on THIS kind re-routes now. A landing already bumped\n // inside ingestColdRows; a miss or failure changed nothing in the\n // tier, but the waiting block must still be told to re-ask.\n if ((this.kindVersions.get(kind) ?? 0) === versionBefore) {\n this.bumpKind(kind);\n }\n }\n })();\n }\n\n /**\n * Refresh-on-view: re-fetch the warm list and REPLACE the db tier, so an\n * edited `source='db'` component (its `updated_at` bump re-keys the host's\n * compile cache) renders fresh on the next view. Deduped in-flight and\n * rate-limited by `maxAgeMs` (default 10s) — mounting several previews costs\n * one fetch. Server-side edits do NOT push to open clients; the contract is\n * refresh-on-view via this call.\n */\n refresh(maxAgeMs = 10_000): Promise<void> {\n const loadAll = this.options.loadAll;\n if (!loadAll) return Promise.resolve();\n if (this.refreshPromise) return this.refreshPromise;\n if (\n this.lastRefreshAt !== null &&\n this.now() - this.lastRefreshAt < maxAgeMs\n ) {\n return Promise.resolve();\n }\n // Any refresh intent invalidates recorded misses immediately (also cleared\n // in replaceDbRows when the fetch lands) — cheap to re-verify.\n this.coldMisses.clear();\n\n this.refreshPromise = loadAll()\n .then((rows) => {\n this.lastRefreshAt = this.now();\n this.replaceDbRows(rows);\n })\n .catch((error: unknown) => {\n // Loud recovery: the current tier keeps answering; a refresh failure is\n // a real defect (same posture as the warm loader).\n this.reportError({\n source: \"content-ir\",\n message: `component-resolver refresh failed (current resolver tier still serving): ${describe(error)}`,\n ...errorFields(error),\n raw: error,\n });\n })\n .finally(() => {\n this.refreshPromise = null;\n });\n return this.refreshPromise;\n }\n\n /** One list fetch per app session; failed loads retry on the next call. */\n ensureWarm(): Promise<void> {\n const loadAll = this.options.loadAll;\n if (!loadAll) return Promise.resolve();\n if (!this.warmPromise) {\n this.warmPromise = loadAll()\n .then((rows) => {\n this.ingestDbRows(rows);\n this.markSettled();\n this.warmFailures = 0;\n if (this.warmRetryTimer) {\n clearTimeout(this.warmRetryTimer);\n this.warmRetryTimer = null;\n }\n })\n .catch((error: unknown) => {\n // The host owns presentation and severity through reportError. A\n // direct console.error here duplicates that report and prevents a\n // host from classifying a still-serving compiled fallback as a\n // recoverable warning.\n const message = `component-resolver warm load failed (compiled bootstrap still serving): ${describe(error)}`;\n this.reportError({\n source: \"content-ir\",\n message,\n ...errorFields(error),\n raw: error,\n });\n this.warmPromise = null;\n // 🚨 A FAILED load is NOT truth (2026-08-31). The 0.9.0 posture —\n // \"a failed load still settles\" — turned the auth-hydration race\n // into a lie: a fresh tab fires this load BEFORE the Supabase\n // session hydrates, the read runs as `anon`, RLS answers\n // 42501 permission denied, and settling on that failure declared an\n // EMPTY resolver to be the loaded state of the world. Every kind on\n // the page then routed to the generic floor as \"unregistered\" —\n // while the same rows were one authenticated retry away. So: retry\n // with backoff, and settle only when retries are exhausted (the\n // backend really is down; the generic floor + the per-attempt\n // scream above are then the honest, announced stand-in).\n this.warmFailures += 1;\n const delay =\n WARM_RETRY_DELAYS_MS[this.warmFailures - 1] ?? null;\n if (delay === null) {\n this.markSettled();\n } else if (!this.warmRetryTimer) {\n this.warmRetryTimer = setTimeout(() => {\n this.warmRetryTimer = null;\n void this.ensureWarm();\n }, delay);\n }\n });\n }\n return this.warmPromise;\n }\n\n /** @see ComponentResolutionSource.hasSettled */\n hasSettled(): boolean {\n // No list loader configured = nothing to wait for: the compiled floor IS\n // the complete truth for this resolver, so it is settled from birth. (A\n // host that never wired a loader must not have every block held forever.)\n if (!this.options.loadAll) return true;\n return this.settled || this.db.size > 0;\n }\n}\n","/**\n * THE KIND ROUTE — the render flip, as a pure block transform.\n *\n * A block whose `metadata.__ir` envelope resolved a REGISTERED kind is routed\n * to that kind's component: via the legacy-bridge facet (`legacyBlockType` +\n * `toLegacyServerData`) when the kind has one, so the block enters the host's\n * existing renderer as its real type with envelope-derived serverData;\n * otherwise via the component resolver. Blocks with no envelope, an\n * unregistered kind, or no bridge facet pass through UNTOUCHED — the strangler\n * seam.\n *\n * This is where a bare/fenced JSON flashcard_set — which a text detector could\n * only ever call \"code\" — becomes real flashcards, live while streaming.\n *\n * PORTABILITY. This function was matrx-frontend's `react/kind-route.ts` and is\n * the single most-copied thing in the system: every UI that renders a kind has\n * to make exactly these decisions in exactly this order, and a second\n * implementation of them is a guaranteed divergence. It takes its registries,\n * its platform, and its error sink as an {@link KindRouteEnv} argument rather\n * than importing them, so it is callable from a reducer, a stream accumulator,\n * a test, or a React render — in any app.\n *\n * Semantics: `matrx-frontend/features/content-ir/docs/SHAPE_SYSTEM.md`\n * (registry, dual gate, `kind_component` resolution, rulings R1 + R6).\n */\n\nimport {\n envelopeFromCompleteValue,\n isReservedDirectiveSlug,\n readEnvelope,\n readObjectKind,\n} from \"@ai-matrx/content-ir\";\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-react.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/** 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 /**\n * The slug is not in the registry at all (typo, foreign emitter, a shape\n * not yet created). Routed anyway — Arman's 2026-08-29 ruling: a root\n * `__kind` key means the kind system owns the render, no exceptions. The\n * repair is creating/registering the shape (or fixing the slug).\n */\n | \"unregistered\";\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 const componentsSettled = env.components.hasSettled?.() ?? true;\n if (!componentsSettled && !resolution && !def) 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 if (envelope.root.kindState === \"raw\") {\n return routeToGeneric(\n block,\n def || resolution ? \"broken-instance\" : \"unregistered\",\n );\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 // A kind slug the platform has NO definition for (a typo, a foreign\n // emitter, a not-yet-created shape). 🚨 Arman's ruling, 2026-08-29: a root\n // `__kind` key means the kind system owns the render — NO exceptions. The\n // old strangler carve-out (\"not ours to claim\", teaching content stayed a\n // raw code block) is retired: an unregistered kind renders through the\n // generic floor with `reason: \"unregistered\"`, so the reader always sees\n // the payload acknowledged AS a kind instance with what is known about it.\n // A repaint hook upgrades this block the moment the registries learn the\n // kind.\n return routeToGeneric(block, \"unregistered\");\n}\n\n/**\n * Rehydration route for STRUCTURED persisted artifacts.\n *\n * A materialized kind artifact stores its zero-loss value object (carrying\n * `__kind`) alongside its row. Given that stored value, derive the registered\n * kind's legacy `serverData` WITHOUT re-parsing any text: the value wraps into\n * a complete envelope and runs through the same `toLegacyServerData` bridge the\n * live stream uses. Returns null for non-objects, unregistered kinds, or kinds\n * without a legacy bridge — callers fall back to their string-payload path.\n */\nexport function kindServerDataFromStoredValue(\n value: unknown,\n env: Pick<KindRouteEnv, \"kinds\">,\n): Record<string, unknown> | null {\n if (!isRecord(value)) return null;\n const kind = readObjectKind(value);\n if (!kind) return null;\n\n const def = env.kinds.getDefinition(kind);\n if (!def?.toLegacyServerData) return null;\n\n return def.toLegacyServerData(envelopeFromCompleteValue(value, kind)) ?? null;\n}\n","/**\n * 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: WITHHOLD BY DEFAULT, OPT IN PER KIND\n * -------------------------------------------------\n * A provisional value MAY be missing required fields — that is what the\n * `partial_unvalidated` notice declares — and §8 of the contract requires that\n * a component which throws on an absent field is not routed one. Rather than\n * audit every component, the default is WITHHOLD: nothing changes and the block\n * keeps its loading skeleton. A kind opts in with `partialReady: true` on its\n * registry definition. If an opted-in component throws anyway,\n * `ProvisionalKindBoundary` screams and calls `markKindPartialUnsafe`, which\n * drops that kind back to withhold for the rest of the session — loud recovery,\n * never a broken surface.\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 {\n envelopeFromCompleteValue,\n IR_ENVELOPE_KEY,\n IR_PARTIAL_KEY,\n IR_VERSION,\n isProvisionalKind,\n readEnvelope,\n readObjectKind,\n readPartialKindEvent,\n} from \"@ai-matrx/content-ir\";\nimport type { CanonicalBlockIR, PartialKindEvent } from \"@ai-matrx/content-ir\";\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-react.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 * Has this kind opted in to being handed a provisional value? Withhold is the\n * default; see the module doc.\n */\nexport function isPartialReadyKind(\n kind: string,\n env: Pick<KindRouteEnv, \"kinds\">,\n): boolean {\n if (!kind || partialUnsafeKinds.has(kind)) return false;\n return env.kinds.getDefinition(kind)?.partialReady === true;\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 cancelled (so a client abort\n * drops every retraction), and a flush failure is swallowed so it never kills\n * a run.\n *\n * Once the stream is over, no terminal can ever arrive, so a still-open\n * provisional is stuck by definition — drop it and let the block's own\n * content and `__ir` be the truth. Correct to be message-wide: a terminal for\n * THIS block may still be in flight while the block itself looks finished.\n *\n * `undefined` reads as active, so a caller that does not thread stream state\n * keeps live rendering rather than silently losing it.\n */\n streamActive?: boolean;\n}\n\n/**\n * The ANNOUNCED-but-not-yet-renderable state: the server has said what this\n * region is, and the region cannot render its real component yet.\n *\n * WHY THIS EXISTS SEPARATELY FROM THE VERIFIED CHANNEL. On a chat stream the\n * host's own accumulator fills `__ir` in as it parses. A WORKFLOW run's lane\n * does not: when the server opens the block scope it marks the text channel\n * `block_shadowed` and the lane stops feeding its accumulator, precisely so one\n * region is never rendered twice under two sets of block ids\n * (STREAMING_PARTIAL_KINDS.md §7b rule 4). So on a run page there is NO\n * streaming `__ir` — the ONLY thing that knows what the region is, is the\n * partial channel. Without this, a workflow node's structured answer fell\n * through to the raw-text renderer: a generic loader, then raw JSON\n * accumulating, then a swap at the end.\n *\n * Returns the provisional envelope to feed the kind's loading component, or\n * null when there is nothing announced (no event, a terminal, a dead stream).\n * Deliberately independent of `partialReady`: withholding a VALUE from a\n * component that might throw on it is a real decision, but withholding the\n * kind's own loading state is not — a skeleton cannot throw, and the reader\n * seeing what is coming is the whole point.\n */\nexport function resolveAnnouncedKindLoading(\n block: { metadata?: Record<string, unknown> },\n options?: Pick<PartialRenderOptions, \"streamActive\">,\n): { kind: string; envelope: CanonicalBlockIR } | null {\n // Same anti-stuck-skeleton backstop as resolveProvisionalKindRender: once the\n // stream is over no terminal can arrive, so a still-open announcement is\n // stuck by definition and must not hold a loader on screen forever.\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n if (!isProvisionalKind(event)) return null;\n const kind = event.root.kind;\n if (!kind) return null;\n\n // A region that already VERIFIED is the truth; never cover it with a loader.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n return { kind, envelope: envelopeFromPartialKind(event) };\n}\n\nexport interface ProvisionalKindRender<T> {\n /** The routed block — same type/serverData shape the final value produces. */\n block: T;\n /** The announced (speculative) kind. */\n kind: string;\n /** Per-block ordering key, for diagnostics. */\n seq: number;\n /** The provisional envelope — feeds the loading skeleton used as the throw fallback. */\n envelope: CanonicalBlockIR;\n}\n\nexport interface SupersededKindRender<T> {\n /** The completed block routed through the announced kind's normal component. */\n block: T;\n /** The kind the producer announced and then confirmed at terminal. */\n kind: string;\n /** Per-block ordering key, for diagnostics. */\n seq: number;\n /** Render-local complete envelope reconstructed from the block's own content. */\n envelope: CanonicalBlockIR;\n}\n\nfunction parseCompletedJsonObject(content: string): Record<string, unknown> | null {\n let source = content.trim();\n const fenced = source.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```$/i);\n if (fenced?.[1]) source = fenced[1].trim();\n\n try {\n const value = JSON.parse(source) as unknown;\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Finish the partial-kind handoff for a `superseded` terminal.\n *\n * A workflow run deliberately shadows its text channel while server-built\n * render blocks stream, so the browser never builds a verified `__ir`\n * envelope for that region. The terminal still proves that the announced kind\n * completed, and the block's own content is now closed JSON. Reconstruct a\n * render-local COMPLETE envelope from that content and route it through the\n * same component path as persisted/reloaded data. `retracted` is never\n * eligible, and a malformed or mismatched payload stays on the host's honest\n * raw fallback.\n */\nexport function resolveSupersededKindRender<\n T extends IrRoutableBlock & {\n content: string;\n metadata?: Record<string, unknown>;\n },\n>(\n block: T,\n env: KindRouteEnv,\n options?: KindRouteOptions,\n): SupersededKindRender<T> | null {\n const event = readPartialKindEvent(block.metadata);\n if (event?.state !== \"superseded\") return null;\n\n // A verified envelope is already the higher-fidelity truth and the ordinary\n // kind route owns it.\n if (readEnvelope(block.metadata)?.root.status === \"complete\") return null;\n\n const value = parseCompletedJsonObject(block.content);\n if (!value || readObjectKind(value) !== event.kind) return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n const envelope = envelopeFromCompleteValue(value, event.kind);\n const terminalBlock = {\n ...block,\n // A code/json block's serverData is an annotation, not kind data.\n serverData: undefined,\n metadata: { ...rest, [IR_ENVELOPE_KEY]: envelope },\n } as T;\n const routed = applyIrKindRoute(terminalBlock, env, options);\n if (routed === terminalBlock) return null;\n\n return { block: routed, kind: event.kind, seq: event.seq, envelope };\n}\n\n/**\n * Resolve a block's provisional render, or null when there is nothing to show\n * provisionally (no event, a terminal event, a withheld kind, a kind nothing\n * can route, or a verified envelope that already won).\n *\n * Pure: no React, no host state, no side effects beyond the registry reads.\n */\nexport function resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n>(\n block: T,\n env: KindRouteEnv,\n options?: PartialRenderOptions,\n): ProvisionalKindRender<T> | null {\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n // Terminal (superseded / retracted) → no provisional render, in this frame.\n if (!isProvisionalKind(event)) return null;\n\n const kind = event.root.kind;\n if (!isPartialReadyKind(kind, env)) return null;\n\n // A verified envelope that has already completed is the truth — a late or\n // duplicated partial must never displace it.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n\n const envelope = envelopeFromPartialKind(event);\n\n const provisionalBlock = {\n ...block,\n // The raw region annotation (`{ language: \"json\" }`) is not kind data —\n // same poison rule the verified route follows.\n serverData: undefined,\n metadata: {\n ...rest,\n [IR_ENVELOPE_KEY]: envelope,\n [IR_PROVISIONAL_KEY]: true,\n },\n } as T;\n\n const routed = applyIrKindRoute(provisionalBlock, env, options);\n // Nothing claimed it (unknown kind, no component) — `applyIrKindRoute`\n // returns the SAME reference. Withhold rather than render raw partial JSON.\n if (routed === provisionalBlock) return null;\n // A bridged kind whose bridge DECLINED this value (too thin to render — a\n // quiz with no answerable question yet) routed on type alone, which would\n // hand the component the partial JSON text to parse. Withhold: the loading\n // skeleton stays up for this frame and the next `seq` tries again.\n if (\n env.kinds.getDefinition(kind)?.toLegacyServerData &&\n !(routed as { serverData?: unknown }).serverData\n ) {\n return null;\n }\n\n return { block: routed, kind, seq: event.seq, envelope };\n}\n","/**\n * THE BOUND ROUTE — the pure route functions with a host's env and owned\n * types partially applied, built ONCE in a host wiring module.\n *\n * Every host was writing the same wrapper file by hand: one function per pure\n * route, each forwarding `matrx…Env` + `ownedTypes` (matrx-frontend carried\n * two such modules; the dashboard a third). Per C22 that repeated delta is\n * package-provided: a host module now only INJECTS (its env, its owned block\n * types) and re-exports what this factory returns.\n *\n * The functions are the exact pure routes — read `kind-route.ts` /\n * `partial-kind-route.ts` for semantics; nothing behavioral lives here.\n */\n\nimport type { IrRoutableBlock, KindRouteEnv } from \"../host/host-types\";\nimport {\n applyIrKindRoute,\n kindServerDataFromStoredValue,\n type KindRouteOptions,\n} from \"./kind-route\";\nimport {\n isPartialReadyKind,\n resolveProvisionalKindRender,\n resolveSupersededKindRender,\n type PartialRenderOptions,\n type ProvisionalKindRender,\n type SupersededKindRender,\n} from \"./partial-kind-route\";\n\nexport interface KindRouteBinding {\n /** Route one block through the bound registries. */\n applyIrKindRoute<T extends IrRoutableBlock>(block: T): T;\n /**\n * Rehydration route for STRUCTURED persisted artifacts: given a stored\n * zero-loss value object, derive the registered kind's legacy `serverData`\n * with no re-parse. Null for non-objects, unregistered kinds, or kinds\n * without a legacy bridge.\n */\n kindServerDataFromStoredValue(value: unknown): Record<string, unknown> | null;\n /** Has this kind opted in to being handed a provisional value? */\n isPartialReadyKind(kind: string): boolean;\n /**\n * Resolve a block's provisional render, or null when there is nothing to\n * show provisionally (no event, a terminal event, a withheld kind, a kind\n * nothing can route, or a verified envelope that already won).\n */\n resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n >(\n block: T,\n options?: Pick<PartialRenderOptions, \"streamActive\">,\n ): ProvisionalKindRender<T> | null;\n /**\n * Route a completed workflow block whose `superseded` terminal confirms the\n * kind but whose shadowed lane never built a verified envelope.\n */\n resolveSupersededKindRender<\n T extends IrRoutableBlock & {\n content: string;\n metadata?: Record<string, unknown>;\n },\n >(block: T): SupersededKindRender<T> | null;\n}\n\n/** Bind the pure routes to one host's env + owned block types. */\nexport function createKindRouteBinding(\n env: KindRouteEnv,\n options?: KindRouteOptions,\n): KindRouteBinding {\n const ownedTypes = options?.ownedTypes;\n return {\n applyIrKindRoute: (block) =>\n applyIrKindRoute(block, env, ownedTypes ? { ownedTypes } : undefined),\n kindServerDataFromStoredValue: (value) =>\n kindServerDataFromStoredValue(value, env),\n isPartialReadyKind: (kind) => isPartialReadyKind(kind, env),\n resolveProvisionalKindRender: (block, streamOptions) =>\n resolveProvisionalKindRender(block, env, {\n ...streamOptions,\n ...(ownedTypes ? { ownedTypes } : null),\n }),\n resolveSupersededKindRender: (block) =>\n resolveSupersededKindRender(\n block,\n env,\n ownedTypes ? { ownedTypes } : undefined,\n ),\n };\n}\n","\"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 {\n envelopeFromCompleteValue,\n IR_ENVELOPE_KEY,\n isReservedDirectiveSlug,\n} from \"@ai-matrx/content-ir\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport { DirectiveRender } from \"../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: a host frame either IS the chrome or has none.\n * \"card\" (default) keeps a bordered surface for preview surfaces. \"bare\"\n * renders with NO border/background/pad — for a host that already draws a\n * titled card, where the default produced a two-tone box-in-a-box with a dead\n * band around it.\n */\n variant?: \"card\" | \"bare\";\n className?: string;\n}\n\ntype RoutingStatus = \"checking\" | \"routable\" | \"unroutable\";\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 = \"card\",\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 =\n variant === \"bare\" ? undefined : \"rounded-md border border-border bg-card p-3\";\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","\"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 \"@ai-matrx/content-ir\";\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 * 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 \"@ai-matrx/content-ir\";\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 * \"Apply\" for a side-effect Kind Directive that arrived as CONTENT.\n *\n * THE POSITION RULE, honoured 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 \"@ai-matrx/content-ir\";\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=\"mt-px h-3.5 w-3.5 shrink-0\" />\n ) : (\n <CheckCircleIcon className=\"mt-px h-3.5 w-3.5 shrink-0\" />\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 grey\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=\"mt-0.5 h-3.5 w-3.5 shrink-0\" />\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 { itemTitle } from \"@ai-matrx/content-ir\";\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. `itemTitle`'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 = itemTitle(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 * labelled \"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-react/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 recognises (`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 * The handful of glyphs the directive cards need, as inline SVG. This package\n * depends on no icon library (see the FEATURE boundary); the paths are the\n * Lucide set's (ISC), so the cards look identical to a Lucide-using host.\n */\n\nimport type { ReactElement, SVGProps } from \"react\";\n\ntype IconProps = SVGProps<SVGSVGElement>;\n\nfunction Svg({ children, ...props }: IconProps) {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n {...props}\n >\n {children}\n </svg>\n );\n}\n\nexport const FilePlusIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4\" />\n <path d=\"M14 2v4a2 2 0 0 0 2 2h4\" />\n <path d=\"M3 15h6\" />\n <path d=\"M6 12v6\" />\n </Svg>\n);\nexport const PencilIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M12 20h9\" />\n <path d=\"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z\" />\n </Svg>\n);\nexport const TrashIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M3 6h18\" />\n <path d=\"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6\" />\n <path d=\"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2\" />\n <line x1=\"10\" x2=\"10\" y1=\"11\" y2=\"17\" />\n <line x1=\"14\" x2=\"14\" y1=\"11\" y2=\"17\" />\n </Svg>\n);\nexport const PlayIcon = (p: IconProps) => (\n <Svg {...p}>\n <polygon points=\"6 3 20 12 6 21 6 3\" />\n </Svg>\n);\nexport const WebhookIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2\" />\n <path d=\"m6 17 3.13-5.78c.53-.97.1-2.01-.4-2.96A4 4 0 0 1 14 5.5c.63.42 1.13 1 1.44 1.66\" />\n <path d=\"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8\" />\n </Svg>\n);\nexport const BoxesIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z\" />\n <path d=\"m7 16.5-4.74-2.85\" />\n <path d=\"m7 16.5 5-3\" />\n <path d=\"M7 16.5v5.17\" />\n <path d=\"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z\" />\n <path d=\"m17 16.5-5-3\" />\n <path d=\"m17 16.5 4.74-2.85\" />\n <path d=\"M17 16.5v5.17\" />\n <path d=\"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z\" />\n <path d=\"M12 8 7.26 5.15\" />\n <path d=\"m12 8 4.74-2.85\" />\n <path d=\"M12 13.5V8\" />\n </Svg>\n);\nexport const ChevronDownIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m6 9 6 6 6-6\" />\n </Svg>\n);\nexport const ChevronRightIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m9 18 6-6-6-6\" />\n </Svg>\n);\nexport const MaximizeIcon = (p: IconProps) => (\n <Svg {...p}>\n <polyline points=\"15 3 21 3 21 9\" />\n <polyline points=\"9 21 3 21 3 15\" />\n <line x1=\"21\" x2=\"14\" y1=\"3\" y2=\"10\" />\n <line x1=\"3\" x2=\"10\" y1=\"21\" y2=\"14\" />\n </Svg>\n);\nexport const LoaderIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />\n </Svg>\n);\n/** Lucide `rotate-ccw` — \"Run again\". */\nexport const RotateCcwIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\" />\n <path d=\"M3 3v5h5\" />\n </Svg>\n);\nexport const CheckCircleIcon = (p: IconProps) => (\n <Svg {...p}>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"m9 12 2 2 4-4\" />\n </Svg>\n);\nexport const AlertIcon = (p: IconProps) => (\n <Svg {...p}>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </Svg>\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 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 honour 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 \"@ai-matrx/content-ir\";\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 {\n type DecodedDirective,\n type DirectiveClass,\n buildDirectiveSlug,\n} from \"@ai-matrx/content-ir\";\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-react.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 {\n asKindInstance,\n directiveDisplay,\n itemFacts,\n itemSubtitle,\n nounLabel,\n nounTitleColumn,\n type DecodedDirective,\n} from \"@ai-matrx/content-ir\";\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 labelled 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","\"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 * (`partialReady`), but an opt-in 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\ninterface ProvisionalKindBoundaryProps extends ProvisionalKindBoundaryOwnProps {\n reportError: ContentIrErrorReporter;\n}\n\ninterface ProvisionalKindBoundaryState {\n failed: boolean;\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(): ProvisionalKindBoundaryState {\n return { failed: true };\n }\n\n override componentDidCatch(error: Error, info: React.ErrorInfo): void {\n const { kind, reportError } = this.props;\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}\" declares partialReady but its component threw on a provisional value — provisional rendering disabled for this kind (falling back to its loading skeleton). Fix the component or drop partialReady.`,\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) return this.props.fallback;\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({ children }: { children: ReactNode }) {\n const host = useContentIrHost();\n const label = \"Still arriving\";\n return (\n <div className=\"relative\" aria-busy=\"true\">\n {children}\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 </div>\n );\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 {\n readEnvelope,\n readObjectKind,\n reconstructRegionValue,\n} from \"@ai-matrx/content-ir\";\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 : marker?.reason === \"unregistered\"\n ? \"this shape isn't registered on this platform\"\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, readObjectKind, readRunResultValue } from \"@ai-matrx/content-ir\";\nimport type { NodeOutcomeWrapper, RunResultWrapper } from \"@ai-matrx/content-ir\";\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","/**\n * The DB-component COMPILE CACHE — session-scoped, keyed per winning row\n * VERSION, with the loud-recovery policy built in.\n *\n * This was matrx-frontend's `dbKindComponentCache.ts` (316 lines of compile\n * caching + invalidation living in one host), absorbed per C22: cache\n * mechanics, key derivation, the scream-once latch, transform recovery, and\n * config narrowing are PACKAGE policy — every host was going to need exactly\n * these lines, bug for bug. What stays host-injected is exactly what is\n * host-shaped:\n *\n * - THE COMPILER ({@link DbKindComponentCompiler}). Compiling or sandboxing\n * user-authored component source is a security-shaped host decision — the\n * package never bundles Babel or an allowlist scope. matrx-frontend\n * injects its shared allowlist compiler (`compileSlotComponent`); a host\n * with no sandbox simply never constructs a cache.\n * - The default allowed-imports list (host scope registry).\n * - Where screams land ({@link ContentIrErrorReporter}) and where durable\n * incidents go ({@link DbKindComponentIncidentSink}).\n * - Invalidation TRIGGERS ({@link DbKindComponentCachePorts.registerInvalidation}):\n * the host wires its invalidation-registry keys (e.g.\n * `@ai-matrx/kit/invalidation` fired by name when an agent edits a\n * component row); the cache owns what invalidation MEANS.\n *\n * Contract (the db-row component contract, SHAPE_SYSTEM.md):\n * - `component_source` compiles to a React component receiving\n * `{ data, kind, config, runAction, itemState?, onResolve?, uiOptions? }`\n * where `data` is the kind instance value and `itemState` what actions\n * saved onto this item.\n * - `props_transform` (optional) compiles to a `(data) => data` function\n * applied to the value BEFORE it reaches the component. A throwing or\n * non-compiling transform screams and the untransformed value is used\n * (never a blank hole).\n * - `config.allowed_imports` (string[]) narrows the compile scope; absent,\n * the row gets the host's FULL registered allowlist.\n *\n * Cache key: (kind, platform, role, row.updated_at) — one compile per winning\n * row VERSION. A resolver refresh delivering an edited row (bumped\n * `updated_at`) re-keys and recompiles naturally; `invalidate` /\n * `invalidateAll` force-drop keys. Server edits never push to open clients —\n * the contract is refresh-on-view.\n */\n\nimport type * as React from \"react\";\n\nimport type { ContentIrErrorReporter } from \"../host/error-report\";\nimport type { ComponentResolution } from \"../resolver/component-resolution.types\";\n\n/**\n * Settings the MOUNTING UI dictates to a kind component — the standard,\n * growing arg list every component honors (Arman, 2026-07-23). `selectionMode`\n * is the first: it tells a component whether the surface wants the user to\n * pick one value, many, or none (pure display). A component reads what it\n * understands and ignores the rest; absent = its own default (usually display).\n */\nexport interface KindComponentUiOptions {\n selectionMode?: \"single\" | \"multiple\" | \"none\";\n [key: string]: unknown;\n}\n\n/**\n * The return channel: how a kind component hands a chosen value back to the\n * surface that mounted it (a Kind Request). The mirror of `runAction`\n * (surface → agent); this is component → surface. Undefined in normal render\n * (chat/notes) — the component simply doesn't offer selection there.\n */\nexport type ResolveKindValue = (value: unknown) => void;\n\n/** The envelope every kind action resolves to — a skip/failure is never a silent pass. */\nexport type DbKindActionResult =\n | { ok: true; result: unknown }\n | { ok: false; error: string };\n\n/**\n * The action seam a compiled component receives: `runAction(key, input)`\n * triggers a registered platform capability (e.g. \"trigger_agent\"). Always\n * resolves to an `{ ok }` envelope, never throws — safe to call from imperfect\n * component code. This is the ONLY side-effect channel a sandboxed component\n * gets; it reaches no data directly.\n */\nexport type RunDbKindAction = (\n key: string,\n input: unknown,\n) => Promise<DbKindActionResult>;\n\n/** Props every compiled DB kind component receives. */\nexport interface DbKindComponentRenderProps {\n /** The kind instance value — post-`props_transform` when one exists. */\n data: unknown;\n /** The kind slug the value belongs to. */\n kind: string;\n /** The resolver row's `config` object, verbatim (narrowed — see {@link DbKindComponentCache.config}). */\n config: Record<string, unknown>;\n /** The action seam — see {@link RunDbKindAction}. */\n runAction: RunDbKindAction;\n /**\n * Present only when the component is mounted inside a Kind Request. Call it\n * with the user's chosen value to hand that value back to the requesting\n * surface (which resolves its promise). Undefined in normal render.\n */\n onResolve?: ResolveKindValue;\n /** Settings the mounting surface dictates (e.g. `{ selectionMode: \"single\" }`). */\n uiOptions?: KindComponentUiOptions;\n /**\n * This item's durable state: what `save_item_state` / `run_shortcut` with\n * `saveAs` wrote onto it (`{}` when nothing yet; survives reload). The host\n * adds `src` to every saved image ref (`{ file_id, mime_type, width, height }`)\n * so the component renders `<img src={itemState.key.src}>`.\n */\n itemState?: Record<string, unknown>;\n}\n\nexport interface CompiledDbKindComponent {\n Component: React.ComponentType<DbKindComponentRenderProps>;\n /** Compiled `props_transform`, or null when the row declares none. */\n transform: ((data: unknown) => unknown) | null;\n}\n\nexport type DbKindCompileResult =\n | { ok: true; compiled: CompiledDbKindComponent }\n | { ok: false; error: string };\n\n/** The failure modes a browser can observe on a DB kind component. */\nexport type DbKindComponentIncidentType =\n /** `component_source` did not compile (or produced no component). */\n | \"compile_error\"\n /** The compiled component threw during render (error boundary caught it). */\n | \"render_throw\"\n /** `props_transform` failed to compile or threw. */\n | \"transform_error\";\n\n/**\n * One durable render incident — the payload for whoever can actually FIX the\n * component. A host sink typically files it on the kind's own incident queue\n * (matrx-frontend: `content_ir.kind_component_incident` via RPC); without a\n * sink, a broken component seen only by ordinary users is invisible to its\n * author forever. `data` is the kind instance value — a privacy-conscious sink\n * reduces it to keys + types before it leaves the browser.\n */\nexport interface DbKindComponentIncident {\n kind: string;\n errorType: DbKindComponentIncidentType;\n message: string;\n platform?: string;\n role?: string;\n componentKey?: string | null;\n componentUpdatedAt?: string | null;\n stack?: string | null;\n data?: unknown;\n}\n\nexport type DbKindComponentIncidentSink = (\n incident: DbKindComponentIncident,\n) => void;\n\n/**\n * THE COMPILER PORT. Matches matrx-frontend's shared allowlist compiler\n * (`compileSlotComponent`) structurally: source in, `{ Component | error }`\n * out, never throws. The compiled component is generically typed — the cache\n * performs the single deliberate narrowing where the generic compiler meets\n * the kind prop contract.\n */\nexport type DbKindComponentCompiler = (args: {\n code: string;\n allowedImports: string[];\n}) => {\n Component: React.ComponentType<Record<string, unknown>> | null;\n error: string | null;\n};\n\nexport interface DbKindComponentCachePorts {\n /** The host's sandbox compiler — see {@link DbKindComponentCompiler}. */\n compile: DbKindComponentCompiler;\n /** The FULL registered allowlist a row without `config.allowed_imports` gets. */\n defaultAllowedImports: () => string[];\n /** Where screams land (every recovery path is loud). */\n reportError: ContentIrErrorReporter;\n /** Durable incident sink — optional, but a host without one blinds authors. */\n reportIncident?: DbKindComponentIncidentSink;\n /** Default `kind_component.platform` for this host (default \"web\"). */\n platform?: string;\n /**\n * THE INVALIDATION REGISTRATION PORT. Called once at construction with the\n * cache's `invalidateAll`; the host registers it under its own invalidation\n * keys (e.g. `@ai-matrx/kit/invalidation`'s name-keyed registry, fired when\n * an agent's component write completes). The cache owns the mechanics —\n * what gets dropped, the scream-latch reset; the host owns only WHEN.\n */\n registerInvalidation?: (invalidateAll: () => void) => void;\n}\n\nexport interface DbKindComponentCache {\n /**\n * Compile (once per resolver key per row version) a db-source resolution's\n * `component_source` + optional `props_transform`. Synchronous — the caller\n * (a lazily-loaded Impl) already paid the compiler chunk.\n */\n getOrCompile(\n kind: string,\n resolution: ComponentResolution,\n platform?: string,\n role?: string,\n ): DbKindCompileResult;\n /**\n * Apply the row's transform to the kind value. Loud on throw, never fatal —\n * the untransformed value comes back so content is never hidden.\n */\n applyPropsTransform(\n kind: string,\n compiled: CompiledDbKindComponent,\n value: unknown,\n ): unknown;\n /**\n * THE CONFIG BOUNDARY. `ComponentResolution.config` is typed\n * `Record<string, unknown>` — deliberately agnostic about a host's JSONB\n * interior. This narrows at runtime (plain object → itself; anything else →\n * scream + empty config) rather than asserting: a row whose `config` is not\n * an object is a malformed `kind_component` row, and the component still\n * renders rather than crashing.\n */\n config(config: unknown, kind: string): Record<string, unknown>;\n /** Drop a (kind, platform, role) key family (authoring surfaces call after editing a row). */\n invalidate(kind: string, platform?: string, role?: string): void;\n /** Drop everything — the invalidation-port payload. */\n invalidateAll(): void;\n}\n\n/**\n * A routed lazy warm row owns a real body, but the per-kind cold fetch has not\n * landed it yet. This is loading, not a compile failure.\n */\nexport function isDbKindComponentBodyPending(\n resolution: ComponentResolution,\n): boolean {\n return resolution.hasComponentSource && resolution.componentSource === null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Build the session cache. One per host app — construct it in the wiring module. */\nexport function createDbKindComponentCache(\n ports: DbKindComponentCachePorts,\n): DbKindComponentCache {\n const cache = new Map<string, DbKindCompileResult>();\n const screamedKeys = new Set<string>();\n const defaultPlatform = ports.platform ?? \"web\";\n\n function cacheKey(\n kind: string,\n platform: string,\n role: string,\n updatedAt: string | null,\n ): string {\n // `updatedAt` (the winning row's freshness) is part of the key: a refresh\n // that delivers an edited row (bumped updated_at) recompiles automatically\n // instead of serving the stale compile for the rest of the session.\n return `${kind}${platform}${role}${updatedAt ?? \"\"}`;\n }\n\n /**\n * Loud recovery: one console scream per key + a structured report on every\n * attempt + a durable incident for whoever can fix the component.\n */\n function screamCompileFailure(\n key: string,\n kind: string,\n error: string,\n resolution: ComponentResolution,\n platform: string,\n role: string,\n ): void {\n const message = `[content-ir] DB kind component for \"${kind}\" failed to compile — rendering the generic structured viewer instead: ${error}`;\n if (!screamedKeys.has(key)) {\n screamedKeys.add(key);\n console.error(message);\n }\n ports.reportError({ source: \"content-ir\", message, raw: { kind, error } });\n ports.reportIncident?.({\n kind,\n errorType: \"compile_error\",\n message,\n platform,\n role,\n componentKey: resolution.componentKey,\n componentUpdatedAt: resolution.updatedAt,\n });\n }\n\n function config(value: unknown, kind: string): Record<string, unknown> {\n if (isPlainObject(value)) return value;\n if (value === null || value === undefined) return {};\n const message = `[content-ir] kind_component.config for \"${kind}\" is not a JSON object (${typeof value}) — rendering with an empty config.`;\n console.error(message);\n ports.reportError({ source: \"content-ir\", message, raw: { kind } });\n return {};\n }\n\n function resolveAllowedImports(rowConfig: Record<string, unknown>): string[] {\n const declared = rowConfig.allowed_imports;\n if (\n Array.isArray(declared) &&\n declared.every((entry): entry is string => typeof entry === \"string\")\n ) {\n return declared;\n }\n return ports.defaultAllowedImports();\n }\n\n function getOrCompile(\n kind: string,\n resolution: ComponentResolution,\n platform: string = defaultPlatform,\n role = \"output\",\n ): DbKindCompileResult {\n const key = cacheKey(kind, platform, role, resolution.updatedAt);\n const cached = cache.get(key);\n if (cached) return cached;\n\n const source = resolution.componentSource;\n if (!source || !source.trim()) {\n const result: DbKindCompileResult = {\n ok: false,\n error: \"db-source resolution has no component_source\",\n };\n screamCompileFailure(key, kind, result.error, resolution, platform, role);\n cache.set(key, result);\n return result;\n }\n\n const allowedImports = resolveAllowedImports(\n config(resolution.config, kind),\n );\n\n const { Component, error } = ports.compile({ code: source, allowedImports });\n if (!Component || error) {\n const result: DbKindCompileResult = {\n ok: false,\n error: error ?? \"compile produced no component\",\n };\n screamCompileFailure(key, kind, result.error, resolution, platform, role);\n cache.set(key, result);\n return result;\n }\n\n // The optional props transform is its own tiny compile — a `(data) => data`\n // function (mirroring tool_ui's header_subtitle_code pattern). A broken\n // transform is LOUD but never fatal: the component still renders, fed the\n // untransformed value.\n let transform: ((data: unknown) => unknown) | null = null;\n if (resolution.propsTransform && resolution.propsTransform.trim()) {\n const { Component: transformFn, error: transformError } = ports.compile({\n code: resolution.propsTransform,\n allowedImports: [],\n });\n if (typeof transformFn === \"function\" && !transformError) {\n transform = transformFn as unknown as (data: unknown) => unknown;\n } else {\n const message = `[content-ir] props_transform for kind \"${kind}\" failed to compile — value passes through untransformed: ${transformError ?? \"no function produced\"}`;\n console.error(message);\n ports.reportError({\n source: \"content-ir\",\n message,\n raw: { kind, error: transformError },\n });\n ports.reportIncident?.({\n kind,\n errorType: \"transform_error\",\n message,\n platform,\n role,\n componentKey: resolution.componentKey,\n componentUpdatedAt: resolution.updatedAt,\n });\n }\n }\n\n const result: DbKindCompileResult = {\n ok: true,\n compiled: {\n // The injected compiler types components as\n // ComponentType<Record<string, unknown>>; the callsite always passes\n // DbKindComponentRenderProps — the single deliberate narrowing where\n // the generic compiler meets the kind contract.\n Component:\n Component as unknown as React.ComponentType<DbKindComponentRenderProps>,\n transform,\n },\n };\n cache.set(key, result);\n return result;\n }\n\n function applyPropsTransform(\n kind: string,\n compiled: CompiledDbKindComponent,\n value: unknown,\n ): unknown {\n if (!compiled.transform) return value;\n try {\n return compiled.transform(value);\n } catch (error) {\n const message = `[content-ir] props_transform for kind \"${kind}\" threw — using the untransformed value: ${\n error instanceof Error ? error.message : String(error)\n }`;\n console.error(message);\n ports.reportError({ source: \"content-ir\", message, raw: { kind } });\n ports.reportIncident?.({\n kind,\n errorType: \"transform_error\",\n message,\n stack: error instanceof Error ? (error.stack ?? null) : null,\n data: value,\n });\n return value;\n }\n }\n\n function invalidate(\n kind: string,\n platform: string = defaultPlatform,\n role = \"output\",\n ): void {\n const prefix = `${kind}${platform}${role}`;\n for (const key of [...cache.keys()]) {\n if (key.startsWith(prefix)) cache.delete(key);\n }\n for (const key of [...screamedKeys]) {\n if (key.startsWith(prefix)) screamedKeys.delete(key);\n }\n }\n\n function invalidateAll(): void {\n cache.clear();\n screamedKeys.clear();\n }\n\n const api: DbKindComponentCache = {\n getOrCompile,\n applyPropsTransform,\n config,\n invalidate,\n invalidateAll,\n };\n\n ports.registerInvalidation?.(() => invalidateAll());\n\n return api;\n}\n","\"use client\";\n\n/**\n * DbKindComponentErrorBoundary — the DEFAULT error boundary around a compiled\n * DB kind component (absorbed from matrx-frontend per the C23 retrofit; the\n * package previously shipped \"no error capture by design\", which left every\n * host to rebuild this class).\n *\n * A user-authored component that throws during render must never crash the\n * surface (chat, notes, admin preview). The boundary catches, renders the\n * fallback (the kind's generic structured viewer — the R6 disposition, never\n * a blank hole), and SCREAMS: a recovery firing means a real bug got past\n * authoring.\n *\n * `resetSignal` (the component's `updated_at`) un-latches the boundary when a\n * NEW component version arrives: an author who fixes a throwing component must\n * see the fix on the next re-render, not stay stuck on the fallback until a\n * full unmount. Without this the error state is sticky for the whole session —\n * the \"broke, then magically fixed itself minutes later\" class. React error\n * boundaries never self-clear, so a version change is the only safe signal\n * (`hasError` alone can't tell a fixed version from the same broken one).\n *\n * `onCaught` is the scream seam: a host binds its structured render-error\n * capture + durable incident filing (matrx-frontend files a `render_throw`\n * incident so the component's author learns). Bound to nothing, the default is\n * an honest console scream — never silence.\n */\nimport * as React from \"react\";\n\nexport interface DbKindComponentErrorBoundaryProps {\n kind: string;\n /** The resolved component's `updated_at`; a change means a new version. */\n resetSignal: string | null;\n fallback: React.ReactNode;\n children: React.ReactNode;\n /**\n * Where the catch lands. A host binds structured capture + incident filing\n * here; the default screams to the console. NOTE for hosts whose console\n * adapter persists `console.error`: bind this (which replaces the default)\n * rather than mirroring the capture through the console twice.\n */\n onCaught?: (\n error: Error,\n info: { componentStack: string | null },\n ) => void;\n}\n\ninterface State {\n hasError: boolean;\n /**\n * The `resetSignal` seen on the LAST render — tracked every render (not just\n * on error) so that at throw time it already holds the version that threw.\n * `getDerivedStateFromError` cannot read props, so this is how the boundary\n * knows which version to un-latch away from.\n */\n signalAtLastRender: string | null;\n}\n\nexport class DbKindComponentErrorBoundary extends React.Component<\n DbKindComponentErrorBoundaryProps,\n State\n> {\n constructor(props: DbKindComponentErrorBoundaryProps) {\n super(props);\n this.state = { hasError: false, signalAtLastRender: props.resetSignal };\n }\n\n static getDerivedStateFromError(): Partial<State> {\n return { hasError: true };\n }\n\n static getDerivedStateFromProps(\n props: DbKindComponentErrorBoundaryProps,\n state: State,\n ): State | null {\n if (props.resetSignal === state.signalAtLastRender) return null;\n // The version changed. If we were latched on the old version, un-latch so\n // the new (hopefully fixed) component gets a fresh render attempt; either\n // way, record the new signal as the one now rendering.\n return { hasError: false, signalAtLastRender: props.resetSignal };\n }\n\n override componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {\n const info = { componentStack: errorInfo.componentStack ?? null };\n if (this.props.onCaught) {\n this.props.onCaught(error, info);\n return;\n }\n // The honest default when a host binds nothing: never silent.\n console.error(\n `[content-ir] DB kind component for \"${this.props.kind}\" threw during render — showing the fallback:`,\n error,\n );\n }\n\n override render(): React.ReactNode {\n if (this.state.hasError) return this.props.fallback;\n return this.props.children;\n }\n}\n"],"mappings":";AA2BO,IAAM,uBAA+C,CAAC,WAAW;AACtE,UAAQ,MAAM,gBAAgB,OAAO,OAAO,IAAI,OAAO,OAAO,EAAE;AAClE;;;AC0HO,SAAS,WAAW,MAAmC;AAC5D,SAAO;AAAA,IAC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AAAA,EACA,YAAY,OAA0C;AACpD,UAAM,KAAK;AACX,SAAK,QAAQ,EAAE,UAAU,OAAO,oBAAoB,MAAM,YAAY;AAAA,EACxE;AAAA,EAEA,OAAO,2BAA2C;AAChD,WAAO,EAAE,UAAU,KAAK;AAAA,EAC1B;AAAA,EAEA,OAAO,yBACL,OACA,OACc;AACd,QAAI,MAAM,gBAAgB,MAAM,mBAAoB,QAAO;AAI3D,WAAO,EAAE,UAAU,OAAO,oBAAoB,MAAM,YAAY;AAAA,EAClE;AAAA,EAES,kBAAkB,OAAc,WAAkC;AACzE,UAAM,OAAO,EAAE,gBAAgB,UAAU,kBAAkB,KAAK;AAChE,QAAI,KAAK,MAAM,UAAU;AACvB,WAAK,MAAM,SAAS,OAAO,IAAI;AAC/B;AAAA,IACF;AAEA,YAAQ;AAAA,MACN,uCAAuC,KAAK,MAAM,IAAI;AAAA,MACtD;AAAA,IACF;AAAA,EACF;AAAA,EAES,SAA0B;AACjC,QAAI,KAAK,MAAM,SAAU,QAAO,KAAK,MAAM;AAC3C,WAAO,KAAK,MAAM;AAAA,EACpB;AACF;","names":["createContext","useContext","jsx","createContext","useContext","listeners","envelopeFromCompleteValue","readEnvelope","readObjectKind","readEnvelope","readObjectKind","envelopeFromCompleteValue","useEffect","useState","envelopeFromCompleteValue","IR_ENVELOPE_KEY","isReservedDirectiveSlug","useEffect","useState","useSyncExternalStore","nounLabel","n","text","useSyncExternalStore","jsx","jsx","jsxs","useSyncExternalStore","useState","useEffect","label","read","jsx","jsxs","directiveDisplay","jsx","jsxs","directiveDisplay","useEffect","useState","directiveDisplay","nounLabel","jsx","jsxs","directiveDisplay","nounLabel","useEffect","useState","jsx","Fragment","jsx","jsxs","isReservedDirectiveSlug","useState","useEffect","IR_ENVELOPE_KEY","envelopeFromCompleteValue","jsx","jsxs","readEnvelope","readObjectKind","jsx","jsxs","readEnvelope","readObjectKind","readObjectKind","Fragment","jsx","isRecord","readObjectKind","result","Component","React"]}