@forgeax/engine-assets-runtime 0.1.3 → 0.1.6

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.
Files changed (313) hide show
  1. package/README.md +442 -175
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/__tests__/aabb.unit.test.d.ts +2 -0
  4. package/dist/__tests__/aabb.unit.test.d.ts.map +1 -0
  5. package/dist/__tests__/artifact-integrity.unit.test.d.ts +2 -0
  6. package/dist/__tests__/artifact-integrity.unit.test.d.ts.map +1 -0
  7. package/dist/__tests__/artifact-io.unit.test.d.ts +2 -0
  8. package/dist/__tests__/artifact-io.unit.test.d.ts.map +1 -0
  9. package/dist/__tests__/asset-evidence-sdk.integration.test.d.ts +2 -0
  10. package/dist/__tests__/asset-evidence-sdk.integration.test.d.ts.map +1 -0
  11. package/dist/__tests__/asset-evidence.unit.test.d.ts +2 -0
  12. package/dist/__tests__/asset-evidence.unit.test.d.ts.map +1 -0
  13. package/dist/__tests__/asset-kind.unit.test.d.ts +2 -0
  14. package/dist/__tests__/asset-kind.unit.test.d.ts.map +1 -0
  15. package/dist/__tests__/asset-registry-catalog-reconcile.integration.test.d.ts +2 -0
  16. package/dist/__tests__/asset-registry-catalog-reconcile.integration.test.d.ts.map +1 -0
  17. package/dist/__tests__/asset-registry-catalog-reconcile.unit.test.d.ts +2 -0
  18. package/dist/__tests__/asset-registry-catalog-reconcile.unit.test.d.ts.map +1 -0
  19. package/dist/__tests__/asset-registry-catalog.unit.test.d.ts +2 -0
  20. package/dist/__tests__/asset-registry-catalog.unit.test.d.ts.map +1 -0
  21. package/dist/__tests__/asset-registry.pack-cache.test.d.ts +2 -0
  22. package/dist/__tests__/asset-registry.pack-cache.test.d.ts.map +1 -0
  23. package/dist/__tests__/asset-registry.unit.test.d.ts +2 -0
  24. package/dist/__tests__/asset-registry.unit.test.d.ts.map +1 -0
  25. package/dist/__tests__/asset-runtime-error-code-owner.test-d.d.ts +2 -0
  26. package/dist/__tests__/asset-runtime-error-code-owner.test-d.d.ts.map +1 -0
  27. package/dist/__tests__/catalog-replica.unit.test.d.ts +2 -0
  28. package/dist/__tests__/catalog-replica.unit.test.d.ts.map +1 -0
  29. package/dist/__tests__/catalog-source-v2.unit.test.d.ts +2 -0
  30. package/dist/__tests__/catalog-source-v2.unit.test.d.ts.map +1 -0
  31. package/dist/__tests__/catalog-source.unit.test.d.ts +2 -0
  32. package/dist/__tests__/catalog-source.unit.test.d.ts.map +1 -0
  33. package/dist/__tests__/catalog-subscription-order.unit.test.d.ts +2 -0
  34. package/dist/__tests__/catalog-subscription-order.unit.test.d.ts.map +1 -0
  35. package/dist/__tests__/catalog-subscription.unit.test.d.ts +2 -0
  36. package/dist/__tests__/catalog-subscription.unit.test.d.ts.map +1 -0
  37. package/dist/__tests__/decode-image-bytes-pass-through.test.d.ts +2 -0
  38. package/dist/__tests__/decode-image-bytes-pass-through.test.d.ts.map +1 -0
  39. package/dist/__tests__/decode-image-bytes.browser.test.d.ts +2 -0
  40. package/dist/__tests__/decode-image-bytes.browser.test.d.ts.map +1 -0
  41. package/dist/__tests__/decode-image-bytes.test-d.d.ts +2 -0
  42. package/dist/__tests__/decode-image-bytes.test-d.d.ts.map +1 -0
  43. package/dist/__tests__/decode-image-bytes.test.d.ts +2 -0
  44. package/dist/__tests__/decode-image-bytes.test.d.ts.map +1 -0
  45. package/dist/__tests__/dynamic-texture-store.unit.test.d.ts +2 -0
  46. package/dist/__tests__/dynamic-texture-store.unit.test.d.ts.map +1 -0
  47. package/dist/__tests__/errors-asset.unit.test.d.ts +2 -0
  48. package/dist/__tests__/errors-asset.unit.test.d.ts.map +1 -0
  49. package/dist/__tests__/inline-pack-loaders.unit.test.d.ts +2 -0
  50. package/dist/__tests__/inline-pack-loaders.unit.test.d.ts.map +1 -0
  51. package/dist/__tests__/instantiate-context.unit.test.d.ts +2 -0
  52. package/dist/__tests__/instantiate-context.unit.test.d.ts.map +1 -0
  53. package/dist/__tests__/instantiate-publication-fence.unit.test.d.ts +2 -0
  54. package/dist/__tests__/instantiate-publication-fence.unit.test.d.ts.map +1 -0
  55. package/dist/__tests__/instantiate.unit.test.d.ts +2 -0
  56. package/dist/__tests__/instantiate.unit.test.d.ts.map +1 -0
  57. package/dist/__tests__/loader-input-contract.unit.test.d.ts +2 -0
  58. package/dist/__tests__/loader-input-contract.unit.test.d.ts.map +1 -0
  59. package/dist/__tests__/loader-registry.unit.test.d.ts +2 -0
  60. package/dist/__tests__/loader-registry.unit.test.d.ts.map +1 -0
  61. package/dist/__tests__/material-dependency-invalidation.unit.test.d.ts +2 -0
  62. package/dist/__tests__/material-dependency-invalidation.unit.test.d.ts.map +1 -0
  63. package/dist/__tests__/material-generation-cache.unit.test.d.ts +2 -0
  64. package/dist/__tests__/material-generation-cache.unit.test.d.ts.map +1 -0
  65. package/dist/__tests__/material-load-consumer.test-d.d.ts +2 -0
  66. package/dist/__tests__/material-load-consumer.test-d.d.ts.map +1 -0
  67. package/dist/__tests__/material-ready.integration.test.d.ts +2 -0
  68. package/dist/__tests__/material-ready.integration.test.d.ts.map +1 -0
  69. package/dist/__tests__/material-stale-generation.unit.test.d.ts +2 -0
  70. package/dist/__tests__/material-stale-generation.unit.test.d.ts.map +1 -0
  71. package/dist/__tests__/mesh-bin-morph-v3.test.d.ts +2 -0
  72. package/dist/__tests__/mesh-bin-morph-v3.test.d.ts.map +1 -0
  73. package/dist/__tests__/mesh-bin.unit.test.d.ts +2 -0
  74. package/dist/__tests__/mesh-bin.unit.test.d.ts.map +1 -0
  75. package/dist/__tests__/mipmap-generator.unit.test.d.ts +2 -0
  76. package/dist/__tests__/mipmap-generator.unit.test.d.ts.map +1 -0
  77. package/dist/__tests__/pack-artifact-transcode-model-owner.test.d.ts +2 -0
  78. package/dist/__tests__/pack-artifact-transcode-model-owner.test.d.ts.map +1 -0
  79. package/dist/__tests__/pack-basis-load.integration.test.d.ts +2 -0
  80. package/dist/__tests__/pack-basis-load.integration.test.d.ts.map +1 -0
  81. package/dist/__tests__/payload-validate.unit.test.d.ts +2 -0
  82. package/dist/__tests__/payload-validate.unit.test.d.ts.map +1 -0
  83. package/dist/__tests__/plugin.test.d.ts +2 -0
  84. package/dist/__tests__/plugin.test.d.ts.map +1 -0
  85. package/dist/__tests__/registry-concurrency.bench.test.d.ts +2 -0
  86. package/dist/__tests__/registry-concurrency.bench.test.d.ts.map +1 -0
  87. package/dist/__tests__/registry-failure-retry.integration.test.d.ts +2 -0
  88. package/dist/__tests__/registry-failure-retry.integration.test.d.ts.map +1 -0
  89. package/dist/__tests__/registry-load-graph.integration.test.d.ts +2 -0
  90. package/dist/__tests__/registry-load-graph.integration.test.d.ts.map +1 -0
  91. package/dist/__tests__/registry-load-state.unit.test.d.ts +2 -0
  92. package/dist/__tests__/registry-load-state.unit.test.d.ts.map +1 -0
  93. package/dist/__tests__/registry-package-cache.unit.test.d.ts +2 -0
  94. package/dist/__tests__/registry-package-cache.unit.test.d.ts.map +1 -0
  95. package/dist/__tests__/registry-public-ready.unit.test.d.ts +2 -0
  96. package/dist/__tests__/registry-public-ready.unit.test.d.ts.map +1 -0
  97. package/dist/__tests__/resolve-asset-handle.unit.test.d.ts +2 -0
  98. package/dist/__tests__/resolve-asset-handle.unit.test.d.ts.map +1 -0
  99. package/dist/__tests__/scene-handle-fields.unit.test.d.ts +2 -0
  100. package/dist/__tests__/scene-handle-fields.unit.test.d.ts.map +1 -0
  101. package/dist/__tests__/scene-payload.unit.test.d.ts +2 -0
  102. package/dist/__tests__/scene-payload.unit.test.d.ts.map +1 -0
  103. package/dist/__tests__/scene-publication-fence.test.d.ts +2 -0
  104. package/dist/__tests__/scene-publication-fence.test.d.ts.map +1 -0
  105. package/dist/__tests__/scriptable-pack-public-surface.test-d.d.ts +2 -0
  106. package/dist/__tests__/scriptable-pack-public-surface.test-d.d.ts.map +1 -0
  107. package/dist/__tests__/static-rig.integration.test.d.ts +2 -0
  108. package/dist/__tests__/static-rig.integration.test.d.ts.map +1 -0
  109. package/dist/__tests__/validate-material.unit.test.d.ts +2 -0
  110. package/dist/__tests__/validate-material.unit.test.d.ts.map +1 -0
  111. package/dist/__tests__/video-pack-loader.integration.test.d.ts +2 -0
  112. package/dist/__tests__/video-pack-loader.integration.test.d.ts.map +1 -0
  113. package/dist/aabb.d.ts +3 -0
  114. package/dist/aabb.d.ts.map +1 -0
  115. package/dist/asset-registry.d.ts +552 -0
  116. package/dist/asset-registry.d.ts.map +1 -0
  117. package/dist/builtin-asset-registry.d.ts +22 -0
  118. package/dist/builtin-asset-registry.d.ts.map +1 -0
  119. package/dist/catalog-source.d.ts +2 -1
  120. package/dist/catalog-source.d.ts.map +1 -1
  121. package/dist/decode-image-bytes.d.ts +57 -0
  122. package/dist/decode-image-bytes.d.ts.map +1 -0
  123. package/dist/dynamic-texture-store.d.ts +89 -0
  124. package/dist/dynamic-texture-store.d.ts.map +1 -0
  125. package/dist/errors/asset.d.ts +201 -0
  126. package/dist/errors/asset.d.ts.map +1 -0
  127. package/dist/handles.d.ts +141 -0
  128. package/dist/handles.d.ts.map +1 -0
  129. package/dist/image-error.d.ts +6 -0
  130. package/dist/image-error.d.ts.map +1 -0
  131. package/dist/index.d.ts +32 -3
  132. package/dist/index.d.ts.map +1 -1
  133. package/dist/index.mjs +7218 -114
  134. package/dist/index.mjs.map +1 -1
  135. package/dist/internal.d.ts +2 -1
  136. package/dist/internal.d.ts.map +1 -1
  137. package/dist/internal.mjs +317 -3
  138. package/dist/internal.mjs.map +1 -1
  139. package/dist/loader-registry.d.ts +63 -0
  140. package/dist/loader-registry.d.ts.map +1 -0
  141. package/dist/loaders/inline-pack.d.ts +72 -0
  142. package/dist/loaders/inline-pack.d.ts.map +1 -0
  143. package/dist/loaders/mesh-bin.d.ts +21 -0
  144. package/dist/loaders/mesh-bin.d.ts.map +1 -0
  145. package/dist/loaders/pack-artifact.d.ts +20 -0
  146. package/dist/loaders/pack-artifact.d.ts.map +1 -0
  147. package/dist/material/dependency-graph.d.ts +9 -0
  148. package/dist/material/dependency-graph.d.ts.map +1 -0
  149. package/dist/material/generation-cache.d.ts +24 -0
  150. package/dist/material/generation-cache.d.ts.map +1 -0
  151. package/dist/material/inspection.d.ts +24 -0
  152. package/dist/material/inspection.d.ts.map +1 -0
  153. package/dist/material/loader.d.ts +59 -0
  154. package/dist/material/loader.d.ts.map +1 -0
  155. package/dist/material/runtime-shader.d.ts +14 -0
  156. package/dist/material/runtime-shader.d.ts.map +1 -0
  157. package/dist/mesh-bin.d.ts +3 -0
  158. package/dist/mesh-bin.d.ts.map +1 -0
  159. package/dist/mipmap-generator.d.ts +132 -0
  160. package/dist/mipmap-generator.d.ts.map +1 -0
  161. package/dist/payload-validate.d.ts +60 -0
  162. package/dist/payload-validate.d.ts.map +1 -0
  163. package/dist/plugin.d.ts +16 -0
  164. package/dist/plugin.d.ts.map +1 -0
  165. package/dist/registry/artifact-io.d.ts +16 -0
  166. package/dist/registry/artifact-io.d.ts.map +1 -0
  167. package/dist/registry/asset-evidence.d.ts +13 -0
  168. package/dist/registry/asset-evidence.d.ts.map +1 -0
  169. package/dist/registry/catalog-state.d.ts +47 -0
  170. package/dist/registry/catalog-state.d.ts.map +1 -0
  171. package/dist/registry/catalog.d.ts +48 -0
  172. package/dist/registry/catalog.d.ts.map +1 -0
  173. package/dist/registry/instantiate.d.ts +153 -0
  174. package/dist/registry/instantiate.d.ts.map +1 -0
  175. package/dist/registry/load-by-guid.d.ts +247 -0
  176. package/dist/registry/load-by-guid.d.ts.map +1 -0
  177. package/dist/registry/load-state.d.ts +26 -0
  178. package/dist/registry/load-state.d.ts.map +1 -0
  179. package/dist/registry/runtime-projection.d.ts +16 -0
  180. package/dist/registry/runtime-projection.d.ts.map +1 -0
  181. package/dist/registry/scene-publication-fence.d.ts +38 -0
  182. package/dist/registry/scene-publication-fence.d.ts.map +1 -0
  183. package/dist/registry/validate-material.d.ts +77 -0
  184. package/dist/registry/validate-material.d.ts.map +1 -0
  185. package/dist/resolve-asset-handle.d.ts +43 -0
  186. package/dist/resolve-asset-handle.d.ts.map +1 -0
  187. package/dist/resolve-tileset-runtime.d.ts +23 -0
  188. package/dist/resolve-tileset-runtime.d.ts.map +1 -0
  189. package/dist/scene-handle-fields.d.ts +88 -0
  190. package/dist/scene-handle-fields.d.ts.map +1 -0
  191. package/dist/scene-payload.d.ts +15 -0
  192. package/dist/scene-payload.d.ts.map +1 -0
  193. package/dist/wire-default-loaders.d.ts +29 -0
  194. package/dist/wire-default-loaders.d.ts.map +1 -0
  195. package/package.json +22 -9
  196. package/src/__tests__/aabb.unit.test.ts +97 -0
  197. package/src/__tests__/artifact-integrity.unit.test.ts +99 -0
  198. package/src/__tests__/artifact-io.unit.test.ts +127 -0
  199. package/src/__tests__/asset-evidence-sdk.integration.test.ts +32 -0
  200. package/src/__tests__/asset-evidence.unit.test.ts +32 -0
  201. package/src/__tests__/{asset-kind.test.ts → asset-kind.unit.test.ts} +1 -1
  202. package/src/__tests__/asset-registry-catalog-reconcile.integration.test.ts +74 -0
  203. package/src/__tests__/asset-registry-catalog-reconcile.unit.test.ts +89 -0
  204. package/src/__tests__/asset-registry-catalog.unit.test.ts +170 -0
  205. package/src/__tests__/asset-registry.pack-cache.test.ts +96 -0
  206. package/src/__tests__/asset-registry.unit.test.ts +511 -0
  207. package/src/__tests__/asset-runtime-error-code-owner.test-d.ts +63 -0
  208. package/src/__tests__/catalog-replica.unit.test.ts +196 -0
  209. package/src/__tests__/catalog-source-v2.unit.test.ts +158 -0
  210. package/src/__tests__/catalog-source.unit.test.ts +126 -0
  211. package/src/__tests__/catalog-subscription-order.unit.test.ts +65 -0
  212. package/src/__tests__/catalog-subscription.unit.test.ts +28 -0
  213. package/src/__tests__/decode-image-bytes-pass-through.test.ts +34 -0
  214. package/src/__tests__/decode-image-bytes.browser.test.ts +102 -0
  215. package/src/__tests__/decode-image-bytes.test-d.ts +108 -0
  216. package/src/__tests__/decode-image-bytes.test.ts +90 -0
  217. package/src/__tests__/decode-image-mime-owner.test.ts +2 -5
  218. package/src/__tests__/dynamic-texture-store.unit.test.ts +115 -0
  219. package/src/__tests__/errors-asset.unit.test.ts +92 -0
  220. package/src/__tests__/inline-pack-loaders.unit.test.ts +548 -0
  221. package/src/__tests__/instantiate-context.unit.test.ts +65 -0
  222. package/src/__tests__/instantiate-publication-fence.unit.test.ts +158 -0
  223. package/src/__tests__/instantiate.unit.test.ts +684 -0
  224. package/src/__tests__/loader-input-contract.unit.test.ts +89 -0
  225. package/src/__tests__/loader-registry.unit.test.ts +101 -0
  226. package/src/__tests__/material-dependency-invalidation.unit.test.ts +14 -0
  227. package/src/__tests__/material-generation-cache.unit.test.ts +46 -0
  228. package/src/__tests__/material-load-consumer.test-d.ts +42 -0
  229. package/src/__tests__/material-ready.integration.test.ts +492 -0
  230. package/src/__tests__/material-stale-generation.unit.test.ts +152 -0
  231. package/src/__tests__/mesh-bin-morph-v3.test.ts +22 -0
  232. package/src/__tests__/mesh-bin.unit.test.ts +152 -0
  233. package/src/__tests__/mipmap-generator.unit.test.ts +202 -0
  234. package/src/__tests__/pack-artifact-transcode-model-owner.test.ts +32 -0
  235. package/src/__tests__/pack-basis-load.integration.test.ts +168 -0
  236. package/src/__tests__/payload-validate.unit.test.ts +285 -0
  237. package/src/__tests__/plugin.test.ts +55 -0
  238. package/src/__tests__/registry-concurrency.bench.test.ts +40 -0
  239. package/src/__tests__/registry-failure-retry.integration.test.ts +69 -0
  240. package/src/__tests__/registry-load-graph.integration.test.ts +246 -0
  241. package/src/__tests__/registry-load-state.unit.test.ts +35 -0
  242. package/src/__tests__/registry-package-cache.unit.test.ts +53 -0
  243. package/src/__tests__/registry-public-ready.unit.test.ts +38 -0
  244. package/src/__tests__/resolve-asset-handle.unit.test.ts +238 -0
  245. package/src/__tests__/scene-handle-fields.unit.test.ts +129 -0
  246. package/src/__tests__/scene-payload.unit.test.ts +151 -0
  247. package/src/__tests__/scene-publication-fence.test.ts +129 -0
  248. package/src/__tests__/scriptable-pack-public-surface.test-d.ts +16 -0
  249. package/src/__tests__/static-rig.integration.test.ts +8 -0
  250. package/src/__tests__/validate-material.unit.test.ts +359 -0
  251. package/src/__tests__/video-pack-loader.integration.test.ts +83 -0
  252. package/src/aabb.ts +107 -0
  253. package/src/asset-registry.ts +2040 -0
  254. package/src/builtin-asset-registry.ts +164 -0
  255. package/src/catalog-source.ts +14 -70
  256. package/src/decode-image-bytes.ts +126 -0
  257. package/src/dynamic-texture-store.ts +234 -0
  258. package/src/errors/asset.ts +347 -0
  259. package/src/handles.ts +180 -0
  260. package/src/image-error.ts +45 -0
  261. package/src/index.ts +177 -19
  262. package/src/internal.ts +2 -0
  263. package/src/loader-registry.ts +157 -0
  264. package/src/loaders/inline-pack.ts +837 -0
  265. package/src/loaders/mesh-bin.ts +304 -0
  266. package/src/loaders/pack-artifact.ts +665 -0
  267. package/src/material/dependency-graph.ts +46 -0
  268. package/src/material/generation-cache.ts +177 -0
  269. package/src/material/inspection.ts +46 -0
  270. package/src/material/loader.ts +326 -0
  271. package/src/material/runtime-shader.ts +133 -0
  272. package/src/mesh-bin.ts +5 -0
  273. package/src/mipmap-generator.ts +450 -0
  274. package/src/payload-validate.ts +573 -0
  275. package/src/plugin.ts +48 -0
  276. package/src/registry/artifact-io.ts +259 -0
  277. package/src/registry/asset-evidence.ts +51 -0
  278. package/src/registry/catalog-state.ts +409 -0
  279. package/src/registry/catalog.ts +369 -0
  280. package/src/registry/instantiate.ts +1056 -0
  281. package/src/registry/load-by-guid.ts +1657 -0
  282. package/src/registry/load-state.ts +115 -0
  283. package/src/registry/runtime-projection.ts +63 -0
  284. package/src/registry/scene-publication-fence.ts +256 -0
  285. package/src/registry/validate-material.ts +386 -0
  286. package/src/resolve-asset-handle.ts +147 -0
  287. package/src/resolve-tileset-runtime.ts +72 -0
  288. package/src/scene-handle-fields.ts +221 -0
  289. package/src/scene-payload.ts +207 -0
  290. package/src/wire-default-loaders.ts +79 -0
  291. package/dist/__tests__/asset-graph-red.integration.test.d.ts +0 -2
  292. package/dist/__tests__/asset-graph-red.integration.test.d.ts.map +0 -1
  293. package/dist/__tests__/asset-kind.test.d.ts +0 -2
  294. package/dist/__tests__/asset-kind.test.d.ts.map +0 -1
  295. package/dist/__tests__/asset-registry-core.integration.test.d.ts +0 -2
  296. package/dist/__tests__/asset-registry-core.integration.test.d.ts.map +0 -1
  297. package/dist/__tests__/asset-registry-public-api.test-d.d.ts +0 -2
  298. package/dist/__tests__/asset-registry-public-api.test-d.d.ts.map +0 -1
  299. package/dist/__tests__/asset-runtime-core-lifecycle.integration.test.d.ts +0 -2
  300. package/dist/__tests__/asset-runtime-core-lifecycle.integration.test.d.ts.map +0 -1
  301. package/dist/__tests__/asset-runtime-snapshot.unit.test.d.ts +0 -2
  302. package/dist/__tests__/asset-runtime-snapshot.unit.test.d.ts.map +0 -1
  303. package/dist/__tests__/catalog-session-red.unit.test.d.ts +0 -2
  304. package/dist/__tests__/catalog-session-red.unit.test.d.ts.map +0 -1
  305. package/dist/__tests__/registry-lifecycle-red.integration.test.d.ts +0 -2
  306. package/dist/__tests__/registry-lifecycle-red.integration.test.d.ts.map +0 -1
  307. package/src/__tests__/asset-graph-red.integration.test.ts +0 -113
  308. package/src/__tests__/asset-registry-core.integration.test.ts +0 -161
  309. package/src/__tests__/asset-registry-public-api.test-d.ts +0 -31
  310. package/src/__tests__/asset-runtime-core-lifecycle.integration.test.ts +0 -79
  311. package/src/__tests__/asset-runtime-snapshot.unit.test.ts +0 -23
  312. package/src/__tests__/catalog-session-red.unit.test.ts +0 -276
  313. package/src/__tests__/registry-lifecycle-red.integration.test.ts +0 -80
