castle-web-cli 0.4.232 → 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 (587) hide show
  1. package/dist/agent-failures.d.ts +8 -0
  2. package/dist/agent-failures.js +19 -2
  3. package/dist/agent-prompts.d.ts +1 -1
  4. package/dist/agent-prompts.js +10 -3
  5. package/dist/agent.d.ts +64 -3
  6. package/dist/agent.js +170 -81
  7. package/dist/api.d.ts +11 -0
  8. package/dist/api.js +43 -0
  9. package/dist/bundle.d.ts +64 -0
  10. package/dist/bundle.js +558 -2
  11. package/dist/castle-host/host.d.ts +18 -2
  12. package/dist/castle-host/host.js +844 -39
  13. package/dist/castleJson.d.ts +23 -2
  14. package/dist/castleJson.js +46 -2
  15. package/dist/check.d.ts +3 -1
  16. package/dist/check.js +20 -3
  17. package/dist/chunkLoader.d.ts +3 -0
  18. package/dist/chunkLoader.js +111 -0
  19. package/dist/devParty.d.ts +26 -0
  20. package/dist/devParty.js +231 -0
  21. package/dist/devSaveStorage.js +4 -0
  22. package/dist/devSessionStorage.js +50 -2
  23. package/dist/devSocial.d.ts +24 -0
  24. package/dist/devSocial.js +70 -0
  25. package/dist/ide.d.ts +2 -0
  26. package/dist/ide.js +119 -15
  27. package/dist/importPinMismatch.d.ts +22 -0
  28. package/dist/importPinMismatch.js +77 -0
  29. package/dist/importRegression.js +3 -15
  30. package/dist/imports.d.ts +10 -3
  31. package/dist/imports.js +88 -20
  32. package/dist/index.js +11 -4
  33. package/dist/init.js +1 -1
  34. package/dist/platformDoc.js +22 -0
  35. package/dist/routerFences.d.ts +5 -0
  36. package/dist/routerFences.js +12 -2
  37. package/dist/save-deck.d.ts +25 -1
  38. package/dist/save-deck.js +178 -9
  39. package/dist/serve.js +32 -11
  40. package/dist/shell/assets/{index-D2tWM896.js → index-DulbYIJm.js} +97 -97
  41. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  42. package/dist/shell/index.html +2 -2
  43. package/dist/taskSteer.d.ts +13 -0
  44. package/dist/taskSteer.js +22 -2
  45. package/dist/vitePlugins.d.ts +2 -1
  46. package/dist/vitePlugins.js +13 -0
  47. package/kits/base/castle.json +1 -1
  48. package/kits/base/package-lock.json +1 -1
  49. package/kits/base/sdk/README.md +339 -5
  50. package/kits/base/sdk/avatar.d.ts +6 -2
  51. package/kits/base/sdk/avatar.js +12 -4
  52. package/kits/base/sdk/castle.d.ts +7 -3
  53. package/kits/base/sdk/castle.js +2 -0
  54. package/kits/base/sdk/commands.d.ts +176 -1
  55. package/kits/base/sdk/commands.js +3 -0
  56. package/kits/base/sdk/display.d.ts +3 -0
  57. package/kits/base/sdk/display.js +9 -3
  58. package/kits/base/sdk/hub.d.ts +37 -6
  59. package/kits/base/sdk/hub.js +63 -4
  60. package/kits/base/sdk/multiplayer.d.ts +7 -1
  61. package/kits/base/sdk/multiplayer.js +148 -32
  62. package/kits/base/sdk/multiplayerProtocol.d.ts +2 -0
  63. package/kits/base/sdk/party.d.ts +23 -0
  64. package/kits/base/sdk/party.js +91 -0
  65. package/kits/base/sdk/reconnectBudget.d.ts +23 -0
  66. package/kits/base/sdk/reconnectBudget.js +96 -0
  67. package/kits/base/sdk/save.d.ts +38 -1
  68. package/kits/base/sdk/save.js +81 -7
  69. package/kits/base/sdk/server/hub.d.ts +117 -0
  70. package/kits/base/sdk/server/hub.js +119 -2
  71. package/kits/base/sdk/server/platformHandle.d.ts +43 -1
  72. package/kits/base/sdk/server/storage.d.ts +17 -0
  73. package/kits/base/sdk/server/storage.js +65 -3
  74. package/kits/base/sdk/server/wrapper.d.ts +43 -6
  75. package/kits/base/sdk/server/wrapper.js +93 -9
  76. package/kits/base/sdk/social.d.ts +9 -0
  77. package/kits/base/sdk/social.js +5 -0
  78. package/kits/hub-game/CLAUDE.md +451 -13
  79. package/kits/hub-game/README.md +63 -0
  80. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  81. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  82. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  83. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  84. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  88. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  89. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  90. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  91. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  92. package/kits/hub-game/castle.json +5 -5
  93. package/kits/hub-game/code/client/act.js +312 -0
  94. package/kits/hub-game/code/client/actionLayout.js +147 -0
  95. package/kits/hub-game/code/client/actionOverflow.js +556 -0
  96. package/kits/hub-game/code/client/actorBudget.js +47 -0
  97. package/kits/hub-game/code/client/arrivalCamera.js +50 -0
  98. package/kits/hub-game/code/client/askSlot.js +117 -0
  99. package/kits/hub-game/code/client/attention.js +11 -2
  100. package/kits/hub-game/code/client/avatar.js +311 -35
  101. package/kits/hub-game/code/client/avatarCap.js +228 -0
  102. package/kits/hub-game/code/client/avatarColors.js +70 -0
  103. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  104. package/kits/hub-game/code/client/avatarShare.js +253 -0
  105. package/kits/hub-game/code/client/backVisibility.js +13 -0
  106. package/kits/hub-game/code/client/ballot.js +472 -0
  107. package/kits/hub-game/code/client/build.js +38 -0
  108. package/kits/hub-game/code/client/chat.js +41 -5
  109. package/kits/hub-game/code/client/chatModeration.js +5 -0
  110. package/kits/hub-game/code/client/chrome.js +2144 -160
  111. package/kits/hub-game/code/client/companion.js +716 -0
  112. package/kits/hub-game/code/client/companionDress.js +99 -0
  113. package/kits/hub-game/code/client/crowdNames.js +241 -0
  114. package/kits/hub-game/code/client/decor.js +515 -0
  115. package/kits/hub-game/code/client/defaultEnvironment.js +194 -0
  116. package/kits/hub-game/code/client/doorErrors.js +39 -0
  117. package/kits/hub-game/code/client/earned.js +131 -0
  118. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  119. package/kits/hub-game/code/client/fall.js +18 -0
  120. package/kits/hub-game/code/client/farAvatars.js +233 -0
  121. package/kits/hub-game/code/client/firstJoin.js +9 -2
  122. package/kits/hub-game/code/client/fpsTelemetry.js +50 -0
  123. package/kits/hub-game/code/client/frameBatch.js +5 -0
  124. package/kits/hub-game/code/client/grab.js +368 -29
  125. package/kits/hub-game/code/client/hookLayer.js +385 -20
  126. package/kits/hub-game/code/client/hudCopy.js +51 -0
  127. package/kits/hub-game/code/client/hudRate.js +20 -0
  128. package/kits/hub-game/code/client/idle.js +177 -24
  129. package/kits/hub-game/code/client/interestCap.js +81 -0
  130. package/kits/hub-game/code/client/invites.js +231 -0
  131. package/kits/hub-game/code/client/joinError.js +9 -0
  132. package/kits/hub-game/code/client/keys.js +36 -0
  133. package/kits/hub-game/code/client/labelsNear.js +234 -0
  134. package/kits/hub-game/code/client/landscapeLayout.js +17 -0
  135. package/kits/hub-game/code/client/layoutCache.js +264 -0
  136. package/kits/hub-game/code/client/loadTelemetry.js +20 -0
  137. package/kits/hub-game/code/client/loadingCover.js +148 -0
  138. package/kits/hub-game/code/client/loadingEntry.js +8 -0
  139. package/kits/hub-game/code/client/menuIcons.js +34 -0
  140. package/kits/hub-game/code/client/menuRows.js +43 -0
  141. package/kits/hub-game/code/client/modelReady.js +7 -0
  142. package/kits/hub-game/code/client/pack.js +6 -2
  143. package/kits/hub-game/code/client/packFormat.js +3 -3
  144. package/kits/hub-game/code/client/padCueArrival.js +23 -0
  145. package/kits/hub-game/code/client/padCues.js +112 -0
  146. package/kits/hub-game/code/client/padOccupancy.js +88 -0
  147. package/kits/hub-game/code/client/padReadability.js +26 -0
  148. package/kits/hub-game/code/client/padRings.js +69 -0
  149. package/kits/hub-game/code/client/pushVisit.js +14 -0
  150. package/kits/hub-game/code/client/quality.js +205 -0
  151. package/kits/hub-game/code/client/qualityEntry.js +55 -0
  152. package/kits/hub-game/code/client/rehello.js +167 -0
  153. package/kits/hub-game/code/client/safeLayout.js +338 -0
  154. package/kits/hub-game/code/client/safeStyle.js +42 -0
  155. package/kits/hub-game/code/client/say.js +12 -3
  156. package/kits/hub-game/code/client/shot.js +146 -0
  157. package/kits/hub-game/code/client/shotFit.js +56 -0
  158. package/kits/hub-game/code/client/signIn.js +28 -0
  159. package/kits/hub-game/code/client/sound.js +63 -8
  160. package/kits/hub-game/code/client/soundscape.js +1151 -0
  161. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  162. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  163. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  164. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  165. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  166. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  167. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  168. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  169. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  170. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  171. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  172. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  173. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  174. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  175. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  176. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  177. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  178. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  179. package/kits/hub-game/code/client/spin.js +101 -0
  180. package/kits/hub-game/code/client/state.js +162 -1
  181. package/kits/hub-game/code/client/stuck.js +259 -0
  182. package/kits/hub-game/code/client/talk.js +714 -59
  183. package/kits/hub-game/code/client/tiers.js +543 -52
  184. package/kits/hub-game/code/client/toastBand.js +37 -0
  185. package/kits/hub-game/code/client/together.js +39 -2
  186. package/kits/hub-game/code/client/visibility.js +43 -0
  187. package/kits/hub-game/code/client/weakestLookBake.js +92 -0
  188. package/kits/hub-game/code/client/weakestTier.js +295 -0
  189. package/kits/hub-game/code/client/wear.js +461 -170
  190. package/kits/hub-game/code/client/worldLabels.js +241 -0
  191. package/kits/hub-game/code/client/yours.js +200 -0
  192. package/kits/hub-game/code/companionSpec.js +45 -0
  193. package/kits/hub-game/code/npcDisplayText.js +55 -0
  194. package/kits/hub-game/code/privateText.js +7 -0
  195. package/kits/hub-game/code/server/act.js +124 -0
  196. package/kits/hub-game/code/server/actions.js +138 -0
  197. package/kits/hub-game/code/server/actors.js +11 -2
  198. package/kits/hub-game/code/server/analytics.js +83 -0
  199. package/kits/hub-game/code/server/anonymousEntry.js +49 -0
  200. package/kits/hub-game/code/server/arrivalPose.js +36 -0
  201. package/kits/hub-game/code/server/ask.js +155 -0
  202. package/kits/hub-game/code/server/ballot.js +539 -0
  203. package/kits/hub-game/code/server/cells.js +100 -0
  204. package/kits/hub-game/code/server/companion.js +107 -0
  205. package/kits/hub-game/code/server/cues.js +70 -0
  206. package/kits/hub-game/code/server/decor.js +269 -0
  207. package/kits/hub-game/code/server/doorAnalytics.js +52 -0
  208. package/kits/hub-game/code/server/earned.js +478 -0
  209. package/kits/hub-game/code/server/frameBatch.js +183 -0
  210. package/kits/hub-game/code/server/friendBests.js +166 -0
  211. package/kits/hub-game/code/server/friendsAmong.js +272 -0
  212. package/kits/hub-game/code/server/history.js +7 -0
  213. package/kits/hub-game/code/server/hub.js +2510 -95
  214. package/kits/hub-game/code/server/idle.js +60 -12
  215. package/kits/hub-game/code/server/index.js +28 -6
  216. package/kits/hub-game/code/server/invites.js +19 -0
  217. package/kits/hub-game/code/server/labels.js +36 -2
  218. package/kits/hub-game/code/server/loadAbandon.js +106 -0
  219. package/kits/hub-game/code/server/manifest.js +586 -7
  220. package/kits/hub-game/code/server/menu.js +161 -0
  221. package/kits/hub-game/code/server/npcs.js +1025 -113
  222. package/kits/hub-game/code/server/observe.js +408 -0
  223. package/kits/hub-game/code/server/padOccupancy.js +85 -0
  224. package/kits/hub-game/code/server/party.js +2 -2
  225. package/kits/hub-game/code/server/players.js +30 -0
  226. package/kits/hub-game/code/server/resumePose.js +152 -0
  227. package/kits/hub-game/code/server/say.js +1 -1
  228. package/kits/hub-game/code/server/shot.js +110 -0
  229. package/kits/hub-game/code/server/standing.js +123 -0
  230. package/kits/hub-game/code/server/storageLimit.js +187 -0
  231. package/kits/hub-game/code/server/vis.js +175 -0
  232. package/kits/hub-game/code/server/wear.js +12 -0
  233. package/kits/hub-game/code/server/yours.js +59 -0
  234. package/kits/hub-game/code/shared/act.js +35 -0
  235. package/kits/hub-game/code/shared/cues.js +9 -0
  236. package/kits/hub-game/code/shared/danceIdle.js +28 -0
  237. package/kits/hub-game/code/shared/decor.js +41 -0
  238. package/kits/hub-game/code/shared/loadStages.js +12 -0
  239. package/kits/hub-game/code/shared/quality.js +74 -0
  240. package/kits/hub-game/code/shared/say.js +2 -0
  241. package/kits/hub-game/code/shared/shot.js +53 -0
  242. package/kits/hub-game/code/shared/spin.js +57 -0
  243. package/kits/hub-game/code/systems/hub.js +1753 -202
  244. package/kits/hub-game/docs/analytics.md +279 -0
  245. package/kits/hub-game/docs/content-pack.md +1 -1
  246. package/kits/hub-game/docs/contract.md +3475 -77
  247. package/kits/hub-game/docs/home-pieces.md +71 -0
  248. package/kits/hub-game/docs/observed-progress.md +252 -0
  249. package/kits/hub-game/main.jsx +2 -0
  250. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  251. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  252. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  253. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  254. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  255. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  256. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  257. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  258. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  259. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  260. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  261. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  262. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  263. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  264. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  265. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  266. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  267. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  268. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  269. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  270. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  271. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  272. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  273. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  274. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  275. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  276. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  277. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  278. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  279. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  280. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  281. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  282. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  283. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  284. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  285. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  286. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  287. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  288. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  289. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  290. package/kits/hub-game/package-lock.json +10 -1
  291. package/kits/hub-game/package.json +6 -2
  292. package/kits/hub-game/play/player.js +142 -0
  293. package/kits/hub-game/play/registry.js +47 -0
  294. package/kits/hub-game/play.jsx +37 -0
  295. package/kits/hub-game/scripts/check.mjs +117 -16
  296. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  297. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +132 -0
  298. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  299. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +26 -0
  300. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +123 -0
  301. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  302. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  303. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  304. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  305. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  306. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  307. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  308. package/kits/hub-game/scripts/pose-storage-fixture.mjs +46 -0
  309. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  310. package/kits/hub-game/scripts/test-act-client.mjs +186 -0
  311. package/kits/hub-game/scripts/test-act.mjs +171 -0
  312. package/kits/hub-game/scripts/test-action-layout.mjs +80 -0
  313. package/kits/hub-game/scripts/test-action-observers.mjs +46 -0
  314. package/kits/hub-game/scripts/test-actions-client.mjs +853 -0
  315. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  316. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  317. package/kits/hub-game/scripts/test-actors.mjs +38 -23
  318. package/kits/hub-game/scripts/test-analytics.mjs +76 -0
  319. package/kits/hub-game/scripts/test-anonymous-entry.mjs +28 -0
  320. package/kits/hub-game/scripts/test-arrival-pose-server.mjs +196 -0
  321. package/kits/hub-game/scripts/test-arrival-pose.mjs +24 -0
  322. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  323. package/kits/hub-game/scripts/test-ask-slot.mjs +85 -0
  324. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  325. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  326. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  327. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  328. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  329. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  330. package/kits/hub-game/scripts/test-avatar-wire.mjs +792 -0
  331. package/kits/hub-game/scripts/test-avatar.mjs +584 -7
  332. package/kits/hub-game/scripts/test-back-visibility.mjs +82 -0
  333. package/kits/hub-game/scripts/test-ballot.mjs +1008 -0
  334. package/kits/hub-game/scripts/test-ban-join.mjs +121 -13
  335. package/kits/hub-game/scripts/test-build.mjs +49 -0
  336. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  337. package/kits/hub-game/scripts/test-chat.mjs +863 -0
  338. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  339. package/kits/hub-game/scripts/test-companion-chat.mjs +216 -0
  340. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  341. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  342. package/kits/hub-game/scripts/test-control-layout-dom.mjs +120 -0
  343. package/kits/hub-game/scripts/test-crowd-names.mjs +205 -0
  344. package/kits/hub-game/scripts/test-decor-client.mjs +344 -0
  345. package/kits/hub-game/scripts/test-decor.mjs +464 -0
  346. package/kits/hub-game/scripts/test-default-environment-root.mjs +95 -0
  347. package/kits/hub-game/scripts/test-default-environment.mjs +267 -0
  348. package/kits/hub-game/scripts/test-door-analytics.mjs +58 -0
  349. package/kits/hub-game/scripts/test-door-jump.mjs +100 -0
  350. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  351. package/kits/hub-game/scripts/test-earned.mjs +1224 -0
  352. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  353. package/kits/hub-game/scripts/test-far-avatars.mjs +340 -0
  354. package/kits/hub-game/scripts/test-fps-telemetry.mjs +112 -0
  355. package/kits/hub-game/scripts/test-frame-batch.mjs +252 -0
  356. package/kits/hub-game/scripts/test-fresh-friends.mjs +118 -0
  357. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  358. package/kits/hub-game/scripts/test-grab-orbit.mjs +961 -0
  359. package/kits/hub-game/scripts/test-grab.mjs +7 -0
  360. package/kits/hub-game/scripts/test-hats.mjs +422 -168
  361. package/kits/hub-game/scripts/test-high-only.mjs +170 -0
  362. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  363. package/kits/hub-game/scripts/test-hub-ops.mjs +758 -2
  364. package/kits/hub-game/scripts/test-hub-trip.mjs +1594 -12
  365. package/kits/hub-game/scripts/test-hud-clear.mjs +484 -57
  366. package/kits/hub-game/scripts/test-hud-defects-dom.mjs +100 -0
  367. package/kits/hub-game/scripts/test-hud-rate.mjs +224 -0
  368. package/kits/hub-game/scripts/test-hud-safe-visibility-dom.mjs +83 -0
  369. package/kits/hub-game/scripts/test-idle.mjs +427 -1
  370. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  371. package/kits/hub-game/scripts/test-interest-cells.mjs +513 -0
  372. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  373. package/kits/hub-game/scripts/test-interest.mjs +15 -0
  374. package/kits/hub-game/scripts/test-invites-client.mjs +430 -0
  375. package/kits/hub-game/scripts/test-invites.mjs +109 -0
  376. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  377. package/kits/hub-game/scripts/test-labels.mjs +664 -0
  378. package/kits/hub-game/scripts/test-landscape-layout.mjs +194 -0
  379. package/kits/hub-game/scripts/test-list-scroll-dom.mjs +49 -0
  380. package/kits/hub-game/scripts/test-load-abandon.mjs +246 -0
  381. package/kits/hub-game/scripts/test-loading-cover.mjs +162 -0
  382. package/kits/hub-game/scripts/test-manifest.mjs +472 -0
  383. package/kits/hub-game/scripts/test-menu-client.mjs +585 -0
  384. package/kits/hub-game/scripts/test-menu.mjs +319 -0
  385. package/kits/hub-game/scripts/test-npcs.mjs +2528 -13
  386. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  387. package/kits/hub-game/scripts/test-observed.mjs +745 -0
  388. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  389. package/kits/hub-game/scripts/test-pad-cues.mjs +304 -0
  390. package/kits/hub-game/scripts/test-pad-occupancy.mjs +177 -0
  391. package/kits/hub-game/scripts/test-picker.mjs +541 -0
  392. package/kits/hub-game/scripts/test-placement-cache.mjs +690 -0
  393. package/kits/hub-game/scripts/test-progress-reset.mjs +559 -0
  394. package/kits/hub-game/scripts/test-push-visit.mjs +26 -0
  395. package/kits/hub-game/scripts/test-quality.mjs +385 -0
  396. package/kits/hub-game/scripts/test-rehello.mjs +1733 -0
  397. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  398. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  399. package/kits/hub-game/scripts/test-resume-action-order.mjs +598 -0
  400. package/kits/hub-game/scripts/test-resume-held.mjs +239 -0
  401. package/kits/hub-game/scripts/test-resume-pose.mjs +142 -0
  402. package/kits/hub-game/scripts/test-safe-events-dom.mjs +116 -0
  403. package/kits/hub-game/scripts/test-safe-layout.mjs +330 -0
  404. package/kits/hub-game/scripts/test-say.mjs +1 -1
  405. package/kits/hub-game/scripts/test-shot.mjs +901 -0
  406. package/kits/hub-game/scripts/test-signin-client.mjs +45 -0
  407. package/kits/hub-game/scripts/test-soundscape.mjs +5437 -0
  408. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  409. package/kits/hub-game/scripts/test-standing.mjs +449 -0
  410. package/kits/hub-game/scripts/test-storage-limit.mjs +333 -0
  411. package/kits/hub-game/scripts/test-stuck.mjs +1904 -0
  412. package/kits/hub-game/scripts/test-talk-overlay-dom.mjs +130 -0
  413. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  414. package/kits/hub-game/scripts/test-tiers-render.mjs +412 -0
  415. package/kits/hub-game/scripts/test-tiers.mjs +476 -2
  416. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  417. package/kits/hub-game/scripts/test-try-on.mjs +22 -22
  418. package/kits/hub-game/scripts/test-vis.mjs +770 -0
  419. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  420. package/kits/hub-game/scripts/test-weakest-tier.mjs +924 -0
  421. package/kits/hub-game/scripts/test-world-labels.mjs +367 -0
  422. package/kits/hub-game/scripts/test-yours-chrome.mjs +210 -0
  423. package/kits/hub-game/scripts/test-yours.mjs +403 -0
  424. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  425. package/kits/multiplayer-3d/castle.json +5 -5
  426. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  427. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  428. package/kits/multiplayer-3d/code/client/joinFailure.js +27 -0
  429. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  430. package/kits/multiplayer-3d/code/client/resumeGate.js +139 -0
  431. package/kits/multiplayer-3d/code/options.js +5 -0
  432. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  433. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  434. package/kits/multiplayer-3d/code/server/world.js +7 -0
  435. package/kits/multiplayer-3d/code/systems/multiplayer.js +443 -34
  436. package/kits/multiplayer-3d/package-lock.json +8 -1
  437. package/kits/multiplayer-3d/package.json +3 -1
  438. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  439. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  440. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  441. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  442. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  443. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  444. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  445. package/kits/multiplayer-3d/scripts/test-join-watchdog.mjs +436 -0
  446. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  447. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +624 -0
  448. package/kits/physics-2d/CLAUDE.md +19 -1
  449. package/kits/physics-2d/castle.json +2 -2
  450. package/kits/physics-2d/engine/frozenActors.js +233 -0
  451. package/kits/physics-2d/engine/scene.js +337 -3
  452. package/kits/physics-2d/engine/skyKey.js +129 -0
  453. package/kits/physics-2d/engine/stillClock.js +106 -0
  454. package/kits/physics-2d/engine/updateBudget.js +21 -0
  455. package/kits/physics-2d/eslint.config.js +1 -1
  456. package/kits/physics-2d/play/behaviors/AnalogStick.js +198 -0
  457. package/kits/physics-2d/play/behaviors/Camera.js +40 -0
  458. package/kits/physics-2d/play/behaviors/Collider.js +122 -0
  459. package/kits/physics-2d/play/behaviors/Draggable.js +115 -0
  460. package/kits/physics-2d/play/behaviors/Goal.js +46 -0
  461. package/kits/physics-2d/play/behaviors/Joints.js +126 -0
  462. package/kits/physics-2d/play/behaviors/Layout.js +71 -0
  463. package/kits/physics-2d/play/behaviors/RigidBody.js +57 -0
  464. package/kits/physics-2d/play/behaviors/Slingshot.js +142 -0
  465. package/kits/physics-2d/play/behaviors/SoundPlayer.js +263 -0
  466. package/kits/physics-2d/play/behaviors/Sprite.js +406 -0
  467. package/kits/physics-2d/play/behaviors/Style.js +209 -0
  468. package/kits/physics-2d/play/behaviors/Text.js +85 -0
  469. package/kits/physics-2d/play/behaviors/Video.js +93 -0
  470. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +326 -1
  471. package/kits/physics-3d/CLAUDE.md +42 -529
  472. package/kits/physics-3d/behaviors/Body.jsx +3 -0
  473. package/kits/physics-3d/behaviors/Model.jsx +3 -0
  474. package/kits/physics-3d/behaviors/Player.jsx +661 -87
  475. package/kits/physics-3d/behaviors/Shape.jsx +3 -0
  476. package/kits/physics-3d/behaviors/Solid.jsx +3 -0
  477. package/kits/physics-3d/behaviors/Transform.jsx +3 -0
  478. package/kits/physics-3d/castle.json +3 -3
  479. package/kits/physics-3d/docs/engine-camera.md +542 -0
  480. package/kits/physics-3d/docs/engine-frame-cap.md +136 -0
  481. package/kits/physics-3d/docs/engine-load.md +149 -0
  482. package/kits/physics-3d/docs/engine-look.md +114 -0
  483. package/kits/physics-3d/docs/engine-shadows.md +372 -0
  484. package/kits/physics-3d/docs/engine-skip-work.md +187 -0
  485. package/kits/physics-3d/docs/engine-sky.md +198 -0
  486. package/kits/physics-3d/docs/engine-static-actors.md +226 -0
  487. package/kits/physics-3d/docs/engine-view.md +37 -0
  488. package/kits/physics-3d/docs/pxmodel-format.md +9 -1
  489. package/kits/physics-3d/engine3d/PlayOnly3D.jsx +5 -1
  490. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +19 -277
  491. package/kits/physics-3d/engine3d/actornode.js +87 -0
  492. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  493. package/kits/physics-3d/engine3d/branches.js +3 -13
  494. package/kits/physics-3d/engine3d/cage.js +2 -7
  495. package/kits/physics-3d/engine3d/cageops.js +2 -17
  496. package/kits/physics-3d/engine3d/dataBehaviors.js +12 -0
  497. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  498. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  499. package/kits/physics-3d/engine3d/framecap.js +99 -0
  500. package/kits/physics-3d/engine3d/frozenphysics.js +140 -0
  501. package/kits/physics-3d/engine3d/frozenstatics.js +273 -0
  502. package/kits/physics-3d/engine3d/gait.js +126 -0
  503. package/kits/physics-3d/engine3d/initialModelFiles.js +18 -0
  504. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  505. package/kits/physics-3d/engine3d/look.js +514 -48
  506. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  507. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  508. package/kits/physics-3d/engine3d/modelFiles.js +3 -17
  509. package/kits/physics-3d/engine3d/modelMath.js +49 -0
  510. package/kits/physics-3d/engine3d/modelready.js +16 -0
  511. package/kits/physics-3d/engine3d/motion.js +39 -10
  512. package/kits/physics-3d/engine3d/nearshadows.js +106 -21
  513. package/kits/physics-3d/engine3d/optimize.js +9 -5
  514. package/kits/physics-3d/engine3d/orbitinput.js +522 -10
  515. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  516. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  517. package/kits/physics-3d/engine3d/partgeometry.js +1 -16
  518. package/kits/physics-3d/engine3d/paths.js +1 -9
  519. package/kits/physics-3d/engine3d/playTimings.js +50 -0
  520. package/kits/physics-3d/engine3d/playerRun.js +372 -0
  521. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  522. package/kits/physics-3d/engine3d/rapier.js +27 -0
  523. package/kits/physics-3d/engine3d/scatter.js +1 -11
  524. package/kits/physics-3d/engine3d/shadowfade.js +890 -0
  525. package/kits/physics-3d/engine3d/sky.js +547 -0
  526. package/kits/physics-3d/engine3d/skylife.js +306 -0
  527. package/kits/physics-3d/engine3d/squarefirst.js +177 -0
  528. package/kits/physics-3d/engine3d/stillshadows.js +399 -0
  529. package/kits/physics-3d/engine3d/sweep.js +1 -25
  530. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  531. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  532. package/kits/physics-3d/engine3d/world3d.js +1253 -76
  533. package/kits/physics-3d/eslint.config.js +2 -1
  534. package/kits/physics-3d/main.jsx +10 -2
  535. package/kits/physics-3d/package-lock.json +7 -0
  536. package/kits/physics-3d/package.json +5 -1
  537. package/kits/physics-3d/play/behaviors/Body.js +31 -0
  538. package/kits/physics-3d/play/behaviors/Door.js +37 -0
  539. package/kits/physics-3d/play/behaviors/Lookable.js +16 -0
  540. package/kits/physics-3d/play/behaviors/Model.js +23 -0
  541. package/kits/physics-3d/play/behaviors/Pickup.js +46 -0
  542. package/kits/physics-3d/play/behaviors/Player.js +1204 -0
  543. package/kits/physics-3d/play/behaviors/Shape.js +47 -0
  544. package/kits/physics-3d/play/behaviors/Solid.js +16 -0
  545. package/kits/physics-3d/play/behaviors/Transform.js +29 -0
  546. package/kits/physics-3d/pnpm-lock.yaml +8 -0
  547. package/kits/physics-3d/scripts/bench-shadow-fade.mjs +37 -0
  548. package/kits/physics-3d/scripts/build-rapier-gz.mjs +56 -0
  549. package/kits/physics-3d/scripts/frozen-statics-fixture.mjs +141 -0
  550. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  551. package/kits/physics-3d/scripts/test-camera-follow.mjs +5 -1
  552. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2613 -82
  553. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +2 -2
  554. package/kits/physics-3d/scripts/test-empty-gait-hints.mjs +89 -0
  555. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +438 -0
  556. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  557. package/kits/physics-3d/scripts/test-frozen-nested.mjs +49 -0
  558. package/kits/physics-3d/scripts/test-frozen-statics-legacy-physics2d.mjs +123 -0
  559. package/kits/physics-3d/scripts/test-frozen-statics.mjs +434 -0
  560. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  561. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  562. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  563. package/kits/physics-3d/scripts/test-near-shadows.mjs +5 -2
  564. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +2001 -0
  565. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +582 -0
  566. package/kits/physics-3d/scripts/test-orbit-shot.mjs +657 -0
  567. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  568. package/kits/physics-3d/scripts/test-rapier-gz.mjs +106 -0
  569. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  570. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  571. package/kits/physics-3d/scripts/test-square-first.mjs +921 -0
  572. package/kits/physics-3d/scripts/test-static-actors.mjs +10 -1
  573. package/kits/physics-3d/scripts/test-static-physics.mjs +4 -1
  574. package/kits/physics-3d/scripts/test-static-scenery.mjs +2174 -0
  575. package/kits/physics-3d/scripts/test-steady-hover.mjs +7 -2
  576. package/kits/physics-3d/scripts/test-still-shadows.mjs +477 -0
  577. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  578. package/kits/physics-3d/systems/physics3d.js +419 -9
  579. package/kits/real-time/castle.json +2 -2
  580. package/kits/real-time/code/client/connection.js +33 -10
  581. package/kits/real-time/code/client/gameHooks.js +2 -0
  582. package/kits/real-time/code/client/joinOverlay.js +9 -4
  583. package/kits/real-time/code/server/gameHooks.js +7 -0
  584. package/kits/real-time/code/server/session.js +102 -22
  585. package/kits/real-time/package-lock.json +1 -1
  586. package/package.json +2 -2
  587. package/dist/shell/assets/index-Cf61cNfT.css +0 -1
