castle-web-cli 0.4.233 → 0.4.234

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 (381) hide show
  1. package/dist/api.d.ts +11 -0
  2. package/dist/api.js +43 -0
  3. package/dist/bundle.d.ts +64 -0
  4. package/dist/bundle.js +558 -2
  5. package/dist/castle-host/host.d.ts +17 -2
  6. package/dist/castle-host/host.js +793 -36
  7. package/dist/castleJson.d.ts +20 -1
  8. package/dist/castleJson.js +44 -2
  9. package/dist/check.js +9 -2
  10. package/dist/chunkLoader.d.ts +3 -0
  11. package/dist/chunkLoader.js +111 -0
  12. package/dist/devParty.d.ts +26 -0
  13. package/dist/devParty.js +231 -0
  14. package/dist/devSaveStorage.js +4 -0
  15. package/dist/devSessionStorage.js +3 -1
  16. package/dist/devSocial.d.ts +24 -0
  17. package/dist/devSocial.js +70 -0
  18. package/dist/ide.d.ts +2 -0
  19. package/dist/ide.js +119 -15
  20. package/dist/index.js +8 -2
  21. package/dist/init.js +1 -1
  22. package/dist/save-deck.d.ts +20 -1
  23. package/dist/save-deck.js +141 -5
  24. package/dist/serve.js +29 -11
  25. package/dist/shell/assets/{index-BjOxR-lW.js → index-DulbYIJm.js} +97 -97
  26. package/dist/shell/index.html +1 -1
  27. package/dist/vitePlugins.d.ts +2 -1
  28. package/dist/vitePlugins.js +13 -0
  29. package/kits/base/castle.json +1 -1
  30. package/kits/base/sdk/README.md +260 -3
  31. package/kits/base/sdk/castle.d.ts +7 -3
  32. package/kits/base/sdk/castle.js +2 -0
  33. package/kits/base/sdk/commands.d.ts +162 -1
  34. package/kits/base/sdk/commands.js +3 -0
  35. package/kits/base/sdk/display.d.ts +3 -0
  36. package/kits/base/sdk/display.js +9 -3
  37. package/kits/base/sdk/hub.d.ts +33 -6
  38. package/kits/base/sdk/hub.js +50 -4
  39. package/kits/base/sdk/multiplayer.d.ts +7 -1
  40. package/kits/base/sdk/multiplayer.js +140 -40
  41. package/kits/base/sdk/multiplayerProtocol.d.ts +2 -0
  42. package/kits/base/sdk/party.d.ts +23 -0
  43. package/kits/base/sdk/party.js +91 -0
  44. package/kits/base/sdk/reconnectBudget.d.ts +23 -0
  45. package/kits/base/sdk/reconnectBudget.js +96 -0
  46. package/kits/base/sdk/save.d.ts +38 -1
  47. package/kits/base/sdk/save.js +79 -6
  48. package/kits/base/sdk/server/hub.d.ts +31 -1
  49. package/kits/base/sdk/server/hub.js +50 -3
  50. package/kits/base/sdk/server/platformHandle.d.ts +13 -1
  51. package/kits/base/sdk/server/storage.d.ts +4 -0
  52. package/kits/base/sdk/server/storage.js +19 -3
  53. package/kits/base/sdk/server/wrapper.d.ts +7 -1
  54. package/kits/base/sdk/server/wrapper.js +10 -1
  55. package/kits/base/sdk/social.d.ts +9 -0
  56. package/kits/base/sdk/social.js +5 -0
  57. package/kits/hub-game/CLAUDE.md +123 -3
  58. package/kits/hub-game/README.md +63 -0
  59. package/kits/hub-game/castle.json +5 -5
  60. package/kits/hub-game/code/client/act.js +312 -0
  61. package/kits/hub-game/code/client/actionLayout.js +147 -0
  62. package/kits/hub-game/code/client/actionOverflow.js +556 -0
  63. package/kits/hub-game/code/client/arrivalCamera.js +50 -0
  64. package/kits/hub-game/code/client/askSlot.js +117 -0
  65. package/kits/hub-game/code/client/avatar.js +4 -2
  66. package/kits/hub-game/code/client/avatarShare.js +2 -0
  67. package/kits/hub-game/code/client/backVisibility.js +13 -0
  68. package/kits/hub-game/code/client/ballot.js +15 -10
  69. package/kits/hub-game/code/client/build.js +16 -0
  70. package/kits/hub-game/code/client/chat.js +41 -5
  71. package/kits/hub-game/code/client/chatModeration.js +5 -0
  72. package/kits/hub-game/code/client/chrome.js +1148 -258
  73. package/kits/hub-game/code/client/crowdNames.js +241 -0
  74. package/kits/hub-game/code/client/decor.js +10 -4
  75. package/kits/hub-game/code/client/defaultEnvironment.js +194 -0
  76. package/kits/hub-game/code/client/doorErrors.js +39 -0
  77. package/kits/hub-game/code/client/fall.js +18 -0
  78. package/kits/hub-game/code/client/farAvatars.js +233 -0
  79. package/kits/hub-game/code/client/firstJoin.js +9 -2
  80. package/kits/hub-game/code/client/fpsTelemetry.js +50 -0
  81. package/kits/hub-game/code/client/frameBatch.js +5 -0
  82. package/kits/hub-game/code/client/grab.js +31 -11
  83. package/kits/hub-game/code/client/hookLayer.js +87 -8
  84. package/kits/hub-game/code/client/hudCopy.js +51 -0
  85. package/kits/hub-game/code/client/hudRate.js +20 -0
  86. package/kits/hub-game/code/client/idle.js +14 -2
  87. package/kits/hub-game/code/client/invites.js +231 -0
  88. package/kits/hub-game/code/client/joinError.js +9 -0
  89. package/kits/hub-game/code/client/labelsNear.js +31 -2
  90. package/kits/hub-game/code/client/landscapeLayout.js +17 -0
  91. package/kits/hub-game/code/client/layoutCache.js +264 -0
  92. package/kits/hub-game/code/client/loadTelemetry.js +20 -0
  93. package/kits/hub-game/code/client/loadingCover.js +148 -0
  94. package/kits/hub-game/code/client/loadingEntry.js +8 -0
  95. package/kits/hub-game/code/client/menuRows.js +43 -0
  96. package/kits/hub-game/code/client/modelReady.js +7 -0
  97. package/kits/hub-game/code/client/padCueArrival.js +23 -0
  98. package/kits/hub-game/code/client/padCues.js +112 -0
  99. package/kits/hub-game/code/client/padOccupancy.js +88 -0
  100. package/kits/hub-game/code/client/padReadability.js +26 -0
  101. package/kits/hub-game/code/client/padRings.js +69 -0
  102. package/kits/hub-game/code/client/pushVisit.js +14 -0
  103. package/kits/hub-game/code/client/quality.js +205 -0
  104. package/kits/hub-game/code/client/qualityEntry.js +55 -0
  105. package/kits/hub-game/code/client/safeLayout.js +338 -0
  106. package/kits/hub-game/code/client/safeStyle.js +42 -0
  107. package/kits/hub-game/code/client/say.js +12 -3
  108. package/kits/hub-game/code/client/shot.js +64 -10
  109. package/kits/hub-game/code/client/shotFit.js +56 -0
  110. package/kits/hub-game/code/client/signIn.js +28 -0
  111. package/kits/hub-game/code/client/state.js +53 -0
  112. package/kits/hub-game/code/client/talk.js +209 -45
  113. package/kits/hub-game/code/client/tiers.js +68 -66
  114. package/kits/hub-game/code/client/together.js +7 -2
  115. package/kits/hub-game/code/client/weakestLookBake.js +92 -0
  116. package/kits/hub-game/code/client/weakestTier.js +295 -0
  117. package/kits/hub-game/code/client/worldLabels.js +241 -0
  118. package/kits/hub-game/code/client/yours.js +10 -9
  119. package/kits/hub-game/code/npcDisplayText.js +55 -0
  120. package/kits/hub-game/code/server/act.js +124 -0
  121. package/kits/hub-game/code/server/actions.js +6 -1
  122. package/kits/hub-game/code/server/actors.js +2 -1
  123. package/kits/hub-game/code/server/analytics.js +83 -0
  124. package/kits/hub-game/code/server/anonymousEntry.js +49 -0
  125. package/kits/hub-game/code/server/arrivalPose.js +36 -0
  126. package/kits/hub-game/code/server/companion.js +28 -3
  127. package/kits/hub-game/code/server/doorAnalytics.js +52 -0
  128. package/kits/hub-game/code/server/earned.js +22 -5
  129. package/kits/hub-game/code/server/frameBatch.js +183 -0
  130. package/kits/hub-game/code/server/friendsAmong.js +49 -9
  131. package/kits/hub-game/code/server/history.js +2 -0
  132. package/kits/hub-game/code/server/hub.js +1306 -95
  133. package/kits/hub-game/code/server/idle.js +30 -1
  134. package/kits/hub-game/code/server/index.js +26 -4
  135. package/kits/hub-game/code/server/invites.js +19 -0
  136. package/kits/hub-game/code/server/labels.js +9 -1
  137. package/kits/hub-game/code/server/loadAbandon.js +106 -0
  138. package/kits/hub-game/code/server/manifest.js +211 -3
  139. package/kits/hub-game/code/server/menu.js +31 -3
  140. package/kits/hub-game/code/server/npcs.js +226 -64
  141. package/kits/hub-game/code/server/observe.js +408 -0
  142. package/kits/hub-game/code/server/padOccupancy.js +85 -0
  143. package/kits/hub-game/code/server/players.js +9 -1
  144. package/kits/hub-game/code/server/resumePose.js +152 -0
  145. package/kits/hub-game/code/server/say.js +1 -1
  146. package/kits/hub-game/code/server/standing.js +4 -5
  147. package/kits/hub-game/code/server/storageLimit.js +187 -0
  148. package/kits/hub-game/code/server/vis.js +67 -5
  149. package/kits/hub-game/code/shared/act.js +35 -0
  150. package/kits/hub-game/code/shared/danceIdle.js +28 -0
  151. package/kits/hub-game/code/shared/loadStages.js +12 -0
  152. package/kits/hub-game/code/shared/quality.js +74 -0
  153. package/kits/hub-game/code/shared/say.js +2 -0
  154. package/kits/hub-game/code/shared/shot.js +35 -1
  155. package/kits/hub-game/code/systems/hub.js +970 -169
  156. package/kits/hub-game/docs/analytics.md +279 -0
  157. package/kits/hub-game/docs/contract.md +1257 -42
  158. package/kits/hub-game/docs/home-pieces.md +9 -2
  159. package/kits/hub-game/docs/observed-progress.md +252 -0
  160. package/kits/hub-game/main.jsx +2 -0
  161. package/kits/hub-game/package-lock.json +10 -3
  162. package/kits/hub-game/package.json +6 -3
  163. package/kits/hub-game/play/player.js +142 -0
  164. package/kits/hub-game/play/registry.js +47 -0
  165. package/kits/hub-game/play.jsx +37 -0
  166. package/kits/hub-game/scripts/check.mjs +39 -5
  167. package/kits/hub-game/scripts/companion-follower-wire.json +1 -1
  168. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +11 -0
  169. package/kits/hub-game/scripts/fixtures/decor-keyless.json +5 -5
  170. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +3 -0
  171. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +19 -3
  172. package/kits/hub-game/scripts/fixtures/interest-legacy.json +3 -3
  173. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -1
  174. package/kits/hub-game/scripts/pose-storage-fixture.mjs +46 -0
  175. package/kits/hub-game/scripts/test-act-client.mjs +186 -0
  176. package/kits/hub-game/scripts/test-act.mjs +171 -0
  177. package/kits/hub-game/scripts/test-action-layout.mjs +80 -0
  178. package/kits/hub-game/scripts/test-action-observers.mjs +46 -0
  179. package/kits/hub-game/scripts/test-actions-client.mjs +367 -2
  180. package/kits/hub-game/scripts/test-actors.mjs +20 -7
  181. package/kits/hub-game/scripts/test-analytics.mjs +76 -0
  182. package/kits/hub-game/scripts/test-anonymous-entry.mjs +28 -0
  183. package/kits/hub-game/scripts/test-arrival-pose-server.mjs +196 -0
  184. package/kits/hub-game/scripts/test-arrival-pose.mjs +24 -0
  185. package/kits/hub-game/scripts/test-ask-slot.mjs +85 -0
  186. package/kits/hub-game/scripts/test-avatar-wire.mjs +49 -10
  187. package/kits/hub-game/scripts/test-avatar.mjs +44 -0
  188. package/kits/hub-game/scripts/test-back-visibility.mjs +82 -0
  189. package/kits/hub-game/scripts/test-ballot.mjs +11 -4
  190. package/kits/hub-game/scripts/test-ban-join.mjs +121 -13
  191. package/kits/hub-game/scripts/test-build.mjs +20 -2
  192. package/kits/hub-game/scripts/test-chat.mjs +206 -5
  193. package/kits/hub-game/scripts/test-companion-chat.mjs +20 -2
  194. package/kits/hub-game/scripts/test-control-layout-dom.mjs +120 -0
  195. package/kits/hub-game/scripts/test-crowd-names.mjs +205 -0
  196. package/kits/hub-game/scripts/test-decor-client.mjs +45 -4
  197. package/kits/hub-game/scripts/test-decor.mjs +7 -0
  198. package/kits/hub-game/scripts/test-default-environment-root.mjs +95 -0
  199. package/kits/hub-game/scripts/test-default-environment.mjs +267 -0
  200. package/kits/hub-game/scripts/test-door-analytics.mjs +58 -0
  201. package/kits/hub-game/scripts/test-door-jump.mjs +100 -0
  202. package/kits/hub-game/scripts/test-earned.mjs +33 -3
  203. package/kits/hub-game/scripts/test-far-avatars.mjs +340 -0
  204. package/kits/hub-game/scripts/test-fps-telemetry.mjs +112 -0
  205. package/kits/hub-game/scripts/test-frame-batch.mjs +252 -0
  206. package/kits/hub-game/scripts/test-fresh-friends.mjs +118 -0
  207. package/kits/hub-game/scripts/test-grab-orbit.mjs +47 -4
  208. package/kits/hub-game/scripts/test-high-only.mjs +170 -0
  209. package/kits/hub-game/scripts/test-hub-ops.mjs +321 -2
  210. package/kits/hub-game/scripts/test-hub-trip.mjs +879 -11
  211. package/kits/hub-game/scripts/test-hud-clear.mjs +162 -59
  212. package/kits/hub-game/scripts/test-hud-defects-dom.mjs +100 -0
  213. package/kits/hub-game/scripts/test-hud-rate.mjs +224 -0
  214. package/kits/hub-game/scripts/test-hud-safe-visibility-dom.mjs +83 -0
  215. package/kits/hub-game/scripts/test-idle.mjs +66 -0
  216. package/kits/hub-game/scripts/test-interest-cells.mjs +20 -0
  217. package/kits/hub-game/scripts/test-interest.mjs +15 -0
  218. package/kits/hub-game/scripts/test-invites-client.mjs +430 -0
  219. package/kits/hub-game/scripts/test-invites.mjs +109 -0
  220. package/kits/hub-game/scripts/test-labels.mjs +71 -3
  221. package/kits/hub-game/scripts/test-landscape-layout.mjs +194 -0
  222. package/kits/hub-game/scripts/test-list-scroll-dom.mjs +49 -0
  223. package/kits/hub-game/scripts/test-load-abandon.mjs +246 -0
  224. package/kits/hub-game/scripts/test-loading-cover.mjs +162 -0
  225. package/kits/hub-game/scripts/test-manifest.mjs +265 -0
  226. package/kits/hub-game/scripts/test-menu-client.mjs +105 -0
  227. package/kits/hub-game/scripts/test-menu.mjs +23 -0
  228. package/kits/hub-game/scripts/test-npcs.mjs +819 -10
  229. package/kits/hub-game/scripts/test-observed.mjs +745 -0
  230. package/kits/hub-game/scripts/test-pad-cues.mjs +304 -0
  231. package/kits/hub-game/scripts/test-pad-occupancy.mjs +177 -0
  232. package/kits/hub-game/scripts/test-picker.mjs +234 -7
  233. package/kits/hub-game/scripts/test-placement-cache.mjs +690 -0
  234. package/kits/hub-game/scripts/test-progress-reset.mjs +559 -0
  235. package/kits/hub-game/scripts/test-push-visit.mjs +26 -0
  236. package/kits/hub-game/scripts/test-quality.mjs +385 -0
  237. package/kits/hub-game/scripts/test-rehello.mjs +699 -5
  238. package/kits/hub-game/scripts/test-resume-action-order.mjs +598 -0
  239. package/kits/hub-game/scripts/test-resume-held.mjs +239 -0
  240. package/kits/hub-game/scripts/test-resume-pose.mjs +142 -0
  241. package/kits/hub-game/scripts/test-safe-events-dom.mjs +116 -0
  242. package/kits/hub-game/scripts/test-safe-layout.mjs +330 -0
  243. package/kits/hub-game/scripts/test-say.mjs +1 -1
  244. package/kits/hub-game/scripts/test-shot.mjs +145 -0
  245. package/kits/hub-game/scripts/test-signin-client.mjs +45 -0
  246. package/kits/hub-game/scripts/test-soundscape.mjs +22 -17
  247. package/kits/hub-game/scripts/test-standing.mjs +35 -2
  248. package/kits/hub-game/scripts/test-storage-limit.mjs +333 -0
  249. package/kits/hub-game/scripts/test-stuck.mjs +5 -4
  250. package/kits/hub-game/scripts/test-talk-overlay-dom.mjs +130 -0
  251. package/kits/hub-game/scripts/test-tiers-render.mjs +86 -13
  252. package/kits/hub-game/scripts/test-tiers.mjs +7 -8
  253. package/kits/hub-game/scripts/test-vis.mjs +433 -6
  254. package/kits/hub-game/scripts/test-weakest-tier.mjs +924 -0
  255. package/kits/hub-game/scripts/test-world-labels.mjs +367 -0
  256. package/kits/hub-game/scripts/test-yours-chrome.mjs +50 -6
  257. package/kits/hub-game/scripts/test-yours.mjs +39 -8
  258. package/kits/multiplayer-3d/castle.json +5 -5
  259. package/kits/multiplayer-3d/code/client/joinFailure.js +27 -0
  260. package/kits/multiplayer-3d/code/client/resumeGate.js +139 -0
  261. package/kits/multiplayer-3d/code/systems/multiplayer.js +369 -30
  262. package/kits/multiplayer-3d/package-lock.json +8 -1
  263. package/kits/multiplayer-3d/package.json +2 -1
  264. package/kits/multiplayer-3d/scripts/test-join-watchdog.mjs +436 -0
  265. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +624 -0
  266. package/kits/physics-2d/CLAUDE.md +10 -1
  267. package/kits/physics-2d/castle.json +2 -2
  268. package/kits/physics-2d/engine/frozenActors.js +233 -0
  269. package/kits/physics-2d/engine/scene.js +87 -5
  270. package/kits/physics-2d/eslint.config.js +1 -1
  271. package/kits/physics-2d/play/behaviors/AnalogStick.js +198 -0
  272. package/kits/physics-2d/play/behaviors/Camera.js +40 -0
  273. package/kits/physics-2d/play/behaviors/Collider.js +122 -0
  274. package/kits/physics-2d/play/behaviors/Draggable.js +115 -0
  275. package/kits/physics-2d/play/behaviors/Goal.js +46 -0
  276. package/kits/physics-2d/play/behaviors/Joints.js +126 -0
  277. package/kits/physics-2d/play/behaviors/Layout.js +71 -0
  278. package/kits/physics-2d/play/behaviors/RigidBody.js +57 -0
  279. package/kits/physics-2d/play/behaviors/Slingshot.js +142 -0
  280. package/kits/physics-2d/play/behaviors/SoundPlayer.js +263 -0
  281. package/kits/physics-2d/play/behaviors/Sprite.js +406 -0
  282. package/kits/physics-2d/play/behaviors/Style.js +209 -0
  283. package/kits/physics-2d/play/behaviors/Text.js +85 -0
  284. package/kits/physics-2d/play/behaviors/Video.js +93 -0
  285. package/kits/physics-3d/CLAUDE.md +25 -1651
  286. package/kits/physics-3d/behaviors/Body.jsx +3 -0
  287. package/kits/physics-3d/behaviors/Model.jsx +3 -0
  288. package/kits/physics-3d/behaviors/Player.jsx +35 -18
  289. package/kits/physics-3d/behaviors/Shape.jsx +3 -0
  290. package/kits/physics-3d/behaviors/Solid.jsx +3 -0
  291. package/kits/physics-3d/behaviors/Transform.jsx +3 -0
  292. package/kits/physics-3d/castle.json +3 -3
  293. package/kits/physics-3d/docs/engine-camera.md +542 -0
  294. package/kits/physics-3d/docs/engine-frame-cap.md +136 -0
  295. package/kits/physics-3d/docs/engine-load.md +149 -0
  296. package/kits/physics-3d/docs/engine-look.md +114 -0
  297. package/kits/physics-3d/docs/engine-shadows.md +372 -0
  298. package/kits/physics-3d/docs/engine-skip-work.md +187 -0
  299. package/kits/physics-3d/docs/engine-sky.md +198 -0
  300. package/kits/physics-3d/docs/engine-static-actors.md +226 -0
  301. package/kits/physics-3d/docs/engine-view.md +37 -0
  302. package/kits/physics-3d/docs/pxmodel-format.md +1 -1
  303. package/kits/physics-3d/engine3d/PlayOnly3D.jsx +5 -1
  304. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +19 -333
  305. package/kits/physics-3d/engine3d/actornode.js +1 -0
  306. package/kits/physics-3d/engine3d/branches.js +3 -13
  307. package/kits/physics-3d/engine3d/cage.js +2 -7
  308. package/kits/physics-3d/engine3d/cageops.js +2 -17
  309. package/kits/physics-3d/engine3d/dataBehaviors.js +12 -0
  310. package/kits/physics-3d/engine3d/framecap.js +4 -1
  311. package/kits/physics-3d/engine3d/frozenphysics.js +140 -0
  312. package/kits/physics-3d/engine3d/frozenstatics.js +273 -0
  313. package/kits/physics-3d/engine3d/gait.js +8 -0
  314. package/kits/physics-3d/engine3d/initialModelFiles.js +18 -0
  315. package/kits/physics-3d/engine3d/look.js +7 -0
  316. package/kits/physics-3d/engine3d/modelFiles.js +3 -17
  317. package/kits/physics-3d/engine3d/modelMath.js +49 -0
  318. package/kits/physics-3d/engine3d/modelready.js +16 -0
  319. package/kits/physics-3d/engine3d/motion.js +3 -3
  320. package/kits/physics-3d/engine3d/nearshadows.js +77 -10
  321. package/kits/physics-3d/engine3d/orbitinput.js +59 -25
  322. package/kits/physics-3d/engine3d/partgeometry.js +1 -16
  323. package/kits/physics-3d/engine3d/paths.js +1 -9
  324. package/kits/physics-3d/engine3d/playTimings.js +50 -0
  325. package/kits/physics-3d/engine3d/playerRun.js +372 -0
  326. package/kits/physics-3d/engine3d/pxmodel.js +3 -3
  327. package/kits/physics-3d/engine3d/rapier.js +27 -0
  328. package/kits/physics-3d/engine3d/scatter.js +1 -11
  329. package/kits/physics-3d/engine3d/shadowfade.js +23 -15
  330. package/kits/physics-3d/engine3d/sky.js +1 -1
  331. package/kits/physics-3d/engine3d/squarefirst.js +177 -0
  332. package/kits/physics-3d/engine3d/stillshadows.js +399 -0
  333. package/kits/physics-3d/engine3d/sweep.js +1 -25
  334. package/kits/physics-3d/engine3d/world3d.js +468 -18
  335. package/kits/physics-3d/eslint.config.js +2 -1
  336. package/kits/physics-3d/main.jsx +6 -3
  337. package/kits/physics-3d/package-lock.json +7 -0
  338. package/kits/physics-3d/package.json +5 -1
  339. package/kits/physics-3d/play/behaviors/Body.js +31 -0
  340. package/kits/physics-3d/play/behaviors/Door.js +37 -0
  341. package/kits/physics-3d/play/behaviors/Lookable.js +16 -0
  342. package/kits/physics-3d/play/behaviors/Model.js +23 -0
  343. package/kits/physics-3d/play/behaviors/Pickup.js +46 -0
  344. package/kits/physics-3d/play/behaviors/Player.js +1204 -0
  345. package/kits/physics-3d/play/behaviors/Shape.js +47 -0
  346. package/kits/physics-3d/play/behaviors/Solid.js +16 -0
  347. package/kits/physics-3d/play/behaviors/Transform.js +29 -0
  348. package/kits/physics-3d/pnpm-lock.yaml +8 -0
  349. package/kits/physics-3d/scripts/bench-shadow-fade.mjs +37 -0
  350. package/kits/physics-3d/scripts/build-rapier-gz.mjs +56 -0
  351. package/kits/physics-3d/scripts/frozen-statics-fixture.mjs +141 -0
  352. package/kits/physics-3d/scripts/test-camera-follow.mjs +5 -1
  353. package/kits/physics-3d/scripts/test-camera-orbit.mjs +52 -4
  354. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +1 -1
  355. package/kits/physics-3d/scripts/test-empty-gait-hints.mjs +89 -0
  356. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +6 -3
  357. package/kits/physics-3d/scripts/test-frame-cap.mjs +1 -1
  358. package/kits/physics-3d/scripts/test-frozen-nested.mjs +49 -0
  359. package/kits/physics-3d/scripts/test-frozen-statics-legacy-physics2d.mjs +123 -0
  360. package/kits/physics-3d/scripts/test-frozen-statics.mjs +434 -0
  361. package/kits/physics-3d/scripts/test-look-bake.mjs +1 -1
  362. package/kits/physics-3d/scripts/test-near-shadows.mjs +2 -2
  363. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +88 -7
  364. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +40 -3
  365. package/kits/physics-3d/scripts/test-orbit-shot.mjs +75 -1
  366. package/kits/physics-3d/scripts/test-rapier-gz.mjs +106 -0
  367. package/kits/physics-3d/scripts/test-sky.mjs +1 -1
  368. package/kits/physics-3d/scripts/test-square-first.mjs +921 -0
  369. package/kits/physics-3d/scripts/test-static-actors.mjs +3 -1
  370. package/kits/physics-3d/scripts/test-static-physics.mjs +4 -1
  371. package/kits/physics-3d/scripts/test-static-scenery.mjs +5 -2
  372. package/kits/physics-3d/scripts/test-steady-hover.mjs +5 -2
  373. package/kits/physics-3d/scripts/test-still-shadows.mjs +477 -0
  374. package/kits/physics-3d/systems/physics3d.js +37 -4
  375. package/kits/real-time/castle.json +2 -2
  376. package/kits/real-time/code/client/connection.js +33 -10
  377. package/kits/real-time/code/client/gameHooks.js +2 -0
  378. package/kits/real-time/code/client/joinOverlay.js +9 -4
  379. package/kits/real-time/code/server/session.js +6 -4
  380. package/kits/real-time/package-lock.json +1 -1
  381. package/package.json +2 -2
