@vgai/editor 0.2.0 → 0.4.0-canary.20260715.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (430) hide show
  1. package/README.md +24 -0
  2. package/dist/assets/axe-C7YBtOuM.js +30 -0
  3. package/dist/assets/browserAll-DDtGGE48.js +1 -0
  4. package/dist/assets/create-runtime-DbTlBlKG.js +1 -0
  5. package/dist/assets/{game-BI111o5f.js → game-BE0r7DMI.js} +3 -3
  6. package/dist/assets/game-BdTHR2_X.js +1 -0
  7. package/dist/assets/{game-pt_1lQLv.js → game-C3iQGSqo.js} +1 -1
  8. package/dist/assets/game-CcHfYxjP.js +1 -0
  9. package/dist/assets/game-Cqzj_lpD.js +1 -0
  10. package/dist/assets/game-DSZdeCHu.js +1 -0
  11. package/dist/assets/game-Dch9sAPc.js +1 -0
  12. package/dist/assets/{game-xsOho_wg.js → game-SAFn90pA.js} +3 -3
  13. package/dist/assets/game-loop-DMIgSMV-.js +1 -0
  14. package/dist/assets/{game-source-CvidN7AB.js → game-source-Dk83w26t.js} +1 -1
  15. package/dist/assets/{index-Bp5cecD6.js → index-4idIsHHJ.js} +2 -2
  16. package/dist/assets/{index-DL7RcQ0n.js → index-C-LhOTBN.js} +1 -1
  17. package/dist/assets/{index-Cs8xwv3e.js → index-CDkxceqE.js} +1 -1
  18. package/dist/assets/index-CQEfi217.js +15412 -0
  19. package/dist/assets/index-Dvi-V0NE.css +1 -0
  20. package/dist/assets/ingest-siblings-s0P5I1Ub.js +1 -0
  21. package/dist/assets/mount-manifest-DXMOlF79.js +1 -0
  22. package/dist/assets/react-18-C9eHn8x1.js +1 -0
  23. package/dist/assets/webworkerAll-Fn0e-ouF.js +1 -0
  24. package/dist/assets/world-documents-GM0a9Kv7.js +1 -0
  25. package/dist/index.html +15 -13
  26. package/dist/ingest/racing-game/vgai.game.json +5 -4
  27. package/dist/ingest/simcity/vgai.game.json +5 -4
  28. package/dist/ingest/tanks/vgai.game.json +5 -4
  29. package/dist/project-scripts.bundle.js +3917 -0
  30. package/dist/scenes/untitled.vscn.json +2 -0
  31. package/dist-server/packaged.mjs +7697 -3435
  32. package/package.json +31 -4
  33. package/scripts/probe-reporter.ts +349 -0
  34. package/scripts/run-probe.ts +2260 -0
  35. package/server/asset-catalog-audit.ts +268 -0
  36. package/server/asset-catalog-v2.ts +146 -0
  37. package/server/asset-library-routes.ts +276 -58
  38. package/server/canonical-path.ts +1 -1
  39. package/server/dev.ts +148 -44
  40. package/server/editor-server.ts +888 -61
  41. package/server/editor-sse.ts +115 -4
  42. package/server/harness-chat-service.ts +796 -0
  43. package/server/local-asset-catalog.ts +157 -22
  44. package/server/packaged.ts +51 -21
  45. package/server/process-shutdown.ts +136 -0
  46. package/server/prod.ts +9 -6
  47. package/server/project-hmr-files.ts +41 -0
  48. package/server/project-operations.ts +343 -0
  49. package/server/project-optimize-deps-entries.ts +4 -4
  50. package/server/project-output-writer.ts +156 -0
  51. package/server/project-validation.ts +140 -0
  52. package/server/project-view.ts +8 -50
  53. package/server/server-utils.ts +75 -10
  54. package/server/session-registry.ts +12 -0
  55. package/src/EditorContext.tsx +107 -3
  56. package/src/action-registry.ts +115 -17
  57. package/src/adapter-resolver.ts +213 -478
  58. package/src/asset-events.ts +64 -1
  59. package/src/asset-preview.ts +906 -0
  60. package/src/asset-selection.ts +121 -0
  61. package/src/asset-workflow/asset-capabilities.ts +259 -0
  62. package/src/asset-workflow/asset-editor-errors.ts +46 -0
  63. package/src/asset-workflow/asset-import-pipeline.ts +176 -0
  64. package/src/asset-workflow/asset-library-query.ts +107 -0
  65. package/src/asset-workflow/asset-types.ts +192 -0
  66. package/src/asset-workflow/asset-workflow-quality.ts +65 -0
  67. package/src/asset-workflow/import-contract.ts +113 -0
  68. package/src/asset-workflow/model-conversion.ts +126 -0
  69. package/src/asset-workflow/model-inspection.ts +185 -0
  70. package/src/asset-workflow/project-asset-commands.ts +23 -0
  71. package/src/asset-workflow/project-asset-health.ts +153 -0
  72. package/src/asset-workflow/project-asset-operations.ts +119 -0
  73. package/src/asset-workflow/thumbnail-system.ts +172 -0
  74. package/src/authoring/active-systems.ts +15 -0
  75. package/src/authoring/boundary-authoring-adapter.ts +16 -5
  76. package/src/authoring/composite-authoring-adapter.ts +305 -124
  77. package/src/authoring/design-time-layers.ts +300 -117
  78. package/src/authoring/edit-mode-authoring.ts +278 -293
  79. package/src/authoring/embed-only-adapter.ts +4 -2
  80. package/src/authoring/first-party-hierarchy-menu.ts +7 -2
  81. package/src/authoring/first-party-inspector/AddSectionMenu.tsx +5 -12
  82. package/src/authoring/first-party-inspector/EnvironmentSection.tsx +53 -126
  83. package/src/authoring/first-party-inspector/HeaderSection.tsx +54 -65
  84. package/src/authoring/first-party-inspector/is-first-party-selection.ts +30 -11
  85. package/src/authoring/first-party-inspector/register.tsx +13 -2
  86. package/src/authoring/ingest-authoring-adapter.ts +142 -45
  87. package/src/authoring/mount-failure-report.ts +5 -5
  88. package/src/authoring/provenance.ts +41 -0
  89. package/src/authoring/react-dom-authoring-adapter.ts +92 -92
  90. package/src/authoring/react-inspector-section.tsx +489 -51
  91. package/src/authoring/react-world-authoring-adapter.ts +541 -306
  92. package/src/authoring/story-overlay.ts +1 -1
  93. package/src/authoring/story-types.ts +11 -0
  94. package/src/authoring/vgai-scene-authoring-adapter.ts +54 -25
  95. package/src/authoring/viewport-tool-context.ts +78 -0
  96. package/src/authoring/world-canvas-viewport-state.ts +35 -0
  97. package/src/authoring/world-hidden-viewport.ts +186 -0
  98. package/src/authoring/world-pan-state.ts +33 -17
  99. package/src/authoring/world-session-state.ts +1 -1
  100. package/src/authoring/world2d-authoring-adapter.ts +109 -52
  101. package/src/availability-tick.ts +56 -0
  102. package/src/browser-play-entry.ts +5 -5
  103. package/src/browser-project-scripts.ts +1 -0
  104. package/src/build-identity.ts +15 -0
  105. package/src/command-listener.ts +893 -19
  106. package/src/components/AlignToolbar.tsx +74 -63
  107. package/src/components/AppRoot.tsx +193 -26
  108. package/src/components/ApplicationMenus.tsx +272 -0
  109. package/src/components/AssetBrowser.tsx +1450 -293
  110. package/src/components/AssetEditorShell.tsx +141 -0
  111. package/src/components/AssetImportDetails.tsx +218 -0
  112. package/src/components/AssetLibraryPanel.tsx +14 -0
  113. package/src/components/CameraInfo.tsx +11 -20
  114. package/src/components/CenterDocuments.tsx +585 -0
  115. package/src/components/CommandPalette.tsx +75 -30
  116. package/src/components/ConsolePanel.css +55 -0
  117. package/src/components/ConsolePanel.tsx +57 -112
  118. package/src/components/DebugConsolePanel.tsx +461 -0
  119. package/src/components/DebuggerPanel.tsx +165 -0
  120. package/src/components/DefaultEditorLayout.tsx +167 -231
  121. package/src/components/GameHierarchy.tsx +873 -290
  122. package/src/components/GamePerformanceOverlay.tsx +46 -0
  123. package/src/components/HarnessChatPanel.tsx +2352 -0
  124. package/src/components/HistoryPanel.tsx +226 -0
  125. package/src/components/Inspector.tsx +153 -99
  126. package/src/components/InspectorToolSection.tsx +6 -4
  127. package/src/components/MountFailureBanner.tsx +31 -48
  128. package/src/components/NetworkSection.tsx +25 -14
  129. package/src/components/OnlineAssetBrowser.tsx +794 -343
  130. package/src/components/OverlayReportBanner.tsx +38 -64
  131. package/src/components/PerformancePanel.tsx +206 -0
  132. package/src/components/PlayBar.tsx +93 -263
  133. package/src/components/PrefabSaveDialog.tsx +55 -127
  134. package/src/components/ProjectHeader.css +60 -0
  135. package/src/components/ProjectHeader.tsx +170 -105
  136. package/src/components/ProjectScreen.tsx +246 -184
  137. package/src/components/ReactCanvasControls.tsx +185 -0
  138. package/src/components/ResolutionPicker.tsx +85 -0
  139. package/src/components/RootActivateDialog.tsx +39 -68
  140. package/src/components/SaveDialog.tsx +55 -127
  141. package/src/components/SaveStatus.tsx +11 -29
  142. package/src/components/StartupLoadingScreen.tsx +96 -0
  143. package/src/components/StateWatchPanel.tsx +302 -0
  144. package/src/components/StatsOverlay.tsx +12 -5
  145. package/src/components/StatusBar.tsx +64 -0
  146. package/src/components/ThemeManagerDialog.css +89 -0
  147. package/src/components/ThemeManagerDialog.tsx +371 -0
  148. package/src/components/ToolHost.tsx +26 -15
  149. package/src/components/Toolbar.tsx +117 -214
  150. package/src/components/VgaiVoxelLogo.tsx +89 -0
  151. package/src/components/ViewportOverlay.tsx +97 -172
  152. package/src/components/ViewportPanel.tsx +130 -31
  153. package/src/components/WorkspaceDock.tsx +891 -0
  154. package/src/components/WorldSelectionOverlay.tsx +51 -63
  155. package/src/components/WorldTextEditor.tsx +9 -5
  156. package/src/components/asset-documents.tsx +390 -0
  157. package/src/components/asset-editor-persistence.ts +44 -0
  158. package/src/components/asset-selection-section.tsx +338 -0
  159. package/src/components/asset-viewers/AudioViewer.tsx +73 -21
  160. package/src/components/asset-viewers/GenericJsonViewer.tsx +26 -11
  161. package/src/components/asset-viewers/ImageViewer.tsx +43 -11
  162. package/src/components/asset-viewers/InputMapViewer.tsx +512 -134
  163. package/src/components/asset-viewers/MaterialAssetEditor.tsx +540 -0
  164. package/src/components/asset-viewers/ModelViewer.tsx +805 -121
  165. package/src/components/asset-viewers/OnlineAssetDetail.tsx +177 -60
  166. package/src/components/asset-viewers/SourceAssetViewer.tsx +121 -0
  167. package/src/components/asset-workflow.css +506 -0
  168. package/src/components/build-documents.tsx +696 -0
  169. package/src/components/core-utilities.tsx +75 -0
  170. package/src/components/data-documents.tsx +364 -0
  171. package/src/components/{DataPanel.tsx → data-editor.tsx} +138 -288
  172. package/src/components/debugger-panel-state.ts +57 -0
  173. package/src/components/inspector-widgets/AlignmentGrid.tsx +8 -14
  174. package/src/components/inspector-widgets/BorderEditor.tsx +41 -33
  175. package/src/components/inspector-widgets/ColorPicker.tsx +39 -39
  176. package/src/components/inspector-widgets/FontPicker.tsx +13 -21
  177. package/src/components/inspector-widgets/GradientEditor.tsx +11 -19
  178. package/src/components/inspector-widgets/ScrubbableInput.tsx +6 -3
  179. package/src/components/inspector-widgets/ShadowEditor.tsx +20 -33
  180. package/src/components/inspector-widgets/shared.tsx +90 -49
  181. package/src/components/inspectors/AnimationSection.tsx +39 -40
  182. package/src/components/inspectors/AudioSection.tsx +28 -39
  183. package/src/components/inspectors/BoneAttachmentSection.tsx +19 -24
  184. package/src/components/inspectors/CameraSection.tsx +14 -23
  185. package/src/components/inspectors/ComponentsSection.tsx +39 -43
  186. package/src/components/inspectors/JointsSection.tsx +34 -43
  187. package/src/components/inspectors/LightSection.tsx +90 -35
  188. package/src/components/inspectors/MaterialSection.tsx +137 -174
  189. package/src/components/inspectors/MeshSection.tsx +9 -17
  190. package/src/components/inspectors/NavigationSection.tsx +8 -15
  191. package/src/components/inspectors/ParticleSection.tsx +91 -76
  192. package/src/components/inspectors/PhysicsSection.tsx +42 -46
  193. package/src/components/inspectors/PostProcessingSection.tsx +28 -36
  194. package/src/components/inspectors/RenderingSection.tsx +12 -20
  195. package/src/components/inspectors/ShadowSection.tsx +7 -8
  196. package/src/components/inspectors/SplineSection.tsx +31 -42
  197. package/src/components/inspectors/TransformSection.tsx +14 -22
  198. package/src/components/patterns/Dialog.tsx +95 -0
  199. package/src/components/patterns/Fields.tsx +44 -0
  200. package/src/components/patterns/List.tsx +25 -0
  201. package/src/components/patterns/StateSurface.tsx +40 -0
  202. package/src/components/patterns/Surfaces.tsx +115 -0
  203. package/src/components/patterns/Tabs.tsx +80 -0
  204. package/src/components/patterns/Toolbar.tsx +51 -0
  205. package/src/components/patterns/Tree.tsx +72 -0
  206. package/src/components/primitives/Button.tsx +46 -0
  207. package/src/components/primitives/ColorInput.tsx +11 -47
  208. package/src/components/primitives/EditorIcon.tsx +99 -0
  209. package/src/components/primitives/FormControls.tsx +71 -0
  210. package/src/components/primitives/JsonInput.tsx +15 -2
  211. package/src/components/primitives/Layout.tsx +100 -0
  212. package/src/components/primitives/Menu.tsx +105 -0
  213. package/src/components/primitives/NumberInput.tsx +8 -35
  214. package/src/components/primitives/Panel.tsx +49 -44
  215. package/src/components/primitives/SectionHeader.tsx +10 -28
  216. package/src/components/primitives/Text.tsx +46 -0
  217. package/src/components/primitives/Tooltip.tsx +20 -12
  218. package/src/components/primitives/Vec3Input.tsx +3 -0
  219. package/src/components/primitives/banner-tones.ts +33 -0
  220. package/src/components/primitives/editor-icons.ts +102 -0
  221. package/src/components/primitives/panel-header-styles.ts +30 -0
  222. package/src/components/project-operation-documents.tsx +226 -0
  223. package/src/components/status-contributions.tsx +175 -0
  224. package/src/components/story-documents-register.ts +15 -0
  225. package/src/components/story-documents.tsx +1185 -0
  226. package/src/components/tool-documents.tsx +110 -0
  227. package/src/components/workspace-dock.css +293 -0
  228. package/src/components/workspace-history.ts +33 -0
  229. package/src/components/world-documents.tsx +145 -0
  230. package/src/components/xstate-documents.tsx +209 -0
  231. package/src/composite-screenshot.ts +248 -0
  232. package/src/design-system/index.ts +70 -0
  233. package/src/design-system-stories/Foundation.stories.tsx +183 -0
  234. package/src/design-system-stories/Patterns.stories.tsx +251 -0
  235. package/src/design-system-stories/Workspace.stories.tsx +538 -0
  236. package/src/doctor/report.ts +57 -13
  237. package/src/editor-api.ts +295 -31
  238. package/src/editor-compatibility.ts +200 -0
  239. package/src/editor-console.ts +35 -17
  240. package/src/editor-hotkeys.ts +85 -33
  241. package/src/editor-store.ts +538 -233
  242. package/src/editor-viewport.ts +160 -34
  243. package/src/entity-factory.ts +14 -3
  244. package/src/gizmo-registry.ts +21 -5
  245. package/src/harness-chat-editor-context.ts +37 -0
  246. package/src/harness-chat-indicator.ts +68 -0
  247. package/src/harness-chat-layout.ts +53 -0
  248. package/src/harness-chat-lifecycle.ts +170 -0
  249. package/src/harness-chat-reconnect.ts +85 -0
  250. package/src/harness-chat-types.ts +409 -0
  251. package/src/hierarchy-drop.ts +50 -0
  252. package/src/hierarchy-expansion-state.ts +100 -0
  253. package/src/hierarchy-menu-registry.ts +1 -1
  254. package/src/hierarchy-projection.ts +76 -0
  255. package/src/history/editor-session.ts +21 -0
  256. package/src/history/history-commands.ts +147 -0
  257. package/src/history/history-service.ts +904 -0
  258. package/src/history/json-history-resource.ts +165 -0
  259. package/src/history/persistence-coordinator.ts +35 -0
  260. package/src/history/project-file-history.ts +266 -0
  261. package/src/history/project-root-history-backends.ts +53 -0
  262. package/src/history/resource-registry.ts +209 -0
  263. package/src/history/snapshot-store.ts +108 -0
  264. package/src/history/source-history-backend.ts +374 -0
  265. package/src/history/types.ts +100 -0
  266. package/src/hmr-registration-group.ts +67 -0
  267. package/src/hmr-stable-react-context.ts +23 -0
  268. package/src/hosted-example.ts +12 -2
  269. package/src/hotkeys.ts +89 -18
  270. package/src/ingest/discovery-react.ts +9 -10
  271. package/src/ingest/discovery.ts +4 -4
  272. package/src/ingest/discovery2d.ts +5 -5
  273. package/src/ingest/games/bloom-composer/vgai.game.json +3 -3
  274. package/src/ingest/games/embed-bundle/vgai.game.json +3 -3
  275. package/src/ingest/games/games-fps/vgai.game.json +3 -3
  276. package/src/ingest/games/iframe-reachable/vgai.game.json +3 -3
  277. package/src/ingest/games/interactive-cubes/vgai.game.json +3 -3
  278. package/src/ingest/games/mismatched-three/vgai.game.json +3 -3
  279. package/src/ingest/games/own-three-bundled/vgai.game.json +3 -3
  280. package/src/ingest/games/pointerlock-maze/vgai.game.json +7 -4
  281. package/src/ingest/games-2d/bubbo-bubbo/vgai.game.json +3 -3
  282. package/src/ingest/games-2d/bunnymark/vgai.game.json +3 -3
  283. package/src/ingest/games-2d/flappy/vgai.game.json +3 -3
  284. package/src/ingest/games-2d/flappy-pixi/vgai.game.json +3 -3
  285. package/src/ingest/games-2d/puzzling-potions/vgai.game.json +3 -3
  286. package/src/ingest/games-2d/tilemap-camera/vgai.game.json +3 -3
  287. package/src/ingest/games-react/react-rpg/vgai.game.json +3 -3
  288. package/src/ingest/types.ts +1 -1
  289. package/src/ingest-mode.ts +47 -52
  290. package/src/ingest-siblings.ts +23 -33
  291. package/src/initial-scene.ts +1 -2
  292. package/src/main.tsx +16 -8
  293. package/src/manifest-project.ts +10 -12
  294. package/src/model-thumbnail.ts +261 -26
  295. package/src/module-mode.ts +44 -50
  296. package/src/play-log-events.ts +26 -0
  297. package/src/play-mode.ts +495 -401
  298. package/src/play-scene-adoption.ts +23 -0
  299. package/src/playground/main.ts +68 -24
  300. package/src/playwright-shim.ts +473 -0
  301. package/src/project-manager.ts +90 -10
  302. package/src/project-operations.ts +112 -0
  303. package/src/project-story-discovery.ts +25 -0
  304. package/src/project-tool-discovery.ts +43 -0
  305. package/src/scene-serializer.ts +0 -6
  306. package/src/scene-sync.ts +7 -2
  307. package/src/script-loader.ts +3 -3
  308. package/src/skeleton-helper.ts +57 -0
  309. package/src/storage/seed.ts +68 -8
  310. package/src/stories/StoryPreviewMount.tsx +265 -0
  311. package/src/stories/action-stories.fixture.tsx +44 -0
  312. package/src/stories/button-stories.fixture.tsx +50 -0
  313. package/src/stories/compose-project-stories.ts +182 -0
  314. package/src/stories/loader-stories.fixture.tsx +53 -0
  315. package/src/stories/story-discovery.ts +130 -0
  316. package/src/stories/story-registry.ts +146 -0
  317. package/src/theme-css.ts +1049 -0
  318. package/src/theme-library.ts +238 -0
  319. package/src/theme-preference.ts +130 -0
  320. package/src/theme.ts +527 -0
  321. package/src/tool-loader.ts +80 -24
  322. package/src/ui-source/inspect.ts +27 -4
  323. package/src/ui-source/source-write-backend.ts +83 -22
  324. package/src/widgets/index.ts +9 -18
  325. package/src/workspace-aux-commands.ts +11 -0
  326. package/src/workspace-dock-controller.ts +64 -0
  327. package/src/workspace-document-ids.ts +5 -0
  328. package/src/workspace-document-registry.ts +367 -0
  329. package/src/workspace-state-persistence.ts +455 -0
  330. package/src/workspace-status-registry.ts +110 -0
  331. package/src/workspace-utility-commands.ts +49 -0
  332. package/src/workspace-utility-registry.ts +161 -0
  333. package/src/world-document-routing.ts +16 -0
  334. package/src/xstate-inspect/XStateMachineInspector.tsx +544 -0
  335. package/src/xstate-inspect/character-animation-machine.fixture.ts +74 -0
  336. package/src/xstate-inspect/use-live-actor-state.ts +39 -0
  337. package/src/xstate-inspect/xstate-graph.ts +265 -0
  338. package/src/xstate-inspect/xstate-layout.ts +76 -0
  339. package/src/z-index.ts +26 -0
  340. package/template/.claude/skills/editor/SKILL.md +129 -90
  341. package/template/AGENTS.md +1110 -0
  342. package/template/CLAUDE.md +1 -512
  343. package/template/IDIOMS.md +50 -0
  344. package/template/check-idioms.ts +706 -0
  345. package/template/manifest-entry-modules-plugin.ts +53 -0
  346. package/template/package.json +13 -4
  347. package/template/public/scenes/default.scn2d.json +6 -0
  348. package/template/public/scenes/default.vscn.json +7 -1
  349. package/template/public/scenes/untitled.vscn.json +10 -0
  350. package/template/scripts/playtest.ts +40 -0
  351. package/template/server/loopback.ts +75 -0
  352. package/template/server/rooms/arena-room.ts +69 -1
  353. package/template/server/rooms/game-room.ts +68 -1
  354. package/template/src/data/README.md +9 -4
  355. package/template/src/data/data-ref.ts +35 -0
  356. package/template/src/data/tuning.schema.ts +1 -1
  357. package/template/src/main.ts +41 -62
  358. package/template/src/manifest-entry-modules.d.ts +3 -0
  359. package/template/src/operations/README.md +88 -0
  360. package/template/src/runtime/pixi-adapter.ts +24 -0
  361. package/template/src/scripts/components/data-spinner.ts +43 -2
  362. package/template/src/scripts/components/spin-lap-math.ts +27 -0
  363. package/template/src/tools/README.md +5 -3
  364. package/template/src/tools/example.tool.tsx +13 -7
  365. package/template/src/ui/Button.stories.tsx +66 -0
  366. package/template/src/ui/RebindPanel.tsx +2 -6
  367. package/template/src/ui/game.tsx +17 -0
  368. package/template/tests/acceptance/example.spec.ts +64 -0
  369. package/template/tests/logic/example.test.ts +31 -0
  370. package/template/tests/logic/room.test.ts +100 -0
  371. package/template/tests/tsconfig.json +30 -0
  372. package/template/validate-manifest.ts +5 -5
  373. package/template/validate-scenes.ts +50 -18
  374. package/template/vgai.game.json +20 -13
  375. package/template/vite.config.ts +77 -16
  376. package/vite-plugin-ui-oid.ts +261 -17
  377. package/dist/assets/CCDIKSolver-Dz-ysxZF.js +0 -1
  378. package/dist/assets/SelectionBox-BXsv_6aH.js +0 -1
  379. package/dist/assets/browser-project-scripts-DOru4L1x.js +0 -2
  380. package/dist/assets/browserAll-CEkWYlFk.js +0 -1
  381. package/dist/assets/create-runtime-DYIWr3va.js +0 -1
  382. package/dist/assets/data-asset-Bb9sIM7i.js +0 -5
  383. package/dist/assets/game-8SDZPPgH.js +0 -1
  384. package/dist/assets/game-CevorxyV.js +0 -1
  385. package/dist/assets/game-Di7XlywD.js +0 -1
  386. package/dist/assets/game-DjnCaw8R.js +0 -1
  387. package/dist/assets/game-Q9A0aXSV.js +0 -1
  388. package/dist/assets/index-CPVV6pjw.js +0 -1
  389. package/dist/assets/index-CpOnYyeD.js +0 -213
  390. package/dist/assets/index-Dr8H_6Rl.js +0 -1
  391. package/dist/assets/index-_bCaipUk.js +0 -13650
  392. package/dist/assets/ingest-siblings-Dz8eEqrV.js +0 -1
  393. package/dist/assets/mount-manifest-Bhk0ohsl.js +0 -1
  394. package/dist/assets/scene-query-BivAHhJu.js +0 -1
  395. package/dist/assets/webworkerAll-BLrH0F6F.js +0 -1
  396. package/dist/assets/xstate-animation-binding-1NGLmw6y.js +0 -1
  397. package/dist/assets/xstate.esm-BgUD33nl.js +0 -3
  398. package/src/authoring/scene-ui-layer.ts +0 -485
  399. package/src/authoring/ui-authoring-adapter.ts +0 -325
  400. package/src/authoring/ui-hierarchy-menu.ts +0 -40
  401. package/src/authoring/ui-inspector-sections.tsx +0 -156
  402. package/src/authoring/undo-timeline.ts +0 -145
  403. package/src/components/BottomPanel.tsx +0 -326
  404. package/src/components/BuildPanel.tsx +0 -455
  405. package/src/components/FolderTree.tsx +0 -179
  406. package/src/components/RightPanel.tsx +0 -166
  407. package/src/components/WorldContextMenu.tsx +0 -257
  408. package/src/components/asset-viewers/AssetViewer.tsx +0 -38
  409. package/src/ingest/games-react/react-rpg/src/ui/game-state.tsx +0 -129
  410. package/src/scene-ui-mode/active-scene-ui.ts +0 -58
  411. package/src/scene-ui-mode/scene-ui-palette-panel.tsx +0 -152
  412. package/src/scene-ui-mode/scene-ui-timeline-tab.tsx +0 -29
  413. package/src/scene-ui-mode/ui-prefab-dialog-host.tsx +0 -74
  414. package/src/scene-ui-mode/ui-prefab-hierarchy-menu.ts +0 -49
  415. package/src/scene-ui-mode/ui-prefab-io.ts +0 -76
  416. package/src/ui-editor/inspector.tsx +0 -563
  417. package/src/ui-editor/node-ops.ts +0 -266
  418. package/src/ui-editor/overlay.tsx +0 -380
  419. package/src/ui-editor/palette.tsx +0 -114
  420. package/src/ui-editor/react-store.ts +0 -78
  421. package/src/ui-editor/timeline-panel.tsx +0 -443
  422. package/src/ui-editor/ui-edit-store.ts +0 -552
  423. package/src/ui-editor/ui-prefab.ts +0 -95
  424. package/template/project.json +0 -9
  425. package/template/src/scripts/main.ts +0 -94
  426. package/template/src/ui/DefaultHud.tsx +0 -40
  427. package/template/src/ui/game-state.tsx +0 -37
  428. package/template/src/ui/mount-default-hud.tsx +0 -19
  429. package/template/src/ui/mount-ui.ts +0 -15
  430. package/vite-plugin-react-world-provider.ts +0 -81
