@ai-matrx/content-ir-react 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/index.cjs +8 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -1
- package/dist/index.d.ts +16 -1
- package/dist/index.js +8 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0 — 2026-08-29
|
|
4
|
+
|
|
5
|
+
- **NO EXCEPTIONS for a root `__kind` (Arman's ruling, 2026-08-29).** The
|
|
6
|
+
strangler carve-out that left an UNREGISTERED kind slug untouched ("not
|
|
7
|
+
ours to claim" — teaching content, typos) is retired: any envelope with a
|
|
8
|
+
non-empty root kind now routes into the kind system. Unregistered slugs
|
|
9
|
+
reach the generic floor with the new `GenericFallbackReason`
|
|
10
|
+
`"unregistered"` (kind-preserved raws included), so the reader always sees
|
|
11
|
+
the payload acknowledged AS a kind instance — never an anonymous code
|
|
12
|
+
block. Both former pass-through tests flipped to pin the new behavior.
|
|
13
|
+
|
|
14
|
+
## 0.3.0 — 2026-08-29
|
|
15
|
+
|
|
16
|
+
- **`broken-instance` — the kind route now acknowledges BROKEN kind
|
|
17
|
+
instances.** An envelope whose root is a kind-preserved raw
|
|
18
|
+
(`kindState: "raw"`, kernel ≥ 0.3.0 preserves the kind on structural
|
|
19
|
+
failures too) routes to the generic floor with
|
|
20
|
+
`reason: "broken-instance"` when the kind is registered — never to a
|
|
21
|
+
bridge/db component (they must not receive non-compliant values) and never
|
|
22
|
+
as anonymous raw JSON. Unregistered slugs still pass through untouched.
|
|
23
|
+
New `GenericFallbackReason` member; `GenericStructuredView`'s honesty note
|
|
24
|
+
names the schema mismatch. Pinned by two new kind-route tests.
|
|
25
|
+
- Depends on `@ai-matrx/content-ir` 0.3.0.
|
|
26
|
+
|
|
3
27
|
## 0.1.0 — 2026-08-23
|
|
4
28
|
|
|
5
29
|
First release: the shared Content IR RENDER layer, extracted from
|
package/dist/index.cjs
CHANGED
|
@@ -387,6 +387,12 @@ function applyIrKindRoute(block, env, options) {
|
|
|
387
387
|
if (envelope.root.kindState === "pending_schema") return block;
|
|
388
388
|
const def = env.kinds.getDefinition(kind);
|
|
389
389
|
const resolution = env.components.resolve(kind, env.platform, "output");
|
|
390
|
+
if (envelope.root.kindState === "raw") {
|
|
391
|
+
return routeToGeneric(
|
|
392
|
+
block,
|
|
393
|
+
def || resolution ? "broken-instance" : "unregistered"
|
|
394
|
+
);
|
|
395
|
+
}
|
|
390
396
|
const dbRouted = routeToDbComponent(block, kind, resolution, env);
|
|
391
397
|
if (dbRouted) return dbRouted;
|
|
392
398
|
if (def?.legacyBlockType) {
|
|
@@ -419,7 +425,7 @@ function applyIrKindRoute(block, env, options) {
|
|
|
419
425
|
if (def) {
|
|
420
426
|
return routeToGeneric(block, resolution ? "inactive" : "no-component");
|
|
421
427
|
}
|
|
422
|
-
return block;
|
|
428
|
+
return routeToGeneric(block, "unregistered");
|
|
423
429
|
}
|
|
424
430
|
function kindServerDataFromStoredValue(value, env) {
|
|
425
431
|
if (!isRecord(value)) return null;
|
|
@@ -653,7 +659,7 @@ function GenericStructuredView({
|
|
|
653
659
|
const { value, recovered } = readStructuredValue(content, metadata);
|
|
654
660
|
const kind = envelope?.root.kind ?? (typeof value === "object" && value !== null && !Array.isArray(value) ? contentIr.readObjectKind(value) : null) ?? "";
|
|
655
661
|
const marker = readIrRouteMarker(metadata);
|
|
656
|
-
const note = marker?.reason === "inactive" ? "a custom view is registered but held inactive" : "no custom view yet";
|
|
662
|
+
const note = marker?.reason === "inactive" ? "a custom view is registered but held inactive" : marker?.reason === "broken-instance" ? "this instance did not match the shape's schema" : marker?.reason === "unregistered" ? "this shape isn't registered on this platform" : "no custom view yet";
|
|
657
663
|
return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: className ? `my-2 min-w-0 ${className}` : "my-2 min-w-0", children: [
|
|
658
664
|
status === "streaming" ? streamingIndicator ?? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mb-2 text-xs text-muted-foreground", children: "Still arriving\u2026" }) : null,
|
|
659
665
|
recovered ? host.renderValue({ value, ...kind ? { kind } : {}, note }) : (
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../host/error-report.ts","../host/host-types.ts","../host/ContentIrProvider.tsx","../resolver/component-resolver.ts","../route/kind-route.ts","../route/partial-kind-route.ts","../react/use-kind-version.ts","../react/KindInstanceRender.tsx","../react/ProvisionalKindBoundary.tsx","../react/GenericStructuredView.tsx","../react/RuntimeWrapperViews.tsx"],"names":["createContext","useContext","useMemo","readEnvelope","readObjectKind","envelopeFromCompleteValue","IR_VERSION","readPartialKindEvent","isProvisionalKind","IR_PARTIAL_KEY","IR_ENVELOPE_KEY","useCallback","useSyncExternalStore","useState","useEffect","jsx","Fragment","React","jsxs","reconstructRegionValue","isRecord","readNodeOutcomeValue","readRunResultValue"],"mappings":";;;;;;;;;;;AA2BO,IAAM,oBAAA,GAA+C,CAAC,MAAA,KAAW;AACtE,EAAA,OAAA,CAAQ,MAAM,CAAA,aAAA,EAAgB,MAAA,CAAO,OAAO,CAAA,CAAA,EAAI,MAAA,CAAO,OAAO,EAAE,CAAA;AAClE;;;AC2GO,SAAS,WAAW,IAAA,EAAmC;AAC5D,EAAA,OAAO;AAAA,IACL,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,UAAU,IAAA,CAAK;AAAA,GACjB;AACF;ACvHA,IAAM,oBAAA,GAAuBA,oBAAoC,IAAI,CAAA;AAO9D,SAAS,uBAAA,CAAwB;AAAA,EACtC,IAAA;AAAA,EACA;AACF,CAAA,EAAiC;AAC/B,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GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA;AAAS;AAAA,GAChD,EAEJ,CAAA;AAEJ","file":"index.cjs","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\";\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\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 components: Pick<ComponentResolutionSource, \"resolve\">;\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\";\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 {children}\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","/**\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\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 private warmFailureLogged = 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 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 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 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 if (changedKinds.size > 0) {\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\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 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 * 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.resolve(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\n void (async () => {\n try {\n this.ingestDbRows(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.resolve(kind, platform, role)) this.coldMisses.add(missKey);\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 }\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 })\n .catch((error: unknown) => {\n // Loud recovery: the compiled floor keeps rendering, but a warm\n // failure is a real defect — one console scream (first failure) plus\n // a structured report per attempt, then retryable.\n const message = `component-resolver warm load failed (compiled bootstrap still serving): ${describe(error)}`;\n if (!this.warmFailureLogged) {\n this.warmFailureLogged = true;\n console.error(`[content-ir] ${message}`);\n }\n this.reportError({\n source: \"content-ir\",\n message,\n ...errorFields(error),\n raw: error,\n });\n this.warmPromise = null;\n });\n }\n return this.warmPromise;\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 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 * 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\nconst reportedSourcelessDbRows = 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 if (!resolution.componentSource || !resolution.componentSource.trim()) {\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\nexport interface IrRouteMarker {\n by: ComponentResolution[\"resolvedBy\"] | \"generic\";\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 const def = env.kinds.getDefinition(kind);\n const resolution = env.components.resolve(kind, env.platform, \"output\");\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 emitter,\n // TEACHING CONTENT showing an example `__kind` payload for a hypothetical\n // kind) is genuinely unknown — we cannot claim to \"know this shape\", so the\n // strangler seam holds and the host's own rendering stands, untouched and by\n // reference. Note the boundary: a kind-PRESERVED raw whose definition IS\n // registered never reaches here — `def` resolves above and it routes;\n // registration is what separates \"known but unrenderable\" from \"not ours to\n // claim\". A repaint hook upgrades this block the moment the registries learn\n // the kind.\n return block;\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/content-ir-system/STREAMING_PARTIAL_KINDS.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 IR_ENVELOPE_KEY,\n IR_PARTIAL_KEY,\n IR_VERSION,\n isProvisionalKind,\n readEnvelope,\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 */\nconst partialUnsafeKinds = 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\n/**\n * Resolve a block's provisional render, or null when there is nothing to show\n * provisionally (no event, a terminal event, a withheld kind, a kind nothing\n * can route, or a verified envelope that already won).\n *\n * Pure: no React, no host state, no side effects beyond the registry reads.\n */\nexport function resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n>(\n block: T,\n env: KindRouteEnv,\n options?: PartialRenderOptions,\n): ProvisionalKindRender<T> | null {\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n // Terminal (superseded / retracted) → no provisional render, in this frame.\n if (!isProvisionalKind(event)) return null;\n\n const kind = event.root.kind;\n if (!isPartialReadyKind(kind, env)) return null;\n\n // A verified envelope that has already completed is the truth — a late or\n // duplicated partial must never displace it.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n\n const envelope = envelopeFromPartialKind(event);\n\n const provisionalBlock = {\n ...block,\n // The raw region annotation (`{ language: \"json\" }`) is not kind data —\n // same poison rule the verified route follows.\n serverData: undefined,\n metadata: {\n ...rest,\n [IR_ENVELOPE_KEY]: envelope,\n [IR_PROVISIONAL_KEY]: true,\n },\n } as T;\n\n const routed = applyIrKindRoute(provisionalBlock, env, options);\n // Nothing claimed it (unknown kind, no component) — `applyIrKindRoute`\n // returns the SAME reference. Withhold rather than render raw partial JSON.\n if (routed === provisionalBlock) return null;\n // A bridged kind whose bridge DECLINED this value (too thin to render — a\n // quiz with no answerable question yet) routed on type alone, which would\n // hand the component the partial JSON text to parse. Withhold: the loading\n // skeleton stays up for this frame and the next `seq` tries again.\n if (\n env.kinds.getDefinition(kind)?.toLegacyServerData &&\n !(routed as { serverData?: unknown }).serverData\n ) {\n return null;\n }\n\n return { block: routed, kind, seq: event.seq, envelope };\n}\n","\"use client\";\n\n/**\n * Late-arrival repaint for the streaming render path — GRANULAR.\n *\n * `applyIrKindRoute` is a pure, synchronous read of two registries. When a\n * schema or component row lands AFTER a block rendered — a cold fetch losing\n * the race with the region end, the warm list resolving mid-conversation —\n * nothing in React state changes, so the block would stay stuck on its\n * pre-arrival rendering (raw JSON / generic) forever.\n *\n * Granularity contract: each consumer subscribes to ONE kind's version\n * (per-kind counters in both registries, plus a rare wholesale epoch). A\n * cold/warm arrival for kind X re-renders only mounted blocks of kind X —\n * never every block in every conversation. In a host WITHOUT the React\n * Compiler, pair this with an explicit `useMemo` on (block, version) so the\n * route itself does not re-execute on unrelated renders.\n */\n\nimport { useCallback, useSyncExternalStore } from \"react\";\nimport { useContentIrHostOrNull } from \"../host/ContentIrProvider\";\nimport type {\n ContentIrHost,\n KindDefinitionSource,\n} from \"../host/host-types\";\nimport type { ComponentResolutionSource } from \"../resolver/component-resolution.types\";\n\n/**\n * The two registries this hook watches. Passed explicitly by a host whose\n * render path sits BELOW no provider — matrx-frontend's block renderer runs\n * deep inside chat, workflow, and canvas trees that predate this package, and\n * threading a provider through all of them to read two counters would be the\n * tail wagging the dog.\n */\nexport interface KindVersionSources {\n kinds: Pick<KindDefinitionSource, \"getKindVersion\" | \"subscribeKind\">;\n components: Pick<ComponentResolutionSource, \"getKindVersion\" | \"subscribeKind\">;\n}\n\nconst noopSubscribe = () => () => {};\nconst zero = () => 0;\n\n/**\n * Subscribes the caller to registry changes FOR ONE KIND and returns that\n * kind's combined version. Pass null for blocks with no envelope kind — they\n * never repaint from registries (nothing to learn about them).\n *\n * `sources` defaults to the provider's host. Passing them explicitly is the\n * supported way to use this hook outside a provider.\n */\nexport function useContentIrKindVersion(\n kind: string | null,\n sources?: KindVersionSources,\n): number {\n const host: ContentIrHost | null = useContentIrHostOrNull();\n const resolved: KindVersionSources | null = sources ?? host;\n\n if (kind && !resolved) {\n throw new Error(\n \"[content-ir-react] useContentIrKindVersion needs either a \" +\n \"ContentIrRenderProvider above it or explicit `sources`.\",\n );\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!kind || !resolved) return noopSubscribe();\n const unsubKinds = resolved.kinds.subscribeKind(kind, onStoreChange);\n const unsubComponents = resolved.components.subscribeKind(\n kind,\n onStoreChange,\n );\n return () => {\n unsubKinds();\n unsubComponents();\n };\n },\n [resolved, kind],\n );\n\n const getSnapshot = useCallback(\n () =>\n kind && resolved\n ? // Both counters are monotonic, so the sum is monotonic — a change in\n // either registry produces a new snapshot value for this kind.\n resolved.kinds.getKindVersion(kind) +\n resolved.components.getKindVersion(kind)\n : 0,\n [resolved, kind],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, zero);\n}\n","\"use client\";\n\n/**\n * KindInstanceRender — render ONE canonical kind instance through the REAL\n * production path, never a lookalike.\n *\n * The value object is wrapped by the kernel's complete-envelope assembler\n * (`envelopeFromCompleteValue`), placed on a raw render block's\n * `metadata.__ir`, and handed to the host's block renderer — which runs\n * `applyIrKindRoute` exactly as it does for streamed content (db-sourced\n * `kind_component` renderers resolve through the same route automatically).\n *\n * If the kind has no registered component/bridge, the value renders through\n * the host's structured-value FLOOR (`renderValue`) — the platform seam that\n * turns any JSON value into a human document. It used to become a ```json code\n * block instead, which is what put 19 of 23 Study Pack steps in front of a\n * non-technical reader as a JSON dump (2026-08-18). A curated `kind_component`\n * is an UPGRADE over a good default, never the prerequisite for one.\n *\n * THIS IS THE COMPONENT EVERY UI NEEDS. It is the door between \"I am holding a\n * kind-shaped value\" and \"the reader sees it drawn properly\", and it was the\n * single biggest reason a second UI could not render a kind: the routing\n * three-state lifecycle, the eager targeted resolve, the warm-then-refresh\n * order, and the \"checking is not the same as missing\" rule are all subtle and\n * were all trapped inside matrx-frontend.\n */\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { envelopeFromCompleteValue, IR_ENVELOPE_KEY } from \"@ai-matrx/content-ir\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport type { ContentIrHost } from \"../host/host-types\";\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 */\nexport function kindIsRoutable(kind: string, host: ContentIrHost): boolean {\n if (host.kinds.getDefinition(kind)?.legacyBlockType) return true;\n return Boolean(\n host.components.resolve(kind, host.platform, \"output\")?.isActive,\n );\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({\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 * 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/content-ir-system/STREAMING_PARTIAL_KINDS.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 : \"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/content-ir-system/RUNTIME_WRAPPER_WIRE.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"]}
|
|
1
|
+
{"version":3,"sources":["../host/error-report.ts","../host/host-types.ts","../host/ContentIrProvider.tsx","../resolver/component-resolver.ts","../route/kind-route.ts","../route/partial-kind-route.ts","../react/use-kind-version.ts","../react/KindInstanceRender.tsx","../react/ProvisionalKindBoundary.tsx","../react/GenericStructuredView.tsx","../react/RuntimeWrapperViews.tsx"],"names":["createContext","useContext","useMemo","readEnvelope","readObjectKind","envelopeFromCompleteValue","IR_VERSION","readPartialKindEvent","isProvisionalKind","IR_PARTIAL_KEY","IR_ENVELOPE_KEY","useCallback","useSyncExternalStore","useState","useEffect","jsx","Fragment","React","jsxs","reconstructRegionValue","isRecord","readNodeOutcomeValue","readRunResultValue"],"mappings":";;;;;;;;;;;AA2BO,IAAM,oBAAA,GAA+C,CAAC,MAAA,KAAW;AACtE,EAAA,OAAA,CAAQ,MAAM,CAAA,aAAA,EAAgB,MAAA,CAAO,OAAO,CAAA,CAAA,EAAI,MAAA,CAAO,OAAO,EAAE,CAAA;AAClE;;;AC2GO,SAAS,WAAW,IAAA,EAAmC;AAC5D,EAAA,OAAO;AAAA,IACL,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,UAAU,IAAA,CAAK;AAAA,GACjB;AACF;ACvHA,IAAM,oBAAA,GAAuBA,oBAAoC,IAAI,CAAA;AAO9D,SAAS,uBAAA,CAAwB;AAAA,EACtC,IAAA;AAAA,EACA;AACF,CAAA,EAAiC;AAC/B,EAAA,sCACG,oBAAA,CAAqB,QAAA,EAArB,EAA8B,KAAA,EAAO,MACnC,QAAA,EACH,CAAA;AAEJ;AAOO,SAAS,sBAAA,GAA+C;AAC7D,EAAA,OAAOC,iBAAW,oBAAoB,CAAA;AACxC;AAGO,SAAS,gBAAA,GAAkC;AAChD,EAAA,MAAM,OAAO,sBAAA,EAAuB;AACpC,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAGO,SAAS,eAAA,GAAgC;AAC9C,EAAA,MAAM,OAAO,gBAAA,EAAiB;AAC9B,EAAA,OAAOC,cAAQ,MAAM,UAAA,CAAW,IAAI,CAAA,EAAG,CAAC,IAAI,CAAC,CAAA;AAC/C;;;AClBA,IAAM,aA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AS,OAAO,IAAA;AAErB,EAAA,uBACEN,cAAAA;AAAA,IAAC,eAAA;AAAA,IAAA;AAAA,MACC,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,cAAc,OAAA,CAAQ,WAAA;AAAA,MACrB,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA;AAAS;AAAA,GAChD;AAEJ;AAmBO,SAAS,aAAA,CAAc,EAAE,UAAA,EAAY,QAAA,EAAS,EAAuB;AAC1E,EAAA,MAAM,OAAA,GAAU,eAAA;AAAA,IACd,UAAA;AAAA,IACAO;AAAA,GACF;AACA,EAAA,IAAI,CAAC,SAAS,OAAO,IAAA;AAErB,EAAA,uBACEP,cAAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAU,aACZ,QAAA,EAAA,OAAA,CAAQ,OAAA,CAAQ,MAAA,GAAS,CAAA,GACxB,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,CAAC,4BACnBA,cAAAA;AAAA,IAAC,eAAA;AAAA,IAAA;AAAA,MAEC,UAAA,EAAY,EAAE,OAAA,EAAS,OAAA,EAAQ;AAAA,MAC9B,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA;AAAS,KAAA;AAAA,IAFzC,CAAA,EAAG,OAAA,CAAQ,OAAO,CAAA,CAAA,EAAI,QAAQ,OAAO,CAAA;AAAA,GAI7C,oBAEDA,cAAAA;AAAA,IAAC,eAAA;AAAA,IAAA;AAAA,MACC,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,cAAc,OAAA,CAAQ,WAAA;AAAA,MACrB,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA;AAAS;AAAA,GAChD,EAEJ,CAAA;AAEJ","file":"index.cjs","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\";\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\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 components: Pick<ComponentResolutionSource, \"resolve\">;\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\";\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 {children}\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","/**\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\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 private warmFailureLogged = 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 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 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 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 if (changedKinds.size > 0) {\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\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 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 * 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.resolve(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\n void (async () => {\n try {\n this.ingestDbRows(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.resolve(kind, platform, role)) this.coldMisses.add(missKey);\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 }\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 })\n .catch((error: unknown) => {\n // Loud recovery: the compiled floor keeps rendering, but a warm\n // failure is a real defect — one console scream (first failure) plus\n // a structured report per attempt, then retryable.\n const message = `component-resolver warm load failed (compiled bootstrap still serving): ${describe(error)}`;\n if (!this.warmFailureLogged) {\n this.warmFailureLogged = true;\n console.error(`[content-ir] ${message}`);\n }\n this.reportError({\n source: \"content-ir\",\n message,\n ...errorFields(error),\n raw: error,\n });\n this.warmPromise = null;\n });\n }\n return this.warmPromise;\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 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 * 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\nconst reportedSourcelessDbRows = 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 if (!resolution.componentSource || !resolution.componentSource.trim()) {\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 but its value failed the schema (or the schema never\n * arrived before the region closed). The instance is BROKEN, not\n * component-less — the repair is fixing the payload/schema, and the generic\n * floor must acknowledge the kind and surface the recorded problems.\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\";\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 const def = env.kinds.getDefinition(kind);\n const resolution = env.components.resolve(kind, env.platform, \"output\");\n\n // A kind-PRESERVED raw is a BROKEN instance (2026-08-29): the payload named\n // a kind and failed its schema (or the schema never arrived before region\n // end). No component — bridge or db — may claim a non-compliant value; the\n // generic floor acknowledges the kind and the envelope's recorded problems\n // (residue notices, the raw_fallback reason) are the host's to show. An\n // UNREGISTERED slug routes too — `reason: \"unregistered\"` (Arman's ruling,\n // 2026-08-29: a root `__kind` key means the kind system owns the render, NO\n // exceptions — the old \"not ours to claim\" carve-out for teaching\n // content/typos is retired). Repaint upgrades it the moment the registries\n // learn more.\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/content-ir-system/STREAMING_PARTIAL_KINDS.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 IR_ENVELOPE_KEY,\n IR_PARTIAL_KEY,\n IR_VERSION,\n isProvisionalKind,\n readEnvelope,\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 */\nconst partialUnsafeKinds = 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\n/**\n * Resolve a block's provisional render, or null when there is nothing to show\n * provisionally (no event, a terminal event, a withheld kind, a kind nothing\n * can route, or a verified envelope that already won).\n *\n * Pure: no React, no host state, no side effects beyond the registry reads.\n */\nexport function resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n>(\n block: T,\n env: KindRouteEnv,\n options?: PartialRenderOptions,\n): ProvisionalKindRender<T> | null {\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n // Terminal (superseded / retracted) → no provisional render, in this frame.\n if (!isProvisionalKind(event)) return null;\n\n const kind = event.root.kind;\n if (!isPartialReadyKind(kind, env)) return null;\n\n // A verified envelope that has already completed is the truth — a late or\n // duplicated partial must never displace it.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n\n const envelope = envelopeFromPartialKind(event);\n\n const provisionalBlock = {\n ...block,\n // The raw region annotation (`{ language: \"json\" }`) is not kind data —\n // same poison rule the verified route follows.\n serverData: undefined,\n metadata: {\n ...rest,\n [IR_ENVELOPE_KEY]: envelope,\n [IR_PROVISIONAL_KEY]: true,\n },\n } as T;\n\n const routed = applyIrKindRoute(provisionalBlock, env, options);\n // Nothing claimed it (unknown kind, no component) — `applyIrKindRoute`\n // returns the SAME reference. Withhold rather than render raw partial JSON.\n if (routed === provisionalBlock) return null;\n // A bridged kind whose bridge DECLINED this value (too thin to render — a\n // quiz with no answerable question yet) routed on type alone, which would\n // hand the component the partial JSON text to parse. Withhold: the loading\n // skeleton stays up for this frame and the next `seq` tries again.\n if (\n env.kinds.getDefinition(kind)?.toLegacyServerData &&\n !(routed as { serverData?: unknown }).serverData\n ) {\n return null;\n }\n\n return { block: routed, kind, seq: event.seq, envelope };\n}\n","\"use client\";\n\n/**\n * Late-arrival repaint for the streaming render path — GRANULAR.\n *\n * `applyIrKindRoute` is a pure, synchronous read of two registries. When a\n * schema or component row lands AFTER a block rendered — a cold fetch losing\n * the race with the region end, the warm list resolving mid-conversation —\n * nothing in React state changes, so the block would stay stuck on its\n * pre-arrival rendering (raw JSON / generic) forever.\n *\n * Granularity contract: each consumer subscribes to ONE kind's version\n * (per-kind counters in both registries, plus a rare wholesale epoch). A\n * cold/warm arrival for kind X re-renders only mounted blocks of kind X —\n * never every block in every conversation. In a host WITHOUT the React\n * Compiler, pair this with an explicit `useMemo` on (block, version) so the\n * route itself does not re-execute on unrelated renders.\n */\n\nimport { useCallback, useSyncExternalStore } from \"react\";\nimport { useContentIrHostOrNull } from \"../host/ContentIrProvider\";\nimport type {\n ContentIrHost,\n KindDefinitionSource,\n} from \"../host/host-types\";\nimport type { ComponentResolutionSource } from \"../resolver/component-resolution.types\";\n\n/**\n * The two registries this hook watches. Passed explicitly by a host whose\n * render path sits BELOW no provider — matrx-frontend's block renderer runs\n * deep inside chat, workflow, and canvas trees that predate this package, and\n * threading a provider through all of them to read two counters would be the\n * tail wagging the dog.\n */\nexport interface KindVersionSources {\n kinds: Pick<KindDefinitionSource, \"getKindVersion\" | \"subscribeKind\">;\n components: Pick<ComponentResolutionSource, \"getKindVersion\" | \"subscribeKind\">;\n}\n\nconst noopSubscribe = () => () => {};\nconst zero = () => 0;\n\n/**\n * Subscribes the caller to registry changes FOR ONE KIND and returns that\n * kind's combined version. Pass null for blocks with no envelope kind — they\n * never repaint from registries (nothing to learn about them).\n *\n * `sources` defaults to the provider's host. Passing them explicitly is the\n * supported way to use this hook outside a provider.\n */\nexport function useContentIrKindVersion(\n kind: string | null,\n sources?: KindVersionSources,\n): number {\n const host: ContentIrHost | null = useContentIrHostOrNull();\n const resolved: KindVersionSources | null = sources ?? host;\n\n if (kind && !resolved) {\n throw new Error(\n \"[content-ir-react] useContentIrKindVersion needs either a \" +\n \"ContentIrRenderProvider above it or explicit `sources`.\",\n );\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!kind || !resolved) return noopSubscribe();\n const unsubKinds = resolved.kinds.subscribeKind(kind, onStoreChange);\n const unsubComponents = resolved.components.subscribeKind(\n kind,\n onStoreChange,\n );\n return () => {\n unsubKinds();\n unsubComponents();\n };\n },\n [resolved, kind],\n );\n\n const getSnapshot = useCallback(\n () =>\n kind && resolved\n ? // Both counters are monotonic, so the sum is monotonic — a change in\n // either registry produces a new snapshot value for this kind.\n resolved.kinds.getKindVersion(kind) +\n resolved.components.getKindVersion(kind)\n : 0,\n [resolved, kind],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, zero);\n}\n","\"use client\";\n\n/**\n * KindInstanceRender — render ONE canonical kind instance through the REAL\n * production path, never a lookalike.\n *\n * The value object is wrapped by the kernel's complete-envelope assembler\n * (`envelopeFromCompleteValue`), placed on a raw render block's\n * `metadata.__ir`, and handed to the host's block renderer — which runs\n * `applyIrKindRoute` exactly as it does for streamed content (db-sourced\n * `kind_component` renderers resolve through the same route automatically).\n *\n * If the kind has no registered component/bridge, the value renders through\n * the host's structured-value FLOOR (`renderValue`) — the platform seam that\n * turns any JSON value into a human document. It used to become a ```json code\n * block instead, which is what put 19 of 23 Study Pack steps in front of a\n * non-technical reader as a JSON dump (2026-08-18). A curated `kind_component`\n * is an UPGRADE over a good default, never the prerequisite for one.\n *\n * THIS IS THE COMPONENT EVERY UI NEEDS. It is the door between \"I am holding a\n * kind-shaped value\" and \"the reader sees it drawn properly\", and it was the\n * single biggest reason a second UI could not render a kind: the routing\n * three-state lifecycle, the eager targeted resolve, the warm-then-refresh\n * order, and the \"checking is not the same as missing\" rule are all subtle and\n * were all trapped inside matrx-frontend.\n */\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { envelopeFromCompleteValue, IR_ENVELOPE_KEY } from \"@ai-matrx/content-ir\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport type { ContentIrHost } from \"../host/host-types\";\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 */\nexport function kindIsRoutable(kind: string, host: ContentIrHost): boolean {\n if (host.kinds.getDefinition(kind)?.legacyBlockType) return true;\n return Boolean(\n host.components.resolve(kind, host.platform, \"output\")?.isActive,\n );\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({\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 * 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/content-ir-system/STREAMING_PARTIAL_KINDS.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/content-ir-system/RUNTIME_WRAPPER_WIRE.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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -452,7 +452,22 @@ type GenericFallbackReason =
|
|
|
452
452
|
* kinds came to be certified as renderable while rendering generically
|
|
453
453
|
* (found 2026-08-23).
|
|
454
454
|
*/
|
|
455
|
-
| "generic-row"
|
|
455
|
+
| "generic-row"
|
|
456
|
+
/**
|
|
457
|
+
* The envelope carries a kind-preserved RAW: the payload identified a
|
|
458
|
+
* registered kind but its value failed the schema (or the schema never
|
|
459
|
+
* arrived before the region closed). The instance is BROKEN, not
|
|
460
|
+
* component-less — the repair is fixing the payload/schema, and the generic
|
|
461
|
+
* floor must acknowledge the kind and surface the recorded problems.
|
|
462
|
+
*/
|
|
463
|
+
| "broken-instance"
|
|
464
|
+
/**
|
|
465
|
+
* The slug is not in the registry at all (typo, foreign emitter, a shape
|
|
466
|
+
* not yet created). Routed anyway — Arman's 2026-08-29 ruling: a root
|
|
467
|
+
* `__kind` key means the kind system owns the render, no exceptions. The
|
|
468
|
+
* repair is creating/registering the shape (or fixing the slug).
|
|
469
|
+
*/
|
|
470
|
+
| "unregistered";
|
|
456
471
|
interface IrRouteMarker {
|
|
457
472
|
by: ComponentResolution["resolvedBy"] | "generic";
|
|
458
473
|
key: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -452,7 +452,22 @@ type GenericFallbackReason =
|
|
|
452
452
|
* kinds came to be certified as renderable while rendering generically
|
|
453
453
|
* (found 2026-08-23).
|
|
454
454
|
*/
|
|
455
|
-
| "generic-row"
|
|
455
|
+
| "generic-row"
|
|
456
|
+
/**
|
|
457
|
+
* The envelope carries a kind-preserved RAW: the payload identified a
|
|
458
|
+
* registered kind but its value failed the schema (or the schema never
|
|
459
|
+
* arrived before the region closed). The instance is BROKEN, not
|
|
460
|
+
* component-less — the repair is fixing the payload/schema, and the generic
|
|
461
|
+
* floor must acknowledge the kind and surface the recorded problems.
|
|
462
|
+
*/
|
|
463
|
+
| "broken-instance"
|
|
464
|
+
/**
|
|
465
|
+
* The slug is not in the registry at all (typo, foreign emitter, a shape
|
|
466
|
+
* not yet created). Routed anyway — Arman's 2026-08-29 ruling: a root
|
|
467
|
+
* `__kind` key means the kind system owns the render, no exceptions. The
|
|
468
|
+
* repair is creating/registering the shape (or fixing the slug).
|
|
469
|
+
*/
|
|
470
|
+
| "unregistered";
|
|
456
471
|
interface IrRouteMarker {
|
|
457
472
|
by: ComponentResolution["resolvedBy"] | "generic";
|
|
458
473
|
key: string;
|
package/dist/index.js
CHANGED
|
@@ -381,6 +381,12 @@ function applyIrKindRoute(block, env, options) {
|
|
|
381
381
|
if (envelope.root.kindState === "pending_schema") return block;
|
|
382
382
|
const def = env.kinds.getDefinition(kind);
|
|
383
383
|
const resolution = env.components.resolve(kind, env.platform, "output");
|
|
384
|
+
if (envelope.root.kindState === "raw") {
|
|
385
|
+
return routeToGeneric(
|
|
386
|
+
block,
|
|
387
|
+
def || resolution ? "broken-instance" : "unregistered"
|
|
388
|
+
);
|
|
389
|
+
}
|
|
384
390
|
const dbRouted = routeToDbComponent(block, kind, resolution, env);
|
|
385
391
|
if (dbRouted) return dbRouted;
|
|
386
392
|
if (def?.legacyBlockType) {
|
|
@@ -413,7 +419,7 @@ function applyIrKindRoute(block, env, options) {
|
|
|
413
419
|
if (def) {
|
|
414
420
|
return routeToGeneric(block, resolution ? "inactive" : "no-component");
|
|
415
421
|
}
|
|
416
|
-
return block;
|
|
422
|
+
return routeToGeneric(block, "unregistered");
|
|
417
423
|
}
|
|
418
424
|
function kindServerDataFromStoredValue(value, env) {
|
|
419
425
|
if (!isRecord(value)) return null;
|
|
@@ -647,7 +653,7 @@ function GenericStructuredView({
|
|
|
647
653
|
const { value, recovered } = readStructuredValue(content, metadata);
|
|
648
654
|
const kind = envelope?.root.kind ?? (typeof value === "object" && value !== null && !Array.isArray(value) ? readObjectKind(value) : null) ?? "";
|
|
649
655
|
const marker = readIrRouteMarker(metadata);
|
|
650
|
-
const note = marker?.reason === "inactive" ? "a custom view is registered but held inactive" : "no custom view yet";
|
|
656
|
+
const note = marker?.reason === "inactive" ? "a custom view is registered but held inactive" : marker?.reason === "broken-instance" ? "this instance did not match the shape's schema" : marker?.reason === "unregistered" ? "this shape isn't registered on this platform" : "no custom view yet";
|
|
651
657
|
return /* @__PURE__ */ jsxs("div", { className: className ? `my-2 min-w-0 ${className}` : "my-2 min-w-0", children: [
|
|
652
658
|
status === "streaming" ? streamingIndicator ?? /* @__PURE__ */ jsx("div", { className: "mb-2 text-xs text-muted-foreground", children: "Still arriving\u2026" }) : null,
|
|
653
659
|
recovered ? host.renderValue({ value, ...kind ? { kind } : {}, note }) : (
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../host/error-report.ts","../host/host-types.ts","../host/ContentIrProvider.tsx","../resolver/component-resolver.ts","../route/kind-route.ts","../route/partial-kind-route.ts","../react/use-kind-version.ts","../react/KindInstanceRender.tsx","../react/ProvisionalKindBoundary.tsx","../react/GenericStructuredView.tsx","../react/RuntimeWrapperViews.tsx"],"names":["readEnvelope","IR_ENVELOPE_KEY","envelopeFromCompleteValue","jsx","jsxs","readObjectKind","isRecord","Fragment"],"mappings":";;;;;AA2BO,IAAM,oBAAA,GAA+C,CAAC,MAAA,KAAW;AACtE,EAAA,OAAA,CAAQ,MAAM,CAAA,aAAA,EAAgB,MAAA,CAAO,OAAO,CAAA,CAAA,EAAI,MAAA,CAAO,OAAO,EAAE,CAAA;A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GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA;AAAS,KAAA;AAAA,IAFzC,CAAA,EAAG,OAAA,CAAQ,OAAO,CAAA,CAAA,EAAI,QAAQ,OAAO,CAAA;AAAA,GAI7C,oBAEDA,GAAAA;AAAA,IAAC,eAAA;AAAA,IAAA;AAAA,MACC,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,cAAc,OAAA,CAAQ,WAAA;AAAA,MACrB,GAAI,QAAA,KAAa,MAAA,GAAY,EAAC,GAAI,EAAE,QAAA;AAAS;AAAA,GAChD,EAEJ,CAAA;AAEJ","file":"index.js","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\";\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\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 components: Pick<ComponentResolutionSource, \"resolve\">;\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\";\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 {children}\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","/**\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\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 private warmFailureLogged = 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 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 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 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 if (changedKinds.size > 0) {\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\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 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 * 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.resolve(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\n void (async () => {\n try {\n this.ingestDbRows(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.resolve(kind, platform, role)) this.coldMisses.add(missKey);\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 }\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 })\n .catch((error: unknown) => {\n // Loud recovery: the compiled floor keeps rendering, but a warm\n // failure is a real defect — one console scream (first failure) plus\n // a structured report per attempt, then retryable.\n const message = `component-resolver warm load failed (compiled bootstrap still serving): ${describe(error)}`;\n if (!this.warmFailureLogged) {\n this.warmFailureLogged = true;\n console.error(`[content-ir] ${message}`);\n }\n this.reportError({\n source: \"content-ir\",\n message,\n ...errorFields(error),\n raw: error,\n });\n this.warmPromise = null;\n });\n }\n return this.warmPromise;\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 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 * 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\nconst reportedSourcelessDbRows = 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 if (!resolution.componentSource || !resolution.componentSource.trim()) {\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\nexport interface IrRouteMarker {\n by: ComponentResolution[\"resolvedBy\"] | \"generic\";\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 const def = env.kinds.getDefinition(kind);\n const resolution = env.components.resolve(kind, env.platform, \"output\");\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 emitter,\n // TEACHING CONTENT showing an example `__kind` payload for a hypothetical\n // kind) is genuinely unknown — we cannot claim to \"know this shape\", so the\n // strangler seam holds and the host's own rendering stands, untouched and by\n // reference. Note the boundary: a kind-PRESERVED raw whose definition IS\n // registered never reaches here — `def` resolves above and it routes;\n // registration is what separates \"known but unrenderable\" from \"not ours to\n // claim\". A repaint hook upgrades this block the moment the registries learn\n // the kind.\n return block;\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/content-ir-system/STREAMING_PARTIAL_KINDS.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 IR_ENVELOPE_KEY,\n IR_PARTIAL_KEY,\n IR_VERSION,\n isProvisionalKind,\n readEnvelope,\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 */\nconst partialUnsafeKinds = 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\n/**\n * Resolve a block's provisional render, or null when there is nothing to show\n * provisionally (no event, a terminal event, a withheld kind, a kind nothing\n * can route, or a verified envelope that already won).\n *\n * Pure: no React, no host state, no side effects beyond the registry reads.\n */\nexport function resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n>(\n block: T,\n env: KindRouteEnv,\n options?: PartialRenderOptions,\n): ProvisionalKindRender<T> | null {\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n // Terminal (superseded / retracted) → no provisional render, in this frame.\n if (!isProvisionalKind(event)) return null;\n\n const kind = event.root.kind;\n if (!isPartialReadyKind(kind, env)) return null;\n\n // A verified envelope that has already completed is the truth — a late or\n // duplicated partial must never displace it.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n\n const envelope = envelopeFromPartialKind(event);\n\n const provisionalBlock = {\n ...block,\n // The raw region annotation (`{ language: \"json\" }`) is not kind data —\n // same poison rule the verified route follows.\n serverData: undefined,\n metadata: {\n ...rest,\n [IR_ENVELOPE_KEY]: envelope,\n [IR_PROVISIONAL_KEY]: true,\n },\n } as T;\n\n const routed = applyIrKindRoute(provisionalBlock, env, options);\n // Nothing claimed it (unknown kind, no component) — `applyIrKindRoute`\n // returns the SAME reference. Withhold rather than render raw partial JSON.\n if (routed === provisionalBlock) return null;\n // A bridged kind whose bridge DECLINED this value (too thin to render — a\n // quiz with no answerable question yet) routed on type alone, which would\n // hand the component the partial JSON text to parse. Withhold: the loading\n // skeleton stays up for this frame and the next `seq` tries again.\n if (\n env.kinds.getDefinition(kind)?.toLegacyServerData &&\n !(routed as { serverData?: unknown }).serverData\n ) {\n return null;\n }\n\n return { block: routed, kind, seq: event.seq, envelope };\n}\n","\"use client\";\n\n/**\n * Late-arrival repaint for the streaming render path — GRANULAR.\n *\n * `applyIrKindRoute` is a pure, synchronous read of two registries. When a\n * schema or component row lands AFTER a block rendered — a cold fetch losing\n * the race with the region end, the warm list resolving mid-conversation —\n * nothing in React state changes, so the block would stay stuck on its\n * pre-arrival rendering (raw JSON / generic) forever.\n *\n * Granularity contract: each consumer subscribes to ONE kind's version\n * (per-kind counters in both registries, plus a rare wholesale epoch). A\n * cold/warm arrival for kind X re-renders only mounted blocks of kind X —\n * never every block in every conversation. In a host WITHOUT the React\n * Compiler, pair this with an explicit `useMemo` on (block, version) so the\n * route itself does not re-execute on unrelated renders.\n */\n\nimport { useCallback, useSyncExternalStore } from \"react\";\nimport { useContentIrHostOrNull } from \"../host/ContentIrProvider\";\nimport type {\n ContentIrHost,\n KindDefinitionSource,\n} from \"../host/host-types\";\nimport type { ComponentResolutionSource } from \"../resolver/component-resolution.types\";\n\n/**\n * The two registries this hook watches. Passed explicitly by a host whose\n * render path sits BELOW no provider — matrx-frontend's block renderer runs\n * deep inside chat, workflow, and canvas trees that predate this package, and\n * threading a provider through all of them to read two counters would be the\n * tail wagging the dog.\n */\nexport interface KindVersionSources {\n kinds: Pick<KindDefinitionSource, \"getKindVersion\" | \"subscribeKind\">;\n components: Pick<ComponentResolutionSource, \"getKindVersion\" | \"subscribeKind\">;\n}\n\nconst noopSubscribe = () => () => {};\nconst zero = () => 0;\n\n/**\n * Subscribes the caller to registry changes FOR ONE KIND and returns that\n * kind's combined version. Pass null for blocks with no envelope kind — they\n * never repaint from registries (nothing to learn about them).\n *\n * `sources` defaults to the provider's host. Passing them explicitly is the\n * supported way to use this hook outside a provider.\n */\nexport function useContentIrKindVersion(\n kind: string | null,\n sources?: KindVersionSources,\n): number {\n const host: ContentIrHost | null = useContentIrHostOrNull();\n const resolved: KindVersionSources | null = sources ?? host;\n\n if (kind && !resolved) {\n throw new Error(\n \"[content-ir-react] useContentIrKindVersion needs either a \" +\n \"ContentIrRenderProvider above it or explicit `sources`.\",\n );\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!kind || !resolved) return noopSubscribe();\n const unsubKinds = resolved.kinds.subscribeKind(kind, onStoreChange);\n const unsubComponents = resolved.components.subscribeKind(\n kind,\n onStoreChange,\n );\n return () => {\n unsubKinds();\n unsubComponents();\n };\n },\n [resolved, kind],\n );\n\n const getSnapshot = useCallback(\n () =>\n kind && resolved\n ? // Both counters are monotonic, so the sum is monotonic — a change in\n // either registry produces a new snapshot value for this kind.\n resolved.kinds.getKindVersion(kind) +\n resolved.components.getKindVersion(kind)\n : 0,\n [resolved, kind],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, zero);\n}\n","\"use client\";\n\n/**\n * KindInstanceRender — render ONE canonical kind instance through the REAL\n * production path, never a lookalike.\n *\n * The value object is wrapped by the kernel's complete-envelope assembler\n * (`envelopeFromCompleteValue`), placed on a raw render block's\n * `metadata.__ir`, and handed to the host's block renderer — which runs\n * `applyIrKindRoute` exactly as it does for streamed content (db-sourced\n * `kind_component` renderers resolve through the same route automatically).\n *\n * If the kind has no registered component/bridge, the value renders through\n * the host's structured-value FLOOR (`renderValue`) — the platform seam that\n * turns any JSON value into a human document. It used to become a ```json code\n * block instead, which is what put 19 of 23 Study Pack steps in front of a\n * non-technical reader as a JSON dump (2026-08-18). A curated `kind_component`\n * is an UPGRADE over a good default, never the prerequisite for one.\n *\n * THIS IS THE COMPONENT EVERY UI NEEDS. It is the door between \"I am holding a\n * kind-shaped value\" and \"the reader sees it drawn properly\", and it was the\n * single biggest reason a second UI could not render a kind: the routing\n * three-state lifecycle, the eager targeted resolve, the warm-then-refresh\n * order, and the \"checking is not the same as missing\" rule are all subtle and\n * were all trapped inside matrx-frontend.\n */\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { envelopeFromCompleteValue, IR_ENVELOPE_KEY } from \"@ai-matrx/content-ir\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport type { ContentIrHost } from \"../host/host-types\";\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 */\nexport function kindIsRoutable(kind: string, host: ContentIrHost): boolean {\n if (host.kinds.getDefinition(kind)?.legacyBlockType) return true;\n return Boolean(\n host.components.resolve(kind, host.platform, \"output\")?.isActive,\n );\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({\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 * 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/content-ir-system/STREAMING_PARTIAL_KINDS.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 : \"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/content-ir-system/RUNTIME_WRAPPER_WIRE.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"]}
|
|
1
|
+
{"version":3,"sources":["../host/error-report.ts","../host/host-types.ts","../host/ContentIrProvider.tsx","../resolver/component-resolver.ts","../route/kind-route.ts","../route/partial-kind-route.ts","../react/use-kind-version.ts","../react/KindInstanceRender.tsx","../react/ProvisionalKindBoundary.tsx","../react/GenericStructuredView.tsx","../react/RuntimeWrapperViews.tsx"],"names":["readEnvelope","IR_ENVELOPE_KEY","envelopeFromCompleteValue","jsx","jsxs","readObjectKind","isRecord","Fragment"],"mappings":";;;;;AA2BO,IAAM,oBAAA,GAA+C,CAAC,MAAA,KAAW;AACtE,EAAA,OAAA,CAAQ,MAAM,CAAA,aAAA,EAAgB,MAAA,CAAO,OAAO,CAAA,CAAA,EAAI,MAAA,CAAO,OAAO,EAAE,CAAA;AAClE;;;AC2GO,SAAS,WAAW,IAAA,EAAmC;AAC5D,EAAA,OAAO;AAAA,IACL,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,UAAU,IAAA,CAAK;AAAA,GACjB;AACF;ACvHA,IAAM,oBAAA,GAAuB,cAAoC,IAAI,CAAA;AAO9D,SAAS,uBAAA,CAAwB;AAAA,EACtC,IAAA;AAAA,EACA;AACF,CAAA,EAAiC;AAC/B,EAAA,2BACG,oBAAA,CAAqB,QAAA,EAArB,EAA8B,KAAA,EAAO,MACnC,QAAA,EACH,CAAA;AAEJ;AAOO,SAAS,sBAAA,GAA+C;AAC7D,EAAA,OAAO,WAAW,oBAAoB,CAAA;AACxC;AAGO,SAAS,gBAAA,GAAkC;AAChD,EAAA,MAAM,OAAO,sBAAA,EAAuB;AACpC,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT;AAGO,SAAS,eAAA,GAAgC;AAC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AM.\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\";\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\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 components: Pick<ComponentResolutionSource, \"resolve\">;\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\";\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 {children}\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","/**\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\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 private warmFailureLogged = 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 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 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 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 if (changedKinds.size > 0) {\n for (const kind of changedKinds) this.bumpKind(kind);\n this.notifyChanged();\n }\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 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 * 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.resolve(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\n void (async () => {\n try {\n this.ingestDbRows(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.resolve(kind, platform, role)) this.coldMisses.add(missKey);\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 }\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 })\n .catch((error: unknown) => {\n // Loud recovery: the compiled floor keeps rendering, but a warm\n // failure is a real defect — one console scream (first failure) plus\n // a structured report per attempt, then retryable.\n const message = `component-resolver warm load failed (compiled bootstrap still serving): ${describe(error)}`;\n if (!this.warmFailureLogged) {\n this.warmFailureLogged = true;\n console.error(`[content-ir] ${message}`);\n }\n this.reportError({\n source: \"content-ir\",\n message,\n ...errorFields(error),\n raw: error,\n });\n this.warmPromise = null;\n });\n }\n return this.warmPromise;\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 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 * 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\nconst reportedSourcelessDbRows = 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 if (!resolution.componentSource || !resolution.componentSource.trim()) {\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 but its value failed the schema (or the schema never\n * arrived before the region closed). The instance is BROKEN, not\n * component-less — the repair is fixing the payload/schema, and the generic\n * floor must acknowledge the kind and surface the recorded problems.\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\";\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 const def = env.kinds.getDefinition(kind);\n const resolution = env.components.resolve(kind, env.platform, \"output\");\n\n // A kind-PRESERVED raw is a BROKEN instance (2026-08-29): the payload named\n // a kind and failed its schema (or the schema never arrived before region\n // end). No component — bridge or db — may claim a non-compliant value; the\n // generic floor acknowledges the kind and the envelope's recorded problems\n // (residue notices, the raw_fallback reason) are the host's to show. An\n // UNREGISTERED slug routes too — `reason: \"unregistered\"` (Arman's ruling,\n // 2026-08-29: a root `__kind` key means the kind system owns the render, NO\n // exceptions — the old \"not ours to claim\" carve-out for teaching\n // content/typos is retired). Repaint upgrades it the moment the registries\n // learn more.\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/content-ir-system/STREAMING_PARTIAL_KINDS.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 IR_ENVELOPE_KEY,\n IR_PARTIAL_KEY,\n IR_VERSION,\n isProvisionalKind,\n readEnvelope,\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 */\nconst partialUnsafeKinds = 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\n/**\n * Resolve a block's provisional render, or null when there is nothing to show\n * provisionally (no event, a terminal event, a withheld kind, a kind nothing\n * can route, or a verified envelope that already won).\n *\n * Pure: no React, no host state, no side effects beyond the registry reads.\n */\nexport function resolveProvisionalKindRender<\n T extends IrRoutableBlock & { metadata?: Record<string, unknown> },\n>(\n block: T,\n env: KindRouteEnv,\n options?: PartialRenderOptions,\n): ProvisionalKindRender<T> | null {\n if (options?.streamActive === false) return null;\n\n const event = readPartialKindEvent(block.metadata);\n // Terminal (superseded / retracted) → no provisional render, in this frame.\n if (!isProvisionalKind(event)) return null;\n\n const kind = event.root.kind;\n if (!isPartialReadyKind(kind, env)) return null;\n\n // A verified envelope that has already completed is the truth — a late or\n // duplicated partial must never displace it.\n const verified = readEnvelope(block.metadata);\n if (verified && verified.root.status === \"complete\") return null;\n\n const { [IR_PARTIAL_KEY]: _partial, ...rest } = block.metadata ?? {};\n void _partial;\n\n const envelope = envelopeFromPartialKind(event);\n\n const provisionalBlock = {\n ...block,\n // The raw region annotation (`{ language: \"json\" }`) is not kind data —\n // same poison rule the verified route follows.\n serverData: undefined,\n metadata: {\n ...rest,\n [IR_ENVELOPE_KEY]: envelope,\n [IR_PROVISIONAL_KEY]: true,\n },\n } as T;\n\n const routed = applyIrKindRoute(provisionalBlock, env, options);\n // Nothing claimed it (unknown kind, no component) — `applyIrKindRoute`\n // returns the SAME reference. Withhold rather than render raw partial JSON.\n if (routed === provisionalBlock) return null;\n // A bridged kind whose bridge DECLINED this value (too thin to render — a\n // quiz with no answerable question yet) routed on type alone, which would\n // hand the component the partial JSON text to parse. Withhold: the loading\n // skeleton stays up for this frame and the next `seq` tries again.\n if (\n env.kinds.getDefinition(kind)?.toLegacyServerData &&\n !(routed as { serverData?: unknown }).serverData\n ) {\n return null;\n }\n\n return { block: routed, kind, seq: event.seq, envelope };\n}\n","\"use client\";\n\n/**\n * Late-arrival repaint for the streaming render path — GRANULAR.\n *\n * `applyIrKindRoute` is a pure, synchronous read of two registries. When a\n * schema or component row lands AFTER a block rendered — a cold fetch losing\n * the race with the region end, the warm list resolving mid-conversation —\n * nothing in React state changes, so the block would stay stuck on its\n * pre-arrival rendering (raw JSON / generic) forever.\n *\n * Granularity contract: each consumer subscribes to ONE kind's version\n * (per-kind counters in both registries, plus a rare wholesale epoch). A\n * cold/warm arrival for kind X re-renders only mounted blocks of kind X —\n * never every block in every conversation. In a host WITHOUT the React\n * Compiler, pair this with an explicit `useMemo` on (block, version) so the\n * route itself does not re-execute on unrelated renders.\n */\n\nimport { useCallback, useSyncExternalStore } from \"react\";\nimport { useContentIrHostOrNull } from \"../host/ContentIrProvider\";\nimport type {\n ContentIrHost,\n KindDefinitionSource,\n} from \"../host/host-types\";\nimport type { ComponentResolutionSource } from \"../resolver/component-resolution.types\";\n\n/**\n * The two registries this hook watches. Passed explicitly by a host whose\n * render path sits BELOW no provider — matrx-frontend's block renderer runs\n * deep inside chat, workflow, and canvas trees that predate this package, and\n * threading a provider through all of them to read two counters would be the\n * tail wagging the dog.\n */\nexport interface KindVersionSources {\n kinds: Pick<KindDefinitionSource, \"getKindVersion\" | \"subscribeKind\">;\n components: Pick<ComponentResolutionSource, \"getKindVersion\" | \"subscribeKind\">;\n}\n\nconst noopSubscribe = () => () => {};\nconst zero = () => 0;\n\n/**\n * Subscribes the caller to registry changes FOR ONE KIND and returns that\n * kind's combined version. Pass null for blocks with no envelope kind — they\n * never repaint from registries (nothing to learn about them).\n *\n * `sources` defaults to the provider's host. Passing them explicitly is the\n * supported way to use this hook outside a provider.\n */\nexport function useContentIrKindVersion(\n kind: string | null,\n sources?: KindVersionSources,\n): number {\n const host: ContentIrHost | null = useContentIrHostOrNull();\n const resolved: KindVersionSources | null = sources ?? host;\n\n if (kind && !resolved) {\n throw new Error(\n \"[content-ir-react] useContentIrKindVersion needs either a \" +\n \"ContentIrRenderProvider above it or explicit `sources`.\",\n );\n }\n\n const subscribe = useCallback(\n (onStoreChange: () => void) => {\n if (!kind || !resolved) return noopSubscribe();\n const unsubKinds = resolved.kinds.subscribeKind(kind, onStoreChange);\n const unsubComponents = resolved.components.subscribeKind(\n kind,\n onStoreChange,\n );\n return () => {\n unsubKinds();\n unsubComponents();\n };\n },\n [resolved, kind],\n );\n\n const getSnapshot = useCallback(\n () =>\n kind && resolved\n ? // Both counters are monotonic, so the sum is monotonic — a change in\n // either registry produces a new snapshot value for this kind.\n resolved.kinds.getKindVersion(kind) +\n resolved.components.getKindVersion(kind)\n : 0,\n [resolved, kind],\n );\n\n return useSyncExternalStore(subscribe, getSnapshot, zero);\n}\n","\"use client\";\n\n/**\n * KindInstanceRender — render ONE canonical kind instance through the REAL\n * production path, never a lookalike.\n *\n * The value object is wrapped by the kernel's complete-envelope assembler\n * (`envelopeFromCompleteValue`), placed on a raw render block's\n * `metadata.__ir`, and handed to the host's block renderer — which runs\n * `applyIrKindRoute` exactly as it does for streamed content (db-sourced\n * `kind_component` renderers resolve through the same route automatically).\n *\n * If the kind has no registered component/bridge, the value renders through\n * the host's structured-value FLOOR (`renderValue`) — the platform seam that\n * turns any JSON value into a human document. It used to become a ```json code\n * block instead, which is what put 19 of 23 Study Pack steps in front of a\n * non-technical reader as a JSON dump (2026-08-18). A curated `kind_component`\n * is an UPGRADE over a good default, never the prerequisite for one.\n *\n * THIS IS THE COMPONENT EVERY UI NEEDS. It is the door between \"I am holding a\n * kind-shaped value\" and \"the reader sees it drawn properly\", and it was the\n * single biggest reason a second UI could not render a kind: the routing\n * three-state lifecycle, the eager targeted resolve, the warm-then-refresh\n * order, and the \"checking is not the same as missing\" rule are all subtle and\n * were all trapped inside matrx-frontend.\n */\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { envelopeFromCompleteValue, IR_ENVELOPE_KEY } from \"@ai-matrx/content-ir\";\nimport { useContentIrHost } from \"../host/ContentIrProvider\";\nimport type { ContentIrHost } from \"../host/host-types\";\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 */\nexport function kindIsRoutable(kind: string, host: ContentIrHost): boolean {\n if (host.kinds.getDefinition(kind)?.legacyBlockType) return true;\n return Boolean(\n host.components.resolve(kind, host.platform, \"output\")?.isActive,\n );\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({\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 * 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/content-ir-system/STREAMING_PARTIAL_KINDS.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/content-ir-system/RUNTIME_WRAPPER_WIRE.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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-matrx/content-ir-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "The shared AI Matrx Content IR RENDER layer: kind routing, the component resolver, provisional (streaming) rendering, the runtime-wrapper chrome, and the generic structured floor — as portable React.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"./package.json": "./package.json"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@ai-matrx/content-ir": "0.
|
|
39
|
+
"@ai-matrx/content-ir": "0.3.0",
|
|
40
40
|
"react": ">=19.0.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"tsup": "^8.5.1",
|
|
52
52
|
"typescript": "^5.9.3",
|
|
53
53
|
"vitest": "^4.1.6",
|
|
54
|
-
"@ai-matrx/content-ir": "0.
|
|
54
|
+
"@ai-matrx/content-ir": "0.3.0"
|
|
55
55
|
},
|
|
56
56
|
"publishConfig": {
|
|
57
57
|
"access": "public",
|