@@ -0,0 +1,2040 @@
1
+ // @forgeax/engine-assets-runtime - AssetRegistry v2 (feat-20260513-guid-asset-package-system).
2
+ //
3
+ // Entrypoints (feat-20260614 M8 de-handle cut, D-15/D-17/D-19): the registry
4
+ // is a GUID->payload catalogue. It no longer mints or maps handles -- column
5
+ // handles are minted on the World via `world.allocSharedRef('Kind', payload)`,
6
+ // and resolved through the two-tier `resolveAssetHandle` (BuiltinAssetRegistry
7
+ // process-static slots [1,1024) + per-World `world.sharedRefs` slots >=1024).
8
+ //
9
+ // - catalog<T extends Asset>(guid, asset): Result<T, AssetError>
10
+ // stores the GUID->payload entry loadByGuid resolves (dev/inline path)
11
+ // - parseGuid(guidStr): AssetGuid
12
+ // - lookup(guid): Asset | undefined (catalogued payload, no fetch)
13
+ // - loadByGuid<T extends Asset>(guid): Promise<Result<T, AssetError | ImageError | RhiError>>
14
+ // returns the PAYLOAD T (never a handle, D-17)
15
+ // dev/fallback: synchronous catalogue lookup wrapped in Promise
16
+ // prod: fetch(packIndexUrl) -> parse catalog -> fetch entry -> parse Asset
17
+ // - instantiate<T extends SceneAsset>(handle, world, parent?): Result<EntityHandle, ...>
18
+ // handle is a `world.allocSharedRef('SceneAsset', payload)` column handle
19
+ // - inspect(): InspectSnapshot
20
+ //
21
+ // v1 load(url) removed in feat-20260513-guid-asset-package-system (w12).
22
+ // loadByGuid is the replacement; M4/w23 adds real fetch-from-pack-index.
23
+ //
24
+ // feat-20260514-ecs-children-instances-managed-buffer-array M3 / w15: the
25
+ // `createInstancedBuffer` / `updateInstancedBuffer` / `getInstancedGpuBuffer`
26
+ // triplet is removed alongside the `InstancedBufferAsset` POD; per-entity
27
+ // instance transforms are now stored inside the ECS via the `Instances {
28
+ // transforms: 'array<f32>' }` component (the RenderSystem record stage owns
29
+ // the GPU storage buffer + dirty-version upload). Asset closed-union narrows
30
+ // 5 -> 4; the registry surface loses the optional `RhiDevice` constructor
31
+ // argument (no remaining device consumer).
32
+ //
33
+ // Dual-backend audited: the registry is engine-agnostic (no @webgpu/types
34
+ // imports + no rhi-webgpu / rhi-wgpu references); the same instance drives
35
+ // both dual-impl shim backends through the @forgeax/engine-rhi interface
36
+ // SSOT at the consumer site.
37
+
38
+ import type { Component, EcsError, EntityHandle, World } from '@forgeax/engine-ecs';
39
+ import type { PackError } from '@forgeax/engine-pack/errors';
40
+ import { AssetGuid } from '@forgeax/engine-pack/guid';
41
+ import { deriveAssetName } from '@forgeax/engine-pack/name';
42
+ import { err, ok, type Result, type RhiError } from '@forgeax/engine-rhi';
43
+ import type { ShaderRegistry } from '@forgeax/engine-shader';
44
+ import {
45
+ ASSET_ERROR_HINTS,
46
+ type Asset,
47
+ type AssetEnvelope,
48
+ AssetError,
49
+ type AssetEvidence,
50
+ type AssetEvidenceError,
51
+ type AssetRef,
52
+ authoringCapabilityForAssetKind,
53
+ type CatalogEntry,
54
+ catalogOperationsFor,
55
+ type EngineMetrics,
56
+ type Handle,
57
+ handleSlot,
58
+ type ImageError,
59
+ type ImportTransport,
60
+ type InspectEntry,
61
+ type InspectSnapshot,
62
+ type Loader,
63
+ type MaterialAsset,
64
+ type MountOverride,
65
+ migrateLegacyMeshMaterialOverrides,
66
+ type Package,
67
+ type ParseErrorDetail,
68
+ type RuntimeAssetBinding,
69
+ type SceneAsset,
70
+ type SceneEntity,
71
+ type SceneInstanceMount,
72
+ type TagOf,
73
+ type TilesetAsset,
74
+ type TranscodeCaps,
75
+ type MeshAsset as TypesMeshAsset,
76
+ unwrapHandle,
77
+ } from '@forgeax/engine-types';
78
+ import {
79
+ BUILTIN_CUBE,
80
+ BUILTIN_CYLINDER,
81
+ BUILTIN_NINESLICE_QUAD,
82
+ BUILTIN_QUAD,
83
+ BUILTIN_SPHERE,
84
+ BUILTIN_TRIANGLE,
85
+ } from './builtin-asset-registry';
86
+ import type { LoaderRegistry } from './loader-registry';
87
+ import { createDefaultLoaderRegistry } from './wire-default-loaders';
88
+
89
+ /**
90
+ * Strip readonly from all fields of T. Used to mutate the MeshAsset.aabb slot
91
+ * after mesh validation passes (the interface is readonly but register-time
92
+ * computation writes the real AABB into the caller's placeholder).
93
+ */
94
+
95
+ // feat-20260705-runtime-tier2-decomposition M1 / w4 (D-4 F1): the pre-class
96
+ // constants, loaders, scene-payload / payload-validate / aabb helpers were
97
+ // straight-cut into sibling modules. The thin class value-imports only what its
98
+ // method bodies still reference; the full public consumer face (barrel + tests)
99
+ // is preserved via the `export ... from` re-export block below (pre-w14 shim,
100
+ // removed when consumers repoint in w14/w15).
101
+ import { withMeshAabb } from './aabb';
102
+ import type { CatalogListener, CatalogSource } from './catalog-source';
103
+ import {
104
+ BUILTIN_MESH_GUIDS,
105
+ HANDLE_CUBE,
106
+ HANDLE_CYLINDER,
107
+ HANDLE_NINESLICE_QUAD,
108
+ HANDLE_QUAD,
109
+ HANDLE_SPHERE,
110
+ HANDLE_TRIANGLE,
111
+ } from './handles';
112
+ import type { MaterialLoadError, MaterialReady } from './material/loader';
113
+ import { installMaterialReadyShaders } from './material/runtime-shader';
114
+ import { inferAtlasExtent, validateMeshPayload, validateTilesetPayload } from './payload-validate';
115
+ import { ArtifactReadCache } from './registry/artifact-io';
116
+ import {
117
+ createRuntimeAssetEvidenceAdapter,
118
+ type RuntimeAssetEvidenceAdapter,
119
+ type RuntimeEvidenceSource,
120
+ } from './registry/asset-evidence';
121
+ import { type CatalogRecord, fetchPackIndex } from './registry/catalog';
122
+ import { CatalogReplica, type CatalogReplicaSnapshot } from './registry/catalog-state';
123
+ import {
124
+ instantiateFlat as instantiateFlatImpl,
125
+ instantiate as instantiateImpl,
126
+ type PostSpawnHook,
127
+ resolveHandleGuid,
128
+ resolveMountsRec,
129
+ } from './registry/instantiate';
130
+ import {
131
+ loadByGuid as loadByGuidImpl,
132
+ parseAndReturnAsset as parseAndReturnAssetImpl,
133
+ parseAssetPayload as parseAssetPayloadImpl,
134
+ registerPackagesFromIndex,
135
+ } from './registry/load-by-guid';
136
+ import { LoadStateStore } from './registry/load-state';
137
+ import type {
138
+ ScenePublicationFence,
139
+ ScenePublicationFenceError,
140
+ } from './registry/scene-publication-fence';
141
+ import {
142
+ detectTileNeedsRepeatSampler,
143
+ materialShaderTextureFieldNames as materialShaderTextureFieldNamesImpl,
144
+ validateMaterialPasses,
145
+ validateSpriteSlices,
146
+ } from './registry/validate-material';
147
+ import { extractSceneEntityHandleGuids } from './scene-handle-fields';
148
+
149
+ // Public re-export surface (pre-w14 consumer face preservation): the extracted
150
+ // modules are the new SSOT; asset-registry re-exports them until w14/w15 repoint
151
+ // every consumer to the sibling modules / the new package.
152
+ export {
153
+ HANDLE_CUBE,
154
+ HANDLE_CYLINDER,
155
+ HANDLE_NINESLICE_QUAD,
156
+ HANDLE_QUAD,
157
+ HANDLE_SPHERE,
158
+ HANDLE_TRIANGLE,
159
+ } from './handles';
160
+ export {
161
+ animationClipLoader,
162
+ animationGraphLoader,
163
+ INLINE_PACK_LOADERS,
164
+ materialLoader,
165
+ meshLoader,
166
+ sceneLoader,
167
+ skeletonLoader,
168
+ skinLoader,
169
+ } from './loaders/inline-pack';
170
+ export {
171
+ equirectLoader,
172
+ fontLoader,
173
+ PACK_ARTIFACT_LOADERS,
174
+ textureLoader,
175
+ } from './loaders/pack-artifact';
176
+ export { type TilesetValidateOptions, validateTilesetPayload } from './payload-validate';
177
+
178
+ // ─── Re-exports for engine-runtime-local consumers ──────────────────────────
179
+ //
180
+ // Legacy re-exports: `Asset` widens to the 4-variant engine-types union;
181
+ // `MeshAsset` keeps the engine-types shape (with `attributes`). Consumers
182
+ // that previously imported from `./asset-registry` keep working through
183
+ // the type alias re-exports below.
184
+
185
+ export type { Asset, TypesMeshAsset as MeshAsset };
186
+
187
+ // D-15: the BUILTIN_* mesh payloads moved to builtin-asset-registry.ts (the
188
+ // process-static payload SSOT); the shared runtime vertex layout remains owned
189
+ // by @forgeax/engine-geometry.
190
+ // imported at the top of this file. The constructor still pre-populates the
191
+ // handle->payload map from those imports (the map itself retires in w49).
192
+
193
+ // feat-20260618-asset-and-pack-name-fields M3 (D-1 / D-3): the mutable runtime
194
+ // package object every GUID of the same import path shares. `assetGuids` grows
195
+ // as `registerPackage` adds GUIDs; `assetCount` (the engine-types `Package`
196
+ // view) is derived from `assetGuids.size`, never stored (#2 Derive). The public
197
+ // `packageOf(guid)` projects this to the readonly `Package` interface.
198
+ interface MutablePackage {
199
+ path: string;
200
+ readonly assetGuids: Set<string>;
201
+ }
202
+
203
+ // ─── Runtime brand helper ──────────────────────────────────────────────────
204
+ //
205
+ // AC-11 inspect() `.brand` is a 4-member string literal union mirroring the
206
+ // engine-types Asset discriminated union. Map a stored Asset value to its
207
+ // brand via the `.kind` discriminator (+ `.shadingModel` refinement for
208
+ // `MaterialAsset`, preserved for forward compatibility though the runtime
209
+ // brand stays at the asset-kind level per AC-11 spec).
210
+ //
211
+ // feat-20260514 M3 / w15: the `'InstancedBufferAsset'` brand is retired
212
+ // alongside the deleted POD + 3 registry methods; the runtime brand union
213
+ // shrinks 5 -> 4 to mirror the Asset closed-union shape.
214
+ // feat-20260514 w3: re-extends to 5 with the addition of the `'SceneAsset'`
215
+ // brand mirroring the new `'scene'` kind in the Asset discriminated union.
216
+ // feat-20260618-asset-and-pack-name-fields M1 / w3: AssetBrand moved to
217
+ // @forgeax/engine-types (public, single-entry discoverability per charter F1).
218
+ // feat-20260608-tilemap-object-layer-rendering M0: AssetBrand union grows
219
+ // 13 -> 14 with `'TilesetAsset'` in @forgeax/engine-types.
220
+
221
+ // feat-20260622 D-4/D-8: the 14-arm assetBrand switch and ASSET_BRAND Record
222
+ // table are both retired (PR #496 eliminated the brand concept entirely).
223
+ // New Asset union members no longer need a brand mapping; the closed union
224
+ // exhaustive switch in test-d files is the sole type-level guard.
225
+
226
+ // ─── Schema-driven material parse result (feat-20260523 M4-T01) ──────────
227
+ // ─── AssetRegistry class ────────────────────────────────────────────────────
228
+
229
+ /**
230
+ * Asset registry (instance-per-engine; `engine.assets: AssetRegistry | null`).
231
+ *
232
+ * The builtin meshes (`HANDLE_CUBE` / `HANDLE_TRIANGLE` / ...) are served by
233
+ * the process-static `BuiltinAssetRegistry`, so AI users see usable handles in
234
+ * the very first frame without registration ceremony (charter proposition 1).
235
+ *
236
+ * @example Catalogue a texture by GUID, load its payload, and bind a material:
237
+ * ```ts
238
+ * const guid = engine.assets.parseGuid('00000000-0000-7000-8000-000000000001');
239
+ * engine.assets.catalog(guid, myTexture); // GUID -> payload
240
+ * const res = await engine.assets.loadByGuid(guid); // payload (D-17)
241
+ * if (!res.ok) {
242
+ * switch (res.error.code) {
243
+ * case 'asset-not-found': // guid not catalogued
244
+ * }
245
+ * return;
246
+ * }
247
+ * const material = world.allocSharedRef('MaterialAsset', { // mint column handle
248
+ * kind: 'material',
249
+ * passes: [{ name: 'Forward', program: { module: 'forgeax::default-standard-pbr' }, tags: { LightMode: 'Forward' }, queue: 2000 }],
250
+ * values: { baseColorTexture: res.value },
251
+ * });
252
+ * world.spawn({ component: MeshRenderer, data: { materials: [material] } });
253
+ * ```
254
+ */
255
+
256
+ // bug-20260610 Fix B: parsed pack-file body stored in the fetchPackFile
257
+ // in-memory cache + in-flight dedup maps (D-4). Only the raw JSON shape is
258
+ // cached -- parseAssetPayload still runs per-call to look up the per-GUID
259
+ // entry (CON-2 register-before-recurse cycle safety).
260
+ export interface ParsedPackFile {
261
+ schemaVersion?: string;
262
+ kind?: string;
263
+ assets: Array<{
264
+ guid: string;
265
+ kind: string;
266
+ payload: Record<string, unknown>;
267
+ refs?: string[];
268
+ artifacts?: Record<string, import('@forgeax/engine-types').ArtifactDescriptor>;
269
+ }>;
270
+ }
271
+
272
+ export type CatalogReconcileError = AssetError;
273
+ export type CatalogReconcileResult = Result<CatalogReplicaSnapshot, CatalogReconcileError>;
274
+
275
+ function catalogSourceUnconfigured<T>(): Result<T, AssetError> {
276
+ return err(
277
+ new AssetError({
278
+ code: 'catalog-source-unconfigured',
279
+ expected: 'a configured catalog source',
280
+ hint: ASSET_ERROR_HINTS['catalog-source-unconfigured'],
281
+ }),
282
+ );
283
+ }
284
+
285
+ export class AssetRegistry {
286
+ private catalogSource: CatalogSource | undefined;
287
+ private catalogEnumerating: Promise<Result<readonly CatalogEntry[], AssetError>> | undefined;
288
+ private readonly catalogListeners = new Set<CatalogListener>();
289
+ private catalogSourceDispose: (() => void) | undefined;
290
+ private catalogReplica: CatalogReplica | undefined;
291
+ // feat-20260614 M8 (D-15 / D-17 / D-19): the registry is a GUID -> payload
292
+ // catalogue. It holds NO handle concept -- it cannot mint a column handle
293
+ // (it has no World). `loadByGuid` returns the PAYLOAD; column minting
294
+ // (`world.allocSharedRef`) is the caller's job on the ECS/render side.
295
+ // Sub-asset refs embedded in a payload stay as GUID strings (AssetGuid /
296
+ // dash-form), never minted at load time. Keyed by lowercased GUID string.
297
+ // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the
298
+ // extracted `./registry/validate-material` free functions (detectTileNeeds-
299
+ // RepeatSampler) can read it. No underscore + genuinely public is the
300
+ // lint-compliant exposure (D-internal R-internal-C ties `@internal` to `_`).
301
+ readonly assetCatalog: Map<string, AssetEnvelope<Asset>> = new Map();
302
+
303
+ /** Owner-injected component catalog used for scene breadcrumb projection. */
304
+ readonly componentCatalog: ReadonlyMap<string, Component>;
305
+
306
+ // feat-20260618-asset-and-pack-name-fields M3 (D-1): the package index that
307
+ // backs the two-segment asset identity `<packagePath>.<name>`. `packages`
308
+ // maps a lowercased GUID key to its `MutablePackage` (a shared object every
309
+ // GUID of the same import path points at), or `null` for assets with no
310
+ // package (catalog() inline + builtin, D-5). All three registration entry
311
+ // points (catalog / loadByGuid / builtin) funnel through the single
312
+ // `registerPackage` primitive so the XOR name invariant lands once (#1 SSOT).
313
+ private readonly packages: Map<string, MutablePackage | null> = new Map();
314
+
315
+ // Secondary index path -> shared MutablePackage so every GUID of the same
316
+ // import path points at one object (the 1->N promotion + assetCount derive
317
+ // depend on this sharing). Not a duplicate of `packages` (#2): `packages` is
318
+ // the per-GUID lookup; this is the per-path dedup used only inside
319
+ // registerPackage to find-or-create the shared object.
320
+ private readonly packageByPath: Map<string, MutablePackage> = new Map();
321
+
322
+ // Per-GUID stored display names now live on the asset envelope's `name` field
323
+ // (the single home, replacing the retired storedNameOf side table; D-6).
324
+ // resolveName reads `assetCatalog.get(key)?.name` as the `storedName` argument
325
+ // of deriveAssetName. `pendingNames` bridges the one ordering where a name is
326
+ // known before its envelope exists: the prod disk path registers the package
327
+ // (entry names) during resolveCatalogEntry, then catalogues the body later --
328
+ // catalog() drains the pending name into the new envelope, so nothing persists
329
+ // here once the envelope is in place.
330
+ private readonly pendingNames: Map<string, string> = new Map();
331
+
332
+ // ─── Prod pack-index fetch state (M4/w23) ──────────────────────────────
333
+ // When packIndexUrl is configured, loadByGuid fetches pack-index.json on
334
+ // first call, caches the parsed catalog in packIndexCache, then fetches
335
+ // each resource URL resolved against that index and registers the asset.
336
+ packIndexUrl: string | undefined = undefined;
337
+ packIndexCache: Map<string, CatalogRecord> | undefined = undefined;
338
+ /** Current browser-facing asset realm; absent for inline/shipped legacy use. */
339
+ runtimeBinding: RuntimeAssetBinding | undefined = undefined;
340
+
341
+ // tweak-20260609 M1: in-flight Map for recursive loadByGuid dedup + cycle
342
+ // prevention (D-5 / B-10). Maps guidKey → Promise<Result<Handle, ...>> so
343
+ // concurrent calls for the same GUID share the same fetch + register chain,
344
+ // and cycles (A→B→A) terminate when the second visit hits the in-flight
345
+ // entry for A instead of re-entering fetch.
346
+ readonly inFlight: Map<string, Promise<Result<unknown, AssetError | ImageError | RhiError>>> =
347
+ new Map();
348
+
349
+ // bug-20260610 Fix B (M3 / D-4): per-instance pack-file cache keyed by
350
+ // packageUrl (the .pack.json URL). `packFileInFlight` de-duplicates
351
+ // concurrent fetches; `packFileCache` stores resolved bodies so the
352
+ // same URL is fetched at most once per AssetRegistry lifetime (CON-6).
353
+ readonly packFileCache: Map<string, ParsedPackFile> = new Map();
354
+ readonly packFileInFlight: Map<string, Promise<ParsedPackFile>> = new Map();
355
+ readonly artifactCache = new ArtifactReadCache();
356
+ readonly loadState = new LoadStateStore();
357
+ /**
358
+ * Render-facing material readiness owned by the production GUID loader.
359
+ * The map stores the complete tuple result, including structured failures,
360
+ * so record code cannot silently fall back to a generic MaterialAsset.
361
+ */
362
+ readonly materialReadiness = new Map<string, MaterialReady | MaterialLoadError>();
363
+ private assetEvidenceAdapter: RuntimeAssetEvidenceAdapter = createRuntimeAssetEvidenceAdapter();
364
+
365
+ // feat-20260621-asset-registry-robustness-invalidate-inflight-cach F17c:
366
+ // per-GUID generation counter incremented on each invalidate(guid) call.
367
+ // loadByGuid captures this value at Promise creation and discards the
368
+ // result (returning asset-invalidated) if the generation has changed by
369
+ // the time the fetch completes.
370
+ // F22: invalidateAll increments a single globalGeneration counter instead,
371
+ // which invalidates every in-flight Promise regardless of GUID.
372
+ readonly generations: Map<string, number> = new Map();
373
+ globalGeneration: number = 0;
374
+ /**
375
+ * Monotonic payload-cache epoch. Render-side derived snapshots use this
376
+ * single stamp to skip re-walking an unchanged material parent chain on
377
+ * every frame; catalog/invalidation mutations advance it conservatively.
378
+ */
379
+ catalogEpoch: number = 0;
380
+
381
+ // F20: per-cache Promise queue to serialise packIndexCache write operations
382
+ // in transportOrFail. The "check -> new Map() -> set" three-step block is
383
+ // not atomic across concurrent transportOrFail calls; chaining through a
384
+ // single queue Promise ensures each patch completes before the next starts.
385
+ packIndexCachePatchQueue: Promise<void> = Promise.resolve();
386
+
387
+ // feat-20260527-sprite-nineslice M4 / w16 + w18 (D-5 + D-9): per-Renderer
388
+ // EngineMetrics shared with the runtime so register-time soft-warns
389
+ // (`nineslice.tile-needs-repeat-sampler` for sliceMode=1 + sampler not
390
+ // 'repeat') and runtime soft-warns (`nineslice.scale-too-small`) increment
391
+ // the SAME counter map. `createRenderer.ts` calls `assets.setMetrics(metrics)`
392
+ // immediately after constructing the registry; standalone test fixtures
393
+ // that do not go through `createRenderer` may leave this null and the
394
+ // soft-warn paths simply no-op (charter P9 graceful degradation: the
395
+ // structured fail-fast branches still fire; only the metric is dropped).
396
+ // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the
397
+ // extracted `./registry/validate-material` free functions (detectTileNeeds-
398
+ // RepeatSampler) can read + increment it. No underscore + genuinely public
399
+ // is the lint-compliant exposure (D-internal R-internal-C ties `@internal`
400
+ // to `_`).
401
+ metrics: EngineMetrics | null = null;
402
+
403
+ // feat-20260707 M5 / w33 (D-11): device texture-compression caps the Basis
404
+ // texture / equirect arms feed to `selectTranscodeTarget`. `createRenderer`
405
+ // projects `RhiCaps` -> `TranscodeCaps` and calls `setTranscodeCaps` right
406
+ // after construction (D-8 one-line projection). A standalone registry (test /
407
+ // headless) keeps the all-false default, which drives the uncompressed
408
+ // fallback path (section 8 P3, AC-04) rather than a hard failure.
409
+ transcodeCaps: TranscodeCaps = { bc: false, etc2: false, astc: false };
410
+
411
+ // feat-20260703-collect-nested-sceneinstance-to-mount-roundtrip M1 (D-1):
412
+ // origin reverse-index: a payload object -> its catalog GUID, for payloads
413
+ // that are NOT the current catalog identity. WeakMap so entries auto-GC when
414
+ // the world despawns and the object is no longer held by sharedRefs.
415
+ // _guidForAsset consults it after the catalog identity scan MISSes.
416
+ // SSOT for the "payload-to-GUID provenance" fact (architecture-principles #1).
417
+ //
418
+ // Two writers populate it:
419
+ // 1. instantiate (registry/instantiate.ts): the resolved SceneAsset copy ->
420
+ // its original catalog GUID (the deep-copied envelope is never the catalog
421
+ // identity).
422
+ // 2. feat-20260713 M4 / w15 (D-6, root cause a): catalog() records the
423
+ // SUPERSEDED payload here when re-cataloguing a GUID with a fresh object.
424
+ // A handle minted before the override still points at the old object; this
425
+ // keeps that object reverse-lookupable so save/collect resolves its GUID
426
+ // instead of failing with a GUID-unresolved error (the 2026-07-06 crash).
427
+ //
428
+ // Key type is `object` (not `SceneAsset`) because both material and scene
429
+ // payloads are recorded (material payloads flow through writer 2).
430
+ /** @internal */
431
+ _originIndex: WeakMap<object, string> = new WeakMap();
432
+
433
+ /**
434
+ * Construct a fresh registry pre-populated with the builtin cube + triangle
435
+ * mesh handles (`HANDLE_CUBE` / `HANDLE_TRIANGLE`).
436
+ *
437
+ * feat-20260514 M3 / w15: the previous optional `RhiDevice` constructor
438
+ * argument (consumed by the now-deleted `createInstancedBuffer` triplet)
439
+ * is removed; the registry surface is engine-agnostic again. Per-entity
440
+ * instance transforms now live inside the ECS `Instances { transforms:
441
+ * 'array<f32>' }` component; the RenderSystem record stage owns GPU
442
+ * storage buffer allocation + cap-gate.
443
+ */
444
+ // feat-20260603-asset-import-loader-injection M1 / w5 (D-7): the registry
445
+ // dispatches `parseAssetPayload` / the texture+font upstream branches through
446
+ // this `LoaderRegistry`. feat-20260623 M3 / w9: the loader registry is now
447
+ // internally built by `createDefaultLoaderRegistry()` (public readonly field)
448
+ // so host apps can reach `engine.assets.loaders.register(...)` without a
449
+ // constructor-injection slot or a phantom passthrough wrapper.
450
+ // The loader set is wired at construction from the complete ordinary Asset
451
+ // vocabulary (including video and audio) plus caller-supplied extensions.
452
+ // Assigned here so the optional loaders cannot appear after a load begins.
453
+ readonly loaders: LoaderRegistry;
454
+
455
+ // feat-20260603-asset-import-loader-injection M4 / w31 (AC-19 / AC-22):
456
+ // the optional `ImportTransport` is the *only* difference between the studio
457
+ // form (transport injected, dev DDC miss triggers lazy import) and the shipped
458
+ // form (transport absent, DDC miss fails fast with `asset-not-imported`).
459
+ // The load path AFTER a successful DDC fetch is identical in both forms --
460
+ // zero branching on transport (AC-23 key invariant). Set at construction (no
461
+ // setter, no illegal intermediate state), same D-7 stance as LoaderRegistry.
462
+ readonly importTransport: ImportTransport | undefined;
463
+
464
+ // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): optional post-spawn
465
+ // hook invoked by `instantiate` after the scene subtree spawns. The shipped
466
+ // implementation is runtime's `postSpawnResolveJoints` (auto-wire Skin.joints),
467
+ // injected at the sole production assembly point (createRenderer, w10). When
468
+ // absent (standalone / test registries), instantiate skips joint wiring
469
+ // silently. Public so the extracted `./registry/instantiate` free function can
470
+ // read it (D-internal R-internal-C ties `@internal` to a `_` prefix;
471
+ // genuinely-public is the lint-compliant exposure).
472
+ readonly postSpawnHook: PostSpawnHook | undefined;
473
+
474
+ /** @internal Stored for M2 validation; TS suppressor reference */
475
+ constructor(
476
+ // feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): public so the
477
+ // extracted `./registry/validate-material` free functions can read it. No
478
+ // underscore + genuinely public is the lint-compliant exposure (an
479
+ // `@internal` tag would require a `_` prefix per D-internal R-internal-C).
480
+ readonly shaderRegistry: ShaderRegistry,
481
+ importTransport?: ImportTransport | undefined,
482
+ // Caller-supplied loaders extend the ordinary default set. Duplicate kinds
483
+ // are rejected by LoaderRegistry so no consumer can observe replacement
484
+ // order as an accidental ownership rule.
485
+ extraLoaders?: readonly Loader[] | undefined,
486
+ // feat-20260705-runtime-tier2-decomposition M1 / w9 (D-1): optional
487
+ // post-spawn hook; createRenderer injects `postSpawnResolveJoints`.
488
+ postSpawnHook?: PostSpawnHook | undefined,
489
+ runtimeBinding?: RuntimeAssetBinding | undefined,
490
+ componentCatalog: ReadonlyMap<string, Component> = new Map(),
491
+ ) {
492
+ void this.shaderRegistry;
493
+ this.importTransport = importTransport;
494
+ this.postSpawnHook = postSpawnHook;
495
+ this.runtimeBinding = runtimeBinding;
496
+ this.componentCatalog = componentCatalog;
497
+ this.loaders = createDefaultLoaderRegistry(extraLoaders);
498
+ this.registerBuiltins();
499
+ }
500
+
501
+ /**
502
+ * Restore the engine-owned GUID catalogue after a runtime-realm transition.
503
+ *
504
+ * Builtin meshes are process-static engine assets, not game-owned catalog
505
+ * rows. A realm transition clears the user catalog and load caches, but must
506
+ * leave these assets addressable so a scene in the newly bound game can keep
507
+ * resolving its builtin mesh references.
508
+ */
509
+ private registerBuiltins(): void {
510
+ // feat-20260614 M8 (D-15): builtins are GUID-addressable catalogue rows.
511
+ // The builtin payloads also live process-static in BuiltinAssetRegistry
512
+ // (slot < BUILTIN_BASE) for handle-tier resolution; here they are
513
+ // catalogued by GUID so loadByGuid(builtinGuid) returns the payload and
514
+ // scene refs[] pointing at a builtin GUID resolve without a hand-
515
+ // maintained table (docs/feedbacks/2026-06-03 §6.2 Tier 0).
516
+ const builtinByHandle = new Map<number, Asset>([
517
+ [handleSlot(HANDLE_CUBE), BUILTIN_CUBE],
518
+ [handleSlot(HANDLE_TRIANGLE), BUILTIN_TRIANGLE],
519
+ [handleSlot(HANDLE_QUAD), BUILTIN_QUAD],
520
+ [handleSlot(HANDLE_SPHERE), BUILTIN_SPHERE],
521
+ [handleSlot(HANDLE_NINESLICE_QUAD), BUILTIN_NINESLICE_QUAD],
522
+ [handleSlot(HANDLE_CYLINDER), BUILTIN_CYLINDER],
523
+ ]);
524
+ for (const [handle, guidStr] of BUILTIN_MESH_GUIDS) {
525
+ const parsed = AssetGuid.parse(guidStr);
526
+ if (!parsed.ok) {
527
+ throw new Error(`[asset-registry] builtin GUID ${guidStr} is not a valid UUID`);
528
+ }
529
+ const payload = builtinByHandle.get(handleSlot(handle));
530
+ if (payload !== undefined)
531
+ this.assetCatalog.set(guidStr.toLowerCase(), {
532
+ guid: guidStr,
533
+ kind: payload.kind,
534
+ payload,
535
+ refs: [],
536
+ });
537
+ if (payload !== undefined) this.loadState.registerReady(guidStr, payload);
538
+ }
539
+ // D-5: builtin meshes have no import path and no source name -- register
540
+ // them with a null package so resolveName returns '' (the detectable
541
+ // "genuinely no name" signal). They are deliberately NOT given a synthetic
542
+ // package + derived name (memory builtin-guid-preregister-collides).
543
+ this._registerPackage(
544
+ null,
545
+ BUILTIN_MESH_GUIDS.map(([, guidStr]) => guidStr),
546
+ );
547
+ }
548
+
549
+ /**
550
+ * feat-20260527-sprite-nineslice M4 / w16 prep + w18 (D-5 + D-9): inject the
551
+ * per-Renderer `EngineMetrics` so register-time soft-warns can bump the same
552
+ * counter map the runtime reads through `renderer.metrics.snapshot()`. Called
553
+ * by `createRenderer` after constructing both the registry and the metrics
554
+ * instance; safe to skip in standalone tests (the soft-warn arms simply do
555
+ * not record).
556
+ */
557
+ setMetrics(metrics: EngineMetrics): void {
558
+ this.metrics = metrics;
559
+ }
560
+
561
+ /**
562
+ * feat-20260707 M5 / w33 (D-11): wire the device compression caps used by the
563
+ * Basis texture / equirect transcode arms. `createRenderer` calls this right
564
+ * after construction with `RhiCaps` projected to `TranscodeCaps` (D-8). Left
565
+ * at the all-false default, the loaders transcode to the uncompressed
566
+ * `rgba8unorm` / `rgba16float` fallback (AC-04, section 8 P3).
567
+ */
568
+ setTranscodeCaps(caps: TranscodeCaps): void {
569
+ this.transcodeCaps = caps;
570
+ }
571
+
572
+ /**
573
+ * Inject authoritative runtime evidence without importing CLI or Node policy.
574
+ * `inspect(guid)` and `verifyByGuid(guid)` return the shared state model; an
575
+ * omitted capability remains an explicit structured error, never a pass.
576
+ */
577
+ configureAssetEvidence(source: RuntimeEvidenceSource): void {
578
+ this.assetEvidenceAdapter = createRuntimeAssetEvidenceAdapter(source);
579
+ }
580
+
581
+ /**
582
+ * @internal — read the metrics handle for register-time soft-warn paths.
583
+ * Returns `null` when no `createRenderer` wired the registry to a renderer
584
+ * (the standalone-test path; the structured fail-fast branches still fire).
585
+ */
586
+ _getMetrics(): EngineMetrics | null {
587
+ return this.metrics;
588
+ }
589
+
590
+ /**
591
+ * @internal — reverse-lookup: find the GUID key for a catalogued asset
592
+ * payload by identity comparison (===). Returns the GUID string if found,
593
+ * `undefined` otherwise. This is the SSOT for the inline identity scan
594
+ * idiom that previously existed in two places (instantiate sceneGuidKey
595
+ * lookup and resolveSkinAsset skeleton match).
596
+ *
597
+ * Linear scan of the assetCatalog (Map<string, AssetEnvelope>). The O(n)
598
+ * cost is acceptable for save-path frequencies (OOS-2).
599
+ */
600
+ _guidForAsset(asset: Asset): string | undefined {
601
+ for (const [key, envelope] of this.assetCatalog) {
602
+ if (envelope.payload === asset) {
603
+ return key;
604
+ }
605
+ }
606
+ // feat-20260703 M1 (D-1): fallback to the origin reverse-index. Covers two
607
+ // MISS cases the catalog identity scan cannot: (1) _resolveSceneGuids deep
608
+ // copies — the copy is never the catalogued original; (2) feat-20260713 M4
609
+ // (D-6): a payload superseded by a catalog override, still live behind a
610
+ // handle minted before the override.
611
+ return this._originIndex.get(asset as object);
612
+ }
613
+
614
+ /** Return the production MaterialReady/Error result for one material GUID. */
615
+ getMaterialReadiness(guid: string): MaterialReady | MaterialLoadError | undefined {
616
+ return this.materialReadiness.get(guid.toLowerCase());
617
+ }
618
+
619
+ /** Record the canonical result produced by the production material loader. */
620
+ recordMaterialReadiness(guid: string, readiness: MaterialReady | MaterialLoadError): void {
621
+ this.materialReadiness.set(guid.toLowerCase(), readiness);
622
+ if (readiness.status === 'Ready') {
623
+ installMaterialReadyShaders(this.shaderRegistry, readiness);
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Configure a catalog URL for `loadByGuid`.
629
+ *
630
+ * Call this once during engine initialization with the URL where
631
+ * `pack-index.json` is served (emitted by `@forgeax/engine-vite-plugin-pack`
632
+ * during `vite build`). In a Vite dev host, use `configureRuntimeBinding`
633
+ * instead so the catalog remains bound to its scope and generation. The
634
+ * index is also the canonical base URL for every
635
+ * catalog entry: relative, root-relative, and absolute entry URLs are resolved
636
+ * against it before the registry fetches a pack body. After configuration,
637
+ * `loadByGuid` will fetch the catalog on its first invocation and cache it for
638
+ * subsequent calls.
639
+ *
640
+ * @example
641
+ * ```ts
642
+ * engine.assets.configurePackIndex('/pack-index.json');
643
+ * const payloadRes = await engine.assets.loadByGuid(guid); // payload, not a handle (D-17)
644
+ * ```
645
+ */
646
+ configurePackIndex(url: string): void {
647
+ this.packIndexUrl = url;
648
+ this.packIndexCache = undefined; // reset cache if URL changes
649
+ }
650
+
651
+ /**
652
+ * Atomically replace the browser-side asset realm. The binding owns the
653
+ * catalog URL and generation; no cache from the previous game survives the
654
+ * transition.
655
+ */
656
+ configureRuntimeBinding(binding: RuntimeAssetBinding): void {
657
+ this.clearCatalogSource();
658
+ this.runtimeBinding = binding;
659
+ this.configurePackIndex(binding.catalogUrl);
660
+ this.invalidateAll();
661
+ this.registerBuiltins();
662
+ }
663
+
664
+ /**
665
+ * feat-20260621 F17c: invalidate a single cached asset by GUID so the next
666
+ * `loadByGuid` performs a genuinely fresh fetch. Clears, for this GUID only:
667
+ * the catalogue entry, the in-flight dedup entry, the cached pack-file body
668
+ * (keyed by the index entry's packageUrl), and the pack-index entry. Then
669
+ * increments the per-GUID generation counter so any still in-flight Promise
670
+ * for this GUID discards its result (returns `asset-invalidated`). The body +
671
+ * index clears are targeted (other GUIDs' cached bodies and index entries
672
+ * survive); deleting the index entry forces `resolveCatalogEntry` to re-fetch
673
+ * the pack-index on the next load, re-resolving the packageUrl whose body
674
+ * cache was just dropped. No-op when the GUID is not catalogued.
675
+ *
676
+ * Does NOT touch `packages` (a re-load's registerPackage overwrites them; D-8)
677
+ * and does NOT trigger GPU resource release (OOS-1,
678
+ * q1 boundary: the asset is CPU-only; GPU resources follow the ECS).
679
+ *
680
+ * @param guid - Case-insensitive GUID string or AssetGuid.
681
+ */
682
+ invalidate(guid: string): void {
683
+ const guidKey = guid.toLowerCase();
684
+ // D-6: the stored name lives on the envelope; preserve it across the delete
685
+ // (the `packages` mapping survives, so resolveName must still see the name
686
+ // until a re-load's registerPackage overwrites it) by parking it on
687
+ // pendingNames -- the next catalog() of this GUID drains it back.
688
+ const survivingEnvelope = this.assetCatalog.get(guidKey);
689
+ const survivingName = survivingEnvelope?.name;
690
+ if (survivingName !== undefined) this.pendingNames.set(guidKey, survivingName);
691
+ if (survivingEnvelope !== undefined) this._originIndex.set(survivingEnvelope.payload, guidKey);
692
+ this.assetCatalog.delete(guidKey);
693
+ this.loadState.remove(guidKey);
694
+ this.materialReadiness.delete(guidKey);
695
+ // R-1 hard fix (research-decisions.md): delete inFlight entry so the
696
+ // next loadByGuid does not hit the old Promise whose generation no
697
+ // longer matches (AC-04 requires a fresh fetch, not asset-invalidated).
698
+ this.inFlight.delete(guidKey);
699
+ // Round-2 M-A: widen the clear so a COMPLETED reload re-fetches fresh
700
+ // bytes instead of serving the stale cached body. Ordering is load-bearing:
701
+ // read packageUrl from the index entry FIRST, then delete the body, then
702
+ // delete the index entry. Targeted delete (not wholesale undefined) keeps
703
+ // other GUIDs' cached bodies/index entries intact (per-GUID precision).
704
+ const entry = this.packIndexCache?.get(guidKey);
705
+ if (entry !== undefined) this.packFileCache.delete(entry.packageUrl);
706
+ this.packIndexCache?.delete(guidKey);
707
+ this.generations.set(guidKey, (this.generations.get(guidKey) ?? 0) + 1);
708
+ this.catalogEpoch++;
709
+ }
710
+
711
+ /**
712
+ * Adopt freshly loaded Mesh material slots into an object that is already
713
+ * pinned by live World shared refs. Geometry and GPU-backed fields deliberately
714
+ * remain untouched: this primitive is only for a default-material source
715
+ * override, never a general Mesh reimport. This is the atomic cutover: Catalog,
716
+ * Ready load state, and payload-to-GUID provenance must all name the same
717
+ * object after the call. Call only after invalidate(guid) + loadByGuid(guid)
718
+ * has completed successfully.
719
+ */
720
+ adoptReloadedMeshMaterialSlots(guid: string, livePayload: Asset): Result<Asset, AssetError> {
721
+ const key = guid.toLowerCase();
722
+ const envelope = this.assetCatalog.get(key);
723
+ const freshPayload = this.loadState.getReady<Asset>(key);
724
+ if (envelope === undefined || freshPayload === undefined || envelope.payload !== freshPayload) {
725
+ return err(
726
+ new AssetError({
727
+ code: 'asset-not-found',
728
+ expected: `GUID ${key} to have one freshly loaded Ready payload`,
729
+ hint: 'complete invalidate + loadByGuid before adopting a live Mesh identity',
730
+ }),
731
+ );
732
+ }
733
+ if (livePayload.kind !== 'mesh' || freshPayload.kind !== 'mesh') {
734
+ return err(
735
+ new AssetError({
736
+ code: 'asset-parse-failed',
737
+ expected: `GUID ${key} live and fresh payloads to both be MeshAsset`,
738
+ hint: 'use Mesh identity adoption only for a recooked MeshAsset',
739
+ }),
740
+ );
741
+ }
742
+ if (this._guidForAsset(livePayload) !== key) {
743
+ return err(
744
+ new AssetError({
745
+ code: 'asset-not-found',
746
+ expected: `live Mesh payload to retain GUID provenance for ${key}`,
747
+ hint: 'capture the catalogued live payload before invalidating and reloading the same GUID',
748
+ }),
749
+ );
750
+ }
751
+ if (livePayload === freshPayload) return ok(livePayload);
752
+
753
+ (livePayload as unknown as { materialSlots: TypesMeshAsset['materialSlots'] }).materialSlots =
754
+ freshPayload.materialSlots;
755
+ this._originIndex.set(freshPayload as object, key);
756
+ this.assetCatalog.set(key, { ...envelope, payload: livePayload });
757
+ this.loadState.registerReady(key, livePayload);
758
+ this.catalogEpoch++;
759
+ return ok(livePayload);
760
+ }
761
+
762
+ /**
763
+ * feat-20260621 F17c: invalidate ALL cached assets so the next `loadByGuid`
764
+ * re-fetches both the pack-index and the asset body. Clears assetCatalog,
765
+ * inFlight, and packFileCache (wholesale), and resets packIndexCache to
766
+ * `undefined` (NOT `.clear()` -- an empty Map would short-circuit
767
+ * `resolveCatalogEntry`'s `=== undefined` re-fetch guard and serve
768
+ * asset-not-imported for every later load; undefined forces a fresh
769
+ * fetchPackIndex). Then increments a single globalGeneration counter so every
770
+ * in-flight Promise (regardless of GUID) discards its result. Returns the
771
+ * number of assets that were catalogued before the call.
772
+ *
773
+ * Idempotent: second call on an already-empty catalogue returns clearedCount 0
774
+ * (AC-06). Does NOT trigger GPU resource release (OOS-1).
775
+ */
776
+ invalidateAll(): { clearedCount: number } {
777
+ const count = this.assetCatalog.size;
778
+ this.assetCatalog.clear();
779
+ this.loadState.clear();
780
+ this.materialReadiness.clear();
781
+ this.inFlight.clear();
782
+ this.globalGeneration++;
783
+ // Round-2 M-A: wholesale clear of the shared body cache, and reset the
784
+ // index cache to UNDEFINED (R2-1) -- NOT .clear(). packFileCache uses
785
+ // .clear() because fetchPackFile checks `.get(packageUrl)` per URL, so an
786
+ // empty Map correctly misses and re-fetches. packIndexCache uses =undefined
787
+ // because resolveCatalogEntry's re-fetch guard tests `=== undefined`; an
788
+ // empty Map would short-circuit it and serve asset-not-imported for every
789
+ // later load -- the exact F17b pollution this feat fixes. The asymmetry is
790
+ // intentional; do not normalise the two operations.
791
+ this.packFileCache.clear();
792
+ this.packIndexCache = undefined;
793
+ this.catalogEpoch++;
794
+ return { clearedCount: count };
795
+ }
796
+
797
+ /**
798
+ * Force a re-fetch of the configured pack-index NOW and repopulate the cache,
799
+ * so a synchronous `listCatalog()` immediately reflects assets added on disk
800
+ * since boot (a freshly imported GLB's sub-assets). `loadByGuid`'s lazy
801
+ * re-fetch only fires on a per-GUID miss and `invalidateAll()` merely clears
802
+ * the cache (leaving `listCatalog()` empty until the next load), so neither
803
+ * makes a Content Browser or `loadByGuid`-driven "Add to Scene" see a new
804
+ * asset without a page reload. This does.
805
+ *
806
+ * No-op (returns false) when no pack-index URL is configured (dev inline
807
+ * catalogue path) or the fetch fails — callers keep the stale cache rather
808
+ * than blanking it. Returns true when the cache was repopulated.
809
+ */
810
+ async refreshCatalog(): Promise<boolean> {
811
+ if (this.packIndexUrl === undefined) return false;
812
+ const result = await fetchPackIndex(this);
813
+ if (!result.ok) return false;
814
+ this.packIndexCache = result.value;
815
+ registerPackagesFromIndex(this, this.packIndexCache);
816
+ return true;
817
+ }
818
+
819
+ setCatalogSource(source: CatalogSource): void {
820
+ this.clearCatalogSource();
821
+ this.catalogSource = source;
822
+ this.catalogReplica = new CatalogReplica(source);
823
+ this.catalogSourceDispose = this.catalogReplica.subscribe((delta) => {
824
+ for (const listener of [...this.catalogListeners]) {
825
+ try {
826
+ listener(delta);
827
+ } catch {
828
+ // One host listener cannot prevent the remaining listeners from seeing a fact.
829
+ }
830
+ }
831
+ });
832
+ void this.catalogReplica.start();
833
+ }
834
+
835
+ /** Stop the catalog transport and remove its replica without clearing payload caches. */
836
+ clearCatalogSource(): void {
837
+ this.catalogReplica?.dispose();
838
+ this.catalogSourceDispose?.();
839
+ this.catalogSourceDispose = undefined;
840
+ this.catalogSource = undefined;
841
+ this.catalogReplica = undefined;
842
+ this.catalogEnumerating = undefined;
843
+ }
844
+
845
+ enumerateCatalog(): Promise<Result<readonly CatalogEntry[], AssetError>> {
846
+ if (this.catalogEnumerating !== undefined) return this.catalogEnumerating;
847
+ if (this.catalogSource === undefined || this.catalogReplica === undefined) {
848
+ return Promise.resolve(catalogSourceUnconfigured());
849
+ }
850
+ const promise = this.catalogReplica
851
+ .start()
852
+ .then((result) => (result.ok ? ok(result.value.entries) : result));
853
+ this.catalogEnumerating = promise;
854
+ void promise.then(() => {
855
+ this.catalogEnumerating = undefined;
856
+ });
857
+ return promise;
858
+ }
859
+
860
+ /** Read the immutable catalog projection folded by this registry. */
861
+ catalogSnapshot(): CatalogReplicaSnapshot | undefined {
862
+ return this.catalogReplica?.snapshot();
863
+ }
864
+
865
+ /** Explicitly recover the registry's single catalog replica from its configured source. */
866
+ reconcileCatalog(): Promise<CatalogReconcileResult> {
867
+ if (this.catalogSource === undefined || this.catalogReplica === undefined) {
868
+ return Promise.resolve(catalogSourceUnconfigured());
869
+ }
870
+ return this.catalogReplica.reconcile();
871
+ }
872
+
873
+ subscribeCatalog(listener: CatalogListener): () => void {
874
+ this.catalogListeners.add(listener);
875
+ return () => {
876
+ this.catalogListeners.delete(listener);
877
+ };
878
+ }
879
+
880
+ /**
881
+ * Materialise a `SceneAsset` into an existing `World` and return the
882
+ * synthetic root `Entity` (feat-20260514 w31 sugar wrapper; AC-03 +
883
+ * requirements §IN-3; M3: returns Entity not SceneInstanceId).
884
+ *
885
+ * Before spawning, handle-type component fields (e.g. `assetHandle`,
886
+ * `material`, `skeleton`) containing GUID strings are resolved to fresh
887
+ * user-tier `Handle` numbers via `world.allocSharedRef` (feat-20260614 M8
888
+ * D-19 instantiate-time GUID->handle mint; supersedes the pre-D-17
889
+ * `resolveGuid` map). GUIDs that fail to parse or are not catalogued return
890
+ * `AssetError(code='asset-not-found')` with a hint containing the GUID,
891
+ * node localId, and field name.
892
+ *
893
+ * Errors propagate verbatim through the closed
894
+ * `AssetError | PackError | EcsError` union so AI users that already
895
+ * narrow `loadByGuid<SceneAsset>` results reuse the same `switch
896
+ * (err.code)` exhaustively (charter proposition 3 machine-readable
897
+ * union; plan-strategy §3.3 closed-union transparency).
898
+ *
899
+ * @example
900
+ * ```ts
901
+ * const sceneRes = await engine.assets.loadByGuid<SceneAsset>(roomGuid); // payload (D-17)
902
+ * if (!sceneRes.ok) return;
903
+ * const handle = world.allocSharedRef('SceneAsset', sceneRes.value); // mint column handle
904
+ * const r = engine.assets.instantiate(handle, world);
905
+ * if (!r.ok) {
906
+ * switch (r.error.code) {
907
+ * case 'asset-not-found':
908
+ * case 'pack-cyclic-reference':
909
+ * // ... AssetErrorCode | PackErrorCode | EcsErrorCode exhaustive
910
+ * }
911
+ * }
912
+ * ```
913
+ */
914
+ instantiate<T extends SceneAsset>(
915
+ handle: Handle<TagOf<T>, 'shared'>,
916
+ world: World,
917
+ parent?: EntityHandle,
918
+ ): Result<EntityHandle, AssetError | PackError | EcsError> {
919
+ return instantiateImpl(this, handle, world, parent) as Result<
920
+ EntityHandle,
921
+ AssetError | PackError | EcsError
922
+ >;
923
+ }
924
+
925
+ instantiateWithPublicationFence<T extends SceneAsset>(
926
+ handle: Handle<TagOf<T>, 'shared'>,
927
+ world: World,
928
+ parent: EntityHandle | undefined,
929
+ expectedPublication: ScenePublicationFence,
930
+ ): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError>;
931
+ instantiateWithPublicationFence<T extends SceneAsset>(
932
+ handle: Handle<TagOf<T>, 'shared'>,
933
+ world: World,
934
+ parent: EntityHandle | undefined,
935
+ expectedPublication: ScenePublicationFence,
936
+ ): Result<EntityHandle, AssetError | PackError | EcsError | ScenePublicationFenceError> {
937
+ return instantiateImpl(this, handle, world, parent, expectedPublication);
938
+ }
939
+
940
+ /**
941
+ * Materialise a `SceneAsset` FLAT into an existing `World` — the "open a scene
942
+ * for authoring" registry entry (#655): NO synthetic SceneInstance root, NO
943
+ * forced `ChildOf` on top-level members. Returns the top-level entity handles.
944
+ * Nested prefabs (`mounts[]`) still materialise as their own SceneInstance
945
+ * anchors. Use {@link instantiate} (anchor) at runtime / Play and for nested
946
+ * prefabs.
947
+ */
948
+ instantiateFlat<T extends SceneAsset>(
949
+ handle: Handle<TagOf<T>, 'shared'>,
950
+ world: World,
951
+ ): Result<EntityHandle[], AssetError | PackError | EcsError> {
952
+ return instantiateFlatImpl(this, handle, world) as Result<
953
+ EntityHandle[],
954
+ AssetError | PackError | EcsError
955
+ >;
956
+ }
957
+
958
+ instantiateFlatWithPublicationFence<T extends SceneAsset>(
959
+ handle: Handle<TagOf<T>, 'shared'>,
960
+ world: World,
961
+ expectedPublication: ScenePublicationFence,
962
+ ): Result<EntityHandle[], AssetError | PackError | EcsError | ScenePublicationFenceError> {
963
+ return instantiateFlatImpl(this, handle, world, expectedPublication);
964
+ }
965
+
966
+ private sceneMeshGuidBySlot(
967
+ scene: SceneAsset,
968
+ visited: Set<string> = new Set(),
969
+ ): Map<number, string> {
970
+ const result = new Map<number, string>();
971
+ for (const entity of scene.entities) {
972
+ const components = entity.components as Record<string, Record<string, unknown>>;
973
+ const meshGuid = components.MeshFilter?.assetHandle;
974
+ if (typeof meshGuid === 'string') result.set(entity.localId as number, meshGuid);
975
+ }
976
+ for (const mount of scene.mounts ?? []) {
977
+ const mountComponents = mount.components as
978
+ | Record<string, Record<string, unknown>>
979
+ | undefined;
980
+ const mountMeshGuid = mountComponents?.MeshFilter?.assetHandle;
981
+ if (typeof mountMeshGuid === 'string') result.set(mount.localId as number, mountMeshGuid);
982
+ if (typeof mount.source !== 'string') continue;
983
+ const childKey = mount.source.toLowerCase();
984
+ if (visited.has(childKey)) continue;
985
+ const child = this.assetCatalog.get(childKey)?.payload;
986
+ if (child?.kind !== 'scene') continue;
987
+ const childVisited = new Set(visited);
988
+ childVisited.add(childKey);
989
+ const childSlots = this.sceneMeshGuidBySlot(child, childVisited);
990
+ const first = mount.memberFirst as unknown as number;
991
+ for (const [childSlot, meshGuid] of childSlots) result.set(first + childSlot, meshGuid);
992
+ for (const override of mount.overrides ?? []) {
993
+ if (override.comp !== 'MeshFilter') continue;
994
+ const nextMeshGuid =
995
+ override.field === 'assetHandle'
996
+ ? override.value
997
+ : override.field === undefined &&
998
+ typeof override.value === 'object' &&
999
+ override.value !== null &&
1000
+ !Array.isArray(override.value)
1001
+ ? (override.value as Record<string, unknown>).assetHandle
1002
+ : undefined;
1003
+ if (typeof nextMeshGuid === 'string') {
1004
+ result.set(override.localId as unknown as number, nextMeshGuid);
1005
+ }
1006
+ }
1007
+ }
1008
+ return result;
1009
+ }
1010
+
1011
+ private migrateLegacySceneMaterialOverrides(
1012
+ scene: SceneAsset,
1013
+ sceneGuidKey?: string,
1014
+ ): Result<{ readonly scene: SceneAsset; readonly changed: boolean }, AssetError> {
1015
+ const nodes: SceneEntity[] = [];
1016
+ let changed = false;
1017
+ for (const node of scene.entities) {
1018
+ const components = node.components as Record<string, Record<string, unknown>>;
1019
+ const rawMeshGuid = components.MeshFilter?.assetHandle;
1020
+ const meshGuid = typeof rawMeshGuid === 'string' ? rawMeshGuid : undefined;
1021
+ const legacyOverrides = components.MeshRenderer?.materials;
1022
+ const mesh =
1023
+ meshGuid === undefined ? undefined : this.assetCatalog.get(meshGuid.toLowerCase())?.payload;
1024
+ if (
1025
+ mesh?.kind !== 'mesh' ||
1026
+ meshGuid === undefined ||
1027
+ !Array.isArray(legacyOverrides) ||
1028
+ legacyOverrides.length < mesh.submeshes.length ||
1029
+ mesh.submeshes.length <= mesh.materialSlots.length ||
1030
+ !legacyOverrides.every((value) => typeof value === 'string')
1031
+ ) {
1032
+ nodes.push(node);
1033
+ continue;
1034
+ }
1035
+ const migrated = migrateLegacyMeshMaterialOverrides(
1036
+ legacyOverrides as string[],
1037
+ mesh.submeshes,
1038
+ mesh.materialSlots.length,
1039
+ {
1040
+ meshGuid: meshGuid.toLowerCase(),
1041
+ sceneGuid: sceneGuidKey ?? '<unregistered-scene>',
1042
+ entityId: node.localId as number,
1043
+ },
1044
+ );
1045
+ if (!migrated.ok) {
1046
+ return err(
1047
+ new AssetError({
1048
+ code: 'asset-parse-failed',
1049
+ expected:
1050
+ 'legacy per-submesh material overrides to collapse unambiguously onto Mesh v3 slots',
1051
+ hint: migrated.error.hint,
1052
+ detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,
1053
+ }),
1054
+ );
1055
+ }
1056
+ changed = true;
1057
+ nodes.push({
1058
+ ...node,
1059
+ components: {
1060
+ ...components,
1061
+ MeshRenderer: { ...components.MeshRenderer, materials: migrated.overrides },
1062
+ },
1063
+ } as SceneEntity);
1064
+ }
1065
+
1066
+ const mounts: SceneInstanceMount[] = [];
1067
+ for (const mount of scene.mounts ?? []) {
1068
+ const child =
1069
+ typeof mount.source === 'string'
1070
+ ? this.assetCatalog.get(mount.source.toLowerCase())?.payload
1071
+ : undefined;
1072
+ let nextMount = mount;
1073
+ let mountChanged = false;
1074
+ const mountComponents = mount.components as
1075
+ | Record<string, Record<string, unknown>>
1076
+ | undefined;
1077
+ const mountMeshGuid = mountComponents?.MeshFilter?.assetHandle;
1078
+ const mountMaterials = mountComponents?.MeshRenderer?.materials;
1079
+ const mountMesh =
1080
+ typeof mountMeshGuid === 'string'
1081
+ ? this.assetCatalog.get(mountMeshGuid.toLowerCase())?.payload
1082
+ : undefined;
1083
+ if (
1084
+ mountMesh?.kind === 'mesh' &&
1085
+ typeof mountMeshGuid === 'string' &&
1086
+ Array.isArray(mountMaterials) &&
1087
+ mountMaterials.length >= mountMesh.submeshes.length &&
1088
+ mountMesh.submeshes.length > mountMesh.materialSlots.length &&
1089
+ mountMaterials.every((value) => typeof value === 'string')
1090
+ ) {
1091
+ const migrated = migrateLegacyMeshMaterialOverrides(
1092
+ mountMaterials as string[],
1093
+ mountMesh.submeshes,
1094
+ mountMesh.materialSlots.length,
1095
+ {
1096
+ meshGuid: mountMeshGuid.toLowerCase(),
1097
+ sceneGuid: sceneGuidKey ?? '<unregistered-scene>',
1098
+ entityId: mount.localId as unknown as number,
1099
+ },
1100
+ );
1101
+ if (!migrated.ok) {
1102
+ return err(
1103
+ new AssetError({
1104
+ code: 'asset-parse-failed',
1105
+ expected:
1106
+ 'legacy mount-entity materials to collapse unambiguously onto Mesh v3 slots',
1107
+ hint: migrated.error.hint,
1108
+ detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,
1109
+ }),
1110
+ );
1111
+ }
1112
+ mountChanged = true;
1113
+ nextMount = {
1114
+ ...mount,
1115
+ components: {
1116
+ ...mountComponents,
1117
+ MeshRenderer: { ...mountComponents?.MeshRenderer, materials: migrated.overrides },
1118
+ },
1119
+ } as SceneInstanceMount;
1120
+ }
1121
+ if (child?.kind !== 'scene' || mount.overrides === undefined) {
1122
+ if (mountChanged) changed = true;
1123
+ mounts.push(nextMount);
1124
+ continue;
1125
+ }
1126
+ const meshByMember = this.sceneMeshGuidBySlot(child);
1127
+ const nextOverrides: MountOverride[] = [];
1128
+ for (const override of mount.overrides) {
1129
+ const childLocalId =
1130
+ (override.localId as unknown as number) - (mount.memberFirst as unknown as number);
1131
+ if (override.comp === 'MeshFilter') {
1132
+ const nextMeshGuid =
1133
+ override.field === 'assetHandle'
1134
+ ? override.value
1135
+ : override.field === undefined &&
1136
+ typeof override.value === 'object' &&
1137
+ override.value !== null &&
1138
+ !Array.isArray(override.value)
1139
+ ? (override.value as Record<string, unknown>).assetHandle
1140
+ : undefined;
1141
+ if (typeof nextMeshGuid === 'string') meshByMember.set(childLocalId, nextMeshGuid);
1142
+ nextOverrides.push(override);
1143
+ continue;
1144
+ }
1145
+ const legacyMaterials =
1146
+ override.comp === 'MeshRenderer' && override.field === 'materials'
1147
+ ? override.value
1148
+ : override.comp === 'MeshRenderer' &&
1149
+ override.field === undefined &&
1150
+ typeof override.value === 'object' &&
1151
+ override.value !== null &&
1152
+ !Array.isArray(override.value)
1153
+ ? (override.value as Record<string, unknown>).materials
1154
+ : undefined;
1155
+ const meshGuid = meshByMember.get(childLocalId);
1156
+ const mesh =
1157
+ meshGuid === undefined
1158
+ ? undefined
1159
+ : this.assetCatalog.get(meshGuid.toLowerCase())?.payload;
1160
+ if (
1161
+ mesh?.kind !== 'mesh' ||
1162
+ meshGuid === undefined ||
1163
+ !Array.isArray(legacyMaterials) ||
1164
+ legacyMaterials.length < mesh.submeshes.length ||
1165
+ mesh.submeshes.length <= mesh.materialSlots.length ||
1166
+ !legacyMaterials.every((value) => typeof value === 'string')
1167
+ ) {
1168
+ nextOverrides.push(override);
1169
+ continue;
1170
+ }
1171
+ const migrated = migrateLegacyMeshMaterialOverrides(
1172
+ legacyMaterials as string[],
1173
+ mesh.submeshes,
1174
+ mesh.materialSlots.length,
1175
+ {
1176
+ meshGuid: meshGuid.toLowerCase(),
1177
+ sceneGuid: sceneGuidKey ?? '<unregistered-scene>',
1178
+ entityId: override.localId as unknown as number,
1179
+ },
1180
+ );
1181
+ if (!migrated.ok) {
1182
+ return err(
1183
+ new AssetError({
1184
+ code: 'asset-parse-failed',
1185
+ expected:
1186
+ 'legacy mount material overrides to collapse unambiguously onto Mesh v3 slots',
1187
+ hint: migrated.error.hint,
1188
+ detail: migrated.error as unknown as import('@forgeax/engine-types').AssetErrorDetail,
1189
+ }),
1190
+ );
1191
+ }
1192
+ mountChanged = true;
1193
+ nextOverrides.push(
1194
+ override.field === 'materials'
1195
+ ? { ...override, value: migrated.overrides }
1196
+ : {
1197
+ ...override,
1198
+ value: {
1199
+ ...(override.value as Record<string, unknown>),
1200
+ materials: migrated.overrides,
1201
+ },
1202
+ },
1203
+ );
1204
+ }
1205
+ if (mountChanged) {
1206
+ changed = true;
1207
+ mounts.push({ ...nextMount, overrides: nextOverrides });
1208
+ } else {
1209
+ mounts.push(nextMount);
1210
+ }
1211
+ }
1212
+ return ok({
1213
+ scene: changed
1214
+ ? {
1215
+ ...scene,
1216
+ entities: nodes,
1217
+ ...(scene.mounts === undefined ? {} : { mounts }),
1218
+ }
1219
+ : scene,
1220
+ changed,
1221
+ });
1222
+ }
1223
+
1224
+ private preflightSceneMaterialGraph(
1225
+ scene: SceneAsset,
1226
+ sceneGuidKey?: string,
1227
+ visited: Set<string> = new Set(),
1228
+ ): Result<void, AssetError> {
1229
+ const key = sceneGuidKey?.toLowerCase();
1230
+ if (key !== undefined) {
1231
+ if (visited.has(key)) return ok(undefined);
1232
+ visited.add(key);
1233
+ }
1234
+ const local = this.migrateLegacySceneMaterialOverrides(scene, sceneGuidKey);
1235
+ if (!local.ok) return local;
1236
+ for (const mount of scene.mounts ?? []) {
1237
+ if (typeof mount.source !== 'string') continue;
1238
+ const childKey = mount.source.toLowerCase();
1239
+ const child = this.assetCatalog.get(childKey)?.payload;
1240
+ if (child?.kind !== 'scene') continue;
1241
+ const nested = this.preflightSceneMaterialGraph(child, childKey, visited);
1242
+ if (!nested.ok) return nested;
1243
+ }
1244
+ return ok(undefined);
1245
+ }
1246
+
1247
+ /**
1248
+ * @internal
1249
+ * Transform a SceneAsset whose handle-type component fields hold GUID
1250
+ * strings (post-parseScenePayload intermediate state) into a copy whose
1251
+ * handle fields hold resolved Handle numbers.
1252
+ *
1253
+ * Schema-driven field detection (plan-strategy D-4): for each component
1254
+ * field whose Component.schema fieldType starts with `shared\<`, the
1255
+ * value is treated as a GUID string and resolved via `AssetGuid.parse` +
1256
+ * catalogue lookup + `world.internSharedRef` (feat-20260614 M8 D-15/D-17;
1257
+ * the registry mints nothing). Unknown component names are silently passed
1258
+ * through (the ecs layer's additionalProperties check will catch unknowns at
1259
+ * spawn if appropriate).
1260
+ *
1261
+ * Stop-on-first-error (AC-08): the first unresolvable GUID aborts
1262
+ * iteration and returns `AssetError(code='asset-not-found')` with a hint
1263
+ * containing the GUID string, node localId, and field name for AI-user
1264
+ * debuggability (P3).
1265
+ */
1266
+ _resolveSceneGuids(
1267
+ scene: SceneAsset,
1268
+ world: World,
1269
+ sceneGuidKey?: string,
1270
+ _visitedMountGuids?: Set<string>,
1271
+ _guidToHandle?: Map<string, number>,
1272
+ _resolvedSceneHandles?: Map<string, number>,
1273
+ _materialGraphPreflighted = false,
1274
+ ): Result<SceneAsset, AssetError> {
1275
+ // feat-20260622 M3 / w8: reverse-decode from envelope.refs edges when
1276
+ // sceneGuidKey is provided and the catalog holds an envelope for this
1277
+ // scene. Each edge with sceneEntityId+sourceField.componentName carries
1278
+ // the (entityLocalId, componentName, fieldName, arrayIndex) triple —
1279
+ // no need to walk entities with a process-global component reflection table.
1280
+ // D-15/D-17 dedup contract: the same catalogued payload referenced from
1281
+ // multiple nodes must resolve to ONE user-tier handle. The local GUID map
1282
+ // avoids repeat lookups inside this traversal; World interning preserves
1283
+ // payload identity across separate scene-resolution calls.
1284
+ if (!_materialGraphPreflighted) {
1285
+ const graph = this.preflightSceneMaterialGraph(scene, sceneGuidKey);
1286
+ if (!graph.ok) return graph;
1287
+ }
1288
+ const localMigration = this.migrateLegacySceneMaterialOverrides(scene, sceneGuidKey);
1289
+ if (!localMigration.ok) return localMigration;
1290
+ const sceneForResolution = localMigration.value.scene;
1291
+ const preflightChanged = localMigration.value.changed;
1292
+
1293
+ const resolvedMap = new Map<string, number>();
1294
+ const guidToHandle = _guidToHandle ?? new Map<string, number>();
1295
+ const resolvedSceneHandles = _resolvedSceneHandles ?? new Map<string, number>();
1296
+ const sceneEnvelope =
1297
+ !preflightChanged && sceneGuidKey !== undefined
1298
+ ? this.assetCatalog.get(sceneGuidKey)
1299
+ : undefined;
1300
+ // Did the structured-edge branch actually resolve anything? Prod-loaded
1301
+ // packs catalogue refs[] as GUID-only edges (sourceField / sceneEntityId
1302
+ // stripped at the w7 D-10 serialization boundary), so the rich-edge loop
1303
+ // below `continue`-skips every ref and resolves nothing. When that happens
1304
+ // we MUST fall through to the entity-walk fallback — otherwise the handle
1305
+ // fields keep their GUID strings and `spawn` writes the sentinel 0 while
1306
+ // `retainSharedScalarHandle(GUID)` routes `shared-ref-released` (the on-disk
1307
+ // game-scene instantiate crash: enemy MeshFilter.assetHandle).
1308
+ let resolvedFromEdges = false;
1309
+ if (
1310
+ sceneEnvelope !== undefined &&
1311
+ sceneEnvelope.refs !== undefined &&
1312
+ sceneEnvelope.refs.length > 0
1313
+ ) {
1314
+ for (const ref of sceneEnvelope.refs) {
1315
+ const { sceneEntityId, sourceField } = ref;
1316
+ if (sceneEntityId === undefined || sourceField === undefined) continue;
1317
+ const { componentName, fieldName, arrayIndex } = sourceField;
1318
+ if (componentName === undefined || fieldName === undefined) continue;
1319
+
1320
+ const fieldPath = `${componentName}.${fieldName}${arrayIndex !== undefined ? `[${arrayIndex}]` : ''}`;
1321
+
1322
+ const envelope = this.assetCatalog.get(ref.guid.toLowerCase());
1323
+ if (envelope === undefined) {
1324
+ return err(
1325
+ new AssetError({
1326
+ code: 'asset-not-found',
1327
+ expected: `GUID ${ref.guid} catalogued in AssetRegistry`,
1328
+ hint:
1329
+ `GUID ${ref.guid} not catalogued; ` +
1330
+ `call loadByGuid('${ref.guid}') before instantiate; ` +
1331
+ `at node localId=${sceneEntityId}, field=${fieldPath}`,
1332
+ }),
1333
+ );
1334
+ }
1335
+ const payload = envelope.payload;
1336
+ const guidKey = ref.guid.toLowerCase();
1337
+ let resolvedSlot = guidToHandle.get(guidKey);
1338
+ if (resolvedSlot === undefined) {
1339
+ resolvedSlot = unwrapHandle(world.internSharedRef(payload.kind, payload));
1340
+ guidToHandle.set(guidKey, resolvedSlot);
1341
+ }
1342
+
1343
+ const key =
1344
+ `${sceneEntityId}|${componentName}|${fieldName}` +
1345
+ (arrayIndex !== undefined ? `|${arrayIndex}` : '|');
1346
+ resolvedMap.set(key, resolvedSlot);
1347
+ resolvedFromEdges = true;
1348
+ }
1349
+ }
1350
+ if (!resolvedFromEdges) {
1351
+ // Fallback: positive extraction via extractSceneEntityHandleGuids when
1352
+ // the structured edges resolved nothing — either the scene envelope is
1353
+ // absent (unit tests that build a SceneAsset without cataloguing it) OR
1354
+ // the catalogued refs[] are GUID-only with no per-entity metadata (the
1355
+ // prod on-disk pack path). The entity-component walk recovers the
1356
+ // (localId, componentName, fieldName, arrayIndex) triple the bare edge
1357
+ // dropped, so GUID strings resolve to live handles before spawn.
1358
+ const entries = extractSceneEntityHandleGuids(
1359
+ world.components.entries(),
1360
+ sceneForResolution.entities as unknown as ReadonlyArray<{
1361
+ readonly localId: number;
1362
+ readonly components: Record<string, Record<string, unknown>>;
1363
+ }>,
1364
+ );
1365
+
1366
+ for (const entry of entries) {
1367
+ const fieldPath =
1368
+ `${entry.componentName}.${entry.fieldName}` +
1369
+ (entry.arrayIndex !== undefined ? `[${entry.arrayIndex}]` : '');
1370
+ const resolvedSlot = resolveHandleGuid(
1371
+ this,
1372
+ world,
1373
+ entry.guidString,
1374
+ guidToHandle,
1375
+ fieldPath,
1376
+ `node localId=${entry.entityLocalId}`,
1377
+ );
1378
+ if (!resolvedSlot.ok) return resolvedSlot;
1379
+
1380
+ const key =
1381
+ `${entry.entityLocalId}|${entry.componentName}|${entry.fieldName}` +
1382
+ (entry.arrayIndex !== undefined ? `|${entry.arrayIndex}` : '|');
1383
+ resolvedMap.set(key, resolvedSlot.value);
1384
+ }
1385
+ }
1386
+
1387
+ // Build the resolved copy. Handle-type fields (detected above) are
1388
+ // reconstructed from the resolvedMap; all other fields pass through as-is.
1389
+ const resolvedNodes: SceneEntity[] = [];
1390
+ for (const node of sceneForResolution.entities) {
1391
+ const rawComponents = node.components as Record<string, Record<string, unknown>>;
1392
+ const resolvedComponents: Record<string, Record<string, unknown>> = {};
1393
+
1394
+ for (const compName of Object.keys(rawComponents)) {
1395
+ const rawFields = rawComponents[compName];
1396
+ if (!rawFields) {
1397
+ resolvedComponents[compName] = {};
1398
+ continue;
1399
+ }
1400
+ const resolvedFields: Record<string, unknown> = {};
1401
+ for (const fieldName of Object.keys(rawFields)) {
1402
+ const value = rawFields[fieldName];
1403
+ const plainKey = `${node.localId}|${compName}|${fieldName}|`;
1404
+ const plainResolved = resolvedMap.get(plainKey);
1405
+ if (plainResolved !== undefined) {
1406
+ resolvedFields[fieldName] = plainResolved;
1407
+ } else if (Array.isArray(value)) {
1408
+ const resolvedArr: number[] = [];
1409
+ let hasAnyResolved = false;
1410
+ for (let i = 0; i < value.length; i++) {
1411
+ const arrKey = `${node.localId}|${compName}|${fieldName}|${i}`;
1412
+ const arrResolved = resolvedMap.get(arrKey);
1413
+ if (arrResolved !== undefined) {
1414
+ resolvedArr.push(arrResolved);
1415
+ hasAnyResolved = true;
1416
+ } else if (typeof value[i] === 'number') {
1417
+ resolvedArr.push(value[i]);
1418
+ }
1419
+ }
1420
+ resolvedFields[fieldName] = hasAnyResolved ? resolvedArr : value;
1421
+ } else {
1422
+ resolvedFields[fieldName] = value;
1423
+ }
1424
+ }
1425
+ resolvedComponents[compName] = resolvedFields;
1426
+ }
1427
+ resolvedNodes.push({
1428
+ localId: node.localId,
1429
+ components: resolvedComponents,
1430
+ });
1431
+ }
1432
+
1433
+ // ── m3-i2 / m3-i3: Resolve mounts recursively (breakpoint B fix) ──
1434
+ // For each mount.source (GUID string), look up the child scene in
1435
+ // assetCatalog, recursively resolve its GUIDs, allocSharedRef the
1436
+ // resolved child copy, register it in originIndex (D-7), and produce
1437
+ // a resolved mount with source as the live handle number.
1438
+ // Cycle detection via visited GUID set (R-9): re-entry =>
1439
+ // pack-cyclic-reference / mount-asset, cast through the return type
1440
+ // as world.ts does for its PackError exits.
1441
+ const mountVisited = _visitedMountGuids ?? new Set<string>();
1442
+ if (sceneGuidKey !== undefined) mountVisited.add(sceneGuidKey.toLowerCase());
1443
+ if (sceneForResolution.mounts !== undefined && sceneForResolution.mounts.length > 0) {
1444
+ // feat-20260713 M3 / w13: share the entity-field dedup map so an override
1445
+ // value GUID that also appears as an entity field mints one handle (D-15/D-17).
1446
+ const resolvedMounts = resolveMountsRec(
1447
+ this,
1448
+ sceneForResolution.mounts,
1449
+ world,
1450
+ mountVisited,
1451
+ guidToHandle,
1452
+ resolvedSceneHandles,
1453
+ );
1454
+ if (sceneGuidKey !== undefined) mountVisited.delete(sceneGuidKey.toLowerCase());
1455
+ if (!resolvedMounts.ok) {
1456
+ // Cycle or child-resolution error: cast through as AssetError
1457
+ // (same pattern as world.ts PackError-as-EcsError casts).
1458
+ return resolvedMounts as unknown as Result<SceneAsset, AssetError>;
1459
+ }
1460
+ return ok({
1461
+ kind: 'scene',
1462
+ entities: resolvedNodes,
1463
+ mounts: resolvedMounts.value,
1464
+ } as SceneAsset);
1465
+ }
1466
+ if (sceneGuidKey !== undefined) mountVisited.delete(sceneGuidKey.toLowerCase());
1467
+ return ok({ kind: 'scene', entities: resolvedNodes });
1468
+ }
1469
+
1470
+ /**
1471
+ * Register an asset and return a fresh
1472
+ * `Result<Handle<TagOf<T>, 'shared'>, AssetError>`. The brand `target`
1473
+ * tag is derived from the Asset's `kind` discriminator via `AssetTagMap`
1474
+ * (charter F1 single-entry indexability). The runtime representation is
1475
+ * an auto-incrementing u32 starting at 1024 (builtins reserve 1-2).
1476
+ *
1477
+ * feat-20260526 M4: `shadingModel` field is retired in favour of
1478
+ * pass-based MaterialAsset. This generic surface covers the full
1479
+ * `Asset` closed union (mesh / texture / sampler / scene / equirect
1480
+ * / material).
1481
+ */
1482
+ /**
1483
+ * feat-20260614 M8 (D-15 / D-17): catalogue a payload under its GUID.
1484
+ * Replaces the old `register` / `registerWithGuid` mint pair -- the registry
1485
+ * stores the PAYLOAD and never produces a handle (it owns no World).
1486
+ * Column minting is the caller's job via `world.allocSharedRef`.
1487
+ *
1488
+ * Validates mesh stride + material passes / sprite slices at catalogue entry
1489
+ * (same fail-fast surface as the old register path). Returns
1490
+ * `Result.err(AssetError)` on validation failure; `Result.ok(payload)` with
1491
+ * the stored payload (mesh payloads gain an `aabb`) on success.
1492
+ */
1493
+ catalog<T = Asset>(
1494
+ guid: AssetGuid | string,
1495
+ asset: T,
1496
+ refs?: readonly AssetRef[],
1497
+ ): Result<T, AssetError> {
1498
+ // D-5: narrow T to Asset for kind-discriminate branches. The runtime
1499
+ // catalog only accepts Asset-kind payloads (host custom kinds enter
1500
+ // through loadByGuid + registerParsedAsset, not catalog directly).
1501
+ const a: Asset = asset as unknown as Asset;
1502
+ const meshValidation = validateMeshPayload(a);
1503
+ if (meshValidation !== null) return err(meshValidation);
1504
+
1505
+ // feat-20260608 M0 baseline rebuild: tileset payload fail-fast gate at
1506
+ // register entry — region rectangle bounds-check uses the implicit atlas
1507
+ // extent (columns * tileWidth x rows * tileHeight) when the caller did
1508
+ // not supply an explicit one (charter P3 explicit failure).
1509
+ if (a.kind === 'tileset') {
1510
+ const tilesetAsset = a as TilesetAsset;
1511
+ const tilesetValidation = validateTilesetPayload(
1512
+ tilesetAsset,
1513
+ inferAtlasExtent(tilesetAsset),
1514
+ );
1515
+ if (tilesetValidation !== null) return err(tilesetValidation);
1516
+ }
1517
+
1518
+ // feat-20260527 M2 / w6: material validation with union paramSchema
1519
+ // semantics across all passes (plan-strategy D-2, D-5).
1520
+ if (a.kind === 'material') {
1521
+ const matValidation = validateMaterialPasses(this, a as MaterialAsset);
1522
+ if (matValidation !== null) return err(matValidation);
1523
+ const sliceValidation = validateSpriteSlices(this, a as MaterialAsset);
1524
+ if (sliceValidation !== null) return err(sliceValidation);
1525
+ detectTileNeedsRepeatSampler(this, a as MaterialAsset);
1526
+ }
1527
+
1528
+ let stored: Asset = a;
1529
+ if (a.kind === 'mesh') {
1530
+ stored = withMeshAabb(a as TypesMeshAsset);
1531
+ }
1532
+ const key =
1533
+ typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();
1534
+ const kind = a.kind;
1535
+ // Drain any name recorded by an earlier _registerPackage call whose body had
1536
+ // not yet been catalogued (prod disk path; D-6). Preserve a name already on
1537
+ // a prior envelope for this key (re-catalog of the same GUID).
1538
+ const pendingName = this.pendingNames.get(key);
1539
+ const priorEnvelope = this.assetCatalog.get(key);
1540
+ const priorName = priorEnvelope?.name;
1541
+ const name = pendingName ?? priorName;
1542
+ this.pendingNames.delete(key);
1543
+ // feat-20260713 M4 / w15 (D-6, root cause a): when this GUID is being
1544
+ // re-catalogued with a DIFFERENT payload object, the prior object may still
1545
+ // be live behind a handle minted before the override (asset-registry.ts:513
1546
+ // identity scan would then MISS it). Record the superseded object -> GUID in
1547
+ // the origin reverse-index so `_guidForAsset` keeps resolving it — save/
1548
+ // collect of an owned entity holding that handle no longer fails with a
1549
+ // GUID-unresolved error (the 2026-07-06 crash). Structurally-modified copies
1550
+ // (a fresh object never catalogued) stay uncatalogued and correctly surface a
1551
+ // structured error at collect (requirements edge case "modified payload judged
1552
+ // as a new asset, not silently zeroed").
1553
+ if (priorEnvelope !== undefined && priorEnvelope.payload !== stored) {
1554
+ this._originIndex.set(priorEnvelope.payload, key);
1555
+ }
1556
+ this.assetCatalog.set(key, {
1557
+ guid: key,
1558
+ kind,
1559
+ ...(name !== undefined ? { name } : {}),
1560
+ payload: stored,
1561
+ refs: refs ?? [],
1562
+ });
1563
+ this.catalogEpoch++;
1564
+ this.loadState.registerReady(key, stored);
1565
+ // D-1: catalog() inline path defaults every GUID to the no-package state
1566
+ // (null). loadByGuid + builtin override via their own registerPackage calls
1567
+ // before / after this so the package mapping is populated for all assets
1568
+ // through the single primitive (#1 SSOT). Do not clobber a package mapping
1569
+ // a prior registerPackage already established for this GUID.
1570
+ if (!this.packages.has(key)) this.packages.set(key, null);
1571
+ return ok(stored as T);
1572
+ }
1573
+
1574
+ /**
1575
+ * @internal feat-20260618-asset-and-pack-name-fields M3 (D-1): the single
1576
+ * package-mapping write primitive. All three registration entry points funnel
1577
+ * here so the XOR name invariant is implemented once (#1 SSOT):
1578
+ * - catalog() inline path -> registerPackage(null, [guid]) (no package)
1579
+ * - loadByGuid disk path -> registerPackage(packageUrl, [g1,g2,...], names)
1580
+ * - constructor builtin -> registerPackage(null, [...guids]) (D-5 null)
1581
+ *
1582
+ * `path === null` registers the GUIDs with no package (resolveName reads their
1583
+ * storedName or returns ''). A non-null `path` finds-or-creates the shared
1584
+ * MutablePackage for that path and adds the GUIDs to it; per-GUID entry names
1585
+ * (D-2: name flows entry -> Package, never the payload) are taken from
1586
+ * `names`. The 1->N promotion branch (D-3) is added by w11. Never throws --
1587
+ * it only writes maps; resolution + validation happen in resolveName / rename.
1588
+ */
1589
+ _registerPackage(
1590
+ path: string | null,
1591
+ guids: readonly string[],
1592
+ names?: Map<string, string>,
1593
+ ): void {
1594
+ if (path === null) {
1595
+ for (const g of guids) {
1596
+ const key = g.toLowerCase();
1597
+ this.packages.set(key, null);
1598
+ const n = names?.get(g) ?? names?.get(key);
1599
+ if (n !== undefined) this.setStoredName(key, n);
1600
+ }
1601
+ return;
1602
+ }
1603
+
1604
+ const pkg = this.packageByPath.get(path) ?? { path, assetGuids: new Set<string>() };
1605
+ this.packageByPath.set(path, pkg);
1606
+
1607
+ // D-3: 1->N promotion. When this path already holds exactly one asset and a
1608
+ // new member is arriving, freeze the original asset's derived basename as its
1609
+ // stored name so it joins the multi-asset branch with a stable name. The
1610
+ // freeze is idempotent: an original that already carries a stored name (the
1611
+ // abnormal single-asset-with-name state, D-4) is left untouched and the
1612
+ // soft-violation counter records it (charter P3 machine-readable signal).
1613
+ const addsNewMember = guids.some((g) => !pkg.assetGuids.has(g.toLowerCase()));
1614
+ if (pkg.assetGuids.size === 1 && addsNewMember) {
1615
+ const [originalKey] = pkg.assetGuids;
1616
+ if (originalKey !== undefined) {
1617
+ if (this.hasStoredName(originalKey)) {
1618
+ this.metrics?.increment('package.xor-invariant-violated');
1619
+ } else {
1620
+ this.setStoredName(originalKey, deriveAssetName(pkg.path, 1));
1621
+ }
1622
+ }
1623
+ }
1624
+
1625
+ for (const g of guids) {
1626
+ const key = g.toLowerCase();
1627
+ pkg.assetGuids.add(key);
1628
+ this.packages.set(key, pkg);
1629
+ const n = names?.get(g) ?? names?.get(key);
1630
+ if (n !== undefined) this.setStoredName(key, n);
1631
+ }
1632
+ }
1633
+
1634
+ /**
1635
+ * Read the per-GUID stored display name (D-6 home: the envelope's `name`
1636
+ * field, with `pendingNames` covering the prod-disk ordering where the name is
1637
+ * known before the body is catalogued). Single read point for resolveName /
1638
+ * the 1->N promotion XOR check.
1639
+ */
1640
+ private storedNameFor(key: string): string | undefined {
1641
+ return this.assetCatalog.get(key)?.name ?? this.pendingNames.get(key);
1642
+ }
1643
+
1644
+ private hasStoredName(key: string): boolean {
1645
+ return this.storedNameFor(key) !== undefined;
1646
+ }
1647
+
1648
+ /**
1649
+ * Write the per-GUID stored display name. When the envelope exists, replace it
1650
+ * with one carrying the new `name` (the envelope is immutable; D-6 keeps the
1651
+ * payload free of the name). Before the envelope is catalogued (prod disk
1652
+ * path), stash on `pendingNames` so catalog() can drain it into the new
1653
+ * envelope. `name === undefined` clears the name in both homes.
1654
+ */
1655
+ private setStoredName(key: string, name: string | undefined): void {
1656
+ const envelope = this.assetCatalog.get(key);
1657
+ if (envelope !== undefined) {
1658
+ const { name: _drop, ...rest } = envelope;
1659
+ this.assetCatalog.set(key, name === undefined ? rest : { ...rest, name });
1660
+ this.pendingNames.delete(key);
1661
+ return;
1662
+ }
1663
+ if (name === undefined) this.pendingNames.delete(key);
1664
+ else this.pendingNames.set(key, name);
1665
+ }
1666
+
1667
+ /**
1668
+ * Return the `Package` this GUID belongs to, or `null` when the asset has no
1669
+ * package (catalog() inline + builtin, D-5), or `undefined` when the GUID was
1670
+ * never registered. The returned `Package` is a readonly snapshot whose
1671
+ * `assetCount` is derived from the live member set (#2 Derive).
1672
+ */
1673
+ packageOf(guid: AssetGuid | string): Package | null | undefined {
1674
+ const key =
1675
+ typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();
1676
+ const pkg = this.packages.get(key);
1677
+ if (pkg === undefined) return undefined;
1678
+ if (pkg === null) return null;
1679
+ return { path: pkg.path, assetGuids: pkg.assetGuids, assetCount: pkg.assetGuids.size };
1680
+ }
1681
+
1682
+ /**
1683
+ * Resolve an asset's human-readable display name -- the single source of truth
1684
+ * for the two-segment identity's `name` segment (D-6). Every name consumer
1685
+ * (inspect / catalog builder / CLI) reads this or the same `deriveAssetName`
1686
+ * pure function it delegates to (AC-04); no consumer re-implements the XOR
1687
+ * rule. Returns a deterministic fallback rather than throwing on a missing
1688
+ * name (AC-15): `basename(path)` for a multi-asset entry that lacks a stored
1689
+ * name, or `''` for a no-package asset with no self name (the detectable
1690
+ * "genuinely no name" signal, charter P3). An unregistered GUID is treated as
1691
+ * the no-package branch.
1692
+ */
1693
+ resolveName(guid: AssetGuid | string): string {
1694
+ const key =
1695
+ typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();
1696
+ const pkg = this.packages.get(key);
1697
+ const storedName = this.storedNameFor(key);
1698
+ const path = pkg == null ? null : pkg.path;
1699
+ const assetCount = pkg == null ? 0 : pkg.assetGuids.size;
1700
+ return deriveAssetName(path, assetCount, storedName);
1701
+ }
1702
+
1703
+ /**
1704
+ * Rename an asset's display name in memory (D-4). Three classes by package
1705
+ * shape:
1706
+ * - no-package asset -> set the stored self name
1707
+ * - multi-asset package -> set the entry stored name
1708
+ * - single-asset package -> rewrite the package path's leaf segment so the
1709
+ * derived basename becomes `newName` (the package
1710
+ * stays single-asset; the leaf IS the name)
1711
+ *
1712
+ * In-memory only (OOS-1: no disk write-back). Returns structured failures via
1713
+ * the closed `AssetErrorCode` union with no new members (D-4): a name that
1714
+ * collides with another member of the same package -> `asset-invalid-value`;
1715
+ * an unregistered GUID -> `asset-not-found`. AI users consume `.code` through
1716
+ * a `switch`, not by parsing `.message` (charter P3).
1717
+ */
1718
+ rename(guid: AssetGuid | string, newName: string): Result<void, AssetError> {
1719
+ const key =
1720
+ typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();
1721
+ if (!this.packages.has(key)) {
1722
+ return err(
1723
+ new AssetError({
1724
+ code: 'asset-not-found',
1725
+ expected: `a registered asset for GUID ${key}`,
1726
+ hint: ASSET_ERROR_HINTS['asset-not-found'],
1727
+ }),
1728
+ );
1729
+ }
1730
+
1731
+ const pkg = this.packages.get(key) ?? null;
1732
+
1733
+ const collision = pkg !== null ? this.nameCollisionIn(pkg, key, newName) : null;
1734
+ if (collision !== null) return err(collision);
1735
+
1736
+ if (pkg !== null && pkg.assetGuids.size === 1) {
1737
+ // Single-asset package: the leaf segment IS the derived name; rewrite it so
1738
+ // basename(path) === newName. Keep the directory prefix intact.
1739
+ const slash = pkg.path.lastIndexOf('/');
1740
+ const oldPath = pkg.path;
1741
+ pkg.path = slash >= 0 ? `${pkg.path.slice(0, slash + 1)}${newName}` : newName;
1742
+ this.packageByPath.delete(oldPath);
1743
+ this.packageByPath.set(pkg.path, pkg);
1744
+ this.setStoredName(key, undefined);
1745
+ return ok(undefined);
1746
+ }
1747
+
1748
+ this.setStoredName(key, newName);
1749
+ return ok(undefined);
1750
+ }
1751
+
1752
+ /**
1753
+ * Return an `asset-invalid-value` AssetError if another member of `pkg`
1754
+ * already resolves to `newName`, else null. Extracted from `rename` to keep
1755
+ * the collision-detection control flow flat (D-4 reuses the closed error code;
1756
+ * the detail narrows via the `{ field, value, reason }` union variant).
1757
+ */
1758
+ private nameCollisionIn(
1759
+ pkg: MutablePackage,
1760
+ selfKey: string,
1761
+ newName: string,
1762
+ ): AssetError | null {
1763
+ for (const memberKey of pkg.assetGuids) {
1764
+ if (memberKey !== selfKey && this.resolveName(memberKey) === newName) {
1765
+ return new AssetError({
1766
+ code: 'asset-invalid-value',
1767
+ expected: `a name unique within package "${pkg.path}"`,
1768
+ hint: `another asset in "${pkg.path}" is already named "${newName}"; choose a distinct name`,
1769
+ detail: {
1770
+ field: 'name',
1771
+ value: newName,
1772
+ reason: `duplicate name within package ${pkg.path}`,
1773
+ },
1774
+ });
1775
+ }
1776
+ }
1777
+ return null;
1778
+ }
1779
+
1780
+ /**
1781
+ * Parse a dash-form GUID string into an `AssetGuid`. Thin convenience over
1782
+ * `AssetGuid.parse` for the `loadByGuid` / `catalog` call sites; throws
1783
+ * `AssetError` on a malformed GUID (caller-error, mirrors `parseInt`-style
1784
+ * eager validation -- the GUID literal is author-supplied, not user data).
1785
+ */
1786
+ parseGuid(guidStr: string): AssetGuid {
1787
+ const parsed = AssetGuid.parse(guidStr);
1788
+ if (!parsed.ok) {
1789
+ throw new AssetError({
1790
+ code: 'asset-parse-failed',
1791
+ expected: `valid dash-form GUID, got "${guidStr}"`,
1792
+ hint: ASSET_ERROR_HINTS['asset-parse-failed'],
1793
+ });
1794
+ }
1795
+ return parsed.value;
1796
+ }
1797
+
1798
+ /**
1799
+ * Look up a catalogued payload by GUID, or `undefined` on miss. Used by the
1800
+ * ECS/render side (e.g. `walkMaterialParents` in `resolve-asset-handle.ts`)
1801
+ * to resolve a payload's embedded sub-asset GUIDs (D-19) without minting.
1802
+ */
1803
+ lookup<T = Asset>(guid: AssetGuid | string): T | undefined {
1804
+ const key =
1805
+ typeof guid === 'string' ? guid.toLowerCase() : AssetGuid.format(guid).toLowerCase();
1806
+ const ready = this.loadState.getReady<T>(key);
1807
+ if (ready !== undefined) return ready;
1808
+ if (this.packIndexUrl === undefined)
1809
+ return this.assetCatalog.get(key)?.payload as T | undefined;
1810
+ return undefined;
1811
+ }
1812
+
1813
+ /**
1814
+ * feat-20260613-material-paramschema-driven-binding M4 / w23 (D-5 graceful):
1815
+ * Return the texture-field name set for the given material-shader id,
1816
+ * derived from the registered shader's paramSchema via `derive(paramSchema)
1817
+ * .textureFieldNames`. Returns `undefined` when the shader is not yet
1818
+ * registered (cross-worktree shader-late-register, plan R-4).
1819
+ *
1820
+ * Used by `extractFrame` to know which values fields the shader
1821
+ * declares as texture handles; the extract layer validates handle-vs-
1822
+ * scalar typing and drops misclassified slots so the record stage's
1823
+ * MISSING_TEXTURE_HANDLE fallback can take over (white default texture)
1824
+ * rather than letting a stray handle reach `device.createBindGroup`.
1825
+ *
1826
+ * feat-20260705-runtime-tier2-decomposition M1 / w5 (D-4): delegates to the
1827
+ * extracted `./registry/validate-material` free function (signature stable).
1828
+ */
1829
+ materialShaderTextureFieldNames(shaderId: string): ReadonlySet<string> | undefined {
1830
+ return materialShaderTextureFieldNamesImpl(this, shaderId);
1831
+ }
1832
+
1833
+ /**
1834
+ * Load an asset and all its transitively referenced sub-assets by GUID.
1835
+ * The result is a durable Asset payload. Consumer owners may narrow the
1836
+ * success type, then call their own World/Host projection; this registry does
1837
+ * not create a generic GUID-to-handle materializer.
1838
+ * Delegates to the load-by-guid collaboration module (w7 / D-4); see
1839
+ * registry/load-by-guid.ts for the full DDC / pack-fetch pipeline.
1840
+ */
1841
+ async loadByGuid<T = Asset>(
1842
+ guid: AssetGuid,
1843
+ parentContext?: {
1844
+ sceneEntityId?: number;
1845
+ componentField?: string;
1846
+ },
1847
+ ): Promise<Result<T, AssetError | ImageError | RhiError>> {
1848
+ return loadByGuidImpl<T>(this, guid, parentContext);
1849
+ }
1850
+
1851
+ /**
1852
+ * Dispatch a pack payload through the injected LoaderRegistry. Delegates to
1853
+ * the load-by-guid collaboration module (w7 / D-4). Kept as a class method so
1854
+ * existing structural-cast test access keeps resolving.
1855
+ */
1856
+ parseAssetPayload(
1857
+ kind: string,
1858
+ payload: Record<string, unknown>,
1859
+ refs?: string[],
1860
+ ):
1861
+ | Asset
1862
+ | Record<string, unknown>
1863
+ | undefined
1864
+ | { readonly ok: false; readonly error: ParseErrorDetail } {
1865
+ return parseAssetPayloadImpl(this, kind, payload, refs);
1866
+ }
1867
+
1868
+ /**
1869
+ * Parse a pack asset entry and return the payload + refs. Delegates to the
1870
+ * load-by-guid collaboration module (w7 / D-4). Kept as a class method so
1871
+ * existing structural-cast test access keeps resolving.
1872
+ */
1873
+ parseAndReturnAsset(assetEntry: {
1874
+ kind: string;
1875
+ payload: Record<string, unknown>;
1876
+ refs?: string[];
1877
+ }): Result<{ asset: Asset; refs: readonly string[] }, AssetError> {
1878
+ return parseAndReturnAssetImpl(this, assetEntry);
1879
+ }
1880
+ /** Return the legacy catalog snapshot when no GUID is supplied. */
1881
+ inspect(): InspectSnapshot;
1882
+ /** Return joined source/cook/package/runtime evidence for one GUID. */
1883
+ inspect(guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>>;
1884
+ inspect(guid?: string): InspectSnapshot | Promise<Result<AssetEvidence, AssetEvidenceError>> {
1885
+ if (guid !== undefined) return this.assetEvidenceAdapter.inspect(guid);
1886
+ const assets: InspectEntry[] = [];
1887
+ for (const [guid, envelope] of this.assetCatalog) {
1888
+ assets.push({
1889
+ guid,
1890
+ kind: envelope.payload.kind,
1891
+ name: this.resolveName(guid),
1892
+ });
1893
+ }
1894
+ return { assets };
1895
+ }
1896
+
1897
+ /** Verify the same GUID evidence chain through the injected SDK capability. */
1898
+ verifyByGuid(guid: string): Promise<Result<AssetEvidence, AssetEvidenceError>> {
1899
+ return this.assetEvidenceAdapter.verifyByGuid(guid);
1900
+ }
1901
+
1902
+ /**
1903
+ * Return a readonly snapshot of all catalogued assets (inlined + pack-index)
1904
+ * for enumeration by asset panels (AC-03 single source of truth).
1905
+ *
1906
+ * Merges entries from the private `packIndexCache` (prod path, carries
1907
+ * `packageUrl`) and `assetCatalog` (inlined / dev path, no URL). Each
1908
+ * GUID appears exactly once. Returns a fresh array on every call — the
1909
+ * internal Maps are never exposed (charter P4 consistent abstraction).
1910
+ *
1911
+ * plan-strategy section 2 D1; requirements AC-03; research Finding 5.
1912
+ *
1913
+ * @example
1914
+ * ```ts
1915
+ * for (const e of registry.listCatalog()) {
1916
+ * console.log(e.guid, e.kind, e.name, e.packageUrl);
1917
+ * }
1918
+ * ```
1919
+ */
1920
+ listCatalog(): readonly {
1921
+ guid: string;
1922
+ kind: string;
1923
+ name?: string;
1924
+ packageUrl: string;
1925
+ packageId?: CatalogEntry['packageId'];
1926
+ provenance?: CatalogEntry['provenance'];
1927
+ revision?: CatalogEntry['revision'];
1928
+ sourceKey?: CatalogEntry['sourceKey'];
1929
+ sourceIndex?: CatalogEntry['sourceIndex'];
1930
+ sourceOverrides?: CatalogEntry['sourceOverrides'];
1931
+ sourceOverrideDescriptors?: CatalogEntry['sourceOverrideDescriptors'];
1932
+ authoring?: CatalogEntry['authoring'];
1933
+ relations?: CatalogEntry['relations'];
1934
+ diagnostics?: CatalogEntry['diagnostics'];
1935
+ refs?: readonly string[];
1936
+ subject?: import('@forgeax/engine-types').CatalogSubject;
1937
+ execution?: import('@forgeax/engine-types').CookExecution;
1938
+ lifecycle?: import('@forgeax/engine-types').CatalogLifecycle;
1939
+ projection?: import('@forgeax/engine-types').CatalogProjection;
1940
+ /**
1941
+ * On-disk source-file path for external imported assets (FBX / GLB / HDR /
1942
+ * audio / font), relative to the game root. Editors locate the
1943
+ * `.meta.json` sidecar via `sourcePath + '.meta.json'` for CRUD; unlike
1944
+ * `packageUrl` (the runtime load artefact) it is stable across DDC cook
1945
+ * state. `undefined` for inline / dev-path assets (no sidecar, no CRUD).
1946
+ */
1947
+ sourcePath?: string;
1948
+ }[] {
1949
+ const seen = new Set<string>();
1950
+ const result: {
1951
+ guid: string;
1952
+ kind: string;
1953
+ name?: string;
1954
+ packageUrl: string;
1955
+ packageId?: CatalogEntry['packageId'];
1956
+ provenance?: CatalogEntry['provenance'];
1957
+ revision?: CatalogEntry['revision'];
1958
+ sourceKey?: CatalogEntry['sourceKey'];
1959
+ sourceIndex?: CatalogEntry['sourceIndex'];
1960
+ sourceOverrides?: CatalogEntry['sourceOverrides'];
1961
+ sourceOverrideDescriptors?: CatalogEntry['sourceOverrideDescriptors'];
1962
+ authoring?: CatalogEntry['authoring'];
1963
+ relations?: CatalogEntry['relations'];
1964
+ diagnostics?: CatalogEntry['diagnostics'];
1965
+ refs?: readonly string[];
1966
+ subject?: import('@forgeax/engine-types').CatalogSubject;
1967
+ execution?: import('@forgeax/engine-types').CookExecution;
1968
+ lifecycle?: import('@forgeax/engine-types').CatalogLifecycle;
1969
+ projection?: import('@forgeax/engine-types').CatalogProjection;
1970
+ sourcePath?: string;
1971
+ cookReceiptUrl?: string;
1972
+ }[] = [];
1973
+
1974
+ // Prod entries: packIndexCache carries packageUrl + optional name + refs.
1975
+ if (this.packIndexCache) {
1976
+ for (const [guidKey, entry] of this.packIndexCache) {
1977
+ seen.add(guidKey);
1978
+ result.push({
1979
+ guid: guidKey,
1980
+ kind: entry.kind,
1981
+ ...(entry.name !== undefined ? { name: entry.name } : {}),
1982
+ packageUrl: entry.packageUrl,
1983
+ ...(entry.packageId !== undefined ? { packageId: entry.packageId } : {}),
1984
+ ...(entry.provenance !== undefined ? { provenance: entry.provenance } : {}),
1985
+ ...(entry.revision !== undefined ? { revision: entry.revision } : {}),
1986
+ ...(entry.sourceKey !== undefined ? { sourceKey: entry.sourceKey } : {}),
1987
+ ...(entry.sourceIndex !== undefined ? { sourceIndex: entry.sourceIndex } : {}),
1988
+ ...(entry.sourceOverrides !== undefined
1989
+ ? { sourceOverrides: entry.sourceOverrides }
1990
+ : {}),
1991
+ ...(entry.sourceOverrideDescriptors !== undefined
1992
+ ? { sourceOverrideDescriptors: entry.sourceOverrideDescriptors }
1993
+ : {}),
1994
+ authoring: entry.authoring ?? authoringCapabilityForAssetKind(entry.kind),
1995
+ ...(entry.relations !== undefined ? { relations: entry.relations } : {}),
1996
+ ...(entry.diagnostics !== undefined ? { diagnostics: entry.diagnostics } : {}),
1997
+ ...(entry.refs !== undefined ? { refs: entry.refs } : {}),
1998
+ ...(entry.sourcePath !== undefined ? { sourcePath: entry.sourcePath } : {}),
1999
+ ...(entry.cookReceiptUrl !== undefined ? { cookReceiptUrl: entry.cookReceiptUrl } : {}),
2000
+ ...(entry.subject !== undefined ? { subject: entry.subject } : {}),
2001
+ ...(entry.execution !== undefined ? { execution: entry.execution } : {}),
2002
+ ...(entry.lifecycle !== undefined ? { lifecycle: entry.lifecycle } : {}),
2003
+ ...(entry.projection !== undefined ? { projection: entry.projection } : {}),
2004
+ });
2005
+ }
2006
+ }
2007
+
2008
+ // Inlined / dev-path entries: assetCatalog, no pack-index URL. The envelope
2009
+ // holds the authoritative AssetRef[] graph; flatten it to plain GUID edges
2010
+ // so both catalog paths expose the same refs: readonly string[] shape.
2011
+ for (const [guidKey, envelope] of this.assetCatalog) {
2012
+ if (!seen.has(guidKey)) {
2013
+ const name = envelope.name ?? this.resolveName(guidKey);
2014
+ result.push({
2015
+ guid: guidKey,
2016
+ kind: envelope.payload.kind,
2017
+ name,
2018
+ packageUrl: '',
2019
+ authoring: authoringCapabilityForAssetKind(envelope.payload.kind),
2020
+ subject: 'internal-asset',
2021
+ execution: 'direct',
2022
+ lifecycle: 'current',
2023
+ projection: {
2024
+ subject: 'internal-asset',
2025
+ execution: 'direct',
2026
+ lifecycle: 'current',
2027
+ operations: catalogOperationsFor({
2028
+ subject: 'internal-asset',
2029
+ execution: 'direct',
2030
+ lifecycle: 'current',
2031
+ }),
2032
+ },
2033
+ ...(envelope.refs.length > 0 ? { refs: envelope.refs.map((r) => r.guid) } : {}),
2034
+ });
2035
+ }
2036
+ }
2037
+
2038
+ return result;
2039
+ }
2040
+ }