package/src/play-mode.ts CHANGED
@@ -11,37 +11,42 @@
11
11
  */
12
12
 
13
13
  import type { AuthoringAdapter } from '@engine/adapter';
14
- import type { VgaiMountedGame } from '@engine/adapter/vgai-scene-game-adapter';
15
- import { assertNever } from '@engine/adapter/world-kind';
14
+ import { assertNever } from '@engine/adapter/adapter-surface';
15
+ import { getSeededRandom, type SeededRandom } from '@engine/core/seeded-random';
16
16
  import { _engineLogActive } from '@engine/dev/logger';
17
+ import type { PerformanceProfiler } from '@engine/dev/performance-profiler';
17
18
  import type { GameComponentClass } from '@engine/ecs/game-component';
18
19
  import * as gameComponentModule from '@engine/ecs/game-component';
19
20
  import { logHmrSwapMiss } from '@engine/ecs/hmr-swap-report';
20
21
  import type { GameSession } from '@engine/runtime/create-runtime';
21
- import { isFirstPartyMounted, type WorldInstance } from '@engine/runtime/game';
22
+ import {
23
+ type DebugVirtualInputTarget,
24
+ getDebugRegistry,
25
+ type RunTicksOptions,
26
+ } from '@engine/runtime/debug-registry';
27
+ import { type GameLoop, isFirstPartyMounted, type WorldInstance } from '@engine/runtime/game';
22
28
  import { parseSceneFile, SceneParseError } from '@engine/scene/parse';