@@ -10,24 +10,54 @@
10
10
  // `worldCharacters`: the session callbacks a place's NPCs answer in a world
11
11
  // that carries shared characters (`npcs.js`).
12
12
 
13
- import { readScene } from '@imports/castle.multiplayer-3d/code/server/sceneBodies.js';
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';
16
+ import * as Cells from './cells.js';
14
17
  import * as Actors from './actors.js';
15
18
  import * as History from './history.js';
19
+ import * as Friends from './friendsAmong.js';
20
+ import { friendBests } from './friendBests.js';
16
21
  import * as Blocks from './blocks.js';
17
22
  import * as Cabinets from './cabinets.js';
18
23
  import * as Grab from './grab.js';
24
+ import * as Act from './act.js';
19
25
  import * as Idle from './idle.js';
26
+ import * as Decor from './decor.js';
27
+ import * as Actions from './actions.js';
28
+ import * as Invites from './invites.js';
29
+ import * as Companion from './companion.js';
30
+ import * as Ask from './ask.js';
31
+ import * as Menu from './menu.js';
32
+ import * as Cues from './cues.js';
33
+ import * as Shot from './shot.js';
34
+ import * as Vis from './vis.js';
35
+ import * as Yours from './yours.js';
20
36
  import * as Manifest from './manifest.js';
21
37
  import { setLabel, wireLabel } from './labels.js';
22
38
  import { makeNpcs } from './npcs.js';
23
39
  import * as Party from './party.js';
40
+ import { bodySize, standingY } from './standing.js';
24
41
  import * as Place from './place.js';
25
42
  import * as Say from './say.js';
43
+ import * as Ballot from './ballot.js';
26
44
  import * as Wear from './wear.js';
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';
27
53
  import { doorPoint } from '../client/doorFrame.js';
28
54
 
29
55
  // How many avatars the kit offers (`blueprints/avatar-<n>.scene`); contract §11.
30
- export const AVATARS = 4;
56
+ // Sixteen since v1.51: a place on an older kit takes 0-3 and draws anyone
57
+ // wearing another as 0.
58
+ export const AVATARS = 16;
59
+ // The avatars every client can draw, a town's saved before v1.51 included.
60
+ const OLD_AVATARS = 4;
31
61
 
32
62
  // Players sent together by one `hub.go` arrive together: the first arrival of a
33
63
  // group waits this long for the rest before the group is placed.
@@ -47,10 +77,21 @@ const PAD_REFRESH_MS = 20000;
47
77
  const SHUT_HOLD_MS = 60000;
48
78
  // How often a place re-reads its doors' boards.
49
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;
50
83
  // The newest result of the game a player came back from counts as this trip's
51
84
  // for this long: the longest visit (maxDurationSec 1800) and some slack.
52
85
  const RESULT_FRESH_MS = 35 * 60 * 1000;
53
- const MAX_BOARD_DOORS = 16;
86
+ // Ghost refuses more than 16 doors per read (ghost-server
87
+ // src/utils/cauldronHubResults.ts: HUB_READ_MAX_DOORS). A door board has at
88
+ // most 10 top rows and 3 last-event winners (a few KB), so 16 stay well
89
+ // below the host channel's roughly 384 KB frame.
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;
54
95
  // Cabinet boards in one read: each may be 44 KB, and a read answers in one
55
96
  // frame of the host's channel (about 384 KB).
56
97
  const CABINET_BOARDS_PER_READ = 6;
@@ -60,6 +101,9 @@ const CABINET_BOARDS_PER_READ = 6;
60
101
  const JUMP_OUT = 7;
61
102
  const JUMP_SPREAD = 2;
62
103
  const JUMP_EVERY_MS = 1000;
104
+ // "Stuck?" (v1.33, a deck with `hub.stuck`): how often one player may be put
105
+ // back at the arrival for the asking.
106
+ const UNSTICK_EVERY_MS = 5000;
63
107
  // A player a client already sees counts as this much nearer when the nearest
64
108
  // are picked, so two players at about the same distance do not swap in and
65
109
  // out of its set every tick.
@@ -79,13 +123,23 @@ const POSE_HZ = 10;
79
123
  // tick and memory, read by the host's log stream (the only per-session
80
124
  // numbers a production layer has).
81
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;
82
131
  const USER_ID = /^\d{1,20}$/;
83
132
 
84
133
  // `layer(castleJson, deckHooks, placeHooks)`: the hooks object for one session