@@ -11,6 +11,8 @@
11
11
  // that carries shared characters (`npcs.js`).
12
12
 
13
13
  import * as Scene from '@imports/castle.multiplayer-3d/code/server/sceneBodies.js';
14
+ import { classify } from '../shared/quality.js';
15
+ import { addOccupancy, makePadOccupancy } from './padOccupancy.js';
14
16
  import * as Cells from './cells.js';
15
17
  import * as Actors from './actors.js';
16
18
  import * as History from './history.js';
@@ -19,9 +21,11 @@ import { friendBests } from './friendBests.js';
19
21
  import * as Blocks from './blocks.js';
20
22
  import * as Cabinets from './cabinets.js';
21
23
  import * as Grab from './grab.js';
24
+ import * as Act from './act.js';
22
25
  import * as Idle from './idle.js';
23
26
  import * as Decor from './decor.js';
24
27
  import * as Actions from './actions.js';
28
+ import * as Invites from './invites.js';
25
29
  import * as Companion from './companion.js';
26
30
  import * as Ask from './ask.js';
27
31
  import * as Menu from './menu.js';
@@ -33,12 +37,19 @@ import * as Manifest from './manifest.js';
33
37
  import { setLabel, wireLabel } from './labels.js';
34
38
  import { makeNpcs } from './npcs.js';
35
39
  import * as Party from './party.js';
36
- import { standingY } from './standing.js';
40
+ import { bodySize, standingY } from './standing.js';
37
41
  import * as Place from './place.js';
38
42
  import * as Say from './say.js';
39
43
  import * as Ballot from './ballot.js';
40
44
  import * as Wear from './wear.js';
41
45
  import * as Earned from './earned.js';
46
+ import * as Analytics from './analytics.js';
47
+ import * as DoorAnalytics from './doorAnalytics.js';
48
+ import * as LoadAbandon from './loadAbandon.js';
49
+ import * as ResumePose from './resumePose.js';
50
+ import * as ArrivalPose from './arrivalPose.js';
51
+ import * as Observe from './observe.js';
52
+ import { makeAnonymousEntry } from './anonymousEntry.js';
42
53
  import { doorPoint } from '../client/doorFrame.js';
43
54
 
44
55
  // How many avatars the kit offers (`blueprints/avatar-<n>.scene`); contract §11.
@@ -66,6 +77,9 @@ const PAD_REFRESH_MS = 20000;
66
77
  const SHUT_HOLD_MS = 60000;
67
78
  // How often a place re-reads its doors' boards.
68
79
  const BOARD_EVERY_MS = 60000;
80
+ // A weekly Cup clock is refreshed with its board once a minute. Two missed
81
+ // intervals are stale: presentation fails closed until a paired read lands.
82
+ const CUP_CLOCK_STALE_MS = BOARD_EVERY_MS * 2;
69
83
  // The newest result of the game a player came back from counts as this trip's
70
84
  // for this long: the longest visit (maxDurationSec 1800) and some slack.
71
85
  const RESULT_FRESH_MS = 35 * 60 * 1000;
@@ -74,6 +88,10 @@ const RESULT_FRESH_MS = 35 * 60 * 1000;
74
88
  // most 10 top rows and 3 last-event winners (a few KB), so 16 stay well
75
89
  // below the host channel's roughly 384 KB frame.
76
90
  const BOARD_DOORS_PER_READ = 16;
91
+ // One combined weekly-Cup read asks only for connected signed-in accounts.
92
+ // Ghost's ordinary read cap is 100, but keeping the batches explicit protects
93
+ // the host operation if a future place raises the session cap.
94
+ const CUP_USERS_PER_READ = 100;
77
95
  // Cabinet boards in one read: each may be 44 KB, and a read answers in one
78
96
  // frame of the host's channel (about 384 KB).
79
97
  const CABINET_BOARDS_PER_READ = 6;
@@ -105,13 +123,19 @@ const POSE_HZ = 10;
105
123
  // tick and memory, read by the host's log stream (the only per-session
106
124
  // numbers a production layer has).
107
125
  const STATS_EVERY_MS = 30000;
126
+ const PROGRESS_ARRIVAL_WAIT_MS = 5000;
127
+ const PROGRESS_RETRY_MS = 5000;
128
+ // Failed reads back off by doubling, per player state, to this; a failure is
129
+ // logged when the gap changes and at most this often at the cap.
130
+ const PROGRESS_RETRY_MAX_MS = 300_000;
108
131
  const USER_ID = /^\d{1,20}$/;
109
132
 
110
133
  // `layer(castleJson, deckHooks, placeHooks)`: the hooks object for one session
111
134
  // process. `placeHooks` maps place id -> that place's own hooks module.
112
- // A scene with no ground catches a fallen player this far down when its place
113
- // names no `fallY`: above the world's floor (-30), below any pit worth having.
114
- const NO_GROUND_FALL_Y = -20;
135
+ // Every place catches a fallen player this far down when it names no `fallY`:
136
+ // above the shared world's report floor (-30), below any pit worth having.
137
+ // A scene with implicit ground needs it too: that finite floor has an edge.
138
+ const DEFAULT_FALL_Y = -20;
115
139
 
116
140
  function hasHook(deckHooks, placeHooks, name) {
117
141
  return typeof deckHooks?.[name] === 'function' || Object.values(placeHooks ?? {}).some((hooks) => typeof hooks?.[name] === 'function');
@@ -130,11 +154,31 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
130
154
  }
131
155
  return { persist: false, sceneFor: () => undefined, worldCharacters: {} };
132
156
  }
133
- const h = newState(manifest);
157
+ const savedDeckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : null;
158
+ for (const [id, place] of Object.entries(manifest.places)) {
159
+ const hooks = placeHooks[id] ?? deckHooks;
160
+ if (place.resumeVisibility === true && typeof hooks?.resume !== 'function') {
161
+ console.error(`[hub] ${id}.resumeVisibility requires an exported resume hook.`);
162
+ return { persist: false, sceneFor: () => undefined, worldCharacters: {} };
163
+ }
164
+ }
165
+ const h = newState(manifest, savedDeckId);
166
+ // Published character definitions stay server-only, outside the place manifest.
167
+ h.characterBundle = castleJson.characterBundle ?? null;
168
+ if (castleJson.hub.firstVisit) {
169
+ h.firstVisit = Object.freeze({ live: Object.freeze([...castleJson.hub.firstVisit.live]) });
170
+ h.ctx.firstVisit = h.firstVisit;
171
+ h.ctx.firstVisitArrived = (playerId, flags) => Analytics.firstVisitArrived(h, playerId, flags);
172
+ }
173
+ // Root-only server opt-in; never added to the public place manifest.
174
+ if (castleJson.hub.bringFriend === true) {h.bringFriend = true;}
175
+ // The kit observes platform resets for its own caches even when the place
176
+ // has no deck-specific reset hook.
177
+ h.progressEnabled = true;
134
178
  // v1.53: the deck's own earned items and id, for an unlock kept in this
135
179
  // session only (a guest, the dev serve).
136
180
  h.unlocks = manifest.unlocks ?? null;
137
- h.deckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : 'local';
181
+ h.deckId = savedDeckId ?? 'local';
138
182
  h.devDecks = devDecks && typeof devDecks === 'object' ? devDecks : null;
139
183
  h.engine = engine;
140
184
  const tickRate = Number.isFinite(castleJson?.server?.tickRate) && castleJson.server.tickRate > 0 ? castleJson.server.tickRate : 20;
@@ -145,23 +189,61 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
145
189
  ...(Object.values(manifest.places).some((place) => place.decor)
146
190
  ? { allowClientGone: () => !h.place?.decor }
147
191
  : {}),
192
+ // The transport can leave and rejoin the same id between two ticks.
193
+ // Pose-only visits must release authored work at that boundary too.
194
+ ...(manifest.act === true || Object.values(manifest.places).some(place => place.resumeArrivalPose === true) ? {
195
+ departed(session, player) {
196
+ if (h.manifest.act === true) {Act.forget(h, player.playerId);}
197
+ if (h.place?.resumeArrivalPose !== true || !h.sim || !h.players.has(player.playerId)) {return;}
198
+ h.session = session;
199
+ forget(h, player.playerId);
200
+ },
201
+ } : {}),
202
+ // v1.138: load-abandoned connections follow the transport's own join,
203
+ // leave and tick (`index.js`), which run before the simulation exists.
204
+ ...(manifest.places[Manifest.MAIN_PLACE]?.loadTelemetry === true ? {
205
+ transportJoin(session, player) {LoadAbandon.join(h, session, player?.playerId);},
206
+ transportLeave(session, player) {LoadAbandon.leave(h, player?.playerId);},
207
+ transportTick() {LoadAbandon.tick(h);},
208
+ } : {}),
148
209
  persist: false,
149
210
  poseEvery,
150
211
  poseIntervalMs: Math.round((poseEvery * 1000) / tickRate),
151
212
 