23
- import type { Overlay2D } from '@engine/world2d/authoring-2d';
24
29
  import { createPhysics2DRegistry } from '@engine/world2d/physics2d-registry';
25
30
  import { createPhysicsAdapter2D } from '@engine/world2d/system-adapters-2d';
26
31
  import gsap from 'gsap';
27
32
  import * as THREE from 'three';
28
- import { resolveAllWorldEntries, resolveWorldAdapter } from './adapter-resolver';
29
33
  import {
30
- getActiveAuthoring,
31
- getAuthoringOverride,
32
- setActiveAuthoring,
33
- } from './authoring/active-adapter';
34
+ clearProjectComponentHotOverrides,
35
+ registerProjectComponentHotOverride,
36
+ resolveAllWorldEntries,
37
+ } from './adapter-resolver';
38
+ import { getAuthoringOverride, setActiveAuthoring } from './authoring/active-adapter';
34
39
  import { setActiveSystems } from './authoring/active-systems';
40
+ import { BoundaryAuthoringAdapter } from './authoring/boundary-authoring-adapter';
35
41
  import {
36
42
  CompositeAuthoringAdapter,
37
43
  type CompositeChild,
38
44
  } from './authoring/composite-authoring-adapter';
45
+ import { resolveFocusedThreejsWorldId } from './authoring/edit-mode-authoring';
39
46
  import { createEphemeralPersistence } from './authoring/ephemeral-persistence';
40
47
  import { IngestAuthoringAdapter } from './authoring/ingest-authoring-adapter';
41
- import type { IngestOverlay } from './authoring/ingest-overlay';
42
48
  import { ReactWorldAuthoringAdapter } from './authoring/react-world-authoring-adapter';
43
- import { type UndoAdapter, unregisterUndoAdapter } from './authoring/undo-timeline';
44
- import { loadWorldOverlay, saveWorldOverlay, worldOverlayPath } from './authoring/world-overlay';
49
+ import { VgaiSceneAuthoringAdapter } from './authoring/vgai-scene-authoring-adapter';
45
50
  import { World2DAuthoringAdapter } from './authoring/world2d-authoring-adapter';
46
51
  import { importFromSource, registerRuntimeModules } from './browser-transpile';
47
52
  import { watchScriptChanges } from './browser-watch-reload';
@@ -52,11 +57,11 @@ import { editorConsole } from './editor-console';
52
57
  import { getEditorMode } from './editor-mode';
53
58
  import type { EditorStore } from './editor-store';
54
59
  import { installGatedGameGlobals, setGameInputGate } from './gated-globals';
55
- import { exampleDispatchFor } from './hosted-example';
60
+ import { hierarchyProjectionFromProjectConfig } from './hierarchy-projection';
56
61
  import { fetchGameManifest } from './manifest-project';
62
+ import { debugEventsToLogEntries } from './play-log-events';
63
+ import { adoptThreePlaySceneIfAvailable } from './play-scene-adoption';
57
64
  import { getCurrentProject } from './project-manager';
58
- import { loadProjectScripts, type ProjectScripts, reloadProjectScripts } from './script-loader';
59
- import { createHttpSourceWriteBackend } from './ui-source/source-write-backend';
60
65
 
61
66
  /** Context needed by the orchestrator (passed from ViewportPanel). */