85
134
  // process. `placeHooks` maps place id -> that place's own hooks module.
86
- // A scene with no ground catches a fallen player this far down when its place
87
- // names no `fallY`: above the world's floor (-30), below any pit worth having.
88
- 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;
139
+
140
+ function hasHook(deckHooks, placeHooks, name) {
141
+ return typeof deckHooks?.[name] === 'function' || Object.values(placeHooks ?? {}).some((hooks) => typeof hooks?.[name] === 'function');
142
+ }
89
143
 
90
144
  // `engine` is multiplayer-3d's world (`createBody`, `removeActor`), which
91
145
  // builds and drops the bodies of actors a game spawns (`hub.spawn`).
@@ -100,32 +154,170 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
100
154
  }
101
155
  return { persist: false, sceneFor: () => undefined, worldCharacters: {} };
102
156
  }
103
- 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;
178
+ // v1.53: the deck's own earned items and id, for an unlock kept in this
179
+ // session only (a guest, the dev serve).
180
+ h.unlocks = manifest.unlocks ?? null;
181
+ h.deckId = savedDeckId ?? 'local';
104
182
  h.devDecks = devDecks && typeof devDecks === 'object' ? devDecks : null;
105
183
  h.engine = engine;
106
184
  const tickRate = Number.isFinite(castleJson?.server?.tickRate) && castleJson.server.tickRate > 0 ? castleJson.server.tickRate : 20;
107
185
  const poseEvery = Math.max(1, Math.round(tickRate / POSE_HZ));
108
186
 
109
187
  return {
188
+ // Decor places own their actors on the server. Keyless decks add no hook.
189
+ ...(Object.values(manifest.places).some((place) => place.decor)
190
+ ? { allowClientGone: () => !h.place?.decor }
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
+ } : {}),
110
209
  persist: false,
111
210
  poseEvery,
112
211
  poseIntervalMs: Math.round((poseEvery * 1000) / tickRate),
113
212
 
114
213
  sceneFor(session) {
214
+ const previousSession = h.session;
115
215
  h.session = session;
116
216
  const { id, source } = Place.resolvePlace(session, manifest);
217
+ if (h.manifest.act === true && (h.placeId !== id || previousSession !== session)) {delete h.actPlayers;}
117
218
  h.placeId = id;
118
219
  h.place = manifest.places[id];
119
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
+ }
233
+ if (typeof h.hooks.resume === 'function') {
234
+ h.resumeDeparting ??= new Set();
235
+ }
236
+ if (h.place.resumeKeep === true || h.place.resumePose === true || houseResume(h) || pinnedResume(h)) {
237
+ h.resumeKept ??= new Map();
238
+ h.resumeDeparting ??= new Set();
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; }
247
+ if (h.place.decor) {
248
+ h.ctx.decor = Decor.api(h);
249
+ } else {
250
+ delete h.ctx.decor;
251
+ }
252
+ if (h.place.actions === true) {
253
+ h.ctx.actions = (playerId, items) => Actions.set(h, playerId, items);
254
+ } else {
255
+ delete h.ctx.actions;
256
+ }
257
+ if (h.place.invite === true) {h.ctx.invite = (playerId, options) => Invites.request(h, playerId, options);}
258
+ else {delete h.ctx.invite;}
259
+ if (h.place.companion === true) {
260
+ h.ctx.companion = (playerId, spec) => Companion.set(h, playerId, spec);
261
+ h.ctx.companionDress = true;
262
+ h.ctx.companionPose = true;
263
+ } else {
264
+ delete h.ctx.companion;
265
+ delete h.ctx.companionDress;
266
+ delete h.ctx.companionPose;
267
+ }
268
+ if (h.place.ask === true) {
269
+ h.ctx.ask = (playerId, spec) => Ask.set(h, playerId, spec);
270
+ } else {
271
+ delete h.ctx.ask;
272
+ }
273
+ if (h.place.menu === true) {
274
+ h.ctx.menu = (playerId, spec) => Menu.set(h, playerId, spec);
275
+ } else {
276
+ delete h.ctx.menu;
277
+ }
120
278
  h.noGround = sceneGround(h.place.scene)?.none === true;
121
- h.fallY = h.place.fallY ?? (h.noGround ? NO_GROUND_FALL_Y : null);
279
+ h.fallY = h.place.fallY ?? DEFAULT_FALL_Y;
122
280
  console.log(`[hub] place ${id} (${source}): ${h.place.scene}`);
123
281
  return h.place.scene;
124
282
  },
125
283
 
284
+ // ready runs before real-time's admit -> addPlayer, including the first
285
+ // tick of a fresh session. Until then no actor-based height is provable.
286
+ standingY(sim, at) {
287
+ return h.sim === sim && h.place ? standingY(h, at) : at.y;
288
+ },
289
+
126
290
  ready(sim) {
127
291
  h.sim = sim;
128
- h.actors = readScene(sim.scenePath);
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
+ }
306
+ if (h.place.interest === 'cells') {
307
+ let result;
308
+ try {
309
+ result = Cells.readCells({ cells: Scene.sceneCells?.(sim.scenePath) });
310
+ } catch {
311
+ result = { table: null, reason: 'could not be read' };
312
+ }
313
+ h.cells = result.table;
314
+ if (!h.cells) {
315
+ console.warn(`[hub] interest: cells table ${result.reason}`);
316
+ h.place = { ...h.place, nearestPlayers: h.place.nearestPlayersFallback };
317
+ delete h.place.interest;
318
+ delete h.place.nearestPlayersFallback;
319
+ }
320
+ }
129
321
  h.npcs.ready();
130
322
  h.hooks.ready?.(h.ctx);
131
323
  },
@@ -134,10 +326,49 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
134
326
  // read when the player gets a body.
135
327
  message(session, player, data) {
136
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
+ }
336
+ if (data?.k === 'hub-cap' && h.cells) {
337
+ if (Number.isInteger(data.n)) {
338
+ const now = Date.now();
339
+ const recent = (h.capAt.get(player.playerId) ?? []).filter((at) => now - at < 1000);
340
+ if (recent.length < 4) {
341
+ h.capAt.set(player.playerId, [...recent, now]);
342
+ h.caps.set(player.playerId, Math.max(1, Math.min(h.place.nearestPlayers, data.n)));
343
+ }
344
+ }
345
+ return;
346
+ }
347
+ // v1.91: opt-in, authenticated sender only. Client time is metadata,
348
+ // never a server clock or a way to name another player.
349
+ if (h.place?.visibility === true && data?.k === 'hub-visibility') {
350
+ const entry = h.players.get(player?.playerId);
351
+ if (!entry ||
352
+ !session.players.some((p) => p.playerId === player.playerId) ||
353
+ typeof data.visible !== 'boolean' || !Number.isFinite(data.at) || data.at < 0) {
354
+ return;
355
+ }
356
+ if (entry.visibility && (data.at < entry.visibility.at || data.visible === entry.visibility.visible)) {
357
+ return;
358
+ }
359
+ entry.visibility = { visible: data.visible, at: data.at };
360
+ entry.visibilityPending = true;
361
+ notifyVisibility(h, player.playerId);
362
+ return;
363
+ }
137
364
  if (data?.k === 'hub-hello') {
365
+ LoadAbandon.hello(h, player?.playerId);
138
366
  hello(h, player, data);
139
367
  return;
140
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; }
141
372
  if (data?.k === 'hub-shut') {
142
373
  doorShut(h, player, data);
143
374
  return;
@@ -146,10 +377,20 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
146
377
  doorJump(h, player, data);
147
378
  return;
148
379
  }
380
+ if (data?.k === 'hub-house-visit') {
381
+ houseVisit(h, player, data);
382
+ return;
383
+ }
149
384
  if (data?.k === 'hub-where') {
150
385
  whereAsk(h, player, data);
151
386
  return;
152
387
  }
388
+ // v1.33: only a deck with `hub.stuck` knows the message; in any other
389
+ // it goes on to the place's own hooks, as it always did.
390
+ if (h.manifest.stuck && data?.k === 'hub-unstick') {
391
+ (data.ask === true ? unstickAsk : unstick)(h, player);
392
+ return;
393
+ }
153
394
  if (data?.k === 'hub-goto') {
154
395
  goTo(h, player, data);
155
396
  return;
@@ -162,6 +403,12 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
162
403
  Party.message(partyDeps(h), player, data);
163
404
  return;
164
405
  }
406
+ // v1.68: only a place that declares `ballot` knows the message; in any
407
+ // other it goes on to the place's own hooks, as it always did.
408
+ if (h.place?.ballot && data?.k === 'hub-ballot') {
409
+ Ballot.message(h, player, data, h.place.ballot.lines);
410
+ return;
411
+ }
165
412
  if (data?.k === 'hub-dev-classic') {
166
413
  // The dev serve's stand-in for ghost's classic boards (`cabinets.js`).
167
414
  if (h.sim && isDevSession(h)) {
@@ -169,6 +416,27 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
169
416
  }
170
417
  return;
171
418
  }
419
+ if (h.place.decor && data?.k === 'decor') {
420
+ Decor.message(h, player?.playerId, data);
421
+ return;
422
+ }
423
+ if (h.place.actions === true && data?.k === 'hub-action') {
424
+ Actions.message(h, player?.playerId, data);
425
+ return;
426
+ }
427
+ if (h.place.ask === true && data?.k === 'hub-answer') {
428
+ Ask.message(h, player?.playerId, data);
429
+ return;
430
+ }
431
+ if (h.place.menu === true && data?.k === 'hub-menu-pick') {
432
+ Menu.message(h, player?.playerId, data);
433
+ return;
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;}
172
440
  if (data?.k === 'hub-grab') {
173
441
  Grab.message(h, player?.playerId, data);
174
442
  return;
@@ -198,12 +466,19 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
198
466
  const dt = h.lastPlaceAt === null ? 0 : Math.min(0.25, (sim.timeMs - h.lastPlaceAt) / 1000);
199
467
  h.lastPlaceAt = sim.timeMs;
200
468
  reconcile(h);
469
+ Friends.tick(h, friendUserIdOf);
201
470
  // v1.28: a try-on on a player who went before saying hello goes too.
202
471
  if (Wear.tryOnUsed(h)) {
203
472
  Wear.pruneTries(h);
204
473
  }
474
+ // v1.53, v1.70: likewise wearable or home ownership before a hello.
475
+ if (Earned.needsPrune(h)) {
476
+ Earned.prune(h);
477
+ }
478
+ retryProgress(h);
205
479
  readResults(h);
206
480
  arrivals(h);
481
+ if (h.place.visibility === true) {notifyVisibility(h);}
207
482
  enforceHolds(h);
208
483
  enforceSettle(h);
209
484
  Idle.tick(h);
@@ -213,26 +488,63 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
213
488
  Actors.dropLostSpawns(h, h.engine);
214
489
  Actors.driveMoves(h);
215
490
  h.npcs.place(dt);
491
+ if (h.manifest.act === true) {Act.tick(h);}
216
492
  Actors.flushHandovers(h, handovers);
217
493
  },
218
494
 
219
495
  step(sim, handovers) {
220
496
  const dt = h.lastStepAt === null ? 0 : (sim.timeMs - h.lastStepAt) / 1000;
221
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);
222
506
  h.hooks.step?.(h.ctx, dt);
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
+ }
520
+ // v1.61: no renewal callback exists unless a player holds a shot.
521
+ h.renewShots?.();
223
522
  Actors.flushTints(h);
224
523
  sendHudOverrides(h);
524
+ // v1.68: nothing in a place that has never shown a choice card.
525
+ if (h.ballotState) {
526
+ Ballot.send(h, ballotDeps(h));
527
+ }
225
528
  Actors.applyTunes(h, h.engine?.maxSpeed?.() ?? 12);
226
529
  sendLabelOverrides(h);
530
+ Vis.send(h);
227
531
  sendAvatarOverrides(h);
532
+ if (h.manifest.yourGames) {
533
+ Yours.send(h, listedDoors(h), membersOf);
534
+ }
228
535
  Party.tick(partyDeps(h));
229
536
  Wear.sendOverrides(h, blockedPairs(h));
537
+ // v1.53 earned items: nothing in a place where nobody shows one.
538
+ if (Earned.used(h)) {
539
+ Earned.sendOverrides(h, blockedPairs(h));
540
+ }
230
541
  // v1.28 `hub.tryOn`: nothing in a place that never calls it.
231
542
  if (Wear.tryOnUsed(h)) {
232
543
  Wear.sendTryOverrides(h, blockedPairs(h));
233
544
  }
234
545
  // Cabinet cards (v1.7): nothing in a place with no classic door.
235
546
  Cabinets.send(h, (playerId) => namesOf(h, blockedPairs(h)?.get(playerId) ?? []));
547
+ notifyResumes(h, false, resumeDeferred);
236
548
  Actors.flushHandovers(h, handovers);
237
549
  },
238
550
 
@@ -243,11 +555,42 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
243
555
  // (`blocks.js`) before the nearest are picked, so a hidden player never
244
556
  // takes one of a client's `nearestPlayers` places.
245
557
  interest(sim, known) {
558
+ if (h.padOccupancy) {
559
+ h.padOccupancy.known = known;
560
+ h.padOccupancy.knownAt = sim.timeMs;
561
+ }
246
562
  const pairs = blockedPairs(h);
247
563
  const hidden = pairs ? (viewer, other) => Boolean(pairs.get(viewer)?.has(other)) : null;
564
+ if (h.cells) {
565
+ return Blocks.withoutHidden(cellPlayers(h, sim, known, hidden), pairs);
566
+ }
248
567
  return Blocks.withoutHidden(nearestPlayers(sim, known, h.place.nearestPlayers, hidden), pairs);
249
568
  },
250
569
 
570
+ ...(manifest.places[Manifest.MAIN_PLACE].interest === 'cells' ? {
571
+ objectInterest(sim) {
572
+ if (!h.cells) {
573
+ return null;
574
+ }
575
+ const views = playerCells(h, sim);
576
+ const located = new Map();
577
+ for (const [id, object] of sim.objects) {
578
+ const at = object.body?.translation?.() ?? object.at;
579
+ const cell = Cells.cellAt(h.cells, at?.x, at?.z, h.objectCells.get(id));
580
+ h.objectCells.set(id, cell);
581
+ located.set(id, cell);
582
+ }
583
+ for (const id of h.objectCells.keys()) {
584
+ if (!sim.objects.has(id)) {
585
+ h.objectCells.delete(id);
586
+ }
587
+ }
588
+ return new Map([...views].map(([viewer, { visible }]) => [viewer, new Set([...located].filter(([id, cell]) =>
589
+ visible === null || cell === null || visible.has(cell) || sim.objects.get(id).owner === viewer || h.grabs.get(viewer) === id,
590
+ ).map(([id]) => id))]));
591
+ },
592
+ } : {}),
593
+
251
594
  shutdown: () => shutdown(h),
252
595
 
253
596
  join() {
@@ -256,7 +599,14 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
256
599
  // under it rather than past the world's floor, where no pose is read.
257
600
  hubPlace: { ...Manifest.publicPlace(h.placeId, h.place), fallY: h.fallY },
258
601
  hubAv: avatars(h, blockedPairs(h)),
602
+ ...(h.place.anonymousEntry === true ? { hubGuests: guests(h, blockedPairs(h)) } : {}),
603
+ // v1.51, only while someone here wears one of the twelve after the first four.
604
+ ...avatars2ForJoin(h),
605
+ ...avatarColorsForJoin(h),
259
606
  ...wearingForJoin(h),
607
+ ...(h.place.companion === true && h.companionUsed ? { hubGlow: Companion.glowOf(h) } : {}),
608
+ // v1.53, only once someone here shows an earned item.
609
+ ...(h.earned.size > 0 ? earnedForJoin(h) : {}),
260
610
  hud: hudForAll(h),
261
611
  hidden: [...h.hidden],
262
612
  held: [...h.held.keys()],
@@ -272,13 +622,27 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
272
622
  ...(h.keptFor.size > 0 ? { hubKept: Grab.keptOf(h) } : {}),
273
623
  // v1.28, only while the place shows a try-on on someone.
274
624
  ...(h.trying.size > 0 ? tryingForJoin(h) : {}),
625
+ // v1.33, only a town of a deck with `hub.stuck`.
626
+ ...(stuckHere(h) ? { hubStuck: { to: arrivalName(h), ...(hasUnstick(h) ? { hook: true } : {}) } } : {}),
275
627
  };
276
628
  },
277
629
 
278
630
  delta() {
279
631
  const out = {};
280
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
+ }
636
+ latchAvatars2(h, out);
637
+ latchAvatarColors(h, out);
281
638
  latchWearing(h, out);
639
+ if (h.place.companion === true && h.companionUsed) {
640
+ latch(h, 'hubGlow', Companion.glowOf(h), out);
641
+ }
642
+ // v1.53: nothing until someone shows an earned item, then each change.
643
+ if (h.earned.size > 0 || h.sent.has('hubEarned')) {
644
+ latchEarned(h, out);
645
+ }
282
646
  latch(h, 'hud', hudForAll(h), out);
283
647
  latch(h, 'hidden', [...h.hidden], out);
284
648
  latch(h, 'held', [...h.held.keys()], out);
@@ -326,6 +690,18 @@ export function layer(castleJson, deckHooks, placeHooks, sceneExists, sceneGroun
326
690
  }
327
691
  await h.npcs.onRead(request);
328
692
  },
693
+ // v1.66: only a deck with an `npcTool` hook listens for lookups.
694
+ ...(hasHook(deckHooks, placeHooks, 'npcTool')
695
+ ? {
696
+ async onWorldCharacterTool(request, session) {
697
+ h.session ??= session;
698
+ if (!h.sim) {
699
+ return { error: 'not ready' };
700
+ }
701
+ return await h.npcs.onTool(request);
702
+ },
703
+ }
704
+ : {}),
329
705
  },
330
706
  };
331
707
  }
@@ -402,9 +778,18 @@ function logStats(h) {
402
778
  Object.assign(s, { at: now, cpu: process.cpuUsage(), ticks: 0 });
403
779
  }
404
780
 