152
213
  sceneFor(session) {
214
+ const previousSession = h.session;
153
215
  h.session = session;
154
216
  const { id, source } = Place.resolvePlace(session, manifest);
217
+ if (h.manifest.act === true && (h.placeId !== id || previousSession !== session)) {delete h.actPlayers;}
155
218
  h.placeId = id;
156
219
  h.place = manifest.places[id];
157
220
  h.hooks = placeHooks[id] ?? deckHooks;
221
+ if (h.place.anonymousEntry === true) {
222
+ h.anonymousEntry ??= makeAnonymousEntry();
223
+ } else {
224
+ delete h.anonymousEntry;
225
+ }
226
+ if (h.place.analytics === true) {
227
+ h.analytics ??= Analytics.create();
228
+ h.ctx.track = (playerId, event, properties) => Analytics.track(h, playerId, event, properties);
229
+ } else {delete h.ctx.track;}
230
+ {
231
+ h.ctx.track = (id, name, props) => DoorAnalytics.EVENTS[name] ? DoorAnalytics.track(h, id, name, props) : Analytics.track(h, id, name, props);
232
+ }
158
233
  if (typeof h.hooks.resume === 'function') {
159
234
  h.resumeDeparting ??= new Set();
160
235
  }
161
- if (h.place.resumeKeep === true) {
236
+ if (h.place.resumeKeep === true || h.place.resumePose === true || houseResume(h) || pinnedResume(h)) {
162
237
  h.resumeKept ??= new Map();
163
238
  h.resumeDeparting ??= new Set();
164
239
  }
240
+ if (h.place.resumeArrivalPose === true) {
241
+ h.arrivalPoses ??= ArrivalPose.create();
242
+ h.resumeDeparting ??= new Set();
243
+ }
244
+ if (h.place.resumePose === true && session.storage?.deck) {
245
+ h.poseStore = ResumePose.store(session, id, session.hub?.owner ?? null);
246
+ } else { delete h.poseStore; }
165
247
  if (h.place.decor) {
166
248
  h.ctx.decor = Decor.api(h);
167
249
  } else {
@@ -172,6 +254,8 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
172
254
  } else {
173
255
  delete h.ctx.actions;
174
256
  }
257
+ if (h.place.invite === true) {h.ctx.invite = (playerId, options) => Invites.request(h, playerId, options);}
258
+ else {delete h.ctx.invite;}
175
259
  if (h.place.companion === true) {
176
260
  h.ctx.companion = (playerId, spec) => Companion.set(h, playerId, spec);
177
261
  h.ctx.companionDress = true;
@@ -192,7 +276,7 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
192
276
  delete h.ctx.menu;
193
277
  }
194
278
  h.noGround = sceneGround(h.place.scene)?.none === true;
195
- h.fallY = h.place.fallY ?? (h.noGround ? NO_GROUND_FALL_Y : null);
279
+ h.fallY = h.place.fallY ?? DEFAULT_FALL_Y;
196
280
  console.log(`[hub] place ${id} (${source}): ${h.place.scene}`);
197
281
  return h.place.scene;
198
282
  },
@@ -206,6 +290,19 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
206
290
  ready(sim) {
207
291
  h.sim = sim;
208
292
  h.actors = Scene.readScene(sim.scenePath);
293
+ if (h.manifest.quality) {
294
+ const decor = new Set((Scene.sceneOptions?.(sim.scenePath)?.actors ?? []).filter((actor) => actor.decor === true).map((actor) => actor.id));
295
+ h.qualityDecor = new Set(h.actors.filter((actor) => decor.has(actor.id) && classify(actor.components) === 'decor').map((actor) => actor.id));
296
+ }
297
+ if (Scene.sceneOptions?.(sim.scenePath)?.engine?.hubPadOccupancy === true) {
298
+ h.padOccupancy = makePadOccupancy(h.actors);
299
+ // Internal scene state for this deck's hooks, never serialized. This
300
+ // avoids a deck -> sceneBodies -> gameHooks -> deck import cycle.
301
+ sim[Symbol.for('castle.hubPadOccupancy')] = true;
302
+ } else {
303
+ delete h.padOccupancy;
304
+ delete sim[Symbol.for('castle.hubPadOccupancy')];
305
+ }
209
306
  if (h.place.interest === 'cells') {
210
307
  let result;
211
308
  try {
@@ -229,6 +326,13 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
229
326
  // read when the player gets a body.
230
327
  message(session, player, data) {
231
328
  h.session ??= session;
329
+ if (h.place?.fpsTelemetry && data?.k === 'hub-fps') {Analytics.fps(h, session, player, data); return;}
330
+ if (h.place?.loadTelemetry === true && data?.k === 'hub-load') {LoadAbandon.message(h, session, player, data); return;}
331
+
332
+ if (data?.k === 'hub-door-error' || data?.k === 'hub-door-quit') {
333
+ if (session.players.some(p => p.playerId === player?.playerId)) {DoorAnalytics.message(h, player.playerId, data);}
334
+ return;
335
+ }
232
336
  if (data?.k === 'hub-cap' && h.cells) {
233
337
  if (Number.isInteger(data.n)) {
234
338
  const now = Date.now();
@@ -258,9 +362,13 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
258
362
  return;
259
363
  }
260
364
  if (data?.k === 'hub-hello') {
365
+ LoadAbandon.hello(h, player?.playerId);
261
366
  hello(h, player, data);
262
367
  return;
263
368
  }
369
+ // A reset check is in flight. Old client actions must not recreate the
370
+ // player's deleted progress before the deck has reloaded it.
371
+ if (h.players.get(player?.playerId)?.progressReading) { return; }
264
372
  if (data?.k === 'hub-shut') {
265
373
  doorShut(h, player, data);
266
374
  return;
@@ -269,6 +377,10 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
269
377
  doorJump(h, player, data);
270
378
  return;
271
379
  }
380
+ if (data?.k === 'hub-house-visit') {
381
+ houseVisit(h, player, data);
382
+ return;
383
+ }
272
384
  if (data?.k === 'hub-where') {
273
385
  whereAsk(h, player, data);
274
386
  return;
@@ -320,6 +432,11 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
320
432
  Menu.message(h, player?.playerId, data);
321
433
  return;
322
434
  }
435
+ if (h.manifest.act === true && (data?.k === 'hub-act' || data?.k === 'hub-act-hold')) {
436
+ Act.message(h, player, data, placeAt);
437
+ return;
438
+ }
439
+ if (h.manifest.act === true && (data?.k === 'hub-sit' || (data?.k === 'hub-grab' && data.op === 'grab') || (data?.k === 'hub-npc-open' && !data.npc?.startsWith?.('companion:')))) {return;}
323
440
  if (data?.k === 'hub-grab') {
324
441
  Grab.message(h, player?.playerId, data);
325
442
  return;
@@ -349,7 +466,7 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
349
466
  const dt = h.lastPlaceAt === null ? 0 : Math.min(0.25, (sim.timeMs - h.lastPlaceAt) / 1000);
350
467
  h.lastPlaceAt = sim.timeMs;
351
468
  reconcile(h);
352
- Friends.tick(h, userIdOf);
469
+ Friends.tick(h, friendUserIdOf);
353
470
  // v1.28: a try-on on a player who went before saying hello goes too.
354
471
  if (Wear.tryOnUsed(h)) {
355
472
  Wear.pruneTries(h);
@@ -358,6 +475,7 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
358
475
  if (Earned.needsPrune(h)) {
359
476
  Earned.prune(h);
360
477
  }
478
+ retryProgress(h);
361
479
  readResults(h);
362
480
  arrivals(h);
363
481
  if (h.place.visibility === true) {notifyVisibility(h);}
@@ -370,14 +488,35 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
370
488
  Actors.dropLostSpawns(h, h.engine);
371
489
  Actors.driveMoves(h);
372
490
  h.npcs.place(dt);
491
+ if (h.manifest.act === true) {Act.tick(h);}
373
492
  Actors.flushHandovers(h, handovers);
374
493
  },
375
494
 
376
495
  step(sim, handovers) {
377
496
  const dt = h.lastStepAt === null ? 0 : (sim.timeMs - h.lastStepAt) / 1000;
378
497
  h.lastStepAt = sim.timeMs;
498
+ // v1.141: where each body was observed, before any hook reads it.
499
+ // Nothing in a place that never asked (`observe.js`).
500
+ Observe.pass(h);
501
+ // A retained viewer's resume hook cancels authored transient work. Run
502
+ // that hook before the authored step can mature old work. An identity
503
+ // replacement cancels the queued preparation before either hook runs.
504
+ cancelChangedResumeIdentity(h);
505
+ const resumeDeferred = notifyResumes(h, true);
379
506
  h.hooks.step?.(h.ctx, dt);
380
507
  rememberResumePoses(h);
508
+ if (h.arrivalPoses) {
509
+ for (const [id, entry] of h.players) {
510
+ if (entry.arrived && h.session.players.some(p => p.playerId === id) && !h.resumeDeparting.has(id)) {
511
+ h.arrivalPoses.remember(id, arrivalPoseUserId(h, id), h.sim.players.get(id));
512
+ }
513
+ }
514
+ }
515
+ rememberAnonymousEntries(h);
516
+ if (h.poseStore && Date.now() >= (h.posePruneAt ?? 0)) {
517
+ h.posePruneAt = Date.now() + 60000;
518
+ void h.poseStore.prune();
519
+ }
381
520
  // v1.61: no renewal callback exists unless a player holds a shot.
382
521
  h.renewShots?.();
383
522
  Actors.flushTints(h);
@@ -405,7 +544,7 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
405
544
  }
406
545
  // Cabinet cards (v1.7): nothing in a place with no classic door.
407
546
  Cabinets.send(h, (playerId) => namesOf(h, blockedPairs(h)?.get(playerId) ?? []));
408
- notifyResumes(h);
547
+ notifyResumes(h, false, resumeDeferred);
409
548
  Actors.flushHandovers(h, handovers);
410
549
  },
411
550
 
@@ -416,6 +555,10 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
416
555
  // (`blocks.js`) before the nearest are picked, so a hidden player never
417
556
  // takes one of a client's `nearestPlayers` places.
418
557
  interest(sim, known) {
558
+ if (h.padOccupancy) {
559
+ h.padOccupancy.known = known;
560
+ h.padOccupancy.knownAt = sim.timeMs;
561
+ }
419
562
  const pairs = blockedPairs(h);
420
563
  const hidden = pairs ? (viewer, other) => Boolean(pairs.get(viewer)?.has(other)) : null;
421
564
  if (h.cells) {
@@ -456,6 +599,7 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
456
599
  // under it rather than past the world's floor, where no pose is read.
457
600
  hubPlace: { ...Manifest.publicPlace(h.placeId, h.place), fallY: h.fallY },
458
601
  hubAv: avatars(h, blockedPairs(h)),
602
+ ...(h.place.anonymousEntry === true ? { hubGuests: guests(h, blockedPairs(h)) } : {}),
459
603
  // v1.51, only while someone here wears one of the twelve after the first four.
460
604
  ...avatars2ForJoin(h),
461
605
  ...avatarColorsForJoin(h),
@@ -486,6 +630,9 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
486
630
  delta() {
487
631
  const out = {};
488
632
  latch(h, 'hubAv', avatars(h, blockedPairs(h)), out);
633
+ if (h.place.anonymousEntry === true) {
634
+ latch(h, 'hubGuests', guests(h, blockedPairs(h)), out);
635
+ }
489
636
  latchAvatars2(h, out);
490
637
  latchAvatarColors(h, out);
491
638
  latchWearing(h, out);
@@ -631,9 +778,10 @@ function logStats(h) {
631
778
  Object.assign(s, { at: now, cpu: process.cpuUsage(), ticks: 0 });
632
779
  }
633
780
 
634
- function newState(manifest) {
781
+ function newState(manifest, savedDeckId) {
635
782
  const h = {
636
783
  manifest,
784
+ savedDeckId,
637
785
  cells: null,
638
786
  cellTick: null,
639
787
  cellViews: null,
@@ -650,6 +798,8 @@ function newState(manifest) {
650
798
  actors: [],
651
799
  lastStepAt: null,
652
800
  lastPlaceAt: null,
801
+ // v1.141 observed progress, null until a place asks (`observe.js`)
802
+ observe: null,
653
803
  // the height below which a player has fallen, or null (`catchFalls`)
654
804
  fallY: null,
655
805
  // playerId -> when they last jumped to a door or to a player
@@ -663,6 +813,12 @@ function newState(manifest) {
663
813
  // playerId -> { avatar, clientAvatar, from, fromDeckId, party, carry, read,
664
814
  // hello, arrived, arrivedAt, helloAt, result, ended }
665
815
  players: new Map(),
816
+ progressGenerations: new Map(),
817
+ progressApplied: new Map(),
818
+ progressRequests: new Map(),
819
+ // Stable per-player reset/read state. Replacement hellos keep this object;
820
+ // forget or an account change replaces it.
821
+ progressStates: new Map(),
666
822
  // door id -> the gathering pad sent to ghost: { padId, json, at }
667
823
  pads: new Map(),
668
824
  // playerId -> { door, at }: the door that last stayed shut for them
@@ -675,6 +831,13 @@ function newState(manifest) {
675
831
  doorObjects: new Map(),
676
832
  boardsAt: 0,
677
833
  boardsReading: false,
834
+ // v1.112, only for a deck with `hub.weeklyCup: true`: player id -> the
835
+ // current identity's private occurrence map. The map is never serialized.
836
+ cups: new Map(),
837
+ // door id -> the authoritative event clock paired with its latest board.
838
+ // Raw clock metadata is stripped before the board reaches authored code.
839
+ cupClocks: new Map(),
840
+ cupRead: null,
678
841
  // `${op}:${code}` refusals already logged
679
842
  refusals: new Set(),
680
843
  hud: null,
@@ -729,9 +892,23 @@ function newState(manifest) {
729
892
  // The `hub` every deck hook is handed.
730
893
  function makeContext(h) {
731
894
  return {
895
+ get push() {
896
+ return h.place?.push?.version === 1 ? h.session?.hub?.push : undefined;
897
+ },
732
898
  get session() {
733
899
  return h.session;
734
900
  },
901
+ // A place may ask for an explicit server-side refresh after an admin reset.
902
+ refreshProgress(playerId) {
903
+ return refreshProgress(h, playerId);
904
+ },
905
+ progressGeneration(playerId) {
906
+ const userId = userIdOf(h, playerId);
907
+ return userId ? h.progressGenerations.get(userId) ?? null : null;
908
+ },
909
+ progressPending(userId) {
910
+ return [...h.players.values()].some((entry) => entry.progressReading && (userId === undefined || String(entry.userId) === String(userId)));
911
+ },
735
912
  get sim() {
736
913
  return h.sim;
737
914
  },
@@ -748,13 +925,18 @@ function makeContext(h) {
748
925
  get now() {
749
926
  return h.sim?.timeMs ?? 0;
750
927
  },
928
+ goalPositions: true,
751
929
  players() {
752
930
  const out = [];
753
931
  for (const [playerId, body] of h.sim?.players ?? []) {
932
+ // A transport departure precedes real-time's physical removal. The
933
+ // opted lifecycle must expose the same live roster as ordinary leave.
934
+ if (h.arrivalPoses && !h.session?.players.some(p => p.playerId === playerId)) {continue;}
754
935
  out.push({
755
936
  playerId,
756
937
  username: usernameOf(h, playerId),
757
938
  userId: userIdOf(h, playerId),
939
+ ...(h.place.anonymousEntry === true ? { identityUserId: identityUserIdOf(h, playerId) } : {}),
758
940
  at: { ...body.at },
759
941
  arrivedAt: h.players.get(playerId)?.arrivedAt ?? null,
760
942
  });
@@ -765,7 +947,19 @@ function makeContext(h) {
765
947
  return h.actors.filter((actor) => actor.components[name]).map((actor) => Actors.describe(actor, name));
766
948
  },
767
949
  username: (playerId) => usernameOf(h, playerId),
768
- placeAt: (playerId, at, facingDeg) => placeAt(h, playerId, at, facingDeg === undefined ? undefined : facingDeg * DEG),
950
+ placeAt(playerId, at, facingDeg) {
951
+ const facing = facingDeg === undefined ? h.sim?.players.get(playerId)?.facing : facingDeg * DEG;
952
+ const signUp = h.players.get(playerId)?.signUp;
953
+ if (signUp && !signUp.finished && at && [at.x, at.y, at.z].every(Number.isFinite)) {
954
+ signUp.chosenPose = { ...at, facing };
955
+ if (h.held.get(playerId)?.waiting) {h.held.delete(playerId);}
956
+ }
957
+ return placeAt(h, playerId, at, facing);
958
+ },
959
+ // v1.141 observed progress (`docs/observed-progress.md`).
960
+ observed: (playerId) => Observe.observed(h, playerId),
961
+ station: (id, spec) => Observe.station(h, id, spec),
962
+ dwell: (playerId, id) => Observe.dwell(h, playerId, id),
769
963
  hold(playerId, at, facingDeg) {
770
964
  const body = h.sim?.players.get(playerId);
771
965
  if (!body) {
@@ -821,12 +1015,21 @@ function makeContext(h) {
821
1015
  mark: (playerId, spec) => Actors.mark(h, playerId, spec),
822
1016
  leaving: (playerId, text) => leaving(h, playerId, text),
823
1017
  results: (playerId) => History.results(h, playerId),
824
- friendsAmong: (playerId, userIds) => Friends.friendsAmong(h, playerId, userIds, userIdOf),
1018
+ ...(h.place.freshFriends === true ? { freshFriends: true } : {}),
1019
+ friendsAmong: (playerId, userIds) => Friends.friendsAmong(h, playerId, userIds, friendUserIdOf),
825
1020
  friendBests: (key, options) => friendBests(h, key, options, userIdOf),
826
1021
  wear: (playerId, spec) => wear(h, playerId, spec),
827
1022
  tryOn: (playerId, spec) => Wear.tryOn(h, playerId, spec),
828
1023
  wearing: (playerId) => Wear.wearing(h, playerId),
829
- unlock: (playerId, itemId) => Earned.unlock(h, playerId, itemId, earnedDeps(h, playerId, 'unlock')),
1024
+ unlock: (playerId, itemId) => {
1025
+ const entry = h.players.get(playerId);
1026
+ return Earned.unlock(h, playerId, itemId, earnedDeps(h, playerId, 'unlock')).then(answer => {
1027
+ if (answer?.saved && answer.isNew && h.players.get(playerId) === entry) {
1028
+ DoorAnalytics.track(h, playerId, 'door_progress', { value: 1, result: 2 });
1029
+ }
1030
+ return answer;
1031
+ });
1032
+ },
830
1033
  wearEarned: (playerId, choice) => Earned.wearEarned(h, playerId, choice, earnedDeps(h, playerId, 'wearEarned')),
831
1034
  unlocksOf: (userIds) => Earned.unlocksOf(platformHub(h), userIds, (err) => refused(h, 'unlocks', err), h),
832
1035
  earned: (playerId) => Earned.earnedOf(h, playerId),
@@ -846,6 +1049,7 @@ function makeContext(h) {
846
1049
  emote: (playerId, id) => Idle.emote(h, playerId, id),
847
1050
  seat: (playerId) => Idle.seat(h, playerId),
848
1051
  sound: (actorId, file, options) => Idle.sound(h, actorId, file, options),
1052
+ danceIdle: (actorId, options) => Idle.danceIdle(h, actorId, options),
849
1053
  cue: (target, name) => Cues.cue(h, target, name),
850
1054
  shot: (playerId, value) => Shot.shot(h, playerId, value),
851
1055
  holding: (playerId) => Grab.holding(h, playerId),
@@ -862,6 +1066,11 @@ function makeContext(h) {
862
1066
  // v1.16: the other members of a player's party who are in this place now.
863
1067
  partyOf: (playerId) => Party.matesHere(h, playerId),
864
1068
  board: (door) => h.boards.get(door) ?? null,
1069
+ ...(h.manifest.weeklyCup === true ? {
1070
+ cup: (playerId, door) => cupFor(h, playerId, door),
1071
+ cupNow: (door) => cupNowFor(h, door),
1072
+ cupDeckId: h.savedDeckId,
1073
+ } : {}),
865
1074
  doors: () => doors(h),
866
1075
  send: (playerId, data) => h.session?.send(playerId, data),
867
1076
  broadcast: (data) => h.session?.broadcast(data),
@@ -879,12 +1088,55 @@ function platformHub(h) {
879
1088
  // the host has hub ops, the door is ghost's arrival and the result and avatar
880
1089
  // are read from ghost (`readResults`). The hello's avatar and colour are
881
1090
  // provisional until that read; colours also work with the manifest opt-in.
1091
+ function queuedResumeHello(h, playerId, known, data, synthetic, signUp, invitedAfresh) {
1092
+ if (!known?.arrived || signUp || invitedAfresh || h.resumeDeparting?.has(playerId) ||
1093
+ typeof h.hooks.resume !== 'function') {
1094
+ return null;
1095
+ }
1096
+ const kept = h.resumeKept?.get(playerId);
1097
+ const body = h.sim?.players.get(playerId);
1098
+ const companionHello = !synthetic && data.resume === true && Boolean(body && kept?.pendingClientHello === body);
1099
+ const freshSignal = data.again !== true && !companionHello;
1100
+ return {
1101
+ kept,
1102
+ body,
1103
+ companionHello,
1104
+ freshSignal,
1105
+ queue: freshSignal || h.resumePending?.has(playerId),
1106
+ };
1107
+ }
1108
+
882
1109
  function hello(h, player, data, synthetic = false) {
883
- prepareResume(h, player.playerId, false);
884
- const clientAvatar = Number.isInteger(data.avatar) && data.avatar >= 0 && data.avatar < AVATARS ? data.avatar : 0;
885
- const clientColor = (h.manifest.avatarColors === true || platformHub(h)) ? cleanAvatarColor(data.color) : 0;
1110
+ const prepared = prepareResume(h, player.playerId, false);
1111
+ if (prepared === 'handled') {
1112
+ return;
1113
+ }
1114
+ if (prepared === 'fresh') {
1115
+ data = { ...data };
1116
+ delete data.resume;
1117
+ }
1118
+ let clientAvatar = Number.isInteger(data.avatar) && data.avatar >= 0 && data.avatar < AVATARS ? data.avatar : 0;
1119
+ let clientColor = (h.manifest.avatarColors === true || platformHub(h)) ? cleanAvatarColor(data.color) : 0;
886
1120
  const party = Number.isInteger(data.party) && data.party >= 1 && data.party <= 24 ? data.party : 1;
887
1121
  const known = h.players.get(player.playerId);
1122
+ // The trusted roster may already show the replacement account on a retained
1123
+ // socket. Preserve the last guest pose before consuming its identity link.
1124
+ if (h.anonymousEntry && known?.anonymous === true) {
1125
+ rememberAnonymousEntry(h, player.playerId, known);
1126
+ }
1127
+ const rosterPlayer = h.session?.players.find((p) => p.playerId === player.playerId);
1128
+ const signedUp = h.anonymousEntry?.take(rosterPlayer, Date.now()) ?? null;
1129
+ // A single transaction survives entry replacement by repeated hellos.
1130
+ const currentIdentity = identityUserIdOf(h, player.playerId);
1131
+ const identityChanged = h.anonymousEntry && known?.identityUserId && currentIdentity !== known.identityUserId;
1132
+ const samePendingIdentity = rosterPlayer?.isAnonymous === false && currentIdentity === known?.identityUserId;
1133
+ if (known?.signUp && !samePendingIdentity) {finishSignUp(h, player.playerId, known.signUp, true);}
1134
+ const signUp = signedUp ? {
1135
+ carry: signedUp, identityUserId: currentIdentity,
1136
+ arrivalSettled: false, readSettled: !platformHub(h),
1137
+ } : samePendingIdentity ? known?.signUp : null;
1138
+ // Ordinary reconnect hellos replay; `again` is an explicit picker action.
1139
+ const keepSignUpChoice = Boolean(signUp && data.again !== true);
888
1140
  // A player this place let go whose connection came back still holding what
889
1141
  // it was sent (`greetLate`): the client's own resume hello or the place's
890
1142
  // late greet for it, whichever comes first, arrives them once and marks that
@@ -905,7 +1157,18 @@ function hello(h, player, data, synthetic = false) {
905
1157
  // (`hub-end` with `again`), and the HUD, shot and the rest (`staleSent`
906
1158
  // and the place's own arrive);
907
1159
  // I4 provenance (`from`, `fromDeckId`) is written once per visit.
908
- const back = !known && data.resume === true && Boolean(h.forgotten?.has(player.playerId));
1160
+ // A fresh replacement page may say an ordinary first hello. Accepting its
1161
+ // authenticated pose also resumes the same visit's result/deadline/door.
1162
+ const poseOwner = h.arrivalPoses ? arrivalPoseUserId(h, player.playerId) : null;
1163
+ // Expiry and one-use ownership are decided together here, never after a
1164
+ // normal group/progress wait. Repeated hello keeps only this owner's claim.
1165
+ const claimedPose = h.arrivalPoses
1166
+ ? known
1167
+ ? known.arrivalPose?.userId === poseOwner ? known.arrivalPose : null
1168
+ : h.arrivalPoses.take(player.playerId, poseOwner)
1169
+ : null;
1170
+ const poseBack = !known && Boolean(claimedPose) && h.forgotten?.get(player.playerId)?.userId === poseOwner;
1171
+ const back = !known && (data.resume === true || poseBack) && Boolean(h.forgotten?.has(player.playerId));
909
1172
  const resumes = h.place?.result ? h.place.resume === true : false;
910
1173
  if (back && h.place?.result && !resumes) {
911
1174
  return;
@@ -938,26 +1201,55 @@ function hello(h, player, data, synthetic = false) {
938
1201
  };
939
1202
  const from = keep('from', said);
940
1203
  const fromDeckId = keep('fromDeckId', arrival?.fromDeckId ?? null);
1204
+ if (keepSignUpChoice && !signedUp && known) {
1205
+ clientAvatar = known.clientAvatar;
1206
+ clientColor = known.clientColor;
1207
+ }
941
1208
  // A later hello with the same choice keeps the platform avatar a read found;
942
1209
  // a new choice wins, and outdates any read in flight (`avatarRev`).
943
- const same = known?.hello && known.clientAvatar === clientAvatar;
1210
+ const same = known?.hello && known.clientAvatar === clientAvatar && !(h.anonymousEntry && data.again === true);
944
1211
  const sameColor = same && known.clientColor === clientColor;
1212
+ const invited = h.place.invite === true && data.invited === true;
1213
+ const inviteNear = typeof data.near === 'string' && USER_ID.test(data.near) ? data.near : null;
1214
+ // A retained connection can accept another invite while its old visit is
1215
+ // still arrived. The explicit target makes this a fresh placement; a plain
1216
+ // reconnect carries no target and keeps the retained pose.
1217
+ const invitedAfresh = invited && inviteNear !== null && data.again !== true && data.resume !== true;
945
1218
  // A stale ballot card still waiting to be cleared survives a repeated
946
1219
  // resume hello, whose joinedAfresh below would otherwise drop the mark.
947
1220
  const ballotStale = back || h.ballotState?.sent.get(player.playerId) === STALE;
1221
+ const resumeHello = queuedResumeHello(
1222
+ h, player.playerId, known, data, synthetic, signUp, invitedAfresh,
1223
+ );
1224
+ // A same-body reload has no observed away tick for prepareResume to mark.
1225
+ // Gate it by the same authored-resume eligibility used below, before any
1226
+ // retained map can replay. Avatar updates and the synthetic companion hello
1227
+ // are not new signals and therefore cannot open another gate.
1228
+ if (h.place.resumeVisibility === true && resumeHello?.freshSignal && resumeHello.kept) {
1229
+ if (typeof resumeHello.kept.identityUserId !== 'string') {
1230
+ // Private retained state needs an authenticated owner. An anonymous
1231
+ // transport id cannot cross this fresh signal: finalize the old visit
1232
+ // before its action/cache replay, then consume this hello as a fresh one.
1233
+ return restartRetainedAsFresh(h, player, known, data, synthetic);
1234
+ }
1235
+ if (resumeHello.kept.identityUserId === userIdOf(h, player.playerId)) {
1236
+ resumeHello.kept.visibilityResumePending = true;
1237
+ }
1238
+ }
948
1239
  // A hello that is not an avatar change is a client that joined afresh: it
949
1240
  // holds none of the cabinet cards it was sent (v1.7).
950
1241
  if (data.again !== true) {
951
1242
  replaySent(h, player.playerId, data.resume === true);
1243
+ if (h.manifest.act === true) {Act.replay(h, player.playerId);}
952
1244
  h.npcs.replayPreferred(player.playerId, data.resume === true);
953
1245
  Shot.joinedAfresh(h, player.playerId);
954
- Vis.joinedAfresh(h, player.playerId);
1246
+ Vis.joinedAfresh(h, player.playerId, userIdOf(h, player.playerId));
955
1247
  Decor.joinedAfresh(h, player.playerId);
956
1248
  if (h.place.actions === true) {
957
1249
  Actions.joinedAfresh(h, player.playerId);
958
1250
  }
959
1251
  if (h.place.companion === true) {
960
- Companion.joinedAfresh(h, player.playerId);
1252
+ Companion.joinedAfresh(h, player.playerId, userIdOf(h, player.playerId));
961
1253
  }
962
1254
  if (h.place.ask === true) {
963
1255
  Ask.joinedAfresh(h, player.playerId);
@@ -981,31 +1273,60 @@ function hello(h, player, data, synthetic = false) {
981
1273
  h.session?.send(player.playerId, { k: 'hub-leaving', text: h.leaving.get(player.playerId) });
982
1274
  }
983
1275
  }
984
- h.players.set(player.playerId, {
1276
+ const progressUser = userIdOf(h, player.playerId) ?? known?.userId ?? null;
1277
+ let progressState = h.progressStates.get(player.playerId);
1278
+ if (!progressState || progressState.userId !== progressUser) {
1279
+ const appliedGeneration = h.progressApplied.get(progressUser) ?? 0;
1280
+ progressState = { userId: progressUser, locks: new Set(), appliedGeneration, cleanupGeneration: appliedGeneration, version: 0, resetting: null, markerKnown: appliedGeneration > 0, markerStartedAt: Date.now(), markerBypass: false };
1281
+ h.progressStates.set(player.playerId, progressState);
1282
+ }
1283
+ const continuedProgress = known?.progressState === progressState;
1284
+ // A new automatic marker read must not turn an already committed retained
1285
+ // visit into blocked preparation. Resume its transient work first, then read.
1286
+ // Existing reads, reset failures and unknown markers still fail closed.
1287
+ const resumeBeforeProgressRead = resumeHello?.queue &&
1288
+ resumeHello.kept?.visibilityResumePending === true && continuedProgress &&
1289
+ progressState.markerKnown && !progressState.locks.size &&
1290
+ !accountProgressBlocked(h, progressUser);
1291
+ const entry = {
985
1292
  // Who this is, kept for `leave`: by then the session has forgotten them.
986
1293
  ...(h.place.visibility === true && known?.visibility ? { visibility: known.visibility, visibilityPending: known.visibilityPending } : {}),
987
- userId: userIdOf(h, player.playerId) ?? known?.userId ?? null,
1294
+ userId: progressUser,
1295
+ ...((known || poseBack) && claimedPose ? { arrivalPose: { ...claimedPose, userId: poseOwner } } : {}),
988
1296
  username: usernameOf(h, player.playerId),
989
1297
  avatar: same ? known.avatar : clientAvatar,
990
- clientAvatar,
1298
+ clientAvatar: clientAvatar,
991
1299
  color: sameColor ? known.color : clientColor,
992
- clientColor,
1300
+ clientColor: clientColor,
993
1301
  colorRev: sameColor ? known.colorRev : (known?.colorRev ?? 0) + 1,
994
1302
  avatarRev: same ? known.avatarRev : (known?.avatarRev ?? 0) + 1,
995
1303
  from,
996
1304
  fromDeckId,
997
1305
  // A jump to a friend says whom (the client's word: it decides only where
998
1306
  // the player appears, beside someone already in this session).
999
- near: typeof data.near === 'string' && USER_ID.test(data.near) ? data.near : (known?.near ?? null),
1307
+ near: inviteNear ?? (invited && known?.arrived ? null : known?.near ?? null),
1308
+ // Authored welcome flow only; this client hint grants no travel or follows.
1309
+ invited,
1000
1310
  party,
1001
1311
  carry: hub ? known?.carry ?? null : cleanCarry(data.carry),
1002
- read: known?.read ?? (hub ? 'want' : 'done'),
1312
+ read: progressState.readLifetime?.phase ?? (continuedProgress ? (known?.read === 'reading' ? 'want' : known?.read) : null) ?? (hub ? 'want' : 'done'),
1313
+ progressVersion: progressState.version,
1314
+ progressState,
1315
+ ...(h.progressEnabled ? { progressReading: Boolean(progressState.locks.size || accountProgressBlocked(h, progressUser) || (!resumeBeforeProgressRead && progressUser && canReadProgress(h) && typeof h.session?.storage?.playthrough === 'function')) } : {}),
1316
+ ...(resumeBeforeProgressRead ? { progressRefreshPending: true } : {}),
1003
1317
  hello: true,
1004
1318
  // A second hello (the avatar changed) keeps the player's place in an
1005
1319
  // arrival group.
1006
1320
  helloAt: known?.hello ? known.helloAt : Date.now(),
1007
- arrived: known?.arrived ?? false,
1008
- arrivedAt: known?.arrivedAt ?? null,
1321
+ arrived: signedUp || identityChanged || invitedAfresh ? false : known?.arrived ?? false,
1322
+ arrivedAt: signedUp || identityChanged || invitedAfresh ? null : known?.arrivedAt ?? null,
1323
+ ...(h.place.anonymousEntry === true ? {
1324
+ identityUserId: identityUserIdOf(h, player.playerId),
1325
+ anonymous: rosterPlayer?.isAnonymous === true,
1326
+ } : {}),
1327
+ ...(signUp ? { signUp } : {}),
1328
+ ...(known?.poseReading ? { poseReading: true } : {}),
1329
+ ...(!signedUp && known?.coldPose ? { coldPose: known.coldPose } : {}),
1009
1330
  result: known?.result ?? (last ? last.result ?? null : null),
1010
1331
  // ghost's results of this player for `hub.results`, kept across hellos
1011
1332
  history: known?.history ?? null,
@@ -1016,35 +1337,262 @@ function hello(h, player, data, synthetic = false) {
1016
1337
  ...(resumes && (known?.visitAt ?? last?.visitAt) !== undefined ? { visitAt: known?.visitAt ?? last.visitAt } : {}),
1017
1338
  ...(resumes && (known?.endWhy ?? last?.endWhy) !== undefined ? { endWhy: known?.endWhy ?? last.endWhy } : {}),
1018
1339
  ...(last?.ended === true || known?.endAgain === true ? { endAgain: true } : {}),
1019
- });
1340
+ ...(resumes && known?.arrived && known.ended && data.resume === true ? { endReplayPending: true } : {}),
1341
+ };
1342
+ if (signedUp) {
1343
+ signUp.avatarRev = entry.avatarRev;
1344
+ signUp.colorRev = entry.colorRev;
1345
+ }
1346
+ h.players.set(player.playerId, entry);
1347
+ if (h.poseStore && !signedUp && !known?.hello && entry.userId) {
1348
+ // The new socket may say hello before reconciliation observed the old one
1349
+ // disappear. End only an absent socket belonging to this same account.
1350
+ for (const [id, old] of h.players) {
1351
+ if (id !== player.playerId && old.userId === entry.userId &&
1352
+ !h.session.players.some((p) => p.playerId === id)) { prepareResume(h, id, false); }
1353
+ }
1354
+ entry.poseReading = true;
1355
+ void h.poseStore.take(entry.userId, player.playerId).then((pose) => {
1356
+ const current = h.players.get(player.playerId);
1357
+ if (!current || current.progressState !== entry.progressState || h.resumeDeparting?.has(player.playerId)) { return; }
1358
+ current.coldPose = pose;
1359
+ current.poseReading = false;
1360
+ });
1361
+ }
1362
+ if (h.players.get(player.playerId).progressReading) { void refreshProgress(h, player.playerId); }
1020
1363
  // v1.89: hook presence opts in. Wait until the private replay was sent;
1021
1364
  // the entry identity also prevents a queued hello from crossing a leave.
1022
- if (known?.arrived && !h.resumeDeparting?.has(player.playerId) && typeof h.hooks.resume === 'function') {
1023
- const kept = h.resumeKept?.get(player.playerId);
1024
- const body = h.sim?.players.get(player.playerId);
1025
- const companionHello = !synthetic && data.resume === true && Boolean(body && kept?.pendingClientHello === body);
1026
- if (companionHello) {
1027
- delete kept.pendingClientHello;
1365
+ if (resumeHello) {
1366
+ if (resumeHello.companionHello) {
1367
+ delete resumeHello.kept.pendingClientHello;
1028
1368
  }
1029
- if (synthetic && kept) {
1030
- kept.pendingClientHello = body;
1369
+ if (synthetic && resumeHello.kept) {
1370
+ resumeHello.kept.pendingClientHello = resumeHello.body;
1031
1371
  }
1032
- if ((data.again !== true && !companionHello) || h.resumePending?.has(player.playerId)) {
1372
+ if (resumeHello.queue) {
1033
1373
  (h.resumePending ??= new Map()).set(player.playerId, h.players.get(player.playerId));
1034
1374
  }
1035
1375
  }
1036
1376
  // I3: one still here whose visit ended hears the end again (a drop may
1037
1377
  // have lost it); one back is told once arrived (`arrivals`).
1038
- if (resumes && known?.arrived && known.ended && data.resume === true) {
1378
+ if (h.players.get(player.playerId).endReplayPending && !h.players.get(player.playerId).progressReading && !h.players.get(player.playerId).progressRefreshPending) {
1379
+ delete h.players.get(player.playerId).endReplayPending;
1039
1380
  endAgain(h, player.playerId);
1040
1381
  }
1041
- Friends.prime(h, player.playerId, userIdOf);
1382
+ Friends.prime(h, player.playerId, friendUserIdOf);
1042
1383
  // After joinedAfresh above, which resets this cache.
1043
1384
  if (ballotStale && h.ballotState) {
1044
1385
  h.ballotState.sent.set(player.playerId, STALE);
1045
1386
  }
1046
1387
  }
1047
1388
 
1389
+ // The reset marker is separate from playthrough generation. Request identity
1390
+ // fences an older open that completes after a newer hello or explicit refresh.
1391
+ async function refreshProgress(h, playerId) {
1392
+ if (!h.progressEnabled || !canReadProgress(h)) { return null; }
1393
+ const entry = h.players.get(playerId);
1394
+ const userId = userIdOf(h, playerId);
1395
+ if (!entry || !userId || typeof h.session?.storage?.playthrough !== 'function') { return null; }
1396
+ const state = entry.progressState;
1397
+ const previous = h.progressRequests.get(playerId);
1398
+ if (previous) {
1399
+ previous.state.locks.delete(previous);
1400
+ }
1401
+ const request = { state };
1402
+ state.markerRetryAt = Date.now() + progressRetryGap(state);
1403
+ h.progressRequests.set(playerId, request);
1404
+ const lock = (id, currentState, token) => {
1405
+ currentState.locks.add(token);
1406
+ syncProgressUser(h, currentState.userId);
1407
+ };
1408
+ const unlock = (id, currentState, token) => {
1409
+ currentState.locks.delete(token);
1410
+ syncProgressUser(h, currentState.userId);
1411
+ };
1412
+ lock(playerId, state, request);
1413
+ if (previous && previous.state.userId !== state.userId) {
1414
+ syncProgressUser(h, previous.state.userId);
1415
+ }
1416
+ try {
1417
+ const opened = await h.session.storage.playthrough(userId);
1418
+ if (h.progressRequests.get(playerId) !== request || h.players.get(playerId) !== entry) { return null; }
1419
+ // Only a successful platform handle proves a never-reset generation.
1420
+ // Missing/failed opens must retain the unknown-marker fallback.
1421
+ const generation = opened?.resetGeneration ??
1422
+ (Number.isSafeInteger(opened?.generation) && opened.generation >= 1 ? 0 : null);
1423
+ if (!Number.isSafeInteger(generation) || generation < 0) { throw Error('Invalid progress marker read'); }
1424
+ if (state.readFailure) {
1425
+ unlock(playerId, state, state.readFailure);
1426
+ state.readFailure = null;
1427
+ }
1428
+ state.readFailures = 0;
1429
+ state.markerKnown = true;
1430
+ state.markerBypass = false;
1431
+ request.generation = generation;
1432
+ if (Number.isSafeInteger(generation) && generation < (h.progressGenerations.get(userId) ?? 0)) {
1433
+ return h.progressGenerations.get(userId);
1434
+ }
1435
+ const newer = Number.isSafeInteger(generation) && generation > (h.progressGenerations.get(userId) ?? 0);
1436
+ const sameUser = [...h.players].filter(([id]) => userIdOf(h, id) === userId);
1437
+ const retryFailed = sameUser.some(([, current]) => current.progressState.failure && current.progressState.appliedGeneration < generation);
1438
+ const targets = newer || retryFailed ? sameUser.filter(([, current]) => current.progressState.resetting?.generation !== generation)
1439
+ : Number.isSafeInteger(generation) && generation > 0
1440
+ ? sameUser.filter(([, current]) => current.progressState.appliedGeneration < generation && current.progressState.resetting?.generation !== generation)
1441
+ : [];
1442
+ if (targets.length) {
1443
+ const resets = new Map();
1444
+ let cleaned = false;
1445
+ if (newer) { h.progressGenerations.set(userId, generation); }
1446
+ if (newer) {
1447
+ for (const pending of h.progressRequests.values()) {
1448
+ if (pending !== request && pending.state.userId === userId && Number.isSafeInteger(pending.generation) && pending.generation < generation) {
1449
+ pending.state.locks.delete(pending);
1450
+ }
1451
+ }
1452
+ for (const [id, forgotten] of h.forgotten ?? []) {
1453
+ if (forgotten.userId === userId) { h.forgotten.delete(id); }
1454
+ }
1455
+ }
1456
+ for (const [id, current] of targets) {
1457
+ const targetState = current.progressState;
1458
+ targetState.markerKnown = true;
1459
+ targetState.markerBypass = false;
1460
+ if (targetState.resetting && targetState.resetting.generation < generation) {
1461
+ unlock(id, targetState, targetState.resetting);
1462
+ }
1463
+ if (targetState.failure) { unlock(id, targetState, targetState.failure); targetState.failure = null; }
1464
+ const reset = { generation };
1465
+ resets.set(id, reset);
1466
+ targetState.resetting = reset;
1467
+ lock(id, targetState, reset);
1468
+ // Kit-owned cleanup belongs to the reset generation, not each hook
1469
+ // attempt. An equal-marker retry reruns only the failed hook, leaving
1470
+ // progress read since the first attempt intact.
1471
+ if (generation > (targetState.cleanupGeneration ?? 0)) {
1472
+ targetState.cleanupGeneration = generation;
1473
+ cleaned = true;
1474
+ current.progressVersion = ++targetState.version;
1475
+ current.carry = null;
1476
+ current.result = null;
1477
+ current.history = null;
1478
+ current.historyFrom = null;
1479
+ targetState.readLifetime = null;
1480
+ current.read = platformHub(h) ? 'want' : 'done';
1481
+ current.ended = false;
1482
+ delete current.endAgain;
1483
+ delete current.endReplayPending;
1484
+ Wear.forget(h, id);
1485
+ Earned.forget(h, id);
1486
+ h.npcs.leave(id);
1487
+ h.hudMe.delete(id);
1488
+ h.labelsMe.delete(id);
1489
+ h.leaving.delete(id);
1490
+ staleSent(h, id, false);
1491
+ }
1492
+ }
1493
+ if (cleaned) {
1494
+ h.historyEpoch = (h.historyEpoch ?? 0) + 1;
1495
+ h.historyAt = 0;
1496
+ }
1497
+ for (const [id, current] of targets) {
1498
+ const targetState = current.progressState;
1499
+ const reset = resets.get(id);
1500
+ let failed = false;
1501
+ try {
1502
+ if (h.progressGenerations.get(userId) !== generation) { continue; }
1503
+ await h.hooks.progressReset?.(h.ctx, id, generation, { arrived: current.arrived });
1504
+ if (h.progressStates.get(id) === targetState && targetState.resetting === reset && h.progressGenerations.get(userId) === generation) {
1505
+ targetState.appliedGeneration = generation;
1506
+ }
1507
+ } catch {
1508
+ if (h.progressStates.get(id) === targetState && targetState.resetting === reset && h.progressGenerations.get(userId) === generation) {
1509
+ targetState.failure = reset;
1510
+ failed = true;
1511
+ }
1512
+ if (!h.progressHookWarned) {
1513
+ h.progressHookWarned = true;
1514
+ console.warn('[hub] progress reset hook failed');
1515
+ }
1516
+ } finally {
1517
+ if (targetState.resetting === reset) { targetState.resetting = null; }
1518
+ if (!failed) { unlock(id, targetState, reset); }
1519
+ }
1520
+ }
1521
+ if (h.progressGenerations.get(userId) === generation &&
1522
+ [...h.players.values()].filter((current) => current.userId === userId)
1523
+ .every((current) => current.progressState.appliedGeneration >= generation && !current.progressState.resetting && !current.progressState.failure)) {
1524
+ h.progressApplied.set(userId, generation);
1525
+ }
1526
+ } else if (Number.isSafeInteger(generation) && !h.progressGenerations.has(userId)) {
1527
+ h.progressGenerations.set(userId, generation);
1528
+ }
1529
+ return Number.isSafeInteger(generation) ? generation : null;
1530
+ } catch (err) {
1531
+ if (h.progressRequests.get(playerId) === request && h.players.get(playerId) === entry) {
1532
+ if (!state.readFailure) {
1533
+ state.readFailure = {};
1534
+ lock(playerId, state, state.readFailure);
1535
+ }
1536
+ state.readFailures = (state.readFailures ?? 0) + 1;
1537
+ const gap = progressRetryGap(state);
1538
+ state.markerRetryAt = Date.now() + gap;
1539
+ if (gap !== state.warnedGap || Date.now() - state.warnedAt >= PROGRESS_RETRY_MAX_MS) {
1540
+ state.warnedGap = gap;
1541
+ state.warnedAt = Date.now();
1542
+ console.warn(`[hub] progress reset read failed (${typeof err?.code === 'string' ? err.code : 'error'}); retrying in ${gap / 1000} s`);
1543
+ }
1544
+ }
1545
+ return null;
1546
+ } finally {
1547
+ if (h.progressRequests.get(playerId) === request) { h.progressRequests.delete(playerId); }
1548
+ unlock(playerId, state, request);
1549
+ }
1550
+ }
1551
+
1552
+ function progressRetryGap(state) {
1553
+ return Math.min(PROGRESS_RETRY_MS * 2 ** Math.max(0, (state.readFailures ?? 0) - 1), PROGRESS_RETRY_MAX_MS);
1554
+ }
1555
+
1556
+ function accountProgressBlocked(h, userId) {
1557
+ return Boolean(userId && [...h.progressStates.values()].some((state) => state.userId === userId && (state.resetting || state.failure || (state.readFailure && !state.markerBypass))));
1558
+ }
1559
+
1560
+ function syncProgressUser(h, userId) {
1561
+ const blocked = accountProgressBlocked(h, userId);
1562
+ for (const [id, entry] of h.players) {
1563
+ if (entry.userId === userId) {
1564
+ entry.progressReading = Boolean((entry.progressState.locks.size && !entry.progressState.markerBypass) || blocked);
1565
+ if (!entry.progressReading && !entry.progressRefreshPending && entry.endReplayPending) {
1566
+ delete entry.endReplayPending;
1567
+ endAgain(h, id);
1568
+ }
1569
+ }
1570
+ }
1571
+ }
1572
+
1573
+ // Older or unavailable platforms must not strand an initial arrival. Only an
1574
+ // unobserved marker may use this fallback; a confirmed reset keeps its lock.
1575
+ function retryProgress(h) {
1576
+ if (!h.progressEnabled || !canReadProgress(h) || typeof h.session?.storage?.playthrough !== 'function') { return; }
1577
+ const now = Date.now();
1578
+ for (const [id, entry] of h.players) {
1579
+ const state = entry.progressState;
1580
+ if (!state || (state.markerKnown && !state.readFailure)) { continue; }
1581
+ if (!state.markerKnown && !state.markerBypass && now - state.markerStartedAt >= PROGRESS_ARRIVAL_WAIT_MS) {
1582
+ state.markerBypass = true;
1583
+ console.warn('[hub] progress reset marker unavailable; allowing arrival while retrying');
1584
+ syncProgressUser(h, state.userId);
1585
+ }
1586
+ if (now >= (state.markerRetryAt ?? Infinity)) { void refreshProgress(h, id); }
1587
+ }
1588
+ }
1589
+
1590
+ // An unsaved local serve has no deck Store or platform reset marker. Its SDK
1591
+ // still exposes playthrough(), but the dev broker refuses every such call.
1592
+ function canReadProgress(h) {
1593
+ return !isDevSession(h) || (h.deckId !== 'local' && h.deckId !== 'dev');
1594
+ }
1595
+
1048
1596
  // What a returning client says it brings back: the result its game sent it.
1049
1597
  // It is the client's word, display-only; read only where the host has no hub
1050
1598
  // ops (the dev serve). Elsewhere a town reads the result from ghost (§7).
@@ -1074,6 +1622,10 @@ function outcomeOrNone(outcome) {
1074
1622
  // result for the visit (the host takes one for a player who has just left)
1075
1623
  // and save their progress under the user id it is handed (v1.2).
1076
1624
  function reconcile(h) {
1625
+ // v1.145: before any private channel below can send to a changed account.
1626
+ if (h.place.resumePose === true && h.place.resumeVisibility !== true) {
1627
+ clearChangedHeldIdentity(h);
1628
+ }
1077
1629
  for (const playerId of h.resumeKept?.keys() ?? []) {
1078
1630
  prepareResume(h, playerId);
1079
1631
  }
@@ -1123,29 +1675,130 @@ function reconcile(h) {
1123
1675
  }
1124
1676
 
1125
1677
  // v1.89 opt-in retention: the transport supplies no close reason. An absent
1126
- // body is held for at most 60 wall-clock seconds; shutdown and explicit kit
1678
+ // body is held for at most 60 wall-clock seconds (five minutes for v1.98
1679
+ // town resumePose); shutdown and explicit kit
1127
1680
  // travel still finalize the visit. Pose copies are taken after the deck's step,
1128
1681
  // before real-time removes a dropped body on its next roster reconciliation.
1682
+ function houseResume(h) {
1683
+ return h.place.houseResume === true && typeof h.session?.hub?.owner === 'string' && h.session.hub.owner.length > 0;
1684
+ }
1685
+ function pinnedResume(h) {
1686
+ return h.place.resumeArrivalPose !== true && !h.place.result && Number.isInteger(h.session?.hub?.reconnectWindowMs) && h.session.hub.reconnectWindowMs > 0;
1687
+ }
1129
1688
  const RESUME_KEEP_MS = 60000;
1689
+ // v1.98: towns opt in separately; result visits keep their 60 s deadline.
1690
+ const RESUME_POSE_MS = 5 * 60000;
1130
1691
  function rememberResumePoses(h) {
1131
1692
  if (!h.resumeKept) {
1132
1693
  return;
1133
1694
  }
1695
+ // Preserve the post-authored-step fence too: a hook may synchronously alter
1696
+ // the trusted roster after the early fence ran.
1697
+ cancelChangedResumeIdentity(h);
1134
1698
  for (const [id, entry] of h.players) {
1135
1699
  const body = h.sim.players.get(id);
1136
1700
  if (!entry.arrived || !body) {
1137
1701
  continue;
1138
1702
  }
1703
+ const previous = h.resumeKept.get(id);
1704
+ // v1.145: a resumePose place holds private state on this deadline too.
1705
+ if ((h.place.resumeVisibility === true || h.place.resumePose === true) && previous) {
1706
+ const rosterPresent = h.session?.players.some((player) => player.playerId === id) === true;
1707
+ // Real-time may retain the old simulation body after its authenticated
1708
+ // roster row disappears. prepareResume has already started the bounded
1709
+ // absence: do not turn that stale body into a fresh sighting, erase its
1710
+ // trusted identity, or move the deadline on each server step.
1711
+ if (!rosterPresent && previous.awayAt !== undefined) {
1712
+ continue;
1713
+ }
1714
+ }
1139
1715
  h.resumeKept.set(id, {
1140
1716
  body,
1141
1717
  at: { ...body.at },
1142
1718
  facing: body.facing,
1143
1719
  seenAt: Date.now(),
1144
- ...(h.resumeKept.get(id)?.pendingClientHello ? { pendingClientHello: h.resumeKept.get(id).pendingClientHello } : {}),
1720
+ // Private visibility retention requires the same authenticated roster
1721
+ // identity on return; playerId alone is only a transport handle.
1722
+ // v1.145: a body real-time still holds after its roster row went keeps
1723
+ // the account it was retained for (Vis/Companion heldAway).
1724
+ identityUserId: h.session?.players.some((player) => player.playerId === id) ? userIdOf(h, id) : previous?.identityUserId ?? null,
1725
+ ...(previous?.pendingClientHello ? { pendingClientHello: previous.pendingClientHello } : {}),
1726
+ ...(previous?.visibilityResumePending ? { visibilityResumePending: true } : {}),
1145
1727
  });
1146
1728
  }
1147
1729
  }
1148
1730
 
1731
+ // A roster identity can change after hello queued a retained preparation and
1732
+ // before the next step. Fence that preparation before the early resume hook;
1733
+ // rememberResumePoses stays after authored step for every marker-absent place.
1734
+ function cancelChangedResumeIdentity(h) {
1735
+ if (h.place.resumePose === true && h.place.resumeVisibility !== true) {
1736
+ clearChangedHeldIdentity(h);
1737
+ return;
1738
+ }
1739
+ if (h.place.resumeVisibility !== true || !h.resumeKept) {
1740
+ return;
1741
+ }
1742
+ for (const [id, entry] of h.players) {
1743
+ const previous = h.resumeKept.get(id);
1744
+ if (!previous || !entry.arrived || !h.sim.players.has(id) ||
1745
+ !h.session?.players.some((player) => player.playerId === id)) {
1746
+ continue;
1747
+ }
1748
+ if (typeof previous.identityUserId === 'string' &&
1749
+ previous.identityUserId !== userIdOf(h, id)) {
1750
+ Vis.clearRetained(h, id);
1751
+ delete previous.visibilityResumePending;
1752
+ delete previous.pendingClientHello;
1753
+ h.resumePending?.delete(id);
1754
+ }
1755
+ }
1756
+ }
1757
+
1758
+ // v1.145: what a resumePose place held for one account never reaches
1759
+ // another named by the same player id, before rememberResumePoses records it.
1760
+ function clearChangedHeldIdentity(h) {
1761
+ for (const [id, previous] of h.resumeKept ?? []) {
1762
+ if (typeof previous.identityUserId !== 'string' ||
1763
+ !h.session?.players.some((player) => player.playerId === id) ||
1764
+ previous.identityUserId === userIdOf(h, id)) {
1765
+ continue;
1766
+ }
1767
+ Vis.clearRetained(h, id);
1768
+ if (h.place.companion === true) {
1769
+ Companion.clearRetained(h, id);
1770
+ }
1771
+ previous.identityUserId = userIdOf(h, id);
1772
+ }
1773
+ }
1774
+
1775
+ function rememberAnonymousEntry(h, playerId, entry = h.players.get(playerId)) {
1776
+ if (!h.anonymousEntry || entry?.anonymous !== true || !entry.identityUserId) {
1777
+ return;
1778
+ }
1779
+ const body = h.sim?.players.get(playerId);
1780
+ const kept = h.resumeKept?.get(playerId);
1781
+ const pose = body
1782
+ ? { ...body.at, facing: body.facing }
1783
+ : kept
1784
+ ? { ...kept.at, facing: kept.facing }
1785
+ : null;
1786
+ h.anonymousEntry.remember(
1787
+ { playerId, userId: entry.identityUserId, isAnonymous: true },
1788
+ pose,
1789
+ entry.avatar,
1790
+ entry.color,
1791
+ Date.now(),
1792
+ );
1793
+ }
1794
+
1795
+ function rememberAnonymousEntries(h) {
1796
+ if (!h.anonymousEntry) {return;}
1797
+ for (const [playerId, entry] of h.players) {
1798
+ rememberAnonymousEntry(h, playerId, entry);
1799
+ }
1800
+ }
1801
+
1149
1802
  function prepareResume(h, playerId, greet = true) {
1150
1803
  const kept = h.resumeKept?.get(playerId);
1151
1804
  if (!kept) {
@@ -1155,19 +1808,55 @@ function prepareResume(h, playerId, greet = true) {
1155
1808
  const present = body && h.session?.players.some((p) => p.playerId === playerId);
1156
1809
  const returning = present && (kept.awayAt !== undefined || body !== kept.body);
1157
1810
  if (!present) {
1811
+ if (kept.awayAt === undefined && h.poseStore && !h.resumeDeparting.has(playerId)) {
1812
+ void h.poseStore.end(h.players.get(playerId)?.userId, kept, Date.now(), playerId);
1813
+ }
1158
1814
  kept.awayAt ??= Date.now();
1159
1815
  }
1160
1816
  // A replacement body can arrive before an absent tick was observed. In that
1161
1817
  // case the last tick that saw the old body bounds its reconnect window.
1162
1818
  const since = kept.awayAt ?? kept.seenAt;
1163
- if ((!present || returning) && (h.resumeDeparting.has(playerId) || Date.now() - since >= RESUME_KEEP_MS)) {
1819
+ if ((!present || returning) && (h.resumeDeparting.has(playerId) || (pinnedResume(h) ? Date.now() - since > h.session.hub.reconnectWindowMs : Date.now() - since >= (houseResume(h) ? RESUME_KEEP_MS : h.place.resumePose === true ? RESUME_POSE_MS : RESUME_KEEP_MS)))) {
1164
1820
  forget(h, playerId);
1165
1821
  return;
1166
1822
  }
1167
1823
  if (!returning) {
1168
1824
  return;
1169
1825
  }
1170
- moveBody(h, playerId, kept.at, kept.facing);
1826
+ if (h.place.resumeVisibility === true) {
1827
+ if (typeof kept.identityUserId === 'string' && kept.identityUserId === userIdOf(h, playerId)) {
1828
+ kept.visibilityResumePending = true;
1829
+ } else if (typeof kept.identityUserId !== 'string') {
1830
+ const entry = h.players.get(playerId);
1831
+ if (!greet) {
1832
+ if (!endRetainedResume(h, playerId, entry)) {
1833
+ return;
1834
+ }
1835
+ return h.players.has(playerId) ? 'handled' : 'fresh';
1836
+ }
1837
+ return restartRetainedAsFresh(h, { playerId }, entry, {
1838
+ k: 'hub-hello',
1839
+ avatar: entry?.clientAvatar,
1840
+ color: entry?.clientColor,
1841
+ party: 1,
1842
+ }, true);
1843
+ } else {
1844
+ // Never let a retained transport id carry one account's private actor
1845
+ // ids into a missing, anonymous, or changed authenticated identity.
1846
+ delete kept.visibilityResumePending;
1847
+ // hello immediately follows every returning path and clears the cache
1848
+ // after its ordinary stale-channel bookkeeping, exactly once.
1849
+ }
1850
+ }
1851
+ // A house guest returns at its arrival; the owner's retained pose stays theirs.
1852
+ // The owner binding comes from Ghost, never the client's hello.
1853
+ if (houseResume(h) && h.session?.hub?.owner &&
1854
+ h.players.get(playerId)?.userId !== h.session.hub.owner) {
1855
+ placeGroup(h, [playerId]);
1856
+ } else {
1857
+ moveBody(h, playerId, kept.at, kept.facing);
1858
+ }
1859
+ if (h.poseStore) { void h.poseStore.take(h.players.get(playerId)?.userId, playerId); }
1171
1860
  settle(h, playerId);
1172
1861
  kept.body = body;
1173
1862
  delete kept.awayAt;
@@ -1301,45 +1990,154 @@ function notifyVisibility(h, only = null) {
1301
1990
  }
1302
1991
  }
1303
1992
 
1304
- // Dispatch after this step's private channels, once per id per step. A hook
1305
- // may queue another hello; that belongs to the next step, not this drain.
1306
- function notifyResumes(h) {
1993
+ // Ordinary resumes dispatch after this step's private channels. A retained
1994
+ // visibility resume gets one synchronous prefix before authored stepping, so
1995
+ // its hook can cancel visit-local work before that work matures.
1996
+ function notifyResumes(h, visibilityFirst = false, deferred = new Set()) {
1307
1997
  if (!h.resumePending?.size) {
1308
- return;
1309
- }
1310
- const pending = [...h.resumePending];
1311
- h.resumePending.clear();
1312
- for (const [playerId, entry] of pending) {
1998
+ return deferred;
1999
+ }
2000
+ for (const [playerId, entry] of [...h.resumePending]) {
2001
+ // A resume hook may synchronously queue a new hello for itself or another
2002
+ // player. As before the split visibility drain, that new entry belongs to
2003
+ // the next step. It must not replace and then be deleted as the old
2004
+ // snapshot continues.
2005
+ if (deferred.has(entry) || h.resumePending.get(playerId) !== entry) {
2006
+ continue;
2007
+ }
2008
+ const kept = h.resumeKept?.get(playerId);
2009
+ const preparesVisibility = kept?.visibilityResumePending === true;
2010
+ if (preparesVisibility !== visibilityFirst) {
2011
+ continue;
2012
+ }
2013
+ if (entry.progressReading) {
2014
+ if (preparesVisibility) { endRetainedResume(h, playerId, entry); }
2015
+ continue;
2016
+ }
2017
+ h.resumePending.delete(playerId);
1313
2018
  if (h.players.get(playerId) !== entry || !entry.arrived || !h.sim.players.has(playerId) || !h.session?.players.some((p) => p.playerId === playerId)) {
2019
+ if (preparesVisibility && kept) { delete kept.visibilityResumePending; }
1314
2020
  continue;
1315
2021
  }
2022
+ const queuedBeforeHook = new Map(h.resumePending);
1316
2023
  try {
2024
+ if (h.place.analytics === true) { Analytics.track(h, playerId, 'reconnect'); }
1317
2025
  const result = h.hooks.resume(h.ctx, { playerId });
1318
2026
  if (result && typeof result.catch === 'function') {
1319
2027
  result.catch(() => console.warn('[hub] resume hook failed'));
1320
2028
  }
2029
+ if (entry.progressRefreshPending) {
2030
+ delete entry.progressRefreshPending;
2031
+ // A reentrant hello or explicit read owns its own preparation/request.
2032
+ if (h.players.get(playerId) === entry && !h.resumePending.has(playerId) &&
2033
+ !entry.progressState.locks.size && !accountProgressBlocked(h, entry.userId)) {
2034
+ void refreshProgress(h, playerId);
2035
+ }
2036
+ }
1321
2037
  } catch {
1322
2038
  console.warn('[hub] resume hook failed');
2039
+ if (preparesVisibility) { endRetainedResume(h, playerId, entry); }
2040
+ } finally {
2041
+ for (const [queuedId, queuedEntry] of h.resumePending) {
2042
+ if (queuedBeforeHook.get(queuedId) !== queuedEntry) {
2043
+ deferred.add(queuedEntry);
2044
+ }
2045
+ }
2046
+ // A hook may have queued a fresh same-player preparation. Preserve its
2047
+ // marker so the final preparation sweep recognizes and ends that entry.
2048
+ if (preparesVisibility && kept && !h.resumePending?.has(playerId)) {
2049
+ delete kept.visibilityResumePending;
2050
+ }
2051
+ }
2052
+ }
2053
+ if (visibilityFirst) {
2054
+ // A synchronous resume prefix may queue a new retained hello. It cannot be
2055
+ // prepared in this drain, and the place must never wait for one player's
2056
+ // preparation, so end that exact new entry through ordinary leave cleanup.
2057
+ for (const [playerId, entry] of [...h.resumePending]) {
2058
+ if (h.resumeKept?.get(playerId)?.visibilityResumePending === true) {
2059
+ endRetainedResume(h, playerId, entry);
2060
+ }
1323
2061
  }
1324
2062
  }
2063
+ return deferred;
2064
+ }
2065
+
2066
+ function endRetainedResume(h, playerId, entry) {
2067
+ if (h.players.get(playerId) !== entry) {
2068
+ if (h.resumePending?.get(playerId) === entry) { h.resumePending.delete(playerId); }
2069
+ return false;
2070
+ }
2071
+ try {
2072
+ end(h, playerId, 'end');
2073
+ } catch {
2074
+ console.warn('[hub] retained resume end failed');
2075
+ } finally {
2076
+ // A synchronous transport callback must not let cleanup finalize a newer
2077
+ // visit that replaced this exact retained entry.
2078
+ if (h.players.get(playerId) === entry) {
2079
+ forget(h, playerId);
2080
+ } else if (h.resumePending?.get(playerId) === entry) {
2081
+ h.resumePending.delete(playerId);
2082
+ }
2083
+ }
2084
+ return true;
2085
+ }
2086
+
2087
+ function restartRetainedAsFresh(h, player, entry, data, synthetic) {
2088
+ if (!endRetainedResume(h, player.playerId, entry) || h.players.has(player.playerId)) {
2089
+ return;
2090
+ }
2091
+ const fresh = { ...data };
2092
+ delete fresh.resume;
2093
+ hello(h, player, fresh, synthetic);
2094
+ const body = h.sim?.players.get(player.playerId);
2095
+ if (synthetic && body && h.players.get(player.playerId)?.hello) {
2096
+ // The client's ordinary resume hello still follows this silent fresh one.
2097
+ // Seed only its body marker until the first authored step records the new
2098
+ // pose, so that companion cannot be mistaken for another fresh signal.
2099
+ h.resumeKept.set(player.playerId, {
2100
+ body,
2101
+ at: { ...body.at },
2102
+ facing: body.facing,
2103
+ seenAt: Date.now(),
2104
+ identityUserId: userIdOf(h, player.playerId),
2105
+ pendingClientHello: body,
2106
+ });
2107
+ }
1325
2108
  }
1326
2109
 
1327
2110
  function forget(h, playerId) {
2111
+ h.padOccupancy?.selected.delete(playerId);
2112
+ const entry = h.players.get(playerId);
2113
+ // resumeKept may be the only remaining pose after the body disappears.
2114
+ rememberAnonymousEntry(h, playerId, entry);
2115
+ if (entry?.signUp) {finishSignUp(h, playerId, entry.signUp, true);}
2116
+ h.inviteAt?.delete(playerId);
1328
2117
  h.resumePending?.delete(playerId);
1329
2118
  h.resumeKept?.delete(playerId);
2119
+ const poseDeparting = h.arrivalPoses && h.resumeDeparting?.has(playerId);
1330
2120
  h.resumeDeparting?.delete(playerId);
1331
- const entry = h.players.get(playerId);
2121
+ if (entry?.arrived && h.place.analytics === true) {Analytics.leave(h, playerId);}
1332
2122
  if (entry?.arrived) {
1333
2123
  // A place's hook that throws still lets the player go, once.
1334
2124
  try {
1335
- h.hooks.leave?.(h.ctx, playerId, { userId: entry.userId ?? null, username: entry.username ?? 'player' });
2125
+ h.hooks.leave?.(h.ctx, playerId, {
2126
+ userId: entry.userId ?? null,
2127
+ username: entry.username ?? 'player',
2128
+ ...(h.place.anonymousEntry === true ? { identityUserId: entry.identityUserId ?? null } : {}),
2129
+ });
1336
2130
  } catch (err) {
1337
2131
  console.warn(`[hub] leave hook failed: ${err?.message ?? err}`);
1338
2132
  }
1339
2133
  }
2134
+ DoorAnalytics.finish(h, playerId, 3);
2135
+ if (h.arrivalPoses) {
2136
+ h.arrivalPoses.leave(playerId, entry?.userId, entry?.arrived === true && !entry.ended && !poseDeparting);
2137
+ }
1340
2138
  // After the leave hook, which may have reported the visit's result.
1341
2139
  if (entry?.hello) {
1342
- const kept = { clientAvatar: entry.clientAvatar, clientColor: entry.clientColor, at: h.sim.timeMs };
2140
+ const kept = { clientAvatar: entry.clientAvatar, clientColor: entry.clientColor, at: h.sim.timeMs, userId: entry.userId };
1343
2141
  // v1.72: a game that resumes keeps what its re-arrival must not lose (the
1344
2142
  // invariants at `hello`): the result (I1), the deadline (I2), the end
1345
2143
  // (I3) and the door (I4).
@@ -1365,6 +2163,9 @@ function forget(h, playerId) {
1365
2163
  h.capAt.delete(playerId);
1366
2164
  h.playerCells.delete(playerId);
1367
2165
  h.players.delete(playerId);
2166
+ if (entry?.progressState) { entry.progressState.readLifetime = null; }
2167
+ h.progressStates.delete(playerId);
2168
+ syncProgressUser(h, entry?.userId);
1368
2169
  h.held.delete(playerId);
1369
2170
  h.hudMe.delete(playerId);
1370
2171
  h.sentHudMe.delete(playerId);
@@ -1384,6 +2185,7 @@ function forget(h, playerId) {
1384
2185
  h.unstuckAskAt?.delete(playerId);
1385
2186
  h.settling.delete(playerId);
1386
2187
  Grab.forget(h, playerId);
2188
+ if (h.manifest.act === true) {Act.forget(h, playerId);}
1387
2189
  Idle.forget(h, playerId);
1388
2190
  Decor.forget(h, playerId);
1389
2191
  if (h.place.actions === true) {
@@ -1415,10 +2217,15 @@ function forget(h, playerId) {
1415
2217
  const SHUTDOWN_DRAIN_MS = 1500;
1416
2218
 
1417
2219
  async function shutdown(h) {
2220
+ h.arrivalPoses?.shutdown();
1418
2221
  if (!h.sim) {
1419
2222
  return;
1420
2223
  }
1421
2224
  for (const playerId of [...h.players.keys()]) {
2225
+ const kept = h.resumeKept?.get(playerId);
2226
+ if (h.poseStore && kept && kept.awayAt === undefined && !h.resumeDeparting?.has(playerId)) {
2227
+ void h.poseStore.end(h.players.get(playerId)?.userId, kept, Date.now(), playerId);
2228
+ }
1422
2229
  forget(h, playerId);
1423
2230
  }
1424
2231
  if (Wear.tryOnUsed(h)) {
@@ -1429,6 +2236,7 @@ async function shutdown(h) {
1429
2236
  Promise.resolve()
1430
2237
  .then(async () => {
1431
2238
  await h.hooks.shutdown?.(h.ctx);
2239
+ await h.poseStore?.drain();
1432
2240
  await Promise.all([...(h.friendBestHelpers?.values() ?? [])].map((helper) => helper.drain()));
1433
2241
  })
1434
2242
  .catch((err) => console.warn(`[hub] shutdown hook failed: ${err?.message ?? err}`)),
@@ -1439,6 +2247,37 @@ async function shutdown(h) {
1439
2247
  clearTimeout(timer);
1440
2248
  }
1441
2249
 
2250
+ // Signup carry invariant: ONE terminal function applies allowed guest state
2251
+ // exactly once, after BOTH placement and account read settle (success, empty or
2252
+ // failure). No other read consumer applies appearance. Later explicit choices
2253
+ // win by revision; a trusted identity switch cancels. Every terminal path clears
2254
+ // pending state in finally, including an authored arrival hook that throws.
2255
+ // The authored arrival carries first-visit/layer state, never wallets or items.
2256
+ function finishSignUp(h, playerId, signUp, cancel = false) {
2257
+ if (!signUp || signUp.finished || (!cancel && (!signUp.arrivalSettled || !signUp.readSettled))) {return;}
2258
+ signUp.finished = true;
2259
+ const entry = h.players.get(playerId);
2260
+ try {
2261
+ if (cancel || entry?.signUp !== signUp || identityUserIdOf(h, playerId) !== signUp.identityUserId || userIdOf(h, playerId) !== signUp.identityUserId) {return;}
2262
+ const { facing, ...at } = signUp.chosenPose ?? signUp.carry.pose;
2263
+ moveBody(h, playerId, at, facing);
2264
+ if (entry.avatarRev === signUp.avatarRev) {entry.avatar = signUp.carry.avatar;}
2265
+ if (entry.colorRev === signUp.colorRev && entry.avatarRev === signUp.avatarRev) {entry.color = signUp.carry.color;}
2266
+ h.held.delete(playerId);
2267
+ h.hooks.arrive?.(h.ctx, [signUp.member]);
2268
+ settle(h, playerId);
2269
+ const body = h.sim.players.get(playerId);
2270
+ if (body) {h.session?.send(playerId, { k: 'hub-arrived', facing: body.facing });}
2271
+ } catch (err) {
2272
+ console.warn(`[hub] signup arrival failed: ${err?.message ?? err}`);
2273
+ } finally {
2274
+ if (entry?.signUp === signUp) {delete entry.signUp;}
2275
+ if (h.held.get(playerId)?.waiting) {h.held.delete(playerId);}
2276
+ signUp.carry = null;
2277
+ signUp.member = null;
2278
+ }
2279
+ }
2280
+
1442
2281
  // Players with a body who said hello and have not arrived, placed as groups
1443
2282
  // at the arrival (contract §5). A group is everyone who said hello inside one
1444
2283
  // window; it is placed when it has as many as its members said were coming,
@@ -1458,7 +2297,8 @@ function arrivals(h) {
1458
2297
  // A group also waits, inside the same window, for ghost's read of what its
1459
2298
  // players bring back.
1460
2299
  const reading = waiting.some(([, e]) => e.read !== 'done');
1461
- if ((waiting.length < expected || reading) && Date.now() - first < GROUP_WAIT_MS) {
2300
+ const progressReading = waiting.some(([, e]) => e.progressReading || e.poseReading);
2301
+ if (progressReading || ((waiting.length < expected || reading) && Date.now() - first < GROUP_WAIT_MS)) {
1462
2302
  // Whoever is in waits where they are, held, until the group is placed.
1463
2303
  for (const [playerId] of waiting) {
1464
2304
  if (!h.held.has(playerId)) {
@@ -1482,9 +2322,12 @@ function arrivals(h) {
1482
2322
  playerId,
1483
2323
  username: usernameOf(h, playerId),
1484
2324
  userId: entry.userId,
2325
+ ...(h.place.anonymousEntry === true ? { identityUserId: entry.identityUserId ?? null } : {}),
2326
+ ...(entry.signUp ? { signedUpFrom: entry.signUp.carry.playerId } : {}),
1485
2327
  from: entry.from,
1486
2328
  fromDeckId: entry.fromDeckId,
1487
2329
  near: entry.near ?? null,
2330
+ ...(h.place.invite === true ? { invited: entry.invited === true } : {}),
1488
2331
  carry: entry.carry,
1489
2332
  // How many went through the door together, by the client's word (the
1490
2333
  // way back carries what the way out was sent with): 1 for anyone else.
@@ -1499,10 +2342,46 @@ function arrivals(h) {
1499
2342
  h.devOwnerChosen = true;
1500
2343
  h.devOwner = group[0]?.userId ?? null;
1501
2344
  }
1502
- h.hooks.arrive?.(h.ctx, group);
2345
+ if (h.place.analytics === true) {Analytics.arrive(h, group);}
2346
+ DoorAnalytics.arrive(h, group);
2347
+ const ordinary = group.filter(({ playerId }) => !h.players.get(playerId)?.signUp);
2348
+ for (const member of group) {
2349
+ const signUp = h.players.get(member.playerId)?.signUp;
2350
+ if (!signUp) {continue;}
2351
+ signUp.member = member;
2352
+ signUp.arrivalSettled = true;
2353
+ const body = h.sim.players.get(member.playerId);
2354
+ h.held.set(member.playerId, { at: { ...body.at }, facing: body.facing, waiting: true });
2355
+ finishSignUp(h, member.playerId, signUp);
2356
+ }
2357
+ // Settle signup placement before an unrelated authored arrival can throw.
2358
+ if (ordinary.length) {h.hooks.arrive?.(h.ctx, ordinary);}
2359
+ if (h.arrivalPoses) {
2360
+ for (const { playerId } of ordinary) {
2361
+ const entry = h.players.get(playerId);
2362
+ const pose = entry?.arrivalPose;
2363
+ if (entry) {delete entry.arrivalPose;}
2364
+ if (pose && pose.userId === arrivalPoseUserId(h, playerId) && !entry?.ended && !entry?.near && !h.resumeDeparting.has(playerId)) {
2365
+ moveBody(h, playerId, pose.at, pose.facing);
2366
+ settle(h, playerId);
2367
+ }
2368
+ }
2369
+ }
2370
+ // A new socket needs the deck's arrival UI (the house's fixed shot included),
2371
+ // then its stored server pose replaces all normal door/spawn placement.
2372
+ for (const { playerId } of group) {
2373
+ const entry = h.players.get(playerId);
2374
+ if (houseResume(h) && h.session?.hub?.owner && entry?.userId !== h.session.hub.owner) {delete entry.coldPose;}
2375
+ if (entry?.coldPose && entry.invited && entry.near) {delete entry.coldPose;}
2376
+ if (entry?.coldPose) {
2377
+ moveBody(h, playerId, entry.coldPose.at, entry.coldPose.facing);
2378
+ settle(h, playerId);
2379
+ delete entry.coldPose;
2380
+ }
2381
+ }
1503
2382
  for (const { playerId } of group) {
1504
2383
  const body = h.sim.players.get(playerId);
1505
- if (body) {
2384
+ if (body && !h.players.get(playerId)?.signUp && !group.find((g) => g.playerId === playerId)?.signedUpFrom) {
1506
2385
  // v1.40: kept where the arrival put them, like a jump. A player waits
1507
2386
  // for their group at the scene's spawn, where their client agrees they
1508
2387
  // are; placed, that client's reports still on their way name the spawn
@@ -1601,6 +2480,12 @@ function placeBeside(h, playerId, otherId, used = new Map()) {
1601
2480
  if (!other?.at || blockedPairs(h)?.get(playerId)?.has(otherId)) {
1602
2481
  return false;
1603
2482
  }
2483
+ // Authored-floor places need the actual standing envelope: the legacy
2484
+ // 1.8m envelope intersects a floor beneath a 1.4m player. Ground-backed
2485
+ // towns/games and invite-only decks keep their original placement bytes.
2486
+ const size = h.bringFriend === true && h.noGround === true
2487
+ ? bodySize(h) : { radius: BODY_RADIUS_M, halfHeight: BODY_HALF_M };
2488
+ if (!size) {return false;}
1604
2489
  const f = other.facing ?? 0;
1605
2490
  // Facing f looks along (sin f, cos f): right, left, behind, ahead, then
1606
2491
  // the same a step further out.
@@ -1618,7 +2503,7 @@ function placeBeside(h, playerId, otherId, used = new Map()) {
1618
2503
  for (const step of [1, 1.5, 2, 2.5, 3, 3.5]) {
1619
2504
  const spot = dirs
1620
2505
  .map(([dx, dz]) => ({ x: other.at.x + dx * NEAR_STEP_M * step, y: other.at.y, z: other.at.z + dz * NEAR_STEP_M * step }))
1621
- .find((at) => !taken.some((t) => Math.hypot(t.x - at.x, t.z - at.z) < 2 * BODY_RADIUS_M) && spotClear(h, at) && padAt(h, at, BODY_RADIUS_M) === null);
2506
+ .find((at) => !taken.some((t) => Math.hypot(t.x - at.x, t.z - at.z) < 2 * size.radius) && spotClear(h, at, size) && padAt(h, at, size.radius) === null);
1622
2507
  if (spot) {
1623
2508
  taken.push(spot);
1624
2509
  used.set(otherId, taken);
@@ -1644,7 +2529,7 @@ function padAt(h, at, margin) {
1644
2529
 
1645
2530
  // Whether a standing body fits at `at`: no solid scene actor overlaps it, and
1646
2531
  // on a scene with no ground (`fallY`) a solid's top is under its feet.
1647
- function spotClear(h, at) {
2532
+ function spotClear(h, at, { radius, halfHeight }) {
1648
2533
  let supported = h.noGround !== true;
1649
2534
  for (const actor of h.actors) {
1650
2535
  const c = actor.components;
@@ -1657,11 +2542,11 @@ function spotClear(h, at) {
1657
2542
  const half = shape.kind === 'sphere' ? (shape.radius ?? 0.5) : (shape.height ?? 1) / 2;
1658
2543
  const top = (t.y ?? 0) + half;
1659
2544
  const bottom = (t.y ?? 0) - half;
1660
- const inside = footprintHas(shape, t, at, BODY_RADIUS_M);
1661
- if (inside && top > at.y - BODY_HALF_M + 0.05 && bottom < at.y + BODY_HALF_M) {
2545
+ const inside = footprintHas(shape, t, at, radius);
2546
+ if (inside && top > at.y - halfHeight + 0.05 && bottom < at.y + halfHeight) {
1662
2547
  return false;
1663
2548
  }
1664
- if (!supported && footprintHas(shape, t, at, 0) && Math.abs(top - (at.y - BODY_HALF_M)) < 0.6) {
2549
+ if (!supported && footprintHas(shape, t, at, 0) && Math.abs(top - (at.y - halfHeight)) < 0.6) {
1665
2550
  supported = true;
1666
2551
  }
1667
2552
  }
@@ -1696,6 +2581,8 @@ function moveBody(h, playerId, at, facing) {
1696
2581
  if (!body || !at || ![at.x, at.y, at.z].every(Number.isFinite)) {
1697
2582
  return;
1698
2583
  }
2584
+ // v1.141: a placement elsewhere is a reset of the player's observation.
2585
+ Observe.placed(h, playerId, at);
1699
2586
  body.at = { x: at.x, y: at.y, z: at.z };
1700
2587
  if (facing !== undefined && Number.isFinite(facing)) {
1701
2588
  body.facing = facing;
@@ -1712,12 +2599,24 @@ function moveBody(h, playerId, at, facing) {
1712
2599
  // counted them. This is not a hold (contract §8): the player is not in the
1713
2600
  // `held` list, keeps what they carry and may jump again at once; the body is
1714
2601
  // only put back each tick it drifts, until the client has caught up.
2602
+ //
2603
+ // Caught up is a move report made since the placement that stands within
2604
+ // SETTLE_NEAR_M of the spot, not a fixed time: a client eases toward a
2605
+ // placement under 4 m a quarter of the way each frame it hears of it, and a
2606
+ // slow phone that had 0.6 s heard of it two or three times. Its next report,
2607
+ // still short of a pad 3 m from where it stood, was a legal step, and the
2608
+ // pad's edge was where the player stayed (the Prism Post pad beside the
2609
+ // square's spawn). SETTLE_MAX_MS bounds a client that never reports; a body
2610
+ // with no report clock (`movedAt`) is kept for SETTLE_MS, as it always was.
1715
2611
  const SETTLE_MS = 600;
2612
+ const SETTLE_MAX_MS = 4000;
2613
+ const SETTLE_NEAR_M = 0.25;
1716
2614
 
1717
2615
  function settle(h, playerId) {
1718
2616
  const body = h.sim?.players.get(playerId);
1719
2617
  if (body) {
1720
- h.settling.set(playerId, { at: { ...body.at }, facing: body.facing, until: Date.now() + SETTLE_MS });
2618
+ const reports = Number.isFinite(body.movedAt);
2619
+ h.settling.set(playerId, { at: { ...body.at }, facing: body.facing, until: Date.now() + (reports ? SETTLE_MAX_MS : SETTLE_MS), movedAt: body.movedAt });
1721
2620
  }
1722
2621
  }
1723
2622
 
@@ -1730,8 +2629,18 @@ function enforceSettle(h) {
1730
2629
  h.settling.delete(playerId);
1731
2630
  continue;
1732
2631
  }
1733
- if (Math.hypot(body.at.x - spot.at.x, body.at.z - spot.at.z) > HOLD_SLACK) {
2632
+ const off = Math.hypot(body.at.x - spot.at.x, body.at.z - spot.at.z);
2633
+ // The client has reported from the spot since it was last put back, and
2634
+ // the report was taken (a refused one leaves the body where it was put):
2635
+ // it stands where it was put.
2636
+ if (body.movedAt !== spot.movedAt && body.clamped === false && off <= SETTLE_NEAR_M) {
2637
+ h.settling.delete(playerId);
2638
+ continue;
2639
+ }
2640
+ if (off > HOLD_SLACK) {
1734
2641
  moveBody(h, playerId, spot.at, spot.facing);
2642
+ // Where the body is now is the server's word, not the client's.
2643
+ spot.movedAt = body.movedAt;
1735
2644
  }
1736
2645
  }
1737
2646
  }
@@ -1804,6 +2713,7 @@ function report(h, playerId, value) {
1804
2713
  return false;
1805
2714
  }
1806
2715
  entry.result = result;
2716
+ if (h.place.analyticsRounds !== 'authored') {DoorAnalytics.finish(h, playerId);}
1807
2717
  const shown = {
1808
2718
  title: h.place.title,
1809
2719
  ...result,
@@ -1828,6 +2738,7 @@ function report(h, playerId, value) {
1828
2738
  }
1829
2739
 
1830
2740
  function end(h, playerId, why) {
2741
+ if (h.place.analyticsRounds !== 'authored') {DoorAnalytics.finish(h, playerId);}
1831
2742
  const entry = h.players.get(playerId);
1832
2743
  if (entry) {
1833
2744
  entry.ended = true;
@@ -1870,7 +2781,8 @@ function doorList(h) {
1870
2781
  const out = [];
1871
2782
  for (const door of listedDoors(h)) {
1872
2783
  const event = h.boards.get(door.id)?.event;
1873
- const row = { id: door.id, title: event ? `Event · ${door.title}`.slice(0, 48) : door.title };
2784
+ const title = typeof door.props.listTitle === 'string' && door.props.listTitle.trim() ? door.props.listTitle.trim().slice(0, 60) : door.title;
2785
+ const row = { id: door.id, title: event ? `Event · ${title}`.slice(0, 48) : title };
1874
2786
  // What a player picking a door wants to know: today's featured door (it
1875
2787
  // is listed first), one that takes a single player, how many it needs.
1876
2788
  if (h.boards.get(door.id)?.featured === true) {
@@ -1915,6 +2827,33 @@ function doorJump(h, player, data) {
1915
2827
  h.session?.send(player.playerId, { k: 'hub-jumped', facing });
1916
2828
  }
1917
2829
 
2830
+ // Join on a friend at home in their House (§5): through that door into the
2831
+ // owner's House. It goes out by `sendGo` like any door's trip, so the visit
2832
+ // here ends (no retained pose for Back to restore). The owner is ghost's to
2833
+ // admit. Without a platform hub (the dev serve) or a well-formed owner it is
2834
+ // the jump to the door, as before.
2835
+ function houseVisit(h, player, data) {
2836
+ const playerId = player?.playerId;
2837
+ const owner = typeof data?.owner === 'string' && USER_ID.test(data.owner) ? data.owner : null;
2838
+ if (!owner || !platformHub(h)) {
2839
+ doorJump(h, player, data);
2840
+ return;
2841
+ }
2842
+ const door = h.sim ? jumpDoors(h).find((d) => d.id === data?.door) : null;
2843
+ const now = Date.now();
2844
+ // A sitter gets up first, as for a door jump: a seat is a hold.
2845
+ if (door && now - (h.jumpAt.get(playerId) ?? 0) >= JUMP_EVERY_MS) {
2846
+ Idle.stand(h, playerId);
2847
+ }
2848
+ if (!door || h.held.has(playerId) || now - (h.jumpAt.get(playerId) ?? 0) < JUMP_EVERY_MS ||
2849
+ isShut(h, playerId, door.id) || !membersOf(h, [playerId]).size) {
2850
+ return;
2851
+ }
2852
+ h.jumpAt.set(playerId, now);
2853
+ tellWent(h, [playerId], door.id);
2854
+ sendGo(h, playerId, { k: 'hub-go', door: door.id, key: null, place: null, scene: null, title: door.title, party: 1, owner });
2855
+ }
2856
+
1918
2857
  // "Stuck?" (v1.33): whether this place puts a player back at its arrival for
1919
2858
  // the asking. A deck with `hub.stuck`, and a town only: in a game (a place
1920
2859
  // with a `result`) the way to the start is the game's to give or keep -- a
@@ -2327,6 +3266,9 @@ function sendGo(h, playerId, msg) {
2327
3266
  Shot.stopHolding(h, playerId);
2328
3267
  // An explicit kit trip ends the visit rather than retaining it for a drop.
2329
3268
  h.resumeDeparting?.add(playerId);
3269
+ if (h.manifest.act === true) {Act.forget(h, playerId); (h.actDeparting ??= new Set()).add(playerId);}
3270
+ h.arrivalPoses?.clear(playerId);
3271
+ if (h.poseStore) { void h.poseStore.clear(h.players.get(playerId)?.userId, playerId); }
2330
3272
  h.resumePending?.delete(playerId);
2331
3273
  }
2332
3274
  }
@@ -2416,9 +3358,9 @@ function isLayerDoor(h, door) {
2416
3358
  // door id, or null when nobody went.
2417
3359
  function goLayer(h, door, playerIds) {
2418
3360
  const found = doors(h).find((d) => d.id === door);
2419
- const going = [...membersOf(h, playerIds).values()];
3361
+ const going = [...travelersOf(h, playerIds).values()];
2420
3362
  if (!going.length) {
2421
- console.warn(`[hub] door ${door}: only signed-in players go through a door`);
3363
+ console.warn(`[hub] door ${door}: only players with an account go through a door`);
2422
3364
  return null;
2423
3365
  }
2424
3366
  for (const playerId of going) {
@@ -2449,9 +3391,9 @@ function goClassic(h, hub, door, playerIds) {
2449
3391
  console.warn(`[hub] no door "${door}" in this place`);
2450
3392
  return null;
2451
3393
  }
2452
- const going = hub ? [...membersOf(h, playerIds).values()] : (playerIds ?? []);
3394
+ const going = hub ? [...travelersOf(h, playerIds).values()] : (playerIds ?? []);
2453
3395
  if (!going.length) {
2454
- console.warn(`[hub] door ${door}: only signed-in players go through a door`);
3396
+ console.warn(`[hub] door ${door}: only players with an account go through a door`);
2455
3397
  return null;
2456
3398
  }
2457
3399
  for (const playerId of going) {
@@ -2471,13 +3413,25 @@ function goClassic(h, hub, door, playerIds) {
2471
3413
  return door;
2472
3414
  }
2473
3415
 
2474
- // Signed-in players' user ids, which is all ghost holds a pad by:
2475
- // userId -> playerId.
3416
+ // Signed-in players' user ids: userId -> playerId. Results, history and
3417
+ // everything else kept on an account go by these.
2476
3418
  function membersOf(h, playerIds) {
3419
+ return userIdsOf(h, playerIds, { guests: false });
3420
+ }
3421
+
3422
+ // Who may go through a door: signed-in players and the guests ghost admitted
3423
+ // to this place, by the user id ghost holds a pad by (a guest has one too).
3424
+ // Ghost decides whether a guest may play here; the kit only keeps a player
3425
+ // without a Castle account (the dev serve's) off the pads.
3426
+ function travelersOf(h, playerIds) {
3427
+ return userIdsOf(h, playerIds, { guests: true });
3428
+ }
3429
+
3430
+ function userIdsOf(h, playerIds, { guests }) {
2477
3431
  const out = new Map();
2478
3432
  for (const playerId of playerIds ?? []) {
2479
3433
  const p = h.session?.players.find((q) => q.playerId === playerId);
2480
- if (p && !p.isAnonymous && USER_ID.test(String(p.userId))) {
3434
+ if (p && (guests || !p.isAnonymous) && USER_ID.test(String(p.userId))) {
2481
3435
  out.set(String(p.userId), playerId);
2482
3436
  }
2483
3437
  }
@@ -2497,6 +3451,7 @@ function gather(h, door, playerIds) {
2497
3451
  }
2498
3452
  const on = new Set(playerIds ?? []);
2499
3453
  h.padDoors.set(door, on);
3454
+ h.padOccupancy?.reportedAt.set(door, h.sim.timeMs);
2500
3455
  for (const [playerId, entry] of h.shut) {
2501
3456
  if (entry.door === door && !on.has(playerId)) {
2502
3457
  // Stepped off: the door may be tried again.
@@ -2508,7 +3463,7 @@ function gather(h, door, playerIds) {
2508
3463
  if (!hub || Cabinets.isClassic(h, door) || Cabinets.cabinetDoorIds(h).has(door) || isLayerDoor(h, door)) {
2509
3464
  return;
2510
3465
  }
2511
- const users = membersOf(h, [...on].filter((playerId) => !isShut(h, playerId, door)));
3466
+ const users = travelersOf(h, [...on].filter((playerId) => !isShut(h, playerId, door)));
2512
3467
  const members = [...users.keys()].sort();
2513
3468
  let pad = h.pads.get(door);
2514
3469
  if (pad?.firing) {
@@ -2558,6 +3513,7 @@ function doorShut(h, player, data) {
2558
3513
  return;
2559
3514
  }
2560
3515
  h.resumeDeparting?.delete(playerId);
3516
+ h.actDeparting?.delete(playerId);
2561
3517
  unshut(h, playerId);
2562
3518
  if (h.padDoors.has(found.id) && !h.padDoors.get(found.id).has(playerId)) {
2563
3519
  // Already stepped off while the trip was failing.
@@ -2596,9 +3552,9 @@ function firePad(h, hub, door, playerIds) {
2596
3552
  console.warn(`[hub] no door "${door}" in this place`);
2597
3553
  return null;
2598
3554
  }
2599
- const members = membersOf(h, playerIds);
3555
+ const members = travelersOf(h, playerIds);
2600
3556
  if (!members.size) {
2601
- console.warn(`[hub] door ${door}: only signed-in players go through a door`);
3557
+ console.warn(`[hub] door ${door}: only players with an account go through a door`);
2602
3558
  return null;
2603
3559
  }
2604
3560
  // The pad keeps its id until ghost answers the fire, so a retried go (or a
@@ -2635,7 +3591,7 @@ function padFired(h, door, pad, users, fired) {
2635
3591
  const found = doors(h).find((d) => d.id === door);
2636
3592
  const group = Array.isArray(fired) ? fired : [];
2637
3593
  // The group is ghost's; anyone of it still here goes, on the pad now or not.
2638
- const here = membersOf(h, h.session?.players.map((p) => p.playerId));
3594
+ const here = travelersOf(h, h.session?.players.map((p) => p.playerId));
2639
3595
  tellWent(h, group.map((userId) => users.get(userId) ?? here.get(userId)).filter(Boolean), door);
2640
3596
  for (const userId of group) {
2641
3597
  const playerId = users.get(userId) ?? here.get(userId);
@@ -2672,16 +3628,27 @@ function readResults(h) {
2672
3628
  const userId = [...membersOf(h, [playerId]).keys()][0];
2673
3629
  if (!userId) {
2674
3630
  entry.read = 'done';
3631
+ if (entry.signUp) {
3632
+ entry.signUp.readSettled = true;
3633
+ finishSignUp(h, playerId, entry.signUp);
3634
+ }
3635
+ if (entry.progressState.readLifetime?.phase === 'want') {
3636
+ entry.progressState.readLifetime = null;
3637
+ }
3638
+ continue;
3639
+ }
3640
+ const state = entry.progressState;
3641
+ const lifetime = state.readLifetime ?? startReadLifetime(h, playerId, entry);
3642
+ if (lifetime.phase !== 'want') {
3643
+ entry.read = lifetime.phase;
2675
3644
  continue;
2676
3645
  }
3646
+ lifetime.phase = 'reading';
2677
3647
  entry.read = 'reading';
2678
3648
  users.set(userId, {
2679
3649
  playerId,
2680
- avatarRev: entry.avatarRev,
2681
- colorRev: entry.colorRev,
2682
- wearRev: h.wearRev.get(playerId) ?? 0,
2683
- earnedRev: h.earnedRev.get(playerId) ?? 0,
2684
- startedAt: Date.now(),
3650
+ state,
3651
+ lifetime,
2685
3652
  });
2686
3653
  }
2687
3654
  if (users.size) {
@@ -2694,10 +3661,17 @@ function readResults(h) {
2694
3661
  })
2695
3662
  .catch((err) => refused(h, 'results', err))
2696
3663
  .finally(() => {
2697
- for (const { playerId } of users.values()) {
2698
- const entry = h.players.get(playerId);
2699
- if (entry?.read === 'reading') {
2700
- entry.read = 'done';
3664
+ for (const { playerId, state, lifetime } of users.values()) {
3665
+ if (h.progressStates.get(playerId) === state && state.readLifetime === lifetime) {
3666
+ state.readLifetime = null;
3667
+ const entry = h.players.get(playerId);
3668
+ if (entry?.progressState === state) {
3669
+ entry.read = 'done';
3670
+ if (entry.signUp) {
3671
+ entry.signUp.readSettled = true;
3672
+ finishSignUp(h, playerId, entry.signUp);
3673
+ }
3674
+ }
2701
3675
  }
2702
3676
  }
2703
3677
  });
@@ -2723,7 +3697,10 @@ function readResults(h) {
2723
3697
  if (batches.length) {
2724
3698
  h.boardsAt = now;
2725
3699
  h.boardsReading = true;
2726
- readBoards(h, hub, batches)
3700
+ const read = h.manifest.weeklyCup === true
3701
+ ? readWeeklyCup(h, hub, batches)
3702
+ : readBoards(h, hub, batches);
3703
+ read
2727
3704
  .catch((err) => refused(h, 'boards', err))
2728
3705
  .finally(() => {
2729
3706
  h.boardsReading = false;
@@ -2731,6 +3708,158 @@ function readResults(h) {
2731
3708
  }
2732
3709
  }
2733
3710
 
3711
+ const OCCURRENCE_DAY = /^\d{4}-\d{2}-\d{2}$/;
3712
+
3713
+ function occurrenceDay(value) {
3714
+ if (typeof value !== 'string' || !OCCURRENCE_DAY.test(value)) { return false; }
3715
+ const time = Date.parse(`${value}T00:00:00.000Z`);
3716
+ return Number.isFinite(time) && new Date(time).toISOString().slice(0, 10) === value;
3717
+ }
3718
+
3719
+ function cleanCupMap(value, askedDoors) {
3720
+ if (!value || typeof value !== 'object' || Array.isArray(value)) { return {}; }
3721
+ const out = {};
3722
+ for (const door of askedDoors) {
3723
+ const raw = value[door];
3724
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { continue; }
3725
+ const rows = Object.entries(raw)
3726
+ .filter(([day, row]) => occurrenceDay(day) && row && typeof row === 'object' && !Array.isArray(row) &&
3727
+ typeof row.participated === 'boolean' && typeof row.champion === 'boolean')
3728
+ .sort(([a], [b]) => b.localeCompare(a))
3729
+ .slice(0, 2);
3730
+ if (rows.length) {
3731
+ out[door] = Object.fromEntries(rows.map(([day, row]) => [day, {
3732
+ participated: row.participated,
3733
+ champion: row.champion,
3734
+ }]));
3735
+ }
3736
+ }
3737
+ return out;
3738
+ }
3739
+
3740
+ function cupFor(h, playerId, door) {
3741
+ if (h.cupRead || typeof playerId !== 'string' || typeof door !== 'string') { return null; }
3742
+ const entry = h.players.get(playerId);
3743
+ const userId = userIdOf(h, playerId);
3744
+ const cached = h.cups.get(playerId);
3745
+ if (!entry || !userId || !cached || cached.entry !== entry || cached.userId !== userId || h.session !== cached.session) {
3746
+ return null;
3747
+ }
3748
+ const occurrences = cached.cup[door];
3749
+ return occurrences ? Object.fromEntries(Object.entries(occurrences).map(([day, row]) => [day, { ...row }])) : null;
3750
+ }
3751
+
3752
+ function cupNowFor(h, door) {
3753
+ if (h.cupRead || typeof door !== 'string') { return null; }
3754
+ const clock = h.cupClocks.get(door);
3755
+ if (!clock || clock.session !== h.session) { return null; }
3756
+ const elapsed = Date.now() - clock.receivedAt;
3757
+ if (!Number.isSafeInteger(elapsed) || elapsed < 0 || elapsed > CUP_CLOCK_STALE_MS) { return null; }
3758
+ const current = clock.at + elapsed;
3759
+ return Number.isSafeInteger(current) ? current : null;
3760
+ }
3761
+
3762
+ // The host puts the authoritative epoch milliseconds beside the event board.
3763
+ // Keep that metadata server-internal: authored code gets the ordinary board
3764
+ // plus `hub.cupNow(door)`, whose freshness is tied to this exact response.
3765
+ function weeklyBoard(value) {
3766
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
3767
+ !value.event || typeof value.event !== 'object' || Array.isArray(value.event)) {
3768
+ return { board: value, at: null };
3769
+ }
3770
+ const { cupNow, ...event } = value.event;
3771
+ return {
3772
+ board: { ...value, event },
3773
+ at: Number.isSafeInteger(cupNow) && cupNow >= 0 ? cupNow : null,
3774
+ };
3775
+ }
3776
+
3777
+ // The opted-in read combines door boards with private result bits. Calls are
3778
+ // serial, bounded by the existing door cap and Ghost's 100-user cap. Until the
3779
+ // whole refresh settles, no caller can combine old bits or clock with new boards.
3780
+ async function readWeeklyCup(h, hub, batches) {
3781
+ const request = { session: h.session };
3782
+ h.cupRead = request;
3783
+ h.cups.clear();
3784
+ const connected = [];
3785
+ for (const player of h.session?.players ?? []) {
3786
+ const entry = h.players.get(player.playerId);
3787
+ const userId = userIdOf(h, player.playerId);
3788
+ if (entry && userId && h.sim?.players.has(player.playerId)) {
3789
+ connected.push({ playerId: player.playerId, userId, entry });
3790
+ }
3791
+ }
3792
+ const identities = new Map();
3793
+ for (const who of connected) {
3794
+ if (!identities.has(who.userId)) { identities.set(who.userId, []); }
3795
+ identities.get(who.userId).push(who);
3796
+ }
3797
+ const users = [...identities].map(([userId, players]) => ({ userId, players }));
3798
+ const userBatches = [];
3799
+ for (let i = 0; i < users.length; i += CUP_USERS_PER_READ) {
3800
+ userBatches.push(users.slice(i, i + CUP_USERS_PER_READ));
3801
+ }
3802
+ const pending = new Map(connected.map((who) => [who.playerId, {}]));
3803
+ const boards = new Map(h.boards);
3804
+ const clocks = new Map(h.cupClocks);
3805
+ const failedClocks = new Set();
3806
+ let privateAvailable = connected.length === 0;
3807
+ let privateFailed = false;
3808
+ for (const ids of batches) {
3809
+ const asks = userBatches.length ? userBatches : [null];
3810
+ for (const usersAsked of asks) {
3811
+ try {
3812
+ const input = { doorIds: ids, ...(usersAsked ? { userIds: usersAsked.map((identity) => identity.userId) } : {}) };
3813
+ const read = await hub.readResults(input);
3814
+ const asked = new Set(ids);
3815
+ const receivedAt = Date.now();
3816
+ for (const id of ids) {
3817
+ boards.delete(id);
3818
+ clocks.delete(id);
3819
+ }
3820
+ for (const [id, raw] of Object.entries(read?.boards ?? {})) {
3821
+ const paired = weeklyBoard(raw);
3822
+ boards.set(id, paired.board);
3823
+ if (asked.has(id) && paired.at !== null) {
3824
+ clocks.set(id, { at: paired.at, receivedAt, session: request.session });
3825
+ }
3826
+ }
3827
+ h.boards = boards;
3828
+ if (usersAsked) {
3829
+ privateAvailable = true;
3830
+ for (const identity of usersAsked) {
3831
+ const clean = cleanCupMap(read?.players?.[identity.userId]?.cup, ids);
3832
+ for (const who of identity.players) { Object.assign(pending.get(who.playerId), clean); }
3833
+ }
3834
+ }
3835
+ } catch (err) {
3836
+ for (const id of ids) {
3837
+ failedClocks.add(id);
3838
+ clocks.delete(id);
3839
+ }
3840
+ if (usersAsked) { privateFailed = true; }
3841
+ refused(h, 'weeklyCup', err);
3842
+ }
3843
+ }
3844
+ }
3845
+ const listed = new Set(doors(h).map((d) => d.id));
3846
+ for (const id of boards.keys()) { if (!listed.has(id)) { boards.delete(id); } }
3847
+ for (const id of clocks.keys()) { if (!listed.has(id) || !boards.has(id)) { clocks.delete(id); } }
3848
+ h.boards = boards;
3849
+ Cabinets.refresh(h, doors(h));
3850
+ if (h.cupRead !== request) { return; }
3851
+ h.cupRead = null;
3852
+ if (h.session !== request.session) { return; }
3853
+ for (const id of failedClocks) { clocks.delete(id); }
3854
+ h.cupClocks = clocks;
3855
+ if (!privateAvailable || privateFailed) { return; }
3856
+ for (const who of connected) {
3857
+ if (h.players.get(who.playerId) === who.entry && userIdOf(h, who.playerId) === who.userId && h.sim?.players.has(who.playerId)) {
3858
+ h.cups.set(who.playerId, { entry: who.entry, userId: who.userId, session: request.session, cup: pending.get(who.playerId) });
3859
+ }
3860
+ }
3861
+ }
3862
+
2734
3863
  // Storage requests share a small in-flight budget with other hub ops. Read
2735
3864
  // one batch at a time, keeping the previous boards of a batch that fails.
2736
3865
  async function readBoards(h, hub, batches) {
@@ -2762,11 +3891,27 @@ async function readBoards(h, hub, batches) {
2762
3891
  Cabinets.refresh(h, doors(h));
2763
3892
  }
2764
3893
 
2765
- function applyRead(h, { playerId, avatarRev, colorRev, wearRev, earnedRev, startedAt }, read) {
3894
+ // One platform read owns one revision capture even when any number of hellos
3895
+ // replace the player's entry before its answer arrives.
3896
+ function startReadLifetime(h, playerId, entry) {
3897
+ const lifetime = {
3898
+ phase: 'want',
3899
+ avatarRev: entry.avatarRev,
3900
+ colorRev: entry.colorRev,
3901
+ wearRev: h.wearRev.get(playerId) ?? 0,
3902
+ earnedRev: h.earnedRev.get(playerId) ?? 0,
3903
+ startedAt: Date.now(),
3904
+ };
3905
+ entry.progressState.readLifetime = lifetime;
3906
+ return lifetime;
3907
+ }
3908
+
3909
+ function applyRead(h, { playerId, state, lifetime }, read) {
2766
3910
  const entry = h.players.get(playerId);
2767
- if (!entry || !read) {
3911
+ if (!entry || entry.progressState !== state || h.progressStates.get(playerId) !== state || state.readLifetime !== lifetime || !read) {
2768
3912
  return;
2769
3913
  }
3914
+ const { avatarRev, colorRev, wearRev, earnedRev, startedAt } = lifetime;
2770
3915
  // Their results and records, for `hub.results` (v1.5).
2771
3916
  History.take(h, playerId, read, startedAt);
2772
3917
  // The wearable likewise, unless the game put one on since (v1.4).
@@ -2774,14 +3919,14 @@ function applyRead(h, { playerId, avatarRev, colorRev, wearRev, earnedRev, start
2774
3919
  // The earned item likewise, unless an unlock or choice was made since (v1.53).
2775
3920
  Earned.applyRead(h, playerId, earnedRev, read);
2776
3921
  // The platform avatar, unless the client chose another since the read began.
2777
- if (Number.isInteger(read.avatar) && read.avatar >= 0 && read.avatar < AVATARS && entry.avatarRev === avatarRev) {
3922
+ if (!entry.signUp && Number.isInteger(read.avatar) && read.avatar >= 0 && read.avatar < AVATARS && entry.avatarRev === avatarRev) {
2778
3923
  if (entry.avatar !== read.avatar) {
2779
3924
  // A colour queued for the previous character cannot follow a new body.
2780
3925
  entry.color = cleanAvatarColor(read.avatarColor);
2781
3926
  }
2782
3927
  entry.avatar = read.avatar;
2783
3928
  }
2784
- if (entry.colorRev === colorRev) {
3929
+ if (!entry.signUp && entry.colorRev === colorRev) {
2785
3930
  entry.color = cleanAvatarColor(read.avatarColor);
2786
3931
  }
2787
3932
  const row = entry.fromDeckId
@@ -2846,6 +3991,7 @@ function sendHudOverrides(h) {
2846
3991
  const hidden = blockedPairs(h);
2847
3992
  const all = hidden ? namesOf(h, hidden.keys()) : null;
2848
3993
  for (const playerId of h.sim.players.keys()) {
3994
+ if (h.players.get(playerId)?.progressReading) { continue; }
2849
3995
  let spec = h.hudMe.get(playerId) ?? null;
2850
3996
  if (hidden) {
2851
3997
  const names = namesOf(h, hidden.get(playerId) ?? []);
@@ -2895,6 +4041,12 @@ function sendLabelOverrides(h) {
2895
4041
  delete out[id];
2896
4042
  }
2897
4043
  }
4044
+ if (h.padOccupancy) {
4045
+ addOccupancy(h, playerId, out, hiddenIds, (id) => {
4046
+ const label = h.labels.get(id);
4047
+ return !label ? null : hidden ? Blocks.labelFor(label, wireLabel(label), hiddenIds, names) : wireLabel(label);
4048
+ });
4049
+ }
2898
4050
  const json = JSON.stringify(out);
2899
4051
  if ((h.sentLabelsMe.get(playerId) ?? '{}') !== json) {
2900
4052
  h.sentLabelsMe.set(playerId, json);
@@ -2997,6 +4149,21 @@ function avatars(h, hidden) {
2997
4149
  return out;
2998
4150
  }
2999
4151
 
4152
+ // Anonymous player ids are a wire field only for a place that explicitly
4153
+ // opts into account-upgrade UI. Like hubAv, the shared list omits anyone in a
4154
+ // blocked pair; sendAvatarOverrides restores both avatar and guest status to
4155
+ // each unaffected viewer.
4156
+ function guests(h, hidden) {
4157
+ const out = [];
4158
+ for (const [playerId, entry] of h.players) {
4159
+ const player = h.session?.players.find((p) => p.playerId === playerId);
4160
+ if (entry.hello && player?.isAnonymous === true && !hidden?.has(playerId)) {
4161
+ out.push(playerId);
4162
+ }
4163
+ }
4164
+ return out;
4165
+ }
4166
+
3000
4167
  function standIn(avatar) {
3001
4168
  return avatar < OLD_AVATARS ? avatar : avatar % OLD_AVATARS;
3002
4169
  }
@@ -3071,16 +4238,21 @@ function blockedPairs(h) {
3071
4238
  // them, when they change. A session with no blocks sends nothing here.
3072
4239
  function sendAvatarOverrides(h) {
3073
4240
  const hidden = blockedPairs(h);
4241
+ const anonymousEntry = h.place.anonymousEntry === true;
3074
4242
  for (const playerId of h.sim.players.keys()) {
3075
4243
  const out = {};
3076
4244
  // v1.51: as `hubAv` and `hubAv2` are, the stand-in for everyone and the
3077
4245
  // avatar really worn beside it, the second only when there is one.
3078
4246
  const real = {};
3079
4247
  const colors = {};
4248
+ const guestOverrides = [];
3080
4249
  for (const shrouded of hidden?.keys() ?? []) {
3081
4250
  const entry = h.players.get(shrouded);
3082
4251
  if (entry?.hello && !hidden.get(playerId)?.has(shrouded)) {
3083
4252
  out[shrouded] = standIn(entry.avatar);
4253
+ if (anonymousEntry && h.session?.players.find((p) => p.playerId === shrouded)?.isAnonymous === true) {
4254
+ guestOverrides.push(shrouded);
4255
+ }
3084
4256
  if (entry.color > 0) {
3085
4257
  colors[shrouded] = entry.color;
3086
4258
  }
@@ -3093,10 +4265,25 @@ function sendAvatarOverrides(h) {
3093
4265
  // `hubAv2` says nobody in it wears one of the twelve (any more).
3094
4266
  const some = Object.keys(real).length > 0;
3095
4267
  const colored = Object.keys(colors).length > 0;
3096
- const json = colored ? JSON.stringify([out, real, colors]) : some ? JSON.stringify([out, real]) : JSON.stringify(out);
4268
+ const populated = Object.keys(out).length > 0;
4269
+ const json = !populated
4270
+ ? '{}'
4271
+ : anonymousEntry
4272
+ ? JSON.stringify([out, real, colors, guestOverrides])
4273
+ : colored
4274
+ ? JSON.stringify([out, real, colors])
4275
+ : some
4276
+ ? JSON.stringify([out, real])
4277
+ : JSON.stringify(out);
3097
4278
  if ((h.sentAvMe.get(playerId) ?? '{}') !== json) {
3098
4279
  h.sentAvMe.set(playerId, json);
3099
- h.session?.send(playerId, { k: 'hub-av', hubAv: out, ...(some ? { hubAv2: real } : {}), ...(colored ? { hubAvC: colors } : {}) });
4280
+ h.session?.send(playerId, {
4281
+ k: 'hub-av',
4282
+ hubAv: out,
4283
+ ...(some ? { hubAv2: real } : {}),
4284
+ ...(colored ? { hubAvC: colors } : {}),
4285
+ ...(anonymousEntry ? { hubGuests: guestOverrides } : {}),
4286
+ });
3100
4287
  }
3101
4288
  }
3102
4289
  }
@@ -3210,7 +4397,7 @@ function playerCells(h, sim) {
3210
4397
 
3211
4398
  function cellPlayers(h, sim, known, hidden) {
3212
4399
  const views = playerCells(h, sim);
3213
- const userIds = new Map([...sim.players.keys()].map((id) => [id, userIdOf(h, id)]));
4400
+ const userIds = new Map([...sim.players.keys()].map((id) => [id, friendUserIdOf(h, id)]));
3214
4401
  const sees = new Map();
3215
4402
  const now = Date.now();
3216
4403
  for (const [viewer, view] of views) {
@@ -3246,6 +4433,13 @@ function isSceneActor(h, id) {
3246
4433
  // subjects (`dev-guest-<n>`) count, since their storage works there.
3247
4434
  const DEV_GUEST = /^dev-guest-\d{1,6}$/;
3248
4435
 
4436
+ // Pose-only reconnect requires a real signed-in account even on a dev host;
4437
+ // dev-guest subjects remain useful to older storage APIs but are not owners.
4438
+ function arrivalPoseUserId(h, playerId) {
4439
+ const p = h.session?.players.find(q => q.playerId === playerId);
4440
+ return p?.isAnonymous === false && USER_ID.test(String(p.userId)) ? String(p.userId) : null;
4441
+ }
4442
+
3249
4443
  function userIdOf(h, playerId) {
3250
4444
  const p = h.session?.players.find((q) => q.playerId === playerId);
3251
4445
  if (!p) {
@@ -3258,6 +4452,23 @@ function userIdOf(h, playerId) {
3258
4452
  return dev && DEV_GUEST.test(String(p.userId)) ? String(p.userId) : null;
3259
4453
  }
3260
4454
 
4455
+ // Who a player is to their friends among the players here (`friendsAmong`,
4456
+ // cell interest priority): the trusted Castle user id, a guest's included,
4457
+ // since a guest is over 13 like any other player and ghost answers for them.
4458
+ // It grants nothing kept on an account; storage, results and history go by
4459
+ // userIdOf alone.
4460
+ function friendUserIdOf(h, playerId) {
4461
+ const p = h.session?.players.find((q) => q.playerId === playerId);
4462
+ return p && USER_ID.test(String(p.userId ?? '')) ? String(p.userId) : null;
4463
+ }
4464
+
4465
+ // A trusted identity used only for opted anonymous-entry continuity. It never
4466
+ // grants account storage, hub operations, or any other userIdOf capability.
4467
+ function identityUserIdOf(h, playerId) {
4468
+ const p = h.session?.players.find((q) => q.playerId === playerId);
4469
+ return p && USER_ID.test(String(p.userId ?? '')) ? String(p.userId) : null;
4470
+ }
4471
+
3261
4472
  function usernameOf(h, playerId) {
3262
4473
  return h.session?.players.find((p) => p.playerId === playerId)?.username ?? 'player';
3263
4474
  }