62
67
  export interface PlayModeContext {
@@ -70,6 +75,52 @@ export interface PlayModeContext {
70
75
  let _gameContainerEl: HTMLElement | null = null;
71
76
  let _ctx: PlayModeContext | null = null;
72
77
  let _session: GameSession | null = null;
78
+ // D15/T-D15.6 — whether the CURRENTLY running session's manifest declares
79
+ // `determinism.seededRandom` (docs/D15-DETERMINISM-DESIGN.md §2.a). Set
80
+ // alongside `_session` in `enterPlayMode` (the `manifest` var is in scope
81
+ // only inside that function's try block — this is the module-level home the
82
+ // `set-seed` relay case and `collectState`'s `deterministic` field both
83
+ // read), reset alongside `_session = null` in `exitPlayMode`. `false` for
84
+ // every legacy (no-manifest) project and for the multi-world/single-world
85
+ // manifest branches alike — read straight off the SAME `manifest` object
86
+ // each branch already fetches.
87
+ let _playDeterminismDeclared = false;
88
+ const sessionListeners = new Set<() => void>();
89
+ const restartRequiredListeners = new Set<() => void>();
90
+ let restartRequiredReason: string | null = null;
91
+
92
+ export function getRestartRequiredReason(): string | null {
93
+ return restartRequiredReason;
94
+ }
95
+
96
+ export function subscribeRestartRequired(listener: () => void): () => void {
97
+ restartRequiredListeners.add(listener);
98
+ return () => restartRequiredListeners.delete(listener);
99
+ }
100
+
101
+ export function markRestartRequired(reason: string): void {
102
+ restartRequiredReason = reason;
103
+ for (const listener of restartRequiredListeners) listener();
104
+ }
105
+
106
+ function clearRestartRequired(): void {
107
+ if (restartRequiredReason === null) return;
108
+ restartRequiredReason = null;
109
+ for (const listener of restartRequiredListeners) listener();
110
+ }
111
+
112
+ function notifySessionListeners(): void {
113
+ for (const listener of sessionListeners) listener();
114
+ }
115
+
116
+ export function subscribeGameSession(listener: () => void): () => void {
117
+ sessionListeners.add(listener);
118
+ return () => sessionListeners.delete(listener);
119
+ }
120
+
121
+ export function getGameProfiler(): PerformanceProfiler | null {
122
+ return _session?.game.profiler ?? null;
123
+ }
73
124
 
74
125
  /**
75
126
  * Play-mode generation counter. Bumped on every enterPlayMode and every
@@ -82,29 +133,21 @@ let _session: GameSession | null = null;
82
133
  * (RAF loop, Rapier world, WebGL context never released).
83
134
  */
84
135
  let _playEpoch = 0;
136
+ // #146 — when the CURRENT play run began (ms epoch), or null while stopped.
137
+ // The relay snapshot's `pageErrors` uses this as its freshness fence.
138
+ let _playStartedAtMs: number | null = null;
85
139
 
86
140
  // T6.3: install the gated window/document proxies once so the dev server's/
87
141
  // browser-transpile's GAME_GLOBALS_PRELUDE (prepended to project modules) has
88
142
  // something to resolve to. No-op outside a browser (headless unit tests).
89
143
  installGatedGameGlobals();
90
144
 
91
- /**
92
- * The first-party game runtime behind the current session. HMR (component
93
- * hot-swap, warm restart) and physics edit-sync are inherently first-party, so
94
- * play-mode reaches the `GameContext` + `hotReload` via the `VgaiMountedGame`
95
- * extras on `session.mounted`. The generic host (`createGameRuntime`) no longer
96
- * exposes these — that confinement is the adapter inversion.
97
- */
98
145
  /** e2e counter: proofs read `window.__vgaiHmrCount` to assert HMR fired. */
99
146
  function bumpHmrCount(): void {
100
147
  const w = window as unknown as { __vgaiHmrCount?: number };
101
148
  w.__vgaiHmrCount = (w.__vgaiHmrCount ?? 0) + 1;
102
149
  }
103
150
 
104
- function firstParty(session: GameSession): VgaiMountedGame {
105
- return session.mounted as VgaiMountedGame;
106
- }
107
-
108
151
  /**
109
152
  * Fan HMR's `hotSwap` out across EVERY first-party world in the session
110
153
  * (§7.1-4, probes 2/2b) — both call sites below used to reach only
@@ -116,7 +159,7 @@ function firstParty(session: GameSession): VgaiMountedGame {
116
159
  * though the instance was alive the whole time, just in a manager this call
117
160
  * never consulted; structurally identical to "you renamed the class."
118
161
  *
119
- * Iterates `session.game.worlds` (declaration order), skipping any
162
+ * Iterates `session.game.roots` (declaration order), skipping any
120
163
  * non-first-party mount (`isFirstPartyMounted` — an opaque/foreign or react
121
164
  * mount has no `ComponentManager` to hotSwap against), and calls each
122
165
  * first-party world's OWN `hotSwap` with its own swap-miss warning
@@ -127,7 +170,7 @@ function firstParty(session: GameSession): VgaiMountedGame {
127
170
  * (`logHmrSwapMiss`), only when the total across every first-party world is
128
171
  * zero.
129
172
  *
130
- * Returns the total number of live instances swapped, summed across worlds.
173
+ * Returns the total number of live instances swapped, summed across roots.
131
174
  */
132
175
  export function hotSwapAcrossWorlds(
133
176
  session: GameSession,
@@ -135,7 +178,7 @@ export function hotSwapAcrossWorlds(
135
178
  NewClass: GameComponentClass,
136
179
  ): number {
137
180
  let total = 0;
138
- for (const world of session.game.worlds) {
181
+ for (const world of session.game.roots) {
139
182
  if (!isFirstPartyMounted(world.mounted)) continue;
140
183
  total += world.mounted.ctx.components.hotSwap(name, NewClass, { warnOnMiss: false });
141
184
  }
@@ -148,7 +191,7 @@ export function hotSwapAcrossWorlds(
148
191
  /**
149
192
  * Warm-restart's fan-out investigation (§7.1-4's second half): the
150
193
  * non-component-edit HMR branch below re-runs ONLY the default world's
151
- * `hotReload` — it does NOT fan out across `session.game.worlds` the way
194
+ * `hotReload` — it does NOT fan out across `session.game.roots` the way
152
195
  * {@link hotSwapAcrossWorlds} does for true-HMR component swaps. This is a
153
196
  * STRUCTURAL limitation, not an oversight left for later:
154
197
  *
@@ -156,7 +199,7 @@ export function hotSwapAcrossWorlds(
156
199
  * `world2d/pixi-game-adapter.ts`'s pixi mount and `create-runtime.ts`'s
157
200
  * react mount expose no such method at all, so there is no capability to
158
201
  * fan out to on a non-threejs world even in principle.
159
- * 2. Even restricted to first-party THREEJS worlds, `reloadProjectScripts`
202
+ * 2. Even restricted to first-party THREEJS roots, `reloadProjectScripts`
160
203
  * (`script-loader.ts`) resolves exactly ONE project entry
161
204
  * (`src/scripts/main.ts` by default) and returns ONE `setup` function —
162
205
  * it has no per-world mapping, so there is no way to know which world a
@@ -168,15 +211,15 @@ export function hotSwapAcrossWorlds(
168
211
  * restart, from the `vgai:script-update` handler below.
169
212
  */
170
213
  export function warnIfOtherFirstPartyWorldsUnrestarted(session: GameSession): void {
171
- const worlds = session.game?.worlds;
172
- if (!worlds || worlds.length <= 1) return;
214
+ const roots = session.game?.roots;
215
+ if (!roots || roots.length <= 1) return;
173
216
  const defaultWorldId = session.game?.defaultWorld.id;
174
- const otherFirstParty = worlds.some(
217
+ const otherFirstParty = roots.some(
175
218
  (w) => w.id !== defaultWorldId && isFirstPartyMounted(w.mounted),
176
219
  );
177
220
  if (otherFirstParty) {
178
221
  editorConsole.warn(
179
- 'Warm restart applied to the default world only — components in other worlds keep ' +
222
+ 'Warm restart applied to the default world only — components in other roots keep ' +
180
223
  'running old code until play restarts (structural limitation: hotReload is a first-party ' +
181
224
  'threejs-mount-only capability, and reloadProjectScripts resolves a single ' +
182
225
  'src/scripts/main.ts entry with no per-world mapping).',
@@ -218,147 +261,140 @@ let _resizeObserver: ResizeObserver | null = null;
218
261
  let _unsubStore: (() => void) | null = null;
219
262
  /** Browser-mode component-source watch (Phase A2); null in server mode / stopped. */
220
263
  let _unsubBrowserScriptWatch: (() => void) | null = null;
221
- /** True for the CURRENT session iff it mounted through the worlds path with
222
- * more than one world — decides which of `installPlayAuthoring` (ephemeral,
223
- * single `.vscn` preview) vs `installMultiWorldAuthoring` (real per-world
224
- * overlay persistence) ran, so `exitPlayMode` tears down the right one. */
225
- let _isMultiWorldSession = false;
226
264
  /**
227
265
  * The authoring override that was active before THIS play session installed its
228
266
  * own (normally `null` — nothing else authors while playing today, but this
229
- * restores whatever was there rather than assuming null; see
230
- * `installPlayAuthoring`/`restorePriorAuthoring`). `undefined` ⇒ this play
267
+ * restores whatever was there rather than assuming null. `undefined` ⇒ this play
231
268
  * session never installed one (e.g. it bailed before adopting the scene) — exit
232
269
  * must then leave the authoring override untouched.
233
270
  */
234
271
  let _priorAuthoringOverride: AuthoringAdapter | null | undefined;
235
272
 
236
273
  /**
237
- * Play adoption drives the SAME authoring adapter the editor already uses for
238
- * `store` (first-party today — `getActiveAuthoring` falls back to it absent an
239
- * override), just with its `persistence` swapped for the ephemeral provider
240
- * (design `docs/PERSISTENCE-PROVIDER-DESIGN.md` §2/§7 slice 1): play-time edits
241
- * apply to the live game scene exactly as before, but the store's autosave/
242
- * saveNow guards now see `isDirty() → false` / no real destination instead of
243
- * relying on the `_playState` flag alone. `undo`/`redo`/`subscribe` are rebound
244
- * explicitly (a plain spread would keep them pointing at `base`'s `this`, which
245
- * is fine for arrow-function fields but not for prototype methods).
274
+ * Replace an adapter's persistence surface without changing its live authoring
275
+ * providers. Play changes are session-local for every world count (D19).
246
276
  */
247
- function installPlayAuthoring(store: EditorStore): void {
248
- _priorAuthoringOverride = getAuthoringOverride();
249
- const base = getActiveAuthoring(store);
250
- const wrapped: AuthoringAdapter = {
251
- ...base,
252
- persistence: createEphemeralPersistence(() => store.getDocument()),
253
- };
254
- // Only rebind when `base` actually implements these (exactOptionalPropertyTypes
255
- // rejects assigning `undefined` to an already-optional property explicitly).
256
- if (base.subscribe) wrapped.subscribe = base.subscribe.bind(base);
257
- if (base.undo) wrapped.undo = base.undo.bind(base);
258
- if (base.redo) wrapped.redo = base.redo.bind(base);
259
- setActiveAuthoring(wrapped);
277
+ function withEphemeralPersistence(
278
+ base: AuthoringAdapter,
279
+ serialize: () => unknown,
280
+ ): AuthoringAdapter {
281
+ const capabilities = { ...base.capabilities, persist: false };
282
+ const persistence = createEphemeralPersistence(serialize);
283
+ return new Proxy(base, {
284
+ get(target, property) {
285
+ if (property === 'capabilities') return capabilities;
286
+ if (property === 'persistence') return persistence;
287
+ const value = Reflect.get(target, property, target) as unknown;
288
+ // Preserve the original class receiver for prototype methods while the
289
+ // Proxy itself preserves `instanceof` identity for inspector routing.
290
+ return typeof value === 'function' ? value.bind(target) : value;
291
+ },
292
+ });
260
293
  }
261
294
 
262
295
  /** Restore whatever authoring override (if any) was active before play started. */
263
296
  function restorePriorAuthoring(): void {
264
- if (_priorAuthoringOverride === undefined) return; // installPlayAuthoring never ran
297
+ if (_priorAuthoringOverride === undefined) return;
265
298
  setActiveAuthoring(_priorAuthoringOverride);
266
299
  _priorAuthoringOverride = undefined;
267
300
  }
268
301
 
269
302
  /**
270
- * Per-world adapters built for the CURRENT multi-world session, tracked ONLY so
271
- * `exitMultiWorldAuthoring` can unregister any that self-registered with the
272
- * global undo timeline. As of v4 §7.1-13, `IngestAuthoringAdapter` AND
273
- * `World2DAuthoringAdapter` both self-register (the `ReactWorldAuthoringAdapter`
274
- * branch does too) — mirrors `ingest-mode.ts`'s teardown of its own single
275
- * adapter.
303
+ * Per-world adapters built for the current play session, retained so
304
+ * teardown can dispose their session-scoped history resources.
276
305
  */
277
- let _multiWorldChildren: AuthoringAdapter[] = [];
306
+ let _playWorldResources: AuthoringAdapter[] = [];
278
307
 
279
308
  /**
280
- * Build ONE {@link AuthoringAdapter} per mounted world (T6.1 slice 3,
281
- * docs/MULTI-WORLD-DESIGN.md §1.F/§3 slice 3) and install the N-ary
282
- * {@link CompositeAuthoringAdapter} over all of them as the active authoring
283
- * override.
284
- *
285
- * Study finding (this slice): `resolveAllWorlds`'s own doc comment records that
286
- * NO world in a multi-world manifest gets the live editor document/editorPreview
287
- * — every world mounts from its own on-disk `scene`/`entry`, single-world OR
288
- * not. So there is no "the store's document IS this world's live scene" world
289
- * the way `VgaiSceneAuthoringAdapter` assumes for the single-world path — EVERY
290
- * world here (including a `kind:'threejs'` world) gets a live-tree REFLECTION
291
- * adapter, the same shape `ingest-mode.ts` already uses for an unmodified game's
292
- * `Object3D` tree: `IngestAuthoringAdapter` for a threejs world's `threeRoot()`,
293
- * `World2DAuthoringAdapter` for a pixijs world's `pixiRoot()`. Persistence is
294
- * REAL (not the ephemeral discard-on-stop wrapper `installPlayAuthoring` uses
295
- * for the single-world `.vscn` preview path) — each per-world adapter's overlay
296
- * (§1.G: `.vgai/overlays/<world-id>.json`, project-root-relative, `authoring/
297
- * world-overlay.ts`) is the honest floor a manifest-mounted world has today,
298
- * exactly like `ingest-mode.ts`'s own overlay persistence (both its three-side
299
- * and — T6.1 slice 4 — pixi-side ingest sessions) —
300
- * this is not a "preview of an editable document" session the way single-world
301
- * play is, so ephemeral-wrapping it would silently discard the ONLY persistence
302
- * mechanism these worlds have.
303
- *
304
- * `store` is used ONLY as the editor-global selection bag + change-notification
305
- * bus (`selectedEntityIds`/`selectMultiple`/`subscribe`/`notifyIngestEdit`) —
306
- * neither per-world adapter reads/writes `store`'s document, matching how
307
- * `ingest-mode.ts` already uses the SAME store for the same narrow purpose
308
- * over a live foreign tree.
309
- *
310
- * A `kind: 'react'` world (T6.2 slice 2, `docs/REACT-WORLD-DESIGN.md` §1.D/§3
311
- * slice 2) gets a {@link ReactWorldAuthoringAdapter} over its `reactRoot()` DOM —
312
- * NOT the overlay-file persistence the threejs/pixijs branches use: a react
313
- * world's truth is JSX SOURCE (D4), so its persistence is the SAME immediate
314
- * source-write seam `UIAuthoringAdapter` already uses
315
- * (`../ui-source/source-write-backend.ts`), wired only under the dev server
316
- * (`import.meta.env.DEV`) exactly like `edit-mode-authoring.ts`'s scene-UI
317
- * child does — a hosted/no-dev-server session degrades to selection/
318
- * inspection only, writes reporting unavailable (never silently faked).
309
+ * D19's one play authoring path for N >= 1. The adopted default Three.js root
310
+ * keeps first-party scene authoring; sibling native roots use their direct
311
+ * reflection adapters. React source writes are deliberately absent in play.
319
312
  */
320
- async function installMultiWorldAuthoring(
313
+ function installPlayWorldAuthoring(
321
314
  store: EditorStore,
322
- worlds: readonly WorldInstance[],
323
- ): Promise<void> {
315
+ roots: readonly WorldInstance[],
316
+ manifest: Awaited<ReturnType<typeof fetchGameManifest>>,
317
+ ): void {
324
318
  _priorAuthoringOverride = getAuthoringOverride();
325
319
  const children: CompositeChild[] = [];
326
- for (const world of worlds) {
320
+ const resources: AuthoringAdapter[] = [];
321
+ for (const world of roots) {
322
+ const declaration = manifest?.roots.find((candidate) => candidate.id === world.id);
323
+ const composition = declaration
324
+ ? {
325
+ zOrder: declaration.zOrder,
326
+ pausable: declaration.pausable,
327
+ ...(declaration.scene
328
+ ? { content: `Scene · ${declaration.scene}` }
329
+ : declaration.entry
330
+ ? { content: `Entry · ${declaration.entry}` }
331
+ : {}),
332
+ }
333
+ : {};
334
+ // D-N4/D-N8: an ingested React game's DOM is disclosed as a read-only
335
+ // boundary. Normalizing composition must never silently grant JSX/DOM
336
+ // authoring to vendored source; the universal tree and write authority
337
+ // are independent concerns.
338
+ if (declaration?.adapter.identity === 'ingest-react') {
339
+ children.push({
340
+ worldId: world.id,
341
+ kind: world.kind,
342
+ adapter: new BoundaryAuthoringAdapter(store, {
343
+ id: world.id,
344
+ kind: world.kind,
345
+ adapter: declaration.adapter.identity,
346
+ entryOrScenePath: declaration.entry ?? declaration.scene,
347
+ zOrder: declaration.zOrder,
348
+ pausable: declaration.pausable,
349
+ }),
350
+ ...composition,
351
+ });
352
+ continue;
353
+ }
327
354
  if (world.kind === 'threejs') {
328
- const overlay = await loadWorldOverlay<IngestOverlay>(world.id);
329
- const adapter = new IngestAuthoringAdapter(store, world.threeRoot(), {
330
- overlay,
331
- persist: (o) => saveWorldOverlay(world.id, o),
332
- destination: worldOverlayPath(world.id),
355
+ const isAdoptedScene = world.threeRoot() === store.scene;
356
+ const adapter = isAdoptedScene
357
+ ? new VgaiSceneAuthoringAdapter(store)
358
+ : new IngestAuthoringAdapter(store, world.threeRoot());
359
+ resources.push(adapter);
360
+ children.push({
361
+ worldId: world.id,
362
+ kind: world.kind,
363
+ adapter: withEphemeralPersistence(adapter, () =>
364
+ isAdoptedScene ? store.getDocument() : {},
365
+ ),
366
+ ...composition,
333
367
  });
334
- children.push({ worldId: world.id, kind: world.kind, adapter });
335
368
  } else if (world.kind === 'pixijs') {
336
- const overlay = await loadWorldOverlay<Overlay2D>(world.id);
337
369
  const physics = createPhysicsAdapter2D(world.physics2d ?? createPhysics2DRegistry());
338
- const adapter = new World2DAuthoringAdapter(world.pixiRoot(), physics, store, {
339
- overlay,
340
- persist: (o) => saveWorldOverlay(world.id, o),
341
- destination: worldOverlayPath(world.id),
370
+ const adapter = new World2DAuthoringAdapter(world.pixiRoot(), physics, store);
371
+ resources.push(adapter);
372
+ children.push({
373
+ worldId: world.id,
374
+ kind: world.kind,
375
+ adapter: withEphemeralPersistence(adapter, () => ({})),
376
+ ...composition,
342
377
  });
343
- children.push({ worldId: world.id, kind: world.kind, adapter });
344
378
  } else if (world.kind === 'react') {
345
- const adapter = new ReactWorldAuthoringAdapter(world.reactRoot(), store, {
346
- // Same dev-server-only gating `edit-mode-authoring.ts`'s scene-UI
347
- // child uses for the identical seam: a hosted/production build has
348
- // no `/__ui-source` middleware.
349
- ...(import.meta.env.DEV ? { writeBackend: createHttpSourceWriteBackend() } : {}),
379
+ const adapter = new ReactWorldAuthoringAdapter(world.reactRoot(), store);
380
+ resources.push(adapter);
381
+ children.push({
382
+ worldId: world.id,
383
+ kind: world.kind,
384
+ adapter: withEphemeralPersistence(adapter, () => ({})),
385
+ ...composition,
350
386
  });
351
- children.push({ worldId: world.id, kind: world.kind, adapter });
352
387
  } else {
353
388
  // Exhaustiveness guard (§7.4-2): the pre-existing if/else-if chain over
354
389
  // `WorldInstance.kind` had no trailing else — a hypothetical 4th kind
355
390
  // would silently get NO authoring child (no error, just missing
356
391
  // authoring for that world) rather than failing loudly/at compile time.
357
- assertNever(world.kind, 'installMultiWorldAuthoring');
392
+ assertNever(world.kind, 'installPlayWorldAuthoring');
358
393
  }
359
394
  }
360
- _multiWorldChildren = children.map((c) => c.adapter);
361
- const composite = new CompositeAuthoringAdapter(children);
395
+ _playWorldResources = resources;
396
+ const projection = hierarchyProjectionFromProjectConfig(getCurrentProject()?.config);
397
+ const composite = new CompositeAuthoringAdapter(children, undefined, projection);
362
398
  setActiveAuthoring(composite);
363
399
  // `setActiveAuthoring` is a plain module-level variable, not React state —
364
400
  // the left hierarchy panel only re-checks `hasAuthoringOverride()` when the
@@ -382,22 +418,12 @@ async function installMultiWorldAuthoring(
382
418
  }
383
419
  }
384
420
 
385
- /** Teardown for `installMultiWorldAuthoring` — unregisters any per-world child
386
- * that self-registered with the global undo timeline (mirrors
387
- * `ingest-mode.ts`'s `unregisterUndoAdapter` call on its own adapter). Must
388
- * pass the ORIGINAL adapter instance (not a rebuilt wrapper) — the timeline
389
- * keys registration by object identity (see undo-timeline.ts's doc comment),
390
- * and `registerUndoAdapter(this)` inside each of `IngestAuthoringAdapter`'s,
391
- * `World2DAuthoringAdapter`'s (v4 §7.1-13), and `ReactWorldAuthoringAdapter`'s
392
- * constructors registered exactly that instance. The type guard below is now
393
- * just a defensive narrowing (every current child kind DOES register), kept
394
- * in case a future child kind legitimately has no undo/redo of its own. */
395
- function exitMultiWorldAuthoring(): void {
396
- for (const adapter of _multiWorldChildren) {
397
- if (adapter.undo && adapter.redo)
398
- unregisterUndoAdapter(adapter as AuthoringAdapter & UndoAdapter);
421
+ /** Teardown every per-world authoring resource owned by the play session. */
422
+ function exitPlayWorldAuthoring(): void {
423
+ for (const adapter of _playWorldResources) {
424
+ if ('dispose' in adapter && typeof adapter.dispose === 'function') adapter.dispose();
399
425
  }
400
- _multiWorldChildren = [];
426
+ _playWorldResources = [];
401
427
  if (import.meta.env.DEV) {
402
428
  delete (window as unknown as Record<string, unknown>)['__vgaiMultiWorld'];
403
429
  }
@@ -410,16 +436,40 @@ let _originalConsoleError: typeof console.error | null = null;
410
436
  let _logFlushChain: Promise<unknown> = Promise.resolve();
411
437
  let _flushInterval: ReturnType<typeof setInterval> | null = null;
412
438
  let _pendingEntries: LogEntry[] = [];
439
+ let _lastPersistedDebugEventSeq = 0;
440
+
441
+ function drainDebugEventsToPlayLog(): void {
442
+ const debug = _session?.game?.systemAdapters?.debug;
443
+ if (!debug) return;
444
+ try {
445
+ const converted = debugEventsToLogEntries(
446
+ debug.events(undefined, _lastPersistedDebugEventSeq),
447
+ _lastPersistedDebugEventSeq,
448
+ );
449
+ _lastPersistedDebugEventSeq = converted.lastSeq;
450
+ _pendingEntries.push(...converted.entries);
451
+ } catch {
452
+ // Logging is evidence, never a reason to break the game loop.
453
+ }
454
+ }
413
455
 
414
456
  // --- Script HMR ---
415
457
  if (import.meta.hot) {
458
+ import.meta.hot.on('vgai:restart-required', (data: { file: string }) => {
459
+ if (!_session) return;
460
+ const project = getCurrentProject();
461
+ if (project && data.file.endsWith('/registry.ts')) {
462
+ clearProjectComponentHotOverrides(project.rootPath);
463
+ }
464
+ const file = data.file.split('/').pop() ?? data.file;
465
+ markRestartRequired(`${file} changed and cannot be applied safely while the game is running.`);
466
+ editorConsole.warn(`Restart required: ${file} changed.`, 'play-mode');
467
+ });
416
468
  import.meta.hot.on('vgai:script-update', async (data: { file: string }) => {
417
469
  if (!_session || !_ctx) return;
418
470
  const project = getCurrentProject();
419
471
  if (!project) return;
420
472
  try {
421
- const { store } = _ctx;
422
-
423
473
  // Strategy based on which file changed:
424
474
  // Component source files → true HMR (import only the file, swap prototypes)
425
475
  // Entry point or registry → warm restart (re-import main, re-run setup)
@@ -431,6 +481,7 @@ if (import.meta.hot) {
431
481
  // This avoids re-importing the full module chain which can trigger page reloads.
432
482
  const modulePath = `/@fs/${data.file}?t=${Date.now()}`;
433
483
  const mod = await import(/* @vite-ignore */ modulePath);
484
+ let componentExports = 0;
434
485
  for (const [key, value] of Object.entries(mod)) {
435
486
  // §7.1-5/probe7: filter to GameComponent subclasses BEFORE ever
436
487
  // calling hotSwap — a plain helper function export sharing a live
@@ -449,46 +500,27 @@ if (import.meta.hot) {
449
500
  typeof value === 'function' &&
450
501
  value.prototype instanceof gameComponentModule.GameComponent
451
502
  ) {
503
+ componentExports++;
504
+ registerProjectComponentHotOverride(
505
+ project.rootPath,
506
+ key,
507
+ value as unknown as GameComponentClass,
508
+ );
452
509
  hotSwapAcrossWorlds(_session, key, value as unknown as GameComponentClass);
453
510
  }
454
511
  }
512
+ if (componentExports === 0) {
513
+ markRestartRequired(
514
+ `${data.file.split('/').pop() ?? data.file} changed but exported no GameComponent class.`,
515
+ );
516
+ return;
517
+ }
455
518
  bumpHmrCount();
456
519
  editorConsole.log('Hot-swapped component classes (true HMR)', 'play-mode');
457
520
  } else {
458
- // Warm restart: re-run setup() with fresh code
459
- const scripts = await reloadProjectScripts(project.rootPath);
460
- // W1 (docs/R3F-FIRST-PARTY-DESIGN.md §1.A) widened `ProjectScripts` so
461
- // `setup` is no longer guaranteed — an entry that exports only
462
- // `adapter` has no re-runnable setup() for `hotReload` to call (the
463
- // adapter owns its whole mount lifecycle itself; O3 in the design doc
464
- // already flags entry-module HMR as unverified for v1). Fail loudly
465
- // here instead of handing `hotReload` an `undefined` — the outer
466
- // try/catch (below) reports it exactly like any other HMR failure.
467
- const reloadedSetup = scripts.setup;
468
- if (!reloadedSetup) {
469
- throw new Error(
470
- 'Warm restart failed: the project entry now exports only `adapter`, not `setup` — ' +
471
- 'hot-reloading a pre-built GameAdapter has no setup() to re-run in v1 ' +
472
- '(docs/R3F-FIRST-PARTY-DESIGN.md O3). Restart play instead.',
473
- );
474
- }
475
- const hotViewCam = _ctx.getViewportCamera();
476
- // Pause the host loop around the warm restart (the generic host no longer
477
- // owns hotReload; gate the loop so it doesn't tick mid-rebuild) — but never
478
- // un-pause a game the USER had already paused (§7.1-1, probe3).
479
- await runWarmRestartPauseBracket(_session, () =>
480
- firstParty(_session as GameSession).hotReload(reloadedSetup, {
481
- scenePath: store.savePath,
482
- sceneData: store.getDocument(),
483
- viewportCamera: {
484
- position: hotViewCam.position.toArray() as [number, number, number],
485
- quaternion: hotViewCam.quaternion.toArray() as [number, number, number, number],
486
- },
487
- }),
521
+ markRestartRequired(
522
+ `${data.file.split('/').pop() ?? data.file} changed and requires remounting all roots.`,
488
523
  );
489
- bumpHmrCount();
490
- editorConsole.log('Hot-reloaded game scripts (warm restart)', 'play-mode');
491
- warnIfOtherFirstPartyWorldsUnrestarted(_session);
492
524
  }
493
525
  } catch (err) {
494
526
  editorConsole.error(`Script hot-reload failed: ${err}`, 'play-mode');
@@ -583,9 +615,77 @@ export function isPlayModeActive(): boolean {
583
615
  return _session !== null;
584
616
  }
585
617
 
618
+ /**
619
+ * Narrow relay accessor (Wave 5, docs/SYNTHETIC-PLAYER-SPEC.md §3.5) — the
620
+ * live play session's `InputManager`(s) and the Game root's loop, for
621
+ * `command-listener.ts`'s `inject-input`/`set-time-scale`/`set-seed` cases.
622
+ * This is exactly the accessor the vgai-sdk honest-gap jsdocs prescribed
623
+ * (`play/input-operations.ts`, `play/control-operations.ts`): `_session` is
624
+ * module-private, so the relay needs this one exported read. Everything else
625
+ * the relay reads (state providers, debug commands) flows through
626
+ * `setActiveSystems`/`getActiveSystems` instead.
627
+ *
628
+ * `getInputTarget(worldId?)` (D15/T-D15.5 — review objection 2's fix)
629
+ * REPLACES what used to be a plain `input: Game['input'] | null` field —
630
+ * `Game.input` always resolves to the DEFAULT world's `InputManager` only,
631
+ * while the debug bridge's `window.__vgai.input.*` reached whichever world's
632
+ * `InputManager` last called `DebugRegistry.setVirtualInputTarget` (a
633
+ * SEPARATE, last-writer-wins slot). In a multi-world project those two could
634
+ * name DIFFERENT roots — the exact closed-PR review objection. Now both
635
+ * doors call the SAME `getDebugRegistry(game).getVirtualInputTarget(worldId)`
636
+ * — one resolution function (`debug-registry.ts`'s `resolveInputWorldId`),
637
+ * so `inject-input` (this accessor) and `window.__vgai.input.*`
638
+ * (`debug-bridge.ts`) can never disagree about which world an unqualified
639
+ * actuation targets again. `null` when nothing is registered for the
640
+ * resolved id (or no `Game` is running at all); throws the registry's own
641
+ * `DEBUG_INPUT_WORLD_NOT_FOUND` for an explicit, unregistered `worldId`.
642
+ *
643
+ * `runTicks` (D15/T-D15.4) is added the SAME way: reached via
644
+ * `getDebugRegistry(game).getRunTicksTarget()` — the identical accessor
645
+ * `runtime/debug-bridge.ts`'s `window.__vgai.runTicks` (door a) goes
646
+ * through, so the editor relay's `run-ticks` case (door b, → `play.runTicks`)
647
+ * calls byte-identical behavior (D17). `null` only when no `Game` is running
648
+ * at all (`_session` is `null`) — a live `Game` always wires a run-ticks
649
+ * target immediately at construction (`createGame`, `runtime/game.ts`), so
650
+ * `runTicks` is non-null whenever `_session` is non-null. `runTicks` itself
651
+ * is game-global (one shared tick loop across every world by design), so —
652
+ * unlike the input target — it never needed per-world routing.
653
+ *
654
+ * `random`/`determinismDeclared` (D15/T-D15.6) back the `set-seed` relay
655
+ * case and `collectState`'s `seed`/`deterministic` fields: `random` is
656
+ * `getSeededRandom(game)` — the SAME game-scoped `SeededRandom` every
657
+ * world's `ctx.random` reads, non-null for every real `createGame` call
658
+ * (see `seeded-random.ts`) — and `determinismDeclared` is
659
+ * `_playDeterminismDeclared`, set from the CURRENT session's manifest in
660
+ * `enterPlayMode`.
661
+ */
662
+ export function getPlayRuntimeAccess(): {
663
+ getInputTarget(worldId?: string): DebugVirtualInputTarget | null;
664
+ loop: GameLoop;
665
+ runTicks: ((n: number, opts?: RunTicksOptions) => void) | null;
666
+ random: SeededRandom | null;
667
+ determinismDeclared: boolean;
668
+ } | null {
669
+ const game = _session?.game;
670
+ if (!game) return null;
671
+ const registry = getDebugRegistry(game);
672
+ const runTicksTarget = registry?.getRunTicksTarget() ?? null;
673
+ return {
674
+ getInputTarget: (worldId?: string) => registry?.getVirtualInputTarget(worldId) ?? null,
675
+ loop: game.loop,
676
+ runTicks: runTicksTarget ? runTicksTarget.runTicks.bind(runTicksTarget) : null,
677
+ random: getSeededRandom(game),
678
+ determinismDeclared: _playDeterminismDeclared,
679
+ };
680
+ }
681
+
586
682
  /** Get the running game's audio context (for volume/mute control). */
587
683
  export function getGameAudio() {
588
- return _session ? firstParty(_session).ctx.audio : null;
684
+ if (!_session) return null;
685
+ for (const world of _session.game.roots) {
686
+ if (isFirstPartyMounted(world.mounted)) return world.mounted.ctx.audio;
687
+ }
688
+ return null;
589
689
  }
590
690
 
591
691
  /** Get the running game's scene (for editor Scene tab rendering). */
@@ -593,15 +693,115 @@ export function getGameScene(): THREE.Scene | null {
593
693
  return _session?.scene ?? null;
594
694
  }
595
695
 
696
+ /**
697
+ * #140 — the live play-mode game canvas, for `command-listener.ts`'s
698
+ * `probe-screenshot` relay op (`RelayTransport.screenshot` in `@vgai/probe`).
699
+ * The legacy single-canvas path (`createGameRuntime`) keeps `_gameCanvas`
700
+ * pointed at the one it created; the manifest/roots path
701
+ * (`mountManifestWorlds`) removes that placeholder canvas and mounts its own
702
+ * stacked canvases straight into `_gameContainerEl` (see `enterPlayMode`'s
703
+ * `manifest` branch above) — querying the container for its (bottom, first)
704
+ * `<canvas>` covers both without needing a second accessor threaded through
705
+ * `mountManifestWorlds`'s return value. `null` when not in play mode or the
706
+ * container/canvas isn't mounted yet.
707
+ */
708
+ export function getPlayCanvas(): HTMLCanvasElement | null {
709
+ if (!_session) return null;
710
+ if (_gameCanvas) return _gameCanvas;
711
+ return _gameContainerEl?.querySelector('canvas') ?? null;
712
+ }
713
+
714
+ /** #146 — when the CURRENT play run began (ms epoch), or `null` while
715
+ * stopped. `command-listener.ts`'s relay `snapshot` uses this to fence
716
+ * `pageErrors` to errors from THIS run (the editor console accumulates
717
+ * across runs; a probe reading "what went wrong during my run" must not
718
+ * see last session's stale failures). */
719
+ export function getPlayStartedAt(): number | null {
720
+ return _playStartedAtMs;
721
+ }
722
+
596
723
  /** Resize the running game to a specific resolution. */
597
724
  export function resizeGame(width: number, height: number): void {
598
725
  _session?.resize(width, height);
599
726
  }
600
727
 
728
+ /**
729
+ * Serializes every `enterPlayMode()` invocation (the ghost-runtime bug:
730
+ * `vgai play` on an already-playing/still-booting session left the
731
+ * PREVIOUS runtime alive, ticking and rendering alongside the new one).
732
+ *
733
+ * Root cause: `enterPlayModeInner`'s own `if (_session) exitPlayMode()`
734
+ * guard (below) only protects the case where a PRIOR play has already fully
735
+ * finished booting and assigned `_session`. While a call is still mid-boot
736
+ * (between this function being entered and `_session` being assigned —
737
+ * awaiting script loads / manifest resolution / asset loads / mount),
738
+ * `_session` reads as `null`, so a SECOND `enterPlayMode()` call landing in
739
+ * that window sees no session to tear down and proceeds to run its own
740
+ * entire prologue (`patchConsole()`, `startLogSession()`, canvas creation,
741
+ * script loading, mount) CONCURRENTLY with the first call's. Both calls
742
+ * mutate shared module-level/global state with no reentrancy guard —
743
+ * `patchConsole()`/`unpatchConsole()` are the sharpest example (proven by a
744
+ * red-before-green regression test: two overlapping calls double-wrap
745
+ * `console.log` and the inner wrapper recurses into itself via the shared
746
+ * `_originalConsoleLog` variable, a real `RangeError: Maximum call stack
747
+ * size exceeded` — not a hypothetical). In the field this window is entered
748
+ * whenever a caller re-issues `play` before the browser has acked the first
749
+ * (a slow scene boot outliving the relay's/SDK's own `play.start` timeout is
750
+ * the documented trigger — `packages/vgai-sdk/src/play/transport.ts`'s
751
+ * `PLAY_START_TIMEOUT_MS`/`editor-server.ts`'s `PLAY_COMMAND_TIMEOUT_MS` —
752
+ * and `play.start`'s own contract is explicitly "start (or restart)", so a
753
+ * caller retrying after a timeout is using the API as documented, not
754
+ * misusing it), or whenever the SSE `editor-command` listener
755
+ * (`command-listener.ts`) dispatches a burst of commands without awaiting
756
+ * the previous `handleCommand()` to settle.
757
+ *
758
+ * The existing `_playEpoch` generation guard decides, AFTER THE FACT, which
759
+ * of two overlapping boots gets adopted into `_session` and stops the loser
760
+ * — but it does nothing to stop both boots from RUNNING (and their
761
+ * prologues from clobbering each other) in the first place. Epoch-checking
762
+ * is an adjudication mechanism, not a mutex.
763
+ *
764
+ * The fix is a FIFO queue, not a smarter epoch check: every call chains onto
765
+ * the tail of `_enterQueue`, so a second call's ENTIRE body — prologue
766
+ * included — never starts until the first call's entire invocation (success
767
+ * or failure, including any self-teardown it performs) has fully settled.
768
+ * This makes "play again while already playing/booting" a genuine, clean,
769
+ * awaited restart for every caller (CLI, SDK, UI Play button, HMR's warm
770
+ * restart) with no code path capable of leaving a booted session
771
+ * unreferenced ("orphaned") — by the time any enterPlayMode() body runs,
772
+ * it is provably the only one running.
773
+ */
774
+ let _enterQueue: Promise<void> = Promise.resolve();
775
+
776
+ export function enterPlayMode(explicitSeed?: number): Promise<void> {
777
+ const run = _enterQueue.then(() => enterPlayModeInner(explicitSeed));
778
+ // Advance the queue unconditionally so one caller's rejection can never
779
+ // wedge every subsequent play attempt — each caller still observes its
780
+ // OWN failure via the `run` promise this function returns.
781
+ _enterQueue = run.then(
782
+ () => undefined,
783
+ () => undefined,
784
+ );
785
+ return run;
786
+ }
787
+
601
788
  /**
602
789
  * Enter play mode: create a game canvas, start game, disable editor controls.
790
+ *
791
+ * `explicitSeed` (D15/T-D15.6, objection-4 fix — `vgai play --seed <n>`)
792
+ * — the CLI's `play` command relays it through as `cmd['seed']`
793
+ * (`command-listener.ts`'s `'play'` case); it is the "explicit config"
794
+ * leg of `resolveDeterminismSeed`'s precedence (highest — beats
795
+ * `manifest.determinism.defaultSeed`/`?vgai-seed=` on the editor's own
796
+ * page URL), threaded into whichever mount path this play resolves to
797
+ * below, exactly like `mountManifestWorlds`'s own `opts.seed` already is
798
+ * for a standalone boot.
799
+ *
800
+ * Not exported directly — always call {@link enterPlayMode}, which
801
+ * serializes invocations of this function so overlapping callers can never
802
+ * run concurrently. See that wrapper's doc comment for why.
603
803
  */
604
- export async function enterPlayMode(): Promise<void> {
804
+ async function enterPlayModeInner(explicitSeed?: number): Promise<void> {
605
805
  if (!_ctx) return;
606
806
  // The play button is only shown while stopped, so a non-null _session here is
607
807
  // stale — a previous play that didn't fully tear down (e.g. a re-entry race).
@@ -611,6 +811,10 @@ export async function enterPlayMode(): Promise<void> {
611
811
  // bumps the epoch via exitPlayMode). Any exitPlayMode — or a newer
612
812
  // enterPlayMode — during the async boot below invalidates this generation.
613
813
  const epoch = ++_playEpoch;
814
+ // #146 — fence for the relay snapshot's `pageErrors` (see
815
+ // `getPlayStartedAt`): errors logged before THIS play run are stale noise
816
+ // to a probe reading "what went wrong during my run".
817
+ _playStartedAtMs = Date.now();
614
818
  const { store } = _ctx;
615
819
 
616
820
  // Validate scene before entering play mode
@@ -628,8 +832,25 @@ export async function enterPlayMode(): Promise<void> {
628
832
  // Start log session and register sink for JSONL persistence
629
833
  await startLogSession();
630
834
  _pendingEntries = [];
835
+ _lastPersistedDebugEventSeq = 0;
631
836
  _logFlushChain = Promise.resolve();
632
837
  editorConsole.setSink((entry: ConsoleEntry) => {
838
+ // Wave 5 (AC-A1.5's play-log half): stamp {tick, simT} from the live
839
+ // session's built-in `time` provider so log entries correlate
840
+ // frame-exactly with `ctx.debug.emit` events. Best-effort — entries
841
+ // logged before the session finishes booting (or after stop) carry no
842
+ // stamp, and a throwing read must never break logging.
843
+ let stamp: { tick: number; simT: number } | undefined;
844
+ try {
845
+ const time = _session?.game?.systemAdapters.debug?.state('time') as
846
+ | { tick?: number; simSeconds?: number }
847
+ | undefined;
848
+ if (typeof time?.tick === 'number' && typeof time.simSeconds === 'number') {
849
+ stamp = { tick: time.tick, simT: time.simSeconds };
850
+ }
851
+ } catch {
852
+ /* unstampable — keep the entry */
853
+ }
633
854
  _pendingEntries.push({
634
855
  t: entry.timestamp,
635
856
  level: entry.level,
@@ -637,9 +858,11 @@ export async function enterPlayMode(): Promise<void> {
637
858
  ...(entry.source ? { source: entry.source } : {}),
638
859
  ...(entry.subsystem ? { sub: entry.subsystem } : {}),
639
860
  ...(entry.metadata ? { meta: entry.metadata } : {}),
861
+ ...(stamp ?? {}),
640
862
  });
641
863
  });
642
864
  _flushInterval = setInterval(() => {
865
+ drainDebugEventsToPlayLog();
643
866
  if (_pendingEntries.length > 0) {
644
867
  const batch = _pendingEntries.splice(0);
645
868
  _logFlushChain = _logFlushChain.then(() => flushLogEntries(batch));
@@ -664,10 +887,7 @@ export async function enterPlayMode(): Promise<void> {
664
887
  const w = gameContainer.clientWidth;
665
888
  const h = gameContainer.clientHeight;
666
889
 
667
- const gameCanvas = document.createElement('canvas');
668
- gameCanvas.style.cssText = 'width:100%;height:100%;display:block;';
669
- gameContainer.appendChild(gameCanvas);
670
- _gameCanvas = gameCanvas;
890
+ _gameCanvas = null;
671
891
 
672
892
  // setPlayState auto-switches to Game tab
673
893
  store.setPlayState('playing');
@@ -683,183 +903,59 @@ export async function enterPlayMode(): Promise<void> {
683
903
  return;
684
904
  }
685
905
 
686
- const { createGameRuntime } = await import('@engine/runtime/create-runtime');
687
-
688
- // T3.3 slice 2 part C: a manifest-backed project (vgai.game.json present)
689
- // plays through the resolver, against its first world — the manifest
690
- // wins for game identity/mounting per docs/CLI-ON-FOLDER-DESIGN.md §1B.
691
- // A legacy (project.json-only) project has no `/vgai.game.json` to fetch
692
- // (404 -> null below) and falls through to today's scripts-based path,
693
- // UNCHANGED. Browser mode (the hosted, no-dev-server build) never has
694
- // this route served at all, so it always takes the legacy branch too.
695
- const manifest =
696
- getEditorMode() === 'browser' ? null : await fetchGameManifest().catch(() => null);
697
- const firstWorld = manifest?.worlds[0];
698
-
699
- // E4.R2 (reopen fix) — honest scoping of the three branches below,
700
- // replacing the old blanket "editor-side because Vite-coupled" framing
701
- // (`mount-manifest.ts`'s header comment, which is true of ADAPTER
702
- // CONSTRUCTION generally but was being read as though it explained every
703
- // branch here equally). Each branch has its OWN, different reason to
704
- // live where it does:
705
- // - The multi-world branch (below) is the one design/26 S-D D2 actually
706
- // names ("editor play mode calls it, adapter-resolver keeps only
707
- // editor-specific concerns: dev-server URLs, ingest session wiring")
708
- // — it migrated onto the engine's `mountManifestWorlds` composer.
709
- // - The single-manifest-world `else if (firstWorld)` branch stays HERE,
710
- // permanently, NOT because of dev-server coupling but because it
711
- // threads `editorPreview` (the live in-memory document + viewport
712
- // camera, so unsaved edits play and the editor's own camera seeds the
713
- // session) — a channel the engine composer must never grow, since it
714
- // is inherently "there is exactly one editable document" (the
715
- // editor's), which stops making sense the moment a manifest declares
716
- // more than one world.
717
- // - The no-manifest `else` branch (project.json-only legacy projects)
718
- // stays HERE because there is no manifest world to resolve AT ALL —
719
- // not a scoping choice, a structural one.
720
- // - `ingest-mode.ts`/`module-mode.ts` (separate files, not this
721
- // dispatch) still call `resolveAllWorlds` un-migrated — genuinely OUT
722
- // of E4's scope (not named by it), left for a follow-on unit; their
723
- // OWN dev-server `/@fs/` coupling for ingest session wiring and
724
- // custom-module loading is real and correctly stays editor-side.
906
+ const manifest = await fetchGameManifest(project.exampleId);
907
+ // Every project mounts through the same manifest composer.
908
+ // Cardinality never selects a runtime, hierarchy, or persistence model.
909
+ // The editor's live document is scoped to its focused threejs world;
910
+ // sibling roots resolve from their own adapter-owned content.
725
911
  let session: GameSession;
726
- if (manifest && (manifest.worlds.length > 1 || firstWorld?.kind === 'pixijs')) {
727
- // T6.1 slice 2 (docs/MULTI-WORLD-DESIGN.md §3 slice 2): a manifest with
728
- // MORE THAN ONE world mounts through the slice-1 worlds path — the
729
- // single-canvas legacy path below is three-only (its `createGameRuntime`
730
- // call constructs exactly one THREE renderer against one canvas) and
731
- // cannot represent N stacked worlds. A LONE pixijs world routes here
732
- // too: the legacy path's HostContext is three-shaped (≠ World2DHost),
733
- // so it could resolve but never mount a pixi adapter — and lone pixi
734
- // had no working legacy behavior to preserve (it THREW pre-slice), so
735
- // this is new capability, not a stability break. A single-THREE-world
736
- // manifest NEVER reaches this branch (the `else if (firstWorld)`
737
- // branch below is BYTE-STABLE — same call shape as before this slice). The
738
- // already-created single `gameCanvas` above is unused on this path —
739
- // the composer's own host builds its OWN canvas stack directly inside
740
- // `gameContainer` (`mountManifestWorlds`'s `MountManifestOptions
741
- // .container`), so discard it rather than leave an orphaned extra
742
- // canvas in the DOM.
743
- gameCanvas.remove();
744
- _gameCanvas = null;
745
-
746
- // E4.R2 (reopen fix, design/26 S-D D2 — "editor play mode calls it,
747
- // adapter-resolver keeps only editor-specific concerns: dev-server
748
- // URLs, ingest session wiring"): per-world adapter construction stays
749
- // HERE, editor-side, via `resolveAllWorldEntries` (which is itself just
750
- // the scope-checked `resolveWorldAdapter` fan-out — the SAME dev-server
751
- // `/@fs/` mechanics `resolveWorldAdapter` always used). What moved OFF
752
- // this file is the WorldMountSpec ASSEMBLY (id/zOrder/pausable/loop +
753
- // per-kind dispatch) that `resolveAllWorlds` used to hand-build for
754
- // this call site — `mountManifestWorlds` below now does that from the
755
- // manifest itself (`mount-manifest.ts`'s `buildWorldMountSpec`, the
756
- // engine's own single authoritative implementation of that
757
- // translation), so it is never duplicated here. `entries` (not the
758
- // process-global `registerWorldKind` registry) is the right channel
759
- // for an editor session specifically because play mode mounts a FRESH
760
- // session on every play — registering into the global registry would
761
- // double-register (and throw) on the second play; `entries` carries no
762
- // such hazard since it is rebuilt from scratch every `enterPlayMode`.
763
- const entries = await resolveAllWorldEntries(manifest, project.rootPath);
764
- editorConsole.log(
765
- `Resolved ${manifest.worlds.length} manifest worlds via the composer path: ` +
766
- manifest.worlds.map((w) => `${w.id} (${w.kind})`).join(', '),
767
- 'play-mode',
768
- );
769
- // Play may have been exited while resolving — don't boot a runtime for
770
- // a play that is already over.
771
- if (epoch !== _playEpoch) return;
772
- // Re-read the container's real size instead of the `w`/`h` captured
773
- // BEFORE `store.setPlayState('playing')` above (that capture can race
774
- // the Game-tab layout switch and read 0x0). This still matters for the
775
- // INITIAL render-buffer resolution (`mountManifestWorlds`'s own
776
- // `width`/`height` default otherwise falls back to the manifest's
777
- // `resolution`) even though it is no longer the ONLY thing standing
778
- // between a 0x0 mount and a correctly-laid-out canvas: the worlds-path
779
- // canvas's on-screen SIZE is now fully CSS-container-driven
780
- // (`create-runtime.ts`'s `mountOneThreeWorld`, E4.R1 reopen fix), not
781
- // pinned to whatever it mounted at.
782
- const rw = gameContainer.clientWidth || w;
783
- const rh = gameContainer.clientHeight || h;
784
- const { mountManifestWorlds } = await import('@engine/runtime/mount-manifest');
785
- session = await mountManifestWorlds({
786
- manifest,
787
- container: gameContainer,
788
- entries,
789
- width: rw,
790
- height: rh,
791
- });
792
- } else if (firstWorld) {
793
- // The SAME editorPreview the legacy branch builds below — live in-memory
794
- // document (so unsaved edits play), current save path, viewport-camera
795
- // spawn. The resolver threads it into whichever default-three branch it
796
- // takes (entry -> setup(ctx, editorPreview), byte-equivalent to the
797
- // legacy path; scene-only -> mounts sceneData, camera honored).
798
- const manifestViewCam = _ctx.getViewportCamera();
799
- const adapter = await resolveWorldAdapter(firstWorld, project.rootPath, {
800
- editorPreview: {
801
- scenePath: store.savePath,
802
- sceneData,
803
- viewportCamera: {
804
- position: manifestViewCam.position.toArray() as [number, number, number],
805
- quaternion: manifestViewCam.quaternion.toArray() as [number, number, number, number],
806
- },
807
- },
808
- });
809
- editorConsole.log(
810
- `Resolved manifest world "${firstWorld.id}" (${firstWorld.adapter.identity})`,
811
- 'play-mode',
812
- );
813
- // Play may have been exited while resolving — don't boot a runtime for
814
- // a play that is already over.
815
- if (epoch !== _playEpoch) return;
816
- session = await createGameRuntime({ canvas: gameCanvas, width: w, height: h, adapter });
817
- } else {
818
- // Load project scripts and run with createGameRuntime.
819
- // Server build: dev-server import of the on-disk project entry.
820
- // Browser build: no dev server — load the pre-bundled scripts and transpile
821
- // them in-browser (same esbuild-wasm path the Playground uses).
822
- let scripts: ProjectScripts;
823
- if (getEditorMode() === 'browser') {
824
- const { loadBrowserProjectScripts } = await import('./browser-project-scripts');
825
- scripts = await loadBrowserProjectScripts();
826
- } else {
827
- scripts = await loadProjectScripts(project.rootPath);
828
- }
829
- editorConsole.log('Loaded project scripts', 'play-mode');
830
-
831
- const viewCam = _ctx.getViewportCamera();
832
- // Play may have been exited while the scripts were loading — don't boot a
833
- // runtime for a play that is already over.
834
- if (epoch !== _playEpoch) return;
835
- // Hosted example project (Track H): route play through the bundled
836
- // example's own setup — or, for a `?scene=` override inside the project,
837
- // play the open scene generically but keep its asset prefix. Pure
838
- // decision in hosted-example.ts; empty object everywhere else.
839
- const exampleDispatch =
840
- getEditorMode() === 'browser'
841
- ? exampleDispatchFor(
842
- project.exampleId,
843
- store.savePath,
844
- new URLSearchParams(window.location.search).has('scene'),
845
- )
846
- : {};
847
- session = await createGameRuntime({
848
- canvas: gameCanvas,
849
- width: w,
850
- height: h,
851
- setup: scripts.setup,
852
- editorPreview: {
853
- scenePath: store.savePath,
854
- sceneData,
855
- viewportCamera: {
856
- position: viewCam.position.toArray() as [number, number, number],
857
- quaternion: viewCam.quaternion.toArray() as [number, number, number, number],
858
- },
859
- ...exampleDispatch,
860
- },
861
- });
862
- }
912
+ const focusedThreejsWorldId = resolveFocusedThreejsWorldId(manifest.roots, store.savePath);
913
+ const manifestViewCam = _ctx.getViewportCamera();
914
+ const entries = await resolveAllWorldEntries(manifest, project.rootPath, {
915
+ editorPreviewWorldId: focusedThreejsWorldId ?? undefined,
916
+ editorPreview: focusedThreejsWorldId
917
+ ? {
918
+ scenePath: store.savePath,
919
+ sceneData,
920
+ viewportCamera: {
921
+ position: manifestViewCam.position.toArray() as [number, number, number],
922
+ quaternion: manifestViewCam.quaternion.toArray() as [number, number, number, number],
923
+ },
924
+ }
925
+ : undefined,
926
+ });
927
+ editorConsole.log(
928
+ `Resolved manifest composition (${manifest.roots.length} world${manifest.roots.length === 1 ? '' : 's'}): ` +
929
+ manifest.roots.map((w) => `${w.id} (${w.surface})`).join(', '),
930
+ 'play-mode',
931
+ );
932
+ // Play may have been exited while resolving — don't boot a runtime for
933
+ // a play that is already over.
934
+ if (epoch !== _playEpoch) return;
935
+ // Re-read the container's real size instead of the `w`/`h` captured
936
+ // BEFORE `store.setPlayState('playing')` above (that capture can race
937
+ // the Game-tab layout switch and read 0x0). This still matters for the
938
+ // INITIAL render-buffer resolution (`mountManifestWorlds`'s own
939
+ // `width`/`height` default otherwise falls back to the manifest's
940
+ // `resolution`) even though it is no longer the ONLY thing standing
941
+ // between a 0x0 mount and a correctly-laid-out canvas: the roots-path
942
+ // canvas's on-screen SIZE is now fully CSS-container-driven
943
+ // (`create-runtime.ts`'s `mountOneThreeWorld`, E4.R1 reopen fix), not
944
+ // pinned to whatever it mounted at.
945
+ const rw = gameContainer.clientWidth || w;
946
+ const rh = gameContainer.clientHeight || h;
947
+ const { mountManifestWorlds } = await import('@engine/runtime/mount-manifest');
948
+ session = await mountManifestWorlds({
949
+ manifest,
950
+ container: gameContainer,
951
+ entries,
952
+ width: rw,
953
+ height: rh,
954
+ // D15/T-D15.6 — `vgai play --seed`'s explicit config leg; `undefined`
955
+ // (the overwhelmingly common case) leaves `mountManifestWorlds`'s own
956
+ // manifest/`?vgai-seed=` precedence untouched.
957
+ seed: explicitSeed,
958
+ });
863
959
 
864
960
  // Play was exited (Stop/Escape) — or re-entered — while the runtime was
865
961
  // booting. This session belongs to a play that is already over: stop it
@@ -871,6 +967,22 @@ export async function enterPlayMode(): Promise<void> {
871
967
  return;
872
968
  }
873
969
  _session = session;
970
+ clearRestartRequired();
971
+ // D15/T-D15.6 — same "read straight off the manifest this enterPlayMode
972
+ // call already resolved" as the D16 room-declared wiring immediately
973
+ // below; `manifest` is `null` for a legacy (no-manifest) project, so
974
+ // `?.determinism?.seededRandom === true` correctly reads `false` there.
975
+ _playDeterminismDeclared = manifest?.determinism?.seededRandom === true;
976
+ // D16 parity with the standalone mount path (`mount-manifest.ts`'s
977
+ // `setRoomDeclared` wiring): a project whose manifest declares a Colyseus
978
+ // room must declare `locus: 'client' | 'server'` on every debug command
979
+ // it registers — in editor play mode exactly like on the standalone
980
+ // page. Idempotent for the manifest composer (`mountManifestWorlds`
981
+ // already set it); `session.game` is optional-chained for the legacy
982
+ // fake-session fixtures, same as every other read below.
983
+ if (manifest?.server && session.game) {
984
+ getDebugRegistry(session.game)?.setRoomDeclared(true);
985
+ }
874
986
  // A2: browser mode has no Vite dev server, so no `vgai:script-update` HMR
875
987
  // event ever fires (the `import.meta.hot` handler below is dead in the
876
988
  // hosted build). Drive the SAME in-browser hot-swap from the storage
@@ -886,40 +998,16 @@ export async function enterPlayMode(): Promise<void> {
886
998
  );
887
999
  });
888
1000
  }
889
- // `session.game.worlds` is always present on a REAL `GameSession` (T6.1
890
- // slice 1 — `create-runtime.ts` unconditionally sets `game`); the
891
- // optional-chaining guard here is for the LEGACY/single-world play-mode
892
- // unit tests (`adapter-resolver-play-path.test.ts`,
893
- // `play-mode-multi-world.test.ts`), whose `fakeSession()` fixtures predate
894
- // this slice and stub only the fields THEY need — never touch those
895
- // pinned files, so this reads defensively instead.
896
- _isMultiWorldSession = (session.game?.worlds.length ?? 1) > 1;
897
- // Wave 20 (docs/MULTI-WORLD-DESIGN.md §1.F candidate improvement /
898
- // MASTER-ARCHITECTURE-REVIEW §7.4 gap 4): surface WHICH persistence regime
899
- // this session's edits are under. Derived from the SAME
900
- // `_isMultiWorldSession` boolean the branch below uses to pick
901
- // `installMultiWorldAuthoring` (overlay, real per-world persistence) vs
902
- // `installPlayAuthoring` (ephemeral, discarded on stop) — never a second,
903
- // independently-computed condition, so this can't drift from the actual
904
- // provider that gets installed.
905
- store.setPlayEditRegime(_isMultiWorldSession ? 'overlay' : 'ephemeral');
1001
+ notifySessionListeners();
1002
+ // D19: play edits are session-local regardless of world count.
1003
+ store.setPlayEditRegime('ephemeral');
906
1004
 
907
1005
  // Swap store to game scene so hierarchy/inspector show game entities.
908
1006
  // liveHierarchy: first-party play mode is the ONLY adoption path that may
909
1007
  // synthesize descriptors for untagged runtime objects (anti-shim rule —
910
1008
  // ingest/module mounts adopt foreign scenes and must never fabricate).
911
- store.enterPlayScene(session.scene, { liveHierarchy: true });
912
- if (_isMultiWorldSession) {
913
- // T6.1 slice 3 (docs/MULTI-WORLD-DESIGN.md §1.F/§3 slice 3): N-ary
914
- // Composite over one per-world adapter each, REAL (overlay) persistence —
915
- // see installMultiWorldAuthoring's doc comment for why this differs from
916
- // the ephemeral-wrapped single-world path below.
917
- await installMultiWorldAuthoring(store, session.game!.worlds);
918
- } else {
919
- // Carry an ephemeral persistence provider for the duration of play (design
920
- // docs/PERSISTENCE-PROVIDER-DESIGN.md §2/§7 slice 1) — see installPlayAuthoring.
921
- installPlayAuthoring(store);
922
- }
1009
+ adoptThreePlaySceneIfAvailable(store, session, focusedThreejsWorldId);
1010
+ installPlayWorldAuthoring(store, session.game!.roots, manifest);
923
1011
 
924
1012
  // Wire physics sync THROUGH the first-party `RapierPhysicsAdapter` (Phase E):
925
1013
  // the gizmo path freezes a Rapier-owned body on beginEdit, commits the edited
@@ -1002,17 +1090,21 @@ export function exitPlayMode(): void {
1002
1090
  // Invalidate any enterPlayMode still awaiting its runtime boot (see
1003
1091
  // _playEpoch): its session must be abandoned, not adopted.
1004
1092
  _playEpoch++;
1093
+ _playStartedAtMs = null;
1005
1094
  const { store } = _ctx;
1095
+ // Drain while the session/debug registry still exists. Stopping disposes
1096
+ // it, and the last pickup/win event is often emitted inside the final 200ms
1097
+ // interval before Stop.
1098
+ drainDebugEventsToPlayLog();
1006
1099
 
1007
1100
  // Restore editor scene before stopping (stop disposes game scene children)
1008
1101
  store.setEcsSyncTransform(null);
1009
1102
  setActiveSystems(null);
1010
1103
  store.exitPlayScene();
1011
- if (_isMultiWorldSession) exitMultiWorldAuthoring();
1104
+ exitPlayWorldAuthoring();
1012
1105
  restorePriorAuthoring();
1013
- _isMultiWorldSession = false;
1014
- // Readout-only — clear the regime the moment play is no longer active
1015
- // (mirrors _isMultiWorldSession's own reset just above). Optional-chained:
1106
+ // Readout-only — clear the regime the moment play is no longer active.
1107
+ // Optional-chained:
1016
1108
  // some pre-existing play-mode unit tests (e.g. play-mode-teardown.test.ts's
1017
1109
  // ED8 no-container path) pass a minimal hand-built fake store that predates
1018
1110
  // this signal and stubs only the methods THEY need — never touch those
@@ -1029,6 +1121,8 @@ export function exitPlayMode(): void {
1029
1121
  editorConsole.error(`Error stopping play session: ${err}`, 'play-mode');
1030
1122
  } finally {
1031
1123
  _session = null;
1124
+ _playDeterminismDeclared = false;
1125
+ notifySessionListeners();
1032
1126
  }
1033
1127
  }
1034
1128