405
- function newState(manifest) {
781
+ function newState(manifest, savedDeckId) {
406
782
  const h = {
407
783
  manifest,
784
+ savedDeckId,
785
+ cells: null,
786
+ cellTick: null,
787
+ cellViews: null,
788
+ playerCells: new Map(),
789
+ objectCells: new Map(),
790
+ caps: new Map(),
791
+ capAt: new Map(),
792
+ sentMaps: new Map(),
408
793
  placeId: Manifest.MAIN_PLACE,
409
794
  place: manifest.places[Manifest.MAIN_PLACE],
410
795
  hooks: {},
@@ -413,6 +798,8 @@ function newState(manifest) {
413
798
  actors: [],
414
799
  lastStepAt: null,
415
800
  lastPlaceAt: null,
801
+ // v1.141 observed progress, null until a place asks (`observe.js`)
802
+ observe: null,
416
803
  // the height below which a player has fallen, or null (`catchFalls`)
417
804
  fallY: null,
418
805
  // playerId -> when they last jumped to a door or to a player
@@ -426,6 +813,12 @@ function newState(manifest) {
426
813
  // playerId -> { avatar, clientAvatar, from, fromDeckId, party, carry, read,
427
814
  // hello, arrived, arrivedAt, helloAt, result, ended }
428
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(),
429
822
  // door id -> the gathering pad sent to ghost: { padId, json, at }
430
823
  pads: new Map(),
431
824
  // playerId -> { door, at }: the door that last stayed shut for them
@@ -437,12 +830,22 @@ function newState(manifest) {
437
830
  // `${actorId}|${doorId}` -> the door's object `doors()` hands out
438
831
  doorObjects: new Map(),
439
832
  boardsAt: 0,
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,
440
841
  // `${op}:${code}` refusals already logged
441
842
  refusals: new Set(),
442
843
  hud: null,
443
844
  // playerId -> spec, and what was last sent of each
444
845
  hudMe: new Map(),
445
846
  sentHudMe: new Map(),
847
+ // v1.52: private leaving lines, never part of a snapshot.
848
+ leaving: new Map(),
446
849
  hidden: new Set(),
447
850
  // playerId -> { at, facing }
448
851
  held: new Map(),
@@ -464,6 +867,8 @@ function newState(manifest) {
464
867
  ...Grab.newGrabState(),
465
868
  // what players wear on their avatars (`wear.js`, v1.4)
466
869
  ...Wear.newWearState(),
870
+ // earned items players show (`earned.js`, v1.53)
871
+ ...Earned.newEarnedState(),
467
872
  // emotes, seats and sounds (`idle.js`, v1.6)
468
873
  ...Idle.newIdleState(),
469
874
  // arcade cabinets' cards (`cabinets.js`, v1.7)
@@ -474,6 +879,10 @@ function newState(manifest) {
474
879
  ...Say.newSayState(),
475
880
  };
476
881
  h.ctx = makeContext(h);
882
+ // v1.68: `hub.ballot` only in a deck that declares the card in some place.
883
+ if (manifest.ballot) {
884
+ h.ctx.ballot = (playerIds, spec) => Ballot.ballot(h, playerIds, spec);
885
+ }
477
886
  h.npcLabel = (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, true);
478
887
  h.blockedPairs = () => blockedPairs(h);
479
888
  h.npcs = makeNpcs(h);
@@ -483,25 +892,51 @@ function newState(manifest) {
483
892
  // The `hub` every deck hook is handed.
484
893
  function makeContext(h) {
485
894
  return {
895
+ get push() {
896
+ return h.place?.push?.version === 1 ? h.session?.hub?.push : undefined;
897
+ },
486
898
  get session() {
487
899
  return h.session;
488
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
+ },
489
912
  get sim() {
490
913
  return h.sim;
491
914
  },
915
+ get owner() {
916
+ const owner = h.session?.hub?.owner;
917
+ if (typeof owner === 'string' && owner.length > 0) {
918
+ return owner;
919
+ }
920
+ return !platformHub(h) && isDevSession(h) && h.manifest.house?.devOwner === 'first' ? h.devOwner ?? null : null;
921
+ },
492
922
  get place() {
493
923
  return { id: h.placeId, title: h.place.title, scene: h.place.scene, manifest: h.place };
494
924
  },
495
925
  get now() {
496
926
  return h.sim?.timeMs ?? 0;
497
927
  },
928
+ goalPositions: true,
498
929
  players() {
499
930
  const out = [];
500
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;}
501
935
  out.push({
502
936
  playerId,
503
937
  username: usernameOf(h, playerId),
504
938
  userId: userIdOf(h, playerId),
939
+ ...(h.place.anonymousEntry === true ? { identityUserId: identityUserIdOf(h, playerId) } : {}),
505
940
  at: { ...body.at },
506
941
  arrivedAt: h.players.get(playerId)?.arrivedAt ?? null,
507
942
  });
@@ -512,7 +947,19 @@ function makeContext(h) {
512
947
  return h.actors.filter((actor) => actor.components[name]).map((actor) => Actors.describe(actor, name));
513
948
  },
514
949
  username: (playerId) => usernameOf(h, playerId),
515
- 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),
516
963
  hold(playerId, at, facingDeg) {
517
964
  const body = h.sim?.players.get(playerId);
518
965
  if (!body) {
@@ -537,7 +984,10 @@ function makeContext(h) {
537
984
  h.hudMe.delete(playerId);
538
985
  }
539
986
  },
540
- hide(actorId) {
987
+ hide(actorId, options) {
988
+ if (options !== undefined) {
989
+ return Vis.set(h, actorId, options, true);
990
+ }
541
991
  if (!isSceneActor(h, actorId)) {
542
992
  return;
543
993
  }
@@ -551,7 +1001,10 @@ function makeContext(h) {
551
1001
  Grab.unkeep(h, actorId);
552
1002
  h.sim?.bodies.get(actorId)?.setEnabled(false);
553
1003
  },
554
- show(actorId) {
1004
+ show(actorId, options) {
1005
+ if (options !== undefined) {
1006
+ return Vis.set(h, actorId, options, false);
1007
+ }
555
1008
  if (!h.hidden.delete(actorId)) {
556
1009
  return;
557
1010
  }
@@ -560,9 +1013,26 @@ function makeContext(h) {
560
1013
  move: (actorId, to, options) => Actors.move(h, actorId, to, options),
561
1014
  tint: (actorId, color) => Actors.tint(h, actorId, color),
562
1015
  mark: (playerId, spec) => Actors.mark(h, playerId, spec),
1016
+ leaving: (playerId, text) => leaving(h, playerId, text),
563
1017
  results: (playerId) => History.results(h, playerId),
1018
+ ...(h.place.freshFriends === true ? { freshFriends: true } : {}),
1019
+ friendsAmong: (playerId, userIds) => Friends.friendsAmong(h, playerId, userIds, friendUserIdOf),
1020
+ friendBests: (key, options) => friendBests(h, key, options, userIdOf),
564
1021
  wear: (playerId, spec) => wear(h, playerId, spec),
565
1022
  tryOn: (playerId, spec) => Wear.tryOn(h, playerId, spec),
1023
+ wearing: (playerId) => Wear.wearing(h, playerId),
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
+ },
1033
+ wearEarned: (playerId, choice) => Earned.wearEarned(h, playerId, choice, earnedDeps(h, playerId, 'wearEarned')),
1034
+ unlocksOf: (userIds) => Earned.unlocksOf(platformHub(h), userIds, (err) => refused(h, 'unlocks', err), h),
1035
+ earned: (playerId) => Earned.earnedOf(h, playerId),
566
1036
  tune: (playerId, spec) => Actors.tune(h, playerId, spec),
567
1037
  spawn: (fromActorId, at) => Actors.spawn(h, fromActorId, at, h.engine),
568
1038
  pose: (actorId) => Actors.pose(h, actorId),
@@ -573,11 +1043,15 @@ function makeContext(h) {
573
1043
  label: (actorId, text, options) => setLabel(h, isSceneActor(h, actorId) ? actorId : null, text, options, false),
574
1044
  npc: (actorId) => h.npcs.handle(actorId),
575
1045
  npcs: () => h.npcs.list(),
1046
+ preferNpc: (playerId, npcId) => h.npcs.prefer(playerId, npcId),
576
1047
  result: (playerId, value) => report(h, playerId, value),
577
1048
  drop: (playerId) => Grab.drop(h, playerId),
578
1049
  emote: (playerId, id) => Idle.emote(h, playerId, id),
579
1050
  seat: (playerId) => Idle.seat(h, playerId),
580
1051
  sound: (actorId, file, options) => Idle.sound(h, actorId, file, options),
1052
+ danceIdle: (actorId, options) => Idle.danceIdle(h, actorId, options),
1053
+ cue: (target, name) => Cues.cue(h, target, name),
1054
+ shot: (playerId, value) => Shot.shot(h, playerId, value),
581
1055
  holding: (playerId) => Grab.holding(h, playerId),
582
1056
  keepFor: (actorId, playerId) => Grab.keepFor(h, actorId, playerId),
583
1057
  end(playerIds) {
@@ -592,6 +1066,11 @@ function makeContext(h) {
592
1066
  // v1.16: the other members of a player's party who are in this place now.
593
1067
  partyOf: (playerId) => Party.matesHere(h, playerId),
594
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
+ } : {}),
595
1074
  doors: () => doors(h),
596
1075
  send: (playerId, data) => h.session?.send(playerId, data),
597
1076
  broadcast: (data) => h.session?.broadcast(data),
@@ -607,51 +1086,511 @@ function platformHub(h) {
607
1086
  // A client's hello: the avatar it wears, the door it came through, how many
608
1087
  // came with it, and what it carries back from a game (a town reads that). Where
609
1088
  // the host has hub ops, the door is ghost's arrival and the result and avatar
610
- // are read from ghost (`readResults`); the client's word is not used for them.
611
- function hello(h, player, data) {
612
- const clientAvatar = Number.isInteger(data.avatar) && data.avatar >= 0 && data.avatar < AVATARS ? data.avatar : 0;
1089
+ // are read from ghost (`readResults`). The hello's avatar and colour are
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
+
1109
+ function hello(h, player, data, synthetic = false) {
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;
613
1120
  const party = Number.isInteger(data.party) && data.party >= 1 && data.party <= 24 ? data.party : 1;
614
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);
1140
+ // A player this place let go whose connection came back still holding what
1141
+ // it was sent (`greetLate`): the client's own resume hello or the place's
1142
+ // late greet for it, whichever comes first, arrives them once and marks that
1143
+ // stale. A game keeps the old way, so it takes no resume hello (its round
1144
+ // and result belong to the visit that left), unless its place says
1145
+ // `resume: true` (v1.72): then it is arrived again like any place, and the
1146
+ // visit goes on. A plain hello is a fresh client (a reload), which holds
1147
+ // nothing.
1148
+ //
1149
+ // v1.72 resume invariants, every one only in a place with `resume: true`
1150
+ // (`resumes`; without the key none of this runs and nothing is stored):
1151
+ // I1 one result per visit, whatever the order of leave, report and
1152
+ // resume: `forget` keeps the result after the leave hook ran (which
1153
+ // may report it), and the re-arrived entry gets it back;
1154
+ // I2 the visit's deadline is set once, at its first arrival (`visitAt`),
1155
+ // and kept across resumes, so drops never extend a visit;
1156
+ // I3 restored state with a packet is sent again on resume: the end
1157
+ // (`hub-end` with `again`), and the HUD, shot and the rest (`staleSent`
1158
+ // and the place's own arrive);
1159
+ // I4 provenance (`from`, `fromDeckId`) is written once per visit.
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));
1172
+ const resumes = h.place?.result ? h.place.resume === true : false;
1173
+ if (back && h.place?.result && !resumes) {
1174
+ return;
1175
+ }
1176
+ // v1.72: what a resume place's forgotten record kept of the visit that left.
1177
+ const last = back && resumes ? h.forgotten.get(player.playerId) : null;
1178
+ h.forgotten?.delete(player.playerId);
1179
+ h.noHelloSince?.delete(player.playerId);
1180
+ if (back) {
1181
+ staleSent(h, player.playerId);
1182
+ } else if (resumes && known?.hello && data.resume === true) {
1183
+ // v1.72: a game that resumes, still holding the player: the drop may have
1184
+ // lost what it sent them, so it all goes again (the leaving line is
1185
+ // re-sent by joinedAfresh below).
1186
+ staleSent(h, player.playerId, false);
1187
+ }
615
1188
  const hub = platformHub(h);
616
1189
  const arrival = hub ? hub.arrival(player.playerId) : null;
617
- const from = hub ? arrival?.doorId ?? null : typeof data.from === 'string' && data.from.length <= 32 ? data.from : null;
1190
+ // A resume place's re-arrived player keeps the door they first came by
1191
+ // when the platform no longer says one (its arrival goes with the leave).
1192
+ const said = hub ? arrival?.doorId ?? null : typeof data.from === 'string' && data.from.length <= 32 ? data.from : null;
1193
+ // I4: a resume place keeps the visit's first door, whatever a later hello says.
1194
+ // A saved none is kept too: only a key never saved takes what is said now.
1195
+ const keep = (key, now) => {
1196
+ if (!resumes) {
1197
+ return now;
1198
+ }
1199
+ const was = known ?? last;
1200
+ return was && Object.hasOwn(was, key) ? was[key] ?? null : now;
1201
+ };
1202
+ const from = keep('from', said);
1203
+ const fromDeckId = keep('fromDeckId', arrival?.fromDeckId ?? null);
1204
+ if (keepSignUpChoice && !signedUp && known) {
1205
+ clientAvatar = known.clientAvatar;
1206
+ clientColor = known.clientColor;
1207
+ }
618
1208
  // A later hello with the same choice keeps the platform avatar a read found;
619
1209
  // a new choice wins, and outdates any read in flight (`avatarRev`).
620
- const same = known?.hello && known.clientAvatar === clientAvatar;
1210
+ const same = known?.hello && known.clientAvatar === clientAvatar && !(h.anonymousEntry && data.again === true);
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;
1218
+ // A stale ballot card still waiting to be cleared survives a repeated
1219
+ // resume hello, whose joinedAfresh below would otherwise drop the mark.
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
+ }
621
1239
  // A hello that is not an avatar change is a client that joined afresh: it
622
1240
  // holds none of the cabinet cards it was sent (v1.7).
623
1241
  if (data.again !== true) {
1242
+ replaySent(h, player.playerId, data.resume === true);
1243
+ if (h.manifest.act === true) {Act.replay(h, player.playerId);}
1244
+ h.npcs.replayPreferred(player.playerId, data.resume === true);
1245
+ Shot.joinedAfresh(h, player.playerId);
1246
+ Vis.joinedAfresh(h, player.playerId, userIdOf(h, player.playerId));
1247
+ Decor.joinedAfresh(h, player.playerId);
1248
+ if (h.place.actions === true) {
1249
+ Actions.joinedAfresh(h, player.playerId);
1250
+ }
1251
+ if (h.place.companion === true) {
1252
+ Companion.joinedAfresh(h, player.playerId, userIdOf(h, player.playerId));
1253
+ }
1254
+ if (h.place.ask === true) {
1255
+ Ask.joinedAfresh(h, player.playerId);
1256
+ }
1257
+ if (h.place.menu === true) {
1258
+ Menu.joinedAfresh(h, player.playerId);
1259
+ }
1260
+ if (h.ballotState) {
1261
+ Ballot.joinedAfresh(h, player.playerId);
1262
+ }
624
1263
  Cabinets.forget(h, player.playerId);
1264
+ Friends.resend(h, player.playerId);
625
1265
  // v1.28: nothing in a place that never sent a try-on to one player alone.
626
1266
  Wear.joinedAfresh(h, player.playerId);
1267
+ // v1.53: likewise its earned items alone, only where someone has one.
1268
+ if (Earned.used(h)) {
1269
+ Earned.joinedAfresh(h, player.playerId);
1270
+ }
1271
+ // A fresh client with a retained id has none of its private leaving line.
1272
+ if (h.leaving.has(player.playerId)) {
1273
+ h.session?.send(player.playerId, { k: 'hub-leaving', text: h.leaving.get(player.playerId) });
1274
+ }
627
1275
  }
628
- 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 = {
629
1292
  // Who this is, kept for `leave`: by then the session has forgotten them.
630
- userId: userIdOf(h, player.playerId) ?? known?.userId ?? null,
1293
+ ...(h.place.visibility === true && known?.visibility ? { visibility: known.visibility, visibilityPending: known.visibilityPending } : {}),
1294
+ userId: progressUser,
1295
+ ...((known || poseBack) && claimedPose ? { arrivalPose: { ...claimedPose, userId: poseOwner } } : {}),
631
1296
  username: usernameOf(h, player.playerId),
632
1297
  avatar: same ? known.avatar : clientAvatar,
633
- clientAvatar,
1298
+ clientAvatar: clientAvatar,
1299
+ color: sameColor ? known.color : clientColor,
1300
+ clientColor: clientColor,
1301
+ colorRev: sameColor ? known.colorRev : (known?.colorRev ?? 0) + 1,
634
1302
  avatarRev: same ? known.avatarRev : (known?.avatarRev ?? 0) + 1,
635
1303
  from,
636
- fromDeckId: arrival?.fromDeckId ?? null,
1304
+ fromDeckId,
637
1305
  // A jump to a friend says whom (the client's word: it decides only where
638
1306
  // the player appears, beside someone already in this session).
639
- 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,
640
1310
  party,
641
1311
  carry: hub ? known?.carry ?? null : cleanCarry(data.carry),
642
- 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 } : {}),
643
1317
  hello: true,
644
1318
  // A second hello (the avatar changed) keeps the player's place in an
645
1319
  // arrival group.
646
1320
  helloAt: known?.hello ? known.helloAt : Date.now(),
647
- arrived: known?.arrived ?? false,
648
- arrivedAt: known?.arrivedAt ?? null,
649
- result: known?.result ?? 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 } : {}),
1330
+ result: known?.result ?? (last ? last.result ?? null : null),
650
1331
  // ghost's results of this player for `hub.results`, kept across hellos
651
1332
  history: known?.history ?? null,
652
1333
  historyFrom: known?.historyFrom ?? null,
653
- ended: known?.ended ?? false,
654
- });
1334
+ ...(h.manifest.yourGames ? { hearts: known?.hearts ?? [], yoursKey: data.again === true ? known?.yoursKey : null } : {}),
1335
+ ended: known?.ended ?? (last ? last.ended === true : false),
1336
+ // v1.72 (I2, I3): only in a resume place, and only once known.
1337
+ ...(resumes && (known?.visitAt ?? last?.visitAt) !== undefined ? { visitAt: known?.visitAt ?? last.visitAt } : {}),
1338
+ ...(resumes && (known?.endWhy ?? last?.endWhy) !== undefined ? { endWhy: known?.endWhy ?? last.endWhy } : {}),
1339
+ ...(last?.ended === true || known?.endAgain === true ? { endAgain: true } : {}),
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); }
1363
+ // v1.89: hook presence opts in. Wait until the private replay was sent;
1364
+ // the entry identity also prevents a queued hello from crossing a leave.
1365
+ if (resumeHello) {
1366
+ if (resumeHello.companionHello) {
1367
+ delete resumeHello.kept.pendingClientHello;
1368
+ }
1369
+ if (synthetic && resumeHello.kept) {
1370
+ resumeHello.kept.pendingClientHello = resumeHello.body;
1371
+ }
1372
+ if (resumeHello.queue) {
1373
+ (h.resumePending ??= new Map()).set(player.playerId, h.players.get(player.playerId));
1374
+ }
1375
+ }
1376
+ // I3: one still here whose visit ended hears the end again (a drop may
1377
+ // have lost it); one back is told once arrived (`arrivals`).
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;
1380
+ endAgain(h, player.playerId);
1381
+ }
1382
+ Friends.prime(h, player.playerId, friendUserIdOf);
1383
+ // After joinedAfresh above, which resets this cache.
1384
+ if (ballotStale && h.ballotState) {
1385
+ h.ballotState.sent.set(player.playerId, STALE);
1386
+ }
1387
+ }
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');
655
1594
  }
656
1595
 
657
1596
  // What a returning client says it brings back: the result its game sent it.
@@ -683,30 +1622,554 @@ function outcomeOrNone(outcome) {
683
1622
  // result for the visit (the host takes one for a player who has just left)
684
1623
  // and save their progress under the user id it is handed (v1.2).
685
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
+ }
1629
+ for (const playerId of h.resumeKept?.keys() ?? []) {
1630
+ prepareResume(h, playerId);
1631
+ }
1632
+ for (const id of h.playerCells.keys()) {
1633
+ if (!h.sim.players.has(id)) {
1634
+ h.playerCells.delete(id);
1635
+ h.caps.delete(id);
1636
+ h.capAt.delete(id);
1637
+ }
1638
+ }
1639
+ // A connection that sent hub-cap and left before it had a body.
1640
+ for (const id of h.caps.keys()) {
1641
+ if (!h.sim.players.has(id) && !h.session?.players.some((p) => p.playerId === id)) {
1642
+ h.caps.delete(id);
1643
+ h.capAt.delete(id);
1644
+ }
1645
+ }
1646
+ Vis.prune(h);
1647
+ Decor.prune(h);
1648
+ if (h.place.actions === true) {
1649
+ Actions.prune(h);
1650
+ }
1651
+ if (h.place.companion === true) {
1652
+ Companion.prune(h);
1653
+ }
1654
+ if (h.place.ask === true) {
1655
+ Ask.prune(h);
1656
+ }
1657
+ if (h.place.menu === true) {
1658
+ Menu.prune(h);
1659
+ }
1660
+ // A call may precede this player's first hello, as hub.wear may.
1661
+ for (const playerId of h.leaving.keys()) {
1662
+ if (!h.sim.players.has(playerId) && !h.session?.players.some((p) => p.playerId === playerId)) {
1663
+ h.leaving.delete(playerId);
1664
+ }
1665
+ }
686
1666
  for (const playerId of [...h.players.keys()]) {
687
1667
  const inSession = h.session?.players.some((p) => p.playerId === playerId);
688
1668
  if (!h.sim.players.has(playerId) && !inSession) {
1669
+ if (!h.resumeKept?.has(playerId)) {
1670
+ forget(h, playerId);
1671
+ }
1672
+ }
1673
+ }
1674
+ greetLate(h);
1675
+ }
1676
+
1677
+ // v1.89 opt-in retention: the transport supplies no close reason. An absent
1678
+ // body is held for at most 60 wall-clock seconds (five minutes for v1.98
1679
+ // town resumePose); shutdown and explicit kit
1680
+ // travel still finalize the visit. Pose copies are taken after the deck's step,
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
+ }
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;
1691
+ function rememberResumePoses(h) {
1692
+ if (!h.resumeKept) {
1693
+ return;
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);
1698
+ for (const [id, entry] of h.players) {
1699
+ const body = h.sim.players.get(id);
1700
+ if (!entry.arrived || !body) {
1701
+ continue;
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
+ }
1715
+ h.resumeKept.set(id, {
1716
+ body,
1717
+ at: { ...body.at },
1718
+ facing: body.facing,
1719
+ seenAt: Date.now(),
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 } : {}),
1727
+ });
1728
+ }
1729
+ }
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
+
1802
+ function prepareResume(h, playerId, greet = true) {
1803
+ const kept = h.resumeKept?.get(playerId);
1804
+ if (!kept) {
1805
+ return;
1806
+ }
1807
+ const body = h.sim?.players.get(playerId);
1808
+ const present = body && h.session?.players.some((p) => p.playerId === playerId);
1809
+ const returning = present && (kept.awayAt !== undefined || body !== kept.body);
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
+ }
1814
+ kept.awayAt ??= Date.now();
1815
+ }
1816
+ // A replacement body can arrive before an absent tick was observed. In that
1817
+ // case the last tick that saw the old body bounds its reconnect window.
1818
+ const since = kept.awayAt ?? kept.seenAt;
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)))) {
1820
+ forget(h, playerId);
1821
+ return;
1822
+ }
1823
+ if (!returning) {
1824
+ return;
1825
+ }
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); }
1860
+ settle(h, playerId);
1861
+ kept.body = body;
1862
+ delete kept.awayAt;
1863
+ // The silent same-id case has no fresh arrive hook. Reuse the existing hello
1864
+ // replay to restore private channels, including a cleared channel it missed.
1865
+ if (greet) {
1866
+ const entry = h.players.get(playerId);
1867
+ hello(
1868
+ h,
1869
+ { playerId },
1870
+ {
1871
+ k: 'hub-hello',
1872
+ avatar: entry.clientAvatar,
1873
+ color: entry.clientColor,
1874
+ party: 1,
1875
+ resume: true,
1876
+ },
1877
+ true,
1878
+ );
1879
+ }
1880
+ }
1881
+
1882
+ // Reconnect re-hello (a bug fix for every place, no contract version): a
1883
+ // connection that comes back inside the host's reconnect window after the place
1884
+ // let its player go (an app switch on a phone) has a body and no hello, and its
1885
+ // client, still on the same connection, never greets again (it greets a new
1886
+ // connection only), so the player would be a ghost: no HUD, no shots, no door.
1887
+ // Only a player this place let go in the last 10 minutes is greeted for, after
1888
+ // 3 s without a hello, with the avatar it last chose here (the platform's
1889
+ // avatar read still applies): a newcomer's own first hello carries its party
1890
+ // and arrival, so it is always waited for. Nothing changes until a reconnect.
1891
+ // Not in a game (a place with `result`): its round and result belong to the
1892
+ // visit that left, so it keeps the old way (a fresh join once the window ends),
1893
+ // unless its place says `resume: true` (v1.72), when it is greeted like any.
1894
+ // The client still holds what it was last sent privately (HUD, labels, tune,
1895
+ // avatars, visibility, party, ballot card, leaving line) while the place forgot
1896
+ // it, so those are marked stale and sent again, clearing what the place no
1897
+ // longer says.
1898
+ const HELLO_LATE_MS = 3000;
1899
+ // Matches no JSON a channel sends, so its next send goes out whatever it holds.
1900
+ const STALE = '\u0000stale';
1901
+ const FORGOTTEN_MS = 10 * 60 * 1000;
1902
+ function greetLate(h) {
1903
+ const now = h.sim.timeMs;
1904
+ if (!Number.isFinite(now)) {
1905
+ return;
1906
+ }
1907
+ const since = (h.noHelloSince ??= new Map());
1908
+ for (const id of [...since.keys()]) {
1909
+ if (!h.session?.players.some((p) => p.playerId === id) || h.players.get(id)?.hello) {
1910
+ since.delete(id);
1911
+ }
1912
+ }
1913
+ for (const [id, last] of h.forgotten ?? []) {
1914
+ if (now - last.at > FORGOTTEN_MS) {
1915
+ h.forgotten.delete(id);
1916
+ }
1917
+ }
1918
+ if (h.place?.result && h.place.resume !== true) {
1919
+ return;
1920
+ }
1921
+ for (const { playerId } of h.session?.players ?? []) {
1922
+ if (!h.forgotten?.has(playerId) || !h.sim.players.has(playerId) || h.players.get(playerId)?.hello) {
1923
+ continue;
1924
+ }
1925
+ const first = since.get(playerId);
1926
+ if (first === undefined) {
1927
+ since.set(playerId, now);
1928
+ continue;
1929
+ }
1930
+ if (now - first < HELLO_LATE_MS) {
1931
+ continue;
1932
+ }
1933
+ since.delete(playerId);
1934
+ hello(h, { playerId }, { k: 'hub-hello', avatar: h.forgotten.get(playerId).clientAvatar, ...(h.forgotten.get(playerId).clientColor ? { color: h.forgotten.get(playerId).clientColor } : {}), party: 1, resume: true });
1935
+ }
1936
+ }
1937
+
1938
+ // What a returning player's client still holds from before the place let it
1939
+ // go: each private channel is marked stale so its next send goes out, clearing
1940
+ // what the place no longer says. Run by `hello` for a player it let go,
1941
+ // whichever hello (the late greet's or the client's own) comes first.
1942
+ // `forgotten` false (v1.72, a resume place's player it still holds): the
1943
+ // leaving line is left to `hello`, which re-sends one that is set.
1944
+ function staleSent(h, playerId, forgotten = true) {
1945
+ for (const sent of [h.sentHudMe, h.sentLabelsMe, h.sentTunes, h.sentAvMe]) {
1946
+ sent?.set(playerId, STALE);
1947
+ }
1948
+ (h.sentVisMe ??= new Map()).set(playerId, STALE);
1949
+ h.party?.sent.set(playerId, STALE);
1950
+ if (!forgotten) {
1951
+ return;
1952
+ }
1953
+ // The leaving line has no cache: it goes out only when set, so clear it here.
1954
+ try {
1955
+ h.session?.send(playerId, { k: 'hub-leaving', text: null });
1956
+ } catch {
1957
+ // A connection that went meanwhile holds nothing.
1958
+ }
1959
+ }
1960
+
1961
+ // A fresh client holds none of its private channels. Only a non-empty last
1962
+ // send needs replaying; an unused or already empty channel stays quiet.
1963
+ // `held` (a resume hello): the client kept what it held and may have missed a
1964
+ // clear while away, so every channel ever sent goes again, empty ones too.
1965
+ function replaySent(h, playerId, held = false) {
1966
+ for (const [sent, empty] of [
1967
+ [h.sentHudMe, 'null'],
1968
+ [h.sentLabelsMe, '{}'],
1969
+ [h.sentTunes, 'null'],
1970
+ [h.sentAvMe, '{}'],
1971
+ ]) {
1972
+ if (sent?.has(playerId) && (held || sent.get(playerId) !== empty)) {
1973
+ sent.set(playerId, STALE);
1974
+ }
1975
+ }
1976
+ }
1977
+
1978
+ // Initial visibility can arrive after hello but before the player's body or
1979
+ // deck arrive hook. Keep its latest state and deliver only after arrival.
1980
+ function notifyVisibility(h, only = null) {
1981
+ for (const [playerId, entry] of only ? [[only, h.players.get(only)]] : h.players) {
1982
+ if (!entry?.visibilityPending || !entry.arrived || !h.sim?.players.has(playerId)) {continue;}
1983
+ entry.visibilityPending = false;
1984
+ try {
1985
+ const result = h.hooks.visibility?.(h.ctx, { playerId, ...entry.visibility });
1986
+ result?.catch?.(() => console.warn('[hub] visibility hook failed'));
1987
+ } catch {
1988
+ console.warn('[hub] visibility hook failed');
1989
+ }
1990
+ }
1991
+ }
1992
+
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()) {
1997
+ if (!h.resumePending?.size) {
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);
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; }
2020
+ continue;
2021
+ }
2022
+ const queuedBeforeHook = new Map(h.resumePending);
2023
+ try {
2024
+ if (h.place.analytics === true) { Analytics.track(h, playerId, 'reconnect'); }
2025
+ const result = h.hooks.resume(h.ctx, { playerId });
2026
+ if (result && typeof result.catch === 'function') {
2027
+ result.catch(() => console.warn('[hub] resume hook failed'));
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
+ }
2037
+ } catch {
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
+ }
2061
+ }
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) {
689
2079
  forget(h, playerId);
2080
+ } else if (h.resumePending?.get(playerId) === entry) {
2081
+ h.resumePending.delete(playerId);
690
2082
  }
