@forgeax/engine-assets-runtime 0.1.7 → 0.1.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/dist/index.d.ts +2 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +40 -2
- package/dist/index.mjs.map +1 -1
- package/dist/mipmap-generator.d.ts +3 -1
- package/dist/mipmap-generator.d.ts.map +1 -1
- package/dist/registry/instantiate.d.ts +2 -0
- package/dist/registry/instantiate.d.ts.map +1 -1
- package/dist/registry/validate-material.d.ts +1 -0
- package/dist/registry/validate-material.d.ts.map +1 -1
- package/package.json +14 -14
- package/src/__tests__/catalog-replica.unit.test.ts +36 -0
- package/src/__tests__/inline-pack-loaders.unit.test.ts +37 -0
- package/src/__tests__/instantiate-publication-fence.unit.test.ts +59 -1
- package/src/__tests__/material-ready.integration.test.ts +65 -0
- package/src/__tests__/validate-material.unit.test.ts +45 -0
- package/src/index.ts +7 -2
- package/src/mipmap-generator.ts +43 -1
- package/src/registry/instantiate.ts +14 -4
- package/src/registry/validate-material.ts +94 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/asset-kind.ts","../src/builtin-asset-registry.ts","../src/loader-registry.ts","../src/errors/asset.ts","../src/handles.ts","../src/scene-payload.ts","../src/loaders/mesh-bin.ts","../src/mipmap-generator.ts","../src/loaders/pack-artifact.ts","../src/loaders/inline-pack.ts","../src/wire-default-loaders.ts","../src/aabb.ts","../src/material/runtime-shader.ts","../src/payload-validate.ts","../src/registry/artifact-io.ts","../src/registry/asset-evidence.ts","../src/registry/catalog.ts","../src/registry/catalog-state.ts","../src/resolve-asset-handle.ts","../src/scene-handle-fields.ts","../src/registry/scene-publication-fence.ts","../src/registry/instantiate.ts","../src/material/loader.ts","../src/registry/runtime-projection.ts","../src/registry/load-by-guid.ts","../src/registry/load-state.ts","../src/registry/validate-material.ts","../src/asset-registry.ts","../src/catalog-source.ts","../src/image-error.ts","../src/decode-image-bytes.ts","../src/dynamic-texture-store.ts","../src/internal/artifact-cache.ts","../src/internal/immutable-payload.ts","../src/internal/asset-graph.ts","../src/internal/validate-runtime-row.ts","../src/internal/catalog-session.ts","../src/internal/decoder-registry.ts","../src/internal/pack-reader.ts","../src/internal/load-asset.ts","../src/material/generation-cache.ts","../src/material/inspection.ts","../src/plugin.ts","../src/resolve-tileset-runtime.ts"],"names":["output","handleSlot","err","component","key","ok","AssetError","failure","value","AssetGuid","PROCEDURAL_FLOATS_PER_VERTEX","ASSET_ERROR_HINTS","record","sameRevision","BUILTIN_BASE","guidKey","missing","decompressZstd","unwrapHandle","guid","authoringCapabilityForAssetKind","freezeSnapshot","sha256","current","createMaterialError"],"mappings":";;;;;;;;;;;;;;;;AAGO,SAAS,gBAA8C,IAAA,EAA0B;AACtF,EAAA,OAAO,MAAA,CAAO,MAAA,CAAO,EAAE,IAAA,EAAM,CAAA;AAC/B;AC0CA,IAAM,cAAA,GAAiB,iBAAA,CAAkB,CAAA,EAAG,CAAA,EAAG,CAAC,CAAA;AAChD,IAAI,CAAC,eAAe,EAAA,EAAI;AACtB,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,CAAA,0DAAA,EAA6D,cAAA,CAAe,KAAA,CAAM,IAAI,CAAA;AAAA,GACxF;AACF;AACO,IAAM,YAAA,GAA+B,MAAA,CAAO,MAAA,CAAO,cAAA,CAAe,KAAK;AAO9E,IAAM,kBAAA,GAAqB,mBAAA;AAAA,EACzB,IAAI,YAAA,CAAa;AAAA;AAAA,IAEf,CAAA;AAAA,IAAG,GAAA;AAAA,IAAK,CAAA;AAAA,IAAG,CAAA;AAAA,IAAG,CAAA;AAAA,IAAG,CAAA;AAAA,IAAG,GAAA;AAAA,IAAK,CAAA;AAAA,IAAG,IAAA;AAAA,IAAM,IAAA;AAAA,IAAM,CAAA;AAAA,IAAG,CAAA;AAAA,IAAG,CAAA;AAAA,IAAG,C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AChB,CAAA;AAAA,EACH;AACA,EAAA,IAAI,UAAU,OAAA,EAAS;AACrB,IAAA,OAAOA,KAAAA,CAAI;AAAA,MACT,IAAA,EAAM,qBAAA;AAAA,MACN,QAAA,EAAU,4CAA4C,IAAI,CAAA,CAAA;AAAA,MAC1D,IAAA,EAAM,kEAAA;AAAA,MACN,MAAA,EAAQ,EAAE,IAAA;AAAK,KAChB,CAAA;AAAA,EACH;AACA,EAAA,IAAI,OAAA,CAAQ,SAAS,SAAA,EAAW;AAC9B,IAAA,OAAOA,KAAAA,CAAI;AAAA,MACT,IAAA,EAAM,6BAAA;AAAA,MACN,QAAA,EAAU,yBAAA;AAAA,MACV,IAAA,EAAM,sBAAsB,IAAI,CAAA,qBAAA,CAAA;AAAA,MAChC,MAAA,EAAQ,EAAE,IAAA,EAAM,UAAA,EAAY,QAAQ,IAAA;AAAK,KAC1C,CAAA;AAAA,EACH;AACA,EAAA,OAAOG,EAAAA,CAAG;AAAA,IACR,IAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAA,EAAQ,KAAA,CAAM,eAAA,CAAgB,cAAA,EAAgB,OAAO;AAAA,GACtD,CAAA;AACH","file":"index.mjs","sourcesContent":["import type { AssetKind } from '@forgeax/engine-types';\n\n/** Create the type witness shared by one custom decoder lease and its loads. */\nexport function defineAssetKind<P, K extends string = string>(kind: K): AssetKind<P, K> {\n return Object.freeze({ kind }) as AssetKind<P, K>;\n}\n","// ─── BuiltinAssetRegistry (D-15 process-static tier) ────────────────────────\n//\n// D-15 two-tier asset resolution. Builtin payloads (the 5 procedural meshes\n// the engine ships with) are PROCESS-STATIC: a frozen const keyed by a fixed\n// slot u32 in [1, BUILTIN_BASE). They never enter a World's SharedRefStore,\n// never participate in reference counting, and resolve without any World\n// reference — so a builtin handle (HANDLE_CUBE etc.) is transparent across\n// every World and every renderer.\n//\n// R-13 (module init-order): all five payload consts are constructed\n// synchronously at module load, are module-level, and have no side effect.\n// Importing this module then calling resolve() observes fully-constructed\n// frozen payloads — there is no lazy getter and no circular-dependency\n// init hazard.\n//\n// The companion AssetRegistry (asset-registry.ts) retreats to a thin\n// guid<->handle index; user-tier payloads live in World.sharedRefs at\n// slots >= BUILTIN_BASE. AssetRegistry.get(handle) dispatches by slot range:\n// slot < BUILTIN_BASE -> BuiltinAssetRegistry.resolve, else world.sharedRefs.\n\nimport {\n createBoxGeometry,\n createCylinderGeometry,\n createPlaneGeometry,\n createSphereGeometry,\n meshFromInterleaved,\n} from '@forgeax/engine-geometry';\nimport type { Handle, MeshAsset as TypesMeshAsset } from '@forgeax/engine-types';\nimport { BUILTIN_BASE, handleSlot } from '@forgeax/engine-types';\n\n// D-16: BUILTIN_BASE is the slot boundary [1, BUILTIN_BASE) builtin /\n// [BUILTIN_BASE, +inf) user-tier. It lives in @forgeax/engine-types (the\n// single shared dependency of ecs + runtime) to avoid a cross-package cycle;\n// re-exported from the runtime barrel here for AI-user discoverability.\nexport { BUILTIN_BASE };\n\n// ─── Builtin geometry data (12F: position + normal + uv + tangent) ──────────\n// bug-20260709-builtin-quad-withoutaabb-disables-sprite-frustum-cu: every\n// builtin geometry payload keeps the local-space AABB produced by its geometry\n// factory. Builtins are ordinary MeshAssets at the render boundary, so removing\n// their bounds silently turns them into always-visible renderables and defeats\n// the same frustum-culling path used by imported meshes.\n\n// BUILTIN_CUBE is synthesized from `createBoxGeometry(1, 1, 1)` so the cube\n// inherits Three.js-aligned per-face UV unwrap and per-vertex tangent vec4.\n// The procedural factory always returns Result.ok for valid (>0) extents,\n// hence the unwrap-with-throw is safe at module init.\nconst builtinCubeRes = createBoxGeometry(1, 1, 1);\nif (!builtinCubeRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createBoxGeometry(1,1,1) failed: ${builtinCubeRes.error.code}`,\n );\n}\nexport const BUILTIN_CUBE: TypesMeshAsset = Object.freeze(builtinCubeRes.value);\n\n// BUILTIN_TRIANGLE: 3 vertices in the XY plane facing +Z, with a [0..1]² UV\n// triangle so a textured triangle samples the texture (apex = top-centre,\n// base = bottom-left / bottom-right). meshFromInterleaved expands the\n// 8-floats interleaved input (pos + normal + uv) to the runtime 12-floats\n// stride (adds tangent vec4 per `geometry/tangent.ts` path A).\nconst builtinTriangleRes = meshFromInterleaved(\n new Float32Array([\n // pos.xyz normal.xyz uv.xy\n 0, 0.7, 0, 0, 0, 1, 0.5, 1, -0.7, -0.6, 0, 0, 0, 1, 0, 0, 0.7, -0.6, 0, 0, 0, 1, 1, 0,\n ]),\n new Uint16Array([0, 1, 2]),\n);\nif (!builtinTriangleRes.ok) {\n throw new Error(\n `[builtin-asset-registry] builtin triangle geometry failed: ${builtinTriangleRes.error.code}`,\n );\n}\nexport const BUILTIN_TRIANGLE: TypesMeshAsset = Object.freeze(builtinTriangleRes.value);\n\n// BUILTIN_QUAD: unit-size plane on XY facing +Z (4 vertices, 2 triangles,\n// 6 indices). Synthesised from `createPlaneGeometry(1, 1)` (which itself\n// chains through `meshFromInterleaved`) so the resulting MeshAsset is\n// byte-identical to procedural plane output — zero new layout\n// discriminator, AI users reason about UV / pivot semantics by reading\n// `packages/runtime/src/geometry/plane.ts` (charter P4 consistent\n// abstraction; feat-20260520 M-1 / w06).\n// bug-20260709-builtin-quad-withoutaabb-disables-sprite-frustum-cu: this\n// payload follows the same local-AABB contract as every other builtin.\nconst builtinQuadRes = createPlaneGeometry(1, 1);\nif (!builtinQuadRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createPlaneGeometry(1,1) failed: ${builtinQuadRes.error.code}`,\n );\n}\nexport const BUILTIN_QUAD: TypesMeshAsset = Object.freeze(builtinQuadRes.value);\n\n// BUILTIN_SPHERE: UV-sphere synthesised from createSphereGeometry(1, 16, 12).\n// Vertices are at exact radius-1 positions (sphere.ts:40-45) so the\n// |hypot(pos)-1| < 1e-6 radius invariant holds by construction. Index\n// buffer is Uint32Array — downstream consumers (step-3 upload loop,\n// createRenderer.ts) auto-select 'uint32' indexFormat via\n// `instanceof Uint32Array`.\nconst builtinSphereRes = createSphereGeometry(1, 16, 12);\nif (!builtinSphereRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createSphereGeometry(1,16,12) failed: ${builtinSphereRes.error.code}`,\n );\n}\nexport const BUILTIN_SPHERE: TypesMeshAsset = Object.freeze(builtinSphereRes.value);\n\n// BUILTIN_CYLINDER: procedural cylinder synthesised from createCylinderGeometry(0.5, 0.5, 1, 16, 1).\n// Radius-top=radius-bottom=0.5, height=1, 16 radial segments, 1 height segment — a\n// unit-height open cylinder (no caps). meshFromInterleaved expands the 8-floats\n// interleaved input (pos + normal + uv) to the runtime 12-floats stride (adds\n// tangent vec4 per geometry/tangent.ts path A).\n// feat-20260701-editor-world-container-doc-ecs-collapse M0 / AC-16:\n// handle=6, GUID = deriveBuiltin('HANDLE_CYLINDER') UUIDv5\n// (plan-strategy §2 D-6 + §5.6 builtin-guid-ssot gate)\nconst builtinCylinderRes = createCylinderGeometry(0.5, 0.5, 1, 16, 1);\nif (!builtinCylinderRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createCylinderGeometry(0.5,0.5,1,16,1) failed: ${builtinCylinderRes.error.code}`,\n );\n}\nexport const BUILTIN_CYLINDER: TypesMeshAsset = Object.freeze(builtinCylinderRes.value);\n\n// BUILTIN_NINESLICE_QUAD: 4×4 grid plane synthesised from\n// createPlaneGeometry(1, 1, 3, 3) — 16 vertices, 9 sub-quads × 6 indices = 54.\n// Reuses the unit-quad vertex layout (12F: pos + normal + uv + tangent) so\n// HANDLE_NINESLICE_QUAD funnels through the same sprite-pipeline binding\n// table as HANDLE_QUAD; only the vertex_index → (i, j) decomposition in\n// sprite.wgsl branches on slices presence (feat-20260527-sprite-nineslice\n// M3, plan-strategy §D-2 + §D-4).\nconst builtinNineSliceQuadRes = createPlaneGeometry(1, 1, 3, 3);\nif (!builtinNineSliceQuadRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createPlaneGeometry(1,1,3,3) failed: ${builtinNineSliceQuadRes.error.code}`,\n );\n}\nexport const BUILTIN_NINESLICE_QUAD: TypesMeshAsset = Object.freeze(builtinNineSliceQuadRes.value);\n\n// Slot u32 -> frozen payload. Slot ids 1..5 are the fixed builtin handle\n// values (HANDLE_CUBE=1 .. HANDLE_NINESLICE_QUAD=5) defined in asset-registry.\nconst BUILTIN_BY_SLOT: ReadonlyMap<number, TypesMeshAsset> = new Map([\n [1, BUILTIN_CUBE],\n [2, BUILTIN_TRIANGLE],\n [3, BUILTIN_QUAD],\n [4, BUILTIN_SPHERE],\n [5, BUILTIN_NINESLICE_QUAD],\n [6, BUILTIN_CYLINDER],\n]);\n\n/**\n * Process-static builtin asset resolver (D-15). `resolve(handle)` returns the\n * frozen builtin payload when `slot < BUILTIN_BASE`, else `null` (the slot\n * belongs to the user tier — resolve it through `world.sharedRefs.resolve`).\n *\n * Read-only: there is no register / mint surface. The five builtin payloads\n * are fixed at module load. AI users `import { BuiltinAssetRegistry } from\n * '@forgeax/engine-runtime'` and resolve a builtin handle without a World.\n */\nexport const BuiltinAssetRegistry = Object.freeze({\n resolve<T extends TypesMeshAsset>(handle: Handle<string, 'shared'>): T | null {\n const slot = handleSlot(handle);\n if (slot >= BUILTIN_BASE) return null;\n const payload = BUILTIN_BY_SLOT.get(slot);\n return payload === undefined ? null : (payload as T);\n },\n});\n","// @forgeax/engine-assets-runtime - LoaderRegistry (feat-20260603-asset-import-loader-injection M1 / w2).\n//\n// The runtime half of the engine's third DIP instance (after RHI + Console):\n// an injectable table that maps `asset.kind` -> a `Loader` (the contract SSOT\n// lives in `@forgeax/engine-types`, plan-strategy D-2). `AssetRegistry` holds\n// one of these (constructor-injected, D-7) and dispatches `loadByGuid` through\n// `get(kind)` instead of a hardcoded `if (kind === ...)` chain (D-1).\n//\n// Shape mirrors the Console `Registry` (packages/console/src/registry.ts)\n// register/lookup pattern (research Finding 8), with one deliberate\n// difference: the injected unit here is an **object** `{ kind, load }`, not a\n// bare function, because a \"one kind -> one loader\" dispatch table is the\n// natural shape (plan-strategy D-1 alt-B rejection).\n//\n// Fail-fast semantics (charter P3): `register` throws on a malformed loader\n// or duplicate kind at wire time, so one canonical owner cannot be silently\n// replaced by a later seed table.\n\nimport type { ArtifactDescriptor, LoadContext, Loader } from '@forgeax/engine-types';\n\nexport interface PackArtifactInput {\n readonly descriptor: ArtifactDescriptor;\n readonly bytes: Uint8Array;\n}\n\nexport interface PackLoaderInput {\n readonly guid: string;\n readonly kind: string;\n readonly payload: Record<string, unknown>;\n readonly refs: readonly string[];\n readonly artifacts: Readonly<Record<string, PackArtifactInput>>;\n}\n\nexport interface PackLoader {\n readonly kind: string;\n load(input: PackLoaderInput, ctx: LoadContext): unknown;\n}\n\nexport type PackLoadResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown };\n\n/**\n * Injectable `asset.kind` -> {@link Loader} table held by `AssetRegistry`.\n *\n * @example Wire + dispatch (host side)\n * ```ts\n * import { LoaderRegistry, wireDefaultLoaders } from '@forgeax/engine-assets-runtime';\n * const loaders = new LoaderRegistry();\n * wireDefaultLoaders(loaders);\n * const meshLoader = loaders.get('mesh'); // Loader | undefined\n * ```\n */\nexport class LoaderRegistry {\n // feat-20260623 M4 / w13: the Map stores Loader<unknown> so host custom kinds\n // (Loader<MyPayload>) are accepted. The P in Loader<P> is covariant (output\n // only: load() returns P), so Loader<Asset> is assignable to Loader<unknown>.\n private readonly loaders = new Map<string, Loader<unknown>>();\n private readonly packLoaders = new Map<string, PackLoader>();\n\n /**\n * Register a loader for its `loader.kind`. Fail-fast on a malformed loader\n * (charter P3); rejects a repeated kind so the canonical owner cannot be replaced.\n *\n * @param loader the `{ kind, load }` object to register.\n * @throws TypeError when `loader.kind` is empty or `loader.load` is not a\n * function — a wire-time misconfiguration the host must fix.\n */\n register(loader: Loader<unknown>): () => void {\n if (typeof loader.kind !== 'string' || loader.kind.length === 0) {\n throw new TypeError(\n `LoaderRegistry.register: loader.kind must be a non-empty string (got ${JSON.stringify(loader.kind)})`,\n );\n }\n if (typeof loader.load !== 'function') {\n throw new TypeError(\n `LoaderRegistry.register: loader.load must be a function for kind \"${loader.kind}\"`,\n );\n }\n if (this.loaders.has(loader.kind)) {\n throw new TypeError(`LoaderRegistry.register: duplicate loader kind \"${loader.kind}\"`);\n }\n this.loaders.set(loader.kind, loader);\n return () => {\n if (this.loaders.get(loader.kind) === loader) this.loaders.delete(loader.kind);\n };\n }\n\n registerPackLoader(loader: PackLoader): () => void {\n if (typeof loader.kind !== 'string' || loader.kind.length === 0) {\n throw new TypeError('LoaderRegistry.registerPackLoader: kind must be non-empty');\n }\n if (typeof loader.load !== 'function') {\n throw new TypeError(\n `LoaderRegistry.registerPackLoader: load must be a function for ${loader.kind}`,\n );\n }\n if (this.packLoaders.has(loader.kind)) {\n throw new TypeError(\n `LoaderRegistry.registerPackLoader: duplicate loader kind \"${loader.kind}\"`,\n );\n }\n this.packLoaders.set(loader.kind, loader);\n return () => {\n if (this.packLoaders.get(loader.kind) === loader) this.packLoaders.delete(loader.kind);\n };\n }\n\n async loadPack(input: PackLoaderInput, ctx: LoadContext): Promise<PackLoadResult> {\n const packLoader = this.packLoaders.get(input.kind);\n if (packLoader !== undefined) {\n const output = await packLoader.load(input, ctx);\n if (isPackLoadResult(output)) return output;\n return { ok: true, value: output };\n }\n const loader = this.loaders.get(input.kind);\n if (loader === undefined) {\n return { ok: false, error: new Error(`no loader registered for ${input.kind}`) };\n }\n if (loader.loadPack !== undefined) {\n const output = await loader.loadPack(input, ctx);\n if (isPackLoadResult(output)) return output;\n return { ok: true, value: output };\n }\n const output = await loader.load(input.payload, input.refs, ctx);\n if (isPackLoadResult(output)) return output;\n return { ok: true, value: output };\n }\n\n /**\n * Look up the loader registered for `kind`. Returns `undefined` when no\n * loader is wired — the `AssetRegistry` consumer maps that to a structured\n * `AssetError(code='loader-not-registered')` with the registered kinds in\n * `.detail` (charter P3).\n */\n get(kind: string): Loader<unknown> | undefined {\n return this.loaders.get(kind);\n }\n\n /**\n * The kinds currently wired, in insertion order. Fed into the\n * `loader-not-registered` error `.detail.registeredKinds` so AI users see\n * exactly what is injectable.\n */\n registeredKinds(): readonly string[] {\n return [...this.loaders.keys()];\n }\n}\n\nfunction isPackLoadResult(value: unknown): value is PackLoadResult {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'ok' in value &&\n typeof (value as { ok?: unknown }).ok === 'boolean'\n );\n}\n","// @forgeax/engine-assets-runtime -- asset cluster error classes.\n//\n// feat-20260704-runtime-tier1-decomposition M2 / w8 (D-3): asset-resolution\n// cluster -- material parent-chain resolve, mesh-SSBO grow ceiling, and\n// scene-collect GUID / forest-closure fail-fast errors. Class names, .code\n// literals, and .detail shapes preserved byte-for-byte (OOS-4).\n//\n// The cluster union type is named AssetRuntimeError / AssetRuntimeErrorCode\n// (not AssetError / AssetErrorCode) because @forgeax/engine-types already owns\n// the AssetError class + AssetErrorCode union (asset-system-v1); D-8 grep\n// uniqueness forbids the collision.\n\nimport type { MeshBinHeaderV4 } from '@forgeax/engine-pack';\nimport {\n AssetError,\n type AssetErrorDetail,\n type AssetMeshBinContractFacts,\n type AssetMeshBinContractViolationReason,\n} from '@forgeax/engine-types';\n\nexport class MeshBinAssetError extends AssetError {\n readonly subject = 'mesh-bin' as const;\n readonly sourceKey: string;\n readonly actual: string;\n readonly recovery = 're-cook the source with its Meta sidecar through the build-time importer';\n\n constructor(args: {\n readonly sourceKey: string;\n readonly expected: string;\n readonly actual: string;\n readonly header?: Partial<MeshBinHeaderV4> & { readonly byteLength?: number };\n readonly reason?: AssetMeshBinContractViolationReason;\n readonly expectedFacts?: AssetMeshBinContractFacts;\n readonly actualFacts?: AssetMeshBinContractFacts;\n }) {\n const expectedFacts: AssetMeshBinContractFacts = args.expectedFacts ?? {\n version: 4,\n projectionVersion: 1,\n };\n const actualFacts: AssetMeshBinContractFacts = {\n ...(args.header ?? {}),\n ...(args.actualFacts ?? {}),\n };\n const detail: AssetErrorDetail = {\n code: 'mesh-bin-contract-violation',\n sourceKey: args.sourceKey,\n reason: args.reason ?? 'header-invalid',\n expected: expectedFacts,\n actual: actualFacts,\n };\n super({\n code: 'mesh-bin-contract-violation',\n expected: args.expected,\n hint: 're-cook the source with its Meta sidecar through the build-time importer',\n detail,\n });\n this.sourceKey = args.sourceKey;\n this.actual = args.actual;\n }\n}\n\n// ── MaterialResolvedEmptyPassesError ──────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'material-resolved-empty-passes'`.\n *\n * Emitted at material parent chain walk time when the resolved passes list\n * is empty. Two reasons: `'missing-parent'` (a parent handle is not\n * registered) and `'no-pass-in-chain'` (the entire parent chain has no\n * pass declarations). AI users switch on `.detail.reason` to surface the\n * right recovery guidance.\n *\n * plan-strategy D-2/D-3: empty-passes is a runtime-layer error\n * (RuntimeErrorCode, not AssetErrorCode).\n */\nexport interface MaterialResolvedEmptyPassesDetail {\n /** GUID of the material whose resolve produced empty passes. */\n readonly materialGuid: string;\n /** Root cause of the empty passes: missing parent vs entire chain has no passes. */\n readonly reason: 'missing-parent' | 'no-pass-in-chain';\n /** The raw numeric handle id of the unregistered parent. Only populated when reason='missing-parent'. */\n readonly missingParentHandle?: number;\n}\n\n/**\n * Structured error for material parent chain resolve yielding zero passes.\n *\n * Emitted by `AssetRegistry.passesOf` when the parent chain walk produces\n * an empty passes list (AC-09, D-3 two-reason). Four-field surface:\n * - `.code = 'material-resolved-empty-passes'` (closed RuntimeErrorCode)\n * - `.expected` — expected-state description\n * - `.hint` — actionable recovery guidance (differs per reason)\n * - `.detail = { materialGuid, reason, missingParentHandle? }`\n */\nexport class MaterialResolvedEmptyPassesError extends Error {\n readonly code = 'material-resolved-empty-passes' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MaterialResolvedEmptyPassesDetail;\n\n constructor(\n materialGuid: string,\n reason: 'missing-parent' | 'no-pass-in-chain',\n missingParentHandle?: number,\n ) {\n const expected =\n reason === 'missing-parent'\n ? `parent handle ${missingParentHandle} present in AssetRegistry`\n : 'at least one material in the parent chain declares passes';\n const hint =\n reason === 'missing-parent'\n ? `material ${materialGuid} references parent handle ${missingParentHandle} which is not registered; inspect AssetRegistry, register the parent first, or rebuild the material chain`\n : `material ${materialGuid} has no passes and its entire parent chain also has no pass declarations; inspect the chain, add pass declarations to one member, then rebuild`;\n const message =\n reason === 'missing-parent'\n ? `material ${materialGuid} parent handle ${missingParentHandle} not registered`\n : `material ${materialGuid} parent chain resolves to zero passes`;\n\n super(message);\n this.name = 'MaterialResolvedEmptyPassesError';\n this.expected = expected;\n this.hint = hint;\n this.detail = {\n materialGuid,\n reason,\n ...(reason === 'missing-parent' && missingParentHandle !== undefined\n ? { missingParentHandle }\n : {}),\n };\n }\n}\n\n// ── MeshSsboCapacityExceededError ────────────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'mesh-ssbo-capacity-exceeded'`.\n *\n * Fired by `growMeshSsbo` (createRenderer.ts grow factory) when, after\n * attempting pow2 doubling, the resulting `slotCount` still cannot\n * accommodate the requested `requested` slot count under the device's\n * `maxStorageBufferBindingSize` ceiling. This is a defensive fallback —\n * the primary path for \"request past device limit\" is\n * `mesh-ssbo-ceiling-reached`. The two codes share the same detail shape so\n * AI users handle both arms identically; the discriminant identifies which\n * branch fired so diagnostics can distinguish the primary vs defensive\n * surface (research §F6.c).\n *\n * - `requested` — slot count requested by the caller (entity count for the frame)\n * - `capacity` — current `slotCount` in the grow controller's state\n * - `ceiling` — `device.limits.maxStorageBufferBindingSize` in BYTES (not slots)\n */\nexport interface MeshSsboCapacityExceededDetail {\n readonly requested: number;\n readonly capacity: number;\n readonly ceiling: number;\n}\n\n/**\n * Structured error for the post-grow defensive fallback when mesh-SSBO\n * capacity cannot accommodate the requested slot count.\n *\n * Emitted by `growMeshSsbo` in `createRenderer.ts` (D-5: fire, never\n * throw). Four-field surface aligned with `SkinPaletteOverflowError`:\n * - `.code = 'mesh-ssbo-capacity-exceeded'`\n * - `.expected` — capacity >= requested\n * - `.hint` — reduce per-frame entity count or split work across frames\n * - `.detail = { requested, capacity, ceiling }`\n */\nexport class MeshSsboCapacityExceededError extends Error {\n readonly code = 'mesh-ssbo-capacity-exceeded' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MeshSsboCapacityExceededDetail;\n\n constructor(requested: number, capacity: number, ceiling: number) {\n const expected = `mesh SSBO slotCount >= ${requested} (currently ${capacity}; device ceiling ${ceiling} B)`;\n const hint =\n `mesh SSBO grow could not satisfy needed=${requested} slots (capacity=${capacity}, ceiling=${ceiling} B); ` +\n 'reduce per-frame entity count or split work across frames (defensive fallback path)';\n super(\n `mesh SSBO capacity exceeded: needed ${requested} slots, capacity ${capacity}, ceiling ${ceiling} B`,\n );\n this.name = 'MeshSsboCapacityExceededError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { requested, capacity, ceiling };\n }\n}\n\n// ── MeshSsboCeilingReachedError ──────────────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'mesh-ssbo-ceiling-reached'`.\n *\n * Fired by `growMeshSsbo` when the requested slot count would exceed the\n * device's `maxStorageBufferBindingSize` (the only ceiling per D-1; engine\n * carries no private capacity constant). Same detail shape as\n * `MeshSsboCapacityExceededDetail`.\n *\n * - `requested` — slot count requested by the caller\n * - `capacity` — current `slotCount` in the grow controller's state\n * - `ceiling` — `device.limits.maxStorageBufferBindingSize` in BYTES\n */\nexport interface MeshSsboCeilingReachedDetail {\n readonly requested: number;\n readonly capacity: number;\n readonly ceiling: number;\n}\n\n/**\n * Structured error for mesh-SSBO grow refused because the request exceeds\n * `device.limits.maxStorageBufferBindingSize`.\n *\n * Emitted by `growMeshSsbo` (D-5: fire, never throw). The frame renders a\n * degraded subset (truncated to pre-grow capacity) per plan-strategy D-2 —\n * no black frame. Four-field surface aligned with `SkinPaletteOverflowError`:\n * - `.code = 'mesh-ssbo-ceiling-reached'`\n * - `.expected` — requested * stride <= device.limits.maxStorageBufferBindingSize\n * - `.hint` — reduce per-frame entity count or pick a higher-tier adapter\n * - `.detail = { requested, capacity, ceiling }`\n */\nexport class MeshSsboCeilingReachedError extends Error {\n readonly code = 'mesh-ssbo-ceiling-reached' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MeshSsboCeilingReachedDetail;\n\n constructor(requested: number, capacity: number, ceiling: number) {\n const expected = `mesh SSBO slot byte size <= device.limits.maxStorageBufferBindingSize (${ceiling} B)`;\n const hint =\n `requested ${requested} mesh SSBO slots would exceed device.limits.maxStorageBufferBindingSize (${ceiling} B); ` +\n 'reduce per-frame entity count or run on an adapter with a larger storage buffer binding size';\n super(\n `mesh SSBO ceiling reached: needed ${requested} slots; capacity ${capacity}; ceiling ${ceiling} B`,\n );\n this.name = 'MeshSsboCeilingReachedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { requested, capacity, ceiling };\n }\n}\n\n// ── SceneCollectEntityRefOutOfClosureError ──────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'scene-collect-entity-ref-out-of-closure'`.\n *\n * Emitted during rootsToSceneAsset when an entity field references a target\n * outside the collected forest closure.\n */\nexport interface SceneCollectEntityRefOutOfClosureDetail {\n readonly entity: number;\n readonly field: string;\n readonly target: number;\n}\n\n/**\n * Structured error for entity ref pointing outside the forest closure.\n *\n * Emitted during rootsToSceneAsset collect; fail-fast per charter P3.\n * - `.code = 'scene-collect-entity-ref-out-of-closure'`\n * - `.expected` — all entity refs resolve within the closure\n * - `.hint` — Expand roots to include the target entity, or remove the reference.\n * - `.detail = { entity, field, target }`\n */\nexport class SceneCollectEntityRefOutOfClosureError extends Error {\n readonly code = 'scene-collect-entity-ref-out-of-closure' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneCollectEntityRefOutOfClosureDetail;\n\n constructor(entity: number, field: string, target: number) {\n const expected = `entity ${entity}.${field} references entity ${target} which is inside the forest closure`;\n const hint = 'Expand roots to include the target entity, or remove the reference.';\n super(`${expected} — ${hint}`);\n this.name = 'SceneCollectEntityRefOutOfClosureError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { entity, field, target };\n }\n}\n\n// ── SceneCollectAssetGuidUnresolvedError ────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'scene-collect-asset-guid-unresolved'`.\n *\n * Emitted at two points with different context on hand:\n * - collect (handle→GUID): the shared handle is known → `.handle` is set.\n * - serialize (GUID→refs): the GUID string is known but absent from the\n * refs index → `.guid` is set. (`.handle` is meaningless there.)\n * Exactly one of `handle` / `guid` is present per instance.\n */\nexport interface SceneCollectAssetGuidUnresolvedDetail {\n readonly field: string;\n readonly handle?: number;\n readonly guid?: string;\n}\n\n/**\n * Structured error for a shared asset reference whose GUID cannot be resolved.\n *\n * Emitted during rootsToSceneAsset collect (handle) or\n * serializeSceneAssetToPack (guid); fail-fast per charter P3.\n * - `.code = 'scene-collect-asset-guid-unresolved'`\n * - `.expected` — every shared asset reference has a catalogued GUID\n * - `.hint` — Register the asset in AssetRegistry before collecting.\n * - `.detail = { field, handle }` (collect) or `{ field, guid }` (serialize)\n */\nexport class SceneCollectAssetGuidUnresolvedError extends Error {\n readonly code = 'scene-collect-asset-guid-unresolved' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneCollectAssetGuidUnresolvedDetail;\n\n constructor(field: string, ref: number | string) {\n const where = typeof ref === 'number' ? `handle ${ref}` : `guid '${ref}'`;\n const expected = `shared field '${field}' (${where}) resolves to an asset whose GUID is catalogued`;\n const hint =\n 'source SceneAsset is not catalogued: call registry.catalog(guid, payload) first, ' +\n 'or load through loadByGuid() which auto-catalogs GUID-scoped assets';\n super(`${expected} — ${hint}`);\n this.name = 'SceneCollectAssetGuidUnresolvedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = typeof ref === 'number' ? { field, handle: ref } : { field, guid: ref };\n }\n}\n\n// -- AssetRuntimeErrorCode / AssetRuntimeError closed unions --------------------\n\n/**\n * Closed union of asset-cluster error codes. AI users perform exhaustive\n * `switch (err.code)` without default; TS guards completeness.\n */\nexport type AssetRuntimeErrorCode = AssetRuntimeError['code'];\n\n/**\n * Closed union of the asset-cluster structured error classes, each carrying\n * an `AssetRuntimeErrorCode` discriminant on `.code`.\n */\nexport type AssetRuntimeError =\n | MaterialResolvedEmptyPassesError\n | MeshSsboCapacityExceededError\n | MeshSsboCeilingReachedError\n | SceneCollectEntityRefOutOfClosureError\n | SceneCollectAssetGuidUnresolvedError;\n","// @forgeax/engine-assets-runtime -- builtin mesh handles + scene-parse handle field\n// name sets (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1\n// straight-cut). Pure move from asset-registry.ts; zero identifier changes.\n\nimport type { Handle } from '@forgeax/engine-types';\nimport { handleSlot, toShared } from '@forgeax/engine-types';\n\n// ─── Builtin handles (D-S9 / backward compat with hello-triangle + hello-cube) ─\n\n/**\n * Builtin unit-cube mesh handle (8 vertices + 36 indices, pos+normal\n * interleaved). Pair with `MeshFilter` to spawn a cube entity.\n *\n * @remarks Typed as `Handle<'MeshAsset', 'shared'>` — feat-20260517\n * unifies the engine-types and engine-ecs Handle brand SSOT into a single\n * `Handle<T extends string, M extends 'unique'|'shared'>` declaration\n * (research Finding 4 import-path-decoupled identity), and constructs the\n * value via the brand-creation factory `toShared<'MeshAsset'>(N)` so\n * the caller-side `as unknown as` cast is eliminated (AC-05). The\n * `'shared'` mode signals the AssetRegistry owns the lifecycle — the\n * ECS does not release the slot on despawn / removeComponent / set.\n * Runtime value is a small u32 (1).\n */\nexport const HANDLE_CUBE: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(1);\n\n/**\n * Builtin triangle mesh handle (3 vertices). Pair with `MeshFilter`.\n *\n * @remarks Typed as `Handle<'MeshAsset', 'shared'>` (same narrow brand\n * as HANDLE_CUBE; constructed via the `toShared<'MeshAsset'>(N)`\n * factory per AC-05).\n */\nexport const HANDLE_TRIANGLE: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(2);\n\n/**\n * Builtin unit-quad mesh handle — 4 vertices, 6 indices, 2 triangles on\n * the XY plane facing +Z. Pair with `MeshFilter` to spawn a sprite quad\n * (feat-20260520-2d-sprite-layer-mvp / M-1 / w06).\n *\n * @derives Same-shape sibling of {@link HANDLE_CUBE} / {@link HANDLE_TRIANGLE}\n * per requirements §2.1.C: built via the `toShared<'MeshAsset'>(N)`\n * brand-creation factory; reserved-id 3 fills the namespace hole between\n * HANDLE_TRIANGLE=2 and FIRST_USER_HANDLE=1024 (no `BUILTIN_HANDLE_`\n * prefix per Q2 naming decision — discoverable next to existing\n * builtins in IDE autocomplete; charter F1 single-entry indexability).\n *\n * @reuses {@link createPlaneGeometry}(1, 1) — the procedural plane factory\n * already produces 8-floats-per-vertex interleaved (position + normal +\n * uv) and is then expanded to the runtime 12-floats layout (adds\n * tangent vec4) by {@link meshFromInterleaved}. This funnels HANDLE_QUAD\n * onto the exact same vertex pipeline branch as BUILTIN_CUBE /\n * BUILTIN_TRIANGLE and the procedural geometry factories — zero new\n * layout discriminator (plan-strategy §3 RT4 + D-9 + charter P4\n * consistent abstraction).\n *\n * @reuses `PROCEDURAL_FLOATS_PER_VERTEX` = 12 from\n * `@forgeax/engine-geometry` (the single layout SSOT; the procedural\n * `createPlaneGeometry` factory already returns 12F via\n * `meshFromInterleaved`).\n */\nexport const HANDLE_QUAD: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(3);\n\n/**\n * Id=4 reserved builtin; occupies the next available slot under\n * FIRST_USER_HANDLE=1024. BUILTIN_SPHERE is synthesised from\n * `createSphereGeometry(1, 16, 12)` through the same\n * `meshFromInterleaved` path as BUILTIN_QUAD, so the runtime\n * 12-float stride is byte-identical to procedural output — zero\n * new layout discriminator (charter P4 consistent abstraction).\n */\nexport const HANDLE_SPHERE: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(4);\n\n/**\n * Builtin cylinder mesh handle — procedural open cylinder (unit-height,\n * radius=0.5, 16 radial segments, no caps). Pair with `MeshFilter`.\n *\n * @derives Same-shape sibling of {@link HANDLE_SPHERE}: synthesised from\n * `createCylinderGeometry(0.5, 0.5, 1, 16, 1)` through the same\n * `meshFromInterleaved` path as BUILTIN_SPHERE, so the runtime\n * 12-float stride is byte-identical to all other built-in meshes —\n * zero new layout discriminator (charter P4 consistent abstraction).\n *\n * @remarks Id=6 follows {@link HANDLE_NINESLICE_QUAD}=5 in the builtin slot\n * sequence (FIRST_USER_HANDLE=1024 untouched).\n * feat-20260701-editor-world-container-doc-ecs-collapse M0 / AC-16:\n * GUID = deriveBuiltin('HANDLE_CYLINDER') UUIDv5\n * (plan-strategy §2 D-6 + §5.6 builtin-guid-ssot gate)\n */\nexport const HANDLE_CYLINDER: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(6);\n\n/**\n * Builtin 9-slice quad mesh handle — 4×4 grid (16 vertices, 9 sub-quads,\n * 54 indices) on the XY plane facing +Z. Pair with `MeshFilter` and a\n * `MaterialAsset` whose first pass shader is `'forgeax::sprite'` and whose\n * `values.slices` is non-zero to render a 9-sliced UI panel\n * (feat-20260527-sprite-nineslice / M2 / w9).\n *\n * @derives Same-shape sibling of {@link HANDLE_QUAD}: synthesised from\n * `createPlaneGeometry(1, 1, 3, 3)` which subdivides the unit quad into\n * 3×3 sub-quads (9 cells). The 16 grid points and 54 indices feed\n * {@link meshFromInterleaved} so the runtime 12-float vertex stride is\n * byte-identical to all other built-in / procedural meshes — zero new\n * layout discriminator (charter P4 consistent abstraction).\n *\n * @remarks Id=5 follows {@link HANDLE_SPHERE}=4 in the builtin slot\n * sequence (FIRST_USER_HANDLE=1024 untouched). The vertex shader uses\n * `vertex_index % 4` / `vertex_index / 4` to recover (i, j) grid\n * coordinates and four anchor vec4s to map each grid cell to the right\n * region of the source texture; only required when the sprite material\n * declares non-zero `slices`. For the legacy zero-slice sprite path use\n * {@link HANDLE_QUAD}.\n *\n * @reuses `PROCEDURAL_FLOATS_PER_VERTEX` = 12 from\n * `@forgeax/engine-geometry` (sprite-pipeline binding table / vertex layout\n * untouched). plan-strategy §D-2 NOTE clarifies\n * the id=5 vs original-plan id=4 drift: HANDLE_SPHERE took id=4 in\n * feat-20260529-fxaa-sphere-builtin before this feat landed.\n */\nexport const HANDLE_NINESLICE_QUAD: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(5);\n\n/**\n * Stable GUIDs for the builtin meshes — the dash-form of\n * `deriveBuiltin('HANDLE_<NAME>')` (UUIDv5, ForgeaX namespace) in\n * `@forgeax/engine-pack`. They are inlined here (not imported) because the\n * pack derivation runs under top-level `await` (async SubtleCrypto) and\n * dragging that into the AssetRegistry constructor — a synchronous hot path\n * consumed engine-wide — would make the whole runtime module graph async.\n *\n * The single source of truth remains `deriveBuiltin`: a cross-package\n * guard test (`builtin-guid-ssot.test.ts`) asserts each literal equals the\n * derived value, so any drift in the derivation reds the suite. This pairs\n * the previously-disconnected dual truths (the u32 `HANDLE_*` constants and\n * the pack GUID strings) into one bidirectionally-resolvable table, so\n * `guidOf(HANDLE_CUBE)` no longer returns `undefined`\n * (docs/feedbacks/2026-06-03 §6.2 Tier 0).\n */\nexport const BUILTIN_MESH_GUIDS: ReadonlyArray<readonly [Handle<'MeshAsset', 'shared'>, string]> = [\n [HANDLE_CUBE, 'cbe42beb-8975-5096-b3a1-3dda4cb4c077'],\n [HANDLE_TRIANGLE, '22592f07-d967-5116-b29c-fa9781929ba8'],\n [HANDLE_QUAD, '339338aa-a338-581c-9fc5-744267ef8a51'],\n [HANDLE_SPHERE, '95730fd2-9846-5f84-8658-0b3c971eb263'],\n [HANDLE_NINESLICE_QUAD, '692d38b4-8cac-5fb2-9dcf-f389e076d6bf'],\n // feat-20260701-editor-world-container-doc-ecs-collapse M0 / AC-16:\n // cylinder builtin handle=6, GUID = deriveBuiltin('HANDLE_CYLINDER') UUIDv5\n // (plan-strategy §5.6 builtin-guid-ssot gate)\n [HANDLE_CYLINDER, 'ab20af21-0764-55be-a7f2-b80ab3d46a0a'],\n];\n\n/** Resolve the stable producer GUID for one process-static builtin mesh handle. */\nexport function builtinMeshGuid(handle: Handle<string, 'shared'>): string | undefined {\n const slot = handleSlot(handle);\n return BUILTIN_MESH_GUIDS.find(([candidate]) => handleSlot(candidate) === slot)?.[1];\n}\n\n/**\n * Field names known to carry handle<> schema-vocab references (plan-strategy\n * D-4). parseScenePayload uses this allowlist to replace integer values\n * with GUID strings from refs[] only for handle fields — a Transform.pos lane of 0,\n * ChildOf.parent=0 and similar non-handle integers are left untouched.\n *\n * When a new handle<> field is added to a runtime component, its field name\n * MUST be added here so parseScenePayload correctly resolves it.\n */\nexport const HANDLE_FIELD_NAMES: ReadonlySet<string> = new Set([\n 'assetHandle',\n 'material',\n 'skeleton',\n 'clip',\n // ParticleEffectPlayer.effect (shared<ParticleEffectAsset>) uses the same\n // scene-pack refs[] index contract as every other scalar shared field.\n 'effect',\n // feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w27:\n // Skylight.equirect + SkyboxBackground.equirect (shared<EquirectAsset>). The\n // generic extractSceneEntityHandleGuids path already covers shared< fields by\n // schema; this allowlist is the second scene-parse path (parseScenePayload),\n // so the new handle field name is registered here too (R-1).\n 'equirect',\n]);\n\n/**\n * Field names known to carry `array<handle<X>>` schema-vocab references\n * (feat-20260608 M2 / w7: MeshRenderer.materials). Each element is a refs\n * index that resolves to a GUID string. Coexists with HANDLE_FIELD_NAMES;\n * a field name lives in exactly one set.\n */\nexport const HANDLE_ARRAY_FIELD_NAMES: ReadonlySet<string> = new Set(['materials']);\n","// @forgeax/engine-assets-runtime -- scene payload parse + ref resolution\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport type {\n LocalEntityId,\n SceneAsset,\n SceneEntity,\n SceneInstanceMount,\n} from '@forgeax/engine-types';\nimport { HANDLE_ARRAY_FIELD_NAMES, HANDLE_FIELD_NAMES } from './handles';\n\n/**\n * Structured error returned by parseScenePayload when a refs index is\n * out of bounds (F-2 / AC-02).\n */\ninterface ParseSceneError {\n readonly localId: number;\n readonly component: string;\n readonly field: string;\n readonly index: number;\n readonly refsLength: number;\n}\n\n// Reconstruct a SceneAsset POD from a serialised pack payload (feat-20260514\n// w3 / parseAssetPayload 'scene' dispatch). The payload arrives as the\n// outer pack file's `assets[i].payload` object after ajv structural\n// validation; this helper re-stamps the LocalEntityId brand on each\n// SceneEntity.localId field and freezes the resulting POD shape so consumer\n// code sees the same readonly surface as a hand-authored SceneAsset (AC-01\n// + plan-strategy §3.1 rt_pkg sub-graph).\n//\n// feat-20260528-scene-asset-guid-refs-and-post-instantiate M1-fixup F-1:\n// refs parameter — when provided, integer values in handle-type component\n// fields (identified via HANDLE_FIELD_NAMES allowlist, plan-strategy D-4)\n// are replaced with refs[N] (GUID string). Non-handle integer fields\n// (Transform pos/quat/scale lanes, ChildOf.parent Entity, etc.)\n// are kept as-is.\n//\n// feat-20260528-scene-asset-guid-refs-and-post-instantiate M1-fixup F-2:\n// out-of-bounds (N < 0 or N >= refs.length) returns a structured\n// ParseSceneError with localId + component + field + index + refs.length\n// so the caller can construct a precise AssetError (AC-02).\n// The M1 stop-on-first-error (AC-08) behaviour is preserved.\nexport function parseScenePayload(\n payload: Record<string, unknown>,\n refs?: string[],\n): SceneAsset | ParseSceneError | undefined {\n const rawEntities = payload.entities;\n if (!Array.isArray(rawEntities)) return undefined;\n const nodes: SceneEntity[] = [];\n for (const rn of rawEntities as Array<{ localId?: unknown; components?: unknown }>) {\n if (typeof rn.localId !== 'number') return undefined;\n const rawComponents = (rn.components ?? {}) as Record<string, Record<string, unknown>>;\n\n // Resolve refs indices to GUID strings only for handle-type fields\n // (plan-strategy D-4 / F-1 fix: non-handle integers preserved as-is).\n if (refs) {\n const resolvedComponents: Record<string, Record<string, unknown>> = {};\n for (const compName of Object.keys(rawComponents)) {\n const rawFields = rawComponents[compName];\n if (!rawFields) continue;\n const resolvedFields: Record<string, unknown> = {};\n for (const fieldName of Object.keys(rawFields)) {\n const value = rawFields[fieldName];\n if (\n HANDLE_FIELD_NAMES.has(fieldName) &&\n typeof value === 'number' &&\n Number.isInteger(value)\n ) {\n const idx = value;\n if (idx < 0 || idx >= refs.length) {\n return {\n localId: rn.localId as number,\n component: compName,\n field: fieldName,\n index: idx,\n refsLength: refs.length,\n };\n }\n resolvedFields[fieldName] = refs[idx];\n } else if (HANDLE_ARRAY_FIELD_NAMES.has(fieldName) && Array.isArray(value)) {\n // feat-20260608 M2 / w7: array<handle<X>> field — each element is a\n // refs index resolved to a GUID string. Out-of-bounds in any element\n // surfaces the same ParseSceneError as the scalar handle path.\n const resolvedArr: string[] = [];\n for (let elemIdx = 0; elemIdx < value.length; elemIdx++) {\n const elem = value[elemIdx];\n if (typeof elem !== 'number' || !Number.isInteger(elem)) {\n resolvedFields[fieldName] = value;\n resolvedArr.length = 0;\n break;\n }\n if (elem < 0 || elem >= refs.length) {\n return {\n localId: rn.localId as number,\n component: compName,\n field: `${fieldName}[${elemIdx}]`,\n index: elem,\n refsLength: refs.length,\n };\n }\n const ref = refs[elem];\n if (ref !== undefined) resolvedArr.push(ref);\n }\n if (resolvedArr.length === value.length) {\n resolvedFields[fieldName] = resolvedArr;\n } else if (resolvedFields[fieldName] === undefined) {\n resolvedFields[fieldName] = value;\n }\n } else {\n resolvedFields[fieldName] = value;\n }\n }\n resolvedComponents[compName] = resolvedFields as Record<string, unknown>;\n }\n nodes.push({\n localId: rn.localId as LocalEntityId,\n components: resolvedComponents,\n });\n } else {\n nodes.push({\n localId: rn.localId as LocalEntityId,\n components: rawComponents,\n });\n }\n }\n const resolvedMounts = resolveMounts(payload, refs);\n if (resolvedMounts === undefined && Array.isArray(payload.mounts)) {\n // mounts resolution failed (e.g. out-of-bounds source index)\n return undefined;\n }\n // feat-20260612 M2 fixup: resolve `skinGuids` field (refs[] indices on disk\n // -> GUID strings post-parse). The SkinAsset chain has no entity-component\n // hook so the scene must carry an explicit cross-edge list; without it,\n // browser-async-pack-fetch never loads SkinAssets and postSpawnResolveJoints\n // silently skips, leaving Skin.joints.length=0 for every frame.\n const resolvedSkinGuids = resolveSkinGuids(payload, refs);\n if (resolvedSkinGuids === undefined && Array.isArray(payload.skinGuids)) {\n return undefined;\n }\n return {\n kind: 'scene',\n entities: nodes,\n mounts: resolvedMounts as unknown as readonly SceneInstanceMount[],\n ...(resolvedSkinGuids !== undefined ? { skinGuids: resolvedSkinGuids } : {}),\n } as SceneAsset;\n}\n\n/**\n * feat-20260612 M2 fixup: resolve `SceneAsset.skinGuids` -- on-disk refs[]\n * indices into post-parse GUID strings. Mirror of {@link resolveMounts}.\n * Returns undefined when no `skinGuids` field is present (back-compat:\n * pre-M2 SceneAssets carry no skin cross-edges).\n */\nfunction resolveSkinGuids(\n payload: Record<string, unknown>,\n refs: readonly string[] | undefined,\n): readonly string[] | undefined {\n const raw = payload.skinGuids;\n if (!Array.isArray(raw)) return undefined;\n const out: string[] = [];\n for (const item of raw as ReadonlyArray<unknown>) {\n if (typeof item === 'string') {\n // Pre-resolved GUID string (in-memory dawn smoke / direct register path).\n out.push(item);\n } else if (typeof item === 'number' && Number.isInteger(item)) {\n // refs[] index path (browser pack-fetch JSON-roundtrip shape).\n if (refs === undefined) return undefined;\n if (item < 0 || item >= refs.length) return undefined;\n const guid = refs[item];\n if (typeof guid !== 'string') return undefined;\n out.push(guid);\n } else {\n return undefined;\n }\n }\n return out;\n}\n\n/**\n * Resolve mounts[].source integer indices through refs[] to GUID strings.\n * Mount.source is resolved positionally (not through HANDLE_FIELD_NAMES),\n * per AC-11. Returns undefined when no mounts field is present (back-compat).\n */\nfunction resolveMounts(\n payload: Record<string, unknown>,\n refs: readonly string[] | undefined,\n): ReadonlyArray<Record<string, unknown>> | undefined {\n const rawMounts = payload.mounts;\n if (!Array.isArray(rawMounts)) return undefined;\n if (refs === undefined) return rawMounts as ReadonlyArray<Record<string, unknown>>;\n const resolved: Record<string, unknown>[] = [];\n for (const rm of rawMounts as ReadonlyArray<Record<string, unknown>>) {\n const mount = { ...rm };\n const source = rm.source;\n if (typeof source === 'number' && Number.isInteger(source)) {\n const idx = source;\n if (idx < 0 || idx >= refs.length) {\n return undefined;\n }\n mount.source = refs[idx];\n }\n resolved.push(mount);\n }\n return resolved;\n}\n","import {\n deriveVertexLayoutProjectionFromMask,\n type VertexLayoutProjection,\n} from '@forgeax/engine-geometry';\nimport {\n decodeMeshBinHeader,\n MESH_BIN_HEADER_V4_BYTES,\n type MeshBinHeaderV4,\n} from '@forgeax/engine-pack';\nimport { err, ok, type Result, type VertexAttributeMap } from '@forgeax/engine-types';\nimport { MeshBinAssetError } from '../errors/asset';\n\nexport interface UnpackedMeshBin {\n readonly version: 4;\n readonly projection: VertexLayoutProjection;\n readonly vertices: Float32Array;\n readonly attributes: VertexAttributeMap;\n readonly indices?: Uint16Array | Uint32Array;\n readonly submeshes: ReadonlyArray<Record<string, unknown>>;\n readonly materialSlots: readonly {\n readonly slotName: string;\n readonly sourceKey?: string;\n readonly defaultMaterialRef?: number;\n }[];\n readonly aabb?: Float32Array;\n readonly morphTargets?: ReadonlyArray<Record<string, Float32Array>>;\n readonly morphWeights?: Float32Array;\n}\n\nfunction fail(\n sourceKey: string,\n expected: string,\n actual: string,\n header?: Partial<MeshBinHeaderV4>,\n reason: import('@forgeax/engine-types').AssetMeshBinContractViolationReason = 'header-invalid',\n expectedFacts?: import('@forgeax/engine-types').AssetMeshBinContractFacts,\n actualFacts?: import('@forgeax/engine-types').AssetMeshBinContractFacts,\n): Result<UnpackedMeshBin, MeshBinAssetError> {\n return err(\n new MeshBinAssetError({\n sourceKey,\n expected,\n actual,\n ...(header === undefined ? {} : { header }),\n reason,\n ...(expectedFacts === undefined ? {} : { expectedFacts }),\n ...(actualFacts === undefined ? {} : { actualFacts }),\n }),\n );\n}\n\nfunction copyAttributes(\n source: Float32Array,\n header: MeshBinHeaderV4,\n projection: VertexLayoutProjection,\n): VertexAttributeMap {\n const view = new DataView(source.buffer, source.byteOffset, source.byteLength);\n const attributes: Record<string, Float32Array | Uint16Array> = {};\n for (const entry of projection.attributes) {\n const components = entry.byteLength / (entry.format === 'uint16x4' ? 2 : 4);\n const target =\n entry.format === 'uint16x4'\n ? new Uint16Array(header.vertexCount * components)\n : new Float32Array(header.vertexCount * components);\n for (let vertex = 0; vertex < header.vertexCount; vertex++) {\n for (let component = 0; component < components; component++) {\n const offset =\n vertex * header.stride + entry.offset + component * (entry.format === 'uint16x4' ? 2 : 4);\n if (target instanceof Uint16Array)\n target[vertex * components + component] = view.getUint16(offset, true);\n else target[vertex * components + component] = view.getFloat32(offset, true);\n }\n }\n attributes[entry.key] = target;\n }\n return attributes as VertexAttributeMap;\n}\n\nexport function unpackMeshBinV4(\n bytes: Uint8Array,\n sourceKey: string,\n): Result<UnpackedMeshBin, MeshBinAssetError> {\n const headerResult = decodeMeshBinHeader(bytes, sourceKey);\n if (!headerResult.ok) {\n const reason =\n headerResult.error.code === 'mesh-bin-header-truncated'\n ? 'header-truncated'\n : headerResult.error.code === 'mesh-bin-version-unsupported'\n ? 'version-unsupported'\n : 'header-invalid';\n const actualFacts = {\n byteLength: bytes.byteLength,\n ...(bytes.byteLength >= 4\n ? {\n version: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(\n 0,\n true,\n ),\n }\n : {}),\n };\n return fail(\n sourceKey,\n headerResult.error.expected,\n headerResult.error.actual,\n undefined,\n reason,\n reason === 'header-truncated'\n ? { field: 'byteLength', byteLength: MESH_BIN_HEADER_V4_BYTES }\n : reason === 'version-unsupported'\n ? { field: 'version', version: 4 }\n : undefined,\n actualFacts,\n );\n }\n const header = headerResult.value;\n const projectionResult = deriveVertexLayoutProjectionFromMask(header.mask);\n if (!projectionResult.ok) {\n return fail(\n sourceKey,\n projectionResult.error.expected,\n `mask=${header.mask}`,\n header,\n 'projection-mismatch',\n {\n field: 'mask',\n mask: projectionResult.error.detail.knownMask,\n },\n {\n field: 'mask',\n mask: header.mask,\n projectionVersion: header.projectionVersion,\n stride: header.stride,\n digest: header.digest,\n },\n );\n }\n const projection = projectionResult.value;\n if (\n projection.schemaVersion !== header.projectionVersion ||\n projection.arrayStride !== header.stride ||\n projection.digest !== header.digest\n ) {\n return fail(\n sourceKey,\n 'wire projection version, mask, stride, and digest to match geometry projection',\n `projection=${projection.schemaVersion}/${projection.arrayStride}/${projection.digest}; wire=${header.projectionVersion}/${header.stride}/${header.digest}`,\n header,\n 'projection-mismatch',\n {\n field: 'projectionVersion',\n projectionVersion: projection.schemaVersion,\n mask: projection.mask,\n stride: projection.arrayStride,\n digest: projection.digest,\n },\n );\n }\n const payloadBytes = header.vertexBytes + header.indexBytes + header.jsonBytes;\n if (MESH_BIN_HEADER_V4_BYTES + payloadBytes !== bytes.byteLength) {\n return fail(\n sourceKey,\n `exactly ${MESH_BIN_HEADER_V4_BYTES + payloadBytes} bytes`,\n `${bytes.byteLength} bytes`,\n header,\n 'payload-length-mismatch',\n { field: 'byteLength', byteLength: MESH_BIN_HEADER_V4_BYTES + payloadBytes },\n {\n field: 'byteLength',\n byteLength: bytes.byteLength,\n vertexBytes: header.vertexBytes,\n indexBytes: header.indexBytes,\n jsonBytes: header.jsonBytes,\n },\n );\n }\n let offset = MESH_BIN_HEADER_V4_BYTES;\n const vertexBytes = bytes.subarray(offset, offset + header.vertexBytes);\n const vertices = new Float32Array(vertexBytes.byteLength / 4);\n new Uint8Array(vertices.buffer).set(vertexBytes);\n offset += header.vertexBytes;\n let indices: Uint16Array | Uint32Array | undefined;\n if (header.indexCount > 0) {\n const indexBytes = bytes.subarray(offset, offset + header.indexBytes);\n if (header.indexWidth === 2) {\n indices = new Uint16Array(header.indexCount);\n new Uint8Array(indices.buffer).set(indexBytes);\n } else {\n indices = new Uint32Array(header.indexCount);\n new Uint8Array(indices.buffer).set(indexBytes);\n }\n offset += header.indexBytes;\n }\n const jsonBytes = bytes.subarray(offset, offset + header.jsonBytes);\n let meta: {\n submeshes?: ReadonlyArray<Record<string, unknown>>;\n materialSlots?: readonly {\n readonly slotName: string;\n readonly sourceKey?: string;\n readonly defaultMaterialRef?: number;\n }[];\n aabb?: readonly number[];\n morphTargets?: ReadonlyArray<Record<string, readonly number[]>>;\n morphWeights?: readonly number[];\n };\n try {\n meta = JSON.parse(new TextDecoder().decode(jsonBytes)) as typeof meta;\n } catch (error) {\n return fail(\n sourceKey,\n 'valid mesh-bin v4 JSON metadata',\n error instanceof Error ? error.message : String(error),\n header,\n 'metadata-invalid',\n { field: 'metadata' },\n { field: 'metadata' },\n );\n }\n if (\n !Array.isArray(meta.submeshes) ||\n meta.submeshes.length === 0 ||\n !Array.isArray(meta.materialSlots)\n ) {\n return fail(\n sourceKey,\n 'non-empty submeshes and materialSlots metadata',\n 'metadata table missing',\n header,\n 'metadata-invalid',\n { field: 'metadata' },\n { field: 'metadata' },\n );\n }\n const attributes = copyAttributes(vertices, header, projection);\n for (const attribute of projection.attributes) {\n const value = attributes[attribute.key];\n if (value === undefined)\n return fail(\n sourceKey,\n `decoded ${attribute.key} attribute`,\n 'attribute missing',\n header,\n 'attribute-invalid',\n {\n field: 'attribute',\n attribute: attribute.key,\n expectedLength:\n header.vertexCount * (attribute.byteLength / (attribute.format === 'uint16x4' ? 2 : 4)),\n },\n {\n field: 'attribute',\n attribute: attribute.key,\n mask: header.mask,\n stride: header.stride,\n vertexCount: header.vertexCount,\n },\n );\n if (value instanceof ArrayBuffer) continue;\n for (const component of value) {\n if (!Number.isFinite(component))\n return fail(\n sourceKey,\n 'finite vertex payload',\n `non-finite ${attribute.key}`,\n header,\n 'payload-non-finite',\n { field: 'attribute', attribute: attribute.key },\n {\n field: 'attribute',\n attribute: attribute.key,\n mask: header.mask,\n stride: header.stride,\n vertexCount: header.vertexCount,\n elementIndex: [...value].findIndex((component) => !Number.isFinite(component)),\n actualValue: Number.isNaN(component)\n ? 'nan'\n : component === Number.POSITIVE_INFINITY\n ? 'positive-infinity'\n : 'negative-infinity',\n },\n );\n }\n }\n const morphTargets = meta.morphTargets?.map((target) =>\n Object.fromEntries(\n Object.entries(target).map(([key, value]) => [key, new Float32Array(value)]),\n ),\n );\n const mesh: UnpackedMeshBin = {\n version: 4,\n projection,\n vertices,\n attributes,\n ...(indices === undefined ? {} : { indices }),\n submeshes: meta.submeshes,\n materialSlots: meta.materialSlots,\n ...(meta.aabb === undefined ? {} : { aabb: new Float32Array(meta.aabb) }),\n ...(morphTargets === undefined ? {} : { morphTargets }),\n ...(meta.morphWeights === undefined\n ? {}\n : { morphWeights: new Float32Array(meta.morphWeights) }),\n };\n return ok(mesh);\n}\n","// @forgeax/engine-assets-runtime - mipmap-generator.ts (T-M3-04).\n//\n// Independent-file home of the runtime mipmap auto-generation utility\n// (plan-strategy section 2.6 D Open Q-5 selection (a)). Purposefully lives\n// outside `asset-registry.ts` so the asset-registry stays single-purpose\n// (charter proposition 5 producer / consumer split; architecture-principles\n// pipeline isolation).\n//\n// Shader-module DI boundary (bug-20260518 D-1): the per-device pipeline\n// cache builds its single ShaderModule via an injected\n// `MipmapShaderModuleFactory`, NOT via `device.createShaderModule` -- the\n// post-fix-f3 `RhiDevice` surface has no synchronous `createShaderModule`\n// member, and the runtime mipmap utility must NOT reverse-import the\n// rhi-webgpu shim package (charter F1 layering). The factory is wired\n// once at `createRenderer.ts` from `pack.createShaderModule` and threaded\n// through `AssetRegistry.configureGpuDevice` -> `generateMipmaps` ->\n// `getOrCreateMipmapPipeline` -> `ensureDeviceCache`.\n//\n// SSOT three-source convergence (research F-1 + F-2):\n// - webgpufundamentals importing-textures-mipmaps (formula + main loop)\n// - toji web-texture-tool webgpu-mipmap-generator (oversized triangle WGSL)\n// - greggman webgpu-utils generate-mipmap (WeakMap<GPUDevice> cache)\n//\n// Public surface (charter F2 minimal):\n// - numMipLevels({ width, height }) -> number (formula SSOT)\n// - getOrCreateMipmapPipeline(device, format) -> Result (cache lookup; per-format)\n// - mipmapCacheSize(device) -> number (introspection)\n// - generateMipmaps(device, texture, descriptor) -> Result<void>(per-mip render-pass blit-loop)\n//\n// Per-device cache structure (greggman SSOT):\n// WeakMap<MipmapDevice, MipmapPipelineCache>\n// where MipmapPipelineCache = {\n// sampler: Sampler, // shared linear / linear / linear sampler (F-5)\n// module: ShaderModule, // shared oversized-triangle vertex + sampling fragment WGSL\n// layout: BindGroupLayout, // shared sampler @binding(0) + texture_2d<f32> @binding(1)\n// pipelines: Map<GPUTextureFormat, RenderPipeline> // per-format pipeline (F-2 cache key)\n// }\n// Per-device isolation prevents pipeline leak across `createRenderer` calls\n// (charter P5 consistent abstraction; greggman 36-44 anchor).\n//\n// Why this layout (not closure / not class):\n// - `getOrCreateMipmapPipeline` is module-level for test surface (T-M3-01\n// directly imports it; cache reference equality assertions need stable\n// identity across calls).\n// - `numMipLevels` is pure (no device argument); the WeakMap lookup only\n// happens at pipeline-create time.\n\nimport { err, ok, type Result, RhiError } from '@forgeax/engine-rhi';\n\n/**\n * Subset of `RhiDevice` consumed by the mipmap utility (charter F2: only\n * the methods the algorithm actually invokes; the dawn integration tests\n * pass a real `RhiDevice` and the unit cache tests pass a hand-rolled stub).\n *\n * Four entry-points (all synchronous Result):\n * - createSampler (default linear / linear / linear)\n * - createBindGroupLayout\n * - createPipelineLayout\n * - createRenderPipeline (per-format pipeline cache miss)\n *\n * Shader module is NOT an entry-point here; it is supplied by an injected\n * `MipmapShaderModuleFactory` (bug-20260518 D-1) so the utility does not\n * reach into the rhi-webgpu shim package from the runtime layer.\n *\n * Plus `createCommandEncoder` + `queue.submit` are added once the upload\n * call-site (T-M3-05) wires generateMipmaps in; the cache-only public hooks\n * exercised by T-M3-01 do not need them, so they live behind an extended\n * MipmapDeviceForBlit alias.\n */\nexport type MipmapDevice = {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createSampler(desc?: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createBindGroupLayout(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createPipelineLayout(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createRenderPipeline(desc: any): Result<any, any>;\n};\n\n/**\n * Async shader-module factory injected through the call-chain\n * `createRenderer.ts` -> `AssetRegistry.configureGpuDevice` ->\n * `generateMipmaps` -> `getOrCreateMipmapPipeline` -> `ensureDeviceCache`\n * (bug-20260518 D-1 / D-4).\n *\n * Signature mirrors the top-level async `createShaderModule(device, desc)`\n * exposed by the rhi-webgpu shim (and the rhi-wgpu shim) so the\n * call-site in createRenderer can pass `pack.createShaderModule` directly\n * without a structural cast. The opaque module value is typed `unknown`\n * here -- callers do not introspect it; they hand the value back to\n * `createRenderPipeline` descriptors via the cached `MipmapPipelineCache`.\n */\nexport type MipmapShaderModuleFactory = (\n device: MipmapDevice,\n desc: { code: string; label?: string },\n) => Promise<Result<unknown, RhiError>>;\n\n/**\n * Per-device pipeline cache structure (research F-2 SSOT).\n * Held under a module-private `WeakMap<MipmapDevice, MipmapPipelineCache>`.\n */\ninterface MipmapPipelineCache {\n // biome-ignore lint/suspicious/noExplicitAny: cached opaque GPU sampler\n readonly sampler: any;\n // biome-ignore lint/suspicious/noExplicitAny: cached opaque GPU shader module\n readonly module: any;\n // biome-ignore lint/suspicious/noExplicitAny: cached opaque GPU bind-group layout\n readonly layout: any;\n // biome-ignore lint/suspicious/noExplicitAny: per-format render pipeline cache\n readonly pipelines: Map<GPUTextureFormat, any>;\n}\n\n// Module-private cache (greggman 36-44 SSOT). WeakMap so that destroying a\n// device naturally clears its cache (no manual cleanup hook needed).\nconst deviceCache: WeakMap<MipmapDevice, MipmapPipelineCache> = new WeakMap();\n\n/**\n * Oversized-triangle WGSL (toji + greggman convergent template).\n *\n * Vertex stage emits a single triangle covering the entire NDC, and texCoord\n * is computed from clip-space position via `pos * vec2(0.5, -0.5) +\n * vec2(0.5)` (NDC -> UV with Y-flip in one fused MAD; saves a 6-vertex quad).\n *\n * Fragment stage samples the bound `texture_2d<f32>` with the linear /\n * linear / linear sampler -- bilinear when the source mip is read by the\n * destination mip, automatic sRGB decode / encode happens in the spec when\n * source AND destination views are the SAME `*-srgb` format (research F-3).\n */\nconst MIPMAP_WGSL = `\nstruct VsOut {\n @builtin(position) clip : vec4<f32>,\n @location(0) uv : vec2<f32>,\n};\n\n@vertex\nfn vs_main(@builtin(vertex_index) vid : u32) -> VsOut {\n // 3 vertices forming an oversized triangle: (-1,-1), (-1,3), (3,-1)\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n vec2<f32>( 3.0, -1.0),\n );\n let pos = positions[vid];\n var out : VsOut;\n out.clip = vec4<f32>(pos, 0.0, 1.0);\n // NDC -> UV with Y-flip fused into a single MAD.\n out.uv = pos * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n return out;\n}\n\n@group(0) @binding(0) var src_sampler : sampler;\n@group(0) @binding(1) var src_texture : texture_2d<f32>;\n\n@fragment\nfn fs_main(in : VsOut) -> @location(0) vec4<f32> {\n return textureSample(src_texture, src_sampler, in.uv);\n}\n`;\n\n/**\n * Compute mip-level count for a 2D texture (research F-1 SSOT formula).\n *\n * Spec-anchor: WebGPU §3.6 texture-creation says `mipLevelCount` defaults\n * to 1; the runtime utility opts AI users into a full chain via\n * `floor(log2(max(width, height))) + 1` -- the same formula greggman /\n * toji / webgpufundamentals all converge on.\n *\n * @example\n * numMipLevels({ width: 256, height: 256 }) // 9\n * numMipLevels({ width: 1, height: 1 }) // 1\n */\nexport function numMipLevels(size: { width: number; height: number }): number {\n const max = Math.max(size.width, size.height);\n if (max <= 1) return 1;\n return Math.floor(Math.log2(max)) + 1;\n}\n\n/**\n * Number of cached pipelines for the device (introspection hook used by\n * T-M3-01 (c) cache-hit / (d) per-device-isolation tests; charter P3\n * explicit failure: a cache size of 0 on a fresh device is a witnessed\n * pre-condition rather than a swept-under hint).\n */\nexport function mipmapCacheSize(device: MipmapDevice): number {\n const cache = deviceCache.get(device);\n return cache?.pipelines.size ?? 0;\n}\n\n/**\n * Get the existing per-format render pipeline or build a fresh one.\n *\n * Per-device WeakMap + per-format `Map<GPUTextureFormat, RenderPipeline>`\n * (greggman 36-44 + 119-122). The shared sampler / shader-module /\n * bind-group-layout are constructed lazily on the first cache miss for a\n * given device and reused across all formats on that device.\n */\nexport async function getOrCreateMipmapPipeline(\n device: MipmapDevice,\n format: GPUTextureFormat,\n asyncCreateShaderModule: MipmapShaderModuleFactory,\n // biome-ignore lint/suspicious/noExplicitAny: returns opaque GPU pipeline\n): Promise<Result<any, unknown>> {\n const cache = await ensureDeviceCache(device, asyncCreateShaderModule);\n if (!cache.ok) return cache;\n const existing = cache.value.pipelines.get(format);\n if (existing !== undefined) {\n return ok(existing);\n }\n const layoutRes = device.createPipelineLayout({\n label: 'mipmap-pl',\n bindGroupLayouts: [cache.value.layout],\n });\n if (!layoutRes.ok) return layoutRes;\n const pipelineRes = device.createRenderPipeline({\n label: `mipmap-pipeline-${format}`,\n layout: layoutRes.value,\n vertex: { module: cache.value.module, entryPoint: 'vs_main' },\n fragment: {\n module: cache.value.module,\n entryPoint: 'fs_main',\n targets: [{ format }],\n },\n primitive: { topology: 'triangle-list' },\n });\n if (!pipelineRes.ok) return pipelineRes;\n cache.value.pipelines.set(format, pipelineRes.value);\n return pipelineRes;\n}\n\nasync function ensureDeviceCache(\n device: MipmapDevice,\n asyncCreateShaderModule: MipmapShaderModuleFactory,\n): Promise<Result<MipmapPipelineCache, RhiError>> {\n const existing = deviceCache.get(device);\n if (existing !== undefined) return ok(existing);\n\n const moduleRes = await asyncCreateShaderModule(device, {\n code: MIPMAP_WGSL,\n label: 'mipmap-wgsl',\n });\n if (!moduleRes.ok) return moduleRes;\n\n const samplerRes = device.createSampler({\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'linear',\n });\n if (!samplerRes.ok) return samplerRes;\n\n // GPUShaderStage.FRAGMENT = 0x2 spec constant; embedded literally to keep\n // the utility math-free (charter F2 minimal surface; spec value is stable).\n const FRAGMENT_STAGE = 0x2;\n const layoutRes = device.createBindGroupLayout({\n label: 'mipmap-bgl',\n entries: [\n { binding: 0, visibility: FRAGMENT_STAGE, sampler: { type: 'filtering' } },\n {\n binding: 1,\n visibility: FRAGMENT_STAGE,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n ],\n });\n if (!layoutRes.ok) return layoutRes;\n\n const cache: MipmapPipelineCache = {\n sampler: samplerRes.value,\n module: moduleRes.value,\n layout: layoutRes.value,\n pipelines: new Map(),\n };\n deviceCache.set(device, cache);\n return ok(cache);\n}\n\n/**\n * Extended device shape used by `generateMipmaps` (call-site T-M3-05).\n * Adds command-encoder + bind-group + texture-view + queue surfaces beyond\n * the cache-only `MipmapDevice` so the pipeline-cache unit tests still\n * compile against the smaller surface.\n */\nexport type MipmapBlitDevice = MipmapDevice & {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createTexture(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createBindGroup(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createTextureView(texture: any, desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createCommandEncoder(desc?: any): Result<any, any>;\n readonly queue: {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n submit(buffers: ReadonlyArray<any>): Result<void, any>;\n };\n};\n\nfunction recordMipmapBlit<E>(\n device: MipmapBlitDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture handle\n texture: any,\n levels: number,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU pipeline handle\n pipeline: any,\n cache: MipmapPipelineCache,\n): Result<void, E> {\n const encoderRes = device.createCommandEncoder({ label: 'mipmap-encoder' });\n if (!encoderRes.ok) return encoderRes;\n const encoder = encoderRes.value;\n\n for (let i = 1; i < levels; i++) {\n const srcViewRes = device.createTextureView(texture, {\n baseMipLevel: i - 1,\n mipLevelCount: 1,\n dimension: '2d',\n });\n if (!srcViewRes.ok) return srcViewRes;\n\n const dstViewRes = device.createTextureView(texture, {\n baseMipLevel: i,\n mipLevelCount: 1,\n dimension: '2d',\n });\n if (!dstViewRes.ok) return dstViewRes;\n\n const bindGroupRes = device.createBindGroup({\n label: `mipmap-bg-${i}`,\n layout: cache.layout,\n entries: [\n { binding: 0, resource: { kind: 'sampler', value: cache.sampler } },\n { binding: 1, resource: { kind: 'textureView', value: srcViewRes.value } },\n ],\n });\n if (!bindGroupRes.ok) return bindGroupRes;\n\n const pass = encoder.beginRenderPass({\n label: `mipmap-pass-${i}`,\n colorAttachments: [\n {\n view: dstViewRes.value,\n clearValue: { r: 0, g: 0, b: 0, a: 1 },\n loadOp: 'clear',\n storeOp: 'store',\n },\n ],\n });\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindGroupRes.value);\n pass.draw(3, 1, 0, 0);\n pass.end();\n }\n\n const finishRes = encoder.finish();\n if (!finishRes.ok) return finishRes;\n return device.queue.submit([finishRes.value]);\n}\n\n/**\n * Per-mip render-pass blit-loop (research F-1 SSOT main template).\n *\n * For mip levels 1..levels-1: source view = previous mip {baseMipLevel:i-1,\n * mipLevelCount:1}; destination view = current mip {baseMipLevel:i,\n * mipLevelCount:1, usage: RENDER_ATTACHMENT}; oversized-triangle pipeline\n * draws 3 vertices, fragment shader samples source via linear sampler.\n *\n * Spec sRGB correctness (F-3): when format is `*-srgb`, both views inherit\n * the sRGB encoding so hardware decode -> bilinear in linear -> encode back\n * happens automatically; no special-casing required.\n *\n * `levels` defaults to `numMipLevels({ width, height })`. AI users that\n * already created the texture with explicit `mipLevelCount` should pass the\n * same value here.\n */\nexport async function generateMipmaps(\n device: MipmapBlitDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture handle\n texture: any,\n descriptor: {\n readonly format: GPUTextureFormat;\n readonly width: number;\n readonly height: number;\n readonly levels?: number;\n },\n asyncCreateShaderModule: MipmapShaderModuleFactory,\n): Promise<Result<void, unknown>> {\n const levels = descriptor.levels ?? numMipLevels(descriptor);\n if (levels <= 1) return ok(undefined);\n\n const pipelineRes = await getOrCreateMipmapPipeline(\n device,\n descriptor.format,\n asyncCreateShaderModule,\n );\n if (!pipelineRes.ok) return pipelineRes;\n const cache = deviceCache.get(device);\n if (cache === undefined) {\n return err({ code: 'webgpu-runtime-error', message: 'mipmap cache missing after create' });\n }\n return recordMipmapBlit<unknown>(device, texture, levels, pipelineRes.value, cache);\n}\n\n/**\n * Synchronous sibling of `generateMipmaps` (feat-20260601-gpu-resource-store\n * -extraction D-9). Identical per-mip blit loop, but reads the per-format\n * pipeline + shared sampler / layout from the prewarmed device cache instead\n * of building them. The pipeline MUST already be present (via a prior\n * `getOrCreateMipmapPipeline` / `prewarmMipmapPipeline` async call) -- an\n * un-prewarmed device or format returns a structured `RhiError` rather than\n * awaiting a build, so the synchronous `draw(world)` frame contract is never\n * broken. The async build itself does not affect the written bytes (same\n * shader, same encoder sequence), so prewarm + sync blit reproduces the\n * pre-extraction async `generateMipmaps` byte-for-byte (D-9 sub-contract 5).\n */\nexport function blitMipmapsSync(\n device: MipmapBlitDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture handle\n texture: any,\n descriptor: {\n readonly format: GPUTextureFormat;\n readonly width: number;\n readonly height: number;\n readonly levels?: number;\n },\n): Result<void, RhiError> {\n const levels = descriptor.levels ?? numMipLevels(descriptor);\n if (levels <= 1) return ok(undefined);\n\n const cache = deviceCache.get(device);\n if (cache === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'mipmap pipeline cache prewarmed for this device before blitMipmapsSync',\n hint: 'call prewarmMipmapPipeline(device, formats) at renderer.ready before the synchronous record-stage mipmap blit',\n }),\n );\n }\n const pipeline = cache.pipelines.get(descriptor.format);\n if (pipeline === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: `mipmap pipeline for format ${descriptor.format} prewarmed`,\n hint: `format ${descriptor.format} was not prewarmed; add it to the prewarmMipmapPipeline format list at renderer.ready`,\n }),\n );\n }\n\n return recordMipmapBlit<RhiError>(device, texture, levels, pipeline, cache);\n}\n","import type { CodecError, TranscodeModel } from '@forgeax/engine-codec';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type {\n AssetCodec,\n AssetCodecFailureDetail,\n EquirectAsset,\n FontAsset,\n LoadContext,\n Loader,\n LoaderAsyncResult,\n RenderPipelineAsset,\n TextureAsset,\n TilesetAsset,\n} from '@forgeax/engine-types';\nimport { AssetError } from '@forgeax/engine-types';\nimport type { PackLoaderInput } from '../loader-registry';\nimport { numMipLevels } from '../mipmap-generator';\n\ntype PackArtifact = PackLoaderInput['artifacts'][string];\n\ntype CodecFailureProjection = {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n};\n\nfunction firstArtifact(input: PackLoaderInput): PackArtifact | undefined {\n return input.artifacts.body ?? Object.values(input.artifacts)[0];\n}\n\nfunction payloadNumber(payload: Record<string, unknown>, key: string, fallback: number): number {\n const value = payload[key];\n return typeof value === 'number' ? value : fallback;\n}\n\nfunction payloadColorSpace(payload: Record<string, unknown>): 'srgb' | 'linear' {\n return payload.colorSpace === 'linear' ? 'linear' : 'srgb';\n}\n\nfunction invalidPackAsset<T>(input: PackLoaderInput, expected: string): LoaderAsyncResult<T> {\n return {\n ok: false,\n error: new AssetError({\n code: 'asset-parse-failed',\n expected,\n hint: `Pack v2 asset ${input.guid} must provide an asset-local artifact`,\n detail: { sourcePath: input.guid },\n }),\n };\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction finiteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction positiveInteger(value: unknown): value is number {\n return finiteNumber(value) && Number.isInteger(value) && value > 0;\n}\n\nfunction validRenderPipelineConfig(value: unknown): value is Record<string, unknown> {\n if (!record(value)) return false;\n const passCount = value.passCount;\n if (passCount !== undefined && !positiveInteger(passCount)) return false;\n const clusterGrid = value.clusterGrid;\n if (clusterGrid !== undefined) {\n if (\n !record(clusterGrid) ||\n !['x', 'y', 'z'].every((axis) => {\n const size = clusterGrid[axis];\n return positiveInteger(size) && size <= 64;\n })\n ) {\n return false;\n }\n }\n const ssao = value.ssao;\n if (ssao !== undefined && (!record(ssao) || typeof ssao.enabled !== 'boolean')) return false;\n const postEffects = value.postEffects;\n return (\n postEffects === undefined ||\n (Array.isArray(postEffects) &&\n postEffects.every((effect) => typeof effect === 'string' && effect.length > 0))\n );\n}\n\nfunction validTilesetRegion(value: unknown, atlasCount: number): boolean {\n if (!record(value)) return false;\n const { x, y, width, height, atlasIndex } = value;\n return (\n finiteNumber(x) &&\n finiteNumber(y) &&\n positiveInteger(width) &&\n positiveInteger(height) &&\n (atlasIndex === undefined ||\n (typeof atlasIndex === 'number' &&\n Number.isInteger(atlasIndex) &&\n atlasIndex >= 0 &&\n atlasIndex < atlasCount))\n );\n}\n\nfunction validTilesetTile(value: unknown, regionCount: number): boolean {\n if (!record(value)) return false;\n const regionIndex = value.regionIndex;\n return (\n typeof regionIndex === 'number' &&\n Number.isInteger(regionIndex) &&\n regionIndex >= 0 &&\n regionIndex < regionCount\n );\n}\n\nfunction validAtlasSize(value: unknown): boolean {\n return record(value) && positiveInteger(value.pixelWidth) && positiveInteger(value.pixelHeight);\n}\n\nfunction readJsonArtifact(\n input: PackLoaderInput,\n kind: string,\n): Record<string, unknown> | undefined {\n const artifact = firstArtifact(input);\n if (artifact === undefined) return undefined;\n try {\n const value: unknown = JSON.parse(new TextDecoder().decode(artifact.bytes));\n return record(value) && value.kind === kind ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction renderPipelineDescriptor(value: Record<string, unknown>): RenderPipelineAsset | undefined {\n if (value.kind !== 'render-pipeline') return undefined;\n const pipelineId = value.pipelineId;\n if (typeof pipelineId !== 'string' || pipelineId.trim().length === 0) return undefined;\n const config = value.config;\n if (config !== undefined && !validRenderPipelineConfig(config)) return undefined;\n return {\n kind: 'render-pipeline',\n pipelineId,\n ...(config === undefined\n ? {}\n : { config: config as NonNullable<RenderPipelineAsset['config']> }),\n };\n}\n\nfunction tilesetDescriptor(\n value: Record<string, unknown>,\n refs: readonly string[],\n): TilesetAsset | undefined {\n if (value.kind !== 'tileset') return undefined;\n const rawAtlases = value.atlases;\n if (!Array.isArray(rawAtlases) || rawAtlases.length === 0) return undefined;\n if (!rawAtlases.every((atlas) => typeof atlas === 'string' && atlas.length > 0)) return undefined;\n const atlases = rawAtlases as string[];\n if (atlases.length !== refs.length || atlases.some((guid, index) => guid !== refs[index])) {\n return undefined;\n }\n const { tileWidth, tileHeight, columns, rows, regions, tiles, atlasSizes } = value;\n if (\n typeof tileWidth !== 'number' ||\n tileWidth <= 0 ||\n typeof tileHeight !== 'number' ||\n tileHeight <= 0 ||\n typeof columns !== 'number' ||\n !Number.isInteger(columns) ||\n columns <= 0 ||\n typeof rows !== 'number' ||\n !Number.isInteger(rows) ||\n rows <= 0 ||\n !Array.isArray(regions) ||\n !regions.every((region) => record(region) && validTilesetRegion(region, atlases.length)) ||\n !Array.isArray(tiles) ||\n !tiles.every((tile) => validTilesetTile(tile, regions.length)) ||\n (atlasSizes !== undefined &&\n (!Array.isArray(atlasSizes) ||\n atlasSizes.length !== atlases.length ||\n !atlasSizes.every((size) => validAtlasSize(size))))\n ) {\n return undefined;\n }\n return {\n kind: 'tileset',\n atlases: [...atlases],\n tileWidth,\n tileHeight,\n columns,\n rows,\n regions: regions as TilesetAsset['regions'],\n tiles: tiles as TilesetAsset['tiles'],\n ...(Array.isArray(atlasSizes)\n ? { atlasSizes: atlasSizes as NonNullable<TilesetAsset['atlasSizes']> }\n : {}),\n };\n}\n\nfunction codecProfile(codec: AssetCodec | undefined): string | undefined {\n return codec?.profile;\n}\n\nexport type CodecContextFailure =\n | {\n readonly code: 'basis-profile-unsupported';\n readonly detail: { readonly profile: string };\n }\n | {\n readonly code: 'ktx2-color-space-mismatch';\n readonly detail: {\n readonly authoredColorSpace: 'srgb' | 'linear';\n readonly dfdColorSpace: 'srgb' | 'linear' | 'unknown';\n };\n };\n\nfunction projectCodecFailureDetail(\n input: PackLoaderInput,\n codec: AssetCodec,\n caps: LoadContext['transcodeCaps'],\n failure: CodecFailureProjection,\n targetFormat?: GPUTextureFormat,\n): AssetCodecFailureDetail {\n return {\n sourcePath: input.guid,\n codecCode: failure.code,\n codecExpected: failure.expected,\n codecHint: failure.hint,\n codecDetail: failure.detail,\n container: codec.container ?? 'basis',\n ...(codec.profile === undefined ? {} : { profile: codec.profile }),\n ...(targetFormat === undefined ? {} : { targetFormat }),\n capabilities: caps,\n };\n}\n\nfunction codecFailure(\n input: PackLoaderInput,\n codec: AssetCodec,\n caps: LoadContext['transcodeCaps'],\n failure: CodecError['error'],\n targetFormat?: GPUTextureFormat,\n): AssetError {\n const detail = projectCodecFailureDetail(input, codec, caps, failure, targetFormat);\n return new AssetError({\n code: 'asset-parse-failed',\n expected: failure.expected,\n hint: failure.hint,\n detail,\n });\n}\n\nfunction codecContextFailure(\n input: PackLoaderInput,\n codec: AssetCodec,\n caps: LoadContext['transcodeCaps'],\n failure: CodecContextFailure,\n expected: string,\n hint: string,\n targetFormat?: GPUTextureFormat,\n): AssetError {\n const detail = projectCodecFailureDetail(\n input,\n codec,\n caps,\n {\n code: failure.code,\n expected,\n hint,\n detail: failure.detail,\n },\n targetFormat,\n );\n return new AssetError({\n code: 'asset-parse-failed',\n expected,\n hint,\n detail,\n });\n}\n\nfunction transcodeModel(profile: string): TranscodeModel | undefined {\n if (profile === 'etc1s') return 'etc1s';\n if (profile === 'uastc' || profile === 'uastc-ldr') return 'uastc-ldr';\n if (profile === 'uastc-hdr') return 'uastc-hdr';\n return undefined;\n}\n\nasync function loadTexturePack(\n input: PackLoaderInput,\n ctx: LoadContext,\n): Promise<LoaderAsyncResult<TextureAsset>> {\n const artifact = firstArtifact(input);\n if (artifact === undefined)\n return invalidPackAsset<TextureAsset>(input, 'texture asset-local image artifact');\n const payload = input.payload;\n const width = payloadNumber(payload, 'width', 0);\n const height = payloadNumber(payload, 'height', 0);\n const colorSpace = payloadColorSpace(payload);\n const codec = artifact.descriptor.assetCodec;\n const profile = codecProfile(codec);\n const model =\n codec?.name === 'basis' && profile !== undefined ? transcodeModel(profile) : undefined;\n\n if (codec?.name === 'basis' && codec.container === 'basis') {\n const basisCodec = codec;\n if (model === undefined) {\n return {\n ok: false,\n error: codecContextFailure(\n input,\n basisCodec,\n ctx.transcodeCaps,\n {\n code: 'basis-profile-unsupported',\n detail: { profile: codec.profile ?? 'missing' },\n },\n 'raw Basis artifact with an explicit ETC1S or UASTC-LDR profile',\n 'set assetCodec.profile to etc1s or uastc-ldr and re-cook the source',\n ),\n };\n }\n try {\n const { selectTranscodeTarget, transcodeBasis } = await import('@forgeax/engine-codec');\n const target = selectTranscodeTarget(\n { model, srgb: colorSpace === 'srgb', channels: 'rgba' },\n ctx.transcodeCaps,\n );\n const transcoded = await transcodeBasis(artifact.bytes, target);\n if (!transcoded.ok) {\n return {\n ok: false,\n error: codecFailure(input, basisCodec, ctx.transcodeCaps, transcoded.error, target),\n };\n }\n const data = new Uint8Array(\n transcoded.value.mips.reduce((size, mip) => size + mip.data.length, 0),\n );\n let offset = 0;\n for (const mip of transcoded.value.mips) {\n data.set(mip.data, offset);\n offset += mip.data.length;\n }\n return {\n ok: true,\n value: {\n kind: 'texture',\n width: transcoded.value.width,\n height: transcoded.value.height,\n format: target,\n data,\n colorSpace,\n mipmap: transcoded.value.mips.length > 1,\n mipLevelCount: Math.max(1, transcoded.value.mips.length),\n },\n };\n } catch (error) {\n return {\n ok: false,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: 'loadable raw Basis texture artifact',\n hint: error instanceof Error ? error.message : String(error),\n detail: {\n sourcePath: input.guid,\n codecCode: 'runtime-loader-exception',\n codecExpected: 'loadable raw Basis texture artifact',\n codecHint: error instanceof Error ? error.message : String(error),\n codecDetail: { reason: 'runtime-loader-exception' },\n container: basisCodec.container ?? 'basis',\n ...(basisCodec.profile === undefined ? {} : { profile: basisCodec.profile }),\n capabilities: ctx.transcodeCaps,\n },\n }),\n };\n }\n }\n\n if (model !== undefined && codec !== undefined) {\n const ktx2Codec = codec;\n try {\n const { ktx2ColorSpace, parseKtx2, selectTranscodeTarget, transcodeKtx2 } = await import(\n '@forgeax/engine-codec'\n );\n const parsed = await parseKtx2(artifact.bytes);\n if (!parsed.ok) {\n return {\n ok: false,\n error: codecFailure(input, ktx2Codec, ctx.transcodeCaps, parsed.error),\n };\n }\n const projectedColorSpace = ktx2ColorSpace(parsed.value);\n if (projectedColorSpace === undefined || projectedColorSpace !== colorSpace) {\n return {\n ok: false,\n error: codecContextFailure(\n input,\n ktx2Codec,\n ctx.transcodeCaps,\n {\n code: 'ktx2-color-space-mismatch',\n detail: {\n authoredColorSpace: colorSpace,\n dfdColorSpace: projectedColorSpace ?? 'unknown',\n },\n },\n 'Basis KTX2 DFD transfer function matching the texture colorSpace',\n 'align the texture payload colorSpace with the KTX2 DFD and re-cook the source',\n ),\n };\n }\n const target = selectTranscodeTarget(\n { model, srgb: colorSpace === 'srgb', channels: 'rgba' },\n ctx.transcodeCaps,\n );\n const transcoded = await transcodeKtx2(parsed.value, target);\n if (!transcoded.ok) {\n return {\n ok: false,\n error: codecFailure(input, ktx2Codec, ctx.transcodeCaps, transcoded.error, target),\n };\n }\n const data = new Uint8Array(\n transcoded.value.mips.reduce((size, mip) => size + mip.data.length, 0),\n );\n let offset = 0;\n for (const mip of transcoded.value.mips) {\n data.set(mip.data, offset);\n offset += mip.data.length;\n }\n return {\n ok: true,\n value: {\n kind: 'texture',\n width: transcoded.value.width,\n height: transcoded.value.height,\n format: target,\n data,\n colorSpace,\n mipmap: transcoded.value.mips.length > 1,\n mipLevelCount: Math.max(1, transcoded.value.mips.length),\n },\n };\n } catch (error) {\n if (error instanceof AssetError) return { ok: false, error };\n return {\n ok: false,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: 'loadable Basis KTX2 texture artifact',\n hint: error instanceof Error ? error.message : String(error),\n detail: {\n sourcePath: input.guid,\n codecCode: 'runtime-loader-exception',\n codecExpected: 'loadable Basis KTX2 texture artifact',\n codecHint: error instanceof Error ? error.message : String(error),\n codecDetail: { reason: 'runtime-loader-exception' },\n container: ktx2Codec.container ?? 'ktx2',\n ...(ktx2Codec.profile === undefined ? {} : { profile: ktx2Codec.profile }),\n capabilities: ctx.transcodeCaps,\n },\n }),\n };\n }\n }\n\n const mipmap = payload.mipmap === true;\n return {\n ok: true,\n value: {\n kind: 'texture',\n width,\n height,\n format: (payload.format ??\n (colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm')) as GPUTextureFormat,\n data: artifact.bytes,\n colorSpace,\n mipmap,\n mipLevelCount: mipmap ? numMipLevels({ width, height }) : 1,\n },\n };\n}\n\nasync function loadEquirectPack(input: PackLoaderInput): Promise<LoaderAsyncResult<EquirectAsset>> {\n const artifact = firstArtifact(input);\n if (artifact === undefined)\n return invalidPackAsset<EquirectAsset>(input, 'equirect asset-local image artifact');\n const payload = input.payload;\n return {\n ok: true,\n value: {\n kind: 'equirect',\n width: payloadNumber(payload, 'width', 0),\n height: payloadNumber(payload, 'height', 0),\n format: (payload.format ?? 'rgba16float') as GPUTextureFormat,\n data: artifact.bytes,\n colorSpace: payloadColorSpace(payload),\n },\n };\n}\n\nfunction parseGlyphs(value: unknown): FontAsset['glyphs'] {\n if (typeof value !== 'object' || value === null) return {};\n const glyphs: FontAsset['glyphs'] = {};\n for (const [codepoint, raw] of Object.entries(value as Record<string, unknown>)) {\n if (typeof raw !== 'object' || raw === null) continue;\n const metric = raw as Record<string, unknown>;\n const size = metric.size as Record<string, unknown> | undefined;\n const region = metric.region as Record<string, unknown> | undefined;\n if (\n typeof metric.advance !== 'number' ||\n typeof metric.bearingX !== 'number' ||\n typeof metric.bearingY !== 'number' ||\n typeof size?.w !== 'number' ||\n typeof size.h !== 'number' ||\n typeof region?.x !== 'number' ||\n typeof region.y !== 'number' ||\n typeof region.w !== 'number' ||\n typeof region.h !== 'number'\n ) {\n continue;\n }\n glyphs[Number(codepoint)] = {\n advance: metric.advance,\n bearingX: metric.bearingX,\n bearingY: metric.bearingY,\n size: { w: size.w, h: size.h },\n region: { x: region.x, y: region.y, w: region.w, h: region.h },\n };\n }\n return glyphs;\n}\n\nasync function loadFontPack(\n input: PackLoaderInput,\n ctx: LoadContext,\n): Promise<LoaderAsyncResult<FontAsset>> {\n const payload = input.payload;\n const atlasGuid = payload.atlasGuid;\n const samplerGuid = payload.samplerGuid;\n const common = payload.common;\n if (\n typeof atlasGuid !== 'string' ||\n typeof samplerGuid !== 'string' ||\n typeof common !== 'object' ||\n common === null\n ) {\n return invalidPackAsset<FontAsset>(\n input,\n 'font payload with atlasGuid, samplerGuid, and common',\n );\n }\n const parsedAtlas = AssetGuid.parse(atlasGuid);\n const parsedSampler = AssetGuid.parse(samplerGuid);\n if (!parsedAtlas.ok) return { ok: false, error: parsedAtlas.error };\n if (!parsedSampler.ok) return { ok: false, error: parsedSampler.error };\n const atlasResolved = await ctx.resolveRef(atlasGuid);\n if (!atlasResolved.ok) return atlasResolved;\n const samplerResolved = await ctx.resolveRef(samplerGuid);\n if (!samplerResolved.ok) return samplerResolved;\n const commonRecord = common as Record<string, unknown>;\n const commonFields = [\n 'lineHeight',\n 'base',\n 'distanceRange',\n 'pxRange',\n 'atlasWidth',\n 'atlasHeight',\n ];\n if (commonFields.some((key) => typeof commonRecord[key] !== 'number')) {\n return invalidPackAsset<FontAsset>(input, 'font common block with numeric layout fields');\n }\n return {\n ok: true,\n value: {\n kind: 'font',\n atlas: parsedAtlas.value,\n sampler: parsedSampler.value,\n glyphs: parseGlyphs(payload.glyphs),\n common: {\n lineHeight: commonRecord.lineHeight as number,\n base: commonRecord.base as number,\n distanceRange: commonRecord.distanceRange as number,\n pxRange: commonRecord.pxRange as number,\n atlasWidth: commonRecord.atlasWidth as number,\n atlasHeight: commonRecord.atlasHeight as number,\n },\n },\n };\n}\n\nexport const textureLoader: Loader = {\n kind: 'texture',\n load: () => undefined,\n loadPack: loadTexturePack,\n};\n\nexport const equirectLoader: Loader = {\n kind: 'equirect',\n load: () => undefined,\n loadPack: loadEquirectPack,\n};\n\nexport const fontLoader: Loader = {\n kind: 'font',\n load: () => undefined,\n loadPack: loadFontPack,\n};\n\nexport const renderPipelineLoader: Loader = {\n kind: 'render-pipeline',\n load: (payload) => renderPipelineDescriptor({ ...payload, kind: 'render-pipeline' }),\n loadPack: async (input) => {\n if (firstArtifact(input) === undefined) {\n const value = renderPipelineDescriptor({ ...input.payload, kind: 'render-pipeline' });\n return value === undefined\n ? invalidPackAsset<RenderPipelineAsset>(input, 'a valid render-pipeline descriptor')\n : { ok: true, value };\n }\n const payload = readJsonArtifact(input, 'render-pipeline');\n const value = payload === undefined ? undefined : renderPipelineDescriptor(payload);\n return payload === undefined\n ? invalidPackAsset<RenderPipelineAsset>(input, 'render-pipeline JSON descriptor artifact')\n : value === undefined\n ? invalidPackAsset<RenderPipelineAsset>(input, 'a complete render-pipeline descriptor')\n : { ok: true, value };\n },\n};\n\nexport const tilesetLoader: Loader = {\n kind: 'tileset',\n load: (payload, refs) => {\n const rawAtlases = payload.atlases;\n const resolved = Array.isArray(rawAtlases)\n ? rawAtlases.map((value) => (typeof value === 'number' ? refs?.[value] : value))\n : undefined;\n return resolved === undefined || resolved.some((value) => typeof value !== 'string')\n ? undefined\n : tilesetDescriptor({ ...payload, kind: 'tileset', atlases: resolved }, resolved);\n },\n loadPack: async (input) => {\n if (firstArtifact(input) === undefined) {\n const value = tilesetDescriptor({ ...input.payload, kind: 'tileset' }, input.refs);\n return value === undefined\n ? invalidPackAsset<TilesetAsset>(input, 'a valid tileset descriptor')\n : { ok: true, value };\n }\n const payload = readJsonArtifact(input, 'tileset');\n const value = payload === undefined ? undefined : tilesetDescriptor(payload, input.refs);\n return payload === undefined\n ? invalidPackAsset<TilesetAsset>(input, 'tileset JSON descriptor artifact')\n : value === undefined\n ? invalidPackAsset<TilesetAsset>(input, 'a tileset descriptor matching envelope refs')\n : { ok: true, value };\n },\n};\n\nexport const PACK_ARTIFACT_LOADERS: readonly Loader[] = [\n textureLoader,\n fontLoader,\n equirectLoader,\n renderPipelineLoader,\n tilesetLoader,\n];\n","// @forgeax/engine-assets-runtime -- inline pack-payload loader bodies\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport { PROCEDURAL_FLOATS_PER_VERTEX } from '@forgeax/engine-geometry';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type {\n AddressMode,\n AnimationChannel,\n AnimationGraph,\n AnimationGraphNode,\n Asset,\n AssetGuid as AssetGuidType,\n AudioClipAsset,\n CompareFunction,\n FilterMode,\n LoadContext,\n Loader,\n MaterialAsset,\n MaterialPass,\n MaterialTextureCoordinates,\n ParseErrorDetail,\n ParticleEffectAsset,\n MeshAsset as TypesMeshAsset,\n} from '@forgeax/engine-types';\nimport { resolveMaterialTextureCoordinates } from '@forgeax/engine-types';\nimport { MeshBinAssetError } from '../errors/asset';\nimport { parseScenePayload } from '../scene-payload';\nimport { unpackMeshBinV4 } from './mesh-bin';\nimport { renderPipelineLoader, tilesetLoader } from './pack-artifact';\n\n// === Inline pack-payload loader bodies (feat-20260603-asset-import-loader-injection\n// M1 / w4) ===\n//\n// The eight `if (kind === ...)` arms that lived inside\n// `AssetRegistry.parseAssetPayload` (research Finding 1) are extracted here as\n// module-level `{ kind, load }` objects so they register into a\n// `LoaderRegistry` (D-1) and can be imported by `wireDefaultLoaders` (w5). The\n// body logic is copied verbatim — M1 is a pure refactor (AC-03), no behavioural\n// change. Each parses an inline `.pack.json` payload synchronously and returns\n// the `Asset` POD or `undefined` (parse rejected). The `scene` arm routes its\n// structured out-of-bounds-ref error back through the LoaderOutput return\n// value instead of the old shared instance slot (D-8 channel replaced by F21).\n\n/** mesh loader — Float32Array / Uint16Array | Uint32Array normalisation -> MeshAsset.\n *\n * feat-20260611: skinIndex (Uint16Array) and skinWeight (Float32Array) accept\n * both their native typed-array shape (in-memory: dawn smoke / direct\n * `register` test) AND `number[]` (post-`JSON.stringify` shape produced by the\n * dev-server / build-mode pack-body round-trip — `JSON.stringify(pack) -> fetch\n * -> JSON.parse` flattens every typed array to a plain Array). Same dual\n * contract `skeletonLoader` / `animationClipLoader` already honour (PR #350);\n * without the array arm, every Fox.glb / Khronos skinned glTF surfaces as\n * `asset-parse-failed` on the browser path while dawn smoke stays green.\n */\nexport const meshLoader: Loader = {\n kind: 'mesh',\n load(payload) {\n const vertexData = payload.vertices;\n const indexData = payload.indices;\n const rawAttributes = (payload.attributes as Record<string, unknown> | undefined) ?? {};\n const attributes: Record<string, unknown> = { ...rawAttributes };\n const rawAabb = payload.aabb;\n let aabb: Float32Array | undefined;\n if (rawAabb instanceof Float32Array) {\n aabb = rawAabb;\n } else if (Array.isArray(rawAabb)) {\n aabb = new Float32Array(rawAabb as number[]);\n } else if (rawAabb !== undefined) {\n return undefined;\n }\n\n let morphTargets: TypesMeshAsset['morphTargets'];\n const rawMorphTargets = payload.morphTargets;\n if (rawMorphTargets !== undefined) {\n if (\n !Array.isArray(rawMorphTargets) ||\n rawMorphTargets.length < 1 ||\n rawMorphTargets.length > 8\n ) {\n return undefined;\n }\n const parsedTargets: NonNullable<TypesMeshAsset['morphTargets']>[number][] = [];\n for (const rawTarget of rawMorphTargets) {\n if (typeof rawTarget !== 'object' || rawTarget === null) return undefined;\n const source = rawTarget as Record<string, unknown>;\n const target: {\n position?: Float32Array;\n normal?: Float32Array;\n tangent?: Float32Array;\n } = {};\n for (const [key, value] of Object.entries(source)) {\n if (key !== 'position' && key !== 'normal' && key !== 'tangent') return undefined;\n if (value instanceof Float32Array) target[key] = new Float32Array(value);\n else if (Array.isArray(value)) target[key] = new Float32Array(value as number[]);\n else return undefined;\n }\n if (Object.keys(target).length === 0) return undefined;\n parsedTargets.push(target);\n }\n morphTargets = parsedTargets;\n }\n let morphWeights: Float32Array | undefined;\n const rawMorphWeights = payload.morphWeights;\n if (rawMorphWeights !== undefined) {\n if (rawMorphWeights instanceof Float32Array) morphWeights = new Float32Array(rawMorphWeights);\n else if (Array.isArray(rawMorphWeights))\n morphWeights = new Float32Array(rawMorphWeights as number[]);\n else return undefined;\n if (morphTargets !== undefined && morphWeights.length !== morphTargets.length)\n return undefined;\n }\n\n const skinIndexRaw = rawAttributes.skinIndex;\n if (skinIndexRaw instanceof Uint16Array) {\n attributes.skinIndex = skinIndexRaw;\n } else if (Array.isArray(skinIndexRaw)) {\n attributes.skinIndex = new Uint16Array(skinIndexRaw as number[]);\n } else if (skinIndexRaw !== undefined) {\n return undefined;\n }\n\n const skinWeightRaw = rawAttributes.skinWeight;\n if (skinWeightRaw instanceof Float32Array) {\n attributes.skinWeight = skinWeightRaw;\n } else if (Array.isArray(skinWeightRaw)) {\n attributes.skinWeight = new Float32Array(skinWeightRaw as number[]);\n } else if (skinWeightRaw !== undefined) {\n return undefined;\n }\n\n let vertices: Float32Array;\n let indices: Uint16Array | Uint32Array | undefined;\n\n if (vertexData instanceof Float32Array) {\n vertices = vertexData;\n } else if (Array.isArray(vertexData)) {\n vertices = new Float32Array(vertexData as number[]);\n } else {\n return undefined;\n }\n\n // bug-20260610: index width must follow vertex count, not a hard-coded\n // Uint16Array. A glTF mesh (e.g. Sponza, ~192k merged verts) overflows\n // Uint16; round-tripping through Uint16Array silently wraps and\n // `mesh-vertex-stride-mismatch` then fires because `maxIndex + 1` no\n // longer equals `vertexCount`. Mirrors `meshIrToMeshAsset` in\n // packages/gltf/src/bridge.ts which picks Uint32 above 0xffff.\n //\n // feat-20260612 M2 fixup: when the input carries an empty index array\n // (Fox.glb-style non-indexed primitives flattened through the mesh-bin\n // sidecar with `ilen=0`), drop the indices field rather than emit a\n // 0-byte typed array. The downstream `gpu-resource-store` chooses the\n // indexed-vs-vertex-only path on `mesh.indices !== undefined`; a 0-byte\n // typed array still satisfies !== undefined and triggers a 0-size IBO\n // allocation, whose `setIndexBuffer(buffer.slice(0..0), ...)` panics\n // wgpu's `BufferSlice` \"buffer slices can not be empty\" assertion.\n if (indexData instanceof Uint16Array || indexData instanceof Uint32Array) {\n indices = indexData.length > 0 ? indexData : undefined;\n } else if (Array.isArray(indexData)) {\n const arr = indexData as number[];\n if (arr.length === 0) {\n indices = undefined;\n } else {\n const vertexCount = vertices.length / PROCEDURAL_FLOATS_PER_VERTEX;\n const useUint32 = vertexCount > 0xffff;\n indices = useUint32 ? new Uint32Array(arr) : new Uint16Array(arr);\n }\n } else if (indexData === undefined) {\n indices = undefined;\n } else {\n return undefined;\n }\n\n // feat-20260608 M5 / w27: pack-payload mesh assets default to a single\n // triangle-list submesh covering the full index/vertex range. Inline\n // .pack.json mesh payloads do not carry submesh tables (single-prim\n // legacy shape); render code unconditionally reads `submeshes[0]`.\n // vertexCount stored as full vertices.length (downstream computes per-\n // attribute strides; submesh keeps the buffer-element-count for now).\n //\n // bug-20260610: when the payload carries an explicit `submeshes` table\n // (gltf importer emits one per primitive), respect it. The\n // `triangle-list 0..indices.length` default fits only single-prim packs.\n const payloadSubmeshes = payload.submeshes;\n const rawSubmeshes =\n Array.isArray(payloadSubmeshes) && payloadSubmeshes.length > 0\n ? (payloadSubmeshes as unknown as TypesMeshAsset['submeshes'])\n : [\n {\n indexOffset: 0,\n indexCount: indices?.length ?? 0,\n vertexCount: vertices.length,\n topology: 'triangle-list' as const,\n },\n ];\n const payloadSlots = payload.materialSlots;\n const materialSlots: TypesMeshAsset['materialSlots'] = Array.isArray(payloadSlots)\n ? payloadSlots.map((raw, slotIndex) => {\n if (typeof raw !== 'object' || raw === null)\n return { slotName: `LegacySlot_${slotIndex}` };\n const slot = raw as Record<string, unknown>;\n let defaultMaterial: AssetGuidType | undefined;\n if (slot.defaultMaterial instanceof Uint8Array) {\n defaultMaterial = slot.defaultMaterial as AssetGuidType;\n } else if (typeof slot.defaultMaterial === 'string') {\n const parsed = AssetGuid.parse(slot.defaultMaterial);\n if (!parsed.ok) return { slotName: `LegacySlot_${slotIndex}` };\n defaultMaterial = parsed.value;\n }\n return {\n slotName:\n typeof slot.slotName === 'string' && slot.slotName.trim().length > 0\n ? slot.slotName\n : `LegacySlot_${slotIndex}`,\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n ...(defaultMaterial !== undefined ? { defaultMaterial } : {}),\n };\n })\n : rawSubmeshes.map((_, slotIndex) => ({ slotName: `LegacySlot_${slotIndex}` }));\n const submeshes = rawSubmeshes.map((submesh, submeshIndex) => ({\n ...submesh,\n materialSlot: Number.isInteger((submesh as { materialSlot?: unknown }).materialSlot)\n ? (submesh as { materialSlot: number }).materialSlot\n : submeshIndex,\n }));\n\n return {\n kind: 'mesh',\n vertices,\n ...(indices !== undefined ? { indices } : {}),\n attributes: attributes as TypesMeshAsset['attributes'],\n ...(aabb !== undefined ? { aabb } : {}),\n ...(morphTargets !== undefined ? { morphTargets } : {}),\n ...(morphWeights !== undefined ? { morphWeights } : {}),\n submeshes,\n materialSlots,\n };\n },\n loadPack(input, ctx) {\n const artifact = input.artifacts.body;\n if (artifact === undefined) return meshLoader.load(input.payload, input.refs, ctx);\n const decoded = unpackMeshBinV4(artifact.bytes, input.guid);\n if (!decoded.ok) return { ok: false, error: decoded.error } as never;\n const materialSlots = decoded.value.materialSlots.map((slot) => {\n const refIndex = slot.defaultMaterialRef;\n const ref = refIndex === undefined ? undefined : input.refs[refIndex];\n if (refIndex !== undefined && ref === undefined) return undefined;\n if (ref === undefined) {\n return {\n slotName: String(slot.slotName),\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n };\n }\n const parsed = AssetGuid.parse(ref);\n if (!parsed.ok) return undefined;\n return {\n slotName: String(slot.slotName),\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n defaultMaterial: parsed.value,\n };\n });\n if (materialSlots.some((slot) => slot === undefined)) {\n return {\n ok: false,\n error: new MeshBinAssetError({\n sourceKey: input.guid,\n expected: 'material slot references must resolve through the pack refs table',\n actual: 'material reference is out of bounds or is not a valid AssetGuid',\n reason: 'metadata-invalid',\n actualFacts: { field: 'metadata' },\n }),\n } as never;\n }\n return meshLoader.load(\n {\n vertices: decoded.value.vertices,\n ...(decoded.value.indices !== undefined ? { indices: decoded.value.indices } : {}),\n submeshes: decoded.value.submeshes,\n materialSlots,\n ...(decoded.value.aabb !== undefined ? { aabb: decoded.value.aabb } : {}),\n ...(decoded.value.morphTargets !== undefined\n ? { morphTargets: decoded.value.morphTargets }\n : {}),\n ...(decoded.value.morphWeights !== undefined\n ? { morphWeights: decoded.value.morphWeights }\n : {}),\n attributes: decoded.value.attributes,\n },\n input.refs,\n ctx,\n );\n },\n};\n\n/** scene loader — delegates to parseScenePayload; routes structured ref error via ctx. */\nexport const sceneLoader: Loader = {\n kind: 'scene',\n load(payload, refs, _ctx: LoadContext) {\n const result = parseScenePayload(payload, refs === undefined ? undefined : [...refs]);\n if (result === undefined) return undefined;\n // Structured ParseSceneError (has an `index` field absent on SceneAsset):\n // return it inline through LoaderOutput so the caller (parseAndReturnAsset)\n // can build a precise AssetError without a shared instance slot (F21).\n if ('index' in result) {\n return { ok: false, error: result as ParseErrorDetail };\n }\n return result as Asset;\n },\n};\n\n/**\n * feat-20260613-material-paramschema-driven-binding M4 / w22 (D-5 graceful):\n * the legacy hardcoded texture-field allowlist Set has been removed\n * (AC-03). The materialLoader now consults `ctx.getMaterialShaderTextureFieldNames`\n * (paramSchema-derived via derive()) to know which values fields carry\n * refs[] indices. When the shader is not yet registered (cross-worktree\n * shader-late-register path, plan R-4), the loader falls back to attempting\n * resolution on every int-typed paramValue in [0, refs.length) — M4 / w23's\n * extract-layer paramSchema validation catches misclassifications and routes\n * unresolved texture slots through `MISSING_TEXTURE_HANDLE`.\n */\nfunction collectShaderTextureFieldNames(\n passesFromPayload: unknown,\n ctx: LoadContext,\n): ReadonlySet<string> | undefined {\n if (!Array.isArray(passesFromPayload) || passesFromPayload.length === 0) return undefined;\n const lookup = ctx.getMaterialShaderTextureFieldNames;\n if (lookup === undefined) return undefined;\n const collected = new Set<string>();\n let anyResolved = false;\n for (const pass of passesFromPayload) {\n const shaderId = (pass as { program?: { module?: unknown } }).program?.module;\n if (typeof shaderId !== 'string' || shaderId.length === 0) continue;\n const fields = lookup(shaderId);\n if (fields === undefined) continue;\n anyResolved = true;\n for (const name of fields) collected.add(name);\n }\n return anyResolved ? collected : undefined;\n}\n\nfunction refGuidAt(refs: readonly unknown[] | undefined, index: number): string | undefined {\n if (!Number.isInteger(index) || index < 0 || index >= (refs?.length ?? 0)) return undefined;\n const guid = refs?.[index];\n if (typeof guid === 'string') return guid;\n if (typeof guid === 'object' && guid !== null && 'guid' in guid) {\n const nestedGuid = (guid as { guid?: unknown }).guid;\n return typeof nestedGuid === 'string' ? nestedGuid : undefined;\n }\n return undefined;\n}\n\nfunction isIdentityTextureCoordinates(value: unknown): boolean {\n if (value === undefined) return true;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const coordinates = value as Record<string, unknown>;\n if (Object.keys(coordinates).some((key) => key !== 'set' && key !== 'transform')) return false;\n const transform = coordinates.transform;\n if (\n transform !== undefined &&\n (typeof transform !== 'object' || transform === null || Array.isArray(transform))\n ) {\n return false;\n }\n if (\n transform !== undefined &&\n Object.keys(transform as Record<string, unknown>).some(\n (key) => key !== 'offset' && key !== 'scale' && key !== 'rotation',\n )\n ) {\n return false;\n }\n const resolved = resolveMaterialTextureCoordinates(coordinates as MaterialTextureCoordinates);\n return (\n resolved.set === 0 &&\n resolved.transform.offset[0] === 0 &&\n resolved.transform.offset[1] === 0 &&\n resolved.transform.scale[0] === 1 &&\n resolved.transform.scale[1] === 1 &&\n resolved.transform.rotation === 0\n );\n}\n\nfunction compactTextureValue(value: Record<string, unknown>): unknown {\n const compact = { ...value };\n if (isIdentityTextureCoordinates(compact.coordinates)) delete compact.coordinates;\n return compact;\n}\n\n/** material loader — passes + values + serialized parent GUID -> parentGuid. */\nexport const materialLoader: Loader = {\n kind: 'material',\n load(payload, refs, ctx: LoadContext) {\n const matPayload = payload;\n const passesFromPayload = matPayload.passes;\n const rawParamValues = (matPayload.values as Record<string, unknown>) ?? {};\n\n let parentGuid: string | undefined;\n if (typeof matPayload.parent === 'string') {\n parentGuid = matPayload.parent;\n } else if (typeof matPayload.parent === 'number') {\n const idx = matPayload.parent;\n const refsArr = refs ?? [];\n if (idx >= 0 && idx < refsArr.length) {\n parentGuid = refGuidAt(refsArr, idx);\n }\n if (parentGuid === undefined) {\n return undefined;\n }\n }\n\n // bug-20260610: values fields that are typed `handle<TextureAsset>`\n // arrive on disk as a refs[] index (small int 0..refs.length-1). The\n // build-time gltfImporter writes these as refs indices, mirroring the\n // scene's HANDLE_FIELD_NAMES treatment.\n //\n // feat-20260613-material-paramschema-driven-binding M4 / w22 (D-5 graceful):\n // texture-field discovery now derives from the registered shader's\n // paramSchema via `ctx.getMaterialShaderTextureFieldNames`. When the\n // shader is registered (the common case), only declared texture fields\n // are resolved — identical to the old hardcoded-Set behaviour without the\n // SSOT duplication. Authored material parameters are an equally valid\n // schema source and remain available before shader registration; this is\n // what keeps a scalar zero (for example metallic) distinct from texture\n // ref index zero. Only legacy payloads with neither schema retain the\n // try-every-integer fallback.\n const values: Record<string, unknown> = { ...rawParamValues };\n if (refs && refs.length > 0) {\n const shaderTextureFields = collectShaderTextureFieldNames(passesFromPayload, ctx);\n const authoredTextureFields = Array.isArray(matPayload.parameters)\n ? new Set(\n matPayload.parameters\n .filter(\n (parameter): parameter is { name: string; type: string } =>\n typeof parameter === 'object' &&\n parameter !== null &&\n 'name' in parameter &&\n typeof parameter.name === 'string' &&\n 'type' in parameter &&\n parameter.type === 'texture',\n )\n .map((parameter) => parameter.name),\n )\n : undefined;\n const textureFields =\n authoredTextureFields !== undefined\n ? new Set([...(shaderTextureFields ?? []), ...authoredTextureFields])\n : shaderTextureFields;\n // Walk every value so the structured MaterialTextureValue shape remains\n // resolvable even when a shader is registered with an empty/late\n // paramSchema (pbr-skin currently takes this path). Scalar values still\n // require schema membership below, so metallic/roughness integers are\n // never mistaken for refs indices merely because the schema is empty.\n const candidateFields = Object.keys(values);\n for (const fieldName of candidateFields) {\n const value = values[fieldName];\n if (typeof value === 'number' && Number.isInteger(value)) {\n if (textureFields !== undefined && !textureFields.has(fieldName)) {\n continue;\n }\n const refGuid = refGuidAt(refs, value);\n if (refGuid === undefined) {\n // Only emit a parse-error breadcrumb when the field is declared as\n // a texture by the shader paramSchema (the OOB is unambiguous).\n // For the graceful \"try every int\" fallback, OOB simply means\n // \"this scalar was not a refs index\" — don't spam parse errors.\n if (textureFields !== undefined) delete values[fieldName];\n continue;\n }\n values[fieldName] = textureFields === undefined ? refGuid : { texture: refGuid };\n continue;\n }\n\n // glTF materials use the engine's structured MaterialTextureValue\n // shape (`{ texture: <refs index> }`), not the legacy scalar form.\n // Resolve that nested index at the same loader boundary; leaving zero\n // here is a valid-looking handle that silently renders the material\n // white and never reaches the browser console as an exception.\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const textureIndex = (value as { texture?: unknown }).texture;\n if (typeof textureIndex !== 'number' || !Number.isInteger(textureIndex)) continue;\n const textureGuid = refGuidAt(refs, textureIndex);\n if (textureGuid === undefined) {\n if (textureFields !== undefined) delete values[fieldName];\n continue;\n }\n const resolved: Record<string, unknown> = {\n ...(value as Record<string, unknown>),\n texture: textureGuid,\n };\n const samplerIndex = resolved.sampler;\n if (typeof samplerIndex === 'number' && Number.isInteger(samplerIndex)) {\n const samplerGuid = refGuidAt(refs, samplerIndex);\n if (samplerGuid === undefined) delete resolved.sampler;\n else resolved.sampler = samplerGuid;\n }\n values[fieldName] = compactTextureValue(resolved);\n }\n }\n }\n\n if (Array.isArray(passesFromPayload) && passesFromPayload.length > 0) {\n return {\n kind: 'material',\n passes: passesFromPayload as readonly MaterialPass[],\n parameters: matPayload.parameters,\n values,\n colorSpace: matPayload.colorSpace,\n parentGuid,\n } as MaterialAsset & { parentGuid?: string };\n }\n\n if (parentGuid !== undefined) {\n return {\n kind: 'material',\n parameters: matPayload.parameters,\n values,\n colorSpace: matPayload.colorSpace,\n parentGuid,\n } as unknown as MaterialAsset & { parentGuid?: string };\n }\n\n return undefined;\n },\n};\n\n/** sampler loader — preserve the serialised SamplerAsset descriptor. */\nexport const samplerLoader: Loader = {\n kind: 'sampler',\n load(payload) {\n const filters = new Set<FilterMode>(['nearest', 'linear']);\n const mipmapFilters = new Set<GPUMipmapFilterMode>(['nearest', 'linear']);\n const addressModes = new Set<AddressMode>(['clamp-to-edge', 'repeat', 'mirror-repeat']);\n const compareFunctions = new Set<CompareFunction>([\n 'never',\n 'less',\n 'equal',\n 'less-equal',\n 'greater',\n 'not-equal',\n 'greater-equal',\n 'always',\n ]);\n const stringField = <T extends string>(\n key: string,\n allowed: ReadonlySet<T>,\n ): T | undefined | null => {\n const value = payload[key];\n if (value === undefined) return undefined;\n return typeof value === 'string' && allowed.has(value as T) ? (value as T) : null;\n };\n const magFilter = stringField('magFilter', filters);\n const minFilter = stringField('minFilter', filters);\n const mipmapFilter = stringField('mipmapFilter', mipmapFilters);\n const addressModeU = stringField('addressModeU', addressModes);\n const addressModeV = stringField('addressModeV', addressModes);\n const addressModeW = stringField('addressModeW', addressModes);\n const compare = stringField('compare', compareFunctions);\n if (\n magFilter === null ||\n minFilter === null ||\n mipmapFilter === null ||\n addressModeU === null ||\n addressModeV === null ||\n addressModeW === null ||\n compare === null\n ) {\n return undefined;\n }\n const numericField = (key: string): number | undefined | null => {\n const value = payload[key];\n if (value === undefined) return undefined;\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n };\n const lodMinClamp = numericField('lodMinClamp');\n const lodMaxClamp = numericField('lodMaxClamp');\n const maxAnisotropy = numericField('maxAnisotropy');\n if (lodMinClamp === null || lodMaxClamp === null || maxAnisotropy === null) return undefined;\n return {\n kind: 'sampler',\n ...(magFilter === undefined ? {} : { magFilter }),\n ...(minFilter === undefined ? {} : { minFilter }),\n ...(mipmapFilter === undefined ? {} : { mipmapFilter }),\n ...(addressModeU === undefined ? {} : { addressModeU }),\n ...(addressModeV === undefined ? {} : { addressModeV }),\n ...(addressModeW === undefined ? {} : { addressModeW }),\n ...(lodMinClamp === undefined ? {} : { lodMinClamp }),\n ...(lodMaxClamp === undefined ? {} : { lodMaxClamp }),\n ...(compare === undefined ? {} : { compare }),\n ...(maxAnisotropy === undefined ? {} : { maxAnisotropy }),\n };\n },\n};\n\n/** skeleton loader — inverseBindMatrices stride validation.\n *\n * bug-20260611: accept both `Float32Array` (in-memory: dawn smoke / direct\n * `register` test) AND `number[]` (post-`JSON.stringify` shape: `normaliseForPack`\n * in @forgeax/engine-import flattens every typed array to a plain Array so\n * `JSON.stringify(pack)` survives the dev-server / build-mode round-trip --\n * the same dual contract `meshLoader` already honours). Without the array arm\n * the .pack.json -> fetch -> JSON.parse path lands a plain object whose\n * `instanceof Float32Array` check fails, surfacing as `asset-parse-failed`\n * for any glTF carrying a Skin (e.g. Khronos Fox.glb).\n */\nexport const skeletonLoader: Loader = {\n kind: 'skeleton',\n load(payload) {\n const ibmRaw = payload.inverseBindMatrices;\n const jointCount = typeof payload.jointCount === 'number' ? payload.jointCount : 0;\n let ibm: Float32Array;\n if (ibmRaw instanceof Float32Array) {\n ibm = ibmRaw;\n } else if (Array.isArray(ibmRaw)) {\n ibm = new Float32Array(ibmRaw as number[]);\n } else {\n return undefined;\n }\n if (ibm.byteLength !== jointCount * 64) return undefined;\n return {\n kind: 'skeleton',\n inverseBindMatrices: ibm,\n jointCount,\n };\n },\n};\n\n/** skin loader — skeletonGuid + jointPaths validation. */\nexport const skinLoader: Loader = {\n kind: 'skin',\n load(payload) {\n const skeletonGuid = payload.skeletonGuid;\n const jointPathsRaw = payload.jointPaths;\n if (typeof skeletonGuid !== 'string') return undefined;\n if (!Array.isArray(jointPathsRaw)) return undefined;\n const jointPaths: string[] = [];\n for (const item of jointPathsRaw) {\n if (typeof item !== 'string') return undefined;\n jointPaths.push(item);\n }\n return { kind: 'skin', skeletonGuid, jointPaths };\n },\n};\n\n/** animation-clip loader — channels / sampler validation.\n *\n * bug-20260611: sampler.input / sampler.output accept both `Float32Array`\n * (in-memory) and `number[]` (post-`JSON.stringify` shape produced by\n * `normaliseForPack`). Same dual contract as `skeletonLoader` /\n * `meshLoader`; without it the dev `.pack.json` round-trip surfaces every\n * skinned-with-animation glTF as `asset-parse-failed`.\n */\nexport const animationClipLoader: Loader = {\n kind: 'animation-clip',\n load(payload) {\n const duration = typeof payload.duration === 'number' ? payload.duration : 0;\n const channelsRaw = payload.channels;\n if (!Array.isArray(channelsRaw)) return undefined;\n const channels: AnimationChannel[] = [];\n for (const ch of channelsRaw) {\n if (typeof ch !== 'object' || ch === null) return undefined;\n const chObj = ch as Record<string, unknown>;\n const targetId = chObj.targetId;\n const property = chObj.property;\n const samplerObj = chObj.sampler as Record<string, unknown> | undefined;\n if (\n typeof targetId !== 'string' ||\n !/^[0-9a-f]{32}$/.test(targetId) ||\n Object.keys(chObj).some(\n (key) => key !== 'targetId' && key !== 'property' && key !== 'sampler',\n )\n ) {\n return undefined;\n }\n if (\n property !== 'translation' &&\n property !== 'rotation' &&\n property !== 'scale' &&\n property !== 'weights'\n )\n return undefined;\n if (samplerObj === undefined) return undefined;\n const inputRaw = samplerObj.input;\n const outputRaw = samplerObj.output;\n const interpolation = samplerObj.interpolation;\n let input: Float32Array;\n if (inputRaw instanceof Float32Array) {\n input = inputRaw;\n } else if (Array.isArray(inputRaw)) {\n input = new Float32Array(inputRaw as number[]);\n } else {\n return undefined;\n }\n let output: Float32Array;\n if (outputRaw instanceof Float32Array) {\n output = outputRaw;\n } else if (Array.isArray(outputRaw)) {\n output = new Float32Array(outputRaw as number[]);\n } else {\n return undefined;\n }\n if (interpolation !== 'LINEAR' && interpolation !== 'STEP') return undefined;\n channels.push({\n targetId: targetId as AnimationChannel['targetId'],\n property: property as AnimationChannel['property'],\n sampler: { input, output, interpolation },\n });\n }\n return { kind: 'animation-clip', duration, channels };\n },\n};\n\n/** animation-graph loader — pack payload -> AnimationGraph POD.\n *\n * feat-20260713-animation-state-machine-plugin M4 / w30 (plan D-4 landing (3)):\n * the inverse of `serializeAnimationGraph` (runtime). Each Clip leaf's `clip`\n * field arrives as a `refs[]` index (small int); the loader resolves it back to\n * the GUID string verbatim, leaving GUID -> handle re-resolution to the ECS/use\n * time (the same \"GUID at load, handle at use\" contract materialLoader honours\n * for parentGuid / values texture fields, asset-registry D-19). Blend/Add\n * node references + `root` are intra-graph node indices, validated against the\n * node count. A malformed payload (out-of-range refs / node index, bad node\n * shape, non-finite weight) returns `undefined` so the load-by-guid path\n * surfaces the existing `asset-parse-failed` error code (AC-14).\n *\n * OOS-7: reconstructs only an engine-authored graph's topology; no DCC-import\n * metadata is consumed.\n */\nexport const animationGraphLoader: Loader = {\n kind: 'animation-graph',\n load(payload, refs) {\n const rawNodes = payload.nodes;\n const root = payload.root;\n if (!Array.isArray(rawNodes)) return undefined;\n const nodeCount = rawNodes.length;\n const isNodeIndex = (value: unknown): value is number =>\n typeof value === 'number' && Number.isInteger(value) && value >= 0 && value < nodeCount;\n if (!isNodeIndex(root)) return undefined;\n const refsArr = refs ?? [];\n\n const nodes: AnimationGraphNode[] = [];\n for (const rawNode of rawNodes) {\n if (typeof rawNode !== 'object' || rawNode === null) return undefined;\n const node = rawNode as Record<string, unknown>;\n const weight = node.weight;\n if (typeof weight !== 'number' || !Number.isFinite(weight)) return undefined;\n\n if (node.type === 'clip') {\n const refIndex = node.clip;\n if (typeof refIndex !== 'number' || !Number.isInteger(refIndex)) return undefined;\n if (refIndex < 0 || refIndex >= refsArr.length) return undefined;\n const guid = refsArr[refIndex];\n if (typeof guid !== 'string') return undefined;\n // GUID verbatim at load; re-resolved to a handle at use time (D-19).\n nodes.push({\n type: 'clip',\n clip: guid,\n weight,\n });\n } else if (node.type === 'blend') {\n const children = node.children;\n if (!Array.isArray(children) || !children.every(isNodeIndex)) return undefined;\n nodes.push({ type: 'blend', children: [...(children as number[])], weight });\n } else if (node.type === 'add') {\n const base = node.base;\n const additive = node.additive;\n if (!isNodeIndex(base)) return undefined;\n if (!Array.isArray(additive) || !additive.every(isNodeIndex)) return undefined;\n nodes.push({ type: 'add', base, additive: [...(additive as number[])], weight });\n } else {\n return undefined;\n }\n }\n\n return { kind: 'animation-graph', nodes, root } as AnimationGraph;\n },\n};\n\n/** audio loader -- restore the durable descriptor; host decode stays elsewhere. */\nexport const audioLoader: Loader = {\n kind: 'audio',\n load(payload) {\n const sourceKey = payload.sourceKey;\n const mediaType = payload.mediaType;\n if (typeof sourceKey !== 'string' || sourceKey.length === 0) return undefined;\n if (typeof mediaType !== 'string' || mediaType.length === 0) return undefined;\n const rawBytes = payload.bytes;\n const bytes =\n rawBytes instanceof Uint8Array\n ? rawBytes\n : Array.isArray(rawBytes)\n ? new Uint8Array(rawBytes as number[])\n : undefined;\n return {\n kind: 'audio',\n sourceKey,\n mediaType,\n ...(bytes === undefined ? {} : { bytes }),\n } as AudioClipAsset;\n },\n};\n\n/** particle loader -- restore the complete cooked program without a GPU device. */\nexport const particleEffectLoader: Loader = {\n kind: 'particle-effect',\n load(payload) {\n if (typeof payload.program !== 'object' || payload.program === null) return undefined;\n if (typeof (payload.program as Record<string, unknown>).fingerprint !== 'string') {\n return undefined;\n }\n return { ...payload, kind: 'particle-effect' } as ParticleEffectAsset;\n },\n};\n\nexport { renderPipelineLoader, tilesetLoader } from './pack-artifact';\n\n/**\n * The eight inline pack-payload loaders, in the historical `if`-chain order\n * (the animation-graph loader, feat-20260713 M4 / w30, appends after the clip\n * loader). `wireDefaultLoaders` (w5) registers these plus the texture / font /\n * equirect loaders (w6) and the audio placeholder (w8).\n */\nexport const INLINE_PACK_LOADERS: readonly Loader[] = [\n meshLoader,\n sceneLoader,\n samplerLoader,\n materialLoader,\n skeletonLoader,\n skinLoader,\n animationClipLoader,\n animationGraphLoader,\n renderPipelineLoader,\n tilesetLoader,\n audioLoader,\n particleEffectLoader,\n];\n","// @forgeax/engine-assets-runtime - wireDefaultLoaders + seed-table SSOT\n// (feat-20260603-asset-import-loader-injection M1 / w5 + w8; restructured by\n// feat-20260705-runtime-tier2-decomposition M1 / w8, D-2).\n//\n// wireDefaultLoaders is a one-line host helper that wires the engine's default\n// loader set onto a `LoaderRegistry`, mirroring the Console\n// `wireDefaultInspectors` shape (packages/console/src/wire-default-inspectors.ts;\n// research Finding 8). An AI user that has wired inspectors once recognises the\n// same form here at near-zero cost (requirements §AI User Affordances).\n//\n// The two seed tables INLINE_PACK_LOADERS + PACK_ARTIFACT_LOADERS are the\n// default set. videoLoader lives in graphics-extras and is wired here. The\n// complete ordinary Asset vocabulary is registered once at this boundary;\n// host-specific loaders may extend the table through `extraLoaders`.\n//\n// Default set wired internally: the 16 ordinary Asset kinds plus the existing\n// UI consumer loader. Host-only execution remains separate from descriptor load.\n//\nimport { videoLoader } from '@forgeax/engine-graphics-extras';\nimport type { Loader } from '@forgeax/engine-types';\nimport { createUiLoader, type UiAsset } from '@forgeax/engine-ui';\nimport { LoaderRegistry } from './loader-registry';\nimport { INLINE_PACK_LOADERS } from './loaders/inline-pack';\nimport { PACK_ARTIFACT_LOADERS } from './loaders/pack-artifact';\n\nconst uiPayloadLoader = createUiLoader();\nconst uiLoader: Loader<UiAsset> = {\n kind: 'ui',\n load: (payload) => {\n const result = uiPayloadLoader.load(payload);\n return result.ok ? result.value : undefined;\n },\n};\n\n/**\n * Wire the engine's default loader set (16 ordinary kinds plus UI) plus any\n * `extraLoaders` onto `registry` in\n * one call. Returns the same `registry` for chaining (so `wireDefaultLoaders(new\n * LoaderRegistry())` is a one-expression wired registry). The `extraLoaders` are\n * appended after the defaults and must use kinds outside the ordinary set.\n *\n * @example\n * ```ts\n * import { LoaderRegistry, wireDefaultLoaders } from '@forgeax/engine-assets-runtime';\n * const loaders = wireDefaultLoaders(new LoaderRegistry());\n * // loaders.get('mesh') / .get('texture') / .get('font') / .get('video') are\n * // non-undefined; all ordinary Asset kinds share this same owner table.\n * ```\n */\nexport function wireDefaultLoaders(\n registry: LoaderRegistry,\n extraLoaders: readonly Loader[] = [],\n): LoaderRegistry {\n const extraKinds = new Set(extraLoaders.map((loader) => loader.kind));\n const seeded = new Set<string>();\n for (const loader of [...INLINE_PACK_LOADERS, ...PACK_ARTIFACT_LOADERS]) {\n if (extraKinds.has(loader.kind)) continue;\n if (seeded.has(loader.kind)) continue;\n seeded.add(loader.kind);\n registry.register(loader);\n }\n registry.register(videoLoader);\n registry.register(uiLoader);\n for (const loader of extraLoaders) registry.register(loader);\n return registry;\n}\n\n/**\n * Convenience factory: a fresh `LoaderRegistry` pre-wired with the default\n * loader set (plus any `extraLoaders`). The production assembly point\n * (`createRenderer`) and tests pass the result into `new LoaderRegistry()` (D-7\n * constructor-injection; loaders always wired at construction -- used by\n * `AssetRegistry` internally via `createDefaultLoaderRegistry(extraLoaders)` and\n * by host code / tests independently) -- no setter / no illegal intermediate\n * state).\n */\nexport function createDefaultLoaderRegistry(extraLoaders: readonly Loader[] = []): LoaderRegistry {\n return wireDefaultLoaders(new LoaderRegistry(), extraLoaders);\n}\n","// @forgeax/engine-assets-runtime — mesh AABB computation (feat-20260705-runtime-tier2-\n// decomposition M1 / w4, D-4 F1 straight-cut). Pure move from asset-registry.ts;\n// zero identifier changes. computeAABB / emptyBox / withMeshAabb travel with the\n// asset cluster into @forgeax/engine-assets-runtime (w13).\n\nimport type { MeshAsset as TypesMeshAsset } from '@forgeax/engine-types';\n\n/**\n * Compute the local-space AABB of a mesh from its position attribute.\n *\n * Reads every third float from the position buffer as (x, y, z) and computes\n * [minX, minY, minZ, maxX, maxY, maxZ]. When position is absent, empty, or\n * less than 3 floats, returns an inverted-infinity empty box ([+Inf,+Inf,+Inf,\n * -Inf,-Inf,-Inf]) — consumers interpret this as \"always-visible\" (no culling).\n *\n * The position attribute can be Float32Array, ArrayBuffer (re-wrapped as\n * Float32Array), or Uint16Array (unlikely for position data; treated as\n * absent). Empty vertices (0 x 12 = 0) also produce empty box.\n *\n * Anchors: plan-strategy D-7 (register-time computation); D-1 (Float32Array\n * bare type); requirements AC-02 (empty -> inverted-infinity).\n */\nfunction computeAABB(asset: TypesMeshAsset): Float32Array {\n const pos = asset.attributes.position;\n // Convert to Float32Array if possible; bail to empty-box otherwise.\n let floatPos: Float32Array;\n if (pos instanceof Float32Array) {\n floatPos = pos;\n } else if (pos instanceof ArrayBuffer) {\n floatPos = new Float32Array(pos);\n } else {\n return emptyBox();\n }\n if (floatPos.length < 3) return emptyBox();\n\n let minX = floatPos[0] ?? 0;\n let minY = floatPos[1] ?? 0;\n let minZ = floatPos[2] ?? 0;\n let maxX = minX;\n let maxY = minY;\n let maxZ = minZ;\n for (let i = 3; i < floatPos.length; i += 3) {\n const x = floatPos[i] ?? 0;\n const y = floatPos[i + 1] ?? 0;\n const z = floatPos[i + 2] ?? 0;\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (z < minZ) minZ = z;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n if (z > maxZ) maxZ = z;\n }\n return Float32Array.of(minX, minY, minZ, maxX, maxY, maxZ);\n}\n\nfunction emptyBox(): Float32Array {\n return Float32Array.of(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity);\n}\n\nfunction hasPositionData(position: unknown): boolean {\n if (position instanceof Float32Array) return position.length >= 3;\n return (\n position instanceof ArrayBuffer && position.byteLength >= 3 * Float32Array.BYTES_PER_ELEMENT\n );\n}\n\nfunction isFiniteAabb(aabb: unknown): aabb is Float32Array {\n if (!(aabb instanceof Float32Array) || aabb.length !== 6) return false;\n for (const value of aabb) {\n if (!Number.isFinite(value)) return false;\n }\n const minX = aabb[0];\n const minY = aabb[1];\n const minZ = aabb[2];\n const maxX = aabb[3];\n const maxY = aabb[4];\n const maxZ = aabb[5];\n return (\n minX !== undefined &&\n minY !== undefined &&\n minZ !== undefined &&\n maxX !== undefined &&\n maxY !== undefined &&\n maxZ !== undefined &&\n minX <= maxX &&\n minY <= maxY &&\n minZ <= maxZ\n );\n}\n\n// Assigns the computed AABB to the mesh in place when the object is\n// extensible; falls back to a shallow copy when frozen / sealed (e.g.\n// BUILTIN_CUBE / BUILTIN_TRIANGLE / BUILTIN_QUAD reused via registerWithGuid).\nexport function withMeshAabb(asset: TypesMeshAsset): TypesMeshAsset {\n // Packed mesh binaries intentionally omit `attributes.position`; their\n // producer-computed AABB is the only available culling fact. Preserve it\n // instead of replacing it with the empty-box result from computeAABB().\n if (!hasPositionData(asset.attributes.position) && isFiniteAabb(asset.aabb)) {\n return asset;\n }\n const aabb = computeAABB(asset);\n if (Object.isExtensible(asset)) {\n (asset as { aabb: Float32Array }).aabb = aabb;\n return asset;\n }\n return { ...asset, aabb };\n}\n","import type { ShaderRegistry } from '@forgeax/engine-shader';\nimport type { MaterialParameter, ParamSchemaEntry } from '@forgeax/engine-types';\nimport type { MaterialReady } from './loader';\n\nconst ENGINE_INJECTED_TEXTURE_FIELDS = new Set(['emissiveTexture', 'occlusionTexture']);\n\nfunction isStandardPbrMaterialShader(shaderId: string): boolean {\n return (\n shaderId === 'forgeax::default-standard-pbr' ||\n shaderId === 'forgeax::pbr-skin' ||\n shaderId === 'forgeax::default-standard-pbr-skin'\n );\n}\n\n/** Project authored MaterialAsset parameters into the runtime shader schema. */\nexport function materialParametersToParamSchema(\n parameters: readonly MaterialParameter[],\n shaderId: string | undefined,\n): readonly ParamSchemaEntry[] {\n const engineInjectedTextureFields =\n shaderId !== undefined && isStandardPbrMaterialShader(shaderId)\n ? ENGINE_INJECTED_TEXTURE_FIELDS\n : undefined;\n return parameters.flatMap((parameter): ParamSchemaEntry[] => {\n if (parameter.type === 'bool') return [];\n if (parameter.type === 'texture') {\n if (engineInjectedTextureFields?.has(parameter.name) === true) return [];\n return [{ name: parameter.name, type: 'texture2d' }];\n }\n const defaultValue = parameter.default;\n const numericDefault =\n typeof defaultValue === 'number' ||\n (Array.isArray(defaultValue) && defaultValue.every((item) => typeof item === 'number'))\n ? { default: defaultValue }\n : {};\n return [\n {\n name: parameter.name,\n type: parameter.type,\n ...(parameter.colorSpace === undefined ? {} : { colorSpace: parameter.colorSpace }),\n ...numericDefault,\n },\n ];\n });\n}\n\n/** Project authored pass module ids onto the renderer's canonical ids. */\nexport function runtimeMaterialShaderId(\n module: string | undefined,\n passName?: string,\n): string | undefined {\n if (\n passName === 'shadow-caster' &&\n (module === 'forgeax_material::standard' ||\n module === 'forgeax_material::unlit' ||\n module === 'forgeax::default-standard-pbr' ||\n module === 'forgeax::default-unlit')\n ) {\n return 'forgeax::default-shadow-caster';\n }\n switch (module) {\n case 'forgeax_material::standard':\n return 'forgeax::default-standard-pbr';\n case 'forgeax_material::unlit':\n return 'forgeax::default-unlit';\n case 'forgeax_material::sprite':\n return 'forgeax::sprite';\n case 'forgeax_material::sprite-lit':\n return 'forgeax::sprite-lit';\n default:\n return module;\n }\n}\n\nfunction sameSchema(\n left: readonly ParamSchemaEntry[],\n right: readonly ParamSchemaEntry[],\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction isManifestVariantSource(\n shaderRegistry: ShaderRegistry,\n identifier: string,\n source: string,\n): boolean {\n const entry = Array.from(shaderRegistry.materialShaderManifestEntries()).find(\n (candidate) => candidate.identifier === identifier,\n );\n return (\n entry?.composedWgsl === source ||\n entry?.variants.some((variant) => variant.composedWgsl === source) === true\n );\n}\n\n/**\n * Install every authored pass module from one validated MaterialReady tuple.\n * The publication artifact is the only runtime shader source; no host entry\n * point is allowed to assemble or register the material separately.\n */\nexport function installMaterialReadyShaders(\n shaderRegistry: ShaderRegistry,\n readiness: MaterialReady,\n): void {\n const source = new TextDecoder().decode(readiness.artifact.bytes);\n if (source.length === 0) {\n throw new Error(\n `MaterialReady ${readiness.guid} published an empty ${readiness.artifact.mediaType} shader artifact`,\n );\n }\n for (const pass of readiness.record.resolved.passes) {\n const identifier = runtimeMaterialShaderId(pass.program.module, pass.name);\n if (identifier === undefined) continue;\n const paramSchema = materialParametersToParamSchema(\n readiness.parameterContract.parameters,\n identifier,\n );\n const existing = shaderRegistry.findMaterialArtifact(identifier);\n if (existing.ok) {\n if (\n !sameSchema(existing.value.paramSchema, paramSchema) ||\n (existing.value.source !== source &&\n !isManifestVariantSource(shaderRegistry, identifier, source))\n ) {\n throw new Error(\n `MaterialReady ${readiness.guid} conflicts with the registered shader '${identifier}'`,\n );\n }\n continue;\n }\n shaderRegistry.installMaterialArtifact(identifier, { source, paramSchema });\n }\n}\n","// @forgeax/engine-assets-runtime -- register-time payload validation\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport { PROCEDURAL_FLOATS_PER_VERTEX } from '@forgeax/engine-geometry';\nimport type {\n Asset,\n AssetErrorDetail,\n TilesetAsset,\n MeshAsset as TypesMeshAsset,\n} from '@forgeax/engine-types';\nimport { ASSET_ERROR_HINTS, AssetError, countExtraUvSets } from '@forgeax/engine-types';\n\n/**\n * Register-stage fail-fast for `kind: 'mesh'` payloads whose vertices buffer\n * is not the canonical 12-floats-per-vertex layout.\n *\n * Validation spec (plan-strategy D-3):\n * (a) asset.kind !== 'mesh' -> return null immediately\n * (b) vertices.length === 0 && indices.length === 0 -> return null (empty mesh legal)\n * (c) vertices.length % PROCEDURAL_FLOATS_PER_VERTEX !== 0 -> `AssetError` with\n * code='mesh-vertex-stride-mismatch', detail = { vertexCount: 0,\n * floatsPerVertex: vertices.length / PROCEDURAL_FLOATS_PER_VERTEX } (non-integer)\n * (d) otherwise compute vertexCount = vertices.length / PROCEDURAL_FLOATS_PER_VERTEX;\n * scan indices for maxIndex;\n * if maxIndex + 1 !== vertexCount -> same AssetError shape with\n * detail = { vertexCount: maxIndex + 1, floatsPerVertex: vertices.length / (maxIndex + 1) }\n *\n * Isomorphic with `validateMaterialPayload` — both are private module-level helpers,\n * both return `AssetError | null`, and both are called from `register()` at entry.\n *\n * Anchors: charter P3 (structured failure); plan-strategy D-2 (gate at register stage);\n * plan-strategy D-3 (three-branch validation: empty / non-divisible-12 / maxIndex mismatch);\n * plan-strategy D-5 (physical location co-located with validateMaterialPayload).\n */\nexport function validateMeshPayload(asset: Asset): AssetError | null {\n if (asset.kind !== 'mesh') return null;\n\n // feat-20260604-mesh-topology-debug-draw M5 / w13: semantic topology gate\n // (plan-strategy D-A2).\n //\n // feat-20260608 M2 / w9: topology is now per-submesh (MeshAsset.submeshes[]).\n // All topology + submesh-empty + index-OOB validation runs here.\n const submeshes = (asset as TypesMeshAsset).submeshes;\n if (submeshes.length === 0) {\n // TypesMeshAsset POD does not carry an inline GUID; the registry assigns\n // one on register, but at validation time we only have the payload. Emit\n // a stable sentinel so the closed AssetErrorDetail union still narrows.\n const guid = '<no-guid>';\n return new AssetError({\n code: 'mesh-asset-submeshes-empty',\n expected: 'submeshes array has at least one Submesh entry',\n hint: ASSET_ERROR_HINTS['mesh-asset-submeshes-empty'],\n detail: { meshAssetGuid: guid },\n });\n }\n\n const materialSlots = (asset as TypesMeshAsset).materialSlots;\n if (!Array.isArray(materialSlots) || materialSlots.length === 0) {\n return new AssetError({\n code: 'mesh-asset-material-slot-index-out-of-range',\n expected: 'a non-empty materialSlots table for a mesh with submeshes',\n hint: ASSET_ERROR_HINTS['mesh-asset-material-slot-index-out-of-range'],\n detail: {\n meshAssetGuid: '<no-guid>',\n submeshIndex: 0,\n materialSlot: -1,\n materialSlotCount: 0,\n },\n });\n }\n const slotNames = new Set<string>();\n const sourceKeys = new Set<string>();\n for (let slotIndex = 0; slotIndex < materialSlots.length; slotIndex++) {\n const slot = materialSlots[slotIndex];\n const slotName = slot?.slotName.trim() ?? '';\n const sourceKey = slot?.sourceKey?.trim();\n if (slotName.length === 0 || slotNames.has(slotName)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `materialSlots[${slotIndex}].slotName is non-empty and unique`,\n hint: 'give every Mesh material slot a stable unique slotName',\n detail: {\n field: `materialSlots[${slotIndex}].slotName`,\n value: slotName,\n reason: 'empty-or-duplicate',\n },\n });\n }\n slotNames.add(slotName);\n if (sourceKey !== undefined && sourceKey.length > 0) {\n if (sourceKeys.has(sourceKey)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `materialSlots[${slotIndex}].sourceKey is unique when present`,\n hint: 'derive a stable unique source identity for every imported Mesh material slot',\n detail: {\n field: `materialSlots[${slotIndex}].sourceKey`,\n value: sourceKey,\n reason: 'duplicate',\n },\n });\n }\n sourceKeys.add(sourceKey);\n }\n }\n\n const hasIndices = (asset.indices?.length ?? 0) > 0;\n const indexBufferLength = asset.indices?.length ?? 0;\n for (let i = 0; i < submeshes.length; i++) {\n const sm = submeshes[i];\n if (sm === undefined) continue;\n const topology = sm.topology;\n if (\n !Number.isInteger(sm.materialSlot) ||\n sm.materialSlot < 0 ||\n sm.materialSlot >= materialSlots.length\n ) {\n return new AssetError({\n code: 'mesh-asset-material-slot-index-out-of-range',\n expected: `submesh[${i}].materialSlot in [0, ${materialSlots.length})`,\n hint: ASSET_ERROR_HINTS['mesh-asset-material-slot-index-out-of-range'],\n detail: {\n meshAssetGuid: '<no-guid>',\n submeshIndex: i,\n materialSlot: sm.materialSlot,\n materialSlotCount: materialSlots.length,\n },\n });\n }\n if ((topology === 'line-strip' || topology === 'triangle-strip') && !hasIndices) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `submesh[${i}] strip topology carries an index buffer`,\n hint: 'line-strip / triangle-strip meshes must provide indices; add MeshAsset.indices or use line-list / triangle-list',\n detail: {\n field: `submeshes[${i}].topology`,\n value: topology,\n reason: 'strip-topology-without-indices',\n },\n });\n }\n if (asset.vertices.length === 0 && topology !== 'triangle-list') {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `submesh[${i}]: empty geometry uses 'triangle-list'`,\n hint: 'a zero-vertex mesh has nothing to draw; change submesh topology to triangle-list or provide vertices',\n detail: {\n field: `submeshes[${i}].topology`,\n value: topology,\n reason: 'empty-geometry-non-default-topology',\n },\n });\n }\n // feat-20260608 M2 / w9: index-range-out-of-bounds per submesh\n if (sm.indexOffset + sm.indexCount > indexBufferLength) {\n // TypesMeshAsset POD does not carry an inline GUID; the registry assigns\n // one on register, but at validation time we only have the payload. Emit\n // a stable sentinel so the closed AssetErrorDetail union still narrows.\n const guid = '<no-guid>';\n return new AssetError({\n code: 'mesh-submesh-index-range-out-of-bounds',\n expected: `submesh[${i}].indexOffset + indexCount <= index buffer length (${indexBufferLength})`,\n hint: ASSET_ERROR_HINTS['mesh-submesh-index-range-out-of-bounds'],\n detail: {\n submeshIndex: i,\n indexOffset: sm.indexOffset,\n indexCount: sm.indexCount,\n indexBufferLength,\n meshAssetGuid: guid,\n },\n });\n }\n }\n\n // indices is optional (vertex-only meshes omit it); read defensively. The\n // stride invariant below stays null-safe for vertex-only meshes (D-A4).\n if (asset.vertices.length === 0 && (asset.indices?.length ?? 0) === 0) return null;\n\n // Skin-aware stride: when MeshAsset.attributes carries skinIndex + skinWeight,\n // the bridge promotes the interleaved buffer to 18 floats/vertex (12 base +\n // 4 uint16x4 packed via aliased Uint16 view at slots 12-13 + 4 float weights\n // at slots 14-17).\n // feat-20260629 multi-uv: extra UV sets (uv1..uv7) add 2 floats each to the\n // interleaved stride, pushed after skin data (canonical order).\n const attrs = (asset as TypesMeshAsset).attributes;\n const isSkinned =\n attrs !== undefined && attrs.skinIndex !== undefined && attrs.skinWeight !== undefined;\n const extraUvSets = countExtraUvSets(attrs);\n const baseFloatsPerVertex = isSkinned ? 18 : PROCEDURAL_FLOATS_PER_VERTEX;\n const floatsPerVertex = baseFloatsPerVertex + extraUvSets * 2;\n\n if (asset.vertices.length % floatsPerVertex !== 0) {\n return new AssetError({\n code: 'mesh-vertex-stride-mismatch',\n expected: isSkinned\n ? '18 floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4 + skinIndex u16x4 + skinWeight vec4)'\n : `${PROCEDURAL_FLOATS_PER_VERTEX} floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4)`,\n hint: ASSET_ERROR_HINTS['mesh-vertex-stride-mismatch'],\n detail: {\n vertexCount: 0,\n floatsPerVertex: asset.vertices.length / floatsPerVertex,\n },\n });\n }\n\n const vertexCount = asset.vertices.length / floatsPerVertex;\n // Vertex-only meshes (no indices) skip the maxIndex-vs-vertexCount invariant:\n // there is no index buffer to bound-check against the vertex array (D-A4).\n const indices = asset.indices;\n if (indices === undefined || indices.length === 0) return null;\n let maxIndex = 0;\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n if (idx !== undefined && idx > maxIndex) maxIndex = idx;\n }\n\n if (maxIndex + 1 !== vertexCount) {\n return new AssetError({\n code: 'mesh-vertex-stride-mismatch',\n expected: isSkinned\n ? '18 floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4 + skinIndex u16x4 + skinWeight vec4)'\n : `${PROCEDURAL_FLOATS_PER_VERTEX} floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4)`,\n hint: ASSET_ERROR_HINTS['mesh-vertex-stride-mismatch'],\n detail: {\n vertexCount: maxIndex + 1,\n floatsPerVertex: vertexCount > 0 ? asset.vertices.length / (maxIndex + 1) : 0,\n },\n });\n }\n\n return null;\n}\n\n// === Tileset / Tilemap / TileLayer validators (feat-20260608 M0 baseline rebuild) ===\n//\n// R-6 first-error path (plan-strategy §R-6 ordering, M1 extended):\n// (1) `atlases.length >= 1` -> 'tileset-tile-entry-malformed'\n// .field='atlases' .scope='tileset-asset' (M1)\n// (2) region rectangle stays in atlas -> 'tileset-region-index-out-of-range' (M0)\n// (3) `region.atlasIndex` in atlases range -> 'tileset-tile-entry-malformed'\n// .field='atlasIndex' .scope='tileset-asset' (M1)\n// (4) `tiles[i].regionIndex` in regions -> 'tileset-region-index-out-of-range' (M0)\n// (5) tile entry widthCells / heightCells -> 'tileset-tile-entry-malformed'\n// / pivotX / pivotY / collider .field=<field> .scope='tile-entry'\n// .tileEntryIndex=i (M1)\n//\n// Tilemap / TileLayer register-time invariants use `AssetError\n// 'asset-invalid-value'` with `.detail = { field, value, reason }` so the\n// closed AssetErrorDetail discriminated union narrows uniformly (charter\n// P4 consistent abstraction with `validateMeshPayload`).\n\n/**\n * Optional atlas extent for `validateTilesetPayload`. When omitted, the\n * region-rectangle bounds-check is skipped — only the\n * `tiles[].regionIndex` in `[0, regions.length)` invariant runs.\n */\nexport interface TilesetValidateOptions {\n readonly atlasWidth?: number;\n readonly atlasHeight?: number;\n}\n\n/**\n * Construct an `AssetError` for the M1 `tileset-tile-entry-malformed`\n * code with structured `.detail` (closed 7-variant `.field` enum +\n * 2-variant `.scope` + optional `.tileEntryIndex`). The helper centralises\n * the boilerplate so each call site stays a one-liner (charter F1 single\n * affordance) and the `.detail` shape stays SSOT-aligned with\n * `AssetTilesetTileEntryMalformedDetail`.\n */\nfunction tileEntryMalformed(args: {\n tilesetGuid: string;\n field: 'widthCells' | 'heightCells' | 'pivotX' | 'pivotY' | 'collider' | 'atlases' | 'atlasIndex';\n scope: 'tileset-asset' | 'tile-entry';\n tileEntryIndex?: number;\n expected: string;\n}): AssetError {\n const detail: AssetErrorDetail = {\n code: 'tileset-tile-entry-malformed',\n field: args.field,\n scope: args.scope,\n tilesetGuid: args.tilesetGuid,\n ...(args.tileEntryIndex !== undefined ? { tileEntryIndex: args.tileEntryIndex } : {}),\n expected: args.expected,\n hint: ASSET_ERROR_HINTS['tileset-tile-entry-malformed'],\n };\n return new AssetError({\n code: 'tileset-tile-entry-malformed',\n expected: args.expected,\n hint: ASSET_ERROR_HINTS['tileset-tile-entry-malformed'],\n detail,\n });\n}\n\n/**\n * Validate the shape of a `TilesetTileCollider` value (R-6 step 5d).\n * Returns `null` when the collider is well-formed, otherwise an\n * `AssetError` with code `'tileset-tile-entry-malformed'` and\n * `.detail.field = 'collider'` (charter P3 closed schema).\n *\n * Rules per variant:\n * - `'none'` -- always accepted.\n * - `'rect'` -- `rect.length === 4`; each component in `[0, 1]`;\n * `w > 0`, `h > 0`; `x + w <= 1`, `y + h <= 1`.\n * - `'polygon'` -- `points.length >= 3`; each point's `x` and `y` in\n * `[0, 1]`.\n * - any other `type` discriminator surfaces the same `.field='collider'`\n * fail-fast (unreachable through the typed surface but defends\n * against unchecked JSON loaders, charter P4 fail-fast in depth).\n */\nfunction validateColliderShape(\n collider: NonNullable<TilesetTileEntryColliderField>,\n tilesetGuid: string,\n tileEntryIndex: number,\n): AssetError | null {\n if (collider.type === 'none') return null;\n if (collider.type === 'rect') {\n const rect = collider.rect;\n if (!Array.isArray(rect) || rect.length !== 4) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.rect length === 4`,\n });\n }\n const [rx, ry, rw, rh] = rect;\n const valid =\n typeof rx === 'number' &&\n typeof ry === 'number' &&\n typeof rw === 'number' &&\n typeof rh === 'number' &&\n rx >= 0 &&\n ry >= 0 &&\n rw > 0 &&\n rh > 0 &&\n rx + rw <= 1 &&\n ry + rh <= 1;\n if (!valid) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.rect in [0, 1]^2 with w > 0, h > 0, x + w <= 1, y + h <= 1`,\n });\n }\n return null;\n }\n if (collider.type === 'polygon') {\n const points = collider.points;\n if (!Array.isArray(points) || points.length < 3) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.points length >= 3`,\n });\n }\n for (let j = 0; j < points.length; j++) {\n const p = points[j];\n if (\n !Array.isArray(p) ||\n p.length !== 2 ||\n typeof p[0] !== 'number' ||\n typeof p[1] !== 'number' ||\n p[0] < 0 ||\n p[0] > 1 ||\n p[1] < 0 ||\n p[1] > 1\n ) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.points[${j}] in [0, 1]^2`,\n });\n }\n }\n return null;\n }\n // Unknown discriminator (only reachable via unchecked JSON loaders bypassing\n // the typed surface). Closed enum -> fail-fast (charter P3).\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.type in {'none', 'rect', 'polygon'}`,\n });\n}\n\n/**\n * Internal alias for the optional `collider` field on `TilesetTileEntry`.\n * Localised to keep the validator helper signature math-free.\n */\ntype TilesetTileEntryColliderField = TilesetAsset['tiles'][number]['collider'];\n\n/**\n * Validate a `TilesetAsset` payload at register time (M0 baseline rebuild\n * + M1 schema extension). Returns `null` on success or an `AssetError`\n * carrying the first-error details (charter P3 fail-fast). R-6 ordering:\n *\n * 1. `atlases.length >= 1` -- 'tileset-tile-entry-malformed' .field='atlases'.\n * 2. Region rectangle escapes atlas extent (when extent is supplied) --\n * M0 code 'tileset-region-index-out-of-range'.\n * 3. `regions[i].atlasIndex` in `[0, atlases.length)` -- 'tileset-tile-entry-malformed'\n * .field='atlasIndex'.\n * 4. `tiles[i].regionIndex` in `[0, regions.length)` -- M0 code.\n * 5. Per-tile-entry boundaries -- 'tileset-tile-entry-malformed'\n * .field=widthCells | heightCells | pivotX | pivotY | collider,\n * in that order, .scope='tile-entry' .tileEntryIndex=i.\n */\nexport function validateTilesetPayload(\n asset: TilesetAsset,\n opts: TilesetValidateOptions = {},\n): AssetError | null {\n const assetGuid = '<no-guid>';\n // (1) atlases empty fail-fast (M1 R-6 top-level invariant).\n if (asset.atlases.length < 1) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'atlases',\n scope: 'tileset-asset',\n expected: 'atlases.length >= 1',\n });\n }\n\n const regionCount = asset.regions.length;\n const atlasesLength = asset.atlases.length;\n // (2) region rectangle bounds-check. Negative coords / non-positive size are\n // rejected regardless of whether an atlas extent is supplied; the optional\n // atlasWidth / atlasHeight tightens the upper bound when present.\n const atlasWidth = opts.atlasWidth;\n const atlasHeight = opts.atlasHeight;\n for (let i = 0; i < regionCount; i++) {\n const region = asset.regions[i];\n if (region === undefined) continue;\n const negativeOrZero = region.x < 0 || region.y < 0 || region.width <= 0 || region.height <= 0;\n const exceedsAtlas =\n typeof atlasWidth === 'number' &&\n typeof atlasHeight === 'number' &&\n (region.x + region.width > atlasWidth || region.y + region.height > atlasHeight);\n if (negativeOrZero || exceedsAtlas) {\n return new AssetError({\n code: 'tileset-region-index-out-of-range',\n expected: `regions[${i}] rectangle (x/y >= 0, width/height > 0${\n typeof atlasWidth === 'number' && typeof atlasHeight === 'number'\n ? `, x + width <= ${atlasWidth}, y + height <= ${atlasHeight}`\n : ''\n })`,\n hint: ASSET_ERROR_HINTS['tileset-region-index-out-of-range'],\n detail: {\n code: 'tileset-region-index-out-of-range',\n tilesetGuid: assetGuid,\n tileId: 0,\n regionIndex: i,\n regionCount,\n },\n });\n }\n // (3) per-region atlasIndex bounds-check (M1; optional field defaults 0).\n if (region.atlasIndex !== undefined) {\n const ai = region.atlasIndex;\n if (!Number.isInteger(ai) || ai < 0 || ai >= atlasesLength) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'atlasIndex',\n scope: 'tileset-asset',\n expected: `regions[${i}].atlasIndex in [0, ${atlasesLength})`,\n });\n }\n }\n }\n // (4) tile entry regionIndex in [0, regions.length) (M0 code).\n for (let i = 0; i < asset.tiles.length; i++) {\n const entry = asset.tiles[i];\n if (entry === undefined) continue;\n const ri = entry.regionIndex;\n if (!Number.isInteger(ri) || ri < 0 || ri >= regionCount) {\n return new AssetError({\n code: 'tileset-region-index-out-of-range',\n expected: `tiles[${i}].regionIndex in [0, ${regionCount})`,\n hint: ASSET_ERROR_HINTS['tileset-region-index-out-of-range'],\n detail: {\n code: 'tileset-region-index-out-of-range',\n tilesetGuid: assetGuid,\n tileId: i + 1,\n regionIndex: ri,\n regionCount,\n },\n });\n }\n }\n // (5) per-tile-entry M1 boundaries -- widthCells > heightCells > pivotX >\n // pivotY > collider, per plan-strategy §R-6 first-error order. Each loop\n // iteration runs the full sub-order on entry i before advancing to i+1 so\n // the deterministic global order is (i=0 widthCells, i=0 heightCells, ...,\n // i=0 collider, i=1 widthCells, ...). Tests in tileset-asset-validate.test.ts\n // R-6 block exercise the sub-order on a single entry.\n for (let i = 0; i < asset.tiles.length; i++) {\n const entry = asset.tiles[i];\n if (entry === undefined) continue;\n if (entry.widthCells !== undefined) {\n const w = entry.widthCells;\n if (!Number.isFinite(w) || w <= 0 || w > 64) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'widthCells',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].widthCells in (0, 64]`,\n });\n }\n }\n if (entry.heightCells !== undefined) {\n const h = entry.heightCells;\n if (!Number.isFinite(h) || h <= 0 || h > 64) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'heightCells',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].heightCells in (0, 64]`,\n });\n }\n }\n if (entry.pivotX !== undefined) {\n const px = entry.pivotX;\n if (!Number.isFinite(px) || px < 0 || px > 1) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'pivotX',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].pivotX in [0, 1]`,\n });\n }\n }\n if (entry.pivotY !== undefined) {\n const py = entry.pivotY;\n if (!Number.isFinite(py) || py < 0 || py > 1) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'pivotY',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].pivotY in [0, 1]`,\n });\n }\n }\n if (entry.collider !== undefined) {\n const colliderErr = validateColliderShape(entry.collider, assetGuid, i);\n if (colliderErr !== null) return colliderErr;\n }\n }\n return null;\n}\n\n/**\n * Compute the implicit atlas extent of a `TilesetAsset` from its grid metadata\n * (`columns * tileWidth` x `rows * tileHeight`). Used by the register-time\n * region-bounds check when the caller does not supply explicit extents.\n */\nexport function inferAtlasExtent(asset: TilesetAsset): { atlasWidth: number; atlasHeight: number } {\n return {\n atlasWidth: asset.columns * asset.tileWidth,\n atlasHeight: asset.rows * asset.tileHeight,\n };\n}\n","import { decompressZstd } from '@forgeax/engine-codec';\nimport { validateArtifactPath } from '@forgeax/engine-pack';\nimport type { ArtifactDescriptor, AssetArtifactError } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport interface ArtifactReadRequest {\n readonly packageUrl: string;\n readonly guid: string;\n readonly artifactKey: string;\n readonly descriptor: ArtifactDescriptor;\n}\n\nexport type ArtifactFetcher = (url: string) => Promise<Response>;\n\nfunction failure(\n code: AssetArtifactError['code'],\n request: ArtifactReadRequest,\n expected: string,\n hint: string,\n observed: string,\n): AssetArtifactError {\n if (code === 'asset-artifact-missing') {\n return {\n code,\n expected,\n hint,\n detail: {\n guid: request.guid,\n artifactKey: request.artifactKey,\n path: request.descriptor.path,\n observed,\n expected,\n },\n };\n }\n return {\n code,\n expected,\n hint,\n detail: {\n guid: request.guid,\n artifactKey: request.artifactKey,\n observed,\n expected,\n },\n };\n}\n\nfunction artifactUrl(packageUrl: string, path: string): string {\n try {\n return new URL(path, packageUrl).toString();\n } catch {\n const queryIndex = packageUrl.search(/[?#]/);\n const cleanPackageUrl = queryIndex < 0 ? packageUrl : packageUrl.slice(0, queryIndex);\n const slash = cleanPackageUrl.lastIndexOf('/');\n return `${slash < 0 ? '' : cleanPackageUrl.slice(0, slash + 1)}${path}`;\n }\n}\n\nfunction encodedBytes(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return globalThis.btoa(binary);\n}\n\nfunction hexBytes(bytes: Uint8Array): string {\n return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nasync function sha256(bytes: Uint8Array): Promise<{ base64: string; hex: string } | undefined> {\n const subtle = globalThis.crypto?.subtle;\n if (subtle === undefined) return undefined;\n const digest = await subtle.digest('SHA-256', bytes.slice().buffer as ArrayBuffer);\n const digestBytes = new Uint8Array(digest);\n return { base64: encodedBytes(digestBytes), hex: hexBytes(digestBytes) };\n}\n\nasync function decodeOuter(\n bytes: Uint8Array,\n request: ArtifactReadRequest,\n): Promise<Result<Uint8Array, AssetArtifactError>> {\n const encoding = request.descriptor.contentEncoding ?? 'identity';\n if (encoding === 'identity') return ok(bytes);\n if (encoding !== 'zstd') {\n return err(\n failure(\n 'asset-artifact-encoding-unsupported',\n request,\n \"contentEncoding 'identity' or 'zstd'\",\n 'change the descriptor to a supported outer content encoding and re-cook the package',\n encoding,\n ),\n );\n }\n const decoded = await decompressZstd(bytes);\n if (!decoded.ok) {\n return err(\n failure(\n 'asset-artifact-decode-failed',\n request,\n 'valid bytes for the declared outer content encoding',\n 're-cook the artifact and verify the stored bytes before loading again',\n JSON.stringify(decoded.error.detail),\n ),\n );\n }\n return ok(decoded.value);\n}\n\nasync function verifyBytes(\n bytes: Uint8Array,\n request: ArtifactReadRequest,\n): Promise<Result<Uint8Array, AssetArtifactError>> {\n const expectedLength = request.descriptor.byteLength;\n if (expectedLength !== undefined && expectedLength !== bytes.byteLength) {\n return err(\n failure(\n 'asset-artifact-integrity-mismatch',\n request,\n `decoded artifact byteLength ${expectedLength}`,\n 're-cook the package or update its artifact descriptor to match the bytes',\n String(bytes.byteLength),\n ),\n );\n }\n const integrity = request.descriptor.integrity;\n if (integrity === undefined) return ok(bytes);\n const digest = await sha256(bytes);\n if (digest === undefined) {\n return err(\n failure(\n 'asset-artifact-integrity-mismatch',\n request,\n 'a runtime with Web Crypto SHA-256 support',\n 'enable Web Crypto or remove the unverifiable artifact from the package',\n 'crypto.subtle unavailable',\n ),\n );\n }\n const expectedDigest = integrity.digest.startsWith('sha256:')\n ? integrity.digest.slice('sha256:'.length)\n : integrity.digest;\n if (expectedDigest !== digest.base64 && expectedDigest.toLowerCase() !== digest.hex) {\n return err(\n failure(\n 'asset-artifact-integrity-mismatch',\n request,\n `sha256 digest ${integrity.digest}`,\n 're-cook the artifact or replace the corrupted stored bytes',\n digest.base64,\n ),\n );\n }\n return ok(bytes);\n}\n\nexport async function readArtifact(\n request: ArtifactReadRequest,\n fetcher: ArtifactFetcher = (url) => globalThis.fetch(url),\n): Promise<Result<Uint8Array, AssetArtifactError>> {\n if (request.descriptor.mediaType.trim().length === 0) {\n return err(\n failure(\n 'asset-artifact-media-unsupported',\n request,\n 'a non-empty durable artifact mediaType',\n 'set the artifact mediaType during production and re-publish the package',\n request.descriptor.mediaType,\n ),\n );\n }\n const path = validateArtifactPath(request.descriptor.path, {\n packageRoot: request.packageUrl,\n guid: request.guid,\n artifactKey: request.artifactKey,\n });\n if (!path.ok) return path;\n\n const encoding = request.descriptor.contentEncoding ?? 'identity';\n if (encoding !== 'identity' && encoding !== 'zstd') {\n return err(\n failure(\n 'asset-artifact-encoding-unsupported',\n request,\n \"contentEncoding 'identity' or 'zstd'\",\n 'change the descriptor to a supported outer content encoding and re-cook the package',\n encoding,\n ),\n );\n }\n\n const url = artifactUrl(request.packageUrl, path.value);\n let response: Response;\n try {\n response = await fetcher(url);\n } catch (cause) {\n return err(\n failure(\n 'asset-artifact-missing',\n request,\n `readable artifact at ${path.value}`,\n 'publish the artifact at the declared package-relative path and retry the load',\n cause instanceof Error ? cause.message : 'artifact fetch failed',\n ),\n );\n }\n if (!response.ok) {\n return err(\n failure(\n 'asset-artifact-missing',\n request,\n `HTTP 200 for artifact at ${path.value}`,\n 'publish the missing artifact and retry the load',\n `HTTP ${response.status}`,\n ),\n );\n }\n\n let bytes: Uint8Array;\n try {\n bytes = new Uint8Array(await response.arrayBuffer());\n } catch (cause) {\n return err(\n failure(\n 'asset-artifact-missing',\n request,\n `readable artifact at ${path.value}`,\n 'repair the published artifact and retry the load',\n cause instanceof Error ? cause.message : 'artifact body unreadable',\n ),\n );\n }\n const decoded = await decodeOuter(bytes, request);\n if (!decoded.ok) return decoded;\n return verifyBytes(decoded.value, request);\n}\n\nexport class ArtifactReadCache {\n private readonly cache = new Map<string, Promise<Result<Uint8Array, AssetArtifactError>>>();\n\n read(\n key: string,\n reader: () => Promise<Result<Uint8Array, AssetArtifactError>>,\n ): Promise<Result<Uint8Array, AssetArtifactError>> {\n const existing = this.cache.get(key);\n if (existing !== undefined) return existing;\n const pending = reader();\n this.cache.set(key, pending);\n void pending.then((result) => {\n if (!result.ok) this.cache.delete(key);\n });\n return pending;\n }\n\n clear(key?: string): void {\n if (key === undefined) this.cache.clear();\n else this.cache.delete(key);\n }\n}\n","import {\n type AssetEvidence,\n type AssetEvidenceError,\n type AssetEvidenceInputs,\n err,\n projectAssetEvidence,\n type Result,\n} from '@forgeax/engine-types';\n\n/** Host-injected runtime bridge; the adapter never imports CLI, Vite, or Node policy. */\nexport interface RuntimeEvidenceSource {\n readonly evidence: (\n guid: string,\n ) => Promise<AssetEvidenceInputs | Result<AssetEvidenceInputs, AssetEvidenceError>>;\n}\n\n/** Runtime SDK view over the shared AssetEvidence projector. */\nexport interface RuntimeAssetEvidenceAdapter {\n readonly inspect: (guid: string) => Promise<Result<AssetEvidence, AssetEvidenceError>>;\n readonly verifyByGuid: (guid: string) => Promise<Result<AssetEvidence, AssetEvidenceError>>;\n}\n\nfunction missingCapability(guid: string): Result<never, AssetEvidenceError> {\n return err({\n code: 'asset-evidence-capability-missing',\n expected: 'an injected runtime evidence source',\n hint: 'configure an evidence source before calling inspect(guid) or verifyByGuid(guid)',\n detail: { capability: 'runtime evidence source', stage: `guid:${guid}` },\n });\n}\n\nasync function project(\n source: RuntimeEvidenceSource,\n guid: string,\n): Promise<Result<AssetEvidence, AssetEvidenceError>> {\n const input = await source.evidence(guid);\n if ('ok' in input) {\n if (!input.ok) return input;\n return projectAssetEvidence(input.value);\n }\n return projectAssetEvidence(input);\n}\n\n/** Create an adapter; omitted source intentionally returns capability-missing errors. */\nexport function createRuntimeAssetEvidenceAdapter(\n source?: RuntimeEvidenceSource,\n): RuntimeAssetEvidenceAdapter {\n const read = async (guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>> =>\n source === undefined ? missingCapability(guid) : project(source, guid);\n return { inspect: read, verifyByGuid: read };\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport {\n ASSET_ERROR_HINTS,\n type Asset,\n type AssetAuthoringCapability,\n type AssetEnvelope,\n AssetError,\n type AssetPublicationEnvelope,\n type AssetRelation,\n authoringCapabilityForAssetKind,\n type CatalogDiagnostic,\n type CatalogLifecycle,\n type CatalogProjection,\n type CatalogSubject,\n type CookExecution,\n type ProviderProvenance,\n type ResourceRevision,\n type RuntimeAssetBinding,\n type SourceOverrideDescriptor,\n type SourceOverrideMap,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry } from '../asset-registry';\n\n/** Runtime catalog row parsed from the shared pack-index POD shape. */\nexport interface CatalogRecord {\n readonly packageUrl: string;\n readonly kind: string;\n readonly authoring?: import('@forgeax/engine-types').AssetAuthoringCapability;\n readonly name?: string;\n readonly refs?: readonly string[];\n readonly sourcePath?: string;\n readonly cookReceiptUrl?: string;\n readonly packageId?: string;\n readonly provenance?: ProviderProvenance;\n readonly revision?: ResourceRevision;\n readonly sourceKey?: string;\n readonly sourceIndex?: number;\n readonly sourceOverrides?: SourceOverrideMap;\n readonly sourceOverrideDescriptors?: readonly SourceOverrideDescriptor[];\n readonly relations?: readonly AssetRelation[];\n readonly diagnostics?: readonly CatalogDiagnostic[];\n /** Producer-owned projection axes; never infer these from locators. */\n readonly subject?: CatalogSubject;\n readonly execution?: CookExecution;\n readonly lifecycle?: CatalogLifecycle;\n readonly projection?: CatalogProjection;\n /** Complete producer publication tuple used by Scene publication fences. */\n readonly publication?: AssetPublicationEnvelope;\n}\n\n/** Build the canonical row for an inline asset without inventing producer facts. */\nexport function createInlineCatalogRecord(\n envelope: AssetEnvelope<Asset>,\n name: string,\n): CatalogRecord {\n return {\n packageUrl: '',\n kind: envelope.payload.kind,\n authoring: authoringCapabilityForAssetKind(envelope.payload.kind),\n name,\n ...(envelope.refs.length > 0 ? { refs: envelope.refs.map((ref) => ref.guid) } : {}),\n };\n}\n\ntype CatalogFetch = (\n input: string,\n init?: { readonly cache?: 'no-store' },\n) => PromiseLike<{\n readonly ok: boolean;\n json(): Promise<unknown>;\n}>;\n\nfunction parseError(\n expected: string,\n detail?: object,\n hint = ASSET_ERROR_HINTS['asset-parse-failed'],\n): AssetError {\n return new AssetError({\n code: 'asset-parse-failed',\n expected,\n hint,\n ...(detail === undefined ? {} : { detail: detail as never }),\n });\n}\n\nfunction sameRevision(left: ResourceRevision, right: ResourceRevision): boolean {\n return (\n left.digest === right.digest &&\n left.observedAt === right.observedAt &&\n left.rootId === right.rootId\n );\n}\n\nfunction checkExpectedRevision(\n records: readonly CatalogRecord[],\n expectedRevision: ResourceRevision | undefined,\n): AssetError | undefined {\n if (expectedRevision === undefined || records.length === 0) return undefined;\n const actualRevisions = records.flatMap((record) =>\n record.revision === undefined ? [] : [record.revision],\n );\n if (\n actualRevisions.length > 0 &&\n actualRevisions.every((revision) => sameRevision(revision, expectedRevision))\n ) {\n return undefined;\n }\n return parseError(\n 'every catalog entry to carry the expected producer revision',\n { expectedRevision, actualRevisions },\n 'restore a verified catalog revision before applying the source',\n );\n}\n\n/** Resolve a catalog entry URL against the configured pack-index URL. */\nexport function resolveCatalogAssetUrl(registry: AssetRegistry, packageUrl: string): string {\n const packIndexUrl = registry.packIndexUrl;\n if (packIndexUrl === undefined) return packageUrl;\n\n try {\n const baseUrl = new URL(packIndexUrl, globalThis.location?.href).href;\n return new URL(packageUrl, baseUrl).href;\n } catch {\n return packageUrl;\n }\n}\n\nfunction isRawSourceLocator(packageUrl: string): boolean {\n const path = packageUrl.split(/[?#]/, 1)[0]?.toLowerCase() ?? packageUrl.toLowerCase();\n if (path.endsWith('.pack.json')) return false;\n return (\n /\\.(bin|fbx|gltf|glb|hdr|jpg|jpeg|png|wav|mp3|ogg|ttf|otf|woff|woff2|svg)$/.test(path) ||\n path.endsWith('.particle-effect.json')\n );\n}\n\n/** Parse the shared pack-index/catalog wire shape without loading payloads. */\nexport function parseCatalog(\n raw: unknown,\n resolveUrl: (packageUrl: string) => string = (packageUrl) => packageUrl,\n expectedRevision?: ResourceRevision,\n expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>,\n): Result<Map<string, CatalogRecord>, AssetError> {\n let rows: readonly unknown[];\n if (expectedScope !== undefined) {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return err(\n parseError(\n 'scoped catalog snapshot to be an object with schema, scopeId, generation, authority, and entries',\n ),\n );\n }\n const snapshot = raw as Record<string, unknown>;\n if (\n snapshot.schemaVersion !== 'runtime-catalog-snapshot-v1' ||\n typeof snapshot.scopeId !== 'string' ||\n typeof snapshot.generation !== 'number' ||\n !Number.isSafeInteger(snapshot.generation) ||\n !Array.isArray(snapshot.entries)\n ) {\n return err(parseError('scoped catalog snapshot to satisfy its runtime schema'));\n }\n if (\n snapshot.scopeId !== expectedScope.scopeId ||\n snapshot.generation !== expectedScope.generation\n ) {\n return err(\n parseError('scoped catalog snapshot to match the active scope and generation', {\n expectedScope,\n actualScope: { scopeId: snapshot.scopeId, generation: snapshot.generation },\n }),\n );\n }\n if (snapshot.authority !== 'authoritative') {\n return err(\n parseError(\n 'scoped catalog snapshot authority to be authoritative before identity lookup',\n { authority: snapshot.authority, diagnostics: snapshot.diagnostics },\n 'repair the active game catalog before loading assets',\n ),\n );\n }\n rows = snapshot.entries;\n } else if (Array.isArray(raw)) {\n rows = raw;\n } else {\n return err(parseError('pack-index.json to be a JSON array'));\n }\n\n const catalog = new Map<string, CatalogRecord>();\n for (const item of rows) {\n if (item === null || typeof item !== 'object') {\n return err(parseError('each catalog row to be an object'));\n }\n const rawRow = item as Record<string, unknown>;\n const legacyLocator = ['relative', 'Url'].join('');\n if (\n legacyLocator in rawRow ||\n 'metadata' in rawRow ||\n 'compression' in rawRow ||\n 'artifacts' in rawRow ||\n 'assetCodec' in rawRow ||\n 'contentEncoding' in rawRow\n ) {\n return err(parseError('catalog rows to expose navigation fields only'));\n }\n if (\n typeof rawRow.guid !== 'string' ||\n rawRow.guid.length === 0 ||\n typeof rawRow.packageUrl !== 'string' ||\n rawRow.packageUrl.length === 0 ||\n typeof rawRow.kind !== 'string' ||\n rawRow.kind.length === 0\n ) {\n return err(parseError('each catalog row to contain guid, packageUrl, and kind strings'));\n }\n if (isRawSourceLocator(rawRow.packageUrl)) {\n return err(\n parseError(`catalog packageUrl ${rawRow.packageUrl} to identify a cooked package`),\n );\n }\n const guid = rawRow.guid.toLowerCase();\n if (catalog.has(guid)) return err(parseError(`catalog GUID ${rawRow.guid} to be unique`));\n const refs = rawRow.refs;\n if (\n refs !== undefined &&\n (!Array.isArray(refs) || !refs.every((ref) => typeof ref === 'string'))\n ) {\n return err(parseError(`catalog refs for GUID ${rawRow.guid} to be a string array`));\n }\n if (\n rawRow.sourceOverrides !== undefined &&\n (rawRow.sourceOverrides === null ||\n typeof rawRow.sourceOverrides !== 'object' ||\n Array.isArray(rawRow.sourceOverrides))\n ) {\n return err(parseError(`catalog sourceOverrides for GUID ${rawRow.guid} to be an object`));\n }\n if (\n rawRow.sourceOverrideDescriptors !== undefined &&\n !Array.isArray(rawRow.sourceOverrideDescriptors)\n ) {\n return err(\n parseError(`catalog sourceOverrideDescriptors for GUID ${rawRow.guid} to be an array`),\n );\n }\n let resolvedUrl: string;\n try {\n resolvedUrl = resolveUrl(rawRow.packageUrl);\n } catch (error) {\n return err(\n parseError(`catalog entry ${rawRow.guid} to resolve its packageUrl`, {\n packageUrl: rawRow.packageUrl,\n reason: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n const row: CatalogRecord = {\n packageUrl: resolvedUrl,\n kind: rawRow.kind,\n ...(rawRow.authoring !== undefined\n ? { authoring: rawRow.authoring as AssetAuthoringCapability }\n : {}),\n ...(typeof rawRow.name === 'string' ? { name: rawRow.name } : {}),\n ...(typeof rawRow.sourcePath === 'string' ? { sourcePath: rawRow.sourcePath } : {}),\n ...(refs !== undefined ? { refs: refs as readonly string[] } : {}),\n ...(typeof rawRow.cookReceiptUrl === 'string'\n ? { cookReceiptUrl: rawRow.cookReceiptUrl }\n : {}),\n ...(typeof rawRow.packageId === 'string' ? { packageId: rawRow.packageId } : {}),\n ...(rawRow.provenance !== undefined\n ? { provenance: rawRow.provenance as ProviderProvenance }\n : {}),\n ...(rawRow.revision !== undefined ? { revision: rawRow.revision as ResourceRevision } : {}),\n ...(typeof rawRow.sourceKey === 'string' ? { sourceKey: rawRow.sourceKey } : {}),\n ...(typeof rawRow.sourceIndex === 'number' ? { sourceIndex: rawRow.sourceIndex } : {}),\n ...(rawRow.sourceOverrides !== undefined\n ? { sourceOverrides: rawRow.sourceOverrides as SourceOverrideMap }\n : {}),\n ...(rawRow.sourceOverrideDescriptors !== undefined\n ? {\n sourceOverrideDescriptors:\n rawRow.sourceOverrideDescriptors as readonly SourceOverrideDescriptor[],\n }\n : {}),\n ...(Array.isArray(rawRow.relations)\n ? { relations: rawRow.relations as readonly AssetRelation[] }\n : {}),\n ...(Array.isArray(rawRow.diagnostics)\n ? { diagnostics: rawRow.diagnostics as readonly CatalogDiagnostic[] }\n : {}),\n ...(rawRow.subject === 'internal-asset' || rawRow.subject === 'imported-output'\n ? { subject: rawRow.subject }\n : {}),\n ...(rawRow.execution === 'direct' || rawRow.execution === 'cooked'\n ? { execution: rawRow.execution }\n : {}),\n ...(rawRow.lifecycle === 'missing' ||\n rawRow.lifecycle === 'cooking' ||\n rawRow.lifecycle === 'current' ||\n rawRow.lifecycle === 'stale' ||\n rawRow.lifecycle === 'failed'\n ? { lifecycle: rawRow.lifecycle }\n : {}),\n ...(rawRow.projection !== undefined\n ? { projection: rawRow.projection as CatalogProjection }\n : {}),\n ...(rawRow.publication !== undefined\n ? { publication: rawRow.publication as AssetPublicationEnvelope }\n : {}),\n };\n catalog.set(guid, row);\n }\n const revisionError = checkExpectedRevision([...catalog.values()], expectedRevision);\n if (revisionError !== undefined) return err(revisionError);\n return ok(catalog);\n}\n\n/** Fetch and parse a catalog using the shared JSON/error boundary. */\nexport async function fetchCatalog(\n url: string,\n fetch: CatalogFetch,\n resolveUrl?: (packageUrl: string) => string,\n expectedRevision?: ResourceRevision,\n expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>,\n requestInit?: { readonly cache?: 'no-store' },\n): Promise<Result<Map<string, CatalogRecord>, AssetError>> {\n let raw: unknown;\n try {\n const response = requestInit === undefined ? await fetch(url) : await fetch(url, requestInit);\n if (!response.ok) {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n raw = await response.json();\n } catch {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n return parseCatalog(raw, resolveUrl, expectedRevision, expectedScope);\n}\n\nexport function fetchPackIndex(\n registry: AssetRegistry,\n): Promise<Result<Map<string, CatalogRecord>, AssetError>> {\n const expectedScope =\n registry.runtimeBinding !== undefined &&\n registry.packIndexUrl === registry.runtimeBinding.catalogUrl\n ? registry.runtimeBinding\n : undefined;\n return fetchCatalog(\n registry.packIndexUrl as string,\n globalThis.fetch,\n (packageUrl) => resolveCatalogAssetUrl(registry, packageUrl),\n undefined,\n expectedScope,\n { cache: 'no-store' },\n );\n}\n","import { ok, type Result } from '@forgeax/engine-rhi';\nimport type {\n AssetError,\n CatalogDelta,\n CatalogDiagnostic,\n CatalogEntry,\n CatalogRevisionWindow,\n ResourceRevision,\n RuntimeAssetBinding,\n} from '@forgeax/engine-types';\nimport type { CatalogSource } from '../catalog-source';\n\nexport interface CatalogReplicaSnapshot {\n readonly version: number;\n readonly entries: readonly CatalogEntry[];\n readonly stale: boolean;\n readonly diagnostics: readonly CatalogDiagnostic[];\n}\n\ntype SnapshotResult = Result<CatalogReplicaSnapshot, AssetError>;\ntype CatalogDeltaListener = (delta: CatalogDelta) => void;\n\nfunction guidKey(guid: string): string {\n return guid.toLowerCase();\n}\n\nfunction freezeEntry(entry: CatalogEntry): CatalogEntry {\n return Object.freeze({ ...entry });\n}\n\nfunction freezeSnapshot(snapshot: CatalogReplicaSnapshot): CatalogReplicaSnapshot {\n return Object.freeze({\n ...snapshot,\n entries: Object.freeze(snapshot.entries.map(freezeEntry)),\n diagnostics: Object.freeze([...snapshot.diagnostics]),\n });\n}\n\nfunction revisionIsOlder(\n incoming: ResourceRevision | undefined,\n current: ResourceRevision | undefined,\n): boolean {\n return (\n incoming !== undefined && current !== undefined && incoming.observedAt < current.observedAt\n );\n}\n\nfunction sameRevision(left: ResourceRevision, right: ResourceRevision): boolean {\n return (\n left.digest === right.digest &&\n left.observedAt === right.observedAt &&\n left.rootId === right.rootId\n );\n}\n\nfunction sameValue(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction diagnosticForGap(): CatalogDiagnostic {\n return {\n code: 'catalog-gap',\n severity: 'blocking',\n expected: 'a contiguous producer revision window',\n hint: 'reconcile the catalog before consuming incremental changes',\n authority: 'catalog',\n };\n}\n\nfunction diagnosticForDegradedRows(): CatalogDiagnostic {\n return {\n code: 'catalog-degraded-rows',\n severity: 'blocking',\n expected: 'a degraded catalog delta to contain no identity-bearing rows',\n hint: 'keep the last verified catalog and reconcile before applying a replacement',\n authority: 'catalog',\n };\n}\n\nfunction hasIdentityChanges(delta: CatalogDelta): boolean {\n return delta.added.length > 0 || delta.changed.length > 0 || delta.removed.length > 0;\n}\n\nfunction revisionDiagnostic(\n revisions: CatalogRevisionWindow,\n hasChanges: boolean,\n): CatalogDiagnostic | undefined {\n const baselineByRoot = new Map(revisions.baseline.map((point) => [point.rootId, point]));\n const currentByRoot = new Map(revisions.current.map((point) => [point.rootId, point]));\n\n for (const point of revisions.current) {\n const baseline = baselineByRoot.get(point.rootId);\n if (baseline === undefined) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'every current root to have a verified baseline',\n actual: point.rootId,\n hint: 'restore the latest verified snapshot for this root before applying the delta',\n authority: 'catalog',\n };\n }\n if (point.revision < baseline.revision) {\n return {\n code: 'catalog-revision-stale',\n severity: 'blocking',\n expected: 'current revision to be at least the verified baseline',\n actual: `${baseline.revision} -> ${point.revision}`,\n hint: 'discard the stale update and request a fresh catalog snapshot',\n authority: 'catalog',\n };\n }\n if (point.revision === baseline.revision && hasChanges) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'a changed delta to advance the root revision',\n actual: `${baseline.revision} -> ${point.revision}`,\n hint: 'keep the verified baseline and serialize concurrent updates before retrying',\n authority: 'catalog',\n };\n }\n if (point.revision > baseline.revision + 1) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'the next revision to be exactly baseline + 1',\n actual: `${baseline.revision} -> ${point.revision}`,\n hint: 'request the missing revisions or rebuild from the latest verified snapshot',\n authority: 'catalog',\n };\n }\n }\n\n for (const point of revisions.baseline) {\n if (!currentByRoot.has(point.rootId)) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'every baseline root to be present in the current revision set',\n actual: point.rootId,\n hint: 'do not apply a partial root set over the verified baseline',\n authority: 'catalog',\n };\n }\n }\n\n return undefined;\n}\n\nfunction rowRevisionDiagnostic(\n entries: ReadonlyMap<string, CatalogEntry>,\n delta: CatalogDelta,\n): CatalogDiagnostic | undefined {\n for (const entry of [...delta.added, ...delta.changed]) {\n const prior = entries.get(guidKey(entry.guid));\n if (prior?.revision === undefined) continue;\n if (prior !== undefined && sameValue(prior, entry)) continue;\n if (entry.revision === undefined) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'a replacement row to carry a newer producer revision',\n actual: `${prior.revision.rootId}@${prior.revision.observedAt} -> missing`,\n hint: 'restore the producer revision before applying the catalog change',\n authority: 'catalog',\n };\n }\n if (entry.revision.observedAt < prior.revision.observedAt) {\n return {\n code: 'catalog-revision-stale',\n severity: 'blocking',\n expected: 'a replacement row to carry a non-decreasing producer revision',\n actual: `${prior.revision.observedAt} -> ${entry.revision.observedAt}`,\n hint: 'discard the stale update and request a fresh catalog snapshot',\n authority: 'catalog',\n };\n }\n if (entry.revision.observedAt === prior.revision.observedAt) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'a changed row to advance its producer revision',\n actual: sameRevision(prior.revision, entry.revision)\n ? `${prior.revision.observedAt} -> ${entry.revision.observedAt}`\n : `${prior.revision.digest} -> ${entry.revision.digest}`,\n hint: 'publish a new producer revision for changed payload bytes',\n authority: 'catalog',\n };\n }\n }\n return undefined;\n}\n\nfunction diagnosticForScopeMismatch(): CatalogDiagnostic {\n return {\n code: 'catalog-scope-mismatch',\n severity: 'blocking',\n expected: 'catalog delta scopeId and generation to match the active runtime binding',\n hint: 'discard the stale publication and reconcile the active runtime catalog',\n authority: 'catalog',\n };\n}\n\nfunction appendDiagnostic(\n diagnostics: readonly CatalogDiagnostic[],\n incoming: readonly CatalogDiagnostic[] | undefined,\n): readonly CatalogDiagnostic[] {\n const next = [...diagnostics];\n for (const diagnostic of incoming ?? []) {\n if (!next.some((existing) => existing.code === diagnostic.code)) next.push(diagnostic);\n }\n return next;\n}\n\n/**\n * One authoritative catalog read model owned by AssetRegistry.\n *\n * The source subscription is installed before the first enumeration. Deltas\n * observed during that baseline read are buffered and folded afterwards, so\n * an early publication cannot disappear between the two operations.\n */\nexport class CatalogReplica {\n private readonly source: CatalogSource;\n private readonly listeners = new Set<CatalogDeltaListener>();\n private readonly entries = new Map<string, CatalogEntry>();\n private pendingBeforeBaseline: CatalogDelta[] = [];\n private pendingDuringReconcile: CatalogDelta[] | undefined;\n private unsubscribe: (() => void) | undefined;\n private startPromise: Promise<SnapshotResult> | undefined;\n private baselineReady = false;\n private version = 0;\n private stale = false;\n private diagnostics: readonly CatalogDiagnostic[] = [];\n private currentSnapshot: CatalogReplicaSnapshot;\n private readonly expectedScope: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'> | undefined;\n\n constructor(source: CatalogSource) {\n this.source = source;\n this.expectedScope = source.expectedScope;\n this.currentSnapshot = freezeSnapshot({\n version: 0,\n entries: [],\n stale: false,\n diagnostics: [],\n });\n }\n\n subscribe(listener: CatalogDeltaListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n snapshot(): CatalogReplicaSnapshot {\n return this.currentSnapshot;\n }\n\n dispose(): void {\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.startPromise = undefined;\n this.pendingBeforeBaseline = [];\n this.pendingDuringReconcile = undefined;\n this.listeners.clear();\n }\n\n async start(): Promise<SnapshotResult> {\n if (this.startPromise !== undefined) return this.startPromise;\n if (this.unsubscribe === undefined) {\n this.unsubscribe = this.source.subscribe((delta) => this.receive(delta));\n }\n const promise = this.loadBaseline(false);\n this.startPromise = promise;\n void promise.then((result) => {\n if (!result.ok) this.startPromise = undefined;\n });\n return promise;\n }\n\n async reconcile(): Promise<SnapshotResult> {\n if (this.unsubscribe === undefined) {\n this.unsubscribe = this.source.subscribe((delta) => this.receive(delta));\n }\n this.pendingDuringReconcile = [];\n return this.loadBaseline(true);\n }\n\n private async loadBaseline(isReconcile: boolean): Promise<SnapshotResult> {\n const result = await this.source.enumerate();\n if (!result.ok) {\n this.stale = true;\n this.currentSnapshot = this.makeSnapshot();\n if (!isReconcile) this.pendingBeforeBaseline = [];\n this.pendingDuringReconcile = undefined;\n return result;\n }\n\n this.entries.clear();\n for (const entry of result.value) this.entries.set(guidKey(entry.guid), freezeEntry(entry));\n this.stale = false;\n this.diagnostics = [];\n this.baselineReady = true;\n const pending = isReconcile ? (this.pendingDuringReconcile ?? []) : this.pendingBeforeBaseline;\n this.pendingBeforeBaseline = [];\n this.pendingDuringReconcile = undefined;\n for (const delta of pending) this.fold(delta, false);\n this.currentSnapshot = this.makeSnapshot();\n return ok(this.currentSnapshot);\n }\n\n private receive(delta: CatalogDelta): void {\n if (!this.baselineReady) {\n if (this.pendingDuringReconcile !== undefined) this.pendingDuringReconcile.push(delta);\n else this.pendingBeforeBaseline.push(delta);\n this.publish(this.safeDelta(delta));\n return;\n }\n if (this.pendingDuringReconcile !== undefined) {\n this.pendingDuringReconcile.push(delta);\n this.publish(this.safeDelta(delta));\n return;\n }\n this.fold(delta, true);\n }\n\n private fold(delta: CatalogDelta, publish: boolean): void {\n const safeDelta = this.safeDelta(delta);\n const degraded = safeDelta.authority === 'degraded';\n this.stale = this.stale || degraded;\n this.diagnostics = appendDiagnostic(\n this.diagnostics,\n safeDelta.diagnostics?.some((diagnostic) => diagnostic.code === 'catalog-gap')\n ? [...(safeDelta.diagnostics ?? []), diagnosticForGap()]\n : safeDelta.diagnostics,\n );\n\n if (!degraded) {\n let changed = false;\n for (const entry of [...safeDelta.added, ...safeDelta.changed]) {\n const key = guidKey(entry.guid);\n const prior = this.entries.get(key);\n if (revisionIsOlder(entry.revision, prior?.revision)) continue;\n if (prior !== undefined && sameValue(prior, entry)) continue;\n this.entries.set(key, freezeEntry(entry));\n changed = true;\n }\n for (const guid of safeDelta.removed) {\n if (this.entries.delete(guidKey(guid))) changed = true;\n }\n if (changed) this.version += 1;\n }\n\n this.currentSnapshot = this.makeSnapshot();\n if (publish) {\n this.publish(safeDelta);\n }\n }\n\n private safeDelta(delta: CatalogDelta): CatalogDelta {\n const diagnostic =\n this.expectedScope !== undefined &&\n (delta.scopeId !== this.expectedScope.scopeId ||\n delta.generation !== this.expectedScope.generation)\n ? diagnosticForScopeMismatch()\n : delta.revisions === undefined\n ? rowRevisionDiagnostic(this.entries, delta)\n : (revisionDiagnostic(delta.revisions, hasIdentityChanges(delta)) ??\n rowRevisionDiagnostic(this.entries, delta));\n const degradedRows = delta.authority === 'degraded' && hasIdentityChanges(delta);\n if (diagnostic === undefined && !degradedRows) return delta;\n return {\n ...delta,\n added: [],\n changed: [],\n removed: [],\n authority: 'degraded',\n diagnostics: appendDiagnostic(\n [],\n [\n ...(diagnostic === undefined ? [] : [diagnostic]),\n ...(degradedRows ? [diagnosticForDegradedRows()] : []),\n ],\n ),\n };\n }\n\n private publish(delta: CatalogDelta): void {\n for (const listener of [...this.listeners]) {\n try {\n listener(delta);\n } catch {\n // One observer cannot prevent the remaining catalog observers from seeing a fact.\n }\n }\n }\n\n private makeSnapshot(): CatalogReplicaSnapshot {\n const entries = [...this.entries.values()].sort((left, right) =>\n guidKey(left.guid).localeCompare(guidKey(right.guid)),\n );\n this.currentSnapshot = freezeSnapshot({\n version: this.version,\n entries,\n stale: this.stale,\n diagnostics: this.diagnostics,\n });\n return this.currentSnapshot;\n }\n}\n","// M8 w59 (round 5 D-18 atomic): two-tier resolution + material-walk over\n// world.sharedRefs.\n//\n// D-15 two-tier asset resolution: slots in [1, BUILTIN_BASE) are builtins\n// (process-static, resolve through BuiltinAssetRegistry.resolve, never\n// reference-counted); slots >= BUILTIN_BASE are user-tier (resolve through\n// world.sharedRefs.resolve). Resolution is entirely ECS/render-side -- it\n// never goes through AssetRegistry (human-inputs implement-architecture-\n// correction 2026-06-16T12:35:07Z: AssetRegistry has NO handle concept).\n//\n// AI-user surface: `resolveAssetHandle(world, handle)` is the single entry\n// point for handle-to-payload resolution; `walkMaterialPassesOverSharedRefs`\n// is the material parent-chain walk used by the render extract stage. Charter\n// F1 single-entry indexability -- one import, one call, no dual-path leak.\n\nimport type { SharedRefStaleError, UniqueRefStaleError, World } from '@forgeax/engine-ecs';\nimport type { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { err, ok, type Result } from '@forgeax/engine-rhi';\nimport type {\n Asset,\n AssetError as AssetErrorType,\n Handle,\n MaterialAsset,\n MaterialError,\n MaterialPass,\n} from '@forgeax/engine-types';\nimport {\n ASSET_ERROR_HINTS,\n AssetError,\n BUILTIN_BASE,\n handleSlot,\n materialGuidText,\n resolveMaterialAsset,\n} from '@forgeax/engine-types';\nimport { BuiltinAssetRegistry } from './builtin-asset-registry';\n\n/**\n * Resolve a handle to its asset payload with two-tier slot-range dispatch.\n *\n * slot < BUILTIN_BASE -> BuiltinAssetRegistry.resolve(handle) (process-static)\n * slot >= BUILTIN_BASE -> world.sharedRefs.resolve(handle) (user-tier RC)\n *\n * Callers must specify the expected asset type explicitly:\n * `resolveAssetHandle<MeshAsset>(world, handle)`. The type parameter is an\n * assertion -- the runtime dispatch returns the correct payload based on slot\n * range; the type parameter mirrors the caller's expectation.\n *\n * @param world - The World owning the per-World SharedRefStore (user-tier).\n * @param handle - The branded handle to resolve.\n * @returns `Result.ok(payload)` on hit, `Result.err(AssetError)` on miss.\n */\nexport function resolveAssetHandle<T extends Asset>(\n world: World,\n handle: Handle<string, 'shared'>,\n): Result<T, AssetErrorType | SharedRefStaleError | UniqueRefStaleError> {\n const slot = handleSlot(handle);\n if (slot < BUILTIN_BASE) {\n const builtin = BuiltinAssetRegistry.resolve(handle);\n if (builtin !== null) return ok(builtin as unknown as T);\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `builtin slot ${slot} present in BuiltinAssetRegistry`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n const res = world.sharedRefs.resolve<string, T>(handle);\n if (res.ok) return ok(res.value);\n // Forward the closed error code transparently. Checking the discriminant,\n // rather than constructor identity, preserves the structured stale detail\n // when a browser bundles the bridge and its World through different module\n // instances.\n switch (res.error.code) {\n case 'shared-ref-stale':\n return err(res.error);\n case 'shared-ref-released':\n case 'builtin-slot-not-owned':\n break;\n }\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `user-tier slot ${slot} present in world.sharedRefs`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n}\n\n/**\n * Walk a MaterialAsset parent chain to produce the inherited passes +\n * shallow-merged values (W-1..W-7 semantics). feat-20260614 M8 (D-19):\n * the starting material is resolved from a column `handle` via\n * {@link resolveAssetHandle} (builtin / user-tier world.sharedRefs); each\n * ancestor `material.parent` is an embedded GUID (AssetGuid) resolved through\n * the AssetRegistry catalogue ({@link AssetRegistry.lookup}). The registry\n * holds no handles -- it is the GUID->payload SSOT for parent resolution.\n *\n * Zero-cache (AC-04): every call builds the same table-shaped input and delegates\n * inheritance semantics to the MaterialAsset resolver in `@forgeax/engine-types`.\n * Compiler and runtime therefore share root-contract ownership and child-value\n * override semantics instead of maintaining two subtly different walks.\n */\nexport function walkMaterialPassesOverSharedRefs(\n world: World,\n handle: Handle<'MaterialAsset', 'shared'>,\n registry: { lookup(guid: AssetGuid | string): Asset | undefined },\n): Result<\n {\n passes: MaterialPass[];\n parameters: MaterialAsset['parameters'];\n values: NonNullable<MaterialAsset['values']>;\n colorSpace: MaterialAsset['colorSpace'];\n },\n AssetErrorType | MaterialError | SharedRefStaleError | UniqueRefStaleError\n> {\n // Resolve the root material payload from its column handle.\n const rootRes = resolveAssetHandle<MaterialAsset>(\n world,\n handle as unknown as Handle<string, 'shared'>,\n );\n\n const rootLabel = `handle-${handleSlot(handle)}`;\n if (!rootRes.ok) return err(rootRes.error);\n\n const table: Record<string, MaterialAsset> = {};\n const visited = new Set<string>();\n const collect = (label: string, material: MaterialAsset): void => {\n if (visited.has(label)) return;\n visited.add(label);\n table[label] = material;\n if (material.parent === undefined) return;\n const parentId = materialGuidText(material.parent);\n const parent = registry.lookup(material.parent);\n if (parent?.kind === 'material') collect(parentId, parent);\n };\n collect(rootLabel, rootRes.value);\n\n const resolved = resolveMaterialAsset(rootLabel, table);\n if (!resolved.ok) return err(resolved.error);\n return ok({\n passes: [...(resolved.value.asset.passes ?? [])],\n parameters: resolved.value.asset.parameters ?? [],\n values: { ...(resolved.value.asset.values ?? {}) },\n colorSpace: resolved.value.asset.colorSpace,\n });\n}\n","// @forgeax/engine-assets-runtime — scene-handle-fields: shared reflection helper for\n// SceneAsset handle-field extraction (plan-strategy D-4 / requirements B-5).\n//\n// `_resolveSceneGuids` (instantiate) and `buildSceneChildContext` (breadcrumb)\n// consume this helper so the \"identify shared<...> / array<shared<...>> schema\n// fields + read GUID string\" logic has exactly one authoritative location\n// (Derive, Don't Duplicate).\n//\n// This helper returns raw GUID strings WITHOUT mutating the registry; resolution\n// to Handle numbers is the caller's responsibility.\n//\n// Both consumers prefer the structured `envelope.refs` edges (D-3) when an\n// envelope is catalogued for the scene, and fall back to this entity-component\n// walk only when no envelope (or no per-entity edge detail) is available:\n// - `_resolveSceneGuids`: envelope-less scenes (e.g. unit tests that build a\n// SceneAsset directly without cataloguing it; no `sceneGuidKey`).\n// - `buildSceneChildContext`: prod GUID-only refs[] edges whose `sourceField`\n// was stripped at the serialization boundary (w7 D-10), plus direct\n// `catalog()` scene registration with no refs. The walk recovers the\n// (entityLocalId, componentName, fieldName, arrayIndex) triple the bare\n// edge no longer carries.\n\nimport type { Component } from '@forgeax/engine-ecs';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport type { MountOverride } from '@forgeax/engine-types';\n\n/**\n * A single handle-field reference extracted from a SceneAsset entity.\n *\n * `entityLocalId` is the `node.localId`; `componentName` and `fieldName`\n * identify the schema field whose `fieldType` starts with `shared\\<` or\n * `array\\<shared\\<`. `guidString` is the raw GUID string value from the\n * entity's component data (NOT a parsed `AssetGuid` — callers parse or\n * resolve as needed).\n *\n * `arrayIndex` is `undefined` for plain `handle<T>` fields; for\n * `array<handle<T>>` fields it is the 0-based index into the array.\n */\nexport interface SceneHandleFieldEntry {\n readonly entityLocalId: number;\n readonly componentName: string;\n readonly fieldName: string;\n readonly guidString: string;\n /** 0-based index for `array<handle<T>>` elements; `undefined` for plain `handle<T>` fields. */\n readonly arrayIndex?: number;\n}\n\n/**\n * Shape of a single entity passed to {@link extractSceneEntityHandleGuids}.\n *\n * Compatible with both `SceneEntity` (from `@forgeax/engine-types`, where\n * `components` is `Partial<ComponentValuesMap>`) and test-side plain objects.\n */\ninterface SceneEntityLike {\n readonly localId: number;\n readonly components: Record<string, Record<string, unknown>>;\n}\n\n/**\n * Walk every `SceneEntityLike` in `entities` and extract all GUID strings\n * bound to schema fields with `handle<...>` or `array<handle<...>>` fieldType.\n *\n * Unknown component names (absent from the supplied World-local catalog) are\n * silently skipped — the ecs layer's `additionalProperties` check will catch\n * unknowns at spawn time if appropriate.\n *\n * Values that are already numbers (resolved Handles) or non-strings are\n * skipped (they are not GUID refs).\n *\n * @internal Shared by {@link AssetRegistry._resolveSceneGuids} and\n * `buildSceneChildContext` as the entity-walk fallback used when the structured\n * `envelope.refs` edges are unavailable or carry no per-entity detail.\n */\nexport function extractSceneEntityHandleGuids(\n components: ReadonlyMap<string, Component>,\n entities: ReadonlyArray<SceneEntityLike>,\n): SceneHandleFieldEntry[] {\n const entries: SceneHandleFieldEntry[] = [];\n\n for (const node of entities) {\n const rawComponents: Record<string, Record<string, unknown>> = node.components as Record<\n string,\n Record<string, unknown>\n >;\n\n for (const compName of Object.keys(rawComponents)) {\n const rawFields = rawComponents[compName];\n if (!rawFields) continue;\n\n const comp = components.get(compName);\n if (!comp) continue;\n\n for (const fieldName of Object.keys(rawFields)) {\n forEachHandleGuid(\n componentSchema(comp)[fieldName],\n rawFields[fieldName],\n (guidString, arrayIndex) => {\n entries.push({\n entityLocalId: node.localId,\n componentName: compName,\n fieldName,\n guidString,\n ...(arrayIndex !== undefined ? { arrayIndex } : {}),\n });\n },\n );\n }\n }\n }\n\n return entries;\n}\n\n/**\n * One handle-field GUID reference extracted from a {@link MountOverride}'s value\n * (feat-20260713 M3 / w12). Mirrors {@link SceneHandleFieldEntry} but keys on the\n * override's array index (there is no entity `localId` — an override targets a\n * mount member by its own `localId`, resolved by the ecs apply loop, not here).\n *\n * `fieldName` is the schema field the GUID binds to: the override's own `field`\n * for the patch form, or a key of the component-add value map for the add form.\n */\nexport interface MountOverrideHandleFieldEntry {\n /** 0-based index into the `overrides[]` array passed to the extractor. */\n readonly overrideIndex: number;\n readonly componentName: string;\n readonly fieldName: string;\n readonly guidString: string;\n /** 0-based index for `array<shared<T>>` elements; `undefined` for scalar `shared<T>`. */\n readonly arrayIndex?: number;\n}\n\n/**\n * Walk `overrides` and extract every GUID string bound to a `shared<...>` /\n * `array<shared<...>>` schema field inside each override's value (feat-20260713\n * M3 / w12, plan-strategy D-2). This is the apply-side counterpart to\n * {@link extractSceneEntityHandleGuids}: it feeds `resolveMountsRec`'s\n * GUID→handle down-drill so a `mounts[].overrides[].value` carrying a raw GUID\n * (e.g. an `AnimationPlayer.clips` clip GUID) resolves to a live handle before\n * the ecs apply loop, which only ever sees numeric handles (D-2: the GUID domain\n * stays sealed in assets-runtime).\n *\n * The `{comp, field?, value}` discriminant is normalized to `(fieldName, value)`\n * pairs: the patch form (`field` present) yields one pair; the component-add form\n * (`field` absent, `value` is a per-field map) yields one pair per value key.\n * Field type is judged from the supplied catalog token schema, the same\n * schema SSOT the entity walk uses. Unknown components / non-shared fields /\n * non-string (already-resolved number) values are skipped (D-8 number pass-through).\n *\n * @internal Shared identification core; resolution lives in `resolveMountsRec`.\n */\nexport function extractMountOverrideHandleGuids(\n components: ReadonlyMap<string, Component>,\n overrides: ReadonlyArray<MountOverride>,\n): MountOverrideHandleFieldEntry[] {\n const entries: MountOverrideHandleFieldEntry[] = [];\n\n for (let overrideIndex = 0; overrideIndex < overrides.length; overrideIndex++) {\n const ov = overrides[overrideIndex];\n if (ov === undefined) continue;\n\n const comp = components.get(ov.comp);\n if (!comp) continue;\n\n for (const [fieldName, value] of normalizeOverrideFields(ov)) {\n forEachHandleGuid(componentSchema(comp)[fieldName], value, (guidString, arrayIndex) => {\n entries.push({\n overrideIndex,\n componentName: ov.comp,\n fieldName,\n guidString,\n ...(arrayIndex !== undefined ? { arrayIndex } : {}),\n });\n });\n }\n }\n\n return entries;\n}\n\n/**\n * Normalize a {@link MountOverride}'s `{comp, field?, value}` shape into\n * `(fieldName, value)` pairs (feat-20260713 M3 / w12). Patch form (`field`\n * present) → one pair; component-add form (`field` absent, `value` a per-field\n * map) → one pair per value key. A non-object add value yields no pairs.\n */\nfunction normalizeOverrideFields(ov: MountOverride): ReadonlyArray<readonly [string, unknown]> {\n if (ov.field !== undefined) return [[ov.field, ov.value]];\n const value = ov.value;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return [];\n const map = value as Record<string, unknown>;\n return Object.keys(map).map((key) => [key, map[key]] as const);\n}\n\n/**\n * Shared handle-GUID identification core (feat-20260713 M3 / w12 SSOT): given a\n * schema `fieldType` and a `value`, invoke `sink(guidString, arrayIndex?)` for\n * every GUID string the field binds — once for a `shared<T>` scalar string, once\n * per string element of an `array<shared<T>>`. Non-shared fields, non-string\n * scalars, and non-string array elements (already-resolved handle numbers, D-8)\n * are skipped. Both the entity walk and the override walk route through here so\n * the \"is this a shared handle field + read its GUID\" logic has one home\n * (architecture-principles §1 SSOT).\n */\nfunction forEachHandleGuid(\n fieldType: string | undefined,\n value: unknown,\n sink: (guidString: string, arrayIndex?: number) => void,\n): void {\n if (fieldType === undefined || typeof fieldType !== 'string') return;\n if (fieldType.startsWith('shared<')) {\n if (typeof value === 'string') sink(value);\n return;\n }\n if (fieldType.startsWith('array<shared<') && Array.isArray(value)) {\n for (let elemIdx = 0; elemIdx < value.length; elemIdx++) {\n const elem = value[elemIdx];\n if (typeof elem === 'string') sink(elem, elemIdx);\n }\n }\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport type {\n AssetPublicationEnvelope,\n CatalogEntry,\n ScenePublicationFence as EngineScenePublicationFence,\n} from '@forgeax/engine-types';\n\nexport const SCENE_PUBLICATION_FENCE_SCHEMA = 'scene-publication-fence/1' as const;\nexport const SCENE_PUBLICATION_RECOVERY_ACTIONS = Object.freeze([\n 'continue-last-known-good',\n 'retry-rebuild',\n 'fresh-reopen',\n] as const);\n\nexport type ScenePublicationFence = EngineScenePublicationFence;\n\nexport type ScenePublicationFencePhase = 'publication' | 'catalog' | 'observation' | 'instantiate';\n\nexport interface ScenePublicationFenceError {\n readonly code: 'asset-generation-fence-mismatch';\n readonly phase: ScenePublicationFencePhase;\n readonly hint: string;\n readonly sourcePath?: string;\n readonly sourceRevision?: string;\n readonly expected?: ScenePublicationFence;\n readonly actual?: ScenePublicationFence;\n readonly currentGeneration?: number;\n readonly lastKnownGood?: ScenePublicationFence;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n}\n\nexport interface ScenePublicationObservation {\n readonly fence: ScenePublicationFence;\n readonly outputs: readonly string[];\n}\n\nfunction errorFor(\n phase: ScenePublicationFencePhase,\n hint: string,\n input: {\n readonly publication?: AssetPublicationEnvelope;\n readonly expected?: ScenePublicationFence;\n readonly actual?: ScenePublicationFence;\n readonly lastKnownGood?: ScenePublicationFence;\n readonly retryable?: boolean;\n } = {},\n): ScenePublicationFenceError {\n return {\n code: 'asset-generation-fence-mismatch',\n phase,\n hint,\n ...(input.publication === undefined\n ? {}\n : {\n sourcePath: input.publication.sourcePath,\n sourceRevision: input.publication.sourceRevision,\n }),\n ...(input.expected === undefined ? {} : { expected: input.expected }),\n ...(input.actual === undefined ? {} : { actual: input.actual }),\n ...(input.actual === undefined\n ? {}\n : { currentGeneration: input.actual.publicationGeneration }),\n ...(input.lastKnownGood === undefined ? {} : { lastKnownGood: input.lastKnownGood }),\n retryable: input.retryable ?? false,\n recoveryActions: SCENE_PUBLICATION_RECOVERY_ACTIONS,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction sameFence(left: ScenePublicationFence, right: ScenePublicationFence): boolean {\n return (\n left.schemaVersion === right.schemaVersion &&\n left.sourcePath === right.sourcePath &&\n left.sourceRevision === right.sourceRevision &&\n left.publicationGeneration === right.publicationGeneration &&\n left.outputDigest === right.outputDigest &&\n left.outputSetDigest === right.outputSetDigest &&\n left.receiptIdentity === right.receiptIdentity\n );\n}\n\n/** Convert one complete Engine publication into the serializable Scene fence. */\nexport function createScenePublicationFence(\n publication: AssetPublicationEnvelope,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n if (publication.outputs.length === 0) {\n return err(\n errorFor('publication', 'publication must contain at least one output', { publication }),\n );\n }\n if (!Number.isSafeInteger(publication.generation) || publication.generation < 1) {\n return err(\n errorFor('publication', 'publication generation must be a positive integer', { publication }),\n );\n }\n const receipt = publication.receipt;\n if (\n receipt.schemaVersion !== 'asset-publication-receipt/1' ||\n receipt.sourcePath !== publication.sourcePath ||\n receipt.sourceRevision !== publication.sourceRevision ||\n receipt.outputDigest !== publication.digest ||\n receipt.outputSetDigest !== publication.outputSetDigest\n ) {\n return err(\n errorFor('publication', 'publication receipt does not match the complete output tuple', {\n publication,\n }),\n );\n }\n const outputGuids = new Set<string>();\n for (const output of publication.outputs) {\n const key = output.guid.toLowerCase();\n if (outputGuids.has(key)) {\n return err(\n errorFor('publication', 'publication output GUIDs must be unique', { publication }),\n );\n }\n outputGuids.add(key);\n }\n return ok({\n schemaVersion: SCENE_PUBLICATION_FENCE_SCHEMA,\n sourcePath: publication.sourcePath,\n sourceRevision: publication.sourceRevision,\n publicationGeneration: publication.generation,\n outputDigest: publication.digest,\n outputSetDigest: publication.outputSetDigest,\n receiptIdentity: receipt.inputFingerprint,\n });\n}\n\n/** Parse the persisted fence without guessing legacy generation or identity. */\nexport function parseScenePublicationFence(\n value: unknown,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n if (\n !isRecord(value) ||\n value.schemaVersion !== SCENE_PUBLICATION_FENCE_SCHEMA ||\n typeof value.sourcePath !== 'string' ||\n typeof value.sourceRevision !== 'string' ||\n !Number.isSafeInteger(value.publicationGeneration) ||\n (value.publicationGeneration as number) < 1 ||\n typeof value.outputDigest !== 'string' ||\n typeof value.outputSetDigest !== 'string' ||\n typeof value.receiptIdentity !== 'string'\n ) {\n return err(errorFor('publication', 'publication fence shape is incomplete or invalid'));\n }\n const generation = value.publicationGeneration as number;\n return ok(\n Object.freeze({\n schemaVersion: SCENE_PUBLICATION_FENCE_SCHEMA,\n sourcePath: value.sourcePath,\n sourceRevision: value.sourceRevision,\n publicationGeneration: generation,\n outputDigest: value.outputDigest,\n outputSetDigest: value.outputSetDigest,\n receiptIdentity: value.receiptIdentity,\n }),\n );\n}\n\n/** Compare all fence fields; no single generation or GUID may stand in for it. */\nexport function compareScenePublicationFences(\n expected: ScenePublicationFence,\n actual: ScenePublicationFence,\n lastKnownGood?: ScenePublicationFence,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n if (sameFence(expected, actual)) return ok(actual);\n const input = {\n expected,\n actual,\n retryable: true,\n ...(lastKnownGood === undefined ? {} : { lastKnownGood }),\n };\n return err(\n errorFor('observation', 'publication fence does not match the expected complete tuple', input),\n );\n}\n\n/** Derive a fence only when every Catalog row for the source publication is present and aligned. */\nexport function scenePublicationFenceFromCatalog(\n entries: readonly CatalogEntry[],\n outputGuid: string,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n const row = entries.find((entry) => entry.guid.toLowerCase() === outputGuid.toLowerCase());\n const publication = row?.publication;\n if (publication === undefined) {\n return err(errorFor('catalog', 'Catalog row has no complete publication tuple'));\n }\n const expected = new Set(publication.outputs.map((output) => output.guid.toLowerCase()));\n const observed = entries.filter((entry) => expected.has(entry.guid.toLowerCase()));\n if (\n observed.length !== expected.size ||\n observed.some(\n (entry) =>\n entry.publication?.sourcePath !== publication.sourcePath ||\n entry.publication?.generation !== publication.generation ||\n entry.publication?.digest !== publication.digest ||\n entry.publication?.outputSetDigest !== publication.outputSetDigest,\n )\n ) {\n return err(\n errorFor('catalog', 'Catalog does not contain one complete publication tuple', {\n publication,\n }),\n );\n }\n return createScenePublicationFence(publication);\n}\n\nexport async function observeScenePublication(input: {\n readonly publication: AssetPublicationEnvelope;\n readonly waitForOutput: (guid: string) => Promise<void>;\n readonly timeoutMs?: number;\n readonly lastKnownGood?: ScenePublicationFence;\n}): Promise<Result<ScenePublicationObservation, ScenePublicationFenceError>> {\n const created = createScenePublicationFence(input.publication);\n if (!created.ok) return created;\n const timeoutMs = input.timeoutMs ?? 5_000;\n const wait = Promise.all(\n input.publication.outputs.map((output) => input.waitForOutput(output.guid)),\n );\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n wait,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('publication-observation-timeout')), timeoutMs);\n }),\n ]);\n } catch {\n const failureInput = {\n publication: input.publication,\n actual: created.value,\n retryable: true,\n ...(input.lastKnownGood === undefined ? {} : { lastKnownGood: input.lastKnownGood }),\n };\n return err(\n errorFor(\n 'observation',\n 'publication output observation did not complete before the fence deadline',\n failureInput,\n ),\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n return ok({\n fence: created.value,\n outputs: input.publication.outputs.map((output) => output.guid),\n });\n}\n","// @forgeax/engine-assets-runtime -- scene instantiate collaboration module\n// (feat-20260705-runtime-tier2-decomposition M1 / w6, D-4 + D-1). Free functions\n// taking the AssetRegistry instance as first param; logic byte-preserved from the\n// class body (this. -> registry.). Hosts the SkinJointResolver + PostSpawnHook\n// hook-contract types relocated from scene-instances/post-spawn-resolve-joints.ts\n// (D-1); w9 wires PostSpawnHook into the AssetRegistry constructor.\n\nimport type { EcsError, EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { PackError } from '@forgeax/engine-pack/errors';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { err, ok, type Result } from '@forgeax/engine-rhi';\nimport {\n worldDespawnScene,\n worldInstantiateScene,\n worldInstantiateSceneFlat,\n worldSetSceneAssetResolver,\n} from '@forgeax/engine-scene';\nimport {\n type Asset,\n type AssetEnvelope,\n AssetError,\n type CatalogEntry,\n type Handle,\n type MountOverride,\n PACK_ERROR_HINTS,\n type SceneAsset,\n type SceneInstanceMount,\n type SkeletonAsset,\n type SkinAsset,\n type TagOf,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry } from '../asset-registry';\nimport { resolveAssetHandle } from '../resolve-asset-handle';\nimport {\n extractMountOverrideHandleGuids,\n extractSceneEntityHandleGuids,\n} from '../scene-handle-fields';\nimport {\n compareScenePublicationFences,\n parseScenePublicationFence,\n type ScenePublicationFence,\n type ScenePublicationFenceError,\n scenePublicationFenceFromCatalog,\n} from './scene-publication-fence';\n\n/**\n * Resolver contract consumed by {@link postSpawnResolveJoints} (D-1: relocated\n * here from scene-instances/post-spawn-resolve-joints.ts so the hook contract\n * travels with the instantiate cluster into @forgeax/engine-assets-runtime).\n */\nexport interface SkinJointResolver {\n resolveSkinAsset(skeletonHandleRaw: number): SkinAsset | undefined;\n}\n\nfunction catalogSourceGuidForFence(\n registry: AssetRegistry,\n expected: ScenePublicationFence,\n): string | undefined {\n const entries = catalogEntriesForFence(registry);\n for (const entry of entries) {\n if (entry.kind !== 'scene') continue;\n const current = scenePublicationFenceFromCatalog(entries, entry.guid);\n if (current.ok && compareScenePublicationFences(expected, current.value).ok) {\n return entry.guid;\n }\n }\n return undefined;\n}\n\n/** Merge the live Edit Catalog and the Play pack-index projection for fences. */\nfunction catalogEntriesForFence(registry: AssetRegistry): readonly CatalogEntry[] {\n const byGuid = new Map<string, CatalogEntry>();\n for (const entry of registry.catalogSnapshot()?.entries ?? []) {\n byGuid.set(entry.guid.toLowerCase(), entry);\n }\n for (const [guid, record] of registry.packIndexCache ?? []) {\n if (record.sourcePath === undefined) continue;\n const candidate = { ...record, guid, sourcePath: record.sourcePath } as CatalogEntry;\n const current = byGuid.get(guid.toLowerCase());\n if (\n current === undefined ||\n (current.publication === undefined && candidate.publication !== undefined)\n ) {\n byGuid.set(guid.toLowerCase(), candidate);\n }\n }\n return [...byGuid.values()];\n}\n\n/**\n * Post-spawn hook contract (D-1). A hook runs after instantiate spawns the\n * scene subtree; the shipped implementation is runtime's `postSpawnResolveJoints`\n * (auto-wire Skin.joints). Injected at the sole production assembly point\n * (createRenderer) in w9/w10; when absent, instantiate skips joint wiring.\n */\nexport type PostSpawnHook = (\n world: World,\n resolver: SkinJointResolver,\n root: EntityHandle,\n) => { ok: true } | { ok: false; error: unknown };\n\n/**\n * Remove the entities and producer grants created by one instantiate call.\n *\n * GUID fields use World interning, so an interned handle is released only when\n * its producer grant is the last live reference. A failed scene has no live\n * holders after `despawnScene`; a handle retained by an unrelated sibling is\n * therefore left untouched. Fresh scene and nested-scene alloc grants are\n * always released after their spawned holders are gone.\n */\nfunction rollbackSpawn(\n world: World,\n roots: readonly EntityHandle[],\n allocHandles: readonly number[],\n internedHandles: readonly number[],\n sharedRefBaseline: number,\n): void {\n for (const root of new Set(roots)) {\n void worldDespawnScene(world, root);\n }\n\n for (const raw of new Set(allocHandles)) {\n const handle = raw as never;\n if (world.sharedRefs.refcount(handle) > 0) void world.sharedRefs.release(handle);\n }\n\n for (const raw of new Set(internedHandles)) {\n if (world.sharedRefs._liveCount() <= sharedRefBaseline) break;\n const handle = raw as never;\n if (world.sharedRefs.refcount(handle) === 1) void world.sharedRefs.release(handle);\n }\n}\n\n/**\n * Materialise a `SceneAsset` into an existing `World` and return the\n * synthetic root `Entity` (feat-20260514 w31 sugar wrapper; AC-03 +\n * requirements §IN-3; M3: returns Entity not SceneInstanceId).\n *\n * Before spawning, handle-type component fields (e.g. `assetHandle`,\n * `material`, `skeleton`) containing GUID strings are resolved to fresh\n * user-tier `Handle` numbers via `world.allocSharedRef` (feat-20260614 M8\n * D-19 instantiate-time GUID->handle mint; supersedes the pre-D-17\n * `resolveGuid` map). GUIDs that fail to parse or are not catalogued return\n * `AssetError(code='asset-not-found')` with a hint containing the GUID,\n * node localId, and field name.\n *\n * Errors propagate verbatim through the closed\n * `AssetError | PackError | EcsError` union so AI users that already\n * narrow `loadByGuid<SceneAsset>` results reuse the same `switch\n * (err.code)` exhaustively (charter proposition 3 machine-readable\n * union; plan-strategy §3.3 closed-union transparency).\n *\n * @example\n * ```ts\n * const sceneRes = await engine.assets.loadByGuid<SceneAsset>(roomGuid); // payload (D-17)\n * if (!sceneRes.ok) return;\n * const handle = world.allocSharedRef('SceneAsset', sceneRes.value); // mint column handle\n * const r = engine.assets.instantiate(handle, world);\n * if (!r.ok) {\n * switch (r.error.code) {\n * case 'asset-not-found':\n * case 'pack-cyclic-reference':\n * // ... AssetErrorCode | PackErrorCode | EcsErrorCode exhaustive\n * }\n * }\n * ```\n */\nexport function instantiate<T extends SceneAsset>(\n registry: AssetRegistry,\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent?: EntityHandle,\n expectedPublication?: ScenePublicationFence,\n): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError> {\n const sharedRefBaseline = world.sharedRefs._liveCount();\n const allocHandles: number[] = [];\n const internedHandles: number[] = [];\n // feat-20260614 M8 (D-15 / D-17): resolve the SceneAsset payload from the\n // handle through the two-tier `resolveAssetHandle` (builtin / user-tier\n // world.sharedRefs) -- the registry holds no handle->payload map. Scene\n // GUID-type component fields are then resolved to fresh user-tier handles\n // via `world.allocSharedRef` (instantiate-time GUID->handle mint). When the\n // handle does not resolve to a scene payload, fall through to the ecs-only\n // path (an externally-resolved SceneAssetResolver handle).\n let instantiateResult: Result<EntityHandle, AssetError | PackError | EcsError>;\n const sceneRes0 = resolveAssetHandle<SceneAsset>(\n world,\n handle as unknown as Handle<string, 'shared'>,\n );\n const sceneAsset = sceneRes0.ok ? sceneRes0.value : undefined;\n if (sceneAsset !== undefined && sceneAsset.kind !== 'scene') {\n return err(\n new AssetError({\n code: 'asset-invalid-value',\n expected: 'instantiate handle resolves to a SceneAsset',\n hint: `resolved asset kind was ${sceneAsset.kind}`,\n }),\n );\n }\n if (sceneAsset !== undefined && sceneAsset.kind === 'scene') {\n // feat-20260622 M3 / w8: find the scene's GUID key in the catalog\n // so _resolveSceneGuids can reverse-decode from envelope.refs edges.\n const sceneGuidKey = registry._guidForAsset(sceneAsset);\n if (expectedPublication !== undefined) {\n const entries = catalogEntriesForFence(registry);\n if (sceneGuidKey === undefined) {\n return err({\n code: 'asset-generation-fence-mismatch',\n phase: 'instantiate',\n hint: 'generated Scene source has no Catalog identity for publication fence validation',\n retryable: true,\n recoveryActions: ['continue-last-known-good', 'retry-rebuild', 'fresh-reopen'],\n } as const);\n }\n const current = scenePublicationFenceFromCatalog(entries, sceneGuidKey);\n if (!current.ok) return current;\n const matches = compareScenePublicationFences(expectedPublication, current.value);\n if (!matches.ok) return matches;\n }\n const guidToHandle = new Map<string, number>();\n const resolvedSceneHandles = new Map<string, number>();\n const sceneRes = registry._resolveSceneGuids(\n sceneAsset,\n world,\n sceneGuidKey,\n undefined,\n guidToHandle,\n resolvedSceneHandles,\n );\n if (!sceneRes.ok) {\n rollbackSpawn(\n world,\n [],\n [...resolvedSceneHandles.values()],\n [...guidToHandle.values()],\n sharedRefBaseline,\n );\n return sceneRes;\n }\n internedHandles.push(...guidToHandle.values());\n allocHandles.push(...resolvedSceneHandles.values());\n\n // feat-20260703 M1 (D-1): register the resolved copy -> original\n // catalog GUID in the origin reverse-index so _guidForAsset can\n // find it even after the local sceneGuidKey variable is discarded.\n if (sceneGuidKey !== undefined) {\n registry._originIndex.set(sceneRes.value, sceneGuidKey);\n }\n\n // Register the GUID-resolved SceneAsset as a shared ref so\n // Scene owner resolves it transparently. The shared\n // ref alloc-grant rc=1 stays held by the alloc; the SceneInstance spawn\n // retains to rc=2 and the despawn path releases back to rc=1.\n const sharedHandle = world.allocSharedRef('SceneAsset', sceneRes.value);\n allocHandles.push(unwrapHandle(sharedHandle));\n\n // m3-i3: wire identity resolver so mount.source already resolved\n // to a live handle number by _resolveMountsRec passes through.\n // Scene mount resolution calls this resolver; when source is a number (live handle),\n // return it as-is; when source is a string (unresolved GUID),\n // fail (should not happen after resolution, but fail-safe).\n worldSetSceneAssetResolver(world, (source, _parentHandle) => {\n if (typeof source === 'number') {\n return ok(source as unknown as Handle<'SceneAsset', 'shared'>);\n }\n return err({\n code: 'asset-not-found' as const,\n expected: `mount source GUID ${source} resolved before instantiate`,\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n });\n });\n\n // C-R2 (feat-20260622-s5 M6): instantiateScene now returns\n // `{ root, diagnostics }` on success. This runtime API keeps its\n // `Result<EntityHandle>` contract; unwrap to `root`. (Surfacing scene\n // unknown-field diagnostics through `assets.instantiate` is M7 README\n // scope — the Scene package owns this boundary.)\n const sceneInst = worldInstantiateScene(world, sharedHandle, parent);\n if (!sceneInst.ok) {\n rollbackSpawn(world, [], allocHandles, internedHandles, sharedRefBaseline);\n return sceneInst as unknown as Result<EntityHandle, AssetError | PackError | EcsError>;\n }\n instantiateResult = ok(sceneInst.value.root);\n } else {\n // Non-resolvable handle: original ecs direct path (backward compat).\n const sceneInst = worldInstantiateScene(\n world,\n handle as Handle<'SceneAsset', 'shared'>,\n parent,\n );\n if (!sceneInst.ok) {\n return sceneInst as unknown as Result<EntityHandle, AssetError | PackError | EcsError>;\n }\n instantiateResult = ok(sceneInst.value.root);\n }\n\n // Post-spawn hook: auto-wire Skin.joints from jointPaths. feat-20260614 M8\n // (D-15): the Skin column holds a user-tier SkeletonAsset handle; resolve\n // it to the payload via the two-tier `resolveAssetHandle`, then match the\n // catalogued SkinAsset whose resolved skeleton payload is the same object\n // (the registry holds no handle->guid index).\n //\n // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): the hook is\n // injected via `registry.postSpawnHook` (the sole production assembly point\n // createRenderer wires `postSpawnResolveJoints`). When no hook is present\n // (standalone / test registries without joint-wiring needs), instantiate\n // skips the post-spawn wiring silently -- the resolver closure below stays\n // inline (it reads registry-internal state: assetCatalog / _guidForAsset).\n const hook = registry.postSpawnHook;\n if (hook !== undefined) {\n const self = registry;\n const resolver: SkinJointResolver = {\n resolveSkinAsset(skeletonHandleRaw: number) {\n const skelRes = resolveAssetHandle<SkeletonAsset>(\n world,\n skeletonHandleRaw as unknown as Handle<string, 'shared'>,\n );\n if (!skelRes.ok) return undefined;\n const skeletonPayload = skelRes.value as Asset;\n const skeletonGuid = self._guidForAsset(skeletonPayload);\n if (skeletonGuid === undefined) return undefined;\n for (const [, envelope] of self.assetCatalog) {\n const asset = envelope.payload;\n if (asset.kind !== 'skin') continue;\n const skinSkeletonGuid = asset.skeletonGuid;\n if (skinSkeletonGuid === undefined) continue;\n if (skinSkeletonGuid.toLowerCase() === skeletonGuid) {\n return asset;\n }\n }\n return undefined;\n },\n };\n const jointResolveResult = hook(world, resolver, instantiateResult.value);\n if (!jointResolveResult.ok) {\n rollbackSpawn(\n world,\n [instantiateResult.value],\n allocHandles,\n internedHandles,\n sharedRefBaseline,\n );\n return { ok: false, error: jointResolveResult.error } as unknown as Result<\n EntityHandle,\n AssetError | PackError | EcsError\n >;\n }\n }\n\n return instantiateResult;\n}\n\n/**\n * Materialise a `SceneAsset` FLAT into an existing `World` — the \"edit the\n * scene itself\" registry entry (#655). Shares the GUID-resolution + shared-ref +\n * SceneAssetResolver prelude with {@link instantiate}, but calls\n * `worldInstantiateSceneFlat` instead of `worldInstantiateScene`: NO synthetic\n * SceneInstance root, NO forced `ChildOf` on top-level members. The scene's own\n * entities become plain top-level world entities; nested prefabs (`mounts[]`)\n * still become their own SceneInstance anchors. Returns the set of top-level\n * entity handles.\n *\n * Use this to OPEN a scene for authoring; use {@link instantiate} (anchor) at\n * runtime / Play and for nested prefabs.\n *\n * The post-spawn Skin.joints hook (when wired via `registry.postSpawnHook`)\n * runs once per top-level root: each GLB root keeps its own `ChildOf` subtree,\n * so joint resolution is scoped to each subtree exactly as the anchor path\n * scopes it to the single synthetic root.\n */\nexport function instantiateFlat<T extends SceneAsset>(\n registry: AssetRegistry,\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n expectedPublication?: ScenePublicationFence,\n): Result<EntityHandle[], AssetError | PackError | EcsError | ScenePublicationFenceError> {\n const sharedRefBaseline = world.sharedRefs._liveCount();\n const allocHandles: number[] = [];\n const internedHandles: number[] = [];\n let roots: EntityHandle[];\n let mountEntities: EntityHandle[];\n const sceneRes0 = resolveAssetHandle<SceneAsset>(\n world,\n handle as unknown as Handle<string, 'shared'>,\n );\n const sceneAsset = sceneRes0.ok ? sceneRes0.value : undefined;\n if (sceneAsset !== undefined && sceneAsset.kind === 'scene') {\n const sceneGuidKey = registry._guidForAsset(sceneAsset);\n if (expectedPublication !== undefined) {\n const entries = catalogEntriesForFence(registry);\n if (sceneGuidKey === undefined) {\n return err({\n code: 'asset-generation-fence-mismatch',\n phase: 'instantiate',\n hint: 'generated Scene source has no Catalog identity for publication fence validation',\n retryable: true,\n recoveryActions: ['continue-last-known-good', 'retry-rebuild', 'fresh-reopen'],\n } as const);\n }\n const current = scenePublicationFenceFromCatalog(entries, sceneGuidKey);\n if (!current.ok) return current;\n const matches = compareScenePublicationFences(expectedPublication, current.value);\n if (!matches.ok) return matches;\n }\n const guidToHandle = new Map<string, number>();\n const resolvedSceneHandles = new Map<string, number>();\n const sceneRes = registry._resolveSceneGuids(\n sceneAsset,\n world,\n sceneGuidKey,\n undefined,\n guidToHandle,\n resolvedSceneHandles,\n );\n if (!sceneRes.ok) {\n rollbackSpawn(\n world,\n [],\n [...resolvedSceneHandles.values()],\n [...guidToHandle.values()],\n sharedRefBaseline,\n );\n return sceneRes;\n }\n internedHandles.push(...guidToHandle.values());\n allocHandles.push(...resolvedSceneHandles.values());\n if (sceneGuidKey !== undefined) {\n registry._originIndex.set(sceneRes.value, sceneGuidKey);\n }\n const sharedHandle = world.allocSharedRef('SceneAsset', sceneRes.value);\n allocHandles.push(unwrapHandle(sharedHandle));\n worldSetSceneAssetResolver(world, (source, _parentHandle) => {\n if (typeof source === 'number') {\n return ok(source as unknown as Handle<'SceneAsset', 'shared'>);\n }\n return err({\n code: 'asset-not-found' as const,\n expected: `mount source GUID ${source} resolved before instantiate`,\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n });\n });\n const sceneInst = worldInstantiateSceneFlat(world, sharedHandle);\n if (!sceneInst.ok) {\n rollbackSpawn(world, [], allocHandles, internedHandles, sharedRefBaseline);\n return sceneInst as unknown as Result<EntityHandle[], AssetError | PackError | EcsError>;\n }\n roots = sceneInst.value.roots;\n mountEntities = sceneInst.value.mountEntities;\n } else {\n const sceneInst = worldInstantiateSceneFlat(world, handle as Handle<'SceneAsset', 'shared'>);\n if (!sceneInst.ok) {\n return sceneInst as unknown as Result<EntityHandle[], AssetError | PackError | EcsError>;\n }\n roots = sceneInst.value.roots;\n mountEntities = sceneInst.value.mountEntities;\n }\n\n // Post-spawn Skin.joints wiring, per top-level root. Mirrors the anchor\n // path's hook (D-1: injected via `registry.postSpawnHook`); when no hook is\n // present the flat path skips joint wiring silently.\n const hook = registry.postSpawnHook;\n if (hook !== undefined) {\n const self = registry;\n const resolver: SkinJointResolver = {\n resolveSkinAsset(skeletonHandleRaw: number) {\n const skelRes = resolveAssetHandle<SkeletonAsset>(\n world,\n skeletonHandleRaw as unknown as Handle<string, 'shared'>,\n );\n if (!skelRes.ok) return undefined;\n const skeletonPayload = skelRes.value as Asset;\n const skeletonGuid = self._guidForAsset(skeletonPayload);\n if (skeletonGuid === undefined) return undefined;\n for (const [, envelope] of self.assetCatalog) {\n const asset = envelope.payload;\n if (asset.kind !== 'skin') continue;\n const skinSkeletonGuid = asset.skeletonGuid;\n if (skinSkeletonGuid === undefined) continue;\n if (skinSkeletonGuid.toLowerCase() === skeletonGuid) {\n return asset;\n }\n }\n return undefined;\n },\n };\n const hookRoots = new Set<EntityHandle>(roots);\n for (const mountEntity of mountEntities) hookRoots.add(mountEntity);\n for (const root of hookRoots) {\n const jointResolveResult = hook(world, resolver, root);\n if (!jointResolveResult.ok) {\n rollbackSpawn(\n world,\n [...roots, ...mountEntities],\n allocHandles,\n internedHandles,\n sharedRefBaseline,\n );\n return { ok: false, error: jointResolveResult.error } as unknown as Result<\n EntityHandle[],\n AssetError | PackError | EcsError\n >;\n }\n }\n }\n\n return ok(roots);\n}\n\n/**\n * m3-i2: Recursively resolve mounts[].source GUID strings.\n * Returns a PackError-shaped object on cycle (R-9) or AssetError\n * on child resolution failure.\n *\n * feat-20260713 M3 / w13: also down-drills `mounts[].overrides[].value`,\n * resolving any GUID string bound to a `shared<...>` / `array<shared<...>>`\n * schema field to a live handle (D-2). `guidToHandle` is the caller's per-scene\n * dedup map (shared with the entity-field resolution in `_resolveSceneGuids`) so\n * the same catalogued GUID mints exactly one user-tier handle across entity\n * fields and override values (D-15/D-17 dedup contract); it defaults to a fresh\n * map so standalone callers keep working. Override resolution runs for every\n * mount regardless of `source` branch — an unresolvable GUID fail-fasts here,\n * before any spawn (P3: no half-initialized member).\n */\nexport function resolveMountsRec(\n registry: AssetRegistry,\n mounts: readonly SceneInstanceMount[],\n world: World,\n visited: Set<string>,\n guidToHandle: Map<string, number> = new Map(),\n resolvedSceneHandles: Map<string, number> = new Map(),\n): Result<\n SceneInstanceMount[],\n | AssetError\n | {\n readonly code: 'pack-cyclic-reference';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly code: 'pack-cyclic-reference';\n readonly kind: 'mount-asset';\n readonly cycle: readonly string[];\n };\n }\n | ScenePublicationFenceError\n> {\n const out: SceneInstanceMount[] = [];\n for (const m of mounts) {\n if (m.publicationFence !== undefined) {\n const parsedFence = parseScenePublicationFence(m.publicationFence);\n if (!parsedFence.ok) return parsedFence;\n const handleSourceGuid =\n typeof m.source === 'string'\n ? m.source\n : (() => {\n const resolved = resolveAssetHandle<SceneAsset>(world, m.source as never);\n return resolved.ok && resolved.value.kind === 'scene'\n ? registry._guidForAsset(resolved.value)\n : undefined;\n })();\n const sourceGuid =\n handleSourceGuid ??\n (typeof m.source === 'string'\n ? undefined\n : catalogSourceGuidForFence(registry, parsedFence.value));\n if (sourceGuid === undefined) {\n return err({\n code: 'asset-generation-fence-mismatch',\n phase: 'instantiate',\n hint: 'publication-fenced mount has no source GUID identity for validation',\n expected: parsedFence.value,\n retryable: true,\n recoveryActions: ['continue-last-known-good', 'retry-rebuild', 'fresh-reopen'],\n });\n }\n const currentFence = scenePublicationFenceFromCatalog(\n catalogEntriesForFence(registry),\n sourceGuid,\n );\n if (!currentFence.ok) return currentFence;\n const matches = compareScenePublicationFences(parsedFence.value, currentFence.value);\n if (!matches.ok) return matches;\n }\n let componentPatch:\n | { components: NonNullable<SceneInstanceMount['components']> }\n | Record<string, never> = {};\n if (m.components !== undefined) {\n const resolvedComponents = resolveMountComponents(\n registry,\n world,\n m.components,\n guidToHandle,\n );\n if (!resolvedComponents.ok) return resolvedComponents;\n componentPatch = {\n components: resolvedComponents.value as NonNullable<SceneInstanceMount['components']>,\n };\n }\n // Resolve override value GUIDs first — applies to every mount regardless of\n // the source branch below (a number-source mount can still carry overrides).\n let overridePatch: { overrides: readonly MountOverride[] } | Record<string, never> = {};\n if (m.overrides !== undefined && m.overrides.length > 0) {\n const ro = resolveMountOverrides(registry, world, m.overrides, guidToHandle);\n if (!ro.ok) return ro;\n overridePatch = { overrides: ro.value };\n }\n\n const src = m.source;\n // m3-i3: if source is already a number (live handle from a prior\n // resolution pass), pass through unchanged.\n if (typeof src === 'number') {\n out.push({ ...m, ...componentPatch, ...overridePatch });\n continue;\n }\n\n // source is a GUID string — resolve it.\n const guidKey = src.toLowerCase();\n\n // Cycle detection.\n if (visited.has(guidKey)) {\n return err({\n code: 'pack-cyclic-reference' as const,\n expected: 'no circular mount.source GUID references',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail: {\n code: 'pack-cyclic-reference' as const,\n kind: 'mount-asset' as const,\n cycle: [...visited, guidKey],\n },\n });\n }\n\n // Look up child scene.\n const childEnv = registry.assetCatalog.get(guidKey);\n if (childEnv === undefined) {\n // Not catalogued — pass through as-is (overrides still resolved above).\n out.push({ ...m, ...componentPatch, ...overridePatch });\n continue;\n }\n const childPayload = childEnv.payload;\n if (\n typeof childPayload !== 'object' ||\n childPayload === null ||\n (childPayload as Asset).kind !== 'scene'\n ) {\n out.push({ ...m, ...componentPatch, ...overridePatch });\n continue;\n }\n\n const cachedChildHandle = resolvedSceneHandles.get(guidKey);\n if (cachedChildHandle !== undefined) {\n out.push({\n ...m,\n source: cachedChildHandle,\n ...componentPatch,\n ...overridePatch,\n } as SceneInstanceMount);\n continue;\n }\n\n // Resolve mounts recursively.\n const childVisited = new Set(visited);\n // Don't add guidKey to visited here — _resolveSceneGuids will do it\n // via its own _visitedMountGuids parameter.\n const childRes = registry._resolveSceneGuids(\n childPayload as SceneAsset,\n world,\n guidKey,\n childVisited,\n guidToHandle,\n resolvedSceneHandles,\n true,\n );\n\n if (!childRes.ok) {\n // Propagate child resolution error.\n return childRes as unknown as Result<SceneInstanceMount[], AssetError>;\n }\n\n // Build resolved child with its own mounts.\n const resolvedChild: SceneAsset = {\n kind: 'scene',\n entities: childRes.value.entities,\n ...(childRes.value.mounts !== undefined && childRes.value.mounts.length > 0\n ? { mounts: childRes.value.mounts }\n : {}),\n } as SceneAsset;\n\n // allocSharedRef + register in originIndex (D-7).\n const chRaw = unwrapHandle(world.allocSharedRef('SceneAsset', resolvedChild));\n resolvedSceneHandles.set(guidKey, chRaw);\n registry._originIndex.set(resolvedChild, guidKey);\n\n // Replace source with live handle number (D-5: source is number|string).\n out.push({\n ...m,\n source: chRaw,\n ...componentPatch,\n ...overridePatch,\n } as SceneInstanceMount);\n }\n return ok(out);\n}\n\nfunction resolveMountComponents(\n registry: AssetRegistry,\n world: World,\n components: NonNullable<SceneInstanceMount['components']>,\n guidToHandle: Map<string, number>,\n): Result<Record<string, Record<string, unknown>>, AssetError> {\n const source = components as Record<string, Record<string, unknown>>;\n const output: Record<string, Record<string, unknown>> = {};\n for (const [componentName, fields] of Object.entries(source))\n output[componentName] = { ...fields };\n const entries = extractSceneEntityHandleGuids(world.components.entries(), [\n { localId: 0, components: source },\n ]);\n for (const entry of entries) {\n const fieldPath =\n `${entry.componentName}.${entry.fieldName}` +\n (entry.arrayIndex === undefined ? '' : `[${entry.arrayIndex}]`);\n const resolved = resolveHandleGuid(\n registry,\n world,\n entry.guidString,\n guidToHandle,\n fieldPath,\n 'mount.components',\n );\n if (!resolved.ok) return resolved;\n const fields = output[entry.componentName];\n if (fields === undefined) continue;\n if (entry.arrayIndex === undefined) {\n fields[entry.fieldName] = resolved.value;\n continue;\n }\n const current = fields[entry.fieldName];\n if (!Array.isArray(current)) continue;\n const next = [...current];\n next[entry.arrayIndex] = resolved.value;\n fields[entry.fieldName] = next;\n }\n return ok(output);\n}\n\n/**\n * Resolve one GUID string to a live user-tier handle (feat-20260713 M3 / w13\n * SSOT). Parses the GUID, uses `guidToHandle` as the per-resolution fast path,\n * and on a miss looks the envelope up in the catalog + interns its shared ref\n * by `(target, payload identity)` in the World. An unparseable / uncatalogued\n * GUID returns `AssetError(code='asset-not-found')` with a breadcrumb hint\n * (`fieldPath` + `location`) for AI-user debuggability (P3). Shared by the\n * entity-field fallback in `_resolveSceneGuids` and the override-value down-drill\n * in {@link resolveMountOverrides} so the parse/dedup/lookup/mint idiom has one\n * home (architecture-principles §1 SSOT).\n */\nexport function resolveHandleGuid(\n registry: AssetRegistry,\n world: World,\n guidString: string,\n guidToHandle: Map<string, number>,\n fieldPath: string,\n location: string,\n): Result<number, AssetError> {\n const guidRes = AssetGuid.parse(guidString);\n if (!guidRes.ok) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `valid GUID string for field ${fieldPath}`,\n hint: `GUID \"${guidString}\" could not be parsed; at ${location}, field=${fieldPath}`,\n }),\n );\n }\n const guidKey = guidString.toLowerCase();\n let slot = guidToHandle.get(guidKey);\n if (slot === undefined) {\n const envelope = registry.assetCatalog.get(guidKey);\n if (envelope === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidString} catalogued in AssetRegistry`,\n hint:\n `GUID ${guidString} not catalogued; ` +\n `call loadByGuid('${guidString}') before instantiate; ` +\n `at ${location}, field=${fieldPath}`,\n }),\n );\n }\n slot = unwrapHandle(world.internSharedRef(envelope.payload.kind, envelope.payload));\n guidToHandle.set(guidKey, slot);\n }\n return ok(slot);\n}\n\n/**\n * feat-20260713 M3 / w13: resolve every GUID string inside a mount's\n * `overrides[].value` to a live handle, returning a new overrides array whose\n * shared fields hold numeric handles (D-2 — the ecs apply loop never sees a\n * GUID). Identification is delegated to the shared w12 core\n * ({@link extractMountOverrideHandleGuids}); resolution reuses the\n * `envelope.payload → world.internSharedRef` path with the caller's\n * `guidToHandle` fast path (D-15/D-17). Stop-on-first-error: an unparseable /\n * uncatalogued GUID\n * returns `AssetError(code='asset-not-found')` with a breadcrumb hint (P3),\n * aborting before any spawn. Number elements pass through untouched (D-8).\n */\nfunction resolveMountOverrides(\n registry: AssetRegistry,\n world: World,\n overrides: readonly MountOverride[],\n guidToHandle: Map<string, number>,\n): Result<MountOverride[], AssetError> {\n const entries = extractMountOverrideHandleGuids(world.components.entries(), overrides);\n if (entries.length === 0) return ok([...overrides]);\n\n // resolvedMap key: `${overrideIndex}|${fieldName}|${arrayIndex ?? ''}`.\n const resolvedMap = new Map<string, number>();\n for (const entry of entries) {\n const fieldPath =\n `${entry.componentName}.${entry.fieldName}` +\n (entry.arrayIndex !== undefined ? `[${entry.arrayIndex}]` : '');\n const slot = resolveHandleGuid(\n registry,\n world,\n entry.guidString,\n guidToHandle,\n fieldPath,\n `mount override index=${entry.overrideIndex}`,\n );\n if (!slot.ok) return slot;\n resolvedMap.set(\n overrideFieldKey(entry.overrideIndex, entry.fieldName, entry.arrayIndex),\n slot.value,\n );\n }\n\n // Reconstruct: substitute resolved handles back into each override's value.\n const out: MountOverride[] = [];\n for (let ovIdx = 0; ovIdx < overrides.length; ovIdx++) {\n out.push(reconstructOverride(overrides[ovIdx] as MountOverride, ovIdx, resolvedMap));\n }\n return ok(out);\n}\n\n/** resolvedMap key for a resolved override handle. */\nfunction overrideFieldKey(overrideIndex: number, fieldName: string, arrayIndex?: number): string {\n return `${overrideIndex}|${fieldName}|${arrayIndex ?? ''}`;\n}\n\n/**\n * Rebuild one override with its shared-field GUID strings replaced by resolved\n * handles from `resolvedMap`. Preserves object identity when nothing resolved\n * (no shared GUID in this override). Patch form substitutes the single `value`;\n * add form substitutes each key of the value map.\n */\nfunction reconstructOverride(\n ov: MountOverride,\n ovIdx: number,\n resolvedMap: Map<string, number>,\n): MountOverride {\n if (ov.field !== undefined) {\n const nv = reconstructFieldValue(ovIdx, ov.field, ov.value, resolvedMap);\n return nv === ov.value ? ov : { ...ov, value: nv };\n }\n const value = ov.value;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return ov;\n const map = value as Record<string, unknown>;\n let changed = false;\n const next: Record<string, unknown> = {};\n for (const key of Object.keys(map)) {\n const nv = reconstructFieldValue(ovIdx, key, map[key], resolvedMap);\n next[key] = nv;\n if (nv !== map[key]) changed = true;\n }\n return changed ? { ...ov, value: next } : ov;\n}\n\n/**\n * Resolve one field value: a scalar `shared<T>` string becomes its handle; an\n * `array<shared<T>>` becomes an array with resolved handles substituted and\n * already-numeric elements passed through (D-8). Non-shared / unresolved values\n * pass through unchanged (identity preserved).\n */\nfunction reconstructFieldValue(\n ovIdx: number,\n fieldName: string,\n value: unknown,\n resolvedMap: Map<string, number>,\n): unknown {\n const scalar = resolvedMap.get(overrideFieldKey(ovIdx, fieldName));\n if (scalar !== undefined) return scalar;\n if (Array.isArray(value)) {\n const arr: unknown[] = [];\n let anyResolved = false;\n for (let i = 0; i < value.length; i++) {\n const resolved = resolvedMap.get(overrideFieldKey(ovIdx, fieldName, i));\n if (resolved !== undefined) {\n arr.push(resolved);\n anyResolved = true;\n } else {\n arr.push(value[i]);\n }\n }\n return anyResolved ? arr : value;\n }\n return value;\n}\n\n/**\n * tweak-20260609 M1 helper: build the per-sub-ref parent context for a\n * SceneAsset child. feat-20260622 M3 / w9: re-sourced to lookup in the\n * scene envelope's ``refs[]`` edges instead of walking entity components\n * via extractSceneEntityHandleGuids (D-7). When the scene envelope is not\n * found in the catalog, falls back to the entity-walk path (backward compat\n * for call sites that lack a catalogued envelope).\n *\n * Texture edges (sourceField=undefined) produce ``componentField:\n * undefined`` — the breadcrumb will show GUID+kind only, no per-entity\n * detail (D-2: texture has no per-entity origin).\n */\nexport function buildSceneChildContext(\n registry: AssetRegistry,\n scene: Asset & { kind: 'scene' },\n subGuidKey: string,\n sceneGuidKey?: string,\n):\n | {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n }\n | undefined {\n // feat-20260622 M3 / w9: direct lookup in envelope.refs edges.\n // feat-20260622 review r1: address the recursing scene's OWN envelope by\n // its guidKey, not the first scene in the catalog -- under a multi-scene\n // glTF catalog the first-scene scan attributes the breadcrumb to the wrong\n // scene. Fall back to the first-scene scan only when no guidKey is given\n // (legacy call sites lacking a catalogued envelope).\n let sceneEnvelope: AssetEnvelope | undefined;\n if (sceneGuidKey !== undefined) {\n const env = registry.assetCatalog.get(sceneGuidKey);\n if (env?.kind === 'scene') sceneEnvelope = env;\n }\n if (sceneEnvelope === undefined) {\n for (const [, env] of registry.assetCatalog) {\n if (env.kind === 'scene' && env.refs !== undefined && env.refs.length > 0) {\n sceneEnvelope = env;\n break;\n }\n }\n }\n let edgeResult:\n | {\n sceneEntityId?: number;\n componentField?: string;\n }\n | undefined;\n if (sceneEnvelope?.refs !== undefined) {\n for (const ref of sceneEnvelope.refs) {\n if (ref.guid.toLowerCase() === subGuidKey) {\n const { sceneEntityId, sourceField } = ref;\n const result: {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n } = {};\n if (sceneEntityId !== undefined) {\n result.sceneEntityId = sceneEntityId;\n }\n if (sourceField?.componentName !== undefined && sourceField?.fieldName !== undefined) {\n result.componentField =\n `${sourceField.componentName}.${sourceField.fieldName}` +\n (sourceField.arrayIndex !== undefined ? `[${sourceField.arrayIndex}]` : '');\n }\n if (sourceField !== undefined) {\n result.sourceField = sourceField;\n }\n // A rich edge (dev register path) carries full detail — return now.\n if (result.sceneEntityId !== undefined || result.componentField !== undefined) {\n return result;\n }\n // feat-20260622 M4 / w14: a GUID-only edge (prod path: on-disk refs[]\n // strip sourceField / sceneEntityId at the serialization boundary, w7\n // D-10) carries no per-entity detail. Keep this empty-but-defined\n // result as the fallback, then try the entity walk below to recover\n // the entity localId + component.field path (D-7 / B-8). The walk\n // recovers handle-field edges (mesh / material); a texture edge (D-2:\n // no per-entity origin) is not found by the walk, so the empty\n // edgeResult is returned (w10 texture-edge contract preserved).\n edgeResult = result;\n break;\n }\n }\n }\n // Backward compat: fall back to entity walk when the envelope edge carries\n // no per-entity detail (prod path: GUID-only refs[]) or no envelope is\n // available (e.g. direct catalog() registration with scene payload, no refs).\n const entries = extractSceneEntityHandleGuids(\n registry.componentCatalog,\n scene.entities as unknown as ReadonlyArray<{\n readonly localId: number;\n readonly components: Record<string, Record<string, unknown>>;\n }>,\n );\n for (const entry of entries) {\n if (entry.guidString.toLowerCase() === subGuidKey) {\n return {\n sceneEntityId: entry.entityLocalId,\n componentField: `${entry.componentName}.${entry.fieldName}${entry.arrayIndex !== undefined ? `[${entry.arrayIndex}]` : ''}`,\n // feat-20260622 verify r1: also surface the recovered provenance in\n // structured parts so the failure `.detail` can expose them for AI\n // property access (charter P3), not only the concatenated hint string.\n sourceField: {\n componentName: entry.componentName,\n fieldName: entry.fieldName,\n ...(entry.arrayIndex !== undefined ? { arrayIndex: entry.arrayIndex } : {}),\n },\n };\n }\n }\n return edgeResult;\n}\n\n/**\n * tweak-20260609 M1 helper: build the error-hint breadcrumb string\n * containing the parent asset's GUID + kind, enriched with the\n * caller-provided `parentContext` (entity localId + component.field).\n *\n * Per D-7 / B-8: the breadcrumb appears before the sub-asset's own hint,\n * separated by \" / \".\n */\nexport function buildBreadcrumbHint(\n parentGuidKey: string,\n parentKind: string,\n subGuidKey: string,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n): string {\n let breadcrumb = `sub-asset ${subGuidKey} referenced by ${parentKind} ${parentGuidKey}`;\n if (parentContext?.sceneEntityId !== undefined && parentContext?.componentField !== undefined) {\n breadcrumb += ` (entity ${parentContext.sceneEntityId}, field ${parentContext.componentField})`;\n }\n return breadcrumb;\n}\n","import {\n type CookedMaterialRecord,\n createMaterialArtifactDigest,\n validateCookedMaterialRecord,\n} from '@forgeax/engine-pack';\n\nexport interface MaterialLoadRequest {\n readonly guid: string;\n readonly specializationKey: string;\n}\n\nexport interface MaterialReady {\n readonly status: 'Ready';\n readonly guid: string;\n readonly materialGuid: string;\n readonly publicationGeneration: number;\n readonly specializationKey: string;\n readonly artifactDigest: string;\n readonly sourceClosure: readonly string[];\n readonly parameterContract: NonNullable<CookedMaterialRecord['parameterContract']>;\n readonly record: CookedMaterialRecord;\n readonly artifact: CookedMaterialRecord['artifact'];\n}\n\nexport interface MaterialPublication {\n readonly guid: string;\n readonly record: unknown;\n readonly artifactError?: {\n readonly code: 'asset-artifact-missing' | 'asset-artifact-integrity-mismatch';\n readonly expected: string;\n readonly actual?: string;\n };\n readonly artifact?: {\n readonly bytes: Uint8Array;\n readonly digest?: string;\n };\n}\n\nexport type MaterialLoadErrorCode =\n | 'material-specialization-not-cooked'\n | 'asset-artifact-missing'\n | 'asset-artifact-integrity-mismatch'\n | 'material-cook-record-invalid'\n | 'material-reference-not-ready';\n\nexport interface MaterialLoadErrorDetail {\n readonly guid: string;\n readonly specializationKey: string;\n readonly publicationGeneration?: number;\n readonly field?: string;\n readonly missing?: readonly string[];\n readonly expected?: string;\n readonly actual?: string;\n}\n\nexport interface MaterialLoadError {\n readonly status: 'Error';\n readonly error: {\n readonly code: MaterialLoadErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly detail: MaterialLoadErrorDetail;\n };\n}\n\nexport interface MaterialLoaderOptions {\n readonly loadPublication: (\n guid: string,\n specializationKey: string,\n ) => Promise<MaterialPublication | undefined>;\n readonly loadReference?: (guid: string) => Promise<boolean>;\n}\n\nfunction materialError(\n request: MaterialLoadRequest,\n code: MaterialLoadErrorCode,\n expected: string,\n hint: string,\n detail: Omit<MaterialLoadErrorDetail, 'guid' | 'specializationKey'> = {},\n retryable = false,\n): MaterialLoadError {\n return {\n status: 'Error',\n error: {\n code,\n expected,\n hint,\n retryable,\n recoveryActions: retryable ? ['retry-material-load'] : ['recook-material-publication'],\n detail: { guid: request.guid, specializationKey: request.specializationKey, ...detail },\n },\n };\n}\n\nfunction missingCook(request: MaterialLoadRequest): MaterialLoadError {\n return materialError(\n request,\n 'material-specialization-not-cooked',\n 'a cooked material specialization record and artifact',\n 'run the build-time material cooker for this specialization before loading it at runtime',\n {},\n true,\n );\n}\n\nfunction recordError(\n request: MaterialLoadRequest,\n field: string,\n expected = 'a complete material-cook/3 publication record',\n): MaterialLoadError {\n return materialError(\n request,\n 'material-cook-record-invalid',\n expected,\n 're-publish the material record and its artifact as one immutable publication',\n { field },\n );\n}\n\nfunction immutableBytes(bytes: Uint8Array): Uint8Array {\n return new Uint8Array(bytes);\n}\n\nfunction immutableParameterContract(\n parameterContract: NonNullable<CookedMaterialRecord['parameterContract']>,\n): NonNullable<CookedMaterialRecord['parameterContract']> {\n return Object.freeze({\n parameters: Object.freeze([...parameterContract.parameters]),\n values: Object.freeze({ ...parameterContract.values }),\n });\n}\n\nfunction sameBytes(left: Uint8Array, right: Uint8Array): boolean {\n return left.byteLength === right.byteLength && left.every((byte, index) => byte === right[index]);\n}\n\nfunction completeTupleField(record: CookedMaterialRecord): string | undefined {\n if (\n typeof record.materialGuid !== 'string' ||\n !Number.isSafeInteger(record.publicationGeneration) ||\n (record.publicationGeneration as number) < 1\n )\n return 'publicationGeneration';\n if (typeof record.specializationKey !== 'string' || record.specializationKey.length === 0)\n return 'specializationKey';\n if (typeof record.artifactDigest !== 'string' || record.artifactDigest.length === 0)\n return 'artifactDigest';\n if (\n !Array.isArray(record.sourceClosure) ||\n record.sourceClosure.some((path) => typeof path !== 'string' || path.length === 0)\n )\n return 'sourceClosure';\n const parameterContract = record.parameterContract;\n if (\n parameterContract === undefined ||\n !Array.isArray(parameterContract.parameters) ||\n parameterContract.values === null ||\n typeof parameterContract.values !== 'object' ||\n Array.isArray(parameterContract.values)\n )\n return 'parameterContract';\n const receipt = record.receipt;\n if (\n !Array.isArray(receipt.sourceClosure) ||\n receipt.sourceClosure.some((path) => typeof path !== 'string' || path.length === 0) ||\n receipt.sourceClosure.length !== record.sourceClosure.length ||\n receipt.sourceClosure.some((path, index) => path !== record.sourceClosure?.[index])\n )\n return 'receipt.sourceClosure';\n if (\n typeof receipt.profile !== 'string' ||\n receipt.profile.length === 0 ||\n typeof receipt.compilerVersion !== 'string' ||\n receipt.compilerVersion.length === 0 ||\n typeof receipt.identity.cookIdentity !== 'string' ||\n receipt.identity.cookIdentity.length === 0 ||\n receipt.identity.artifactDigest !== record.artifactDigest ||\n receipt.identity.cookGeneration !== record.publicationGeneration\n )\n return 'receipt';\n if (\n typeof receipt.identity.layoutIdentity !== 'string' ||\n receipt.identity.layoutIdentity.length === 0 ||\n receipt.derivedInterface?.layoutIdentity !== receipt.identity.layoutIdentity\n )\n return 'receipt.identity.layoutIdentity';\n if (\n typeof record.artifact.mediaType !== 'string' ||\n record.artifact.mediaType.length === 0 ||\n typeof record.artifact.path !== 'string' ||\n record.artifact.path.length === 0\n )\n return 'artifact';\n return undefined;\n}\n\nexport function createMaterialLoader(options: MaterialLoaderOptions) {\n return {\n async load(request: MaterialLoadRequest): Promise<MaterialReady | MaterialLoadError> {\n const publication = await options.loadPublication(request.guid, request.specializationKey);\n if (publication === undefined) return missingCook(request);\n if (publication.artifactError !== undefined) {\n return materialError(\n request,\n publication.artifactError.code,\n publication.artifactError.expected,\n 'restore the published material artifact and retry the load',\n {\n expected: publication.artifactError.expected,\n ...(publication.artifactError.actual === undefined\n ? {}\n : { actual: publication.artifactError.actual }),\n },\n true,\n );\n }\n const parsed = validateCookedMaterialRecord(publication.record);\n if (!parsed.ok) return recordError(request, parsed.error.detail.field);\n const record = parsed.value;\n const invalidTupleField = completeTupleField(record);\n if (invalidTupleField !== undefined) return recordError(request, invalidTupleField);\n const publicationGeneration = record.publicationGeneration;\n const sourceClosure = record.sourceClosure;\n const parameterContract = record.parameterContract;\n const materialGuid = record.materialGuid;\n const recordSpecializationKey = record.specializationKey;\n const artifactDigest = record.artifactDigest;\n if (publicationGeneration === undefined) return recordError(request, 'publicationGeneration');\n if (sourceClosure === undefined) return recordError(request, 'sourceClosure');\n if (parameterContract === undefined) return recordError(request, 'parameterContract');\n if (materialGuid === undefined) return recordError(request, 'materialGuid');\n if (recordSpecializationKey === undefined) return recordError(request, 'specializationKey');\n if (artifactDigest === undefined) return recordError(request, 'artifactDigest');\n if (\n publication.guid.toLowerCase() !== request.guid.toLowerCase() ||\n record.guid.toLowerCase() !== request.guid.toLowerCase()\n ) {\n return recordError(\n request,\n 'guid',\n `record GUID ${request.guid} to match the requested GUID`,\n );\n }\n if (materialGuid.toLowerCase() !== request.guid.toLowerCase())\n return recordError(request, 'materialGuid');\n if (recordSpecializationKey !== request.specializationKey) return missingCook(request);\n if (publication.artifact === undefined) {\n return materialError(\n request,\n 'asset-artifact-missing',\n `published artifact for material ${request.guid}`,\n 'publish the immutable material artifact before loading the specialization',\n { publicationGeneration },\n true,\n );\n }\n const artifactBytes = immutableBytes(publication.artifact.bytes);\n const actualDigest = createMaterialArtifactDigest(artifactBytes);\n if (\n actualDigest !== artifactDigest ||\n (publication.artifact.digest !== undefined && publication.artifact.digest !== actualDigest)\n ) {\n return materialError(\n request,\n 'asset-artifact-integrity-mismatch',\n `artifact digest ${artifactDigest}`,\n 'restore the published artifact bytes or re-publish the matching material record',\n {\n publicationGeneration,\n expected: artifactDigest,\n actual: actualDigest,\n },\n );\n }\n if (!sameBytes(record.artifact.bytes, artifactBytes)) {\n return recordError(\n request,\n 'artifact.bytes',\n 'record artifact bytes to match the published artifact bytes',\n );\n }\n const refs = [\n ...record.refs.parent,\n ...record.refs.textures,\n ...record.refs.samplers,\n ...record.refs.modules,\n ];\n const missing = options.loadReference\n ? (\n await Promise.all(\n refs.map(async (reference) =>\n (await options.loadReference?.(reference)) ? undefined : reference,\n ),\n )\n ).filter((reference): reference is string => reference !== undefined)\n : [];\n if (missing.length > 0) {\n return materialError(\n request,\n 'material-reference-not-ready',\n 'all cooked material references to be available',\n 'load referenced parent, texture, sampler, and module assets before publishing Ready',\n { publicationGeneration, missing },\n true,\n );\n }\n return {\n status: 'Ready',\n guid: request.guid,\n materialGuid,\n publicationGeneration,\n specializationKey: request.specializationKey,\n artifactDigest,\n sourceClosure: Object.freeze([...sourceClosure]),\n parameterContract: immutableParameterContract(parameterContract),\n record,\n artifact: Object.freeze({\n ...record.artifact,\n bytes: artifactBytes,\n }),\n };\n },\n };\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport { ASSET_ERROR_HINTS, AssetError, type CatalogProjection } from '@forgeax/engine-types';\nimport type { CatalogRecord } from './catalog';\n\nexport interface RuntimeProjection {\n readonly subject: CatalogProjection['subject'];\n readonly execution: CatalogProjection['execution'];\n readonly lifecycle: CatalogProjection['lifecycle'];\n readonly packageUrl: string;\n}\n\nfunction projectionError(guid: string, expected: string): AssetError {\n return new AssetError({\n code: 'asset-not-imported',\n expected,\n hint: `${ASSET_ERROR_HINTS['asset-not-imported']} (GUID ${guid})`,\n });\n}\n\n/**\n * Resolve the producer-declared runtime projection. Legacy rows return\n * undefined so inline/dev assets retain their existing registration path;\n * rows that publish any projection axis must publish all three axes.\n */\nexport function resolveRuntimeProjection(\n guid: string,\n record: CatalogRecord,\n): Result<RuntimeProjection | undefined, AssetError> {\n const hasAxes =\n record.subject !== undefined ||\n record.execution !== undefined ||\n record.lifecycle !== undefined ||\n record.projection !== undefined;\n if (!hasAxes) return ok(undefined);\n\n const projection = record.projection;\n if (\n projection === undefined ||\n record.subject === undefined ||\n record.execution === undefined ||\n record.lifecycle === undefined\n ) {\n return err(\n projectionError(\n guid,\n 'catalog entry to publish subject, execution, lifecycle, and projection together',\n ),\n );\n }\n if (\n projection.subject !== record.subject ||\n projection.execution !== record.execution ||\n projection.lifecycle !== record.lifecycle\n ) {\n return err(projectionError(guid, 'catalog projection axes to agree with their row fields'));\n }\n return ok({\n subject: projection.subject,\n execution: projection.execution,\n lifecycle: projection.lifecycle,\n packageUrl: record.packageUrl,\n });\n}\n","// @forgeax/engine-assets-runtime -- load-by-guid + pack-fetch collaboration module\n// (feat-20260705-runtime-tier2-decomposition M1 / w7, D-4). Free functions\n// taking the AssetRegistry instance as first param; logic byte-preserved from the\n// class body (this. -> registry.). This is the largest method cluster (loadByGuid\n// + the DDC / pack-index / pack-file fetch + parse pipeline).\n\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { err, ok, type Result, type RhiError } from '@forgeax/engine-rhi';\nimport { isEngineMaterial } from '@forgeax/engine-shader';\nimport {\n type ArtifactDescriptor,\n ASSET_ERROR_HINTS,\n type Asset,\n type AssetCompression,\n AssetError,\n type AssetErrorCode,\n type AssetErrorDetail,\n type AssetRef,\n type CatalogSubject,\n type ImageError,\n type ImageMetadata,\n type LoadContext,\n type LoaderAsyncResult,\n type MaterialAsset,\n type MeshAsset,\n type ParseErrorDetail,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry, ParsedPackFile } from '../asset-registry';\nimport {\n createMaterialLoader,\n type MaterialLoadError,\n type MaterialLoadRequest,\n type MaterialPublication,\n type MaterialReady,\n} from '../material/loader';\nimport { readArtifact } from './artifact-io';\nimport { fetchPackIndex, resolveCatalogAssetUrl } from './catalog';\nimport { buildBreadcrumbHint, buildSceneChildContext } from './instantiate';\nimport { resolveRuntimeProjection } from './runtime-projection';\n\n/**\n * Load an asset and all its transitively referenced sub-assets by GUID;\n * returns `ok(handle)` only when the asset and every sub-asset are in the\n * registry.\n *\n * **Post-condition:** `ok(payload)` is returned ONLY when the asset AND every\n * transitively referenced sub-asset (per the asset envelope's `refs[]`) are\n * present in this registry. The implementation walks `envelope.refs` and\n * recursively calls `loadByGuid` on each ref before cataloguing the top-level\n * asset. The resolved value is the PAYLOAD `T`\n * (D-17), never a handle -- mint a column handle with\n * `world.allocSharedRef('Kind', payload)` when one is needed (e.g. before\n * `instantiate`).\n *\n * Two paths:\n * - **Dev / fallback** (no `configurePackIndex` call): synchronous catalogue\n * lookup wrapped in `Promise.resolve`. Returns `Err(asset-not-found)` if not\n * catalogued.\n * - **Prod** (after `configurePackIndex(url)`): fetches `pack-index.json`\n * on the first call (cached as a `Map<guid, {packageUrl, kind}>`), then\n * fetches the individual resource URL and parses the asset payload, then\n * catalogues it (GUID -> payload) and returns the payload.\n *\n * Error union: `AssetError | PackError | ImageError | RhiError` (closed -- no\n * new codes were introduced by the recursive walk; every code is pre-existing).\n *\n * An in-flight `Map` (D-5) deduplicates concurrent calls for the same GUID and\n * prevents stack overflow on cycles (A->B->A).\n *\n * **Breaking-change classification:** this is a semantic strengthening, not a\n * shape change. Sub-assets catalogued by a prior `catalog(guid, payload)` /\n * `loadByGuid` call are protected by the catalogue fast-path: the recursive\n * walk hits cache on every node and incurs zero additional fetch.\n *\n * @example\n * ```ts\n * const res = await engine.assets.loadByGuid<SceneAsset>(sceneGuid);\n * if (!res.ok) {\n * switch (res.error.code) {\n * case 'asset-not-found':\n * // top GUID or any sub-asset GUID is missing from the catalog\n * break;\n * case 'asset-fetch-failed':\n * // network / CORS\n * break;\n * case 'asset-parse-failed':\n * // payload malformed\n * break;\n * // ... AssetErrorCode | PackErrorCode | ImageErrorCode | RhiErrorCode exhaustive\n * }\n * return;\n * }\n * ```\n */\nexport async function loadByGuid<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n return loadByGuidInternal(registry, guid, parentContext, new Set());\n}\n\nfunction cookedRecordFromPayload(payload: Record<string, unknown>): unknown {\n if (payload.schemaVersion === 'material-cook/3') return payload;\n if (payload.cooked !== null && typeof payload.cooked === 'object') return payload.cooked;\n if (payload.record !== null && typeof payload.record === 'object') return payload.record;\n return undefined;\n}\n\nfunction materialArtifactKey(\n record: Record<string, unknown> | undefined,\n descriptors: Readonly<Record<string, ArtifactDescriptor>>,\n): string | undefined {\n const artifact = record?.artifact;\n const path =\n artifact !== null && typeof artifact === 'object' && 'path' in artifact\n ? (artifact as { readonly path?: unknown }).path\n : undefined;\n if (typeof path === 'string') {\n const match = Object.entries(descriptors).find(([, descriptor]) => descriptor.path === path);\n if (match !== undefined) return match[0];\n }\n const shaderArtifacts = Object.entries(descriptors).filter(\n ([, descriptor]) => descriptor.mediaType === 'text/wgsl',\n );\n return shaderArtifacts.length === 1 ? shaderArtifacts[0]?.[0] : undefined;\n}\n\nfunction materialRecordPath(descriptor: ArtifactDescriptor): string {\n return `${descriptor.path}.record.json`;\n}\n\nfunction inlineMaterialArtifact(\n record: Record<string, unknown> | undefined,\n): MaterialPublication['artifact'] | undefined {\n const artifact = record?.artifact;\n if (artifact === null || typeof artifact !== 'object' || Array.isArray(artifact)) {\n return undefined;\n }\n const bytes = (artifact as { readonly bytes?: unknown }).bytes;\n const normalizedBytes =\n bytes instanceof Uint8Array\n ? new Uint8Array(bytes)\n : Array.isArray(bytes) &&\n bytes.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255)\n ? Uint8Array.from(bytes)\n : undefined;\n if (normalizedBytes === undefined) return undefined;\n const digest = (artifact as { readonly digest?: unknown }).digest;\n return {\n bytes: normalizedBytes,\n ...(typeof digest === 'string' ? { digest } : {}),\n };\n}\n\nasync function loadMaterialPublicationByGuid(\n registry: AssetRegistry,\n request: MaterialLoadRequest,\n): Promise<MaterialPublication | undefined> {\n const parsedGuid = AssetGuid.parse(request.guid);\n if (!parsedGuid.ok) return undefined;\n const entry = await resolveCatalogEntry(registry, request.guid.toLowerCase());\n if (entry === undefined) return undefined;\n let pack = registry.packFileCache.get(entry.packageUrl);\n if (pack === undefined) {\n const fetched = await fetchAndCachePackFile(\n registry,\n entry.packageUrl,\n request.guid.toLowerCase(),\n );\n if (!fetched.ok) return undefined;\n pack = registry.packFileCache.get(entry.packageUrl);\n }\n const asset = pack?.assets.find(\n (candidate) => candidate.guid.toLowerCase() === request.guid.toLowerCase(),\n );\n if (asset === undefined || asset.kind !== 'material') return undefined;\n const record = cookedRecordFromPayload(asset.payload);\n const recordObject =\n record !== undefined && typeof record === 'object' && record !== null\n ? (record as Record<string, unknown>)\n : undefined;\n const artifactKey = materialArtifactKey(recordObject, asset.artifacts ?? {});\n if (artifactKey === undefined) {\n const inlineArtifact = inlineMaterialArtifact(recordObject);\n if (inlineArtifact !== undefined) {\n return {\n guid: request.guid,\n record,\n artifact: inlineArtifact,\n };\n }\n return {\n guid: request.guid,\n record,\n artifactError: {\n code: 'asset-artifact-missing',\n expected: 'a published material artifact descriptor',\n },\n };\n }\n const descriptor = asset.artifacts?.[artifactKey];\n if (descriptor === undefined) {\n return {\n guid: request.guid,\n record,\n artifactError: {\n code: 'asset-artifact-missing',\n expected: `artifact descriptor '${artifactKey}'`,\n },\n };\n }\n let publicationRecord = record;\n if (publicationRecord === undefined) {\n const recordArtifact = await readArtifact({\n packageUrl: entry.packageUrl,\n guid: request.guid,\n artifactKey: `${artifactKey}.record`,\n descriptor: {\n path: materialRecordPath(descriptor),\n mediaType: 'application/json',\n },\n });\n if (!recordArtifact.ok) return undefined;\n try {\n publicationRecord = JSON.parse(new TextDecoder().decode(recordArtifact.value));\n } catch {\n publicationRecord = null;\n }\n }\n const artifactCacheKey = `${entry.packageUrl}\\0${request.guid.toLowerCase()}\\0${artifactKey}`;\n const artifact = await registry.artifactCache.read(artifactCacheKey, () =>\n readArtifact({\n packageUrl: entry.packageUrl,\n guid: request.guid,\n artifactKey,\n descriptor,\n }),\n );\n if (!artifact.ok) {\n if (artifact.error.code === 'asset-artifact-missing') {\n return {\n guid: request.guid,\n record: publicationRecord,\n artifactError: {\n code: artifact.error.code,\n expected: artifact.error.expected,\n actual: artifact.error.detail.observed,\n },\n };\n }\n if (artifact.error.code === 'asset-artifact-integrity-mismatch') {\n return {\n guid: request.guid,\n record: publicationRecord,\n artifactError: {\n code: artifact.error.code,\n expected: artifact.error.expected,\n actual: artifact.error.detail.observed,\n },\n };\n }\n return {\n guid: request.guid,\n record: publicationRecord,\n artifactError: {\n code: 'asset-artifact-missing',\n expected: artifact.error.expected,\n actual: artifact.error.detail.observed,\n },\n };\n }\n return {\n guid: request.guid,\n record: publicationRecord,\n artifact: {\n bytes: artifact.value,\n },\n };\n}\n\nexport async function loadMaterialReadyByGuid(\n registry: AssetRegistry,\n request: MaterialLoadRequest,\n): Promise<MaterialReady | MaterialLoadError> {\n const publication = await loadMaterialPublicationByGuid(registry, request);\n return loadMaterialReadyPublication(registry, request, publication);\n}\n\nfunction publicationSpecializationKey(publication: MaterialPublication | undefined): string {\n const record = publication?.record;\n if (record === null || typeof record !== 'object') return '';\n const specializationKey = (record as { readonly specializationKey?: unknown }).specializationKey;\n return typeof specializationKey === 'string' ? specializationKey : '';\n}\n\nasync function loadMaterialReadyPublication(\n registry: AssetRegistry,\n request: MaterialLoadRequest,\n publication: MaterialPublication | undefined,\n): Promise<MaterialReady | MaterialLoadError> {\n const loader = createMaterialLoader({\n loadPublication: async () => publication,\n loadReference: async (guid) => {\n const parsed = AssetGuid.parse(guid);\n if (!parsed.ok) return true;\n const result = await loadByGuid(registry, parsed.value);\n return result.ok;\n },\n });\n const readiness = await loader.load(request);\n registry.recordMaterialReadiness(request.guid, readiness);\n return readiness;\n}\n\nasync function loadByGuidInternal<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n parentContext:\n | {\n sceneEntityId?: number;\n componentField?: string;\n }\n | undefined,\n ancestry: ReadonlySet<string>,\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n const guidKey = AssetGuid.format(guid).toLowerCase();\n\n // feat-20260614 M8 (D-17): the registry catalogues GUID -> payload and\n // returns the PAYLOAD (never a handle). Fast path: already catalogued\n // (covers dev catalog() + prod cached repeat calls).\n const existing = registry.assetCatalog.get(guidKey);\n if (existing !== undefined) {\n const state = registry.loadState.get(guidKey);\n if (state?.status === 'provisional') {\n // A provisional value is only a legal bridge for a true SCC back-edge.\n // A sibling or unrelated concurrent load must await its owning promise;\n // otherwise the parent reaches promoteReady while the dependency is\n // still provisional and reports a spurious public-readiness failure.\n if (ancestry.has(guidKey)) {\n const provisional = registry.loadState.getProvisional<T>(guidKey);\n if (provisional !== undefined) return ok(provisional);\n } else {\n const inFlight = registry.inFlight.get(guidKey);\n if (inFlight !== undefined) {\n return inFlight as Promise<Result<T, AssetError | ImageError | RhiError>>;\n }\n }\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `GUID ${guidKey} to be promoted to Ready before public load`,\n hint: 'wait for the active load to finish or retry after the referenced assets are ready',\n }),\n );\n }\n if (state?.status === 'ready' || (state === undefined && registry.packIndexUrl === undefined)) {\n const ready = registry.loadState.getReady<T>(guidKey);\n if (ready !== undefined) return ok(ready);\n if (state === undefined) return ok(existing.payload as T);\n }\n }\n\n // In-flight dedup (D-5 / B-10): if another call is already loading this\n // GUID, return that same Promise — covers (a) concurrent same-GUID calls\n // and (b) cycle A→B→A termination (B reaches A's in-flight entry).\n const inFlightPromise = registry.inFlight.get(guidKey);\n if (inFlightPromise !== undefined) {\n return inFlightPromise as Promise<Result<T, AssetError | ImageError | RhiError>>;\n }\n\n // Prod fetch path: only enabled when packIndexUrl is configured.\n if (registry.packIndexUrl !== undefined && typeof globalThis.fetch === 'function') {\n // F22: capture generation snapshot at Promise creation time so the\n // resolve path can detect whether invalidate/invalidateAll was called\n // while the fetch was in flight.\n const genAtStart = registry.generations.get(guidKey) ?? 0;\n const globalGenAtStart = registry.globalGeneration;\n\n const promise = (async () => {\n const result = await loadByGuidProd<T>(registry, guid, guidKey, parentContext, ancestry);\n // F22: if the generation counters changed since the Promise was\n // created, discard the result -- the asset was invalidated.\n if (\n genAtStart !== (registry.generations.get(guidKey) ?? 0) ||\n globalGenAtStart !== registry.globalGeneration\n ) {\n registry.assetCatalog.delete(guidKey);\n registry.loadState.remove(guidKey);\n return err(\n new AssetError({\n code: 'asset-invalidated',\n expected: `GUID ${guidKey} was invalidated during load`,\n hint: ASSET_ERROR_HINTS['asset-invalidated'],\n }),\n ) as Result<T, AssetError | ImageError | RhiError>;\n }\n return result;\n })();\n registry.inFlight.set(guidKey, promise);\n try {\n return await promise;\n } finally {\n if (registry.inFlight.get(guidKey) === promise) registry.inFlight.delete(guidKey);\n }\n }\n\n // Dev / fallback: synchronous catalogue miss (no network).\n return Promise.resolve(\n err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} catalogued in AssetRegistry`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n ),\n );\n}\n\n/**\n * feat-20260603-asset-import-loader-injection M1 / w6: load an\n * upstream-branch kind (texture / font) straight from its catalog entry\n * through the injected async loader, then register the produced POD. Replaces\n * the bespoke `loadTextureFromEntry` / `loadFontFromEntry` methods; the decode\n * / glyph-parse logic moved verbatim into the loader bodies (D-2 — loader is\n * pure of `registerWithGuid`, which stays here).\n */\nexport async function loadFromUpstreamEntry<T = Asset>(\n registry: AssetRegistry,\n guidKey: string,\n entry: {\n packageUrl: string;\n kind: string;\n name?: string;\n metadata?: ImageMetadata | undefined;\n },\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n const loader = registry.loaders.get(entry.kind);\n if (loader === undefined) {\n return err(\n new AssetError({\n code: 'loader-not-registered',\n expected: `a loader registered for kind '${entry.kind}'`,\n hint: ASSET_ERROR_HINTS['loader-not-registered'],\n detail: { kind: entry.kind, registeredKinds: registry.loaders.registeredKinds() },\n }),\n );\n }\n const out = loader.load({ ...entry, guidKey }, undefined, makeLoadContext(registry));\n // Upstream-branch loaders are async (Promise<LoaderAsyncResult>).\n const result = (await out) as LoaderAsyncResult;\n if (!result.ok) {\n return err(result.error as AssetError | ImageError | RhiError);\n }\n const guid = AssetGuid.parse(guidKey);\n if (!guid.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `valid GUID ${guidKey}`,\n hint: ASSET_ERROR_HINTS['asset-parse-failed'],\n }),\n );\n }\n return registry.catalog(guid.value, result.value) as Result<\n T,\n AssetError | ImageError | RhiError\n >;\n}\n\n/**\n * Internal: prod fetch path for `loadByGuid`.\n * Fetches pack-index.json (cached), then fetches the pack file, parses the\n * asset payload, and registers it.\n */\nexport async function loadByGuidProd<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n guidKey: string,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n ancestry: ReadonlySet<string> = new Set(),\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n // feat-20260603-asset-import-loader-injection M4 / w31 (AC-19 lazy iron law):\n // wrap the DDC fetch + load path so a DDC miss can be routed through the\n // injected ImportTransport (studio form) or fail-fast with\n // `asset-not-imported` (shipped form, AC-22). The load path after a\n // successful DDC resolve is identical in both forms -- zero branches on\n // `registry.importTransport` (AC-23 key invariant).\n //\n // A DDC miss is: (a) the GUID is absent from the catalog, OR (b) the\n // `.pack.json` fetch returns `asset-not-found` / `asset-fetch-failed`.\n // In case (a) the transport is probed first (the pack-index may have been\n // built before the asset was imported); in case (b) the transport is the\n // only fallback (the pack file is genuinely missing).\n\n const entry = await resolveCatalogEntry(registry, guidKey);\n if (entry !== undefined) {\n const projection = resolveRuntimeProjection(guidKey, entry);\n if (!projection.ok) return projection;\n if (projection.value?.lifecycle !== undefined && projection.value.lifecycle !== 'current') {\n return transportOrFail<T>(registry, guid, guidKey, 'asset-not-imported');\n }\n // Catalog hit: try the DDC load path.\n const result = await ddcLoad<T>(registry, guid, guidKey, entry, parentContext, ancestry);\n if (result.ok) return result;\n // DDC miss: only route through transport when the error indicates a\n // missing pack file (not a parse / validation failure inside the pack) or\n // an unimported texture source (feat-20260604 M2 / D-1: import-on-demand).\n // `texture-source-not-imported` is an AssetError, so it passes the\n // `instanceof AssetError` guard naturally. `image-decode-failed` is an\n // ImageError (a genuinely corrupt imported .bin) -- it fails the guard and\n // is therefore never transport-eligible (Risk-1), so a real decode\n // failure is never silently lazy-imported.\n const ddcError = result.error;\n const transportEligible =\n ddcError instanceof AssetError &&\n (ddcError.code === 'asset-not-found' ||\n ddcError.code === 'asset-fetch-failed' ||\n ddcError.code === 'texture-source-not-imported' ||\n // perf-20260706: the raw-container fail-fast (mesh/material/scene whose\n // packageUrl is still a .glb/.gltf/.fbx) surfaces source-not-imported;\n // it is transport-eligible so the import runs once and rewrites the row\n // to .bin/.pack.json (the shipped form, with no transport, fails fast).\n // Distinct from the generic asset-not-imported, which must stay\n // NON-eligible so the parent-missing breadcrumb is never masked.\n ddcError.code === 'source-not-imported');\n if (transportEligible) {\n return transportOrFail<T>(registry, guid, guidKey, ddcError.code);\n }\n return result;\n }\n\n // Catalog miss: the GUID is not in the pack-index. In the studio form the\n // import transport can lazily create the missing DDC.\n return transportOrFail<T>(registry, guid, guidKey, 'asset-not-found');\n}\n\n/**\n * Resolve the catalog entry for a GUID, lazily fetching the pack-index on\n * first call. Returns `undefined` when the GUID is absent from the catalog.\n */\nexport async function resolveCatalogEntry(\n registry: AssetRegistry,\n guidKey: string,\n): Promise<\n | {\n packageUrl: string;\n kind: string;\n name?: string;\n metadata?: ImageMetadata | undefined;\n compression?: AssetCompression;\n }\n | undefined\n> {\n const key = guidKey.toLowerCase();\n // Re-fetch the pack-index when it has never been fetched (=== undefined) OR\n // when the cached Map lacks this GUID. The miss case covers invalidate(guid)\n // round-2 M-A, which deletes the per-GUID index entry (targeted, bystanders\n // survive) without nuking the whole Map to undefined: the next loadByGuid\n // must re-consult the source so the GUID re-resolves and its freshly-cleared\n // body cache re-fetches. A genuinely absent GUID re-fetches once then still\n // misses, falling through to the transport / asset-not-found path as before.\n if (registry.packIndexCache === undefined || !registry.packIndexCache.has(key)) {\n const catalogResult = await fetchPackIndex(registry);\n if (!catalogResult.ok) {\n // Keep packIndexCache === undefined so next resolveCatalogEntry re-enters\n // the fetch path instead of short-circuiting on an empty (polluted) cache.\n if (registry.packIndexCache === undefined) return undefined;\n } else {\n registry.packIndexCache = catalogResult.value;\n registerPackagesFromIndex(registry, registry.packIndexCache);\n }\n }\n return registry.packIndexCache?.get(key);\n}\n\n/**\n * feat-20260618 M3 (D-2): once the pack-index is parsed, group every row by\n * its `packageUrl` and register each package fully -- all of its GUIDs and\n * their entry display names in one `registerPackage` call. Registering the\n * whole package at once (rather than one GUID per load) means the package\n * cardinality is known up front, so `resolveName` returns the basename for a\n * genuinely single-asset package and the entry name for a multi-asset one,\n * with no incremental 1->N promotion needed on the prod path. The name travels\n * entry -> Package, never through the payload (Risk-3 JSON-roundtrip safety),\n * and covers both the sync (parseAssetPayload) and async (texture/font) loads.\n */\nexport function registerPackagesFromIndex(\n registry: AssetRegistry,\n catalog: Map<\n string,\n {\n packageUrl: string;\n name?: string;\n sourcePath?: string;\n subject?: CatalogSubject;\n }\n >,\n): void {\n const byPath = new Map<string, { guids: string[]; names: Map<string, string> }>();\n for (const [guidKey, entry] of catalog) {\n // Imported outputs are published under generated DDC/package URLs, but\n // their stable package identity is the authored source. Keeping that\n // source path here preserves `sky.hdr` (and equivalent source names) for\n // single-asset lazy imports; authored internal packages retain their\n // package URL semantics.\n const packagePath =\n entry.subject === 'imported-output' && entry.sourcePath !== undefined\n ? entry.sourcePath\n : entry.packageUrl;\n let group = byPath.get(packagePath);\n if (group === undefined) {\n group = { guids: [], names: new Map() };\n byPath.set(packagePath, group);\n }\n group.guids.push(guidKey);\n if (entry.name !== undefined) group.names.set(guidKey, entry.name);\n }\n for (const [path, group] of byPath) {\n registry._registerPackage(path, group.guids, group.names);\n }\n}\n\n/**\n * Load an asset through the DDC (catalog entry -> fetch pack -> loader.load\n * -> register). Returns `Err(asset-not-found)` or `Err(asset-fetch-failed)`\n * on DDC miss (the caller then decides whether to route through the\n * import transport).\n *\n * This path is IDENTICAL in studio and shipped forms -- the only difference\n * between the two is whether `registry.importTransport` exists when the caller\n * falls back to `transportOrFail` (AC-23 key invariant).\n */\nexport async function ddcLoad<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n guidKey: string,\n entry: {\n packageUrl: string;\n kind: string;\n name?: string;\n metadata?: ImageMetadata | undefined;\n compression?: AssetCompression;\n },\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n ancestry: ReadonlySet<string> = new Set(),\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n if (typeof entry.packageUrl !== 'string' || entry.packageUrl.length === 0) {\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `catalog entry for GUID ${guidKey} to contain a packageUrl locator`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n const packResult = await loadPackV2Asset(registry, guidKey, entry.packageUrl);\n if (packResult === undefined) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `Pack v2 package for GUID ${guidKey}`,\n hint: 'legacy top-level asset payloads are not accepted',\n }),\n );\n }\n if (!packResult.ok) {\n return packResult as Result<T, AssetError>;\n }\n\n const asset = packResult.value.asset;\n // feat-20260622 M4 / w12: project the pack-entry refs[] (GUID strings) into\n // AssetRef[] for the envelope. The on-disk pack.json refs[] carries only\n // GUID strings (sourceField / sceneEntityId are stripped at the\n // serialization boundary, w7 D-10), so prod-loaded edges have no per-entity\n // metadata — the scene breadcrumb fallback (buildSceneChildContext) still\n // walks the payload for entity/field detail. Dev-server register paths that\n // carry rich AssetRef[] keep their edge metadata end-to-end.\n const packRefs: readonly AssetRef[] = packResult.value.refs.map((g) => ({ guid: g }));\n\n // feat-20260622 M5 / w17 (D-8, R5): the former material parent preload\n // \"Path B\" (an independent early-return that loaded the parent BEFORE the\n // unified for-loop and carried the precise breadcrumb hint `loading parent\n // material X for child Y`) is folded into the unified envelope.refs\n // for-loop. The parent GUID already rides on the material envelope.refs\n // (gltf-importer w5 writes it; the on-disk pack refs[] carries it as a\n // GUID string -> packRefs above projects it), so the unified for-loop\n // recurses on it like any other edge. Here we only resolve the parent\n // GUID -> AssetGuid and stamp `parent` onto the asset payload (the\n // renderer-facing field read by walkMaterialPassesOverSharedRefs); the\n // parent EDGE load + the `loading parent material X for child Y` breadcrumb\n // + the not-a-material guard all move into the for-loop's\n // sourceField.fieldName==='parent' / parent-edge branch below. No early\n // return: the material registers (register-before-recurse) and its parent\n // edge loads through the same unified path as texture / scene edges.\n let assetToRegister: Asset = asset;\n let parentGuidKey: string | undefined;\n if (\n asset.kind === 'material' &&\n 'parentGuid' in (asset as unknown as Record<string, unknown>) &&\n typeof (asset as unknown as Record<string, unknown>).parentGuid === 'string'\n ) {\n const parentGuidStr = (asset as unknown as MaterialAsset & { parentGuid: string }).parentGuid;\n const parentGuid = AssetGuid.parse(parentGuidStr);\n if (!parentGuid.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `valid parent GUID for child ${guidKey}`,\n hint: `parent GUID '${parentGuidStr}' is not a valid UUID format`,\n }),\n );\n }\n parentGuidKey = parentGuidStr.toLowerCase();\n const matAsset = asset as unknown as MaterialAsset & { parentGuid?: string };\n const passes = matAsset.passes;\n const values = matAsset.values;\n assetToRegister = {\n kind: 'material',\n ...(passes !== undefined ? { passes } : {}),\n ...(values !== undefined ? { values } : {}),\n parent: parentGuid.value,\n };\n }\n\n registry.loadState.begin(\n guidKey,\n packRefs.map((ref) => ref.guid),\n );\n\n // The provisional record lets cycle back-edges terminate internally while\n // lookup()/inspect() remain limited to the ready domain.\n // tweak-20260609 M1: catalogue the asset BEFORE recursing into its\n // sub-assets. This way, when a cycle (A→B→A) reaches back to A during\n // B's recursion, A is already catalogued (fast-path hit) and the inFlight\n // Promise for A can be fulfilled. The inFlight entry in `loadByGuid` is\n // the second line of defense — it catches concurrent same-GUID calls\n // before the asset is catalogued.\n const registerResult = registerParsedAsset<T>(registry, guid, assetToRegister, guidKey, packRefs);\n if (!registerResult.ok) {\n purgeFailedLoad(registry, guidKey, entry.packageUrl, registerResult.error);\n return registerResult;\n }\n const registeredPayload = registerResult.value;\n registry.loadState.resolveAsset(guidKey, registeredPayload);\n\n // feat-20260622 M4 / w12 (D-5): the recursion source is the just-catalogued\n // envelope's refs[]. The for-loop is kind-agnostic\n // — every AssetRef carries the GUID to recurse on; scene/material/skin all\n // flow through this one loop. Each edge optionally carries sourceField /\n // sceneEntityId; when present the childContext is built straight from the\n // edge, otherwise the scene branch falls back to walking the payload\n // (buildSceneChildContext) so the prod-path breadcrumb keeps its entity /\n // field detail (on-disk refs[] are GUID-string-only, w7 D-10).\n const envelope = registry.assetCatalog.get(guidKey);\n const refs: readonly AssetRef[] = envelope?.refs ?? [];\n if (refs.length > 0) {\n const subResults = await Promise.all(\n refs.map((ref) => {\n const refGuidKey = ref.guid.toLowerCase();\n const parsedRef = AssetGuid.parse(ref.guid);\n if (!parsedRef.ok) {\n return Promise.resolve({\n guidKey: refGuidKey,\n result: err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `valid sub-asset GUID referenced by ${asset.kind} ${guidKey}`,\n hint: `refs[] entry '${ref.guid}' is not a valid UUID format`,\n }),\n ) as Result<Asset, AssetError | ImageError | RhiError>,\n childContext: undefined as\n | {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n }\n | undefined,\n isParentEdge: false,\n edge: ref,\n });\n }\n let childContext:\n | {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n }\n | undefined;\n if (ref.sceneEntityId !== undefined || ref.sourceField !== undefined) {\n childContext = {};\n if (ref.sceneEntityId !== undefined) childContext.sceneEntityId = ref.sceneEntityId;\n if (ref.sourceField?.fieldName !== undefined) {\n childContext.componentField =\n (ref.sourceField.componentName !== undefined\n ? `${ref.sourceField.componentName}.`\n : '') +\n ref.sourceField.fieldName +\n (ref.sourceField.arrayIndex !== undefined ? `[${ref.sourceField.arrayIndex}]` : '');\n childContext.sourceField = ref.sourceField;\n }\n } else if (asset.kind === 'scene') {\n childContext = buildSceneChildContext(registry, asset, refGuidKey, guidKey);\n }\n // feat-20260622 M5 / w17 (D-8): the material parent edge. Identify it\n // by either the rich dev-path marker (sourceField.fieldName==='parent')\n // or the prod-path GUID match against the resolved parent GUID\n // (on-disk refs[] strip sourceField, w7 D-10, so the GUID is the only\n // signal). The parent edge carries the distinct `loading parent\n // material X for child Y` breadcrumb (AC-10) instead of the generic\n // buildBreadcrumbHint form, and is guarded to be a material.\n const isParentEdge =\n asset.kind === 'material' &&\n (ref.sourceField?.fieldName === 'parent' ||\n (parentGuidKey !== undefined && refGuidKey === parentGuidKey));\n const childAncestry = new Set(ancestry);\n childAncestry.add(guidKey);\n return loadByGuidInternal(\n registry,\n parsedRef.value,\n childContext ?? parentContext,\n childAncestry,\n ).then((r) => ({\n guidKey: refGuidKey,\n result: r,\n childContext,\n isParentEdge,\n edge: ref,\n }));\n }),\n );\n\n // If any sub-asset load failed, propagate the first error enriched with\n // parent breadcrumb.\n for (const {\n guidKey: subGuidKey,\n result: subResult,\n childContext: subChildContext,\n isParentEdge,\n edge: subEdge,\n } of subResults) {\n // feat-20260622 M5 / w17: parent-edge breadcrumb migration (former Path\n // B). On load failure, carry the distinct `loading parent material X for\n // child Y: <subErr.hint>` form (AC-10 downstream literal assertion) and\n // propagate the parent's own error code verbatim.\n if (isParentEdge && !subResult.ok) {\n const subErr = subResult.error;\n const code: AssetErrorCode =\n subErr instanceof AssetError ? subErr.code : 'asset-parse-failed';\n purgeFailedLoad(registry, guidKey, entry.packageUrl, subErr);\n return err(\n new AssetError({\n code,\n expected: subErr.expected,\n hint: `loading parent material ${subGuidKey} for child ${guidKey}: ${\n subErr.hint ?? ''\n }`,\n ...(subErr instanceof AssetError && subErr.detail !== undefined\n ? { detail: subErr.detail as Readonly<AssetErrorDetail> }\n : {}),\n }),\n );\n }\n // feat-20260622 M5 / w17: parent edge loaded but is not a material —\n // same guard the former Path B carried, with the matching breadcrumb.\n if (isParentEdge && subResult.ok && subResult.value?.kind !== 'material') {\n const error = new AssetError({\n code: 'asset-parse-failed',\n expected: `parent GUID ${subGuidKey} to reference a MaterialAsset`,\n hint: `loading parent material ${subGuidKey} for child ${guidKey}: referenced asset is ${subResult.value?.kind ?? 'unknown'}, not 'material'`,\n });\n purgeFailedLoad(registry, guidKey, entry.packageUrl, error);\n return err(error);\n }\n if (!subResult.ok) {\n const subErr = subResult.error;\n const breadcrumb = buildBreadcrumbHint(\n guidKey,\n asset.kind,\n subGuidKey,\n subChildContext ?? parentContext,\n );\n const code: AssetErrorCode =\n subErr instanceof AssetError ? subErr.code : 'asset-fetch-failed';\n // feat-20260622 verify r1: deliver the breadcrumb provenance in\n // structured form so AI users locate the broken edge by property\n // access (charter P3), not by parsing the hint. Preserve the sub\n // error's own detail when it carries one (more specific); otherwise\n // expose the edge provenance (entity / source field).\n // Prefer the rich dev-path edge provenance; on the prod path the\n // on-disk edge is GUID-only (sourceField stripped, w7 D-10), so fall\n // back to the entity-walk-recovered provenance carried on the\n // childContext (verify r1).\n const provEntityId = subEdge?.sceneEntityId ?? subChildContext?.sceneEntityId;\n const provSourceField = subEdge?.sourceField ?? subChildContext?.sourceField;\n const breadcrumbDetail: Readonly<AssetErrorDetail> = {\n referencedByGuid: guidKey,\n referencedByKind: asset.kind,\n subAssetGuid: subGuidKey,\n ...(provEntityId !== undefined ? { sceneEntityId: provEntityId } : {}),\n ...(provSourceField !== undefined ? { sourceField: provSourceField } : {}),\n };\n const detail: Readonly<AssetErrorDetail> =\n subErr instanceof AssetError && subErr.detail !== undefined\n ? subErr.detail\n : breadcrumbDetail;\n purgeFailedLoad(registry, guidKey, entry.packageUrl, subErr);\n return err(\n new AssetError({\n code,\n expected: subErr.expected,\n hint: `${breadcrumb} / ${subErr.hint ?? ''}`,\n detail,\n }),\n );\n }\n }\n }\n\n // A Mesh default is a typed dependency, not merely a loadable GUID. This\n // check deliberately lives outside the `refs.length > 0` branch: a producer\n // that puts a default GUID in the payload but omits the matching refs[] edge\n // must fail closed instead of publishing a Mesh whose dependency closure is\n // incomplete.\n if (asset.kind === 'mesh') {\n const directRefGuids = new Set(refs.map((ref) => ref.guid.toLowerCase()));\n const slots = (asset as MeshAsset).materialSlots;\n for (let slotIndex = 0; slotIndex < slots.length; slotIndex++) {\n const slot = slots[slotIndex];\n if (slot?.defaultMaterial === undefined) continue;\n const defaultMaterialGuid = AssetGuid.format(slot.defaultMaterial).toLowerCase();\n const loaded = directRefGuids.has(defaultMaterialGuid)\n ? registry.assetCatalog.get(defaultMaterialGuid)?.payload\n : undefined;\n if (loaded?.kind === 'material') continue;\n const actualKind = directRefGuids.has(defaultMaterialGuid)\n ? (loaded?.kind ?? 'missing')\n : 'missing-ref-edge';\n const error = new AssetError({\n code: 'asset-parse-failed',\n expected: `mesh ${guidKey} materialSlots[${slotIndex}] (${slot.slotName}) default ${defaultMaterialGuid} to reference a MaterialAsset`,\n hint: `recook mesh ${guidKey}; slot ${slotIndex} '${slot.slotName}' resolves to ${actualKind}, not 'material'`,\n detail: {\n meshAssetGuid: guidKey,\n slotIndex,\n slotName: slot.slotName,\n defaultMaterialGuid,\n actualKind,\n },\n });\n purgeFailedLoad(registry, guidKey, entry.packageUrl, error);\n return err(error);\n }\n }\n\n registry.loadState.promoteReady(guidKey);\n if (registry.loadState.getReady(guidKey) === undefined) {\n const error = new AssetError({\n code: 'asset-parse-failed',\n expected: `GUID ${guidKey} and all referenced assets to be public-ready`,\n hint: 'retry after every referenced GUID has loaded successfully',\n });\n purgeFailedLoad(registry, guidKey, entry.packageUrl, error);\n return err(error);\n }\n const registeredAsset = registeredPayload as Asset;\n if (registeredAsset.kind === 'material' && !isEngineMaterial(registeredAsset)) {\n const publication = await loadMaterialPublicationByGuid(registry, {\n guid: guidKey,\n specializationKey: '',\n });\n await loadMaterialReadyPublication(\n registry,\n {\n guid: guidKey,\n specializationKey: publicationSpecializationKey(publication),\n },\n publication,\n );\n }\n return ok(registeredPayload as T);\n}\n\nasync function loadPackV2Asset(\n registry: AssetRegistry,\n guidKey: string,\n packageUrl: string,\n): Promise<\n | Result<\n {\n asset: Asset;\n refs: readonly string[];\n },\n AssetError\n >\n | undefined\n> {\n const cached = registry.packFileCache.get(packageUrl);\n if (cached === undefined) {\n const inFlight = registry.packFileInFlight.get(packageUrl);\n if (inFlight !== undefined) await inFlight.catch(() => undefined);\n const fetched =\n registry.packFileCache.get(packageUrl) === undefined\n ? await fetchAndCachePackFile(registry, packageUrl, guidKey)\n : undefined;\n if (registry.packFileCache.get(packageUrl) === undefined) {\n if (fetched === undefined) {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `pack file ${packageUrl} to be cached after its shared fetch`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n return fetched as unknown as Result<{ asset: Asset; refs: readonly string[] }, AssetError>;\n }\n }\n const pack = registry.packFileCache.get(packageUrl);\n if (pack?.schemaVersion !== '2.0.0') return undefined;\n const asset = pack.assets.find((candidate) => candidate.guid.toLowerCase() === guidKey);\n if (asset === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in Pack v2 package ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n const artifacts: Record<string, { descriptor: ArtifactDescriptor; bytes: Uint8Array }> = {};\n for (const [artifactKey, descriptor] of Object.entries(asset.artifacts ?? {})) {\n const cacheKey = `${packageUrl}\\0${guidKey}\\0${artifactKey}`;\n const artifact = await registry.artifactCache.read(cacheKey, () =>\n readArtifact({ packageUrl, guid: guidKey, artifactKey, descriptor }),\n );\n if (!artifact.ok)\n return artifact as unknown as Result<{ asset: Asset; refs: readonly string[] }, AssetError>;\n artifacts[artifactKey] = { descriptor, bytes: artifact.value };\n }\n const loaded = await registry.loaders.loadPack(\n {\n guid: guidKey,\n kind: asset.kind,\n payload: asset.payload,\n refs: asset.refs ?? [],\n artifacts,\n },\n makeLoadContext(registry),\n );\n if (!loaded.ok) return err(loaded.error as AssetError);\n if (loaded.value === undefined || typeof loaded.value !== 'object') {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `loader '${asset.kind}' to return an asset payload`,\n hint: 'register a loader that accepts the Pack v2 asset-local input',\n }),\n );\n }\n return ok({ asset: loaded.value as Asset, refs: asset.refs ?? [] });\n}\n\nfunction purgeFailedLoad(\n registry: AssetRegistry,\n guidKey: string,\n packageUrl: string,\n error: unknown,\n): void {\n const doomed = registry.loadState.fail(guidKey, error);\n for (const key of doomed) registry.assetCatalog.delete(key);\n registry.packFileCache.delete(packageUrl);\n}\n\n/**\n * M4 transport fallback: try the injected {@link ImportTransport} to lazily\n * import a missing DDC, then re-enter the DDC load path. When no transport\n * is wired (shipped form), fail fast with `asset-not-imported` (AC-22).\n */\nexport async function transportOrFail<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n guidKey: string,\n _missReason: AssetErrorCode,\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n if (registry.importTransport === undefined) {\n // shipped form: no transport wired -> fail fast, never degrade to\n // runtime import (AC-22, charter P3 explicit failure).\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `GUID ${guidKey} to have been pre-imported at build time or to have an ImportTransport wired`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n\n // studio form: request the transport to import this GUID on-the-fly.\n // After a successful transport call the DDC is available; re-enter the\n // catalog + DDC load path (the transport writes the DDC but does NOT\n // register the asset — that's the Loader's job).\n const transportResult = await registry.importTransport.fetchPack(\n guidKey,\n registry.runtimeBinding,\n );\n if (!transportResult.ok) {\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `import transport to fetch pack for GUID ${guidKey}`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n\n // Patch ONLY the freshly imported rows into the catalog cache (per-asset\n // incremental, the four-verb redesign 2026-06-06) instead of nuking the\n // cache and re-fetching the whole pack-index. The transport returns the one\n // imported entry (+ sub-asset siblings); each becomes / overwrites a cache\n // row. This keeps 122 concurrent texture imports O(N) instead of O(N^2)\n // whole-catalog re-fetches and never resets a sibling's imported row.\n const importedEntries = 'entries' in transportResult ? transportResult.entries : undefined;\n if (importedEntries !== undefined && importedEntries.length > 0) {\n // F20: serialise packIndexCache writes through a per-cache Promise queue.\n // The \"check -> new Map -> set\" block is not atomic across concurrent\n // transportOrFail calls; chaining through the queue ensures each patch\n // completes before the next starts, preventing new-Map overwrite races.\n registry.packIndexCachePatchQueue = registry.packIndexCachePatchQueue.then(() => {\n if (registry.packIndexCache === undefined) registry.packIndexCache = new Map();\n for (const e of importedEntries) {\n if (typeof e.packageUrl !== 'string' || e.packageUrl.length === 0) continue;\n registry.packIndexCache.set(e.guid.toLowerCase(), {\n packageUrl: resolveCatalogAssetUrl(registry, e.packageUrl),\n kind: e.kind,\n // Carry the transport's derived display name into the cache row.\n // buildCatalog already resolves it (deriveAssetName: basename of the\n // source for single-/no-storedName sub-assets), so a freshly imported\n // GLB's 1000+ sub-assets show as \"<file>.glb\" in the Content Browser\n // instead of blank. Dropping it here made listCatalog fall back to\n // `entry.name ?? ''` — the whole-index re-read path (else branch) kept\n // names, so only the incremental patch path was blank.\n ...(e.name !== undefined ? { name: e.name } : {}),\n // Carry refs on the incremental patch path too, else an asset\n // imported via POST /__import shows missing dependency edges until\n // the next full pack-index refresh (feat: listCatalog refs).\n ...(e.refs !== undefined ? { refs: e.refs } : {}),\n ...(e.packageId !== undefined ? { packageId: e.packageId } : {}),\n ...(e.provenance !== undefined ? { provenance: e.provenance } : {}),\n ...(e.revision !== undefined ? { revision: e.revision } : {}),\n ...(e.authoring !== undefined ? { authoring: e.authoring } : {}),\n ...(e.sourceKey !== undefined ? { sourceKey: e.sourceKey } : {}),\n ...(e.sourceIndex !== undefined ? { sourceIndex: e.sourceIndex } : {}),\n ...(e.relations !== undefined ? { relations: e.relations } : {}),\n ...(e.diagnostics !== undefined ? { diagnostics: e.diagnostics } : {}),\n // Carry sourcePath on the incremental patch path too (same red-line\n // as refs above): an asset imported via POST /__import would\n // otherwise expose no source-file path in listCatalog until the next\n // full pack-index refresh, breaking editor CRUD sidecar lookup for\n // freshly imported assets. `sourcePath` is a required PackIndexEntry\n // field, so it is always present on the transport row.\n ...(e.sourcePath !== undefined ? { sourcePath: e.sourcePath } : {}),\n });\n }\n });\n await registry.packIndexCachePatchQueue;\n } else {\n // No inline rows -- fall back to a full pack-index re-read so the freshly\n // imported DDC entry is visible (legacy / non-row-returning transports).\n registry.packIndexCache = undefined;\n }\n const entry = await resolveCatalogEntry(registry, guidKey);\n if (entry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `import transport to produce a catalog entry for GUID ${guidKey}`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n\n // Re-enter the DDC load path (identical to the catalog-hit path).\n return ddcLoad<T>(registry, guid, guidKey, entry);\n}\n\n/**\n * Register a parsed asset POD (the synchronous tail of the DDC load path:\n * `registerWithGuid`). Material parent preload is handled asynchronously\n * inside `ddcLoad` before calling this method; the registered asset is\n * always fully resolved by the time it reaches here.\n *\n * Extracted from the old `loadByGuidProd` body so `ddcLoad` and\n * `transportOrFail` share an identical load path (AC-23 key invariant).\n */\nexport function registerParsedAsset<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n asset: Asset,\n _guidKey: string,\n refs?: readonly AssetRef[],\n): Result<T, AssetError | ImageError | RhiError> {\n // feat-20260614 M8 (D-17): catalogue the parsed payload under its GUID and\n // return the PAYLOAD. `catalog` validates mesh stride + material passes and\n // returns Result.err on failure (no throw), so the loadByGuid surface stays\n // a consistent Result (charter P4 consistent abstraction).\n //\n // feat-20260622 M4 / w12 (D-9): the pack-entry refs[] ride onto the\n // catalogued envelope here so the recursive core can read envelope.refs as\n // its single recursion source.\n return registry.catalog<T>(guid, asset as T, refs) as Result<\n T,\n AssetError | ImageError | RhiError\n >;\n}\n\n/**\n * Fetch a .pack.json file, find the asset entry matching guidKey, and\n * reconstruct the Asset from its payload.\n */\n/**\n * bug-20260610: fetch one pack file and return the raw asset entry without\n * parsing. Used by `loadByGuidProd` for material kinds so the caller can\n * recursively preload `refs[]` (texture sub-assets) BEFORE the synchronous\n * materialLoader runs and rewrites values handle fields to their refs[]\n * GUID strings (feat-20260614 M8 / D-19: GUID verbatim, no handle minting).\n */\nexport async function fetchPackEntry(\n _registry: AssetRegistry,\n packageUrl: string,\n guidKey: string,\n): Promise<\n Result<{ kind: string; payload: Record<string, unknown>; refs?: string[] }, AssetError>\n> {\n let raw: unknown;\n try {\n const res = await globalThis.fetch(packageUrl);\n if (!res.ok) {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n raw = (await res.json()) as unknown;\n } catch {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n const packFile = raw as {\n assets?: Array<{\n guid: string;\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n }>;\n };\n const assetEntry = (packFile.assets ?? []).find(\n (a) => a.guid.toLowerCase() === guidKey.toLowerCase(),\n );\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return ok({\n kind: assetEntry.kind,\n payload: assetEntry.payload,\n ...(assetEntry.refs !== undefined ? { refs: assetEntry.refs } : {}),\n });\n}\n\n/**\n * Fetch one pack file, locate the requested asset entry, and either parse it\n * inline or expose the entry to the caller (for kinds that need to preload\n * `refs[]` BEFORE running the loader — currently 'material', whose\n * values handle fields are rewritten to their refs[] GUID strings\n * (feat-20260614 M8 / D-19: GUID verbatim, no handle minting at load time)).\n *\n * bug-20260610 Fix B (M3 / D-4): the fetch+parse result is cached per\n * `packageUrl` in `packFileCache`; concurrent calls for the same URL share\n * a single in-flight promise via `packFileInFlight`. Only the raw parsed\n * body is cached — `parseAssetPayload` still runs per-call (CON-2).\n */\nexport async function fetchPackFile(\n registry: AssetRegistry,\n packageUrl: string,\n guidKey: string,\n _kind: string,\n): Promise<Result<{ asset: Asset; refs: readonly string[] }, AssetError>> {\n // ── cache hit ───────────────────────────────────────────────────────\n const cached = registry.packFileCache.get(packageUrl);\n if (cached !== undefined) {\n const assetEntry = cached.assets.find((a) => a.guid.toLowerCase() === guidKey.toLowerCase());\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return parseAndReturnAsset(registry, assetEntry);\n }\n\n // ── in-flight dedup ─────────────────────────────────────────────────\n const inFlight = registry.packFileInFlight.get(packageUrl);\n if (inFlight !== undefined) {\n try {\n const packFile = await inFlight;\n const assetEntry = packFile.assets.find(\n (a) => a.guid.toLowerCase() === guidKey.toLowerCase(),\n );\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return parseAndReturnAsset(registry, assetEntry);\n } catch {\n // In-flight promise rejected (network failure) — fall through to\n // re-fetch. The in-flight entry was already cleaned by the\n // catch block in the original miss path.\n }\n }\n\n // ── miss: fetch + parse + cache ─────────────────────────────────────\n return fetchAndCachePackFile(registry, packageUrl, guidKey);\n}\n\n/**\n * Parse the asset payload from a pack-file entry and return the result.\n * Extracted so cache-hit and in-flight-dedup paths share the same\n * parseAssetPayload + error-wrapping logic.\n */\nexport function parseAndReturnAsset(\n registry: AssetRegistry,\n assetEntry: {\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n },\n): Result<{ asset: Asset; refs: readonly string[] }, AssetError> {\n const parsed = parseAssetPayload(registry, assetEntry.kind, assetEntry.payload, assetEntry.refs);\n // F21: the scene loader returns its structured ParseErrorDetail inline via\n // the LoaderOutput `{ ok: false, error }` arm, surfaced here through\n // parseAssetPayload's return value -- no shared instance slot.\n if (parsed !== undefined && typeof parsed === 'object' && 'ok' in parsed) {\n const e = (parsed as { readonly ok: false; readonly error: ParseErrorDetail }).error;\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `refs index ${e.index} within [0, ${e.refsLength})`,\n detail: {\n localId: e.localId,\n component: e.component,\n field: e.field,\n index: e.index,\n refsLength: e.refsLength,\n },\n hint:\n `at node localId=${e.localId}, component=${e.component}, ` +\n `field=${e.field}: index ${e.index} is out of bounds ` +\n `(refs has ${e.refsLength} entries)`,\n }),\n );\n }\n if (parsed === undefined) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `parseable asset payload for kind ${assetEntry.kind}`,\n hint: ASSET_ERROR_HINTS['asset-parse-failed'],\n }),\n );\n }\n // feat-20260622 M4 / w12: surface the pack-entry refs[] (GUID-string\n // projection) alongside the parsed payload so ddcLoad can store them on\n // the catalogued envelope. The recursive core then reads envelope.refs\n // as the single recursion source (D-5), never re-deriving them from\n // the payload.\n return ok({ asset: parsed as Asset, refs: assetEntry.refs ?? [] });\n}\n\n/**\n * Fetch a pack file from the network, parse the JSON body, store the\n * result in the cache, and return the requested asset entry.\n *\n * Registers the in-flight promise in `packFileInFlight` so concurrent\n * callers share a single fetch. On success the body moves to\n * `packFileCache`; on failure the in-flight entry is removed so\n * subsequent retries re-fetch (D-7).\n */\nexport async function fetchAndCachePackFile(\n registry: AssetRegistry,\n packageUrl: string,\n guidKey: string,\n): Promise<Result<{ asset: Asset; refs: readonly string[] }, AssetError>> {\n const fetchPromise = (async (): Promise<ParsedPackFile> => {\n let raw: unknown;\n try {\n const res = await globalThis.fetch(packageUrl);\n if (!res.ok) {\n throw new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n });\n }\n raw = (await res.json()) as unknown;\n } catch (e) {\n if (e instanceof AssetError) throw e;\n throw new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n });\n }\n // Shape guard: the dev-server / preview / 404 fallback can return\n // index.html or an unrelated JSON body that satisfies res.ok but lacks\n // the ParsedPackFile contract. Without this guard the downstream\n // `packFile.assets.find` raises TypeError outside any AssetError\n // branch, escapes as a process-level Unhandled Rejection, and drives\n // vitest browser-project exit=1 even when every onerror-gate test\n // assertion passes (feat-20260611 step-implement F-4).\n if (\n raw === null ||\n typeof raw !== 'object' ||\n !Array.isArray((raw as { assets?: unknown }).assets)\n ) {\n throw new AssetError({\n code: 'asset-fetch-failed',\n expected: `pack-file body at ${packageUrl} to be { assets: [...] }`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n });\n }\n return raw as ParsedPackFile;\n })();\n\n registry.packFileInFlight.set(packageUrl, fetchPromise);\n\n try {\n const packFile = await fetchPromise;\n registry.packFileCache.set(packageUrl, packFile);\n registry.packFileInFlight.delete(packageUrl);\n\n const assetEntry = packFile.assets.find((a) => a.guid.toLowerCase() === guidKey.toLowerCase());\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return parseAndReturnAsset(registry, assetEntry);\n } catch (e) {\n registry.packFileInFlight.delete(packageUrl);\n if (e instanceof AssetError) {\n return err(e);\n }\n throw e;\n }\n}\n\n/**\n * Reconstruct a typed `Asset` from a raw payload object.\n *\n * @param kind The asset kind discriminant (matches the pack entry or\n * dev-register dispatch).\n * @param payload The serialised asset payload (keys mirror the asset\n * interface field names).\n * @param refs Pack-file refs array for Handle fields — when a field\n * value is `number` it resolves to `refs[N]` (glTF-style index).\n * Optional to preserve compatibility with callers outside the pack\n * ingestion path (e.g., direct `registerWithGuid`).\n */\nexport function parseAssetPayload(\n registry: AssetRegistry,\n kind: string,\n payload: Record<string, unknown>,\n refs?: string[],\n):\n | Asset\n | Record<string, unknown>\n | undefined\n | { readonly ok: false; readonly error: ParseErrorDetail } {\n // feat-20260603-asset-import-loader-injection M1 / w4: dispatch on\n // `kind` through the injected LoaderRegistry instead of a hardcoded\n // `if (kind === ...)` chain (D-1 / AC-01). The seven inline pack-payload\n // loaders parse synchronously; texture / font live on the upstream\n // loadByGuidProd branch (w6) and are never reached here.\n // feat-20260623 M2 / w5: unknown kinds pass through the raw payload so\n // host-registered loaders can parse their own kind. The engine does not\n // parse payloads it cannot match; parse responsibility is explicit on the\n // missing loader (charter P3).\n const loader = registry.loaders.get(kind);\n if (loader === undefined) return { ...payload, kind };\n const out = loader.load(payload, refs, makeLoadContext(registry));\n // The inline pack-payload loaders are synchronous (`Asset | undefined`);\n // the async texture / font loaders are dispatched from loadByGuidProd, not\n // here. A Promise here would mean a misregistered loader -> treat as a\n // parse miss rather than leaking a thenable into the sync return.\n if (out !== undefined && typeof (out as { then?: unknown }).then === 'function') {\n return undefined;\n }\n // F21: the scene loader returns { ok: false, error: ParseErrorDetail } for\n // structured parse errors. Pass the error arm straight through the return\n // value so the caller constructs a precise AssetError -- no instance slot.\n if (out !== undefined && out !== null && typeof out === 'object' && 'ok' in out) {\n return out as { readonly ok: false; readonly error: ParseErrorDetail };\n }\n return out as Asset | undefined;\n}\n\n/**\n * Build the {@link LoadContext} passed to a loader's `load`.\n * `fetchBinary` / `resolveRef` / `device` are wired for the async texture /\n * font loaders (w6).\n */\nexport function makeLoadContext(registry: AssetRegistry): LoadContext {\n return {\n /**\n * feat-20260706 M3 / w19: fetchBinary signature extended per D-2.\n * `opts?.compression` triggers the single decompression gate (AC-02).\n * 'zstd' → lazy-init codec decompressZstd · 'none' / undefined → pass-through.\n * On decompression failure, the codec error is nested in asset-fetch-failed\n * detail (D-8: runtime error union NOT extended).\n */\n fetchBinary: async (url: string, opts?: { readonly compression?: AssetCompression }) => {\n try {\n const res = await globalThis.fetch(url);\n if (!res.ok) {\n return {\n ok: false as const,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n };\n }\n const buf = await res.arrayBuffer();\n let bytes: Uint8Array = new Uint8Array(buf);\n\n // --- Decompression gate (AC-02: single gate inside fetchBinary) ---\n if (opts?.compression === 'zstd') {\n const { decompressZstd } = await import('@forgeax/engine-codec');\n const decRes = await decompressZstd(bytes);\n if (!decRes.ok) {\n return {\n ok: false as const,\n error: new AssetError({\n code: 'asset-parse-failed',\n expected: `zstd decompression for ${url}`,\n hint: `[${decRes.error.code}] ${decRes.error.hint}`,\n detail: { sourcePath: url },\n }),\n };\n }\n bytes = new Uint8Array(\n decRes.value.buffer,\n decRes.value.byteOffset,\n decRes.value.byteLength,\n );\n }\n // compression === 'none' / undefined → E1 pass-through\n\n return { ok: true as const, value: bytes };\n } catch {\n return {\n ok: false as const,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n };\n }\n },\n resolveRef: async (guid: string) => {\n const parsed = AssetGuid.parse(guid);\n if (!parsed.ok) {\n return { ok: false as const, error: parsed.error };\n }\n const r = await loadByGuid(registry, parsed.value);\n if (!r.ok) return { ok: false as const, error: r.error };\n // feat-20260614 M8 (D-19): resolveRef ensures the sub-asset is\n // catalogued (recursive load). The numeric value is vestigial -- the\n // registry mints no handles; callers store the GUID, not this number.\n return { ok: true as const, value: 0 };\n },\n // feat-20260613-material-paramschema-driven-binding M4 / w22 (D-5 graceful):\n // expose the registered shader's derive(paramSchema).textureFieldNames to\n // the materialLoader so it can decide which values fields carry\n // refs[] indices without a hardcoded texture-field allowlist Set\n // (AC-03). Returns `undefined` when the shader is not registered (cross-\n // worktree shader-late-register, plan R-4) — the loader then falls back\n // to a graceful \"try every int paramValue\" walk.\n getMaterialShaderTextureFieldNames: (shaderId: string) => {\n const lookup = registry.shaderRegistry.findMaterialArtifact(shaderId);\n if (!lookup.ok) return undefined;\n return lookup.value.paramSchemaProjection.derivedInterface.textureFieldNames;\n },\n transcodeCaps: registry.transcodeCaps,\n device: undefined,\n };\n}\n\n/**\n * Return a runtime snapshot of every catalogued asset. Each entry exposes\n * `{ guid, kind, name }` where `kind` is the asset discriminant string\n * from `payload.kind`. feat-20260614 M8 (D-15): the registry holds no\n * handles -- entries are keyed by GUID (the catalogue key).\n *\n * AI-user narrowing flow (AC-11 + plan-strategy §7.4):\n * ```ts\n * for (const e of registry.inspect().assets) {\n * if (e.kind === 'texture') {\n * // re-query via registry.lookup(e.guid) to get the typed Asset value.\n * }\n * }\n * ```\n */\n","export type LoadStatus = 'unloaded' | 'provisional' | 'ready' | 'failed';\n\nexport interface LoadRecord {\n readonly status: LoadStatus;\n readonly refs: readonly string[];\n readonly value?: unknown;\n readonly error?: unknown;\n}\n\ninterface MutableLoadRecord {\n status: LoadStatus;\n refs: readonly string[];\n value?: unknown;\n error?: unknown;\n}\n\nexport class LoadStateStore {\n private readonly records = new Map<string, MutableLoadRecord>();\n\n get(guid: string): LoadRecord | undefined {\n return this.records.get(guid.toLowerCase());\n }\n\n getReady<T = unknown>(guid: string): T | undefined {\n const record = this.records.get(guid.toLowerCase());\n return record?.status === 'ready' ? (record.value as T) : undefined;\n }\n\n /**\n * Return a provisional value only for the internal SCC back-edge bridge.\n * Public callers must use getReady so promotion remains the visibility gate.\n */\n getProvisional<T = unknown>(guid: string): T | undefined {\n const record = this.records.get(guid.toLowerCase());\n return record?.status === 'provisional' ? (record.value as T) : undefined;\n }\n\n begin(guid: string, refs: readonly string[]): LoadRecord {\n const key = guid.toLowerCase();\n const existing = this.records.get(key);\n if (existing?.status === 'provisional' || existing?.status === 'ready') return existing;\n const record: MutableLoadRecord = {\n status: 'provisional',\n refs: refs.map((ref) => ref.toLowerCase()),\n };\n this.records.set(key, record);\n return record;\n }\n\n resolveAsset(guid: string, value: unknown): void {\n const key = guid.toLowerCase();\n const record = this.records.get(key);\n if (record === undefined) {\n this.records.set(key, { status: 'provisional', refs: [], value });\n return;\n }\n record.value = value;\n }\n\n registerReady(guid: string, value: unknown): void {\n this.begin(guid, []);\n this.resolveAsset(guid, value);\n this.promoteReady(guid);\n }\n\n promoteReady(guid: string): void {\n const root = guid.toLowerCase();\n const group = this.provisionalGroup(root);\n if (group.size === 0) return;\n for (const key of group) {\n const record = this.records.get(key);\n if (record?.value === undefined) return;\n for (const ref of record.refs) {\n const dependency = this.records.get(ref);\n if (dependency === undefined || (dependency.status !== 'ready' && !group.has(ref))) return;\n }\n }\n for (const key of group) {\n const record = this.records.get(key);\n if (record !== undefined) record.status = 'ready';\n }\n }\n\n fail(guid: string, error: unknown): readonly string[] {\n const doomed = this.provisionalGroup(guid.toLowerCase());\n if (doomed.size === 0) doomed.add(guid.toLowerCase());\n for (const key of doomed) {\n this.records.set(key, { status: 'unloaded', refs: [] });\n }\n const root = this.records.get(guid.toLowerCase());\n if (root !== undefined) root.error = error;\n return [...doomed];\n }\n\n remove(guid: string): void {\n this.records.delete(guid.toLowerCase());\n }\n\n clear(): void {\n this.records.clear();\n }\n\n private provisionalGroup(root: string): Set<string> {\n const group = new Set<string>();\n const visit = (key: string): void => {\n if (group.has(key)) return;\n const record = this.records.get(key);\n if (record?.status !== 'provisional') return;\n group.add(key);\n for (const ref of record.refs) visit(ref);\n };\n visit(root);\n return group;\n }\n}\n","// @forgeax/engine-assets-runtime -- material validation collaboration module (feat-20260705-runtime-tier2-decomposition M1 / w5, D-4). Free functions taking the AssetRegistry instance as first param; extracted from the class body, logic byte-preserved.\n\nimport type { CookedMaterialRecord } from '@forgeax/engine-pack';\nimport {\n AssetError,\n createMaterialError,\n type MaterialAsset,\n type MaterialError,\n type MaterialParameter,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry } from '../asset-registry';\n\n/**\n * Validate a MaterialAsset's passes[] against the ShaderRegistry's\n * paramSchema (union semantics: all declared params across all passes\n * must be satisfiable from values).\n *\n * - Empty / undefined passes[] → error\n * - Each pass's shader must exist in ShaderRegistry\n * - Union of all pass paramSchemas: params without `default` must\n * appear in values with matching type\n * - Extra keys in values are silently ignored (D-5)\n *\n * @returns AssetError on failure, null on success\n */\nexport function validateMaterialPasses(\n registry: AssetRegistry,\n asset: MaterialAsset,\n): AssetError | null {\n const passes = asset.passes;\n // undefined passes is valid (material inherits from parent at resolve time);\n // only explicit empty passes[] is an error.\n if (passes === undefined || passes.length === 0) {\n if (passes !== undefined && passes.length === 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: 'MaterialAsset with at least one pass',\n hint: 'add at least one pass descriptor to passes[] before register',\n detail: { passCount: 0 },\n });\n }\n // passes undefined: skip validation (inherits from parent later)\n return null;\n }\n\n const allSchemas: MaterialParameter[] = [...(asset.parameters ?? [])];\n for (let passIndex = 0; passIndex < passes.length; passIndex++) {\n const pass = passes[passIndex];\n if (pass === undefined) continue;\n if (pass.program.module.length === 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: 'pass.program.module to be a non-empty module identifier',\n hint: `pass[${passIndex}] has an empty program.module`,\n });\n }\n }\n\n // Deduplicate by name (first occurrence wins)\n const seen = new Set<string>();\n const unionSchema: MaterialParameter[] = [];\n for (const entry of allSchemas) {\n if (!seen.has(entry.name)) {\n seen.add(entry.name);\n unionSchema.push(entry);\n }\n }\n\n const values: Record<string, unknown> = (asset.values as Record<string, unknown>) ?? {};\n\n // feat-20260613-material-paramschema-driven-binding M3 / w16 (D-2):\n // derive(schema) is the SSOT for which schema fields are textures vs\n // samplers vs numeric. The register-time three-layer validation (extra-\n // key / type-mismatch / missing-required) categorizes fields via\n // derive output instead of a hardcoded literal type list. Texture\n // and sampler fields are always optional at register time (the\n // resource handles may not be available yet — D-5 graceful path),\n // so derive-derived membership decides the skip set without keeping\n // a parallel literal table.\n const missingParams: string[] = [];\n for (const entry of unionSchema) {\n const value = values[entry.name];\n if (value === undefined) {\n if (entry.default !== undefined || entry.optional || entry.type === 'texture') {\n continue;\n }\n missingParams.push(entry.name);\n continue;\n }\n if (value === null && entry.optional) continue;\n // Type-check supplied values\n const typeOk = validateParamType(registry, entry.name, entry.type, value);\n if (!typeOk) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `values.${entry.name} to be of type ${entry.type}`,\n hint: `values['${entry.name}'] has type ${typeof value} but paramSchema declares ${entry.type}`,\n detail: { paramName: entry.name, expectedType: entry.type, got: typeof value },\n });\n }\n }\n\n if (missingParams.length > 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `values to contain keys: ${missingParams.join(', ')}`,\n hint: `missing required params: ${missingParams.join(', ')}`,\n detail: { missingParams },\n });\n }\n\n return null;\n}\n\nexport interface MaterialEffectiveRootIdentity {\n readonly guid: string;\n readonly layoutIdentity: string;\n}\n\nexport function validateMaterialCookIdentity(\n record: Pick<CookedMaterialRecord, 'guid' | 'receipt'>,\n root: MaterialEffectiveRootIdentity,\n): MaterialError | null {\n const actual = record.receipt.identity.layoutIdentity;\n if (\n actual !== root.layoutIdentity ||\n record.receipt.derivedInterface.layoutIdentity !== root.layoutIdentity\n ) {\n return createMaterialError('material-derived-interface-mismatch', {\n code: 'material-derived-interface-mismatch',\n stage: 'extract',\n material: record.guid,\n layoutIdentity: root.layoutIdentity,\n expectedIdentity: root.layoutIdentity,\n actualIdentity: actual,\n action: 'recook',\n });\n }\n return null;\n}\n\n/**\n * Sprite 9-slice values fail-fast validation\n * (feat-20260527-sprite-nineslice M2 / w8, plan-strategy §D-1 + AC-08).\n *\n * Fires when:\n * - asset.kind === 'material'\n * - first pass shader === 'forgeax::sprite'\n * - values.slices is present\n *\n * Six fail-fast branches (1:1 with w4 test):\n * (1) any component is negative\n * (2) slices.x + slices.z >= region.zw[0] (X-axis overlap)\n * (3) slices.y + slices.w >= region.zw[1] (Y-axis overlap)\n * (4) any component is NaN\n * (5) any component is Infinity\n * (6) length !== 4\n *\n * Reuses the existing 'asset-invalid-value' member of the closed\n * `AssetErrorCode` 13-member union (no new code added per\n * AGENTS.md §Error model). The `.expected` literal mirrors the AI-User\n * Charter §3 string; `.hint` inlines the offending sum + the relevant\n * `region.zw` numeral so AI users can copy-paste the prompt straight\n * back into the IDE for self-recovery (plan-strategy §R-4).\n *\n * @returns AssetError on failure, null on success.\n */\nexport function validateSpriteSlices(\n _registry: AssetRegistry,\n asset: MaterialAsset,\n): AssetError | null {\n const passes = asset.passes;\n if (passes === undefined || passes.length === 0) return null;\n const firstPass = passes[0];\n if (firstPass === undefined || firstPass.program.module !== 'forgeax_material::sprite')\n return null;\n const pv = (asset.values ?? {}) as Record<string, unknown>;\n const slicesRaw = pv.slices;\n // Field absent — caller relies on paramSchema default [0, 0, 0, 0]; nothing to check.\n if (slicesRaw === undefined) return null;\n const expected =\n 'values.slices: [number, number, number, number] with 0 ≤ left + right < region.zw[0] and 0 ≤ top + bottom < region.zw[1]';\n if (!Array.isArray(slicesRaw)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices is not an array (got ${typeof slicesRaw}); must be a 4-tuple [left, top, right, bottom]`,\n detail: { paramName: 'slices', got: typeof slicesRaw },\n });\n }\n // (6) length check\n if (slicesRaw.length !== 4) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices length is ${slicesRaw.length}; must be 4 ([left, top, right, bottom])`,\n detail: { paramName: 'slices', got: slicesRaw.length },\n });\n }\n const slices = slicesRaw as readonly unknown[];\n // Type check each component first.\n for (let i = 0; i < 4; i++) {\n if (typeof slices[i] !== 'number') {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] is not a number (got ${typeof slices[i]})`,\n detail: { paramName: 'slices', got: typeof slices[i] },\n });\n }\n }\n const left = slices[0] as number;\n const top = slices[1] as number;\n const right = slices[2] as number;\n const bottom = slices[3] as number;\n // (4) NaN\n for (let i = 0; i < 4; i++) {\n if (Number.isNaN(slices[i] as number)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] is NaN; all four components must be finite non-negative numbers`,\n detail: { paramName: 'slices', got: 'NaN' },\n });\n }\n }\n // (5) Infinity\n for (let i = 0; i < 4; i++) {\n if (!Number.isFinite(slices[i] as number)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] is Infinity; all four components must be finite non-negative numbers`,\n detail: { paramName: 'slices', got: 'Infinity' },\n });\n }\n }\n // (1) negative — D-3 sentinel uses negative .w for tile mode but only\n // after extract; at register-time the user-supplied tuple must be all\n // non-negative (the engine encodes the sign downstream).\n for (let i = 0; i < 4; i++) {\n if ((slices[i] as number) < 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] = ${slices[i]}; all four components must be non-negative`,\n detail: { paramName: 'slices', got: slices[i] as number },\n });\n }\n }\n // (2)/(3) overlap with region. region default is [0, 0, 1, 1];\n // user override comes via values.region (vec4).\n const regionRaw = pv.region;\n let regionZ = 1;\n let regionW = 1;\n if (Array.isArray(regionRaw) && regionRaw.length >= 4) {\n const rz = regionRaw[2];\n const rw = regionRaw[3];\n if (typeof rz === 'number') regionZ = rz;\n if (typeof rw === 'number') regionW = rw;\n }\n const sumX = left + right;\n if (sumX >= regionZ) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `received slices=[${left}, ${top}, ${right}, ${bottom}]; left + right = ${sumX} ≥ ${regionZ} (region.z)`,\n detail: { paramName: 'slices', got: sumX },\n });\n }\n const sumY = top + bottom;\n if (sumY >= regionW) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `received slices=[${left}, ${top}, ${right}, ${bottom}]; top + bottom = ${sumY} ≥ ${regionW} (region.w)`,\n detail: { paramName: 'slices', got: sumY },\n });\n }\n return null;\n}\n\nexport function validateParamType(\n _registry: AssetRegistry,\n _name: string,\n type: string,\n value: unknown,\n): boolean {\n switch (type) {\n case 'f32':\n case 'i32':\n case 'u32':\n return typeof value === 'number';\n case 'vec2':\n return Array.isArray(value) && value.length >= 2 && value.every((v) => typeof v === 'number');\n case 'vec3':\n return Array.isArray(value) && value.length >= 3 && value.every((v) => typeof v === 'number');\n case 'vec4':\n return Array.isArray(value) && value.length >= 4 && value.every((v) => typeof v === 'number');\n case 'color':\n return (\n Array.isArray(value) &&\n (value.length === 3 || value.length === 4) &&\n value.every((v) => typeof v === 'number')\n );\n case 'texture':\n // A cooked pack may keep an asset GUID as the compact texture\n // shorthand. The render material resolver expands that reference at\n // the resource boundary; rejecting it here makes authored packs fail\n // before the same value can reach the resolver.\n return (\n typeof value === 'string' ||\n (typeof value === 'object' && value !== null && !Array.isArray(value))\n );\n case 'bool':\n return typeof value === 'boolean';\n default:\n return false;\n }\n}\n\n/**\n * feat-20260527-sprite-nineslice M4 / w18 (D-9): register-time soft-warn\n * for sliceMode=1 (tile) bound to a sampler whose addressMode is not\n * 'repeat'. Bumps `nineslice.tile-needs-repeat-sampler` once per offending\n * catalogue call. Never throws -- the counter is the sole AI-user-facing\n * signal (charter P3 machine-readable; AC-08 closed, never extends\n * AssetErrorCode).\n *\n * feat-20260614 M8 (D-19): `values.sampler` is now an embedded GUID\n * string (dash-form), resolved against the catalogue rather than a handle.\n */\nexport function detectTileNeedsRepeatSampler(registry: AssetRegistry, asset: MaterialAsset): void {\n if (registry.metrics === null) return;\n const passes = asset.passes;\n if (passes === undefined || passes.length === 0) return;\n const firstPass = passes[0];\n if (\n firstPass === undefined ||\n (firstPass.program.module !== 'forgeax_material::sprite' &&\n firstPass.program.module !== 'forgeax::sprite')\n )\n return;\n const pv = (asset.values ?? {}) as Record<string, unknown>;\n const slicesAndMode = pv.slicesAndMode;\n const encodedTile =\n Array.isArray(slicesAndMode) && typeof slicesAndMode[3] === 'number'\n ? slicesAndMode[3] < 0\n : false;\n const legacyTile = typeof pv.sliceMode === 'number' && pv.sliceMode === 1;\n if (!encodedTile && !legacyTile) return;\n const samplerGuid = typeof pv.sampler === 'string' ? pv.sampler : undefined;\n if (samplerGuid === undefined) return;\n const samplerEnvelope = registry.assetCatalog.get(samplerGuid.toLowerCase());\n if (samplerEnvelope === undefined || samplerEnvelope.kind !== 'sampler') return;\n const samplerAsset = samplerEnvelope.payload;\n if (samplerAsset.kind !== 'sampler') return;\n const u = samplerAsset.addressModeU;\n const v = samplerAsset.addressModeV;\n if (u !== 'repeat' || v !== 'repeat') {\n registry.metrics.increment('nineslice.tile-needs-repeat-sampler');\n }\n}\n\n/**\n * feat-20260613-material-paramschema-driven-binding M4 / w23 (D-5 graceful):\n * Return the texture-field name set for the given material-shader id,\n * derived from the registered shader's paramSchema via `derive(paramSchema)\n * .textureFieldNames`. Returns `undefined` when the shader is not yet\n * registered (cross-worktree shader-late-register, plan R-4).\n *\n * Used by `extractFrame` to know which values fields the shader\n * declares as texture handles; the extract layer validates handle-vs-\n * scalar typing and drops misclassified slots so the record stage's\n * MISSING_TEXTURE_HANDLE fallback can take over (white default texture)\n * rather than letting a stray handle reach `device.createBindGroup`.\n */\nexport function materialShaderTextureFieldNames(\n registry: AssetRegistry,\n shaderId: string,\n): ReadonlySet<string> | undefined {\n const lookup = registry.shaderRegistry.findMaterialArtifact(shaderId);\n if (!lookup.ok) return undefined;\n return lookup.value.paramSchemaProjection.derivedInterface.textureFieldNames;\n}\n","// @forgeax/engine-assets-runtime - AssetRegistry v2 (feat-20260513-guid-asset-package-system).\n//\n// Entrypoints (feat-20260614 M8 de-handle cut, D-15/D-17/D-19): the registry\n// is a GUID->payload catalogue. It no longer mints or maps handles -- column\n// handles are minted on the World via `world.allocSharedRef('Kind', payload)`,\n// and resolved through the two-tier `resolveAssetHandle` (BuiltinAssetRegistry\n// process-static slots [1,1024) + per-World `world.sharedRefs` slots >=1024).\n//\n// - catalog<T extends Asset>(guid, asset): Result<T, AssetError>\n// stores the GUID->payload entry loadByGuid resolves (dev/inline path)\n// - parseGuid(guidStr): AssetGuid\n// - lookup(guid): Asset | undefined (catalogued payload, no fetch)\n// - loadByGuid<T extends Asset>(guid): Promise<Result<T, AssetError | ImageError | RhiError>>\n// returns the PAYLOAD T (never a handle, D-17)\n// dev/fallback: synchronous catalogue lookup wrapped in Promise\n// prod: fetch(packIndexUrl) -> parse catalog -> fetch entry -> parse Asset\n// - instantiate<T extends SceneAsset>(handle, world, parent?): Result<EntityHandle, ...>\n// handle is a `world.allocSharedRef('SceneAsset', payload)` column handle\n// - inspect(): InspectSnapshot\n//\n// v1 load(url) removed in feat-20260513-guid-asset-package-system (w12).\n// loadByGuid is the replacement; M4/w23 adds real fetch-from-pack-index.\n//\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w15: the\n// `createInstancedBuffer` / `updateInstancedBuffer` / `getInstancedGpuBuffer`\n// triplet is removed alongside the `InstancedBufferAsset` POD; per-entity\n// instance transforms are now stored inside the ECS via the `Instances {\n// transforms: 'array<f32>' }` component (the RenderSystem record stage owns\n// the GPU storage buffer + dirty-version upload). Asset closed-union narrows\n// 5 -> 4; the registry surface loses the optional `RhiDevice` constructor\n// argument (no remaining device consumer).\n//\n// Dual-backend audited: the registry is engine-agnostic (no @webgpu/types\n// imports + no rhi-webgpu / rhi-wgpu references); the same instance drives\n// both dual-impl shim backends through the @forgeax/engine-rhi interface\n// SSOT at the consumer site.\n\nimport type { Component, EcsError, EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { PackError } from '@forgeax/engine-pack/errors';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { deriveAssetName } from '@forgeax/engine-pack/name';\nimport { err, ok, type Result, type RhiError } from '@forgeax/engine-rhi';\nimport type { ShaderRegistry } from '@forgeax/engine-shader';\nimport {\n ASSET_ERROR_HINTS,\n type Asset,\n type AssetEnvelope,\n AssetError,\n type AssetEvidence,\n type AssetEvidenceError,\n type AssetRef,\n authoringCapabilityForAssetKind,\n type CatalogEntry,\n catalogOperationsFor,\n type EngineMetrics,\n type Handle,\n handleSlot,\n type ImageError,\n type ImportTransport,\n type InspectEntry,\n type InspectSnapshot,\n type Loader,\n type MaterialAsset,\n type MountOverride,\n migrateLegacyMeshMaterialOverrides,\n type Package,\n type ParseErrorDetail,\n type RuntimeAssetBinding,\n type SceneAsset,\n type SceneEntity,\n type SceneInstanceMount,\n type TagOf,\n type TilesetAsset,\n type TranscodeCaps,\n type MeshAsset as TypesMeshAsset,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport {\n BUILTIN_CUBE,\n BUILTIN_CYLINDER,\n BUILTIN_NINESLICE_QUAD,\n BUILTIN_QUAD,\n BUILTIN_SPHERE,\n BUILTIN_TRIANGLE,\n} from './builtin-asset-registry';\nimport type { LoaderRegistry } from './loader-registry';\nimport { createDefaultLoaderRegistry } from './wire-default-loaders';\n\n/**\n * Strip readonly from all fields of T. Used to mutate the MeshAsset.aabb slot\n * after mesh validation passes (the interface is readonly but register-time\n * computation writes the real AABB into the caller's placeholder).\n */\n\n// feat-20260705-runtime-tier2-decomposition M1 / w4 (D-4 F1): the pre-class\n// constants, loaders, scene-payload / payload-validate / aabb helpers were\n// straight-cut into sibling modules. The thin class value-imports only what its\n// method bodies still reference; the full public consumer face (barrel + tests)\n// is preserved via the `export ... from` re-export block below (pre-w14 shim,\n// removed when consumers repoint in w14/w15).\nimport { withMeshAabb } from './aabb';\nimport type { CatalogListener, CatalogSource } from './catalog-source';\nimport {\n BUILTIN_MESH_GUIDS,\n HANDLE_CUBE,\n HANDLE_CYLINDER,\n HANDLE_NINESLICE_QUAD,\n HANDLE_QUAD,\n HANDLE_SPHERE,\n HANDLE_TRIANGLE,\n} from './handles';\nimport type { MaterialLoadError, MaterialReady } from './material/loader';\nimport { installMaterialReadyShaders } from './material/runtime-shader';\nimport { inferAtlasExtent, validateMeshPayload, validateTilesetPayload } from './payload-validate';\nimport { ArtifactReadCache } from './registry/artifact-io';\nimport {\n createRuntimeAssetEvidenceAdapter,\n type RuntimeAssetEvidenceAdapter,\n type RuntimeEvidenceSource,\n} from './registry/asset-evidence';\nimport { type CatalogRecord, fetchPackIndex } from './registry/catalog';\nimport { CatalogReplica, type CatalogReplicaSnapshot } from './registry/catalog-state';\nimport {\n instantiateFlat as instantiateFlatImpl,\n instantiate as instantiateImpl,\n type PostSpawnHook,\n resolveHandleGuid,\n resolveMountsRec,\n} from './registry/instantiate';\nimport {\n loadByGuid as loadByGuidImpl,\n parseAndReturnAsset as parseAndReturnAssetImpl,\n parseAssetPayload as parseAssetPayloadImpl,\n registerPackagesFromIndex,\n} from './registry/load-by-guid';\nimport { LoadStateStore } from './registry/load-state';\nimport type {\n ScenePublicationFence,\n ScenePublicationFenceError,\n} from './registry/scene-publication-fence';\nimport {\n detectTileNeedsRepeatSampler,\n materialShaderTextureFieldNames as materialShaderTextureFieldNamesImpl,\n validateMaterialPasses,\n validateSpriteSlices,\n} from './registry/validate-material';\nimport { extractSceneEntityHandleGuids } from './scene-handle-fields';\n\n// Public re-export surface (pre-w14 consumer face preservation): the extracted\n// modules are the new SSOT; asset-registry re-exports them until w14/w15 repoint\n// every consumer to the sibling modules / the new package.\nexport {\n HANDLE_CUBE,\n HANDLE_CYLINDER,\n HANDLE_NINESLICE_QUAD,\n HANDLE_QUAD,\n HANDLE_SPHERE,\n HANDLE_TRIANGLE,\n} from './handles';\nexport {\n animationClipLoader,\n animationGraphLoader,\n INLINE_PACK_LOADERS,\n materialLoader,\n meshLoader,\n sceneLoader,\n skeletonLoader,\n skinLoader,\n} from './loaders/inline-pack';\nexport {\n equirectLoader,\n fontLoader,\n PACK_ARTIFACT_LOADERS,\n textureLoader,\n} from './loaders/pack-artifact';\nexport { type TilesetValidateOptions, validateTilesetPayload } from './payload-validate';\n\n// ─── Re-exports for engine-runtime-local consumers ──────────────────────────\n//\n// Legacy re-exports: `Asset` widens to the 4-variant engine-types union;\n// `MeshAsset` keeps the engine-types shape (with `attributes`). Consumers\n// that previously imported from `./asset-registry` keep working through\n// the type alias re-exports below.\n\nexport type { Asset, TypesMeshAsset as MeshAsset };\n\n// D-15: the BUILTIN_* mesh payloads moved to builtin-asset-registry.ts (the\n// process-static payload SSOT); the shared runtime vertex layout remains owned\n// by @forgeax/engine-geometry.\n// imported at the top of this file. The constructor still pre-populates the\n// handle->payload map from those imports (the map itself retires in w49).\n\n// feat-20260618-asset-and-pack-name-fields M3 (D-1 / D-3): the mutable runtime\n// package object every GUID of the same import path shares. `assetGuids` grows\n// as `registerPackage` adds GUIDs; `assetCount` (the engine-types `Package`\n// view) is derived from `assetGuids.size`, never stored (#2 Derive). The public\n// `packageOf(guid)` projects this to the readonly `Package` interface.\ninterface MutablePackage {\n path: string;\n readonly assetGuids: Set<string>;\n}\n\n// ─── Runtime brand helper ──────────────────────────────────────────────────\n//\n// AC-11 inspect() `.brand` is a 4-member string literal union mirroring the\n// engine-types Asset discriminated union. Map a stored Asset value to its\n// brand via the `.kind` discriminator (+ `.shadingModel` refinement for\n// `MaterialAsset`, preserved for forward compatibility though the runtime\n// brand stays at the asset-kind level per AC-11 spec).\n//\n// feat-20260514 M3 / w15: the `'InstancedBufferAsset'` brand is retired\n// alongside the deleted POD + 3 registry methods; the runtime brand union\n// shrinks 5 -> 4 to mirror the Asset closed-union shape.\n// feat-20260514 w3: re-extends to 5 with the addition of the `'SceneAsset'`\n// brand mirroring the new `'scene'` kind in the Asset discriminated union.\n// feat-20260618-asset-and-pack-name-fields M1 / w3: AssetBrand moved to\n// @forgeax/engine-types (public, single-entry discoverability per charter F1).\n// feat-20260608-tilemap-object-layer-rendering M0: AssetBrand union grows\n// 13 -> 14 with `'TilesetAsset'` in @forgeax/engine-types.\n\n// feat-20260622 D-4/D-8: the 14-arm assetBrand switch and ASSET_BRAND Record\n// table are both retired (PR #496 eliminated the brand concept entirely).\n// New Asset union members no longer need a brand mapping; the closed union\n// exhaustive switch in test-d files is the sole type-level guard.\n\n// ─── Schema-driven material parse result (feat-20260523 M4-T01) ──────────\n// ─── AssetRegistry class ────────────────────────────────────────────────────\n\n/**\n * Asset registry (instance-per-engine; `engine.assets: AssetRegistry | null`).\n *\n * The builtin meshes (`HANDLE_CUBE` / `HANDLE_TRIANGLE` / ...) are served by\n * the process-static `BuiltinAssetRegistry`, so AI users see usable handles in\n * the very first frame without registration ceremony (charter proposition 1).\n *\n * @example Catalogue a texture by GUID, load its payload, and bind a material:\n * ```ts\n * const guid = engine.assets.parseGuid('00000000-0000-7000-8000-000000000001');\n * engine.assets.catalog(guid, myTexture); // GUID -> payload\n * const res = await engine.assets.loadByGuid(guid); // payload (D-17)\n * if (!res.ok) {\n * switch (res.error.code) {\n * case 'asset-not-found': // guid not catalogued\n * }\n * return;\n * }\n * const material = world.allocSharedRef('MaterialAsset', { // mint column handle\n * kind: 'material',\n * passes: [{ name: 'Forward', program: { module: 'forgeax::default-standard-pbr' }, tags: { LightMode: 'Forward' }, queue: 2000 }],\n * values: { baseColorTexture: res.value },\n * });\n * world.spawn({ component: MeshRenderer, data: { materials: [material] } });\n * ```\n */\n\n// bug-20260610 Fix B: parsed pack-file body stored in the fetchPackFile\n// in-memory cache + in-flight dedup maps (D-4). Only the raw JSON shape is\n// cached -- parseAssetPayload still runs per-call to look up the per-GUID\n// entry (CON-2 register-before-recurse cycle safety).\nexport interface ParsedPackFile {\n schemaVersion?: string;\n kind?: string;\n assets: Array<{\n guid: string;\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n artifacts?: Record<string, import('@forgeax/engine-types').ArtifactDescriptor>;\n }>;\n}\n\nexport type CatalogReconcileError = AssetError;\nexport type CatalogReconcileResult = Result<CatalogReplicaSnapshot, CatalogReconcileError>;\n\nfunction catalogSourceUnconfigured<T>(): Result<T, AssetError> {\n return err(\n new AssetError({\n code: 'catalog-source-unconfigured',\n expected: 'a configured catalog source',\n hint: ASSET_ERROR_HINTS['catalog-source-unconfigured'],\n }),\n );\n}\n\nexport class AssetRegistry {\n private catalogSource: CatalogSource | undefined;\n private catalogEnumerating: Promise<Result<readonly CatalogEntry[], AssetError>> | undefined;\n private readonly catalogListeners = new Set<CatalogListener>();\n private catalogSourceDispose: (() => void) | undefined;\n private catalogReplica: CatalogReplica | undefined;\n // feat-20260614 M8 (D-15 / D-17 / D-19): the registry is a GUID -> payload\n // catalogue. It holds NO handle concept -- it cannot mint a column handle\n // (it has no World). `loadByGuid` returns the PAYLOAD; column minting\n // (`world.allocSharedRef`) is the caller's job on the ECS/render side.\n // Sub-asset refs embedded in a payload stay as GUID strings (AssetGuid /\n // dash-form), never minted at load time. Keyed by lowercased GUID string.\n // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the\n // extracted `./registry/validate-material` free functions (detectTileNeeds-\n // RepeatSampler) can read it. No underscore + genuinely public is the\n // lint-compliant exposure (D-internal R-internal-C ties `@internal` to `_`).\n readonly assetCatalog: Map<string, AssetEnvelope<Asset>> = new Map();\n\n /** Owner-injected component catalog used for scene breadcrumb projection. */\n readonly componentCatalog: ReadonlyMap<string, Component>;\n\n // feat-20260618-asset-and-pack-name-fields M3 (D-1): the package index that\n // backs the two-segment asset identity `<packagePath>.<name>`. `packages`\n // maps a lowercased GUID key to its `MutablePackage` (a shared object every\n // GUID of the same import path points at), or `null` for assets with no\n // package (catalog() inline + builtin, D-5). All three registration entry\n // points (catalog / loadByGuid / builtin) funnel through the single\n // `registerPackage` primitive so the XOR name invariant lands once (#1 SSOT).\n private readonly packages: Map<string, MutablePackage | null> = new Map();\n\n // Secondary index path -> shared MutablePackage so every GUID of the same\n // import path points at one object (the 1->N promotion + assetCount derive\n // depend on this sharing). Not a duplicate of `packages` (#2): `packages` is\n // the per-GUID lookup; this is the per-path dedup used only inside\n // registerPackage to find-or-create the shared object.\n private readonly packageByPath: Map<string, MutablePackage> = new Map();\n\n // Per-GUID stored display names now live on the asset envelope's `name` field\n // (the single home, replacing the retired storedNameOf side table; D-6).\n // resolveName reads `assetCatalog.get(key)?.name` as the `storedName` argument\n // of deriveAssetName. `pendingNames` bridges the one ordering where a name is\n // known before its envelope exists: the prod disk path registers the package\n // (entry names) during resolveCatalogEntry, then catalogues the body later --\n // catalog() drains the pending name into the new envelope, so nothing persists\n // here once the envelope is in place.\n private readonly pendingNames: Map<string, string> = new Map();\n\n // ─── Prod pack-index fetch state (M4/w23) ──────────────────────────────\n // When packIndexUrl is configured, loadByGuid fetches pack-index.json on\n // first call, caches the parsed catalog in packIndexCache, then fetches\n // each resource URL resolved against that index and registers the asset.\n packIndexUrl: string | undefined = undefined;\n packIndexCache: Map<string, CatalogRecord> | undefined = undefined;\n /** Current browser-facing asset realm; absent for inline/shipped legacy use. */\n runtimeBinding: RuntimeAssetBinding | undefined = undefined;\n\n // tweak-20260609 M1: in-flight Map for recursive loadByGuid dedup + cycle\n // prevention (D-5 / B-10). Maps guidKey → Promise<Result<Handle, ...>> so\n // concurrent calls for the same GUID share the same fetch + register chain,\n // and cycles (A→B→A) terminate when the second visit hits the in-flight\n // entry for A instead of re-entering fetch.\n readonly inFlight: Map<string, Promise<Result<unknown, AssetError | ImageError | RhiError>>> =\n new Map();\n\n // bug-20260610 Fix B (M3 / D-4): per-instance pack-file cache keyed by\n // packageUrl (the .pack.json URL). `packFileInFlight` de-duplicates\n // concurrent fetches; `packFileCache` stores resolved bodies so the\n // same URL is fetched at most once per AssetRegistry lifetime (CON-6).\n readonly packFileCache: Map<string, ParsedPackFile> = new Map();\n readonly packFileInFlight: Map<string, Promise<ParsedPackFile>> = new Map();\n readonly artifactCache = new ArtifactReadCache();\n readonly loadState = new LoadStateStore();\n /**\n * Render-facing material readiness owned by the production GUID loader.\n * The map stores the complete tuple result, including structured failures,\n * so record code cannot silently fall back to a generic MaterialAsset.\n */\n readonly materialReadiness = new Map<string, MaterialReady | MaterialLoadError>();\n private assetEvidenceAdapter: RuntimeAssetEvidenceAdapter = createRuntimeAssetEvidenceAdapter();\n\n // feat-20260621-asset-registry-robustness-invalidate-inflight-cach F17c:\n // per-GUID generation counter incremented on each invalidate(guid) call.\n // loadByGuid captures this value at Promise creation and discards the\n // result (returning asset-invalidated) if the generation has changed by\n // the time the fetch completes.\n // F22: invalidateAll increments a single globalGeneration counter instead,\n // which invalidates every in-flight Promise regardless of GUID.\n readonly generations: Map<string, number> = new Map();\n globalGeneration: number = 0;\n /**\n * Monotonic payload-cache epoch. Render-side derived snapshots use this\n * single stamp to skip re-walking an unchanged material parent chain on\n * every frame; catalog/invalidation mutations advance it conservatively.\n */\n catalogEpoch: number = 0;\n\n // F20: per-cache Promise queue to serialise packIndexCache write operations\n // in transportOrFail. The \"check -> new Map() -> set\" three-step block is\n // not atomic across concurrent transportOrFail calls; chaining through a\n // single queue Promise ensures each patch completes before the next starts.\n packIndexCachePatchQueue: Promise<void> = Promise.resolve();\n\n // feat-20260527-sprite-nineslice M4 / w16 + w18 (D-5 + D-9): per-Renderer\n // EngineMetrics shared with the runtime so register-time soft-warns\n // (`nineslice.tile-needs-repeat-sampler` for sliceMode=1 + sampler not\n // 'repeat') and runtime soft-warns (`nineslice.scale-too-small`) increment\n // the SAME counter map. `createRenderer.ts` calls `assets.setMetrics(metrics)`\n // immediately after constructing the registry; standalone test fixtures\n // that do not go through `createRenderer` may leave this null and the\n // soft-warn paths simply no-op (charter P9 graceful degradation: the\n // structured fail-fast branches still fire; only the metric is dropped).\n // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the\n // extracted `./registry/validate-material` free functions (detectTileNeeds-\n // RepeatSampler) can read + increment it. No underscore + genuinely public\n // is the lint-compliant exposure (D-internal R-internal-C ties `@internal`\n // to `_`).\n metrics: EngineMetrics | null = null;\n\n // feat-20260707 M5 / w33 (D-11): device texture-compression caps the Basis\n // texture / equirect arms feed to `selectTranscodeTarget`. `createRenderer`\n // projects `RhiCaps` -> `TranscodeCaps` and calls `setTranscodeCaps` right\n // after construction (D-8 one-line projection). A standalone registry (test /\n // headless) keeps the all-false default, which drives the uncompressed\n // fallback path (section 8 P3, AC-04) rather than a hard failure.\n transcodeCaps: TranscodeCaps = { bc: false, etc2: false, astc: false };\n\n // feat-20260703-collect-nested-sceneinstance-to-mount-roundtrip M1 (D-1):\n // origin reverse-index: a payload object -> its catalog GUID, for payloads\n // that are NOT the current catalog identity. WeakMap so entries auto-GC when\n // the world despawns and the object is no longer held by sharedRefs.\n // _guidForAsset consults it after the catalog identity scan MISSes.\n // SSOT for the \"payload-to-GUID provenance\" fact (architecture-principles #1).\n //\n // Two writers populate it:\n // 1. instantiate (registry/instantiate.ts): the resolved SceneAsset copy ->\n // its original catalog GUID (the deep-copied envelope is never the catalog\n // identity).\n // 2. feat-20260713 M4 / w15 (D-6, root cause a): catalog() records the\n // SUPERSEDED payload here when re-cataloguing a GUID with a fresh object.\n // A handle minted before the override still points at the old object; this\n // keeps that object reverse-lookupable so save/collect resolves its GUID\n // instead of failing with a GUID-unresolved error (the 2026-07-06 crash).\n //\n // Key type is `object` (not `SceneAsset`) because both material and scene\n // payloads are recorded (material payloads flow through writer 2).\n /** @internal */\n _originIndex: WeakMap<object, string> = new WeakMap();\n\n /**\n * Construct a fresh registry pre-populated with the builtin cube + triangle\n * mesh handles (`HANDLE_CUBE` / `HANDLE_TRIANGLE`).\n *\n * feat-20260514 M3 / w15: the previous optional `RhiDevice` constructor\n * argument (consumed by the now-deleted `createInstancedBuffer` triplet)\n * is removed; the registry surface is engine-agnostic again. Per-entity\n * instance transforms now live inside the ECS `Instances { transforms:\n * 'array<f32>' }` component; the RenderSystem record stage owns GPU\n * storage buffer allocation + cap-gate.\n */\n // feat-20260603-asset-import-loader-injection M1 / w5 (D-7): the registry\n // dispatches `parseAssetPayload` / the texture+font upstream branches through\n // this `LoaderRegistry`. feat-20260623 M3 / w9: the loader registry is now\n // internally built by `createDefaultLoaderRegistry()` (public readonly field)\n // so host apps can reach `engine.assets.loaders.register(...)` without a\n // constructor-injection slot or a phantom passthrough wrapper.\n // The loader set is wired at construction from the complete ordinary Asset\n // vocabulary (including video and audio) plus caller-supplied extensions.\n // Assigned here so the optional loaders cannot appear after a load begins.\n readonly loaders: LoaderRegistry;\n\n // feat-20260603-asset-import-loader-injection M4 / w31 (AC-19 / AC-22):\n // the optional `ImportTransport` is the *only* difference between the studio\n // form (transport injected, dev DDC miss triggers lazy import) and the shipped\n // form (transport absent, DDC miss fails fast with `asset-not-imported`).\n // The load path AFTER a successful DDC fetch is identical in both forms --\n // zero branching on transport (AC-23 key invariant). Set at construction (no\n // setter, no illegal intermediate state), same D-7 stance as LoaderRegistry.\n readonly importTransport: ImportTransport | undefined;\n\n // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): optional post-spawn\n // hook invoked by `instantiate` after the scene subtree spawns. The shipped\n // implementation is runtime's `postSpawnResolveJoints` (auto-wire Skin.joints),\n // injected at the sole production assembly point (createRenderer, w10). When\n // absent (standalone / test registries), instantiate skips joint wiring\n // silently. Public so the extracted `./registry/instantiate` free function can\n // read it (D-internal R-internal-C ties `@internal` to a `_` prefix;\n // genuinely-public is the lint-compliant exposure).\n readonly postSpawnHook: PostSpawnHook | undefined;\n\n /** @internal Stored for M2 validation; TS suppressor reference */\n constructor(\n // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the\n // extracted `./registry/validate-material` free functions can read it. No\n // underscore + genuinely public is the lint-compliant exposure (an\n // `@internal` tag would require a `_` prefix per D-internal R-internal-C).\n readonly shaderRegistry: ShaderRegistry,\n importTransport?: ImportTransport | undefined,\n // Caller-supplied loaders extend the ordinary default set. Duplicate kinds\n // are rejected by LoaderRegistry so no consumer can observe replacement\n // order as an accidental ownership rule.\n extraLoaders?: readonly Loader[] | undefined,\n // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): optional\n // post-spawn hook; createRenderer injects `postSpawnResolveJoints`.\n postSpawnHook?: PostSpawnHook | undefined,\n runtimeBinding?: RuntimeAssetBinding | undefined,\n componentCatalog: ReadonlyMap<string, Component> = new Map(),\n ) {\n void this.shaderRegistry;\n this.importTransport = importTransport;\n this.postSpawnHook = postSpawnHook;\n this.runtimeBinding = runtimeBinding;\n this.componentCatalog = componentCatalog;\n this.loaders = createDefaultLoaderRegistry(extraLoaders);\n this.registerBuiltins();\n }\n\n /**\n * Restore the engine-owned GUID catalogue after a runtime-realm transition.\n *\n * Builtin meshes are process-static engine assets, not game-owned catalog\n * rows. A realm transition clears the user catalog and load caches, but must\n * leave these assets addressable so a scene in the newly bound game can keep\n * resolving its builtin mesh references.\n */\n private registerBuiltins(): void {\n // feat-20260614 M8 (D-15): builtins are GUID-addressable catalogue rows.\n // The builtin payloads also live process-static in BuiltinAssetRegistry\n // (slot < BUILTIN_BASE) for handle-tier resolution; here they are\n // catalogued by GUID so loadByGuid(builtinGuid) returns the payload and\n // scene refs[] pointing at a builtin GUID resolve without a hand-\n // maintained table (docs/feedbacks/2026-06-03 §6.2 Tier 0).\n const builtinByHandle = new Map<number, Asset>([\n [handleSlot(HANDLE_CUBE), BUILTIN_CUBE],\n [handleSlot(HANDLE_TRIANGLE), BUILTIN_TRIANGLE],\n [handleSlot(HANDLE_QUAD), BUILTIN_QUAD],\n [handleSlot(HANDLE_SPHERE), BUILTIN_SPHERE],\n [handleSlot(HANDLE_NINESLICE_QUAD), BUILTIN_NINESLICE_QUAD],\n [handleSlot(HANDLE_CYLINDER), BUILTIN_CYLINDER],\n ]);\n for (const [handle, guidStr] of BUILTIN_MESH_GUIDS) {\n const parsed = AssetGuid.parse(guidStr);\n if (!parsed.ok) {\n throw new Error(`[asset-registry] builtin GUID ${guidStr} is not a valid UUID`);\n }\n const payload = builtinByHandle.get(handleSlot(handle));\n if (payload !== undefined)\n this.assetCatalog.set(guidStr.toLowerCase(), {\n guid: guidStr,\n kind: payload.kind,\n payload,\n refs: [],\n });\n if (payload !== undefined) this.loadState.registerReady(guidStr, payload);\n }\n // D-5: builtin meshes have no import path and no source name -- register\n // them with a null package so resolveName returns '' (the detectable\n // \"genuinely no name\" signal). They are deliberately NOT given a synthetic\n // package + derived name (memory builtin-guid-preregister-collides).\n this._registerPackage(\n null,\n BUILTIN_MESH_GUIDS.map(([, guidStr]) => guidStr),\n );\n }\n\n /**\n * feat-20260527-sprite-nineslice M4 / w16 prep + w18 (D-5 + D-9): inject the\n * per-Renderer `EngineMetrics` so register-time soft-warns can bump the same\n * counter map the runtime reads through `renderer.metrics.snapshot()`. Called\n * by `createRenderer` after constructing both the registry and the metrics\n * instance; safe to skip in standalone tests (the soft-warn arms simply do\n * not record).\n */\n setMetrics(metrics: EngineMetrics): void {\n this.metrics = metrics;\n }\n\n /**\n * feat-20260707 M5 / w33 (D-11): wire the device compression caps used by the\n * Basis texture / equirect transcode arms. `createRenderer` calls this right\n * after construction with `RhiCaps` projected to `TranscodeCaps` (D-8). Left\n * at the all-false default, the loaders transcode to the uncompressed\n * `rgba8unorm` / `rgba16float` fallback (AC-04, section 8 P3).\n */\n setTranscodeCaps(caps: TranscodeCaps): void {\n this.transcodeCaps = caps;\n }\n\n /**\n * Inject authoritative runtime evidence without importing CLI or Node policy.\n * `inspect(guid)` and `verifyByGuid(guid)` return the shared state model; an\n * omitted capability remains an explicit structured error, never a pass.\n */\n configureAssetEvidence(source: RuntimeEvidenceSource): void {\n this.assetEvidenceAdapter = createRuntimeAssetEvidenceAdapter(source);\n }\n\n /**\n * @internal — read the metrics handle for register-time soft-warn paths.\n * Returns `null` when no `createRenderer` wired the registry to a renderer\n * (the standalone-test path; the structured fail-fast branches still fire).\n */\n _getMetrics(): EngineMetrics | null {\n return this.metrics;\n }\n\n /**\n * @internal — reverse-lookup: find the GUID key for a catalogued asset\n * payload by identity comparison (===). Returns the GUID string if found,\n * `undefined` otherwise. This is the SSOT for the inline identity scan\n * idiom that previously existed in two places (instantiate sceneGuidKey\n * lookup and resolveSkinAsset skeleton match).\n *\n * Linear scan of the assetCatalog (Map<string, AssetEnvelope>). The O(n)\n * cost is acceptable for save-path frequencies (OOS-2).\n */\n _guidForAsset(asset: Asset): string | undefined {\n for (const [key, envelope] of this.assetCatalog) {\n if (envelope.payload === asset) {\n return key;\n }\n }\n // feat-20260703 M1 (D-1): fallback to the origin reverse-index. Covers two\n // MISS cases the catalog identity scan cannot: (1) _resolveSceneGuids deep\n // copies — the copy is never the catalogued original; (2) feat-20260713 M4\n // (D-6): a payload superseded by a catalog override, still live behind a\n // handle minted before the override.\n return this._originIndex.get(asset as object);\n }\n\n /** Public identity projection consumed by scene collection boundaries. */\n guidOf(asset: Asset): string | undefined {\n return this._guidForAsset(asset);\n }\n\n /** Return the production MaterialReady/Error result for one material GUID. */\n getMaterialReadiness(guid: string): MaterialReady | MaterialLoadError | undefined {\n return this.materialReadiness.get(guid.toLowerCase());\n }\n\n /** Record the canonical result produced by the production material loader. */\n recordMaterialReadiness(guid: string, readiness: MaterialReady | MaterialLoadError): void {\n this.materialReadiness.set(guid.toLowerCase(), readiness);\n if (readiness.status === 'Ready') {\n installMaterialReadyShaders(this.shaderRegistry, readiness);\n }\n }\n\n /**\n * Configure a catalog URL for `loadByGuid`.\n *\n * Call this once during engine initialization with the URL where\n * `pack-index.json` is served (emitted by `@forgeax/engine-vite-plugin-pack`\n * during `vite build`). In a Vite dev host, use `configureRuntimeBinding`\n * instead so the catalog remains bound to its scope and generation. The\n * index is also the canonical base URL for every\n * catalog entry: relative, root-relative, and absolute entry URLs are resolved\n * against it before the registry fetches a pack body. After configuration,\n * `loadByGuid` will fetch the catalog on its first invocation and cache it for\n * subsequent calls.\n *\n * @example\n * ```ts\n * engine.assets.configurePackIndex('/pack-index.json');\n * const payloadRes = await engine.assets.loadByGuid(guid); // payload, not a handle (D-17)\n * ```\n */\n configurePackIndex(url: string): void {\n this.packIndexUrl = url;\n this.packIndexCache = undefined; // reset cache if URL changes\n }\n\n /**\n * Atomically replace the browser-side asset realm. The binding owns the\n * catalog URL and generation; no cache from the previous game survives the\n * transition.\n */\n configureRuntimeBinding(binding: RuntimeAssetBinding): void {\n this.clearCatalogSource();\n this.runtimeBinding = binding;\n this.configurePackIndex(binding.catalogUrl);\n this.invalidateAll();\n this.registerBuiltins();\n }\n\n /**\n * feat-20260621 F17c: invalidate a single cached asset by GUID so the next\n * `loadByGuid` performs a genuinely fresh fetch. Clears, for this GUID only:\n * the catalogue entry, the in-flight dedup entry, the cached pack-file body\n * (keyed by the index entry's packageUrl), and the pack-index entry. Then\n * increments the per-GUID generation counter so any still in-flight Promise\n * for this GUID discards its result (returns `asset-invalidated`). The body +\n * index clears are targeted (other GUIDs' cached bodies and index entries\n * survive); deleting the index entry forces `resolveCatalogEntry` to re-fetch\n * the pack-index on the next load, re-resolving the packageUrl whose body\n * cache was just dropped. No-op when the GUID is not catalogued.\n *\n * Does NOT touch `packages` (a re-load's registerPackage overwrites them; D-8)\n * and does NOT trigger GPU resource release (OOS-1,\n * q1 boundary: the asset is CPU-only; GPU resources follow the ECS).\n *\n * @param guid - Case-insensitive GUID string or AssetGuid.\n */\n invalidate(guid: string): void {\n const guidKey = guid.toLowerCase();\n // D-6: the stored name lives on the envelope; preserve it across the delete\n // (the `packages` mapping survives, so resolveName must still see the name\n // until a re-load's registerPackage overwrites it) by parking it on\n // pendingNames -- the next catalog() of this GUID drains it back.\n const survivingEnvelope = this.assetCatalog.get(guidKey);\n const survivingName = survivingEnvelope?.name;\n if (survivingName !== undefined) this.pendingNames.set(guidKey, survivingName);\n if (survivingEnvelope !== undefined) this._originIndex.set(survivingEnvelope.payload, guidKey);\n this.assetCatalog.delete(guidKey);\n this.loadState.remove(guidKey);\n this.materialReadiness.delete(guidKey);\n // R-1 hard fix (research-decisions.md): delete inFlight entry so the\n // next loadByGuid does not hit the old Promise whose generation no\n // longer matches (AC-04 requires a fresh fetch, not asset-invalidated).\n this.inFlight.delete(guidKey);\n // Round-2 M-A: widen the clear so a COMPLETED reload re-fetches fresh\n // bytes instead of serving the stale cached body. Ordering is load-bearing:\n // read packageUrl from the index entry FIRST, then delete the body, then\n // delete the index entry. Targeted delete (not wholesale undefined) keeps\n // other GUIDs' cached bodies/index entries intact (per-GUID precision).\n const entry = this.packIndexCache?.get(guidKey);\n if (entry !== undefined) this.packFileCache.delete(entry.packageUrl);\n this.packIndexCache?.delete(guidKey);\n this.generations.set(guidKey, (this.generations.get(guidKey) ?? 0) + 1);\n this.catalogEpoch++;\n }\n\n /**\n * Adopt freshly loaded Mesh material slots into an object that is already\n * pinned by live World shared refs. Geometry and GPU-backed fields deliberately\n * remain untouched: this primitive is only for a default-material source\n * override, never a general Mesh reimport. This is the atomic cutover: Catalog,\n * Ready load state, and payload-to-GUID provenance must all name the same\n * object after the call. Call only after invalidate(guid) + loadByGuid(guid)\n * has completed successfully.\n */\n adoptReloadedMeshMaterialSlots(guid: string, livePayload: Asset): Result<Asset, AssetError> {\n const key = guid.toLowerCase();\n const envelope = this.assetCatalog.get(key);\n const freshPayload = this.loadState.getReady<Asset>(key);\n if (envelope === undefined || freshPayload === undefined || envelope.payload !== freshPayload) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${key} to have one freshly loaded Ready payload`,\n hint: 'complete invalidate + loadByGuid before adopting a live Mesh identity',\n }),\n );\n }\n if (livePayload.kind !== 'mesh' || freshPayload.kind !== 'mesh') {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `GUID ${key} live and fresh payloads to both be MeshAsset`,\n hint: 'use Mesh identity adoption only for a recooked MeshAsset',\n }),\n );\n }\n if (this._guidForAsset(livePayload) !== key) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `live Mesh payload to retain GUID provenance for ${key}`,\n hint: 'capture the catalogued live payload before invalidating and reloading the same GUID',\n }),\n );\n }\n if (livePayload === freshPayload) return ok(livePayload);\n\n (livePayload as unknown as { materialSlots: TypesMeshAsset['materialSlots'] }).materialSlots =\n freshPayload.materialSlots;\n this._originIndex.set(freshPayload as object, key);\n this.assetCatalog.set(key, { ...envelope, payload: livePayload });\n this.loadState.registerReady(key, livePayload);\n this.catalogEpoch++;\n return ok(livePayload);\n }\n\n /**\n * feat-20260621 F17c: invalidate ALL cached assets so the next `loadByGuid`\n * re-fetches both the pack-index and the asset body. Clears assetCatalog,\n * inFlight, and packFileCache (wholesale), and resets packIndexCache to\n * `undefined` (NOT `.clear()` -- an empty Map would short-circuit\n * `resolveCatalogEntry`'s `=== undefined` re-fetch guard and serve\n * asset-not-imported for every later load; undefined forces a fresh\n * fetchPackIndex). Then increments a single globalGeneration counter so every\n * in-flight Promise (regardless of GUID) discards its result. Returns the\n * number of assets that were catalogued before the call.\n *\n * Idempotent: second call on an already-empty catalogue returns clearedCount 0\n * (AC-06). Does NOT trigger GPU resource release (OOS-1).\n */\n invalidateAll(): { clearedCount: number } {\n const count = this.assetCatalog.size;\n this.assetCatalog.clear();\n this.loadState.clear();\n this.materialReadiness.clear();\n this.inFlight.clear();\n this.globalGeneration++;\n // Round-2 M-A: wholesale clear of the shared body cache, and reset the\n // index cache to UNDEFINED (R2-1) -- NOT .clear(). packFileCache uses\n // .clear() because fetchPackFile checks `.get(packageUrl)` per URL, so an\n // empty Map correctly misses and re-fetches. packIndexCache uses =undefined\n // because resolveCatalogEntry's re-fetch guard tests `=== undefined`; an\n // empty Map would short-circuit it and serve asset-not-imported for every\n // later load -- the exact F17b pollution this feat fixes. The asymmetry is\n // intentional; do not normalise the two operations.\n this.packFileCache.clear();\n this.packIndexCache = undefined;\n this.catalogEpoch++;\n return { clearedCount: count };\n }\n\n /**\n * Force a re-fetch of the configured pack-index NOW and repopulate the cache,\n * so a synchronous `listCatalog()` immediately reflects assets added on disk\n * since boot (a freshly imported GLB's sub-assets). `loadByGuid`'s lazy\n * re-fetch only fires on a per-GUID miss and `invalidateAll()` merely clears\n * the cache (leaving `listCatalog()` empty until the next load), so neither\n * makes a Content Browser or `loadByGuid`-driven \"Add to Scene\" see a new\n * asset without a page reload. This does.\n *\n * No-op (returns false) when no pack-index URL is configured (dev inline\n * catalogue path) or the fetch fails — callers keep the stale cache rather\n * than blanking it. Returns true when the cache was repopulated.\n */\n async refreshCatalog(): Promise<boolean> {\n if (this.packIndexUrl === undefined) return false;\n const result = await fetchPackIndex(this);\n if (!result.ok) return false;\n this.packIndexCache = result.value;\n registerPackagesFromIndex(this, this.packIndexCache);\n return true;\n }\n\n setCatalogSource(source: CatalogSource): void {\n this.clearCatalogSource();\n this.catalogSource = source;\n this.catalogReplica = new CatalogReplica(source);\n this.catalogSourceDispose = this.catalogReplica.subscribe((delta) => {\n for (const listener of [...this.catalogListeners]) {\n try {\n listener(delta);\n } catch {\n // One host listener cannot prevent the remaining listeners from seeing a fact.\n }\n }\n });\n void this.catalogReplica.start();\n }\n\n /** Stop the catalog transport and remove its replica without clearing payload caches. */\n clearCatalogSource(): void {\n this.catalogReplica?.dispose();\n this.catalogSourceDispose?.();\n this.catalogSourceDispose = undefined;\n this.catalogSource = undefined;\n this.catalogReplica = undefined;\n this.catalogEnumerating = undefined;\n }\n\n enumerateCatalog(): Promise<Result<readonly CatalogEntry[], AssetError>> {\n if (this.catalogEnumerating !== undefined) return this.catalogEnumerating;\n if (this.catalogSource === undefined || this.catalogReplica === undefined) {\n return Promise.resolve(catalogSourceUnconfigured());\n }\n const promise = this.catalogReplica\n .start()\n .then((result) => (result.ok ? ok(result.value.entries) : result));\n this.catalogEnumerating = promise;\n void promise.then(() => {\n this.catalogEnumerating = undefined;\n });\n return promise;\n }\n\n /** Read the immutable catalog projection folded by this registry. */\n catalogSnapshot(): CatalogReplicaSnapshot | undefined {\n return this.catalogReplica?.snapshot();\n }\n\n /** Explicitly recover the registry's single catalog replica from its configured source. */\n reconcileCatalog(): Promise<CatalogReconcileResult> {\n if (this.catalogSource === undefined || this.catalogReplica === undefined) {\n return Promise.resolve(catalogSourceUnconfigured());\n }\n return this.catalogReplica.reconcile();\n }\n\n subscribeCatalog(listener: CatalogListener): () => void {\n this.catalogListeners.add(listener);\n return () => {\n this.catalogListeners.delete(listener);\n };\n }\n\n /**\n * Materialise a `SceneAsset` into an existing `World` and return the\n * synthetic root `Entity` (feat-20260514 w31 sugar wrapper; AC-03 +\n * requirements §IN-3; M3: returns Entity not SceneInstanceId).\n *\n * Before spawning, handle-type component fields (e.g. `assetHandle`,\n * `material`, `skeleton`) containing GUID strings are resolved to fresh\n * user-tier `Handle` numbers via `world.allocSharedRef` (feat-20260614 M8\n * D-19 instantiate-time GUID->handle mint; supersedes the pre-D-17\n * `resolveGuid` map). GUIDs that fail to parse or are not catalogued return\n * `AssetError(code='asset-not-found')` with a hint containing the GUID,\n * node localId, and field name.\n *\n * Errors propagate verbatim through the closed\n * `AssetError | PackError | EcsError` union so AI users that already\n * narrow `loadByGuid<SceneAsset>` results reuse the same `switch\n * (err.code)` exhaustively (charter proposition 3 machine-readable\n * union; plan-strategy §3.3 closed-union transparency).\n *\n * @example\n * ```ts\n * const sceneRes = await engine.assets.loadByGuid<SceneAsset>(roomGuid); // payload (D-17)\n * if (!sceneRes.ok) return;\n * const handle = world.allocSharedRef('SceneAsset', sceneRes.value); // mint column handle\n * const r = engine.assets.instantiate(handle, world);\n * if (!r.ok) {\n * switch (r.error.code) {\n * case 'asset-not-found':\n * case 'pack-cyclic-reference':\n * // ... AssetErrorCode | PackErrorCode | EcsErrorCode exhaustive\n * }\n * }\n * ```\n */\n instantiate<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent?: EntityHandle,\n ): Result<EntityHandle, AssetError | PackError | EcsError> {\n return instantiateImpl(this, handle, world, parent) as Result<\n EntityHandle,\n AssetError | PackError | EcsError\n >;\n }\n\n instantiateWithPublicationFence<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent: EntityHandle | undefined,\n expectedPublication: ScenePublicationFence,\n ): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError>;\n instantiateWithPublicationFence<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent: EntityHandle | undefined,\n expectedPublication: ScenePublicationFence,\n ): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError> {\n return instantiateImpl(this, handle, world, parent, expectedPublication);\n }\n\n /**\n * Materialise a `SceneAsset` FLAT into an existing `World` — the \"open a scene\n * for authoring\" registry entry (#655): NO synthetic SceneInstance root, NO\n * forced `ChildOf` on top-level members. Returns the top-level entity handles.\n * Nested prefabs (`mounts[]`) still materialise as their own SceneInstance\n * anchors. Use {@link instantiate} (anchor) at runtime / Play and for nested\n * prefabs.\n */\n instantiateFlat<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n ): Result<EntityHandle[], AssetError | PackError | EcsError> {\n return instantiateFlatImpl(this, handle, world) as Result<\n EntityHandle[],\n AssetError | PackError | EcsError\n >;\n }\n\n instantiateFlatWithPublicationFence<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n expectedPublication: ScenePublicationFence,\n ): Result<EntityHandle[], AssetError | PackError | EcsError | ScenePublicationFenceError> {\n return instantiateFlatImpl(this, handle, world, expectedPublication);\n }\n\n private sceneMeshGuidBySlot(\n scene: SceneAsset,\n visited: Set<string> = new Set(),\n ): Map<number, string> {\n const result = new Map<number, string>();\n for (const entity of scene.entities) {\n const components = entity.components as Record<string, Record<string, unknown>>;\n const meshGuid = components.MeshFilter?.assetHandle;\n if (typeof meshGuid === 'string') result.set(entity.localId as number, meshGuid);\n }\n for (const mount of scene.mounts ?? []) {\n const mountComponents = mount.components as\n | Record<string, Record<string, unknown>>\n | undefined;\n const mountMeshGuid = mountComponents?.MeshFilter?.assetHandle;\n if (typeof mountMeshGuid === 'string') result.set(mount.localId as number, mountMeshGuid);\n if (typeof mount.source !== 'string') continue;\n const childKey = mount.source.toLowerCase();\n if (visited.has(childKey)) continue;\n const child = this.assetCatalog.get(childKey)?.payload;\n if (child?.kind !== 'scene') continue;\n const childVisited = new Set(visited);\n childVisited.add(childKey);\n const childSlots = this.sceneMeshGuidBySlot(child, childVisited);\n const first = mount.memberFirst as unknown as number;\n for (const [childSlot, meshGuid] of childSlots) result.set(first + childSlot, meshGuid);\n for (const override of mount.overrides ?? []) {\n if (override.comp !== 'MeshFilter') continue;\n const nextMeshGuid =\n override.field === 'assetHandle'\n ? override.value\n : override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null &&\n !Array.isArray(override.value)\n ? (override.value as Record<string, unknown>).assetHandle\n : undefined;\n if (typeof nextMeshGuid === 'string') {\n result.set(override.localId as unknown as number, nextMeshGuid);\n }\n }\n }\n return result;\n }\n\n private migrateLegacySceneMaterialOverrides(\n scene: SceneAsset,\n sceneGuidKey?: string,\n ): Result<{ readonly scene: SceneAsset; readonly changed: boolean }, AssetError> {\n const nodes: SceneEntity[] = [];\n let changed = false;\n for (const node of scene.entities) {\n const components = node.components as Record<string, Record<string, unknown>>;\n const rawMeshGuid = components.MeshFilter?.assetHandle;\n const meshGuid = typeof rawMeshGuid === 'string' ? rawMeshGuid : undefined;\n const legacyOverrides = components.MeshRenderer?.materials;\n const mesh =\n meshGuid === undefined ? undefined : this.assetCatalog.get(meshGuid.toLowerCase())?.payload;\n if (\n mesh?.kind !== 'mesh' ||\n meshGuid === undefined ||\n !Array.isArray(legacyOverrides) ||\n legacyOverrides.length < mesh.submeshes.length ||\n mesh.submeshes.length <= mesh.materialSlots.length ||\n !legacyOverrides.every((value) => typeof value === 'string')\n ) {\n nodes.push(node);\n continue;\n }\n const migrated = migrateLegacyMeshMaterialOverrides(\n legacyOverrides as string[],\n mesh.submeshes,\n mesh.materialSlots.length,\n {\n meshGuid: meshGuid.toLowerCase(),\n sceneGuid: sceneGuidKey ?? '<unregistered-scene>',\n entityId: node.localId as number,\n },\n );\n if (!migrated.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected:\n 'legacy per-submesh material overrides to collapse unambiguously onto Mesh v3 slots',\n hint: migrated.error.hint,\n detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,\n }),\n );\n }\n changed = true;\n nodes.push({\n ...node,\n components: {\n ...components,\n MeshRenderer: { ...components.MeshRenderer, materials: migrated.overrides },\n },\n } as SceneEntity);\n }\n\n const mounts: SceneInstanceMount[] = [];\n for (const mount of scene.mounts ?? []) {\n const child =\n typeof mount.source === 'string'\n ? this.assetCatalog.get(mount.source.toLowerCase())?.payload\n : undefined;\n let nextMount = mount;\n let mountChanged = false;\n const mountComponents = mount.components as\n | Record<string, Record<string, unknown>>\n | undefined;\n const mountMeshGuid = mountComponents?.MeshFilter?.assetHandle;\n const mountMaterials = mountComponents?.MeshRenderer?.materials;\n const mountMesh =\n typeof mountMeshGuid === 'string'\n ? this.assetCatalog.get(mountMeshGuid.toLowerCase())?.payload\n : undefined;\n if (\n mountMesh?.kind === 'mesh' &&\n typeof mountMeshGuid === 'string' &&\n Array.isArray(mountMaterials) &&\n mountMaterials.length >= mountMesh.submeshes.length &&\n mountMesh.submeshes.length > mountMesh.materialSlots.length &&\n mountMaterials.every((value) => typeof value === 'string')\n ) {\n const migrated = migrateLegacyMeshMaterialOverrides(\n mountMaterials as string[],\n mountMesh.submeshes,\n mountMesh.materialSlots.length,\n {\n meshGuid: mountMeshGuid.toLowerCase(),\n sceneGuid: sceneGuidKey ?? '<unregistered-scene>',\n entityId: mount.localId as unknown as number,\n },\n );\n if (!migrated.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected:\n 'legacy mount-entity materials to collapse unambiguously onto Mesh v3 slots',\n hint: migrated.error.hint,\n detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,\n }),\n );\n }\n mountChanged = true;\n nextMount = {\n ...mount,\n components: {\n ...mountComponents,\n MeshRenderer: { ...mountComponents?.MeshRenderer, materials: migrated.overrides },\n },\n } as SceneInstanceMount;\n }\n if (child?.kind !== 'scene' || mount.overrides === undefined) {\n if (mountChanged) changed = true;\n mounts.push(nextMount);\n continue;\n }\n const meshByMember = this.sceneMeshGuidBySlot(child);\n const nextOverrides: MountOverride[] = [];\n for (const override of mount.overrides) {\n const childLocalId =\n (override.localId as unknown as number) - (mount.memberFirst as unknown as number);\n if (override.comp === 'MeshFilter') {\n const nextMeshGuid =\n override.field === 'assetHandle'\n ? override.value\n : override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null &&\n !Array.isArray(override.value)\n ? (override.value as Record<string, unknown>).assetHandle\n : undefined;\n if (typeof nextMeshGuid === 'string') meshByMember.set(childLocalId, nextMeshGuid);\n nextOverrides.push(override);\n continue;\n }\n const legacyMaterials =\n override.comp === 'MeshRenderer' && override.field === 'materials'\n ? override.value\n : override.comp === 'MeshRenderer' &&\n override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null &&\n !Array.isArray(override.value)\n ? (override.value as Record<string, unknown>).materials\n : undefined;\n const meshGuid = meshByMember.get(childLocalId);\n const mesh =\n meshGuid === undefined\n ? undefined\n : this.assetCatalog.get(meshGuid.toLowerCase())?.payload;\n if (\n mesh?.kind !== 'mesh' ||\n meshGuid === undefined ||\n !Array.isArray(legacyMaterials) ||\n legacyMaterials.length < mesh.submeshes.length ||\n mesh.submeshes.length <= mesh.materialSlots.length ||\n !legacyMaterials.every((value) => typeof value === 'string')\n ) {\n nextOverrides.push(override);\n continue;\n }\n const migrated = migrateLegacyMeshMaterialOverrides(\n legacyMaterials as string[],\n mesh.submeshes,\n mesh.materialSlots.length,\n {\n meshGuid: meshGuid.toLowerCase(),\n sceneGuid: sceneGuidKey ?? '<unregistered-scene>',\n entityId: override.localId as unknown as number,\n },\n );\n if (!migrated.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected:\n 'legacy mount material overrides to collapse unambiguously onto Mesh v3 slots',\n hint: migrated.error.hint,\n detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,\n }),\n );\n }\n mountChanged = true;\n nextOverrides.push(\n override.field === 'materials'\n ? { ...override, value: migrated.overrides }\n : {\n ...override,\n value: {\n ...(override.value as Record<string, unknown>),\n materials: migrated.overrides,\n },\n },\n );\n }\n if (mountChanged) {\n changed = true;\n mounts.push({ ...nextMount, overrides: nextOverrides });\n } else {\n mounts.push(nextMount);\n }\n }\n return ok({\n scene: changed\n ? {\n ...scene,\n entities: nodes,\n ...(scene.mounts === undefined ? {} : { mounts }),\n }\n : scene,\n changed,\n });\n }\n\n private preflightSceneMaterialGraph(\n scene: SceneAsset,\n sceneGuidKey?: string,\n visited: Set<string> = new Set(),\n ): Result<void, AssetError> {\n const key = sceneGuidKey?.toLowerCase();\n if (key !== undefined) {\n if (visited.has(key)) return ok(undefined);\n visited.add(key);\n }\n const local = this.migrateLegacySceneMaterialOverrides(scene, sceneGuidKey);\n if (!local.ok) return local;\n for (const mount of scene.mounts ?? []) {\n if (typeof mount.source !== 'string') continue;\n const childKey = mount.source.toLowerCase();\n const child = this.assetCatalog.get(childKey)?.payload;\n if (child?.kind !== 'scene') continue;\n const nested = this.preflightSceneMaterialGraph(child, childKey, visited);\n if (!nested.ok) return nested;\n }\n return ok(undefined);\n }\n\n /**\n * @internal\n * Transform a SceneAsset whose handle-type component fields hold GUID\n * strings (post-parseScenePayload intermediate state) into a copy whose\n * handle fields hold resolved Handle numbers.\n *\n * Schema-driven field detection (plan-strategy D-4): for each component\n * field whose Component.schema fieldType starts with `shared\\<`, the\n * value is treated as a GUID string and resolved via `AssetGuid.parse` +\n * catalogue lookup + `world.internSharedRef` (feat-20260614 M8 D-15/D-17;\n * the registry mints nothing). Unknown component names are silently passed\n * through (the ecs layer's additionalProperties check will catch unknowns at\n * spawn if appropriate).\n *\n * Stop-on-first-error (AC-08): the first unresolvable GUID aborts\n * iteration and returns `AssetError(code='asset-not-found')` with a hint\n * containing the GUID string, node localId, and field name for AI-user\n * debuggability (P3).\n */\n _resolveSceneGuids(\n scene: SceneAsset,\n world: World,\n sceneGuidKey?: string,\n _visitedMountGuids?: Set<string>,\n _guidToHandle?: Map<string, number>,\n _resolvedSceneHandles?: Map<string, number>,\n _materialGraphPreflighted = false,\n ): Result<SceneAsset, AssetError> {\n // feat-20260622 M3 / w8: reverse-decode from envelope.refs edges when\n // sceneGuidKey is provided and the catalog holds an envelope for this\n // scene. Each edge with sceneEntityId+sourceField.componentName carries\n // the (entityLocalId, componentName, fieldName, arrayIndex) triple —\n // no need to walk entities with a process-global component reflection table.\n // D-15/D-17 dedup contract: the same catalogued payload referenced from\n // multiple nodes must resolve to ONE user-tier handle. The local GUID map\n // avoids repeat lookups inside this traversal; World interning preserves\n // payload identity across separate scene-resolution calls.\n if (!_materialGraphPreflighted) {\n const graph = this.preflightSceneMaterialGraph(scene, sceneGuidKey);\n if (!graph.ok) return graph;\n }\n const localMigration = this.migrateLegacySceneMaterialOverrides(scene, sceneGuidKey);\n if (!localMigration.ok) return localMigration;\n const sceneForResolution = localMigration.value.scene;\n const preflightChanged = localMigration.value.changed;\n\n const resolvedMap = new Map<string, number>();\n const guidToHandle = _guidToHandle ?? new Map<string, number>();\n const resolvedSceneHandles = _resolvedSceneHandles ?? new Map<string, number>();\n const sceneEnvelope =\n !preflightChanged && sceneGuidKey !== undefined\n ? this.assetCatalog.get(sceneGuidKey)\n : undefined;\n // Did the structured-edge branch actually resolve anything? Prod-loaded\n // packs catalogue refs[] as GUID-only edges (sourceField / sceneEntityId\n // stripped at the w7 D-10 serialization boundary), so the rich-edge loop\n // below `continue`-skips every ref and resolves nothing. When that happens\n // we MUST fall through to the entity-walk fallback — otherwise the handle\n // fields keep their GUID strings and `spawn` writes the sentinel 0 while\n // `retainSharedScalarHandle(GUID)` routes `shared-ref-released` (the on-disk\n // game-scene instantiate crash: enemy MeshFilter.assetHandle).\n let resolvedFromEdges = false;\n if (\n sceneEnvelope !== undefined &&\n sceneEnvelope.refs !== undefined &&\n sceneEnvelope.refs.length > 0\n ) {\n for (const ref of sceneEnvelope.refs) {\n const { sceneEntityId, sourceField } = ref;\n if (sceneEntityId === undefined || sourceField === undefined) continue;\n const { componentName, fieldName, arrayIndex } = sourceField;\n if (componentName === undefined || fieldName === undefined) continue;\n\n const fieldPath = `${componentName}.${fieldName}${arrayIndex !== undefined ? `[${arrayIndex}]` : ''}`;\n\n const envelope = this.assetCatalog.get(ref.guid.toLowerCase());\n if (envelope === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${ref.guid} catalogued in AssetRegistry`,\n hint:\n `GUID ${ref.guid} not catalogued; ` +\n `call loadByGuid('${ref.guid}') before instantiate; ` +\n `at node localId=${sceneEntityId}, field=${fieldPath}`,\n }),\n );\n }\n const payload = envelope.payload;\n const guidKey = ref.guid.toLowerCase();\n let resolvedSlot = guidToHandle.get(guidKey);\n if (resolvedSlot === undefined) {\n resolvedSlot = unwrapHandle(world.internSharedRef(payload.kind, payload));\n guidToHandle.set(guidKey, resolvedSlot);\n }\n\n const key =\n `${sceneEntityId}|${componentName}|${fieldName}` +\n (arrayIndex !== undefined ? `|${arrayIndex}` : '|');\n resolvedMap.set(key, resolvedSlot);\n resolvedFromEdges = true;\n }\n }\n if (!resolvedFromEdges) {\n // Fallback: positive extraction via extractSceneEntityHandleGuids when\n // the structured edges resolved nothing — either the scene envelope is\n // absent (unit tests that build a SceneAsset without cataloguing it) OR\n // the catalogued refs[] are GUID-only with no per-entity metadata (the\n // prod on-disk pack path). The entity-component walk recovers the\n // (localId, componentName, fieldName, arrayIndex) triple the bare edge\n // dropped, so GUID strings resolve to live handles before spawn.\n const entries = extractSceneEntityHandleGuids(\n world.components.entries(),\n sceneForResolution.entities as unknown as ReadonlyArray<{\n readonly localId: number;\n readonly components: Record<string, Record<string, unknown>>;\n }>,\n );\n\n for (const entry of entries) {\n const fieldPath =\n `${entry.componentName}.${entry.fieldName}` +\n (entry.arrayIndex !== undefined ? `[${entry.arrayIndex}]` : '');\n const resolvedSlot = resolveHandleGuid(\n this,\n world,\n entry.guidString,\n guidToHandle,\n fieldPath,\n `node localId=${entry.entityLocalId}`,\n );\n if (!resolvedSlot.ok) return resolvedSlot;\n\n const key =\n `${entry.entityLocalId}|${entry.componentName}|${entry.fieldName}` +\n (entry.arrayIndex !== undefined ? `|${entry.arrayIndex}` : '|');\n resolvedMap.set(key, resolvedSlot.value);\n }\n }\n\n // Build the resolved copy. Handle-type fields (detected above) are\n // reconstructed from the resolvedMap; all other fields pass through as-is.\n const resolvedNodes: SceneEntity[] = [];\n for (const node of sceneForResolution.entities) {\n const rawComponents = node.components as Record<string, Record<string, unknown>>;\n const resolvedComponents: Record<string, Record<string, unknown>> = {};\n\n for (const compName of Object.keys(rawComponents)) {\n const rawFields = rawComponents[compName];\n if (!rawFields) {\n resolvedComponents[compName] = {};\n continue;\n }\n const resolvedFields: Record<string, unknown> = {};\n for (const fieldName of Object.keys(rawFields)) {\n const value = rawFields[fieldName];\n const plainKey = `${node.localId}|${compName}|${fieldName}|`;\n const plainResolved = resolvedMap.get(plainKey);\n if (plainResolved !== undefined) {\n resolvedFields[fieldName] = plainResolved;\n } else if (Array.isArray(value)) {\n const resolvedArr: number[] = [];\n let hasAnyResolved = false;\n for (let i = 0; i < value.length; i++) {\n const arrKey = `${node.localId}|${compName}|${fieldName}|${i}`;\n const arrResolved = resolvedMap.get(arrKey);\n if (arrResolved !== undefined) {\n resolvedArr.push(arrResolved);\n hasAnyResolved = true;\n } else if (typeof value[i] === 'number') {\n resolvedArr.push(value[i]);\n }\n }\n resolvedFields[fieldName] = hasAnyResolved ? resolvedArr : value;\n } else {\n resolvedFields[fieldName] = value;\n }\n }\n resolvedComponents[compName] = resolvedFields;\n }\n resolvedNodes.push({\n localId: node.localId,\n components: resolvedComponents,\n });\n }\n\n // ── m3-i2 / m3-i3: Resolve mounts recursively (breakpoint B fix) ──\n // For each mount.source (GUID string), look up the child scene in\n // assetCatalog, recursively resolve its GUIDs, allocSharedRef the\n // resolved child copy, register it in originIndex (D-7), and produce\n // a resolved mount with source as the live handle number.\n // Cycle detection via visited GUID set (R-9): re-entry =>\n // pack-cyclic-reference / mount-asset, cast through the return type\n // as world.ts does for its PackError exits.\n const mountVisited = _visitedMountGuids ?? new Set<string>();\n if (sceneGuidKey !== undefined) mountVisited.add(sceneGuidKey.toLowerCase());\n if (sceneForResolution.mounts !== undefined && sceneForResolution.mounts.length > 0) {\n // feat-20260713 M3 / w13: share the entity-field dedup map so an override\n // value GUID that also appears as an entity field mints one handle (D-15/D-17).\n const resolvedMounts = resolveMountsRec(\n this,\n sceneForResolution.mounts,\n world,\n mountVisited,\n guidToHandle,\n resolvedSceneHandles,\n );\n if (sceneGuidKey !== undefined) mountVisited.delete(sceneGuidKey.toLowerCase());\n if (!resolvedMounts.ok) {\n // Cycle or child-resolution error: cast through as AssetError\n // (same pattern as world.ts PackError-as-EcsError casts).\n return resolvedMounts as unknown as Result<SceneAsset, AssetError>;\n }\n return ok({\n kind: 'scene',\n entities: resolvedNodes,\n mounts: resolvedMounts.value,\n } as SceneAsset);\n }\n if (sceneGuidKey !== undefined) mountVisited.delete(sceneGuidKey.toLowerCase());\n return ok({ kind: 'scene', entities: resolvedNodes });\n }\n\n /**\n * Register an asset and return a fresh\n * `Result<Handle<TagOf<T>, 'shared'>, AssetError>`. The brand `target`\n * tag is derived from the Asset's `kind` discriminator via `AssetTagMap`\n * (charter F1 single-entry indexability). The runtime representation is\n * an auto-incrementing u32 starting at 1024 (builtins reserve 1-2).\n *\n * feat-20260526 M4: `shadingModel` field is retired in favour of\n * pass-based MaterialAsset. This generic surface covers the full\n * `Asset` closed union (mesh / texture / sampler / scene / equirect\n * / material).\n */\n /**\n * feat-20260614 M8 (D-15 / D-17): catalogue a payload under its GUID.\n * Replaces the old `register` / `registerWithGuid` mint pair -- the registry\n * stores the PAYLOAD and never produces a handle (it owns no World).\n * Column minting is the caller's job via `world.allocSharedRef`.\n *\n * Validates mesh stride + material passes / sprite slices at catalogue entry\n * (same fail-fast surface as the old register path). Returns\n * `Result.err(AssetError)` on validation failure; `Result.ok(payload)` with\n * the stored payload (mesh payloads gain an `aabb`) on success.\n */\n catalog<T = Asset>(\n guid: AssetGuid | string,\n asset: T,\n refs?: readonly AssetRef[],\n ): Result<T, AssetError> {\n // D-5: narrow T to Asset for kind-discriminate branches. The runtime\n // catalog only accepts Asset-kind payloads (host custom kinds enter\n // through loadByGuid + registerParsedAsset, not catalog directly).\n const a: Asset = asset as unknown as Asset;\n const meshValidation = validateMeshPayload(a);\n if (meshValidation !== null) return err(meshValidation);\n\n // feat-20260608 M0 baseline rebuild: tileset payload fail-fast gate at\n // register entry — region rectangle bounds-check uses the implicit atlas\n // extent (columns * tileWidth x rows * tileHeight) when the caller did\n // not supply an explicit one (charter P3 explicit failure).\n if (a.kind === 'tileset') {\n const tilesetAsset = a as TilesetAsset;\n const tilesetValidation = validateTilesetPayload(\n tilesetAsset,\n inferAtlasExtent(tilesetAsset),\n );\n if (tilesetValidation !== null) return err(tilesetValidation);\n }\n\n // feat-20260527 M2 / w6: material validation with union paramSchema\n // semantics across all passes (plan-strategy D-2, D-5).\n if (a.kind === 'material') {\n const matValidation = validateMaterialPasses(this, a as MaterialAsset);\n if (matValidation !== null) return err(matValidation);\n const sliceValidation = validateSpriteSlices(this, a as MaterialAsset);\n if (sliceValidation !== null) return err(sliceValidation);\n detectTileNeedsRepeatSampler(this, a as MaterialAsset);\n }\n\n let stored: Asset = a;\n if (a.kind === 'mesh') {\n stored = withMeshAabb(a as TypesMeshAsset);\n }\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const kind = a.kind;\n // Drain any name recorded by an earlier _registerPackage call whose body had\n // not yet been catalogued (prod disk path; D-6). Preserve a name already on\n // a prior envelope for this key (re-catalog of the same GUID).\n const pendingName = this.pendingNames.get(key);\n const priorEnvelope = this.assetCatalog.get(key);\n const priorName = priorEnvelope?.name;\n const name = pendingName ?? priorName;\n this.pendingNames.delete(key);\n // feat-20260713 M4 / w15 (D-6, root cause a): when this GUID is being\n // re-catalogued with a DIFFERENT payload object, the prior object may still\n // be live behind a handle minted before the override (asset-registry.ts:513\n // identity scan would then MISS it). Record the superseded object -> GUID in\n // the origin reverse-index so `_guidForAsset` keeps resolving it — save/\n // collect of an owned entity holding that handle no longer fails with a\n // GUID-unresolved error (the 2026-07-06 crash). Structurally-modified copies\n // (a fresh object never catalogued) stay uncatalogued and correctly surface a\n // structured error at collect (requirements edge case \"modified payload judged\n // as a new asset, not silently zeroed\").\n if (priorEnvelope !== undefined && priorEnvelope.payload !== stored) {\n this._originIndex.set(priorEnvelope.payload, key);\n }\n this.assetCatalog.set(key, {\n guid: key,\n kind,\n ...(name !== undefined ? { name } : {}),\n payload: stored,\n refs: refs ?? [],\n });\n this.catalogEpoch++;\n this.loadState.registerReady(key, stored);\n // D-1: catalog() inline path defaults every GUID to the no-package state\n // (null). loadByGuid + builtin override via their own registerPackage calls\n // before / after this so the package mapping is populated for all assets\n // through the single primitive (#1 SSOT). Do not clobber a package mapping\n // a prior registerPackage already established for this GUID.\n if (!this.packages.has(key)) this.packages.set(key, null);\n return ok(stored as T);\n }\n\n /**\n * @internal feat-20260618-asset-and-pack-name-fields M3 (D-1): the single\n * package-mapping write primitive. All three registration entry points funnel\n * here so the XOR name invariant is implemented once (#1 SSOT):\n * - catalog() inline path -> registerPackage(null, [guid]) (no package)\n * - loadByGuid disk path -> registerPackage(packageUrl, [g1,g2,...], names)\n * - constructor builtin -> registerPackage(null, [...guids]) (D-5 null)\n *\n * `path === null` registers the GUIDs with no package (resolveName reads their\n * storedName or returns ''). A non-null `path` finds-or-creates the shared\n * MutablePackage for that path and adds the GUIDs to it; per-GUID entry names\n * (D-2: name flows entry -> Package, never the payload) are taken from\n * `names`. The 1->N promotion branch (D-3) is added by w11. Never throws --\n * it only writes maps; resolution + validation happen in resolveName / rename.\n */\n _registerPackage(\n path: string | null,\n guids: readonly string[],\n names?: Map<string, string>,\n ): void {\n if (path === null) {\n for (const g of guids) {\n const key = g.toLowerCase();\n this.packages.set(key, null);\n const n = names?.get(g) ?? names?.get(key);\n if (n !== undefined) this.setStoredName(key, n);\n }\n return;\n }\n\n const pkg = this.packageByPath.get(path) ?? { path, assetGuids: new Set<string>() };\n this.packageByPath.set(path, pkg);\n\n // D-3: 1->N promotion. When this path already holds exactly one asset and a\n // new member is arriving, freeze the original asset's derived basename as its\n // stored name so it joins the multi-asset branch with a stable name. The\n // freeze is idempotent: an original that already carries a stored name (the\n // abnormal single-asset-with-name state, D-4) is left untouched and the\n // soft-violation counter records it (charter P3 machine-readable signal).\n const addsNewMember = guids.some((g) => !pkg.assetGuids.has(g.toLowerCase()));\n if (pkg.assetGuids.size === 1 && addsNewMember) {\n const [originalKey] = pkg.assetGuids;\n if (originalKey !== undefined) {\n if (this.hasStoredName(originalKey)) {\n this.metrics?.increment('package.xor-invariant-violated');\n } else {\n this.setStoredName(originalKey, deriveAssetName(pkg.path, 1));\n }\n }\n }\n\n for (const g of guids) {\n const key = g.toLowerCase();\n pkg.assetGuids.add(key);\n this.packages.set(key, pkg);\n const n = names?.get(g) ?? names?.get(key);\n if (n !== undefined) this.setStoredName(key, n);\n }\n }\n\n /**\n * Read the per-GUID stored display name (D-6 home: the envelope's `name`\n * field, with `pendingNames` covering the prod-disk ordering where the name is\n * known before the body is catalogued). Single read point for resolveName /\n * the 1->N promotion XOR check.\n */\n private storedNameFor(key: string): string | undefined {\n return this.assetCatalog.get(key)?.name ?? this.pendingNames.get(key);\n }\n\n private hasStoredName(key: string): boolean {\n return this.storedNameFor(key) !== undefined;\n }\n\n /**\n * Write the per-GUID stored display name. When the envelope exists, replace it\n * with one carrying the new `name` (the envelope is immutable; D-6 keeps the\n * payload free of the name). Before the envelope is catalogued (prod disk\n * path), stash on `pendingNames` so catalog() can drain it into the new\n * envelope. `name === undefined` clears the name in both homes.\n */\n private setStoredName(key: string, name: string | undefined): void {\n const envelope = this.assetCatalog.get(key);\n if (envelope !== undefined) {\n const { name: _drop, ...rest } = envelope;\n this.assetCatalog.set(key, name === undefined ? rest : { ...rest, name });\n this.pendingNames.delete(key);\n return;\n }\n if (name === undefined) this.pendingNames.delete(key);\n else this.pendingNames.set(key, name);\n }\n\n /**\n * Return the `Package` this GUID belongs to, or `null` when the asset has no\n * package (catalog() inline + builtin, D-5), or `undefined` when the GUID was\n * never registered. The returned `Package` is a readonly snapshot whose\n * `assetCount` is derived from the live member set (#2 Derive).\n */\n packageOf(guid: AssetGuid | string): Package | null | undefined {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const pkg = this.packages.get(key);\n if (pkg === undefined) return undefined;\n if (pkg === null) return null;\n return { path: pkg.path, assetGuids: pkg.assetGuids, assetCount: pkg.assetGuids.size };\n }\n\n /**\n * Resolve an asset's human-readable display name -- the single source of truth\n * for the two-segment identity's `name` segment (D-6). Every name consumer\n * (inspect / catalog builder / CLI) reads this or the same `deriveAssetName`\n * pure function it delegates to (AC-04); no consumer re-implements the XOR\n * rule. Returns a deterministic fallback rather than throwing on a missing\n * name (AC-15): `basename(path)` for a multi-asset entry that lacks a stored\n * name, or `''` for a no-package asset with no self name (the detectable\n * \"genuinely no name\" signal, charter P3). An unregistered GUID is treated as\n * the no-package branch.\n */\n resolveName(guid: AssetGuid | string): string {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const pkg = this.packages.get(key);\n const storedName = this.storedNameFor(key);\n const path = pkg == null ? null : pkg.path;\n const assetCount = pkg == null ? 0 : pkg.assetGuids.size;\n return deriveAssetName(path, assetCount, storedName);\n }\n\n /**\n * Rename an asset's display name in memory (D-4). Three classes by package\n * shape:\n * - no-package asset -> set the stored self name\n * - multi-asset package -> set the entry stored name\n * - single-asset package -> rewrite the package path's leaf segment so the\n * derived basename becomes `newName` (the package\n * stays single-asset; the leaf IS the name)\n *\n * In-memory only (OOS-1: no disk write-back). Returns structured failures via\n * the closed `AssetErrorCode` union with no new members (D-4): a name that\n * collides with another member of the same package -> `asset-invalid-value`;\n * an unregistered GUID -> `asset-not-found`. AI users consume `.code` through\n * a `switch`, not by parsing `.message` (charter P3).\n */\n rename(guid: AssetGuid | string, newName: string): Result<void, AssetError> {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n if (!this.packages.has(key)) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `a registered asset for GUID ${key}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n\n const pkg = this.packages.get(key) ?? null;\n\n const collision = pkg !== null ? this.nameCollisionIn(pkg, key, newName) : null;\n if (collision !== null) return err(collision);\n\n if (pkg !== null && pkg.assetGuids.size === 1) {\n // Single-asset package: the leaf segment IS the derived name; rewrite it so\n // basename(path) === newName. Keep the directory prefix intact.\n const slash = pkg.path.lastIndexOf('/');\n const oldPath = pkg.path;\n pkg.path = slash >= 0 ? `${pkg.path.slice(0, slash + 1)}${newName}` : newName;\n this.packageByPath.delete(oldPath);\n this.packageByPath.set(pkg.path, pkg);\n this.setStoredName(key, undefined);\n return ok(undefined);\n }\n\n this.setStoredName(key, newName);\n return ok(undefined);\n }\n\n /**\n * Return an `asset-invalid-value` AssetError if another member of `pkg`\n * already resolves to `newName`, else null. Extracted from `rename` to keep\n * the collision-detection control flow flat (D-4 reuses the closed error code;\n * the detail narrows via the `{ field, value, reason }` union variant).\n */\n private nameCollisionIn(\n pkg: MutablePackage,\n selfKey: string,\n newName: string,\n ): AssetError | null {\n for (const memberKey of pkg.assetGuids) {\n if (memberKey !== selfKey && this.resolveName(memberKey) === newName) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `a name unique within package \"${pkg.path}\"`,\n hint: `another asset in \"${pkg.path}\" is already named \"${newName}\"; choose a distinct name`,\n detail: {\n field: 'name',\n value: newName,\n reason: `duplicate name within package ${pkg.path}`,\n },\n });\n }\n }\n return null;\n }\n\n /**\n * Parse a dash-form GUID string into an `AssetGuid`. Thin convenience over\n * `AssetGuid.parse` for the `loadByGuid` / `catalog` call sites; throws\n * `AssetError` on a malformed GUID (caller-error, mirrors `parseInt`-style\n * eager validation -- the GUID literal is author-supplied, not user data).\n */\n parseGuid(guidStr: string): AssetGuid {\n const parsed = AssetGuid.parse(guidStr);\n if (!parsed.ok) {\n throw new AssetError({\n code: 'asset-parse-failed',\n expected: `valid dash-form GUID, got \"${guidStr}\"`,\n hint: ASSET_ERROR_HINTS['asset-parse-failed'],\n });\n }\n return parsed.value;\n }\n\n /**\n * Look up a catalogued payload by GUID, or `undefined` on miss. Used by the\n * ECS/render side (e.g. `walkMaterialParents` in `resolve-asset-handle.ts`)\n * to resolve a payload's embedded sub-asset GUIDs (D-19) without minting.\n */\n lookup<T = Asset>(guid: AssetGuid | string): T | undefined {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const ready = this.loadState.getReady<T>(key);\n if (ready !== undefined) return ready;\n if (this.packIndexUrl === undefined)\n return this.assetCatalog.get(key)?.payload as T | undefined;\n return undefined;\n }\n\n /**\n * feat-20260613-material-paramschema-driven-binding M4 / w23 (D-5 graceful):\n * Return the texture-field name set for the given material-shader id,\n * derived from the registered shader's paramSchema via `derive(paramSchema)\n * .textureFieldNames`. Returns `undefined` when the shader is not yet\n * registered (cross-worktree shader-late-register, plan R-4).\n *\n * Used by `extractFrame` to know which values fields the shader\n * declares as texture handles; the extract layer validates handle-vs-\n * scalar typing and drops misclassified slots so the record stage's\n * MISSING_TEXTURE_HANDLE fallback can take over (white default texture)\n * rather than letting a stray handle reach `device.createBindGroup`.\n *\n * feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): delegates to the\n * extracted `./registry/validate-material` free function (signature stable).\n */\n materialShaderTextureFieldNames(shaderId: string): ReadonlySet<string> | undefined {\n return materialShaderTextureFieldNamesImpl(this, shaderId);\n }\n\n /**\n * Load an asset and all its transitively referenced sub-assets by GUID.\n * The result is a durable Asset payload. Consumer owners may narrow the\n * success type, then call their own World/Host projection; this registry does\n * not create a generic GUID-to-handle materializer.\n * Delegates to the load-by-guid collaboration module (w7 / D-4); see\n * registry/load-by-guid.ts for the full DDC / pack-fetch pipeline.\n */\n async loadByGuid<T = Asset>(\n guid: AssetGuid,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n ): Promise<Result<T, AssetError | ImageError | RhiError>> {\n return loadByGuidImpl<T>(this, guid, parentContext);\n }\n\n /**\n * Dispatch a pack payload through the injected LoaderRegistry. Delegates to\n * the load-by-guid collaboration module (w7 / D-4). Kept as a class method so\n * existing structural-cast test access keeps resolving.\n */\n parseAssetPayload(\n kind: string,\n payload: Record<string, unknown>,\n refs?: string[],\n ):\n | Asset\n | Record<string, unknown>\n | undefined\n | { readonly ok: false; readonly error: ParseErrorDetail } {\n return parseAssetPayloadImpl(this, kind, payload, refs);\n }\n\n /**\n * Parse a pack asset entry and return the payload + refs. Delegates to the\n * load-by-guid collaboration module (w7 / D-4). Kept as a class method so\n * existing structural-cast test access keeps resolving.\n */\n parseAndReturnAsset(assetEntry: {\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n }): Result<{ asset: Asset; refs: readonly string[] }, AssetError> {\n return parseAndReturnAssetImpl(this, assetEntry);\n }\n /** Return the legacy catalog snapshot when no GUID is supplied. */\n inspect(): InspectSnapshot;\n /** Return joined source/cook/package/runtime evidence for one GUID. */\n inspect(guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>>;\n inspect(guid?: string): InspectSnapshot | Promise<Result<AssetEvidence, AssetEvidenceError>> {\n if (guid !== undefined) return this.assetEvidenceAdapter.inspect(guid);\n const assets: InspectEntry[] = [];\n for (const [guid, envelope] of this.assetCatalog) {\n assets.push({\n guid,\n kind: envelope.payload.kind,\n name: this.resolveName(guid),\n });\n }\n return { assets };\n }\n\n /** Verify the same GUID evidence chain through the injected SDK capability. */\n verifyByGuid(guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>> {\n return this.assetEvidenceAdapter.verifyByGuid(guid);\n }\n\n /**\n * Return a readonly snapshot of all catalogued assets (inlined + pack-index)\n * for enumeration by asset panels (AC-03 single source of truth).\n *\n * Merges entries from the private `packIndexCache` (prod path, carries\n * `packageUrl`) and `assetCatalog` (inlined / dev path, no URL). Each\n * GUID appears exactly once. Returns a fresh array on every call — the\n * internal Maps are never exposed (charter P4 consistent abstraction).\n *\n * plan-strategy section 2 D1; requirements AC-03; research Finding 5.\n *\n * @example\n * ```ts\n * for (const e of registry.listCatalog()) {\n * console.log(e.guid, e.kind, e.name, e.packageUrl);\n * }\n * ```\n */\n listCatalog(): readonly {\n guid: string;\n kind: string;\n name?: string;\n packageUrl: string;\n packageId?: CatalogEntry['packageId'];\n provenance?: CatalogEntry['provenance'];\n revision?: CatalogEntry['revision'];\n sourceKey?: CatalogEntry['sourceKey'];\n sourceIndex?: CatalogEntry['sourceIndex'];\n sourceOverrides?: CatalogEntry['sourceOverrides'];\n sourceOverrideDescriptors?: CatalogEntry['sourceOverrideDescriptors'];\n authoring?: CatalogEntry['authoring'];\n relations?: CatalogEntry['relations'];\n diagnostics?: CatalogEntry['diagnostics'];\n refs?: readonly string[];\n subject?: import('@forgeax/engine-types').CatalogSubject;\n execution?: import('@forgeax/engine-types').CookExecution;\n lifecycle?: import('@forgeax/engine-types').CatalogLifecycle;\n projection?: import('@forgeax/engine-types').CatalogProjection;\n /**\n * On-disk source-file path for external imported assets (FBX / GLB / HDR /\n * audio / font), relative to the game root. Editors locate the\n * `.meta.json` sidecar via `sourcePath + '.meta.json'` for CRUD; unlike\n * `packageUrl` (the runtime load artefact) it is stable across DDC cook\n * state. `undefined` for inline / dev-path assets (no sidecar, no CRUD).\n */\n sourcePath?: string;\n }[] {\n const seen = new Set<string>();\n const result: {\n guid: string;\n kind: string;\n name?: string;\n packageUrl: string;\n packageId?: CatalogEntry['packageId'];\n provenance?: CatalogEntry['provenance'];\n revision?: CatalogEntry['revision'];\n sourceKey?: CatalogEntry['sourceKey'];\n sourceIndex?: CatalogEntry['sourceIndex'];\n sourceOverrides?: CatalogEntry['sourceOverrides'];\n sourceOverrideDescriptors?: CatalogEntry['sourceOverrideDescriptors'];\n authoring?: CatalogEntry['authoring'];\n relations?: CatalogEntry['relations'];\n diagnostics?: CatalogEntry['diagnostics'];\n refs?: readonly string[];\n subject?: import('@forgeax/engine-types').CatalogSubject;\n execution?: import('@forgeax/engine-types').CookExecution;\n lifecycle?: import('@forgeax/engine-types').CatalogLifecycle;\n projection?: import('@forgeax/engine-types').CatalogProjection;\n sourcePath?: string;\n cookReceiptUrl?: string;\n }[] = [];\n\n // Prod entries: packIndexCache carries packageUrl + optional name + refs.\n if (this.packIndexCache) {\n for (const [guidKey, entry] of this.packIndexCache) {\n seen.add(guidKey);\n result.push({\n guid: guidKey,\n kind: entry.kind,\n ...(entry.name !== undefined ? { name: entry.name } : {}),\n packageUrl: entry.packageUrl,\n ...(entry.packageId !== undefined ? { packageId: entry.packageId } : {}),\n ...(entry.provenance !== undefined ? { provenance: entry.provenance } : {}),\n ...(entry.revision !== undefined ? { revision: entry.revision } : {}),\n ...(entry.sourceKey !== undefined ? { sourceKey: entry.sourceKey } : {}),\n ...(entry.sourceIndex !== undefined ? { sourceIndex: entry.sourceIndex } : {}),\n ...(entry.sourceOverrides !== undefined\n ? { sourceOverrides: entry.sourceOverrides }\n : {}),\n ...(entry.sourceOverrideDescriptors !== undefined\n ? { sourceOverrideDescriptors: entry.sourceOverrideDescriptors }\n : {}),\n authoring: entry.authoring ?? authoringCapabilityForAssetKind(entry.kind),\n ...(entry.relations !== undefined ? { relations: entry.relations } : {}),\n ...(entry.diagnostics !== undefined ? { diagnostics: entry.diagnostics } : {}),\n ...(entry.refs !== undefined ? { refs: entry.refs } : {}),\n ...(entry.sourcePath !== undefined ? { sourcePath: entry.sourcePath } : {}),\n ...(entry.cookReceiptUrl !== undefined ? { cookReceiptUrl: entry.cookReceiptUrl } : {}),\n ...(entry.subject !== undefined ? { subject: entry.subject } : {}),\n ...(entry.execution !== undefined ? { execution: entry.execution } : {}),\n ...(entry.lifecycle !== undefined ? { lifecycle: entry.lifecycle } : {}),\n ...(entry.projection !== undefined ? { projection: entry.projection } : {}),\n });\n }\n }\n\n // Inlined / dev-path entries: assetCatalog, no pack-index URL. The envelope\n // holds the authoritative AssetRef[] graph; flatten it to plain GUID edges\n // so both catalog paths expose the same refs: readonly string[] shape.\n for (const [guidKey, envelope] of this.assetCatalog) {\n if (!seen.has(guidKey)) {\n const name = envelope.name ?? this.resolveName(guidKey);\n result.push({\n guid: guidKey,\n kind: envelope.payload.kind,\n name,\n packageUrl: '',\n authoring: authoringCapabilityForAssetKind(envelope.payload.kind),\n subject: 'internal-asset',\n execution: 'direct',\n lifecycle: 'current',\n projection: {\n subject: 'internal-asset',\n execution: 'direct',\n lifecycle: 'current',\n operations: catalogOperationsFor({\n subject: 'internal-asset',\n execution: 'direct',\n lifecycle: 'current',\n }),\n },\n ...(envelope.refs.length > 0 ? { refs: envelope.refs.map((r) => r.guid) } : {}),\n });\n }\n }\n\n return result;\n }\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport {\n ASSET_ERROR_HINTS,\n AssetError,\n type CatalogDelta,\n type CatalogEntry,\n type ResourceRevision,\n type RuntimeAssetBinding,\n} from '@forgeax/engine-types';\nimport { fetchCatalog } from './registry/catalog';\n\nexport type CatalogListener = (delta: CatalogDelta) => void;\n\n/** Read-only catalog source backed by static entries or a canonical URL. */\nexport interface CatalogSource {\n enumerate(): Promise<Result<readonly CatalogEntry[], AssetError>>;\n subscribe(listener: CatalogListener): () => void;\n readonly expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>;\n}\n\n/**\n * Create a read-only catalog source while preserving the schema SSOT.\n *\n * Static and fetched sources use the same `CatalogEntry` and revision fields;\n * an expected revision rejects unverified data before it reaches consumers.\n */\nexport function createCatalogSource(options: {\n readonly url?: string;\n readonly entries?: readonly CatalogEntry[];\n readonly fetch?: typeof globalThis.fetch;\n readonly expectedRevision?: ResourceRevision;\n readonly expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>;\n readonly subscribe?: (listener: CatalogListener) => () => void;\n}): CatalogSource {\n const entries = options.entries;\n return {\n async enumerate() {\n if (entries !== undefined) {\n if (options.expectedRevision === undefined) return ok(entries);\n const actualRevisions = entries.flatMap((entry) =>\n entry.revision === undefined ? [] : [entry.revision],\n );\n const matches =\n actualRevisions.length > 0 &&\n actualRevisions.every(\n (revision) =>\n revision.digest === options.expectedRevision?.digest &&\n revision.observedAt === options.expectedRevision?.observedAt &&\n revision.rootId === options.expectedRevision?.rootId,\n );\n if (!matches) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: 'static catalog entries to carry the expected producer revision',\n hint: 'restore a verified catalog revision before applying the source',\n detail: { expectedRevision: options.expectedRevision, actualRevisions } as never,\n }),\n );\n }\n return ok(entries);\n }\n if (options.url === undefined) {\n return err(\n new AssetError({\n code: 'catalog-source-unconfigured',\n expected: 'a configured catalog source',\n hint: ASSET_ERROR_HINTS['catalog-source-unconfigured'],\n }),\n );\n }\n const result = await fetchCatalog(\n options.url,\n options.fetch ?? globalThis.fetch,\n undefined,\n options.expectedRevision,\n options.expectedScope,\n );\n if (!result.ok) return result;\n return ok(\n [...result.value].map(([guid, entry]) => ({ guid, ...entry })) as readonly CatalogEntry[],\n );\n },\n subscribe(listener) {\n return options.subscribe?.(listener) ?? (() => {});\n },\n ...(options.expectedScope === undefined ? {} : { expectedScope: options.expectedScope }),\n };\n}\n","// @forgeax/engine-assets-runtime -- runtime-local ImageError constructor\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport type { ImageErrorDetailFor, ImageErrorFor } from '@forgeax/engine-types';\nimport { IMAGE_ERROR_HINTS } from '@forgeax/engine-types';\n\n// Local minimal `ImageError` constructor (charter P5 producer / consumer\n// split: the runtime AssetRegistry should not import @forgeax/engine-image\n// errors module because the image package is the disk-side decoder; the\n// runtime is the GPU consumer. Both packages share the `ImageError`\n// interface SSOT in @forgeax/engine-types so runtime constructs the\n// 4-field surface (.code / .expected / .hint / .detail) directly without\n// duplicating the @forgeax/engine-image errors.ts class).\ntype UnsupportedMimeImageError = ImageErrorFor<'image-format-unsupported'>;\ntype UnsupportedMimeImageErrorDetail = ImageErrorDetailFor<'image-format-unsupported'>;\n\nconst IMAGE_ERROR_EXPECTED_LOCAL: Readonly<\n Record<UnsupportedMimeImageErrorDetail['code'], string>\n> = {\n 'image-format-unsupported':\n \"mime is one of ['image/png', 'image/jpeg', 'image/x-tga']; texture format <-> colorSpace family agrees\",\n};\n\nclass RuntimeImageError extends Error implements UnsupportedMimeImageError {\n readonly code: UnsupportedMimeImageError['code'];\n readonly expected: string;\n readonly hint: string;\n readonly detail: UnsupportedMimeImageErrorDetail;\n constructor(detail: UnsupportedMimeImageErrorDetail) {\n const code = detail.code;\n const expected = IMAGE_ERROR_EXPECTED_LOCAL[code];\n const hint = IMAGE_ERROR_HINTS[code];\n super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);\n this.name = 'ImageError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\nexport function makeImageError(detail: UnsupportedMimeImageErrorDetail): UnsupportedMimeImageError {\n return new RuntimeImageError(detail);\n}\n","// @forgeax/engine-assets-runtime -- runtime image byte decoder\n// (tweak-20260714-runtime-image-bytes-decoder-add-decodeimagebytes M2 / m2-1).\n//\n// M1 established the signature + TSDoc contract + red test skeleton. M2\n// fills the body:\n// 1. mime whitelist pre-check (PNG / JPEG); non-match -> structured\n// `image-format-unsupported` err (charter P3 explicit failure).\n// 2. Delegate to `@forgeax/engine-image::decodeImageInBrowser` (SSOT\n// browser-safe decoder; charter architecture principle 1 SSOT).\n// 3. Map `DecodedImage` -> `TextureAsset` POD; `format` derives from\n// `opts.colorSpace` (srgb -> 'rgba8unorm-srgb' / linear ->\n// 'rgba8unorm', mirrors `image-importer.ts` colorSpaceToFormat); when\n// `opts.mipmap !== false`, `mipLevelCount` derives from\n// `numMipLevels({width,height})` (charter Derive-Don't-Duplicate).\n//\n// decode-image-bytes.ts is the SINGLE assets-runtime file allowed to\n// statically import @forgeax/engine-image (charter D-2; the\n// scripts/check-image-pipeline-isolation.mjs Path (a.2-anti) whitelist\n// row anchors this exact path). The gate's (a.1) forbidden-symbol regex\n// `\\basync\\s+function\\s+decodeImage\\b` does NOT match `decodeImageBytes`\n// because `\\b` between `e` and `B` fails (both are word chars) --\n// verified at M2 by running the gate locally.\nimport { decodeImageInBrowser } from '@forgeax/engine-image';\nimport type { ImageError, Result, TextureAsset } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { makeImageError } from './image-error';\nimport { numMipLevels } from './mipmap-generator';\n\n/** v1 mime whitelist -- PNG / JPEG only (charter P1 progressive disclosure). */\nconst SUPPORTED_MIMES = ['image/png', 'image/jpeg'] as const;\ntype SupportedMime = (typeof SUPPORTED_MIMES)[number];\n\nfunction isSupportedMime(mime: string): mime is SupportedMime {\n return SUPPORTED_MIMES.some((supportedMime) => supportedMime === mime);\n}\n\n/**\n * Decode a PNG / JPEG byte stream into a `TextureAsset` POD.\n *\n * Runtime SDK entry for AI users who hold image bytes (fetched over the\n * network, embedded as base64, produced by an out-of-tree decoder, etc.) and\n * want to feed them into `world.allocSharedRef('TextureAsset', pod)` +\n * `GpuResourceStore.ensureResident` without the disk-side importer / build\n * pipeline in the loop (charter P1 progressive disclosure: one-step \"bytes\n * in, POD out\").\n *\n * v1 supports the two universally-decodable mime types: `image/png` and\n * `image/jpeg`. Failure surfaces are all structured via the closed\n * `ImageError` union (`.code` / `.expected` / `.hint` / `.detail`); the\n * function never throws for expected failures (AGENTS.md Error model +\n * charter P3 explicit failure).\n *\n * Error codes possible (subset of the closed `ImageErrorCode` union):\n * - `image-format-unsupported` -- mime not in the v1 whitelist (`detail.actualMime`)\n * - `image-decode-failed` -- decoder rejected the bytes, or the environment\n * lacks `createImageBitmap` (`detail.reason`)\n *\n * @param bytes - Encoded image byte stream (`Uint8Array` or `ArrayBuffer`).\n * @param mime - Byte-stream mime type. v1 whitelist: `'image/png' | 'image/jpeg'`.\n * @param opts - Optional decode overrides:\n * - `colorSpace`: `'srgb'` (default) or `'linear'`. Derives POD `format`:\n * `srgb -> 'rgba8unorm-srgb'`, `linear -> 'rgba8unorm'`.\n * - `mipmap`: `true` (default) or `false`. When true, `mipLevelCount` is\n * computed via `numMipLevels({ width, height })`; when false, forced 1.\n * @returns `ok(TextureAsset)` on success; `err(ImageError)` on failure.\n *\n * @example\n * ```ts\n * import { decodeImageBytes } from '@forgeax/engine-assets-runtime';\n *\n * const bytes = new Uint8Array(await (await fetch(url)).arrayBuffer());\n * const result = await decodeImageBytes(bytes, 'image/png');\n * if (!result.ok) {\n * // The ImageError code and detail are one correlated discriminated union.\n * switch (result.error.code) {\n * case 'image-format-unsupported':\n * console.error('bad mime:', result.error.detail.actualMime);\n * break;\n * case 'image-decode-failed':\n * console.error('decode reason:', result.error.detail.reason);\n * break;\n * }\n * return;\n * }\n * const handle = world.allocSharedRef('TextureAsset', result.value);\n * ```\n */\nexport async function decodeImageBytes(\n bytes: Uint8Array | ArrayBuffer,\n mime: string,\n opts: { colorSpace?: 'srgb' | 'linear'; mipmap?: boolean } = {},\n): Promise<Result<TextureAsset, ImageError>> {\n if (!isSupportedMime(mime)) {\n return err(\n makeImageError({\n code: 'image-format-unsupported',\n actualMime: mime,\n }),\n );\n }\n\n const colorSpace = opts.colorSpace ?? 'srgb';\n const mipmap = opts.mipmap ?? true;\n\n const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n const decoded = await decodeImageInBrowser(u8, mime, { colorSpace, mipmap });\n if (!decoded.ok) {\n return err(decoded.error);\n }\n\n const dec = decoded.value;\n const format: GPUTextureFormat = colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm';\n const mipLevelCount = mipmap ? numMipLevels({ width: dec.width, height: dec.height }) : 1;\n\n const pod: TextureAsset = {\n kind: 'texture',\n width: dec.width,\n height: dec.height,\n format,\n data: dec.bytes,\n colorSpace,\n mipmap,\n mipLevelCount,\n };\n return ok(pod);\n}\n","// @forgeax/engine-assets-runtime — DynamicTextureStore: transient per-frame GPU\n// textures for video sources (feat-20260623-world-space-video-asset M4 / w15).\n//\n// D-3: video frames are re-uploaded every frame — the opposite of the static\n// \"upload once / cache forever\" semantics GpuResourceStore.ensureResident\n// implements. Routing video through ensureResident would either poison its\n// permanent cache (AC-08) or crash it (its `switch (pod.kind)` has no `video`\n// arm). So video gets its OWN store with a transient lifecycle, exactly the way\n// cube-texture upload is an eager independent path that never enters the\n// ensureResident switch (research Finding 7 precedent).\n//\n// This store does NOT import GpuResourceStore and accepts NO static texture\n// handle — it is keyed solely by the VideoAsset clip handle. Each key owns a\n// single GPUTexture sized to the source video; the texture is recreated only\n// when the source dimensions change (a steady-size clip allocates once and is\n// re-written in place every frame via copyExternalImageToTexture). The view is\n// re-fetched after each upload so the bind group always samples the latest\n// frame.\n//\n// Charter P3: every failure returns a structured Result (never throws for an\n// expected GPU failure); the per-frame caller (record stage videoTextureView)\n// fires the RhiError on the engine error channel and falls back to the default\n// view for that frame.\n\nimport type { Result, RhiDevice, RhiError, Texture, TextureView } from '@forgeax/engine-rhi';\nimport { ok } from '@forgeax/engine-rhi';\nimport type { Handle } from '@forgeax/engine-types';\nimport { handleSlot } from '@forgeax/engine-types';\n\n/**\n * The host-owned external image the engine copies a video frame from\n * (HTMLVideoElement / VideoFrame / ImageBitmap / canvas). Mirrors the `source`\n * member of the WebGPU `GPUCopyExternalImageSourceInfo` the RHI\n * `copyExternalImageToTexture` consumes; aliased here so the store does not pull\n * the whole webgpu descriptor type into its surface.\n */\nexport type CopyExternalImageSource = GPUCopyExternalImageSourceInfo['source'];\n\n/**\n * GPUTextureUsage bits a video destination texture needs: COPY_DST (the\n * copyExternalImageToTexture write target), TEXTURE_BINDING (sampled in the\n * material bind group), and RENDER_ATTACHMENT (required by the WebGPU spec for\n * a copyExternalImageToTexture destination). Mirrors the literals\n * gpu-resource-store.ts uses for its upload textures (no shared const exists to\n * import without coupling the two stores — D-3 keeps them independent).\n */\nconst VIDEO_TEXTURE_USAGE = 0x2 | 0x4 | 0x10;\n\n/** rgba8unorm-srgb: a video frame decodes to sRGB; sampling returns linear. */\nconst VIDEO_TEXTURE_FORMAT = 'rgba8unorm-srgb' as const;\n\n/**\n * The minimal RHI device surface DynamicTextureStore needs. Declared structurally\n * (not the full RhiDevice) so unit tests drive it with a small mock and the store\n * stays decoupled from the rest of the device surface (Pipeline Isolation).\n */\nexport interface DynamicTextureDevice {\n createTexture(desc: {\n readonly size: {\n readonly width: number;\n readonly height: number;\n readonly depthOrArrayLayers: number;\n };\n readonly format: typeof VIDEO_TEXTURE_FORMAT;\n readonly usage: number;\n readonly label?: string;\n }): Result<Texture, RhiError>;\n createTextureView(texture: Texture, desc: Record<string, never>): Result<TextureView, RhiError>;\n destroyTexture(texture: Texture): Result<void, RhiError>;\n readonly queue: {\n copyExternalImageToTexture(\n source: { readonly source: CopyExternalImageSource; readonly flipY?: boolean },\n destination: { readonly texture: Texture },\n copySize: {\n readonly width: number;\n readonly height: number;\n readonly depthOrArrayLayers: number;\n },\n ): Result<void, RhiError>;\n };\n}\n\n/** Adapt the opaque RHI device to the store's intentionally small upload seam. */\nexport function adaptDynamicTextureDevice(device: RhiDevice): DynamicTextureDevice {\n return {\n createTexture: (descriptor) =>\n device.createTexture({\n ...descriptor,\n mipLevelCount: undefined,\n sampleCount: undefined,\n dimension: undefined,\n viewFormats: undefined,\n textureBindingViewDimension: undefined,\n }),\n createTextureView: (texture) =>\n device.createTextureView(texture, {\n label: undefined,\n format: undefined,\n dimension: undefined,\n usage: undefined,\n aspect: undefined,\n baseMipLevel: undefined,\n mipLevelCount: undefined,\n baseArrayLayer: undefined,\n arrayLayerCount: undefined,\n }),\n destroyTexture: (texture) => device.destroyTexture(texture),\n queue: {\n copyExternalImageToTexture: (source, destination, copySize) =>\n device.queue.copyExternalImageToTexture(\n { source: source.source, origin: [0, 0], flipY: source.flipY ?? false },\n { texture: destination.texture, origin: [0, 0, 0] },\n copySize,\n ),\n },\n };\n}\n\ninterface TransientEntry {\n texture: Texture;\n view: TextureView;\n width: number;\n height: number;\n}\n\n/**\n * Transient per-frame texture store for video sources. Independent of\n * GpuResourceStore: it neither imports nor reaches into the static residency\n * cache (AC-08 / D-3).\n */\nexport class DynamicTextureStore {\n private device: DynamicTextureDevice | undefined = undefined;\n private readonly entries = new Map<number, TransientEntry>();\n\n /**\n * Wire the GPU device the store uploads through. Called once after the\n * renderer captures its device (mirrors GpuResourceStore.configureGpuDevice).\n * A replacement device invalidates every cached texture: the handles in the\n * map belong to the old device and cannot be reused after renderer recovery.\n */\n configureGpuDevice(device: DynamicTextureDevice): void {\n if (this.device !== undefined && this.device !== device) {\n this.destroyAll();\n }\n this.device = device;\n }\n\n /**\n * Upload one video frame for `clip` from the host-owned source image\n * (HTMLVideoElement / VideoFrame / ImageBitmap), (re)allocating the transient\n * texture when its size changes, and return the current-frame view to bind.\n *\n * Returns `undefined` (not an error) when the device is not yet wired or the\n * source has no decodable dimensions yet (metadata pending) — the caller binds\n * the default view that frame. A structured RhiError surfaces only when a wired\n * device rejects the allocation or the copy (charter P3).\n */\n uploadFrame(\n clip: Handle<'VideoAsset', 'shared'>,\n source: CopyExternalImageSource,\n width: number,\n height: number,\n ): Result<TextureView, RhiError> | undefined {\n const device = this.device;\n if (device === undefined) return undefined;\n if (width <= 0 || height <= 0) return undefined;\n\n const id = handleSlot(clip);\n const ensured = this.ensureEntry(device, id, width, height);\n if (!ensured.ok) return ensured;\n const entry = ensured.value;\n\n const copyRes = device.queue.copyExternalImageToTexture(\n { source, flipY: true },\n { texture: entry.texture },\n { width, height, depthOrArrayLayers: 1 },\n );\n if (!copyRes.ok) return copyRes;\n return ok(entry.view);\n }\n\n /**\n * The current-frame view for a clip, if one has been uploaded this session,\n * else undefined. The record stage reads this when assembling the bind group\n * (a frame that has not uploaded yet falls back to the default view).\n */\n getView(clip: Handle<'VideoAsset', 'shared'>): TextureView | undefined {\n return this.entries.get(handleSlot(clip))?.view;\n }\n\n /** Destroy every transient texture + drop the map (renderer teardown). */\n destroyAll(): void {\n const device = this.device;\n for (const entry of this.entries.values()) {\n device?.destroyTexture(entry.texture);\n }\n this.entries.clear();\n }\n\n /**\n * Get the entry for `id`, (re)allocating its texture + view when absent or\n * when the source dimensions changed. A same-size re-upload reuses the\n * existing texture (allocate-once for a steady clip; the per-frame cost is the\n * copyExternalImageToTexture write, not a texture create).\n */\n private ensureEntry(\n device: DynamicTextureDevice,\n id: number,\n width: number,\n height: number,\n ): Result<TransientEntry, RhiError> {\n const existing = this.entries.get(id);\n if (existing !== undefined && existing.width === width && existing.height === height) {\n return ok(existing);\n }\n if (existing !== undefined) device.destroyTexture(existing.texture);\n\n const texRes = device.createTexture({\n size: { width, height, depthOrArrayLayers: 1 },\n format: VIDEO_TEXTURE_FORMAT,\n usage: VIDEO_TEXTURE_USAGE,\n label: `video-transient-${id}`,\n });\n if (!texRes.ok) return texRes;\n const viewRes = device.createTextureView(texRes.value, {});\n if (!viewRes.ok) {\n device.destroyTexture(texRes.value);\n return viewRes;\n }\n const entry: TransientEntry = { texture: texRes.value, view: viewRes.value, width, height };\n this.entries.set(id, entry);\n return ok(entry);\n }\n}\n","import type { AssetLoadError, Result } from '@forgeax/engine-types';\n\nexport interface ArtifactCacheSnapshot {\n readonly entries: number;\n readonly pending: number;\n readonly hits: number;\n readonly misses: number;\n}\n\nexport class ArtifactCache {\n private readonly values = new Map<string, Uint8Array>();\n private readonly pending = new Map<string, Promise<Result<Uint8Array, AssetLoadError>>>();\n private hits = 0;\n private misses = 0;\n\n read(\n contentAddress: string,\n reader: () => Promise<Result<Uint8Array, AssetLoadError>>,\n ): Promise<Result<Uint8Array, AssetLoadError>> {\n const value = this.values.get(contentAddress);\n if (value !== undefined) {\n this.hits += 1;\n return Promise.resolve({ ok: true, value: new Uint8Array(value) } as Result<\n Uint8Array,\n AssetLoadError\n >);\n }\n const pending = this.pending.get(contentAddress);\n if (pending !== undefined) {\n this.hits += 1;\n return pending;\n }\n this.misses += 1;\n const request = Promise.resolve()\n .then(reader)\n .then((result) => {\n if (result.ok) this.values.set(contentAddress, new Uint8Array(result.value));\n return result;\n })\n .finally(() => {\n if (this.pending.get(contentAddress) === request) this.pending.delete(contentAddress);\n });\n this.pending.set(contentAddress, request);\n return request;\n }\n\n clear(contentAddress?: string): void {\n if (contentAddress === undefined) {\n this.values.clear();\n this.pending.clear();\n return;\n }\n this.values.delete(contentAddress);\n this.pending.delete(contentAddress);\n }\n\n snapshot(): ArtifactCacheSnapshot {\n return Object.freeze({\n entries: this.values.size,\n pending: this.pending.size,\n hits: this.hits,\n misses: this.misses,\n });\n }\n}\n","/**\n * Decoder output becomes an owner fact at this boundary. Freeze the ordinary\n * POD graph so a caller cannot mutate the cached payload between loads.\n * Typed-array storage is deliberately left as an opaque byte/vector carrier:\n * JavaScript cannot freeze a non-empty typed array without changing its public\n * engine type, so owners must treat those carriers as read-only by contract.\n */\nexport function freezeRuntimePayload<T>(value: T): T {\n const seen = new WeakSet<object>();\n return freeze(value, seen);\n}\n\nfunction freeze<T>(value: T, seen: WeakSet<object>): T {\n if (value === null || typeof value !== 'object') return value;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return value;\n if (seen.has(value)) return value;\n seen.add(value);\n for (const child of Object.values(value as Record<string, unknown>)) freeze(child, seen);\n return Object.freeze(value);\n}\n","import type { AssetLoadError, Result } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { freezeRuntimePayload } from './immutable-payload.js';\n\nexport interface AssetGraphValue<P> {\n readonly value: P;\n readonly refs: readonly string[];\n}\n\nexport interface AssetGraphOptions<\n P extends { readonly value: unknown; readonly refs: readonly string[] },\n> {\n readonly read: (guid: string, signal: AbortSignal) => Promise<Result<P, AssetLoadError>>;\n readonly maxConcurrentReads?: number;\n}\n\nexport interface AssetGraphCounters {\n readonly loads: number;\n readonly cacheHits: number;\n readonly readErrors: number;\n readonly noChange: number;\n readonly listenerFailures: number;\n}\n\nexport interface AssetGraphSnapshot {\n readonly epoch: number;\n readonly ready: readonly string[];\n readonly pending: number;\n readonly resources: number;\n readonly sccs: readonly (readonly string[])[];\n readonly counters: AssetGraphCounters;\n}\n\ntype GraphResult<P> = Result<P, AssetLoadError>;\ntype GraphListener = (snapshot: AssetGraphSnapshot) => void;\n\nfunction cancelled(guid: string): AssetLoadError {\n return {\n code: 'asset-load-cancelled',\n expected: 'the request AbortSignal to remain live until asset closure completes',\n hint: 'retry with a live AbortSignal when the request is still needed',\n detail: { guid },\n };\n}\n\nfunction disposed(scopeId = 'asset-runtime'): AssetLoadError {\n return {\n code: 'asset-runtime-disposed',\n expected: 'an active asset runtime scope',\n hint: 'obtain a new Registry from the current realm',\n detail: { scopeId },\n };\n}\n\nfunction superseded(guid: string, generation: number): AssetLoadError {\n return {\n code: 'asset-superseded',\n expected: 'the load ticket to remain current until promotion',\n hint: 'load the current publication after the Catalog change',\n detail: { guid, generation },\n };\n}\n\nfunction thrown(guid: string): AssetLoadError {\n return {\n code: 'asset-decode-failed',\n expected: 'the graph reader to return a Result',\n hint: 'repair the owner reader and retry the current publication',\n detail: { guid, kind: 'asset-graph-reader' },\n };\n}\n\nfunction freezeSnapshot(snapshot: AssetGraphSnapshot): AssetGraphSnapshot {\n return Object.freeze({\n ...snapshot,\n ready: Object.freeze([...snapshot.ready]),\n sccs: Object.freeze(snapshot.sccs.map((scc) => Object.freeze([...scc]))),\n counters: Object.freeze({ ...snapshot.counters }),\n });\n}\n\nexport class AssetGraph<P extends { readonly value: unknown; readonly refs: readonly string[] }> {\n private readonly read: AssetGraphOptions<P>['read'];\n private readonly limit: number;\n private readonly ready = new Map<string, P>();\n private readonly forward = new Map<string, Set<string>>();\n private readonly reverse = new Map<string, Set<string>>();\n private readonly reads = new Map<string, Promise<GraphResult<P>>>();\n private readonly requests = new Map<string, Promise<GraphResult<P>>>();\n private readonly listeners = new Set<GraphListener>();\n private readonly sccs: (readonly string[])[] = [];\n private activeReads = 0;\n private readWaiters: (() => void)[] = [];\n private disposed = false;\n private epoch = 0;\n private counters: AssetGraphCounters = {\n loads: 0,\n cacheHits: 0,\n readErrors: 0,\n noChange: 0,\n listenerFailures: 0,\n };\n private currentSnapshot: AssetGraphSnapshot;\n\n constructor(options: AssetGraphOptions<P>) {\n this.read = options.read;\n this.limit = Math.max(1, Math.floor(options.maxConcurrentReads ?? 8));\n this.currentSnapshot = freezeSnapshot({\n epoch: 0,\n ready: [],\n pending: 0,\n resources: 0,\n sccs: [],\n counters: this.counters,\n });\n }\n\n load(guid: string, signal = new AbortController().signal): Promise<GraphResult<P>> {\n const canonicalGuid = guid.toLowerCase();\n if (this.disposed) return Promise.resolve(err(disposed()));\n if (signal.aborted) return Promise.resolve(err(cancelled(canonicalGuid)));\n const cached = this.ready.get(canonicalGuid);\n if (cached !== undefined) {\n this.counters = {\n ...this.counters,\n cacheHits: this.counters.cacheHits + 1,\n noChange: this.counters.noChange + 1,\n };\n this.publish();\n return Promise.resolve(ok(cached));\n }\n const existing = this.requests.get(canonicalGuid);\n if (existing !== undefined) {\n this.counters = { ...this.counters, cacheHits: this.counters.cacheHits + 1 };\n return existing;\n }\n this.counters = { ...this.counters, loads: this.counters.loads + 1 };\n const ticketEpoch = this.epoch;\n const request = this.loadClosure(canonicalGuid, signal, ticketEpoch).finally(() => {\n if (this.requests.get(canonicalGuid) === request) this.requests.delete(canonicalGuid);\n this.publish();\n });\n this.requests.set(canonicalGuid, request);\n this.publish();\n return request;\n }\n\n invalidate(guid: string): readonly string[] {\n const affected = this.collectAffected([guid.toLowerCase()]);\n this.drop(affected);\n this.epoch += 1;\n this.publish();\n return [...affected].sort();\n }\n\n invalidateForCatalogChange(guids?: readonly string[]): void {\n if (this.disposed) return;\n const affected =\n guids === undefined || guids.length === 0\n ? new Set([...this.ready.keys(), ...this.requests.keys(), ...this.reads.keys()])\n : this.collectAffected(guids.map((item) => item.toLowerCase()));\n this.drop(affected);\n this.epoch += 1;\n this.publish();\n }\n\n subscribe(listener: GraphListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n snapshot(): AssetGraphSnapshot {\n return this.currentSnapshot;\n }\n\n lookup(guid: string): P['value'] | undefined {\n return this.ready.get(guid.toLowerCase())?.value;\n }\n\n guidOf(value: P['value']): string | undefined {\n for (const [guid, entry] of this.ready) {\n if (entry.value === value) return guid;\n }\n return undefined;\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.epoch += 1;\n this.ready.clear();\n this.forward.clear();\n this.reverse.clear();\n this.reads.clear();\n const waiters = this.readWaiters;\n this.readWaiters = [];\n for (const resolve of waiters) resolve();\n this.publish();\n }\n\n private async loadClosure(\n root: string,\n signal: AbortSignal,\n ticketEpoch: number,\n ): Promise<GraphResult<P>> {\n const values = new Map<string, P>();\n const visiting = new Set<string>();\n const visited = new Set<string>();\n const group = new Set<string>();\n const result = await this.visit(root, signal, visiting, visited, values, group);\n if (!result.ok) return result;\n if (this.disposed) return err(disposed());\n if (signal.aborted) return err(cancelled(root));\n if (ticketEpoch !== this.epoch) return err(superseded(root, ticketEpoch));\n for (const [guid, value] of values) this.promote(guid, value);\n this.recordScc();\n return ok(values.get(root) as P);\n }\n\n private async visit(\n guid: string,\n signal: AbortSignal,\n visiting: Set<string>,\n visited: Set<string>,\n values: Map<string, P>,\n group: Set<string>,\n ): Promise<GraphResult<P>> {\n if (visiting.has(guid)) {\n group.add(guid);\n return ok({ value: undefined as unknown as P, refs: [] } as unknown as P);\n }\n if (visited.has(guid)) return ok(values.get(guid) as P);\n const cached = this.ready.get(guid);\n if (cached !== undefined) {\n values.set(guid, cached);\n visited.add(guid);\n return ok(cached);\n }\n visiting.add(guid);\n const read = await this.readOnce(guid, signal);\n if (!read.ok) {\n visiting.delete(guid);\n return read;\n }\n values.set(guid, read.value);\n group.add(guid);\n this.link(guid, read.value.refs);\n for (const ref of read.value.refs) {\n const child = await this.visit(ref, signal, visiting, visited, values, group);\n if (!child.ok) {\n visiting.delete(guid);\n return err({\n code: 'asset-dependency-failed',\n expected: 'every referenced asset to load successfully',\n hint: 'repair the dependency publication and retry the root asset',\n detail: { guid, dependencyGuid: ref },\n });\n }\n }\n visiting.delete(guid);\n visited.add(guid);\n return ok(read.value);\n }\n\n private readOnce(guid: string, signal: AbortSignal): Promise<GraphResult<P>> {\n const existing = this.reads.get(guid);\n if (existing !== undefined) return existing;\n const request = this.withPermit(async () => {\n if (this.disposed) return err(disposed());\n if (signal.aborted) return err(cancelled(guid));\n try {\n const result = await this.read(guid, signal);\n if (signal.aborted) return err(cancelled(guid));\n if (!result.ok)\n this.counters = { ...this.counters, readErrors: this.counters.readErrors + 1 };\n return result;\n } catch {\n this.counters = { ...this.counters, readErrors: this.counters.readErrors + 1 };\n return err(thrown(guid));\n }\n });\n this.reads.set(guid, request);\n void request.finally(() => {\n if (this.reads.get(guid) === request) this.reads.delete(guid);\n });\n return request;\n }\n\n private async withPermit<T>(operation: () => Promise<T>): Promise<T> {\n if (this.activeReads >= this.limit) {\n await new Promise<void>((resolve) => this.readWaiters.push(resolve));\n }\n this.activeReads += 1;\n try {\n return await operation();\n } finally {\n this.activeReads -= 1;\n this.readWaiters.shift()?.();\n }\n }\n\n private link(guid: string, refs: readonly string[]): void {\n const previous = this.forward.get(guid) ?? new Set<string>();\n for (const ref of previous) this.reverse.get(ref)?.delete(guid);\n const next = new Set(refs.map((ref) => ref.toLowerCase()));\n this.forward.set(guid, next);\n for (const ref of next) {\n const dependents = this.reverse.get(ref) ?? new Set<string>();\n dependents.add(guid);\n this.reverse.set(ref, dependents);\n }\n }\n\n private collectAffected(guids: readonly string[]): Set<string> {\n const affected = new Set<string>();\n const queue = [...guids];\n while (queue.length > 0) {\n const current = queue.shift();\n if (current === undefined || affected.has(current)) continue;\n affected.add(current);\n for (const dependent of this.reverse.get(current) ?? []) queue.push(dependent);\n }\n return affected;\n }\n\n private drop(affected: ReadonlySet<string>): void {\n for (const item of affected) {\n for (const ref of this.forward.get(item) ?? []) this.reverse.get(ref)?.delete(item);\n for (const dependent of this.reverse.get(item) ?? []) {\n this.forward.get(dependent)?.delete(item);\n }\n }\n for (const item of affected) {\n this.ready.delete(item);\n this.requests.delete(item);\n this.reads.delete(item);\n this.forward.delete(item);\n this.reverse.delete(item);\n }\n this.sccs.splice(0, this.sccs.length);\n }\n\n private promote(guid: string, value: P): void {\n if (value === undefined) return;\n this.ready.set(\n guid,\n Object.freeze({\n ...value,\n value: freezeRuntimePayload(value.value),\n refs: Object.freeze([...value.refs]),\n }) as P,\n );\n }\n\n private recordScc(): void {\n const indexByGuid = new Map<string, number>();\n const lowByGuid = new Map<string, number>();\n const stack: string[] = [];\n const onStack = new Set<string>();\n let nextIndex = 0;\n const components: string[][] = [];\n const visit = (guid: string): void => {\n indexByGuid.set(guid, nextIndex);\n lowByGuid.set(guid, nextIndex);\n nextIndex += 1;\n stack.push(guid);\n onStack.add(guid);\n for (const ref of this.forward.get(guid) ?? []) {\n if (!indexByGuid.has(ref)) {\n visit(ref);\n lowByGuid.set(guid, Math.min(lowByGuid.get(guid) ?? 0, lowByGuid.get(ref) ?? 0));\n } else if (onStack.has(ref)) {\n lowByGuid.set(guid, Math.min(lowByGuid.get(guid) ?? 0, indexByGuid.get(ref) ?? 0));\n }\n }\n if (lowByGuid.get(guid) !== indexByGuid.get(guid)) return;\n const component: string[] = [];\n let member: string | undefined;\n do {\n member = stack.pop();\n if (member === undefined) break;\n onStack.delete(member);\n component.push(member);\n } while (member !== guid);\n if (component.length > 1 || this.forward.get(guid)?.has(guid) === true)\n components.push(component.sort());\n };\n for (const guid of this.forward.keys()) if (!indexByGuid.has(guid)) visit(guid);\n this.sccs.splice(\n 0,\n this.sccs.length,\n ...components.map((component) => Object.freeze(component)),\n );\n }\n\n private publish(): void {\n this.currentSnapshot = freezeSnapshot({\n epoch: this.epoch,\n ready: [...this.ready.keys()].sort(),\n pending: this.requests.size + this.reads.size,\n resources: this.ready.size,\n sccs: this.sccs,\n counters: this.counters,\n });\n for (const listener of [...this.listeners]) {\n try {\n listener(this.currentSnapshot);\n } catch {\n this.counters = {\n ...this.counters,\n listenerFailures: Math.min(1024, this.counters.listenerFailures + 1),\n };\n this.currentSnapshot = freezeSnapshot({\n ...this.currentSnapshot,\n counters: this.counters,\n });\n }\n }\n }\n}\n","import type { CatalogEntry } from '@forgeax/engine-types';\nimport { type AssetLoadError, err, ok, type Result } from '@forgeax/engine-types';\n\nexport interface RuntimeCatalogRow extends CatalogEntry {\n readonly publication: NonNullable<CatalogEntry['publication']>;\n}\n\nfunction invalidRow(guid: string, reason: string): Result<never, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'one complete current runtime Catalog row',\n hint: 'rebuild the producer Catalog and publish one Pack v2 tuple',\n detail: { guid, reason },\n });\n}\n\nexport function validateRuntimeRow(row: CatalogEntry): Result<RuntimeCatalogRow, AssetLoadError> {\n if (row === null || typeof row !== 'object') return invalidRow('', 'row');\n const candidate = row as Partial<CatalogEntry>;\n const guid = typeof candidate.guid === 'string' ? candidate.guid : '';\n if (guid.trim().length === 0) return invalidRow(guid, 'guid');\n if (typeof candidate.kind !== 'string' || candidate.kind.trim().length === 0)\n return invalidRow(guid, 'kind');\n if (typeof candidate.packageUrl !== 'string' || candidate.packageUrl.trim().length === 0)\n return invalidRow(guid, 'packageUrl');\n if (typeof candidate.sourcePath !== 'string' || candidate.sourcePath.trim().length === 0)\n return invalidRow(guid, 'sourcePath');\n if (!Number.isSafeInteger(candidate.publication?.generation))\n return invalidRow(guid, 'publication generation');\n if (candidate.publication === undefined) return invalidRow(guid, 'publication');\n const publication = candidate.publication;\n if (\n publication.schemaVersion !== 'asset-publication/1' ||\n typeof publication.sourcePath !== 'string' ||\n publication.sourcePath.trim().length === 0 ||\n typeof publication.sourceRevision !== 'string' ||\n publication.sourceRevision.trim().length === 0 ||\n publication.generation < 0 ||\n typeof publication.digest !== 'string' ||\n publication.digest.trim().length === 0 ||\n typeof publication.outputSetDigest !== 'string' ||\n publication.outputSetDigest.trim().length === 0 ||\n !Array.isArray(publication.outputs) ||\n publication.receipt === null ||\n typeof publication.receipt !== 'object' ||\n !Array.isArray(publication.externalEvidence)\n ) {\n return invalidRow(guid, 'publication tuple');\n }\n return ok(Object.freeze({ ...candidate, guid, publication }) as RuntimeCatalogRow);\n}\n","import type {\n CatalogDelta,\n CatalogDiagnostic,\n CatalogEntry,\n ResourceRevision,\n} from '@forgeax/engine-types';\nimport { type AssetLoadError, err, ok, type Result } from '@forgeax/engine-types';\nimport type { CatalogSource } from '../catalog-source.js';\nimport { type RuntimeCatalogRow, validateRuntimeRow } from './validate-runtime-row.js';\n\nexport interface CatalogSessionOptions {\n readonly scopeId?: string;\n readonly generation?: number;\n}\n\nexport interface CatalogSessionSnapshot {\n readonly scopeId: string;\n readonly generation: number;\n readonly epoch: number;\n readonly revision?: ResourceRevision;\n readonly entries: readonly RuntimeCatalogRow[];\n readonly changed: readonly string[];\n readonly removed: readonly string[];\n readonly diagnostics: readonly CatalogDiagnostic[];\n readonly listenerFailures: number;\n readonly stale: boolean;\n}\n\ntype SessionResult = Result<CatalogSessionSnapshot, AssetLoadError>;\ntype SessionListener = (snapshot: CatalogSessionSnapshot) => void;\n\nfunction runtimeError(\n code: AssetLoadError['code'],\n guid: string,\n detail: Record<string, unknown>,\n): AssetLoadError {\n if (code === 'catalog-discontinuous') {\n return {\n code,\n expected: 'an ordered catalog revision window',\n hint: 'reconcile the current Catalog before consuming this delta',\n detail: {\n scopeId: String(detail.scopeId ?? 'unknown'),\n expectedGeneration: Number(detail.expectedGeneration ?? 0),\n actualGeneration: Number(detail.actualGeneration ?? 0),\n },\n };\n }\n return {\n code: 'asset-package-invalid',\n expected: 'a verified Catalog source',\n hint: 'repair the producer Catalog and retry with the current publication',\n detail: { guid, reason: String(detail.reason ?? 'catalog source failed') },\n };\n}\n\nfunction freezeSnapshot(snapshot: CatalogSessionSnapshot): CatalogSessionSnapshot {\n return Object.freeze({\n ...snapshot,\n entries: Object.freeze([...snapshot.entries]),\n changed: Object.freeze([...snapshot.changed]),\n removed: Object.freeze([...snapshot.removed]),\n diagnostics: Object.freeze([...snapshot.diagnostics]),\n });\n}\n\nfunction sameEntry(left: CatalogEntry, right: CatalogEntry): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction key(guid: string): string {\n return guid.toLowerCase();\n}\n\nexport class CatalogSession {\n private readonly source: CatalogSource;\n private readonly scopeId: string;\n private readonly generation: number;\n private readonly entries = new Map<string, RuntimeCatalogRow>();\n private readonly listeners = new Set<SessionListener>();\n private unsubscribe: (() => void) | undefined;\n private baselinePromise: Promise<SessionResult> | undefined;\n private reconcilePromise: Promise<SessionResult> | undefined;\n private pending: CatalogDelta[] = [];\n private currentSnapshot: CatalogSessionSnapshot;\n private revision: ResourceRevision | undefined;\n private diagnostics: CatalogDiagnostic[] = [];\n private listenerFailures = 0;\n private changed = new Set<string>();\n private removed = new Set<string>();\n private epoch = 0;\n private stale = false;\n private staleGeneration = 0;\n private started = false;\n private disposed = false;\n\n constructor(source: CatalogSource, options: CatalogSessionOptions = {}) {\n this.source = source;\n this.scopeId = options.scopeId ?? source.expectedScope?.scopeId ?? 'asset-runtime';\n this.generation = options.generation ?? source.expectedScope?.generation ?? 0;\n this.currentSnapshot = freezeSnapshot({\n scopeId: this.scopeId,\n generation: this.generation,\n epoch: 0,\n entries: [],\n changed: [],\n removed: [],\n diagnostics: [],\n listenerFailures: 0,\n stale: false,\n });\n }\n\n start(): Promise<SessionResult> {\n if (this.baselinePromise !== undefined) return this.baselinePromise;\n if (this.disposed) return Promise.resolve(err(this.disposedError()));\n this.unsubscribe = this.source.subscribe((delta) => this.receive(delta));\n const promise = this.source\n .enumerate()\n .then((result) => {\n if (!result.ok) {\n this.markStale();\n this.publish();\n return err(runtimeError('asset-package-invalid', '', { reason: result.error.code }));\n }\n this.entries.clear();\n for (const entry of result.value) {\n const validated = validateRuntimeRow(entry);\n if (!validated.ok) {\n this.markStale();\n this.publish();\n return err(validated.error);\n }\n this.entries.set(key(validated.value.guid), validated.value);\n }\n this.started = true;\n this.stale = false;\n this.staleGeneration = this.generation;\n this.diagnostics = [];\n for (const delta of this.pending) this.fold(delta, false);\n this.pending = [];\n this.publish();\n return ok(this.currentSnapshot);\n })\n .catch((cause: unknown) => {\n this.markStale();\n this.addDiagnostic('catalog-degraded-rows', 'Catalog enumeration must resolve a Result');\n this.publish();\n return err(\n runtimeError('asset-package-invalid', '', {\n reason: cause instanceof Error ? cause.message : String(cause),\n }),\n );\n });\n this.baselinePromise = promise;\n void promise.then(\n (result) => {\n if (!result.ok) this.baselinePromise = undefined;\n },\n () => {\n this.baselinePromise = undefined;\n },\n );\n return promise;\n }\n\n reconcile(): Promise<SessionResult> {\n if (this.disposed) return Promise.resolve(err(this.disposedError()));\n if (this.reconcilePromise !== undefined) return this.reconcilePromise;\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.started = false;\n this.pending = [];\n this.baselinePromise = undefined;\n this.epoch += 1;\n const promise = this.start();\n this.reconcilePromise = promise;\n void promise.then(\n () => {\n if (this.reconcilePromise === promise) this.reconcilePromise = undefined;\n },\n () => {\n if (this.reconcilePromise === promise) this.reconcilePromise = undefined;\n },\n );\n return promise;\n }\n\n current(guid: string): RuntimeCatalogRow | undefined {\n return this.entries.get(key(guid));\n }\n\n snapshot(): CatalogSessionSnapshot {\n return this.currentSnapshot;\n }\n\n discontinuity(): AssetLoadError | undefined {\n if (!this.stale) return undefined;\n return {\n code: 'catalog-discontinuous',\n expected: 'an ordered, authoritative catalog revision window',\n hint: 'reconcile the Catalog source and retry the current publication',\n detail: {\n scopeId: this.scopeId,\n expectedGeneration: this.generation,\n actualGeneration: this.staleGeneration,\n },\n };\n }\n\n subscribe(listener: SessionListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.pending = [];\n this.listeners.clear();\n }\n\n private receive(delta: CatalogDelta): void {\n if (this.disposed) return;\n if (!this.started) {\n this.pending.push(delta);\n return;\n }\n this.fold(delta, true);\n }\n\n private fold(delta: CatalogDelta, publish: boolean): void {\n if (\n (delta.scopeId !== undefined && delta.scopeId !== this.scopeId) ||\n (delta.generation !== undefined && delta.generation !== this.generation)\n ) {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-scope-mismatch', 'delta scope does not match the session');\n if (publish) this.publish();\n return;\n }\n if (delta.authority === 'degraded') {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-degraded-rows', 'degraded rows are not identity-bearing');\n if (publish) this.publish();\n return;\n }\n if (delta.revisions !== undefined) {\n const baseline = delta.revisions.baseline;\n const current = delta.revisions.current;\n const valid =\n baseline.length === current.length &&\n current.every((point) => {\n const prior = baseline.find((item) => item.rootId === point.rootId);\n return prior !== undefined && point.revision === prior.revision + 1;\n });\n if (!valid) {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-gap', 'delta revision window is not contiguous');\n if (publish) this.publish();\n return;\n }\n }\n let changed = false;\n for (const entry of [...delta.added, ...delta.changed]) {\n const validated = validateRuntimeRow(entry);\n if (!validated.ok) {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-degraded-rows', 'delta contains an invalid runtime row');\n if (publish) this.publish();\n return;\n }\n const entryKey = key(validated.value.guid);\n const prior = this.entries.get(entryKey);\n if (prior === undefined || !sameEntry(prior, validated.value)) {\n this.entries.set(entryKey, validated.value);\n this.changed.add(entryKey);\n changed = true;\n if (validated.value.revision !== undefined) this.revision = validated.value.revision;\n }\n }\n for (const guid of delta.removed) {\n const entryKey = key(guid);\n if (this.entries.delete(entryKey)) {\n this.removed.add(entryKey);\n changed = true;\n }\n }\n if (changed) this.epoch += 1;\n if (publish) this.publish();\n }\n\n private addDiagnostic(code: CatalogDiagnostic['code'], expected: string): void {\n if (this.diagnostics.some((diagnostic) => diagnostic.code === code)) return;\n this.diagnostics.push({\n code,\n severity: 'blocking',\n expected,\n hint: 'reconcile the Catalog before loading the affected publication',\n authority: 'catalog',\n });\n }\n\n private markStale(actualGeneration = this.generation): void {\n this.stale = true;\n this.staleGeneration = actualGeneration;\n this.epoch += 1;\n }\n\n private publish(): void {\n this.currentSnapshot = freezeSnapshot({\n scopeId: this.scopeId,\n generation: this.generation,\n epoch: this.epoch,\n ...(this.revision === undefined ? {} : { revision: this.revision }),\n entries: [...this.entries.values()].sort((left, right) =>\n key(left.guid).localeCompare(key(right.guid)),\n ),\n changed: [...this.changed].sort(),\n removed: [...this.removed].sort(),\n diagnostics: this.diagnostics,\n listenerFailures: this.listenerFailures,\n stale: this.stale,\n });\n this.changed.clear();\n this.removed.clear();\n for (const listener of [...this.listeners]) {\n try {\n listener(this.currentSnapshot);\n } catch {\n this.listenerFailures = Math.min(1024, this.listenerFailures + 1);\n this.currentSnapshot = freezeSnapshot({\n ...this.currentSnapshot,\n listenerFailures: this.listenerFailures,\n });\n }\n }\n }\n\n private disposedError(): AssetLoadError {\n return runtimeError('asset-runtime-disposed', '', { scopeId: this.scopeId });\n }\n}\n","import type {\n AssetDecoder,\n AssetDecoderInput,\n AssetDecoderLease,\n AssetKind,\n AssetLoadError,\n Result,\n} from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { freezeRuntimePayload } from './immutable-payload.js';\n\ninterface DecoderEntry {\n readonly identity: symbol;\n readonly decoder: AssetDecoder<unknown>;\n readonly decode: (input: AssetDecoderInput<unknown>) => Promise<Result<unknown, AssetLoadError>>;\n references: number;\n}\n\nexport interface DecoderRegistryOptions {\n readonly scopeId?: string;\n}\n\nexport class DecoderRegistry {\n private readonly dispatch = new Map<string, DecoderEntry>();\n private readonly scopeId: string;\n private disposed = false;\n\n constructor(options: DecoderRegistryOptions = {}) {\n this.scopeId = options.scopeId ?? 'asset-runtime';\n }\n\n install<P, K extends string>(kind: AssetKind<P, K>, decoder: AssetDecoder<P>): AssetDecoderLease {\n if (this.disposed) throw new TypeError('asset runtime decoder registry is disposed');\n const normalizedDecoder = decoder as AssetDecoder<unknown>;\n const existing = this.dispatch.get(kind.kind);\n if (existing !== undefined) {\n if (existing.decoder !== normalizedDecoder) {\n throw new TypeError(`duplicate decoder kind \"${kind.kind}\"`);\n }\n existing.references += 1;\n return this.createLease(kind.kind, existing);\n }\n const identity = Symbol(kind.kind);\n const entry: DecoderEntry = {\n identity,\n decoder: normalizedDecoder,\n decode: (input) =>\n decoder.decode(input as AssetDecoderInput<P>) as Promise<Result<unknown, AssetLoadError>>,\n references: 1,\n };\n this.dispatch.set(kind.kind, entry);\n return this.createLease(kind.kind, entry);\n }\n\n private createLease(kind: string, entry: DecoderEntry): AssetDecoderLease {\n let released = false;\n return {\n kind,\n dispose: () => {\n if (released) return;\n released = true;\n entry.references -= 1;\n if (entry.references === 0 && this.dispatch.get(kind)?.identity === entry.identity) {\n this.dispatch.delete(kind);\n }\n },\n };\n }\n\n has<P, K extends string>(kind: AssetKind<P, K>): boolean {\n return this.dispatch.has(kind.kind);\n }\n\n load<P, K extends string>(\n kind: AssetKind<P, K>,\n input: AssetDecoderInput<P>,\n ): Promise<Result<P, AssetLoadError>> {\n return this.decode(kind, input);\n }\n\n loadByKind(\n kind: string,\n input: AssetDecoderInput<unknown>,\n ): Promise<Result<unknown, AssetLoadError>> {\n if (this.disposed) return Promise.resolve(err(disposedError(this.scopeId)));\n const entry = this.dispatch.get(kind);\n if (entry === undefined) {\n return Promise.resolve(\n err({\n code: 'asset-decoder-missing',\n expected: `an active decoder for kind \"${kind}\"`,\n hint: 'install the owner decoder lease before loading this kind',\n detail: { kind },\n }),\n );\n }\n return this.decodeEntry(kind, entry, input);\n }\n\n async decode<P, K extends string>(\n kind: AssetKind<P, K>,\n input: AssetDecoderInput<P>,\n ): Promise<Result<P, AssetLoadError>> {\n if (this.disposed) return err(disposedError(this.scopeId));\n if (input.signal.aborted) return err(cancelledError(input.envelope.guid));\n const entry = this.dispatch.get(kind.kind);\n if (entry === undefined) {\n return err({\n code: 'asset-decoder-missing',\n expected: `an active decoder for kind \"${kind.kind}\"`,\n hint: 'install the owner decoder lease before loading this kind',\n detail: { kind: kind.kind },\n });\n }\n return (await this.decodeEntry(kind.kind, entry, input)) as Result<P, AssetLoadError>;\n }\n\n private async decodeEntry(\n kind: string,\n entry: DecoderEntry,\n input: AssetDecoderInput<unknown>,\n ): Promise<Result<unknown, AssetLoadError>> {\n if (this.disposed) return err(disposedError(this.scopeId));\n if (input.signal.aborted) return err(cancelledError(input.envelope.guid));\n try {\n const result = await entry.decode(input);\n if (this.disposed) return err(disposedError(this.scopeId));\n if (this.dispatch.get(kind)?.identity !== entry.identity) {\n return err(supersededError(input.envelope.guid, kind));\n }\n if (input.signal.aborted) return err(cancelledError(input.envelope.guid));\n return result.ok ? ok(freezeRuntimePayload(result.value)) : result;\n } catch {\n return err({\n code: 'asset-decode-failed',\n expected: `decoder for kind \"${kind}\" to return a Result`,\n hint: 'inspect the owner decoder and retry the current publication',\n detail: { guid: input.envelope.guid, kind },\n });\n }\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.dispatch.clear();\n }\n}\n\nfunction cancelledError(guid: string): AssetLoadError {\n return {\n code: 'asset-load-cancelled',\n expected: 'the request AbortSignal to remain live until decode completes',\n hint: 'retry with a live AbortSignal when the request is still needed',\n detail: { guid },\n };\n}\n\nfunction disposedError(scopeId: string): AssetLoadError {\n return {\n code: 'asset-runtime-disposed',\n expected: 'an active asset runtime decoder scope',\n hint: 'obtain a new Registry from the current realm',\n detail: { scopeId },\n };\n}\n\nfunction supersededError(guid: string, kind: string): AssetLoadError {\n return {\n code: 'asset-superseded',\n expected: `the decoder lease for kind \"${kind}\" to remain current until decode completes`,\n hint: 'retry the current publication after reinstalling its owner decoder',\n detail: { guid, generation: 0 },\n };\n}\n","import type {\n AssetEnvelopeV2,\n AssetLoadError,\n AssetPublicationTuple,\n PackV2,\n Result,\n} from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\n\nexport interface PackReaderOptions {\n readonly fetcher?: typeof globalThis.fetch;\n}\n\nexport type VerifiedPack = PackV2<unknown>;\n\nfunction invalid(guid: string, reason: string): Result<never, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a verified Pack v2 envelope with complete runtime artifacts',\n hint: 're-cook the Pack v2 publication and retry the current tuple',\n detail: { guid, reason },\n });\n}\n\nfunction frozen<T>(value: T): T {\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) frozen(child);\n }\n return value;\n}\n\nfunction sameTuple(left: AssetPublicationTuple, right: AssetPublicationTuple): boolean {\n return (\n left.scopeId === right.scopeId &&\n left.generation === right.generation &&\n left.digest === right.digest &&\n left.outputSetDigest === right.outputSetDigest\n );\n}\n\nexport class PackReader {\n private readonly fetcher: typeof globalThis.fetch | undefined;\n private readonly verified = new Map<string, VerifiedPack>();\n private readonly pending = new Map<string, Promise<Result<VerifiedPack, AssetLoadError>>>();\n\n constructor(options: PackReaderOptions = {}) {\n // An injected fetcher is an explicit transport lease and is fixed for the\n // reader lifetime. With no injection, resolve the host fetch at read time:\n // App assembly can precede a dev/test host installing its transport.\n this.fetcher = options.fetcher?.bind(globalThis);\n }\n\n async read(\n packageUrl: string,\n expected: AssetPublicationTuple,\n signal: AbortSignal,\n ): Promise<Result<VerifiedPack, AssetLoadError>> {\n if (signal.aborted) return err(this.cancelled(packageUrl));\n const key = this.key(packageUrl, expected);\n const cached = this.verified.get(key);\n if (cached !== undefined) return ok(cached);\n const active = this.pending.get(key);\n if (active !== undefined) return active;\n const request = this.fetchAndVerify(packageUrl, expected, signal);\n this.pending.set(key, request);\n const result = await request;\n this.pending.delete(key);\n if (result.ok) this.verified.set(key, result.value);\n return result;\n }\n\n private async fetchAndVerify(\n packageUrl: string,\n expected: AssetPublicationTuple,\n signal: AbortSignal,\n ): Promise<Result<VerifiedPack, AssetLoadError>> {\n let response: Response;\n try {\n const fetcher = this.fetcher ?? globalThis.fetch.bind(globalThis);\n response = await fetcher(packageUrl, { signal });\n } catch (_cause) {\n if (signal.aborted) return err(this.cancelled(packageUrl));\n return err({\n code: 'asset-fetch-failed',\n expected: 'HTTP 200 for the current Pack URL',\n hint: 'verify the package locator and republish the Pack',\n detail: { guid: packageUrl, packageUrl },\n });\n }\n if (!response.ok) {\n return err({\n code: 'asset-fetch-failed',\n expected: 'HTTP 200 for the current Pack URL',\n hint: 'verify the package locator and republish the Pack',\n detail: { guid: packageUrl, packageUrl },\n });\n }\n let value: unknown;\n try {\n value = await response.json();\n } catch {\n return invalid(packageUrl, 'invalid JSON');\n }\n return this.verify(value, expected);\n }\n\n private key(packageUrl: string, tuple: AssetPublicationTuple): string {\n return `${packageUrl}\\u0000${tuple.scopeId}\\u0000${tuple.generation}\\u0000${tuple.digest}\\u0000${tuple.outputSetDigest}`;\n }\n\n verify(value: unknown, expected: AssetPublicationTuple): Result<VerifiedPack, AssetLoadError> {\n if (value === null || typeof value !== 'object') return invalid('', 'Pack is not an object');\n const pack = value as Partial<PackV2<unknown>>;\n if (pack.schemaVersion !== '2.0.0' || pack.kind !== 'internal-text-package') {\n return invalid('', 'schemaVersion or kind');\n }\n if (\n typeof pack.scopeId !== 'string' ||\n !Number.isSafeInteger(pack.generation) ||\n typeof pack.digest !== 'string' ||\n typeof pack.outputSetDigest !== 'string' ||\n !sameTuple(pack as AssetPublicationTuple, expected)\n ) {\n return invalid('', 'publication tuple mismatch');\n }\n if (!Array.isArray(pack.assets)) return invalid('', 'assets');\n const guids = new Set<string>();\n for (const raw of pack.assets) {\n const asset = raw as Partial<AssetEnvelopeV2<unknown>>;\n const guid = typeof asset.guid === 'string' ? asset.guid : '';\n if (guid.length === 0 || guids.has(guid.toLowerCase()))\n return invalid(guid, 'duplicate guid');\n guids.add(guid.toLowerCase());\n if (\n typeof asset.kind !== 'string' ||\n asset.payload === undefined ||\n !Array.isArray(asset.refs) ||\n asset.refs.some((ref) => typeof ref !== 'string') ||\n asset.artifacts === null ||\n typeof asset.artifacts !== 'object'\n ) {\n return invalid(guid, 'asset envelope fields');\n }\n for (const [artifactKey, descriptor] of Object.entries(asset.artifacts)) {\n if (!this.validArtifact(guid, artifactKey, descriptor)) {\n return invalid(guid, `artifact ${artifactKey}`);\n }\n }\n }\n return ok(frozen(pack as VerifiedPack));\n }\n\n private validArtifact(_guid: string, key: string, value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n const descriptor = value as Record<string, unknown>;\n const integrity = descriptor.integrity;\n return (\n key.length > 0 &&\n typeof descriptor.path === 'string' &&\n descriptor.path.length > 0 &&\n typeof descriptor.mediaType === 'string' &&\n descriptor.mediaType.length > 0 &&\n (descriptor.contentEncoding === 'identity' || descriptor.contentEncoding === 'zstd') &&\n Number.isSafeInteger(descriptor.byteLength) &&\n Number(descriptor.byteLength) >= 0 &&\n integrity !== null &&\n typeof integrity === 'object' &&\n (integrity as Record<string, unknown>).algorithm === 'sha256' &&\n typeof (integrity as Record<string, unknown>).digest === 'string' &&\n /^sha256:[0-9a-f]{64}$/i.test(String((integrity as Record<string, unknown>).digest))\n );\n }\n\n private cancelled(guid: string): AssetLoadError {\n return {\n code: 'asset-load-cancelled',\n expected: 'the request AbortSignal to remain live while reading the Pack',\n hint: 'retry with a live AbortSignal when the request is still needed',\n detail: { guid },\n };\n }\n}\n","import type {\n Asset,\n AssetArtifactReader,\n AssetDecoder,\n AssetDecoderInput,\n AssetDecoderLease,\n AssetKind,\n AssetLoadError,\n BuiltinAssetKind,\n BuiltinAssetPayload,\n Result,\n} from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport type { CatalogSource } from '../catalog-source.js';\nimport { ArtifactCache } from './artifact-cache.js';\nimport { AssetGraph, type AssetGraphSnapshot } from './asset-graph.js';\nimport { CatalogSession, type CatalogSessionOptions } from './catalog-session.js';\nimport { DecoderRegistry } from './decoder-registry.js';\nimport { freezeRuntimePayload } from './immutable-payload.js';\nimport { PackReader } from './pack-reader.js';\nimport { validateRuntimeRow } from './validate-runtime-row.js';\n\nexport interface AssetRegistryOptions extends CatalogSessionOptions {\n readonly catalog: CatalogSource;\n readonly fetcher?: typeof globalThis.fetch;\n readonly maxConcurrentReads?: number;\n}\n\nexport interface AssetLoadOptions {\n readonly signal?: AbortSignal;\n}\n\nexport type AssetRegistrySnapshot = AssetGraphSnapshot;\n\nexport type AssetRegistrySnapshotCounters = AssetRegistrySnapshot['counters'];\n\nexport interface AssetRegistry {\n installDecoder<P, K extends string>(\n kind: AssetKind<P, K>,\n decoder: AssetDecoder<P>,\n ): AssetDecoderLease;\n load<K extends BuiltinAssetKind>(\n guid: string,\n kind: K,\n options?: AssetLoadOptions,\n ): Promise<Result<BuiltinAssetPayload<K>, AssetLoadError>>;\n load<P, K extends string>(\n guid: string,\n kind: AssetKind<P, K>,\n options?: AssetLoadOptions,\n ): Promise<Result<P, AssetLoadError>>;\n snapshot(): AssetRegistrySnapshot;\n subscribe(listener: (snapshot: AssetRegistrySnapshot) => void): () => void;\n dispose(): void;\n}\n\n/** Internal render projection; the root Registry keeps only its five actions. */\nexport interface AssetRegistryResolver {\n readonly epoch: number;\n lookup<T extends Asset>(guid: string): T | undefined;\n guidOf(asset: Asset): string | undefined;\n}\n\nconst REGISTRY_RESOLVER = Symbol.for('forgeax.assets-runtime.registry-resolver');\ntype RegistryWithResolver = AssetRegistry & {\n [REGISTRY_RESOLVER]?: AssetRegistryResolver;\n};\n\nexport function getAssetRegistryResolver(registry: AssetRegistry): AssetRegistryResolver {\n const resolver = (registry as RegistryWithResolver)[REGISTRY_RESOLVER];\n if (resolver === undefined) {\n throw new TypeError('AssetRegistry resolver is not owned by this asset runtime');\n }\n return resolver;\n}\n\nfunction missing(guid: string): AssetLoadError {\n return {\n code: 'asset-not-found',\n expected: `the current Catalog to contain GUID \"${guid}\"`,\n hint: 'inspect the producer Catalog and rebuild the missing publication',\n detail: { guid },\n };\n}\n\nfunction mismatch(guid: string, expectedKind: string, actualKind: string): AssetLoadError {\n return {\n code: 'asset-kind-mismatch',\n expected: `Catalog kind \"${actualKind}\" to match \"${expectedKind}\"`,\n hint: 'pass the Catalog kind or the matching custom AssetKind token',\n detail: { guid, expectedKind, actualKind },\n };\n}\n\nfunction artifactError(guid: string, reason: string): AssetLoadError {\n return {\n code: 'asset-integrity-failed',\n expected: 'the verified artifact byte length and digest',\n hint: 'verify the artifact digest and recook the Pack',\n detail: {\n guid,\n artifactKey: reason,\n expectedDigest: 'descriptor integrity',\n actualDigest: reason,\n },\n };\n}\n\nconst ASSET_GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction invalidGuid(guid: string): AssetLoadError {\n return {\n code: 'asset-guid-invalid',\n expected: 'a 36-character dash-form asset GUID',\n hint: 'pass the producer GUID from the current Catalog row',\n detail: { guid },\n };\n}\n\nexport function createAssetRegistry(options: AssetRegistryOptions): AssetRegistry {\n const session = new CatalogSession(options.catalog, options);\n const reader = new PackReader(options.fetcher === undefined ? {} : { fetcher: options.fetcher });\n const cache = new ArtifactCache();\n const decoders = new DecoderRegistry(\n options.scopeId === undefined ? {} : { scopeId: options.scopeId },\n );\n const graph = new AssetGraph<{ readonly value: unknown; readonly refs: readonly string[] }>({\n ...(options.maxConcurrentReads === undefined\n ? {}\n : { maxConcurrentReads: options.maxConcurrentReads }),\n read: async (guid, signal) => {\n const row = session.current(guid);\n if (row === undefined) return err(missing(guid));\n const validated = validateRuntimeRow(row);\n if (!validated.ok) return validated;\n const publication = validated.value.publication;\n const tuple = {\n scopeId: session.snapshot().scopeId,\n generation: publication.generation,\n digest: publication.digest,\n outputSetDigest: publication.outputSetDigest,\n };\n const pack = await reader.read(row.packageUrl, tuple, signal);\n if (!pack.ok) return pack;\n const envelope = pack.value.assets.find(\n (asset) => asset.guid.toLowerCase() === guid.toLowerCase(),\n );\n if (envelope === undefined) return err(missing(guid));\n const artifacts: AssetArtifactReader = {\n read: (descriptor) => {\n const integrity = descriptor.integrity;\n if (integrity === undefined)\n return Promise.resolve(err(artifactError(guid, descriptor.path)));\n const key = `${tuple.scopeId}:${tuple.generation}:${tuple.outputSetDigest}:${integrity.digest}`;\n return cache.read(key, async () => {\n const url = resolveArtifactUrl(row.packageUrl, descriptor.path);\n let response: Response;\n try {\n response = await (options.fetcher ?? globalThis.fetch)(url, { signal });\n } catch {\n return err(artifactError(guid, descriptor.path));\n }\n if (!response.ok) return err(artifactError(guid, descriptor.path));\n const bytes = new Uint8Array(await response.arrayBuffer());\n if (descriptor.byteLength === undefined || bytes.byteLength !== descriptor.byteLength) {\n return err(artifactError(guid, descriptor.path));\n }\n const actualDigest = await sha256(bytes);\n if (actualDigest !== descriptor.integrity?.digest.toLowerCase()) {\n return err(artifactError(guid, `${descriptor.path}:${actualDigest}`));\n }\n return ok(bytes);\n });\n },\n };\n const input: AssetDecoderInput<unknown> = { envelope, artifacts, signal };\n const decoded = await decoders.loadByKind(envelope.kind, input);\n if (!decoded.ok) return decoded;\n return ok({ value: freezeRuntimePayload(decoded.value), refs: envelope.refs });\n },\n });\n\n let catalogEpoch = session.snapshot().epoch;\n const unsubscribeCatalog = session.subscribe((snapshot) => {\n if (snapshot.epoch === catalogEpoch) return;\n catalogEpoch = snapshot.epoch;\n graph.invalidateForCatalogChange(\n snapshot.stale ? undefined : [...snapshot.changed, ...snapshot.removed],\n );\n });\n\n const registry: AssetRegistry = {\n installDecoder: (kind, decoder) => decoders.install(kind, decoder),\n load: (async (\n guid: string,\n kind: BuiltinAssetKind | AssetKind<unknown, string>,\n loadOptions: AssetLoadOptions = {},\n ): Promise<Result<unknown, AssetLoadError>> => {\n if (!ASSET_GUID_PATTERN.test(guid)) return err(invalidGuid(guid));\n const expectedKind = typeof kind === 'string' ? kind : kind.kind;\n const started = await session.start();\n if (!started.ok) return err(started.error);\n if (session.snapshot().stale) {\n const reconciled = await session.reconcile();\n if (!reconciled.ok) return err(reconciled.error);\n const discontinuity = session.discontinuity();\n if (discontinuity !== undefined) return err(discontinuity);\n }\n const row = session.current(guid);\n if (row === undefined) return err(missing(guid));\n if (row.kind !== expectedKind) return err(mismatch(guid, expectedKind, row.kind));\n const result = await graph.load(guid, loadOptions.signal);\n return result.ok ? ok(result.value.value) : result;\n }) as AssetRegistry['load'],\n snapshot: () => graph.snapshot(),\n subscribe: (listener) => graph.subscribe(listener),\n dispose: () => {\n graph.dispose();\n unsubscribeCatalog();\n decoders.dispose();\n cache.clear();\n session.dispose();\n },\n };\n const resolver: AssetRegistryResolver = {\n get epoch() {\n return graph.snapshot().epoch;\n },\n lookup: <T extends Asset>(guid: string) => graph.lookup(guid) as T | undefined,\n guidOf: (asset: Asset) => graph.guidOf(asset),\n };\n Object.defineProperty(registry, REGISTRY_RESOLVER, {\n value: resolver,\n enumerable: false,\n });\n return registry;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes as unknown as BufferSource);\n return `sha256:${Array.from(new Uint8Array(digest), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('')}`;\n}\n\nfunction resolveArtifactUrl(packageUrl: string, path: string): string {\n const separator = packageUrl.lastIndexOf('/');\n const packageDirectory = separator < 0 ? '' : packageUrl.slice(0, separator + 1);\n try {\n return new URL(path, packageDirectory).toString();\n } catch {\n return `${packageDirectory}${path.replace(/^\\//, '')}`;\n }\n}\n","import {\n createMaterialError,\n err,\n type MaterialErrorFor,\n type MaterialGenerationVector,\n ok,\n type Result,\n} from '@forgeax/engine-types';\n\nexport type { MaterialGenerationVector } from '@forgeax/engine-types';\n\nexport interface MaterialCachedArtifact {\n readonly bytes: Uint8Array;\n}\n\nexport type MaterialStaleGenerationError =\n MaterialErrorFor<'material-specialization-stale-generation'>;\n\nfunction sameVector(left: MaterialGenerationVector, right: MaterialGenerationVector): boolean {\n const names = new Set([...Object.keys(left.dependencies), ...Object.keys(right.dependencies)]);\n return [...names].every((name) => left.dependencies[name] === right.dependencies[name]);\n}\n\nexport class MaterialGenerationCache {\n readonly #resolved = new Map<string, Promise<unknown>>();\n readonly #resolvedByMaterial = new Map<string, Set<string>>();\n readonly #resolvedKeys = new Map<string, string>();\n readonly #artifacts = new Map<string, MaterialCachedArtifact>();\n readonly #generations = new Map<string, number>();\n readonly #errors = new Map<string, MaterialStaleGenerationError>();\n readonly #materialDependencies = new Map<string, readonly string[]>();\n readonly #dependents = new Map<string, Set<string>>();\n\n resolve<T>(\n materialGuid: string,\n specializationKey: string,\n load: () => Promise<T>,\n publicationGeneration = 0,\n ): Promise<T> {\n const cacheKey = `${materialGuid}:${specializationKey}:${publicationGeneration}`;\n const previous = this.#resolved.get(cacheKey);\n if (previous !== undefined) return previous as Promise<T>;\n const promise = load();\n this.#resolved.set(cacheKey, promise);\n const resolvedKeys = this.#resolvedByMaterial.get(materialGuid) ?? new Set<string>();\n resolvedKeys.add(cacheKey);\n this.#resolvedByMaterial.set(materialGuid, resolvedKeys);\n void promise.then(\n (value) => {\n if (isStaleGenerationResult(value)) this.removeResolved(materialGuid, cacheKey, promise);\n },\n () => this.removeResolved(materialGuid, cacheKey, promise),\n );\n return promise;\n }\n\n linkResolved(materialGuid: string, specializationKey: string): void {\n this.#resolvedKeys.set(materialGuid, specializationKey);\n }\n\n getResolvedKey(materialGuid: string): string | undefined {\n return this.#resolvedKeys.get(materialGuid);\n }\n\n storeArtifact(key: string, artifact: MaterialCachedArtifact): void {\n this.#artifacts.set(key, artifact);\n }\n\n getArtifact(key: string): MaterialCachedArtifact | undefined {\n return this.#artifacts.get(key);\n }\n\n bump(dependency: string): number {\n const generation = (this.#generations.get(dependency) ?? 0) + 1;\n this.#generations.set(dependency, generation);\n for (const materialGuid of this.#dependents.get(dependency) ?? []) {\n for (const cacheKey of this.#resolvedByMaterial.get(materialGuid) ?? []) {\n this.#resolved.delete(cacheKey);\n }\n this.#resolvedByMaterial.delete(materialGuid);\n }\n return generation;\n }\n\n generationError(materialGuid: string): MaterialStaleGenerationError | undefined {\n return this.#errors.get(materialGuid);\n }\n\n async loadWithGeneration<T>(\n materialGuid: string,\n dependencies: readonly string[],\n load: (\n generation: MaterialGenerationVector,\n ) => Promise<{ readonly generation: MaterialGenerationVector; readonly value: T }>,\n ): Promise<Result<T, MaterialStaleGenerationError>> {\n const dependencySet = Object.freeze([...dependencies]);\n this.trackDependencies(materialGuid, dependencySet);\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const generation = this.vector(dependencySet);\n const loaded = await load(generation);\n const observed = snapshotVector(loaded.generation);\n const current = this.vector(dependencySet);\n if (sameVector(observed, current)) {\n this.#errors.delete(materialGuid);\n return ok(loaded.value);\n }\n if (attempt === 1) {\n const error = staleGenerationError(materialGuid, dependencySet, observed, current);\n this.#errors.set(materialGuid, error);\n return err(error);\n }\n }\n const current = this.vector(dependencySet);\n return err(staleGenerationError(materialGuid, dependencySet, current, current));\n }\n\n private trackDependencies(materialGuid: string, dependencies: readonly string[]): void {\n const previous = this.#materialDependencies.get(materialGuid);\n if (previous !== undefined) {\n for (const dependency of previous) this.#dependents.get(dependency)?.delete(materialGuid);\n }\n this.#materialDependencies.set(materialGuid, dependencies);\n for (const dependency of dependencies) {\n const dependents = this.#dependents.get(dependency) ?? new Set<string>();\n dependents.add(materialGuid);\n this.#dependents.set(dependency, dependents);\n }\n }\n\n private removeResolved(materialGuid: string, cacheKey: string, promise: Promise<unknown>): void {\n if (this.#resolved.get(cacheKey) !== promise) return;\n this.#resolved.delete(cacheKey);\n const resolvedKeys = this.#resolvedByMaterial.get(materialGuid);\n if (resolvedKeys === undefined) return;\n resolvedKeys.delete(cacheKey);\n if (resolvedKeys.size === 0) this.#resolvedByMaterial.delete(materialGuid);\n }\n\n private vector(dependencies: readonly string[]): MaterialGenerationVector {\n return snapshotVector({\n dependencies: Object.fromEntries(\n dependencies.map((dependency) => [dependency, this.#generations.get(dependency) ?? 0]),\n ),\n });\n }\n}\n\nfunction snapshotVector(vector: MaterialGenerationVector): MaterialGenerationVector {\n return Object.freeze({ dependencies: Object.freeze({ ...vector.dependencies }) });\n}\n\nfunction staleGenerationError(\n material: string,\n dependencies: readonly string[],\n observed: MaterialGenerationVector,\n current: MaterialGenerationVector,\n): MaterialStaleGenerationError {\n const detail = Object.freeze({\n code: 'material-specialization-stale-generation' as const,\n material,\n dependencies,\n observed,\n current,\n });\n return Object.freeze(createMaterialError('material-specialization-stale-generation', detail));\n}\n\nfunction isStaleGenerationResult(value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n const result = value as { readonly ok?: unknown; readonly error?: unknown };\n if (result.ok !== false || result.error === null || typeof result.error !== 'object')\n return false;\n return (\n (result.error as { readonly code?: unknown }).code ===\n 'material-specialization-stale-generation'\n );\n}\n","import type { MaterialReady } from './loader.js';\n\n/**\n * Read-only facts for one GUID after the MaterialReady gate succeeds.\n * `status` is retained for the existing runtime API; `readiness` is the\n * machine-readable first-level field for inspection consumers. This owner\n * does not invent transport provenance or compare transport URLs.\n */\nexport interface MaterialRuntimeInfo {\n readonly materialGuid: string;\n readonly readiness: 'ready';\n readonly publicationGeneration: number;\n readonly specializationKey: string;\n readonly artifactDigest: string;\n readonly layoutIdentity: string;\n readonly dependencies: readonly string[];\n readonly profile: string;\n readonly sourceClosure: readonly string[];\n readonly parameterContract: MaterialReady['parameterContract'];\n readonly refs: MaterialReady['record']['refs'];\n readonly receipt: MaterialReady['record']['receipt'];\n readonly status: 'Ready';\n}\n\nexport function inspectMaterialRuntime(ready: MaterialReady): MaterialRuntimeInfo {\n return {\n materialGuid: ready.materialGuid,\n readiness: 'ready',\n publicationGeneration: ready.publicationGeneration,\n specializationKey: ready.specializationKey,\n artifactDigest: ready.artifactDigest,\n layoutIdentity: ready.record.receipt.identity.layoutIdentity,\n dependencies: [\n ...ready.record.refs.parent,\n ...ready.record.refs.textures,\n ...ready.record.refs.samplers,\n ...ready.record.refs.modules,\n ],\n profile: ready.record.receipt.profile,\n sourceClosure: ready.sourceClosure,\n parameterContract: ready.parameterContract,\n refs: ready.record.refs,\n receipt: ready.record.receipt,\n status: 'Ready',\n };\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport type { Loader } from '@forgeax/engine-types';\n\nimport type { AssetRegistry } from './asset-registry';\nimport type { PackLoader } from './loader-registry';\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n assets?: AssetRegistry;\n }\n}\n\n/** Provide one renderer-owned asset registry to the current Cordis realm. */\nexport function assetsPlugin(assets: AssetRegistry): Plugin {\n return {\n name: 'assets',\n provide: 'assets',\n apply(ctx) {\n ctx.provide('assets', assets);\n },\n };\n}\n\n/** Reversibly register one runtime asset loader. */\nexport function assetLoaderPlugin(loader: Loader<unknown>): Plugin {\n return {\n name: `asset-loader:${loader.kind}`,\n inject: ['assets'],\n apply(ctx) {\n const assets = ctx.assets;\n if (assets === undefined) throw new Error('asset loader plugin requires the assets service');\n ctx.effect(() => assets.loaders.register(loader), `assets/loader:${loader.kind}`);\n },\n };\n}\n\n/** Reversibly register one pack loader. */\nexport function packLoaderPlugin(loader: PackLoader): Plugin {\n return {\n name: `pack-loader:${loader.kind}`,\n inject: ['assets'],\n apply(ctx) {\n const assets = ctx.assets;\n if (assets === undefined) throw new Error('pack loader plugin requires the assets service');\n ctx.effect(() => assets.loaders.registerPackLoader(loader), `assets/pack:${loader.kind}`);\n },\n };\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport type { Asset, Handle, Result, TextureAsset } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\n\nexport type TilesetRuntimeErrorCode =\n | 'tileset-atlas-not-found'\n | 'tileset-atlas-stale'\n | 'tileset-atlas-kind-mismatch';\n\nexport interface TilesetRuntimeError {\n readonly code: TilesetRuntimeErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly guid: string;\n readonly actualKind?: string;\n };\n}\n\nexport interface ResolvedTilesetRuntime {\n readonly guid: string;\n readonly payload: TextureAsset;\n readonly handle: Handle<'TextureAsset', 'shared'>;\n}\n\nexport type TilesetAtlasLookup = Asset | { readonly code: 'stale' } | undefined;\n\n/** Project one durable atlas GUID into the current World at the tilemap owner. */\nexport function resolveTilesetRuntime(\n world: World,\n guid: string,\n lookup: (guid: string) => TilesetAtlasLookup,\n): Result<ResolvedTilesetRuntime, TilesetRuntimeError> {\n if (guid.length === 0) {\n return err({\n code: 'tileset-atlas-not-found',\n expected: 'a non-empty durable atlas GUID',\n hint: 'load the atlas payload before extracting the tilemap',\n detail: { guid },\n });\n }\n const payload = lookup(guid);\n if (payload === undefined) {\n return err({\n code: 'tileset-atlas-not-found',\n expected: `a loaded texture payload for atlas GUID ${guid}`,\n hint: 'load or retain the atlas before extracting the tilemap',\n detail: { guid },\n });\n }\n if ('code' in payload) {\n return err({\n code: 'tileset-atlas-stale',\n expected: `a current texture payload for atlas GUID ${guid}`,\n hint: 'rebuild the stale atlas projection before extracting the tilemap',\n detail: { guid },\n });\n }\n if (payload.kind !== 'texture') {\n return err({\n code: 'tileset-atlas-kind-mismatch',\n expected: 'a texture atlas payload',\n hint: `replace atlas GUID ${guid} with a texture asset`,\n detail: { guid, actualKind: payload.kind },\n });\n }\n return ok({\n guid,\n payload,\n handle: world.internSharedRef('TextureAsset', payload),\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/asset-kind.ts","../src/builtin-asset-registry.ts","../src/loader-registry.ts","../src/errors/asset.ts","../src/handles.ts","../src/scene-payload.ts","../src/loaders/mesh-bin.ts","../src/mipmap-generator.ts","../src/loaders/pack-artifact.ts","../src/loaders/inline-pack.ts","../src/wire-default-loaders.ts","../src/aabb.ts","../src/material/runtime-shader.ts","../src/payload-validate.ts","../src/registry/artifact-io.ts","../src/registry/asset-evidence.ts","../src/registry/catalog.ts","../src/registry/catalog-state.ts","../src/resolve-asset-handle.ts","../src/scene-handle-fields.ts","../src/registry/scene-publication-fence.ts","../src/registry/instantiate.ts","../src/material/loader.ts","../src/registry/runtime-projection.ts","../src/registry/load-by-guid.ts","../src/registry/load-state.ts","../src/registry/validate-material.ts","../src/asset-registry.ts","../src/catalog-source.ts","../src/image-error.ts","../src/decode-image-bytes.ts","../src/dynamic-texture-store.ts","../src/internal/artifact-cache.ts","../src/internal/immutable-payload.ts","../src/internal/asset-graph.ts","../src/internal/validate-runtime-row.ts","../src/internal/catalog-session.ts","../src/internal/decoder-registry.ts","../src/internal/pack-reader.ts","../src/internal/load-asset.ts","../src/material/generation-cache.ts","../src/material/inspection.ts","../src/plugin.ts","../src/resolve-tileset-runtime.ts"],"names":["output","handleSlot","err","component","key","ok","AssetError","failure","value","AssetGuid","PROCEDURAL_FLOATS_PER_VERTEX","ASSET_ERROR_HINTS","record","sameRevision","BUILTIN_BASE","guidKey","missing","decompressZstd","unwrapHandle","guid","authoringCapabilityForAssetKind","freezeSnapshot","sha256","current","createMaterialError"],"mappings":";;;;;;;;;;;;;;;;AAGO,SAAS,gBAA8C,IAAA,EAA0B;AACtF,EAAA,OAAO,MAAA,CAAO,MAAA,CAAO,EAAE,IAAA,EAAM,CAAA;AAC/B;AC0CA,IAAM,cAAA,GAAiB,iBAAA,CAAkB,CAAA,EAAG,CAAA,EAAG,CAAC,CAAA;AAChD,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,CAAA;AAAA,MAChC,MAAA,EAAQ,EAAE,IAAA,EAAM,UAAA,EAAY,QAAQ,IAAA;AAAK,KAC1C,CAAA;AAAA,EACH;AACA,EAAA,OAAOG,EAAAA,CAAG;AAAA,IACR,IAAA;AAAA,IACA,OAAA;AAAA,IACA,MAAA,EAAQ,KAAA,CAAM,eAAA,CAAgB,cAAA,EAAgB,OAAO;AAAA,GACtD,CAAA;AACH","file":"index.mjs","sourcesContent":["import type { AssetKind } from '@forgeax/engine-types';\n\n/** Create the type witness shared by one custom decoder lease and its loads. */\nexport function defineAssetKind<P, K extends string = string>(kind: K): AssetKind<P, K> {\n return Object.freeze({ kind }) as AssetKind<P, K>;\n}\n","// ─── BuiltinAssetRegistry (D-15 process-static tier) ────────────────────────\n//\n// D-15 two-tier asset resolution. Builtin payloads (the 5 procedural meshes\n// the engine ships with) are PROCESS-STATIC: a frozen const keyed by a fixed\n// slot u32 in [1, BUILTIN_BASE). They never enter a World's SharedRefStore,\n// never participate in reference counting, and resolve without any World\n// reference — so a builtin handle (HANDLE_CUBE etc.) is transparent across\n// every World and every renderer.\n//\n// R-13 (module init-order): all five payload consts are constructed\n// synchronously at module load, are module-level, and have no side effect.\n// Importing this module then calling resolve() observes fully-constructed\n// frozen payloads — there is no lazy getter and no circular-dependency\n// init hazard.\n//\n// The companion AssetRegistry (asset-registry.ts) retreats to a thin\n// guid<->handle index; user-tier payloads live in World.sharedRefs at\n// slots >= BUILTIN_BASE. AssetRegistry.get(handle) dispatches by slot range:\n// slot < BUILTIN_BASE -> BuiltinAssetRegistry.resolve, else world.sharedRefs.\n\nimport {\n createBoxGeometry,\n createCylinderGeometry,\n createPlaneGeometry,\n createSphereGeometry,\n meshFromInterleaved,\n} from '@forgeax/engine-geometry';\nimport type { Handle, MeshAsset as TypesMeshAsset } from '@forgeax/engine-types';\nimport { BUILTIN_BASE, handleSlot } from '@forgeax/engine-types';\n\n// D-16: BUILTIN_BASE is the slot boundary [1, BUILTIN_BASE) builtin /\n// [BUILTIN_BASE, +inf) user-tier. It lives in @forgeax/engine-types (the\n// single shared dependency of ecs + runtime) to avoid a cross-package cycle;\n// re-exported from the runtime barrel here for AI-user discoverability.\nexport { BUILTIN_BASE };\n\n// ─── Builtin geometry data (12F: position + normal + uv + tangent) ──────────\n// bug-20260709-builtin-quad-withoutaabb-disables-sprite-frustum-cu: every\n// builtin geometry payload keeps the local-space AABB produced by its geometry\n// factory. Builtins are ordinary MeshAssets at the render boundary, so removing\n// their bounds silently turns them into always-visible renderables and defeats\n// the same frustum-culling path used by imported meshes.\n\n// BUILTIN_CUBE is synthesized from `createBoxGeometry(1, 1, 1)` so the cube\n// inherits Three.js-aligned per-face UV unwrap and per-vertex tangent vec4.\n// The procedural factory always returns Result.ok for valid (>0) extents,\n// hence the unwrap-with-throw is safe at module init.\nconst builtinCubeRes = createBoxGeometry(1, 1, 1);\nif (!builtinCubeRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createBoxGeometry(1,1,1) failed: ${builtinCubeRes.error.code}`,\n );\n}\nexport const BUILTIN_CUBE: TypesMeshAsset = Object.freeze(builtinCubeRes.value);\n\n// BUILTIN_TRIANGLE: 3 vertices in the XY plane facing +Z, with a [0..1]² UV\n// triangle so a textured triangle samples the texture (apex = top-centre,\n// base = bottom-left / bottom-right). meshFromInterleaved expands the\n// 8-floats interleaved input (pos + normal + uv) to the runtime 12-floats\n// stride (adds tangent vec4 per `geometry/tangent.ts` path A).\nconst builtinTriangleRes = meshFromInterleaved(\n new Float32Array([\n // pos.xyz normal.xyz uv.xy\n 0, 0.7, 0, 0, 0, 1, 0.5, 1, -0.7, -0.6, 0, 0, 0, 1, 0, 0, 0.7, -0.6, 0, 0, 0, 1, 1, 0,\n ]),\n new Uint16Array([0, 1, 2]),\n);\nif (!builtinTriangleRes.ok) {\n throw new Error(\n `[builtin-asset-registry] builtin triangle geometry failed: ${builtinTriangleRes.error.code}`,\n );\n}\nexport const BUILTIN_TRIANGLE: TypesMeshAsset = Object.freeze(builtinTriangleRes.value);\n\n// BUILTIN_QUAD: unit-size plane on XY facing +Z (4 vertices, 2 triangles,\n// 6 indices). Synthesised from `createPlaneGeometry(1, 1)` (which itself\n// chains through `meshFromInterleaved`) so the resulting MeshAsset is\n// byte-identical to procedural plane output — zero new layout\n// discriminator, AI users reason about UV / pivot semantics by reading\n// `packages/runtime/src/geometry/plane.ts` (charter P4 consistent\n// abstraction; feat-20260520 M-1 / w06).\n// bug-20260709-builtin-quad-withoutaabb-disables-sprite-frustum-cu: this\n// payload follows the same local-AABB contract as every other builtin.\nconst builtinQuadRes = createPlaneGeometry(1, 1);\nif (!builtinQuadRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createPlaneGeometry(1,1) failed: ${builtinQuadRes.error.code}`,\n );\n}\nexport const BUILTIN_QUAD: TypesMeshAsset = Object.freeze(builtinQuadRes.value);\n\n// BUILTIN_SPHERE: UV-sphere synthesised from createSphereGeometry(1, 16, 12).\n// Vertices are at exact radius-1 positions (sphere.ts:40-45) so the\n// |hypot(pos)-1| < 1e-6 radius invariant holds by construction. Index\n// buffer is Uint32Array — downstream consumers (step-3 upload loop,\n// createRenderer.ts) auto-select 'uint32' indexFormat via\n// `instanceof Uint32Array`.\nconst builtinSphereRes = createSphereGeometry(1, 16, 12);\nif (!builtinSphereRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createSphereGeometry(1,16,12) failed: ${builtinSphereRes.error.code}`,\n );\n}\nexport const BUILTIN_SPHERE: TypesMeshAsset = Object.freeze(builtinSphereRes.value);\n\n// BUILTIN_CYLINDER: procedural cylinder synthesised from createCylinderGeometry(0.5, 0.5, 1, 16, 1).\n// Radius-top=radius-bottom=0.5, height=1, 16 radial segments, 1 height segment — a\n// unit-height open cylinder (no caps). meshFromInterleaved expands the 8-floats\n// interleaved input (pos + normal + uv) to the runtime 12-floats stride (adds\n// tangent vec4 per geometry/tangent.ts path A).\n// feat-20260701-editor-world-container-doc-ecs-collapse M0 / AC-16:\n// handle=6, GUID = deriveBuiltin('HANDLE_CYLINDER') UUIDv5\n// (plan-strategy §2 D-6 + §5.6 builtin-guid-ssot gate)\nconst builtinCylinderRes = createCylinderGeometry(0.5, 0.5, 1, 16, 1);\nif (!builtinCylinderRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createCylinderGeometry(0.5,0.5,1,16,1) failed: ${builtinCylinderRes.error.code}`,\n );\n}\nexport const BUILTIN_CYLINDER: TypesMeshAsset = Object.freeze(builtinCylinderRes.value);\n\n// BUILTIN_NINESLICE_QUAD: 4×4 grid plane synthesised from\n// createPlaneGeometry(1, 1, 3, 3) — 16 vertices, 9 sub-quads × 6 indices = 54.\n// Reuses the unit-quad vertex layout (12F: pos + normal + uv + tangent) so\n// HANDLE_NINESLICE_QUAD funnels through the same sprite-pipeline binding\n// table as HANDLE_QUAD; only the vertex_index → (i, j) decomposition in\n// sprite.wgsl branches on slices presence (feat-20260527-sprite-nineslice\n// M3, plan-strategy §D-2 + §D-4).\nconst builtinNineSliceQuadRes = createPlaneGeometry(1, 1, 3, 3);\nif (!builtinNineSliceQuadRes.ok) {\n throw new Error(\n `[builtin-asset-registry] createPlaneGeometry(1,1,3,3) failed: ${builtinNineSliceQuadRes.error.code}`,\n );\n}\nexport const BUILTIN_NINESLICE_QUAD: TypesMeshAsset = Object.freeze(builtinNineSliceQuadRes.value);\n\n// Slot u32 -> frozen payload. Slot ids 1..5 are the fixed builtin handle\n// values (HANDLE_CUBE=1 .. HANDLE_NINESLICE_QUAD=5) defined in asset-registry.\nconst BUILTIN_BY_SLOT: ReadonlyMap<number, TypesMeshAsset> = new Map([\n [1, BUILTIN_CUBE],\n [2, BUILTIN_TRIANGLE],\n [3, BUILTIN_QUAD],\n [4, BUILTIN_SPHERE],\n [5, BUILTIN_NINESLICE_QUAD],\n [6, BUILTIN_CYLINDER],\n]);\n\n/**\n * Process-static builtin asset resolver (D-15). `resolve(handle)` returns the\n * frozen builtin payload when `slot < BUILTIN_BASE`, else `null` (the slot\n * belongs to the user tier — resolve it through `world.sharedRefs.resolve`).\n *\n * Read-only: there is no register / mint surface. The five builtin payloads\n * are fixed at module load. AI users `import { BuiltinAssetRegistry } from\n * '@forgeax/engine-runtime'` and resolve a builtin handle without a World.\n */\nexport const BuiltinAssetRegistry = Object.freeze({\n resolve<T extends TypesMeshAsset>(handle: Handle<string, 'shared'>): T | null {\n const slot = handleSlot(handle);\n if (slot >= BUILTIN_BASE) return null;\n const payload = BUILTIN_BY_SLOT.get(slot);\n return payload === undefined ? null : (payload as T);\n },\n});\n","// @forgeax/engine-assets-runtime - LoaderRegistry (feat-20260603-asset-import-loader-injection M1 / w2).\n//\n// The runtime half of the engine's third DIP instance (after RHI + Console):\n// an injectable table that maps `asset.kind` -> a `Loader` (the contract SSOT\n// lives in `@forgeax/engine-types`, plan-strategy D-2). `AssetRegistry` holds\n// one of these (constructor-injected, D-7) and dispatches `loadByGuid` through\n// `get(kind)` instead of a hardcoded `if (kind === ...)` chain (D-1).\n//\n// Shape mirrors the Console `Registry` (packages/console/src/registry.ts)\n// register/lookup pattern (research Finding 8), with one deliberate\n// difference: the injected unit here is an **object** `{ kind, load }`, not a\n// bare function, because a \"one kind -> one loader\" dispatch table is the\n// natural shape (plan-strategy D-1 alt-B rejection).\n//\n// Fail-fast semantics (charter P3): `register` throws on a malformed loader\n// or duplicate kind at wire time, so one canonical owner cannot be silently\n// replaced by a later seed table.\n\nimport type { ArtifactDescriptor, LoadContext, Loader } from '@forgeax/engine-types';\n\nexport interface PackArtifactInput {\n readonly descriptor: ArtifactDescriptor;\n readonly bytes: Uint8Array;\n}\n\nexport interface PackLoaderInput {\n readonly guid: string;\n readonly kind: string;\n readonly payload: Record<string, unknown>;\n readonly refs: readonly string[];\n readonly artifacts: Readonly<Record<string, PackArtifactInput>>;\n}\n\nexport interface PackLoader {\n readonly kind: string;\n load(input: PackLoaderInput, ctx: LoadContext): unknown;\n}\n\nexport type PackLoadResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: unknown };\n\n/**\n * Injectable `asset.kind` -> {@link Loader} table held by `AssetRegistry`.\n *\n * @example Wire + dispatch (host side)\n * ```ts\n * import { LoaderRegistry, wireDefaultLoaders } from '@forgeax/engine-assets-runtime';\n * const loaders = new LoaderRegistry();\n * wireDefaultLoaders(loaders);\n * const meshLoader = loaders.get('mesh'); // Loader | undefined\n * ```\n */\nexport class LoaderRegistry {\n // feat-20260623 M4 / w13: the Map stores Loader<unknown> so host custom kinds\n // (Loader<MyPayload>) are accepted. The P in Loader<P> is covariant (output\n // only: load() returns P), so Loader<Asset> is assignable to Loader<unknown>.\n private readonly loaders = new Map<string, Loader<unknown>>();\n private readonly packLoaders = new Map<string, PackLoader>();\n\n /**\n * Register a loader for its `loader.kind`. Fail-fast on a malformed loader\n * (charter P3); rejects a repeated kind so the canonical owner cannot be replaced.\n *\n * @param loader the `{ kind, load }` object to register.\n * @throws TypeError when `loader.kind` is empty or `loader.load` is not a\n * function — a wire-time misconfiguration the host must fix.\n */\n register(loader: Loader<unknown>): () => void {\n if (typeof loader.kind !== 'string' || loader.kind.length === 0) {\n throw new TypeError(\n `LoaderRegistry.register: loader.kind must be a non-empty string (got ${JSON.stringify(loader.kind)})`,\n );\n }\n if (typeof loader.load !== 'function') {\n throw new TypeError(\n `LoaderRegistry.register: loader.load must be a function for kind \"${loader.kind}\"`,\n );\n }\n if (this.loaders.has(loader.kind)) {\n throw new TypeError(`LoaderRegistry.register: duplicate loader kind \"${loader.kind}\"`);\n }\n this.loaders.set(loader.kind, loader);\n return () => {\n if (this.loaders.get(loader.kind) === loader) this.loaders.delete(loader.kind);\n };\n }\n\n registerPackLoader(loader: PackLoader): () => void {\n if (typeof loader.kind !== 'string' || loader.kind.length === 0) {\n throw new TypeError('LoaderRegistry.registerPackLoader: kind must be non-empty');\n }\n if (typeof loader.load !== 'function') {\n throw new TypeError(\n `LoaderRegistry.registerPackLoader: load must be a function for ${loader.kind}`,\n );\n }\n if (this.packLoaders.has(loader.kind)) {\n throw new TypeError(\n `LoaderRegistry.registerPackLoader: duplicate loader kind \"${loader.kind}\"`,\n );\n }\n this.packLoaders.set(loader.kind, loader);\n return () => {\n if (this.packLoaders.get(loader.kind) === loader) this.packLoaders.delete(loader.kind);\n };\n }\n\n async loadPack(input: PackLoaderInput, ctx: LoadContext): Promise<PackLoadResult> {\n const packLoader = this.packLoaders.get(input.kind);\n if (packLoader !== undefined) {\n const output = await packLoader.load(input, ctx);\n if (isPackLoadResult(output)) return output;\n return { ok: true, value: output };\n }\n const loader = this.loaders.get(input.kind);\n if (loader === undefined) {\n return { ok: false, error: new Error(`no loader registered for ${input.kind}`) };\n }\n if (loader.loadPack !== undefined) {\n const output = await loader.loadPack(input, ctx);\n if (isPackLoadResult(output)) return output;\n return { ok: true, value: output };\n }\n const output = await loader.load(input.payload, input.refs, ctx);\n if (isPackLoadResult(output)) return output;\n return { ok: true, value: output };\n }\n\n /**\n * Look up the loader registered for `kind`. Returns `undefined` when no\n * loader is wired — the `AssetRegistry` consumer maps that to a structured\n * `AssetError(code='loader-not-registered')` with the registered kinds in\n * `.detail` (charter P3).\n */\n get(kind: string): Loader<unknown> | undefined {\n return this.loaders.get(kind);\n }\n\n /**\n * The kinds currently wired, in insertion order. Fed into the\n * `loader-not-registered` error `.detail.registeredKinds` so AI users see\n * exactly what is injectable.\n */\n registeredKinds(): readonly string[] {\n return [...this.loaders.keys()];\n }\n}\n\nfunction isPackLoadResult(value: unknown): value is PackLoadResult {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'ok' in value &&\n typeof (value as { ok?: unknown }).ok === 'boolean'\n );\n}\n","// @forgeax/engine-assets-runtime -- asset cluster error classes.\n//\n// feat-20260704-runtime-tier1-decomposition M2 / w8 (D-3): asset-resolution\n// cluster -- material parent-chain resolve, mesh-SSBO grow ceiling, and\n// scene-collect GUID / forest-closure fail-fast errors. Class names, .code\n// literals, and .detail shapes preserved byte-for-byte (OOS-4).\n//\n// The cluster union type is named AssetRuntimeError / AssetRuntimeErrorCode\n// (not AssetError / AssetErrorCode) because @forgeax/engine-types already owns\n// the AssetError class + AssetErrorCode union (asset-system-v1); D-8 grep\n// uniqueness forbids the collision.\n\nimport type { MeshBinHeaderV4 } from '@forgeax/engine-pack';\nimport {\n AssetError,\n type AssetErrorDetail,\n type AssetMeshBinContractFacts,\n type AssetMeshBinContractViolationReason,\n} from '@forgeax/engine-types';\n\nexport class MeshBinAssetError extends AssetError {\n readonly subject = 'mesh-bin' as const;\n readonly sourceKey: string;\n readonly actual: string;\n readonly recovery = 're-cook the source with its Meta sidecar through the build-time importer';\n\n constructor(args: {\n readonly sourceKey: string;\n readonly expected: string;\n readonly actual: string;\n readonly header?: Partial<MeshBinHeaderV4> & { readonly byteLength?: number };\n readonly reason?: AssetMeshBinContractViolationReason;\n readonly expectedFacts?: AssetMeshBinContractFacts;\n readonly actualFacts?: AssetMeshBinContractFacts;\n }) {\n const expectedFacts: AssetMeshBinContractFacts = args.expectedFacts ?? {\n version: 4,\n projectionVersion: 1,\n };\n const actualFacts: AssetMeshBinContractFacts = {\n ...(args.header ?? {}),\n ...(args.actualFacts ?? {}),\n };\n const detail: AssetErrorDetail = {\n code: 'mesh-bin-contract-violation',\n sourceKey: args.sourceKey,\n reason: args.reason ?? 'header-invalid',\n expected: expectedFacts,\n actual: actualFacts,\n };\n super({\n code: 'mesh-bin-contract-violation',\n expected: args.expected,\n hint: 're-cook the source with its Meta sidecar through the build-time importer',\n detail,\n });\n this.sourceKey = args.sourceKey;\n this.actual = args.actual;\n }\n}\n\n// ── MaterialResolvedEmptyPassesError ──────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'material-resolved-empty-passes'`.\n *\n * Emitted at material parent chain walk time when the resolved passes list\n * is empty. Two reasons: `'missing-parent'` (a parent handle is not\n * registered) and `'no-pass-in-chain'` (the entire parent chain has no\n * pass declarations). AI users switch on `.detail.reason` to surface the\n * right recovery guidance.\n *\n * plan-strategy D-2/D-3: empty-passes is a runtime-layer error\n * (RuntimeErrorCode, not AssetErrorCode).\n */\nexport interface MaterialResolvedEmptyPassesDetail {\n /** GUID of the material whose resolve produced empty passes. */\n readonly materialGuid: string;\n /** Root cause of the empty passes: missing parent vs entire chain has no passes. */\n readonly reason: 'missing-parent' | 'no-pass-in-chain';\n /** The raw numeric handle id of the unregistered parent. Only populated when reason='missing-parent'. */\n readonly missingParentHandle?: number;\n}\n\n/**\n * Structured error for material parent chain resolve yielding zero passes.\n *\n * Emitted by `AssetRegistry.passesOf` when the parent chain walk produces\n * an empty passes list (AC-09, D-3 two-reason). Four-field surface:\n * - `.code = 'material-resolved-empty-passes'` (closed RuntimeErrorCode)\n * - `.expected` — expected-state description\n * - `.hint` — actionable recovery guidance (differs per reason)\n * - `.detail = { materialGuid, reason, missingParentHandle? }`\n */\nexport class MaterialResolvedEmptyPassesError extends Error {\n readonly code = 'material-resolved-empty-passes' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MaterialResolvedEmptyPassesDetail;\n\n constructor(\n materialGuid: string,\n reason: 'missing-parent' | 'no-pass-in-chain',\n missingParentHandle?: number,\n ) {\n const expected =\n reason === 'missing-parent'\n ? `parent handle ${missingParentHandle} present in AssetRegistry`\n : 'at least one material in the parent chain declares passes';\n const hint =\n reason === 'missing-parent'\n ? `material ${materialGuid} references parent handle ${missingParentHandle} which is not registered; inspect AssetRegistry, register the parent first, or rebuild the material chain`\n : `material ${materialGuid} has no passes and its entire parent chain also has no pass declarations; inspect the chain, add pass declarations to one member, then rebuild`;\n const message =\n reason === 'missing-parent'\n ? `material ${materialGuid} parent handle ${missingParentHandle} not registered`\n : `material ${materialGuid} parent chain resolves to zero passes`;\n\n super(message);\n this.name = 'MaterialResolvedEmptyPassesError';\n this.expected = expected;\n this.hint = hint;\n this.detail = {\n materialGuid,\n reason,\n ...(reason === 'missing-parent' && missingParentHandle !== undefined\n ? { missingParentHandle }\n : {}),\n };\n }\n}\n\n// ── MeshSsboCapacityExceededError ────────────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'mesh-ssbo-capacity-exceeded'`.\n *\n * Fired by `growMeshSsbo` (createRenderer.ts grow factory) when, after\n * attempting pow2 doubling, the resulting `slotCount` still cannot\n * accommodate the requested `requested` slot count under the device's\n * `maxStorageBufferBindingSize` ceiling. This is a defensive fallback —\n * the primary path for \"request past device limit\" is\n * `mesh-ssbo-ceiling-reached`. The two codes share the same detail shape so\n * AI users handle both arms identically; the discriminant identifies which\n * branch fired so diagnostics can distinguish the primary vs defensive\n * surface (research §F6.c).\n *\n * - `requested` — slot count requested by the caller (entity count for the frame)\n * - `capacity` — current `slotCount` in the grow controller's state\n * - `ceiling` — `device.limits.maxStorageBufferBindingSize` in BYTES (not slots)\n */\nexport interface MeshSsboCapacityExceededDetail {\n readonly requested: number;\n readonly capacity: number;\n readonly ceiling: number;\n}\n\n/**\n * Structured error for the post-grow defensive fallback when mesh-SSBO\n * capacity cannot accommodate the requested slot count.\n *\n * Emitted by `growMeshSsbo` in `createRenderer.ts` (D-5: fire, never\n * throw). Four-field surface aligned with `SkinPaletteOverflowError`:\n * - `.code = 'mesh-ssbo-capacity-exceeded'`\n * - `.expected` — capacity >= requested\n * - `.hint` — reduce per-frame entity count or split work across frames\n * - `.detail = { requested, capacity, ceiling }`\n */\nexport class MeshSsboCapacityExceededError extends Error {\n readonly code = 'mesh-ssbo-capacity-exceeded' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MeshSsboCapacityExceededDetail;\n\n constructor(requested: number, capacity: number, ceiling: number) {\n const expected = `mesh SSBO slotCount >= ${requested} (currently ${capacity}; device ceiling ${ceiling} B)`;\n const hint =\n `mesh SSBO grow could not satisfy needed=${requested} slots (capacity=${capacity}, ceiling=${ceiling} B); ` +\n 'reduce per-frame entity count or split work across frames (defensive fallback path)';\n super(\n `mesh SSBO capacity exceeded: needed ${requested} slots, capacity ${capacity}, ceiling ${ceiling} B`,\n );\n this.name = 'MeshSsboCapacityExceededError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { requested, capacity, ceiling };\n }\n}\n\n// ── MeshSsboCeilingReachedError ──────────────────────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'mesh-ssbo-ceiling-reached'`.\n *\n * Fired by `growMeshSsbo` when the requested slot count would exceed the\n * device's `maxStorageBufferBindingSize` (the only ceiling per D-1; engine\n * carries no private capacity constant). Same detail shape as\n * `MeshSsboCapacityExceededDetail`.\n *\n * - `requested` — slot count requested by the caller\n * - `capacity` — current `slotCount` in the grow controller's state\n * - `ceiling` — `device.limits.maxStorageBufferBindingSize` in BYTES\n */\nexport interface MeshSsboCeilingReachedDetail {\n readonly requested: number;\n readonly capacity: number;\n readonly ceiling: number;\n}\n\n/**\n * Structured error for mesh-SSBO grow refused because the request exceeds\n * `device.limits.maxStorageBufferBindingSize`.\n *\n * Emitted by `growMeshSsbo` (D-5: fire, never throw). The frame renders a\n * degraded subset (truncated to pre-grow capacity) per plan-strategy D-2 —\n * no black frame. Four-field surface aligned with `SkinPaletteOverflowError`:\n * - `.code = 'mesh-ssbo-ceiling-reached'`\n * - `.expected` — requested * stride <= device.limits.maxStorageBufferBindingSize\n * - `.hint` — reduce per-frame entity count or pick a higher-tier adapter\n * - `.detail = { requested, capacity, ceiling }`\n */\nexport class MeshSsboCeilingReachedError extends Error {\n readonly code = 'mesh-ssbo-ceiling-reached' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: MeshSsboCeilingReachedDetail;\n\n constructor(requested: number, capacity: number, ceiling: number) {\n const expected = `mesh SSBO slot byte size <= device.limits.maxStorageBufferBindingSize (${ceiling} B)`;\n const hint =\n `requested ${requested} mesh SSBO slots would exceed device.limits.maxStorageBufferBindingSize (${ceiling} B); ` +\n 'reduce per-frame entity count or run on an adapter with a larger storage buffer binding size';\n super(\n `mesh SSBO ceiling reached: needed ${requested} slots; capacity ${capacity}; ceiling ${ceiling} B`,\n );\n this.name = 'MeshSsboCeilingReachedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { requested, capacity, ceiling };\n }\n}\n\n// ── SceneCollectEntityRefOutOfClosureError ──────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'scene-collect-entity-ref-out-of-closure'`.\n *\n * Emitted during rootsToSceneAsset when an entity field references a target\n * outside the collected forest closure.\n */\nexport interface SceneCollectEntityRefOutOfClosureDetail {\n readonly entity: number;\n readonly field: string;\n readonly target: number;\n}\n\n/**\n * Structured error for entity ref pointing outside the forest closure.\n *\n * Emitted during rootsToSceneAsset collect; fail-fast per charter P3.\n * - `.code = 'scene-collect-entity-ref-out-of-closure'`\n * - `.expected` — all entity refs resolve within the closure\n * - `.hint` — Expand roots to include the target entity, or remove the reference.\n * - `.detail = { entity, field, target }`\n */\nexport class SceneCollectEntityRefOutOfClosureError extends Error {\n readonly code = 'scene-collect-entity-ref-out-of-closure' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneCollectEntityRefOutOfClosureDetail;\n\n constructor(entity: number, field: string, target: number) {\n const expected = `entity ${entity}.${field} references entity ${target} which is inside the forest closure`;\n const hint = 'Expand roots to include the target entity, or remove the reference.';\n super(`${expected} — ${hint}`);\n this.name = 'SceneCollectEntityRefOutOfClosureError';\n this.expected = expected;\n this.hint = hint;\n this.detail = { entity, field, target };\n }\n}\n\n// ── SceneCollectAssetGuidUnresolvedError ────────────────────────────\n\n/**\n * Detail for `RuntimeErrorCode 'scene-collect-asset-guid-unresolved'`.\n *\n * Emitted at two points with different context on hand:\n * - collect (handle→GUID): the shared handle is known → `.handle` is set.\n * - serialize (GUID→refs): the GUID string is known but absent from the\n * refs index → `.guid` is set. (`.handle` is meaningless there.)\n * Exactly one of `handle` / `guid` is present per instance.\n */\nexport interface SceneCollectAssetGuidUnresolvedDetail {\n readonly field: string;\n readonly handle?: number;\n readonly guid?: string;\n}\n\n/**\n * Structured error for a shared asset reference whose GUID cannot be resolved.\n *\n * Emitted during rootsToSceneAsset collect (handle) or\n * serializeSceneAssetToPack (guid); fail-fast per charter P3.\n * - `.code = 'scene-collect-asset-guid-unresolved'`\n * - `.expected` — every shared asset reference has a catalogued GUID\n * - `.hint` — Register the asset in AssetRegistry before collecting.\n * - `.detail = { field, handle }` (collect) or `{ field, guid }` (serialize)\n */\nexport class SceneCollectAssetGuidUnresolvedError extends Error {\n readonly code = 'scene-collect-asset-guid-unresolved' as const;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneCollectAssetGuidUnresolvedDetail;\n\n constructor(field: string, ref: number | string) {\n const where = typeof ref === 'number' ? `handle ${ref}` : `guid '${ref}'`;\n const expected = `shared field '${field}' (${where}) resolves to an asset whose GUID is catalogued`;\n const hint =\n 'source SceneAsset is not catalogued: call registry.catalog(guid, payload) first, ' +\n 'or load through loadByGuid() which auto-catalogs GUID-scoped assets';\n super(`${expected} — ${hint}`);\n this.name = 'SceneCollectAssetGuidUnresolvedError';\n this.expected = expected;\n this.hint = hint;\n this.detail = typeof ref === 'number' ? { field, handle: ref } : { field, guid: ref };\n }\n}\n\n// -- AssetRuntimeErrorCode / AssetRuntimeError closed unions --------------------\n\n/**\n * Closed union of asset-cluster error codes. AI users perform exhaustive\n * `switch (err.code)` without default; TS guards completeness.\n */\nexport type AssetRuntimeErrorCode = AssetRuntimeError['code'];\n\n/**\n * Closed union of the asset-cluster structured error classes, each carrying\n * an `AssetRuntimeErrorCode` discriminant on `.code`.\n */\nexport type AssetRuntimeError =\n | MaterialResolvedEmptyPassesError\n | MeshSsboCapacityExceededError\n | MeshSsboCeilingReachedError\n | SceneCollectEntityRefOutOfClosureError\n | SceneCollectAssetGuidUnresolvedError;\n","// @forgeax/engine-assets-runtime -- builtin mesh handles + scene-parse handle field\n// name sets (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1\n// straight-cut). Pure move from asset-registry.ts; zero identifier changes.\n\nimport type { Handle } from '@forgeax/engine-types';\nimport { handleSlot, toShared } from '@forgeax/engine-types';\n\n// ─── Builtin handles (D-S9 / backward compat with hello-triangle + hello-cube) ─\n\n/**\n * Builtin unit-cube mesh handle (8 vertices + 36 indices, pos+normal\n * interleaved). Pair with `MeshFilter` to spawn a cube entity.\n *\n * @remarks Typed as `Handle<'MeshAsset', 'shared'>` — feat-20260517\n * unifies the engine-types and engine-ecs Handle brand SSOT into a single\n * `Handle<T extends string, M extends 'unique'|'shared'>` declaration\n * (research Finding 4 import-path-decoupled identity), and constructs the\n * value via the brand-creation factory `toShared<'MeshAsset'>(N)` so\n * the caller-side `as unknown as` cast is eliminated (AC-05). The\n * `'shared'` mode signals the AssetRegistry owns the lifecycle — the\n * ECS does not release the slot on despawn / removeComponent / set.\n * Runtime value is a small u32 (1).\n */\nexport const HANDLE_CUBE: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(1);\n\n/**\n * Builtin triangle mesh handle (3 vertices). Pair with `MeshFilter`.\n *\n * @remarks Typed as `Handle<'MeshAsset', 'shared'>` (same narrow brand\n * as HANDLE_CUBE; constructed via the `toShared<'MeshAsset'>(N)`\n * factory per AC-05).\n */\nexport const HANDLE_TRIANGLE: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(2);\n\n/**\n * Builtin unit-quad mesh handle — 4 vertices, 6 indices, 2 triangles on\n * the XY plane facing +Z. Pair with `MeshFilter` to spawn a sprite quad\n * (feat-20260520-2d-sprite-layer-mvp / M-1 / w06).\n *\n * @derives Same-shape sibling of {@link HANDLE_CUBE} / {@link HANDLE_TRIANGLE}\n * per requirements §2.1.C: built via the `toShared<'MeshAsset'>(N)`\n * brand-creation factory; reserved-id 3 fills the namespace hole between\n * HANDLE_TRIANGLE=2 and FIRST_USER_HANDLE=1024 (no `BUILTIN_HANDLE_`\n * prefix per Q2 naming decision — discoverable next to existing\n * builtins in IDE autocomplete; charter F1 single-entry indexability).\n *\n * @reuses {@link createPlaneGeometry}(1, 1) — the procedural plane factory\n * already produces 8-floats-per-vertex interleaved (position + normal +\n * uv) and is then expanded to the runtime 12-floats layout (adds\n * tangent vec4) by {@link meshFromInterleaved}. This funnels HANDLE_QUAD\n * onto the exact same vertex pipeline branch as BUILTIN_CUBE /\n * BUILTIN_TRIANGLE and the procedural geometry factories — zero new\n * layout discriminator (plan-strategy §3 RT4 + D-9 + charter P4\n * consistent abstraction).\n *\n * @reuses `PROCEDURAL_FLOATS_PER_VERTEX` = 12 from\n * `@forgeax/engine-geometry` (the single layout SSOT; the procedural\n * `createPlaneGeometry` factory already returns 12F via\n * `meshFromInterleaved`).\n */\nexport const HANDLE_QUAD: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(3);\n\n/**\n * Id=4 reserved builtin; occupies the next available slot under\n * FIRST_USER_HANDLE=1024. BUILTIN_SPHERE is synthesised from\n * `createSphereGeometry(1, 16, 12)` through the same\n * `meshFromInterleaved` path as BUILTIN_QUAD, so the runtime\n * 12-float stride is byte-identical to procedural output — zero\n * new layout discriminator (charter P4 consistent abstraction).\n */\nexport const HANDLE_SPHERE: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(4);\n\n/**\n * Builtin cylinder mesh handle — procedural open cylinder (unit-height,\n * radius=0.5, 16 radial segments, no caps). Pair with `MeshFilter`.\n *\n * @derives Same-shape sibling of {@link HANDLE_SPHERE}: synthesised from\n * `createCylinderGeometry(0.5, 0.5, 1, 16, 1)` through the same\n * `meshFromInterleaved` path as BUILTIN_SPHERE, so the runtime\n * 12-float stride is byte-identical to all other built-in meshes —\n * zero new layout discriminator (charter P4 consistent abstraction).\n *\n * @remarks Id=6 follows {@link HANDLE_NINESLICE_QUAD}=5 in the builtin slot\n * sequence (FIRST_USER_HANDLE=1024 untouched).\n * feat-20260701-editor-world-container-doc-ecs-collapse M0 / AC-16:\n * GUID = deriveBuiltin('HANDLE_CYLINDER') UUIDv5\n * (plan-strategy §2 D-6 + §5.6 builtin-guid-ssot gate)\n */\nexport const HANDLE_CYLINDER: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(6);\n\n/**\n * Builtin 9-slice quad mesh handle — 4×4 grid (16 vertices, 9 sub-quads,\n * 54 indices) on the XY plane facing +Z. Pair with `MeshFilter` and a\n * `MaterialAsset` whose first pass shader is `'forgeax::sprite'` and whose\n * `values.slices` is non-zero to render a 9-sliced UI panel\n * (feat-20260527-sprite-nineslice / M2 / w9).\n *\n * @derives Same-shape sibling of {@link HANDLE_QUAD}: synthesised from\n * `createPlaneGeometry(1, 1, 3, 3)` which subdivides the unit quad into\n * 3×3 sub-quads (9 cells). The 16 grid points and 54 indices feed\n * {@link meshFromInterleaved} so the runtime 12-float vertex stride is\n * byte-identical to all other built-in / procedural meshes — zero new\n * layout discriminator (charter P4 consistent abstraction).\n *\n * @remarks Id=5 follows {@link HANDLE_SPHERE}=4 in the builtin slot\n * sequence (FIRST_USER_HANDLE=1024 untouched). The vertex shader uses\n * `vertex_index % 4` / `vertex_index / 4` to recover (i, j) grid\n * coordinates and four anchor vec4s to map each grid cell to the right\n * region of the source texture; only required when the sprite material\n * declares non-zero `slices`. For the legacy zero-slice sprite path use\n * {@link HANDLE_QUAD}.\n *\n * @reuses `PROCEDURAL_FLOATS_PER_VERTEX` = 12 from\n * `@forgeax/engine-geometry` (sprite-pipeline binding table / vertex layout\n * untouched). plan-strategy §D-2 NOTE clarifies\n * the id=5 vs original-plan id=4 drift: HANDLE_SPHERE took id=4 in\n * feat-20260529-fxaa-sphere-builtin before this feat landed.\n */\nexport const HANDLE_NINESLICE_QUAD: Handle<'MeshAsset', 'shared'> = toShared<'MeshAsset'>(5);\n\n/**\n * Stable GUIDs for the builtin meshes — the dash-form of\n * `deriveBuiltin('HANDLE_<NAME>')` (UUIDv5, ForgeaX namespace) in\n * `@forgeax/engine-pack`. They are inlined here (not imported) because the\n * pack derivation runs under top-level `await` (async SubtleCrypto) and\n * dragging that into the AssetRegistry constructor — a synchronous hot path\n * consumed engine-wide — would make the whole runtime module graph async.\n *\n * The single source of truth remains `deriveBuiltin`: a cross-package\n * guard test (`builtin-guid-ssot.test.ts`) asserts each literal equals the\n * derived value, so any drift in the derivation reds the suite. This pairs\n * the previously-disconnected dual truths (the u32 `HANDLE_*` constants and\n * the pack GUID strings) into one bidirectionally-resolvable table, so\n * `guidOf(HANDLE_CUBE)` no longer returns `undefined`\n * (docs/feedbacks/2026-06-03 §6.2 Tier 0).\n */\nexport const BUILTIN_MESH_GUIDS: ReadonlyArray<readonly [Handle<'MeshAsset', 'shared'>, string]> = [\n [HANDLE_CUBE, 'cbe42beb-8975-5096-b3a1-3dda4cb4c077'],\n [HANDLE_TRIANGLE, '22592f07-d967-5116-b29c-fa9781929ba8'],\n [HANDLE_QUAD, '339338aa-a338-581c-9fc5-744267ef8a51'],\n [HANDLE_SPHERE, '95730fd2-9846-5f84-8658-0b3c971eb263'],\n [HANDLE_NINESLICE_QUAD, '692d38b4-8cac-5fb2-9dcf-f389e076d6bf'],\n // feat-20260701-editor-world-container-doc-ecs-collapse M0 / AC-16:\n // cylinder builtin handle=6, GUID = deriveBuiltin('HANDLE_CYLINDER') UUIDv5\n // (plan-strategy §5.6 builtin-guid-ssot gate)\n [HANDLE_CYLINDER, 'ab20af21-0764-55be-a7f2-b80ab3d46a0a'],\n];\n\n/** Resolve the stable producer GUID for one process-static builtin mesh handle. */\nexport function builtinMeshGuid(handle: Handle<string, 'shared'>): string | undefined {\n const slot = handleSlot(handle);\n return BUILTIN_MESH_GUIDS.find(([candidate]) => handleSlot(candidate) === slot)?.[1];\n}\n\n/**\n * Field names known to carry handle<> schema-vocab references (plan-strategy\n * D-4). parseScenePayload uses this allowlist to replace integer values\n * with GUID strings from refs[] only for handle fields — a Transform.pos lane of 0,\n * ChildOf.parent=0 and similar non-handle integers are left untouched.\n *\n * When a new handle<> field is added to a runtime component, its field name\n * MUST be added here so parseScenePayload correctly resolves it.\n */\nexport const HANDLE_FIELD_NAMES: ReadonlySet<string> = new Set([\n 'assetHandle',\n 'material',\n 'skeleton',\n 'clip',\n // ParticleEffectPlayer.effect (shared<ParticleEffectAsset>) uses the same\n // scene-pack refs[] index contract as every other scalar shared field.\n 'effect',\n // feat-20260630-equirect-kind-internalized-ibl-declarative-skyligh M3 / w27:\n // Skylight.equirect + SkyboxBackground.equirect (shared<EquirectAsset>). The\n // generic extractSceneEntityHandleGuids path already covers shared< fields by\n // schema; this allowlist is the second scene-parse path (parseScenePayload),\n // so the new handle field name is registered here too (R-1).\n 'equirect',\n]);\n\n/**\n * Field names known to carry `array<handle<X>>` schema-vocab references\n * (feat-20260608 M2 / w7: MeshRenderer.materials). Each element is a refs\n * index that resolves to a GUID string. Coexists with HANDLE_FIELD_NAMES;\n * a field name lives in exactly one set.\n */\nexport const HANDLE_ARRAY_FIELD_NAMES: ReadonlySet<string> = new Set(['materials']);\n","// @forgeax/engine-assets-runtime -- scene payload parse + ref resolution\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport type {\n LocalEntityId,\n SceneAsset,\n SceneEntity,\n SceneInstanceMount,\n} from '@forgeax/engine-types';\nimport { HANDLE_ARRAY_FIELD_NAMES, HANDLE_FIELD_NAMES } from './handles';\n\n/**\n * Structured error returned by parseScenePayload when a refs index is\n * out of bounds (F-2 / AC-02).\n */\ninterface ParseSceneError {\n readonly localId: number;\n readonly component: string;\n readonly field: string;\n readonly index: number;\n readonly refsLength: number;\n}\n\n// Reconstruct a SceneAsset POD from a serialised pack payload (feat-20260514\n// w3 / parseAssetPayload 'scene' dispatch). The payload arrives as the\n// outer pack file's `assets[i].payload` object after ajv structural\n// validation; this helper re-stamps the LocalEntityId brand on each\n// SceneEntity.localId field and freezes the resulting POD shape so consumer\n// code sees the same readonly surface as a hand-authored SceneAsset (AC-01\n// + plan-strategy §3.1 rt_pkg sub-graph).\n//\n// feat-20260528-scene-asset-guid-refs-and-post-instantiate M1-fixup F-1:\n// refs parameter — when provided, integer values in handle-type component\n// fields (identified via HANDLE_FIELD_NAMES allowlist, plan-strategy D-4)\n// are replaced with refs[N] (GUID string). Non-handle integer fields\n// (Transform pos/quat/scale lanes, ChildOf.parent Entity, etc.)\n// are kept as-is.\n//\n// feat-20260528-scene-asset-guid-refs-and-post-instantiate M1-fixup F-2:\n// out-of-bounds (N < 0 or N >= refs.length) returns a structured\n// ParseSceneError with localId + component + field + index + refs.length\n// so the caller can construct a precise AssetError (AC-02).\n// The M1 stop-on-first-error (AC-08) behaviour is preserved.\nexport function parseScenePayload(\n payload: Record<string, unknown>,\n refs?: string[],\n): SceneAsset | ParseSceneError | undefined {\n const rawEntities = payload.entities;\n if (!Array.isArray(rawEntities)) return undefined;\n const nodes: SceneEntity[] = [];\n for (const rn of rawEntities as Array<{ localId?: unknown; components?: unknown }>) {\n if (typeof rn.localId !== 'number') return undefined;\n const rawComponents = (rn.components ?? {}) as Record<string, Record<string, unknown>>;\n\n // Resolve refs indices to GUID strings only for handle-type fields\n // (plan-strategy D-4 / F-1 fix: non-handle integers preserved as-is).\n if (refs) {\n const resolvedComponents: Record<string, Record<string, unknown>> = {};\n for (const compName of Object.keys(rawComponents)) {\n const rawFields = rawComponents[compName];\n if (!rawFields) continue;\n const resolvedFields: Record<string, unknown> = {};\n for (const fieldName of Object.keys(rawFields)) {\n const value = rawFields[fieldName];\n if (\n HANDLE_FIELD_NAMES.has(fieldName) &&\n typeof value === 'number' &&\n Number.isInteger(value)\n ) {\n const idx = value;\n if (idx < 0 || idx >= refs.length) {\n return {\n localId: rn.localId as number,\n component: compName,\n field: fieldName,\n index: idx,\n refsLength: refs.length,\n };\n }\n resolvedFields[fieldName] = refs[idx];\n } else if (HANDLE_ARRAY_FIELD_NAMES.has(fieldName) && Array.isArray(value)) {\n // feat-20260608 M2 / w7: array<handle<X>> field — each element is a\n // refs index resolved to a GUID string. Out-of-bounds in any element\n // surfaces the same ParseSceneError as the scalar handle path.\n const resolvedArr: string[] = [];\n for (let elemIdx = 0; elemIdx < value.length; elemIdx++) {\n const elem = value[elemIdx];\n if (typeof elem !== 'number' || !Number.isInteger(elem)) {\n resolvedFields[fieldName] = value;\n resolvedArr.length = 0;\n break;\n }\n if (elem < 0 || elem >= refs.length) {\n return {\n localId: rn.localId as number,\n component: compName,\n field: `${fieldName}[${elemIdx}]`,\n index: elem,\n refsLength: refs.length,\n };\n }\n const ref = refs[elem];\n if (ref !== undefined) resolvedArr.push(ref);\n }\n if (resolvedArr.length === value.length) {\n resolvedFields[fieldName] = resolvedArr;\n } else if (resolvedFields[fieldName] === undefined) {\n resolvedFields[fieldName] = value;\n }\n } else {\n resolvedFields[fieldName] = value;\n }\n }\n resolvedComponents[compName] = resolvedFields as Record<string, unknown>;\n }\n nodes.push({\n localId: rn.localId as LocalEntityId,\n components: resolvedComponents,\n });\n } else {\n nodes.push({\n localId: rn.localId as LocalEntityId,\n components: rawComponents,\n });\n }\n }\n const resolvedMounts = resolveMounts(payload, refs);\n if (resolvedMounts === undefined && Array.isArray(payload.mounts)) {\n // mounts resolution failed (e.g. out-of-bounds source index)\n return undefined;\n }\n // feat-20260612 M2 fixup: resolve `skinGuids` field (refs[] indices on disk\n // -> GUID strings post-parse). The SkinAsset chain has no entity-component\n // hook so the scene must carry an explicit cross-edge list; without it,\n // browser-async-pack-fetch never loads SkinAssets and postSpawnResolveJoints\n // silently skips, leaving Skin.joints.length=0 for every frame.\n const resolvedSkinGuids = resolveSkinGuids(payload, refs);\n if (resolvedSkinGuids === undefined && Array.isArray(payload.skinGuids)) {\n return undefined;\n }\n return {\n kind: 'scene',\n entities: nodes,\n mounts: resolvedMounts as unknown as readonly SceneInstanceMount[],\n ...(resolvedSkinGuids !== undefined ? { skinGuids: resolvedSkinGuids } : {}),\n } as SceneAsset;\n}\n\n/**\n * feat-20260612 M2 fixup: resolve `SceneAsset.skinGuids` -- on-disk refs[]\n * indices into post-parse GUID strings. Mirror of {@link resolveMounts}.\n * Returns undefined when no `skinGuids` field is present (back-compat:\n * pre-M2 SceneAssets carry no skin cross-edges).\n */\nfunction resolveSkinGuids(\n payload: Record<string, unknown>,\n refs: readonly string[] | undefined,\n): readonly string[] | undefined {\n const raw = payload.skinGuids;\n if (!Array.isArray(raw)) return undefined;\n const out: string[] = [];\n for (const item of raw as ReadonlyArray<unknown>) {\n if (typeof item === 'string') {\n // Pre-resolved GUID string (in-memory dawn smoke / direct register path).\n out.push(item);\n } else if (typeof item === 'number' && Number.isInteger(item)) {\n // refs[] index path (browser pack-fetch JSON-roundtrip shape).\n if (refs === undefined) return undefined;\n if (item < 0 || item >= refs.length) return undefined;\n const guid = refs[item];\n if (typeof guid !== 'string') return undefined;\n out.push(guid);\n } else {\n return undefined;\n }\n }\n return out;\n}\n\n/**\n * Resolve mounts[].source integer indices through refs[] to GUID strings.\n * Mount.source is resolved positionally (not through HANDLE_FIELD_NAMES),\n * per AC-11. Returns undefined when no mounts field is present (back-compat).\n */\nfunction resolveMounts(\n payload: Record<string, unknown>,\n refs: readonly string[] | undefined,\n): ReadonlyArray<Record<string, unknown>> | undefined {\n const rawMounts = payload.mounts;\n if (!Array.isArray(rawMounts)) return undefined;\n if (refs === undefined) return rawMounts as ReadonlyArray<Record<string, unknown>>;\n const resolved: Record<string, unknown>[] = [];\n for (const rm of rawMounts as ReadonlyArray<Record<string, unknown>>) {\n const mount = { ...rm };\n const source = rm.source;\n if (typeof source === 'number' && Number.isInteger(source)) {\n const idx = source;\n if (idx < 0 || idx >= refs.length) {\n return undefined;\n }\n mount.source = refs[idx];\n }\n resolved.push(mount);\n }\n return resolved;\n}\n","import {\n deriveVertexLayoutProjectionFromMask,\n type VertexLayoutProjection,\n} from '@forgeax/engine-geometry';\nimport {\n decodeMeshBinHeader,\n MESH_BIN_HEADER_V4_BYTES,\n type MeshBinHeaderV4,\n} from '@forgeax/engine-pack';\nimport { err, ok, type Result, type VertexAttributeMap } from '@forgeax/engine-types';\nimport { MeshBinAssetError } from '../errors/asset';\n\nexport interface UnpackedMeshBin {\n readonly version: 4;\n readonly projection: VertexLayoutProjection;\n readonly vertices: Float32Array;\n readonly attributes: VertexAttributeMap;\n readonly indices?: Uint16Array | Uint32Array;\n readonly submeshes: ReadonlyArray<Record<string, unknown>>;\n readonly materialSlots: readonly {\n readonly slotName: string;\n readonly sourceKey?: string;\n readonly defaultMaterialRef?: number;\n }[];\n readonly aabb?: Float32Array;\n readonly morphTargets?: ReadonlyArray<Record<string, Float32Array>>;\n readonly morphWeights?: Float32Array;\n}\n\nfunction fail(\n sourceKey: string,\n expected: string,\n actual: string,\n header?: Partial<MeshBinHeaderV4>,\n reason: import('@forgeax/engine-types').AssetMeshBinContractViolationReason = 'header-invalid',\n expectedFacts?: import('@forgeax/engine-types').AssetMeshBinContractFacts,\n actualFacts?: import('@forgeax/engine-types').AssetMeshBinContractFacts,\n): Result<UnpackedMeshBin, MeshBinAssetError> {\n return err(\n new MeshBinAssetError({\n sourceKey,\n expected,\n actual,\n ...(header === undefined ? {} : { header }),\n reason,\n ...(expectedFacts === undefined ? {} : { expectedFacts }),\n ...(actualFacts === undefined ? {} : { actualFacts }),\n }),\n );\n}\n\nfunction copyAttributes(\n source: Float32Array,\n header: MeshBinHeaderV4,\n projection: VertexLayoutProjection,\n): VertexAttributeMap {\n const view = new DataView(source.buffer, source.byteOffset, source.byteLength);\n const attributes: Record<string, Float32Array | Uint16Array> = {};\n for (const entry of projection.attributes) {\n const components = entry.byteLength / (entry.format === 'uint16x4' ? 2 : 4);\n const target =\n entry.format === 'uint16x4'\n ? new Uint16Array(header.vertexCount * components)\n : new Float32Array(header.vertexCount * components);\n for (let vertex = 0; vertex < header.vertexCount; vertex++) {\n for (let component = 0; component < components; component++) {\n const offset =\n vertex * header.stride + entry.offset + component * (entry.format === 'uint16x4' ? 2 : 4);\n if (target instanceof Uint16Array)\n target[vertex * components + component] = view.getUint16(offset, true);\n else target[vertex * components + component] = view.getFloat32(offset, true);\n }\n }\n attributes[entry.key] = target;\n }\n return attributes as VertexAttributeMap;\n}\n\nexport function unpackMeshBinV4(\n bytes: Uint8Array,\n sourceKey: string,\n): Result<UnpackedMeshBin, MeshBinAssetError> {\n const headerResult = decodeMeshBinHeader(bytes, sourceKey);\n if (!headerResult.ok) {\n const reason =\n headerResult.error.code === 'mesh-bin-header-truncated'\n ? 'header-truncated'\n : headerResult.error.code === 'mesh-bin-version-unsupported'\n ? 'version-unsupported'\n : 'header-invalid';\n const actualFacts = {\n byteLength: bytes.byteLength,\n ...(bytes.byteLength >= 4\n ? {\n version: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(\n 0,\n true,\n ),\n }\n : {}),\n };\n return fail(\n sourceKey,\n headerResult.error.expected,\n headerResult.error.actual,\n undefined,\n reason,\n reason === 'header-truncated'\n ? { field: 'byteLength', byteLength: MESH_BIN_HEADER_V4_BYTES }\n : reason === 'version-unsupported'\n ? { field: 'version', version: 4 }\n : undefined,\n actualFacts,\n );\n }\n const header = headerResult.value;\n const projectionResult = deriveVertexLayoutProjectionFromMask(header.mask);\n if (!projectionResult.ok) {\n return fail(\n sourceKey,\n projectionResult.error.expected,\n `mask=${header.mask}`,\n header,\n 'projection-mismatch',\n {\n field: 'mask',\n mask: projectionResult.error.detail.knownMask,\n },\n {\n field: 'mask',\n mask: header.mask,\n projectionVersion: header.projectionVersion,\n stride: header.stride,\n digest: header.digest,\n },\n );\n }\n const projection = projectionResult.value;\n if (\n projection.schemaVersion !== header.projectionVersion ||\n projection.arrayStride !== header.stride ||\n projection.digest !== header.digest\n ) {\n return fail(\n sourceKey,\n 'wire projection version, mask, stride, and digest to match geometry projection',\n `projection=${projection.schemaVersion}/${projection.arrayStride}/${projection.digest}; wire=${header.projectionVersion}/${header.stride}/${header.digest}`,\n header,\n 'projection-mismatch',\n {\n field: 'projectionVersion',\n projectionVersion: projection.schemaVersion,\n mask: projection.mask,\n stride: projection.arrayStride,\n digest: projection.digest,\n },\n );\n }\n const payloadBytes = header.vertexBytes + header.indexBytes + header.jsonBytes;\n if (MESH_BIN_HEADER_V4_BYTES + payloadBytes !== bytes.byteLength) {\n return fail(\n sourceKey,\n `exactly ${MESH_BIN_HEADER_V4_BYTES + payloadBytes} bytes`,\n `${bytes.byteLength} bytes`,\n header,\n 'payload-length-mismatch',\n { field: 'byteLength', byteLength: MESH_BIN_HEADER_V4_BYTES + payloadBytes },\n {\n field: 'byteLength',\n byteLength: bytes.byteLength,\n vertexBytes: header.vertexBytes,\n indexBytes: header.indexBytes,\n jsonBytes: header.jsonBytes,\n },\n );\n }\n let offset = MESH_BIN_HEADER_V4_BYTES;\n const vertexBytes = bytes.subarray(offset, offset + header.vertexBytes);\n const vertices = new Float32Array(vertexBytes.byteLength / 4);\n new Uint8Array(vertices.buffer).set(vertexBytes);\n offset += header.vertexBytes;\n let indices: Uint16Array | Uint32Array | undefined;\n if (header.indexCount > 0) {\n const indexBytes = bytes.subarray(offset, offset + header.indexBytes);\n if (header.indexWidth === 2) {\n indices = new Uint16Array(header.indexCount);\n new Uint8Array(indices.buffer).set(indexBytes);\n } else {\n indices = new Uint32Array(header.indexCount);\n new Uint8Array(indices.buffer).set(indexBytes);\n }\n offset += header.indexBytes;\n }\n const jsonBytes = bytes.subarray(offset, offset + header.jsonBytes);\n let meta: {\n submeshes?: ReadonlyArray<Record<string, unknown>>;\n materialSlots?: readonly {\n readonly slotName: string;\n readonly sourceKey?: string;\n readonly defaultMaterialRef?: number;\n }[];\n aabb?: readonly number[];\n morphTargets?: ReadonlyArray<Record<string, readonly number[]>>;\n morphWeights?: readonly number[];\n };\n try {\n meta = JSON.parse(new TextDecoder().decode(jsonBytes)) as typeof meta;\n } catch (error) {\n return fail(\n sourceKey,\n 'valid mesh-bin v4 JSON metadata',\n error instanceof Error ? error.message : String(error),\n header,\n 'metadata-invalid',\n { field: 'metadata' },\n { field: 'metadata' },\n );\n }\n if (\n !Array.isArray(meta.submeshes) ||\n meta.submeshes.length === 0 ||\n !Array.isArray(meta.materialSlots)\n ) {\n return fail(\n sourceKey,\n 'non-empty submeshes and materialSlots metadata',\n 'metadata table missing',\n header,\n 'metadata-invalid',\n { field: 'metadata' },\n { field: 'metadata' },\n );\n }\n const attributes = copyAttributes(vertices, header, projection);\n for (const attribute of projection.attributes) {\n const value = attributes[attribute.key];\n if (value === undefined)\n return fail(\n sourceKey,\n `decoded ${attribute.key} attribute`,\n 'attribute missing',\n header,\n 'attribute-invalid',\n {\n field: 'attribute',\n attribute: attribute.key,\n expectedLength:\n header.vertexCount * (attribute.byteLength / (attribute.format === 'uint16x4' ? 2 : 4)),\n },\n {\n field: 'attribute',\n attribute: attribute.key,\n mask: header.mask,\n stride: header.stride,\n vertexCount: header.vertexCount,\n },\n );\n if (value instanceof ArrayBuffer) continue;\n for (const component of value) {\n if (!Number.isFinite(component))\n return fail(\n sourceKey,\n 'finite vertex payload',\n `non-finite ${attribute.key}`,\n header,\n 'payload-non-finite',\n { field: 'attribute', attribute: attribute.key },\n {\n field: 'attribute',\n attribute: attribute.key,\n mask: header.mask,\n stride: header.stride,\n vertexCount: header.vertexCount,\n elementIndex: [...value].findIndex((component) => !Number.isFinite(component)),\n actualValue: Number.isNaN(component)\n ? 'nan'\n : component === Number.POSITIVE_INFINITY\n ? 'positive-infinity'\n : 'negative-infinity',\n },\n );\n }\n }\n const morphTargets = meta.morphTargets?.map((target) =>\n Object.fromEntries(\n Object.entries(target).map(([key, value]) => [key, new Float32Array(value)]),\n ),\n );\n const mesh: UnpackedMeshBin = {\n version: 4,\n projection,\n vertices,\n attributes,\n ...(indices === undefined ? {} : { indices }),\n submeshes: meta.submeshes,\n materialSlots: meta.materialSlots,\n ...(meta.aabb === undefined ? {} : { aabb: new Float32Array(meta.aabb) }),\n ...(morphTargets === undefined ? {} : { morphTargets }),\n ...(meta.morphWeights === undefined\n ? {}\n : { morphWeights: new Float32Array(meta.morphWeights) }),\n };\n return ok(mesh);\n}\n","// @forgeax/engine-assets-runtime - mipmap-generator.ts (T-M3-04).\n//\n// Independent-file home of the runtime mipmap auto-generation utility\n// (plan-strategy section 2.6 D Open Q-5 selection (a)). Purposefully lives\n// outside `asset-registry.ts` so the asset-registry stays single-purpose\n// (charter proposition 5 producer / consumer split; architecture-principles\n// pipeline isolation).\n//\n// Shader-module DI boundary (bug-20260518 D-1): the per-device pipeline\n// cache builds its single ShaderModule via an injected\n// `MipmapShaderModuleFactory`, NOT via `device.createShaderModule` -- the\n// post-fix-f3 `RhiDevice` surface has no synchronous `createShaderModule`\n// member, and the runtime mipmap utility must NOT reverse-import the\n// rhi-webgpu shim package (charter F1 layering). The factory is wired\n// once at `createRenderer.ts` from `pack.createShaderModule` and threaded\n// through `AssetRegistry.configureGpuDevice` -> `generateMipmaps` ->\n// `getOrCreateMipmapPipeline` -> `ensureDeviceCache`.\n//\n// SSOT three-source convergence (research F-1 + F-2):\n// - webgpufundamentals importing-textures-mipmaps (formula + main loop)\n// - toji web-texture-tool webgpu-mipmap-generator (oversized triangle WGSL)\n// - greggman webgpu-utils generate-mipmap (WeakMap<GPUDevice> cache)\n//\n// Public surface (charter F2 minimal):\n// - numMipLevels({ width, height }) -> number (formula SSOT)\n// - getOrCreateMipmapPipeline(device, format) -> Result (cache lookup; per-format)\n// - mipmapCacheSize(device) -> number (introspection)\n// - generateMipmaps(device, texture, descriptor) -> Result<void>(per-mip render-pass blit-loop)\n//\n// Per-device cache structure (greggman SSOT):\n// WeakMap<MipmapDevice, MipmapPipelineCache>\n// where MipmapPipelineCache = {\n// sampler: Sampler, // shared linear / linear / linear sampler (F-5)\n// module: ShaderModule, // shared oversized-triangle vertex + sampling fragment WGSL\n// layout: BindGroupLayout, // shared sampler @binding(0) + texture_2d<f32> @binding(1)\n// pipelines: Map<GPUTextureFormat, RenderPipeline> // per-format pipeline (F-2 cache key)\n// }\n// Per-device isolation prevents pipeline leak across `createRenderer` calls\n// (charter P5 consistent abstraction; greggman 36-44 anchor).\n//\n// Why this layout (not closure / not class):\n// - `getOrCreateMipmapPipeline` is module-level for test surface (T-M3-01\n// directly imports it; cache reference equality assertions need stable\n// identity across calls).\n// - `numMipLevels` is pure (no device argument); the WeakMap lookup only\n// happens at pipeline-create time.\n\nimport { err, ok, type Result, RhiError, type RhiRenderPassEncoder } from '@forgeax/engine-rhi';\n\n/**\n * Subset of `RhiDevice` consumed by the mipmap utility (charter F2: only\n * the methods the algorithm actually invokes; the dawn integration tests\n * pass a real `RhiDevice` and the unit cache tests pass a hand-rolled stub).\n *\n * Four entry-points (all synchronous Result):\n * - createSampler (default linear / linear / linear)\n * - createBindGroupLayout\n * - createPipelineLayout\n * - createRenderPipeline (per-format pipeline cache miss)\n *\n * Shader module is NOT an entry-point here; it is supplied by an injected\n * `MipmapShaderModuleFactory` (bug-20260518 D-1) so the utility does not\n * reach into the rhi-webgpu shim package from the runtime layer.\n *\n * Plus `createCommandEncoder` + `queue.submit` are added once the upload\n * call-site (T-M3-05) wires generateMipmaps in; the cache-only public hooks\n * exercised by T-M3-01 do not need them, so they live behind an extended\n * MipmapDeviceForBlit alias.\n */\nexport type MipmapDevice = {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createSampler(desc?: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createBindGroupLayout(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createPipelineLayout(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createRenderPipeline(desc: any): Result<any, any>;\n};\n\n/**\n * Async shader-module factory injected through the call-chain\n * `createRenderer.ts` -> `AssetRegistry.configureGpuDevice` ->\n * `generateMipmaps` -> `getOrCreateMipmapPipeline` -> `ensureDeviceCache`\n * (bug-20260518 D-1 / D-4).\n *\n * Signature mirrors the top-level async `createShaderModule(device, desc)`\n * exposed by the rhi-webgpu shim (and the rhi-wgpu shim) so the\n * call-site in createRenderer can pass `pack.createShaderModule` directly\n * without a structural cast. The opaque module value is typed `unknown`\n * here -- callers do not introspect it; they hand the value back to\n * `createRenderPipeline` descriptors via the cached `MipmapPipelineCache`.\n */\nexport type MipmapShaderModuleFactory = (\n device: MipmapDevice,\n desc: { code: string; label?: string },\n) => Promise<Result<unknown, RhiError>>;\n\n/**\n * Per-device pipeline cache structure (research F-2 SSOT).\n * Held under a module-private `WeakMap<MipmapDevice, MipmapPipelineCache>`.\n */\ninterface MipmapPipelineCache {\n // biome-ignore lint/suspicious/noExplicitAny: cached opaque GPU sampler\n readonly sampler: any;\n // biome-ignore lint/suspicious/noExplicitAny: cached opaque GPU shader module\n readonly module: any;\n // biome-ignore lint/suspicious/noExplicitAny: cached opaque GPU bind-group layout\n readonly layout: any;\n // biome-ignore lint/suspicious/noExplicitAny: per-format render pipeline cache\n readonly pipelines: Map<GPUTextureFormat, any>;\n}\n\n// Module-private cache (greggman 36-44 SSOT). WeakMap so that destroying a\n// device naturally clears its cache (no manual cleanup hook needed).\nconst deviceCache: WeakMap<MipmapDevice, MipmapPipelineCache> = new WeakMap();\n\n/**\n * Oversized-triangle WGSL (toji + greggman convergent template).\n *\n * Vertex stage emits a single triangle covering the entire NDC, and texCoord\n * is computed from clip-space position via `pos * vec2(0.5, -0.5) +\n * vec2(0.5)` (NDC -> UV with Y-flip in one fused MAD; saves a 6-vertex quad).\n *\n * Fragment stage samples the bound `texture_2d<f32>` with the linear /\n * linear / linear sampler -- bilinear when the source mip is read by the\n * destination mip, automatic sRGB decode / encode happens in the spec when\n * source AND destination views are the SAME `*-srgb` format (research F-3).\n */\nconst MIPMAP_WGSL = `\nstruct VsOut {\n @builtin(position) clip : vec4<f32>,\n @location(0) uv : vec2<f32>,\n};\n\n@vertex\nfn vs_main(@builtin(vertex_index) vid : u32) -> VsOut {\n // 3 vertices forming an oversized triangle: (-1,-1), (-1,3), (3,-1)\n var positions = array<vec2<f32>, 3>(\n vec2<f32>(-1.0, -1.0),\n vec2<f32>(-1.0, 3.0),\n vec2<f32>( 3.0, -1.0),\n );\n let pos = positions[vid];\n var out : VsOut;\n out.clip = vec4<f32>(pos, 0.0, 1.0);\n // NDC -> UV with Y-flip fused into a single MAD.\n out.uv = pos * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);\n return out;\n}\n\n@group(0) @binding(0) var src_sampler : sampler;\n@group(0) @binding(1) var src_texture : texture_2d<f32>;\n\n@fragment\nfn fs_main(in : VsOut) -> @location(0) vec4<f32> {\n return textureSample(src_texture, src_sampler, in.uv);\n}\n`;\n\n/**\n * Compute mip-level count for a 2D texture (research F-1 SSOT formula).\n *\n * Spec-anchor: WebGPU §3.6 texture-creation says `mipLevelCount` defaults\n * to 1; the runtime utility opts AI users into a full chain via\n * `floor(log2(max(width, height))) + 1` -- the same formula greggman /\n * toji / webgpufundamentals all converge on.\n *\n * @example\n * numMipLevels({ width: 256, height: 256 }) // 9\n * numMipLevels({ width: 1, height: 1 }) // 1\n */\nexport function numMipLevels(size: { width: number; height: number }): number {\n const max = Math.max(size.width, size.height);\n if (max <= 1) return 1;\n return Math.floor(Math.log2(max)) + 1;\n}\n\n/**\n * Number of cached pipelines for the device (introspection hook used by\n * T-M3-01 (c) cache-hit / (d) per-device-isolation tests; charter P3\n * explicit failure: a cache size of 0 on a fresh device is a witnessed\n * pre-condition rather than a swept-under hint).\n */\nexport function mipmapCacheSize(device: MipmapDevice): number {\n const cache = deviceCache.get(device);\n return cache?.pipelines.size ?? 0;\n}\n\n/**\n * Get the existing per-format render pipeline or build a fresh one.\n *\n * Per-device WeakMap + per-format `Map<GPUTextureFormat, RenderPipeline>`\n * (greggman 36-44 + 119-122). The shared sampler / shader-module /\n * bind-group-layout are constructed lazily on the first cache miss for a\n * given device and reused across all formats on that device.\n */\nexport async function getOrCreateMipmapPipeline(\n device: MipmapDevice,\n format: GPUTextureFormat,\n asyncCreateShaderModule: MipmapShaderModuleFactory,\n // biome-ignore lint/suspicious/noExplicitAny: returns opaque GPU pipeline\n): Promise<Result<any, unknown>> {\n const cache = await ensureDeviceCache(device, asyncCreateShaderModule);\n if (!cache.ok) return cache;\n const existing = cache.value.pipelines.get(format);\n if (existing !== undefined) {\n return ok(existing);\n }\n const layoutRes = device.createPipelineLayout({\n label: 'mipmap-pl',\n bindGroupLayouts: [cache.value.layout],\n });\n if (!layoutRes.ok) return layoutRes;\n const pipelineRes = device.createRenderPipeline({\n label: `mipmap-pipeline-${format}`,\n layout: layoutRes.value,\n vertex: { module: cache.value.module, entryPoint: 'vs_main' },\n fragment: {\n module: cache.value.module,\n entryPoint: 'fs_main',\n targets: [{ format }],\n },\n primitive: { topology: 'triangle-list' },\n });\n if (!pipelineRes.ok) return pipelineRes;\n cache.value.pipelines.set(format, pipelineRes.value);\n return pipelineRes;\n}\n\nasync function ensureDeviceCache(\n device: MipmapDevice,\n asyncCreateShaderModule: MipmapShaderModuleFactory,\n): Promise<Result<MipmapPipelineCache, RhiError>> {\n const existing = deviceCache.get(device);\n if (existing !== undefined) return ok(existing);\n\n const moduleRes = await asyncCreateShaderModule(device, {\n code: MIPMAP_WGSL,\n label: 'mipmap-wgsl',\n });\n if (!moduleRes.ok) return moduleRes;\n\n const samplerRes = device.createSampler({\n magFilter: 'linear',\n minFilter: 'linear',\n mipmapFilter: 'linear',\n });\n if (!samplerRes.ok) return samplerRes;\n\n // GPUShaderStage.FRAGMENT = 0x2 spec constant; embedded literally to keep\n // the utility math-free (charter F2 minimal surface; spec value is stable).\n const FRAGMENT_STAGE = 0x2;\n const layoutRes = device.createBindGroupLayout({\n label: 'mipmap-bgl',\n entries: [\n { binding: 0, visibility: FRAGMENT_STAGE, sampler: { type: 'filtering' } },\n {\n binding: 1,\n visibility: FRAGMENT_STAGE,\n texture: { sampleType: 'float', viewDimension: '2d' },\n },\n ],\n });\n if (!layoutRes.ok) return layoutRes;\n\n const cache: MipmapPipelineCache = {\n sampler: samplerRes.value,\n module: moduleRes.value,\n layout: layoutRes.value,\n pipelines: new Map(),\n };\n deviceCache.set(device, cache);\n return ok(cache);\n}\n\n/**\n * Extended device shape used by `generateMipmaps` (call-site T-M3-05).\n * Adds command-encoder + bind-group + texture-view + queue surfaces beyond\n * the cache-only `MipmapDevice` so the pipeline-cache unit tests still\n * compile against the smaller surface.\n */\nexport type MipmapBlitDevice = MipmapDevice & {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createTexture(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createBindGroup(desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createTextureView(texture: any, desc: any): Result<any, any>;\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n createCommandEncoder(desc?: any): Result<any, any>;\n readonly queue: {\n // biome-ignore lint/suspicious/noExplicitAny: shim accepts any descriptor\n submit(buffers: ReadonlyArray<any>): Result<void, any>;\n };\n};\n\nfunction recordMipmapBlit<E>(\n device: MipmapBlitDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture handle\n texture: any,\n levels: number,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU pipeline handle\n pipeline: any,\n cache: MipmapPipelineCache,\n): Result<void, E> {\n const encoderRes = device.createCommandEncoder({ label: 'mipmap-encoder' });\n if (!encoderRes.ok) return encoderRes;\n const encoder = encoderRes.value;\n\n for (let i = 1; i < levels; i++) {\n const srcViewRes = device.createTextureView(texture, {\n baseMipLevel: i - 1,\n mipLevelCount: 1,\n dimension: '2d',\n });\n if (!srcViewRes.ok) return srcViewRes;\n\n const dstViewRes = device.createTextureView(texture, {\n baseMipLevel: i,\n mipLevelCount: 1,\n dimension: '2d',\n });\n if (!dstViewRes.ok) return dstViewRes;\n\n const bindGroupRes = device.createBindGroup({\n label: `mipmap-bg-${i}`,\n layout: cache.layout,\n entries: [\n { binding: 0, resource: { kind: 'sampler', value: cache.sampler } },\n { binding: 1, resource: { kind: 'textureView', value: srcViewRes.value } },\n ],\n });\n if (!bindGroupRes.ok) return bindGroupRes;\n\n const pass = encoder.beginRenderPass({\n label: `mipmap-pass-${i}`,\n colorAttachments: [\n {\n view: dstViewRes.value,\n clearValue: { r: 0, g: 0, b: 0, a: 1 },\n loadOp: 'clear',\n storeOp: 'store',\n },\n ],\n });\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindGroupRes.value);\n pass.draw(3, 1, 0, 0);\n pass.end();\n }\n\n const finishRes = encoder.finish();\n if (!finishRes.ok) return finishRes;\n return device.queue.submit([finishRes.value]);\n}\n\n/**\n * Per-mip render-pass blit-loop (research F-1 SSOT main template).\n *\n * For mip levels 1..levels-1: source view = previous mip {baseMipLevel:i-1,\n * mipLevelCount:1}; destination view = current mip {baseMipLevel:i,\n * mipLevelCount:1, usage: RENDER_ATTACHMENT}; oversized-triangle pipeline\n * draws 3 vertices, fragment shader samples source via linear sampler.\n *\n * Spec sRGB correctness (F-3): when format is `*-srgb`, both views inherit\n * the sRGB encoding so hardware decode -> bilinear in linear -> encode back\n * happens automatically; no special-casing required.\n *\n * `levels` defaults to `numMipLevels({ width, height })`. AI users that\n * already created the texture with explicit `mipLevelCount` should pass the\n * same value here.\n */\nexport async function generateMipmaps(\n device: MipmapBlitDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture handle\n texture: any,\n descriptor: {\n readonly format: GPUTextureFormat;\n readonly width: number;\n readonly height: number;\n readonly levels?: number;\n },\n asyncCreateShaderModule: MipmapShaderModuleFactory,\n): Promise<Result<void, unknown>> {\n const levels = descriptor.levels ?? numMipLevels(descriptor);\n if (levels <= 1) return ok(undefined);\n\n const pipelineRes = await getOrCreateMipmapPipeline(\n device,\n descriptor.format,\n asyncCreateShaderModule,\n );\n if (!pipelineRes.ok) return pipelineRes;\n const cache = deviceCache.get(device);\n if (cache === undefined) {\n return err({ code: 'webgpu-runtime-error', message: 'mipmap cache missing after create' });\n }\n return recordMipmapBlit<unknown>(device, texture, levels, pipelineRes.value, cache);\n}\n\n/**\n * Synchronous sibling of `generateMipmaps` (feat-20260601-gpu-resource-store\n * -extraction D-9). Identical per-mip blit loop, but reads the per-format\n * pipeline + shared sampler / layout from the prewarmed device cache instead\n * of building them. The pipeline MUST already be present (via a prior\n * `getOrCreateMipmapPipeline` / `prewarmMipmapPipeline` async call) -- an\n * un-prewarmed device or format returns a structured `RhiError` rather than\n * awaiting a build, so the synchronous `draw(world)` frame contract is never\n * broken. The async build itself does not affect the written bytes (same\n * shader, same encoder sequence), so prewarm + sync blit reproduces the\n * pre-extraction async `generateMipmaps` byte-for-byte (D-9 sub-contract 5).\n */\nexport function blitMipmapsSync(\n device: MipmapBlitDevice,\n // biome-ignore lint/suspicious/noExplicitAny: opaque GPU texture handle\n texture: any,\n descriptor: {\n readonly format: GPUTextureFormat;\n readonly width: number;\n readonly height: number;\n readonly levels?: number;\n },\n): Result<void, RhiError> {\n const levels = descriptor.levels ?? numMipLevels(descriptor);\n if (levels <= 1) return ok(undefined);\n\n const cache = deviceCache.get(device);\n if (cache === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'mipmap pipeline cache prewarmed for this device before blitMipmapsSync',\n hint: 'call prewarmMipmapPipeline(device, formats) at renderer.ready before the synchronous record-stage mipmap blit',\n }),\n );\n }\n const pipeline = cache.pipelines.get(descriptor.format);\n if (pipeline === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: `mipmap pipeline for format ${descriptor.format} prewarmed`,\n hint: `format ${descriptor.format} was not prewarmed; add it to the prewarmMipmapPipeline format list at renderer.ready`,\n }),\n );\n }\n\n return recordMipmapBlit<RhiError>(device, texture, levels, pipeline, cache);\n}\n\n/** Encode one prewarmed mip level into a caller-owned graph render pass. */\nexport function encodeMipmapLevel(\n device: MipmapBlitDevice,\n pass: RhiRenderPassEncoder,\n sourceView: unknown,\n format: GPUTextureFormat,\n): Result<void, RhiError> {\n const cache = deviceCache.get(device);\n if (cache === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: 'mipmap pipeline cache prewarmed for the graph device before encoding',\n hint: 'call prewarmMipmapPipeline(device, formats) at renderer.ready',\n }),\n );\n }\n const pipeline = cache.pipelines.get(format);\n if (pipeline === undefined) {\n return err(\n new RhiError({\n code: 'rhi-not-available',\n expected: `mipmap pipeline for format ${format} prewarmed`,\n hint: `format ${format} was not prewarmed; add it to the renderer prewarm list`,\n }),\n );\n }\n const bindGroup = device.createBindGroup({\n label: 'mipmap-graph-bind-group',\n layout: cache.layout,\n entries: [\n { binding: 0, resource: { kind: 'sampler', value: cache.sampler } },\n { binding: 1, resource: { kind: 'textureView', value: sourceView } },\n ],\n });\n if (!bindGroup.ok) return bindGroup;\n pass.setPipeline(pipeline);\n pass.setBindGroup(0, bindGroup.value);\n pass.draw(3, 1, 0, 0);\n return ok(undefined);\n}\n","import type { CodecError, TranscodeModel } from '@forgeax/engine-codec';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type {\n AssetCodec,\n AssetCodecFailureDetail,\n EquirectAsset,\n FontAsset,\n LoadContext,\n Loader,\n LoaderAsyncResult,\n RenderPipelineAsset,\n TextureAsset,\n TilesetAsset,\n} from '@forgeax/engine-types';\nimport { AssetError } from '@forgeax/engine-types';\nimport type { PackLoaderInput } from '../loader-registry';\nimport { numMipLevels } from '../mipmap-generator';\n\ntype PackArtifact = PackLoaderInput['artifacts'][string];\n\ntype CodecFailureProjection = {\n readonly code: string;\n readonly expected: string;\n readonly hint: string;\n readonly detail: Readonly<Record<string, unknown>>;\n};\n\nfunction firstArtifact(input: PackLoaderInput): PackArtifact | undefined {\n return input.artifacts.body ?? Object.values(input.artifacts)[0];\n}\n\nfunction payloadNumber(payload: Record<string, unknown>, key: string, fallback: number): number {\n const value = payload[key];\n return typeof value === 'number' ? value : fallback;\n}\n\nfunction payloadColorSpace(payload: Record<string, unknown>): 'srgb' | 'linear' {\n return payload.colorSpace === 'linear' ? 'linear' : 'srgb';\n}\n\nfunction invalidPackAsset<T>(input: PackLoaderInput, expected: string): LoaderAsyncResult<T> {\n return {\n ok: false,\n error: new AssetError({\n code: 'asset-parse-failed',\n expected,\n hint: `Pack v2 asset ${input.guid} must provide an asset-local artifact`,\n detail: { sourcePath: input.guid },\n }),\n };\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction finiteNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction positiveInteger(value: unknown): value is number {\n return finiteNumber(value) && Number.isInteger(value) && value > 0;\n}\n\nfunction validRenderPipelineConfig(value: unknown): value is Record<string, unknown> {\n if (!record(value)) return false;\n const passCount = value.passCount;\n if (passCount !== undefined && !positiveInteger(passCount)) return false;\n const clusterGrid = value.clusterGrid;\n if (clusterGrid !== undefined) {\n if (\n !record(clusterGrid) ||\n !['x', 'y', 'z'].every((axis) => {\n const size = clusterGrid[axis];\n return positiveInteger(size) && size <= 64;\n })\n ) {\n return false;\n }\n }\n const ssao = value.ssao;\n if (ssao !== undefined && (!record(ssao) || typeof ssao.enabled !== 'boolean')) return false;\n const postEffects = value.postEffects;\n return (\n postEffects === undefined ||\n (Array.isArray(postEffects) &&\n postEffects.every((effect) => typeof effect === 'string' && effect.length > 0))\n );\n}\n\nfunction validTilesetRegion(value: unknown, atlasCount: number): boolean {\n if (!record(value)) return false;\n const { x, y, width, height, atlasIndex } = value;\n return (\n finiteNumber(x) &&\n finiteNumber(y) &&\n positiveInteger(width) &&\n positiveInteger(height) &&\n (atlasIndex === undefined ||\n (typeof atlasIndex === 'number' &&\n Number.isInteger(atlasIndex) &&\n atlasIndex >= 0 &&\n atlasIndex < atlasCount))\n );\n}\n\nfunction validTilesetTile(value: unknown, regionCount: number): boolean {\n if (!record(value)) return false;\n const regionIndex = value.regionIndex;\n return (\n typeof regionIndex === 'number' &&\n Number.isInteger(regionIndex) &&\n regionIndex >= 0 &&\n regionIndex < regionCount\n );\n}\n\nfunction validAtlasSize(value: unknown): boolean {\n return record(value) && positiveInteger(value.pixelWidth) && positiveInteger(value.pixelHeight);\n}\n\nfunction readJsonArtifact(\n input: PackLoaderInput,\n kind: string,\n): Record<string, unknown> | undefined {\n const artifact = firstArtifact(input);\n if (artifact === undefined) return undefined;\n try {\n const value: unknown = JSON.parse(new TextDecoder().decode(artifact.bytes));\n return record(value) && value.kind === kind ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction renderPipelineDescriptor(value: Record<string, unknown>): RenderPipelineAsset | undefined {\n if (value.kind !== 'render-pipeline') return undefined;\n const pipelineId = value.pipelineId;\n if (typeof pipelineId !== 'string' || pipelineId.trim().length === 0) return undefined;\n const config = value.config;\n if (config !== undefined && !validRenderPipelineConfig(config)) return undefined;\n return {\n kind: 'render-pipeline',\n pipelineId,\n ...(config === undefined\n ? {}\n : { config: config as NonNullable<RenderPipelineAsset['config']> }),\n };\n}\n\nfunction tilesetDescriptor(\n value: Record<string, unknown>,\n refs: readonly string[],\n): TilesetAsset | undefined {\n if (value.kind !== 'tileset') return undefined;\n const rawAtlases = value.atlases;\n if (!Array.isArray(rawAtlases) || rawAtlases.length === 0) return undefined;\n if (!rawAtlases.every((atlas) => typeof atlas === 'string' && atlas.length > 0)) return undefined;\n const atlases = rawAtlases as string[];\n if (atlases.length !== refs.length || atlases.some((guid, index) => guid !== refs[index])) {\n return undefined;\n }\n const { tileWidth, tileHeight, columns, rows, regions, tiles, atlasSizes } = value;\n if (\n typeof tileWidth !== 'number' ||\n tileWidth <= 0 ||\n typeof tileHeight !== 'number' ||\n tileHeight <= 0 ||\n typeof columns !== 'number' ||\n !Number.isInteger(columns) ||\n columns <= 0 ||\n typeof rows !== 'number' ||\n !Number.isInteger(rows) ||\n rows <= 0 ||\n !Array.isArray(regions) ||\n !regions.every((region) => record(region) && validTilesetRegion(region, atlases.length)) ||\n !Array.isArray(tiles) ||\n !tiles.every((tile) => validTilesetTile(tile, regions.length)) ||\n (atlasSizes !== undefined &&\n (!Array.isArray(atlasSizes) ||\n atlasSizes.length !== atlases.length ||\n !atlasSizes.every((size) => validAtlasSize(size))))\n ) {\n return undefined;\n }\n return {\n kind: 'tileset',\n atlases: [...atlases],\n tileWidth,\n tileHeight,\n columns,\n rows,\n regions: regions as TilesetAsset['regions'],\n tiles: tiles as TilesetAsset['tiles'],\n ...(Array.isArray(atlasSizes)\n ? { atlasSizes: atlasSizes as NonNullable<TilesetAsset['atlasSizes']> }\n : {}),\n };\n}\n\nfunction codecProfile(codec: AssetCodec | undefined): string | undefined {\n return codec?.profile;\n}\n\nexport type CodecContextFailure =\n | {\n readonly code: 'basis-profile-unsupported';\n readonly detail: { readonly profile: string };\n }\n | {\n readonly code: 'ktx2-color-space-mismatch';\n readonly detail: {\n readonly authoredColorSpace: 'srgb' | 'linear';\n readonly dfdColorSpace: 'srgb' | 'linear' | 'unknown';\n };\n };\n\nfunction projectCodecFailureDetail(\n input: PackLoaderInput,\n codec: AssetCodec,\n caps: LoadContext['transcodeCaps'],\n failure: CodecFailureProjection,\n targetFormat?: GPUTextureFormat,\n): AssetCodecFailureDetail {\n return {\n sourcePath: input.guid,\n codecCode: failure.code,\n codecExpected: failure.expected,\n codecHint: failure.hint,\n codecDetail: failure.detail,\n container: codec.container ?? 'basis',\n ...(codec.profile === undefined ? {} : { profile: codec.profile }),\n ...(targetFormat === undefined ? {} : { targetFormat }),\n capabilities: caps,\n };\n}\n\nfunction codecFailure(\n input: PackLoaderInput,\n codec: AssetCodec,\n caps: LoadContext['transcodeCaps'],\n failure: CodecError['error'],\n targetFormat?: GPUTextureFormat,\n): AssetError {\n const detail = projectCodecFailureDetail(input, codec, caps, failure, targetFormat);\n return new AssetError({\n code: 'asset-parse-failed',\n expected: failure.expected,\n hint: failure.hint,\n detail,\n });\n}\n\nfunction codecContextFailure(\n input: PackLoaderInput,\n codec: AssetCodec,\n caps: LoadContext['transcodeCaps'],\n failure: CodecContextFailure,\n expected: string,\n hint: string,\n targetFormat?: GPUTextureFormat,\n): AssetError {\n const detail = projectCodecFailureDetail(\n input,\n codec,\n caps,\n {\n code: failure.code,\n expected,\n hint,\n detail: failure.detail,\n },\n targetFormat,\n );\n return new AssetError({\n code: 'asset-parse-failed',\n expected,\n hint,\n detail,\n });\n}\n\nfunction transcodeModel(profile: string): TranscodeModel | undefined {\n if (profile === 'etc1s') return 'etc1s';\n if (profile === 'uastc' || profile === 'uastc-ldr') return 'uastc-ldr';\n if (profile === 'uastc-hdr') return 'uastc-hdr';\n return undefined;\n}\n\nasync function loadTexturePack(\n input: PackLoaderInput,\n ctx: LoadContext,\n): Promise<LoaderAsyncResult<TextureAsset>> {\n const artifact = firstArtifact(input);\n if (artifact === undefined)\n return invalidPackAsset<TextureAsset>(input, 'texture asset-local image artifact');\n const payload = input.payload;\n const width = payloadNumber(payload, 'width', 0);\n const height = payloadNumber(payload, 'height', 0);\n const colorSpace = payloadColorSpace(payload);\n const codec = artifact.descriptor.assetCodec;\n const profile = codecProfile(codec);\n const model =\n codec?.name === 'basis' && profile !== undefined ? transcodeModel(profile) : undefined;\n\n if (codec?.name === 'basis' && codec.container === 'basis') {\n const basisCodec = codec;\n if (model === undefined) {\n return {\n ok: false,\n error: codecContextFailure(\n input,\n basisCodec,\n ctx.transcodeCaps,\n {\n code: 'basis-profile-unsupported',\n detail: { profile: codec.profile ?? 'missing' },\n },\n 'raw Basis artifact with an explicit ETC1S or UASTC-LDR profile',\n 'set assetCodec.profile to etc1s or uastc-ldr and re-cook the source',\n ),\n };\n }\n try {\n const { selectTranscodeTarget, transcodeBasis } = await import('@forgeax/engine-codec');\n const target = selectTranscodeTarget(\n { model, srgb: colorSpace === 'srgb', channels: 'rgba' },\n ctx.transcodeCaps,\n );\n const transcoded = await transcodeBasis(artifact.bytes, target);\n if (!transcoded.ok) {\n return {\n ok: false,\n error: codecFailure(input, basisCodec, ctx.transcodeCaps, transcoded.error, target),\n };\n }\n const data = new Uint8Array(\n transcoded.value.mips.reduce((size, mip) => size + mip.data.length, 0),\n );\n let offset = 0;\n for (const mip of transcoded.value.mips) {\n data.set(mip.data, offset);\n offset += mip.data.length;\n }\n return {\n ok: true,\n value: {\n kind: 'texture',\n width: transcoded.value.width,\n height: transcoded.value.height,\n format: target,\n data,\n colorSpace,\n mipmap: transcoded.value.mips.length > 1,\n mipLevelCount: Math.max(1, transcoded.value.mips.length),\n },\n };\n } catch (error) {\n return {\n ok: false,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: 'loadable raw Basis texture artifact',\n hint: error instanceof Error ? error.message : String(error),\n detail: {\n sourcePath: input.guid,\n codecCode: 'runtime-loader-exception',\n codecExpected: 'loadable raw Basis texture artifact',\n codecHint: error instanceof Error ? error.message : String(error),\n codecDetail: { reason: 'runtime-loader-exception' },\n container: basisCodec.container ?? 'basis',\n ...(basisCodec.profile === undefined ? {} : { profile: basisCodec.profile }),\n capabilities: ctx.transcodeCaps,\n },\n }),\n };\n }\n }\n\n if (model !== undefined && codec !== undefined) {\n const ktx2Codec = codec;\n try {\n const { ktx2ColorSpace, parseKtx2, selectTranscodeTarget, transcodeKtx2 } = await import(\n '@forgeax/engine-codec'\n );\n const parsed = await parseKtx2(artifact.bytes);\n if (!parsed.ok) {\n return {\n ok: false,\n error: codecFailure(input, ktx2Codec, ctx.transcodeCaps, parsed.error),\n };\n }\n const projectedColorSpace = ktx2ColorSpace(parsed.value);\n if (projectedColorSpace === undefined || projectedColorSpace !== colorSpace) {\n return {\n ok: false,\n error: codecContextFailure(\n input,\n ktx2Codec,\n ctx.transcodeCaps,\n {\n code: 'ktx2-color-space-mismatch',\n detail: {\n authoredColorSpace: colorSpace,\n dfdColorSpace: projectedColorSpace ?? 'unknown',\n },\n },\n 'Basis KTX2 DFD transfer function matching the texture colorSpace',\n 'align the texture payload colorSpace with the KTX2 DFD and re-cook the source',\n ),\n };\n }\n const target = selectTranscodeTarget(\n { model, srgb: colorSpace === 'srgb', channels: 'rgba' },\n ctx.transcodeCaps,\n );\n const transcoded = await transcodeKtx2(parsed.value, target);\n if (!transcoded.ok) {\n return {\n ok: false,\n error: codecFailure(input, ktx2Codec, ctx.transcodeCaps, transcoded.error, target),\n };\n }\n const data = new Uint8Array(\n transcoded.value.mips.reduce((size, mip) => size + mip.data.length, 0),\n );\n let offset = 0;\n for (const mip of transcoded.value.mips) {\n data.set(mip.data, offset);\n offset += mip.data.length;\n }\n return {\n ok: true,\n value: {\n kind: 'texture',\n width: transcoded.value.width,\n height: transcoded.value.height,\n format: target,\n data,\n colorSpace,\n mipmap: transcoded.value.mips.length > 1,\n mipLevelCount: Math.max(1, transcoded.value.mips.length),\n },\n };\n } catch (error) {\n if (error instanceof AssetError) return { ok: false, error };\n return {\n ok: false,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: 'loadable Basis KTX2 texture artifact',\n hint: error instanceof Error ? error.message : String(error),\n detail: {\n sourcePath: input.guid,\n codecCode: 'runtime-loader-exception',\n codecExpected: 'loadable Basis KTX2 texture artifact',\n codecHint: error instanceof Error ? error.message : String(error),\n codecDetail: { reason: 'runtime-loader-exception' },\n container: ktx2Codec.container ?? 'ktx2',\n ...(ktx2Codec.profile === undefined ? {} : { profile: ktx2Codec.profile }),\n capabilities: ctx.transcodeCaps,\n },\n }),\n };\n }\n }\n\n const mipmap = payload.mipmap === true;\n return {\n ok: true,\n value: {\n kind: 'texture',\n width,\n height,\n format: (payload.format ??\n (colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm')) as GPUTextureFormat,\n data: artifact.bytes,\n colorSpace,\n mipmap,\n mipLevelCount: mipmap ? numMipLevels({ width, height }) : 1,\n },\n };\n}\n\nasync function loadEquirectPack(input: PackLoaderInput): Promise<LoaderAsyncResult<EquirectAsset>> {\n const artifact = firstArtifact(input);\n if (artifact === undefined)\n return invalidPackAsset<EquirectAsset>(input, 'equirect asset-local image artifact');\n const payload = input.payload;\n return {\n ok: true,\n value: {\n kind: 'equirect',\n width: payloadNumber(payload, 'width', 0),\n height: payloadNumber(payload, 'height', 0),\n format: (payload.format ?? 'rgba16float') as GPUTextureFormat,\n data: artifact.bytes,\n colorSpace: payloadColorSpace(payload),\n },\n };\n}\n\nfunction parseGlyphs(value: unknown): FontAsset['glyphs'] {\n if (typeof value !== 'object' || value === null) return {};\n const glyphs: FontAsset['glyphs'] = {};\n for (const [codepoint, raw] of Object.entries(value as Record<string, unknown>)) {\n if (typeof raw !== 'object' || raw === null) continue;\n const metric = raw as Record<string, unknown>;\n const size = metric.size as Record<string, unknown> | undefined;\n const region = metric.region as Record<string, unknown> | undefined;\n if (\n typeof metric.advance !== 'number' ||\n typeof metric.bearingX !== 'number' ||\n typeof metric.bearingY !== 'number' ||\n typeof size?.w !== 'number' ||\n typeof size.h !== 'number' ||\n typeof region?.x !== 'number' ||\n typeof region.y !== 'number' ||\n typeof region.w !== 'number' ||\n typeof region.h !== 'number'\n ) {\n continue;\n }\n glyphs[Number(codepoint)] = {\n advance: metric.advance,\n bearingX: metric.bearingX,\n bearingY: metric.bearingY,\n size: { w: size.w, h: size.h },\n region: { x: region.x, y: region.y, w: region.w, h: region.h },\n };\n }\n return glyphs;\n}\n\nasync function loadFontPack(\n input: PackLoaderInput,\n ctx: LoadContext,\n): Promise<LoaderAsyncResult<FontAsset>> {\n const payload = input.payload;\n const atlasGuid = payload.atlasGuid;\n const samplerGuid = payload.samplerGuid;\n const common = payload.common;\n if (\n typeof atlasGuid !== 'string' ||\n typeof samplerGuid !== 'string' ||\n typeof common !== 'object' ||\n common === null\n ) {\n return invalidPackAsset<FontAsset>(\n input,\n 'font payload with atlasGuid, samplerGuid, and common',\n );\n }\n const parsedAtlas = AssetGuid.parse(atlasGuid);\n const parsedSampler = AssetGuid.parse(samplerGuid);\n if (!parsedAtlas.ok) return { ok: false, error: parsedAtlas.error };\n if (!parsedSampler.ok) return { ok: false, error: parsedSampler.error };\n const atlasResolved = await ctx.resolveRef(atlasGuid);\n if (!atlasResolved.ok) return atlasResolved;\n const samplerResolved = await ctx.resolveRef(samplerGuid);\n if (!samplerResolved.ok) return samplerResolved;\n const commonRecord = common as Record<string, unknown>;\n const commonFields = [\n 'lineHeight',\n 'base',\n 'distanceRange',\n 'pxRange',\n 'atlasWidth',\n 'atlasHeight',\n ];\n if (commonFields.some((key) => typeof commonRecord[key] !== 'number')) {\n return invalidPackAsset<FontAsset>(input, 'font common block with numeric layout fields');\n }\n return {\n ok: true,\n value: {\n kind: 'font',\n atlas: parsedAtlas.value,\n sampler: parsedSampler.value,\n glyphs: parseGlyphs(payload.glyphs),\n common: {\n lineHeight: commonRecord.lineHeight as number,\n base: commonRecord.base as number,\n distanceRange: commonRecord.distanceRange as number,\n pxRange: commonRecord.pxRange as number,\n atlasWidth: commonRecord.atlasWidth as number,\n atlasHeight: commonRecord.atlasHeight as number,\n },\n },\n };\n}\n\nexport const textureLoader: Loader = {\n kind: 'texture',\n load: () => undefined,\n loadPack: loadTexturePack,\n};\n\nexport const equirectLoader: Loader = {\n kind: 'equirect',\n load: () => undefined,\n loadPack: loadEquirectPack,\n};\n\nexport const fontLoader: Loader = {\n kind: 'font',\n load: () => undefined,\n loadPack: loadFontPack,\n};\n\nexport const renderPipelineLoader: Loader = {\n kind: 'render-pipeline',\n load: (payload) => renderPipelineDescriptor({ ...payload, kind: 'render-pipeline' }),\n loadPack: async (input) => {\n if (firstArtifact(input) === undefined) {\n const value = renderPipelineDescriptor({ ...input.payload, kind: 'render-pipeline' });\n return value === undefined\n ? invalidPackAsset<RenderPipelineAsset>(input, 'a valid render-pipeline descriptor')\n : { ok: true, value };\n }\n const payload = readJsonArtifact(input, 'render-pipeline');\n const value = payload === undefined ? undefined : renderPipelineDescriptor(payload);\n return payload === undefined\n ? invalidPackAsset<RenderPipelineAsset>(input, 'render-pipeline JSON descriptor artifact')\n : value === undefined\n ? invalidPackAsset<RenderPipelineAsset>(input, 'a complete render-pipeline descriptor')\n : { ok: true, value };\n },\n};\n\nexport const tilesetLoader: Loader = {\n kind: 'tileset',\n load: (payload, refs) => {\n const rawAtlases = payload.atlases;\n const resolved = Array.isArray(rawAtlases)\n ? rawAtlases.map((value) => (typeof value === 'number' ? refs?.[value] : value))\n : undefined;\n return resolved === undefined || resolved.some((value) => typeof value !== 'string')\n ? undefined\n : tilesetDescriptor({ ...payload, kind: 'tileset', atlases: resolved }, resolved);\n },\n loadPack: async (input) => {\n if (firstArtifact(input) === undefined) {\n const value = tilesetDescriptor({ ...input.payload, kind: 'tileset' }, input.refs);\n return value === undefined\n ? invalidPackAsset<TilesetAsset>(input, 'a valid tileset descriptor')\n : { ok: true, value };\n }\n const payload = readJsonArtifact(input, 'tileset');\n const value = payload === undefined ? undefined : tilesetDescriptor(payload, input.refs);\n return payload === undefined\n ? invalidPackAsset<TilesetAsset>(input, 'tileset JSON descriptor artifact')\n : value === undefined\n ? invalidPackAsset<TilesetAsset>(input, 'a tileset descriptor matching envelope refs')\n : { ok: true, value };\n },\n};\n\nexport const PACK_ARTIFACT_LOADERS: readonly Loader[] = [\n textureLoader,\n fontLoader,\n equirectLoader,\n renderPipelineLoader,\n tilesetLoader,\n];\n","// @forgeax/engine-assets-runtime -- inline pack-payload loader bodies\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport { PROCEDURAL_FLOATS_PER_VERTEX } from '@forgeax/engine-geometry';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type {\n AddressMode,\n AnimationChannel,\n AnimationGraph,\n AnimationGraphNode,\n Asset,\n AssetGuid as AssetGuidType,\n AudioClipAsset,\n CompareFunction,\n FilterMode,\n LoadContext,\n Loader,\n MaterialAsset,\n MaterialPass,\n MaterialTextureCoordinates,\n ParseErrorDetail,\n ParticleEffectAsset,\n MeshAsset as TypesMeshAsset,\n} from '@forgeax/engine-types';\nimport { resolveMaterialTextureCoordinates } from '@forgeax/engine-types';\nimport { MeshBinAssetError } from '../errors/asset';\nimport { parseScenePayload } from '../scene-payload';\nimport { unpackMeshBinV4 } from './mesh-bin';\nimport { renderPipelineLoader, tilesetLoader } from './pack-artifact';\n\n// === Inline pack-payload loader bodies (feat-20260603-asset-import-loader-injection\n// M1 / w4) ===\n//\n// The eight `if (kind === ...)` arms that lived inside\n// `AssetRegistry.parseAssetPayload` (research Finding 1) are extracted here as\n// module-level `{ kind, load }` objects so they register into a\n// `LoaderRegistry` (D-1) and can be imported by `wireDefaultLoaders` (w5). The\n// body logic is copied verbatim — M1 is a pure refactor (AC-03), no behavioural\n// change. Each parses an inline `.pack.json` payload synchronously and returns\n// the `Asset` POD or `undefined` (parse rejected). The `scene` arm routes its\n// structured out-of-bounds-ref error back through the LoaderOutput return\n// value instead of the old shared instance slot (D-8 channel replaced by F21).\n\n/** mesh loader — Float32Array / Uint16Array | Uint32Array normalisation -> MeshAsset.\n *\n * feat-20260611: skinIndex (Uint16Array) and skinWeight (Float32Array) accept\n * both their native typed-array shape (in-memory: dawn smoke / direct\n * `register` test) AND `number[]` (post-`JSON.stringify` shape produced by the\n * dev-server / build-mode pack-body round-trip — `JSON.stringify(pack) -> fetch\n * -> JSON.parse` flattens every typed array to a plain Array). Same dual\n * contract `skeletonLoader` / `animationClipLoader` already honour (PR #350);\n * without the array arm, every Fox.glb / Khronos skinned glTF surfaces as\n * `asset-parse-failed` on the browser path while dawn smoke stays green.\n */\nexport const meshLoader: Loader = {\n kind: 'mesh',\n load(payload) {\n const vertexData = payload.vertices;\n const indexData = payload.indices;\n const rawAttributes = (payload.attributes as Record<string, unknown> | undefined) ?? {};\n const attributes: Record<string, unknown> = { ...rawAttributes };\n const rawAabb = payload.aabb;\n let aabb: Float32Array | undefined;\n if (rawAabb instanceof Float32Array) {\n aabb = rawAabb;\n } else if (Array.isArray(rawAabb)) {\n aabb = new Float32Array(rawAabb as number[]);\n } else if (rawAabb !== undefined) {\n return undefined;\n }\n\n let morphTargets: TypesMeshAsset['morphTargets'];\n const rawMorphTargets = payload.morphTargets;\n if (rawMorphTargets !== undefined) {\n if (\n !Array.isArray(rawMorphTargets) ||\n rawMorphTargets.length < 1 ||\n rawMorphTargets.length > 8\n ) {\n return undefined;\n }\n const parsedTargets: NonNullable<TypesMeshAsset['morphTargets']>[number][] = [];\n for (const rawTarget of rawMorphTargets) {\n if (typeof rawTarget !== 'object' || rawTarget === null) return undefined;\n const source = rawTarget as Record<string, unknown>;\n const target: {\n position?: Float32Array;\n normal?: Float32Array;\n tangent?: Float32Array;\n } = {};\n for (const [key, value] of Object.entries(source)) {\n if (key !== 'position' && key !== 'normal' && key !== 'tangent') return undefined;\n if (value instanceof Float32Array) target[key] = new Float32Array(value);\n else if (Array.isArray(value)) target[key] = new Float32Array(value as number[]);\n else return undefined;\n }\n if (Object.keys(target).length === 0) return undefined;\n parsedTargets.push(target);\n }\n morphTargets = parsedTargets;\n }\n let morphWeights: Float32Array | undefined;\n const rawMorphWeights = payload.morphWeights;\n if (rawMorphWeights !== undefined) {\n if (rawMorphWeights instanceof Float32Array) morphWeights = new Float32Array(rawMorphWeights);\n else if (Array.isArray(rawMorphWeights))\n morphWeights = new Float32Array(rawMorphWeights as number[]);\n else return undefined;\n if (morphTargets !== undefined && morphWeights.length !== morphTargets.length)\n return undefined;\n }\n\n const skinIndexRaw = rawAttributes.skinIndex;\n if (skinIndexRaw instanceof Uint16Array) {\n attributes.skinIndex = skinIndexRaw;\n } else if (Array.isArray(skinIndexRaw)) {\n attributes.skinIndex = new Uint16Array(skinIndexRaw as number[]);\n } else if (skinIndexRaw !== undefined) {\n return undefined;\n }\n\n const skinWeightRaw = rawAttributes.skinWeight;\n if (skinWeightRaw instanceof Float32Array) {\n attributes.skinWeight = skinWeightRaw;\n } else if (Array.isArray(skinWeightRaw)) {\n attributes.skinWeight = new Float32Array(skinWeightRaw as number[]);\n } else if (skinWeightRaw !== undefined) {\n return undefined;\n }\n\n let vertices: Float32Array;\n let indices: Uint16Array | Uint32Array | undefined;\n\n if (vertexData instanceof Float32Array) {\n vertices = vertexData;\n } else if (Array.isArray(vertexData)) {\n vertices = new Float32Array(vertexData as number[]);\n } else {\n return undefined;\n }\n\n // bug-20260610: index width must follow vertex count, not a hard-coded\n // Uint16Array. A glTF mesh (e.g. Sponza, ~192k merged verts) overflows\n // Uint16; round-tripping through Uint16Array silently wraps and\n // `mesh-vertex-stride-mismatch` then fires because `maxIndex + 1` no\n // longer equals `vertexCount`. Mirrors `meshIrToMeshAsset` in\n // packages/gltf/src/bridge.ts which picks Uint32 above 0xffff.\n //\n // feat-20260612 M2 fixup: when the input carries an empty index array\n // (Fox.glb-style non-indexed primitives flattened through the mesh-bin\n // sidecar with `ilen=0`), drop the indices field rather than emit a\n // 0-byte typed array. The downstream `gpu-resource-store` chooses the\n // indexed-vs-vertex-only path on `mesh.indices !== undefined`; a 0-byte\n // typed array still satisfies !== undefined and triggers a 0-size IBO\n // allocation, whose `setIndexBuffer(buffer.slice(0..0), ...)` panics\n // wgpu's `BufferSlice` \"buffer slices can not be empty\" assertion.\n if (indexData instanceof Uint16Array || indexData instanceof Uint32Array) {\n indices = indexData.length > 0 ? indexData : undefined;\n } else if (Array.isArray(indexData)) {\n const arr = indexData as number[];\n if (arr.length === 0) {\n indices = undefined;\n } else {\n const vertexCount = vertices.length / PROCEDURAL_FLOATS_PER_VERTEX;\n const useUint32 = vertexCount > 0xffff;\n indices = useUint32 ? new Uint32Array(arr) : new Uint16Array(arr);\n }\n } else if (indexData === undefined) {\n indices = undefined;\n } else {\n return undefined;\n }\n\n // feat-20260608 M5 / w27: pack-payload mesh assets default to a single\n // triangle-list submesh covering the full index/vertex range. Inline\n // .pack.json mesh payloads do not carry submesh tables (single-prim\n // legacy shape); render code unconditionally reads `submeshes[0]`.\n // vertexCount stored as full vertices.length (downstream computes per-\n // attribute strides; submesh keeps the buffer-element-count for now).\n //\n // bug-20260610: when the payload carries an explicit `submeshes` table\n // (gltf importer emits one per primitive), respect it. The\n // `triangle-list 0..indices.length` default fits only single-prim packs.\n const payloadSubmeshes = payload.submeshes;\n const rawSubmeshes =\n Array.isArray(payloadSubmeshes) && payloadSubmeshes.length > 0\n ? (payloadSubmeshes as unknown as TypesMeshAsset['submeshes'])\n : [\n {\n indexOffset: 0,\n indexCount: indices?.length ?? 0,\n vertexCount: vertices.length,\n topology: 'triangle-list' as const,\n },\n ];\n const payloadSlots = payload.materialSlots;\n const materialSlots: TypesMeshAsset['materialSlots'] = Array.isArray(payloadSlots)\n ? payloadSlots.map((raw, slotIndex) => {\n if (typeof raw !== 'object' || raw === null)\n return { slotName: `LegacySlot_${slotIndex}` };\n const slot = raw as Record<string, unknown>;\n let defaultMaterial: AssetGuidType | undefined;\n if (slot.defaultMaterial instanceof Uint8Array) {\n defaultMaterial = slot.defaultMaterial as AssetGuidType;\n } else if (typeof slot.defaultMaterial === 'string') {\n const parsed = AssetGuid.parse(slot.defaultMaterial);\n if (!parsed.ok) return { slotName: `LegacySlot_${slotIndex}` };\n defaultMaterial = parsed.value;\n }\n return {\n slotName:\n typeof slot.slotName === 'string' && slot.slotName.trim().length > 0\n ? slot.slotName\n : `LegacySlot_${slotIndex}`,\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n ...(defaultMaterial !== undefined ? { defaultMaterial } : {}),\n };\n })\n : rawSubmeshes.map((_, slotIndex) => ({ slotName: `LegacySlot_${slotIndex}` }));\n const submeshes = rawSubmeshes.map((submesh, submeshIndex) => ({\n ...submesh,\n materialSlot: Number.isInteger((submesh as { materialSlot?: unknown }).materialSlot)\n ? (submesh as { materialSlot: number }).materialSlot\n : submeshIndex,\n }));\n\n return {\n kind: 'mesh',\n vertices,\n ...(indices !== undefined ? { indices } : {}),\n attributes: attributes as TypesMeshAsset['attributes'],\n ...(aabb !== undefined ? { aabb } : {}),\n ...(morphTargets !== undefined ? { morphTargets } : {}),\n ...(morphWeights !== undefined ? { morphWeights } : {}),\n submeshes,\n materialSlots,\n };\n },\n loadPack(input, ctx) {\n const artifact = input.artifacts.body;\n if (artifact === undefined) return meshLoader.load(input.payload, input.refs, ctx);\n const decoded = unpackMeshBinV4(artifact.bytes, input.guid);\n if (!decoded.ok) return { ok: false, error: decoded.error } as never;\n const materialSlots = decoded.value.materialSlots.map((slot) => {\n const refIndex = slot.defaultMaterialRef;\n const ref = refIndex === undefined ? undefined : input.refs[refIndex];\n if (refIndex !== undefined && ref === undefined) return undefined;\n if (ref === undefined) {\n return {\n slotName: String(slot.slotName),\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n };\n }\n const parsed = AssetGuid.parse(ref);\n if (!parsed.ok) return undefined;\n return {\n slotName: String(slot.slotName),\n ...(typeof slot.sourceKey === 'string' ? { sourceKey: slot.sourceKey } : {}),\n defaultMaterial: parsed.value,\n };\n });\n if (materialSlots.some((slot) => slot === undefined)) {\n return {\n ok: false,\n error: new MeshBinAssetError({\n sourceKey: input.guid,\n expected: 'material slot references must resolve through the pack refs table',\n actual: 'material reference is out of bounds or is not a valid AssetGuid',\n reason: 'metadata-invalid',\n actualFacts: { field: 'metadata' },\n }),\n } as never;\n }\n return meshLoader.load(\n {\n vertices: decoded.value.vertices,\n ...(decoded.value.indices !== undefined ? { indices: decoded.value.indices } : {}),\n submeshes: decoded.value.submeshes,\n materialSlots,\n ...(decoded.value.aabb !== undefined ? { aabb: decoded.value.aabb } : {}),\n ...(decoded.value.morphTargets !== undefined\n ? { morphTargets: decoded.value.morphTargets }\n : {}),\n ...(decoded.value.morphWeights !== undefined\n ? { morphWeights: decoded.value.morphWeights }\n : {}),\n attributes: decoded.value.attributes,\n },\n input.refs,\n ctx,\n );\n },\n};\n\n/** scene loader — delegates to parseScenePayload; routes structured ref error via ctx. */\nexport const sceneLoader: Loader = {\n kind: 'scene',\n load(payload, refs, _ctx: LoadContext) {\n const result = parseScenePayload(payload, refs === undefined ? undefined : [...refs]);\n if (result === undefined) return undefined;\n // Structured ParseSceneError (has an `index` field absent on SceneAsset):\n // return it inline through LoaderOutput so the caller (parseAndReturnAsset)\n // can build a precise AssetError without a shared instance slot (F21).\n if ('index' in result) {\n return { ok: false, error: result as ParseErrorDetail };\n }\n return result as Asset;\n },\n};\n\n/**\n * feat-20260613-material-paramschema-driven-binding M4 / w22 (D-5 graceful):\n * the legacy hardcoded texture-field allowlist Set has been removed\n * (AC-03). The materialLoader now consults `ctx.getMaterialShaderTextureFieldNames`\n * (paramSchema-derived via derive()) to know which values fields carry\n * refs[] indices. When the shader is not yet registered (cross-worktree\n * shader-late-register path, plan R-4), the loader falls back to attempting\n * resolution on every int-typed paramValue in [0, refs.length) — M4 / w23's\n * extract-layer paramSchema validation catches misclassifications and routes\n * unresolved texture slots through `MISSING_TEXTURE_HANDLE`.\n */\nfunction collectShaderTextureFieldNames(\n passesFromPayload: unknown,\n ctx: LoadContext,\n): ReadonlySet<string> | undefined {\n if (!Array.isArray(passesFromPayload) || passesFromPayload.length === 0) return undefined;\n const lookup = ctx.getMaterialShaderTextureFieldNames;\n if (lookup === undefined) return undefined;\n const collected = new Set<string>();\n let anyResolved = false;\n for (const pass of passesFromPayload) {\n const shaderId = (pass as { program?: { module?: unknown } }).program?.module;\n if (typeof shaderId !== 'string' || shaderId.length === 0) continue;\n const fields = lookup(shaderId);\n if (fields === undefined) continue;\n anyResolved = true;\n for (const name of fields) collected.add(name);\n }\n return anyResolved ? collected : undefined;\n}\n\nfunction refGuidAt(refs: readonly unknown[] | undefined, index: number): string | undefined {\n if (!Number.isInteger(index) || index < 0 || index >= (refs?.length ?? 0)) return undefined;\n const guid = refs?.[index];\n if (typeof guid === 'string') return guid;\n if (typeof guid === 'object' && guid !== null && 'guid' in guid) {\n const nestedGuid = (guid as { guid?: unknown }).guid;\n return typeof nestedGuid === 'string' ? nestedGuid : undefined;\n }\n return undefined;\n}\n\nfunction isIdentityTextureCoordinates(value: unknown): boolean {\n if (value === undefined) return true;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const coordinates = value as Record<string, unknown>;\n if (Object.keys(coordinates).some((key) => key !== 'set' && key !== 'transform')) return false;\n const transform = coordinates.transform;\n if (\n transform !== undefined &&\n (typeof transform !== 'object' || transform === null || Array.isArray(transform))\n ) {\n return false;\n }\n if (\n transform !== undefined &&\n Object.keys(transform as Record<string, unknown>).some(\n (key) => key !== 'offset' && key !== 'scale' && key !== 'rotation',\n )\n ) {\n return false;\n }\n const resolved = resolveMaterialTextureCoordinates(coordinates as MaterialTextureCoordinates);\n return (\n resolved.set === 0 &&\n resolved.transform.offset[0] === 0 &&\n resolved.transform.offset[1] === 0 &&\n resolved.transform.scale[0] === 1 &&\n resolved.transform.scale[1] === 1 &&\n resolved.transform.rotation === 0\n );\n}\n\nfunction compactTextureValue(value: Record<string, unknown>): unknown {\n const compact = { ...value };\n if (isIdentityTextureCoordinates(compact.coordinates)) delete compact.coordinates;\n return compact;\n}\n\n/** material loader — passes + values + serialized parent GUID -> parentGuid. */\nexport const materialLoader: Loader = {\n kind: 'material',\n load(payload, refs, ctx: LoadContext) {\n const matPayload = payload;\n const passesFromPayload = matPayload.passes;\n const rawParamValues = (matPayload.values as Record<string, unknown>) ?? {};\n\n let parentGuid: string | undefined;\n if (typeof matPayload.parent === 'string') {\n parentGuid = matPayload.parent;\n } else if (typeof matPayload.parent === 'number') {\n const idx = matPayload.parent;\n const refsArr = refs ?? [];\n if (idx >= 0 && idx < refsArr.length) {\n parentGuid = refGuidAt(refsArr, idx);\n }\n if (parentGuid === undefined) {\n return undefined;\n }\n }\n\n // bug-20260610: values fields that are typed `handle<TextureAsset>`\n // arrive on disk as a refs[] index (small int 0..refs.length-1). The\n // build-time gltfImporter writes these as refs indices, mirroring the\n // scene's HANDLE_FIELD_NAMES treatment.\n //\n // feat-20260613-material-paramschema-driven-binding M4 / w22 (D-5 graceful):\n // texture-field discovery now derives from the registered shader's\n // paramSchema via `ctx.getMaterialShaderTextureFieldNames`. When the\n // shader is registered (the common case), only declared texture fields\n // are resolved — identical to the old hardcoded-Set behaviour without the\n // SSOT duplication. Authored material parameters are an equally valid\n // schema source and remain available before shader registration; this is\n // what keeps a scalar zero (for example metallic) distinct from texture\n // ref index zero. Only legacy payloads with neither schema retain the\n // try-every-integer fallback.\n const values: Record<string, unknown> = { ...rawParamValues };\n if (refs && refs.length > 0) {\n const shaderTextureFields = collectShaderTextureFieldNames(passesFromPayload, ctx);\n const authoredTextureFields = Array.isArray(matPayload.parameters)\n ? new Set(\n matPayload.parameters\n .filter(\n (parameter): parameter is { name: string; type: string } =>\n typeof parameter === 'object' &&\n parameter !== null &&\n 'name' in parameter &&\n typeof parameter.name === 'string' &&\n 'type' in parameter &&\n parameter.type === 'texture',\n )\n .map((parameter) => parameter.name),\n )\n : undefined;\n const textureFields =\n authoredTextureFields !== undefined\n ? new Set([...(shaderTextureFields ?? []), ...authoredTextureFields])\n : shaderTextureFields;\n // Walk every value so the structured MaterialTextureValue shape remains\n // resolvable even when a shader is registered with an empty/late\n // paramSchema (pbr-skin currently takes this path). Scalar values still\n // require schema membership below, so metallic/roughness integers are\n // never mistaken for refs indices merely because the schema is empty.\n const candidateFields = Object.keys(values);\n for (const fieldName of candidateFields) {\n const value = values[fieldName];\n if (typeof value === 'number' && Number.isInteger(value)) {\n if (textureFields !== undefined && !textureFields.has(fieldName)) {\n continue;\n }\n const refGuid = refGuidAt(refs, value);\n if (refGuid === undefined) {\n // Only emit a parse-error breadcrumb when the field is declared as\n // a texture by the shader paramSchema (the OOB is unambiguous).\n // For the graceful \"try every int\" fallback, OOB simply means\n // \"this scalar was not a refs index\" — don't spam parse errors.\n if (textureFields !== undefined) delete values[fieldName];\n continue;\n }\n values[fieldName] = textureFields === undefined ? refGuid : { texture: refGuid };\n continue;\n }\n\n // glTF materials use the engine's structured MaterialTextureValue\n // shape (`{ texture: <refs index> }`), not the legacy scalar form.\n // Resolve that nested index at the same loader boundary; leaving zero\n // here is a valid-looking handle that silently renders the material\n // white and never reaches the browser console as an exception.\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const textureIndex = (value as { texture?: unknown }).texture;\n if (typeof textureIndex !== 'number' || !Number.isInteger(textureIndex)) continue;\n const textureGuid = refGuidAt(refs, textureIndex);\n if (textureGuid === undefined) {\n if (textureFields !== undefined) delete values[fieldName];\n continue;\n }\n const resolved: Record<string, unknown> = {\n ...(value as Record<string, unknown>),\n texture: textureGuid,\n };\n const samplerIndex = resolved.sampler;\n if (typeof samplerIndex === 'number' && Number.isInteger(samplerIndex)) {\n const samplerGuid = refGuidAt(refs, samplerIndex);\n if (samplerGuid === undefined) delete resolved.sampler;\n else resolved.sampler = samplerGuid;\n }\n values[fieldName] = compactTextureValue(resolved);\n }\n }\n }\n\n if (Array.isArray(passesFromPayload) && passesFromPayload.length > 0) {\n return {\n kind: 'material',\n passes: passesFromPayload as readonly MaterialPass[],\n parameters: matPayload.parameters,\n values,\n colorSpace: matPayload.colorSpace,\n parentGuid,\n } as MaterialAsset & { parentGuid?: string };\n }\n\n if (parentGuid !== undefined) {\n return {\n kind: 'material',\n parameters: matPayload.parameters,\n values,\n colorSpace: matPayload.colorSpace,\n parentGuid,\n } as unknown as MaterialAsset & { parentGuid?: string };\n }\n\n return undefined;\n },\n};\n\n/** sampler loader — preserve the serialised SamplerAsset descriptor. */\nexport const samplerLoader: Loader = {\n kind: 'sampler',\n load(payload) {\n const filters = new Set<FilterMode>(['nearest', 'linear']);\n const mipmapFilters = new Set<GPUMipmapFilterMode>(['nearest', 'linear']);\n const addressModes = new Set<AddressMode>(['clamp-to-edge', 'repeat', 'mirror-repeat']);\n const compareFunctions = new Set<CompareFunction>([\n 'never',\n 'less',\n 'equal',\n 'less-equal',\n 'greater',\n 'not-equal',\n 'greater-equal',\n 'always',\n ]);\n const stringField = <T extends string>(\n key: string,\n allowed: ReadonlySet<T>,\n ): T | undefined | null => {\n const value = payload[key];\n if (value === undefined) return undefined;\n return typeof value === 'string' && allowed.has(value as T) ? (value as T) : null;\n };\n const magFilter = stringField('magFilter', filters);\n const minFilter = stringField('minFilter', filters);\n const mipmapFilter = stringField('mipmapFilter', mipmapFilters);\n const addressModeU = stringField('addressModeU', addressModes);\n const addressModeV = stringField('addressModeV', addressModes);\n const addressModeW = stringField('addressModeW', addressModes);\n const compare = stringField('compare', compareFunctions);\n if (\n magFilter === null ||\n minFilter === null ||\n mipmapFilter === null ||\n addressModeU === null ||\n addressModeV === null ||\n addressModeW === null ||\n compare === null\n ) {\n return undefined;\n }\n const numericField = (key: string): number | undefined | null => {\n const value = payload[key];\n if (value === undefined) return undefined;\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n };\n const lodMinClamp = numericField('lodMinClamp');\n const lodMaxClamp = numericField('lodMaxClamp');\n const maxAnisotropy = numericField('maxAnisotropy');\n if (lodMinClamp === null || lodMaxClamp === null || maxAnisotropy === null) return undefined;\n return {\n kind: 'sampler',\n ...(magFilter === undefined ? {} : { magFilter }),\n ...(minFilter === undefined ? {} : { minFilter }),\n ...(mipmapFilter === undefined ? {} : { mipmapFilter }),\n ...(addressModeU === undefined ? {} : { addressModeU }),\n ...(addressModeV === undefined ? {} : { addressModeV }),\n ...(addressModeW === undefined ? {} : { addressModeW }),\n ...(lodMinClamp === undefined ? {} : { lodMinClamp }),\n ...(lodMaxClamp === undefined ? {} : { lodMaxClamp }),\n ...(compare === undefined ? {} : { compare }),\n ...(maxAnisotropy === undefined ? {} : { maxAnisotropy }),\n };\n },\n};\n\n/** skeleton loader — inverseBindMatrices stride validation.\n *\n * bug-20260611: accept both `Float32Array` (in-memory: dawn smoke / direct\n * `register` test) AND `number[]` (post-`JSON.stringify` shape: `normaliseForPack`\n * in @forgeax/engine-import flattens every typed array to a plain Array so\n * `JSON.stringify(pack)` survives the dev-server / build-mode round-trip --\n * the same dual contract `meshLoader` already honours). Without the array arm\n * the .pack.json -> fetch -> JSON.parse path lands a plain object whose\n * `instanceof Float32Array` check fails, surfacing as `asset-parse-failed`\n * for any glTF carrying a Skin (e.g. Khronos Fox.glb).\n */\nexport const skeletonLoader: Loader = {\n kind: 'skeleton',\n load(payload) {\n const ibmRaw = payload.inverseBindMatrices;\n const jointCount = typeof payload.jointCount === 'number' ? payload.jointCount : 0;\n let ibm: Float32Array;\n if (ibmRaw instanceof Float32Array) {\n ibm = ibmRaw;\n } else if (Array.isArray(ibmRaw)) {\n ibm = new Float32Array(ibmRaw as number[]);\n } else {\n return undefined;\n }\n if (ibm.byteLength !== jointCount * 64) return undefined;\n return {\n kind: 'skeleton',\n inverseBindMatrices: ibm,\n jointCount,\n };\n },\n};\n\n/** skin loader — skeletonGuid + jointPaths validation. */\nexport const skinLoader: Loader = {\n kind: 'skin',\n load(payload) {\n const skeletonGuid = payload.skeletonGuid;\n const jointPathsRaw = payload.jointPaths;\n if (typeof skeletonGuid !== 'string') return undefined;\n if (!Array.isArray(jointPathsRaw)) return undefined;\n const jointPaths: string[] = [];\n for (const item of jointPathsRaw) {\n if (typeof item !== 'string') return undefined;\n jointPaths.push(item);\n }\n return { kind: 'skin', skeletonGuid, jointPaths };\n },\n};\n\n/** animation-clip loader — channels / sampler validation.\n *\n * bug-20260611: sampler.input / sampler.output accept both `Float32Array`\n * (in-memory) and `number[]` (post-`JSON.stringify` shape produced by\n * `normaliseForPack`). Same dual contract as `skeletonLoader` /\n * `meshLoader`; without it the dev `.pack.json` round-trip surfaces every\n * skinned-with-animation glTF as `asset-parse-failed`.\n */\nexport const animationClipLoader: Loader = {\n kind: 'animation-clip',\n load(payload) {\n const duration = typeof payload.duration === 'number' ? payload.duration : 0;\n const channelsRaw = payload.channels;\n if (!Array.isArray(channelsRaw)) return undefined;\n const channels: AnimationChannel[] = [];\n for (const ch of channelsRaw) {\n if (typeof ch !== 'object' || ch === null) return undefined;\n const chObj = ch as Record<string, unknown>;\n const targetId = chObj.targetId;\n const property = chObj.property;\n const samplerObj = chObj.sampler as Record<string, unknown> | undefined;\n if (\n typeof targetId !== 'string' ||\n !/^[0-9a-f]{32}$/.test(targetId) ||\n Object.keys(chObj).some(\n (key) => key !== 'targetId' && key !== 'property' && key !== 'sampler',\n )\n ) {\n return undefined;\n }\n if (\n property !== 'translation' &&\n property !== 'rotation' &&\n property !== 'scale' &&\n property !== 'weights'\n )\n return undefined;\n if (samplerObj === undefined) return undefined;\n const inputRaw = samplerObj.input;\n const outputRaw = samplerObj.output;\n const interpolation = samplerObj.interpolation;\n let input: Float32Array;\n if (inputRaw instanceof Float32Array) {\n input = inputRaw;\n } else if (Array.isArray(inputRaw)) {\n input = new Float32Array(inputRaw as number[]);\n } else {\n return undefined;\n }\n let output: Float32Array;\n if (outputRaw instanceof Float32Array) {\n output = outputRaw;\n } else if (Array.isArray(outputRaw)) {\n output = new Float32Array(outputRaw as number[]);\n } else {\n return undefined;\n }\n if (interpolation !== 'LINEAR' && interpolation !== 'STEP') return undefined;\n channels.push({\n targetId: targetId as AnimationChannel['targetId'],\n property: property as AnimationChannel['property'],\n sampler: { input, output, interpolation },\n });\n }\n return { kind: 'animation-clip', duration, channels };\n },\n};\n\n/** animation-graph loader — pack payload -> AnimationGraph POD.\n *\n * feat-20260713-animation-state-machine-plugin M4 / w30 (plan D-4 landing (3)):\n * the inverse of `serializeAnimationGraph` (runtime). Each Clip leaf's `clip`\n * field arrives as a `refs[]` index (small int); the loader resolves it back to\n * the GUID string verbatim, leaving GUID -> handle re-resolution to the ECS/use\n * time (the same \"GUID at load, handle at use\" contract materialLoader honours\n * for parentGuid / values texture fields, asset-registry D-19). Blend/Add\n * node references + `root` are intra-graph node indices, validated against the\n * node count. A malformed payload (out-of-range refs / node index, bad node\n * shape, non-finite weight) returns `undefined` so the load-by-guid path\n * surfaces the existing `asset-parse-failed` error code (AC-14).\n *\n * OOS-7: reconstructs only an engine-authored graph's topology; no DCC-import\n * metadata is consumed.\n */\nexport const animationGraphLoader: Loader = {\n kind: 'animation-graph',\n load(payload, refs) {\n const rawNodes = payload.nodes;\n const root = payload.root;\n if (!Array.isArray(rawNodes)) return undefined;\n const nodeCount = rawNodes.length;\n const isNodeIndex = (value: unknown): value is number =>\n typeof value === 'number' && Number.isInteger(value) && value >= 0 && value < nodeCount;\n if (!isNodeIndex(root)) return undefined;\n const refsArr = refs ?? [];\n\n const nodes: AnimationGraphNode[] = [];\n for (const rawNode of rawNodes) {\n if (typeof rawNode !== 'object' || rawNode === null) return undefined;\n const node = rawNode as Record<string, unknown>;\n const weight = node.weight;\n if (typeof weight !== 'number' || !Number.isFinite(weight)) return undefined;\n\n if (node.type === 'clip') {\n const refIndex = node.clip;\n if (typeof refIndex !== 'number' || !Number.isInteger(refIndex)) return undefined;\n if (refIndex < 0 || refIndex >= refsArr.length) return undefined;\n const guid = refsArr[refIndex];\n if (typeof guid !== 'string') return undefined;\n // GUID verbatim at load; re-resolved to a handle at use time (D-19).\n nodes.push({\n type: 'clip',\n clip: guid,\n weight,\n });\n } else if (node.type === 'blend') {\n const children = node.children;\n if (!Array.isArray(children) || !children.every(isNodeIndex)) return undefined;\n nodes.push({ type: 'blend', children: [...(children as number[])], weight });\n } else if (node.type === 'add') {\n const base = node.base;\n const additive = node.additive;\n if (!isNodeIndex(base)) return undefined;\n if (!Array.isArray(additive) || !additive.every(isNodeIndex)) return undefined;\n nodes.push({ type: 'add', base, additive: [...(additive as number[])], weight });\n } else {\n return undefined;\n }\n }\n\n return { kind: 'animation-graph', nodes, root } as AnimationGraph;\n },\n};\n\n/** audio loader -- restore the durable descriptor; host decode stays elsewhere. */\nexport const audioLoader: Loader = {\n kind: 'audio',\n load(payload) {\n const sourceKey = payload.sourceKey;\n const mediaType = payload.mediaType;\n if (typeof sourceKey !== 'string' || sourceKey.length === 0) return undefined;\n if (typeof mediaType !== 'string' || mediaType.length === 0) return undefined;\n const rawBytes = payload.bytes;\n const bytes =\n rawBytes instanceof Uint8Array\n ? rawBytes\n : Array.isArray(rawBytes)\n ? new Uint8Array(rawBytes as number[])\n : undefined;\n return {\n kind: 'audio',\n sourceKey,\n mediaType,\n ...(bytes === undefined ? {} : { bytes }),\n } as AudioClipAsset;\n },\n};\n\n/** particle loader -- restore the complete cooked program without a GPU device. */\nexport const particleEffectLoader: Loader = {\n kind: 'particle-effect',\n load(payload) {\n if (typeof payload.program !== 'object' || payload.program === null) return undefined;\n if (typeof (payload.program as Record<string, unknown>).fingerprint !== 'string') {\n return undefined;\n }\n return { ...payload, kind: 'particle-effect' } as ParticleEffectAsset;\n },\n};\n\nexport { renderPipelineLoader, tilesetLoader } from './pack-artifact';\n\n/**\n * The eight inline pack-payload loaders, in the historical `if`-chain order\n * (the animation-graph loader, feat-20260713 M4 / w30, appends after the clip\n * loader). `wireDefaultLoaders` (w5) registers these plus the texture / font /\n * equirect loaders (w6) and the audio placeholder (w8).\n */\nexport const INLINE_PACK_LOADERS: readonly Loader[] = [\n meshLoader,\n sceneLoader,\n samplerLoader,\n materialLoader,\n skeletonLoader,\n skinLoader,\n animationClipLoader,\n animationGraphLoader,\n renderPipelineLoader,\n tilesetLoader,\n audioLoader,\n particleEffectLoader,\n];\n","// @forgeax/engine-assets-runtime - wireDefaultLoaders + seed-table SSOT\n// (feat-20260603-asset-import-loader-injection M1 / w5 + w8; restructured by\n// feat-20260705-runtime-tier2-decomposition M1 / w8, D-2).\n//\n// wireDefaultLoaders is a one-line host helper that wires the engine's default\n// loader set onto a `LoaderRegistry`, mirroring the Console\n// `wireDefaultInspectors` shape (packages/console/src/wire-default-inspectors.ts;\n// research Finding 8). An AI user that has wired inspectors once recognises the\n// same form here at near-zero cost (requirements §AI User Affordances).\n//\n// The two seed tables INLINE_PACK_LOADERS + PACK_ARTIFACT_LOADERS are the\n// default set. videoLoader lives in graphics-extras and is wired here. The\n// complete ordinary Asset vocabulary is registered once at this boundary;\n// host-specific loaders may extend the table through `extraLoaders`.\n//\n// Default set wired internally: the 16 ordinary Asset kinds plus the existing\n// UI consumer loader. Host-only execution remains separate from descriptor load.\n//\nimport { videoLoader } from '@forgeax/engine-graphics-extras';\nimport type { Loader } from '@forgeax/engine-types';\nimport { createUiLoader, type UiAsset } from '@forgeax/engine-ui';\nimport { LoaderRegistry } from './loader-registry';\nimport { INLINE_PACK_LOADERS } from './loaders/inline-pack';\nimport { PACK_ARTIFACT_LOADERS } from './loaders/pack-artifact';\n\nconst uiPayloadLoader = createUiLoader();\nconst uiLoader: Loader<UiAsset> = {\n kind: 'ui',\n load: (payload) => {\n const result = uiPayloadLoader.load(payload);\n return result.ok ? result.value : undefined;\n },\n};\n\n/**\n * Wire the engine's default loader set (16 ordinary kinds plus UI) plus any\n * `extraLoaders` onto `registry` in\n * one call. Returns the same `registry` for chaining (so `wireDefaultLoaders(new\n * LoaderRegistry())` is a one-expression wired registry). The `extraLoaders` are\n * appended after the defaults and must use kinds outside the ordinary set.\n *\n * @example\n * ```ts\n * import { LoaderRegistry, wireDefaultLoaders } from '@forgeax/engine-assets-runtime';\n * const loaders = wireDefaultLoaders(new LoaderRegistry());\n * // loaders.get('mesh') / .get('texture') / .get('font') / .get('video') are\n * // non-undefined; all ordinary Asset kinds share this same owner table.\n * ```\n */\nexport function wireDefaultLoaders(\n registry: LoaderRegistry,\n extraLoaders: readonly Loader[] = [],\n): LoaderRegistry {\n const extraKinds = new Set(extraLoaders.map((loader) => loader.kind));\n const seeded = new Set<string>();\n for (const loader of [...INLINE_PACK_LOADERS, ...PACK_ARTIFACT_LOADERS]) {\n if (extraKinds.has(loader.kind)) continue;\n if (seeded.has(loader.kind)) continue;\n seeded.add(loader.kind);\n registry.register(loader);\n }\n registry.register(videoLoader);\n registry.register(uiLoader);\n for (const loader of extraLoaders) registry.register(loader);\n return registry;\n}\n\n/**\n * Convenience factory: a fresh `LoaderRegistry` pre-wired with the default\n * loader set (plus any `extraLoaders`). The production assembly point\n * (`createRenderer`) and tests pass the result into `new LoaderRegistry()` (D-7\n * constructor-injection; loaders always wired at construction -- used by\n * `AssetRegistry` internally via `createDefaultLoaderRegistry(extraLoaders)` and\n * by host code / tests independently) -- no setter / no illegal intermediate\n * state).\n */\nexport function createDefaultLoaderRegistry(extraLoaders: readonly Loader[] = []): LoaderRegistry {\n return wireDefaultLoaders(new LoaderRegistry(), extraLoaders);\n}\n","// @forgeax/engine-assets-runtime — mesh AABB computation (feat-20260705-runtime-tier2-\n// decomposition M1 / w4, D-4 F1 straight-cut). Pure move from asset-registry.ts;\n// zero identifier changes. computeAABB / emptyBox / withMeshAabb travel with the\n// asset cluster into @forgeax/engine-assets-runtime (w13).\n\nimport type { MeshAsset as TypesMeshAsset } from '@forgeax/engine-types';\n\n/**\n * Compute the local-space AABB of a mesh from its position attribute.\n *\n * Reads every third float from the position buffer as (x, y, z) and computes\n * [minX, minY, minZ, maxX, maxY, maxZ]. When position is absent, empty, or\n * less than 3 floats, returns an inverted-infinity empty box ([+Inf,+Inf,+Inf,\n * -Inf,-Inf,-Inf]) — consumers interpret this as \"always-visible\" (no culling).\n *\n * The position attribute can be Float32Array, ArrayBuffer (re-wrapped as\n * Float32Array), or Uint16Array (unlikely for position data; treated as\n * absent). Empty vertices (0 x 12 = 0) also produce empty box.\n *\n * Anchors: plan-strategy D-7 (register-time computation); D-1 (Float32Array\n * bare type); requirements AC-02 (empty -> inverted-infinity).\n */\nfunction computeAABB(asset: TypesMeshAsset): Float32Array {\n const pos = asset.attributes.position;\n // Convert to Float32Array if possible; bail to empty-box otherwise.\n let floatPos: Float32Array;\n if (pos instanceof Float32Array) {\n floatPos = pos;\n } else if (pos instanceof ArrayBuffer) {\n floatPos = new Float32Array(pos);\n } else {\n return emptyBox();\n }\n if (floatPos.length < 3) return emptyBox();\n\n let minX = floatPos[0] ?? 0;\n let minY = floatPos[1] ?? 0;\n let minZ = floatPos[2] ?? 0;\n let maxX = minX;\n let maxY = minY;\n let maxZ = minZ;\n for (let i = 3; i < floatPos.length; i += 3) {\n const x = floatPos[i] ?? 0;\n const y = floatPos[i + 1] ?? 0;\n const z = floatPos[i + 2] ?? 0;\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (z < minZ) minZ = z;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n if (z > maxZ) maxZ = z;\n }\n return Float32Array.of(minX, minY, minZ, maxX, maxY, maxZ);\n}\n\nfunction emptyBox(): Float32Array {\n return Float32Array.of(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity);\n}\n\nfunction hasPositionData(position: unknown): boolean {\n if (position instanceof Float32Array) return position.length >= 3;\n return (\n position instanceof ArrayBuffer && position.byteLength >= 3 * Float32Array.BYTES_PER_ELEMENT\n );\n}\n\nfunction isFiniteAabb(aabb: unknown): aabb is Float32Array {\n if (!(aabb instanceof Float32Array) || aabb.length !== 6) return false;\n for (const value of aabb) {\n if (!Number.isFinite(value)) return false;\n }\n const minX = aabb[0];\n const minY = aabb[1];\n const minZ = aabb[2];\n const maxX = aabb[3];\n const maxY = aabb[4];\n const maxZ = aabb[5];\n return (\n minX !== undefined &&\n minY !== undefined &&\n minZ !== undefined &&\n maxX !== undefined &&\n maxY !== undefined &&\n maxZ !== undefined &&\n minX <= maxX &&\n minY <= maxY &&\n minZ <= maxZ\n );\n}\n\n// Assigns the computed AABB to the mesh in place when the object is\n// extensible; falls back to a shallow copy when frozen / sealed (e.g.\n// BUILTIN_CUBE / BUILTIN_TRIANGLE / BUILTIN_QUAD reused via registerWithGuid).\nexport function withMeshAabb(asset: TypesMeshAsset): TypesMeshAsset {\n // Packed mesh binaries intentionally omit `attributes.position`; their\n // producer-computed AABB is the only available culling fact. Preserve it\n // instead of replacing it with the empty-box result from computeAABB().\n if (!hasPositionData(asset.attributes.position) && isFiniteAabb(asset.aabb)) {\n return asset;\n }\n const aabb = computeAABB(asset);\n if (Object.isExtensible(asset)) {\n (asset as { aabb: Float32Array }).aabb = aabb;\n return asset;\n }\n return { ...asset, aabb };\n}\n","import type { ShaderRegistry } from '@forgeax/engine-shader';\nimport type { MaterialParameter, ParamSchemaEntry } from '@forgeax/engine-types';\nimport type { MaterialReady } from './loader';\n\nconst ENGINE_INJECTED_TEXTURE_FIELDS = new Set(['emissiveTexture', 'occlusionTexture']);\n\nfunction isStandardPbrMaterialShader(shaderId: string): boolean {\n return (\n shaderId === 'forgeax::default-standard-pbr' ||\n shaderId === 'forgeax::pbr-skin' ||\n shaderId === 'forgeax::default-standard-pbr-skin'\n );\n}\n\n/** Project authored MaterialAsset parameters into the runtime shader schema. */\nexport function materialParametersToParamSchema(\n parameters: readonly MaterialParameter[],\n shaderId: string | undefined,\n): readonly ParamSchemaEntry[] {\n const engineInjectedTextureFields =\n shaderId !== undefined && isStandardPbrMaterialShader(shaderId)\n ? ENGINE_INJECTED_TEXTURE_FIELDS\n : undefined;\n return parameters.flatMap((parameter): ParamSchemaEntry[] => {\n if (parameter.type === 'bool') return [];\n if (parameter.type === 'texture') {\n if (engineInjectedTextureFields?.has(parameter.name) === true) return [];\n return [{ name: parameter.name, type: 'texture2d' }];\n }\n const defaultValue = parameter.default;\n const numericDefault =\n typeof defaultValue === 'number' ||\n (Array.isArray(defaultValue) && defaultValue.every((item) => typeof item === 'number'))\n ? { default: defaultValue }\n : {};\n return [\n {\n name: parameter.name,\n type: parameter.type,\n ...(parameter.colorSpace === undefined ? {} : { colorSpace: parameter.colorSpace }),\n ...numericDefault,\n },\n ];\n });\n}\n\n/** Project authored pass module ids onto the renderer's canonical ids. */\nexport function runtimeMaterialShaderId(\n module: string | undefined,\n passName?: string,\n): string | undefined {\n if (\n passName === 'shadow-caster' &&\n (module === 'forgeax_material::standard' ||\n module === 'forgeax_material::unlit' ||\n module === 'forgeax::default-standard-pbr' ||\n module === 'forgeax::default-unlit')\n ) {\n return 'forgeax::default-shadow-caster';\n }\n switch (module) {\n case 'forgeax_material::standard':\n return 'forgeax::default-standard-pbr';\n case 'forgeax_material::unlit':\n return 'forgeax::default-unlit';\n case 'forgeax_material::sprite':\n return 'forgeax::sprite';\n case 'forgeax_material::sprite-lit':\n return 'forgeax::sprite-lit';\n default:\n return module;\n }\n}\n\nfunction sameSchema(\n left: readonly ParamSchemaEntry[],\n right: readonly ParamSchemaEntry[],\n): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction isManifestVariantSource(\n shaderRegistry: ShaderRegistry,\n identifier: string,\n source: string,\n): boolean {\n const entry = Array.from(shaderRegistry.materialShaderManifestEntries()).find(\n (candidate) => candidate.identifier === identifier,\n );\n return (\n entry?.composedWgsl === source ||\n entry?.variants.some((variant) => variant.composedWgsl === source) === true\n );\n}\n\n/**\n * Install every authored pass module from one validated MaterialReady tuple.\n * The publication artifact is the only runtime shader source; no host entry\n * point is allowed to assemble or register the material separately.\n */\nexport function installMaterialReadyShaders(\n shaderRegistry: ShaderRegistry,\n readiness: MaterialReady,\n): void {\n const source = new TextDecoder().decode(readiness.artifact.bytes);\n if (source.length === 0) {\n throw new Error(\n `MaterialReady ${readiness.guid} published an empty ${readiness.artifact.mediaType} shader artifact`,\n );\n }\n for (const pass of readiness.record.resolved.passes) {\n const identifier = runtimeMaterialShaderId(pass.program.module, pass.name);\n if (identifier === undefined) continue;\n const paramSchema = materialParametersToParamSchema(\n readiness.parameterContract.parameters,\n identifier,\n );\n const existing = shaderRegistry.findMaterialArtifact(identifier);\n if (existing.ok) {\n if (\n !sameSchema(existing.value.paramSchema, paramSchema) ||\n (existing.value.source !== source &&\n !isManifestVariantSource(shaderRegistry, identifier, source))\n ) {\n throw new Error(\n `MaterialReady ${readiness.guid} conflicts with the registered shader '${identifier}'`,\n );\n }\n continue;\n }\n shaderRegistry.installMaterialArtifact(identifier, { source, paramSchema });\n }\n}\n","// @forgeax/engine-assets-runtime -- register-time payload validation\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport { PROCEDURAL_FLOATS_PER_VERTEX } from '@forgeax/engine-geometry';\nimport type {\n Asset,\n AssetErrorDetail,\n TilesetAsset,\n MeshAsset as TypesMeshAsset,\n} from '@forgeax/engine-types';\nimport { ASSET_ERROR_HINTS, AssetError, countExtraUvSets } from '@forgeax/engine-types';\n\n/**\n * Register-stage fail-fast for `kind: 'mesh'` payloads whose vertices buffer\n * is not the canonical 12-floats-per-vertex layout.\n *\n * Validation spec (plan-strategy D-3):\n * (a) asset.kind !== 'mesh' -> return null immediately\n * (b) vertices.length === 0 && indices.length === 0 -> return null (empty mesh legal)\n * (c) vertices.length % PROCEDURAL_FLOATS_PER_VERTEX !== 0 -> `AssetError` with\n * code='mesh-vertex-stride-mismatch', detail = { vertexCount: 0,\n * floatsPerVertex: vertices.length / PROCEDURAL_FLOATS_PER_VERTEX } (non-integer)\n * (d) otherwise compute vertexCount = vertices.length / PROCEDURAL_FLOATS_PER_VERTEX;\n * scan indices for maxIndex;\n * if maxIndex + 1 !== vertexCount -> same AssetError shape with\n * detail = { vertexCount: maxIndex + 1, floatsPerVertex: vertices.length / (maxIndex + 1) }\n *\n * Isomorphic with `validateMaterialPayload` — both are private module-level helpers,\n * both return `AssetError | null`, and both are called from `register()` at entry.\n *\n * Anchors: charter P3 (structured failure); plan-strategy D-2 (gate at register stage);\n * plan-strategy D-3 (three-branch validation: empty / non-divisible-12 / maxIndex mismatch);\n * plan-strategy D-5 (physical location co-located with validateMaterialPayload).\n */\nexport function validateMeshPayload(asset: Asset): AssetError | null {\n if (asset.kind !== 'mesh') return null;\n\n // feat-20260604-mesh-topology-debug-draw M5 / w13: semantic topology gate\n // (plan-strategy D-A2).\n //\n // feat-20260608 M2 / w9: topology is now per-submesh (MeshAsset.submeshes[]).\n // All topology + submesh-empty + index-OOB validation runs here.\n const submeshes = (asset as TypesMeshAsset).submeshes;\n if (submeshes.length === 0) {\n // TypesMeshAsset POD does not carry an inline GUID; the registry assigns\n // one on register, but at validation time we only have the payload. Emit\n // a stable sentinel so the closed AssetErrorDetail union still narrows.\n const guid = '<no-guid>';\n return new AssetError({\n code: 'mesh-asset-submeshes-empty',\n expected: 'submeshes array has at least one Submesh entry',\n hint: ASSET_ERROR_HINTS['mesh-asset-submeshes-empty'],\n detail: { meshAssetGuid: guid },\n });\n }\n\n const materialSlots = (asset as TypesMeshAsset).materialSlots;\n if (!Array.isArray(materialSlots) || materialSlots.length === 0) {\n return new AssetError({\n code: 'mesh-asset-material-slot-index-out-of-range',\n expected: 'a non-empty materialSlots table for a mesh with submeshes',\n hint: ASSET_ERROR_HINTS['mesh-asset-material-slot-index-out-of-range'],\n detail: {\n meshAssetGuid: '<no-guid>',\n submeshIndex: 0,\n materialSlot: -1,\n materialSlotCount: 0,\n },\n });\n }\n const slotNames = new Set<string>();\n const sourceKeys = new Set<string>();\n for (let slotIndex = 0; slotIndex < materialSlots.length; slotIndex++) {\n const slot = materialSlots[slotIndex];\n const slotName = slot?.slotName.trim() ?? '';\n const sourceKey = slot?.sourceKey?.trim();\n if (slotName.length === 0 || slotNames.has(slotName)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `materialSlots[${slotIndex}].slotName is non-empty and unique`,\n hint: 'give every Mesh material slot a stable unique slotName',\n detail: {\n field: `materialSlots[${slotIndex}].slotName`,\n value: slotName,\n reason: 'empty-or-duplicate',\n },\n });\n }\n slotNames.add(slotName);\n if (sourceKey !== undefined && sourceKey.length > 0) {\n if (sourceKeys.has(sourceKey)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `materialSlots[${slotIndex}].sourceKey is unique when present`,\n hint: 'derive a stable unique source identity for every imported Mesh material slot',\n detail: {\n field: `materialSlots[${slotIndex}].sourceKey`,\n value: sourceKey,\n reason: 'duplicate',\n },\n });\n }\n sourceKeys.add(sourceKey);\n }\n }\n\n const hasIndices = (asset.indices?.length ?? 0) > 0;\n const indexBufferLength = asset.indices?.length ?? 0;\n for (let i = 0; i < submeshes.length; i++) {\n const sm = submeshes[i];\n if (sm === undefined) continue;\n const topology = sm.topology;\n if (\n !Number.isInteger(sm.materialSlot) ||\n sm.materialSlot < 0 ||\n sm.materialSlot >= materialSlots.length\n ) {\n return new AssetError({\n code: 'mesh-asset-material-slot-index-out-of-range',\n expected: `submesh[${i}].materialSlot in [0, ${materialSlots.length})`,\n hint: ASSET_ERROR_HINTS['mesh-asset-material-slot-index-out-of-range'],\n detail: {\n meshAssetGuid: '<no-guid>',\n submeshIndex: i,\n materialSlot: sm.materialSlot,\n materialSlotCount: materialSlots.length,\n },\n });\n }\n if ((topology === 'line-strip' || topology === 'triangle-strip') && !hasIndices) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `submesh[${i}] strip topology carries an index buffer`,\n hint: 'line-strip / triangle-strip meshes must provide indices; add MeshAsset.indices or use line-list / triangle-list',\n detail: {\n field: `submeshes[${i}].topology`,\n value: topology,\n reason: 'strip-topology-without-indices',\n },\n });\n }\n if (asset.vertices.length === 0 && topology !== 'triangle-list') {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `submesh[${i}]: empty geometry uses 'triangle-list'`,\n hint: 'a zero-vertex mesh has nothing to draw; change submesh topology to triangle-list or provide vertices',\n detail: {\n field: `submeshes[${i}].topology`,\n value: topology,\n reason: 'empty-geometry-non-default-topology',\n },\n });\n }\n // feat-20260608 M2 / w9: index-range-out-of-bounds per submesh\n if (sm.indexOffset + sm.indexCount > indexBufferLength) {\n // TypesMeshAsset POD does not carry an inline GUID; the registry assigns\n // one on register, but at validation time we only have the payload. Emit\n // a stable sentinel so the closed AssetErrorDetail union still narrows.\n const guid = '<no-guid>';\n return new AssetError({\n code: 'mesh-submesh-index-range-out-of-bounds',\n expected: `submesh[${i}].indexOffset + indexCount <= index buffer length (${indexBufferLength})`,\n hint: ASSET_ERROR_HINTS['mesh-submesh-index-range-out-of-bounds'],\n detail: {\n submeshIndex: i,\n indexOffset: sm.indexOffset,\n indexCount: sm.indexCount,\n indexBufferLength,\n meshAssetGuid: guid,\n },\n });\n }\n }\n\n // indices is optional (vertex-only meshes omit it); read defensively. The\n // stride invariant below stays null-safe for vertex-only meshes (D-A4).\n if (asset.vertices.length === 0 && (asset.indices?.length ?? 0) === 0) return null;\n\n // Skin-aware stride: when MeshAsset.attributes carries skinIndex + skinWeight,\n // the bridge promotes the interleaved buffer to 18 floats/vertex (12 base +\n // 4 uint16x4 packed via aliased Uint16 view at slots 12-13 + 4 float weights\n // at slots 14-17).\n // feat-20260629 multi-uv: extra UV sets (uv1..uv7) add 2 floats each to the\n // interleaved stride, pushed after skin data (canonical order).\n const attrs = (asset as TypesMeshAsset).attributes;\n const isSkinned =\n attrs !== undefined && attrs.skinIndex !== undefined && attrs.skinWeight !== undefined;\n const extraUvSets = countExtraUvSets(attrs);\n const baseFloatsPerVertex = isSkinned ? 18 : PROCEDURAL_FLOATS_PER_VERTEX;\n const floatsPerVertex = baseFloatsPerVertex + extraUvSets * 2;\n\n if (asset.vertices.length % floatsPerVertex !== 0) {\n return new AssetError({\n code: 'mesh-vertex-stride-mismatch',\n expected: isSkinned\n ? '18 floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4 + skinIndex u16x4 + skinWeight vec4)'\n : `${PROCEDURAL_FLOATS_PER_VERTEX} floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4)`,\n hint: ASSET_ERROR_HINTS['mesh-vertex-stride-mismatch'],\n detail: {\n vertexCount: 0,\n floatsPerVertex: asset.vertices.length / floatsPerVertex,\n },\n });\n }\n\n const vertexCount = asset.vertices.length / floatsPerVertex;\n // Vertex-only meshes (no indices) skip the maxIndex-vs-vertexCount invariant:\n // there is no index buffer to bound-check against the vertex array (D-A4).\n const indices = asset.indices;\n if (indices === undefined || indices.length === 0) return null;\n let maxIndex = 0;\n for (let i = 0; i < indices.length; i++) {\n const idx = indices[i];\n if (idx !== undefined && idx > maxIndex) maxIndex = idx;\n }\n\n if (maxIndex + 1 !== vertexCount) {\n return new AssetError({\n code: 'mesh-vertex-stride-mismatch',\n expected: isSkinned\n ? '18 floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4 + skinIndex u16x4 + skinWeight vec4)'\n : `${PROCEDURAL_FLOATS_PER_VERTEX} floats per vertex (= position vec3 + normal vec3 + uv vec2 + tangent vec4)`,\n hint: ASSET_ERROR_HINTS['mesh-vertex-stride-mismatch'],\n detail: {\n vertexCount: maxIndex + 1,\n floatsPerVertex: vertexCount > 0 ? asset.vertices.length / (maxIndex + 1) : 0,\n },\n });\n }\n\n return null;\n}\n\n// === Tileset / Tilemap / TileLayer validators (feat-20260608 M0 baseline rebuild) ===\n//\n// R-6 first-error path (plan-strategy §R-6 ordering, M1 extended):\n// (1) `atlases.length >= 1` -> 'tileset-tile-entry-malformed'\n// .field='atlases' .scope='tileset-asset' (M1)\n// (2) region rectangle stays in atlas -> 'tileset-region-index-out-of-range' (M0)\n// (3) `region.atlasIndex` in atlases range -> 'tileset-tile-entry-malformed'\n// .field='atlasIndex' .scope='tileset-asset' (M1)\n// (4) `tiles[i].regionIndex` in regions -> 'tileset-region-index-out-of-range' (M0)\n// (5) tile entry widthCells / heightCells -> 'tileset-tile-entry-malformed'\n// / pivotX / pivotY / collider .field=<field> .scope='tile-entry'\n// .tileEntryIndex=i (M1)\n//\n// Tilemap / TileLayer register-time invariants use `AssetError\n// 'asset-invalid-value'` with `.detail = { field, value, reason }` so the\n// closed AssetErrorDetail discriminated union narrows uniformly (charter\n// P4 consistent abstraction with `validateMeshPayload`).\n\n/**\n * Optional atlas extent for `validateTilesetPayload`. When omitted, the\n * region-rectangle bounds-check is skipped — only the\n * `tiles[].regionIndex` in `[0, regions.length)` invariant runs.\n */\nexport interface TilesetValidateOptions {\n readonly atlasWidth?: number;\n readonly atlasHeight?: number;\n}\n\n/**\n * Construct an `AssetError` for the M1 `tileset-tile-entry-malformed`\n * code with structured `.detail` (closed 7-variant `.field` enum +\n * 2-variant `.scope` + optional `.tileEntryIndex`). The helper centralises\n * the boilerplate so each call site stays a one-liner (charter F1 single\n * affordance) and the `.detail` shape stays SSOT-aligned with\n * `AssetTilesetTileEntryMalformedDetail`.\n */\nfunction tileEntryMalformed(args: {\n tilesetGuid: string;\n field: 'widthCells' | 'heightCells' | 'pivotX' | 'pivotY' | 'collider' | 'atlases' | 'atlasIndex';\n scope: 'tileset-asset' | 'tile-entry';\n tileEntryIndex?: number;\n expected: string;\n}): AssetError {\n const detail: AssetErrorDetail = {\n code: 'tileset-tile-entry-malformed',\n field: args.field,\n scope: args.scope,\n tilesetGuid: args.tilesetGuid,\n ...(args.tileEntryIndex !== undefined ? { tileEntryIndex: args.tileEntryIndex } : {}),\n expected: args.expected,\n hint: ASSET_ERROR_HINTS['tileset-tile-entry-malformed'],\n };\n return new AssetError({\n code: 'tileset-tile-entry-malformed',\n expected: args.expected,\n hint: ASSET_ERROR_HINTS['tileset-tile-entry-malformed'],\n detail,\n });\n}\n\n/**\n * Validate the shape of a `TilesetTileCollider` value (R-6 step 5d).\n * Returns `null` when the collider is well-formed, otherwise an\n * `AssetError` with code `'tileset-tile-entry-malformed'` and\n * `.detail.field = 'collider'` (charter P3 closed schema).\n *\n * Rules per variant:\n * - `'none'` -- always accepted.\n * - `'rect'` -- `rect.length === 4`; each component in `[0, 1]`;\n * `w > 0`, `h > 0`; `x + w <= 1`, `y + h <= 1`.\n * - `'polygon'` -- `points.length >= 3`; each point's `x` and `y` in\n * `[0, 1]`.\n * - any other `type` discriminator surfaces the same `.field='collider'`\n * fail-fast (unreachable through the typed surface but defends\n * against unchecked JSON loaders, charter P4 fail-fast in depth).\n */\nfunction validateColliderShape(\n collider: NonNullable<TilesetTileEntryColliderField>,\n tilesetGuid: string,\n tileEntryIndex: number,\n): AssetError | null {\n if (collider.type === 'none') return null;\n if (collider.type === 'rect') {\n const rect = collider.rect;\n if (!Array.isArray(rect) || rect.length !== 4) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.rect length === 4`,\n });\n }\n const [rx, ry, rw, rh] = rect;\n const valid =\n typeof rx === 'number' &&\n typeof ry === 'number' &&\n typeof rw === 'number' &&\n typeof rh === 'number' &&\n rx >= 0 &&\n ry >= 0 &&\n rw > 0 &&\n rh > 0 &&\n rx + rw <= 1 &&\n ry + rh <= 1;\n if (!valid) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.rect in [0, 1]^2 with w > 0, h > 0, x + w <= 1, y + h <= 1`,\n });\n }\n return null;\n }\n if (collider.type === 'polygon') {\n const points = collider.points;\n if (!Array.isArray(points) || points.length < 3) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.points length >= 3`,\n });\n }\n for (let j = 0; j < points.length; j++) {\n const p = points[j];\n if (\n !Array.isArray(p) ||\n p.length !== 2 ||\n typeof p[0] !== 'number' ||\n typeof p[1] !== 'number' ||\n p[0] < 0 ||\n p[0] > 1 ||\n p[1] < 0 ||\n p[1] > 1\n ) {\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.points[${j}] in [0, 1]^2`,\n });\n }\n }\n return null;\n }\n // Unknown discriminator (only reachable via unchecked JSON loaders bypassing\n // the typed surface). Closed enum -> fail-fast (charter P3).\n return tileEntryMalformed({\n tilesetGuid,\n field: 'collider',\n scope: 'tile-entry',\n tileEntryIndex,\n expected: `tiles[${tileEntryIndex}].collider.type in {'none', 'rect', 'polygon'}`,\n });\n}\n\n/**\n * Internal alias for the optional `collider` field on `TilesetTileEntry`.\n * Localised to keep the validator helper signature math-free.\n */\ntype TilesetTileEntryColliderField = TilesetAsset['tiles'][number]['collider'];\n\n/**\n * Validate a `TilesetAsset` payload at register time (M0 baseline rebuild\n * + M1 schema extension). Returns `null` on success or an `AssetError`\n * carrying the first-error details (charter P3 fail-fast). R-6 ordering:\n *\n * 1. `atlases.length >= 1` -- 'tileset-tile-entry-malformed' .field='atlases'.\n * 2. Region rectangle escapes atlas extent (when extent is supplied) --\n * M0 code 'tileset-region-index-out-of-range'.\n * 3. `regions[i].atlasIndex` in `[0, atlases.length)` -- 'tileset-tile-entry-malformed'\n * .field='atlasIndex'.\n * 4. `tiles[i].regionIndex` in `[0, regions.length)` -- M0 code.\n * 5. Per-tile-entry boundaries -- 'tileset-tile-entry-malformed'\n * .field=widthCells | heightCells | pivotX | pivotY | collider,\n * in that order, .scope='tile-entry' .tileEntryIndex=i.\n */\nexport function validateTilesetPayload(\n asset: TilesetAsset,\n opts: TilesetValidateOptions = {},\n): AssetError | null {\n const assetGuid = '<no-guid>';\n // (1) atlases empty fail-fast (M1 R-6 top-level invariant).\n if (asset.atlases.length < 1) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'atlases',\n scope: 'tileset-asset',\n expected: 'atlases.length >= 1',\n });\n }\n\n const regionCount = asset.regions.length;\n const atlasesLength = asset.atlases.length;\n // (2) region rectangle bounds-check. Negative coords / non-positive size are\n // rejected regardless of whether an atlas extent is supplied; the optional\n // atlasWidth / atlasHeight tightens the upper bound when present.\n const atlasWidth = opts.atlasWidth;\n const atlasHeight = opts.atlasHeight;\n for (let i = 0; i < regionCount; i++) {\n const region = asset.regions[i];\n if (region === undefined) continue;\n const negativeOrZero = region.x < 0 || region.y < 0 || region.width <= 0 || region.height <= 0;\n const exceedsAtlas =\n typeof atlasWidth === 'number' &&\n typeof atlasHeight === 'number' &&\n (region.x + region.width > atlasWidth || region.y + region.height > atlasHeight);\n if (negativeOrZero || exceedsAtlas) {\n return new AssetError({\n code: 'tileset-region-index-out-of-range',\n expected: `regions[${i}] rectangle (x/y >= 0, width/height > 0${\n typeof atlasWidth === 'number' && typeof atlasHeight === 'number'\n ? `, x + width <= ${atlasWidth}, y + height <= ${atlasHeight}`\n : ''\n })`,\n hint: ASSET_ERROR_HINTS['tileset-region-index-out-of-range'],\n detail: {\n code: 'tileset-region-index-out-of-range',\n tilesetGuid: assetGuid,\n tileId: 0,\n regionIndex: i,\n regionCount,\n },\n });\n }\n // (3) per-region atlasIndex bounds-check (M1; optional field defaults 0).\n if (region.atlasIndex !== undefined) {\n const ai = region.atlasIndex;\n if (!Number.isInteger(ai) || ai < 0 || ai >= atlasesLength) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'atlasIndex',\n scope: 'tileset-asset',\n expected: `regions[${i}].atlasIndex in [0, ${atlasesLength})`,\n });\n }\n }\n }\n // (4) tile entry regionIndex in [0, regions.length) (M0 code).\n for (let i = 0; i < asset.tiles.length; i++) {\n const entry = asset.tiles[i];\n if (entry === undefined) continue;\n const ri = entry.regionIndex;\n if (!Number.isInteger(ri) || ri < 0 || ri >= regionCount) {\n return new AssetError({\n code: 'tileset-region-index-out-of-range',\n expected: `tiles[${i}].regionIndex in [0, ${regionCount})`,\n hint: ASSET_ERROR_HINTS['tileset-region-index-out-of-range'],\n detail: {\n code: 'tileset-region-index-out-of-range',\n tilesetGuid: assetGuid,\n tileId: i + 1,\n regionIndex: ri,\n regionCount,\n },\n });\n }\n }\n // (5) per-tile-entry M1 boundaries -- widthCells > heightCells > pivotX >\n // pivotY > collider, per plan-strategy §R-6 first-error order. Each loop\n // iteration runs the full sub-order on entry i before advancing to i+1 so\n // the deterministic global order is (i=0 widthCells, i=0 heightCells, ...,\n // i=0 collider, i=1 widthCells, ...). Tests in tileset-asset-validate.test.ts\n // R-6 block exercise the sub-order on a single entry.\n for (let i = 0; i < asset.tiles.length; i++) {\n const entry = asset.tiles[i];\n if (entry === undefined) continue;\n if (entry.widthCells !== undefined) {\n const w = entry.widthCells;\n if (!Number.isFinite(w) || w <= 0 || w > 64) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'widthCells',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].widthCells in (0, 64]`,\n });\n }\n }\n if (entry.heightCells !== undefined) {\n const h = entry.heightCells;\n if (!Number.isFinite(h) || h <= 0 || h > 64) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'heightCells',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].heightCells in (0, 64]`,\n });\n }\n }\n if (entry.pivotX !== undefined) {\n const px = entry.pivotX;\n if (!Number.isFinite(px) || px < 0 || px > 1) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'pivotX',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].pivotX in [0, 1]`,\n });\n }\n }\n if (entry.pivotY !== undefined) {\n const py = entry.pivotY;\n if (!Number.isFinite(py) || py < 0 || py > 1) {\n return tileEntryMalformed({\n tilesetGuid: assetGuid,\n field: 'pivotY',\n scope: 'tile-entry',\n tileEntryIndex: i,\n expected: `tiles[${i}].pivotY in [0, 1]`,\n });\n }\n }\n if (entry.collider !== undefined) {\n const colliderErr = validateColliderShape(entry.collider, assetGuid, i);\n if (colliderErr !== null) return colliderErr;\n }\n }\n return null;\n}\n\n/**\n * Compute the implicit atlas extent of a `TilesetAsset` from its grid metadata\n * (`columns * tileWidth` x `rows * tileHeight`). Used by the register-time\n * region-bounds check when the caller does not supply explicit extents.\n */\nexport function inferAtlasExtent(asset: TilesetAsset): { atlasWidth: number; atlasHeight: number } {\n return {\n atlasWidth: asset.columns * asset.tileWidth,\n atlasHeight: asset.rows * asset.tileHeight,\n };\n}\n","import { decompressZstd } from '@forgeax/engine-codec';\nimport { validateArtifactPath } from '@forgeax/engine-pack';\nimport type { ArtifactDescriptor, AssetArtifactError } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport interface ArtifactReadRequest {\n readonly packageUrl: string;\n readonly guid: string;\n readonly artifactKey: string;\n readonly descriptor: ArtifactDescriptor;\n}\n\nexport type ArtifactFetcher = (url: string) => Promise<Response>;\n\nfunction failure(\n code: AssetArtifactError['code'],\n request: ArtifactReadRequest,\n expected: string,\n hint: string,\n observed: string,\n): AssetArtifactError {\n if (code === 'asset-artifact-missing') {\n return {\n code,\n expected,\n hint,\n detail: {\n guid: request.guid,\n artifactKey: request.artifactKey,\n path: request.descriptor.path,\n observed,\n expected,\n },\n };\n }\n return {\n code,\n expected,\n hint,\n detail: {\n guid: request.guid,\n artifactKey: request.artifactKey,\n observed,\n expected,\n },\n };\n}\n\nfunction artifactUrl(packageUrl: string, path: string): string {\n try {\n return new URL(path, packageUrl).toString();\n } catch {\n const queryIndex = packageUrl.search(/[?#]/);\n const cleanPackageUrl = queryIndex < 0 ? packageUrl : packageUrl.slice(0, queryIndex);\n const slash = cleanPackageUrl.lastIndexOf('/');\n return `${slash < 0 ? '' : cleanPackageUrl.slice(0, slash + 1)}${path}`;\n }\n}\n\nfunction encodedBytes(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return globalThis.btoa(binary);\n}\n\nfunction hexBytes(bytes: Uint8Array): string {\n return [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nasync function sha256(bytes: Uint8Array): Promise<{ base64: string; hex: string } | undefined> {\n const subtle = globalThis.crypto?.subtle;\n if (subtle === undefined) return undefined;\n const digest = await subtle.digest('SHA-256', bytes.slice().buffer as ArrayBuffer);\n const digestBytes = new Uint8Array(digest);\n return { base64: encodedBytes(digestBytes), hex: hexBytes(digestBytes) };\n}\n\nasync function decodeOuter(\n bytes: Uint8Array,\n request: ArtifactReadRequest,\n): Promise<Result<Uint8Array, AssetArtifactError>> {\n const encoding = request.descriptor.contentEncoding ?? 'identity';\n if (encoding === 'identity') return ok(bytes);\n if (encoding !== 'zstd') {\n return err(\n failure(\n 'asset-artifact-encoding-unsupported',\n request,\n \"contentEncoding 'identity' or 'zstd'\",\n 'change the descriptor to a supported outer content encoding and re-cook the package',\n encoding,\n ),\n );\n }\n const decoded = await decompressZstd(bytes);\n if (!decoded.ok) {\n return err(\n failure(\n 'asset-artifact-decode-failed',\n request,\n 'valid bytes for the declared outer content encoding',\n 're-cook the artifact and verify the stored bytes before loading again',\n JSON.stringify(decoded.error.detail),\n ),\n );\n }\n return ok(decoded.value);\n}\n\nasync function verifyBytes(\n bytes: Uint8Array,\n request: ArtifactReadRequest,\n): Promise<Result<Uint8Array, AssetArtifactError>> {\n const expectedLength = request.descriptor.byteLength;\n if (expectedLength !== undefined && expectedLength !== bytes.byteLength) {\n return err(\n failure(\n 'asset-artifact-integrity-mismatch',\n request,\n `decoded artifact byteLength ${expectedLength}`,\n 're-cook the package or update its artifact descriptor to match the bytes',\n String(bytes.byteLength),\n ),\n );\n }\n const integrity = request.descriptor.integrity;\n if (integrity === undefined) return ok(bytes);\n const digest = await sha256(bytes);\n if (digest === undefined) {\n return err(\n failure(\n 'asset-artifact-integrity-mismatch',\n request,\n 'a runtime with Web Crypto SHA-256 support',\n 'enable Web Crypto or remove the unverifiable artifact from the package',\n 'crypto.subtle unavailable',\n ),\n );\n }\n const expectedDigest = integrity.digest.startsWith('sha256:')\n ? integrity.digest.slice('sha256:'.length)\n : integrity.digest;\n if (expectedDigest !== digest.base64 && expectedDigest.toLowerCase() !== digest.hex) {\n return err(\n failure(\n 'asset-artifact-integrity-mismatch',\n request,\n `sha256 digest ${integrity.digest}`,\n 're-cook the artifact or replace the corrupted stored bytes',\n digest.base64,\n ),\n );\n }\n return ok(bytes);\n}\n\nexport async function readArtifact(\n request: ArtifactReadRequest,\n fetcher: ArtifactFetcher = (url) => globalThis.fetch(url),\n): Promise<Result<Uint8Array, AssetArtifactError>> {\n if (request.descriptor.mediaType.trim().length === 0) {\n return err(\n failure(\n 'asset-artifact-media-unsupported',\n request,\n 'a non-empty durable artifact mediaType',\n 'set the artifact mediaType during production and re-publish the package',\n request.descriptor.mediaType,\n ),\n );\n }\n const path = validateArtifactPath(request.descriptor.path, {\n packageRoot: request.packageUrl,\n guid: request.guid,\n artifactKey: request.artifactKey,\n });\n if (!path.ok) return path;\n\n const encoding = request.descriptor.contentEncoding ?? 'identity';\n if (encoding !== 'identity' && encoding !== 'zstd') {\n return err(\n failure(\n 'asset-artifact-encoding-unsupported',\n request,\n \"contentEncoding 'identity' or 'zstd'\",\n 'change the descriptor to a supported outer content encoding and re-cook the package',\n encoding,\n ),\n );\n }\n\n const url = artifactUrl(request.packageUrl, path.value);\n let response: Response;\n try {\n response = await fetcher(url);\n } catch (cause) {\n return err(\n failure(\n 'asset-artifact-missing',\n request,\n `readable artifact at ${path.value}`,\n 'publish the artifact at the declared package-relative path and retry the load',\n cause instanceof Error ? cause.message : 'artifact fetch failed',\n ),\n );\n }\n if (!response.ok) {\n return err(\n failure(\n 'asset-artifact-missing',\n request,\n `HTTP 200 for artifact at ${path.value}`,\n 'publish the missing artifact and retry the load',\n `HTTP ${response.status}`,\n ),\n );\n }\n\n let bytes: Uint8Array;\n try {\n bytes = new Uint8Array(await response.arrayBuffer());\n } catch (cause) {\n return err(\n failure(\n 'asset-artifact-missing',\n request,\n `readable artifact at ${path.value}`,\n 'repair the published artifact and retry the load',\n cause instanceof Error ? cause.message : 'artifact body unreadable',\n ),\n );\n }\n const decoded = await decodeOuter(bytes, request);\n if (!decoded.ok) return decoded;\n return verifyBytes(decoded.value, request);\n}\n\nexport class ArtifactReadCache {\n private readonly cache = new Map<string, Promise<Result<Uint8Array, AssetArtifactError>>>();\n\n read(\n key: string,\n reader: () => Promise<Result<Uint8Array, AssetArtifactError>>,\n ): Promise<Result<Uint8Array, AssetArtifactError>> {\n const existing = this.cache.get(key);\n if (existing !== undefined) return existing;\n const pending = reader();\n this.cache.set(key, pending);\n void pending.then((result) => {\n if (!result.ok) this.cache.delete(key);\n });\n return pending;\n }\n\n clear(key?: string): void {\n if (key === undefined) this.cache.clear();\n else this.cache.delete(key);\n }\n}\n","import {\n type AssetEvidence,\n type AssetEvidenceError,\n type AssetEvidenceInputs,\n err,\n projectAssetEvidence,\n type Result,\n} from '@forgeax/engine-types';\n\n/** Host-injected runtime bridge; the adapter never imports CLI, Vite, or Node policy. */\nexport interface RuntimeEvidenceSource {\n readonly evidence: (\n guid: string,\n ) => Promise<AssetEvidenceInputs | Result<AssetEvidenceInputs, AssetEvidenceError>>;\n}\n\n/** Runtime SDK view over the shared AssetEvidence projector. */\nexport interface RuntimeAssetEvidenceAdapter {\n readonly inspect: (guid: string) => Promise<Result<AssetEvidence, AssetEvidenceError>>;\n readonly verifyByGuid: (guid: string) => Promise<Result<AssetEvidence, AssetEvidenceError>>;\n}\n\nfunction missingCapability(guid: string): Result<never, AssetEvidenceError> {\n return err({\n code: 'asset-evidence-capability-missing',\n expected: 'an injected runtime evidence source',\n hint: 'configure an evidence source before calling inspect(guid) or verifyByGuid(guid)',\n detail: { capability: 'runtime evidence source', stage: `guid:${guid}` },\n });\n}\n\nasync function project(\n source: RuntimeEvidenceSource,\n guid: string,\n): Promise<Result<AssetEvidence, AssetEvidenceError>> {\n const input = await source.evidence(guid);\n if ('ok' in input) {\n if (!input.ok) return input;\n return projectAssetEvidence(input.value);\n }\n return projectAssetEvidence(input);\n}\n\n/** Create an adapter; omitted source intentionally returns capability-missing errors. */\nexport function createRuntimeAssetEvidenceAdapter(\n source?: RuntimeEvidenceSource,\n): RuntimeAssetEvidenceAdapter {\n const read = async (guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>> =>\n source === undefined ? missingCapability(guid) : project(source, guid);\n return { inspect: read, verifyByGuid: read };\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport {\n ASSET_ERROR_HINTS,\n type Asset,\n type AssetAuthoringCapability,\n type AssetEnvelope,\n AssetError,\n type AssetPublicationEnvelope,\n type AssetRelation,\n authoringCapabilityForAssetKind,\n type CatalogDiagnostic,\n type CatalogLifecycle,\n type CatalogProjection,\n type CatalogSubject,\n type CookExecution,\n type ProviderProvenance,\n type ResourceRevision,\n type RuntimeAssetBinding,\n type SourceOverrideDescriptor,\n type SourceOverrideMap,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry } from '../asset-registry';\n\n/** Runtime catalog row parsed from the shared pack-index POD shape. */\nexport interface CatalogRecord {\n readonly packageUrl: string;\n readonly kind: string;\n readonly authoring?: import('@forgeax/engine-types').AssetAuthoringCapability;\n readonly name?: string;\n readonly refs?: readonly string[];\n readonly sourcePath?: string;\n readonly cookReceiptUrl?: string;\n readonly packageId?: string;\n readonly provenance?: ProviderProvenance;\n readonly revision?: ResourceRevision;\n readonly sourceKey?: string;\n readonly sourceIndex?: number;\n readonly sourceOverrides?: SourceOverrideMap;\n readonly sourceOverrideDescriptors?: readonly SourceOverrideDescriptor[];\n readonly relations?: readonly AssetRelation[];\n readonly diagnostics?: readonly CatalogDiagnostic[];\n /** Producer-owned projection axes; never infer these from locators. */\n readonly subject?: CatalogSubject;\n readonly execution?: CookExecution;\n readonly lifecycle?: CatalogLifecycle;\n readonly projection?: CatalogProjection;\n /** Complete producer publication tuple used by Scene publication fences. */\n readonly publication?: AssetPublicationEnvelope;\n}\n\n/** Build the canonical row for an inline asset without inventing producer facts. */\nexport function createInlineCatalogRecord(\n envelope: AssetEnvelope<Asset>,\n name: string,\n): CatalogRecord {\n return {\n packageUrl: '',\n kind: envelope.payload.kind,\n authoring: authoringCapabilityForAssetKind(envelope.payload.kind),\n name,\n ...(envelope.refs.length > 0 ? { refs: envelope.refs.map((ref) => ref.guid) } : {}),\n };\n}\n\ntype CatalogFetch = (\n input: string,\n init?: { readonly cache?: 'no-store' },\n) => PromiseLike<{\n readonly ok: boolean;\n json(): Promise<unknown>;\n}>;\n\nfunction parseError(\n expected: string,\n detail?: object,\n hint = ASSET_ERROR_HINTS['asset-parse-failed'],\n): AssetError {\n return new AssetError({\n code: 'asset-parse-failed',\n expected,\n hint,\n ...(detail === undefined ? {} : { detail: detail as never }),\n });\n}\n\nfunction sameRevision(left: ResourceRevision, right: ResourceRevision): boolean {\n return (\n left.digest === right.digest &&\n left.observedAt === right.observedAt &&\n left.rootId === right.rootId\n );\n}\n\nfunction checkExpectedRevision(\n records: readonly CatalogRecord[],\n expectedRevision: ResourceRevision | undefined,\n): AssetError | undefined {\n if (expectedRevision === undefined || records.length === 0) return undefined;\n const actualRevisions = records.flatMap((record) =>\n record.revision === undefined ? [] : [record.revision],\n );\n if (\n actualRevisions.length > 0 &&\n actualRevisions.every((revision) => sameRevision(revision, expectedRevision))\n ) {\n return undefined;\n }\n return parseError(\n 'every catalog entry to carry the expected producer revision',\n { expectedRevision, actualRevisions },\n 'restore a verified catalog revision before applying the source',\n );\n}\n\n/** Resolve a catalog entry URL against the configured pack-index URL. */\nexport function resolveCatalogAssetUrl(registry: AssetRegistry, packageUrl: string): string {\n const packIndexUrl = registry.packIndexUrl;\n if (packIndexUrl === undefined) return packageUrl;\n\n try {\n const baseUrl = new URL(packIndexUrl, globalThis.location?.href).href;\n return new URL(packageUrl, baseUrl).href;\n } catch {\n return packageUrl;\n }\n}\n\nfunction isRawSourceLocator(packageUrl: string): boolean {\n const path = packageUrl.split(/[?#]/, 1)[0]?.toLowerCase() ?? packageUrl.toLowerCase();\n if (path.endsWith('.pack.json')) return false;\n return (\n /\\.(bin|fbx|gltf|glb|hdr|jpg|jpeg|png|wav|mp3|ogg|ttf|otf|woff|woff2|svg)$/.test(path) ||\n path.endsWith('.particle-effect.json')\n );\n}\n\n/** Parse the shared pack-index/catalog wire shape without loading payloads. */\nexport function parseCatalog(\n raw: unknown,\n resolveUrl: (packageUrl: string) => string = (packageUrl) => packageUrl,\n expectedRevision?: ResourceRevision,\n expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>,\n): Result<Map<string, CatalogRecord>, AssetError> {\n let rows: readonly unknown[];\n if (expectedScope !== undefined) {\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {\n return err(\n parseError(\n 'scoped catalog snapshot to be an object with schema, scopeId, generation, authority, and entries',\n ),\n );\n }\n const snapshot = raw as Record<string, unknown>;\n if (\n snapshot.schemaVersion !== 'runtime-catalog-snapshot-v1' ||\n typeof snapshot.scopeId !== 'string' ||\n typeof snapshot.generation !== 'number' ||\n !Number.isSafeInteger(snapshot.generation) ||\n !Array.isArray(snapshot.entries)\n ) {\n return err(parseError('scoped catalog snapshot to satisfy its runtime schema'));\n }\n if (\n snapshot.scopeId !== expectedScope.scopeId ||\n snapshot.generation !== expectedScope.generation\n ) {\n return err(\n parseError('scoped catalog snapshot to match the active scope and generation', {\n expectedScope,\n actualScope: { scopeId: snapshot.scopeId, generation: snapshot.generation },\n }),\n );\n }\n if (snapshot.authority !== 'authoritative') {\n return err(\n parseError(\n 'scoped catalog snapshot authority to be authoritative before identity lookup',\n { authority: snapshot.authority, diagnostics: snapshot.diagnostics },\n 'repair the active game catalog before loading assets',\n ),\n );\n }\n rows = snapshot.entries;\n } else if (Array.isArray(raw)) {\n rows = raw;\n } else {\n return err(parseError('pack-index.json to be a JSON array'));\n }\n\n const catalog = new Map<string, CatalogRecord>();\n for (const item of rows) {\n if (item === null || typeof item !== 'object') {\n return err(parseError('each catalog row to be an object'));\n }\n const rawRow = item as Record<string, unknown>;\n const legacyLocator = ['relative', 'Url'].join('');\n if (\n legacyLocator in rawRow ||\n 'metadata' in rawRow ||\n 'compression' in rawRow ||\n 'artifacts' in rawRow ||\n 'assetCodec' in rawRow ||\n 'contentEncoding' in rawRow\n ) {\n return err(parseError('catalog rows to expose navigation fields only'));\n }\n if (\n typeof rawRow.guid !== 'string' ||\n rawRow.guid.length === 0 ||\n typeof rawRow.packageUrl !== 'string' ||\n rawRow.packageUrl.length === 0 ||\n typeof rawRow.kind !== 'string' ||\n rawRow.kind.length === 0\n ) {\n return err(parseError('each catalog row to contain guid, packageUrl, and kind strings'));\n }\n if (isRawSourceLocator(rawRow.packageUrl)) {\n return err(\n parseError(`catalog packageUrl ${rawRow.packageUrl} to identify a cooked package`),\n );\n }\n const guid = rawRow.guid.toLowerCase();\n if (catalog.has(guid)) return err(parseError(`catalog GUID ${rawRow.guid} to be unique`));\n const refs = rawRow.refs;\n if (\n refs !== undefined &&\n (!Array.isArray(refs) || !refs.every((ref) => typeof ref === 'string'))\n ) {\n return err(parseError(`catalog refs for GUID ${rawRow.guid} to be a string array`));\n }\n if (\n rawRow.sourceOverrides !== undefined &&\n (rawRow.sourceOverrides === null ||\n typeof rawRow.sourceOverrides !== 'object' ||\n Array.isArray(rawRow.sourceOverrides))\n ) {\n return err(parseError(`catalog sourceOverrides for GUID ${rawRow.guid} to be an object`));\n }\n if (\n rawRow.sourceOverrideDescriptors !== undefined &&\n !Array.isArray(rawRow.sourceOverrideDescriptors)\n ) {\n return err(\n parseError(`catalog sourceOverrideDescriptors for GUID ${rawRow.guid} to be an array`),\n );\n }\n let resolvedUrl: string;\n try {\n resolvedUrl = resolveUrl(rawRow.packageUrl);\n } catch (error) {\n return err(\n parseError(`catalog entry ${rawRow.guid} to resolve its packageUrl`, {\n packageUrl: rawRow.packageUrl,\n reason: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n const row: CatalogRecord = {\n packageUrl: resolvedUrl,\n kind: rawRow.kind,\n ...(rawRow.authoring !== undefined\n ? { authoring: rawRow.authoring as AssetAuthoringCapability }\n : {}),\n ...(typeof rawRow.name === 'string' ? { name: rawRow.name } : {}),\n ...(typeof rawRow.sourcePath === 'string' ? { sourcePath: rawRow.sourcePath } : {}),\n ...(refs !== undefined ? { refs: refs as readonly string[] } : {}),\n ...(typeof rawRow.cookReceiptUrl === 'string'\n ? { cookReceiptUrl: rawRow.cookReceiptUrl }\n : {}),\n ...(typeof rawRow.packageId === 'string' ? { packageId: rawRow.packageId } : {}),\n ...(rawRow.provenance !== undefined\n ? { provenance: rawRow.provenance as ProviderProvenance }\n : {}),\n ...(rawRow.revision !== undefined ? { revision: rawRow.revision as ResourceRevision } : {}),\n ...(typeof rawRow.sourceKey === 'string' ? { sourceKey: rawRow.sourceKey } : {}),\n ...(typeof rawRow.sourceIndex === 'number' ? { sourceIndex: rawRow.sourceIndex } : {}),\n ...(rawRow.sourceOverrides !== undefined\n ? { sourceOverrides: rawRow.sourceOverrides as SourceOverrideMap }\n : {}),\n ...(rawRow.sourceOverrideDescriptors !== undefined\n ? {\n sourceOverrideDescriptors:\n rawRow.sourceOverrideDescriptors as readonly SourceOverrideDescriptor[],\n }\n : {}),\n ...(Array.isArray(rawRow.relations)\n ? { relations: rawRow.relations as readonly AssetRelation[] }\n : {}),\n ...(Array.isArray(rawRow.diagnostics)\n ? { diagnostics: rawRow.diagnostics as readonly CatalogDiagnostic[] }\n : {}),\n ...(rawRow.subject === 'internal-asset' || rawRow.subject === 'imported-output'\n ? { subject: rawRow.subject }\n : {}),\n ...(rawRow.execution === 'direct' || rawRow.execution === 'cooked'\n ? { execution: rawRow.execution }\n : {}),\n ...(rawRow.lifecycle === 'missing' ||\n rawRow.lifecycle === 'cooking' ||\n rawRow.lifecycle === 'current' ||\n rawRow.lifecycle === 'stale' ||\n rawRow.lifecycle === 'failed'\n ? { lifecycle: rawRow.lifecycle }\n : {}),\n ...(rawRow.projection !== undefined\n ? { projection: rawRow.projection as CatalogProjection }\n : {}),\n ...(rawRow.publication !== undefined\n ? { publication: rawRow.publication as AssetPublicationEnvelope }\n : {}),\n };\n catalog.set(guid, row);\n }\n const revisionError = checkExpectedRevision([...catalog.values()], expectedRevision);\n if (revisionError !== undefined) return err(revisionError);\n return ok(catalog);\n}\n\n/** Fetch and parse a catalog using the shared JSON/error boundary. */\nexport async function fetchCatalog(\n url: string,\n fetch: CatalogFetch,\n resolveUrl?: (packageUrl: string) => string,\n expectedRevision?: ResourceRevision,\n expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>,\n requestInit?: { readonly cache?: 'no-store' },\n): Promise<Result<Map<string, CatalogRecord>, AssetError>> {\n let raw: unknown;\n try {\n const response = requestInit === undefined ? await fetch(url) : await fetch(url, requestInit);\n if (!response.ok) {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n raw = await response.json();\n } catch {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n return parseCatalog(raw, resolveUrl, expectedRevision, expectedScope);\n}\n\nexport function fetchPackIndex(\n registry: AssetRegistry,\n): Promise<Result<Map<string, CatalogRecord>, AssetError>> {\n const expectedScope =\n registry.runtimeBinding !== undefined &&\n registry.packIndexUrl === registry.runtimeBinding.catalogUrl\n ? registry.runtimeBinding\n : undefined;\n return fetchCatalog(\n registry.packIndexUrl as string,\n globalThis.fetch,\n (packageUrl) => resolveCatalogAssetUrl(registry, packageUrl),\n undefined,\n expectedScope,\n { cache: 'no-store' },\n );\n}\n","import { ok, type Result } from '@forgeax/engine-rhi';\nimport type {\n AssetError,\n CatalogDelta,\n CatalogDiagnostic,\n CatalogEntry,\n CatalogRevisionWindow,\n ResourceRevision,\n RuntimeAssetBinding,\n} from '@forgeax/engine-types';\nimport type { CatalogSource } from '../catalog-source';\n\nexport interface CatalogReplicaSnapshot {\n readonly version: number;\n readonly entries: readonly CatalogEntry[];\n readonly stale: boolean;\n readonly diagnostics: readonly CatalogDiagnostic[];\n}\n\ntype SnapshotResult = Result<CatalogReplicaSnapshot, AssetError>;\ntype CatalogDeltaListener = (delta: CatalogDelta) => void;\n\nfunction guidKey(guid: string): string {\n return guid.toLowerCase();\n}\n\nfunction freezeEntry(entry: CatalogEntry): CatalogEntry {\n return Object.freeze({ ...entry });\n}\n\nfunction freezeSnapshot(snapshot: CatalogReplicaSnapshot): CatalogReplicaSnapshot {\n return Object.freeze({\n ...snapshot,\n entries: Object.freeze(snapshot.entries.map(freezeEntry)),\n diagnostics: Object.freeze([...snapshot.diagnostics]),\n });\n}\n\nfunction revisionIsOlder(\n incoming: ResourceRevision | undefined,\n current: ResourceRevision | undefined,\n): boolean {\n return (\n incoming !== undefined && current !== undefined && incoming.observedAt < current.observedAt\n );\n}\n\nfunction sameRevision(left: ResourceRevision, right: ResourceRevision): boolean {\n return (\n left.digest === right.digest &&\n left.observedAt === right.observedAt &&\n left.rootId === right.rootId\n );\n}\n\nfunction sameValue(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction diagnosticForGap(): CatalogDiagnostic {\n return {\n code: 'catalog-gap',\n severity: 'blocking',\n expected: 'a contiguous producer revision window',\n hint: 'reconcile the catalog before consuming incremental changes',\n authority: 'catalog',\n };\n}\n\nfunction diagnosticForDegradedRows(): CatalogDiagnostic {\n return {\n code: 'catalog-degraded-rows',\n severity: 'blocking',\n expected: 'a degraded catalog delta to contain no identity-bearing rows',\n hint: 'keep the last verified catalog and reconcile before applying a replacement',\n authority: 'catalog',\n };\n}\n\nfunction hasIdentityChanges(delta: CatalogDelta): boolean {\n return delta.added.length > 0 || delta.changed.length > 0 || delta.removed.length > 0;\n}\n\nfunction revisionDiagnostic(\n revisions: CatalogRevisionWindow,\n hasChanges: boolean,\n): CatalogDiagnostic | undefined {\n const baselineByRoot = new Map(revisions.baseline.map((point) => [point.rootId, point]));\n const currentByRoot = new Map(revisions.current.map((point) => [point.rootId, point]));\n\n for (const point of revisions.current) {\n const baseline = baselineByRoot.get(point.rootId);\n if (baseline === undefined) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'every current root to have a verified baseline',\n actual: point.rootId,\n hint: 'restore the latest verified snapshot for this root before applying the delta',\n authority: 'catalog',\n };\n }\n if (point.revision < baseline.revision) {\n return {\n code: 'catalog-revision-stale',\n severity: 'blocking',\n expected: 'current revision to be at least the verified baseline',\n actual: `${baseline.revision} -> ${point.revision}`,\n hint: 'discard the stale update and request a fresh catalog snapshot',\n authority: 'catalog',\n };\n }\n if (point.revision === baseline.revision && hasChanges) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'a changed delta to advance the root revision',\n actual: `${baseline.revision} -> ${point.revision}`,\n hint: 'keep the verified baseline and serialize concurrent updates before retrying',\n authority: 'catalog',\n };\n }\n if (point.revision > baseline.revision + 1) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'the next revision to be exactly baseline + 1',\n actual: `${baseline.revision} -> ${point.revision}`,\n hint: 'request the missing revisions or rebuild from the latest verified snapshot',\n authority: 'catalog',\n };\n }\n }\n\n for (const point of revisions.baseline) {\n if (!currentByRoot.has(point.rootId)) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'every baseline root to be present in the current revision set',\n actual: point.rootId,\n hint: 'do not apply a partial root set over the verified baseline',\n authority: 'catalog',\n };\n }\n }\n\n return undefined;\n}\n\nfunction rowRevisionDiagnostic(\n entries: ReadonlyMap<string, CatalogEntry>,\n delta: CatalogDelta,\n): CatalogDiagnostic | undefined {\n for (const entry of [...delta.added, ...delta.changed]) {\n const prior = entries.get(guidKey(entry.guid));\n if (prior?.revision === undefined) continue;\n if (prior !== undefined && sameValue(prior, entry)) continue;\n if (entry.revision === undefined) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'a replacement row to carry a newer producer revision',\n actual: `${prior.revision.rootId}@${prior.revision.observedAt} -> missing`,\n hint: 'restore the producer revision before applying the catalog change',\n authority: 'catalog',\n };\n }\n if (entry.revision.observedAt < prior.revision.observedAt) {\n return {\n code: 'catalog-revision-stale',\n severity: 'blocking',\n expected: 'a replacement row to carry a non-decreasing producer revision',\n actual: `${prior.revision.observedAt} -> ${entry.revision.observedAt}`,\n hint: 'discard the stale update and request a fresh catalog snapshot',\n authority: 'catalog',\n };\n }\n if (entry.revision.observedAt === prior.revision.observedAt) {\n return {\n code: 'catalog-revision-conflict',\n severity: 'blocking',\n expected: 'a changed row to advance its producer revision',\n actual: sameRevision(prior.revision, entry.revision)\n ? `${prior.revision.observedAt} -> ${entry.revision.observedAt}`\n : `${prior.revision.digest} -> ${entry.revision.digest}`,\n hint: 'publish a new producer revision for changed payload bytes',\n authority: 'catalog',\n };\n }\n }\n return undefined;\n}\n\nfunction diagnosticForScopeMismatch(): CatalogDiagnostic {\n return {\n code: 'catalog-scope-mismatch',\n severity: 'blocking',\n expected: 'catalog delta scopeId and generation to match the active runtime binding',\n hint: 'discard the stale publication and reconcile the active runtime catalog',\n authority: 'catalog',\n };\n}\n\nfunction appendDiagnostic(\n diagnostics: readonly CatalogDiagnostic[],\n incoming: readonly CatalogDiagnostic[] | undefined,\n): readonly CatalogDiagnostic[] {\n const next = [...diagnostics];\n for (const diagnostic of incoming ?? []) {\n if (!next.some((existing) => existing.code === diagnostic.code)) next.push(diagnostic);\n }\n return next;\n}\n\n/**\n * One authoritative catalog read model owned by AssetRegistry.\n *\n * The source subscription is installed before the first enumeration. Deltas\n * observed during that baseline read are buffered and folded afterwards, so\n * an early publication cannot disappear between the two operations.\n */\nexport class CatalogReplica {\n private readonly source: CatalogSource;\n private readonly listeners = new Set<CatalogDeltaListener>();\n private readonly entries = new Map<string, CatalogEntry>();\n private pendingBeforeBaseline: CatalogDelta[] = [];\n private pendingDuringReconcile: CatalogDelta[] | undefined;\n private unsubscribe: (() => void) | undefined;\n private startPromise: Promise<SnapshotResult> | undefined;\n private baselineReady = false;\n private version = 0;\n private stale = false;\n private diagnostics: readonly CatalogDiagnostic[] = [];\n private currentSnapshot: CatalogReplicaSnapshot;\n private readonly expectedScope: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'> | undefined;\n\n constructor(source: CatalogSource) {\n this.source = source;\n this.expectedScope = source.expectedScope;\n this.currentSnapshot = freezeSnapshot({\n version: 0,\n entries: [],\n stale: false,\n diagnostics: [],\n });\n }\n\n subscribe(listener: CatalogDeltaListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n snapshot(): CatalogReplicaSnapshot {\n return this.currentSnapshot;\n }\n\n dispose(): void {\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.startPromise = undefined;\n this.pendingBeforeBaseline = [];\n this.pendingDuringReconcile = undefined;\n this.listeners.clear();\n }\n\n async start(): Promise<SnapshotResult> {\n if (this.startPromise !== undefined) return this.startPromise;\n if (this.unsubscribe === undefined) {\n this.unsubscribe = this.source.subscribe((delta) => this.receive(delta));\n }\n const promise = this.loadBaseline(false);\n this.startPromise = promise;\n void promise.then((result) => {\n if (!result.ok) this.startPromise = undefined;\n });\n return promise;\n }\n\n async reconcile(): Promise<SnapshotResult> {\n if (this.unsubscribe === undefined) {\n this.unsubscribe = this.source.subscribe((delta) => this.receive(delta));\n }\n this.pendingDuringReconcile = [];\n return this.loadBaseline(true);\n }\n\n private async loadBaseline(isReconcile: boolean): Promise<SnapshotResult> {\n const result = await this.source.enumerate();\n if (!result.ok) {\n this.stale = true;\n this.currentSnapshot = this.makeSnapshot();\n if (!isReconcile) this.pendingBeforeBaseline = [];\n this.pendingDuringReconcile = undefined;\n return result;\n }\n\n this.entries.clear();\n for (const entry of result.value) this.entries.set(guidKey(entry.guid), freezeEntry(entry));\n this.stale = false;\n this.diagnostics = [];\n this.baselineReady = true;\n const pending = isReconcile ? (this.pendingDuringReconcile ?? []) : this.pendingBeforeBaseline;\n this.pendingBeforeBaseline = [];\n this.pendingDuringReconcile = undefined;\n for (const delta of pending) this.fold(delta, false);\n this.currentSnapshot = this.makeSnapshot();\n return ok(this.currentSnapshot);\n }\n\n private receive(delta: CatalogDelta): void {\n if (!this.baselineReady) {\n if (this.pendingDuringReconcile !== undefined) this.pendingDuringReconcile.push(delta);\n else this.pendingBeforeBaseline.push(delta);\n this.publish(this.safeDelta(delta));\n return;\n }\n if (this.pendingDuringReconcile !== undefined) {\n this.pendingDuringReconcile.push(delta);\n this.publish(this.safeDelta(delta));\n return;\n }\n this.fold(delta, true);\n }\n\n private fold(delta: CatalogDelta, publish: boolean): void {\n const safeDelta = this.safeDelta(delta);\n const degraded = safeDelta.authority === 'degraded';\n this.stale = this.stale || degraded;\n this.diagnostics = appendDiagnostic(\n this.diagnostics,\n safeDelta.diagnostics?.some((diagnostic) => diagnostic.code === 'catalog-gap')\n ? [...(safeDelta.diagnostics ?? []), diagnosticForGap()]\n : safeDelta.diagnostics,\n );\n\n if (!degraded) {\n let changed = false;\n for (const entry of [...safeDelta.added, ...safeDelta.changed]) {\n const key = guidKey(entry.guid);\n const prior = this.entries.get(key);\n if (revisionIsOlder(entry.revision, prior?.revision)) continue;\n if (prior !== undefined && sameValue(prior, entry)) continue;\n this.entries.set(key, freezeEntry(entry));\n changed = true;\n }\n for (const guid of safeDelta.removed) {\n if (this.entries.delete(guidKey(guid))) changed = true;\n }\n if (changed) this.version += 1;\n }\n\n this.currentSnapshot = this.makeSnapshot();\n if (publish) {\n this.publish(safeDelta);\n }\n }\n\n private safeDelta(delta: CatalogDelta): CatalogDelta {\n const diagnostic =\n this.expectedScope !== undefined &&\n (delta.scopeId !== this.expectedScope.scopeId ||\n delta.generation !== this.expectedScope.generation)\n ? diagnosticForScopeMismatch()\n : delta.revisions === undefined\n ? rowRevisionDiagnostic(this.entries, delta)\n : (revisionDiagnostic(delta.revisions, hasIdentityChanges(delta)) ??\n rowRevisionDiagnostic(this.entries, delta));\n const degradedRows = delta.authority === 'degraded' && hasIdentityChanges(delta);\n if (diagnostic === undefined && !degradedRows) return delta;\n return {\n ...delta,\n added: [],\n changed: [],\n removed: [],\n authority: 'degraded',\n diagnostics: appendDiagnostic(\n [],\n [\n ...(diagnostic === undefined ? [] : [diagnostic]),\n ...(degradedRows ? [diagnosticForDegradedRows()] : []),\n ],\n ),\n };\n }\n\n private publish(delta: CatalogDelta): void {\n for (const listener of [...this.listeners]) {\n try {\n listener(delta);\n } catch {\n // One observer cannot prevent the remaining catalog observers from seeing a fact.\n }\n }\n }\n\n private makeSnapshot(): CatalogReplicaSnapshot {\n const entries = [...this.entries.values()].sort((left, right) =>\n guidKey(left.guid).localeCompare(guidKey(right.guid)),\n );\n this.currentSnapshot = freezeSnapshot({\n version: this.version,\n entries,\n stale: this.stale,\n diagnostics: this.diagnostics,\n });\n return this.currentSnapshot;\n }\n}\n","// M8 w59 (round 5 D-18 atomic): two-tier resolution + material-walk over\n// world.sharedRefs.\n//\n// D-15 two-tier asset resolution: slots in [1, BUILTIN_BASE) are builtins\n// (process-static, resolve through BuiltinAssetRegistry.resolve, never\n// reference-counted); slots >= BUILTIN_BASE are user-tier (resolve through\n// world.sharedRefs.resolve). Resolution is entirely ECS/render-side -- it\n// never goes through AssetRegistry (human-inputs implement-architecture-\n// correction 2026-06-16T12:35:07Z: AssetRegistry has NO handle concept).\n//\n// AI-user surface: `resolveAssetHandle(world, handle)` is the single entry\n// point for handle-to-payload resolution; `walkMaterialPassesOverSharedRefs`\n// is the material parent-chain walk used by the render extract stage. Charter\n// F1 single-entry indexability -- one import, one call, no dual-path leak.\n\nimport type { SharedRefStaleError, UniqueRefStaleError, World } from '@forgeax/engine-ecs';\nimport type { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { err, ok, type Result } from '@forgeax/engine-rhi';\nimport type {\n Asset,\n AssetError as AssetErrorType,\n Handle,\n MaterialAsset,\n MaterialError,\n MaterialPass,\n} from '@forgeax/engine-types';\nimport {\n ASSET_ERROR_HINTS,\n AssetError,\n BUILTIN_BASE,\n handleSlot,\n materialGuidText,\n resolveMaterialAsset,\n} from '@forgeax/engine-types';\nimport { BuiltinAssetRegistry } from './builtin-asset-registry';\n\n/**\n * Resolve a handle to its asset payload with two-tier slot-range dispatch.\n *\n * slot < BUILTIN_BASE -> BuiltinAssetRegistry.resolve(handle) (process-static)\n * slot >= BUILTIN_BASE -> world.sharedRefs.resolve(handle) (user-tier RC)\n *\n * Callers must specify the expected asset type explicitly:\n * `resolveAssetHandle<MeshAsset>(world, handle)`. The type parameter is an\n * assertion -- the runtime dispatch returns the correct payload based on slot\n * range; the type parameter mirrors the caller's expectation.\n *\n * @param world - The World owning the per-World SharedRefStore (user-tier).\n * @param handle - The branded handle to resolve.\n * @returns `Result.ok(payload)` on hit, `Result.err(AssetError)` on miss.\n */\nexport function resolveAssetHandle<T extends Asset>(\n world: World,\n handle: Handle<string, 'shared'>,\n): Result<T, AssetErrorType | SharedRefStaleError | UniqueRefStaleError> {\n const slot = handleSlot(handle);\n if (slot < BUILTIN_BASE) {\n const builtin = BuiltinAssetRegistry.resolve(handle);\n if (builtin !== null) return ok(builtin as unknown as T);\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `builtin slot ${slot} present in BuiltinAssetRegistry`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n const res = world.sharedRefs.resolve<string, T>(handle);\n if (res.ok) return ok(res.value);\n // Forward the closed error code transparently. Checking the discriminant,\n // rather than constructor identity, preserves the structured stale detail\n // when a browser bundles the bridge and its World through different module\n // instances.\n switch (res.error.code) {\n case 'shared-ref-stale':\n return err(res.error);\n case 'shared-ref-released':\n case 'builtin-slot-not-owned':\n break;\n }\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `user-tier slot ${slot} present in world.sharedRefs`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n}\n\n/**\n * Walk a MaterialAsset parent chain to produce the inherited passes +\n * shallow-merged values (W-1..W-7 semantics). feat-20260614 M8 (D-19):\n * the starting material is resolved from a column `handle` via\n * {@link resolveAssetHandle} (builtin / user-tier world.sharedRefs); each\n * ancestor `material.parent` is an embedded GUID (AssetGuid) resolved through\n * the AssetRegistry catalogue ({@link AssetRegistry.lookup}). The registry\n * holds no handles -- it is the GUID->payload SSOT for parent resolution.\n *\n * Zero-cache (AC-04): every call builds the same table-shaped input and delegates\n * inheritance semantics to the MaterialAsset resolver in `@forgeax/engine-types`.\n * Compiler and runtime therefore share root-contract ownership and child-value\n * override semantics instead of maintaining two subtly different walks.\n */\nexport function walkMaterialPassesOverSharedRefs(\n world: World,\n handle: Handle<'MaterialAsset', 'shared'>,\n registry: { lookup(guid: AssetGuid | string): Asset | undefined },\n): Result<\n {\n passes: MaterialPass[];\n parameters: MaterialAsset['parameters'];\n values: NonNullable<MaterialAsset['values']>;\n colorSpace: MaterialAsset['colorSpace'];\n },\n AssetErrorType | MaterialError | SharedRefStaleError | UniqueRefStaleError\n> {\n // Resolve the root material payload from its column handle.\n const rootRes = resolveAssetHandle<MaterialAsset>(\n world,\n handle as unknown as Handle<string, 'shared'>,\n );\n\n const rootLabel = `handle-${handleSlot(handle)}`;\n if (!rootRes.ok) return err(rootRes.error);\n\n const table: Record<string, MaterialAsset> = {};\n const visited = new Set<string>();\n const collect = (label: string, material: MaterialAsset): void => {\n if (visited.has(label)) return;\n visited.add(label);\n table[label] = material;\n if (material.parent === undefined) return;\n const parentId = materialGuidText(material.parent);\n const parent = registry.lookup(material.parent);\n if (parent?.kind === 'material') collect(parentId, parent);\n };\n collect(rootLabel, rootRes.value);\n\n const resolved = resolveMaterialAsset(rootLabel, table);\n if (!resolved.ok) return err(resolved.error);\n return ok({\n passes: [...(resolved.value.asset.passes ?? [])],\n parameters: resolved.value.asset.parameters ?? [],\n values: { ...(resolved.value.asset.values ?? {}) },\n colorSpace: resolved.value.asset.colorSpace,\n });\n}\n","// @forgeax/engine-assets-runtime — scene-handle-fields: shared reflection helper for\n// SceneAsset handle-field extraction (plan-strategy D-4 / requirements B-5).\n//\n// `_resolveSceneGuids` (instantiate) and `buildSceneChildContext` (breadcrumb)\n// consume this helper so the \"identify shared<...> / array<shared<...>> schema\n// fields + read GUID string\" logic has exactly one authoritative location\n// (Derive, Don't Duplicate).\n//\n// This helper returns raw GUID strings WITHOUT mutating the registry; resolution\n// to Handle numbers is the caller's responsibility.\n//\n// Both consumers prefer the structured `envelope.refs` edges (D-3) when an\n// envelope is catalogued for the scene, and fall back to this entity-component\n// walk only when no envelope (or no per-entity edge detail) is available:\n// - `_resolveSceneGuids`: envelope-less scenes (e.g. unit tests that build a\n// SceneAsset directly without cataloguing it; no `sceneGuidKey`).\n// - `buildSceneChildContext`: prod GUID-only refs[] edges whose `sourceField`\n// was stripped at the serialization boundary (w7 D-10), plus direct\n// `catalog()` scene registration with no refs. The walk recovers the\n// (entityLocalId, componentName, fieldName, arrayIndex) triple the bare\n// edge no longer carries.\n\nimport type { Component } from '@forgeax/engine-ecs';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport type { MountOverride } from '@forgeax/engine-types';\n\n/**\n * A single handle-field reference extracted from a SceneAsset entity.\n *\n * `entityLocalId` is the `node.localId`; `componentName` and `fieldName`\n * identify the schema field whose `fieldType` starts with `shared\\<` or\n * `array\\<shared\\<`. `guidString` is the raw GUID string value from the\n * entity's component data (NOT a parsed `AssetGuid` — callers parse or\n * resolve as needed).\n *\n * `arrayIndex` is `undefined` for plain `handle<T>` fields; for\n * `array<handle<T>>` fields it is the 0-based index into the array.\n */\nexport interface SceneHandleFieldEntry {\n readonly entityLocalId: number;\n readonly componentName: string;\n readonly fieldName: string;\n readonly guidString: string;\n /** 0-based index for `array<handle<T>>` elements; `undefined` for plain `handle<T>` fields. */\n readonly arrayIndex?: number;\n}\n\n/**\n * Shape of a single entity passed to {@link extractSceneEntityHandleGuids}.\n *\n * Compatible with both `SceneEntity` (from `@forgeax/engine-types`, where\n * `components` is `Partial<ComponentValuesMap>`) and test-side plain objects.\n */\ninterface SceneEntityLike {\n readonly localId: number;\n readonly components: Record<string, Record<string, unknown>>;\n}\n\n/**\n * Walk every `SceneEntityLike` in `entities` and extract all GUID strings\n * bound to schema fields with `handle<...>` or `array<handle<...>>` fieldType.\n *\n * Unknown component names (absent from the supplied World-local catalog) are\n * silently skipped — the ecs layer's `additionalProperties` check will catch\n * unknowns at spawn time if appropriate.\n *\n * Values that are already numbers (resolved Handles) or non-strings are\n * skipped (they are not GUID refs).\n *\n * @internal Shared by {@link AssetRegistry._resolveSceneGuids} and\n * `buildSceneChildContext` as the entity-walk fallback used when the structured\n * `envelope.refs` edges are unavailable or carry no per-entity detail.\n */\nexport function extractSceneEntityHandleGuids(\n components: ReadonlyMap<string, Component>,\n entities: ReadonlyArray<SceneEntityLike>,\n): SceneHandleFieldEntry[] {\n const entries: SceneHandleFieldEntry[] = [];\n\n for (const node of entities) {\n const rawComponents: Record<string, Record<string, unknown>> = node.components as Record<\n string,\n Record<string, unknown>\n >;\n\n for (const compName of Object.keys(rawComponents)) {\n const rawFields = rawComponents[compName];\n if (!rawFields) continue;\n\n const comp = components.get(compName);\n if (!comp) continue;\n\n for (const fieldName of Object.keys(rawFields)) {\n forEachHandleGuid(\n componentSchema(comp)[fieldName],\n rawFields[fieldName],\n (guidString, arrayIndex) => {\n entries.push({\n entityLocalId: node.localId,\n componentName: compName,\n fieldName,\n guidString,\n ...(arrayIndex !== undefined ? { arrayIndex } : {}),\n });\n },\n );\n }\n }\n }\n\n return entries;\n}\n\n/**\n * One handle-field GUID reference extracted from a {@link MountOverride}'s value\n * (feat-20260713 M3 / w12). Mirrors {@link SceneHandleFieldEntry} but keys on the\n * override's array index (there is no entity `localId` — an override targets a\n * mount member by its own `localId`, resolved by the ecs apply loop, not here).\n *\n * `fieldName` is the schema field the GUID binds to: the override's own `field`\n * for the patch form, or a key of the component-add value map for the add form.\n */\nexport interface MountOverrideHandleFieldEntry {\n /** 0-based index into the `overrides[]` array passed to the extractor. */\n readonly overrideIndex: number;\n readonly componentName: string;\n readonly fieldName: string;\n readonly guidString: string;\n /** 0-based index for `array<shared<T>>` elements; `undefined` for scalar `shared<T>`. */\n readonly arrayIndex?: number;\n}\n\n/**\n * Walk `overrides` and extract every GUID string bound to a `shared<...>` /\n * `array<shared<...>>` schema field inside each override's value (feat-20260713\n * M3 / w12, plan-strategy D-2). This is the apply-side counterpart to\n * {@link extractSceneEntityHandleGuids}: it feeds `resolveMountsRec`'s\n * GUID→handle down-drill so a `mounts[].overrides[].value` carrying a raw GUID\n * (e.g. an `AnimationPlayer.clips` clip GUID) resolves to a live handle before\n * the ecs apply loop, which only ever sees numeric handles (D-2: the GUID domain\n * stays sealed in assets-runtime).\n *\n * The `{comp, field?, value}` discriminant is normalized to `(fieldName, value)`\n * pairs: the patch form (`field` present) yields one pair; the component-add form\n * (`field` absent, `value` is a per-field map) yields one pair per value key.\n * Field type is judged from the supplied catalog token schema, the same\n * schema SSOT the entity walk uses. Unknown components / non-shared fields /\n * non-string (already-resolved number) values are skipped (D-8 number pass-through).\n *\n * @internal Shared identification core; resolution lives in `resolveMountsRec`.\n */\nexport function extractMountOverrideHandleGuids(\n components: ReadonlyMap<string, Component>,\n overrides: ReadonlyArray<MountOverride>,\n): MountOverrideHandleFieldEntry[] {\n const entries: MountOverrideHandleFieldEntry[] = [];\n\n for (let overrideIndex = 0; overrideIndex < overrides.length; overrideIndex++) {\n const ov = overrides[overrideIndex];\n if (ov === undefined) continue;\n\n const comp = components.get(ov.comp);\n if (!comp) continue;\n\n for (const [fieldName, value] of normalizeOverrideFields(ov)) {\n forEachHandleGuid(componentSchema(comp)[fieldName], value, (guidString, arrayIndex) => {\n entries.push({\n overrideIndex,\n componentName: ov.comp,\n fieldName,\n guidString,\n ...(arrayIndex !== undefined ? { arrayIndex } : {}),\n });\n });\n }\n }\n\n return entries;\n}\n\n/**\n * Normalize a {@link MountOverride}'s `{comp, field?, value}` shape into\n * `(fieldName, value)` pairs (feat-20260713 M3 / w12). Patch form (`field`\n * present) → one pair; component-add form (`field` absent, `value` a per-field\n * map) → one pair per value key. A non-object add value yields no pairs.\n */\nfunction normalizeOverrideFields(ov: MountOverride): ReadonlyArray<readonly [string, unknown]> {\n if (ov.field !== undefined) return [[ov.field, ov.value]];\n const value = ov.value;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return [];\n const map = value as Record<string, unknown>;\n return Object.keys(map).map((key) => [key, map[key]] as const);\n}\n\n/**\n * Shared handle-GUID identification core (feat-20260713 M3 / w12 SSOT): given a\n * schema `fieldType` and a `value`, invoke `sink(guidString, arrayIndex?)` for\n * every GUID string the field binds — once for a `shared<T>` scalar string, once\n * per string element of an `array<shared<T>>`. Non-shared fields, non-string\n * scalars, and non-string array elements (already-resolved handle numbers, D-8)\n * are skipped. Both the entity walk and the override walk route through here so\n * the \"is this a shared handle field + read its GUID\" logic has one home\n * (architecture-principles §1 SSOT).\n */\nfunction forEachHandleGuid(\n fieldType: string | undefined,\n value: unknown,\n sink: (guidString: string, arrayIndex?: number) => void,\n): void {\n if (fieldType === undefined || typeof fieldType !== 'string') return;\n if (fieldType.startsWith('shared<')) {\n if (typeof value === 'string') sink(value);\n return;\n }\n if (fieldType.startsWith('array<shared<') && Array.isArray(value)) {\n for (let elemIdx = 0; elemIdx < value.length; elemIdx++) {\n const elem = value[elemIdx];\n if (typeof elem === 'string') sink(elem, elemIdx);\n }\n }\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport type {\n AssetPublicationEnvelope,\n CatalogEntry,\n ScenePublicationFence as EngineScenePublicationFence,\n} from '@forgeax/engine-types';\n\nexport const SCENE_PUBLICATION_FENCE_SCHEMA = 'scene-publication-fence/1' as const;\nexport const SCENE_PUBLICATION_RECOVERY_ACTIONS = Object.freeze([\n 'continue-last-known-good',\n 'retry-rebuild',\n 'fresh-reopen',\n] as const);\n\nexport type ScenePublicationFence = EngineScenePublicationFence;\n\nexport type ScenePublicationFencePhase = 'publication' | 'catalog' | 'observation' | 'instantiate';\n\nexport interface ScenePublicationFenceError {\n readonly code: 'asset-generation-fence-mismatch';\n readonly phase: ScenePublicationFencePhase;\n readonly hint: string;\n readonly sourcePath?: string;\n readonly sourceRevision?: string;\n readonly expected?: ScenePublicationFence;\n readonly actual?: ScenePublicationFence;\n readonly currentGeneration?: number;\n readonly lastKnownGood?: ScenePublicationFence;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n}\n\nexport interface ScenePublicationObservation {\n readonly fence: ScenePublicationFence;\n readonly outputs: readonly string[];\n}\n\nfunction errorFor(\n phase: ScenePublicationFencePhase,\n hint: string,\n input: {\n readonly publication?: AssetPublicationEnvelope;\n readonly expected?: ScenePublicationFence;\n readonly actual?: ScenePublicationFence;\n readonly lastKnownGood?: ScenePublicationFence;\n readonly retryable?: boolean;\n } = {},\n): ScenePublicationFenceError {\n return {\n code: 'asset-generation-fence-mismatch',\n phase,\n hint,\n ...(input.publication === undefined\n ? {}\n : {\n sourcePath: input.publication.sourcePath,\n sourceRevision: input.publication.sourceRevision,\n }),\n ...(input.expected === undefined ? {} : { expected: input.expected }),\n ...(input.actual === undefined ? {} : { actual: input.actual }),\n ...(input.actual === undefined\n ? {}\n : { currentGeneration: input.actual.publicationGeneration }),\n ...(input.lastKnownGood === undefined ? {} : { lastKnownGood: input.lastKnownGood }),\n retryable: input.retryable ?? false,\n recoveryActions: SCENE_PUBLICATION_RECOVERY_ACTIONS,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction sameFence(left: ScenePublicationFence, right: ScenePublicationFence): boolean {\n return (\n left.schemaVersion === right.schemaVersion &&\n left.sourcePath === right.sourcePath &&\n left.sourceRevision === right.sourceRevision &&\n left.publicationGeneration === right.publicationGeneration &&\n left.outputDigest === right.outputDigest &&\n left.outputSetDigest === right.outputSetDigest &&\n left.receiptIdentity === right.receiptIdentity\n );\n}\n\n/** Convert one complete Engine publication into the serializable Scene fence. */\nexport function createScenePublicationFence(\n publication: AssetPublicationEnvelope,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n if (publication.outputs.length === 0) {\n return err(\n errorFor('publication', 'publication must contain at least one output', { publication }),\n );\n }\n if (!Number.isSafeInteger(publication.generation) || publication.generation < 1) {\n return err(\n errorFor('publication', 'publication generation must be a positive integer', { publication }),\n );\n }\n const receipt = publication.receipt;\n if (\n receipt.schemaVersion !== 'asset-publication-receipt/1' ||\n receipt.sourcePath !== publication.sourcePath ||\n receipt.sourceRevision !== publication.sourceRevision ||\n receipt.outputDigest !== publication.digest ||\n receipt.outputSetDigest !== publication.outputSetDigest\n ) {\n return err(\n errorFor('publication', 'publication receipt does not match the complete output tuple', {\n publication,\n }),\n );\n }\n const outputGuids = new Set<string>();\n for (const output of publication.outputs) {\n const key = output.guid.toLowerCase();\n if (outputGuids.has(key)) {\n return err(\n errorFor('publication', 'publication output GUIDs must be unique', { publication }),\n );\n }\n outputGuids.add(key);\n }\n return ok({\n schemaVersion: SCENE_PUBLICATION_FENCE_SCHEMA,\n sourcePath: publication.sourcePath,\n sourceRevision: publication.sourceRevision,\n publicationGeneration: publication.generation,\n outputDigest: publication.digest,\n outputSetDigest: publication.outputSetDigest,\n receiptIdentity: receipt.inputFingerprint,\n });\n}\n\n/** Parse the persisted fence without guessing legacy generation or identity. */\nexport function parseScenePublicationFence(\n value: unknown,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n if (\n !isRecord(value) ||\n value.schemaVersion !== SCENE_PUBLICATION_FENCE_SCHEMA ||\n typeof value.sourcePath !== 'string' ||\n typeof value.sourceRevision !== 'string' ||\n !Number.isSafeInteger(value.publicationGeneration) ||\n (value.publicationGeneration as number) < 1 ||\n typeof value.outputDigest !== 'string' ||\n typeof value.outputSetDigest !== 'string' ||\n typeof value.receiptIdentity !== 'string'\n ) {\n return err(errorFor('publication', 'publication fence shape is incomplete or invalid'));\n }\n const generation = value.publicationGeneration as number;\n return ok(\n Object.freeze({\n schemaVersion: SCENE_PUBLICATION_FENCE_SCHEMA,\n sourcePath: value.sourcePath,\n sourceRevision: value.sourceRevision,\n publicationGeneration: generation,\n outputDigest: value.outputDigest,\n outputSetDigest: value.outputSetDigest,\n receiptIdentity: value.receiptIdentity,\n }),\n );\n}\n\n/** Compare all fence fields; no single generation or GUID may stand in for it. */\nexport function compareScenePublicationFences(\n expected: ScenePublicationFence,\n actual: ScenePublicationFence,\n lastKnownGood?: ScenePublicationFence,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n if (sameFence(expected, actual)) return ok(actual);\n const input = {\n expected,\n actual,\n retryable: true,\n ...(lastKnownGood === undefined ? {} : { lastKnownGood }),\n };\n return err(\n errorFor('observation', 'publication fence does not match the expected complete tuple', input),\n );\n}\n\n/** Derive a fence only when every Catalog row for the source publication is present and aligned. */\nexport function scenePublicationFenceFromCatalog(\n entries: readonly CatalogEntry[],\n outputGuid: string,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n const row = entries.find((entry) => entry.guid.toLowerCase() === outputGuid.toLowerCase());\n const publication = row?.publication;\n if (publication === undefined) {\n return err(errorFor('catalog', 'Catalog row has no complete publication tuple'));\n }\n const expected = new Set(publication.outputs.map((output) => output.guid.toLowerCase()));\n const observed = entries.filter((entry) => expected.has(entry.guid.toLowerCase()));\n if (\n observed.length !== expected.size ||\n observed.some(\n (entry) =>\n entry.publication?.sourcePath !== publication.sourcePath ||\n entry.publication?.generation !== publication.generation ||\n entry.publication?.digest !== publication.digest ||\n entry.publication?.outputSetDigest !== publication.outputSetDigest,\n )\n ) {\n return err(\n errorFor('catalog', 'Catalog does not contain one complete publication tuple', {\n publication,\n }),\n );\n }\n return createScenePublicationFence(publication);\n}\n\nexport async function observeScenePublication(input: {\n readonly publication: AssetPublicationEnvelope;\n readonly waitForOutput: (guid: string) => Promise<void>;\n readonly timeoutMs?: number;\n readonly lastKnownGood?: ScenePublicationFence;\n}): Promise<Result<ScenePublicationObservation, ScenePublicationFenceError>> {\n const created = createScenePublicationFence(input.publication);\n if (!created.ok) return created;\n const timeoutMs = input.timeoutMs ?? 5_000;\n const wait = Promise.all(\n input.publication.outputs.map((output) => input.waitForOutput(output.guid)),\n );\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n wait,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('publication-observation-timeout')), timeoutMs);\n }),\n ]);\n } catch {\n const failureInput = {\n publication: input.publication,\n actual: created.value,\n retryable: true,\n ...(input.lastKnownGood === undefined ? {} : { lastKnownGood: input.lastKnownGood }),\n };\n return err(\n errorFor(\n 'observation',\n 'publication output observation did not complete before the fence deadline',\n failureInput,\n ),\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n return ok({\n fence: created.value,\n outputs: input.publication.outputs.map((output) => output.guid),\n });\n}\n","// @forgeax/engine-assets-runtime -- scene instantiate collaboration module\n// (feat-20260705-runtime-tier2-decomposition M1 / w6, D-4 + D-1). Free functions\n// taking the AssetRegistry instance as first param; logic byte-preserved from the\n// class body (this. -> registry.). Hosts the SkinJointResolver + PostSpawnHook\n// hook-contract types relocated from scene-instances/post-spawn-resolve-joints.ts\n// (D-1); w9 wires PostSpawnHook into the AssetRegistry constructor.\n\nimport type { EcsError, EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { PackError } from '@forgeax/engine-pack/errors';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { err, ok, type Result } from '@forgeax/engine-rhi';\nimport {\n worldDespawnScene,\n worldInstantiateScene,\n worldInstantiateSceneFlat,\n worldSetSceneAssetResolver,\n} from '@forgeax/engine-scene';\nimport {\n type Asset,\n type AssetEnvelope,\n AssetError,\n type CatalogEntry,\n type Handle,\n type MountOverride,\n PACK_ERROR_HINTS,\n type SceneAsset,\n type SceneInstanceMount,\n type SkeletonAsset,\n type SkinAsset,\n type TagOf,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry } from '../asset-registry';\nimport { resolveAssetHandle } from '../resolve-asset-handle';\nimport {\n extractMountOverrideHandleGuids,\n extractSceneEntityHandleGuids,\n} from '../scene-handle-fields';\nimport {\n compareScenePublicationFences,\n parseScenePublicationFence,\n type ScenePublicationFence,\n type ScenePublicationFenceError,\n scenePublicationFenceFromCatalog,\n} from './scene-publication-fence';\n\n/**\n * Resolver contract consumed by {@link postSpawnResolveJoints} (D-1: relocated\n * here from scene-instances/post-spawn-resolve-joints.ts so the hook contract\n * travels with the instantiate cluster into @forgeax/engine-assets-runtime).\n */\nexport interface SkinJointResolver {\n resolveSkinAsset(skeletonHandleRaw: number): SkinAsset | undefined;\n}\n\nfunction catalogSourceGuidForFence(\n registry: AssetRegistry,\n expected: ScenePublicationFence,\n): string | undefined {\n const entries = catalogEntriesForFence(registry);\n for (const entry of entries) {\n if (entry.kind !== 'scene') continue;\n const current = scenePublicationFenceFromCatalog(entries, entry.guid);\n if (current.ok && compareScenePublicationFences(expected, current.value).ok) {\n return entry.guid;\n }\n }\n return undefined;\n}\n\n/** Merge the live Edit Catalog and the Play pack-index projection for fences. */\nfunction catalogEntriesForFence(registry: AssetRegistry): readonly CatalogEntry[] {\n const byGuid = new Map<string, CatalogEntry>();\n for (const entry of registry.catalogSnapshot()?.entries ?? []) {\n byGuid.set(entry.guid.toLowerCase(), entry);\n }\n for (const [guid, record] of registry.packIndexCache ?? []) {\n if (record.sourcePath === undefined) continue;\n const candidate = { ...record, guid, sourcePath: record.sourcePath } as CatalogEntry;\n const current = byGuid.get(guid.toLowerCase());\n if (current === undefined || candidate.publication !== undefined) {\n // A persisted Scene fence is captured from the complete pack-index\n // publication at save time. If the CatalogReplica is still carrying its\n // previous tuple during the watcher handoff, keep the same pack-index\n // authority here or the freshly reopened scene will reject its own\n // mount with asset-generation-fence-mismatch.\n byGuid.set(guid.toLowerCase(), candidate);\n }\n }\n return [...byGuid.values()];\n}\n\n/** Derive a publication fence from the registry's unified live projections. */\nexport function scenePublicationFenceFromRegistry(\n registry: AssetRegistry,\n outputGuid: string,\n): Result<ScenePublicationFence, ScenePublicationFenceError> {\n return scenePublicationFenceFromCatalog(catalogEntriesForFence(registry), outputGuid);\n}\n\n/**\n * Post-spawn hook contract (D-1). A hook runs after instantiate spawns the\n * scene subtree; the shipped implementation is runtime's `postSpawnResolveJoints`\n * (auto-wire Skin.joints). Injected at the sole production assembly point\n * (createRenderer) in w9/w10; when absent, instantiate skips joint wiring.\n */\nexport type PostSpawnHook = (\n world: World,\n resolver: SkinJointResolver,\n root: EntityHandle,\n) => { ok: true } | { ok: false; error: unknown };\n\n/**\n * Remove the entities and producer grants created by one instantiate call.\n *\n * GUID fields use World interning, so an interned handle is released only when\n * its producer grant is the last live reference. A failed scene has no live\n * holders after `despawnScene`; a handle retained by an unrelated sibling is\n * therefore left untouched. Fresh scene and nested-scene alloc grants are\n * always released after their spawned holders are gone.\n */\nfunction rollbackSpawn(\n world: World,\n roots: readonly EntityHandle[],\n allocHandles: readonly number[],\n internedHandles: readonly number[],\n sharedRefBaseline: number,\n): void {\n for (const root of new Set(roots)) {\n void worldDespawnScene(world, root);\n }\n\n for (const raw of new Set(allocHandles)) {\n const handle = raw as never;\n if (world.sharedRefs.refcount(handle) > 0) void world.sharedRefs.release(handle);\n }\n\n for (const raw of new Set(internedHandles)) {\n if (world.sharedRefs._liveCount() <= sharedRefBaseline) break;\n const handle = raw as never;\n if (world.sharedRefs.refcount(handle) === 1) void world.sharedRefs.release(handle);\n }\n}\n\n/**\n * Materialise a `SceneAsset` into an existing `World` and return the\n * synthetic root `Entity` (feat-20260514 w31 sugar wrapper; AC-03 +\n * requirements §IN-3; M3: returns Entity not SceneInstanceId).\n *\n * Before spawning, handle-type component fields (e.g. `assetHandle`,\n * `material`, `skeleton`) containing GUID strings are resolved to fresh\n * user-tier `Handle` numbers via `world.allocSharedRef` (feat-20260614 M8\n * D-19 instantiate-time GUID->handle mint; supersedes the pre-D-17\n * `resolveGuid` map). GUIDs that fail to parse or are not catalogued return\n * `AssetError(code='asset-not-found')` with a hint containing the GUID,\n * node localId, and field name.\n *\n * Errors propagate verbatim through the closed\n * `AssetError | PackError | EcsError` union so AI users that already\n * narrow `loadByGuid<SceneAsset>` results reuse the same `switch\n * (err.code)` exhaustively (charter proposition 3 machine-readable\n * union; plan-strategy §3.3 closed-union transparency).\n *\n * @example\n * ```ts\n * const sceneRes = await engine.assets.loadByGuid<SceneAsset>(roomGuid); // payload (D-17)\n * if (!sceneRes.ok) return;\n * const handle = world.allocSharedRef('SceneAsset', sceneRes.value); // mint column handle\n * const r = engine.assets.instantiate(handle, world);\n * if (!r.ok) {\n * switch (r.error.code) {\n * case 'asset-not-found':\n * case 'pack-cyclic-reference':\n * // ... AssetErrorCode | PackErrorCode | EcsErrorCode exhaustive\n * }\n * }\n * ```\n */\nexport function instantiate<T extends SceneAsset>(\n registry: AssetRegistry,\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent?: EntityHandle,\n expectedPublication?: ScenePublicationFence,\n): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError> {\n const sharedRefBaseline = world.sharedRefs._liveCount();\n const allocHandles: number[] = [];\n const internedHandles: number[] = [];\n // feat-20260614 M8 (D-15 / D-17): resolve the SceneAsset payload from the\n // handle through the two-tier `resolveAssetHandle` (builtin / user-tier\n // world.sharedRefs) -- the registry holds no handle->payload map. Scene\n // GUID-type component fields are then resolved to fresh user-tier handles\n // via `world.allocSharedRef` (instantiate-time GUID->handle mint). When the\n // handle does not resolve to a scene payload, fall through to the ecs-only\n // path (an externally-resolved SceneAssetResolver handle).\n let instantiateResult: Result<EntityHandle, AssetError | PackError | EcsError>;\n const sceneRes0 = resolveAssetHandle<SceneAsset>(\n world,\n handle as unknown as Handle<string, 'shared'>,\n );\n const sceneAsset = sceneRes0.ok ? sceneRes0.value : undefined;\n if (sceneAsset !== undefined && sceneAsset.kind !== 'scene') {\n return err(\n new AssetError({\n code: 'asset-invalid-value',\n expected: 'instantiate handle resolves to a SceneAsset',\n hint: `resolved asset kind was ${sceneAsset.kind}`,\n }),\n );\n }\n if (sceneAsset !== undefined && sceneAsset.kind === 'scene') {\n // feat-20260622 M3 / w8: find the scene's GUID key in the catalog\n // so _resolveSceneGuids can reverse-decode from envelope.refs edges.\n const sceneGuidKey = registry._guidForAsset(sceneAsset);\n if (expectedPublication !== undefined) {\n const entries = catalogEntriesForFence(registry);\n if (sceneGuidKey === undefined) {\n return err({\n code: 'asset-generation-fence-mismatch',\n phase: 'instantiate',\n hint: 'generated Scene source has no Catalog identity for publication fence validation',\n retryable: true,\n recoveryActions: ['continue-last-known-good', 'retry-rebuild', 'fresh-reopen'],\n } as const);\n }\n const current = scenePublicationFenceFromCatalog(entries, sceneGuidKey);\n if (!current.ok) return current;\n const matches = compareScenePublicationFences(expectedPublication, current.value);\n if (!matches.ok) return matches;\n }\n const guidToHandle = new Map<string, number>();\n const resolvedSceneHandles = new Map<string, number>();\n const sceneRes = registry._resolveSceneGuids(\n sceneAsset,\n world,\n sceneGuidKey,\n undefined,\n guidToHandle,\n resolvedSceneHandles,\n );\n if (!sceneRes.ok) {\n rollbackSpawn(\n world,\n [],\n [...resolvedSceneHandles.values()],\n [...guidToHandle.values()],\n sharedRefBaseline,\n );\n return sceneRes;\n }\n internedHandles.push(...guidToHandle.values());\n allocHandles.push(...resolvedSceneHandles.values());\n\n // feat-20260703 M1 (D-1): register the resolved copy -> original\n // catalog GUID in the origin reverse-index so _guidForAsset can\n // find it even after the local sceneGuidKey variable is discarded.\n if (sceneGuidKey !== undefined) {\n registry._originIndex.set(sceneRes.value, sceneGuidKey);\n }\n\n // Register the GUID-resolved SceneAsset as a shared ref so\n // Scene owner resolves it transparently. The shared\n // ref alloc-grant rc=1 stays held by the alloc; the SceneInstance spawn\n // retains to rc=2 and the despawn path releases back to rc=1.\n const sharedHandle = world.allocSharedRef('SceneAsset', sceneRes.value);\n allocHandles.push(unwrapHandle(sharedHandle));\n\n // m3-i3: wire identity resolver so mount.source already resolved\n // to a live handle number by _resolveMountsRec passes through.\n // Scene mount resolution calls this resolver; when source is a number (live handle),\n // return it as-is; when source is a string (unresolved GUID),\n // fail (should not happen after resolution, but fail-safe).\n worldSetSceneAssetResolver(world, (source, _parentHandle) => {\n if (typeof source === 'number') {\n return ok(source as unknown as Handle<'SceneAsset', 'shared'>);\n }\n return err({\n code: 'asset-not-found' as const,\n expected: `mount source GUID ${source} resolved before instantiate`,\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n });\n });\n\n // C-R2 (feat-20260622-s5 M6): instantiateScene now returns\n // `{ root, diagnostics }` on success. This runtime API keeps its\n // `Result<EntityHandle>` contract; unwrap to `root`. (Surfacing scene\n // unknown-field diagnostics through `assets.instantiate` is M7 README\n // scope — the Scene package owns this boundary.)\n const sceneInst = worldInstantiateScene(world, sharedHandle, parent);\n if (!sceneInst.ok) {\n rollbackSpawn(world, [], allocHandles, internedHandles, sharedRefBaseline);\n return sceneInst as unknown as Result<EntityHandle, AssetError | PackError | EcsError>;\n }\n instantiateResult = ok(sceneInst.value.root);\n } else {\n // Non-resolvable handle: original ecs direct path (backward compat).\n const sceneInst = worldInstantiateScene(\n world,\n handle as Handle<'SceneAsset', 'shared'>,\n parent,\n );\n if (!sceneInst.ok) {\n return sceneInst as unknown as Result<EntityHandle, AssetError | PackError | EcsError>;\n }\n instantiateResult = ok(sceneInst.value.root);\n }\n\n // Post-spawn hook: auto-wire Skin.joints from jointPaths. feat-20260614 M8\n // (D-15): the Skin column holds a user-tier SkeletonAsset handle; resolve\n // it to the payload via the two-tier `resolveAssetHandle`, then match the\n // catalogued SkinAsset whose resolved skeleton payload is the same object\n // (the registry holds no handle->guid index).\n //\n // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): the hook is\n // injected via `registry.postSpawnHook` (the sole production assembly point\n // createRenderer wires `postSpawnResolveJoints`). When no hook is present\n // (standalone / test registries without joint-wiring needs), instantiate\n // skips the post-spawn wiring silently -- the resolver closure below stays\n // inline (it reads registry-internal state: assetCatalog / _guidForAsset).\n const hook = registry.postSpawnHook;\n if (hook !== undefined) {\n const self = registry;\n const resolver: SkinJointResolver = {\n resolveSkinAsset(skeletonHandleRaw: number) {\n const skelRes = resolveAssetHandle<SkeletonAsset>(\n world,\n skeletonHandleRaw as unknown as Handle<string, 'shared'>,\n );\n if (!skelRes.ok) return undefined;\n const skeletonPayload = skelRes.value as Asset;\n const skeletonGuid = self._guidForAsset(skeletonPayload);\n if (skeletonGuid === undefined) return undefined;\n for (const [, envelope] of self.assetCatalog) {\n const asset = envelope.payload;\n if (asset.kind !== 'skin') continue;\n const skinSkeletonGuid = asset.skeletonGuid;\n if (skinSkeletonGuid === undefined) continue;\n if (skinSkeletonGuid.toLowerCase() === skeletonGuid) {\n return asset;\n }\n }\n return undefined;\n },\n };\n const jointResolveResult = hook(world, resolver, instantiateResult.value);\n if (!jointResolveResult.ok) {\n rollbackSpawn(\n world,\n [instantiateResult.value],\n allocHandles,\n internedHandles,\n sharedRefBaseline,\n );\n return { ok: false, error: jointResolveResult.error } as unknown as Result<\n EntityHandle,\n AssetError | PackError | EcsError\n >;\n }\n }\n\n return instantiateResult;\n}\n\n/**\n * Materialise a `SceneAsset` FLAT into an existing `World` — the \"edit the\n * scene itself\" registry entry (#655). Shares the GUID-resolution + shared-ref +\n * SceneAssetResolver prelude with {@link instantiate}, but calls\n * `worldInstantiateSceneFlat` instead of `worldInstantiateScene`: NO synthetic\n * SceneInstance root, NO forced `ChildOf` on top-level members. The scene's own\n * entities become plain top-level world entities; nested prefabs (`mounts[]`)\n * still become their own SceneInstance anchors. Returns the set of top-level\n * entity handles.\n *\n * Use this to OPEN a scene for authoring; use {@link instantiate} (anchor) at\n * runtime / Play and for nested prefabs.\n *\n * The post-spawn Skin.joints hook (when wired via `registry.postSpawnHook`)\n * runs once per top-level root: each GLB root keeps its own `ChildOf` subtree,\n * so joint resolution is scoped to each subtree exactly as the anchor path\n * scopes it to the single synthetic root.\n */\nexport function instantiateFlat<T extends SceneAsset>(\n registry: AssetRegistry,\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n expectedPublication?: ScenePublicationFence,\n): Result<EntityHandle[], AssetError | PackError | EcsError | ScenePublicationFenceError> {\n const sharedRefBaseline = world.sharedRefs._liveCount();\n const allocHandles: number[] = [];\n const internedHandles: number[] = [];\n let roots: EntityHandle[];\n let mountEntities: EntityHandle[];\n const sceneRes0 = resolveAssetHandle<SceneAsset>(\n world,\n handle as unknown as Handle<string, 'shared'>,\n );\n const sceneAsset = sceneRes0.ok ? sceneRes0.value : undefined;\n if (sceneAsset !== undefined && sceneAsset.kind === 'scene') {\n const sceneGuidKey = registry._guidForAsset(sceneAsset);\n if (expectedPublication !== undefined) {\n const entries = catalogEntriesForFence(registry);\n if (sceneGuidKey === undefined) {\n return err({\n code: 'asset-generation-fence-mismatch',\n phase: 'instantiate',\n hint: 'generated Scene source has no Catalog identity for publication fence validation',\n retryable: true,\n recoveryActions: ['continue-last-known-good', 'retry-rebuild', 'fresh-reopen'],\n } as const);\n }\n const current = scenePublicationFenceFromCatalog(entries, sceneGuidKey);\n if (!current.ok) return current;\n const matches = compareScenePublicationFences(expectedPublication, current.value);\n if (!matches.ok) return matches;\n }\n const guidToHandle = new Map<string, number>();\n const resolvedSceneHandles = new Map<string, number>();\n const sceneRes = registry._resolveSceneGuids(\n sceneAsset,\n world,\n sceneGuidKey,\n undefined,\n guidToHandle,\n resolvedSceneHandles,\n );\n if (!sceneRes.ok) {\n rollbackSpawn(\n world,\n [],\n [...resolvedSceneHandles.values()],\n [...guidToHandle.values()],\n sharedRefBaseline,\n );\n return sceneRes;\n }\n internedHandles.push(...guidToHandle.values());\n allocHandles.push(...resolvedSceneHandles.values());\n if (sceneGuidKey !== undefined) {\n registry._originIndex.set(sceneRes.value, sceneGuidKey);\n }\n const sharedHandle = world.allocSharedRef('SceneAsset', sceneRes.value);\n allocHandles.push(unwrapHandle(sharedHandle));\n worldSetSceneAssetResolver(world, (source, _parentHandle) => {\n if (typeof source === 'number') {\n return ok(source as unknown as Handle<'SceneAsset', 'shared'>);\n }\n return err({\n code: 'asset-not-found' as const,\n expected: `mount source GUID ${source} resolved before instantiate`,\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n });\n });\n const sceneInst = worldInstantiateSceneFlat(world, sharedHandle);\n if (!sceneInst.ok) {\n rollbackSpawn(world, [], allocHandles, internedHandles, sharedRefBaseline);\n return sceneInst as unknown as Result<EntityHandle[], AssetError | PackError | EcsError>;\n }\n roots = sceneInst.value.roots;\n mountEntities = sceneInst.value.mountEntities;\n } else {\n const sceneInst = worldInstantiateSceneFlat(world, handle as Handle<'SceneAsset', 'shared'>);\n if (!sceneInst.ok) {\n return sceneInst as unknown as Result<EntityHandle[], AssetError | PackError | EcsError>;\n }\n roots = sceneInst.value.roots;\n mountEntities = sceneInst.value.mountEntities;\n }\n\n // Post-spawn Skin.joints wiring, per top-level root. Mirrors the anchor\n // path's hook (D-1: injected via `registry.postSpawnHook`); when no hook is\n // present the flat path skips joint wiring silently.\n const hook = registry.postSpawnHook;\n if (hook !== undefined) {\n const self = registry;\n const resolver: SkinJointResolver = {\n resolveSkinAsset(skeletonHandleRaw: number) {\n const skelRes = resolveAssetHandle<SkeletonAsset>(\n world,\n skeletonHandleRaw as unknown as Handle<string, 'shared'>,\n );\n if (!skelRes.ok) return undefined;\n const skeletonPayload = skelRes.value as Asset;\n const skeletonGuid = self._guidForAsset(skeletonPayload);\n if (skeletonGuid === undefined) return undefined;\n for (const [, envelope] of self.assetCatalog) {\n const asset = envelope.payload;\n if (asset.kind !== 'skin') continue;\n const skinSkeletonGuid = asset.skeletonGuid;\n if (skinSkeletonGuid === undefined) continue;\n if (skinSkeletonGuid.toLowerCase() === skeletonGuid) {\n return asset;\n }\n }\n return undefined;\n },\n };\n const hookRoots = new Set<EntityHandle>(roots);\n for (const mountEntity of mountEntities) hookRoots.add(mountEntity);\n for (const root of hookRoots) {\n const jointResolveResult = hook(world, resolver, root);\n if (!jointResolveResult.ok) {\n rollbackSpawn(\n world,\n [...roots, ...mountEntities],\n allocHandles,\n internedHandles,\n sharedRefBaseline,\n );\n return { ok: false, error: jointResolveResult.error } as unknown as Result<\n EntityHandle[],\n AssetError | PackError | EcsError\n >;\n }\n }\n }\n\n return ok(roots);\n}\n\n/**\n * m3-i2: Recursively resolve mounts[].source GUID strings.\n * Returns a PackError-shaped object on cycle (R-9) or AssetError\n * on child resolution failure.\n *\n * feat-20260713 M3 / w13: also down-drills `mounts[].overrides[].value`,\n * resolving any GUID string bound to a `shared<...>` / `array<shared<...>>`\n * schema field to a live handle (D-2). `guidToHandle` is the caller's per-scene\n * dedup map (shared with the entity-field resolution in `_resolveSceneGuids`) so\n * the same catalogued GUID mints exactly one user-tier handle across entity\n * fields and override values (D-15/D-17 dedup contract); it defaults to a fresh\n * map so standalone callers keep working. Override resolution runs for every\n * mount regardless of `source` branch — an unresolvable GUID fail-fasts here,\n * before any spawn (P3: no half-initialized member).\n */\nexport function resolveMountsRec(\n registry: AssetRegistry,\n mounts: readonly SceneInstanceMount[],\n world: World,\n visited: Set<string>,\n guidToHandle: Map<string, number> = new Map(),\n resolvedSceneHandles: Map<string, number> = new Map(),\n): Result<\n SceneInstanceMount[],\n | AssetError\n | {\n readonly code: 'pack-cyclic-reference';\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly code: 'pack-cyclic-reference';\n readonly kind: 'mount-asset';\n readonly cycle: readonly string[];\n };\n }\n | ScenePublicationFenceError\n> {\n const out: SceneInstanceMount[] = [];\n for (const m of mounts) {\n if (m.publicationFence !== undefined) {\n const parsedFence = parseScenePublicationFence(m.publicationFence);\n if (!parsedFence.ok) return parsedFence;\n const handleSourceGuid =\n typeof m.source === 'string'\n ? m.source\n : (() => {\n const resolved = resolveAssetHandle<SceneAsset>(world, m.source as never);\n return resolved.ok && resolved.value.kind === 'scene'\n ? registry._guidForAsset(resolved.value)\n : undefined;\n })();\n const sourceGuid =\n handleSourceGuid ??\n (typeof m.source === 'string'\n ? undefined\n : catalogSourceGuidForFence(registry, parsedFence.value));\n if (sourceGuid === undefined) {\n return err({\n code: 'asset-generation-fence-mismatch',\n phase: 'instantiate',\n hint: 'publication-fenced mount has no source GUID identity for validation',\n expected: parsedFence.value,\n retryable: true,\n recoveryActions: ['continue-last-known-good', 'retry-rebuild', 'fresh-reopen'],\n });\n }\n const currentFence = scenePublicationFenceFromCatalog(\n catalogEntriesForFence(registry),\n sourceGuid,\n );\n if (!currentFence.ok) return currentFence;\n const matches = compareScenePublicationFences(parsedFence.value, currentFence.value);\n if (!matches.ok) return matches;\n }\n let componentPatch:\n | { components: NonNullable<SceneInstanceMount['components']> }\n | Record<string, never> = {};\n if (m.components !== undefined) {\n const resolvedComponents = resolveMountComponents(\n registry,\n world,\n m.components,\n guidToHandle,\n );\n if (!resolvedComponents.ok) return resolvedComponents;\n componentPatch = {\n components: resolvedComponents.value as NonNullable<SceneInstanceMount['components']>,\n };\n }\n // Resolve override value GUIDs first — applies to every mount regardless of\n // the source branch below (a number-source mount can still carry overrides).\n let overridePatch: { overrides: readonly MountOverride[] } | Record<string, never> = {};\n if (m.overrides !== undefined && m.overrides.length > 0) {\n const ro = resolveMountOverrides(registry, world, m.overrides, guidToHandle);\n if (!ro.ok) return ro;\n overridePatch = { overrides: ro.value };\n }\n\n const src = m.source;\n // m3-i3: if source is already a number (live handle from a prior\n // resolution pass), pass through unchanged.\n if (typeof src === 'number') {\n out.push({ ...m, ...componentPatch, ...overridePatch });\n continue;\n }\n\n // source is a GUID string — resolve it.\n const guidKey = src.toLowerCase();\n\n // Cycle detection.\n if (visited.has(guidKey)) {\n return err({\n code: 'pack-cyclic-reference' as const,\n expected: 'no circular mount.source GUID references',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail: {\n code: 'pack-cyclic-reference' as const,\n kind: 'mount-asset' as const,\n cycle: [...visited, guidKey],\n },\n });\n }\n\n // Look up child scene.\n const childEnv = registry.assetCatalog.get(guidKey);\n if (childEnv === undefined) {\n // Not catalogued — pass through as-is (overrides still resolved above).\n out.push({ ...m, ...componentPatch, ...overridePatch });\n continue;\n }\n const childPayload = childEnv.payload;\n if (\n typeof childPayload !== 'object' ||\n childPayload === null ||\n (childPayload as Asset).kind !== 'scene'\n ) {\n out.push({ ...m, ...componentPatch, ...overridePatch });\n continue;\n }\n\n const cachedChildHandle = resolvedSceneHandles.get(guidKey);\n if (cachedChildHandle !== undefined) {\n out.push({\n ...m,\n source: cachedChildHandle,\n ...componentPatch,\n ...overridePatch,\n } as SceneInstanceMount);\n continue;\n }\n\n // Resolve mounts recursively.\n const childVisited = new Set(visited);\n // Don't add guidKey to visited here — _resolveSceneGuids will do it\n // via its own _visitedMountGuids parameter.\n const childRes = registry._resolveSceneGuids(\n childPayload as SceneAsset,\n world,\n guidKey,\n childVisited,\n guidToHandle,\n resolvedSceneHandles,\n true,\n );\n\n if (!childRes.ok) {\n // Propagate child resolution error.\n return childRes as unknown as Result<SceneInstanceMount[], AssetError>;\n }\n\n // Build resolved child with its own mounts.\n const resolvedChild: SceneAsset = {\n kind: 'scene',\n entities: childRes.value.entities,\n ...(childRes.value.mounts !== undefined && childRes.value.mounts.length > 0\n ? { mounts: childRes.value.mounts }\n : {}),\n } as SceneAsset;\n\n // allocSharedRef + register in originIndex (D-7).\n const chRaw = unwrapHandle(world.allocSharedRef('SceneAsset', resolvedChild));\n resolvedSceneHandles.set(guidKey, chRaw);\n registry._originIndex.set(resolvedChild, guidKey);\n\n // Replace source with live handle number (D-5: source is number|string).\n out.push({\n ...m,\n source: chRaw,\n ...componentPatch,\n ...overridePatch,\n } as SceneInstanceMount);\n }\n return ok(out);\n}\n\nfunction resolveMountComponents(\n registry: AssetRegistry,\n world: World,\n components: NonNullable<SceneInstanceMount['components']>,\n guidToHandle: Map<string, number>,\n): Result<Record<string, Record<string, unknown>>, AssetError> {\n const source = components as Record<string, Record<string, unknown>>;\n const output: Record<string, Record<string, unknown>> = {};\n for (const [componentName, fields] of Object.entries(source))\n output[componentName] = { ...fields };\n const entries = extractSceneEntityHandleGuids(world.components.entries(), [\n { localId: 0, components: source },\n ]);\n for (const entry of entries) {\n const fieldPath =\n `${entry.componentName}.${entry.fieldName}` +\n (entry.arrayIndex === undefined ? '' : `[${entry.arrayIndex}]`);\n const resolved = resolveHandleGuid(\n registry,\n world,\n entry.guidString,\n guidToHandle,\n fieldPath,\n 'mount.components',\n );\n if (!resolved.ok) return resolved;\n const fields = output[entry.componentName];\n if (fields === undefined) continue;\n if (entry.arrayIndex === undefined) {\n fields[entry.fieldName] = resolved.value;\n continue;\n }\n const current = fields[entry.fieldName];\n if (!Array.isArray(current)) continue;\n const next = [...current];\n next[entry.arrayIndex] = resolved.value;\n fields[entry.fieldName] = next;\n }\n return ok(output);\n}\n\n/**\n * Resolve one GUID string to a live user-tier handle (feat-20260713 M3 / w13\n * SSOT). Parses the GUID, uses `guidToHandle` as the per-resolution fast path,\n * and on a miss looks the envelope up in the catalog + interns its shared ref\n * by `(target, payload identity)` in the World. An unparseable / uncatalogued\n * GUID returns `AssetError(code='asset-not-found')` with a breadcrumb hint\n * (`fieldPath` + `location`) for AI-user debuggability (P3). Shared by the\n * entity-field fallback in `_resolveSceneGuids` and the override-value down-drill\n * in {@link resolveMountOverrides} so the parse/dedup/lookup/mint idiom has one\n * home (architecture-principles §1 SSOT).\n */\nexport function resolveHandleGuid(\n registry: AssetRegistry,\n world: World,\n guidString: string,\n guidToHandle: Map<string, number>,\n fieldPath: string,\n location: string,\n): Result<number, AssetError> {\n const guidRes = AssetGuid.parse(guidString);\n if (!guidRes.ok) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `valid GUID string for field ${fieldPath}`,\n hint: `GUID \"${guidString}\" could not be parsed; at ${location}, field=${fieldPath}`,\n }),\n );\n }\n const guidKey = guidString.toLowerCase();\n let slot = guidToHandle.get(guidKey);\n if (slot === undefined) {\n const envelope = registry.assetCatalog.get(guidKey);\n if (envelope === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidString} catalogued in AssetRegistry`,\n hint:\n `GUID ${guidString} not catalogued; ` +\n `call loadByGuid('${guidString}') before instantiate; ` +\n `at ${location}, field=${fieldPath}`,\n }),\n );\n }\n slot = unwrapHandle(world.internSharedRef(envelope.payload.kind, envelope.payload));\n guidToHandle.set(guidKey, slot);\n }\n return ok(slot);\n}\n\n/**\n * feat-20260713 M3 / w13: resolve every GUID string inside a mount's\n * `overrides[].value` to a live handle, returning a new overrides array whose\n * shared fields hold numeric handles (D-2 — the ecs apply loop never sees a\n * GUID). Identification is delegated to the shared w12 core\n * ({@link extractMountOverrideHandleGuids}); resolution reuses the\n * `envelope.payload → world.internSharedRef` path with the caller's\n * `guidToHandle` fast path (D-15/D-17). Stop-on-first-error: an unparseable /\n * uncatalogued GUID\n * returns `AssetError(code='asset-not-found')` with a breadcrumb hint (P3),\n * aborting before any spawn. Number elements pass through untouched (D-8).\n */\nfunction resolveMountOverrides(\n registry: AssetRegistry,\n world: World,\n overrides: readonly MountOverride[],\n guidToHandle: Map<string, number>,\n): Result<MountOverride[], AssetError> {\n const entries = extractMountOverrideHandleGuids(world.components.entries(), overrides);\n if (entries.length === 0) return ok([...overrides]);\n\n // resolvedMap key: `${overrideIndex}|${fieldName}|${arrayIndex ?? ''}`.\n const resolvedMap = new Map<string, number>();\n for (const entry of entries) {\n const fieldPath =\n `${entry.componentName}.${entry.fieldName}` +\n (entry.arrayIndex !== undefined ? `[${entry.arrayIndex}]` : '');\n const slot = resolveHandleGuid(\n registry,\n world,\n entry.guidString,\n guidToHandle,\n fieldPath,\n `mount override index=${entry.overrideIndex}`,\n );\n if (!slot.ok) return slot;\n resolvedMap.set(\n overrideFieldKey(entry.overrideIndex, entry.fieldName, entry.arrayIndex),\n slot.value,\n );\n }\n\n // Reconstruct: substitute resolved handles back into each override's value.\n const out: MountOverride[] = [];\n for (let ovIdx = 0; ovIdx < overrides.length; ovIdx++) {\n out.push(reconstructOverride(overrides[ovIdx] as MountOverride, ovIdx, resolvedMap));\n }\n return ok(out);\n}\n\n/** resolvedMap key for a resolved override handle. */\nfunction overrideFieldKey(overrideIndex: number, fieldName: string, arrayIndex?: number): string {\n return `${overrideIndex}|${fieldName}|${arrayIndex ?? ''}`;\n}\n\n/**\n * Rebuild one override with its shared-field GUID strings replaced by resolved\n * handles from `resolvedMap`. Preserves object identity when nothing resolved\n * (no shared GUID in this override). Patch form substitutes the single `value`;\n * add form substitutes each key of the value map.\n */\nfunction reconstructOverride(\n ov: MountOverride,\n ovIdx: number,\n resolvedMap: Map<string, number>,\n): MountOverride {\n if (ov.field !== undefined) {\n const nv = reconstructFieldValue(ovIdx, ov.field, ov.value, resolvedMap);\n return nv === ov.value ? ov : { ...ov, value: nv };\n }\n const value = ov.value;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return ov;\n const map = value as Record<string, unknown>;\n let changed = false;\n const next: Record<string, unknown> = {};\n for (const key of Object.keys(map)) {\n const nv = reconstructFieldValue(ovIdx, key, map[key], resolvedMap);\n next[key] = nv;\n if (nv !== map[key]) changed = true;\n }\n return changed ? { ...ov, value: next } : ov;\n}\n\n/**\n * Resolve one field value: a scalar `shared<T>` string becomes its handle; an\n * `array<shared<T>>` becomes an array with resolved handles substituted and\n * already-numeric elements passed through (D-8). Non-shared / unresolved values\n * pass through unchanged (identity preserved).\n */\nfunction reconstructFieldValue(\n ovIdx: number,\n fieldName: string,\n value: unknown,\n resolvedMap: Map<string, number>,\n): unknown {\n const scalar = resolvedMap.get(overrideFieldKey(ovIdx, fieldName));\n if (scalar !== undefined) return scalar;\n if (Array.isArray(value)) {\n const arr: unknown[] = [];\n let anyResolved = false;\n for (let i = 0; i < value.length; i++) {\n const resolved = resolvedMap.get(overrideFieldKey(ovIdx, fieldName, i));\n if (resolved !== undefined) {\n arr.push(resolved);\n anyResolved = true;\n } else {\n arr.push(value[i]);\n }\n }\n return anyResolved ? arr : value;\n }\n return value;\n}\n\n/**\n * tweak-20260609 M1 helper: build the per-sub-ref parent context for a\n * SceneAsset child. feat-20260622 M3 / w9: re-sourced to lookup in the\n * scene envelope's ``refs[]`` edges instead of walking entity components\n * via extractSceneEntityHandleGuids (D-7). When the scene envelope is not\n * found in the catalog, falls back to the entity-walk path (backward compat\n * for call sites that lack a catalogued envelope).\n *\n * Texture edges (sourceField=undefined) produce ``componentField:\n * undefined`` — the breadcrumb will show GUID+kind only, no per-entity\n * detail (D-2: texture has no per-entity origin).\n */\nexport function buildSceneChildContext(\n registry: AssetRegistry,\n scene: Asset & { kind: 'scene' },\n subGuidKey: string,\n sceneGuidKey?: string,\n):\n | {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n }\n | undefined {\n // feat-20260622 M3 / w9: direct lookup in envelope.refs edges.\n // feat-20260622 review r1: address the recursing scene's OWN envelope by\n // its guidKey, not the first scene in the catalog -- under a multi-scene\n // glTF catalog the first-scene scan attributes the breadcrumb to the wrong\n // scene. Fall back to the first-scene scan only when no guidKey is given\n // (legacy call sites lacking a catalogued envelope).\n let sceneEnvelope: AssetEnvelope | undefined;\n if (sceneGuidKey !== undefined) {\n const env = registry.assetCatalog.get(sceneGuidKey);\n if (env?.kind === 'scene') sceneEnvelope = env;\n }\n if (sceneEnvelope === undefined) {\n for (const [, env] of registry.assetCatalog) {\n if (env.kind === 'scene' && env.refs !== undefined && env.refs.length > 0) {\n sceneEnvelope = env;\n break;\n }\n }\n }\n let edgeResult:\n | {\n sceneEntityId?: number;\n componentField?: string;\n }\n | undefined;\n if (sceneEnvelope?.refs !== undefined) {\n for (const ref of sceneEnvelope.refs) {\n if (ref.guid.toLowerCase() === subGuidKey) {\n const { sceneEntityId, sourceField } = ref;\n const result: {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n } = {};\n if (sceneEntityId !== undefined) {\n result.sceneEntityId = sceneEntityId;\n }\n if (sourceField?.componentName !== undefined && sourceField?.fieldName !== undefined) {\n result.componentField =\n `${sourceField.componentName}.${sourceField.fieldName}` +\n (sourceField.arrayIndex !== undefined ? `[${sourceField.arrayIndex}]` : '');\n }\n if (sourceField !== undefined) {\n result.sourceField = sourceField;\n }\n // A rich edge (dev register path) carries full detail — return now.\n if (result.sceneEntityId !== undefined || result.componentField !== undefined) {\n return result;\n }\n // feat-20260622 M4 / w14: a GUID-only edge (prod path: on-disk refs[]\n // strip sourceField / sceneEntityId at the serialization boundary, w7\n // D-10) carries no per-entity detail. Keep this empty-but-defined\n // result as the fallback, then try the entity walk below to recover\n // the entity localId + component.field path (D-7 / B-8). The walk\n // recovers handle-field edges (mesh / material); a texture edge (D-2:\n // no per-entity origin) is not found by the walk, so the empty\n // edgeResult is returned (w10 texture-edge contract preserved).\n edgeResult = result;\n break;\n }\n }\n }\n // Backward compat: fall back to entity walk when the envelope edge carries\n // no per-entity detail (prod path: GUID-only refs[]) or no envelope is\n // available (e.g. direct catalog() registration with scene payload, no refs).\n const entries = extractSceneEntityHandleGuids(\n registry.componentCatalog,\n scene.entities as unknown as ReadonlyArray<{\n readonly localId: number;\n readonly components: Record<string, Record<string, unknown>>;\n }>,\n );\n for (const entry of entries) {\n if (entry.guidString.toLowerCase() === subGuidKey) {\n return {\n sceneEntityId: entry.entityLocalId,\n componentField: `${entry.componentName}.${entry.fieldName}${entry.arrayIndex !== undefined ? `[${entry.arrayIndex}]` : ''}`,\n // feat-20260622 verify r1: also surface the recovered provenance in\n // structured parts so the failure `.detail` can expose them for AI\n // property access (charter P3), not only the concatenated hint string.\n sourceField: {\n componentName: entry.componentName,\n fieldName: entry.fieldName,\n ...(entry.arrayIndex !== undefined ? { arrayIndex: entry.arrayIndex } : {}),\n },\n };\n }\n }\n return edgeResult;\n}\n\n/**\n * tweak-20260609 M1 helper: build the error-hint breadcrumb string\n * containing the parent asset's GUID + kind, enriched with the\n * caller-provided `parentContext` (entity localId + component.field).\n *\n * Per D-7 / B-8: the breadcrumb appears before the sub-asset's own hint,\n * separated by \" / \".\n */\nexport function buildBreadcrumbHint(\n parentGuidKey: string,\n parentKind: string,\n subGuidKey: string,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n): string {\n let breadcrumb = `sub-asset ${subGuidKey} referenced by ${parentKind} ${parentGuidKey}`;\n if (parentContext?.sceneEntityId !== undefined && parentContext?.componentField !== undefined) {\n breadcrumb += ` (entity ${parentContext.sceneEntityId}, field ${parentContext.componentField})`;\n }\n return breadcrumb;\n}\n","import {\n type CookedMaterialRecord,\n createMaterialArtifactDigest,\n validateCookedMaterialRecord,\n} from '@forgeax/engine-pack';\n\nexport interface MaterialLoadRequest {\n readonly guid: string;\n readonly specializationKey: string;\n}\n\nexport interface MaterialReady {\n readonly status: 'Ready';\n readonly guid: string;\n readonly materialGuid: string;\n readonly publicationGeneration: number;\n readonly specializationKey: string;\n readonly artifactDigest: string;\n readonly sourceClosure: readonly string[];\n readonly parameterContract: NonNullable<CookedMaterialRecord['parameterContract']>;\n readonly record: CookedMaterialRecord;\n readonly artifact: CookedMaterialRecord['artifact'];\n}\n\nexport interface MaterialPublication {\n readonly guid: string;\n readonly record: unknown;\n readonly artifactError?: {\n readonly code: 'asset-artifact-missing' | 'asset-artifact-integrity-mismatch';\n readonly expected: string;\n readonly actual?: string;\n };\n readonly artifact?: {\n readonly bytes: Uint8Array;\n readonly digest?: string;\n };\n}\n\nexport type MaterialLoadErrorCode =\n | 'material-specialization-not-cooked'\n | 'asset-artifact-missing'\n | 'asset-artifact-integrity-mismatch'\n | 'material-cook-record-invalid'\n | 'material-reference-not-ready';\n\nexport interface MaterialLoadErrorDetail {\n readonly guid: string;\n readonly specializationKey: string;\n readonly publicationGeneration?: number;\n readonly field?: string;\n readonly missing?: readonly string[];\n readonly expected?: string;\n readonly actual?: string;\n}\n\nexport interface MaterialLoadError {\n readonly status: 'Error';\n readonly error: {\n readonly code: MaterialLoadErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly retryable: boolean;\n readonly recoveryActions: readonly string[];\n readonly detail: MaterialLoadErrorDetail;\n };\n}\n\nexport interface MaterialLoaderOptions {\n readonly loadPublication: (\n guid: string,\n specializationKey: string,\n ) => Promise<MaterialPublication | undefined>;\n readonly loadReference?: (guid: string) => Promise<boolean>;\n}\n\nfunction materialError(\n request: MaterialLoadRequest,\n code: MaterialLoadErrorCode,\n expected: string,\n hint: string,\n detail: Omit<MaterialLoadErrorDetail, 'guid' | 'specializationKey'> = {},\n retryable = false,\n): MaterialLoadError {\n return {\n status: 'Error',\n error: {\n code,\n expected,\n hint,\n retryable,\n recoveryActions: retryable ? ['retry-material-load'] : ['recook-material-publication'],\n detail: { guid: request.guid, specializationKey: request.specializationKey, ...detail },\n },\n };\n}\n\nfunction missingCook(request: MaterialLoadRequest): MaterialLoadError {\n return materialError(\n request,\n 'material-specialization-not-cooked',\n 'a cooked material specialization record and artifact',\n 'run the build-time material cooker for this specialization before loading it at runtime',\n {},\n true,\n );\n}\n\nfunction recordError(\n request: MaterialLoadRequest,\n field: string,\n expected = 'a complete material-cook/3 publication record',\n): MaterialLoadError {\n return materialError(\n request,\n 'material-cook-record-invalid',\n expected,\n 're-publish the material record and its artifact as one immutable publication',\n { field },\n );\n}\n\nfunction immutableBytes(bytes: Uint8Array): Uint8Array {\n return new Uint8Array(bytes);\n}\n\nfunction immutableParameterContract(\n parameterContract: NonNullable<CookedMaterialRecord['parameterContract']>,\n): NonNullable<CookedMaterialRecord['parameterContract']> {\n return Object.freeze({\n parameters: Object.freeze([...parameterContract.parameters]),\n values: Object.freeze({ ...parameterContract.values }),\n });\n}\n\nfunction sameBytes(left: Uint8Array, right: Uint8Array): boolean {\n return left.byteLength === right.byteLength && left.every((byte, index) => byte === right[index]);\n}\n\nfunction completeTupleField(record: CookedMaterialRecord): string | undefined {\n if (\n typeof record.materialGuid !== 'string' ||\n !Number.isSafeInteger(record.publicationGeneration) ||\n (record.publicationGeneration as number) < 1\n )\n return 'publicationGeneration';\n if (typeof record.specializationKey !== 'string' || record.specializationKey.length === 0)\n return 'specializationKey';\n if (typeof record.artifactDigest !== 'string' || record.artifactDigest.length === 0)\n return 'artifactDigest';\n if (\n !Array.isArray(record.sourceClosure) ||\n record.sourceClosure.some((path) => typeof path !== 'string' || path.length === 0)\n )\n return 'sourceClosure';\n const parameterContract = record.parameterContract;\n if (\n parameterContract === undefined ||\n !Array.isArray(parameterContract.parameters) ||\n parameterContract.values === null ||\n typeof parameterContract.values !== 'object' ||\n Array.isArray(parameterContract.values)\n )\n return 'parameterContract';\n const receipt = record.receipt;\n if (\n !Array.isArray(receipt.sourceClosure) ||\n receipt.sourceClosure.some((path) => typeof path !== 'string' || path.length === 0) ||\n receipt.sourceClosure.length !== record.sourceClosure.length ||\n receipt.sourceClosure.some((path, index) => path !== record.sourceClosure?.[index])\n )\n return 'receipt.sourceClosure';\n if (\n typeof receipt.profile !== 'string' ||\n receipt.profile.length === 0 ||\n typeof receipt.compilerVersion !== 'string' ||\n receipt.compilerVersion.length === 0 ||\n typeof receipt.identity.cookIdentity !== 'string' ||\n receipt.identity.cookIdentity.length === 0 ||\n receipt.identity.artifactDigest !== record.artifactDigest ||\n receipt.identity.cookGeneration !== record.publicationGeneration\n )\n return 'receipt';\n if (\n typeof receipt.identity.layoutIdentity !== 'string' ||\n receipt.identity.layoutIdentity.length === 0 ||\n receipt.derivedInterface?.layoutIdentity !== receipt.identity.layoutIdentity\n )\n return 'receipt.identity.layoutIdentity';\n if (\n typeof record.artifact.mediaType !== 'string' ||\n record.artifact.mediaType.length === 0 ||\n typeof record.artifact.path !== 'string' ||\n record.artifact.path.length === 0\n )\n return 'artifact';\n return undefined;\n}\n\nexport function createMaterialLoader(options: MaterialLoaderOptions) {\n return {\n async load(request: MaterialLoadRequest): Promise<MaterialReady | MaterialLoadError> {\n const publication = await options.loadPublication(request.guid, request.specializationKey);\n if (publication === undefined) return missingCook(request);\n if (publication.artifactError !== undefined) {\n return materialError(\n request,\n publication.artifactError.code,\n publication.artifactError.expected,\n 'restore the published material artifact and retry the load',\n {\n expected: publication.artifactError.expected,\n ...(publication.artifactError.actual === undefined\n ? {}\n : { actual: publication.artifactError.actual }),\n },\n true,\n );\n }\n const parsed = validateCookedMaterialRecord(publication.record);\n if (!parsed.ok) return recordError(request, parsed.error.detail.field);\n const record = parsed.value;\n const invalidTupleField = completeTupleField(record);\n if (invalidTupleField !== undefined) return recordError(request, invalidTupleField);\n const publicationGeneration = record.publicationGeneration;\n const sourceClosure = record.sourceClosure;\n const parameterContract = record.parameterContract;\n const materialGuid = record.materialGuid;\n const recordSpecializationKey = record.specializationKey;\n const artifactDigest = record.artifactDigest;\n if (publicationGeneration === undefined) return recordError(request, 'publicationGeneration');\n if (sourceClosure === undefined) return recordError(request, 'sourceClosure');\n if (parameterContract === undefined) return recordError(request, 'parameterContract');\n if (materialGuid === undefined) return recordError(request, 'materialGuid');\n if (recordSpecializationKey === undefined) return recordError(request, 'specializationKey');\n if (artifactDigest === undefined) return recordError(request, 'artifactDigest');\n if (\n publication.guid.toLowerCase() !== request.guid.toLowerCase() ||\n record.guid.toLowerCase() !== request.guid.toLowerCase()\n ) {\n return recordError(\n request,\n 'guid',\n `record GUID ${request.guid} to match the requested GUID`,\n );\n }\n if (materialGuid.toLowerCase() !== request.guid.toLowerCase())\n return recordError(request, 'materialGuid');\n if (recordSpecializationKey !== request.specializationKey) return missingCook(request);\n if (publication.artifact === undefined) {\n return materialError(\n request,\n 'asset-artifact-missing',\n `published artifact for material ${request.guid}`,\n 'publish the immutable material artifact before loading the specialization',\n { publicationGeneration },\n true,\n );\n }\n const artifactBytes = immutableBytes(publication.artifact.bytes);\n const actualDigest = createMaterialArtifactDigest(artifactBytes);\n if (\n actualDigest !== artifactDigest ||\n (publication.artifact.digest !== undefined && publication.artifact.digest !== actualDigest)\n ) {\n return materialError(\n request,\n 'asset-artifact-integrity-mismatch',\n `artifact digest ${artifactDigest}`,\n 'restore the published artifact bytes or re-publish the matching material record',\n {\n publicationGeneration,\n expected: artifactDigest,\n actual: actualDigest,\n },\n );\n }\n if (!sameBytes(record.artifact.bytes, artifactBytes)) {\n return recordError(\n request,\n 'artifact.bytes',\n 'record artifact bytes to match the published artifact bytes',\n );\n }\n const refs = [\n ...record.refs.parent,\n ...record.refs.textures,\n ...record.refs.samplers,\n ...record.refs.modules,\n ];\n const missing = options.loadReference\n ? (\n await Promise.all(\n refs.map(async (reference) =>\n (await options.loadReference?.(reference)) ? undefined : reference,\n ),\n )\n ).filter((reference): reference is string => reference !== undefined)\n : [];\n if (missing.length > 0) {\n return materialError(\n request,\n 'material-reference-not-ready',\n 'all cooked material references to be available',\n 'load referenced parent, texture, sampler, and module assets before publishing Ready',\n { publicationGeneration, missing },\n true,\n );\n }\n return {\n status: 'Ready',\n guid: request.guid,\n materialGuid,\n publicationGeneration,\n specializationKey: request.specializationKey,\n artifactDigest,\n sourceClosure: Object.freeze([...sourceClosure]),\n parameterContract: immutableParameterContract(parameterContract),\n record,\n artifact: Object.freeze({\n ...record.artifact,\n bytes: artifactBytes,\n }),\n };\n },\n };\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport { ASSET_ERROR_HINTS, AssetError, type CatalogProjection } from '@forgeax/engine-types';\nimport type { CatalogRecord } from './catalog';\n\nexport interface RuntimeProjection {\n readonly subject: CatalogProjection['subject'];\n readonly execution: CatalogProjection['execution'];\n readonly lifecycle: CatalogProjection['lifecycle'];\n readonly packageUrl: string;\n}\n\nfunction projectionError(guid: string, expected: string): AssetError {\n return new AssetError({\n code: 'asset-not-imported',\n expected,\n hint: `${ASSET_ERROR_HINTS['asset-not-imported']} (GUID ${guid})`,\n });\n}\n\n/**\n * Resolve the producer-declared runtime projection. Legacy rows return\n * undefined so inline/dev assets retain their existing registration path;\n * rows that publish any projection axis must publish all three axes.\n */\nexport function resolveRuntimeProjection(\n guid: string,\n record: CatalogRecord,\n): Result<RuntimeProjection | undefined, AssetError> {\n const hasAxes =\n record.subject !== undefined ||\n record.execution !== undefined ||\n record.lifecycle !== undefined ||\n record.projection !== undefined;\n if (!hasAxes) return ok(undefined);\n\n const projection = record.projection;\n if (\n projection === undefined ||\n record.subject === undefined ||\n record.execution === undefined ||\n record.lifecycle === undefined\n ) {\n return err(\n projectionError(\n guid,\n 'catalog entry to publish subject, execution, lifecycle, and projection together',\n ),\n );\n }\n if (\n projection.subject !== record.subject ||\n projection.execution !== record.execution ||\n projection.lifecycle !== record.lifecycle\n ) {\n return err(projectionError(guid, 'catalog projection axes to agree with their row fields'));\n }\n return ok({\n subject: projection.subject,\n execution: projection.execution,\n lifecycle: projection.lifecycle,\n packageUrl: record.packageUrl,\n });\n}\n","// @forgeax/engine-assets-runtime -- load-by-guid + pack-fetch collaboration module\n// (feat-20260705-runtime-tier2-decomposition M1 / w7, D-4). Free functions\n// taking the AssetRegistry instance as first param; logic byte-preserved from the\n// class body (this. -> registry.). This is the largest method cluster (loadByGuid\n// + the DDC / pack-index / pack-file fetch + parse pipeline).\n\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { err, ok, type Result, type RhiError } from '@forgeax/engine-rhi';\nimport { isEngineMaterial } from '@forgeax/engine-shader';\nimport {\n type ArtifactDescriptor,\n ASSET_ERROR_HINTS,\n type Asset,\n type AssetCompression,\n AssetError,\n type AssetErrorCode,\n type AssetErrorDetail,\n type AssetRef,\n type CatalogSubject,\n type ImageError,\n type ImageMetadata,\n type LoadContext,\n type LoaderAsyncResult,\n type MaterialAsset,\n type MeshAsset,\n type ParseErrorDetail,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry, ParsedPackFile } from '../asset-registry';\nimport {\n createMaterialLoader,\n type MaterialLoadError,\n type MaterialLoadRequest,\n type MaterialPublication,\n type MaterialReady,\n} from '../material/loader';\nimport { readArtifact } from './artifact-io';\nimport { fetchPackIndex, resolveCatalogAssetUrl } from './catalog';\nimport { buildBreadcrumbHint, buildSceneChildContext } from './instantiate';\nimport { resolveRuntimeProjection } from './runtime-projection';\n\n/**\n * Load an asset and all its transitively referenced sub-assets by GUID;\n * returns `ok(handle)` only when the asset and every sub-asset are in the\n * registry.\n *\n * **Post-condition:** `ok(payload)` is returned ONLY when the asset AND every\n * transitively referenced sub-asset (per the asset envelope's `refs[]`) are\n * present in this registry. The implementation walks `envelope.refs` and\n * recursively calls `loadByGuid` on each ref before cataloguing the top-level\n * asset. The resolved value is the PAYLOAD `T`\n * (D-17), never a handle -- mint a column handle with\n * `world.allocSharedRef('Kind', payload)` when one is needed (e.g. before\n * `instantiate`).\n *\n * Two paths:\n * - **Dev / fallback** (no `configurePackIndex` call): synchronous catalogue\n * lookup wrapped in `Promise.resolve`. Returns `Err(asset-not-found)` if not\n * catalogued.\n * - **Prod** (after `configurePackIndex(url)`): fetches `pack-index.json`\n * on the first call (cached as a `Map<guid, {packageUrl, kind}>`), then\n * fetches the individual resource URL and parses the asset payload, then\n * catalogues it (GUID -> payload) and returns the payload.\n *\n * Error union: `AssetError | PackError | ImageError | RhiError` (closed -- no\n * new codes were introduced by the recursive walk; every code is pre-existing).\n *\n * An in-flight `Map` (D-5) deduplicates concurrent calls for the same GUID and\n * prevents stack overflow on cycles (A->B->A).\n *\n * **Breaking-change classification:** this is a semantic strengthening, not a\n * shape change. Sub-assets catalogued by a prior `catalog(guid, payload)` /\n * `loadByGuid` call are protected by the catalogue fast-path: the recursive\n * walk hits cache on every node and incurs zero additional fetch.\n *\n * @example\n * ```ts\n * const res = await engine.assets.loadByGuid<SceneAsset>(sceneGuid);\n * if (!res.ok) {\n * switch (res.error.code) {\n * case 'asset-not-found':\n * // top GUID or any sub-asset GUID is missing from the catalog\n * break;\n * case 'asset-fetch-failed':\n * // network / CORS\n * break;\n * case 'asset-parse-failed':\n * // payload malformed\n * break;\n * // ... AssetErrorCode | PackErrorCode | ImageErrorCode | RhiErrorCode exhaustive\n * }\n * return;\n * }\n * ```\n */\nexport async function loadByGuid<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n return loadByGuidInternal(registry, guid, parentContext, new Set());\n}\n\nfunction cookedRecordFromPayload(payload: Record<string, unknown>): unknown {\n if (payload.schemaVersion === 'material-cook/3') return payload;\n if (payload.cooked !== null && typeof payload.cooked === 'object') return payload.cooked;\n if (payload.record !== null && typeof payload.record === 'object') return payload.record;\n return undefined;\n}\n\nfunction materialArtifactKey(\n record: Record<string, unknown> | undefined,\n descriptors: Readonly<Record<string, ArtifactDescriptor>>,\n): string | undefined {\n const artifact = record?.artifact;\n const path =\n artifact !== null && typeof artifact === 'object' && 'path' in artifact\n ? (artifact as { readonly path?: unknown }).path\n : undefined;\n if (typeof path === 'string') {\n const match = Object.entries(descriptors).find(([, descriptor]) => descriptor.path === path);\n if (match !== undefined) return match[0];\n }\n const shaderArtifacts = Object.entries(descriptors).filter(\n ([, descriptor]) => descriptor.mediaType === 'text/wgsl',\n );\n return shaderArtifacts.length === 1 ? shaderArtifacts[0]?.[0] : undefined;\n}\n\nfunction materialRecordPath(descriptor: ArtifactDescriptor): string {\n return `${descriptor.path}.record.json`;\n}\n\nfunction inlineMaterialArtifact(\n record: Record<string, unknown> | undefined,\n): MaterialPublication['artifact'] | undefined {\n const artifact = record?.artifact;\n if (artifact === null || typeof artifact !== 'object' || Array.isArray(artifact)) {\n return undefined;\n }\n const bytes = (artifact as { readonly bytes?: unknown }).bytes;\n const normalizedBytes =\n bytes instanceof Uint8Array\n ? new Uint8Array(bytes)\n : Array.isArray(bytes) &&\n bytes.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255)\n ? Uint8Array.from(bytes)\n : undefined;\n if (normalizedBytes === undefined) return undefined;\n const digest = (artifact as { readonly digest?: unknown }).digest;\n return {\n bytes: normalizedBytes,\n ...(typeof digest === 'string' ? { digest } : {}),\n };\n}\n\nasync function loadMaterialPublicationByGuid(\n registry: AssetRegistry,\n request: MaterialLoadRequest,\n): Promise<MaterialPublication | undefined> {\n const parsedGuid = AssetGuid.parse(request.guid);\n if (!parsedGuid.ok) return undefined;\n const entry = await resolveCatalogEntry(registry, request.guid.toLowerCase());\n if (entry === undefined) return undefined;\n let pack = registry.packFileCache.get(entry.packageUrl);\n if (pack === undefined) {\n const fetched = await fetchAndCachePackFile(\n registry,\n entry.packageUrl,\n request.guid.toLowerCase(),\n );\n if (!fetched.ok) return undefined;\n pack = registry.packFileCache.get(entry.packageUrl);\n }\n const asset = pack?.assets.find(\n (candidate) => candidate.guid.toLowerCase() === request.guid.toLowerCase(),\n );\n if (asset === undefined || asset.kind !== 'material') return undefined;\n const record = cookedRecordFromPayload(asset.payload);\n const recordObject =\n record !== undefined && typeof record === 'object' && record !== null\n ? (record as Record<string, unknown>)\n : undefined;\n const artifactKey = materialArtifactKey(recordObject, asset.artifacts ?? {});\n if (artifactKey === undefined) {\n const inlineArtifact = inlineMaterialArtifact(recordObject);\n if (inlineArtifact !== undefined) {\n return {\n guid: request.guid,\n record,\n artifact: inlineArtifact,\n };\n }\n return {\n guid: request.guid,\n record,\n artifactError: {\n code: 'asset-artifact-missing',\n expected: 'a published material artifact descriptor',\n },\n };\n }\n const descriptor = asset.artifacts?.[artifactKey];\n if (descriptor === undefined) {\n return {\n guid: request.guid,\n record,\n artifactError: {\n code: 'asset-artifact-missing',\n expected: `artifact descriptor '${artifactKey}'`,\n },\n };\n }\n let publicationRecord = record;\n if (publicationRecord === undefined) {\n const recordArtifact = await readArtifact({\n packageUrl: entry.packageUrl,\n guid: request.guid,\n artifactKey: `${artifactKey}.record`,\n descriptor: {\n path: materialRecordPath(descriptor),\n mediaType: 'application/json',\n },\n });\n if (!recordArtifact.ok) return undefined;\n try {\n publicationRecord = JSON.parse(new TextDecoder().decode(recordArtifact.value));\n } catch {\n publicationRecord = null;\n }\n }\n const artifactCacheKey = `${entry.packageUrl}\\0${request.guid.toLowerCase()}\\0${artifactKey}`;\n const artifact = await registry.artifactCache.read(artifactCacheKey, () =>\n readArtifact({\n packageUrl: entry.packageUrl,\n guid: request.guid,\n artifactKey,\n descriptor,\n }),\n );\n if (!artifact.ok) {\n if (artifact.error.code === 'asset-artifact-missing') {\n return {\n guid: request.guid,\n record: publicationRecord,\n artifactError: {\n code: artifact.error.code,\n expected: artifact.error.expected,\n actual: artifact.error.detail.observed,\n },\n };\n }\n if (artifact.error.code === 'asset-artifact-integrity-mismatch') {\n return {\n guid: request.guid,\n record: publicationRecord,\n artifactError: {\n code: artifact.error.code,\n expected: artifact.error.expected,\n actual: artifact.error.detail.observed,\n },\n };\n }\n return {\n guid: request.guid,\n record: publicationRecord,\n artifactError: {\n code: 'asset-artifact-missing',\n expected: artifact.error.expected,\n actual: artifact.error.detail.observed,\n },\n };\n }\n return {\n guid: request.guid,\n record: publicationRecord,\n artifact: {\n bytes: artifact.value,\n },\n };\n}\n\nexport async function loadMaterialReadyByGuid(\n registry: AssetRegistry,\n request: MaterialLoadRequest,\n): Promise<MaterialReady | MaterialLoadError> {\n const publication = await loadMaterialPublicationByGuid(registry, request);\n return loadMaterialReadyPublication(registry, request, publication);\n}\n\nfunction publicationSpecializationKey(publication: MaterialPublication | undefined): string {\n const record = publication?.record;\n if (record === null || typeof record !== 'object') return '';\n const specializationKey = (record as { readonly specializationKey?: unknown }).specializationKey;\n return typeof specializationKey === 'string' ? specializationKey : '';\n}\n\nasync function loadMaterialReadyPublication(\n registry: AssetRegistry,\n request: MaterialLoadRequest,\n publication: MaterialPublication | undefined,\n): Promise<MaterialReady | MaterialLoadError> {\n const loader = createMaterialLoader({\n loadPublication: async () => publication,\n loadReference: async (guid) => {\n const parsed = AssetGuid.parse(guid);\n if (!parsed.ok) return true;\n const result = await loadByGuid(registry, parsed.value);\n return result.ok;\n },\n });\n const readiness = await loader.load(request);\n registry.recordMaterialReadiness(request.guid, readiness);\n return readiness;\n}\n\nasync function loadByGuidInternal<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n parentContext:\n | {\n sceneEntityId?: number;\n componentField?: string;\n }\n | undefined,\n ancestry: ReadonlySet<string>,\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n const guidKey = AssetGuid.format(guid).toLowerCase();\n\n // feat-20260614 M8 (D-17): the registry catalogues GUID -> payload and\n // returns the PAYLOAD (never a handle). Fast path: already catalogued\n // (covers dev catalog() + prod cached repeat calls).\n const existing = registry.assetCatalog.get(guidKey);\n if (existing !== undefined) {\n const state = registry.loadState.get(guidKey);\n if (state?.status === 'provisional') {\n // A provisional value is only a legal bridge for a true SCC back-edge.\n // A sibling or unrelated concurrent load must await its owning promise;\n // otherwise the parent reaches promoteReady while the dependency is\n // still provisional and reports a spurious public-readiness failure.\n if (ancestry.has(guidKey)) {\n const provisional = registry.loadState.getProvisional<T>(guidKey);\n if (provisional !== undefined) return ok(provisional);\n } else {\n const inFlight = registry.inFlight.get(guidKey);\n if (inFlight !== undefined) {\n return inFlight as Promise<Result<T, AssetError | ImageError | RhiError>>;\n }\n }\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `GUID ${guidKey} to be promoted to Ready before public load`,\n hint: 'wait for the active load to finish or retry after the referenced assets are ready',\n }),\n );\n }\n if (state?.status === 'ready' || (state === undefined && registry.packIndexUrl === undefined)) {\n const ready = registry.loadState.getReady<T>(guidKey);\n if (ready !== undefined) return ok(ready);\n if (state === undefined) return ok(existing.payload as T);\n }\n }\n\n // In-flight dedup (D-5 / B-10): if another call is already loading this\n // GUID, return that same Promise — covers (a) concurrent same-GUID calls\n // and (b) cycle A→B→A termination (B reaches A's in-flight entry).\n const inFlightPromise = registry.inFlight.get(guidKey);\n if (inFlightPromise !== undefined) {\n return inFlightPromise as Promise<Result<T, AssetError | ImageError | RhiError>>;\n }\n\n // Prod fetch path: only enabled when packIndexUrl is configured.\n if (registry.packIndexUrl !== undefined && typeof globalThis.fetch === 'function') {\n // F22: capture generation snapshot at Promise creation time so the\n // resolve path can detect whether invalidate/invalidateAll was called\n // while the fetch was in flight.\n const genAtStart = registry.generations.get(guidKey) ?? 0;\n const globalGenAtStart = registry.globalGeneration;\n\n const promise = (async () => {\n const result = await loadByGuidProd<T>(registry, guid, guidKey, parentContext, ancestry);\n // F22: if the generation counters changed since the Promise was\n // created, discard the result -- the asset was invalidated.\n if (\n genAtStart !== (registry.generations.get(guidKey) ?? 0) ||\n globalGenAtStart !== registry.globalGeneration\n ) {\n registry.assetCatalog.delete(guidKey);\n registry.loadState.remove(guidKey);\n return err(\n new AssetError({\n code: 'asset-invalidated',\n expected: `GUID ${guidKey} was invalidated during load`,\n hint: ASSET_ERROR_HINTS['asset-invalidated'],\n }),\n ) as Result<T, AssetError | ImageError | RhiError>;\n }\n return result;\n })();\n registry.inFlight.set(guidKey, promise);\n try {\n return await promise;\n } finally {\n if (registry.inFlight.get(guidKey) === promise) registry.inFlight.delete(guidKey);\n }\n }\n\n // Dev / fallback: synchronous catalogue miss (no network).\n return Promise.resolve(\n err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} catalogued in AssetRegistry`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n ),\n );\n}\n\n/**\n * feat-20260603-asset-import-loader-injection M1 / w6: load an\n * upstream-branch kind (texture / font) straight from its catalog entry\n * through the injected async loader, then register the produced POD. Replaces\n * the bespoke `loadTextureFromEntry` / `loadFontFromEntry` methods; the decode\n * / glyph-parse logic moved verbatim into the loader bodies (D-2 — loader is\n * pure of `registerWithGuid`, which stays here).\n */\nexport async function loadFromUpstreamEntry<T = Asset>(\n registry: AssetRegistry,\n guidKey: string,\n entry: {\n packageUrl: string;\n kind: string;\n name?: string;\n metadata?: ImageMetadata | undefined;\n },\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n const loader = registry.loaders.get(entry.kind);\n if (loader === undefined) {\n return err(\n new AssetError({\n code: 'loader-not-registered',\n expected: `a loader registered for kind '${entry.kind}'`,\n hint: ASSET_ERROR_HINTS['loader-not-registered'],\n detail: { kind: entry.kind, registeredKinds: registry.loaders.registeredKinds() },\n }),\n );\n }\n const out = loader.load({ ...entry, guidKey }, undefined, makeLoadContext(registry));\n // Upstream-branch loaders are async (Promise<LoaderAsyncResult>).\n const result = (await out) as LoaderAsyncResult;\n if (!result.ok) {\n return err(result.error as AssetError | ImageError | RhiError);\n }\n const guid = AssetGuid.parse(guidKey);\n if (!guid.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `valid GUID ${guidKey}`,\n hint: ASSET_ERROR_HINTS['asset-parse-failed'],\n }),\n );\n }\n return registry.catalog(guid.value, result.value) as Result<\n T,\n AssetError | ImageError | RhiError\n >;\n}\n\n/**\n * Internal: prod fetch path for `loadByGuid`.\n * Fetches pack-index.json (cached), then fetches the pack file, parses the\n * asset payload, and registers it.\n */\nexport async function loadByGuidProd<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n guidKey: string,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n ancestry: ReadonlySet<string> = new Set(),\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n // feat-20260603-asset-import-loader-injection M4 / w31 (AC-19 lazy iron law):\n // wrap the DDC fetch + load path so a DDC miss can be routed through the\n // injected ImportTransport (studio form) or fail-fast with\n // `asset-not-imported` (shipped form, AC-22). The load path after a\n // successful DDC resolve is identical in both forms -- zero branches on\n // `registry.importTransport` (AC-23 key invariant).\n //\n // A DDC miss is: (a) the GUID is absent from the catalog, OR (b) the\n // `.pack.json` fetch returns `asset-not-found` / `asset-fetch-failed`.\n // In case (a) the transport is probed first (the pack-index may have been\n // built before the asset was imported); in case (b) the transport is the\n // only fallback (the pack file is genuinely missing).\n\n const entry = await resolveCatalogEntry(registry, guidKey);\n if (entry !== undefined) {\n const projection = resolveRuntimeProjection(guidKey, entry);\n if (!projection.ok) return projection;\n if (projection.value?.lifecycle !== undefined && projection.value.lifecycle !== 'current') {\n return transportOrFail<T>(registry, guid, guidKey, 'asset-not-imported');\n }\n // Catalog hit: try the DDC load path.\n const result = await ddcLoad<T>(registry, guid, guidKey, entry, parentContext, ancestry);\n if (result.ok) return result;\n // DDC miss: only route through transport when the error indicates a\n // missing pack file (not a parse / validation failure inside the pack) or\n // an unimported texture source (feat-20260604 M2 / D-1: import-on-demand).\n // `texture-source-not-imported` is an AssetError, so it passes the\n // `instanceof AssetError` guard naturally. `image-decode-failed` is an\n // ImageError (a genuinely corrupt imported .bin) -- it fails the guard and\n // is therefore never transport-eligible (Risk-1), so a real decode\n // failure is never silently lazy-imported.\n const ddcError = result.error;\n const transportEligible =\n ddcError instanceof AssetError &&\n (ddcError.code === 'asset-not-found' ||\n ddcError.code === 'asset-fetch-failed' ||\n ddcError.code === 'texture-source-not-imported' ||\n // perf-20260706: the raw-container fail-fast (mesh/material/scene whose\n // packageUrl is still a .glb/.gltf/.fbx) surfaces source-not-imported;\n // it is transport-eligible so the import runs once and rewrites the row\n // to .bin/.pack.json (the shipped form, with no transport, fails fast).\n // Distinct from the generic asset-not-imported, which must stay\n // NON-eligible so the parent-missing breadcrumb is never masked.\n ddcError.code === 'source-not-imported');\n if (transportEligible) {\n return transportOrFail<T>(registry, guid, guidKey, ddcError.code);\n }\n return result;\n }\n\n // Catalog miss: the GUID is not in the pack-index. In the studio form the\n // import transport can lazily create the missing DDC.\n return transportOrFail<T>(registry, guid, guidKey, 'asset-not-found');\n}\n\n/**\n * Resolve the catalog entry for a GUID, lazily fetching the pack-index on\n * first call. Returns `undefined` when the GUID is absent from the catalog.\n */\nexport async function resolveCatalogEntry(\n registry: AssetRegistry,\n guidKey: string,\n): Promise<\n | {\n packageUrl: string;\n kind: string;\n name?: string;\n metadata?: ImageMetadata | undefined;\n compression?: AssetCompression;\n }\n | undefined\n> {\n const key = guidKey.toLowerCase();\n // Re-fetch the pack-index when it has never been fetched (=== undefined) OR\n // when the cached Map lacks this GUID. The miss case covers invalidate(guid)\n // round-2 M-A, which deletes the per-GUID index entry (targeted, bystanders\n // survive) without nuking the whole Map to undefined: the next loadByGuid\n // must re-consult the source so the GUID re-resolves and its freshly-cleared\n // body cache re-fetches. A genuinely absent GUID re-fetches once then still\n // misses, falling through to the transport / asset-not-found path as before.\n if (registry.packIndexCache === undefined || !registry.packIndexCache.has(key)) {\n const catalogResult = await fetchPackIndex(registry);\n if (!catalogResult.ok) {\n // Keep packIndexCache === undefined so next resolveCatalogEntry re-enters\n // the fetch path instead of short-circuiting on an empty (polluted) cache.\n if (registry.packIndexCache === undefined) return undefined;\n } else {\n registry.packIndexCache = catalogResult.value;\n registerPackagesFromIndex(registry, registry.packIndexCache);\n }\n }\n return registry.packIndexCache?.get(key);\n}\n\n/**\n * feat-20260618 M3 (D-2): once the pack-index is parsed, group every row by\n * its `packageUrl` and register each package fully -- all of its GUIDs and\n * their entry display names in one `registerPackage` call. Registering the\n * whole package at once (rather than one GUID per load) means the package\n * cardinality is known up front, so `resolveName` returns the basename for a\n * genuinely single-asset package and the entry name for a multi-asset one,\n * with no incremental 1->N promotion needed on the prod path. The name travels\n * entry -> Package, never through the payload (Risk-3 JSON-roundtrip safety),\n * and covers both the sync (parseAssetPayload) and async (texture/font) loads.\n */\nexport function registerPackagesFromIndex(\n registry: AssetRegistry,\n catalog: Map<\n string,\n {\n packageUrl: string;\n name?: string;\n sourcePath?: string;\n subject?: CatalogSubject;\n }\n >,\n): void {\n const byPath = new Map<string, { guids: string[]; names: Map<string, string> }>();\n for (const [guidKey, entry] of catalog) {\n // Imported outputs are published under generated DDC/package URLs, but\n // their stable package identity is the authored source. Keeping that\n // source path here preserves `sky.hdr` (and equivalent source names) for\n // single-asset lazy imports; authored internal packages retain their\n // package URL semantics.\n const packagePath =\n entry.subject === 'imported-output' && entry.sourcePath !== undefined\n ? entry.sourcePath\n : entry.packageUrl;\n let group = byPath.get(packagePath);\n if (group === undefined) {\n group = { guids: [], names: new Map() };\n byPath.set(packagePath, group);\n }\n group.guids.push(guidKey);\n if (entry.name !== undefined) group.names.set(guidKey, entry.name);\n }\n for (const [path, group] of byPath) {\n registry._registerPackage(path, group.guids, group.names);\n }\n}\n\n/**\n * Load an asset through the DDC (catalog entry -> fetch pack -> loader.load\n * -> register). Returns `Err(asset-not-found)` or `Err(asset-fetch-failed)`\n * on DDC miss (the caller then decides whether to route through the\n * import transport).\n *\n * This path is IDENTICAL in studio and shipped forms -- the only difference\n * between the two is whether `registry.importTransport` exists when the caller\n * falls back to `transportOrFail` (AC-23 key invariant).\n */\nexport async function ddcLoad<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n guidKey: string,\n entry: {\n packageUrl: string;\n kind: string;\n name?: string;\n metadata?: ImageMetadata | undefined;\n compression?: AssetCompression;\n },\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n ancestry: ReadonlySet<string> = new Set(),\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n if (typeof entry.packageUrl !== 'string' || entry.packageUrl.length === 0) {\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `catalog entry for GUID ${guidKey} to contain a packageUrl locator`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n const packResult = await loadPackV2Asset(registry, guidKey, entry.packageUrl);\n if (packResult === undefined) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `Pack v2 package for GUID ${guidKey}`,\n hint: 'legacy top-level asset payloads are not accepted',\n }),\n );\n }\n if (!packResult.ok) {\n return packResult as Result<T, AssetError>;\n }\n\n const asset = packResult.value.asset;\n // feat-20260622 M4 / w12: project the pack-entry refs[] (GUID strings) into\n // AssetRef[] for the envelope. The on-disk pack.json refs[] carries only\n // GUID strings (sourceField / sceneEntityId are stripped at the\n // serialization boundary, w7 D-10), so prod-loaded edges have no per-entity\n // metadata — the scene breadcrumb fallback (buildSceneChildContext) still\n // walks the payload for entity/field detail. Dev-server register paths that\n // carry rich AssetRef[] keep their edge metadata end-to-end.\n const packRefs: readonly AssetRef[] = packResult.value.refs.map((g) => ({ guid: g }));\n\n // feat-20260622 M5 / w17 (D-8, R5): the former material parent preload\n // \"Path B\" (an independent early-return that loaded the parent BEFORE the\n // unified for-loop and carried the precise breadcrumb hint `loading parent\n // material X for child Y`) is folded into the unified envelope.refs\n // for-loop. The parent GUID already rides on the material envelope.refs\n // (gltf-importer w5 writes it; the on-disk pack refs[] carries it as a\n // GUID string -> packRefs above projects it), so the unified for-loop\n // recurses on it like any other edge. Here we only resolve the parent\n // GUID -> AssetGuid and stamp `parent` onto the asset payload (the\n // renderer-facing field read by walkMaterialPassesOverSharedRefs); the\n // parent EDGE load + the `loading parent material X for child Y` breadcrumb\n // + the not-a-material guard all move into the for-loop's\n // sourceField.fieldName==='parent' / parent-edge branch below. No early\n // return: the material registers (register-before-recurse) and its parent\n // edge loads through the same unified path as texture / scene edges.\n let assetToRegister: Asset = asset;\n let parentGuidKey: string | undefined;\n if (\n asset.kind === 'material' &&\n 'parentGuid' in (asset as unknown as Record<string, unknown>) &&\n typeof (asset as unknown as Record<string, unknown>).parentGuid === 'string'\n ) {\n const parentGuidStr = (asset as unknown as MaterialAsset & { parentGuid: string }).parentGuid;\n const parentGuid = AssetGuid.parse(parentGuidStr);\n if (!parentGuid.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `valid parent GUID for child ${guidKey}`,\n hint: `parent GUID '${parentGuidStr}' is not a valid UUID format`,\n }),\n );\n }\n parentGuidKey = parentGuidStr.toLowerCase();\n const matAsset = asset as unknown as MaterialAsset & { parentGuid?: string };\n const passes = matAsset.passes;\n const values = matAsset.values;\n assetToRegister = {\n kind: 'material',\n ...(passes !== undefined ? { passes } : {}),\n ...(values !== undefined ? { values } : {}),\n parent: parentGuid.value,\n };\n }\n\n registry.loadState.begin(\n guidKey,\n packRefs.map((ref) => ref.guid),\n );\n\n // The provisional record lets cycle back-edges terminate internally while\n // lookup()/inspect() remain limited to the ready domain.\n // tweak-20260609 M1: catalogue the asset BEFORE recursing into its\n // sub-assets. This way, when a cycle (A→B→A) reaches back to A during\n // B's recursion, A is already catalogued (fast-path hit) and the inFlight\n // Promise for A can be fulfilled. The inFlight entry in `loadByGuid` is\n // the second line of defense — it catches concurrent same-GUID calls\n // before the asset is catalogued.\n const registerResult = registerParsedAsset<T>(registry, guid, assetToRegister, guidKey, packRefs);\n if (!registerResult.ok) {\n purgeFailedLoad(registry, guidKey, entry.packageUrl, registerResult.error);\n return registerResult;\n }\n const registeredPayload = registerResult.value;\n registry.loadState.resolveAsset(guidKey, registeredPayload);\n\n // feat-20260622 M4 / w12 (D-5): the recursion source is the just-catalogued\n // envelope's refs[]. The for-loop is kind-agnostic\n // — every AssetRef carries the GUID to recurse on; scene/material/skin all\n // flow through this one loop. Each edge optionally carries sourceField /\n // sceneEntityId; when present the childContext is built straight from the\n // edge, otherwise the scene branch falls back to walking the payload\n // (buildSceneChildContext) so the prod-path breadcrumb keeps its entity /\n // field detail (on-disk refs[] are GUID-string-only, w7 D-10).\n const envelope = registry.assetCatalog.get(guidKey);\n const refs: readonly AssetRef[] = envelope?.refs ?? [];\n if (refs.length > 0) {\n const subResults = await Promise.all(\n refs.map((ref) => {\n const refGuidKey = ref.guid.toLowerCase();\n const parsedRef = AssetGuid.parse(ref.guid);\n if (!parsedRef.ok) {\n return Promise.resolve({\n guidKey: refGuidKey,\n result: err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `valid sub-asset GUID referenced by ${asset.kind} ${guidKey}`,\n hint: `refs[] entry '${ref.guid}' is not a valid UUID format`,\n }),\n ) as Result<Asset, AssetError | ImageError | RhiError>,\n childContext: undefined as\n | {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n }\n | undefined,\n isParentEdge: false,\n edge: ref,\n });\n }\n let childContext:\n | {\n sceneEntityId?: number;\n componentField?: string;\n sourceField?: {\n componentName?: string;\n fieldName: string;\n arrayIndex?: number;\n };\n }\n | undefined;\n if (ref.sceneEntityId !== undefined || ref.sourceField !== undefined) {\n childContext = {};\n if (ref.sceneEntityId !== undefined) childContext.sceneEntityId = ref.sceneEntityId;\n if (ref.sourceField?.fieldName !== undefined) {\n childContext.componentField =\n (ref.sourceField.componentName !== undefined\n ? `${ref.sourceField.componentName}.`\n : '') +\n ref.sourceField.fieldName +\n (ref.sourceField.arrayIndex !== undefined ? `[${ref.sourceField.arrayIndex}]` : '');\n childContext.sourceField = ref.sourceField;\n }\n } else if (asset.kind === 'scene') {\n childContext = buildSceneChildContext(registry, asset, refGuidKey, guidKey);\n }\n // feat-20260622 M5 / w17 (D-8): the material parent edge. Identify it\n // by either the rich dev-path marker (sourceField.fieldName==='parent')\n // or the prod-path GUID match against the resolved parent GUID\n // (on-disk refs[] strip sourceField, w7 D-10, so the GUID is the only\n // signal). The parent edge carries the distinct `loading parent\n // material X for child Y` breadcrumb (AC-10) instead of the generic\n // buildBreadcrumbHint form, and is guarded to be a material.\n const isParentEdge =\n asset.kind === 'material' &&\n (ref.sourceField?.fieldName === 'parent' ||\n (parentGuidKey !== undefined && refGuidKey === parentGuidKey));\n const childAncestry = new Set(ancestry);\n childAncestry.add(guidKey);\n return loadByGuidInternal(\n registry,\n parsedRef.value,\n childContext ?? parentContext,\n childAncestry,\n ).then((r) => ({\n guidKey: refGuidKey,\n result: r,\n childContext,\n isParentEdge,\n edge: ref,\n }));\n }),\n );\n\n // If any sub-asset load failed, propagate the first error enriched with\n // parent breadcrumb.\n for (const {\n guidKey: subGuidKey,\n result: subResult,\n childContext: subChildContext,\n isParentEdge,\n edge: subEdge,\n } of subResults) {\n // feat-20260622 M5 / w17: parent-edge breadcrumb migration (former Path\n // B). On load failure, carry the distinct `loading parent material X for\n // child Y: <subErr.hint>` form (AC-10 downstream literal assertion) and\n // propagate the parent's own error code verbatim.\n if (isParentEdge && !subResult.ok) {\n const subErr = subResult.error;\n const code: AssetErrorCode =\n subErr instanceof AssetError ? subErr.code : 'asset-parse-failed';\n purgeFailedLoad(registry, guidKey, entry.packageUrl, subErr);\n return err(\n new AssetError({\n code,\n expected: subErr.expected,\n hint: `loading parent material ${subGuidKey} for child ${guidKey}: ${\n subErr.hint ?? ''\n }`,\n ...(subErr instanceof AssetError && subErr.detail !== undefined\n ? { detail: subErr.detail as Readonly<AssetErrorDetail> }\n : {}),\n }),\n );\n }\n // feat-20260622 M5 / w17: parent edge loaded but is not a material —\n // same guard the former Path B carried, with the matching breadcrumb.\n if (isParentEdge && subResult.ok && subResult.value?.kind !== 'material') {\n const error = new AssetError({\n code: 'asset-parse-failed',\n expected: `parent GUID ${subGuidKey} to reference a MaterialAsset`,\n hint: `loading parent material ${subGuidKey} for child ${guidKey}: referenced asset is ${subResult.value?.kind ?? 'unknown'}, not 'material'`,\n });\n purgeFailedLoad(registry, guidKey, entry.packageUrl, error);\n return err(error);\n }\n if (!subResult.ok) {\n const subErr = subResult.error;\n const breadcrumb = buildBreadcrumbHint(\n guidKey,\n asset.kind,\n subGuidKey,\n subChildContext ?? parentContext,\n );\n const code: AssetErrorCode =\n subErr instanceof AssetError ? subErr.code : 'asset-fetch-failed';\n // feat-20260622 verify r1: deliver the breadcrumb provenance in\n // structured form so AI users locate the broken edge by property\n // access (charter P3), not by parsing the hint. Preserve the sub\n // error's own detail when it carries one (more specific); otherwise\n // expose the edge provenance (entity / source field).\n // Prefer the rich dev-path edge provenance; on the prod path the\n // on-disk edge is GUID-only (sourceField stripped, w7 D-10), so fall\n // back to the entity-walk-recovered provenance carried on the\n // childContext (verify r1).\n const provEntityId = subEdge?.sceneEntityId ?? subChildContext?.sceneEntityId;\n const provSourceField = subEdge?.sourceField ?? subChildContext?.sourceField;\n const breadcrumbDetail: Readonly<AssetErrorDetail> = {\n referencedByGuid: guidKey,\n referencedByKind: asset.kind,\n subAssetGuid: subGuidKey,\n ...(provEntityId !== undefined ? { sceneEntityId: provEntityId } : {}),\n ...(provSourceField !== undefined ? { sourceField: provSourceField } : {}),\n };\n const detail: Readonly<AssetErrorDetail> =\n subErr instanceof AssetError && subErr.detail !== undefined\n ? subErr.detail\n : breadcrumbDetail;\n purgeFailedLoad(registry, guidKey, entry.packageUrl, subErr);\n return err(\n new AssetError({\n code,\n expected: subErr.expected,\n hint: `${breadcrumb} / ${subErr.hint ?? ''}`,\n detail,\n }),\n );\n }\n }\n }\n\n // A Mesh default is a typed dependency, not merely a loadable GUID. This\n // check deliberately lives outside the `refs.length > 0` branch: a producer\n // that puts a default GUID in the payload but omits the matching refs[] edge\n // must fail closed instead of publishing a Mesh whose dependency closure is\n // incomplete.\n if (asset.kind === 'mesh') {\n const directRefGuids = new Set(refs.map((ref) => ref.guid.toLowerCase()));\n const slots = (asset as MeshAsset).materialSlots;\n for (let slotIndex = 0; slotIndex < slots.length; slotIndex++) {\n const slot = slots[slotIndex];\n if (slot?.defaultMaterial === undefined) continue;\n const defaultMaterialGuid = AssetGuid.format(slot.defaultMaterial).toLowerCase();\n const loaded = directRefGuids.has(defaultMaterialGuid)\n ? registry.assetCatalog.get(defaultMaterialGuid)?.payload\n : undefined;\n if (loaded?.kind === 'material') continue;\n const actualKind = directRefGuids.has(defaultMaterialGuid)\n ? (loaded?.kind ?? 'missing')\n : 'missing-ref-edge';\n const error = new AssetError({\n code: 'asset-parse-failed',\n expected: `mesh ${guidKey} materialSlots[${slotIndex}] (${slot.slotName}) default ${defaultMaterialGuid} to reference a MaterialAsset`,\n hint: `recook mesh ${guidKey}; slot ${slotIndex} '${slot.slotName}' resolves to ${actualKind}, not 'material'`,\n detail: {\n meshAssetGuid: guidKey,\n slotIndex,\n slotName: slot.slotName,\n defaultMaterialGuid,\n actualKind,\n },\n });\n purgeFailedLoad(registry, guidKey, entry.packageUrl, error);\n return err(error);\n }\n }\n\n registry.loadState.promoteReady(guidKey);\n if (registry.loadState.getReady(guidKey) === undefined) {\n const error = new AssetError({\n code: 'asset-parse-failed',\n expected: `GUID ${guidKey} and all referenced assets to be public-ready`,\n hint: 'retry after every referenced GUID has loaded successfully',\n });\n purgeFailedLoad(registry, guidKey, entry.packageUrl, error);\n return err(error);\n }\n const registeredAsset = registeredPayload as Asset;\n if (registeredAsset.kind === 'material' && !isEngineMaterial(registeredAsset)) {\n const publication = await loadMaterialPublicationByGuid(registry, {\n guid: guidKey,\n specializationKey: '',\n });\n await loadMaterialReadyPublication(\n registry,\n {\n guid: guidKey,\n specializationKey: publicationSpecializationKey(publication),\n },\n publication,\n );\n }\n return ok(registeredPayload as T);\n}\n\nasync function loadPackV2Asset(\n registry: AssetRegistry,\n guidKey: string,\n packageUrl: string,\n): Promise<\n | Result<\n {\n asset: Asset;\n refs: readonly string[];\n },\n AssetError\n >\n | undefined\n> {\n const cached = registry.packFileCache.get(packageUrl);\n if (cached === undefined) {\n const inFlight = registry.packFileInFlight.get(packageUrl);\n if (inFlight !== undefined) await inFlight.catch(() => undefined);\n const fetched =\n registry.packFileCache.get(packageUrl) === undefined\n ? await fetchAndCachePackFile(registry, packageUrl, guidKey)\n : undefined;\n if (registry.packFileCache.get(packageUrl) === undefined) {\n if (fetched === undefined) {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `pack file ${packageUrl} to be cached after its shared fetch`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n return fetched as unknown as Result<{ asset: Asset; refs: readonly string[] }, AssetError>;\n }\n }\n const pack = registry.packFileCache.get(packageUrl);\n if (pack?.schemaVersion !== '2.0.0') return undefined;\n const asset = pack.assets.find((candidate) => candidate.guid.toLowerCase() === guidKey);\n if (asset === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in Pack v2 package ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n const artifacts: Record<string, { descriptor: ArtifactDescriptor; bytes: Uint8Array }> = {};\n for (const [artifactKey, descriptor] of Object.entries(asset.artifacts ?? {})) {\n const cacheKey = `${packageUrl}\\0${guidKey}\\0${artifactKey}`;\n const artifact = await registry.artifactCache.read(cacheKey, () =>\n readArtifact({ packageUrl, guid: guidKey, artifactKey, descriptor }),\n );\n if (!artifact.ok)\n return artifact as unknown as Result<{ asset: Asset; refs: readonly string[] }, AssetError>;\n artifacts[artifactKey] = { descriptor, bytes: artifact.value };\n }\n const loaded = await registry.loaders.loadPack(\n {\n guid: guidKey,\n kind: asset.kind,\n payload: asset.payload,\n refs: asset.refs ?? [],\n artifacts,\n },\n makeLoadContext(registry),\n );\n if (!loaded.ok) return err(loaded.error as AssetError);\n if (loaded.value === undefined || typeof loaded.value !== 'object') {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `loader '${asset.kind}' to return an asset payload`,\n hint: 'register a loader that accepts the Pack v2 asset-local input',\n }),\n );\n }\n return ok({ asset: loaded.value as Asset, refs: asset.refs ?? [] });\n}\n\nfunction purgeFailedLoad(\n registry: AssetRegistry,\n guidKey: string,\n packageUrl: string,\n error: unknown,\n): void {\n const doomed = registry.loadState.fail(guidKey, error);\n for (const key of doomed) registry.assetCatalog.delete(key);\n registry.packFileCache.delete(packageUrl);\n}\n\n/**\n * M4 transport fallback: try the injected {@link ImportTransport} to lazily\n * import a missing DDC, then re-enter the DDC load path. When no transport\n * is wired (shipped form), fail fast with `asset-not-imported` (AC-22).\n */\nexport async function transportOrFail<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n guidKey: string,\n _missReason: AssetErrorCode,\n): Promise<Result<T, AssetError | ImageError | RhiError>> {\n if (registry.importTransport === undefined) {\n // shipped form: no transport wired -> fail fast, never degrade to\n // runtime import (AC-22, charter P3 explicit failure).\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `GUID ${guidKey} to have been pre-imported at build time or to have an ImportTransport wired`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n\n // studio form: request the transport to import this GUID on-the-fly.\n // After a successful transport call the DDC is available; re-enter the\n // catalog + DDC load path (the transport writes the DDC but does NOT\n // register the asset — that's the Loader's job).\n const transportResult = await registry.importTransport.fetchPack(\n guidKey,\n registry.runtimeBinding,\n );\n if (!transportResult.ok) {\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `import transport to fetch pack for GUID ${guidKey}`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n\n // Patch ONLY the freshly imported rows into the catalog cache (per-asset\n // incremental, the four-verb redesign 2026-06-06) instead of nuking the\n // cache and re-fetching the whole pack-index. The transport returns the one\n // imported entry (+ sub-asset siblings); each becomes / overwrites a cache\n // row. This keeps 122 concurrent texture imports O(N) instead of O(N^2)\n // whole-catalog re-fetches and never resets a sibling's imported row.\n const importedEntries = 'entries' in transportResult ? transportResult.entries : undefined;\n if (importedEntries !== undefined && importedEntries.length > 0) {\n // F20: serialise packIndexCache writes through a per-cache Promise queue.\n // The \"check -> new Map -> set\" block is not atomic across concurrent\n // transportOrFail calls; chaining through the queue ensures each patch\n // completes before the next starts, preventing new-Map overwrite races.\n registry.packIndexCachePatchQueue = registry.packIndexCachePatchQueue.then(() => {\n if (registry.packIndexCache === undefined) registry.packIndexCache = new Map();\n for (const e of importedEntries) {\n if (typeof e.packageUrl !== 'string' || e.packageUrl.length === 0) continue;\n registry.packIndexCache.set(e.guid.toLowerCase(), {\n packageUrl: resolveCatalogAssetUrl(registry, e.packageUrl),\n kind: e.kind,\n // Carry the transport's derived display name into the cache row.\n // buildCatalog already resolves it (deriveAssetName: basename of the\n // source for single-/no-storedName sub-assets), so a freshly imported\n // GLB's 1000+ sub-assets show as \"<file>.glb\" in the Content Browser\n // instead of blank. Dropping it here made listCatalog fall back to\n // `entry.name ?? ''` — the whole-index re-read path (else branch) kept\n // names, so only the incremental patch path was blank.\n ...(e.name !== undefined ? { name: e.name } : {}),\n // Carry refs on the incremental patch path too, else an asset\n // imported via POST /__import shows missing dependency edges until\n // the next full pack-index refresh (feat: listCatalog refs).\n ...(e.refs !== undefined ? { refs: e.refs } : {}),\n ...(e.packageId !== undefined ? { packageId: e.packageId } : {}),\n ...(e.provenance !== undefined ? { provenance: e.provenance } : {}),\n ...(e.revision !== undefined ? { revision: e.revision } : {}),\n ...(e.authoring !== undefined ? { authoring: e.authoring } : {}),\n ...(e.sourceKey !== undefined ? { sourceKey: e.sourceKey } : {}),\n ...(e.sourceIndex !== undefined ? { sourceIndex: e.sourceIndex } : {}),\n ...(e.relations !== undefined ? { relations: e.relations } : {}),\n ...(e.diagnostics !== undefined ? { diagnostics: e.diagnostics } : {}),\n // Carry sourcePath on the incremental patch path too (same red-line\n // as refs above): an asset imported via POST /__import would\n // otherwise expose no source-file path in listCatalog until the next\n // full pack-index refresh, breaking editor CRUD sidecar lookup for\n // freshly imported assets. `sourcePath` is a required PackIndexEntry\n // field, so it is always present on the transport row.\n ...(e.sourcePath !== undefined ? { sourcePath: e.sourcePath } : {}),\n });\n }\n });\n await registry.packIndexCachePatchQueue;\n } else {\n // No inline rows -- fall back to a full pack-index re-read so the freshly\n // imported DDC entry is visible (legacy / non-row-returning transports).\n registry.packIndexCache = undefined;\n }\n const entry = await resolveCatalogEntry(registry, guidKey);\n if (entry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-imported',\n expected: `import transport to produce a catalog entry for GUID ${guidKey}`,\n hint: ASSET_ERROR_HINTS['asset-not-imported'],\n }),\n );\n }\n\n // Re-enter the DDC load path (identical to the catalog-hit path).\n return ddcLoad<T>(registry, guid, guidKey, entry);\n}\n\n/**\n * Register a parsed asset POD (the synchronous tail of the DDC load path:\n * `registerWithGuid`). Material parent preload is handled asynchronously\n * inside `ddcLoad` before calling this method; the registered asset is\n * always fully resolved by the time it reaches here.\n *\n * Extracted from the old `loadByGuidProd` body so `ddcLoad` and\n * `transportOrFail` share an identical load path (AC-23 key invariant).\n */\nexport function registerParsedAsset<T = Asset>(\n registry: AssetRegistry,\n guid: AssetGuid,\n asset: Asset,\n _guidKey: string,\n refs?: readonly AssetRef[],\n): Result<T, AssetError | ImageError | RhiError> {\n // feat-20260614 M8 (D-17): catalogue the parsed payload under its GUID and\n // return the PAYLOAD. `catalog` validates mesh stride + material passes and\n // returns Result.err on failure (no throw), so the loadByGuid surface stays\n // a consistent Result (charter P4 consistent abstraction).\n //\n // feat-20260622 M4 / w12 (D-9): the pack-entry refs[] ride onto the\n // catalogued envelope here so the recursive core can read envelope.refs as\n // its single recursion source.\n return registry.catalog<T>(guid, asset as T, refs) as Result<\n T,\n AssetError | ImageError | RhiError\n >;\n}\n\n/**\n * Fetch a .pack.json file, find the asset entry matching guidKey, and\n * reconstruct the Asset from its payload.\n */\n/**\n * bug-20260610: fetch one pack file and return the raw asset entry without\n * parsing. Used by `loadByGuidProd` for material kinds so the caller can\n * recursively preload `refs[]` (texture sub-assets) BEFORE the synchronous\n * materialLoader runs and rewrites values handle fields to their refs[]\n * GUID strings (feat-20260614 M8 / D-19: GUID verbatim, no handle minting).\n */\nexport async function fetchPackEntry(\n _registry: AssetRegistry,\n packageUrl: string,\n guidKey: string,\n): Promise<\n Result<{ kind: string; payload: Record<string, unknown>; refs?: string[] }, AssetError>\n> {\n let raw: unknown;\n try {\n const res = await globalThis.fetch(packageUrl);\n if (!res.ok) {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n raw = (await res.json()) as unknown;\n } catch {\n return err(\n new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n );\n }\n const packFile = raw as {\n assets?: Array<{\n guid: string;\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n }>;\n };\n const assetEntry = (packFile.assets ?? []).find(\n (a) => a.guid.toLowerCase() === guidKey.toLowerCase(),\n );\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return ok({\n kind: assetEntry.kind,\n payload: assetEntry.payload,\n ...(assetEntry.refs !== undefined ? { refs: assetEntry.refs } : {}),\n });\n}\n\n/**\n * Fetch one pack file, locate the requested asset entry, and either parse it\n * inline or expose the entry to the caller (for kinds that need to preload\n * `refs[]` BEFORE running the loader — currently 'material', whose\n * values handle fields are rewritten to their refs[] GUID strings\n * (feat-20260614 M8 / D-19: GUID verbatim, no handle minting at load time)).\n *\n * bug-20260610 Fix B (M3 / D-4): the fetch+parse result is cached per\n * `packageUrl` in `packFileCache`; concurrent calls for the same URL share\n * a single in-flight promise via `packFileInFlight`. Only the raw parsed\n * body is cached — `parseAssetPayload` still runs per-call (CON-2).\n */\nexport async function fetchPackFile(\n registry: AssetRegistry,\n packageUrl: string,\n guidKey: string,\n _kind: string,\n): Promise<Result<{ asset: Asset; refs: readonly string[] }, AssetError>> {\n // ── cache hit ───────────────────────────────────────────────────────\n const cached = registry.packFileCache.get(packageUrl);\n if (cached !== undefined) {\n const assetEntry = cached.assets.find((a) => a.guid.toLowerCase() === guidKey.toLowerCase());\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return parseAndReturnAsset(registry, assetEntry);\n }\n\n // ── in-flight dedup ─────────────────────────────────────────────────\n const inFlight = registry.packFileInFlight.get(packageUrl);\n if (inFlight !== undefined) {\n try {\n const packFile = await inFlight;\n const assetEntry = packFile.assets.find(\n (a) => a.guid.toLowerCase() === guidKey.toLowerCase(),\n );\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return parseAndReturnAsset(registry, assetEntry);\n } catch {\n // In-flight promise rejected (network failure) — fall through to\n // re-fetch. The in-flight entry was already cleaned by the\n // catch block in the original miss path.\n }\n }\n\n // ── miss: fetch + parse + cache ─────────────────────────────────────\n return fetchAndCachePackFile(registry, packageUrl, guidKey);\n}\n\n/**\n * Parse the asset payload from a pack-file entry and return the result.\n * Extracted so cache-hit and in-flight-dedup paths share the same\n * parseAssetPayload + error-wrapping logic.\n */\nexport function parseAndReturnAsset(\n registry: AssetRegistry,\n assetEntry: {\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n },\n): Result<{ asset: Asset; refs: readonly string[] }, AssetError> {\n const parsed = parseAssetPayload(registry, assetEntry.kind, assetEntry.payload, assetEntry.refs);\n // F21: the scene loader returns its structured ParseErrorDetail inline via\n // the LoaderOutput `{ ok: false, error }` arm, surfaced here through\n // parseAssetPayload's return value -- no shared instance slot.\n if (parsed !== undefined && typeof parsed === 'object' && 'ok' in parsed) {\n const e = (parsed as { readonly ok: false; readonly error: ParseErrorDetail }).error;\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `refs index ${e.index} within [0, ${e.refsLength})`,\n detail: {\n localId: e.localId,\n component: e.component,\n field: e.field,\n index: e.index,\n refsLength: e.refsLength,\n },\n hint:\n `at node localId=${e.localId}, component=${e.component}, ` +\n `field=${e.field}: index ${e.index} is out of bounds ` +\n `(refs has ${e.refsLength} entries)`,\n }),\n );\n }\n if (parsed === undefined) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `parseable asset payload for kind ${assetEntry.kind}`,\n hint: ASSET_ERROR_HINTS['asset-parse-failed'],\n }),\n );\n }\n // feat-20260622 M4 / w12: surface the pack-entry refs[] (GUID-string\n // projection) alongside the parsed payload so ddcLoad can store them on\n // the catalogued envelope. The recursive core then reads envelope.refs\n // as the single recursion source (D-5), never re-deriving them from\n // the payload.\n return ok({ asset: parsed as Asset, refs: assetEntry.refs ?? [] });\n}\n\n/**\n * Fetch a pack file from the network, parse the JSON body, store the\n * result in the cache, and return the requested asset entry.\n *\n * Registers the in-flight promise in `packFileInFlight` so concurrent\n * callers share a single fetch. On success the body moves to\n * `packFileCache`; on failure the in-flight entry is removed so\n * subsequent retries re-fetch (D-7).\n */\nexport async function fetchAndCachePackFile(\n registry: AssetRegistry,\n packageUrl: string,\n guidKey: string,\n): Promise<Result<{ asset: Asset; refs: readonly string[] }, AssetError>> {\n const fetchPromise = (async (): Promise<ParsedPackFile> => {\n let raw: unknown;\n try {\n const res = await globalThis.fetch(packageUrl);\n if (!res.ok) {\n throw new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n });\n }\n raw = (await res.json()) as unknown;\n } catch (e) {\n if (e instanceof AssetError) throw e;\n throw new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${packageUrl}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n });\n }\n // Shape guard: the dev-server / preview / 404 fallback can return\n // index.html or an unrelated JSON body that satisfies res.ok but lacks\n // the ParsedPackFile contract. Without this guard the downstream\n // `packFile.assets.find` raises TypeError outside any AssetError\n // branch, escapes as a process-level Unhandled Rejection, and drives\n // vitest browser-project exit=1 even when every onerror-gate test\n // assertion passes (feat-20260611 step-implement F-4).\n if (\n raw === null ||\n typeof raw !== 'object' ||\n !Array.isArray((raw as { assets?: unknown }).assets)\n ) {\n throw new AssetError({\n code: 'asset-fetch-failed',\n expected: `pack-file body at ${packageUrl} to be { assets: [...] }`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n });\n }\n return raw as ParsedPackFile;\n })();\n\n registry.packFileInFlight.set(packageUrl, fetchPromise);\n\n try {\n const packFile = await fetchPromise;\n registry.packFileCache.set(packageUrl, packFile);\n registry.packFileInFlight.delete(packageUrl);\n\n const assetEntry = packFile.assets.find((a) => a.guid.toLowerCase() === guidKey.toLowerCase());\n if (assetEntry === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${guidKey} present in pack file ${packageUrl}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n return parseAndReturnAsset(registry, assetEntry);\n } catch (e) {\n registry.packFileInFlight.delete(packageUrl);\n if (e instanceof AssetError) {\n return err(e);\n }\n throw e;\n }\n}\n\n/**\n * Reconstruct a typed `Asset` from a raw payload object.\n *\n * @param kind The asset kind discriminant (matches the pack entry or\n * dev-register dispatch).\n * @param payload The serialised asset payload (keys mirror the asset\n * interface field names).\n * @param refs Pack-file refs array for Handle fields — when a field\n * value is `number` it resolves to `refs[N]` (glTF-style index).\n * Optional to preserve compatibility with callers outside the pack\n * ingestion path (e.g., direct `registerWithGuid`).\n */\nexport function parseAssetPayload(\n registry: AssetRegistry,\n kind: string,\n payload: Record<string, unknown>,\n refs?: string[],\n):\n | Asset\n | Record<string, unknown>\n | undefined\n | { readonly ok: false; readonly error: ParseErrorDetail } {\n // feat-20260603-asset-import-loader-injection M1 / w4: dispatch on\n // `kind` through the injected LoaderRegistry instead of a hardcoded\n // `if (kind === ...)` chain (D-1 / AC-01). The seven inline pack-payload\n // loaders parse synchronously; texture / font live on the upstream\n // loadByGuidProd branch (w6) and are never reached here.\n // feat-20260623 M2 / w5: unknown kinds pass through the raw payload so\n // host-registered loaders can parse their own kind. The engine does not\n // parse payloads it cannot match; parse responsibility is explicit on the\n // missing loader (charter P3).\n const loader = registry.loaders.get(kind);\n if (loader === undefined) return { ...payload, kind };\n const out = loader.load(payload, refs, makeLoadContext(registry));\n // The inline pack-payload loaders are synchronous (`Asset | undefined`);\n // the async texture / font loaders are dispatched from loadByGuidProd, not\n // here. A Promise here would mean a misregistered loader -> treat as a\n // parse miss rather than leaking a thenable into the sync return.\n if (out !== undefined && typeof (out as { then?: unknown }).then === 'function') {\n return undefined;\n }\n // F21: the scene loader returns { ok: false, error: ParseErrorDetail } for\n // structured parse errors. Pass the error arm straight through the return\n // value so the caller constructs a precise AssetError -- no instance slot.\n if (out !== undefined && out !== null && typeof out === 'object' && 'ok' in out) {\n return out as { readonly ok: false; readonly error: ParseErrorDetail };\n }\n return out as Asset | undefined;\n}\n\n/**\n * Build the {@link LoadContext} passed to a loader's `load`.\n * `fetchBinary` / `resolveRef` / `device` are wired for the async texture /\n * font loaders (w6).\n */\nexport function makeLoadContext(registry: AssetRegistry): LoadContext {\n return {\n /**\n * feat-20260706 M3 / w19: fetchBinary signature extended per D-2.\n * `opts?.compression` triggers the single decompression gate (AC-02).\n * 'zstd' → lazy-init codec decompressZstd · 'none' / undefined → pass-through.\n * On decompression failure, the codec error is nested in asset-fetch-failed\n * detail (D-8: runtime error union NOT extended).\n */\n fetchBinary: async (url: string, opts?: { readonly compression?: AssetCompression }) => {\n try {\n const res = await globalThis.fetch(url);\n if (!res.ok) {\n return {\n ok: false as const,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to return ok`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n };\n }\n const buf = await res.arrayBuffer();\n let bytes: Uint8Array = new Uint8Array(buf);\n\n // --- Decompression gate (AC-02: single gate inside fetchBinary) ---\n if (opts?.compression === 'zstd') {\n const { decompressZstd } = await import('@forgeax/engine-codec');\n const decRes = await decompressZstd(bytes);\n if (!decRes.ok) {\n return {\n ok: false as const,\n error: new AssetError({\n code: 'asset-parse-failed',\n expected: `zstd decompression for ${url}`,\n hint: `[${decRes.error.code}] ${decRes.error.hint}`,\n detail: { sourcePath: url },\n }),\n };\n }\n bytes = new Uint8Array(\n decRes.value.buffer,\n decRes.value.byteOffset,\n decRes.value.byteLength,\n );\n }\n // compression === 'none' / undefined → E1 pass-through\n\n return { ok: true as const, value: bytes };\n } catch {\n return {\n ok: false as const,\n error: new AssetError({\n code: 'asset-fetch-failed',\n expected: `fetch(${url}) to succeed`,\n hint: ASSET_ERROR_HINTS['asset-fetch-failed'],\n }),\n };\n }\n },\n resolveRef: async (guid: string) => {\n const parsed = AssetGuid.parse(guid);\n if (!parsed.ok) {\n return { ok: false as const, error: parsed.error };\n }\n const r = await loadByGuid(registry, parsed.value);\n if (!r.ok) return { ok: false as const, error: r.error };\n // feat-20260614 M8 (D-19): resolveRef ensures the sub-asset is\n // catalogued (recursive load). The numeric value is vestigial -- the\n // registry mints no handles; callers store the GUID, not this number.\n return { ok: true as const, value: 0 };\n },\n // feat-20260613-material-paramschema-driven-binding M4 / w22 (D-5 graceful):\n // expose the registered shader's derive(paramSchema).textureFieldNames to\n // the materialLoader so it can decide which values fields carry\n // refs[] indices without a hardcoded texture-field allowlist Set\n // (AC-03). Returns `undefined` when the shader is not registered (cross-\n // worktree shader-late-register, plan R-4) — the loader then falls back\n // to a graceful \"try every int paramValue\" walk.\n getMaterialShaderTextureFieldNames: (shaderId: string) => {\n const lookup = registry.shaderRegistry.findMaterialArtifact(shaderId);\n if (!lookup.ok) return undefined;\n return lookup.value.paramSchemaProjection.derivedInterface.textureFieldNames;\n },\n transcodeCaps: registry.transcodeCaps,\n device: undefined,\n };\n}\n\n/**\n * Return a runtime snapshot of every catalogued asset. Each entry exposes\n * `{ guid, kind, name }` where `kind` is the asset discriminant string\n * from `payload.kind`. feat-20260614 M8 (D-15): the registry holds no\n * handles -- entries are keyed by GUID (the catalogue key).\n *\n * AI-user narrowing flow (AC-11 + plan-strategy §7.4):\n * ```ts\n * for (const e of registry.inspect().assets) {\n * if (e.kind === 'texture') {\n * // re-query via registry.lookup(e.guid) to get the typed Asset value.\n * }\n * }\n * ```\n */\n","export type LoadStatus = 'unloaded' | 'provisional' | 'ready' | 'failed';\n\nexport interface LoadRecord {\n readonly status: LoadStatus;\n readonly refs: readonly string[];\n readonly value?: unknown;\n readonly error?: unknown;\n}\n\ninterface MutableLoadRecord {\n status: LoadStatus;\n refs: readonly string[];\n value?: unknown;\n error?: unknown;\n}\n\nexport class LoadStateStore {\n private readonly records = new Map<string, MutableLoadRecord>();\n\n get(guid: string): LoadRecord | undefined {\n return this.records.get(guid.toLowerCase());\n }\n\n getReady<T = unknown>(guid: string): T | undefined {\n const record = this.records.get(guid.toLowerCase());\n return record?.status === 'ready' ? (record.value as T) : undefined;\n }\n\n /**\n * Return a provisional value only for the internal SCC back-edge bridge.\n * Public callers must use getReady so promotion remains the visibility gate.\n */\n getProvisional<T = unknown>(guid: string): T | undefined {\n const record = this.records.get(guid.toLowerCase());\n return record?.status === 'provisional' ? (record.value as T) : undefined;\n }\n\n begin(guid: string, refs: readonly string[]): LoadRecord {\n const key = guid.toLowerCase();\n const existing = this.records.get(key);\n if (existing?.status === 'provisional' || existing?.status === 'ready') return existing;\n const record: MutableLoadRecord = {\n status: 'provisional',\n refs: refs.map((ref) => ref.toLowerCase()),\n };\n this.records.set(key, record);\n return record;\n }\n\n resolveAsset(guid: string, value: unknown): void {\n const key = guid.toLowerCase();\n const record = this.records.get(key);\n if (record === undefined) {\n this.records.set(key, { status: 'provisional', refs: [], value });\n return;\n }\n record.value = value;\n }\n\n registerReady(guid: string, value: unknown): void {\n this.begin(guid, []);\n this.resolveAsset(guid, value);\n this.promoteReady(guid);\n }\n\n promoteReady(guid: string): void {\n const root = guid.toLowerCase();\n const group = this.provisionalGroup(root);\n if (group.size === 0) return;\n for (const key of group) {\n const record = this.records.get(key);\n if (record?.value === undefined) return;\n for (const ref of record.refs) {\n const dependency = this.records.get(ref);\n if (dependency === undefined || (dependency.status !== 'ready' && !group.has(ref))) return;\n }\n }\n for (const key of group) {\n const record = this.records.get(key);\n if (record !== undefined) record.status = 'ready';\n }\n }\n\n fail(guid: string, error: unknown): readonly string[] {\n const doomed = this.provisionalGroup(guid.toLowerCase());\n if (doomed.size === 0) doomed.add(guid.toLowerCase());\n for (const key of doomed) {\n this.records.set(key, { status: 'unloaded', refs: [] });\n }\n const root = this.records.get(guid.toLowerCase());\n if (root !== undefined) root.error = error;\n return [...doomed];\n }\n\n remove(guid: string): void {\n this.records.delete(guid.toLowerCase());\n }\n\n clear(): void {\n this.records.clear();\n }\n\n private provisionalGroup(root: string): Set<string> {\n const group = new Set<string>();\n const visit = (key: string): void => {\n if (group.has(key)) return;\n const record = this.records.get(key);\n if (record?.status !== 'provisional') return;\n group.add(key);\n for (const ref of record.refs) visit(ref);\n };\n visit(root);\n return group;\n }\n}\n","// @forgeax/engine-assets-runtime -- material validation collaboration module (feat-20260705-runtime-tier2-decomposition M1 / w5, D-4). Free functions taking the AssetRegistry instance as first param; extracted from the class body, logic byte-preserved.\n\nimport type { CookedMaterialRecord } from '@forgeax/engine-pack';\nimport {\n AssetError,\n createMaterialError,\n type MaterialAsset,\n type MaterialError,\n type MaterialParameter,\n} from '@forgeax/engine-types';\nimport type { AssetRegistry } from '../asset-registry';\n\n/**\n * Validate a MaterialAsset's passes[] against the ShaderRegistry's\n * paramSchema (union semantics: all declared params across all passes\n * must be satisfiable from values).\n *\n * - Empty / undefined passes[] → error\n * - Each pass's shader must exist in ShaderRegistry\n * - Union of all pass paramSchemas: params without `default` must\n * appear in values with matching type\n * - Extra keys in values are silently ignored (D-5)\n *\n * @returns AssetError on failure, null on success\n */\nexport function validateMaterialPasses(\n registry: AssetRegistry,\n asset: MaterialAsset,\n): AssetError | null {\n const passes = asset.passes;\n // undefined passes is valid (material inherits from parent at resolve time);\n // only explicit empty passes[] is an error.\n if (passes === undefined || passes.length === 0) {\n if (passes !== undefined && passes.length === 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: 'MaterialAsset with at least one pass',\n hint: 'add at least one pass descriptor to passes[] before register',\n detail: { passCount: 0 },\n });\n }\n // passes undefined: skip validation (inherits from parent later)\n return null;\n }\n\n const allSchemas: MaterialParameter[] = [...(asset.parameters ?? [])];\n for (let passIndex = 0; passIndex < passes.length; passIndex++) {\n const pass = passes[passIndex];\n if (pass === undefined) continue;\n if (pass.program.module.length === 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: 'pass.program.module to be a non-empty module identifier',\n hint: `pass[${passIndex}] has an empty program.module`,\n });\n }\n }\n\n // Deduplicate by name (first occurrence wins)\n const seen = new Set<string>();\n const unionSchema: MaterialParameter[] = [];\n for (const entry of allSchemas) {\n if (!seen.has(entry.name)) {\n seen.add(entry.name);\n unionSchema.push(entry);\n }\n }\n\n const values: Record<string, unknown> = (asset.values as Record<string, unknown>) ?? {};\n\n // feat-20260613-material-paramschema-driven-binding M3 / w16 (D-2):\n // derive(schema) is the SSOT for which schema fields are textures vs\n // samplers vs numeric. The register-time three-layer validation (extra-\n // key / type-mismatch / missing-required) categorizes fields via\n // derive output instead of a hardcoded literal type list. Texture\n // and sampler fields are always optional at register time (the\n // resource handles may not be available yet — D-5 graceful path),\n // so derive-derived membership decides the skip set without keeping\n // a parallel literal table.\n const missingParams: string[] = [];\n for (const entry of unionSchema) {\n const value = values[entry.name];\n if (value === undefined) {\n if (entry.default !== undefined || entry.optional || entry.type === 'texture') {\n continue;\n }\n missingParams.push(entry.name);\n continue;\n }\n if (value === null && entry.optional) continue;\n // Type-check supplied values\n const typeOk = validateParamType(registry, entry.name, entry.type, value);\n if (!typeOk) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `values.${entry.name} to be of type ${entry.type}`,\n hint: `values['${entry.name}'] has type ${typeof value} but paramSchema declares ${entry.type}`,\n detail: { paramName: entry.name, expectedType: entry.type, got: typeof value },\n });\n }\n }\n\n if (missingParams.length > 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `values to contain keys: ${missingParams.join(', ')}`,\n hint: `missing required params: ${missingParams.join(', ')}`,\n detail: { missingParams },\n });\n }\n\n return null;\n}\n\ntype TransmissionParameter =\n | 'transmission'\n | 'ior'\n | 'thickness'\n | 'attenuationColor'\n | 'attenuationDistance'\n | 'transmissionTexture'\n | 'thicknessTexture';\n\nfunction transmissionError(\n material: string,\n parameter: TransmissionParameter,\n reason: 'non-finite' | 'range' | 'shape' | 'blend' | 'depth-write',\n actual?: unknown,\n): MaterialError {\n return createMaterialError('material-transmission-contract-invalid', {\n code: 'material-transmission-contract-invalid',\n material,\n parameter,\n reason,\n ...(actual === undefined ? {} : { actual }),\n });\n}\n\nfunction validateTransmissionNumber(\n material: string,\n values: Record<string, unknown>,\n parameter: 'transmission' | 'ior' | 'thickness' | 'attenuationDistance',\n minimum: number,\n maximum?: number,\n): MaterialError | null {\n const value = values[parameter];\n if (value === undefined) return null;\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n return transmissionError(material, parameter, 'non-finite', value);\n }\n if (value < minimum || (maximum !== undefined && value > maximum)) {\n return transmissionError(material, parameter, 'range', value);\n }\n return null;\n}\n\nexport function validateMaterialTransmissionContract(asset: MaterialAsset): MaterialError | null {\n const material = (asset.values?.materialName as string | undefined) ?? '<unnamed>';\n const values = (asset.values ?? {}) as Record<string, unknown>;\n const numericChecks: ReadonlyArray<\n ['transmission' | 'ior' | 'thickness' | 'attenuationDistance', number, number | undefined]\n > = [\n ['transmission', 0, 1],\n ['ior', 1, undefined],\n ['thickness', 0, undefined],\n ['attenuationDistance', Number.MIN_VALUE, undefined],\n ];\n for (const [parameter, minimum, maximum] of numericChecks) {\n const error = validateTransmissionNumber(material, values, parameter, minimum, maximum);\n if (error !== null) return error;\n }\n const attenuationColor = values.attenuationColor;\n if (attenuationColor !== undefined) {\n if (\n !Array.isArray(attenuationColor) ||\n attenuationColor.length !== 3 ||\n attenuationColor.some(\n (value) => typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1,\n )\n ) {\n return transmissionError(material, 'attenuationColor', 'shape', attenuationColor);\n }\n }\n for (const parameter of ['transmissionTexture', 'thicknessTexture'] as const) {\n const value = values[parameter];\n if (\n value !== undefined &&\n typeof value !== 'string' &&\n !(typeof value === 'number' && Number.isInteger(value) && value >= 0) &&\n (typeof value !== 'object' || value === null || Array.isArray(value))\n ) {\n return transmissionError(material, parameter, 'shape', value);\n }\n }\n const transmission = values.transmission;\n if (typeof transmission === 'number' && transmission > 0) {\n for (const pass of asset.passes ?? []) {\n if (pass.renderState?.blend !== undefined) {\n return transmissionError(material, 'transmission', 'blend');\n }\n if (pass.renderState?.depthWriteEnabled === true) {\n return transmissionError(material, 'transmission', 'depth-write');\n }\n }\n }\n return null;\n}\n\nexport interface MaterialEffectiveRootIdentity {\n readonly guid: string;\n readonly layoutIdentity: string;\n}\n\nexport function validateMaterialCookIdentity(\n record: Pick<CookedMaterialRecord, 'guid' | 'receipt'>,\n root: MaterialEffectiveRootIdentity,\n): MaterialError | null {\n const actual = record.receipt.identity.layoutIdentity;\n if (\n actual !== root.layoutIdentity ||\n record.receipt.derivedInterface.layoutIdentity !== root.layoutIdentity\n ) {\n return createMaterialError('material-derived-interface-mismatch', {\n code: 'material-derived-interface-mismatch',\n stage: 'extract',\n material: record.guid,\n layoutIdentity: root.layoutIdentity,\n expectedIdentity: root.layoutIdentity,\n actualIdentity: actual,\n action: 'recook',\n });\n }\n return null;\n}\n\n/**\n * Sprite 9-slice values fail-fast validation\n * (feat-20260527-sprite-nineslice M2 / w8, plan-strategy §D-1 + AC-08).\n *\n * Fires when:\n * - asset.kind === 'material'\n * - first pass shader === 'forgeax::sprite'\n * - values.slices is present\n *\n * Six fail-fast branches (1:1 with w4 test):\n * (1) any component is negative\n * (2) slices.x + slices.z >= region.zw[0] (X-axis overlap)\n * (3) slices.y + slices.w >= region.zw[1] (Y-axis overlap)\n * (4) any component is NaN\n * (5) any component is Infinity\n * (6) length !== 4\n *\n * Reuses the existing 'asset-invalid-value' member of the closed\n * `AssetErrorCode` 13-member union (no new code added per\n * AGENTS.md §Error model). The `.expected` literal mirrors the AI-User\n * Charter §3 string; `.hint` inlines the offending sum + the relevant\n * `region.zw` numeral so AI users can copy-paste the prompt straight\n * back into the IDE for self-recovery (plan-strategy §R-4).\n *\n * @returns AssetError on failure, null on success.\n */\nexport function validateSpriteSlices(\n _registry: AssetRegistry,\n asset: MaterialAsset,\n): AssetError | null {\n const passes = asset.passes;\n if (passes === undefined || passes.length === 0) return null;\n const firstPass = passes[0];\n if (firstPass === undefined || firstPass.program.module !== 'forgeax_material::sprite')\n return null;\n const pv = (asset.values ?? {}) as Record<string, unknown>;\n const slicesRaw = pv.slices;\n // Field absent — caller relies on paramSchema default [0, 0, 0, 0]; nothing to check.\n if (slicesRaw === undefined) return null;\n const expected =\n 'values.slices: [number, number, number, number] with 0 ≤ left + right < region.zw[0] and 0 ≤ top + bottom < region.zw[1]';\n if (!Array.isArray(slicesRaw)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices is not an array (got ${typeof slicesRaw}); must be a 4-tuple [left, top, right, bottom]`,\n detail: { paramName: 'slices', got: typeof slicesRaw },\n });\n }\n // (6) length check\n if (slicesRaw.length !== 4) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices length is ${slicesRaw.length}; must be 4 ([left, top, right, bottom])`,\n detail: { paramName: 'slices', got: slicesRaw.length },\n });\n }\n const slices = slicesRaw as readonly unknown[];\n // Type check each component first.\n for (let i = 0; i < 4; i++) {\n if (typeof slices[i] !== 'number') {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] is not a number (got ${typeof slices[i]})`,\n detail: { paramName: 'slices', got: typeof slices[i] },\n });\n }\n }\n const left = slices[0] as number;\n const top = slices[1] as number;\n const right = slices[2] as number;\n const bottom = slices[3] as number;\n // (4) NaN\n for (let i = 0; i < 4; i++) {\n if (Number.isNaN(slices[i] as number)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] is NaN; all four components must be finite non-negative numbers`,\n detail: { paramName: 'slices', got: 'NaN' },\n });\n }\n }\n // (5) Infinity\n for (let i = 0; i < 4; i++) {\n if (!Number.isFinite(slices[i] as number)) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] is Infinity; all four components must be finite non-negative numbers`,\n detail: { paramName: 'slices', got: 'Infinity' },\n });\n }\n }\n // (1) negative — D-3 sentinel uses negative .w for tile mode but only\n // after extract; at register-time the user-supplied tuple must be all\n // non-negative (the engine encodes the sign downstream).\n for (let i = 0; i < 4; i++) {\n if ((slices[i] as number) < 0) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `values.slices[${i}] = ${slices[i]}; all four components must be non-negative`,\n detail: { paramName: 'slices', got: slices[i] as number },\n });\n }\n }\n // (2)/(3) overlap with region. region default is [0, 0, 1, 1];\n // user override comes via values.region (vec4).\n const regionRaw = pv.region;\n let regionZ = 1;\n let regionW = 1;\n if (Array.isArray(regionRaw) && regionRaw.length >= 4) {\n const rz = regionRaw[2];\n const rw = regionRaw[3];\n if (typeof rz === 'number') regionZ = rz;\n if (typeof rw === 'number') regionW = rw;\n }\n const sumX = left + right;\n if (sumX >= regionZ) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `received slices=[${left}, ${top}, ${right}, ${bottom}]; left + right = ${sumX} ≥ ${regionZ} (region.z)`,\n detail: { paramName: 'slices', got: sumX },\n });\n }\n const sumY = top + bottom;\n if (sumY >= regionW) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected,\n hint: `received slices=[${left}, ${top}, ${right}, ${bottom}]; top + bottom = ${sumY} ≥ ${regionW} (region.w)`,\n detail: { paramName: 'slices', got: sumY },\n });\n }\n return null;\n}\n\nexport function validateParamType(\n _registry: AssetRegistry,\n _name: string,\n type: string,\n value: unknown,\n): boolean {\n switch (type) {\n case 'f32':\n case 'i32':\n case 'u32':\n return typeof value === 'number';\n case 'vec2':\n return Array.isArray(value) && value.length >= 2 && value.every((v) => typeof v === 'number');\n case 'vec3':\n return Array.isArray(value) && value.length >= 3 && value.every((v) => typeof v === 'number');\n case 'vec4':\n return Array.isArray(value) && value.length >= 4 && value.every((v) => typeof v === 'number');\n case 'color':\n return (\n Array.isArray(value) &&\n (value.length === 3 || value.length === 4) &&\n value.every((v) => typeof v === 'number')\n );\n case 'texture':\n // A cooked pack may keep an asset GUID as the compact texture\n // shorthand. The render material resolver expands that reference at\n // the resource boundary; rejecting it here makes authored packs fail\n // before the same value can reach the resolver.\n return (\n typeof value === 'string' ||\n (typeof value === 'object' && value !== null && !Array.isArray(value))\n );\n case 'bool':\n return typeof value === 'boolean';\n default:\n return false;\n }\n}\n\n/**\n * feat-20260527-sprite-nineslice M4 / w18 (D-9): register-time soft-warn\n * for sliceMode=1 (tile) bound to a sampler whose addressMode is not\n * 'repeat'. Bumps `nineslice.tile-needs-repeat-sampler` once per offending\n * catalogue call. Never throws -- the counter is the sole AI-user-facing\n * signal (charter P3 machine-readable; AC-08 closed, never extends\n * AssetErrorCode).\n *\n * feat-20260614 M8 (D-19): `values.sampler` is now an embedded GUID\n * string (dash-form), resolved against the catalogue rather than a handle.\n */\nexport function detectTileNeedsRepeatSampler(registry: AssetRegistry, asset: MaterialAsset): void {\n if (registry.metrics === null) return;\n const passes = asset.passes;\n if (passes === undefined || passes.length === 0) return;\n const firstPass = passes[0];\n if (\n firstPass === undefined ||\n (firstPass.program.module !== 'forgeax_material::sprite' &&\n firstPass.program.module !== 'forgeax::sprite')\n )\n return;\n const pv = (asset.values ?? {}) as Record<string, unknown>;\n const slicesAndMode = pv.slicesAndMode;\n const encodedTile =\n Array.isArray(slicesAndMode) && typeof slicesAndMode[3] === 'number'\n ? slicesAndMode[3] < 0\n : false;\n const legacyTile = typeof pv.sliceMode === 'number' && pv.sliceMode === 1;\n if (!encodedTile && !legacyTile) return;\n const samplerGuid = typeof pv.sampler === 'string' ? pv.sampler : undefined;\n if (samplerGuid === undefined) return;\n const samplerEnvelope = registry.assetCatalog.get(samplerGuid.toLowerCase());\n if (samplerEnvelope === undefined || samplerEnvelope.kind !== 'sampler') return;\n const samplerAsset = samplerEnvelope.payload;\n if (samplerAsset.kind !== 'sampler') return;\n const u = samplerAsset.addressModeU;\n const v = samplerAsset.addressModeV;\n if (u !== 'repeat' || v !== 'repeat') {\n registry.metrics.increment('nineslice.tile-needs-repeat-sampler');\n }\n}\n\n/**\n * feat-20260613-material-paramschema-driven-binding M4 / w23 (D-5 graceful):\n * Return the texture-field name set for the given material-shader id,\n * derived from the registered shader's paramSchema via `derive(paramSchema)\n * .textureFieldNames`. Returns `undefined` when the shader is not yet\n * registered (cross-worktree shader-late-register, plan R-4).\n *\n * Used by `extractFrame` to know which values fields the shader\n * declares as texture handles; the extract layer validates handle-vs-\n * scalar typing and drops misclassified slots so the record stage's\n * MISSING_TEXTURE_HANDLE fallback can take over (white default texture)\n * rather than letting a stray handle reach `device.createBindGroup`.\n */\nexport function materialShaderTextureFieldNames(\n registry: AssetRegistry,\n shaderId: string,\n): ReadonlySet<string> | undefined {\n const lookup = registry.shaderRegistry.findMaterialArtifact(shaderId);\n if (!lookup.ok) return undefined;\n return lookup.value.paramSchemaProjection.derivedInterface.textureFieldNames;\n}\n","// @forgeax/engine-assets-runtime - AssetRegistry v2 (feat-20260513-guid-asset-package-system).\n//\n// Entrypoints (feat-20260614 M8 de-handle cut, D-15/D-17/D-19): the registry\n// is a GUID->payload catalogue. It no longer mints or maps handles -- column\n// handles are minted on the World via `world.allocSharedRef('Kind', payload)`,\n// and resolved through the two-tier `resolveAssetHandle` (BuiltinAssetRegistry\n// process-static slots [1,1024) + per-World `world.sharedRefs` slots >=1024).\n//\n// - catalog<T extends Asset>(guid, asset): Result<T, AssetError>\n// stores the GUID->payload entry loadByGuid resolves (dev/inline path)\n// - parseGuid(guidStr): AssetGuid\n// - lookup(guid): Asset | undefined (catalogued payload, no fetch)\n// - loadByGuid<T extends Asset>(guid): Promise<Result<T, AssetError | ImageError | RhiError>>\n// returns the PAYLOAD T (never a handle, D-17)\n// dev/fallback: synchronous catalogue lookup wrapped in Promise\n// prod: fetch(packIndexUrl) -> parse catalog -> fetch entry -> parse Asset\n// - instantiate<T extends SceneAsset>(handle, world, parent?): Result<EntityHandle, ...>\n// handle is a `world.allocSharedRef('SceneAsset', payload)` column handle\n// - inspect(): InspectSnapshot\n//\n// v1 load(url) removed in feat-20260513-guid-asset-package-system (w12).\n// loadByGuid is the replacement; M4/w23 adds real fetch-from-pack-index.\n//\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w15: the\n// `createInstancedBuffer` / `updateInstancedBuffer` / `getInstancedGpuBuffer`\n// triplet is removed alongside the `InstancedBufferAsset` POD; per-entity\n// instance transforms are now stored inside the ECS via the `Instances {\n// transforms: 'array<f32>' }` component (the RenderSystem record stage owns\n// the GPU storage buffer + dirty-version upload). Asset closed-union narrows\n// 5 -> 4; the registry surface loses the optional `RhiDevice` constructor\n// argument (no remaining device consumer).\n//\n// Dual-backend audited: the registry is engine-agnostic (no @webgpu/types\n// imports + no rhi-webgpu / rhi-wgpu references); the same instance drives\n// both dual-impl shim backends through the @forgeax/engine-rhi interface\n// SSOT at the consumer site.\n\nimport type { Component, EcsError, EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { PackError } from '@forgeax/engine-pack/errors';\nimport { AssetGuid } from '@forgeax/engine-pack/guid';\nimport { deriveAssetName } from '@forgeax/engine-pack/name';\nimport { err, ok, type Result, type RhiError } from '@forgeax/engine-rhi';\nimport type { ShaderRegistry } from '@forgeax/engine-shader';\nimport {\n ASSET_ERROR_HINTS,\n type Asset,\n type AssetEnvelope,\n AssetError,\n type AssetEvidence,\n type AssetEvidenceError,\n type AssetRef,\n authoringCapabilityForAssetKind,\n type CatalogEntry,\n catalogOperationsFor,\n type EngineMetrics,\n type Handle,\n handleSlot,\n type ImageError,\n type ImportTransport,\n type InspectEntry,\n type InspectSnapshot,\n type Loader,\n type MaterialAsset,\n type MountOverride,\n migrateLegacyMeshMaterialOverrides,\n type Package,\n type ParseErrorDetail,\n type RuntimeAssetBinding,\n type SceneAsset,\n type SceneEntity,\n type SceneInstanceMount,\n type TagOf,\n type TilesetAsset,\n type TranscodeCaps,\n type MeshAsset as TypesMeshAsset,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport {\n BUILTIN_CUBE,\n BUILTIN_CYLINDER,\n BUILTIN_NINESLICE_QUAD,\n BUILTIN_QUAD,\n BUILTIN_SPHERE,\n BUILTIN_TRIANGLE,\n} from './builtin-asset-registry';\nimport type { LoaderRegistry } from './loader-registry';\nimport { createDefaultLoaderRegistry } from './wire-default-loaders';\n\n/**\n * Strip readonly from all fields of T. Used to mutate the MeshAsset.aabb slot\n * after mesh validation passes (the interface is readonly but register-time\n * computation writes the real AABB into the caller's placeholder).\n */\n\n// feat-20260705-runtime-tier2-decomposition M1 / w4 (D-4 F1): the pre-class\n// constants, loaders, scene-payload / payload-validate / aabb helpers were\n// straight-cut into sibling modules. The thin class value-imports only what its\n// method bodies still reference; the full public consumer face (barrel + tests)\n// is preserved via the `export ... from` re-export block below (pre-w14 shim,\n// removed when consumers repoint in w14/w15).\nimport { withMeshAabb } from './aabb';\nimport type { CatalogListener, CatalogSource } from './catalog-source';\nimport {\n BUILTIN_MESH_GUIDS,\n HANDLE_CUBE,\n HANDLE_CYLINDER,\n HANDLE_NINESLICE_QUAD,\n HANDLE_QUAD,\n HANDLE_SPHERE,\n HANDLE_TRIANGLE,\n} from './handles';\nimport type { MaterialLoadError, MaterialReady } from './material/loader';\nimport { installMaterialReadyShaders } from './material/runtime-shader';\nimport { inferAtlasExtent, validateMeshPayload, validateTilesetPayload } from './payload-validate';\nimport { ArtifactReadCache } from './registry/artifact-io';\nimport {\n createRuntimeAssetEvidenceAdapter,\n type RuntimeAssetEvidenceAdapter,\n type RuntimeEvidenceSource,\n} from './registry/asset-evidence';\nimport { type CatalogRecord, fetchPackIndex } from './registry/catalog';\nimport { CatalogReplica, type CatalogReplicaSnapshot } from './registry/catalog-state';\nimport {\n instantiateFlat as instantiateFlatImpl,\n instantiate as instantiateImpl,\n type PostSpawnHook,\n resolveHandleGuid,\n resolveMountsRec,\n} from './registry/instantiate';\nimport {\n loadByGuid as loadByGuidImpl,\n parseAndReturnAsset as parseAndReturnAssetImpl,\n parseAssetPayload as parseAssetPayloadImpl,\n registerPackagesFromIndex,\n} from './registry/load-by-guid';\nimport { LoadStateStore } from './registry/load-state';\nimport type {\n ScenePublicationFence,\n ScenePublicationFenceError,\n} from './registry/scene-publication-fence';\nimport {\n detectTileNeedsRepeatSampler,\n materialShaderTextureFieldNames as materialShaderTextureFieldNamesImpl,\n validateMaterialPasses,\n validateSpriteSlices,\n} from './registry/validate-material';\nimport { extractSceneEntityHandleGuids } from './scene-handle-fields';\n\n// Public re-export surface (pre-w14 consumer face preservation): the extracted\n// modules are the new SSOT; asset-registry re-exports them until w14/w15 repoint\n// every consumer to the sibling modules / the new package.\nexport {\n HANDLE_CUBE,\n HANDLE_CYLINDER,\n HANDLE_NINESLICE_QUAD,\n HANDLE_QUAD,\n HANDLE_SPHERE,\n HANDLE_TRIANGLE,\n} from './handles';\nexport {\n animationClipLoader,\n animationGraphLoader,\n INLINE_PACK_LOADERS,\n materialLoader,\n meshLoader,\n sceneLoader,\n skeletonLoader,\n skinLoader,\n} from './loaders/inline-pack';\nexport {\n equirectLoader,\n fontLoader,\n PACK_ARTIFACT_LOADERS,\n textureLoader,\n} from './loaders/pack-artifact';\nexport { type TilesetValidateOptions, validateTilesetPayload } from './payload-validate';\n\n// ─── Re-exports for engine-runtime-local consumers ──────────────────────────\n//\n// Legacy re-exports: `Asset` widens to the 4-variant engine-types union;\n// `MeshAsset` keeps the engine-types shape (with `attributes`). Consumers\n// that previously imported from `./asset-registry` keep working through\n// the type alias re-exports below.\n\nexport type { Asset, TypesMeshAsset as MeshAsset };\n\n// D-15: the BUILTIN_* mesh payloads moved to builtin-asset-registry.ts (the\n// process-static payload SSOT); the shared runtime vertex layout remains owned\n// by @forgeax/engine-geometry.\n// imported at the top of this file. The constructor still pre-populates the\n// handle->payload map from those imports (the map itself retires in w49).\n\n// feat-20260618-asset-and-pack-name-fields M3 (D-1 / D-3): the mutable runtime\n// package object every GUID of the same import path shares. `assetGuids` grows\n// as `registerPackage` adds GUIDs; `assetCount` (the engine-types `Package`\n// view) is derived from `assetGuids.size`, never stored (#2 Derive). The public\n// `packageOf(guid)` projects this to the readonly `Package` interface.\ninterface MutablePackage {\n path: string;\n readonly assetGuids: Set<string>;\n}\n\n// ─── Runtime brand helper ──────────────────────────────────────────────────\n//\n// AC-11 inspect() `.brand` is a 4-member string literal union mirroring the\n// engine-types Asset discriminated union. Map a stored Asset value to its\n// brand via the `.kind` discriminator (+ `.shadingModel` refinement for\n// `MaterialAsset`, preserved for forward compatibility though the runtime\n// brand stays at the asset-kind level per AC-11 spec).\n//\n// feat-20260514 M3 / w15: the `'InstancedBufferAsset'` brand is retired\n// alongside the deleted POD + 3 registry methods; the runtime brand union\n// shrinks 5 -> 4 to mirror the Asset closed-union shape.\n// feat-20260514 w3: re-extends to 5 with the addition of the `'SceneAsset'`\n// brand mirroring the new `'scene'` kind in the Asset discriminated union.\n// feat-20260618-asset-and-pack-name-fields M1 / w3: AssetBrand moved to\n// @forgeax/engine-types (public, single-entry discoverability per charter F1).\n// feat-20260608-tilemap-object-layer-rendering M0: AssetBrand union grows\n// 13 -> 14 with `'TilesetAsset'` in @forgeax/engine-types.\n\n// feat-20260622 D-4/D-8: the 14-arm assetBrand switch and ASSET_BRAND Record\n// table are both retired (PR #496 eliminated the brand concept entirely).\n// New Asset union members no longer need a brand mapping; the closed union\n// exhaustive switch in test-d files is the sole type-level guard.\n\n// ─── Schema-driven material parse result (feat-20260523 M4-T01) ──────────\n// ─── AssetRegistry class ────────────────────────────────────────────────────\n\n/**\n * Asset registry (instance-per-engine; `engine.assets: AssetRegistry | null`).\n *\n * The builtin meshes (`HANDLE_CUBE` / `HANDLE_TRIANGLE` / ...) are served by\n * the process-static `BuiltinAssetRegistry`, so AI users see usable handles in\n * the very first frame without registration ceremony (charter proposition 1).\n *\n * @example Catalogue a texture by GUID, load its payload, and bind a material:\n * ```ts\n * const guid = engine.assets.parseGuid('00000000-0000-7000-8000-000000000001');\n * engine.assets.catalog(guid, myTexture); // GUID -> payload\n * const res = await engine.assets.loadByGuid(guid); // payload (D-17)\n * if (!res.ok) {\n * switch (res.error.code) {\n * case 'asset-not-found': // guid not catalogued\n * }\n * return;\n * }\n * const material = world.allocSharedRef('MaterialAsset', { // mint column handle\n * kind: 'material',\n * passes: [{ name: 'Forward', program: { module: 'forgeax::default-standard-pbr' }, tags: { LightMode: 'Forward' }, queue: 2000 }],\n * values: { baseColorTexture: res.value },\n * });\n * world.spawn({ component: MeshRenderer, data: { materials: [material] } });\n * ```\n */\n\n// bug-20260610 Fix B: parsed pack-file body stored in the fetchPackFile\n// in-memory cache + in-flight dedup maps (D-4). Only the raw JSON shape is\n// cached -- parseAssetPayload still runs per-call to look up the per-GUID\n// entry (CON-2 register-before-recurse cycle safety).\nexport interface ParsedPackFile {\n schemaVersion?: string;\n kind?: string;\n assets: Array<{\n guid: string;\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n artifacts?: Record<string, import('@forgeax/engine-types').ArtifactDescriptor>;\n }>;\n}\n\nexport type CatalogReconcileError = AssetError;\nexport type CatalogReconcileResult = Result<CatalogReplicaSnapshot, CatalogReconcileError>;\n\nfunction catalogSourceUnconfigured<T>(): Result<T, AssetError> {\n return err(\n new AssetError({\n code: 'catalog-source-unconfigured',\n expected: 'a configured catalog source',\n hint: ASSET_ERROR_HINTS['catalog-source-unconfigured'],\n }),\n );\n}\n\nexport class AssetRegistry {\n private catalogSource: CatalogSource | undefined;\n private catalogEnumerating: Promise<Result<readonly CatalogEntry[], AssetError>> | undefined;\n private readonly catalogListeners = new Set<CatalogListener>();\n private catalogSourceDispose: (() => void) | undefined;\n private catalogReplica: CatalogReplica | undefined;\n // feat-20260614 M8 (D-15 / D-17 / D-19): the registry is a GUID -> payload\n // catalogue. It holds NO handle concept -- it cannot mint a column handle\n // (it has no World). `loadByGuid` returns the PAYLOAD; column minting\n // (`world.allocSharedRef`) is the caller's job on the ECS/render side.\n // Sub-asset refs embedded in a payload stay as GUID strings (AssetGuid /\n // dash-form), never minted at load time. Keyed by lowercased GUID string.\n // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the\n // extracted `./registry/validate-material` free functions (detectTileNeeds-\n // RepeatSampler) can read it. No underscore + genuinely public is the\n // lint-compliant exposure (D-internal R-internal-C ties `@internal` to `_`).\n readonly assetCatalog: Map<string, AssetEnvelope<Asset>> = new Map();\n\n /** Owner-injected component catalog used for scene breadcrumb projection. */\n readonly componentCatalog: ReadonlyMap<string, Component>;\n\n // feat-20260618-asset-and-pack-name-fields M3 (D-1): the package index that\n // backs the two-segment asset identity `<packagePath>.<name>`. `packages`\n // maps a lowercased GUID key to its `MutablePackage` (a shared object every\n // GUID of the same import path points at), or `null` for assets with no\n // package (catalog() inline + builtin, D-5). All three registration entry\n // points (catalog / loadByGuid / builtin) funnel through the single\n // `registerPackage` primitive so the XOR name invariant lands once (#1 SSOT).\n private readonly packages: Map<string, MutablePackage | null> = new Map();\n\n // Secondary index path -> shared MutablePackage so every GUID of the same\n // import path points at one object (the 1->N promotion + assetCount derive\n // depend on this sharing). Not a duplicate of `packages` (#2): `packages` is\n // the per-GUID lookup; this is the per-path dedup used only inside\n // registerPackage to find-or-create the shared object.\n private readonly packageByPath: Map<string, MutablePackage> = new Map();\n\n // Per-GUID stored display names now live on the asset envelope's `name` field\n // (the single home, replacing the retired storedNameOf side table; D-6).\n // resolveName reads `assetCatalog.get(key)?.name` as the `storedName` argument\n // of deriveAssetName. `pendingNames` bridges the one ordering where a name is\n // known before its envelope exists: the prod disk path registers the package\n // (entry names) during resolveCatalogEntry, then catalogues the body later --\n // catalog() drains the pending name into the new envelope, so nothing persists\n // here once the envelope is in place.\n private readonly pendingNames: Map<string, string> = new Map();\n\n // ─── Prod pack-index fetch state (M4/w23) ──────────────────────────────\n // When packIndexUrl is configured, loadByGuid fetches pack-index.json on\n // first call, caches the parsed catalog in packIndexCache, then fetches\n // each resource URL resolved against that index and registers the asset.\n packIndexUrl: string | undefined = undefined;\n packIndexCache: Map<string, CatalogRecord> | undefined = undefined;\n /** Current browser-facing asset realm; absent for inline/shipped legacy use. */\n runtimeBinding: RuntimeAssetBinding | undefined = undefined;\n\n // tweak-20260609 M1: in-flight Map for recursive loadByGuid dedup + cycle\n // prevention (D-5 / B-10). Maps guidKey → Promise<Result<Handle, ...>> so\n // concurrent calls for the same GUID share the same fetch + register chain,\n // and cycles (A→B→A) terminate when the second visit hits the in-flight\n // entry for A instead of re-entering fetch.\n readonly inFlight: Map<string, Promise<Result<unknown, AssetError | ImageError | RhiError>>> =\n new Map();\n\n // bug-20260610 Fix B (M3 / D-4): per-instance pack-file cache keyed by\n // packageUrl (the .pack.json URL). `packFileInFlight` de-duplicates\n // concurrent fetches; `packFileCache` stores resolved bodies so the\n // same URL is fetched at most once per AssetRegistry lifetime (CON-6).\n readonly packFileCache: Map<string, ParsedPackFile> = new Map();\n readonly packFileInFlight: Map<string, Promise<ParsedPackFile>> = new Map();\n readonly artifactCache = new ArtifactReadCache();\n readonly loadState = new LoadStateStore();\n /**\n * Render-facing material readiness owned by the production GUID loader.\n * The map stores the complete tuple result, including structured failures,\n * so record code cannot silently fall back to a generic MaterialAsset.\n */\n readonly materialReadiness = new Map<string, MaterialReady | MaterialLoadError>();\n private assetEvidenceAdapter: RuntimeAssetEvidenceAdapter = createRuntimeAssetEvidenceAdapter();\n\n // feat-20260621-asset-registry-robustness-invalidate-inflight-cach F17c:\n // per-GUID generation counter incremented on each invalidate(guid) call.\n // loadByGuid captures this value at Promise creation and discards the\n // result (returning asset-invalidated) if the generation has changed by\n // the time the fetch completes.\n // F22: invalidateAll increments a single globalGeneration counter instead,\n // which invalidates every in-flight Promise regardless of GUID.\n readonly generations: Map<string, number> = new Map();\n globalGeneration: number = 0;\n /**\n * Monotonic payload-cache epoch. Render-side derived snapshots use this\n * single stamp to skip re-walking an unchanged material parent chain on\n * every frame; catalog/invalidation mutations advance it conservatively.\n */\n catalogEpoch: number = 0;\n\n // F20: per-cache Promise queue to serialise packIndexCache write operations\n // in transportOrFail. The \"check -> new Map() -> set\" three-step block is\n // not atomic across concurrent transportOrFail calls; chaining through a\n // single queue Promise ensures each patch completes before the next starts.\n packIndexCachePatchQueue: Promise<void> = Promise.resolve();\n\n // feat-20260527-sprite-nineslice M4 / w16 + w18 (D-5 + D-9): per-Renderer\n // EngineMetrics shared with the runtime so register-time soft-warns\n // (`nineslice.tile-needs-repeat-sampler` for sliceMode=1 + sampler not\n // 'repeat') and runtime soft-warns (`nineslice.scale-too-small`) increment\n // the SAME counter map. `createRenderer.ts` calls `assets.setMetrics(metrics)`\n // immediately after constructing the registry; standalone test fixtures\n // that do not go through `createRenderer` may leave this null and the\n // soft-warn paths simply no-op (charter P9 graceful degradation: the\n // structured fail-fast branches still fire; only the metric is dropped).\n // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the\n // extracted `./registry/validate-material` free functions (detectTileNeeds-\n // RepeatSampler) can read + increment it. No underscore + genuinely public\n // is the lint-compliant exposure (D-internal R-internal-C ties `@internal`\n // to `_`).\n metrics: EngineMetrics | null = null;\n\n // feat-20260707 M5 / w33 (D-11): device texture-compression caps the Basis\n // texture / equirect arms feed to `selectTranscodeTarget`. `createRenderer`\n // projects `RhiCaps` -> `TranscodeCaps` and calls `setTranscodeCaps` right\n // after construction (D-8 one-line projection). A standalone registry (test /\n // headless) keeps the all-false default, which drives the uncompressed\n // fallback path (section 8 P3, AC-04) rather than a hard failure.\n transcodeCaps: TranscodeCaps = { bc: false, etc2: false, astc: false };\n\n // feat-20260703-collect-nested-sceneinstance-to-mount-roundtrip M1 (D-1):\n // origin reverse-index: a payload object -> its catalog GUID, for payloads\n // that are NOT the current catalog identity. WeakMap so entries auto-GC when\n // the world despawns and the object is no longer held by sharedRefs.\n // _guidForAsset consults it after the catalog identity scan MISSes.\n // SSOT for the \"payload-to-GUID provenance\" fact (architecture-principles #1).\n //\n // Two writers populate it:\n // 1. instantiate (registry/instantiate.ts): the resolved SceneAsset copy ->\n // its original catalog GUID (the deep-copied envelope is never the catalog\n // identity).\n // 2. feat-20260713 M4 / w15 (D-6, root cause a): catalog() records the\n // SUPERSEDED payload here when re-cataloguing a GUID with a fresh object.\n // A handle minted before the override still points at the old object; this\n // keeps that object reverse-lookupable so save/collect resolves its GUID\n // instead of failing with a GUID-unresolved error (the 2026-07-06 crash).\n //\n // Key type is `object` (not `SceneAsset`) because both material and scene\n // payloads are recorded (material payloads flow through writer 2).\n /** @internal */\n _originIndex: WeakMap<object, string> = new WeakMap();\n\n /**\n * Construct a fresh registry pre-populated with the builtin cube + triangle\n * mesh handles (`HANDLE_CUBE` / `HANDLE_TRIANGLE`).\n *\n * feat-20260514 M3 / w15: the previous optional `RhiDevice` constructor\n * argument (consumed by the now-deleted `createInstancedBuffer` triplet)\n * is removed; the registry surface is engine-agnostic again. Per-entity\n * instance transforms now live inside the ECS `Instances { transforms:\n * 'array<f32>' }` component; the RenderSystem record stage owns GPU\n * storage buffer allocation + cap-gate.\n */\n // feat-20260603-asset-import-loader-injection M1 / w5 (D-7): the registry\n // dispatches `parseAssetPayload` / the texture+font upstream branches through\n // this `LoaderRegistry`. feat-20260623 M3 / w9: the loader registry is now\n // internally built by `createDefaultLoaderRegistry()` (public readonly field)\n // so host apps can reach `engine.assets.loaders.register(...)` without a\n // constructor-injection slot or a phantom passthrough wrapper.\n // The loader set is wired at construction from the complete ordinary Asset\n // vocabulary (including video and audio) plus caller-supplied extensions.\n // Assigned here so the optional loaders cannot appear after a load begins.\n readonly loaders: LoaderRegistry;\n\n // feat-20260603-asset-import-loader-injection M4 / w31 (AC-19 / AC-22):\n // the optional `ImportTransport` is the *only* difference between the studio\n // form (transport injected, dev DDC miss triggers lazy import) and the shipped\n // form (transport absent, DDC miss fails fast with `asset-not-imported`).\n // The load path AFTER a successful DDC fetch is identical in both forms --\n // zero branching on transport (AC-23 key invariant). Set at construction (no\n // setter, no illegal intermediate state), same D-7 stance as LoaderRegistry.\n readonly importTransport: ImportTransport | undefined;\n\n // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): optional post-spawn\n // hook invoked by `instantiate` after the scene subtree spawns. The shipped\n // implementation is runtime's `postSpawnResolveJoints` (auto-wire Skin.joints),\n // injected at the sole production assembly point (createRenderer, w10). When\n // absent (standalone / test registries), instantiate skips joint wiring\n // silently. Public so the extracted `./registry/instantiate` free function can\n // read it (D-internal R-internal-C ties `@internal` to a `_` prefix;\n // genuinely-public is the lint-compliant exposure).\n readonly postSpawnHook: PostSpawnHook | undefined;\n\n /** @internal Stored for M2 validation; TS suppressor reference */\n constructor(\n // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the\n // extracted `./registry/validate-material` free functions can read it. No\n // underscore + genuinely public is the lint-compliant exposure (an\n // `@internal` tag would require a `_` prefix per D-internal R-internal-C).\n readonly shaderRegistry: ShaderRegistry,\n importTransport?: ImportTransport | undefined,\n // Caller-supplied loaders extend the ordinary default set. Duplicate kinds\n // are rejected by LoaderRegistry so no consumer can observe replacement\n // order as an accidental ownership rule.\n extraLoaders?: readonly Loader[] | undefined,\n // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): optional\n // post-spawn hook; createRenderer injects `postSpawnResolveJoints`.\n postSpawnHook?: PostSpawnHook | undefined,\n runtimeBinding?: RuntimeAssetBinding | undefined,\n componentCatalog: ReadonlyMap<string, Component> = new Map(),\n ) {\n void this.shaderRegistry;\n this.importTransport = importTransport;\n this.postSpawnHook = postSpawnHook;\n this.runtimeBinding = runtimeBinding;\n this.componentCatalog = componentCatalog;\n this.loaders = createDefaultLoaderRegistry(extraLoaders);\n this.registerBuiltins();\n }\n\n /**\n * Restore the engine-owned GUID catalogue after a runtime-realm transition.\n *\n * Builtin meshes are process-static engine assets, not game-owned catalog\n * rows. A realm transition clears the user catalog and load caches, but must\n * leave these assets addressable so a scene in the newly bound game can keep\n * resolving its builtin mesh references.\n */\n private registerBuiltins(): void {\n // feat-20260614 M8 (D-15): builtins are GUID-addressable catalogue rows.\n // The builtin payloads also live process-static in BuiltinAssetRegistry\n // (slot < BUILTIN_BASE) for handle-tier resolution; here they are\n // catalogued by GUID so loadByGuid(builtinGuid) returns the payload and\n // scene refs[] pointing at a builtin GUID resolve without a hand-\n // maintained table (docs/feedbacks/2026-06-03 §6.2 Tier 0).\n const builtinByHandle = new Map<number, Asset>([\n [handleSlot(HANDLE_CUBE), BUILTIN_CUBE],\n [handleSlot(HANDLE_TRIANGLE), BUILTIN_TRIANGLE],\n [handleSlot(HANDLE_QUAD), BUILTIN_QUAD],\n [handleSlot(HANDLE_SPHERE), BUILTIN_SPHERE],\n [handleSlot(HANDLE_NINESLICE_QUAD), BUILTIN_NINESLICE_QUAD],\n [handleSlot(HANDLE_CYLINDER), BUILTIN_CYLINDER],\n ]);\n for (const [handle, guidStr] of BUILTIN_MESH_GUIDS) {\n const parsed = AssetGuid.parse(guidStr);\n if (!parsed.ok) {\n throw new Error(`[asset-registry] builtin GUID ${guidStr} is not a valid UUID`);\n }\n const payload = builtinByHandle.get(handleSlot(handle));\n if (payload !== undefined)\n this.assetCatalog.set(guidStr.toLowerCase(), {\n guid: guidStr,\n kind: payload.kind,\n payload,\n refs: [],\n });\n if (payload !== undefined) this.loadState.registerReady(guidStr, payload);\n }\n // D-5: builtin meshes have no import path and no source name -- register\n // them with a null package so resolveName returns '' (the detectable\n // \"genuinely no name\" signal). They are deliberately NOT given a synthetic\n // package + derived name (memory builtin-guid-preregister-collides).\n this._registerPackage(\n null,\n BUILTIN_MESH_GUIDS.map(([, guidStr]) => guidStr),\n );\n }\n\n /**\n * feat-20260527-sprite-nineslice M4 / w16 prep + w18 (D-5 + D-9): inject the\n * per-Renderer `EngineMetrics` so register-time soft-warns can bump the same\n * counter map the runtime reads through `renderer.metrics.snapshot()`. Called\n * by `createRenderer` after constructing both the registry and the metrics\n * instance; safe to skip in standalone tests (the soft-warn arms simply do\n * not record).\n */\n setMetrics(metrics: EngineMetrics): void {\n this.metrics = metrics;\n }\n\n /**\n * feat-20260707 M5 / w33 (D-11): wire the device compression caps used by the\n * Basis texture / equirect transcode arms. `createRenderer` calls this right\n * after construction with `RhiCaps` projected to `TranscodeCaps` (D-8). Left\n * at the all-false default, the loaders transcode to the uncompressed\n * `rgba8unorm` / `rgba16float` fallback (AC-04, section 8 P3).\n */\n setTranscodeCaps(caps: TranscodeCaps): void {\n this.transcodeCaps = caps;\n }\n\n /**\n * Inject authoritative runtime evidence without importing CLI or Node policy.\n * `inspect(guid)` and `verifyByGuid(guid)` return the shared state model; an\n * omitted capability remains an explicit structured error, never a pass.\n */\n configureAssetEvidence(source: RuntimeEvidenceSource): void {\n this.assetEvidenceAdapter = createRuntimeAssetEvidenceAdapter(source);\n }\n\n /**\n * @internal — read the metrics handle for register-time soft-warn paths.\n * Returns `null` when no `createRenderer` wired the registry to a renderer\n * (the standalone-test path; the structured fail-fast branches still fire).\n */\n _getMetrics(): EngineMetrics | null {\n return this.metrics;\n }\n\n /**\n * @internal — reverse-lookup: find the GUID key for a catalogued asset\n * payload by identity comparison (===). Returns the GUID string if found,\n * `undefined` otherwise. This is the SSOT for the inline identity scan\n * idiom that previously existed in two places (instantiate sceneGuidKey\n * lookup and resolveSkinAsset skeleton match).\n *\n * Linear scan of the assetCatalog (Map<string, AssetEnvelope>). The O(n)\n * cost is acceptable for save-path frequencies (OOS-2).\n */\n _guidForAsset(asset: Asset): string | undefined {\n for (const [key, envelope] of this.assetCatalog) {\n if (envelope.payload === asset) {\n return key;\n }\n }\n // feat-20260703 M1 (D-1): fallback to the origin reverse-index. Covers two\n // MISS cases the catalog identity scan cannot: (1) _resolveSceneGuids deep\n // copies — the copy is never the catalogued original; (2) feat-20260713 M4\n // (D-6): a payload superseded by a catalog override, still live behind a\n // handle minted before the override.\n return this._originIndex.get(asset as object);\n }\n\n /** Public identity projection consumed by scene collection boundaries. */\n guidOf(asset: Asset): string | undefined {\n return this._guidForAsset(asset);\n }\n\n /** Return the production MaterialReady/Error result for one material GUID. */\n getMaterialReadiness(guid: string): MaterialReady | MaterialLoadError | undefined {\n return this.materialReadiness.get(guid.toLowerCase());\n }\n\n /** Record the canonical result produced by the production material loader. */\n recordMaterialReadiness(guid: string, readiness: MaterialReady | MaterialLoadError): void {\n this.materialReadiness.set(guid.toLowerCase(), readiness);\n if (readiness.status === 'Ready') {\n installMaterialReadyShaders(this.shaderRegistry, readiness);\n }\n }\n\n /**\n * Configure a catalog URL for `loadByGuid`.\n *\n * Call this once during engine initialization with the URL where\n * `pack-index.json` is served (emitted by `@forgeax/engine-vite-plugin-pack`\n * during `vite build`). In a Vite dev host, use `configureRuntimeBinding`\n * instead so the catalog remains bound to its scope and generation. The\n * index is also the canonical base URL for every\n * catalog entry: relative, root-relative, and absolute entry URLs are resolved\n * against it before the registry fetches a pack body. After configuration,\n * `loadByGuid` will fetch the catalog on its first invocation and cache it for\n * subsequent calls.\n *\n * @example\n * ```ts\n * engine.assets.configurePackIndex('/pack-index.json');\n * const payloadRes = await engine.assets.loadByGuid(guid); // payload, not a handle (D-17)\n * ```\n */\n configurePackIndex(url: string): void {\n this.packIndexUrl = url;\n this.packIndexCache = undefined; // reset cache if URL changes\n }\n\n /**\n * Atomically replace the browser-side asset realm. The binding owns the\n * catalog URL and generation; no cache from the previous game survives the\n * transition.\n */\n configureRuntimeBinding(binding: RuntimeAssetBinding): void {\n this.clearCatalogSource();\n this.runtimeBinding = binding;\n this.configurePackIndex(binding.catalogUrl);\n this.invalidateAll();\n this.registerBuiltins();\n }\n\n /**\n * feat-20260621 F17c: invalidate a single cached asset by GUID so the next\n * `loadByGuid` performs a genuinely fresh fetch. Clears, for this GUID only:\n * the catalogue entry, the in-flight dedup entry, the cached pack-file body\n * (keyed by the index entry's packageUrl), and the pack-index entry. Then\n * increments the per-GUID generation counter so any still in-flight Promise\n * for this GUID discards its result (returns `asset-invalidated`). The body +\n * index clears are targeted (other GUIDs' cached bodies and index entries\n * survive); deleting the index entry forces `resolveCatalogEntry` to re-fetch\n * the pack-index on the next load, re-resolving the packageUrl whose body\n * cache was just dropped. No-op when the GUID is not catalogued.\n *\n * Does NOT touch `packages` (a re-load's registerPackage overwrites them; D-8)\n * and does NOT trigger GPU resource release (OOS-1,\n * q1 boundary: the asset is CPU-only; GPU resources follow the ECS).\n *\n * @param guid - Case-insensitive GUID string or AssetGuid.\n */\n invalidate(guid: string): void {\n const guidKey = guid.toLowerCase();\n // D-6: the stored name lives on the envelope; preserve it across the delete\n // (the `packages` mapping survives, so resolveName must still see the name\n // until a re-load's registerPackage overwrites it) by parking it on\n // pendingNames -- the next catalog() of this GUID drains it back.\n const survivingEnvelope = this.assetCatalog.get(guidKey);\n const survivingName = survivingEnvelope?.name;\n if (survivingName !== undefined) this.pendingNames.set(guidKey, survivingName);\n if (survivingEnvelope !== undefined) this._originIndex.set(survivingEnvelope.payload, guidKey);\n this.assetCatalog.delete(guidKey);\n this.loadState.remove(guidKey);\n this.materialReadiness.delete(guidKey);\n // R-1 hard fix (research-decisions.md): delete inFlight entry so the\n // next loadByGuid does not hit the old Promise whose generation no\n // longer matches (AC-04 requires a fresh fetch, not asset-invalidated).\n this.inFlight.delete(guidKey);\n // Round-2 M-A: widen the clear so a COMPLETED reload re-fetches fresh\n // bytes instead of serving the stale cached body. Ordering is load-bearing:\n // read packageUrl from the index entry FIRST, then delete the body, then\n // delete the index entry. Targeted delete (not wholesale undefined) keeps\n // other GUIDs' cached bodies/index entries intact (per-GUID precision).\n const entry = this.packIndexCache?.get(guidKey);\n if (entry !== undefined) this.packFileCache.delete(entry.packageUrl);\n this.packIndexCache?.delete(guidKey);\n this.generations.set(guidKey, (this.generations.get(guidKey) ?? 0) + 1);\n this.catalogEpoch++;\n }\n\n /**\n * Adopt freshly loaded Mesh material slots into an object that is already\n * pinned by live World shared refs. Geometry and GPU-backed fields deliberately\n * remain untouched: this primitive is only for a default-material source\n * override, never a general Mesh reimport. This is the atomic cutover: Catalog,\n * Ready load state, and payload-to-GUID provenance must all name the same\n * object after the call. Call only after invalidate(guid) + loadByGuid(guid)\n * has completed successfully.\n */\n adoptReloadedMeshMaterialSlots(guid: string, livePayload: Asset): Result<Asset, AssetError> {\n const key = guid.toLowerCase();\n const envelope = this.assetCatalog.get(key);\n const freshPayload = this.loadState.getReady<Asset>(key);\n if (envelope === undefined || freshPayload === undefined || envelope.payload !== freshPayload) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${key} to have one freshly loaded Ready payload`,\n hint: 'complete invalidate + loadByGuid before adopting a live Mesh identity',\n }),\n );\n }\n if (livePayload.kind !== 'mesh' || freshPayload.kind !== 'mesh') {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: `GUID ${key} live and fresh payloads to both be MeshAsset`,\n hint: 'use Mesh identity adoption only for a recooked MeshAsset',\n }),\n );\n }\n if (this._guidForAsset(livePayload) !== key) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `live Mesh payload to retain GUID provenance for ${key}`,\n hint: 'capture the catalogued live payload before invalidating and reloading the same GUID',\n }),\n );\n }\n if (livePayload === freshPayload) return ok(livePayload);\n\n (livePayload as unknown as { materialSlots: TypesMeshAsset['materialSlots'] }).materialSlots =\n freshPayload.materialSlots;\n this._originIndex.set(freshPayload as object, key);\n this.assetCatalog.set(key, { ...envelope, payload: livePayload });\n this.loadState.registerReady(key, livePayload);\n this.catalogEpoch++;\n return ok(livePayload);\n }\n\n /**\n * feat-20260621 F17c: invalidate ALL cached assets so the next `loadByGuid`\n * re-fetches both the pack-index and the asset body. Clears assetCatalog,\n * inFlight, and packFileCache (wholesale), and resets packIndexCache to\n * `undefined` (NOT `.clear()` -- an empty Map would short-circuit\n * `resolveCatalogEntry`'s `=== undefined` re-fetch guard and serve\n * asset-not-imported for every later load; undefined forces a fresh\n * fetchPackIndex). Then increments a single globalGeneration counter so every\n * in-flight Promise (regardless of GUID) discards its result. Returns the\n * number of assets that were catalogued before the call.\n *\n * Idempotent: second call on an already-empty catalogue returns clearedCount 0\n * (AC-06). Does NOT trigger GPU resource release (OOS-1).\n */\n invalidateAll(): { clearedCount: number } {\n const count = this.assetCatalog.size;\n this.assetCatalog.clear();\n this.loadState.clear();\n this.materialReadiness.clear();\n this.inFlight.clear();\n this.globalGeneration++;\n // Round-2 M-A: wholesale clear of the shared body cache, and reset the\n // index cache to UNDEFINED (R2-1) -- NOT .clear(). packFileCache uses\n // .clear() because fetchPackFile checks `.get(packageUrl)` per URL, so an\n // empty Map correctly misses and re-fetches. packIndexCache uses =undefined\n // because resolveCatalogEntry's re-fetch guard tests `=== undefined`; an\n // empty Map would short-circuit it and serve asset-not-imported for every\n // later load -- the exact F17b pollution this feat fixes. The asymmetry is\n // intentional; do not normalise the two operations.\n this.packFileCache.clear();\n this.packIndexCache = undefined;\n this.catalogEpoch++;\n return { clearedCount: count };\n }\n\n /**\n * Force a re-fetch of the configured pack-index NOW and repopulate the cache,\n * so a synchronous `listCatalog()` immediately reflects assets added on disk\n * since boot (a freshly imported GLB's sub-assets). `loadByGuid`'s lazy\n * re-fetch only fires on a per-GUID miss and `invalidateAll()` merely clears\n * the cache (leaving `listCatalog()` empty until the next load), so neither\n * makes a Content Browser or `loadByGuid`-driven \"Add to Scene\" see a new\n * asset without a page reload. This does.\n *\n * No-op (returns false) when no pack-index URL is configured (dev inline\n * catalogue path) or the fetch fails — callers keep the stale cache rather\n * than blanking it. Returns true when the cache was repopulated.\n */\n async refreshCatalog(): Promise<boolean> {\n if (this.packIndexUrl === undefined) return false;\n const result = await fetchPackIndex(this);\n if (!result.ok) return false;\n this.packIndexCache = result.value;\n registerPackagesFromIndex(this, this.packIndexCache);\n return true;\n }\n\n setCatalogSource(source: CatalogSource): void {\n this.clearCatalogSource();\n this.catalogSource = source;\n this.catalogReplica = new CatalogReplica(source);\n this.catalogSourceDispose = this.catalogReplica.subscribe((delta) => {\n for (const listener of [...this.catalogListeners]) {\n try {\n listener(delta);\n } catch {\n // One host listener cannot prevent the remaining listeners from seeing a fact.\n }\n }\n });\n void this.catalogReplica.start();\n }\n\n /** Stop the catalog transport and remove its replica without clearing payload caches. */\n clearCatalogSource(): void {\n this.catalogReplica?.dispose();\n this.catalogSourceDispose?.();\n this.catalogSourceDispose = undefined;\n this.catalogSource = undefined;\n this.catalogReplica = undefined;\n this.catalogEnumerating = undefined;\n }\n\n enumerateCatalog(): Promise<Result<readonly CatalogEntry[], AssetError>> {\n if (this.catalogEnumerating !== undefined) return this.catalogEnumerating;\n if (this.catalogSource === undefined || this.catalogReplica === undefined) {\n return Promise.resolve(catalogSourceUnconfigured());\n }\n const promise = this.catalogReplica\n .start()\n .then((result) => (result.ok ? ok(result.value.entries) : result));\n this.catalogEnumerating = promise;\n void promise.then(() => {\n this.catalogEnumerating = undefined;\n });\n return promise;\n }\n\n /** Read the immutable catalog projection folded by this registry. */\n catalogSnapshot(): CatalogReplicaSnapshot | undefined {\n return this.catalogReplica?.snapshot();\n }\n\n /** Explicitly recover the registry's single catalog replica from its configured source. */\n reconcileCatalog(): Promise<CatalogReconcileResult> {\n if (this.catalogSource === undefined || this.catalogReplica === undefined) {\n return Promise.resolve(catalogSourceUnconfigured());\n }\n return this.catalogReplica.reconcile();\n }\n\n subscribeCatalog(listener: CatalogListener): () => void {\n this.catalogListeners.add(listener);\n return () => {\n this.catalogListeners.delete(listener);\n };\n }\n\n /**\n * Materialise a `SceneAsset` into an existing `World` and return the\n * synthetic root `Entity` (feat-20260514 w31 sugar wrapper; AC-03 +\n * requirements §IN-3; M3: returns Entity not SceneInstanceId).\n *\n * Before spawning, handle-type component fields (e.g. `assetHandle`,\n * `material`, `skeleton`) containing GUID strings are resolved to fresh\n * user-tier `Handle` numbers via `world.allocSharedRef` (feat-20260614 M8\n * D-19 instantiate-time GUID->handle mint; supersedes the pre-D-17\n * `resolveGuid` map). GUIDs that fail to parse or are not catalogued return\n * `AssetError(code='asset-not-found')` with a hint containing the GUID,\n * node localId, and field name.\n *\n * Errors propagate verbatim through the closed\n * `AssetError | PackError | EcsError` union so AI users that already\n * narrow `loadByGuid<SceneAsset>` results reuse the same `switch\n * (err.code)` exhaustively (charter proposition 3 machine-readable\n * union; plan-strategy §3.3 closed-union transparency).\n *\n * @example\n * ```ts\n * const sceneRes = await engine.assets.loadByGuid<SceneAsset>(roomGuid); // payload (D-17)\n * if (!sceneRes.ok) return;\n * const handle = world.allocSharedRef('SceneAsset', sceneRes.value); // mint column handle\n * const r = engine.assets.instantiate(handle, world);\n * if (!r.ok) {\n * switch (r.error.code) {\n * case 'asset-not-found':\n * case 'pack-cyclic-reference':\n * // ... AssetErrorCode | PackErrorCode | EcsErrorCode exhaustive\n * }\n * }\n * ```\n */\n instantiate<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent?: EntityHandle,\n ): Result<EntityHandle, AssetError | PackError | EcsError> {\n return instantiateImpl(this, handle, world, parent) as Result<\n EntityHandle,\n AssetError | PackError | EcsError\n >;\n }\n\n instantiateWithPublicationFence<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent: EntityHandle | undefined,\n expectedPublication: ScenePublicationFence,\n ): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError>;\n instantiateWithPublicationFence<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n parent: EntityHandle | undefined,\n expectedPublication: ScenePublicationFence,\n ): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError> {\n return instantiateImpl(this, handle, world, parent, expectedPublication);\n }\n\n /**\n * Materialise a `SceneAsset` FLAT into an existing `World` — the \"open a scene\n * for authoring\" registry entry (#655): NO synthetic SceneInstance root, NO\n * forced `ChildOf` on top-level members. Returns the top-level entity handles.\n * Nested prefabs (`mounts[]`) still materialise as their own SceneInstance\n * anchors. Use {@link instantiate} (anchor) at runtime / Play and for nested\n * prefabs.\n */\n instantiateFlat<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n ): Result<EntityHandle[], AssetError | PackError | EcsError> {\n return instantiateFlatImpl(this, handle, world) as Result<\n EntityHandle[],\n AssetError | PackError | EcsError\n >;\n }\n\n instantiateFlatWithPublicationFence<T extends SceneAsset>(\n handle: Handle<TagOf<T>, 'shared'>,\n world: World,\n expectedPublication: ScenePublicationFence,\n ): Result<EntityHandle[], AssetError | PackError | EcsError | ScenePublicationFenceError> {\n return instantiateFlatImpl(this, handle, world, expectedPublication);\n }\n\n private sceneMeshGuidBySlot(\n scene: SceneAsset,\n visited: Set<string> = new Set(),\n ): Map<number, string> {\n const result = new Map<number, string>();\n for (const entity of scene.entities) {\n const components = entity.components as Record<string, Record<string, unknown>>;\n const meshGuid = components.MeshFilter?.assetHandle;\n if (typeof meshGuid === 'string') result.set(entity.localId as number, meshGuid);\n }\n for (const mount of scene.mounts ?? []) {\n const mountComponents = mount.components as\n | Record<string, Record<string, unknown>>\n | undefined;\n const mountMeshGuid = mountComponents?.MeshFilter?.assetHandle;\n if (typeof mountMeshGuid === 'string') result.set(mount.localId as number, mountMeshGuid);\n if (typeof mount.source !== 'string') continue;\n const childKey = mount.source.toLowerCase();\n if (visited.has(childKey)) continue;\n const child = this.assetCatalog.get(childKey)?.payload;\n if (child?.kind !== 'scene') continue;\n const childVisited = new Set(visited);\n childVisited.add(childKey);\n const childSlots = this.sceneMeshGuidBySlot(child, childVisited);\n const first = mount.memberFirst as unknown as number;\n for (const [childSlot, meshGuid] of childSlots) result.set(first + childSlot, meshGuid);\n for (const override of mount.overrides ?? []) {\n if (override.comp !== 'MeshFilter') continue;\n const nextMeshGuid =\n override.field === 'assetHandle'\n ? override.value\n : override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null &&\n !Array.isArray(override.value)\n ? (override.value as Record<string, unknown>).assetHandle\n : undefined;\n if (typeof nextMeshGuid === 'string') {\n result.set(override.localId as unknown as number, nextMeshGuid);\n }\n }\n }\n return result;\n }\n\n private migrateLegacySceneMaterialOverrides(\n scene: SceneAsset,\n sceneGuidKey?: string,\n ): Result<{ readonly scene: SceneAsset; readonly changed: boolean }, AssetError> {\n const nodes: SceneEntity[] = [];\n let changed = false;\n for (const node of scene.entities) {\n const components = node.components as Record<string, Record<string, unknown>>;\n const rawMeshGuid = components.MeshFilter?.assetHandle;\n const meshGuid = typeof rawMeshGuid === 'string' ? rawMeshGuid : undefined;\n const legacyOverrides = components.MeshRenderer?.materials;\n const mesh =\n meshGuid === undefined ? undefined : this.assetCatalog.get(meshGuid.toLowerCase())?.payload;\n if (\n mesh?.kind !== 'mesh' ||\n meshGuid === undefined ||\n !Array.isArray(legacyOverrides) ||\n legacyOverrides.length < mesh.submeshes.length ||\n mesh.submeshes.length <= mesh.materialSlots.length ||\n !legacyOverrides.every((value) => typeof value === 'string')\n ) {\n nodes.push(node);\n continue;\n }\n const migrated = migrateLegacyMeshMaterialOverrides(\n legacyOverrides as string[],\n mesh.submeshes,\n mesh.materialSlots.length,\n {\n meshGuid: meshGuid.toLowerCase(),\n sceneGuid: sceneGuidKey ?? '<unregistered-scene>',\n entityId: node.localId as number,\n },\n );\n if (!migrated.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected:\n 'legacy per-submesh material overrides to collapse unambiguously onto Mesh v3 slots',\n hint: migrated.error.hint,\n detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,\n }),\n );\n }\n changed = true;\n nodes.push({\n ...node,\n components: {\n ...components,\n MeshRenderer: { ...components.MeshRenderer, materials: migrated.overrides },\n },\n } as SceneEntity);\n }\n\n const mounts: SceneInstanceMount[] = [];\n for (const mount of scene.mounts ?? []) {\n const child =\n typeof mount.source === 'string'\n ? this.assetCatalog.get(mount.source.toLowerCase())?.payload\n : undefined;\n let nextMount = mount;\n let mountChanged = false;\n const mountComponents = mount.components as\n | Record<string, Record<string, unknown>>\n | undefined;\n const mountMeshGuid = mountComponents?.MeshFilter?.assetHandle;\n const mountMaterials = mountComponents?.MeshRenderer?.materials;\n const mountMesh =\n typeof mountMeshGuid === 'string'\n ? this.assetCatalog.get(mountMeshGuid.toLowerCase())?.payload\n : undefined;\n if (\n mountMesh?.kind === 'mesh' &&\n typeof mountMeshGuid === 'string' &&\n Array.isArray(mountMaterials) &&\n mountMaterials.length >= mountMesh.submeshes.length &&\n mountMesh.submeshes.length > mountMesh.materialSlots.length &&\n mountMaterials.every((value) => typeof value === 'string')\n ) {\n const migrated = migrateLegacyMeshMaterialOverrides(\n mountMaterials as string[],\n mountMesh.submeshes,\n mountMesh.materialSlots.length,\n {\n meshGuid: mountMeshGuid.toLowerCase(),\n sceneGuid: sceneGuidKey ?? '<unregistered-scene>',\n entityId: mount.localId as unknown as number,\n },\n );\n if (!migrated.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected:\n 'legacy mount-entity materials to collapse unambiguously onto Mesh v3 slots',\n hint: migrated.error.hint,\n detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,\n }),\n );\n }\n mountChanged = true;\n nextMount = {\n ...mount,\n components: {\n ...mountComponents,\n MeshRenderer: { ...mountComponents?.MeshRenderer, materials: migrated.overrides },\n },\n } as SceneInstanceMount;\n }\n if (child?.kind !== 'scene' || mount.overrides === undefined) {\n if (mountChanged) changed = true;\n mounts.push(nextMount);\n continue;\n }\n const meshByMember = this.sceneMeshGuidBySlot(child);\n const nextOverrides: MountOverride[] = [];\n for (const override of mount.overrides) {\n const childLocalId =\n (override.localId as unknown as number) - (mount.memberFirst as unknown as number);\n if (override.comp === 'MeshFilter') {\n const nextMeshGuid =\n override.field === 'assetHandle'\n ? override.value\n : override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null &&\n !Array.isArray(override.value)\n ? (override.value as Record<string, unknown>).assetHandle\n : undefined;\n if (typeof nextMeshGuid === 'string') meshByMember.set(childLocalId, nextMeshGuid);\n nextOverrides.push(override);\n continue;\n }\n const legacyMaterials =\n override.comp === 'MeshRenderer' && override.field === 'materials'\n ? override.value\n : override.comp === 'MeshRenderer' &&\n override.field === undefined &&\n typeof override.value === 'object' &&\n override.value !== null &&\n !Array.isArray(override.value)\n ? (override.value as Record<string, unknown>).materials\n : undefined;\n const meshGuid = meshByMember.get(childLocalId);\n const mesh =\n meshGuid === undefined\n ? undefined\n : this.assetCatalog.get(meshGuid.toLowerCase())?.payload;\n if (\n mesh?.kind !== 'mesh' ||\n meshGuid === undefined ||\n !Array.isArray(legacyMaterials) ||\n legacyMaterials.length < mesh.submeshes.length ||\n mesh.submeshes.length <= mesh.materialSlots.length ||\n !legacyMaterials.every((value) => typeof value === 'string')\n ) {\n nextOverrides.push(override);\n continue;\n }\n const migrated = migrateLegacyMeshMaterialOverrides(\n legacyMaterials as string[],\n mesh.submeshes,\n mesh.materialSlots.length,\n {\n meshGuid: meshGuid.toLowerCase(),\n sceneGuid: sceneGuidKey ?? '<unregistered-scene>',\n entityId: override.localId as unknown as number,\n },\n );\n if (!migrated.ok) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected:\n 'legacy mount material overrides to collapse unambiguously onto Mesh v3 slots',\n hint: migrated.error.hint,\n detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,\n }),\n );\n }\n mountChanged = true;\n nextOverrides.push(\n override.field === 'materials'\n ? { ...override, value: migrated.overrides }\n : {\n ...override,\n value: {\n ...(override.value as Record<string, unknown>),\n materials: migrated.overrides,\n },\n },\n );\n }\n if (mountChanged) {\n changed = true;\n mounts.push({ ...nextMount, overrides: nextOverrides });\n } else {\n mounts.push(nextMount);\n }\n }\n return ok({\n scene: changed\n ? {\n ...scene,\n entities: nodes,\n ...(scene.mounts === undefined ? {} : { mounts }),\n }\n : scene,\n changed,\n });\n }\n\n private preflightSceneMaterialGraph(\n scene: SceneAsset,\n sceneGuidKey?: string,\n visited: Set<string> = new Set(),\n ): Result<void, AssetError> {\n const key = sceneGuidKey?.toLowerCase();\n if (key !== undefined) {\n if (visited.has(key)) return ok(undefined);\n visited.add(key);\n }\n const local = this.migrateLegacySceneMaterialOverrides(scene, sceneGuidKey);\n if (!local.ok) return local;\n for (const mount of scene.mounts ?? []) {\n if (typeof mount.source !== 'string') continue;\n const childKey = mount.source.toLowerCase();\n const child = this.assetCatalog.get(childKey)?.payload;\n if (child?.kind !== 'scene') continue;\n const nested = this.preflightSceneMaterialGraph(child, childKey, visited);\n if (!nested.ok) return nested;\n }\n return ok(undefined);\n }\n\n /**\n * @internal\n * Transform a SceneAsset whose handle-type component fields hold GUID\n * strings (post-parseScenePayload intermediate state) into a copy whose\n * handle fields hold resolved Handle numbers.\n *\n * Schema-driven field detection (plan-strategy D-4): for each component\n * field whose Component.schema fieldType starts with `shared\\<`, the\n * value is treated as a GUID string and resolved via `AssetGuid.parse` +\n * catalogue lookup + `world.internSharedRef` (feat-20260614 M8 D-15/D-17;\n * the registry mints nothing). Unknown component names are silently passed\n * through (the ecs layer's additionalProperties check will catch unknowns at\n * spawn if appropriate).\n *\n * Stop-on-first-error (AC-08): the first unresolvable GUID aborts\n * iteration and returns `AssetError(code='asset-not-found')` with a hint\n * containing the GUID string, node localId, and field name for AI-user\n * debuggability (P3).\n */\n _resolveSceneGuids(\n scene: SceneAsset,\n world: World,\n sceneGuidKey?: string,\n _visitedMountGuids?: Set<string>,\n _guidToHandle?: Map<string, number>,\n _resolvedSceneHandles?: Map<string, number>,\n _materialGraphPreflighted = false,\n ): Result<SceneAsset, AssetError> {\n // feat-20260622 M3 / w8: reverse-decode from envelope.refs edges when\n // sceneGuidKey is provided and the catalog holds an envelope for this\n // scene. Each edge with sceneEntityId+sourceField.componentName carries\n // the (entityLocalId, componentName, fieldName, arrayIndex) triple —\n // no need to walk entities with a process-global component reflection table.\n // D-15/D-17 dedup contract: the same catalogued payload referenced from\n // multiple nodes must resolve to ONE user-tier handle. The local GUID map\n // avoids repeat lookups inside this traversal; World interning preserves\n // payload identity across separate scene-resolution calls.\n if (!_materialGraphPreflighted) {\n const graph = this.preflightSceneMaterialGraph(scene, sceneGuidKey);\n if (!graph.ok) return graph;\n }\n const localMigration = this.migrateLegacySceneMaterialOverrides(scene, sceneGuidKey);\n if (!localMigration.ok) return localMigration;\n const sceneForResolution = localMigration.value.scene;\n const preflightChanged = localMigration.value.changed;\n\n const resolvedMap = new Map<string, number>();\n const guidToHandle = _guidToHandle ?? new Map<string, number>();\n const resolvedSceneHandles = _resolvedSceneHandles ?? new Map<string, number>();\n const sceneEnvelope =\n !preflightChanged && sceneGuidKey !== undefined\n ? this.assetCatalog.get(sceneGuidKey)\n : undefined;\n // Did the structured-edge branch actually resolve anything? Prod-loaded\n // packs catalogue refs[] as GUID-only edges (sourceField / sceneEntityId\n // stripped at the w7 D-10 serialization boundary), so the rich-edge loop\n // below `continue`-skips every ref and resolves nothing. When that happens\n // we MUST fall through to the entity-walk fallback — otherwise the handle\n // fields keep their GUID strings and `spawn` writes the sentinel 0 while\n // `retainSharedScalarHandle(GUID)` routes `shared-ref-released` (the on-disk\n // game-scene instantiate crash: enemy MeshFilter.assetHandle).\n let resolvedFromEdges = false;\n if (\n sceneEnvelope !== undefined &&\n sceneEnvelope.refs !== undefined &&\n sceneEnvelope.refs.length > 0\n ) {\n for (const ref of sceneEnvelope.refs) {\n const { sceneEntityId, sourceField } = ref;\n if (sceneEntityId === undefined || sourceField === undefined) continue;\n const { componentName, fieldName, arrayIndex } = sourceField;\n if (componentName === undefined || fieldName === undefined) continue;\n\n const fieldPath = `${componentName}.${fieldName}${arrayIndex !== undefined ? `[${arrayIndex}]` : ''}`;\n\n const envelope = this.assetCatalog.get(ref.guid.toLowerCase());\n if (envelope === undefined) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `GUID ${ref.guid} catalogued in AssetRegistry`,\n hint:\n `GUID ${ref.guid} not catalogued; ` +\n `call loadByGuid('${ref.guid}') before instantiate; ` +\n `at node localId=${sceneEntityId}, field=${fieldPath}`,\n }),\n );\n }\n const payload = envelope.payload;\n const guidKey = ref.guid.toLowerCase();\n let resolvedSlot = guidToHandle.get(guidKey);\n if (resolvedSlot === undefined) {\n resolvedSlot = unwrapHandle(world.internSharedRef(payload.kind, payload));\n guidToHandle.set(guidKey, resolvedSlot);\n }\n\n const key =\n `${sceneEntityId}|${componentName}|${fieldName}` +\n (arrayIndex !== undefined ? `|${arrayIndex}` : '|');\n resolvedMap.set(key, resolvedSlot);\n resolvedFromEdges = true;\n }\n }\n if (!resolvedFromEdges) {\n // Fallback: positive extraction via extractSceneEntityHandleGuids when\n // the structured edges resolved nothing — either the scene envelope is\n // absent (unit tests that build a SceneAsset without cataloguing it) OR\n // the catalogued refs[] are GUID-only with no per-entity metadata (the\n // prod on-disk pack path). The entity-component walk recovers the\n // (localId, componentName, fieldName, arrayIndex) triple the bare edge\n // dropped, so GUID strings resolve to live handles before spawn.\n const entries = extractSceneEntityHandleGuids(\n world.components.entries(),\n sceneForResolution.entities as unknown as ReadonlyArray<{\n readonly localId: number;\n readonly components: Record<string, Record<string, unknown>>;\n }>,\n );\n\n for (const entry of entries) {\n const fieldPath =\n `${entry.componentName}.${entry.fieldName}` +\n (entry.arrayIndex !== undefined ? `[${entry.arrayIndex}]` : '');\n const resolvedSlot = resolveHandleGuid(\n this,\n world,\n entry.guidString,\n guidToHandle,\n fieldPath,\n `node localId=${entry.entityLocalId}`,\n );\n if (!resolvedSlot.ok) return resolvedSlot;\n\n const key =\n `${entry.entityLocalId}|${entry.componentName}|${entry.fieldName}` +\n (entry.arrayIndex !== undefined ? `|${entry.arrayIndex}` : '|');\n resolvedMap.set(key, resolvedSlot.value);\n }\n }\n\n // Build the resolved copy. Handle-type fields (detected above) are\n // reconstructed from the resolvedMap; all other fields pass through as-is.\n const resolvedNodes: SceneEntity[] = [];\n for (const node of sceneForResolution.entities) {\n const rawComponents = node.components as Record<string, Record<string, unknown>>;\n const resolvedComponents: Record<string, Record<string, unknown>> = {};\n\n for (const compName of Object.keys(rawComponents)) {\n const rawFields = rawComponents[compName];\n if (!rawFields) {\n resolvedComponents[compName] = {};\n continue;\n }\n const resolvedFields: Record<string, unknown> = {};\n for (const fieldName of Object.keys(rawFields)) {\n const value = rawFields[fieldName];\n const plainKey = `${node.localId}|${compName}|${fieldName}|`;\n const plainResolved = resolvedMap.get(plainKey);\n if (plainResolved !== undefined) {\n resolvedFields[fieldName] = plainResolved;\n } else if (Array.isArray(value)) {\n const resolvedArr: number[] = [];\n let hasAnyResolved = false;\n for (let i = 0; i < value.length; i++) {\n const arrKey = `${node.localId}|${compName}|${fieldName}|${i}`;\n const arrResolved = resolvedMap.get(arrKey);\n if (arrResolved !== undefined) {\n resolvedArr.push(arrResolved);\n hasAnyResolved = true;\n } else if (typeof value[i] === 'number') {\n resolvedArr.push(value[i]);\n }\n }\n resolvedFields[fieldName] = hasAnyResolved ? resolvedArr : value;\n } else {\n resolvedFields[fieldName] = value;\n }\n }\n resolvedComponents[compName] = resolvedFields;\n }\n resolvedNodes.push({\n localId: node.localId,\n components: resolvedComponents,\n });\n }\n\n // ── m3-i2 / m3-i3: Resolve mounts recursively (breakpoint B fix) ──\n // For each mount.source (GUID string), look up the child scene in\n // assetCatalog, recursively resolve its GUIDs, allocSharedRef the\n // resolved child copy, register it in originIndex (D-7), and produce\n // a resolved mount with source as the live handle number.\n // Cycle detection via visited GUID set (R-9): re-entry =>\n // pack-cyclic-reference / mount-asset, cast through the return type\n // as world.ts does for its PackError exits.\n const mountVisited = _visitedMountGuids ?? new Set<string>();\n if (sceneGuidKey !== undefined) mountVisited.add(sceneGuidKey.toLowerCase());\n if (sceneForResolution.mounts !== undefined && sceneForResolution.mounts.length > 0) {\n // feat-20260713 M3 / w13: share the entity-field dedup map so an override\n // value GUID that also appears as an entity field mints one handle (D-15/D-17).\n const resolvedMounts = resolveMountsRec(\n this,\n sceneForResolution.mounts,\n world,\n mountVisited,\n guidToHandle,\n resolvedSceneHandles,\n );\n if (sceneGuidKey !== undefined) mountVisited.delete(sceneGuidKey.toLowerCase());\n if (!resolvedMounts.ok) {\n // Cycle or child-resolution error: cast through as AssetError\n // (same pattern as world.ts PackError-as-EcsError casts).\n return resolvedMounts as unknown as Result<SceneAsset, AssetError>;\n }\n return ok({\n kind: 'scene',\n entities: resolvedNodes,\n mounts: resolvedMounts.value,\n } as SceneAsset);\n }\n if (sceneGuidKey !== undefined) mountVisited.delete(sceneGuidKey.toLowerCase());\n return ok({ kind: 'scene', entities: resolvedNodes });\n }\n\n /**\n * Register an asset and return a fresh\n * `Result<Handle<TagOf<T>, 'shared'>, AssetError>`. The brand `target`\n * tag is derived from the Asset's `kind` discriminator via `AssetTagMap`\n * (charter F1 single-entry indexability). The runtime representation is\n * an auto-incrementing u32 starting at 1024 (builtins reserve 1-2).\n *\n * feat-20260526 M4: `shadingModel` field is retired in favour of\n * pass-based MaterialAsset. This generic surface covers the full\n * `Asset` closed union (mesh / texture / sampler / scene / equirect\n * / material).\n */\n /**\n * feat-20260614 M8 (D-15 / D-17): catalogue a payload under its GUID.\n * Replaces the old `register` / `registerWithGuid` mint pair -- the registry\n * stores the PAYLOAD and never produces a handle (it owns no World).\n * Column minting is the caller's job via `world.allocSharedRef`.\n *\n * Validates mesh stride + material passes / sprite slices at catalogue entry\n * (same fail-fast surface as the old register path). Returns\n * `Result.err(AssetError)` on validation failure; `Result.ok(payload)` with\n * the stored payload (mesh payloads gain an `aabb`) on success.\n */\n catalog<T = Asset>(\n guid: AssetGuid | string,\n asset: T,\n refs?: readonly AssetRef[],\n ): Result<T, AssetError> {\n // D-5: narrow T to Asset for kind-discriminate branches. The runtime\n // catalog only accepts Asset-kind payloads (host custom kinds enter\n // through loadByGuid + registerParsedAsset, not catalog directly).\n const a: Asset = asset as unknown as Asset;\n const meshValidation = validateMeshPayload(a);\n if (meshValidation !== null) return err(meshValidation);\n\n // feat-20260608 M0 baseline rebuild: tileset payload fail-fast gate at\n // register entry — region rectangle bounds-check uses the implicit atlas\n // extent (columns * tileWidth x rows * tileHeight) when the caller did\n // not supply an explicit one (charter P3 explicit failure).\n if (a.kind === 'tileset') {\n const tilesetAsset = a as TilesetAsset;\n const tilesetValidation = validateTilesetPayload(\n tilesetAsset,\n inferAtlasExtent(tilesetAsset),\n );\n if (tilesetValidation !== null) return err(tilesetValidation);\n }\n\n // feat-20260527 M2 / w6: material validation with union paramSchema\n // semantics across all passes (plan-strategy D-2, D-5).\n if (a.kind === 'material') {\n const matValidation = validateMaterialPasses(this, a as MaterialAsset);\n if (matValidation !== null) return err(matValidation);\n const sliceValidation = validateSpriteSlices(this, a as MaterialAsset);\n if (sliceValidation !== null) return err(sliceValidation);\n detectTileNeedsRepeatSampler(this, a as MaterialAsset);\n }\n\n let stored: Asset = a;\n if (a.kind === 'mesh') {\n stored = withMeshAabb(a as TypesMeshAsset);\n }\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const kind = a.kind;\n // Drain any name recorded by an earlier _registerPackage call whose body had\n // not yet been catalogued (prod disk path; D-6). Preserve a name already on\n // a prior envelope for this key (re-catalog of the same GUID).\n const pendingName = this.pendingNames.get(key);\n const priorEnvelope = this.assetCatalog.get(key);\n const priorName = priorEnvelope?.name;\n const name = pendingName ?? priorName;\n this.pendingNames.delete(key);\n // feat-20260713 M4 / w15 (D-6, root cause a): when this GUID is being\n // re-catalogued with a DIFFERENT payload object, the prior object may still\n // be live behind a handle minted before the override (asset-registry.ts:513\n // identity scan would then MISS it). Record the superseded object -> GUID in\n // the origin reverse-index so `_guidForAsset` keeps resolving it — save/\n // collect of an owned entity holding that handle no longer fails with a\n // GUID-unresolved error (the 2026-07-06 crash). Structurally-modified copies\n // (a fresh object never catalogued) stay uncatalogued and correctly surface a\n // structured error at collect (requirements edge case \"modified payload judged\n // as a new asset, not silently zeroed\").\n if (priorEnvelope !== undefined && priorEnvelope.payload !== stored) {\n this._originIndex.set(priorEnvelope.payload, key);\n }\n this.assetCatalog.set(key, {\n guid: key,\n kind,\n ...(name !== undefined ? { name } : {}),\n payload: stored,\n refs: refs ?? [],\n });\n this.catalogEpoch++;\n this.loadState.registerReady(key, stored);\n // D-1: catalog() inline path defaults every GUID to the no-package state\n // (null). loadByGuid + builtin override via their own registerPackage calls\n // before / after this so the package mapping is populated for all assets\n // through the single primitive (#1 SSOT). Do not clobber a package mapping\n // a prior registerPackage already established for this GUID.\n if (!this.packages.has(key)) this.packages.set(key, null);\n return ok(stored as T);\n }\n\n /**\n * @internal feat-20260618-asset-and-pack-name-fields M3 (D-1): the single\n * package-mapping write primitive. All three registration entry points funnel\n * here so the XOR name invariant is implemented once (#1 SSOT):\n * - catalog() inline path -> registerPackage(null, [guid]) (no package)\n * - loadByGuid disk path -> registerPackage(packageUrl, [g1,g2,...], names)\n * - constructor builtin -> registerPackage(null, [...guids]) (D-5 null)\n *\n * `path === null` registers the GUIDs with no package (resolveName reads their\n * storedName or returns ''). A non-null `path` finds-or-creates the shared\n * MutablePackage for that path and adds the GUIDs to it; per-GUID entry names\n * (D-2: name flows entry -> Package, never the payload) are taken from\n * `names`. The 1->N promotion branch (D-3) is added by w11. Never throws --\n * it only writes maps; resolution + validation happen in resolveName / rename.\n */\n _registerPackage(\n path: string | null,\n guids: readonly string[],\n names?: Map<string, string>,\n ): void {\n if (path === null) {\n for (const g of guids) {\n const key = g.toLowerCase();\n this.packages.set(key, null);\n const n = names?.get(g) ?? names?.get(key);\n if (n !== undefined) this.setStoredName(key, n);\n }\n return;\n }\n\n const pkg = this.packageByPath.get(path) ?? { path, assetGuids: new Set<string>() };\n this.packageByPath.set(path, pkg);\n\n // D-3: 1->N promotion. When this path already holds exactly one asset and a\n // new member is arriving, freeze the original asset's derived basename as its\n // stored name so it joins the multi-asset branch with a stable name. The\n // freeze is idempotent: an original that already carries a stored name (the\n // abnormal single-asset-with-name state, D-4) is left untouched and the\n // soft-violation counter records it (charter P3 machine-readable signal).\n const addsNewMember = guids.some((g) => !pkg.assetGuids.has(g.toLowerCase()));\n if (pkg.assetGuids.size === 1 && addsNewMember) {\n const [originalKey] = pkg.assetGuids;\n if (originalKey !== undefined) {\n if (this.hasStoredName(originalKey)) {\n this.metrics?.increment('package.xor-invariant-violated');\n } else {\n this.setStoredName(originalKey, deriveAssetName(pkg.path, 1));\n }\n }\n }\n\n for (const g of guids) {\n const key = g.toLowerCase();\n pkg.assetGuids.add(key);\n this.packages.set(key, pkg);\n const n = names?.get(g) ?? names?.get(key);\n if (n !== undefined) this.setStoredName(key, n);\n }\n }\n\n /**\n * Read the per-GUID stored display name (D-6 home: the envelope's `name`\n * field, with `pendingNames` covering the prod-disk ordering where the name is\n * known before the body is catalogued). Single read point for resolveName /\n * the 1->N promotion XOR check.\n */\n private storedNameFor(key: string): string | undefined {\n return this.assetCatalog.get(key)?.name ?? this.pendingNames.get(key);\n }\n\n private hasStoredName(key: string): boolean {\n return this.storedNameFor(key) !== undefined;\n }\n\n /**\n * Write the per-GUID stored display name. When the envelope exists, replace it\n * with one carrying the new `name` (the envelope is immutable; D-6 keeps the\n * payload free of the name). Before the envelope is catalogued (prod disk\n * path), stash on `pendingNames` so catalog() can drain it into the new\n * envelope. `name === undefined` clears the name in both homes.\n */\n private setStoredName(key: string, name: string | undefined): void {\n const envelope = this.assetCatalog.get(key);\n if (envelope !== undefined) {\n const { name: _drop, ...rest } = envelope;\n this.assetCatalog.set(key, name === undefined ? rest : { ...rest, name });\n this.pendingNames.delete(key);\n return;\n }\n if (name === undefined) this.pendingNames.delete(key);\n else this.pendingNames.set(key, name);\n }\n\n /**\n * Return the `Package` this GUID belongs to, or `null` when the asset has no\n * package (catalog() inline + builtin, D-5), or `undefined` when the GUID was\n * never registered. The returned `Package` is a readonly snapshot whose\n * `assetCount` is derived from the live member set (#2 Derive).\n */\n packageOf(guid: AssetGuid | string): Package | null | undefined {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const pkg = this.packages.get(key);\n if (pkg === undefined) return undefined;\n if (pkg === null) return null;\n return { path: pkg.path, assetGuids: pkg.assetGuids, assetCount: pkg.assetGuids.size };\n }\n\n /**\n * Resolve an asset's human-readable display name -- the single source of truth\n * for the two-segment identity's `name` segment (D-6). Every name consumer\n * (inspect / catalog builder / CLI) reads this or the same `deriveAssetName`\n * pure function it delegates to (AC-04); no consumer re-implements the XOR\n * rule. Returns a deterministic fallback rather than throwing on a missing\n * name (AC-15): `basename(path)` for a multi-asset entry that lacks a stored\n * name, or `''` for a no-package asset with no self name (the detectable\n * \"genuinely no name\" signal, charter P3). An unregistered GUID is treated as\n * the no-package branch.\n */\n resolveName(guid: AssetGuid | string): string {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const pkg = this.packages.get(key);\n const storedName = this.storedNameFor(key);\n const path = pkg == null ? null : pkg.path;\n const assetCount = pkg == null ? 0 : pkg.assetGuids.size;\n return deriveAssetName(path, assetCount, storedName);\n }\n\n /**\n * Rename an asset's display name in memory (D-4). Three classes by package\n * shape:\n * - no-package asset -> set the stored self name\n * - multi-asset package -> set the entry stored name\n * - single-asset package -> rewrite the package path's leaf segment so the\n * derived basename becomes `newName` (the package\n * stays single-asset; the leaf IS the name)\n *\n * In-memory only (OOS-1: no disk write-back). Returns structured failures via\n * the closed `AssetErrorCode` union with no new members (D-4): a name that\n * collides with another member of the same package -> `asset-invalid-value`;\n * an unregistered GUID -> `asset-not-found`. AI users consume `.code` through\n * a `switch`, not by parsing `.message` (charter P3).\n */\n rename(guid: AssetGuid | string, newName: string): Result<void, AssetError> {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n if (!this.packages.has(key)) {\n return err(\n new AssetError({\n code: 'asset-not-found',\n expected: `a registered asset for GUID ${key}`,\n hint: ASSET_ERROR_HINTS['asset-not-found'],\n }),\n );\n }\n\n const pkg = this.packages.get(key) ?? null;\n\n const collision = pkg !== null ? this.nameCollisionIn(pkg, key, newName) : null;\n if (collision !== null) return err(collision);\n\n if (pkg !== null && pkg.assetGuids.size === 1) {\n // Single-asset package: the leaf segment IS the derived name; rewrite it so\n // basename(path) === newName. Keep the directory prefix intact.\n const slash = pkg.path.lastIndexOf('/');\n const oldPath = pkg.path;\n pkg.path = slash >= 0 ? `${pkg.path.slice(0, slash + 1)}${newName}` : newName;\n this.packageByPath.delete(oldPath);\n this.packageByPath.set(pkg.path, pkg);\n this.setStoredName(key, undefined);\n return ok(undefined);\n }\n\n this.setStoredName(key, newName);\n return ok(undefined);\n }\n\n /**\n * Return an `asset-invalid-value` AssetError if another member of `pkg`\n * already resolves to `newName`, else null. Extracted from `rename` to keep\n * the collision-detection control flow flat (D-4 reuses the closed error code;\n * the detail narrows via the `{ field, value, reason }` union variant).\n */\n private nameCollisionIn(\n pkg: MutablePackage,\n selfKey: string,\n newName: string,\n ): AssetError | null {\n for (const memberKey of pkg.assetGuids) {\n if (memberKey !== selfKey && this.resolveName(memberKey) === newName) {\n return new AssetError({\n code: 'asset-invalid-value',\n expected: `a name unique within package \"${pkg.path}\"`,\n hint: `another asset in \"${pkg.path}\" is already named \"${newName}\"; choose a distinct name`,\n detail: {\n field: 'name',\n value: newName,\n reason: `duplicate name within package ${pkg.path}`,\n },\n });\n }\n }\n return null;\n }\n\n /**\n * Parse a dash-form GUID string into an `AssetGuid`. Thin convenience over\n * `AssetGuid.parse` for the `loadByGuid` / `catalog` call sites; throws\n * `AssetError` on a malformed GUID (caller-error, mirrors `parseInt`-style\n * eager validation -- the GUID literal is author-supplied, not user data).\n */\n parseGuid(guidStr: string): AssetGuid {\n const parsed = AssetGuid.parse(guidStr);\n if (!parsed.ok) {\n throw new AssetError({\n code: 'asset-parse-failed',\n expected: `valid dash-form GUID, got \"${guidStr}\"`,\n hint: ASSET_ERROR_HINTS['asset-parse-failed'],\n });\n }\n return parsed.value;\n }\n\n /**\n * Look up a catalogued payload by GUID, or `undefined` on miss. Used by the\n * ECS/render side (e.g. `walkMaterialParents` in `resolve-asset-handle.ts`)\n * to resolve a payload's embedded sub-asset GUIDs (D-19) without minting.\n */\n lookup<T = Asset>(guid: AssetGuid | string): T | undefined {\n const key =\n typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();\n const ready = this.loadState.getReady<T>(key);\n if (ready !== undefined) return ready;\n if (this.packIndexUrl === undefined)\n return this.assetCatalog.get(key)?.payload as T | undefined;\n return undefined;\n }\n\n /**\n * feat-20260613-material-paramschema-driven-binding M4 / w23 (D-5 graceful):\n * Return the texture-field name set for the given material-shader id,\n * derived from the registered shader's paramSchema via `derive(paramSchema)\n * .textureFieldNames`. Returns `undefined` when the shader is not yet\n * registered (cross-worktree shader-late-register, plan R-4).\n *\n * Used by `extractFrame` to know which values fields the shader\n * declares as texture handles; the extract layer validates handle-vs-\n * scalar typing and drops misclassified slots so the record stage's\n * MISSING_TEXTURE_HANDLE fallback can take over (white default texture)\n * rather than letting a stray handle reach `device.createBindGroup`.\n *\n * feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): delegates to the\n * extracted `./registry/validate-material` free function (signature stable).\n */\n materialShaderTextureFieldNames(shaderId: string): ReadonlySet<string> | undefined {\n return materialShaderTextureFieldNamesImpl(this, shaderId);\n }\n\n /**\n * Load an asset and all its transitively referenced sub-assets by GUID.\n * The result is a durable Asset payload. Consumer owners may narrow the\n * success type, then call their own World/Host projection; this registry does\n * not create a generic GUID-to-handle materializer.\n * Delegates to the load-by-guid collaboration module (w7 / D-4); see\n * registry/load-by-guid.ts for the full DDC / pack-fetch pipeline.\n */\n async loadByGuid<T = Asset>(\n guid: AssetGuid,\n parentContext?: {\n sceneEntityId?: number;\n componentField?: string;\n },\n ): Promise<Result<T, AssetError | ImageError | RhiError>> {\n return loadByGuidImpl<T>(this, guid, parentContext);\n }\n\n /**\n * Dispatch a pack payload through the injected LoaderRegistry. Delegates to\n * the load-by-guid collaboration module (w7 / D-4). Kept as a class method so\n * existing structural-cast test access keeps resolving.\n */\n parseAssetPayload(\n kind: string,\n payload: Record<string, unknown>,\n refs?: string[],\n ):\n | Asset\n | Record<string, unknown>\n | undefined\n | { readonly ok: false; readonly error: ParseErrorDetail } {\n return parseAssetPayloadImpl(this, kind, payload, refs);\n }\n\n /**\n * Parse a pack asset entry and return the payload + refs. Delegates to the\n * load-by-guid collaboration module (w7 / D-4). Kept as a class method so\n * existing structural-cast test access keeps resolving.\n */\n parseAndReturnAsset(assetEntry: {\n kind: string;\n payload: Record<string, unknown>;\n refs?: string[];\n }): Result<{ asset: Asset; refs: readonly string[] }, AssetError> {\n return parseAndReturnAssetImpl(this, assetEntry);\n }\n /** Return the legacy catalog snapshot when no GUID is supplied. */\n inspect(): InspectSnapshot;\n /** Return joined source/cook/package/runtime evidence for one GUID. */\n inspect(guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>>;\n inspect(guid?: string): InspectSnapshot | Promise<Result<AssetEvidence, AssetEvidenceError>> {\n if (guid !== undefined) return this.assetEvidenceAdapter.inspect(guid);\n const assets: InspectEntry[] = [];\n for (const [guid, envelope] of this.assetCatalog) {\n assets.push({\n guid,\n kind: envelope.payload.kind,\n name: this.resolveName(guid),\n });\n }\n return { assets };\n }\n\n /** Verify the same GUID evidence chain through the injected SDK capability. */\n verifyByGuid(guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>> {\n return this.assetEvidenceAdapter.verifyByGuid(guid);\n }\n\n /**\n * Return a readonly snapshot of all catalogued assets (inlined + pack-index)\n * for enumeration by asset panels (AC-03 single source of truth).\n *\n * Merges entries from the private `packIndexCache` (prod path, carries\n * `packageUrl`) and `assetCatalog` (inlined / dev path, no URL). Each\n * GUID appears exactly once. Returns a fresh array on every call — the\n * internal Maps are never exposed (charter P4 consistent abstraction).\n *\n * plan-strategy section 2 D1; requirements AC-03; research Finding 5.\n *\n * @example\n * ```ts\n * for (const e of registry.listCatalog()) {\n * console.log(e.guid, e.kind, e.name, e.packageUrl);\n * }\n * ```\n */\n listCatalog(): readonly {\n guid: string;\n kind: string;\n name?: string;\n packageUrl: string;\n packageId?: CatalogEntry['packageId'];\n provenance?: CatalogEntry['provenance'];\n revision?: CatalogEntry['revision'];\n sourceKey?: CatalogEntry['sourceKey'];\n sourceIndex?: CatalogEntry['sourceIndex'];\n sourceOverrides?: CatalogEntry['sourceOverrides'];\n sourceOverrideDescriptors?: CatalogEntry['sourceOverrideDescriptors'];\n authoring?: CatalogEntry['authoring'];\n relations?: CatalogEntry['relations'];\n diagnostics?: CatalogEntry['diagnostics'];\n refs?: readonly string[];\n subject?: import('@forgeax/engine-types').CatalogSubject;\n execution?: import('@forgeax/engine-types').CookExecution;\n lifecycle?: import('@forgeax/engine-types').CatalogLifecycle;\n projection?: import('@forgeax/engine-types').CatalogProjection;\n /**\n * On-disk source-file path for external imported assets (FBX / GLB / HDR /\n * audio / font), relative to the game root. Editors locate the\n * `.meta.json` sidecar via `sourcePath + '.meta.json'` for CRUD; unlike\n * `packageUrl` (the runtime load artefact) it is stable across DDC cook\n * state. `undefined` for inline / dev-path assets (no sidecar, no CRUD).\n */\n sourcePath?: string;\n }[] {\n const seen = new Set<string>();\n const result: {\n guid: string;\n kind: string;\n name?: string;\n packageUrl: string;\n packageId?: CatalogEntry['packageId'];\n provenance?: CatalogEntry['provenance'];\n revision?: CatalogEntry['revision'];\n sourceKey?: CatalogEntry['sourceKey'];\n sourceIndex?: CatalogEntry['sourceIndex'];\n sourceOverrides?: CatalogEntry['sourceOverrides'];\n sourceOverrideDescriptors?: CatalogEntry['sourceOverrideDescriptors'];\n authoring?: CatalogEntry['authoring'];\n relations?: CatalogEntry['relations'];\n diagnostics?: CatalogEntry['diagnostics'];\n refs?: readonly string[];\n subject?: import('@forgeax/engine-types').CatalogSubject;\n execution?: import('@forgeax/engine-types').CookExecution;\n lifecycle?: import('@forgeax/engine-types').CatalogLifecycle;\n projection?: import('@forgeax/engine-types').CatalogProjection;\n sourcePath?: string;\n cookReceiptUrl?: string;\n }[] = [];\n\n // Prod entries: packIndexCache carries packageUrl + optional name + refs.\n if (this.packIndexCache) {\n for (const [guidKey, entry] of this.packIndexCache) {\n seen.add(guidKey);\n result.push({\n guid: guidKey,\n kind: entry.kind,\n ...(entry.name !== undefined ? { name: entry.name } : {}),\n packageUrl: entry.packageUrl,\n ...(entry.packageId !== undefined ? { packageId: entry.packageId } : {}),\n ...(entry.provenance !== undefined ? { provenance: entry.provenance } : {}),\n ...(entry.revision !== undefined ? { revision: entry.revision } : {}),\n ...(entry.sourceKey !== undefined ? { sourceKey: entry.sourceKey } : {}),\n ...(entry.sourceIndex !== undefined ? { sourceIndex: entry.sourceIndex } : {}),\n ...(entry.sourceOverrides !== undefined\n ? { sourceOverrides: entry.sourceOverrides }\n : {}),\n ...(entry.sourceOverrideDescriptors !== undefined\n ? { sourceOverrideDescriptors: entry.sourceOverrideDescriptors }\n : {}),\n authoring: entry.authoring ?? authoringCapabilityForAssetKind(entry.kind),\n ...(entry.relations !== undefined ? { relations: entry.relations } : {}),\n ...(entry.diagnostics !== undefined ? { diagnostics: entry.diagnostics } : {}),\n ...(entry.refs !== undefined ? { refs: entry.refs } : {}),\n ...(entry.sourcePath !== undefined ? { sourcePath: entry.sourcePath } : {}),\n ...(entry.cookReceiptUrl !== undefined ? { cookReceiptUrl: entry.cookReceiptUrl } : {}),\n ...(entry.subject !== undefined ? { subject: entry.subject } : {}),\n ...(entry.execution !== undefined ? { execution: entry.execution } : {}),\n ...(entry.lifecycle !== undefined ? { lifecycle: entry.lifecycle } : {}),\n ...(entry.projection !== undefined ? { projection: entry.projection } : {}),\n });\n }\n }\n\n // Inlined / dev-path entries: assetCatalog, no pack-index URL. The envelope\n // holds the authoritative AssetRef[] graph; flatten it to plain GUID edges\n // so both catalog paths expose the same refs: readonly string[] shape.\n for (const [guidKey, envelope] of this.assetCatalog) {\n if (!seen.has(guidKey)) {\n const name = envelope.name ?? this.resolveName(guidKey);\n result.push({\n guid: guidKey,\n kind: envelope.payload.kind,\n name,\n packageUrl: '',\n authoring: authoringCapabilityForAssetKind(envelope.payload.kind),\n subject: 'internal-asset',\n execution: 'direct',\n lifecycle: 'current',\n projection: {\n subject: 'internal-asset',\n execution: 'direct',\n lifecycle: 'current',\n operations: catalogOperationsFor({\n subject: 'internal-asset',\n execution: 'direct',\n lifecycle: 'current',\n }),\n },\n ...(envelope.refs.length > 0 ? { refs: envelope.refs.map((r) => r.guid) } : {}),\n });\n }\n }\n\n return result;\n }\n}\n","import { err, ok, type Result } from '@forgeax/engine-rhi';\nimport {\n ASSET_ERROR_HINTS,\n AssetError,\n type CatalogDelta,\n type CatalogEntry,\n type ResourceRevision,\n type RuntimeAssetBinding,\n} from '@forgeax/engine-types';\nimport { fetchCatalog } from './registry/catalog';\n\nexport type CatalogListener = (delta: CatalogDelta) => void;\n\n/** Read-only catalog source backed by static entries or a canonical URL. */\nexport interface CatalogSource {\n enumerate(): Promise<Result<readonly CatalogEntry[], AssetError>>;\n subscribe(listener: CatalogListener): () => void;\n readonly expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>;\n}\n\n/**\n * Create a read-only catalog source while preserving the schema SSOT.\n *\n * Static and fetched sources use the same `CatalogEntry` and revision fields;\n * an expected revision rejects unverified data before it reaches consumers.\n */\nexport function createCatalogSource(options: {\n readonly url?: string;\n readonly entries?: readonly CatalogEntry[];\n readonly fetch?: typeof globalThis.fetch;\n readonly expectedRevision?: ResourceRevision;\n readonly expectedScope?: Pick<RuntimeAssetBinding, 'scopeId' | 'generation'>;\n readonly subscribe?: (listener: CatalogListener) => () => void;\n}): CatalogSource {\n const entries = options.entries;\n return {\n async enumerate() {\n if (entries !== undefined) {\n if (options.expectedRevision === undefined) return ok(entries);\n const actualRevisions = entries.flatMap((entry) =>\n entry.revision === undefined ? [] : [entry.revision],\n );\n const matches =\n actualRevisions.length > 0 &&\n actualRevisions.every(\n (revision) =>\n revision.digest === options.expectedRevision?.digest &&\n revision.observedAt === options.expectedRevision?.observedAt &&\n revision.rootId === options.expectedRevision?.rootId,\n );\n if (!matches) {\n return err(\n new AssetError({\n code: 'asset-parse-failed',\n expected: 'static catalog entries to carry the expected producer revision',\n hint: 'restore a verified catalog revision before applying the source',\n detail: { expectedRevision: options.expectedRevision, actualRevisions } as never,\n }),\n );\n }\n return ok(entries);\n }\n if (options.url === undefined) {\n return err(\n new AssetError({\n code: 'catalog-source-unconfigured',\n expected: 'a configured catalog source',\n hint: ASSET_ERROR_HINTS['catalog-source-unconfigured'],\n }),\n );\n }\n const result = await fetchCatalog(\n options.url,\n options.fetch ?? globalThis.fetch,\n undefined,\n options.expectedRevision,\n options.expectedScope,\n );\n if (!result.ok) return result;\n return ok(\n [...result.value].map(([guid, entry]) => ({ guid, ...entry })) as readonly CatalogEntry[],\n );\n },\n subscribe(listener) {\n return options.subscribe?.(listener) ?? (() => {});\n },\n ...(options.expectedScope === undefined ? {} : { expectedScope: options.expectedScope }),\n };\n}\n","// @forgeax/engine-assets-runtime -- runtime-local ImageError constructor\n// (feat-20260705-runtime-tier2-decomposition M1 / w4, D-4 F1 straight-cut).\n// Pure move from asset-registry.ts; zero identifier changes.\n\nimport type { ImageErrorDetailFor, ImageErrorFor } from '@forgeax/engine-types';\nimport { IMAGE_ERROR_HINTS } from '@forgeax/engine-types';\n\n// Local minimal `ImageError` constructor (charter P5 producer / consumer\n// split: the runtime AssetRegistry should not import @forgeax/engine-image\n// errors module because the image package is the disk-side decoder; the\n// runtime is the GPU consumer. Both packages share the `ImageError`\n// interface SSOT in @forgeax/engine-types so runtime constructs the\n// 4-field surface (.code / .expected / .hint / .detail) directly without\n// duplicating the @forgeax/engine-image errors.ts class).\ntype UnsupportedMimeImageError = ImageErrorFor<'image-format-unsupported'>;\ntype UnsupportedMimeImageErrorDetail = ImageErrorDetailFor<'image-format-unsupported'>;\n\nconst IMAGE_ERROR_EXPECTED_LOCAL: Readonly<\n Record<UnsupportedMimeImageErrorDetail['code'], string>\n> = {\n 'image-format-unsupported':\n \"mime is one of ['image/png', 'image/jpeg', 'image/x-tga']; texture format <-> colorSpace family agrees\",\n};\n\nclass RuntimeImageError extends Error implements UnsupportedMimeImageError {\n readonly code: UnsupportedMimeImageError['code'];\n readonly expected: string;\n readonly hint: string;\n readonly detail: UnsupportedMimeImageErrorDetail;\n constructor(detail: UnsupportedMimeImageErrorDetail) {\n const code = detail.code;\n const expected = IMAGE_ERROR_EXPECTED_LOCAL[code];\n const hint = IMAGE_ERROR_HINTS[code];\n super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);\n this.name = 'ImageError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\nexport function makeImageError(detail: UnsupportedMimeImageErrorDetail): UnsupportedMimeImageError {\n return new RuntimeImageError(detail);\n}\n","// @forgeax/engine-assets-runtime -- runtime image byte decoder\n// (tweak-20260714-runtime-image-bytes-decoder-add-decodeimagebytes M2 / m2-1).\n//\n// M1 established the signature + TSDoc contract + red test skeleton. M2\n// fills the body:\n// 1. mime whitelist pre-check (PNG / JPEG); non-match -> structured\n// `image-format-unsupported` err (charter P3 explicit failure).\n// 2. Delegate to `@forgeax/engine-image::decodeImageInBrowser` (SSOT\n// browser-safe decoder; charter architecture principle 1 SSOT).\n// 3. Map `DecodedImage` -> `TextureAsset` POD; `format` derives from\n// `opts.colorSpace` (srgb -> 'rgba8unorm-srgb' / linear ->\n// 'rgba8unorm', mirrors `image-importer.ts` colorSpaceToFormat); when\n// `opts.mipmap !== false`, `mipLevelCount` derives from\n// `numMipLevels({width,height})` (charter Derive-Don't-Duplicate).\n//\n// decode-image-bytes.ts is the SINGLE assets-runtime file allowed to\n// statically import @forgeax/engine-image (charter D-2; the\n// scripts/check-image-pipeline-isolation.mjs Path (a.2-anti) whitelist\n// row anchors this exact path). The gate's (a.1) forbidden-symbol regex\n// `\\basync\\s+function\\s+decodeImage\\b` does NOT match `decodeImageBytes`\n// because `\\b` between `e` and `B` fails (both are word chars) --\n// verified at M2 by running the gate locally.\nimport { decodeImageInBrowser } from '@forgeax/engine-image';\nimport type { ImageError, Result, TextureAsset } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { makeImageError } from './image-error';\nimport { numMipLevels } from './mipmap-generator';\n\n/** v1 mime whitelist -- PNG / JPEG only (charter P1 progressive disclosure). */\nconst SUPPORTED_MIMES = ['image/png', 'image/jpeg'] as const;\ntype SupportedMime = (typeof SUPPORTED_MIMES)[number];\n\nfunction isSupportedMime(mime: string): mime is SupportedMime {\n return SUPPORTED_MIMES.some((supportedMime) => supportedMime === mime);\n}\n\n/**\n * Decode a PNG / JPEG byte stream into a `TextureAsset` POD.\n *\n * Runtime SDK entry for AI users who hold image bytes (fetched over the\n * network, embedded as base64, produced by an out-of-tree decoder, etc.) and\n * want to feed them into `world.allocSharedRef('TextureAsset', pod)` +\n * `GpuResourceStore.ensureResident` without the disk-side importer / build\n * pipeline in the loop (charter P1 progressive disclosure: one-step \"bytes\n * in, POD out\").\n *\n * v1 supports the two universally-decodable mime types: `image/png` and\n * `image/jpeg`. Failure surfaces are all structured via the closed\n * `ImageError` union (`.code` / `.expected` / `.hint` / `.detail`); the\n * function never throws for expected failures (AGENTS.md Error model +\n * charter P3 explicit failure).\n *\n * Error codes possible (subset of the closed `ImageErrorCode` union):\n * - `image-format-unsupported` -- mime not in the v1 whitelist (`detail.actualMime`)\n * - `image-decode-failed` -- decoder rejected the bytes, or the environment\n * lacks `createImageBitmap` (`detail.reason`)\n *\n * @param bytes - Encoded image byte stream (`Uint8Array` or `ArrayBuffer`).\n * @param mime - Byte-stream mime type. v1 whitelist: `'image/png' | 'image/jpeg'`.\n * @param opts - Optional decode overrides:\n * - `colorSpace`: `'srgb'` (default) or `'linear'`. Derives POD `format`:\n * `srgb -> 'rgba8unorm-srgb'`, `linear -> 'rgba8unorm'`.\n * - `mipmap`: `true` (default) or `false`. When true, `mipLevelCount` is\n * computed via `numMipLevels({ width, height })`; when false, forced 1.\n * @returns `ok(TextureAsset)` on success; `err(ImageError)` on failure.\n *\n * @example\n * ```ts\n * import { decodeImageBytes } from '@forgeax/engine-assets-runtime';\n *\n * const bytes = new Uint8Array(await (await fetch(url)).arrayBuffer());\n * const result = await decodeImageBytes(bytes, 'image/png');\n * if (!result.ok) {\n * // The ImageError code and detail are one correlated discriminated union.\n * switch (result.error.code) {\n * case 'image-format-unsupported':\n * console.error('bad mime:', result.error.detail.actualMime);\n * break;\n * case 'image-decode-failed':\n * console.error('decode reason:', result.error.detail.reason);\n * break;\n * }\n * return;\n * }\n * const handle = world.allocSharedRef('TextureAsset', result.value);\n * ```\n */\nexport async function decodeImageBytes(\n bytes: Uint8Array | ArrayBuffer,\n mime: string,\n opts: { colorSpace?: 'srgb' | 'linear'; mipmap?: boolean } = {},\n): Promise<Result<TextureAsset, ImageError>> {\n if (!isSupportedMime(mime)) {\n return err(\n makeImageError({\n code: 'image-format-unsupported',\n actualMime: mime,\n }),\n );\n }\n\n const colorSpace = opts.colorSpace ?? 'srgb';\n const mipmap = opts.mipmap ?? true;\n\n const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n const decoded = await decodeImageInBrowser(u8, mime, { colorSpace, mipmap });\n if (!decoded.ok) {\n return err(decoded.error);\n }\n\n const dec = decoded.value;\n const format: GPUTextureFormat = colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm';\n const mipLevelCount = mipmap ? numMipLevels({ width: dec.width, height: dec.height }) : 1;\n\n const pod: TextureAsset = {\n kind: 'texture',\n width: dec.width,\n height: dec.height,\n format,\n data: dec.bytes,\n colorSpace,\n mipmap,\n mipLevelCount,\n };\n return ok(pod);\n}\n","// @forgeax/engine-assets-runtime — DynamicTextureStore: transient per-frame GPU\n// textures for video sources (feat-20260623-world-space-video-asset M4 / w15).\n//\n// D-3: video frames are re-uploaded every frame — the opposite of the static\n// \"upload once / cache forever\" semantics GpuResourceStore.ensureResident\n// implements. Routing video through ensureResident would either poison its\n// permanent cache (AC-08) or crash it (its `switch (pod.kind)` has no `video`\n// arm). So video gets its OWN store with a transient lifecycle, exactly the way\n// cube-texture upload is an eager independent path that never enters the\n// ensureResident switch (research Finding 7 precedent).\n//\n// This store does NOT import GpuResourceStore and accepts NO static texture\n// handle — it is keyed solely by the VideoAsset clip handle. Each key owns a\n// single GPUTexture sized to the source video; the texture is recreated only\n// when the source dimensions change (a steady-size clip allocates once and is\n// re-written in place every frame via copyExternalImageToTexture). The view is\n// re-fetched after each upload so the bind group always samples the latest\n// frame.\n//\n// Charter P3: every failure returns a structured Result (never throws for an\n// expected GPU failure); the per-frame caller (record stage videoTextureView)\n// fires the RhiError on the engine error channel and falls back to the default\n// view for that frame.\n\nimport type { Result, RhiDevice, RhiError, Texture, TextureView } from '@forgeax/engine-rhi';\nimport { ok } from '@forgeax/engine-rhi';\nimport type { Handle } from '@forgeax/engine-types';\nimport { handleSlot } from '@forgeax/engine-types';\n\n/**\n * The host-owned external image the engine copies a video frame from\n * (HTMLVideoElement / VideoFrame / ImageBitmap / canvas). Mirrors the `source`\n * member of the WebGPU `GPUCopyExternalImageSourceInfo` the RHI\n * `copyExternalImageToTexture` consumes; aliased here so the store does not pull\n * the whole webgpu descriptor type into its surface.\n */\nexport type CopyExternalImageSource = GPUCopyExternalImageSourceInfo['source'];\n\n/**\n * GPUTextureUsage bits a video destination texture needs: COPY_DST (the\n * copyExternalImageToTexture write target), TEXTURE_BINDING (sampled in the\n * material bind group), and RENDER_ATTACHMENT (required by the WebGPU spec for\n * a copyExternalImageToTexture destination). Mirrors the literals\n * gpu-resource-store.ts uses for its upload textures (no shared const exists to\n * import without coupling the two stores — D-3 keeps them independent).\n */\nconst VIDEO_TEXTURE_USAGE = 0x2 | 0x4 | 0x10;\n\n/** rgba8unorm-srgb: a video frame decodes to sRGB; sampling returns linear. */\nconst VIDEO_TEXTURE_FORMAT = 'rgba8unorm-srgb' as const;\n\n/**\n * The minimal RHI device surface DynamicTextureStore needs. Declared structurally\n * (not the full RhiDevice) so unit tests drive it with a small mock and the store\n * stays decoupled from the rest of the device surface (Pipeline Isolation).\n */\nexport interface DynamicTextureDevice {\n createTexture(desc: {\n readonly size: {\n readonly width: number;\n readonly height: number;\n readonly depthOrArrayLayers: number;\n };\n readonly format: typeof VIDEO_TEXTURE_FORMAT;\n readonly usage: number;\n readonly label?: string;\n }): Result<Texture, RhiError>;\n createTextureView(texture: Texture, desc: Record<string, never>): Result<TextureView, RhiError>;\n destroyTexture(texture: Texture): Result<void, RhiError>;\n readonly queue: {\n copyExternalImageToTexture(\n source: { readonly source: CopyExternalImageSource; readonly flipY?: boolean },\n destination: { readonly texture: Texture },\n copySize: {\n readonly width: number;\n readonly height: number;\n readonly depthOrArrayLayers: number;\n },\n ): Result<void, RhiError>;\n };\n}\n\n/** Adapt the opaque RHI device to the store's intentionally small upload seam. */\nexport function adaptDynamicTextureDevice(device: RhiDevice): DynamicTextureDevice {\n return {\n createTexture: (descriptor) =>\n device.createTexture({\n ...descriptor,\n mipLevelCount: undefined,\n sampleCount: undefined,\n dimension: undefined,\n viewFormats: undefined,\n textureBindingViewDimension: undefined,\n }),\n createTextureView: (texture) =>\n device.createTextureView(texture, {\n label: undefined,\n format: undefined,\n dimension: undefined,\n usage: undefined,\n aspect: undefined,\n baseMipLevel: undefined,\n mipLevelCount: undefined,\n baseArrayLayer: undefined,\n arrayLayerCount: undefined,\n }),\n destroyTexture: (texture) => device.destroyTexture(texture),\n queue: {\n copyExternalImageToTexture: (source, destination, copySize) =>\n device.queue.copyExternalImageToTexture(\n { source: source.source, origin: [0, 0], flipY: source.flipY ?? false },\n { texture: destination.texture, origin: [0, 0, 0] },\n copySize,\n ),\n },\n };\n}\n\ninterface TransientEntry {\n texture: Texture;\n view: TextureView;\n width: number;\n height: number;\n}\n\n/**\n * Transient per-frame texture store for video sources. Independent of\n * GpuResourceStore: it neither imports nor reaches into the static residency\n * cache (AC-08 / D-3).\n */\nexport class DynamicTextureStore {\n private device: DynamicTextureDevice | undefined = undefined;\n private readonly entries = new Map<number, TransientEntry>();\n\n /**\n * Wire the GPU device the store uploads through. Called once after the\n * renderer captures its device (mirrors GpuResourceStore.configureGpuDevice).\n * A replacement device invalidates every cached texture: the handles in the\n * map belong to the old device and cannot be reused after renderer recovery.\n */\n configureGpuDevice(device: DynamicTextureDevice): void {\n if (this.device !== undefined && this.device !== device) {\n this.destroyAll();\n }\n this.device = device;\n }\n\n /**\n * Upload one video frame for `clip` from the host-owned source image\n * (HTMLVideoElement / VideoFrame / ImageBitmap), (re)allocating the transient\n * texture when its size changes, and return the current-frame view to bind.\n *\n * Returns `undefined` (not an error) when the device is not yet wired or the\n * source has no decodable dimensions yet (metadata pending) — the caller binds\n * the default view that frame. A structured RhiError surfaces only when a wired\n * device rejects the allocation or the copy (charter P3).\n */\n uploadFrame(\n clip: Handle<'VideoAsset', 'shared'>,\n source: CopyExternalImageSource,\n width: number,\n height: number,\n ): Result<TextureView, RhiError> | undefined {\n const device = this.device;\n if (device === undefined) return undefined;\n if (width <= 0 || height <= 0) return undefined;\n\n const id = handleSlot(clip);\n const ensured = this.ensureEntry(device, id, width, height);\n if (!ensured.ok) return ensured;\n const entry = ensured.value;\n\n const copyRes = device.queue.copyExternalImageToTexture(\n { source, flipY: true },\n { texture: entry.texture },\n { width, height, depthOrArrayLayers: 1 },\n );\n if (!copyRes.ok) return copyRes;\n return ok(entry.view);\n }\n\n /**\n * The current-frame view for a clip, if one has been uploaded this session,\n * else undefined. The record stage reads this when assembling the bind group\n * (a frame that has not uploaded yet falls back to the default view).\n */\n getView(clip: Handle<'VideoAsset', 'shared'>): TextureView | undefined {\n return this.entries.get(handleSlot(clip))?.view;\n }\n\n /** Destroy every transient texture + drop the map (renderer teardown). */\n destroyAll(): void {\n const device = this.device;\n for (const entry of this.entries.values()) {\n device?.destroyTexture(entry.texture);\n }\n this.entries.clear();\n }\n\n /**\n * Get the entry for `id`, (re)allocating its texture + view when absent or\n * when the source dimensions changed. A same-size re-upload reuses the\n * existing texture (allocate-once for a steady clip; the per-frame cost is the\n * copyExternalImageToTexture write, not a texture create).\n */\n private ensureEntry(\n device: DynamicTextureDevice,\n id: number,\n width: number,\n height: number,\n ): Result<TransientEntry, RhiError> {\n const existing = this.entries.get(id);\n if (existing !== undefined && existing.width === width && existing.height === height) {\n return ok(existing);\n }\n if (existing !== undefined) device.destroyTexture(existing.texture);\n\n const texRes = device.createTexture({\n size: { width, height, depthOrArrayLayers: 1 },\n format: VIDEO_TEXTURE_FORMAT,\n usage: VIDEO_TEXTURE_USAGE,\n label: `video-transient-${id}`,\n });\n if (!texRes.ok) return texRes;\n const viewRes = device.createTextureView(texRes.value, {});\n if (!viewRes.ok) {\n device.destroyTexture(texRes.value);\n return viewRes;\n }\n const entry: TransientEntry = { texture: texRes.value, view: viewRes.value, width, height };\n this.entries.set(id, entry);\n return ok(entry);\n }\n}\n","import type { AssetLoadError, Result } from '@forgeax/engine-types';\n\nexport interface ArtifactCacheSnapshot {\n readonly entries: number;\n readonly pending: number;\n readonly hits: number;\n readonly misses: number;\n}\n\nexport class ArtifactCache {\n private readonly values = new Map<string, Uint8Array>();\n private readonly pending = new Map<string, Promise<Result<Uint8Array, AssetLoadError>>>();\n private hits = 0;\n private misses = 0;\n\n read(\n contentAddress: string,\n reader: () => Promise<Result<Uint8Array, AssetLoadError>>,\n ): Promise<Result<Uint8Array, AssetLoadError>> {\n const value = this.values.get(contentAddress);\n if (value !== undefined) {\n this.hits += 1;\n return Promise.resolve({ ok: true, value: new Uint8Array(value) } as Result<\n Uint8Array,\n AssetLoadError\n >);\n }\n const pending = this.pending.get(contentAddress);\n if (pending !== undefined) {\n this.hits += 1;\n return pending;\n }\n this.misses += 1;\n const request = Promise.resolve()\n .then(reader)\n .then((result) => {\n if (result.ok) this.values.set(contentAddress, new Uint8Array(result.value));\n return result;\n })\n .finally(() => {\n if (this.pending.get(contentAddress) === request) this.pending.delete(contentAddress);\n });\n this.pending.set(contentAddress, request);\n return request;\n }\n\n clear(contentAddress?: string): void {\n if (contentAddress === undefined) {\n this.values.clear();\n this.pending.clear();\n return;\n }\n this.values.delete(contentAddress);\n this.pending.delete(contentAddress);\n }\n\n snapshot(): ArtifactCacheSnapshot {\n return Object.freeze({\n entries: this.values.size,\n pending: this.pending.size,\n hits: this.hits,\n misses: this.misses,\n });\n }\n}\n","/**\n * Decoder output becomes an owner fact at this boundary. Freeze the ordinary\n * POD graph so a caller cannot mutate the cached payload between loads.\n * Typed-array storage is deliberately left as an opaque byte/vector carrier:\n * JavaScript cannot freeze a non-empty typed array without changing its public\n * engine type, so owners must treat those carriers as read-only by contract.\n */\nexport function freezeRuntimePayload<T>(value: T): T {\n const seen = new WeakSet<object>();\n return freeze(value, seen);\n}\n\nfunction freeze<T>(value: T, seen: WeakSet<object>): T {\n if (value === null || typeof value !== 'object') return value;\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) return value;\n if (seen.has(value)) return value;\n seen.add(value);\n for (const child of Object.values(value as Record<string, unknown>)) freeze(child, seen);\n return Object.freeze(value);\n}\n","import type { AssetLoadError, Result } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { freezeRuntimePayload } from './immutable-payload.js';\n\nexport interface AssetGraphValue<P> {\n readonly value: P;\n readonly refs: readonly string[];\n}\n\nexport interface AssetGraphOptions<\n P extends { readonly value: unknown; readonly refs: readonly string[] },\n> {\n readonly read: (guid: string, signal: AbortSignal) => Promise<Result<P, AssetLoadError>>;\n readonly maxConcurrentReads?: number;\n}\n\nexport interface AssetGraphCounters {\n readonly loads: number;\n readonly cacheHits: number;\n readonly readErrors: number;\n readonly noChange: number;\n readonly listenerFailures: number;\n}\n\nexport interface AssetGraphSnapshot {\n readonly epoch: number;\n readonly ready: readonly string[];\n readonly pending: number;\n readonly resources: number;\n readonly sccs: readonly (readonly string[])[];\n readonly counters: AssetGraphCounters;\n}\n\ntype GraphResult<P> = Result<P, AssetLoadError>;\ntype GraphListener = (snapshot: AssetGraphSnapshot) => void;\n\nfunction cancelled(guid: string): AssetLoadError {\n return {\n code: 'asset-load-cancelled',\n expected: 'the request AbortSignal to remain live until asset closure completes',\n hint: 'retry with a live AbortSignal when the request is still needed',\n detail: { guid },\n };\n}\n\nfunction disposed(scopeId = 'asset-runtime'): AssetLoadError {\n return {\n code: 'asset-runtime-disposed',\n expected: 'an active asset runtime scope',\n hint: 'obtain a new Registry from the current realm',\n detail: { scopeId },\n };\n}\n\nfunction superseded(guid: string, generation: number): AssetLoadError {\n return {\n code: 'asset-superseded',\n expected: 'the load ticket to remain current until promotion',\n hint: 'load the current publication after the Catalog change',\n detail: { guid, generation },\n };\n}\n\nfunction thrown(guid: string): AssetLoadError {\n return {\n code: 'asset-decode-failed',\n expected: 'the graph reader to return a Result',\n hint: 'repair the owner reader and retry the current publication',\n detail: { guid, kind: 'asset-graph-reader' },\n };\n}\n\nfunction freezeSnapshot(snapshot: AssetGraphSnapshot): AssetGraphSnapshot {\n return Object.freeze({\n ...snapshot,\n ready: Object.freeze([...snapshot.ready]),\n sccs: Object.freeze(snapshot.sccs.map((scc) => Object.freeze([...scc]))),\n counters: Object.freeze({ ...snapshot.counters }),\n });\n}\n\nexport class AssetGraph<P extends { readonly value: unknown; readonly refs: readonly string[] }> {\n private readonly read: AssetGraphOptions<P>['read'];\n private readonly limit: number;\n private readonly ready = new Map<string, P>();\n private readonly forward = new Map<string, Set<string>>();\n private readonly reverse = new Map<string, Set<string>>();\n private readonly reads = new Map<string, Promise<GraphResult<P>>>();\n private readonly requests = new Map<string, Promise<GraphResult<P>>>();\n private readonly listeners = new Set<GraphListener>();\n private readonly sccs: (readonly string[])[] = [];\n private activeReads = 0;\n private readWaiters: (() => void)[] = [];\n private disposed = false;\n private epoch = 0;\n private counters: AssetGraphCounters = {\n loads: 0,\n cacheHits: 0,\n readErrors: 0,\n noChange: 0,\n listenerFailures: 0,\n };\n private currentSnapshot: AssetGraphSnapshot;\n\n constructor(options: AssetGraphOptions<P>) {\n this.read = options.read;\n this.limit = Math.max(1, Math.floor(options.maxConcurrentReads ?? 8));\n this.currentSnapshot = freezeSnapshot({\n epoch: 0,\n ready: [],\n pending: 0,\n resources: 0,\n sccs: [],\n counters: this.counters,\n });\n }\n\n load(guid: string, signal = new AbortController().signal): Promise<GraphResult<P>> {\n const canonicalGuid = guid.toLowerCase();\n if (this.disposed) return Promise.resolve(err(disposed()));\n if (signal.aborted) return Promise.resolve(err(cancelled(canonicalGuid)));\n const cached = this.ready.get(canonicalGuid);\n if (cached !== undefined) {\n this.counters = {\n ...this.counters,\n cacheHits: this.counters.cacheHits + 1,\n noChange: this.counters.noChange + 1,\n };\n this.publish();\n return Promise.resolve(ok(cached));\n }\n const existing = this.requests.get(canonicalGuid);\n if (existing !== undefined) {\n this.counters = { ...this.counters, cacheHits: this.counters.cacheHits + 1 };\n return existing;\n }\n this.counters = { ...this.counters, loads: this.counters.loads + 1 };\n const ticketEpoch = this.epoch;\n const request = this.loadClosure(canonicalGuid, signal, ticketEpoch).finally(() => {\n if (this.requests.get(canonicalGuid) === request) this.requests.delete(canonicalGuid);\n this.publish();\n });\n this.requests.set(canonicalGuid, request);\n this.publish();\n return request;\n }\n\n invalidate(guid: string): readonly string[] {\n const affected = this.collectAffected([guid.toLowerCase()]);\n this.drop(affected);\n this.epoch += 1;\n this.publish();\n return [...affected].sort();\n }\n\n invalidateForCatalogChange(guids?: readonly string[]): void {\n if (this.disposed) return;\n const affected =\n guids === undefined || guids.length === 0\n ? new Set([...this.ready.keys(), ...this.requests.keys(), ...this.reads.keys()])\n : this.collectAffected(guids.map((item) => item.toLowerCase()));\n this.drop(affected);\n this.epoch += 1;\n this.publish();\n }\n\n subscribe(listener: GraphListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n snapshot(): AssetGraphSnapshot {\n return this.currentSnapshot;\n }\n\n lookup(guid: string): P['value'] | undefined {\n return this.ready.get(guid.toLowerCase())?.value;\n }\n\n guidOf(value: P['value']): string | undefined {\n for (const [guid, entry] of this.ready) {\n if (entry.value === value) return guid;\n }\n return undefined;\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.epoch += 1;\n this.ready.clear();\n this.forward.clear();\n this.reverse.clear();\n this.reads.clear();\n const waiters = this.readWaiters;\n this.readWaiters = [];\n for (const resolve of waiters) resolve();\n this.publish();\n }\n\n private async loadClosure(\n root: string,\n signal: AbortSignal,\n ticketEpoch: number,\n ): Promise<GraphResult<P>> {\n const values = new Map<string, P>();\n const visiting = new Set<string>();\n const visited = new Set<string>();\n const group = new Set<string>();\n const result = await this.visit(root, signal, visiting, visited, values, group);\n if (!result.ok) return result;\n if (this.disposed) return err(disposed());\n if (signal.aborted) return err(cancelled(root));\n if (ticketEpoch !== this.epoch) return err(superseded(root, ticketEpoch));\n for (const [guid, value] of values) this.promote(guid, value);\n this.recordScc();\n return ok(values.get(root) as P);\n }\n\n private async visit(\n guid: string,\n signal: AbortSignal,\n visiting: Set<string>,\n visited: Set<string>,\n values: Map<string, P>,\n group: Set<string>,\n ): Promise<GraphResult<P>> {\n if (visiting.has(guid)) {\n group.add(guid);\n return ok({ value: undefined as unknown as P, refs: [] } as unknown as P);\n }\n if (visited.has(guid)) return ok(values.get(guid) as P);\n const cached = this.ready.get(guid);\n if (cached !== undefined) {\n values.set(guid, cached);\n visited.add(guid);\n return ok(cached);\n }\n visiting.add(guid);\n const read = await this.readOnce(guid, signal);\n if (!read.ok) {\n visiting.delete(guid);\n return read;\n }\n values.set(guid, read.value);\n group.add(guid);\n this.link(guid, read.value.refs);\n for (const ref of read.value.refs) {\n const child = await this.visit(ref, signal, visiting, visited, values, group);\n if (!child.ok) {\n visiting.delete(guid);\n return err({\n code: 'asset-dependency-failed',\n expected: 'every referenced asset to load successfully',\n hint: 'repair the dependency publication and retry the root asset',\n detail: { guid, dependencyGuid: ref },\n });\n }\n }\n visiting.delete(guid);\n visited.add(guid);\n return ok(read.value);\n }\n\n private readOnce(guid: string, signal: AbortSignal): Promise<GraphResult<P>> {\n const existing = this.reads.get(guid);\n if (existing !== undefined) return existing;\n const request = this.withPermit(async () => {\n if (this.disposed) return err(disposed());\n if (signal.aborted) return err(cancelled(guid));\n try {\n const result = await this.read(guid, signal);\n if (signal.aborted) return err(cancelled(guid));\n if (!result.ok)\n this.counters = { ...this.counters, readErrors: this.counters.readErrors + 1 };\n return result;\n } catch {\n this.counters = { ...this.counters, readErrors: this.counters.readErrors + 1 };\n return err(thrown(guid));\n }\n });\n this.reads.set(guid, request);\n void request.finally(() => {\n if (this.reads.get(guid) === request) this.reads.delete(guid);\n });\n return request;\n }\n\n private async withPermit<T>(operation: () => Promise<T>): Promise<T> {\n if (this.activeReads >= this.limit) {\n await new Promise<void>((resolve) => this.readWaiters.push(resolve));\n }\n this.activeReads += 1;\n try {\n return await operation();\n } finally {\n this.activeReads -= 1;\n this.readWaiters.shift()?.();\n }\n }\n\n private link(guid: string, refs: readonly string[]): void {\n const previous = this.forward.get(guid) ?? new Set<string>();\n for (const ref of previous) this.reverse.get(ref)?.delete(guid);\n const next = new Set(refs.map((ref) => ref.toLowerCase()));\n this.forward.set(guid, next);\n for (const ref of next) {\n const dependents = this.reverse.get(ref) ?? new Set<string>();\n dependents.add(guid);\n this.reverse.set(ref, dependents);\n }\n }\n\n private collectAffected(guids: readonly string[]): Set<string> {\n const affected = new Set<string>();\n const queue = [...guids];\n while (queue.length > 0) {\n const current = queue.shift();\n if (current === undefined || affected.has(current)) continue;\n affected.add(current);\n for (const dependent of this.reverse.get(current) ?? []) queue.push(dependent);\n }\n return affected;\n }\n\n private drop(affected: ReadonlySet<string>): void {\n for (const item of affected) {\n for (const ref of this.forward.get(item) ?? []) this.reverse.get(ref)?.delete(item);\n for (const dependent of this.reverse.get(item) ?? []) {\n this.forward.get(dependent)?.delete(item);\n }\n }\n for (const item of affected) {\n this.ready.delete(item);\n this.requests.delete(item);\n this.reads.delete(item);\n this.forward.delete(item);\n this.reverse.delete(item);\n }\n this.sccs.splice(0, this.sccs.length);\n }\n\n private promote(guid: string, value: P): void {\n if (value === undefined) return;\n this.ready.set(\n guid,\n Object.freeze({\n ...value,\n value: freezeRuntimePayload(value.value),\n refs: Object.freeze([...value.refs]),\n }) as P,\n );\n }\n\n private recordScc(): void {\n const indexByGuid = new Map<string, number>();\n const lowByGuid = new Map<string, number>();\n const stack: string[] = [];\n const onStack = new Set<string>();\n let nextIndex = 0;\n const components: string[][] = [];\n const visit = (guid: string): void => {\n indexByGuid.set(guid, nextIndex);\n lowByGuid.set(guid, nextIndex);\n nextIndex += 1;\n stack.push(guid);\n onStack.add(guid);\n for (const ref of this.forward.get(guid) ?? []) {\n if (!indexByGuid.has(ref)) {\n visit(ref);\n lowByGuid.set(guid, Math.min(lowByGuid.get(guid) ?? 0, lowByGuid.get(ref) ?? 0));\n } else if (onStack.has(ref)) {\n lowByGuid.set(guid, Math.min(lowByGuid.get(guid) ?? 0, indexByGuid.get(ref) ?? 0));\n }\n }\n if (lowByGuid.get(guid) !== indexByGuid.get(guid)) return;\n const component: string[] = [];\n let member: string | undefined;\n do {\n member = stack.pop();\n if (member === undefined) break;\n onStack.delete(member);\n component.push(member);\n } while (member !== guid);\n if (component.length > 1 || this.forward.get(guid)?.has(guid) === true)\n components.push(component.sort());\n };\n for (const guid of this.forward.keys()) if (!indexByGuid.has(guid)) visit(guid);\n this.sccs.splice(\n 0,\n this.sccs.length,\n ...components.map((component) => Object.freeze(component)),\n );\n }\n\n private publish(): void {\n this.currentSnapshot = freezeSnapshot({\n epoch: this.epoch,\n ready: [...this.ready.keys()].sort(),\n pending: this.requests.size + this.reads.size,\n resources: this.ready.size,\n sccs: this.sccs,\n counters: this.counters,\n });\n for (const listener of [...this.listeners]) {\n try {\n listener(this.currentSnapshot);\n } catch {\n this.counters = {\n ...this.counters,\n listenerFailures: Math.min(1024, this.counters.listenerFailures + 1),\n };\n this.currentSnapshot = freezeSnapshot({\n ...this.currentSnapshot,\n counters: this.counters,\n });\n }\n }\n }\n}\n","import type { CatalogEntry } from '@forgeax/engine-types';\nimport { type AssetLoadError, err, ok, type Result } from '@forgeax/engine-types';\n\nexport interface RuntimeCatalogRow extends CatalogEntry {\n readonly publication: NonNullable<CatalogEntry['publication']>;\n}\n\nfunction invalidRow(guid: string, reason: string): Result<never, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'one complete current runtime Catalog row',\n hint: 'rebuild the producer Catalog and publish one Pack v2 tuple',\n detail: { guid, reason },\n });\n}\n\nexport function validateRuntimeRow(row: CatalogEntry): Result<RuntimeCatalogRow, AssetLoadError> {\n if (row === null || typeof row !== 'object') return invalidRow('', 'row');\n const candidate = row as Partial<CatalogEntry>;\n const guid = typeof candidate.guid === 'string' ? candidate.guid : '';\n if (guid.trim().length === 0) return invalidRow(guid, 'guid');\n if (typeof candidate.kind !== 'string' || candidate.kind.trim().length === 0)\n return invalidRow(guid, 'kind');\n if (typeof candidate.packageUrl !== 'string' || candidate.packageUrl.trim().length === 0)\n return invalidRow(guid, 'packageUrl');\n if (typeof candidate.sourcePath !== 'string' || candidate.sourcePath.trim().length === 0)\n return invalidRow(guid, 'sourcePath');\n if (!Number.isSafeInteger(candidate.publication?.generation))\n return invalidRow(guid, 'publication generation');\n if (candidate.publication === undefined) return invalidRow(guid, 'publication');\n const publication = candidate.publication;\n if (\n publication.schemaVersion !== 'asset-publication/1' ||\n typeof publication.sourcePath !== 'string' ||\n publication.sourcePath.trim().length === 0 ||\n typeof publication.sourceRevision !== 'string' ||\n publication.sourceRevision.trim().length === 0 ||\n publication.generation < 0 ||\n typeof publication.digest !== 'string' ||\n publication.digest.trim().length === 0 ||\n typeof publication.outputSetDigest !== 'string' ||\n publication.outputSetDigest.trim().length === 0 ||\n !Array.isArray(publication.outputs) ||\n publication.receipt === null ||\n typeof publication.receipt !== 'object' ||\n !Array.isArray(publication.externalEvidence)\n ) {\n return invalidRow(guid, 'publication tuple');\n }\n return ok(Object.freeze({ ...candidate, guid, publication }) as RuntimeCatalogRow);\n}\n","import type {\n CatalogDelta,\n CatalogDiagnostic,\n CatalogEntry,\n ResourceRevision,\n} from '@forgeax/engine-types';\nimport { type AssetLoadError, err, ok, type Result } from '@forgeax/engine-types';\nimport type { CatalogSource } from '../catalog-source.js';\nimport { type RuntimeCatalogRow, validateRuntimeRow } from './validate-runtime-row.js';\n\nexport interface CatalogSessionOptions {\n readonly scopeId?: string;\n readonly generation?: number;\n}\n\nexport interface CatalogSessionSnapshot {\n readonly scopeId: string;\n readonly generation: number;\n readonly epoch: number;\n readonly revision?: ResourceRevision;\n readonly entries: readonly RuntimeCatalogRow[];\n readonly changed: readonly string[];\n readonly removed: readonly string[];\n readonly diagnostics: readonly CatalogDiagnostic[];\n readonly listenerFailures: number;\n readonly stale: boolean;\n}\n\ntype SessionResult = Result<CatalogSessionSnapshot, AssetLoadError>;\ntype SessionListener = (snapshot: CatalogSessionSnapshot) => void;\n\nfunction runtimeError(\n code: AssetLoadError['code'],\n guid: string,\n detail: Record<string, unknown>,\n): AssetLoadError {\n if (code === 'catalog-discontinuous') {\n return {\n code,\n expected: 'an ordered catalog revision window',\n hint: 'reconcile the current Catalog before consuming this delta',\n detail: {\n scopeId: String(detail.scopeId ?? 'unknown'),\n expectedGeneration: Number(detail.expectedGeneration ?? 0),\n actualGeneration: Number(detail.actualGeneration ?? 0),\n },\n };\n }\n return {\n code: 'asset-package-invalid',\n expected: 'a verified Catalog source',\n hint: 'repair the producer Catalog and retry with the current publication',\n detail: { guid, reason: String(detail.reason ?? 'catalog source failed') },\n };\n}\n\nfunction freezeSnapshot(snapshot: CatalogSessionSnapshot): CatalogSessionSnapshot {\n return Object.freeze({\n ...snapshot,\n entries: Object.freeze([...snapshot.entries]),\n changed: Object.freeze([...snapshot.changed]),\n removed: Object.freeze([...snapshot.removed]),\n diagnostics: Object.freeze([...snapshot.diagnostics]),\n });\n}\n\nfunction sameEntry(left: CatalogEntry, right: CatalogEntry): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nfunction key(guid: string): string {\n return guid.toLowerCase();\n}\n\nexport class CatalogSession {\n private readonly source: CatalogSource;\n private readonly scopeId: string;\n private readonly generation: number;\n private readonly entries = new Map<string, RuntimeCatalogRow>();\n private readonly listeners = new Set<SessionListener>();\n private unsubscribe: (() => void) | undefined;\n private baselinePromise: Promise<SessionResult> | undefined;\n private reconcilePromise: Promise<SessionResult> | undefined;\n private pending: CatalogDelta[] = [];\n private currentSnapshot: CatalogSessionSnapshot;\n private revision: ResourceRevision | undefined;\n private diagnostics: CatalogDiagnostic[] = [];\n private listenerFailures = 0;\n private changed = new Set<string>();\n private removed = new Set<string>();\n private epoch = 0;\n private stale = false;\n private staleGeneration = 0;\n private started = false;\n private disposed = false;\n\n constructor(source: CatalogSource, options: CatalogSessionOptions = {}) {\n this.source = source;\n this.scopeId = options.scopeId ?? source.expectedScope?.scopeId ?? 'asset-runtime';\n this.generation = options.generation ?? source.expectedScope?.generation ?? 0;\n this.currentSnapshot = freezeSnapshot({\n scopeId: this.scopeId,\n generation: this.generation,\n epoch: 0,\n entries: [],\n changed: [],\n removed: [],\n diagnostics: [],\n listenerFailures: 0,\n stale: false,\n });\n }\n\n start(): Promise<SessionResult> {\n if (this.baselinePromise !== undefined) return this.baselinePromise;\n if (this.disposed) return Promise.resolve(err(this.disposedError()));\n this.unsubscribe = this.source.subscribe((delta) => this.receive(delta));\n const promise = this.source\n .enumerate()\n .then((result) => {\n if (!result.ok) {\n this.markStale();\n this.publish();\n return err(runtimeError('asset-package-invalid', '', { reason: result.error.code }));\n }\n this.entries.clear();\n for (const entry of result.value) {\n const validated = validateRuntimeRow(entry);\n if (!validated.ok) {\n this.markStale();\n this.publish();\n return err(validated.error);\n }\n this.entries.set(key(validated.value.guid), validated.value);\n }\n this.started = true;\n this.stale = false;\n this.staleGeneration = this.generation;\n this.diagnostics = [];\n for (const delta of this.pending) this.fold(delta, false);\n this.pending = [];\n this.publish();\n return ok(this.currentSnapshot);\n })\n .catch((cause: unknown) => {\n this.markStale();\n this.addDiagnostic('catalog-degraded-rows', 'Catalog enumeration must resolve a Result');\n this.publish();\n return err(\n runtimeError('asset-package-invalid', '', {\n reason: cause instanceof Error ? cause.message : String(cause),\n }),\n );\n });\n this.baselinePromise = promise;\n void promise.then(\n (result) => {\n if (!result.ok) this.baselinePromise = undefined;\n },\n () => {\n this.baselinePromise = undefined;\n },\n );\n return promise;\n }\n\n reconcile(): Promise<SessionResult> {\n if (this.disposed) return Promise.resolve(err(this.disposedError()));\n if (this.reconcilePromise !== undefined) return this.reconcilePromise;\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.started = false;\n this.pending = [];\n this.baselinePromise = undefined;\n this.epoch += 1;\n const promise = this.start();\n this.reconcilePromise = promise;\n void promise.then(\n () => {\n if (this.reconcilePromise === promise) this.reconcilePromise = undefined;\n },\n () => {\n if (this.reconcilePromise === promise) this.reconcilePromise = undefined;\n },\n );\n return promise;\n }\n\n current(guid: string): RuntimeCatalogRow | undefined {\n return this.entries.get(key(guid));\n }\n\n snapshot(): CatalogSessionSnapshot {\n return this.currentSnapshot;\n }\n\n discontinuity(): AssetLoadError | undefined {\n if (!this.stale) return undefined;\n return {\n code: 'catalog-discontinuous',\n expected: 'an ordered, authoritative catalog revision window',\n hint: 'reconcile the Catalog source and retry the current publication',\n detail: {\n scopeId: this.scopeId,\n expectedGeneration: this.generation,\n actualGeneration: this.staleGeneration,\n },\n };\n }\n\n subscribe(listener: SessionListener): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.pending = [];\n this.listeners.clear();\n }\n\n private receive(delta: CatalogDelta): void {\n if (this.disposed) return;\n if (!this.started) {\n this.pending.push(delta);\n return;\n }\n this.fold(delta, true);\n }\n\n private fold(delta: CatalogDelta, publish: boolean): void {\n if (\n (delta.scopeId !== undefined && delta.scopeId !== this.scopeId) ||\n (delta.generation !== undefined && delta.generation !== this.generation)\n ) {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-scope-mismatch', 'delta scope does not match the session');\n if (publish) this.publish();\n return;\n }\n if (delta.authority === 'degraded') {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-degraded-rows', 'degraded rows are not identity-bearing');\n if (publish) this.publish();\n return;\n }\n if (delta.revisions !== undefined) {\n const baseline = delta.revisions.baseline;\n const current = delta.revisions.current;\n const valid =\n baseline.length === current.length &&\n current.every((point) => {\n const prior = baseline.find((item) => item.rootId === point.rootId);\n return prior !== undefined && point.revision === prior.revision + 1;\n });\n if (!valid) {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-gap', 'delta revision window is not contiguous');\n if (publish) this.publish();\n return;\n }\n }\n let changed = false;\n for (const entry of [...delta.added, ...delta.changed]) {\n const validated = validateRuntimeRow(entry);\n if (!validated.ok) {\n this.markStale(delta.generation);\n this.addDiagnostic('catalog-degraded-rows', 'delta contains an invalid runtime row');\n if (publish) this.publish();\n return;\n }\n const entryKey = key(validated.value.guid);\n const prior = this.entries.get(entryKey);\n if (prior === undefined || !sameEntry(prior, validated.value)) {\n this.entries.set(entryKey, validated.value);\n this.changed.add(entryKey);\n changed = true;\n if (validated.value.revision !== undefined) this.revision = validated.value.revision;\n }\n }\n for (const guid of delta.removed) {\n const entryKey = key(guid);\n if (this.entries.delete(entryKey)) {\n this.removed.add(entryKey);\n changed = true;\n }\n }\n if (changed) this.epoch += 1;\n if (publish) this.publish();\n }\n\n private addDiagnostic(code: CatalogDiagnostic['code'], expected: string): void {\n if (this.diagnostics.some((diagnostic) => diagnostic.code === code)) return;\n this.diagnostics.push({\n code,\n severity: 'blocking',\n expected,\n hint: 'reconcile the Catalog before loading the affected publication',\n authority: 'catalog',\n });\n }\n\n private markStale(actualGeneration = this.generation): void {\n this.stale = true;\n this.staleGeneration = actualGeneration;\n this.epoch += 1;\n }\n\n private publish(): void {\n this.currentSnapshot = freezeSnapshot({\n scopeId: this.scopeId,\n generation: this.generation,\n epoch: this.epoch,\n ...(this.revision === undefined ? {} : { revision: this.revision }),\n entries: [...this.entries.values()].sort((left, right) =>\n key(left.guid).localeCompare(key(right.guid)),\n ),\n changed: [...this.changed].sort(),\n removed: [...this.removed].sort(),\n diagnostics: this.diagnostics,\n listenerFailures: this.listenerFailures,\n stale: this.stale,\n });\n this.changed.clear();\n this.removed.clear();\n for (const listener of [...this.listeners]) {\n try {\n listener(this.currentSnapshot);\n } catch {\n this.listenerFailures = Math.min(1024, this.listenerFailures + 1);\n this.currentSnapshot = freezeSnapshot({\n ...this.currentSnapshot,\n listenerFailures: this.listenerFailures,\n });\n }\n }\n }\n\n private disposedError(): AssetLoadError {\n return runtimeError('asset-runtime-disposed', '', { scopeId: this.scopeId });\n }\n}\n","import type {\n AssetDecoder,\n AssetDecoderInput,\n AssetDecoderLease,\n AssetKind,\n AssetLoadError,\n Result,\n} from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { freezeRuntimePayload } from './immutable-payload.js';\n\ninterface DecoderEntry {\n readonly identity: symbol;\n readonly decoder: AssetDecoder<unknown>;\n readonly decode: (input: AssetDecoderInput<unknown>) => Promise<Result<unknown, AssetLoadError>>;\n references: number;\n}\n\nexport interface DecoderRegistryOptions {\n readonly scopeId?: string;\n}\n\nexport class DecoderRegistry {\n private readonly dispatch = new Map<string, DecoderEntry>();\n private readonly scopeId: string;\n private disposed = false;\n\n constructor(options: DecoderRegistryOptions = {}) {\n this.scopeId = options.scopeId ?? 'asset-runtime';\n }\n\n install<P, K extends string>(kind: AssetKind<P, K>, decoder: AssetDecoder<P>): AssetDecoderLease {\n if (this.disposed) throw new TypeError('asset runtime decoder registry is disposed');\n const normalizedDecoder = decoder as AssetDecoder<unknown>;\n const existing = this.dispatch.get(kind.kind);\n if (existing !== undefined) {\n if (existing.decoder !== normalizedDecoder) {\n throw new TypeError(`duplicate decoder kind \"${kind.kind}\"`);\n }\n existing.references += 1;\n return this.createLease(kind.kind, existing);\n }\n const identity = Symbol(kind.kind);\n const entry: DecoderEntry = {\n identity,\n decoder: normalizedDecoder,\n decode: (input) =>\n decoder.decode(input as AssetDecoderInput<P>) as Promise<Result<unknown, AssetLoadError>>,\n references: 1,\n };\n this.dispatch.set(kind.kind, entry);\n return this.createLease(kind.kind, entry);\n }\n\n private createLease(kind: string, entry: DecoderEntry): AssetDecoderLease {\n let released = false;\n return {\n kind,\n dispose: () => {\n if (released) return;\n released = true;\n entry.references -= 1;\n if (entry.references === 0 && this.dispatch.get(kind)?.identity === entry.identity) {\n this.dispatch.delete(kind);\n }\n },\n };\n }\n\n has<P, K extends string>(kind: AssetKind<P, K>): boolean {\n return this.dispatch.has(kind.kind);\n }\n\n load<P, K extends string>(\n kind: AssetKind<P, K>,\n input: AssetDecoderInput<P>,\n ): Promise<Result<P, AssetLoadError>> {\n return this.decode(kind, input);\n }\n\n loadByKind(\n kind: string,\n input: AssetDecoderInput<unknown>,\n ): Promise<Result<unknown, AssetLoadError>> {\n if (this.disposed) return Promise.resolve(err(disposedError(this.scopeId)));\n const entry = this.dispatch.get(kind);\n if (entry === undefined) {\n return Promise.resolve(\n err({\n code: 'asset-decoder-missing',\n expected: `an active decoder for kind \"${kind}\"`,\n hint: 'install the owner decoder lease before loading this kind',\n detail: { kind },\n }),\n );\n }\n return this.decodeEntry(kind, entry, input);\n }\n\n async decode<P, K extends string>(\n kind: AssetKind<P, K>,\n input: AssetDecoderInput<P>,\n ): Promise<Result<P, AssetLoadError>> {\n if (this.disposed) return err(disposedError(this.scopeId));\n if (input.signal.aborted) return err(cancelledError(input.envelope.guid));\n const entry = this.dispatch.get(kind.kind);\n if (entry === undefined) {\n return err({\n code: 'asset-decoder-missing',\n expected: `an active decoder for kind \"${kind.kind}\"`,\n hint: 'install the owner decoder lease before loading this kind',\n detail: { kind: kind.kind },\n });\n }\n return (await this.decodeEntry(kind.kind, entry, input)) as Result<P, AssetLoadError>;\n }\n\n private async decodeEntry(\n kind: string,\n entry: DecoderEntry,\n input: AssetDecoderInput<unknown>,\n ): Promise<Result<unknown, AssetLoadError>> {\n if (this.disposed) return err(disposedError(this.scopeId));\n if (input.signal.aborted) return err(cancelledError(input.envelope.guid));\n try {\n const result = await entry.decode(input);\n if (this.disposed) return err(disposedError(this.scopeId));\n if (this.dispatch.get(kind)?.identity !== entry.identity) {\n return err(supersededError(input.envelope.guid, kind));\n }\n if (input.signal.aborted) return err(cancelledError(input.envelope.guid));\n return result.ok ? ok(freezeRuntimePayload(result.value)) : result;\n } catch {\n return err({\n code: 'asset-decode-failed',\n expected: `decoder for kind \"${kind}\" to return a Result`,\n hint: 'inspect the owner decoder and retry the current publication',\n detail: { guid: input.envelope.guid, kind },\n });\n }\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.dispatch.clear();\n }\n}\n\nfunction cancelledError(guid: string): AssetLoadError {\n return {\n code: 'asset-load-cancelled',\n expected: 'the request AbortSignal to remain live until decode completes',\n hint: 'retry with a live AbortSignal when the request is still needed',\n detail: { guid },\n };\n}\n\nfunction disposedError(scopeId: string): AssetLoadError {\n return {\n code: 'asset-runtime-disposed',\n expected: 'an active asset runtime decoder scope',\n hint: 'obtain a new Registry from the current realm',\n detail: { scopeId },\n };\n}\n\nfunction supersededError(guid: string, kind: string): AssetLoadError {\n return {\n code: 'asset-superseded',\n expected: `the decoder lease for kind \"${kind}\" to remain current until decode completes`,\n hint: 'retry the current publication after reinstalling its owner decoder',\n detail: { guid, generation: 0 },\n };\n}\n","import type {\n AssetEnvelopeV2,\n AssetLoadError,\n AssetPublicationTuple,\n PackV2,\n Result,\n} from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\n\nexport interface PackReaderOptions {\n readonly fetcher?: typeof globalThis.fetch;\n}\n\nexport type VerifiedPack = PackV2<unknown>;\n\nfunction invalid(guid: string, reason: string): Result<never, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a verified Pack v2 envelope with complete runtime artifacts',\n hint: 're-cook the Pack v2 publication and retry the current tuple',\n detail: { guid, reason },\n });\n}\n\nfunction frozen<T>(value: T): T {\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) frozen(child);\n }\n return value;\n}\n\nfunction sameTuple(left: AssetPublicationTuple, right: AssetPublicationTuple): boolean {\n return (\n left.scopeId === right.scopeId &&\n left.generation === right.generation &&\n left.digest === right.digest &&\n left.outputSetDigest === right.outputSetDigest\n );\n}\n\nexport class PackReader {\n private readonly fetcher: typeof globalThis.fetch | undefined;\n private readonly verified = new Map<string, VerifiedPack>();\n private readonly pending = new Map<string, Promise<Result<VerifiedPack, AssetLoadError>>>();\n\n constructor(options: PackReaderOptions = {}) {\n // An injected fetcher is an explicit transport lease and is fixed for the\n // reader lifetime. With no injection, resolve the host fetch at read time:\n // App assembly can precede a dev/test host installing its transport.\n this.fetcher = options.fetcher?.bind(globalThis);\n }\n\n async read(\n packageUrl: string,\n expected: AssetPublicationTuple,\n signal: AbortSignal,\n ): Promise<Result<VerifiedPack, AssetLoadError>> {\n if (signal.aborted) return err(this.cancelled(packageUrl));\n const key = this.key(packageUrl, expected);\n const cached = this.verified.get(key);\n if (cached !== undefined) return ok(cached);\n const active = this.pending.get(key);\n if (active !== undefined) return active;\n const request = this.fetchAndVerify(packageUrl, expected, signal);\n this.pending.set(key, request);\n const result = await request;\n this.pending.delete(key);\n if (result.ok) this.verified.set(key, result.value);\n return result;\n }\n\n private async fetchAndVerify(\n packageUrl: string,\n expected: AssetPublicationTuple,\n signal: AbortSignal,\n ): Promise<Result<VerifiedPack, AssetLoadError>> {\n let response: Response;\n try {\n const fetcher = this.fetcher ?? globalThis.fetch.bind(globalThis);\n response = await fetcher(packageUrl, { signal });\n } catch (_cause) {\n if (signal.aborted) return err(this.cancelled(packageUrl));\n return err({\n code: 'asset-fetch-failed',\n expected: 'HTTP 200 for the current Pack URL',\n hint: 'verify the package locator and republish the Pack',\n detail: { guid: packageUrl, packageUrl },\n });\n }\n if (!response.ok) {\n return err({\n code: 'asset-fetch-failed',\n expected: 'HTTP 200 for the current Pack URL',\n hint: 'verify the package locator and republish the Pack',\n detail: { guid: packageUrl, packageUrl },\n });\n }\n let value: unknown;\n try {\n value = await response.json();\n } catch {\n return invalid(packageUrl, 'invalid JSON');\n }\n return this.verify(value, expected);\n }\n\n private key(packageUrl: string, tuple: AssetPublicationTuple): string {\n return `${packageUrl}\\u0000${tuple.scopeId}\\u0000${tuple.generation}\\u0000${tuple.digest}\\u0000${tuple.outputSetDigest}`;\n }\n\n verify(value: unknown, expected: AssetPublicationTuple): Result<VerifiedPack, AssetLoadError> {\n if (value === null || typeof value !== 'object') return invalid('', 'Pack is not an object');\n const pack = value as Partial<PackV2<unknown>>;\n if (pack.schemaVersion !== '2.0.0' || pack.kind !== 'internal-text-package') {\n return invalid('', 'schemaVersion or kind');\n }\n if (\n typeof pack.scopeId !== 'string' ||\n !Number.isSafeInteger(pack.generation) ||\n typeof pack.digest !== 'string' ||\n typeof pack.outputSetDigest !== 'string' ||\n !sameTuple(pack as AssetPublicationTuple, expected)\n ) {\n return invalid('', 'publication tuple mismatch');\n }\n if (!Array.isArray(pack.assets)) return invalid('', 'assets');\n const guids = new Set<string>();\n for (const raw of pack.assets) {\n const asset = raw as Partial<AssetEnvelopeV2<unknown>>;\n const guid = typeof asset.guid === 'string' ? asset.guid : '';\n if (guid.length === 0 || guids.has(guid.toLowerCase()))\n return invalid(guid, 'duplicate guid');\n guids.add(guid.toLowerCase());\n if (\n typeof asset.kind !== 'string' ||\n asset.payload === undefined ||\n !Array.isArray(asset.refs) ||\n asset.refs.some((ref) => typeof ref !== 'string') ||\n asset.artifacts === null ||\n typeof asset.artifacts !== 'object'\n ) {\n return invalid(guid, 'asset envelope fields');\n }\n for (const [artifactKey, descriptor] of Object.entries(asset.artifacts)) {\n if (!this.validArtifact(guid, artifactKey, descriptor)) {\n return invalid(guid, `artifact ${artifactKey}`);\n }\n }\n }\n return ok(frozen(pack as VerifiedPack));\n }\n\n private validArtifact(_guid: string, key: string, value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n const descriptor = value as Record<string, unknown>;\n const integrity = descriptor.integrity;\n return (\n key.length > 0 &&\n typeof descriptor.path === 'string' &&\n descriptor.path.length > 0 &&\n typeof descriptor.mediaType === 'string' &&\n descriptor.mediaType.length > 0 &&\n (descriptor.contentEncoding === 'identity' || descriptor.contentEncoding === 'zstd') &&\n Number.isSafeInteger(descriptor.byteLength) &&\n Number(descriptor.byteLength) >= 0 &&\n integrity !== null &&\n typeof integrity === 'object' &&\n (integrity as Record<string, unknown>).algorithm === 'sha256' &&\n typeof (integrity as Record<string, unknown>).digest === 'string' &&\n /^sha256:[0-9a-f]{64}$/i.test(String((integrity as Record<string, unknown>).digest))\n );\n }\n\n private cancelled(guid: string): AssetLoadError {\n return {\n code: 'asset-load-cancelled',\n expected: 'the request AbortSignal to remain live while reading the Pack',\n hint: 'retry with a live AbortSignal when the request is still needed',\n detail: { guid },\n };\n }\n}\n","import type {\n Asset,\n AssetArtifactReader,\n AssetDecoder,\n AssetDecoderInput,\n AssetDecoderLease,\n AssetKind,\n AssetLoadError,\n BuiltinAssetKind,\n BuiltinAssetPayload,\n Result,\n} from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport type { CatalogSource } from '../catalog-source.js';\nimport { ArtifactCache } from './artifact-cache.js';\nimport { AssetGraph, type AssetGraphSnapshot } from './asset-graph.js';\nimport { CatalogSession, type CatalogSessionOptions } from './catalog-session.js';\nimport { DecoderRegistry } from './decoder-registry.js';\nimport { freezeRuntimePayload } from './immutable-payload.js';\nimport { PackReader } from './pack-reader.js';\nimport { validateRuntimeRow } from './validate-runtime-row.js';\n\nexport interface AssetRegistryOptions extends CatalogSessionOptions {\n readonly catalog: CatalogSource;\n readonly fetcher?: typeof globalThis.fetch;\n readonly maxConcurrentReads?: number;\n}\n\nexport interface AssetLoadOptions {\n readonly signal?: AbortSignal;\n}\n\nexport type AssetRegistrySnapshot = AssetGraphSnapshot;\n\nexport type AssetRegistrySnapshotCounters = AssetRegistrySnapshot['counters'];\n\nexport interface AssetRegistry {\n installDecoder<P, K extends string>(\n kind: AssetKind<P, K>,\n decoder: AssetDecoder<P>,\n ): AssetDecoderLease;\n load<K extends BuiltinAssetKind>(\n guid: string,\n kind: K,\n options?: AssetLoadOptions,\n ): Promise<Result<BuiltinAssetPayload<K>, AssetLoadError>>;\n load<P, K extends string>(\n guid: string,\n kind: AssetKind<P, K>,\n options?: AssetLoadOptions,\n ): Promise<Result<P, AssetLoadError>>;\n snapshot(): AssetRegistrySnapshot;\n subscribe(listener: (snapshot: AssetRegistrySnapshot) => void): () => void;\n dispose(): void;\n}\n\n/** Internal render projection; the root Registry keeps only its five actions. */\nexport interface AssetRegistryResolver {\n readonly epoch: number;\n lookup<T extends Asset>(guid: string): T | undefined;\n guidOf(asset: Asset): string | undefined;\n}\n\nconst REGISTRY_RESOLVER = Symbol.for('forgeax.assets-runtime.registry-resolver');\ntype RegistryWithResolver = AssetRegistry & {\n [REGISTRY_RESOLVER]?: AssetRegistryResolver;\n};\n\nexport function getAssetRegistryResolver(registry: AssetRegistry): AssetRegistryResolver {\n const resolver = (registry as RegistryWithResolver)[REGISTRY_RESOLVER];\n if (resolver === undefined) {\n throw new TypeError('AssetRegistry resolver is not owned by this asset runtime');\n }\n return resolver;\n}\n\nfunction missing(guid: string): AssetLoadError {\n return {\n code: 'asset-not-found',\n expected: `the current Catalog to contain GUID \"${guid}\"`,\n hint: 'inspect the producer Catalog and rebuild the missing publication',\n detail: { guid },\n };\n}\n\nfunction mismatch(guid: string, expectedKind: string, actualKind: string): AssetLoadError {\n return {\n code: 'asset-kind-mismatch',\n expected: `Catalog kind \"${actualKind}\" to match \"${expectedKind}\"`,\n hint: 'pass the Catalog kind or the matching custom AssetKind token',\n detail: { guid, expectedKind, actualKind },\n };\n}\n\nfunction artifactError(guid: string, reason: string): AssetLoadError {\n return {\n code: 'asset-integrity-failed',\n expected: 'the verified artifact byte length and digest',\n hint: 'verify the artifact digest and recook the Pack',\n detail: {\n guid,\n artifactKey: reason,\n expectedDigest: 'descriptor integrity',\n actualDigest: reason,\n },\n };\n}\n\nconst ASSET_GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction invalidGuid(guid: string): AssetLoadError {\n return {\n code: 'asset-guid-invalid',\n expected: 'a 36-character dash-form asset GUID',\n hint: 'pass the producer GUID from the current Catalog row',\n detail: { guid },\n };\n}\n\nexport function createAssetRegistry(options: AssetRegistryOptions): AssetRegistry {\n const session = new CatalogSession(options.catalog, options);\n const reader = new PackReader(options.fetcher === undefined ? {} : { fetcher: options.fetcher });\n const cache = new ArtifactCache();\n const decoders = new DecoderRegistry(\n options.scopeId === undefined ? {} : { scopeId: options.scopeId },\n );\n const graph = new AssetGraph<{ readonly value: unknown; readonly refs: readonly string[] }>({\n ...(options.maxConcurrentReads === undefined\n ? {}\n : { maxConcurrentReads: options.maxConcurrentReads }),\n read: async (guid, signal) => {\n const row = session.current(guid);\n if (row === undefined) return err(missing(guid));\n const validated = validateRuntimeRow(row);\n if (!validated.ok) return validated;\n const publication = validated.value.publication;\n const tuple = {\n scopeId: session.snapshot().scopeId,\n generation: publication.generation,\n digest: publication.digest,\n outputSetDigest: publication.outputSetDigest,\n };\n const pack = await reader.read(row.packageUrl, tuple, signal);\n if (!pack.ok) return pack;\n const envelope = pack.value.assets.find(\n (asset) => asset.guid.toLowerCase() === guid.toLowerCase(),\n );\n if (envelope === undefined) return err(missing(guid));\n const artifacts: AssetArtifactReader = {\n read: (descriptor) => {\n const integrity = descriptor.integrity;\n if (integrity === undefined)\n return Promise.resolve(err(artifactError(guid, descriptor.path)));\n const key = `${tuple.scopeId}:${tuple.generation}:${tuple.outputSetDigest}:${integrity.digest}`;\n return cache.read(key, async () => {\n const url = resolveArtifactUrl(row.packageUrl, descriptor.path);\n let response: Response;\n try {\n response = await (options.fetcher ?? globalThis.fetch)(url, { signal });\n } catch {\n return err(artifactError(guid, descriptor.path));\n }\n if (!response.ok) return err(artifactError(guid, descriptor.path));\n const bytes = new Uint8Array(await response.arrayBuffer());\n if (descriptor.byteLength === undefined || bytes.byteLength !== descriptor.byteLength) {\n return err(artifactError(guid, descriptor.path));\n }\n const actualDigest = await sha256(bytes);\n if (actualDigest !== descriptor.integrity?.digest.toLowerCase()) {\n return err(artifactError(guid, `${descriptor.path}:${actualDigest}`));\n }\n return ok(bytes);\n });\n },\n };\n const input: AssetDecoderInput<unknown> = { envelope, artifacts, signal };\n const decoded = await decoders.loadByKind(envelope.kind, input);\n if (!decoded.ok) return decoded;\n return ok({ value: freezeRuntimePayload(decoded.value), refs: envelope.refs });\n },\n });\n\n let catalogEpoch = session.snapshot().epoch;\n const unsubscribeCatalog = session.subscribe((snapshot) => {\n if (snapshot.epoch === catalogEpoch) return;\n catalogEpoch = snapshot.epoch;\n graph.invalidateForCatalogChange(\n snapshot.stale ? undefined : [...snapshot.changed, ...snapshot.removed],\n );\n });\n\n const registry: AssetRegistry = {\n installDecoder: (kind, decoder) => decoders.install(kind, decoder),\n load: (async (\n guid: string,\n kind: BuiltinAssetKind | AssetKind<unknown, string>,\n loadOptions: AssetLoadOptions = {},\n ): Promise<Result<unknown, AssetLoadError>> => {\n if (!ASSET_GUID_PATTERN.test(guid)) return err(invalidGuid(guid));\n const expectedKind = typeof kind === 'string' ? kind : kind.kind;\n const started = await session.start();\n if (!started.ok) return err(started.error);\n if (session.snapshot().stale) {\n const reconciled = await session.reconcile();\n if (!reconciled.ok) return err(reconciled.error);\n const discontinuity = session.discontinuity();\n if (discontinuity !== undefined) return err(discontinuity);\n }\n const row = session.current(guid);\n if (row === undefined) return err(missing(guid));\n if (row.kind !== expectedKind) return err(mismatch(guid, expectedKind, row.kind));\n const result = await graph.load(guid, loadOptions.signal);\n return result.ok ? ok(result.value.value) : result;\n }) as AssetRegistry['load'],\n snapshot: () => graph.snapshot(),\n subscribe: (listener) => graph.subscribe(listener),\n dispose: () => {\n graph.dispose();\n unsubscribeCatalog();\n decoders.dispose();\n cache.clear();\n session.dispose();\n },\n };\n const resolver: AssetRegistryResolver = {\n get epoch() {\n return graph.snapshot().epoch;\n },\n lookup: <T extends Asset>(guid: string) => graph.lookup(guid) as T | undefined,\n guidOf: (asset: Asset) => graph.guidOf(asset),\n };\n Object.defineProperty(registry, REGISTRY_RESOLVER, {\n value: resolver,\n enumerable: false,\n });\n return registry;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes as unknown as BufferSource);\n return `sha256:${Array.from(new Uint8Array(digest), (byte) =>\n byte.toString(16).padStart(2, '0'),\n ).join('')}`;\n}\n\nfunction resolveArtifactUrl(packageUrl: string, path: string): string {\n const separator = packageUrl.lastIndexOf('/');\n const packageDirectory = separator < 0 ? '' : packageUrl.slice(0, separator + 1);\n try {\n return new URL(path, packageDirectory).toString();\n } catch {\n return `${packageDirectory}${path.replace(/^\\//, '')}`;\n }\n}\n","import {\n createMaterialError,\n err,\n type MaterialErrorFor,\n type MaterialGenerationVector,\n ok,\n type Result,\n} from '@forgeax/engine-types';\n\nexport type { MaterialGenerationVector } from '@forgeax/engine-types';\n\nexport interface MaterialCachedArtifact {\n readonly bytes: Uint8Array;\n}\n\nexport type MaterialStaleGenerationError =\n MaterialErrorFor<'material-specialization-stale-generation'>;\n\nfunction sameVector(left: MaterialGenerationVector, right: MaterialGenerationVector): boolean {\n const names = new Set([...Object.keys(left.dependencies), ...Object.keys(right.dependencies)]);\n return [...names].every((name) => left.dependencies[name] === right.dependencies[name]);\n}\n\nexport class MaterialGenerationCache {\n readonly #resolved = new Map<string, Promise<unknown>>();\n readonly #resolvedByMaterial = new Map<string, Set<string>>();\n readonly #resolvedKeys = new Map<string, string>();\n readonly #artifacts = new Map<string, MaterialCachedArtifact>();\n readonly #generations = new Map<string, number>();\n readonly #errors = new Map<string, MaterialStaleGenerationError>();\n readonly #materialDependencies = new Map<string, readonly string[]>();\n readonly #dependents = new Map<string, Set<string>>();\n\n resolve<T>(\n materialGuid: string,\n specializationKey: string,\n load: () => Promise<T>,\n publicationGeneration = 0,\n ): Promise<T> {\n const cacheKey = `${materialGuid}:${specializationKey}:${publicationGeneration}`;\n const previous = this.#resolved.get(cacheKey);\n if (previous !== undefined) return previous as Promise<T>;\n const promise = load();\n this.#resolved.set(cacheKey, promise);\n const resolvedKeys = this.#resolvedByMaterial.get(materialGuid) ?? new Set<string>();\n resolvedKeys.add(cacheKey);\n this.#resolvedByMaterial.set(materialGuid, resolvedKeys);\n void promise.then(\n (value) => {\n if (isStaleGenerationResult(value)) this.removeResolved(materialGuid, cacheKey, promise);\n },\n () => this.removeResolved(materialGuid, cacheKey, promise),\n );\n return promise;\n }\n\n linkResolved(materialGuid: string, specializationKey: string): void {\n this.#resolvedKeys.set(materialGuid, specializationKey);\n }\n\n getResolvedKey(materialGuid: string): string | undefined {\n return this.#resolvedKeys.get(materialGuid);\n }\n\n storeArtifact(key: string, artifact: MaterialCachedArtifact): void {\n this.#artifacts.set(key, artifact);\n }\n\n getArtifact(key: string): MaterialCachedArtifact | undefined {\n return this.#artifacts.get(key);\n }\n\n bump(dependency: string): number {\n const generation = (this.#generations.get(dependency) ?? 0) + 1;\n this.#generations.set(dependency, generation);\n for (const materialGuid of this.#dependents.get(dependency) ?? []) {\n for (const cacheKey of this.#resolvedByMaterial.get(materialGuid) ?? []) {\n this.#resolved.delete(cacheKey);\n }\n this.#resolvedByMaterial.delete(materialGuid);\n }\n return generation;\n }\n\n generationError(materialGuid: string): MaterialStaleGenerationError | undefined {\n return this.#errors.get(materialGuid);\n }\n\n async loadWithGeneration<T>(\n materialGuid: string,\n dependencies: readonly string[],\n load: (\n generation: MaterialGenerationVector,\n ) => Promise<{ readonly generation: MaterialGenerationVector; readonly value: T }>,\n ): Promise<Result<T, MaterialStaleGenerationError>> {\n const dependencySet = Object.freeze([...dependencies]);\n this.trackDependencies(materialGuid, dependencySet);\n for (let attempt = 0; attempt < 2; attempt += 1) {\n const generation = this.vector(dependencySet);\n const loaded = await load(generation);\n const observed = snapshotVector(loaded.generation);\n const current = this.vector(dependencySet);\n if (sameVector(observed, current)) {\n this.#errors.delete(materialGuid);\n return ok(loaded.value);\n }\n if (attempt === 1) {\n const error = staleGenerationError(materialGuid, dependencySet, observed, current);\n this.#errors.set(materialGuid, error);\n return err(error);\n }\n }\n const current = this.vector(dependencySet);\n return err(staleGenerationError(materialGuid, dependencySet, current, current));\n }\n\n private trackDependencies(materialGuid: string, dependencies: readonly string[]): void {\n const previous = this.#materialDependencies.get(materialGuid);\n if (previous !== undefined) {\n for (const dependency of previous) this.#dependents.get(dependency)?.delete(materialGuid);\n }\n this.#materialDependencies.set(materialGuid, dependencies);\n for (const dependency of dependencies) {\n const dependents = this.#dependents.get(dependency) ?? new Set<string>();\n dependents.add(materialGuid);\n this.#dependents.set(dependency, dependents);\n }\n }\n\n private removeResolved(materialGuid: string, cacheKey: string, promise: Promise<unknown>): void {\n if (this.#resolved.get(cacheKey) !== promise) return;\n this.#resolved.delete(cacheKey);\n const resolvedKeys = this.#resolvedByMaterial.get(materialGuid);\n if (resolvedKeys === undefined) return;\n resolvedKeys.delete(cacheKey);\n if (resolvedKeys.size === 0) this.#resolvedByMaterial.delete(materialGuid);\n }\n\n private vector(dependencies: readonly string[]): MaterialGenerationVector {\n return snapshotVector({\n dependencies: Object.fromEntries(\n dependencies.map((dependency) => [dependency, this.#generations.get(dependency) ?? 0]),\n ),\n });\n }\n}\n\nfunction snapshotVector(vector: MaterialGenerationVector): MaterialGenerationVector {\n return Object.freeze({ dependencies: Object.freeze({ ...vector.dependencies }) });\n}\n\nfunction staleGenerationError(\n material: string,\n dependencies: readonly string[],\n observed: MaterialGenerationVector,\n current: MaterialGenerationVector,\n): MaterialStaleGenerationError {\n const detail = Object.freeze({\n code: 'material-specialization-stale-generation' as const,\n material,\n dependencies,\n observed,\n current,\n });\n return Object.freeze(createMaterialError('material-specialization-stale-generation', detail));\n}\n\nfunction isStaleGenerationResult(value: unknown): boolean {\n if (value === null || typeof value !== 'object') return false;\n const result = value as { readonly ok?: unknown; readonly error?: unknown };\n if (result.ok !== false || result.error === null || typeof result.error !== 'object')\n return false;\n return (\n (result.error as { readonly code?: unknown }).code ===\n 'material-specialization-stale-generation'\n );\n}\n","import type { MaterialReady } from './loader.js';\n\n/**\n * Read-only facts for one GUID after the MaterialReady gate succeeds.\n * `status` is retained for the existing runtime API; `readiness` is the\n * machine-readable first-level field for inspection consumers. This owner\n * does not invent transport provenance or compare transport URLs.\n */\nexport interface MaterialRuntimeInfo {\n readonly materialGuid: string;\n readonly readiness: 'ready';\n readonly publicationGeneration: number;\n readonly specializationKey: string;\n readonly artifactDigest: string;\n readonly layoutIdentity: string;\n readonly dependencies: readonly string[];\n readonly profile: string;\n readonly sourceClosure: readonly string[];\n readonly parameterContract: MaterialReady['parameterContract'];\n readonly refs: MaterialReady['record']['refs'];\n readonly receipt: MaterialReady['record']['receipt'];\n readonly status: 'Ready';\n}\n\nexport function inspectMaterialRuntime(ready: MaterialReady): MaterialRuntimeInfo {\n return {\n materialGuid: ready.materialGuid,\n readiness: 'ready',\n publicationGeneration: ready.publicationGeneration,\n specializationKey: ready.specializationKey,\n artifactDigest: ready.artifactDigest,\n layoutIdentity: ready.record.receipt.identity.layoutIdentity,\n dependencies: [\n ...ready.record.refs.parent,\n ...ready.record.refs.textures,\n ...ready.record.refs.samplers,\n ...ready.record.refs.modules,\n ],\n profile: ready.record.receipt.profile,\n sourceClosure: ready.sourceClosure,\n parameterContract: ready.parameterContract,\n refs: ready.record.refs,\n receipt: ready.record.receipt,\n status: 'Ready',\n };\n}\n","import type { Plugin } from '@forgeax/engine-plugin';\nimport type { Loader } from '@forgeax/engine-types';\n\nimport type { AssetRegistry } from './asset-registry';\nimport type { PackLoader } from './loader-registry';\n\ndeclare module '@forgeax/engine-plugin' {\n interface EngineContextServices {\n assets?: AssetRegistry;\n }\n}\n\n/** Provide one renderer-owned asset registry to the current Cordis realm. */\nexport function assetsPlugin(assets: AssetRegistry): Plugin {\n return {\n name: 'assets',\n provide: 'assets',\n apply(ctx) {\n ctx.provide('assets', assets);\n },\n };\n}\n\n/** Reversibly register one runtime asset loader. */\nexport function assetLoaderPlugin(loader: Loader<unknown>): Plugin {\n return {\n name: `asset-loader:${loader.kind}`,\n inject: ['assets'],\n apply(ctx) {\n const assets = ctx.assets;\n if (assets === undefined) throw new Error('asset loader plugin requires the assets service');\n ctx.effect(() => assets.loaders.register(loader), `assets/loader:${loader.kind}`);\n },\n };\n}\n\n/** Reversibly register one pack loader. */\nexport function packLoaderPlugin(loader: PackLoader): Plugin {\n return {\n name: `pack-loader:${loader.kind}`,\n inject: ['assets'],\n apply(ctx) {\n const assets = ctx.assets;\n if (assets === undefined) throw new Error('pack loader plugin requires the assets service');\n ctx.effect(() => assets.loaders.registerPackLoader(loader), `assets/pack:${loader.kind}`);\n },\n };\n}\n","import type { World } from '@forgeax/engine-ecs';\nimport type { Asset, Handle, Result, TextureAsset } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\n\nexport type TilesetRuntimeErrorCode =\n | 'tileset-atlas-not-found'\n | 'tileset-atlas-stale'\n | 'tileset-atlas-kind-mismatch';\n\nexport interface TilesetRuntimeError {\n readonly code: TilesetRuntimeErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: {\n readonly guid: string;\n readonly actualKind?: string;\n };\n}\n\nexport interface ResolvedTilesetRuntime {\n readonly guid: string;\n readonly payload: TextureAsset;\n readonly handle: Handle<'TextureAsset', 'shared'>;\n}\n\nexport type TilesetAtlasLookup = Asset | { readonly code: 'stale' } | undefined;\n\n/** Project one durable atlas GUID into the current World at the tilemap owner. */\nexport function resolveTilesetRuntime(\n world: World,\n guid: string,\n lookup: (guid: string) => TilesetAtlasLookup,\n): Result<ResolvedTilesetRuntime, TilesetRuntimeError> {\n if (guid.length === 0) {\n return err({\n code: 'tileset-atlas-not-found',\n expected: 'a non-empty durable atlas GUID',\n hint: 'load the atlas payload before extracting the tilemap',\n detail: { guid },\n });\n }\n const payload = lookup(guid);\n if (payload === undefined) {\n return err({\n code: 'tileset-atlas-not-found',\n expected: `a loaded texture payload for atlas GUID ${guid}`,\n hint: 'load or retain the atlas before extracting the tilemap',\n detail: { guid },\n });\n }\n if ('code' in payload) {\n return err({\n code: 'tileset-atlas-stale',\n expected: `a current texture payload for atlas GUID ${guid}`,\n hint: 'rebuild the stale atlas projection before extracting the tilemap',\n detail: { guid },\n });\n }\n if (payload.kind !== 'texture') {\n return err({\n code: 'tileset-atlas-kind-mismatch',\n expected: 'a texture atlas payload',\n hint: `replace atlas GUID ${guid} with a texture asset`,\n detail: { guid, actualKind: payload.kind },\n });\n }\n return ok({\n guid,\n payload,\n handle: world.internSharedRef('TextureAsset', payload),\n });\n}\n"]}
|