691
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
+ }
692
2108
  }
693
2109
 
694
2110
  function forget(h, playerId) {
2111
+ h.padOccupancy?.selected.delete(playerId);
695
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);
2117
+ h.resumePending?.delete(playerId);
2118
+ h.resumeKept?.delete(playerId);
2119
+ const poseDeparting = h.arrivalPoses && h.resumeDeparting?.has(playerId);
2120
+ h.resumeDeparting?.delete(playerId);
2121
+ if (entry?.arrived && h.place.analytics === true) {Analytics.leave(h, playerId);}
696
2122
  if (entry?.arrived) {
697
2123
  // A place's hook that throws still lets the player go, once.
698
2124
  try {
699
- 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
+ });
700
2130
  } catch (err) {
701
2131
  console.warn(`[hub] leave hook failed: ${err?.message ?? err}`);
702
2132
  }
703
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
+ }
2138
+ // After the leave hook, which may have reported the visit's result.
2139
+ if (entry?.hello) {
2140
+ const kept = { clientAvatar: entry.clientAvatar, clientColor: entry.clientColor, at: h.sim.timeMs, userId: entry.userId };
2141
+ // v1.72: a game that resumes keeps what its re-arrival must not lose (the
2142
+ // invariants at `hello`): the result (I1), the deadline (I2), the end
2143
+ // (I3) and the door (I4).
2144
+ if (h.place?.result && h.place.resume === true && h.place.resumeKeep !== true) {
2145
+ Object.assign(kept, {
2146
+ result: entry.result ?? null,
2147
+ ended: entry.ended === true,
2148
+ endWhy: entry.endWhy,
2149
+ visitAt: entry.visitAt,
2150
+ from: entry.from ?? null,
2151
+ fromDeckId: entry.fromDeckId ?? null,
2152
+ });
2153
+ }
2154
+ (h.forgotten ??= new Map()).set(playerId, kept);
2155
+ }
704
2156
  Party.forget(h, playerId);
705
2157
  Say.forget(h, playerId);
2158
+ if (h.ballotState) {
2159
+ Ballot.forget(h, playerId);
2160
+ }
2161
+ Friends.forget(h, playerId);
2162
+ h.caps.delete(playerId);
2163
+ h.capAt.delete(playerId);
2164
+ h.playerCells.delete(playerId);
706
2165
  h.players.delete(playerId);
2166
+ if (entry?.progressState) { entry.progressState.readLifetime = null; }
2167
+ h.progressStates.delete(playerId);
2168
+ syncProgressUser(h, entry?.userId);
707
2169
  h.held.delete(playerId);
708
2170
  h.hudMe.delete(playerId);
709
2171
  h.sentHudMe.delete(playerId);
2172
+ h.leaving.delete(playerId);
710
2173
  h.tunes.delete(playerId);
711
2174
  h.sentTunes.delete(playerId);
712
2175
  h.labelsMe.delete(playerId);
@@ -714,12 +2177,34 @@ function forget(h, playerId) {
714
2177
  h.sentAvMe.delete(playerId);
715
2178
  h.marks.delete(playerId);
716
2179
  Wear.forget(h, playerId);
2180
+ Earned.forget(h, playerId);
717
2181
  h.shut.delete(playerId);
718
2182
  h.jumpAt.delete(playerId);
719
2183
  h.whereAt.delete(playerId);
2184
+ h.unstuckAt?.delete(playerId);
2185
+ h.unstuckAskAt?.delete(playerId);
720
2186
  h.settling.delete(playerId);
721
2187
  Grab.forget(h, playerId);
2188
+ if (h.manifest.act === true) {Act.forget(h, playerId);}
722
2189
  Idle.forget(h, playerId);
2190
+ Decor.forget(h, playerId);
2191
+ if (h.place.actions === true) {
2192
+ Actions.forget(h, playerId);
2193
+ }
2194
+ if (h.place.companion === true) {
2195
+ Companion.forget(h, playerId);
2196
+ }
2197
+ if (h.place.ask === true) {
2198
+ Ask.forget(h, playerId);
2199
+ }
2200
+ if (h.place.menu === true) {
2201
+ Menu.forget(h, playerId);
2202
+ }
2203
+ if (h.cueBudgets) {
2204
+ h.cueBudgets.delete(`player:${playerId}`);
2205
+ }
2206
+ Shot.forgetPlayer(h, playerId);
2207
+ Vis.forget(h, playerId);
723
2208
  Cabinets.forget(h, playerId);
724
2209
  h.npcs.leave(playerId);
725
2210
  }
@@ -732,10 +2217,15 @@ function forget(h, playerId) {
732
2217
  const SHUTDOWN_DRAIN_MS = 1500;
733
2218
 
734
2219
  async function shutdown(h) {
2220
+ h.arrivalPoses?.shutdown();
735
2221
  if (!h.sim) {
736
2222
  return;
737
2223
  }
738
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
+ }
739
2229
  forget(h, playerId);
740
2230
  }
741
2231
  if (Wear.tryOnUsed(h)) {
@@ -744,7 +2234,11 @@ async function shutdown(h) {
744
2234
  let timer = null;
745
2235
  await Promise.race([
746
2236
  Promise.resolve()
747
- .then(() => h.hooks.shutdown?.(h.ctx))
2237
+ .then(async () => {
2238
+ await h.hooks.shutdown?.(h.ctx);
2239
+ await h.poseStore?.drain();
2240
+ await Promise.all([...(h.friendBestHelpers?.values() ?? [])].map((helper) => helper.drain()));
2241
+ })
748
2242
  .catch((err) => console.warn(`[hub] shutdown hook failed: ${err?.message ?? err}`)),
749
2243
  new Promise((resolve) => {
750
2244
  timer = setTimeout(resolve, SHUTDOWN_DRAIN_MS);
@@ -753,6 +2247,37 @@ async function shutdown(h) {
753
2247
  clearTimeout(timer);
754
2248
  }
755
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
+
756
2281
  // Players with a body who said hello and have not arrived, placed as groups
757
2282
  // at the arrival (contract §5). A group is everyone who said hello inside one
758
2283
  // window; it is placed when it has as many as its members said were coming,
@@ -772,7 +2297,8 @@ function arrivals(h) {
772
2297
  // A group also waits, inside the same window, for ghost's read of what its
773
2298
  // players bring back.
774
2299
  const reading = waiting.some(([, e]) => e.read !== 'done');
775
- 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)) {
776
2302
  // Whoever is in waits where they are, held, until the group is placed.
777
2303
  for (const [playerId] of waiting) {
778
2304
  if (!h.held.has(playerId)) {
@@ -785,6 +2311,10 @@ function arrivals(h) {
785
2311
  const group = waiting.map(([playerId, entry]) => {
786
2312
  entry.arrived = true;
787
2313
  entry.arrivedAt = h.sim.timeMs;
2314
+ // v1.72 (I2): a resume place's visit has one deadline, from its first arrival.
2315
+ if (h.place.resume === true && h.place.result) {
2316
+ entry.visitAt ??= entry.arrivedAt;
2317
+ }
788
2318
  if (h.held.get(playerId)?.waiting) {
789
2319
  h.held.delete(playerId);
790
2320
  }
@@ -792,33 +2322,113 @@ function arrivals(h) {
792
2322
  playerId,
793
2323
  username: usernameOf(h, playerId),
794
2324
  userId: entry.userId,
2325
+ ...(h.place.anonymousEntry === true ? { identityUserId: entry.identityUserId ?? null } : {}),
2326
+ ...(entry.signUp ? { signedUpFrom: entry.signUp.carry.playerId } : {}),
795
2327
  from: entry.from,
796
2328
  fromDeckId: entry.fromDeckId,
797
2329
  near: entry.near ?? null,
2330
+ ...(h.place.invite === true ? { invited: entry.invited === true } : {}),
798
2331
  carry: entry.carry,
799
2332
  // How many went through the door together, by the client's word (the
800
2333
  // way back carries what the way out was sent with): 1 for anyone else.
801
2334
  party: entry.party ?? 1,
802
2335
  };
803
2336
  });
2337
+ const waitedAt = new Map(group.map((g) => [g.playerId, { ...h.sim.players.get(g.playerId)?.at }]));
804
2338
  placeGroup(h, group.map((g) => g.playerId));
805
2339
  placeNearFriends(h, group);
806
- h.hooks.arrive?.(h.ctx, group);
2340
+ // v1.67: a dev house keeps its first arrival as owner for this session.
2341
+ if (!platformHub(h) && isDevSession(h) && h.manifest.house?.devOwner === 'first' && !h.devOwnerChosen) {
2342
+ h.devOwnerChosen = true;
2343
+ h.devOwner = group[0]?.userId ?? null;
2344
+ }
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
+ }
807
2382
  for (const { playerId } of group) {
808
2383
  const body = h.sim.players.get(playerId);
809
- if (body) {
2384
+ if (body && !h.players.get(playerId)?.signUp && !group.find((g) => g.playerId === playerId)?.signedUpFrom) {
2385
+ // v1.40: kept where the arrival put them, like a jump. A player waits
2386
+ // for their group at the scene's spawn, where their client agrees they
2387
+ // are; placed, that client's reports still on their way name the spawn
2388
+ // and each pulled the body a step back toward it: four back from Tag
2389
+ // were dragged 2 to 3 m off the spots the town gave them, two onto the
2390
+ // next door's pad, and were taken into its game. Only one the arrival
2391
+ // moved: a player placed where they waited has no stale report to be
2392
+ // pulled by. (A place's hold is its own spot and is left alone.)
2393
+ const was = waitedAt.get(playerId);
2394
+ if (Math.hypot(body.at.x - was.x, body.at.z - was.z) > HOLD_SLACK) {
2395
+ settle(h, playerId);
2396
+ }
810
2397
  h.session?.send(playerId, { k: 'hub-arrived', facing: body.facing });
811
2398
  }
2399
+ if (h.players.get(playerId)?.endAgain) {
2400
+ delete h.players.get(playerId).endAgain;
2401
+ endAgain(h, playerId);
2402
+ }
812
2403
  }
813
2404
  }
814
2405
 
815
- // A row at the arrival actor, facing the way the manifest says.
816
- function placeGroup(h, playerIds) {
2406
+ // v1.72 (I3): the end of a resume place's visit, again, to a client a drop
2407
+ // may have kept it from (`again`: a client already ending keeps its pause).
2408
+ function endAgain(h, playerId) {
2409
+ const entry = h.players.get(playerId);
2410
+ if (!entry?.ended) {
2411
+ return;
2412
+ }
2413
+ h.held.delete(playerId);
2414
+ Shot.stopHolding(h, playerId);
2415
+ h.session?.send(playerId, { k: 'hub-end', why: entry.endWhy ?? 'end', again: true });
2416
+ }
2417
+
2418
+ // Where the place's players arrive: the arrival actor's Transform, else the
2419
+ // scene's spawn.
2420
+ function arrivalPoint(h) {
817
2421
  const arrival = h.place.arrival;
818
2422
  const actor = arrival.actor
819
2423
  ? h.actors.find((a) => a.id === arrival.actor)
820
2424
  : h.actors.find((a) => a.components.Player);
821
- const t = actor?.components.Transform ?? h.sim.spawn ?? { x: 0, y: 1, z: 0 };
2425
+ return actor?.components.Transform ?? h.sim?.spawn ?? { x: 0, y: 1, z: 0 };
2426
+ }
2427
+
2428
+ // A row at the arrival actor, facing the way the manifest says.
2429
+ function placeGroup(h, playerIds) {
2430
+ const arrival = h.place.arrival;
2431
+ const t = arrivalPoint(h);
822
2432
  let facing;
823
2433
  if (typeof arrival.face === 'number') {
824
2434
  facing = arrival.face * DEG;
@@ -832,7 +2442,8 @@ function placeGroup(h, playerIds) {
832
2442
  const n = playerIds.length;
833
2443
  playerIds.forEach((playerId, i) => {
834
2444
  const offset = (i - (n - 1) / 2) * arrival.spread;
835
- placeAt(h, playerId, { x: t.x + across.x * offset, y: Math.max(t.y ?? 1, 1.2), z: t.z + across.z * offset }, facing);
2445
+ const at = { x: t.x + across.x * offset, y: Math.max(t.y ?? 1, 1.2), z: t.z + across.z * offset };
2446
+ placeAt(h, playerId, { ...at, y: standingY(h, at) }, facing);
836
2447
  });
837
2448
  }
838
2449
 
@@ -869,6 +2480,12 @@ function placeBeside(h, playerId, otherId, used = new Map()) {
869
2480
  if (!other?.at || blockedPairs(h)?.get(playerId)?.has(otherId)) {
870
2481
  return false;
871
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;}
872
2489
  const f = other.facing ?? 0;
873
2490
  // Facing f looks along (sin f, cos f): right, left, behind, ahead, then
874
2491
  // the same a step further out.
@@ -886,7 +2503,7 @@ function placeBeside(h, playerId, otherId, used = new Map()) {
886
2503
  for (const step of [1, 1.5, 2, 2.5, 3, 3.5]) {
887
2504
  const spot = dirs
888
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 }))
889
- .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);
890
2507
  if (spot) {
891
2508
  taken.push(spot);
892
2509
  used.set(otherId, taken);
@@ -912,7 +2529,7 @@ function padAt(h, at, margin) {
912
2529
 
913
2530
  // Whether a standing body fits at `at`: no solid scene actor overlaps it, and
914
2531
  // on a scene with no ground (`fallY`) a solid's top is under its feet.
915
- function spotClear(h, at) {
2532
+ function spotClear(h, at, { radius, halfHeight }) {
916
2533
  let supported = h.noGround !== true;
917
2534
  for (const actor of h.actors) {
918
2535
  const c = actor.components;
@@ -925,11 +2542,11 @@ function spotClear(h, at) {
925
2542
  const half = shape.kind === 'sphere' ? (shape.radius ?? 0.5) : (shape.height ?? 1) / 2;
926
2543
  const top = (t.y ?? 0) + half;
927
2544
  const bottom = (t.y ?? 0) - half;
928
- const inside = footprintHas(shape, t, at, BODY_RADIUS_M);
929
- 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) {
930
2547
  return false;
931
2548
  }
932
- 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) {
933
2550
  supported = true;
934
2551
  }
935
2552
  }
@@ -952,10 +2569,20 @@ function footprintHas(shape, t, at, pad) {
952
2569
  // Move a body. One placed before the joiner's WORLD snapshot is where that
953
2570
  // snapshot starts them; a later one reaches the client as a clamp.
954
2571
  function placeAt(h, playerId, at, facing) {
2572
+ // A new placement is where the player is now: whatever was keeping them at
2573
+ // an earlier one (v1.40: an arrival's) lets go, so a place that puts a
2574
+ // player somewhere just after they arrive is not undone.
2575
+ h.settling.delete(playerId);
2576
+ moveBody(h, playerId, at, facing);
2577
+ }
2578
+
2579
+ function moveBody(h, playerId, at, facing) {
955
2580
  const body = h.sim?.players.get(playerId);
956
2581
  if (!body || !at || ![at.x, at.y, at.z].every(Number.isFinite)) {
957
2582
  return;
958
2583
  }
2584
+ // v1.141: a placement elsewhere is a reset of the player's observation.
2585
+ Observe.placed(h, playerId, at);
959
2586
  body.at = { x: at.x, y: at.y, z: at.z };
960
2587
  if (facing !== undefined && Number.isFinite(facing)) {
961
2588
  body.facing = facing;
@@ -964,20 +2591,32 @@ function placeAt(h, playerId, at, facing) {
964
2591
  body.body.setTranslation(body.at, true);
965
2592
  }
966
2593
 
967
- // After a jump (to a door's pad, beside a player) the body is kept where it
968
- // was put for a moment. The client's move reports already on their way still
2594
+ // After a jump (to a door's pad, beside a player) or an arrival (v1.40) the
2595
+ // body is kept where it was put for a moment. The client's move reports already on their way still
969
2596
  // name the spot it left, and the server's movement clamp lets each one pull
970
2597
  // the body a step back toward it: on a slow phone that dragged a player a
971
2598
  // metre or two off the pad they had just been put on, and the pad never
972
2599
  // counted them. This is not a hold (contract §8): the player is not in the
973
2600
  // `held` list, keeps what they carry and may jump again at once; the body is
974
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.
975
2611
  const SETTLE_MS = 600;
2612
+ const SETTLE_MAX_MS = 4000;
2613
+ const SETTLE_NEAR_M = 0.25;
976
2614
 
977
2615
  function settle(h, playerId) {
978
2616
  const body = h.sim?.players.get(playerId);
979
2617
  if (body) {
980
- 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 });
981
2620
  }
982
2621
  }
983
2622
 
@@ -990,8 +2629,18 @@ function enforceSettle(h) {
990
2629
  h.settling.delete(playerId);
991
2630
  continue;
992
2631
  }
993
- if (Math.hypot(body.at.x - spot.at.x, body.at.z - spot.at.z) > HOLD_SLACK) {
994
- placeAt(h, playerId, spot.at, spot.facing);
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) {
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;
995
2644
  }
996
2645
  }
997
2646
  }
@@ -1040,7 +2689,7 @@ function enforceDuration(h) {
1040
2689
  }
1041
2690
  const limit = h.place.maxDurationSec * 1000;
1042
2691
  for (const [playerId, entry] of h.players) {
1043
- if (entry.arrived && !entry.ended && h.sim.timeMs - entry.arrivedAt >= limit) {
2692
+ if (entry.arrived && !entry.ended && h.sim.timeMs - (entry.visitAt ?? entry.arrivedAt) >= limit) {
1044
2693
  console.log(`[hub] ${usernameOf(h, playerId)} reached maxDurationSec`);
1045
2694
  end(h, playerId, 'time');
1046
2695
  }
@@ -1064,6 +2713,7 @@ function report(h, playerId, value) {
1064
2713
  return false;
1065
2714
  }
1066
2715
  entry.result = result;
2716
+ if (h.place.analyticsRounds !== 'authored') {DoorAnalytics.finish(h, playerId);}
1067
2717
  const shown = {
1068
2718
  title: h.place.title,
1069
2719
  ...result,
@@ -1088,11 +2738,17 @@ function report(h, playerId, value) {
1088
2738
  }
1089
2739
 
1090
2740
  function end(h, playerId, why) {
2741
+ if (h.place.analyticsRounds !== 'authored') {DoorAnalytics.finish(h, playerId);}
1091
2742
  const entry = h.players.get(playerId);
1092
2743
  if (entry) {
1093
2744
  entry.ended = true;
2745
+ // v1.72 (I3): kept to say it again on resume.
2746
+ if (h.place.resume === true && h.place.result) {
2747
+ entry.endWhy = why;
2748
+ }
1094
2749
  }
1095
2750
  h.held.delete(playerId);
2751
+ Shot.stopHolding(h, playerId);
1096
2752
  h.session?.send(playerId, { k: 'hub-end', why });
1097
2753
  }
1098
2754
 
@@ -1114,14 +2770,19 @@ function jumpDoors(h) {
1114
2770
  // The Doors list's rows. An event gate leads to a game another door already
1115
2771
  // leads to, so it is listed only while its event is open, and as the event
1116
2772
  // (two rows reading "King of the Hill" was one too many).
2773
+ function listedDoors(h) {
2774
+ return jumpDoors(h).filter((door) => {
2775
+ const event = h.boards.get(door.id)?.event;
2776
+ return !event || event.open;
2777
+ });
2778
+ }
2779
+
1117
2780
  function doorList(h) {
1118
2781
  const out = [];
1119
- for (const door of jumpDoors(h)) {
2782
+ for (const door of listedDoors(h)) {
1120
2783
  const event = h.boards.get(door.id)?.event;
1121
- if (event && !event.open) {
1122
- continue;
1123
- }
1124
- 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 };
1125
2786
  // What a player picking a door wants to know: today's featured door (it
1126
2787
  // is listed first), one that takes a single player, how many it needs.
1127
2788
  if (h.boards.get(door.id)?.featured === true) {
@@ -1161,17 +2822,247 @@ function doorJump(h, player, data) {
1161
2822
  // two who jump there do not land in one spot; else in front of the door.
1162
2823
  const at = Party.padPoint(h, door, Math.floor(Math.random() * 6), player.playerId) ?? frontOf(door);
1163
2824
  const facing = ((door.t.rotationY ?? 0) + 180) * DEG;
1164
- placeAt(h, player.playerId, { x: at.x, y: 1.2, z: at.z }, facing);
2825
+ placeAt(h, player.playerId, { x: at.x, y: standingY(h, { ...at, y: 1.2 }), z: at.z }, facing);
1165
2826
  settle(h, player.playerId);
1166
2827
  h.session?.send(player.playerId, { k: 'hub-jumped', facing });
1167
2828
  }
1168
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
+
2857
+ // "Stuck?" (v1.33): whether this place puts a player back at its arrival for
2858
+ // the asking. A deck with `hub.stuck`, and a town only: in a game (a place
2859
+ // with a `result`) the way to the start is the game's to give or keep -- a
2860
+ // free one would be a way out of a trap, a tag or a lost position.
2861
+ function stuckHere(h) {
2862
+ return h.manifest.stuck === true && !h.place.result;
2863
+ }
2864
+
2865
+ // What the chip calls the arrival ("the square"), or null for none: the
2866
+ // place's own `where` words for the spot (§5: "in the square", "on Race Row",
2867
+ // "at the Arcade") without their first word. Words of another shape are not
2868
+ // guessed at.
2869
+ // Whether what a place's hook returned is an answer for later (a promise, or
2870
+ // anything with a callable `then`) rather than one given at once: the hooks
2871
+ // "Stuck?" asks are synchronous, and such a result is no answer. Its `then`
2872
+ // is never called -- that is running the place's code a second time, and an
2873
+ // `async then` that throws hands back a rejection of its own. A native
2874
+ // promise is the one thing that can reject with nobody having called
2875
+ // anything, so it alone is given a handler, by the built-in `then` (not the
2876
+ // object's own, which a place may have replaced); what that returns cannot
2877
+ // reject. Called inside the caller's catch: reading `then` may throw.
2878
+ function answersLater(result) {
2879
+ if (result === null || (typeof result !== 'object' && typeof result !== 'function')) {
2880
+ return false;
2881
+ }
2882
+ if (result instanceof Promise) {
2883
+ Promise.prototype.then.call(result, undefined, () => {});
2884
+ return true;
2885
+ }
2886
+ return typeof result.then === 'function';
2887
+ }
2888
+
2889
+ function arrivalName(h) {
2890
+ // The place's part is inside one catch, as `unstickSpot`'s is: this is said
2891
+ // in the answer to a tap, which nothing of the place's may stop. A promise
2892
+ // is no words (`answersLater`).
2893
+ try {
2894
+ const t = arrivalPoint(h);
2895
+ const words = h.hooks.where?.(h.ctx, { x: t.x, y: t.y ?? 1, z: t.z });
2896
+ if (answersLater(words)) {
2897
+ return null;
2898
+ }
2899
+ const name = typeof words === 'string' ? /^(?:in|on|at) (\S.*)$/.exec(words.trim())?.[1] : null;
2900
+ return name ? name.slice(0, WHERE_TEXT_MAX) : null;
2901
+ } catch (err) {
2902
+ try {
2903
+ console.warn(`[hub] where hook failed: ${err?.message ?? err}`);
2904
+ } catch {
2905
+ console.warn('[hub] where hook failed');
2906
+ }
2907
+ return null;
2908
+ }
2909
+ }
2910
+
2911
+ // Whether the place has the `unstick` hook (v1.39). Read behind a catch like
2912
+ // everything else of the place's: a hooks object may be anything.
2913
+ function hasUnstick(h) {
2914
+ try {
2915
+ return typeof h.hooks.unstick === 'function';
2916
+ } catch {
2917
+ return false;
2918
+ }
2919
+ }
2920
+
2921
+ // v1.39: where the place itself would put a player stuck where this one is
2922
+ // (its `unstick` hook, asked with the body's own position), as `{ at,
2923
+ // facing, to }`, or null for the arrival.
2924
+ //
2925
+ // The invariant: nothing the place returns or throws can stop a tap from
2926
+ // landing somewhere valid and answering. So the whole of the place's part --
2927
+ // the call, and every read of what it returned -- is inside one catch, and
2928
+ // what leaves it is either null or a spot made here of plain numbers and a
2929
+ // plain string, which nothing after it can make throw. Null is: no hook; a
2930
+ // hook that throws, or answers null; an answer whose fields cannot be read
2931
+ // (a getter that throws); a promise or any other thenable -- the hook is
2932
+ // synchronous (`answersLater`: a native promise is silenced so that its
2933
+ // rejection is not left unhandled to end the session's process, and nothing
2934
+ // else's `then` is ever called); and an answer that is
2935
+ // not a spot: `x` and `z` finite and inside the world box, `y` (default standing
2936
+ // height when proved clear and no higher, else 1.2, as an arrival's; v1.48)
2937
+ // and `facing` (degrees; default: as the body faces) finite where given.
2938
+ // `to` is the place's name for the spot, a string of up to 40 characters, or none.
2939
+ function unstickSpot(h, playerId) {
2940
+ const body = h.sim?.players.get(playerId);
2941
+ if (!body || !hasUnstick(h)) {
2942
+ return null;
2943
+ }
2944
+ try {
2945
+ const answer = h.hooks.unstick(h.ctx, playerId, { x: body.at.x, y: body.at.y, z: body.at.z });
2946
+ if (answer === null || answer === undefined) {
2947
+ return null;
2948
+ }
2949
+ if (answersLater(answer)) {
2950
+ console.warn('[hub] unstick hook: it must answer at once, not with a promise; the arrival is used');
2951
+ return null;
2952
+ }
2953
+ if (typeof answer !== 'object') {
2954
+ console.warn('[hub] unstick hook: not a spot ({ x, z } inside the world box); the arrival is used');
2955
+ return null;
2956
+ }
2957
+ // Each field read once, here, into a value of this function's own.
2958
+ const x = answer.x;
2959
+ const z = answer.z;
2960
+ const givenY = answer.y;
2961
+ const y = givenY === undefined && [x, z].every(Number.isFinite) ? standingY(h, { x, y: 1.2, z }) : givenY;
2962
+ const facing = answer.facing;
2963
+ const name = answer.to;
2964
+ const B = Actors.BOUNDS;
2965
+ if (
2966
+ ![x, y, z].every((v) => typeof v === 'number' && Number.isFinite(v)) || Math.abs(x) > B.xz || Math.abs(z) > B.xz || y < B.low || y > B.high ||
2967
+ (facing !== undefined && !(typeof facing === 'number' && Number.isFinite(facing)))
2968
+ ) {
2969
+ console.warn('[hub] unstick hook: not a spot ({ x, z } inside the world box); the arrival is used');
2970
+ return null;
2971
+ }
2972
+ const to = typeof name === 'string' && name.trim() ? name.trim().slice(0, WHERE_TEXT_MAX) : null;
2973
+ return { at: { x, y, z }, facing: facing === undefined ? undefined : facing * DEG, to };
2974
+ } catch (err) {
2975
+ try {
2976
+ console.warn(`[hub] unstick hook failed: ${err?.message ?? err}`);
2977
+ } catch {
2978
+ console.warn('[hub] unstick hook failed');
2979
+ }
2980
+ return null;
2981
+ }
2982
+ }
2983
+
2984
+ // Whether this player may be moved by "Stuck?" at all: in a town of a deck
2985
+ // with `hub.stuck`, here, arrived, and their visit not ended.
2986
+ function mayUnstick(h, playerId) {
2987
+ const entry = playerId ? h.players.get(playerId) : null;
2988
+ return stuckHere(h) && Boolean(h.sim?.players.has(playerId)) && Boolean(entry?.arrived) && !entry.ended;
2989
+ }
2990
+
2991
+ // v1.39: what a tap would do for this player now, asked by a client about to
2992
+ // show the chip (`{ k: 'hub-unstick', ask: true }`) so its words can say where
2993
+ // the tap goes. Only a place with the `unstick` hook is asked, and answers
2994
+ // (`hub-unstick-to`): once a second, to a player who may be moved and is not
2995
+ // held. Nobody is moved by it.
2996
+ function unstickAsk(h, player) {
2997
+ const playerId = player?.playerId;
2998
+ const now = Date.now();
2999
+ const last = (h.unstuckAskAt ??= new Map());
3000
+ if (!hasUnstick(h) || !mayUnstick(h, playerId) || h.held.has(playerId) || now - (last.get(playerId) ?? -Infinity) < JUMP_EVERY_MS) {
3001
+ return;
3002
+ }
3003
+ last.set(playerId, now);
3004
+ const spot = unstickSpot(h, playerId);
3005
+ h.session?.send(playerId, { k: 'hub-unstick-to', spot: Boolean(spot), to: spot ? spot.to : arrivalName(h) });
3006
+ }
3007
+
3008
+ // A player who asked to be moved (the chrome's "Stuck?" chip and Doors row):
3009
+ // to the spot the place picks for them (v1.39, its `unstick` hook), else to
3010
+ // the arrival by the fall rule's own placement (`placeGroup`), for that one
3011
+ // player. Never in a game, never a held player or one who has not arrived or
3012
+ // has ended, once in 5 s, and counted as a jump (so not within a second of
3013
+ // one). A sitter gets up first, as for any jump.
3014
+ function unstick(h, player) {
3015
+ const playerId = player?.playerId;
3016
+ const now = Date.now();
3017
+ const last = (h.unstuckAt ??= new Map());
3018
+ if (
3019
+ !mayUnstick(h, playerId) ||
3020
+ now - (last.get(playerId) ?? -Infinity) < UNSTICK_EVERY_MS ||
3021
+ now - (h.jumpAt.get(playerId) ?? 0) < JUMP_EVERY_MS
3022
+ ) {
3023
+ return;
3024
+ }
3025
+ Idle.stand(h, playerId);
3026
+ if (h.held.has(playerId)) {
3027
+ return;
3028
+ }
3029
+ // The place is asked before anything is spent, and cannot stop what
3030
+ // follows (`unstickSpot`): from here the player is moved and answered.
3031
+ const hooked = hasUnstick(h);
3032
+ const spot = hooked ? unstickSpot(h, playerId) : null;
3033
+ last.set(playerId, now);
3034
+ h.jumpAt.set(playerId, now);
3035
+ if (spot) {
3036
+ placeAt(h, playerId, spot.at, spot.facing);
3037
+ } else {
3038
+ placeGroup(h, [playerId]);
3039
+ }
3040
+ settle(h, playerId);
3041
+ h.session?.send(playerId, {
3042
+ k: 'hub-jumped',
3043
+ facing: h.sim.players.get(playerId)?.facing ?? 0,
3044
+ // v1.39, only from a place with the hook: where the player was put.
3045
+ ...(hooked ? { stuck: { spot: Boolean(spot), to: spot ? spot.to : arrivalName(h) } } : {}),
3046
+ });
3047
+ }
3048
+
1169
3049
  // A spot in front of a door, for a jump to a door with no pad.
1170
3050
  function frontOf(door) {
1171
3051
  const t = door.t;
1172
3052
  return doorPoint({ x: t.x, z: t.z, rotationY: t.rotationY ?? 0 }, (Math.random() - 0.5) * JUMP_SPREAD, JUMP_OUT);
1173
3053
  }
1174
3054
 
3055
+ // What `ballot.js` uses of this layer (v1.68): names and avatars are the
3056
+ // kit's own, never the deck's; a player not in the session is no face.
3057
+ function ballotDeps(h) {
3058
+ return {
3059
+ blockedPairs: () => blockedPairs(h),
3060
+ namesOf: (ids) => namesOf(h, ids),
3061
+ usernameOf: (playerId) => (h.sim?.players.has(playerId) ? h.session?.players.find((p) => p.playerId === playerId)?.username ?? null : null),
3062
+ avatarOf: (playerId) => (h.players.get(playerId)?.hello ? h.players.get(playerId).avatar : null),
3063
+ };
3064
+ }
3065
+
1175
3066
  // What `say.js` uses of this layer. A deck whose manifest sets `cues` (v1.23)
1176
3067
  // hands it more; any other hands it exactly what it did.
1177
3068
  function sayDeps(h) {
@@ -1191,7 +3082,7 @@ function partyDeps(h) {
1191
3082
  placeAt(state, playerId, at, facing);
1192
3083
  settle(state, playerId);
1193
3084
  };
1194
- return { h, blockedPairs, usernameOf, placeAt: placeAndSettle, stand: Idle.stand, jumpDoors, front: frontOf };
3085
+ return { h, blockedPairs, usernameOf, standingY, placeAt: placeAndSettle, stand: Idle.stand, jumpDoors, front: frontOf };
1195
3086
  }
1196
3087
 
1197
3088
  // Where the players a client asks about are (the chrome's People list and its
@@ -1368,6 +3259,20 @@ function deckDoorPlace(h, props, deck) {
1368
3259
  };
1369
3260
  }
1370
3261
 
3262
+ // All outgoing travel paths retire the lease after sending the command.
3263
+ function sendGo(h, playerId, msg) {
3264
+ if (h.session?.send) {
3265
+ h.session.send(playerId, msg);
3266
+ Shot.stopHolding(h, playerId);
3267
+ // An explicit kit trip ends the visit rather than retaining it for a drop.
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); }
3272
+ h.resumePending?.delete(playerId);
3273
+ }
3274
+ }
3275
+
1371
3276
  // Send players through one of this place's doors (contract §4), into a new
1372
3277
  // instance or, with `instance`, one this place sent players to before (a late
1373
3278
  // join). In dev the destination is a named session whose key names the place;
@@ -1417,7 +3322,7 @@ function go(h, door, playerIds, { instance } = {}) {
1417
3322
  typeof instance === 'string' && instance.startsWith(`${prefix}hub.${to}.`) ? instance : prefix + Place.devKey(to);
1418
3323
  tellWent(h, playerIds, door);
1419
3324
  for (const playerId of playerIds) {
1420
- h.session?.send(playerId, {
3325
+ sendGo(h, playerId, {
1421
3326
  k: 'hub-go',
1422
3327
  door,
1423
3328
  key,
@@ -1453,13 +3358,13 @@ function isLayerDoor(h, door) {
1453
3358
  // door id, or null when nobody went.
1454
3359
  function goLayer(h, door, playerIds) {
1455
3360
  const found = doors(h).find((d) => d.id === door);
1456
- const going = [...membersOf(h, playerIds).values()];
3361
+ const going = [...travelersOf(h, playerIds).values()];
1457
3362
  if (!going.length) {
1458
- 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`);
1459
3364
  return null;
1460
3365
  }
1461
3366
  for (const playerId of going) {
1462
- h.session?.send(playerId, {
3367
+ sendGo(h, playerId, {
1463
3368
  k: 'hub-go',
1464
3369
  door,
1465
3370
  key: null,
@@ -1486,13 +3391,13 @@ function goClassic(h, hub, door, playerIds) {
1486
3391
  console.warn(`[hub] no door "${door}" in this place`);
1487
3392
  return null;
1488
3393
  }
1489
- const going = hub ? [...membersOf(h, playerIds).values()] : (playerIds ?? []);
3394
+ const going = hub ? [...travelersOf(h, playerIds).values()] : (playerIds ?? []);
1490
3395
  if (!going.length) {
1491
- 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`);
1492
3397
  return null;
1493
3398
  }
1494
3399
  for (const playerId of going) {
1495
- h.session?.send(playerId, {
3400
+ sendGo(h, playerId, {
1496
3401
  k: 'hub-go',
1497
3402
  door,
1498
3403
  classic: true,
@@ -1508,13 +3413,25 @@ function goClassic(h, hub, door, playerIds) {
1508
3413
  return door;
1509
3414
  }
1510
3415
 
1511
- // Signed-in players' user ids, which is all ghost holds a pad by:
1512
- // userId -> playerId.
3416
+ // Signed-in players' user ids: userId -> playerId. Results, history and
3417
+ // everything else kept on an account go by these.
1513
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 }) {
1514
3431
  const out = new Map();
1515
3432
  for (const playerId of playerIds ?? []) {
1516
3433
  const p = h.session?.players.find((q) => q.playerId === playerId);
1517
- if (p && !p.isAnonymous && USER_ID.test(String(p.userId))) {
3434
+ if (p && (guests || !p.isAnonymous) && USER_ID.test(String(p.userId))) {
1518
3435
  out.set(String(p.userId), playerId);
1519
3436
  }
1520
3437
  }
@@ -1534,6 +3451,7 @@ function gather(h, door, playerIds) {
1534
3451
  }
1535
3452
  const on = new Set(playerIds ?? []);
1536
3453
  h.padDoors.set(door, on);
3454
+ h.padOccupancy?.reportedAt.set(door, h.sim.timeMs);
1537
3455
  for (const [playerId, entry] of h.shut) {
1538
3456
  if (entry.door === door && !on.has(playerId)) {
1539
3457
  // Stepped off: the door may be tried again.
@@ -1545,7 +3463,7 @@ function gather(h, door, playerIds) {
1545
3463
  if (!hub || Cabinets.isClassic(h, door) || Cabinets.cabinetDoorIds(h).has(door) || isLayerDoor(h, door)) {
1546
3464
  return;
1547
3465
  }
1548
- const users = membersOf(h, [...on].filter((playerId) => !isShut(h, playerId, door)));
3466
+ const users = travelersOf(h, [...on].filter((playerId) => !isShut(h, playerId, door)));
1549
3467
  const members = [...users.keys()].sort();
1550
3468
  let pad = h.pads.get(door);
1551
3469
  if (pad?.firing) {
@@ -1594,6 +3512,8 @@ function doorShut(h, player, data) {
1594
3512
  if (!playerId || !found) {
1595
3513
  return;
1596
3514
  }
3515
+ h.resumeDeparting?.delete(playerId);
3516
+ h.actDeparting?.delete(playerId);
1597
3517
  unshut(h, playerId);
1598
3518
  if (h.padDoors.has(found.id) && !h.padDoors.get(found.id).has(playerId)) {
1599
3519
  // Already stepped off while the trip was failing.
@@ -1632,9 +3552,9 @@ function firePad(h, hub, door, playerIds) {
1632
3552
  console.warn(`[hub] no door "${door}" in this place`);
1633
3553
  return null;
1634
3554
  }
1635
- const members = membersOf(h, playerIds);
3555
+ const members = travelersOf(h, playerIds);
1636
3556
  if (!members.size) {
1637
- 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`);
1638
3558
  return null;
1639
3559
  }
1640
3560
  // The pad keeps its id until ghost answers the fire, so a retried go (or a
@@ -1671,12 +3591,12 @@ function padFired(h, door, pad, users, fired) {
1671
3591
  const found = doors(h).find((d) => d.id === door);
1672
3592
  const group = Array.isArray(fired) ? fired : [];
1673
3593
  // The group is ghost's; anyone of it still here goes, on the pad now or not.
1674
- const here = membersOf(h, h.session?.players.map((p) => p.playerId));
3594
+ const here = travelersOf(h, h.session?.players.map((p) => p.playerId));
1675
3595
  tellWent(h, group.map((userId) => users.get(userId) ?? here.get(userId)).filter(Boolean), door);
1676
3596
  for (const userId of group) {
1677
3597
  const playerId = users.get(userId) ?? here.get(userId);
1678
3598
  if (playerId) {
1679
- h.session?.send(playerId, {
3599
+ sendGo(h, playerId, {
1680
3600
  k: 'hub-go',
1681
3601
  door,
1682
3602
  pad: pad.padId,
@@ -1708,10 +3628,28 @@ function readResults(h) {
1708
3628
  const userId = [...membersOf(h, [playerId]).keys()][0];
1709
3629
  if (!userId) {
1710
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
+ }
1711
3638
  continue;
1712
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;
3644
+ continue;
3645
+ }
3646
+ lifetime.phase = 'reading';
1713
3647
  entry.read = 'reading';
1714
- users.set(userId, { playerId, avatarRev: entry.avatarRev, wearRev: h.wearRev.get(playerId) ?? 0, startedAt: Date.now() });
3648
+ users.set(userId, {
3649
+ playerId,
3650
+ state,
3651
+ lifetime,
3652
+ });
1715
3653
  }
1716
3654
  if (users.size) {
1717
3655
  hub
@@ -1723,55 +3661,274 @@ function readResults(h) {
1723
3661
  })
1724
3662
  .catch((err) => refused(h, 'results', err))
1725
3663
  .finally(() => {
1726
- for (const { playerId } of users.values()) {
1727
- const entry = h.players.get(playerId);
1728
- if (entry?.read === 'reading') {
1729
- 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
+ }
1730
3675
  }
1731
3676
  }
1732
3677
  });
1733
3678
  }
1734
3679
  const now = Date.now();
1735
- if (now - h.boardsAt < BOARD_EVERY_MS) {
3680
+ if (h.boardsReading || now - h.boardsAt < BOARD_EVERY_MS) {
1736
3681
  return;
1737
3682
  }
1738
3683
  // A cabinet's board carries its pictures (v1.7), and a read answers in one
1739
3684
  // frame of the host's channel: cabinets are read apart from the doors, a
1740
- // few at a time. A place with none makes the one read it always did.
3685
+ // few at a time.
1741
3686
  const cabinets = Cabinets.cabinetDoorIds(h);
1742
3687
  const all = doors(h).map((d) => d.id);
1743
- const doorIds = all.filter((id) => !cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
1744
- const batches = doorIds.length ? [doorIds] : [];
1745
- const cabinetIds = all.filter((id) => cabinets.has(id)).slice(0, MAX_BOARD_DOORS);
3688
+ const doorIds = all.filter((id) => !cabinets.has(id));
3689
+ const batches = [];
3690
+ for (let i = 0; i < doorIds.length; i += BOARD_DOORS_PER_READ) {
3691
+ batches.push(doorIds.slice(i, i + BOARD_DOORS_PER_READ));
3692
+ }
3693
+ const cabinetIds = all.filter((id) => cabinets.has(id));
1746
3694
  for (let i = 0; i < cabinetIds.length; i += CABINET_BOARDS_PER_READ) {
1747
3695
  batches.push(cabinetIds.slice(i, i + CABINET_BOARDS_PER_READ));
1748
3696
  }
1749
3697
  if (batches.length) {
1750
3698
  h.boardsAt = now;
1751
- Promise.all(batches.map((ids) => hub.readResults({ doorIds: ids })))
1752
- .then((reads) => {
1753
- h.boards = new Map(reads.flatMap((read) => Object.entries(read.boards ?? {})));
1754
- // Doors to other decks take their title and group from the boards,
1755
- // and a cabinet its card.
1756
- Cabinets.refresh(h, doors(h));
1757
- })
1758
- .catch((err) => refused(h, 'boards', err));
3699
+ h.boardsReading = true;
3700
+ const read = h.manifest.weeklyCup === true
3701
+ ? readWeeklyCup(h, hub, batches)
3702
+ : readBoards(h, hub, batches);
3703
+ read
3704
+ .catch((err) => refused(h, 'boards', err))
3705
+ .finally(() => {
3706
+ h.boardsReading = false;
3707
+ });
3708
+ }
3709
+ }
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
+ }
1759
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
+
3863
+ // Storage requests share a small in-flight budget with other hub ops. Read
3864
+ // one batch at a time, keeping the previous boards of a batch that fails.
3865
+ async function readBoards(h, hub, batches) {
3866
+ const boards = new Map(h.boards);
3867
+ for (const ids of batches) {
3868
+ try {
3869
+ const read = await hub.readResults({ doorIds: ids });
3870
+ const rows = Object.entries(read.boards ?? {});
3871
+ for (const id of ids) {
3872
+ boards.delete(id);
3873
+ }
3874
+ for (const [id, board] of rows) {
3875
+ boards.set(id, board);
3876
+ }
3877
+ h.boards = boards;
3878
+ } catch (err) {
3879
+ refused(h, 'boards', err);
3880
+ }
3881
+ }
3882
+ const listed = new Set(doors(h).map((d) => d.id));
3883
+ for (const id of boards.keys()) {
3884
+ if (!listed.has(id)) {
3885
+ boards.delete(id);
3886
+ }
3887
+ }
3888
+ h.boards = boards;
3889
+ // Doors to other decks take their title and group from the boards,
3890
+ // and a cabinet its card, even when another batch failed.
3891
+ Cabinets.refresh(h, doors(h));
1760
3892
  }
1761
3893
 
1762
- function applyRead(h, { playerId, avatarRev, wearRev, 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) {
1763
3910
  const entry = h.players.get(playerId);
1764
- if (!entry || !read) {
3911
+ if (!entry || entry.progressState !== state || h.progressStates.get(playerId) !== state || state.readLifetime !== lifetime || !read) {
1765
3912
  return;
1766
3913
  }
3914
+ const { avatarRev, colorRev, wearRev, earnedRev, startedAt } = lifetime;
1767
3915
  // Their results and records, for `hub.results` (v1.5).
1768
3916
  History.take(h, playerId, read, startedAt);
1769
3917
  // The wearable likewise, unless the game put one on since (v1.4).
1770
3918
  Wear.applyRead(h, playerId, wearRev, read);
3919
+ // The earned item likewise, unless an unlock or choice was made since (v1.53).
3920
+ Earned.applyRead(h, playerId, earnedRev, read);
1771
3921
  // The platform avatar, unless the client chose another since the read began.
1772
- 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) {
3923
+ if (entry.avatar !== read.avatar) {
3924
+ // A colour queued for the previous character cannot follow a new body.
3925
+ entry.color = cleanAvatarColor(read.avatarColor);
3926
+ }
1773
3927
  entry.avatar = read.avatar;
1774
3928
  }
3929
+ if (!entry.signUp && entry.colorRev === colorRev) {
3930
+ entry.color = cleanAvatarColor(read.avatarColor);
3931
+ }
1775
3932
  const row = entry.fromDeckId
1776
3933
  ? (read.recent ?? []).find((r) => r.deckId === entry.fromDeckId && Date.now() - Date.parse(r.at) < RESULT_FRESH_MS)
1777
3934
  : null;
@@ -1803,6 +3960,30 @@ function refused(h, op, err) {
1803
3960
  }
1804
3961
  }
1805
3962
 
3963
+ // A place's next-visit line (v1.52), latched for its player alone. Send now
3964
+ // so a subsequent hub.go or hub.end cannot overtake the line.
3965
+ function leaving(h, playerId, text) {
3966
+ if (typeof playerId !== 'string' || !(h.players.has(playerId) || h.sim?.players.has(playerId))) {
3967
+ refused(h, 'leaving', { code: 'player', message: 'a player here is required' });
3968
+ return false;
3969
+ }
3970
+ if (text !== null && typeof text !== 'string') {
3971
+ refused(h, 'leaving', { code: 'text', message: 'text must be a string or null' });
3972
+ return false;
3973
+ }
3974
+ const line = text === null ? null : text.trim().slice(0, HUD_LIMITS.text) || null;
3975
+ if ((h.leaving.get(playerId) ?? null) === line) {
3976
+ return true;
3977
+ }
3978
+ if (line === null) {
3979
+ h.leaving.delete(playerId);
3980
+ } else {
3981
+ h.leaving.set(playerId, line);
3982
+ }
3983
+ h.session?.send(playerId, { k: 'hub-leaving', text: line });
3984
+ return true;
3985
+ }
3986
+
1806
3987
  // Per-player HUD overrides go to their player alone, when they change. Where
1807
3988
  // a block hides players, each player is also sent the shared HUD as they may
1808
3989
  // read it, when that names someone the shared one leaves out.
@@ -1810,6 +3991,7 @@ function sendHudOverrides(h) {
1810
3991
  const hidden = blockedPairs(h);
1811
3992
  const all = hidden ? namesOf(h, hidden.keys()) : null;
1812
3993
  for (const playerId of h.sim.players.keys()) {
3994
+ if (h.players.get(playerId)?.progressReading) { continue; }
1813
3995
  let spec = h.hudMe.get(playerId) ?? null;
1814
3996
  if (hidden) {
1815
3997
  const names = namesOf(h, hidden.get(playerId) ?? []);
@@ -1859,6 +4041,12 @@ function sendLabelOverrides(h) {
1859
4041
  delete out[id];
1860
4042
  }
1861
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
+ }
1862
4050
  const json = JSON.stringify(out);
1863
4051
  if ((h.sentLabelsMe.get(playerId) ?? '{}') !== json) {
1864
4052
  h.sentLabelsMe.set(playerId, json);
@@ -1945,16 +4133,96 @@ function labelsOf(h) {
1945
4133
  // Every helloed player's avatar, for everyone: all but the players a block
1946
4134
  // hides from someone here, whose avatars go to each player who may see them
1947
4135
  // alone (`sendAvatarOverrides`).
4136
+ //
4137
+ // `hubAv` only ever carries one of the first four (v1.51): a client from
4138
+ // before the twelve has no blueprint for another and would not draw the
4139
+ // player at all, so one who wears 4-15 is listed there as `avatar % 4`, the
4140
+ // stand-in a v1.51 client draws for an index past its own. Who really wears
4141
+ // what is `hubAv2`, below.
1948
4142
  function avatars(h, hidden) {
1949
4143
  const out = {};
1950
4144
  for (const [playerId, entry] of h.players) {
1951
4145
  if (entry.hello && !hidden?.has(playerId)) {
4146
+ out[playerId] = standIn(entry.avatar);
4147
+ }
4148
+ }
4149
+ return out;
4150
+ }
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
+
4167
+ function standIn(avatar) {
4168
+ return avatar < OLD_AVATARS ? avatar : avatar % OLD_AVATARS;
4169
+ }
4170
+
4171
+ // `hubAv2` (v1.51): the avatar of each player who wears one past the first
4172
+ // four, by `hubAv`'s rules of who is listed. A client that knows it draws
4173
+ // that; one from before ignores it and draws `hubAv`'s stand-in.
4174
+ function avatars2(h, hidden) {
4175
+ const out = {};
4176
+ for (const [playerId, entry] of h.players) {
4177
+ if (entry.hello && !hidden?.has(playerId) && entry.avatar >= OLD_AVATARS) {
1952
4178
  out[playerId] = entry.avatar;
1953
4179
  }
1954
4180
  }
1955
4181
  return out;
1956
4182
  }
1957
4183
 
4184
+ // In the snapshot only while someone wears one; in deltas from the first one
4185
+ // on, and `{}` once when the last is gone, so a client that had the block
4186
+ // hears that it is empty. A place where nobody ever wears one never sends the
4187
+ // key: its bytes are what they were before v1.51.
4188
+ function avatars2ForJoin(h) {
4189
+ const real = avatars2(h, blockedPairs(h));
4190
+ return Object.keys(real).length ? { hubAv2: real } : {};
4191
+ }
4192
+
4193
+ function latchAvatars2(h, out) {
4194
+ const real = avatars2(h, blockedPairs(h));
4195
+ if (Object.keys(real).length || h.sent.has('hubAv2')) {
4196
+ latch(h, 'hubAv2', real, out);
4197
+ }
4198
+ }
4199
+
4200
+ function cleanAvatarColor(color) {
4201
+ return Number.isInteger(color) && color >= 0 && color < 16 ? color : 0;
4202
+ }
4203
+
4204
+ function avatarColors(h, hidden) {
4205
+ const out = {};
4206
+ for (const [playerId, entry] of h.players) {
4207
+ if (entry.hello && !hidden?.has(playerId) && entry.color > 0) {
4208
+ out[playerId] = entry.color;
4209
+ }
4210
+ }
4211
+ return out;
4212
+ }
4213
+
4214
+ function avatarColorsForJoin(h) {
4215
+ const colors = avatarColors(h, blockedPairs(h));
4216
+ return Object.keys(colors).length ? { hubAvC: colors } : {};
4217
+ }
4218
+
4219
+ function latchAvatarColors(h, out) {
4220
+ const colors = avatarColors(h, blockedPairs(h));
4221
+ if (Object.keys(colors).length || h.sent.has('hubAvC')) {
4222
+ latch(h, 'hubAvC', colors, out);
4223
+ }
4224
+ }
4225
+
1958
4226
  // Who a block hides from whom (`blocks.js`), asked of the host once a tick
1959
4227
  // and again when the roster changes.
1960
4228
  function blockedPairs(h) {
@@ -1970,18 +4238,52 @@ function blockedPairs(h) {
1970
4238
  // them, when they change. A session with no blocks sends nothing here.
1971
4239
  function sendAvatarOverrides(h) {
1972
4240
  const hidden = blockedPairs(h);
4241
+ const anonymousEntry = h.place.anonymousEntry === true;
1973
4242
  for (const playerId of h.sim.players.keys()) {
1974
4243
  const out = {};
4244
+ // v1.51: as `hubAv` and `hubAv2` are, the stand-in for everyone and the
4245
+ // avatar really worn beside it, the second only when there is one.
4246
+ const real = {};
4247
+ const colors = {};
4248
+ const guestOverrides = [];
1975
4249
  for (const shrouded of hidden?.keys() ?? []) {
1976
4250
  const entry = h.players.get(shrouded);
1977
4251
  if (entry?.hello && !hidden.get(playerId)?.has(shrouded)) {
1978
- out[shrouded] = entry.avatar;
4252
+ out[shrouded] = standIn(entry.avatar);
4253
+ if (anonymousEntry && h.session?.players.find((p) => p.playerId === shrouded)?.isAnonymous === true) {
4254
+ guestOverrides.push(shrouded);
4255
+ }
4256
+ if (entry.color > 0) {
4257
+ colors[shrouded] = entry.color;
4258
+ }
4259
+ if (entry.avatar >= OLD_AVATARS) {
4260
+ real[shrouded] = entry.avatar;
4261
+ }
1979
4262
  }
1980
4263
  }
1981
- const json = JSON.stringify(out);
4264
+ // The message is the whole of what this player is told here: one without
4265
+ // `hubAv2` says nobody in it wears one of the twelve (any more).
4266
+ const some = Object.keys(real).length > 0;
4267
+ const colored = Object.keys(colors).length > 0;
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);
1982
4278
  if ((h.sentAvMe.get(playerId) ?? '{}') !== json) {
1983
4279
  h.sentAvMe.set(playerId, json);
1984
- h.session?.send(playerId, { k: 'hub-av', hubAv: out });
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
+ });
1985
4287
  }
1986
4288
  }
1987
4289
  }
@@ -2010,6 +4312,31 @@ function latchWearing(h, out) {
2010
4312
  }
2011
4313
  }
2012
4314
 
4315
+ // What `hub.unlock` and `hub.wearEarned` (v1.53) are handed.
4316
+ function earnedDeps(h, playerId, op) {
4317
+ return {
4318
+ platform: platformHub(h),
4319
+ userId: userIdOf(h, playerId),
4320
+ declared: h.unlocks,
4321
+ deckId: h.deckId,
4322
+ refused: (err) => refused(h, op, err),
4323
+ };
4324
+ }
4325
+
4326
+ // `hubEarned` (v1.53) as `hubWear` goes: in the snapshot only while someone
4327
+ // shows an earned item, in deltas from the first one on.
4328
+ function earnedForJoin(h) {
4329
+ const earned = Earned.earnedForAll(h, blockedPairs(h));
4330
+ return Object.keys(earned).length ? { hubEarned: earned } : {};
4331
+ }
4332
+
4333
+ function latchEarned(h, out) {
4334
+ const earned = Earned.earnedForAll(h, blockedPairs(h));
4335
+ if (Object.keys(earned).length || h.sent.has('hubEarned')) {
4336
+ latch(h, 'hubEarned', earned, out);
4337
+ }
4338
+ }
4339
+
2013
4340
  // `hubTry` (v1.28) the same way: in the snapshot only while a try-on is
2014
4341
  // shown, in deltas from the first one on, `{}` once when the last is gone.
2015
4342
  function tryingForJoin(h) {
@@ -2025,6 +4352,26 @@ function latchTrying(h, out) {
2025
4352
  }
2026
4353
 
2027
4354
  function latch(h, field, value, out) {
4355
+ if (h.cells && ['labels', 'tints', 'marks'].includes(field)) {
4356
+ const previous = h.sentMaps.get(field) ?? {};
4357
+ const next = Object.fromEntries(Object.entries(value).map(([id, v]) => [id, JSON.stringify(v)]));
4358
+ const delta = Object.create(null);
4359
+ for (const [id, json] of Object.entries(next)) {
4360
+ if (previous[id] !== json) {
4361
+ delta[id] = value[id];
4362
+ }
4363
+ }
4364
+ for (const id of Object.keys(previous)) {
4365
+ if (!Object.hasOwn(next, id)) {
4366
+ delta[id] = null;
4367
+ }
4368
+ }
4369
+ h.sentMaps.set(field, next);
4370
+ if (Object.keys(delta).length) {
4371
+ out[`${field}D`] = delta;
4372
+ }
4373
+ return;
4374
+ }
2028
4375
  const json = JSON.stringify(value);
2029
4376
  if (h.sent.get(field) !== json) {
2030
4377
  h.sent.set(field, json);
@@ -2032,6 +4379,50 @@ function latch(h, field, value, out) {
2032
4379
  }
2033
4380
  }
2034
4381
 
4382
+ // Both hooks share one body-cell and camera-neighbour lookup per tick.
4383
+ function playerCells(h, sim) {
4384
+ if (h.cellTick === sim.timeMs && h.cellViews) {
4385
+ return h.cellViews;
4386
+ }
4387
+ h.cellTick = sim.timeMs;
4388
+ h.cellViews = new Map();
4389
+ for (const [id, player] of sim.players) {
4390
+ const at = player.at;
4391
+ const cell = Cells.cellAt(h.cells, at.x, at.z, h.playerCells.get(id));
4392
+ h.playerCells.set(id, cell);
4393
+ h.cellViews.set(id, { cell, visible: Cells.visibleCells(h.cells, at.x, at.z) });
4394
+ }
4395
+ return h.cellViews;
4396
+ }
4397
+
4398
+ function cellPlayers(h, sim, known, hidden) {
4399
+ const views = playerCells(h, sim);
4400
+ const userIds = new Map([...sim.players.keys()].map((id) => [id, friendUserIdOf(h, id)]));
4401
+ const sees = new Map();
4402
+ const now = Date.now();
4403
+ for (const [viewer, view] of views) {
4404
+ const cached = h.friendsCache?.get(viewer);
4405
+ const entry = cached && now - cached.at < cached.ttl ? cached : null;
4406
+ const friends = new Set([
4407
+ ...(entry?.ids ?? []), ...(entry?.follows ?? []), ...(entry?.followedBy ?? []),
4408
+ ]);
4409
+ const at = sim.players.get(viewer).at;
4410
+ const scored = [];
4411
+ for (const [id, candidate] of views) {
4412
+ if (id === viewer || hidden?.(viewer, id) || (view.visible !== null && candidate.cell !== null && !view.visible.has(candidate.cell))) {
4413
+ continue;
4414
+ }
4415
+ const other = sim.players.get(id).at;
4416
+ const d = (at.x - other.x) ** 2 + (at.y - other.y) ** 2 + (at.z - other.z) ** 2;
4417
+ scored.push({ id, friend: friends.has(userIds.get(id)), d: known.get(viewer)?.has(id) ? d * KEEP_NEARER ** 2 : d });
4418
+ }
4419
+ scored.sort((a, b) => Number(b.friend) - Number(a.friend) || a.d - b.d);
4420
+ const cap = Math.min(h.caps.get(viewer) ?? h.place.nearestPlayers, h.place.nearestPlayers);
4421
+ sees.set(viewer, new Set(scored.slice(0, cap).map(({ id }) => id)));
4422
+ }
4423
+ return sees;
4424
+ }
4425
+
2035
4426
  // A scene actor of the place, or a copy the game spawned.
2036
4427
  function isSceneActor(h, id) {
2037
4428
  return Actors.isActor(h, id);
@@ -2042,6 +4433,13 @@ function isSceneActor(h, id) {
2042
4433
  // subjects (`dev-guest-<n>`) count, since their storage works there.
2043
4434
  const DEV_GUEST = /^dev-guest-\d{1,6}$/;
2044
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
+
2045
4443
  function userIdOf(h, playerId) {
2046
4444
  const p = h.session?.players.find((q) => q.playerId === playerId);
2047
4445
  if (!p) {
@@ -2054,6 +4452,23 @@ function userIdOf(h, playerId) {
2054
4452
  return dev && DEV_GUEST.test(String(p.userId)) ? String(p.userId) : null;
2055
4453
  }
2056
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
+
2057
4472
  function usernameOf(h, playerId) {
2058
4473
  return h.session?.players.find((p) => p.playerId === playerId)?.username ?? 'player';
2059
4474
  }