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
@@ -4,9 +4,15 @@
4
4
  // budget, who sees a reply, and following only what the world says.
5
5
 
6
6
  import assert from 'node:assert/strict';
7
+ import { npcDisplayText } from '../code/npcDisplayText.js';
8
+ import { readFileSync } from 'node:fs';
7
9
  import { setLabel, wireLabel } from '../code/server/labels.js';
8
10
  import { firstJoinFor } from '../code/client/firstJoin.js';
9
11
  import { NOTES_HEAD, NOTES_MAX, NOTES_SAYS, makeNpcs } from '../code/server/npcs.js';
12
+ import * as Idle from '../code/server/idle.js';
13
+ import { makeTalk } from '../code/client/talk.js';
14
+ import { hub as clientHub, clear as clearClientHub } from '../code/client/state.js';
15
+ import * as Rehello from '../code/client/rehello.js';
10
16
 
11
17
  function body(x, z) {
12
18
  const b = {
@@ -29,7 +35,9 @@ function body(x, z) {
29
35
  // through the route on an older SDK (`session.world.characters` only),
30
36
  // 'layer' a layer of the place (`session.characters`, `session.world` null),
31
37
  // 'world' a world on an SDK with place characters (both, the same object).
32
- function world({ mind = true, turnsPerMinute = 6, inspect, notes = null, extra = [] } = {}) {
38
+ const bundleAsks = Object.fromEntries(JSON.parse(readFileSync(new URL('../../../experiments/hub-town/castle.json', import.meta.url), 'utf8')).characterBundle.characters.filter((c) => c.childAsks).map((c) => [c.id, c.childAsks]));
39
+
40
+ function world({ childAsks, greeterName = 'Rowan', firstVisit = false, mind = true, turnsPerMinute = 6, turnsAtOnce, bodyTurnsAtOnce, inspect, notes = null, extra = [] } = {}) {
33
41
  const sent = [];
34
42
  const labels = [];
35
43
  const lines = [];
@@ -37,12 +45,16 @@ function world({ mind = true, turnsPerMinute = 6, inspect, notes = null, extra =
37
45
  const heard = [];
38
46
  const sim = { timeMs: 0, players: new Map(), bodies: new Map([['greeter', body(0, 0)], ...extra.map((e) => [e.id, body(e.x, e.z)])]) };
39
47
  const h = {
48
+ ...(firstVisit ? { firstVisit: { live: ['npc'] } } : {}),
40
49
  sim,
50
+ ...(childAsks ? { characterBundle: { characters: [{ id: 'greeter', childAsks }] } } : {}),
51
+ players: new Map(),
52
+ ...Idle.newIdleState(),
41
53
  actors: [
42
- { id: 'greeter', components: { HubNpc: { name: 'Rowan', character: 'greeter', follow: 'greeterFollow' }, Transform: { x: 0, y: 1, z: 0 } } },
54
+ { id: 'greeter', components: { HubNpc: { name: greeterName, character: 'greeter', follow: 'greeterFollow', ...(bodyTurnsAtOnce !== undefined ? { turnsAtOnce: bodyTurnsAtOnce } : {}) }, Transform: { x: 0, y: 1, z: 0 } } },
43
55
  ...extra.map((e) => ({ id: e.id, components: { HubNpc: { name: e.name, character: e.character }, Transform: { x: e.x, y: 1, z: e.z } } })),
44
56
  ],
45
- place: { npcs: mind ? { route: 'town', slot: 'main', turnsPerMinute, disclosure: 'participants', followSec: 120 } : null },
57
+ place: { npcs: mind ? { route: 'town', slot: 'main', turnsPerMinute, ...(turnsAtOnce !== undefined ? { turnsAtOnce } : {}), disclosure: 'participants', followSec: 120 } : null },
46
58
  session: sessionFor(mind, {
47
59
  publicInspect: async () => {
48
60
  reads.inspect += 1;
@@ -70,7 +82,10 @@ function world({ mind = true, turnsPerMinute = 6, inspect, notes = null, extra =
70
82
  h.npcLabel = (id, text, options) => labels.push({ id, text, to: options?.to ?? null, about: options?.about ?? null });
71
83
  h.npcs = makeNpcs(h);
72
84
  h.npcs.ready();
73
- const at = (playerId, x, z) => sim.players.set(playerId, { at: { x, y: 1, z } });
85
+ const at = (playerId, x, z) => {
86
+ h.players.set(playerId, { arrived: true, ended: false });
87
+ sim.players.set(playerId, { at: { x, y: 1, z } });
88
+ };
74
89
  const tick = (ms = 100) => {
75
90
  sim.timeMs += ms;
76
91
  h.npcs.place(ms / 1000);
@@ -101,9 +116,11 @@ function turn({ speaker, audience = [], disclosure = 'participants', operationId
101
116
  input,
102
117
  audience: { disclosure, players: audience.map((playerId) => ({ playerId })), characterIds: [] },
103
118
  sent: 0,
119
+ sendArgs: [],
104
120
  rejected: null,
105
- async send() {
121
+ async send(...args) {
106
122
  t.sent += 1;
123
+ t.sendArgs.push(args);
107
124
  return { operationId, status: 'queued', replayed: false };
108
125
  },
109
126
  reject(code) {
@@ -175,7 +192,7 @@ await test('without a mind the place answers, and no turn is admitted', async ()
175
192
  assert.equal(w.sent.find((m) => m.k === 'hub-npc').mind, false);
176
193
  assert.equal(w.lines.at(-1).why, 'hello');
177
194
  w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'hi there' });
178
- assert.deepEqual(w.lines.at(-1), { npc: 'greeter', playerId: 'a', why: 'authored', text: 'hi there' });
195
+ assert.deepEqual(w.lines.at(-1), { npc: 'greeter', playerId: 'a', why: 'authored', text: 'hi there', conversation: 1 });
179
196
  // Authored lines are the place's own words, for everyone.
180
197
  assert.equal(w.labels.at(-1).to, null);
181
198
  assert.equal(w.sent.at(-1).k, 'hub-npc-line');
@@ -278,6 +295,7 @@ await test('over budget the place answers, no model is called', async () => {
278
295
  assert.equal(t.rejected, 'HUB_NPC_BUDGET');
279
296
  assert.equal(t.sent, 0);
280
297
  assert.equal(w.lines.at(-1).why, 'budget');
298
+ assert.equal(w.sent.findLast((m) => m.k === 'hub-npc-line').op, 'op9');
281
299
  });
282
300
 
283
301
  await test("a full place-mind queue is the place's busy line, a spent town-wide budget its budget line, another failure its unavailable one", async () => {
@@ -295,9 +313,50 @@ await test("a full place-mind queue is the place's busy line, a spent town-wide
295
313
  };
296
314
  await w.npcs.onTurn(t).catch(() => {});
297
315
  assert.equal(w.lines.at(-1).why, why, code);
316
+ assert.equal(w.sent.findLast((m) => m.k === 'hub-npc-line').op, t.operationId, code);
317
+ }
318
+ });
319
+
320
+ const characterRefusal = () => Object.assign(new Error('characters are unavailable right now'), { code: 'CAULDRON_CHARACTER_UNAVAILABLE' });
321
+
322
+ await test("a turn ghost refused characters gets the kit's calm unavailable line, decided by that turn alone", async () => {
323
+ const w = world();
324
+ w.h.hooks.npcLine = (_hub, npc, playerId, info) => { w.lines.push({ npc: npc.id, playerId, ...info }); return null; };
325
+ w.at('a', 0, 2);
326
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
327
+ for (const [operationId, err, said] of [
328
+ ['op1', characterRefusal(), 'Rowan smiles and nods.'],
329
+ ['op2', Object.assign(new Error('refused'), { code: 'CAULDRON_UPSTREAM' }), "Rowan doesn't catch that. Try again in a moment."],
330
+ ]) {
331
+ const t = turn({ speaker: 'a', operationId });
332
+ t.send = async () => { throw err; };
333
+ await w.npcs.onTurn(t).catch(() => {});
334
+ assert.equal(w.lines.at(-1).why, 'unavailable', 'the hook still hears unavailable');
335
+ const sent = w.sent.findLast((m) => m.k === 'hub-npc-line');
336
+ assert.deepEqual([sent.text, sent.why, sent.op], [said, 'unavailable', operationId]);
298
337
  }
299
338
  });
300
339
 
340
+ await test('a refusal in flight across leave leaves nothing for the next speaker', async () => {
341
+ const w = world();
342
+ w.h.hooks.npcLine = () => null;
343
+ w.at('a', 0, 2);
344
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
345
+ let fail;
346
+ const t = turn({ speaker: 'a' });
347
+ t.send = () => new Promise((_resolve, reject) => { fail = reject; });
348
+ const sending = w.npcs.onTurn(t).catch(() => {});
349
+ await Promise.resolve();
350
+ w.npcs.leave('a');
351
+ fail(characterRefusal()); await sending;
352
+ w.at('a', 0, 2);
353
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
354
+ const next = turn({ speaker: 'a', operationId: 'op2' });
355
+ next.send = async () => { throw Object.assign(new Error('refused'), { code: 'CAULDRON_UPSTREAM' }); };
356
+ await w.npcs.onTurn(next).catch(() => {});
357
+ assert.equal(w.sent.findLast((m) => m.k === 'hub-npc-line').text, "Rowan doesn't catch that. Try again in a moment.");
358
+ });
359
+
301
360
  await test('a replayed admission keeps its first record', async () => {
302
361
  const w = world();
303
362
  w.at('a', 0, 2);
@@ -387,6 +446,7 @@ await test('ending the conversation does not free the body from an unanswered tu
387
446
  const t = turn({ speaker: 'b', operationId: 'b1' });
388
447
  await w.npcs.onTurn(t);
389
448
  assert.equal(t.rejected, 'HUB_NPC_BUSY');
449
+ assert.equal(w.sent.findLast((m) => m.k === 'hub-npc-line').op, 'b1');
390
450
  // Nor does a's leaving.
391
451
  w.npcs.leave('a');
392
452
  const again = turn({ speaker: 'b', operationId: 'b2' });
@@ -467,6 +527,40 @@ await test('a failed public read backs off and later sees the follow', async ()
467
527
  }
468
528
  });
469
529
 
530
+ await test('failing public reads back off to five minutes, warned once per run', async () => {
531
+ let fail = false;
532
+ const w = world({ inspect: () => (fail ? characterRefusal() : { gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } }) });
533
+ // A follow that outlasts the test keeps the poll going.
534
+ w.h.place.npcs.followSec = 10_000;
535
+ w.at('a', 0, 2);
536
+ await w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: async () => ({ participantId: 'p-a' }), reject() {} });
537
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
538
+ await w.npcs.onTurn(turn({ speaker: 'a' }));
539
+ await w.npcs.onRead(statusRead('a', 'op1', 'Sure!'));
540
+ w.tick();
541
+ await new Promise((resolve) => setImmediate(resolve));
542
+ assert.equal(w.npcs.handle('greeter').following, 'a', 'a follow keeps the poll going');
543
+ fail = true;
544
+ const warn = console.warn, warned = [];
545
+ console.warn = (...args) => warned.push(args.join(' '));
546
+ try {
547
+ const times = [];
548
+ for (let i = 0; i < 3000 && times.length < 12; i++) {
549
+ const before = w.reads.inspect;
550
+ w.tick(1000);
551
+ await new Promise((resolve) => setImmediate(resolve));
552
+ if (w.reads.inspect > before) times.push(w.sim.timeMs);
553
+ }
554
+ const gaps = times.slice(1).map((at, i) => at - times[i]);
555
+ assert(gaps.every((gap, i) => i === 0 || gap >= gaps[i - 1]), `gaps grow: ${gaps}`);
556
+ assert.equal(gaps.at(-1), gaps.at(-2), `the gap is capped: ${gaps}`);
557
+ assert(gaps.at(-1) >= 300_000 && gaps.at(-1) <= 301_000, `capped at five minutes: ${gaps}`);
558
+ assert.equal(warned.length, 1);
559
+ } finally {
560
+ console.warn = warn;
561
+ }
562
+ });
563
+
470
564
  for (const mind of ['layer', 'world']) {
471
565
  await test(`with place characters (${mind}), a mind answers from session.characters and its follow is read there`, async () => {
472
566
  const w = world({ mind, inspect: () => ({ gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } }) });
@@ -571,6 +665,146 @@ await test("blocks: the kit's line naming a player is marked as about them", asy
571
665
  assert.equal(hello.to, null);
572
666
  });
573
667
 
668
+ await test('v1.80: without npcAsks the notes trace is byte-identical to the captured v1.77 fixture', async () => {
669
+ let ledger = 'one';
670
+ const w = world({ notes: () => ledger });
671
+ w.at('a', 0, 2);
672
+ w.at('b', 2, 0);
673
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
674
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
675
+ w.tick(1100);
676
+ ledger = 'two';
677
+ w.tick(1100);
678
+ await w.npcs.onTurn(turn({ speaker: 'a', input: 'missing notes' }));
679
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
680
+ ledger = 'three';
681
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
682
+ const trace = w.sent.filter((m) => m.k === 'hub-npc-notes').map((m) => JSON.stringify(m)).join('\n') + '\n';
683
+ assert.equal(trace, readFileSync(new URL('./fixtures/npc-notes-v1.77.jsonl', import.meta.url), 'utf8'));
684
+ });
685
+
686
+ await test('v1.80: persistent asks trim, cap at forty, deduplicate after cutting, and keep at most two strings', () => {
687
+ const w = world({ notes: () => 'Same notes.' });
688
+ w.h.hooks.npcAsks = (hub, npc, playerId) => {
689
+ assert.equal(hub, w.h.ctx);
690
+ assert.equal(npc.id, 'greeter');
691
+ assert.equal(playerId, 'a');
692
+ return { persistentAsks: [null, 7, {}, '', ' ', ' x'.padEnd(70, 'x'), 'x'.repeat(50), ' Gift? ', 'Gift?', 'Third?'] };
693
+ };
694
+ w.at('a', 0, 2);
695
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
696
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, ['x'.repeat(40), 'Gift?']);
697
+ for (const value of [null, undefined, 'Gift?', ['Gift?'], { persistentAsks: 'Gift?' }, { persistentAsks: [false, {}, [], '', ' '] }]) {
698
+ const bare = world({ notes: () => 'Same notes.' });
699
+ bare.h.hooks.npcAsks = () => value;
700
+ bare.at('a', 0, 2);
701
+ bare.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
702
+ assert.deepEqual(bare.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, []);
703
+ }
704
+ });
705
+
706
+ await test('v1.80: unchanged notes re-read the offer, send chip-only changes and clear a stopped offer', () => {
707
+ const w = world({ notes: () => 'Same notes.' });
708
+ let offered = { persistentAsks: ['Gift?'] };
709
+ let calls = 0;
710
+ w.h.hooks.npcAsks = () => { calls += 1; return offered; };
711
+ w.at('a', 0, 2);
712
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
713
+ const first = w.sent.findLast((m) => m.k === 'hub-npc-notes');
714
+ const count = () => w.sent.filter((m) => m.k === 'hub-npc-notes').length;
715
+ w.tick(1100);
716
+ assert.equal(calls, 2);
717
+ assert.equal(count(), 1, 'an unchanged offer sends nothing');
718
+ offered = { persistentAsks: ['Another?'] };
719
+ w.tick(1100);
720
+ assert.equal(count(), 2);
721
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes'), { ...first, persistentAsks: ['Another?'] });
722
+ offered = null;
723
+ w.tick(1100);
724
+ assert.equal(count(), 3);
725
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes'), { ...first, persistentAsks: [] });
726
+ w.tick(1100);
727
+ assert.equal(count(), 3);
728
+ });
729
+
730
+ await test('v1.80: persistent asks work with a null prefix without inventing mind notes', async () => {
731
+ const w = world();
732
+ w.h.hooks.npcAsks = () => ({ persistentAsks: ['Gift?'] });
733
+ w.at('a', 0, 2);
734
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
735
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes'), { playerId: 'a', k: 'hub-npc-notes', npc: 'greeter', prefix: null, persistentAsks: ['Gift?'] });
736
+ const t = turn({ speaker: 'a', input: 'Gift?' });
737
+ await w.npcs.onTurn(t);
738
+ assert.equal(t.sent, 1);
739
+ w.h.hooks.npcAsks = () => null;
740
+ w.tick(1100);
741
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, []);
742
+ });
743
+
744
+ await test('v1.80: a refused turn re-reads and carries the latest persistent asks with fresh notes', async () => {
745
+ const w = world({ notes: () => 'Same notes.' });
746
+ let asks = ['Gift?'];
747
+ w.h.hooks.npcAsks = () => ({ persistentAsks: asks });
748
+ w.at('a', 0, 2);
749
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
750
+ asks = ['Changed?'];
751
+ const t = turn({ speaker: 'a', input: 'missing notes' });
752
+ await w.npcs.onTurn(t);
753
+ assert.equal(t.rejected, 'HUB_NPC_NOTES');
754
+ assert.equal(t.sent, 0);
755
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, ['Changed?']);
756
+ });
757
+
758
+ await test('v1.80: offers reach only their talking player, never a spectator or another conversation', () => {
759
+ const w = world({ notes: (_npc, playerId) => `Notes for ${playerId}.`, extra: [{ id: 'other', name: 'Other', character: 'other', x: 1, z: 0 }] });
760
+ const calls = [];
761
+ w.h.hooks.npcAsks = (_hub, npc, playerId) => { calls.push([npc.id, playerId]); return { persistentAsks: [`private:${playerId}`] }; };
762
+ for (const playerId of ['a', 'b', 'spectator']) w.at(playerId, 0, 2);
763
+ for (const [playerId, npc] of [['a', 'greeter'], ['b', 'other'], ['spectator', 'greeter']]) {
764
+ w.npcs.message({ playerId }, { k: 'hub-npc-open', npc });
765
+ }
766
+ w.tick(1100);
767
+ assert.deepEqual(calls, [['greeter', 'a'], ['other', 'b'], ['greeter', 'a'], ['other', 'b']]);
768
+ const notes = w.sent.filter((m) => m.k === 'hub-npc-notes');
769
+ assert.equal(notes.length, 2);
770
+ for (const msg of notes) assert.deepEqual(msg.persistentAsks, [`private:${msg.playerId}`]);
771
+ assert.ok(w.labels.every((label) => !label.text.includes('private:')));
772
+ });
773
+
774
+ await test('v1.80: throwing or rejected async npcAsks is contained, logged once without private words', async () => {
775
+ const w = world({ notes: () => 'Same notes.' });
776
+ const logs = [];
777
+ const warn = console.warn;
778
+ console.warn = (...args) => logs.push(args.join(' '));
779
+ try {
780
+ w.h.hooks.npcAsks = () => { throw new Error('Private gift words.'); };
781
+ w.at('a', 0, 2);
782
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
783
+ w.tick(1100);
784
+ assert.deepEqual(logs, ['[hub] npcAsks failed']);
785
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, []);
786
+ w.h.hooks.npcAsks = async () => { throw new Error('Private async words.'); };
787
+ w.tick(1100);
788
+ w.tick(1100);
789
+ await new Promise((done) => setImmediate(done));
790
+ assert.deepEqual(logs, ['[hub] npcAsks failed', '[hub] npcAsks async hook failed; using the default']);
791
+ } finally {
792
+ console.warn = warn;
793
+ }
794
+ });
795
+
796
+ await test('v1.80: the speaker binding is rechecked after npcAsks before private delivery', () => {
797
+ const w = world({ notes: () => 'Same notes.' });
798
+ w.at('a', 0, 2);
799
+ w.h.hooks.npcAsks = () => {
800
+ w.at('a', 0, 2); // Replace the exact player body inside the hook.
801
+ return { persistentAsks: ['private:old body'] };
802
+ };
803
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
804
+ assert.equal(w.sent.some((m) => m.k === 'hub-npc-notes'), false);
805
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
806
+ });
807
+
574
808
  await test("a mind's turn carries the place's notes, which only the server writes", async () => {
575
809
  let ledger = 'Task: beat Rowan at Foot Race.';
576
810
  const w = world({ notes: (npc, playerId) => (npc.id === 'greeter' ? `${ledger} For ${playerId}.` : null) });
@@ -578,7 +812,7 @@ await test("a mind's turn carries the place's notes, which only the server write
578
812
  w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
579
813
  const first = w.sent.find((m) => m.k === 'hub-npc-notes');
580
814
  assert.equal(first.playerId, 'a');
581
- assert.equal(first.prefix, `${NOTES_HEAD}Task: beat Rowan at Foot Race. For a.${NOTES_SAYS}`);
815
+ assert.equal(first.prefix, `${NOTES_HEAD}Task: beat Rowan at Foot Race. For a.\nYou opened this conversation by saying: "Hi, I'm Rowan! Ask me anything."${NOTES_SAYS}`);
582
816
  // Without the notes, or with notes of the player's own, nothing reaches ghost.
583
817
  const bare = turn({ speaker: 'a', input: 'what now?' });
584
818
  await w.npcs.onTurn(bare);
@@ -594,7 +828,7 @@ await test("a mind's turn carries the place's notes, which only the server write
594
828
  await w.npcs.onTurn(ok);
595
829
  assert.equal(ok.rejected, null);
596
830
  assert.equal(ok.sent, 1);
597
- assert.deepEqual(w.heard, [{ npc: 'greeter', playerId: 'a', text: 'what now?' }]);
831
+ assert.deepEqual(w.heard, [{ npc: 'greeter', playerId: 'a', text: 'what now?', conversation: 1 }]);
598
832
  });
599
833
 
600
834
  await test('changed notes are sent again; the previous ones stay good for a while', async () => {
@@ -638,12 +872,13 @@ await test("notes are capped and can't close their own frame", async () => {
638
872
  assert.ok(!/[[\]]/.test(body));
639
873
  });
640
874
 
641
- await test('a place with no notes admits the words alone', async () => {
875
+ await test('v1.46: null place notes still carry the default opening', async () => {
642
876
  const w = world({ notes: () => null });
643
877
  w.at('a', 0, 2);
644
878
  w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
645
- assert.equal(w.sent.find((m) => m.k === 'hub-npc-notes')?.prefix ?? null, null);
646
- const t = turn({ speaker: 'a', input: 'hello' });
879
+ const prefix = w.sent.find((m) => m.k === 'hub-npc-notes').prefix;
880
+ assert.ok(prefix.includes("Hi, I'm Rowan! Ask me anything."));
881
+ const t = turn({ speaker: 'a', input: `${prefix}hello` });
647
882
  await w.npcs.onTurn(t);
648
883
  assert.equal(t.rejected, null);
649
884
  const framed = turn({ speaker: 'a', operationId: 'op2', input: `${NOTES_HEAD}x${NOTES_SAYS}hello` });
@@ -694,7 +929,7 @@ await test('review: notes gone and back again; the newest notes win over an empt
694
929
  const t = turn({ speaker: 'a', input: `${prefix}hi` });
695
930
  await w.npcs.onTurn(t);
696
931
  assert.equal(t.rejected, null);
697
- assert.deepEqual(w.heard.at(-1), { npc: 'greeter', playerId: 'a', text: 'hi' });
932
+ assert.deepEqual(w.heard.at(-1), { npc: 'greeter', playerId: 'a', text: 'hi', conversation: 1 });
698
933
  });
699
934
 
700
935
  await test('review: a turn refused for its notes is sent the current ones again, even unchanged', async () => {
@@ -721,4 +956,2284 @@ await test('review: without npcContext a turn is the words as they came, markers
721
956
  assert.equal(t.sent, 1);
722
957
  });
723
958
 
724
- console.log(`hub-game npcs: ${n} tests passed`);
959
+ // v1.37: an NPC speaks first. A mindless body still needs the place's words.
960
+ await test('v1.37: npcOpening gives the first words and what to ask, cut to size; mindless bodies without it keep their hello', async () => {
961
+ // No hook: the open message has no `opening` key, and a body without a mind says its hello.
962
+ const plain = world({ mind: false });
963
+ plain.at('a', 0, 2);
964
+ plain.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
965
+ const was = plain.sent.find((m) => m.k === 'hub-npc' && m.open);
966
+ assert.equal('opening' in was, false);
967
+ assert.equal(plain.lines.at(-1).why, 'hello');
968
+
969
+ // With the hook, no mind: the opening is its hello (no `npcLine` hello too).
970
+ const w = world({ mind: false });
971
+ const asked = [];
972
+ w.h.hooks.npcOpening = (_hub, npc, playerId, info) => {
973
+ asked.push({ npc: npc.id, playerId, ...info });
974
+ return { text: ` ${'Welcome! '.repeat(40)}`, asks: ['What can I do here?', 7, '', 'What can I do here?', 'x'.repeat(60), 'Where is the inn?', 'A fifth'] };
975
+ };
976
+ w.at('a', 0, 2);
977
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
978
+ const opened = w.sent.find((m) => m.k === 'hub-npc' && m.open);
979
+ assert.equal(opened.opening.text.length, 240);
980
+ assert.ok(opened.opening.text.startsWith('Welcome!'));
981
+ assert.deepEqual(opened.opening.asks, ['What can I do here?', 'x'.repeat(40), 'Where is the inn?']);
982
+ assert.deepEqual(asked, [{ npc: 'greeter', playerId: 'a', met: false, greeting: null, conversation: 1 }]);
983
+ assert.equal(w.lines.length, 0, 'no hello line beside the opening');
984
+ // The opening goes to the one who opened, and to nobody else.
985
+ assert.deepEqual(w.sent.filter((m) => m.opening).map((m) => m.playerId), ['a']);
986
+ // Having said something, they have met: the next opening is told so.
987
+ w.tick(1000);
988
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'hi' });
989
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
990
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
991
+ assert.equal(asked.at(-1).met, true);
992
+ w.at('b', 1, 1);
993
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
994
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
995
+ assert.equal(asked.at(-1).met, false, 'someone else has not');
996
+ // A guest who leaves is forgotten; the record is bounded; a place with no hook keeps none.
997
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-say', npc: 'greeter', text: 'hi' });
998
+ assert.equal(w.npcs.metCount?.('greeter') ?? null, 2);
999
+ w.npcs.leave('b');
1000
+ assert.equal(w.npcs.metCount('greeter'), 1);
1001
+ assert.equal(plain.npcs.metCount('greeter'), 0);
1002
+ plain.tick(1000);
1003
+ plain.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'hi' });
1004
+ assert.equal(plain.npcs.metCount('greeter'), 0, 'no hook: nobody is kept');
1005
+
1006
+ // A string is the words alone; null, a thrown error or nothing usable is no opening.
1007
+ for (const [given, want] of [['Hello there.', { text: 'Hello there.', asks: [] }], [null, null], [{ asks: ['Why?'] }, null], [{ text: 5 }, null], [() => { throw new Error('boom'); }, null]]) {
1008
+ const v = world({ mind: false });
1009
+ v.h.hooks.npcOpening = typeof given === 'function' ? given : () => given;
1010
+ v.at('a', 0, 2);
1011
+ v.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1012
+ const msg = v.sent.find((m) => m.k === 'hub-npc' && m.open);
1013
+ assert.deepEqual(msg.opening ?? null, want);
1014
+ assert.equal(v.lines.some((l) => l.why === 'hello'), want === null, 'the hello line only when there is no opening');
1015
+ }
1016
+ });
1017
+
1018
+ await test('v1.37: with a mind, the opening is in that conversation\'s notes; v1.46: the next can get the default', async () => {
1019
+ const w = world({ notes: () => 'The pad is empty.' });
1020
+ w.h.hooks.npcOpening = () => ({ text: 'I am Rowan [the] greeter.', asks: ['Where do I go?'] });
1021
+ w.at('a', 0, 2);
1022
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1023
+ assert.equal(w.sent.find((m) => m.k === 'hub-npc' && m.open).opening.text, 'I am Rowan [the] greeter.');
1024
+ const first = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1025
+ assert.ok(first.includes('The pad is empty.') && first.includes('You opened this conversation by saying: "I am Rowan the greeter."'), first);
1026
+ // v1.46: null now gives a mind the kit's opening in the next conversation.
1027
+ w.h.hooks.npcOpening = () => null;
1028
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1029
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1030
+ const next = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1031
+ assert.ok(next.includes('The pad is empty.') && next.includes("Hi, I'm Rowan! Ask me anything.") && !next.includes('I am Rowan'), next);
1032
+
1033
+ // The place's notes come first and whole; the opening has what is left of
1034
+ // NOTES_MAX, and is left out where that is too little.
1035
+ for (const [size, wantOpening] of [[NOTES_MAX, false], [NOTES_MAX - 30, false], [NOTES_MAX - 120, true], [100, true]]) {
1036
+ const full = world({ notes: () => 'n'.repeat(size) });
1037
+ full.h.hooks.npcOpening = () => 'W'.repeat(240);
1038
+ full.at('a', 0, 2);
1039
+ full.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1040
+ const prefix = full.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1041
+ const bodyOf = prefix.slice(NOTES_HEAD.length, prefix.length - NOTES_SAYS.length);
1042
+ assert.ok(bodyOf.length <= NOTES_MAX, `notes of ${bodyOf.length} characters for a context of ${size}`);
1043
+ assert.ok(bodyOf.startsWith('n'.repeat(size)), 'the place\'s notes whole');
1044
+ assert.equal(bodyOf.includes('You opened'), wantOpening, `context ${size}`);
1045
+ }
1046
+
1047
+ // A place with no notes of its own sends its turns as the words alone: the opening adds none.
1048
+ const bare = world();
1049
+ bare.h.hooks.npcOpening = () => 'Hello.';
1050
+ bare.at('a', 0, 2);
1051
+ bare.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1052
+ assert.equal(bare.sent.find((m) => m.k === 'hub-npc' && m.open).opening.text, 'Hello.');
1053
+ assert.ok(bare.sent.filter((m) => m.k === 'hub-npc-notes').every((m) => m.prefix === null));
1054
+ });
1055
+
1056
+ await test('v1.46: a mind without opening words speaks first; a place opening stays its own', () => {
1057
+ for (const hook of [undefined, () => null, () => '', () => ({ text: ' ', asks: ['Ignored?'] })]) {
1058
+ const w = world({ notes: () => 'The pad is empty.', extra: [{ id: 'puppy', name: 'Biscuit, the puppy', character: 'puppy', x: 1, z: 0 }] });
1059
+ if (hook) {
1060
+ w.h.hooks.npcOpening = hook;
1061
+ }
1062
+ w.at('a', 0, 2);
1063
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'puppy' });
1064
+ const opened = w.sent.find((m) => m.k === 'hub-npc' && m.open);
1065
+ assert.deepEqual(opened.opening, {
1066
+ text: "Hi, I'm Biscuit! Ask me anything.",
1067
+ asks: ['Who are you?', 'What do you do here?', 'Tell me a secret!'],
1068
+ more: ["What's your favourite thing here?", 'What should I try first?', 'Do you have any friends here?', "What's the funniest thing you've seen?", 'What do you dream about?', 'What makes you laugh?'],
1069
+ });
1070
+ const prefix = w.sent.find((m) => m.k === 'hub-npc-notes').prefix;
1071
+ assert.ok(prefix.includes(opened.opening.text));
1072
+ assert.ok(prefix.includes('You opened this conversation by saying:'));
1073
+ assert.equal(w.lines.length, 0);
1074
+ }
1075
+ for (const given of ['My own words.', { text: 'My own words.' }, { text: 'My own words.', asks: ['My own question?'] }]) {
1076
+ const w = world();
1077
+ w.h.hooks.npcOpening = () => given;
1078
+ w.at('a', 0, 2);
1079
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1080
+ assert.deepEqual(w.sent.find((m) => m.k === 'hub-npc' && m.open).opening, { text: 'My own words.', asks: given.asks ?? [] });
1081
+ assert.equal(w.sent.filter((m) => m.k === 'hub-npc-notes').length, 0, 'no npcContext still means no notes');
1082
+ }
1083
+ const bare = world();
1084
+ bare.at('a', 0, 2);
1085
+ bare.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1086
+ assert.equal(bare.sent.filter((m) => m.k === 'hub-npc-notes').length, 0, 'the default follows the same notes rule');
1087
+ const mindless = world({ mind: false });
1088
+ mindless.at('a', 0, 2);
1089
+ mindless.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1090
+ assert.equal('opening' in mindless.sent.find((m) => m.k === 'hub-npc' && m.open), false);
1091
+ assert.equal(mindless.lines.at(-1).why, 'hello');
1092
+ });
1093
+
1094
+ await test('v1.46: more questions are cut, deduped and bounded; empty more is not sent', () => {
1095
+ for (const mind of [true, false]) {
1096
+ const w = world({ mind });
1097
+ w.h.hooks.npcOpening = () => ({ text: 'Hello.', asks: [' Why? ', 'x'.repeat(60)], more: [7, '', 'Why?', 'x'.repeat(41), ' Later? ', 'Later?', 'y'.repeat(50), ...Array.from({ length: 12 }, (_, i) => `Question ${i}?`)] });
1098
+ w.at('a', 0, 2);
1099
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1100
+ const opening = w.sent.find((m) => m.k === 'hub-npc' && m.open).opening;
1101
+ assert.deepEqual(opening.asks, ['Why?', 'x'.repeat(40)]);
1102
+ assert.deepEqual(opening.more, ['Later?', 'y'.repeat(40), ...Array.from({ length: 7 }, (_, i) => `Question ${i}?`)]);
1103
+ for (const more of [undefined, [], ['Why?', 'x'.repeat(41), null, ' ']]) {
1104
+ w.h.hooks.npcOpening = () => ({ text: 'Hello.', asks: ['Why?', 'x'.repeat(40)], more });
1105
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1106
+ assert.equal('more' in w.sent.findLast((m) => m.k === 'hub-npc' && m.open).opening, false);
1107
+ }
1108
+ }
1109
+ });
1110
+
1111
+ await test('v1.46: authored replies keep no operation id and cooldown drops send no reply', () => {
1112
+ const w = world({ mind: false });
1113
+ w.at('a', 0, 2);
1114
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1115
+ assert.equal('op' in w.sent.findLast((m) => m.k === 'hub-npc-line'), false);
1116
+ assert.equal('rid' in w.sent.at(-1), false);
1117
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'One?', rid: 'say-a' });
1118
+ const count = w.sent.filter((m) => m.k === 'hub-npc-line').length;
1119
+ assert.equal(w.sent.at(-1).why, 'authored');
1120
+ assert.equal('op' in w.sent.at(-1), false);
1121
+ assert.equal(w.sent.at(-1).rid, 'say-a');
1122
+ w.tick(899);
1123
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Two?', rid: 'dropped' });
1124
+ assert.equal(w.sent.filter((m) => m.k === 'hub-npc-line').length, count);
1125
+ assert.equal(w.sent.some((m) => m.rid === 'dropped'), false);
1126
+ w.tick(1);
1127
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Two?', rid: 'say-b' });
1128
+ assert.equal(w.sent.filter((m) => m.k === 'hub-npc-line').length, count + 1);
1129
+ assert.equal(w.sent.at(-1).rid, 'say-b');
1130
+ w.tick(900);
1131
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Legacy client' });
1132
+ assert.equal('rid' in w.sent.at(-1), false, 'an older client gets no added request id');
1133
+ for (const rid of [5, {}, 'x'.repeat(65)]) {
1134
+ w.tick(900);
1135
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Hello', rid });
1136
+ assert.equal('rid' in w.sent.at(-1), false, 'only short string request ids are echoed');
1137
+ }
1138
+ });
1139
+
1140
+ function reacting(options = {}) {
1141
+ const w = world(options);
1142
+ w.h.place.idle = { emotes: true, seats: false, sounds: [] };
1143
+ w.at('a', 0, 2);
1144
+ // The speech choice is tested separately from the emote cooldown.
1145
+ w.h.hooks.npcReact = () => ({ line: null });
1146
+ return w;
1147
+ }
1148
+
1149
+ await test('v1.47: the nearest three free bodies within six flat metres answer and face the player', () => {
1150
+ const w = reacting({ extra: [
1151
+ { id: 'far', x: 0, z: 8.01 }, { id: 'edge', x: 0, z: 8 },
1152
+ { id: 'near', x: 0, z: 3 }, { id: 'next', x: 2, z: 2 },
1153
+ ] });
1154
+ w.sim.bodies.get('near').p.y = 100;
1155
+ assert.deepEqual(Idle.fields(w.h), { hubEmotes: {} });
1156
+ Idle.emoteMessage(w.h, 'a', { id: 'wave' });
1157
+ assert.deepEqual(Object.keys(Idle.fields(w.h).hubNpcEmotes).sort(), ['greeter', 'near', 'next']);
1158
+ assert.deepEqual(Idle.fields(w.h).hubNpcEmotes.near, { id: 'wave', at: 0, until: Idle.EMOTES.wave });
1159
+ assert.ok(Math.abs(w.sim.bodies.get('near').rot.y - 1) < 1e-9, 'near faces -z');
1160
+ w.tick(Idle.EMOTES.wave);
1161
+ assert.deepEqual(Idle.fields(w.h).hubNpcEmotes, {}, 'expiry is latched too');
1162
+ const edge = reacting({ extra: [{ id: 'edge', x: 0, z: 8 }, { id: 'far', x: 0, z: 8.01 }] });
1163
+ Idle.emote(edge.h, 'a', 'spin');
1164
+ assert.deepEqual(Object.keys(Idle.fields(edge.h).hubNpcEmotes), ['greeter', 'edge']);
1165
+ assert.equal(Idle.fields(edge.h).hubNpcEmotes.edge.id, 'cheer');
1166
+ });
1167
+
1168
+ await test('v1.47: player reactions wait four seconds and each NPC waits eight, even for place emotes', () => {
1169
+ const w = reacting();
1170
+ w.at('b', 0, 1);
1171
+ let asked = 0;
1172
+ w.h.hooks.npcReact = () => { asked += 1; return { line: null }; };
1173
+ Idle.emote(w.h, 'a', 'wave');
1174
+ w.sim.timeMs = 2000;
1175
+ Idle.emoteMessage(w.h, 'a', { id: 'dance' });
1176
+ assert.equal(w.h.emotes.get('a').id, 'dance', 'the player still emotes');
1177
+ assert.equal(asked, 1);
1178
+ Idle.emote(w.h, 'b', 'cheer');
1179
+ assert.equal(asked, 1, 'a second player cannot restart the NPC');
1180
+ w.sim.timeMs = 4000;
1181
+ Idle.emote(w.h, 'a', 'bow');
1182
+ assert.equal(asked, 1);
1183
+ w.sim.timeMs = 8000;
1184
+ Idle.emote(w.h, 'a', 'bow');
1185
+ assert.equal(asked, 2);
1186
+ assert.equal(Idle.fields(w.h).hubNpcEmotes.greeter.at, 8000);
1187
+ // A fresh body is still protected by the player's own reaction cooldown.
1188
+ const p = reacting({ extra: [{ id: 'second', x: 100, z: 0 }] });
1189
+ Idle.emote(p.h, 'a', 'wave');
1190
+ p.sim.bodies.get('second').p = { x: 0, y: 1, z: 2 };
1191
+ p.sim.timeMs = 3999;
1192
+ Idle.emote(p.h, 'a', 'wave');
1193
+ assert.equal(p.npcs.emoteFields().hubNpcEmotes.second, undefined);
1194
+ p.sim.timeMs = 4000;
1195
+ Idle.emote(p.h, 'a', 'wave');
1196
+ assert.equal(p.npcs.emoteFields().hubNpcEmotes.second.at, 4000);
1197
+ });
1198
+
1199
+ await test('v1.47: conversations, pending speech, follows, walks and place moves are left alone', () => {
1200
+ for (const busy of [
1201
+ (w) => w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' }),
1202
+ (w) => w.npcs.handle('greeter').follow('a'),
1203
+ (w) => w.npcs.handle('greeter').walkTo({ x: 5, z: 0 }),
1204
+ (w) => w.npcs.handle('greeter').say('Working.'),
1205
+ (w) => { w.h.moves = new Map([['greeter', {}]]); },
1206
+ (w) => { w.h.held = new Map([['greeter', {}]]); },
1207
+ (w) => { w.h.resetHolds = new Map([['greeter', {}]]); },
1208
+ ]) {
1209
+ const w = reacting();
1210
+ busy(w);
1211
+ Idle.emote(w.h, 'a', 'wave');
1212
+ assert.deepEqual(w.npcs.emoteFields(), {});
1213
+ }
1214
+ const w = reacting();
1215
+ w.npcs.handle('greeter').say('Just a moment.', { to: ['a'], ttlMs: 5000 });
1216
+ Idle.emote(w.h, 'a', 'wave');
1217
+ w.sim.timeMs = 5000;
1218
+ Idle.emote(w.h, 'a', 'wave');
1219
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave');
1220
+ });
1221
+
1222
+ await test('v1.47: props and hook overrides choose bounded public words and kit emotes; false skips a body', () => {
1223
+ const w = reacting({ extra: [{ id: 'second', x: 0, z: 1 }] });
1224
+ const asked = [];
1225
+ w.h.hooks.npcReact = (_hub, npc, playerId, info) => {
1226
+ asked.push({ npc: npc.id, playerId, ...info });
1227
+ return npc.id === 'second' ? false : { emote: 'dance', line: ` ${'x'.repeat(100)}\u0000` };
1228
+ };
1229
+ Idle.emote(w.h, 'a', 'wave');
1230
+ assert.deepEqual(asked.map((a) => a.npc), ['second', 'greeter']);
1231
+ assert.deepEqual(asked[1], { npc: 'greeter', playerId: 'a', emote: 'wave' });
1232
+ assert.deepEqual(Object.keys(w.npcs.emoteFields().hubNpcEmotes), ['greeter']);
1233
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'dance');
1234
+ assert.deepEqual(w.labels.at(-1), { id: 'greeter', text: `Rowan: ${'x'.repeat(80)}`, to: null, about: null });
1235
+ for (const override of [undefined, null, { line: null }]) {
1236
+ const p = reacting();
1237
+ p.h.hooks.npcReact = () => override;
1238
+ p.npcs.handle('greeter').props.reactions = { wave: { emote: 'bow', lines: ['Only my words.'] } };
1239
+ // Find a tick that speaks; other ticks keep just the emote.
1240
+ for (let ms = 0; ms < 3; ms++) {
1241
+ p.sim.timeMs = ms * 8000;
1242
+ Idle.emote(p.h, 'a', 'wave');
1243
+ assert.equal(p.npcs.emoteFields().hubNpcEmotes.greeter.id, 'bow');
1244
+ }
1245
+ if (override?.line === null) {
1246
+ assert.equal(p.labels.length, 0);
1247
+ } else {
1248
+ assert.ok(p.labels.some((l) => l.text === 'Rowan: Only my words.' && l.to === null));
1249
+ }
1250
+ }
1251
+ const quiet = reacting();
1252
+ quiet.npcs.handle('greeter').props.reactions = { wave: { emote: null, lines: [] } };
1253
+ quiet.h.hooks.npcReact = () => undefined;
1254
+ Idle.emote(quiet.h, 'a', 'wave');
1255
+ assert.deepEqual(quiet.npcs.emoteFields(), {});
1256
+ assert.equal(quiet.labels.length, 0);
1257
+ });
1258
+
1259
+ await test('v1.47: hook errors log once and fall back; absent players and NPC emotes cannot react', () => {
1260
+ const w = reacting();
1261
+ const warned = [];
1262
+ const warn = console.warn;
1263
+ console.warn = (...args) => warned.push(args.join(' '));
1264
+ try {
1265
+ w.h.hooks.npcReact = () => { throw new Error('private detail'); };
1266
+ Idle.emote(w.h, 'a', 'dance');
1267
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'dance');
1268
+ w.sim.timeMs = 8000;
1269
+ Idle.emote(w.h, 'a', 'dance');
1270
+ assert.equal(warned.length, 1);
1271
+ assert.ok(!warned[0].includes('private detail'));
1272
+ } finally {
1273
+ console.warn = warn;
1274
+ }
1275
+ const absent = reacting();
1276
+ absent.h.players.get('a').arrived = false;
1277
+ Idle.emote(absent.h, 'a', 'wave');
1278
+ absent.npcs.react('greeter', 'wave');
1279
+ Idle.emoteMessage(absent.h, 'gone', { id: 'wave' });
1280
+ assert.deepEqual(absent.npcs.emoteFields(), {});
1281
+ const empty = reacting();
1282
+ empty.h.actors = [];
1283
+ empty.h.npcs = makeNpcs(empty.h);
1284
+ empty.h.npcs.ready();
1285
+ Idle.emote(empty.h, 'a', 'wave');
1286
+ assert.deepEqual(Idle.fields(empty.h), { hubEmotes: { a: { id: 'wave', at: 0, until: Idle.EMOTES.wave } } });
1287
+ const refused = reacting();
1288
+ refused.h.hooks.npcReact = () => false;
1289
+ Idle.emote(refused.h, 'a', 'wave');
1290
+ assert.equal('hubNpcEmotes' in Idle.fields(refused.h), false);
1291
+ });
1292
+
1293
+ await test('v1.47: each default answers with a kit emote and sometimes its own public line', () => {
1294
+ const lines = {
1295
+ wave: ['Hello there!', 'Hi!', 'Hey, hi!'], dance: ['Nice moves!', 'Ooh, let me try!'],
1296
+ cheer: ['Woo!', 'Yay!'], bow: ['Likewise!', 'Oh, how polite!'], spin: ['Whee!', 'Dizzy yet?'],
1297
+ };
1298
+ for (const emote of Object.keys(lines)) {
1299
+ const w = reacting();
1300
+ delete w.h.hooks.npcReact;
1301
+ for (let tick = 0; tick < 6; tick++) {
1302
+ w.sim.timeMs = tick * 8000;
1303
+ Idle.emote(w.h, 'a', emote);
1304
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, emote === 'spin' ? 'cheer' : emote);
1305
+ }
1306
+ assert.ok(w.labels.length > 0 && w.labels.length < 6, 'speech is occasional');
1307
+ assert.ok(w.labels.every((l) => l.to === null && lines[emote].some((line) => l.text === `Rowan: ${line}`)));
1308
+ }
1309
+ const w = reacting();
1310
+ delete w.h.hooks.npcReact;
1311
+ w.npcs.handle('greeter').props.reactions = { wave: { lines: Array.from({ length: 10 }, (_, i) => `${i}: ${'x'.repeat(100)}\u0000`) } };
1312
+ for (let tick = 0; tick < 18; tick++) {
1313
+ w.sim.timeMs = tick * 8000;
1314
+ Idle.emote(w.h, 'a', 'wave');
1315
+ }
1316
+ assert.ok(w.labels.length > 0);
1317
+ assert.ok(w.labels.every((l) => /^Rowan: [0-5]: /.test(l.text) && l.text.length === 87));
1318
+ });
1319
+
1320
+ const inspectGreeting = (w, playerId, characters) => w.npcs.onRead({
1321
+ speaker: { playerId }, query: { type: 'inspect' },
1322
+ read: async () => ({ participantId: `p-${playerId}`, characters }), reject() {},
1323
+ });
1324
+
1325
+ function signIn(w, playerId, userId = `user-${playerId}`) {
1326
+ w.h.session.players ??= [];
1327
+ w.h.session.players = w.h.session.players.filter((p) => p.playerId !== playerId);
1328
+ w.h.session.players.push({ playerId, userId });
1329
+ }
1330
+
1331
+ await test('v1.47: a greeting is private to its speaker, character and opening notes; hooks keep their questions', async () => {
1332
+ const w = world({ notes: () => 'The pad is empty.', extra: [{ id: 'other', character: 'other', x: 1, z: 0 }] });
1333
+ signIn(w, 'a');
1334
+ w.at('a', 0, 2);
1335
+ w.at('b', 0, 2);
1336
+ await inspectGreeting(w, 'a', [{ characterId: 'greeter', privateState: { nextGreeting: { text: ' How is\u0000 your hamster?\n ', at: 10 } } }]);
1337
+ const asked = [];
1338
+ w.h.hooks.npcOpening = (_hub, npc, playerId, info) => {
1339
+ asked.push({ npc: npc.id, playerId, ...info });
1340
+ return { text: 'Place words.', asks: ['Where now?'], more: ['Then what?'] };
1341
+ };
1342
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1343
+ assert.deepEqual(w.sent.findLast((m) => m.open).opening, { text: 'How is your hamster?', asks: ['Where now?'], more: ['Then what?'] });
1344
+ assert.equal(asked.at(-1).greeting, 'How is your hamster?');
1345
+ assert.ok(w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix.includes('How is your hamster?'));
1346
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1347
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
1348
+ assert.equal(asked.at(-1).greeting, null);
1349
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Place words.');
1350
+ assert.ok(w.sent.filter((m) => JSON.stringify(m).includes('hamster')).every((m) => m.playerId === 'a'));
1351
+ assert.equal(w.labels.length, 0, 'the greeting is never a speech bubble');
1352
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'other' });
1353
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Place words.');
1354
+ w.npcs.leave('a');
1355
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-end', npc: 'greeter' });
1356
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1357
+ assert.equal(asked.at(-1).greeting, null, 'departure clears the cache');
1358
+ });
1359
+
1360
+ await test('v1.47: old or empty inspect clears greetings; a late inspect after leave cannot restore them', async () => {
1361
+ const w = world();
1362
+ signIn(w, 'a');
1363
+ w.at('a', 0, 2);
1364
+ const read = (text) => inspectGreeting(w, 'a', [{ characterId: 'greeter', privateState: { nextGreeting: { text } } }]);
1365
+ await read(` \u007f${'x'.repeat(300)}\u009f `);
1366
+ const open = () => w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1367
+ open();
1368
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'x'.repeat(240));
1369
+ assert.equal(w.sent.findLast((m) => m.open).opening.asks.length, 3);
1370
+ for (const characters of [undefined, [], [{ characterId: 'greeter', privateState: {} }]]) {
1371
+ await inspectGreeting(w, 'a', characters);
1372
+ open();
1373
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1374
+ }
1375
+ let finish;
1376
+ const pending = w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: () => new Promise((resolve) => { finish = resolve; }), reject() {} });
1377
+ w.npcs.leave('a');
1378
+ finish({ participantId: 'p-a', characters: [{ characterId: 'greeter', privateState: { nextGreeting: { text: 'Late private words.' } } }] });
1379
+ await pending;
1380
+ open();
1381
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1382
+ });
1383
+
1384
+ await test('v1.47: a hook error cannot log the greeting it was given', async () => {
1385
+ const w = world();
1386
+ signIn(w, 'a');
1387
+ w.at('a', 0, 2);
1388
+ await inspectGreeting(w, 'a', [{ characterId: 'greeter', privateState: { nextGreeting: { text: 'Private hamster.' } } }]);
1389
+ w.h.hooks.npcOpening = (_hub, _npc, _player, info) => { throw new Error(info.greeting); };
1390
+ const warn = console.warn;
1391
+ const logs = [];
1392
+ console.warn = (...args) => logs.push(args.join(' '));
1393
+ try {
1394
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1395
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Private hamster.');
1396
+ assert.deepEqual(logs, ['[hub] npcOpening failed']);
1397
+ assert.equal(w.labels.length, 0);
1398
+ } finally {
1399
+ console.warn = warn;
1400
+ }
1401
+ });
1402
+
1403
+ const greetingCharacters = (text = 'Private returning words.') => [{ characterId: 'greeter', privateState: { nextGreeting: { text } } }];
1404
+ const openGreeter = (w, playerId = 'a') => w.npcs.message({ playerId }, { k: 'hub-npc-open', npc: 'greeter' });
1405
+
1406
+ await test('review: greetings stay bound to the authenticated account and the exact body, never a guest', async () => {
1407
+ for (const change of [
1408
+ (w) => signIn(w, 'a', 'other-account'),
1409
+ (w) => w.at('a', 0, 2),
1410
+ (w) => signIn(w, 'a', null),
1411
+ ]) {
1412
+ const w = world();
1413
+ w.at('a', 0, 2);
1414
+ signIn(w, 'a');
1415
+ await inspectGreeting(w, 'a', greetingCharacters());
1416
+ change(w);
1417
+ const greetings = [];
1418
+ w.h.hooks.npcOpening = (_h, _n, _p, info) => { greetings.push(info.greeting); return null; };
1419
+ openGreeter(w);
1420
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1421
+ assert.deepEqual(greetings, [null]);
1422
+ signIn(w, 'a');
1423
+ openGreeter(w);
1424
+ assert.equal(greetings.at(-1), null, 'an invalid cache stays invalid');
1425
+ assert.ok(!JSON.stringify(w.sent).includes('Private returning words.'));
1426
+ }
1427
+ const guest = world();
1428
+ guest.at('a', 0, 2);
1429
+ await inspectGreeting(guest, 'a', greetingCharacters());
1430
+ signIn(guest, 'a');
1431
+ openGreeter(guest);
1432
+ assert.equal(guest.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1433
+ });
1434
+
1435
+ await test('review: an inspect cannot cache a greeting across an account change during the read', async () => {
1436
+ const w = world();
1437
+ w.at('a', 0, 2);
1438
+ signIn(w, 'a');
1439
+ let finish;
1440
+ const pending = w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: () => new Promise((resolve) => { finish = resolve; }), reject() {} });
1441
+ signIn(w, 'a', 'other-account');
1442
+ finish({ participantId: 'p-a', characters: greetingCharacters() });
1443
+ await pending;
1444
+ openGreeter(w);
1445
+ signIn(w, 'a');
1446
+ openGreeter(w);
1447
+ assert.ok(!JSON.stringify(w.sent).includes('Private returning words.'));
1448
+ });
1449
+
1450
+ await test('review: rejected hook promises and thenables are caught, ignored and logged once without their text', async () => {
1451
+ const logs = [];
1452
+ const unhandled = [];
1453
+ const onUnhandled = (err) => unhandled.push(err);
1454
+ const warn = console.warn;
1455
+ console.warn = (...args) => logs.push(args.join(' '));
1456
+ process.on('unhandledRejection', onUnhandled);
1457
+ try {
1458
+ const w = world();
1459
+ w.at('a', 0, 2);
1460
+ signIn(w, 'a');
1461
+ await inspectGreeting(w, 'a', greetingCharacters('Secret hamster.'));
1462
+ w.h.hooks.npcOpening = async (_h, _n, _p, info) => { throw new Error(info.greeting); };
1463
+ openGreeter(w);
1464
+ openGreeter(w);
1465
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Secret hamster.');
1466
+ assert.equal(w.sent.findLast((m) => m.open).opening.asks.length, 3);
1467
+ w.h.hooks.npcOpening = () => ({ text: 'Ignored words.', then(_resolve, reject) { reject(new Error('Secret thenable.')); } });
1468
+ openGreeter(w);
1469
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Secret hamster.');
1470
+ const r = reacting();
1471
+ r.h.hooks.npcReact = async () => { throw new Error('Secret reaction.'); };
1472
+ Idle.emote(r.h, 'a', 'wave');
1473
+ r.sim.timeMs = 8000;
1474
+ Idle.emote(r.h, 'a', 'wave');
1475
+ assert.equal(r.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave');
1476
+ r.h.hooks.npcReact = () => ({ emote: 'dance', then(resolve) { resolve({ emote: 'dance' }); } });
1477
+ r.sim.timeMs = 16000;
1478
+ Idle.emote(r.h, 'a', 'wave');
1479
+ assert.equal(r.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave', 'fulfilled thenables are ignored too');
1480
+ await new Promise((resolve) => setImmediate(resolve));
1481
+ assert.deepEqual(unhandled, []);
1482
+ assert.deepEqual(logs.sort(), ['[hub] npcOpening async hook failed; using the default', '[hub] npcReact async hook failed; using the default']);
1483
+ } finally {
1484
+ console.warn = warn;
1485
+ process.off('unhandledRejection', onUnhandled);
1486
+ }
1487
+ });
1488
+
1489
+ await test('review: a late inspect replaces only an unsent opening and reissues its private notes', async () => {
1490
+ for (const spoke of [false, true, 'stale']) {
1491
+ const w = world({ notes: () => 'The pad is empty.' });
1492
+ w.at('a', 0, 2);
1493
+ w.at('b', 0, 2);
1494
+ signIn(w, 'a');
1495
+ w.h.hooks.npcOpening = () => ({ text: 'First words.', asks: ['Place question?'], more: ['Next?'] });
1496
+ let finish;
1497
+ const pending = w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: () => new Promise((resolve) => { finish = resolve; }), reject() {} });
1498
+ openGreeter(w);
1499
+ const opening = w.sent.findLast((m) => m.open).opening;
1500
+ assert.deepEqual(opening, { text: 'First words.', asks: ['Place question?'], more: ['Next?'] });
1501
+ const firstPrefix = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1502
+ if (spoke) {
1503
+ const sent = turn({ speaker: 'a', input: `${spoke === 'stale' ? '' : firstPrefix}Hello!` });
1504
+ await w.npcs.onTurn(sent);
1505
+ assert.equal(sent.rejected, spoke === 'stale' ? 'HUB_NPC_NOTES' : null);
1506
+ }
1507
+ finish({ participantId: 'p-a', characters: greetingCharacters('How is your hamster?') });
1508
+ await pending;
1509
+ const updates = w.sent.filter((m) => m.k === 'hub-npc-opening');
1510
+ assert.deepEqual(updates, spoke ? [] : [{ playerId: 'a', k: 'hub-npc-opening', npc: 'greeter', text: 'How is your hamster?' }]);
1511
+ const prefix = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1512
+ assert.equal(prefix.includes('How is your hamster?'), !spoke);
1513
+ assert.equal(prefix.includes('First words.'), Boolean(spoke));
1514
+ assert.equal(w.labels.length, 0);
1515
+ assert.deepEqual(opening.asks, ['Place question?']);
1516
+ assert.ok(w.sent.filter((m) => JSON.stringify(m).includes('hamster')).every((m) => m.playerId === 'a'));
1517
+ }
1518
+ const closed = world();
1519
+ closed.at('a', 0, 2);
1520
+ signIn(closed, 'a');
1521
+ openGreeter(closed);
1522
+ closed.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1523
+ await inspectGreeting(closed, 'a', greetingCharacters());
1524
+ assert.equal(closed.sent.some((m) => m.k === 'hub-npc-opening'), false);
1525
+ });
1526
+
1527
+ await test('review: a later short line cannot shorten another listener\'s active speech deadline', () => {
1528
+ const w = reacting();
1529
+ w.npcs.handle('greeter').say('Long public words.', { ttlMs: 12000 });
1530
+ w.sim.timeMs = 1000;
1531
+ w.npcs.handle('greeter').say('Short private words.', { to: ['a'], ttlMs: 1000 });
1532
+ w.sim.timeMs = 4000;
1533
+ Idle.emote(w.h, 'a', 'wave');
1534
+ assert.deepEqual(w.npcs.emoteFields(), {});
1535
+ w.sim.timeMs = 12000;
1536
+ Idle.emote(w.h, 'a', 'wave');
1537
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave');
1538
+ });
1539
+
1540
+ await test('review: a replacement speaker cannot force-send the old conversation\'s greeting notes', async () => {
1541
+ for (const change of [
1542
+ (w) => signIn(w, 'a', 'replacement-account'),
1543
+ (w) => w.at('a', 0, 2),
1544
+ (w) => signIn(w, 'a', null),
1545
+ ]) {
1546
+ for (const replay of [false, true]) {
1547
+ const w = world({ notes: () => 'The pad is empty.' });
1548
+ w.at('a', 0, 2);
1549
+ signIn(w, 'a');
1550
+ await inspectGreeting(w, 'a', greetingCharacters('Only the original account knows this.'));
1551
+ openGreeter(w);
1552
+ const prefix = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1553
+ assert.ok(prefix.includes('Only the original account knows this.'));
1554
+ if (replay) {
1555
+ const original = turn({ speaker: 'a', input: `${prefix}Hello.` });
1556
+ await w.npcs.onTurn(original);
1557
+ assert.equal(original.sent, 1);
1558
+ }
1559
+ // Reuse the id before leave() runs: no new open, no valid old prefix.
1560
+ change(w);
1561
+ w.sent.length = 0;
1562
+ const replacement = turn({ speaker: 'a', operationId: replay ? 'op1' : 'replacement', input: 'Hello.' });
1563
+ await w.npcs.onTurn(replacement);
1564
+ assert.equal(replacement.rejected, 'HUB_NPC_NOT_TALKING');
1565
+ assert.equal(replacement.sent, 0);
1566
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
1567
+ assert.deepEqual(w.sent, [{ playerId: 'a', k: 'hub-npc', npc: 'greeter', open: false, why: 'left' }]);
1568
+ w.tick(1000);
1569
+ assert.equal(w.sent.some((m) => m.k === 'hub-npc-notes' || m.k === 'hub-npc-opening'), false);
1570
+ // Reopening creates fresh notes for the replacement, never the old copy.
1571
+ openGreeter(w);
1572
+ assert.ok(!JSON.stringify(w.sent).includes('Only the original account knows this.'));
1573
+ }
1574
+ }
1575
+ });
1576
+
1577
+ await test('review: periodic notes and late opening updates end conversations bound to a replaced speaker', async () => {
1578
+ for (const path of ['tick', 'inspect']) {
1579
+ for (const change of [(w) => signIn(w, 'a', 'replacement-account'), (w) => w.at('a', 0, 2)]) {
1580
+ const w = world({ notes: () => 'The pad is empty.' });
1581
+ w.at('a', 0, 2);
1582
+ signIn(w, 'a');
1583
+ await inspectGreeting(w, 'a', greetingCharacters('Original private greeting.'));
1584
+ openGreeter(w);
1585
+ change(w);
1586
+ w.sent.length = 0;
1587
+ if (path === 'tick') {
1588
+ w.tick(1000);
1589
+ } else {
1590
+ await inspectGreeting(w, 'a', greetingCharacters('Replacement private greeting.'));
1591
+ }
1592
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
1593
+ assert.deepEqual(w.sent, [
1594
+ { playerId: 'a', k: 'hub-npc', npc: 'greeter', open: false, why: 'left' },
1595
+ ...(path === 'inspect' ? [{ playerId: 'a', k: 'hub-npc-hooks', hooks: [{ npc: 'greeter', character: 'greeter' }] }] : []),
1596
+ ]);
1597
+ }
1598
+ }
1599
+ });
1600
+
1601
+ await test('review: speaker identity is checked again after opening and context hooks before any private send', async () => {
1602
+ for (const hook of ['npcOpening', 'npcContext']) {
1603
+ const w = world({ notes: () => 'Original private context.' });
1604
+ w.at('a', 0, 2);
1605
+ signIn(w, 'a');
1606
+ await inspectGreeting(w, 'a', greetingCharacters('Original private greeting.'));
1607
+ if (hook === 'npcContext') {
1608
+ openGreeter(w);
1609
+ }
1610
+ w.h.hooks[hook] = () => {
1611
+ signIn(w, 'a', 'replacement-account');
1612
+ return 'Original private words.';
1613
+ };
1614
+ w.sent.length = 0;
1615
+ if (hook === 'npcOpening') {
1616
+ openGreeter(w);
1617
+ } else {
1618
+ w.tick(1000);
1619
+ }
1620
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
1621
+ assert.deepEqual(w.sent, [{ playerId: 'a', k: 'hub-npc', npc: 'greeter', open: false, why: 'left' }]);
1622
+ }
1623
+ });
1624
+
1625
+ await test('v1.47: admitted words report the opening conversation only while its bound speaker still owns it', async () => {
1626
+ for (const change of ['same', 'close', 'reopen', 'handoff', 'account', 'body']) {
1627
+ const w = world();
1628
+ w.at('a', 0, 2);
1629
+ w.at('b', 0, 2);
1630
+ signIn(w, 'a');
1631
+ const openings = [];
1632
+ const heard = [];
1633
+ w.h.hooks.npcOpening = (_h, _n, playerId, info) => {
1634
+ openings.push({ playerId, conversation: info.conversation });
1635
+ return 'What would you like?';
1636
+ };
1637
+ w.h.hooks.npcHeard = (_h, _n, playerId, info) => heard.push({ playerId, ...info });
1638
+ openGreeter(w);
1639
+ const conversation = openings[0].conversation;
1640
+ assert.ok(Number.isInteger(conversation));
1641
+ assert.equal(conversation, 1);
1642
+ const admitted = turn({ speaker: 'a', input: 'My private answer.' });
1643
+ let finish;
1644
+ admitted.send = () => new Promise((resolve) => { finish = resolve; });
1645
+ const pending = w.npcs.onTurn(admitted);
1646
+ assert.equal(typeof finish, 'function', 'the turn reached its awaited send');
1647
+ assert.deepEqual(heard, [], 'the hook waits for send to settle');
1648
+ if (['close', 'reopen', 'handoff'].includes(change)) {
1649
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1650
+ if (change !== 'close') {
1651
+ openGreeter(w, change === 'handoff' ? 'b' : 'a');
1652
+ assert.equal(openings.at(-1).conversation, conversation + 1);
1653
+ }
1654
+ } else if (change === 'account') {
1655
+ // Keep the exact body, reusing only the player id for another account.
1656
+ signIn(w, 'a', 'replacement-account');
1657
+ } else if (change === 'body') {
1658
+ // Keep the account, replacing only the body before leave runs.
1659
+ w.at('a', 0, 2);
1660
+ }
1661
+ const logs = [];
1662
+ const warn = console.warn;
1663
+ console.warn = (...args) => logs.push(args.join(' '));
1664
+ try {
1665
+ finish({ status: 'queued' });
1666
+ await pending;
1667
+ } finally {
1668
+ console.warn = warn;
1669
+ }
1670
+ assert.deepEqual(heard, change === 'same' ? [{ playerId: 'a', text: 'My private answer.', conversation }] : [], change);
1671
+ assert.deepEqual(logs, [], 'dropping old words logs none of them');
1672
+ if (change === 'reopen' || change === 'handoff') {
1673
+ assert.equal(w.npcs.handle('greeter').talkingTo, change === 'handoff' ? 'b' : 'a', 'the old send leaves the new conversation intact');
1674
+ }
1675
+ }
1676
+ });
1677
+
1678
+ await test('v1.47: authored words match their opening; sequences increase independently per NPC', () => {
1679
+ const w = world({ mind: false, extra: [{ id: 'other', character: 'other', x: 1, z: 0 }] });
1680
+ w.at('a', 0, 2);
1681
+ signIn(w, 'a');
1682
+ const openings = [];
1683
+ w.h.hooks.npcOpening = (_h, npc, _p, info) => { openings.push({ npc: npc.id, conversation: info.conversation }); return 'Question?'; };
1684
+ for (const conversation of [1, 2]) {
1685
+ openGreeter(w);
1686
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Answer.' });
1687
+ assert.equal(w.lines.at(-1).conversation, conversation);
1688
+ assert.equal(w.lines.at(-1).conversation, openings.at(-1).conversation);
1689
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1690
+ w.tick(1000);
1691
+ }
1692
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'other' });
1693
+ assert.deepEqual(openings, [{ npc: 'greeter', conversation: 1 }, { npc: 'greeter', conversation: 2 }, { npc: 'other', conversation: 1 }]);
1694
+ openGreeter(w);
1695
+ signIn(w, 'a', 'replacement-account');
1696
+ const count = w.lines.length;
1697
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Replacement answer.' });
1698
+ assert.equal(w.lines.length, count, 'a reused player id cannot submit authored words in the old conversation');
1699
+ });
1700
+
1701
+
1702
+ await test('v1.66: without npcTools a turn is sent exactly as before, and nothing answers a lookup', async () => {
1703
+ const w = world();
1704
+ w.at('a', 0, 2);
1705
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1706
+ const t = turn({ speaker: 'a' });
1707
+ await w.npcs.onTurn(t);
1708
+ assert.deepEqual(t.sendArgs, [[]]);
1709
+ assert.deepEqual(await w.npcs.onTool({ operationId: 'op1', characterId: 'greeter', playerId: 'a', name: 'x', input: {} }), { error: 'not available' });
1710
+ });
1711
+
1712
+ await test('v1.66: npcTools rides with a new turn; npcTool answers one lookup for that turn only', async () => {
1713
+ const w = world();
1714
+ const calls = [];
1715
+ const good = { name: 'findGames', description: 'Find doors.', input_schema: { type: 'object', properties: { kind: { type: 'string' } } } };
1716
+ w.h.hooks.npcTools = () => [
1717
+ good,
1718
+ { ...good },
1719
+ { name: 'bad name', description: 'x', input_schema: {} },
1720
+ { name: 'perform_action', description: 'x', input_schema: {} },
1721
+ { name: 'long', description: 'x'.repeat(301), input_schema: {} },
1722
+ { name: 'bigSchema', description: 'x', input_schema: { d: 'x'.repeat(1100) } },
1723
+ { name: 'noSchema', description: 'x' },
1724
+ { name: 'today', description: 'Today.', input_schema: { type: 'object' } },
1725
+ ];
1726
+ w.h.hooks.npcTool = async (_hub, npc, playerId, name, input) => {
1727
+ calls.push({ npc: npc.id, playerId, name, input });
1728
+ return { games: [] };
1729
+ };
1730
+ w.at('a', 0, 2);
1731
+ w.at('b', 1, 1);
1732
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1733
+ const t = turn({ speaker: 'a' });
1734
+ await w.npcs.onTurn(t);
1735
+ assert.equal(t.rejected, null);
1736
+ assert.deepEqual(t.sendArgs[0][0].tools.map((x) => x.name), ['findGames', 'today']);
1737
+ const ask = { operationId: 'op1', characterId: 'greeter', playerId: 'a', name: 'findGames', input: { kind: 'farm' } };
1738
+ // Another player, another character, an undeclared tool, another turn: no hook runs.
1739
+ for (const wrong of [{ playerId: 'b' }, { characterId: 'innkeeper' }, { name: 'whereIs' }, { operationId: 'op9' }]) {
1740
+ assert.deepEqual(await w.npcs.onTool({ ...ask, ...wrong }), { error: 'not available' });
1741
+ }
1742
+ assert.equal(calls.length, 0);
1743
+ assert.deepEqual(await w.npcs.onTool(ask), { games: [] });
1744
+ assert.deepEqual(calls, [{ npc: 'greeter', playerId: 'a', name: 'findGames', input: { kind: 'farm' } }]);
1745
+ // Once per turn.
1746
+ assert.deepEqual(await w.npcs.onTool({ ...ask, name: 'today' }), { error: 'not available' });
1747
+ assert.equal(calls.length, 1);
1748
+ });
1749
+
1750
+ await test('v1.66: a throwing or empty npcTools sends the plain turn; a throwing npcTool answers an error', async () => {
1751
+ for (const npcTools of [() => { throw new Error('x'); }, () => [], () => 'nope', () => [{ name: 'a' }]]) {
1752
+ const w = world();
1753
+ w.h.hooks.npcTools = npcTools;
1754
+ w.at('a', 0, 2);
1755
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1756
+ const t = turn({ speaker: 'a' });
1757
+ await w.npcs.onTurn(t);
1758
+ assert.equal(t.rejected, null);
1759
+ assert.deepEqual(t.sendArgs, [[]]);
1760
+ }
1761
+ const w = world();
1762
+ w.h.hooks.npcTools = () => [{ name: 'today', description: 'Today.', input_schema: { type: 'object' } }];
1763
+ w.h.hooks.npcTool = () => { throw new Error('boom'); };
1764
+ w.at('a', 0, 2);
1765
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1766
+ await w.npcs.onTurn(turn({ speaker: 'a' }));
1767
+ assert.deepEqual(await w.npcs.onTool({ operationId: 'op1', characterId: 'greeter', playerId: 'a', name: 'today', input: {} }), { error: 'tool failed' });
1768
+ });
1769
+
1770
+ await test('v1.66: an async or rejecting npcTools, or a schema that serializes to nothing, still sends the turn', async () => {
1771
+ let unhandled = 0;
1772
+ const onUnhandled = () => { unhandled += 1; };
1773
+ process.on('unhandledRejection', onUnhandled);
1774
+ const good = { name: 'today', description: 'Today.', input_schema: { type: 'object' } };
1775
+ for (const npcTools of [
1776
+ async () => { throw new Error('x'); },
1777
+ async () => [good],
1778
+ () => [{ name: 'odd', description: 'x', input_schema: { toJSON() { return undefined; } } }, good],
1779
+ () => [{ name: 'odd', description: 'x', input_schema: { toJSON() { return 'text'; } } }],
1780
+ ]) {
1781
+ const w = world();
1782
+ w.h.hooks.npcTools = npcTools;
1783
+ w.at('a', 0, 2);
1784
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1785
+ const t = turn({ speaker: 'a' });
1786
+ await w.npcs.onTurn(t);
1787
+ assert.equal(t.rejected, null);
1788
+ assert.equal(t.sent, 1);
1789
+ const names = t.sendArgs[0][0]?.tools?.map((x) => x.name) ?? [];
1790
+ assert.ok(names.every((n) => n === 'today'), JSON.stringify(names));
1791
+ }
1792
+ await new Promise((r) => setTimeout(r, 20));
1793
+ process.off('unhandledRejection', onUnhandled);
1794
+ assert.equal(unhandled, 0);
1795
+ });
1796
+
1797
+ const greetingRead = (playerId = 'a', result = { characterId: 'greeter', greeting: { text: 'How did your test go?', at: 10 } }, character = 'greeter') => ({
1798
+ speaker: { playerId }, query: { type: 'status', operationId: `greeting:${character}` },
1799
+ read: async () => result, reject(code) { assert.fail(code); },
1800
+ });
1801
+
1802
+ await test('v1.76: inspect privately offers physical mind ids only, never guests or companions', async () => {
1803
+ const w = world({ extra: [
1804
+ { id: 'other', character: 'greeter', x: 1, z: 0 },
1805
+ { id: 'empty', character: null, x: 1, z: 0 },
1806
+ { id: 'quiet', character: 'quiet', x: 1, z: 0 },
1807
+ ] });
1808
+ w.at('a', 0, 2);
1809
+ w.at('b', 0, 2);
1810
+ signIn(w, 'a');
1811
+ w.h.place.companionChat = { character: 'pet', name: 'Chirp' };
1812
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'companion:a' });
1813
+ const characters = [...greetingCharacters(), { characterId: 'pet', privateState: { nextGreeting: { text: 'Owner words.' } } }];
1814
+ await inspectGreeting(w, 'a', characters);
1815
+ assert.deepEqual(w.sent.filter((m) => m.k === 'hub-npc-hooks'), [{
1816
+ playerId: 'a', k: 'hub-npc-hooks', hooks: [{ npc: 'greeter', character: 'greeter' }, { npc: 'other', character: 'greeter' }],
1817
+ }]);
1818
+ const count = w.sent.length;
1819
+ await inspectGreeting(w, 'b', characters);
1820
+ await inspectGreeting(w, 'a', []);
1821
+ assert.equal(w.sent.length, count, 'guests and empty lists send nothing');
1822
+ const plain = world({ mind: false });
1823
+ plain.at('a', 0, 2); signIn(plain, 'a');
1824
+ await inspectGreeting(plain, 'a', characters);
1825
+ assert.deepEqual(plain.sent, [], 'no mind means no new wire bytes');
1826
+ });
1827
+
1828
+ await test('v1.76: a walk-up greeting uses only the nearest private label and stays cached for chat', async () => {
1829
+ const w = world({ notes: () => 'The pad.', extra: [{ id: 'other', character: 'greeter', name: 'Other', x: 0, z: 1 }] });
1830
+ w.at('a', 0, 2); w.at('b', 0, 2); signIn(w, 'a');
1831
+ await inspectGreeting(w, 'a', greetingCharacters('How did your test go?'));
1832
+ w.h.labels = new Map(); w.h.labelsMe = new Map();
1833
+ w.h.npcLabel = (id, text, options) => {
1834
+ w.labels.push({ id, text, ...options });
1835
+ setLabel(w.h, id, text, options, true);
1836
+ };
1837
+ await w.npcs.onRead(greetingRead('a', { characterId: 'greeter', greeting: { text: ' How did\u0000 your test go?\n ', at: 10 } }));
1838
+ assert.deepEqual(w.labels, [{ id: 'other', text: 'Other: How did your test go?', style: 'speech', ttlMs: 7000, to: ['a'], about: 'a' }]);
1839
+ assert.deepEqual([...w.h.labels], [], 'public snapshots have no greeting');
1840
+ assert.equal(w.h.labelsMe.has('b'), false, 'the nearby player has no greeting label');
1841
+ assert.deepEqual(wireLabel(w.h.labelsMe.get('a').get('other')), { text: 'Other: How did your test go?', style: 'speech', npc: true });
1842
+ assert.equal(w.lines.length, 0, 'no place line hook');
1843
+ openGreeter(w);
1844
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'How did your test go?');
1845
+ assert.ok(w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix.includes('How did your test go?'));
1846
+ await w.npcs.onRead(greetingRead('a', { characterId: 'greeter', greeting: null }));
1847
+ assert.equal(w.labels.length, 1, 'a consumed hook says nothing');
1848
+ });
1849
+
1850
+ await test('v1.76: null, malformed, far, busy and mindless greeting results say nothing', async () => {
1851
+ for (const [result, character, change] of [
1852
+ [null],
1853
+ [{ characterId: 'greeter', greeting: null }],
1854
+ [{ characterId: 'other', greeting: { text: 'Private.' } }],
1855
+ [{ characterId: 'greeter', greeting: { text: ' \u0000\n ' } }],
1856
+ [{ characterId: 'greeter', greeting: { text: 10 } }],
1857
+ [undefined, ''],
1858
+ [undefined, 'greeter', (w) => { w.sim.players.get('a').at.z = 5.51; }],
1859
+ [undefined, 'greeter', (w) => { w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' }); }],
1860
+ [undefined, 'greeter', (w) => { w.h.place.npcs = null; }],
1861
+ [undefined, 'greeter', (w) => { w.h.session.world.characters = null; }],
1862
+ [undefined, 'greeter', (w) => { w.sim.bodies.delete('greeter'); }],
1863
+ ]) {
1864
+ const w = world(); w.at('a', 0, 2); w.at('b', 0, 2); signIn(w, 'a');
1865
+ change?.(w);
1866
+ w.labels.length = 0;
1867
+ await w.npcs.onRead(greetingRead('a', result, character));
1868
+ assert.deepEqual(w.labels, []);
1869
+ }
1870
+ const guest = world(); guest.at('a', 0, 2);
1871
+ await guest.npcs.onRead(greetingRead());
1872
+ assert.deepEqual(guest.labels, []);
1873
+ const pet = world(); pet.at('a', 0, 2); signIn(pet, 'a');
1874
+ pet.h.place.companionChat = { character: 'pet', name: 'Chirp' };
1875
+ pet.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'companion:a' });
1876
+ assert.equal(pet.npcs.handle('companion:a').owner, 'a');
1877
+ await pet.npcs.onRead(greetingRead('a', { characterId: 'pet', greeting: { text: 'Owner only.' } }, 'pet'));
1878
+ assert.deepEqual(pet.labels, [], 'owner/virtual records never draw a bubble');
1879
+ });
1880
+
1881
+ await test('v1.76: greeting reads recheck departure, exact body and account after the await', async () => {
1882
+ for (const change of [
1883
+ (w) => { w.npcs.leave('a'); w.sim.players.delete('a'); },
1884
+ (w) => { w.at('a', 0, 2); },
1885
+ (w) => { signIn(w, 'a', 'other-account'); },
1886
+ (w) => { w.h.session.players = []; },
1887
+ (w) => { w.sim.players.get('a').at.z = 100; },
1888
+ (w) => { w.sim.bodies.delete('greeter'); },
1889
+ ]) {
1890
+ const w = world(); w.at('a', 0, 2); signIn(w, 'a');
1891
+ let finish;
1892
+ const request = greetingRead();
1893
+ request.read = () => new Promise((resolve) => { finish = resolve; });
1894
+ const pending = w.npcs.onRead(request);
1895
+ change(w);
1896
+ finish({ characterId: 'greeter', greeting: { text: 'Private.' } });
1897
+ await pending;
1898
+ assert.deepEqual(w.labels, []);
1899
+ }
1900
+ });
1901
+
1902
+ await test('v1.76: reserved greeting ids never deliver turns; real turn status still works', async () => {
1903
+ const w = world(); w.at('a', 0, 2); signIn(w, 'a'); openGreeter(w);
1904
+ for (const operationId of ['greeting:greeter', 'greeting:', 'greeting:other']) {
1905
+ const reserved = turn({ speaker: 'a', operationId });
1906
+ await w.npcs.onTurn(reserved);
1907
+ assert.equal(reserved.rejected, 'HUB_NPC_OPERATION_RESERVED');
1908
+ assert.equal(reserved.sent, 0);
1909
+ await w.npcs.onRead(statusRead('a', operationId, 'A turn must never be drawn.'));
1910
+ assert.deepEqual(w.labels, []);
1911
+ }
1912
+ const real = turn({ speaker: 'a', operationId: 'af4dd2b6-40ee-4d43-99e9-9479d8e21856' });
1913
+ await w.npcs.onTurn(real);
1914
+ assert.equal(real.sent, 1);
1915
+ await w.npcs.onRead(statusRead('a', real.operationId, '“**Real** *reply*.”'));
1916
+ assert.deepEqual(w.labels, [{ id: 'greeter', text: 'Rowan: Real reply.', to: ['a'], about: 'a' }]);
1917
+ const disallowed = { ...greetingRead(), query: { type: 'greeting', characterId: 'greeter' }, rejected: null, reject(code) { this.rejected = code; } };
1918
+ await w.npcs.onRead(disallowed);
1919
+ assert.equal(disallowed.rejected, 'HUB_NPC_READ_NOT_ALLOWED', 'the live host still uses status');
1920
+ });
1921
+
1922
+ await test('v1.83: three simultaneous sends, speaker-only replies, notes and panels; slots free independently', async () => {
1923
+ const w = world({ turnsAtOnce: 3, notes: (_npc, playerId) => `Private notes for ${playerId}` });
1924
+ const labelState = { sim: w.sim, labels: new Map(), labelsMe: new Map() };
1925
+ const capture = w.h.npcLabel;
1926
+ w.h.npcLabel = (id, text, options) => { capture(id, text, options); setLabel(labelState, id, text, options, true); };
1927
+ w.h.hooks.npcOpening = (_hub, _npc, playerId) => ({ text: `Private opening for ${playerId}`, asks: [`Ask ${playerId}?`] });
1928
+ w.h.hooks.npcAsks = (_hub, _npc, playerId) => ({ persistentAsks: [`Private chip ${playerId}?`] });
1929
+ const open = (id) => w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' });
1930
+ const end = (id) => w.npcs.message({ playerId: id }, { k: 'hub-npc-end', npc: 'greeter' });
1931
+ for (const id of ['a', 'b', 'c', 'd']) w.at(id, 0, 2);
1932
+ for (const id of ['a', 'b', 'c']) open(id);
1933
+ const handle = w.npcs.handle('greeter');
1934
+ assert.deepEqual(handle.talkingWith, ['a', 'b', 'c']);
1935
+ assert.equal(handle.talkingTo, 'a');
1936
+ assert.equal(handle.busy, true);
1937
+ const starts = [], releases = [], tasks = [];
1938
+ for (const id of ['a', 'b', 'c']) {
1939
+ const prefix = w.sent.findLast((m) => m.playerId === id && m.k === 'hub-npc-notes').prefix;
1940
+ const request = turn({ speaker: id, operationId: `op-${id}`, input: `${prefix}Private words ${id}` });
1941
+ request.send = () => { starts.push(id); return new Promise((resolve) => releases.push(resolve)); };
1942
+ tasks.push(w.npcs.onTurn(request));
1943
+ }
1944
+ assert.deepEqual(starts, ['a', 'b', 'c'], 'all three sends run before any finishes');
1945
+ const duplicate = turn({ speaker: 'b', operationId: 'duplicate-b', input: w.sent.findLast((m) => m.playerId === 'b' && m.k === 'hub-npc-notes').prefix + 'Again' });
1946
+ await w.npcs.onTurn(duplicate);
1947
+ assert.equal(duplicate.rejected, 'HUB_NPC_BUSY', 'the same speaker cannot send a second pending turn');
1948
+ open('d');
1949
+ assert.equal(w.sent.findLast((m) => m.playerId === 'd' && m.k === 'hub-npc').why, 'busy');
1950
+ const fourth = turn({ speaker: 'd', operationId: 'fourth' });
1951
+ await w.npcs.onTurn(fourth);
1952
+ assert.equal(fourth.rejected, 'HUB_NPC_BUSY');
1953
+ assert.equal(w.lines.at(-1).why, 'busy');
1954
+ end('a');
1955
+ assert.deepEqual(handle.talkingWith, ['b', 'c']);
1956
+ assert.equal(handle.talkingTo, 'b');
1957
+ assert.equal(handle.busy, false);
1958
+ open('d');
1959
+ assert.deepEqual(handle.talkingWith, ['b', 'c', 'd']);
1960
+ w.npcs.leave('b');
1961
+ assert.deepEqual(handle.talkingWith, ['c', 'd']);
1962
+ open('a');
1963
+ assert.deepEqual(handle.talkingWith, ['c', 'd', 'a']);
1964
+ releases.forEach((resolve) => resolve());
1965
+ await Promise.all(tasks);
1966
+ for (const id of ['a', 'b', 'c']) {
1967
+ await w.npcs.onRead(statusRead(id, `op-${id}`, `Private reply ${id}`));
1968
+ }
1969
+ w.tick(1000);
1970
+ for (const id of ['a', 'b', 'c', 'd']) {
1971
+ const privateMessages = w.sent.filter((m) => m.playerId === id);
1972
+ const visibleLabels = w.labels.filter((label) => !label.to || label.to.includes(id));
1973
+ const visible = JSON.stringify([...privateMessages, ...visibleLabels]);
1974
+ for (const other of ['a', 'b', 'c', 'd'].filter((other) => other !== id)) {
1975
+ for (const kind of ['notes for', 'opening for', 'chip', 'reply', 'words']) {
1976
+ assert.ok(!visible.includes(`Private ${kind} ${other}`), `${id} must never receive ${other}'s ${kind}`);
1977
+ }
1978
+ }
1979
+ }
1980
+ assert.deepEqual(w.labels.filter((label) => label.text.includes('Private reply')).map((label) => label.to), [['a'], ['b'], ['c']]);
1981
+ assert.ok([...labelState.labels.values()].every((label) => !label.text.includes('Private')));
1982
+ for (const id of ['a', 'b', 'c']) {
1983
+ assert.equal(wireLabel(labelState.labelsMe.get(id).get('greeter')).text, `Rowan: Private reply ${id}`);
1984
+ }
1985
+ assert.equal(w.sent.filter((m) => m.playerId === 'c' && m.open === false).length, 0, 'another player ending/leaving never closes my panel');
1986
+ assert.ok(w.heard.every((entry) => entry.playerId === 'c'), 'only the unchanged conversation gets the admitted words');
1987
+ handle.end();
1988
+ assert.deepEqual(handle.talkingWith, []);
1989
+ assert.equal(handle.talkingTo, null);
1990
+ });
1991
+
1992
+ await test('v1.83: notes cannot cross speakers and the budget is shared across slots', async () => {
1993
+ const w = world({ turnsAtOnce: 3, turnsPerMinute: 2, notes: (_npc, id) => `Notes ${id}` });
1994
+ const prefix = (id) => w.sent.findLast((m) => m.playerId === id && m.k === 'hub-npc-notes').prefix;
1995
+ for (const id of ['a', 'b', 'c']) { w.at(id, 0, 2); w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' }); }
1996
+ const wrong = turn({ speaker: 'b', operationId: 'wrong', input: prefix('a') + 'hello' });
1997
+ await w.npcs.onTurn(wrong);
1998
+ assert.equal(wrong.rejected, 'HUB_NPC_NOTES');
1999
+ for (const id of ['a', 'b']) {
2000
+ const request = turn({ speaker: id, operationId: id, input: prefix(id) + 'hello' });
2001
+ await w.npcs.onTurn(request);
2002
+ assert.equal(request.sent, 1);
2003
+ }
2004
+ const over = turn({ speaker: 'c', input: prefix('c') + 'hello' });
2005
+ await w.npcs.onTurn(over);
2006
+ assert.equal(over.rejected, 'HUB_NPC_BUDGET');
2007
+ assert.equal(w.lines.at(-1).why, 'budget');
2008
+ assert.equal(over.sent, 0);
2009
+ });
2010
+
2011
+ await test('v1.83: multi-slot walks and follows continue, one-slot override holds them; override beats place', async () => {
2012
+ for (const [slots, override, capacity] of [[3, undefined, 3], [3, 1, 1], [1, 3, 3], [3, 2, 2], [undefined, 3, 3]]) {
2013
+ for (const movement of ['walk', 'follow']) {
2014
+ const w = world({ turnsAtOnce: slots, bodyTurnsAtOnce: override });
2015
+ w.at('a', 0, 2); w.at('leader', 6, 0);
2016
+ const handle = w.npcs.handle('greeter');
2017
+ if (movement === 'walk') handle.walkTo({ x: 10, z: 0 }); else handle.follow('leader');
2018
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2019
+ w.tick(100);
2020
+ assert.equal(w.greeter().p.x > 0, capacity > 1, `${slots}/${override}: ${movement}`);
2021
+ for (let i = 1; i <= capacity; i++) {
2022
+ w.at(`other-${i}`, 0, 2);
2023
+ w.npcs.message({ playerId: `other-${i}` }, { k: 'hub-npc-open', npc: 'greeter' });
2024
+ assert.equal(w.sent.findLast((m) => m.playerId === `other-${i}` && m.k === 'hub-npc').open, i < capacity);
2025
+ }
2026
+ assert.equal(handle.talkingWith.length, capacity);
2027
+ }
2028
+ }
2029
+ });
2030
+
2031
+ await test('v1.83: absent and explicit one slot have byte-identical protocol and timing', async () => {
2032
+ const traces = [];
2033
+ for (const config of [{}, { turnsAtOnce: 1 }, { bodyTurnsAtOnce: 1 }, { turnsAtOnce: 1, bodyTurnsAtOnce: 1 }]) {
2034
+ const w = world({ ...config, notes: () => 'Same notes' });
2035
+ const handle = w.npcs.handle('greeter');
2036
+ w.at('a', 0, 2); w.at('b', 2, 0);
2037
+ handle.walkTo({ x: 10, z: 0 });
2038
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2039
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
2040
+ const input = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix + 'hello';
2041
+ await w.npcs.onTurn(turn({ speaker: 'a', input }));
2042
+ w.tick(1000);
2043
+ await w.npcs.onRead(statusRead('a', 'op1', 'Same reply'));
2044
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
2045
+ w.tick(1000);
2046
+ traces.push(JSON.stringify({ sent: w.sent, labels: w.labels, lines: w.lines, at: w.greeter().p, rot: w.greeter().rot, time: w.sim.timeMs, busy: handle.busy }));
2047
+ }
2048
+ assert.ok(traces.every((trace) => trace === traces[0]));
2049
+ });
2050
+
2051
+ await test('v1.83: per-speaker timeouts and authored replies stay private', async () => {
2052
+ const w = world({ turnsAtOnce: 3 });
2053
+ w.h.session = { world: null };
2054
+ w.h.hooks.npcLine = (_hub, _npc, _id, info) => info.text ?? `line:${info.why}`;
2055
+ for (const id of ['a', 'b', 'c']) { w.at(id, 0, 2); w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' }); }
2056
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Only A typed this' });
2057
+ assert.deepEqual(w.labels.findLast((label) => label.text.includes('Only A')).to, ['a']);
2058
+ w.tick(80_000);
2059
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Only B typed this' });
2060
+ w.sim.players.delete('c');
2061
+ w.tick(11_000);
2062
+ assert.deepEqual(w.npcs.handle('greeter').talkingWith, ['b']);
2063
+ assert.equal(w.sent.findLast((m) => m.playerId === 'a' && m.open === false).why, 'idle');
2064
+ assert.equal(w.sent.findLast((m) => m.playerId === 'c' && m.open === false).why, 'left');
2065
+ });
2066
+
2067
+ await test('v1.83: reopened speakers retain their in-flight turn, and send failure clears only their pending state', async () => {
2068
+ const w = world({ turnsAtOnce: 3 });
2069
+ const open = (id) => w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' });
2070
+ for (const id of ['a', 'b']) { w.at(id, 0, 2); open(id); }
2071
+ let fail;
2072
+ const first = turn({ speaker: 'a', operationId: 'a-first' });
2073
+ first.send = () => new Promise((_resolve, reject) => { fail = reject; });
2074
+ const sending = w.npcs.onTurn(first);
2075
+ const observed = assert.rejects(sending, (err) => err.code === 'CAULDRON_SHARED_CHARACTER_BUSY');
2076
+ await w.npcs.onTurn(turn({ speaker: 'b', operationId: 'b-first' }));
2077
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
2078
+ open('a');
2079
+ const blocked = turn({ speaker: 'a', operationId: 'a-blocked' });
2080
+ await w.npcs.onTurn(blocked);
2081
+ assert.equal(blocked.rejected, 'HUB_NPC_BUSY');
2082
+ fail(Object.assign(new Error('capacity'), { code: 'CAULDRON_SHARED_CHARACTER_BUSY' }));
2083
+ await observed;
2084
+ assert.equal(w.lines.at(-1).why, 'busy', 'ghost mapping stays unchanged');
2085
+ const retry = turn({ speaker: 'a', operationId: 'a-retry' });
2086
+ await w.npcs.onTurn(retry);
2087
+ assert.equal(retry.sent, 1);
2088
+ const stillBlocked = turn({ speaker: 'b', operationId: 'b-blocked' });
2089
+ await w.npcs.onTurn(stillBlocked);
2090
+ assert.equal(stillBlocked.rejected, 'HUB_NPC_BUSY', "A's failure does not release B's turn");
2091
+ assert.deepEqual(w.npcs.handle('greeter').talkingWith, ['b', 'a']);
2092
+ });
2093
+
2094
+ await test('v1.83: handle exposes effective capacity without changing the protocol', () => {
2095
+ for (const [place, override, expected] of [[undefined, undefined, 1], [1, undefined, 1], [3, undefined, 3], [3, 1, 1], [1, 3, 3], [undefined, 2, 2]]) {
2096
+ const w = world({ turnsAtOnce: place, bodyTurnsAtOnce: override });
2097
+ const handle = w.npcs.handle('greeter');
2098
+ assert.equal(handle.turnsAtOnce, expected);
2099
+ assert.equal(w.npcs.list()[0].turnsAtOnce, expected);
2100
+ w.at('a', 0, 2);
2101
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2102
+ assert.ok(w.sent.every((msg) => !Object.hasOwn(msg, 'turnsAtOnce')));
2103
+ }
2104
+ });
2105
+
2106
+ // The actual panel and NPC server, with the socket's WORLD re-admission
2107
+ // signal and a controlled clock. No private question uses net.send.
2108
+ async function talkRig(options, run) {
2109
+ const realSetTimeout = globalThis.setTimeout;
2110
+ const realClearTimeout = globalThis.clearTimeout;
2111
+ const realNow = Object.getOwnPropertyDescriptor(performance, 'now');
2112
+ const timers = new Map();
2113
+ let now = 0, timerId = 0;
2114
+ Object.defineProperty(performance, 'now', { configurable: true, value: () => now });
2115
+ globalThis.setTimeout = (fn, ms) => { timers.set(++timerId, { fn, at: now + ms }); return timerId; };
2116
+ globalThis.clearTimeout = (id) => timers.delete(id);
2117
+ const settle = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); };
2118
+ const advance = async (ms) => {
2119
+ now += ms;
2120
+ for (const [id, timer] of [...timers]) {
2121
+ if (timer.at <= now && timers.delete(id)) timer.fn();
2122
+ }
2123
+ await settle();
2124
+ };
2125
+ clearClientHub();
2126
+ const w = world({ childAsks: options.childAsks, ...(options.name ? { greeterName: options.name } : {}), turnsAtOnce: options.slots, notes: options.noNotes ? null : () => 'fresh place notes' });
2127
+ w.at('p1', 0, 2);
2128
+ if (options.child) {
2129
+ w.h.place.under13Choices = true;
2130
+ w.h.session.players = [{ playerId: 'p1', userId: '101', under13: true }];
2131
+ }
2132
+ if (options.kid) {
2133
+ w.h.session.players = [{ playerId: 'p1', userId: '101', under13: true }];
2134
+ }
2135
+ if (options.guest) {
2136
+ w.h.session.players = [{ playerId: 'p1', userId: '101', isAnonymous: true }];
2137
+ }
2138
+ if (options.opening) {
2139
+ w.h.hooks.npcOpening = () => options.opening;
2140
+ }
2141
+ const npc = options.companion ? 'companion:p1' : 'greeter';
2142
+ const character = options.companion ? 'companion' : 'greeter';
2143
+ if (options.companion) {
2144
+ w.h.place.companionChat = { name: 'Chirp', character };
2145
+ w.h.session.players = [{ playerId: 'p1', userId: 'owner' }];
2146
+ clientHub.place = { companionChat: { name: 'Chirp' } };
2147
+ clientHub.companion = { c: { look: 'bird' } };
2148
+ }
2149
+ let handlers, cursor = 0, queue = [], closed = 0, opened = 0, draft = '', forceNotTalking = false;
2150
+ let held = [], recoveryRefusal = null, releaseRefusal;
2151
+ let turnRefusals = [];
2152
+ let holdInspects = Boolean(options.holdInspects), holdTurns = false;
2153
+ const heldInspects = [], heldTurns = [];
2154
+ const reads = {}, inspectFailures = [...(options.inspectFailures ?? [])], statusFailures = [...(options.statusFailures ?? [])];
2155
+ const lines = [], wire = [], requests = [], admitted = [];
2156
+ let typing = null, offered = [], choose = null, hint = null, waiting = false;
2157
+ const chrome = {
2158
+ onTalk(value) { handlers = value; },
2159
+ openTalk(_name, opts) { opened++; lines.length = 0; draft = ''; typing = opts.canType; },
2160
+ closeTalk() { closed++; }, talkPrompt() {}, talkAsks(asks, fn) { offered = asks; choose = fn; }, talkWaiting(value) { waiting = value; }, talkTyping(value) { typing = value; },
2161
+ talkFocused: () => false, talkLine: (who, text) => lines.push([who, text]),
2162
+ talkDraft(text) { if (text !== undefined) draft = text; return draft; },
2163
+ talkHint(text) { hint = text; },
2164
+ };
2165
+ const net = {
2166
+ selfId: () => 'p1', drain: () => { const messages = queue; queue = []; return messages; },
2167
+ send(msg) { wire.push(msg); w.npcs.message({ playerId: 'p1' }, msg); },
2168
+ characters: {
2169
+ async requestCharacterTurn(request) {
2170
+ requests.push(request);
2171
+ if (holdTurns) return new Promise((_resolve, reject) => heldTurns.push(reject));
2172
+ if (forceNotTalking) throw { code: 'HUB_NPC_NOT_TALKING' };
2173
+ if (turnRefusals.length) throw { code: turnRefusals.shift() };
2174
+ const event = turn({ speaker: 'p1', ...request, audience: request.audience.playerIds, disclosure: request.audience.disclosure });
2175
+ if (recoveryRefusal && wire.filter((msg) => msg.k === 'hub-npc-open').length > 1) {
2176
+ event.send = async () => { throw { code: recoveryRefusal }; };
2177
+ }
2178
+ try {
2179
+ await w.npcs.onTurn(event);
2180
+ } catch (err) {
2181
+ if (recoveryRefusal) await new Promise((resolve) => { releaseRefusal = resolve; });
2182
+ throw err;
2183
+ }
2184
+ if (event.rejected) throw { code: event.rejected };
2185
+ assert.equal(event.sent, 1);
2186
+ admitted.push(event);
2187
+ },
2188
+ async readCharacters({ query }) {
2189
+ reads[query.type] = (reads[query.type] ?? 0) + 1;
2190
+ if (query.type === 'inspect') {
2191
+ if (holdInspects) return new Promise((resolve, reject) => heldInspects.push({ resolve, reject }));
2192
+ const failure = inspectFailures.shift();
2193
+ if (failure) throw failure;
2194
+ return {};
2195
+ }
2196
+ const failure = statusFailures.shift();
2197
+ if (failure) throw failure;
2198
+ const status = options.status ?? 'completed';
2199
+ const response = options.reply ?? '**private** *mind* reply';
2200
+ const event = statusRead('p1', query.operationId, response, status);
2201
+ await w.npcs.onRead(event);
2202
+ return { status, response, ...(options.suggestions ? { suggestions: options.suggestions } : {}) };
2203
+ },
2204
+ },
2205
+ };
2206
+ const mp = { net, joined: true };
2207
+ const scene = { multiplayer: mp, actorWith: () => ({ components: { Transform: { x: 0, z: 2 } } }), getActors: () => [] };
2208
+ const talk = makeTalk(chrome);
2209
+ const frame = (accept = () => true) => {
2210
+ const incoming = [...held, ...w.sent.slice(cursor).filter((msg) => msg.playerId === 'p1')];
2211
+ held = incoming.filter((msg) => !accept(msg));
2212
+ clientHub.npcEvents.push(...incoming.filter(accept));
2213
+ cursor = w.sent.length;
2214
+ talk.frame(scene, mp, false);
2215
+ };
2216
+ try {
2217
+ frame();
2218
+ net.send({ k: 'hub-npc-open', npc }); frame(); await settle();
2219
+ const mark = Rehello.mark(mp, net);
2220
+ const drop = () => {
2221
+ w.sim.players.delete('p1'); w.tick(30_000); w.npcs.leave('p1');
2222
+ // The closing packet was sent to the dead socket.
2223
+ cursor = w.sent.length;
2224
+ };
2225
+ const reconnect = () => {
2226
+ w.at('p1', 0, 2); queue.push({ k: 'w' }); net.drain();
2227
+ assert.equal(Rehello.resumed(mp, net, mark), 'world');
2228
+ talk.resume();
2229
+ };
2230
+ await run({ w, npc, talk, handlers, frame, settle, advance, drop, reconnect, net, lines, wire, requests, admitted,
2231
+ typing: () => typing, waiting: () => waiting, offered: () => offered, hint: () => hint, choose: (text) => choose(text),
2232
+ opened: () => opened, closed: () => closed, draft: () => draft, setDraft: (text) => { draft = text; }, forceNotTalking: () => { forceNotTalking = true; },
2233
+ skipMessages: () => { held = []; cursor = w.sent.length; },
2234
+ refuseTurns: (...codes) => { turnRefusals = codes; }, reads,
2235
+ heldInspects, heldTurns, holdInspects: (on) => { holdInspects = on; }, holdTurns: (on) => { holdTurns = on; },
2236
+ deferRecoveryRefusal: (code) => { recoveryRefusal = code; }, releaseRefusal: () => releaseRefusal() });
2237
+ } finally {
2238
+ talk.reset(); clearClientHub();
2239
+ globalThis.setTimeout = realSetTimeout;
2240
+ globalThis.clearTimeout = realClearTimeout;
2241
+ if (realNow) {Object.defineProperty(performance, 'now', realNow);} else {delete performance.now;}
2242
+ }
2243
+ }
2244
+
2245
+ for (const options of [{ slots: 1 }, { slots: 3 }, { companion: true }]) {
2246
+ await test(`same-id WORLD re-attach sends first question once (${JSON.stringify(options)})`, () => talkRig(options, async (r) => {
2247
+ r.drop(); r.reconnect();
2248
+ r.handlers.send('private first question'); r.handlers.send('duplicate tap');
2249
+ assert.equal(r.requests.length, 0, 'question waits for the open and fresh notes');
2250
+ r.frame(); await r.settle();
2251
+ assert.equal(r.opened(), 1, 'reattach does not clear or rebuild the transcript');
2252
+ assert.equal(r.admitted.length, 1);
2253
+ assert.equal(r.requests.length, 1);
2254
+ assert(r.requests[0].input.endsWith('private first question'));
2255
+ assert(r.requests[0].input.startsWith(NOTES_HEAD));
2256
+ assert.deepEqual(r.requests[0].audience, { disclosure: 'participants', playerIds: [], characterIds: [] });
2257
+ assert.equal(r.lines.filter(([who]) => who === 'me').length, 1);
2258
+ assert(r.lines.some(([who]) => who === 'them'), 'opening remains visible');
2259
+ await r.advance(1200); r.frame();
2260
+ assert.equal(r.requests.length, 1);
2261
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, 2);
2262
+ assert(r.w.labels.every((label) => !JSON.stringify(label).includes('private first question')));
2263
+ assert(r.w.sent.every((msg) => !JSON.stringify(msg).includes('private first question')));
2264
+ }));
2265
+ }
2266
+
2267
+ // Console lines the panel logs while `run` runs.
2268
+ async function withLogs(run) {
2269
+ const log = console.log, logs = [];
2270
+ console.log = (...args) => logs.push(args.join(' '));
2271
+ try {
2272
+ await run(logs);
2273
+ } finally {
2274
+ console.log = log;
2275
+ }
2276
+ }
2277
+ const npcLogs = (logs) => logs.filter((line) => line.startsWith('[hub] NPC'));
2278
+
2279
+ await test('a failed inspect backs off, offers nothing to type meanwhile, and logs once per code', () => withLogs((logs) => talkRig({ inspectFailures: [characterRefusal(), characterRefusal(), characterRefusal()] }, async (r) => {
2280
+ const reopen = async () => { r.handlers.end(); r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle(); };
2281
+ assert.equal(r.reads.inspect, 1);
2282
+ assert.equal(r.typing(), false);
2283
+ assert.deepEqual(r.offered(), []);
2284
+ assert(r.lines.some(([who]) => who === 'them'), 'the opening stays');
2285
+ await reopen();
2286
+ assert.equal(r.reads.inspect, 1, 'held back');
2287
+ await r.advance(5000); await reopen();
2288
+ assert.equal(r.reads.inspect, 2);
2289
+ await r.advance(5000); await reopen();
2290
+ assert.equal(r.reads.inspect, 2, 'the second failure doubles the wait');
2291
+ await r.advance(5000); await reopen();
2292
+ assert.equal(r.reads.inspect, 3);
2293
+ await r.advance(20_000); await reopen();
2294
+ assert.equal(r.reads.inspect, 4);
2295
+ assert.equal(r.typing(), true, 'a successful inspect lets the player type');
2296
+ await r.advance(300_000);
2297
+ assert.deepEqual(npcLogs(logs), ['[hub] NPC inspect failed: CAULDRON_CHARACTER_UNAVAILABLE']);
2298
+ })));
2299
+
2300
+ await test('a replacement session reads afresh: no backoff, permission or logs carried over', () => withLogs((logs) => talkRig({ inspectFailures: [characterRefusal(), undefined, characterRefusal()] }, async (r) => {
2301
+ assert.equal(r.reads.inspect, 1);
2302
+ r.talk.reset();
2303
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle();
2304
+ assert.equal(r.reads.inspect, 2, 'the new session is not held back');
2305
+ assert.equal(r.typing(), true);
2306
+ r.talk.reset();
2307
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle();
2308
+ assert.equal(r.reads.inspect, 3, 'nor does it inherit the old permission to type');
2309
+ assert.equal(r.typing(), false);
2310
+ assert.equal(npcLogs(logs).length, 2, 'each session logs its own');
2311
+ })));
2312
+
2313
+ // A guest (their own account is anonymous) is over 13 like any other player:
2314
+ // a refusal shows them the opening alone, with no line of their own, as it
2315
+ // does a signed-in player; a later inspect lets them type.
2316
+ for (const [what, options] of [['a guest', { guest: true }], ['a signed-in player', {}]]) {
2317
+ await test(`${what} refused a mind sees only the opening, no sign-in line; a later inspect lets them type`, () => withLogs(() => talkRig({ ...options, name: 'Rowan, the baker', inspectFailures: [characterRefusal()] }, async (r) => {
2318
+ const reopen = async () => { r.handlers.end(); r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle(); };
2319
+ assert.equal(r.reads.inspect, 1);
2320
+ assert.equal(r.typing(), false);
2321
+ r.frame();
2322
+ assert.equal(r.hint() ?? null, null, 'no line under the opening');
2323
+ assert(r.lines.some(([who]) => who === 'them'), 'the opening stays');
2324
+ await r.advance(5000); await reopen();
2325
+ assert.equal(r.typing(), true);
2326
+ assert.equal(r.hint() ?? null, null);
2327
+ })));
2328
+ }
2329
+
2330
+ // The server tells only an under-13 speaker (trusted identity) that a mind's
2331
+ // typing is off for them by age; the client never infers it.
2332
+ await test('a mind\'s open carries ageOff only to its under-13 speaker, by the trusted stamp, in any place', () => {
2333
+ for (const [what, mind, stamp, expected] of [['under 13', true, true, true], ['over 13', true, false, false], ['no stamp', true, undefined, false], ['no mind', false, true, false]]) {
2334
+ for (const choices of [false, true]) {
2335
+ const w = world({ mind });
2336
+ if (choices) w.h.place.under13Choices = true;
2337
+ w.h.session.players = [{ playerId: 'a', userId: '101', ...(stamp === undefined ? {} : { under13: stamp }) }, { playerId: 'b', userId: '102' }];
2338
+ w.at('a', 0, 2);
2339
+ w.at('b', 0, -2);
2340
+ // What a client says of itself counts for nothing.
2341
+ w.npcs.message({ playerId: 'a', under13: !stamp }, { k: 'hub-npc-open', npc: 'greeter' });
2342
+ const opened = w.sent.find((m) => m.k === 'hub-npc' && m.open);
2343
+ assert.equal(opened.playerId, 'a');
2344
+ assert.equal(Object.hasOwn(opened, 'ageOff'), expected, `${what}, choices ${choices}`);
2345
+ if (expected) assert.equal(opened.ageOff, true);
2346
+ assert.ok(w.sent.filter((m) => m.playerId !== 'a').every((m) => !Object.hasOwn(m, 'ageOff')), 'never to anyone else');
2347
+ }
2348
+ }
2349
+ });
2350
+
2351
+ await test('an under-13 speaker on a talkLog place opens a mind without chips and archives nothing', async () => {
2352
+ for (const kid of [true, false]) {
2353
+ const w = world();
2354
+ w.h.place.talkLog = true;
2355
+ const archived = [];
2356
+ w.h.session.hub = { archiveText: async (...args) => { archived.push(args); if (kid) throw new Error('refused'); } };
2357
+ w.h.session.players = [{ playerId: 'a', userId: '101', under13: kid }];
2358
+ w.at('a', 0, 2);
2359
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2360
+ await new Promise((resolve) => setTimeout(resolve, 0));
2361
+ await new Promise((resolve) => setTimeout(resolve, 0));
2362
+ assert.ok(w.sent.find((m) => m.k === 'hub-npc' && m.open), `opened, kid ${kid}`);
2363
+ assert.ok(w.sent.every((m) => !(m.k === 'hub-npc' && m.open === false)), `not closed, kid ${kid}`);
2364
+ assert.equal(archived.length > 0, !kid, `archive attempted only for over 13, kid ${kid}`);
2365
+ if (kid) {
2366
+ const t = turn({ speaker: 'a', input: 'hello' });
2367
+ await w.npcs.onTurn(t);
2368
+ assert.ok(!t.sendArgs?.some((args) => args.some((a) => a?.hubTextArchive)), 'no archive metadata');
2369
+ }
2370
+ }
2371
+ });
2372
+
2373
+ const AGE_TALK = 'Talking with Rowan is for players 13 and up';
2374
+
2375
+ const WELCOME = { text: 'Welcome to town! Shall I show you around?', asks: ['Show me around', "I'll look myself"], more: [], authored: true };
2376
+ await test('v1.148: an under-13 speaker taps a place\'s authored asks, answered by the place and never a mind turn', () => withLogs(() => talkRig({ kid: true, opening: WELCOME, inspectFailures: [characterRefusal()] }, async (r) => {
2377
+ r.frame();
2378
+ assert.deepEqual(r.offered(), WELCOME.asks);
2379
+ assert.equal(r.typing(), false);
2380
+ assert.equal(r.hint() ?? null, null, 'choices, not the 13+ line');
2381
+ const open = r.w.sent.find((m) => m.k === 'hub-npc' && m.open);
2382
+ assert.equal(open.authoredChoices, true);
2383
+ assert.equal(open.ageOff, true);
2384
+ r.choose('Show me around'); r.frame(); await r.settle();
2385
+ assert.equal(r.requests.length, 0, 'no mind turn');
2386
+ assert.ok(r.wire.some((m) => m.k === 'hub-npc-say' && m.text === 'Show me around'));
2387
+ assert.ok(r.w.lines.some((l) => l.why === 'authored' && l.text === 'Show me around'), 'the place heard the tap');
2388
+ assert.ok(r.lines.some(([who, text]) => who === 'them' && text === 'line:authored'), 'the place answered');
2389
+ assert.deepEqual(r.offered(), [], 'the choice is made; the next open brings the next ones');
2390
+ })));
2391
+
2392
+ await test('v1.148: authored taps lead bundle chips; an adult and a plain opening are unchanged', async () => {
2393
+ await withLogs(() => talkRig({ kid: true, opening: WELCOME, childAsks: [{ id: 'hi', label: 'Hi!', prompt: 'Say hi.' }], inspectFailures: [characterRefusal()] }, async (r) => {
2394
+ r.frame();
2395
+ assert.deepEqual(r.offered(), WELCOME.asks);
2396
+ r.choose("I'll look myself"); r.frame(); await r.settle();
2397
+ assert.ok(r.w.lines.some((l) => l.why === 'authored' && l.text === "I'll look myself"), 'the place hears it despite bundle chips');
2398
+ assert.ok(r.lines.some(([who, text]) => who === 'them' && text === 'line:authored'), 'and its answer arrives');
2399
+ assert.equal(r.requests.length, 0);
2400
+ }));
2401
+ await withLogs(() => talkRig({ opening: WELCOME }, async (r) => {
2402
+ r.frame();
2403
+ const open = r.w.sent.find((m) => m.k === 'hub-npc' && m.open);
2404
+ assert.equal(open.choices, undefined);
2405
+ assert.equal(open.authoredChoices, undefined);
2406
+ assert.equal(r.typing(), true);
2407
+ }));
2408
+ const { authored: _authored, ...plain } = WELCOME;
2409
+ await withLogs(() => talkRig({ kid: true, opening: plain, inspectFailures: [characterRefusal()] }, async (r) => {
2410
+ r.frame();
2411
+ assert.deepEqual(r.offered(), []);
2412
+ assert.equal(r.hint(), AGE_TALK);
2413
+ }));
2414
+ });
2415
+
2416
+ await test('v1.148: a tap queued across a reattach stays authored, and is dropped if the new open no longer offers it', () => withLogs(async () => {
2417
+ let offer = WELCOME;
2418
+ const { authored: _authored, ...plain } = WELCOME;
2419
+ await talkRig({ kid: true, opening: WELCOME, inspectFailures: [characterRefusal(), characterRefusal()] }, async (r) => {
2420
+ r.w.h.hooks.npcOpening = () => offer;
2421
+ r.frame();
2422
+ assert.deepEqual(r.offered(), WELCOME.asks);
2423
+ r.drop();
2424
+ offer = plain;
2425
+ r.reconnect();
2426
+ r.handlers.send('Show me around');
2427
+ r.frame(); await r.settle(); r.frame(); await r.settle();
2428
+ assert.equal(r.requests.length, 0, 'never a mind turn');
2429
+ assert.ok(!r.wire.some((m) => m.k === 'hub-npc-say'), 'not offered any more, so not sent');
2430
+ assert.equal(r.waiting(), false);
2431
+ });
2432
+ }));
2433
+
2434
+ await test('v1.148: a mind with authored taps hears only those taps, and refuses its speaker\'s mind turns', async () => {
2435
+ const w = world();
2436
+ w.h.hooks.npcOpening = () => WELCOME;
2437
+ w.h.session.players = [{ playerId: 'a', userId: '101', under13: true }];
2438
+ w.at('a', 0, 2);
2439
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2440
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'tell me a secret', rid: 'r1' });
2441
+ assert.equal(w.lines.filter((l) => l.why === 'authored').length, 0, 'free text is dropped');
2442
+ const t = turn({ speaker: 'a', input: 'Show me around' });
2443
+ await w.npcs.onTurn(t);
2444
+ assert.equal(t.rejected, 'HUB_NPC_CHOICE_REQUIRED');
2445
+ w.tick(5000);
2446
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: " I'll look myself ", rid: 'r2' });
2447
+ assert.deepEqual(w.lines.filter((l) => l.why === 'authored').map((l) => l.text), ["I'll look myself"]);
2448
+ });
2449
+
2450
+ await test('an under-13 speaker refused a mind reads "Talking with <name> is for players 13 and up"; a later inspect clears it', () => withLogs(() => talkRig({ kid: true, name: 'Rowan, the baker', inspectFailures: [characterRefusal()] }, async (r) => {
2451
+ const reopen = async () => { r.handlers.end(); r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle(); };
2452
+ assert.equal(r.typing(), false);
2453
+ assert.equal(r.hint(), AGE_TALK);
2454
+ r.frame();
2455
+ assert.equal(r.hint(), AGE_TALK);
2456
+ await r.advance(5000); await reopen();
2457
+ assert.equal(r.typing(), true);
2458
+ assert.equal(r.hint(), null);
2459
+ })));
2460
+
2461
+ await test('the under-13 line waits for the inspect: none while it is out, shown when it is refused', () => withLogs(() => talkRig({ kid: true, holdInspects: true }, async (r) => {
2462
+ r.frame();
2463
+ assert.equal(r.hint() ?? null, null, 'not while the inspect is out');
2464
+ r.heldInspects.shift().reject(characterRefusal()); await r.settle();
2465
+ assert.equal(r.hint(), AGE_TALK);
2466
+ })));
2467
+
2468
+ await test('v1.101 places: a refused child sees the opening only -- no chips, no field, no line', () => withLogs(() => talkRig({ child: true, inspectFailures: [characterRefusal()] }, async (r) => {
2469
+ assert.equal(r.typing(), false);
2470
+ assert.deepEqual(r.offered(), []);
2471
+ r.frame();
2472
+ assert.equal(r.hint() ?? null, null);
2473
+ assert(r.lines.some(([who]) => who === 'them'), 'the opening stays');
2474
+ })));
2475
+
2476
+ await test('a body without a mind never shows the under-13 line', () => {
2477
+ clearClientHub();
2478
+ let hint = 'unset';
2479
+ const chrome = {
2480
+ onTalk() {}, openTalk() {}, closeTalk() {}, talkPrompt() {}, talkAsks() {}, talkWaiting() {}, talkTyping() {}, talkLine() {},
2481
+ talkFocused: () => false, talkHint(text) { hint = text; },
2482
+ };
2483
+ const net = { selfId: () => 'p1', send() {}, characters: { readCharacters: async () => { throw characterRefusal(); } } };
2484
+ const mp = { net, joined: true };
2485
+ const scene = { multiplayer: mp, actorWith: () => null, getActors: () => [] };
2486
+ const talk = makeTalk(chrome);
2487
+ try {
2488
+ talk.frame(scene, mp, false);
2489
+ clientHub.npcEvents.push({ k: 'hub-npc', npc: 'baker', open: true, name: 'Rowan, the baker', mind: false, ageOff: true, opening: { text: 'Fresh bread!' } });
2490
+ talk.frame(scene, mp, false);
2491
+ assert.equal(hint, null);
2492
+ } finally {
2493
+ talk.reset(); clearClientHub();
2494
+ }
2495
+ });
2496
+
2497
+ for (const outcome of ['hangs', 'succeeds', 'fails']) {
2498
+ await test(`an inspect in flight across reset ${outcome}: the new session reads for itself and may type`, () => withLogs((logs) => talkRig({ holdInspects: true }, async (r) => {
2499
+ assert.equal(r.heldInspects.length, 1);
2500
+ const old = r.heldInspects.shift();
2501
+ r.talk.reset();
2502
+ r.holdInspects(false);
2503
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle();
2504
+ assert.equal(r.reads.inspect, 2, 'the old read does not block the new one');
2505
+ assert.equal(r.typing(), true);
2506
+ if (outcome === 'succeeds') old.resolve({});
2507
+ if (outcome === 'fails') old.reject(characterRefusal());
2508
+ await r.settle();
2509
+ assert.equal(r.typing(), true);
2510
+ r.handlers.end(); r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle();
2511
+ assert.equal(r.reads.inspect, 2, 'the new success is remembered; an old failure arms no backoff');
2512
+ assert.equal(r.typing(), true);
2513
+ assert.deepEqual(npcLogs(logs), []);
2514
+ })));
2515
+ }
2516
+
2517
+ await test('a turn refused after reset logs nothing into the new session', () => withLogs((logs) => talkRig({}, async (r) => {
2518
+ r.holdTurns(true);
2519
+ r.handlers.send('before reset'); await r.settle();
2520
+ assert.equal(r.heldTurns.length, 1);
2521
+ const old = r.heldTurns.shift();
2522
+ r.talk.reset();
2523
+ old({ code: 'HUB_NPC_BUDGET' }); await r.settle();
2524
+ assert.deepEqual(npcLogs(logs), []);
2525
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame(); await r.settle();
2526
+ r.handlers.send('after reset'); await r.settle();
2527
+ r.heldTurns.shift()({ code: 'HUB_NPC_BUDGET' }); await r.settle();
2528
+ assert.deepEqual(npcLogs(logs), ['[hub] NPC turn refused: HUB_NPC_BUDGET'], "the new session's first refusal is logged");
2529
+ })));
2530
+
2531
+ await test("a failing status read gives up that turn's poll; a transient one keeps polling", async () => {
2532
+ await withLogs((logs) => talkRig({ statusFailures: [characterRefusal(), characterRefusal()] }, async (r) => {
2533
+ r.handlers.send('a question'); await r.settle();
2534
+ assert.equal(r.admitted.length, 1);
2535
+ for (let i = 0; i < 10; i++) await r.advance(1200);
2536
+ assert.equal(r.reads.status, 2, 'two failures end the poll');
2537
+ assert.equal(r.talk.talking(), true);
2538
+ r.handlers.send('another question'); await r.settle();
2539
+ assert.equal(r.requests.length, 2, 'the panel takes words again');
2540
+ assert.deepEqual(npcLogs(logs).filter((line) => line.includes('status')), ['[hub] NPC status read failed: CAULDRON_CHARACTER_UNAVAILABLE']);
2541
+ }));
2542
+ await withLogs(() => talkRig({ statusFailures: [new Error('socket hiccup')] }, async (r) => {
2543
+ r.handlers.send('a question'); await r.settle();
2544
+ await r.advance(1200); await r.advance(1200);
2545
+ assert.equal(r.reads.status, 2, 'a single failure is read again');
2546
+ assert(r.lines.some(([who, text]) => who === 'them' && text === 'private mind reply'));
2547
+ }));
2548
+ });
2549
+
2550
+ await test('NOT_TALKING fallback re-attaches and retries exactly once', () => talkRig({ slots: 1 }, async (r) => {
2551
+ r.drop(); r.w.at('p1', 0, 2);
2552
+ r.handlers.send('private fallback'); await r.settle();
2553
+ assert.equal(r.requests.length, 1); assert.equal(r.admitted.length, 0);
2554
+ r.frame(); await r.settle();
2555
+ assert.equal(r.requests.length, 2); assert.equal(r.admitted.length, 1);
2556
+ assert.equal(r.opened(), 1); assert.equal(r.lines.filter(([who]) => who === 'me').length, 1);
2557
+ await r.advance(1200); r.frame(); assert.equal(r.requests.length, 2);
2558
+ }));
2559
+
2560
+ await test('old body close queued before NOT_TALKING is not an open refusal', () => talkRig({}, async (r) => {
2561
+ // No gone/leave tick: the body was replaced before the conversation's
2562
+ // identity check ran. Its close precedes the refused receipt and new open.
2563
+ r.w.at('p1', 0, 2);
2564
+ r.handlers.send('question after body replacement'); await r.settle();
2565
+ r.frame(); await r.settle();
2566
+ assert.equal(r.requests.length, 2); assert.equal(r.admitted.length, 1);
2567
+ assert.equal(r.opened(), 1); assert.equal(r.talk.talking(), true);
2568
+ }));
2569
+
2570
+ await test('ordinary conversation preserves open/turn traffic', () => talkRig({}, async (r) => {
2571
+ r.handlers.send('ordinary question'); await r.settle();
2572
+ await r.advance(1200); r.frame();
2573
+ assert.deepEqual(r.wire, [{ k: 'hub-npc-open', npc: 'greeter' }]);
2574
+ assert.equal(r.requests.length, 1); assert.equal(r.admitted.length, 1);
2575
+ assert.deepEqual(Object.keys(r.requests[0]), ['requestId', 'operationId', 'characterId', 'input', 'audience']);
2576
+ assert.deepEqual(r.requests[0].audience, { disclosure: 'participants', playerIds: [], characterIds: [] });
2577
+ }));
2578
+
2579
+ for (const slots of [1, 3]) {
2580
+ await test(`full body re-attach shows place busy line, closes and restores draft (${slots} slots)`, () => talkRig({ slots }, async (r) => {
2581
+ r.drop();
2582
+ for (let i = 0; i < slots; i++) {
2583
+ const id = `other${i}`; r.w.at(id, 0, 1); r.w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: r.npc });
2584
+ }
2585
+ r.reconnect(); r.handlers.send('private unsent question'); r.frame(); await r.settle();
2586
+ assert.equal(r.requests.length, 0); assert.equal(r.lines.at(-1)[1], 'line:busy');
2587
+ assert.equal(r.talk.talking(), true, 'interruption line is visible before closing');
2588
+ assert.equal(r.draft(), 'private unsent question');
2589
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2590
+ for (let i = 0; i < slots; i++) r.w.npcs.leave(`other${i}`);
2591
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame();
2592
+ assert.equal(r.draft(), 'private unsent question');
2593
+ assert(r.w.sent.every((msg) => !JSON.stringify(msg).includes('private unsent question')));
2594
+ }));
2595
+ }
2596
+
2597
+ for (const refusal of ['gone', 'far', 'signed out']) {
2598
+ await test(`refused re-attach explains ${refusal} and closes`, () => talkRig({ companion: refusal === 'signed out' }, async (r) => {
2599
+ r.drop(); r.w.at('p1', 0, 2);
2600
+ if (refusal === 'gone') r.w.sim.players.delete('p1');
2601
+ if (refusal === 'far') r.w.sim.players.get('p1').at.x = 50;
2602
+ if (refusal === 'signed out') r.w.h.players.get('p1').arrived = false;
2603
+ r.talk.resume(); r.handlers.send('keep this question'); r.frame(); await r.settle();
2604
+ assert.equal(r.requests.length, 0);
2605
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2606
+ assert.equal(r.draft(), 'keep this question');
2607
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2608
+ }));
2609
+ }
2610
+
2611
+ await test('second NOT_TALKING cannot loop; late opens and Done cannot resend', () => talkRig({}, async (r) => {
2612
+ r.forceNotTalking(); r.handlers.send('only one retry'); await r.settle();
2613
+ r.frame(); await r.settle();
2614
+ assert.equal(r.requests.length, 2); assert.equal(r.wire.filter((m) => m.k === 'hub-npc-open').length, 2);
2615
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2616
+ r.handlers.send('duplicate'); await r.advance(1800); r.frame();
2617
+ assert.equal(r.talk.talking(), false); assert.equal(r.requests.length, 2);
2618
+ }));
2619
+
2620
+ await test('reattach timeout explains interruption; late open cannot resurrect panel', () => talkRig({}, async (r) => {
2621
+ r.drop(); r.reconnect(); r.handlers.send('draft');
2622
+ await r.advance(8000); assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2623
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2624
+ r.frame(); await r.settle(); assert.equal(r.requests.length, 0);
2625
+ assert.equal(r.talk.talking(), false, 'late open stays closed after the interruption deadline');
2626
+ }));
2627
+
2628
+ await test('Done while reattaching cancels queued send and discards late open', () => talkRig({}, async (r) => {
2629
+ r.drop(); r.reconnect(); r.handlers.send('cancel this'); r.handlers.end();
2630
+ r.frame(); await r.settle(); assert.equal(r.requests.length, 0); assert.equal(r.talk.talking(), false);
2631
+ }));
2632
+
2633
+ await test('place unavailable line split across frames wins over interruption fallback', () => talkRig({}, async (r) => {
2634
+ r.drop(); r.reconnect(); r.handlers.send('draft');
2635
+ r.w.sent.length = 0;
2636
+ clientHub.npcEvents.push({ k: 'hub-npc', npc: r.npc, open: false, why: 'unavailable' });
2637
+ r.talk.frame(null, { net: r.net }, false); await r.settle();
2638
+ clientHub.npcEvents.push({ k: 'hub-npc-line', npc: r.npc, text: 'Place unavailable words', why: 'unavailable' });
2639
+ r.talk.frame(null, { net: r.net }, false);
2640
+ assert.equal(r.lines.at(-1)[1], 'Place unavailable words');
2641
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2642
+ }));
2643
+
2644
+ await test('reattach cannot downgrade private question to authored/public speech', () => talkRig({}, async (r) => {
2645
+ r.drop(); r.w.h.place.npcs = null; r.reconnect(); r.handlers.send('private draft');
2646
+ r.frame(); await r.settle(); assert.equal(r.requests.length, 0);
2647
+ assert(!r.wire.some((msg) => msg.k === 'hub-npc-say'));
2648
+ assert.equal(r.draft(), 'private draft');
2649
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2650
+ }));
2651
+
2652
+ await test('refused proactive reattach retains a question still being composed', () => talkRig({}, async (r) => {
2653
+ r.setDraft('not submitted yet'); r.drop(); r.w.at('p1', 50, 0);
2654
+ r.talk.resume(); r.frame(); await r.settle();
2655
+ assert.equal(r.requests.length, 0); assert.equal(r.draft(), 'not submitted yet');
2656
+ await r.advance(1800); r.w.at('p1', 0, 2);
2657
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame();
2658
+ assert.equal(r.draft(), 'not submitted yet');
2659
+ }));
2660
+
2661
+ await test('reconnect never replays an admitted turn; reset cancels queued question and draft', () => talkRig({}, async (r) => {
2662
+ r.handlers.send('already admitted'); await r.settle(); assert.equal(r.admitted.length, 1);
2663
+ r.drop(); r.reconnect(); r.frame(); await r.settle(); assert.equal(r.requests.length, 1);
2664
+ await r.advance(1200); r.frame();
2665
+ r.handlers.send('new pending'); r.talk.reset(); r.frame(); await r.settle();
2666
+ assert.equal(r.requests.length, 1, 'reset cancels a question waiting for reattach');
2667
+ assert.equal(r.draft(), '');
2668
+ }));
2669
+
2670
+ // v1.84 review regressions: independently verify packet frames and receipt
2671
+ // ordering instead of draining every server response in one frame.
2672
+ const followupCases = [];
2673
+ for (const options of [{ slots: 1 }, { slots: 3 }, { companion: true }]) {
2674
+ for (const fallback of [false, true]) {
2675
+ followupCases.push([`recovery waits for fresh notes delayed beyond 400 ms (${JSON.stringify(options)}, fallback=${fallback})`, () => talkRig(options, async (r) => {
2676
+ if (options.companion && fallback) {
2677
+ // Idle/end leaves the virtual body known; leave forgets it entirely
2678
+ // and that separate server refusal is UNKNOWN, not NOT_TALKING.
2679
+ r.w.npcs.handle(r.npc).end(); r.skipMessages();
2680
+ } else {
2681
+ r.drop();
2682
+ }
2683
+ if (fallback) {
2684
+ r.w.at('p1', 0, 2); r.handlers.send('delayed notes question'); await r.settle();
2685
+ } else {
2686
+ r.reconnect(); r.handlers.send('delayed notes question');
2687
+ }
2688
+ const before = fallback ? 1 : 0;
2689
+ r.frame((msg) => msg.k !== 'hub-npc-notes'); await r.settle();
2690
+ assert.equal(r.requests.length, before, 'open acknowledgement alone cannot send the question');
2691
+ await r.advance(600);
2692
+ assert.equal(r.requests.length, before, 'recovery keeps waiting past the old notes retry delay');
2693
+ r.frame(); await r.settle();
2694
+ assert.equal(r.requests.length, before + 1); assert.equal(r.admitted.length, 1);
2695
+ assert(r.requests.at(-1).input.startsWith(NOTES_HEAD));
2696
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, 2);
2697
+ await r.advance(1200); r.frame();
2698
+ assert.equal(r.requests.length, before + 1); assert.equal(r.talk.talking(), true);
2699
+ })]);
2700
+ }
2701
+ }
2702
+ for (const code of ['CAULDRON_SHARED_CHARACTER_BUSY', 'CAULDRON_SHARED_CHARACTER_BUDGET']) {
2703
+ for (const lineFirst of [true, false]) {
2704
+ followupCases.push([`recovered turn closes after ${code} (lineFirst=${lineFirst})`, () => talkRig({}, async (r) => {
2705
+ r.drop(); r.w.at('p1', 0, 2);
2706
+ r.deferRecoveryRefusal(code); r.handlers.send('refused recovered question'); await r.settle();
2707
+ r.frame(); await r.settle();
2708
+ if (lineFirst) r.frame();
2709
+ r.releaseRefusal(); await r.settle();
2710
+ if (!lineFirst) r.frame();
2711
+ assert.equal(r.lines.at(-1)[1], code.endsWith('BUSY') ? 'line:busy' : 'line:budget');
2712
+ await r.advance(1800);
2713
+ assert.equal(r.talk.talking(), false, 'the place line cannot cancel refusal cleanup');
2714
+ assert.equal(r.draft(), 'refused recovered question');
2715
+ assert.equal(r.requests.length, 2);
2716
+ assert.equal(r.lines.filter(([, text]) => text === 'line:busy' || text === 'line:budget').length, 1);
2717
+ })]);
2718
+ }
2719
+ }
2720
+ followupCases.push(['no-note conversation reattaches without waiting for a packet the server never sends', () => talkRig({ noNotes: true }, async (r) => {
2721
+ assert(!r.w.sent.some((msg) => msg.k === 'hub-npc-notes'));
2722
+ r.drop(); r.reconnect(); r.handlers.send('no notes needed'); r.frame(); await r.settle();
2723
+ assert.equal(r.requests.length, 1); assert.equal(r.admitted.length, 1);
2724
+ assert.equal(r.requests[0].input, 'no notes needed');
2725
+ await r.advance(1200); r.frame(); assert.equal(r.talk.talking(), true);
2726
+ })]);
2727
+ followupCases.push(['open acknowledgement without required notes times out without sending the question', () => talkRig({}, async (r) => {
2728
+ r.drop(); r.reconnect(); r.handlers.send('keep waiting question');
2729
+ r.frame((msg) => msg.k !== 'hub-npc-notes'); await r.settle();
2730
+ await r.advance(8000); assert.equal(r.requests.length, 0);
2731
+ assert.equal(r.draft(), 'keep waiting question');
2732
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2733
+ await r.advance(1800); r.frame(); await r.settle();
2734
+ assert.equal(r.talk.talking(), false); assert.equal(r.requests.length, 0);
2735
+ })]);
2736
+ for (const codes of [['HUB_NPC_NOT_TALKING', 'HUB_NPC_NOTES'], ['HUB_NPC_NOTES', 'HUB_NPC_NOT_TALKING']]) {
2737
+ followupCases.push([`notes and attachment share one resend limit (${codes.join(' -> ')})`, () => talkRig({}, async (r) => {
2738
+ r.refuseTurns(...codes); r.handlers.send('one resend total'); await r.settle();
2739
+ r.frame(); await r.settle(); await r.advance(400); r.frame(); await r.settle();
2740
+ assert.equal(r.requests.length, 2, 'different refusal codes cannot each spend a resend');
2741
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, codes[0] === 'HUB_NPC_NOT_TALKING' ? 2 : 1);
2742
+ assert.equal(r.draft(), 'one resend total');
2743
+ await r.advance(8000); r.frame(); await r.settle();
2744
+ assert.equal(r.requests.length, 2); assert.equal(r.talk.talking(), false);
2745
+ })]);
2746
+ }
2747
+ followupCases.push(['recovery notes retry waits for newer notes instead of resending at 400 ms', () => talkRig({}, async (r) => {
2748
+ r.drop(); r.reconnect(); r.frame(); await r.settle();
2749
+ r.refuseTurns('HUB_NPC_NOTES'); r.handlers.send('changed notes question'); await r.settle();
2750
+ await r.advance(600); assert.equal(r.requests.length, 1);
2751
+ r.w.h.hooks.npcContext = () => 'newer notes'; r.w.tick(1000);
2752
+ r.frame(); await r.settle();
2753
+ assert.equal(r.requests.length, 2); assert.equal(r.admitted.length, 1);
2754
+ assert(r.requests.at(-1).input.includes('newer notes'));
2755
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, 2);
2756
+ })]);
2757
+ for (const [name, run] of followupCases) {
2758
+ await test(name, run);
2759
+ }
2760
+
2761
+ console.log(`hub-game npcs: ${n} tests passed`);
2762
+
2763
+ // v1.90: a delayed real follow-token read cannot restart a held body between
2764
+ // place ticks; nor can a queued physics step or a later place errand.
2765
+ await test('movement hold gates queued steps, commands and asynchronous token follows', async () => {
2766
+ let releaseInspect;
2767
+ const w = world({ inspect: () => new Promise((resolve) => { releaseInspect = resolve; }) });
2768
+ const npc = w.npcs.handle('greeter');
2769
+ w.at('a', 0, 2);
2770
+ await w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: async () => ({ participantId: 'p-a' }), reject() {} });
2771
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2772
+ await w.npcs.onTurn(turn({ speaker: 'a' }));
2773
+ await w.npcs.onRead(statusRead('a', 'op1', 'Lead the way!'));
2774
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
2775
+ w.at('a', 30, 0);
2776
+ npc.walkTo({ x: 30, z: 0 });
2777
+ w.sim.timeMs += 100;
2778
+ w.npcs.place(0.1); // Queues movement and starts the public inspect read.
2779
+ assert.ok(w.greeter().next.x > 0);
2780
+ assert.equal(typeof releaseInspect, 'function');
2781
+ npc.holdMovement(true);
2782
+ const post = { ...w.greeter().p };
2783
+ assert.deepEqual(w.greeter().next, post, 'hold cancels a step queued before physics');
2784
+ releaseInspect({ gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } });
2785
+ await new Promise((resolve) => setImmediate(resolve));
2786
+ assert.equal(npc.following, null, 'pending token result cannot restart following');
2787
+ for (let i = 0; i < 60; i++) {
2788
+ npc.walkTo({ x: 30, z: 0 }); npc.home(); npc.follow('a');
2789
+ w.tick(100);
2790
+ if (releaseInspect) releaseInspect({ gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } });
2791
+ await new Promise((resolve) => setImmediate(resolve));
2792
+ assert.deepEqual(w.greeter().p, post);
2793
+ assert.equal(npc.walking, false);
2794
+ assert.equal(npc.following, null);
2795
+ }
2796
+ npc.holdMovement(false);
2797
+ w.tick(3000);
2798
+ releaseInspect({ gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } });
2799
+ await new Promise((resolve) => setImmediate(resolve));
2800
+ assert.equal(npc.following, 'a', 'new token read resumes after release');
2801
+ w.tick(100);
2802
+ assert.ok(w.greeter().p.x > post.x);
2803
+ });
2804
+
2805
+ // v1.90: preference is private, opt-in, idempotent and replayed only as needed.
2806
+ {
2807
+ const w = world();
2808
+ w.at('a', 0, 0); w.at('b', 0, 0);
2809
+ w.npcs.replayPreferred('a');
2810
+ assert.deepEqual(w.sent, []);
2811
+ assert.equal(w.npcs.prefer('missing', 'greeter'), false);
2812
+ assert.equal(w.npcs.prefer('a', 'missing'), false);
2813
+ assert.equal(w.npcs.prefer('a', 'greeter'), true);
2814
+ w.npcs.prefer('a', 'greeter');
2815
+ assert.deepEqual(w.sent, [{ playerId: 'a', k: 'hub-npc-preferred', npc: 'greeter' }]);
2816
+ w.npcs.replayPreferred('a');
2817
+ assert.equal(w.sent.length, 2);
2818
+ w.npcs.prefer('a', null);
2819
+ w.npcs.replayPreferred('a');
2820
+ assert.equal(w.sent.length, 3, 'fresh client needs no empty hint');
2821
+ w.npcs.replayPreferred('a', true);
2822
+ assert.equal(w.sent.length, 4, 'retained client receives missed clear');
2823
+ w.npcs.leave('a');
2824
+ w.npcs.replayPreferred('a', true);
2825
+ assert.equal(w.sent.length, 4, 'departure forgets preference');
2826
+ }
2827
+
2828
+ {
2829
+ const { pongJoin } = await import('../code/client/firstJoin.js');
2830
+ for (const join of [undefined, { mode: 'public' }, { mode: 'named', key: 'room' }, { mode: 'hub', handoff: { nonce: 'handoff' } }]) {
2831
+ for (const ms of [undefined, 0, -1, '45000', Infinity]) assert.equal(pongJoin(join, ms), join);
2832
+ const withDeadline = pongJoin(join, 45000);
2833
+ assert.deepEqual(withDeadline, { ...(join ?? { mode: 'public' }), pongTimeoutMs: 45000 });
2834
+ if (join?.handoff) assert.equal(withDeadline.handoff, join.handoff);
2835
+ }
2836
+ assert.deepEqual(firstJoinFor({ hub: { pongTimeoutMs: 45000 } }, { placeCharacters: true }), { mode: 'public', pongTimeoutMs: 45000 });
2837
+ const legacy = firstJoinFor({ hub: { pongTimeoutMs: 45000, npcs: { route: 'town' } } }, {});
2838
+ assert.deepEqual(legacy.fallback, { mode: 'public', pongTimeoutMs: 45000 });
2839
+ assert.deepEqual(legacy.destination, { routeId: 'town', slot: 'main' });
2840
+ console.log('hub-game pong joins: keyless identity, public, named, handoff and legacy fallback passed');
2841
+ }
2842
+
2843
+ await test('v1.142: bundle chips open in every place without deck text, notes, tools or archives', async () => {
2844
+ for (const legacy of [undefined, false, true]) for (const count of [3, 4]) {
2845
+ const asks = bundleAsks.greeter.slice(0, count);
2846
+ const called = [];
2847
+ const w = world({ childAsks: asks, greeterName: 'Rowan, the greeter', notes: () => { called.push('notes'); return 'Deck notes'; } });
2848
+ w.h.place.under13Choices = legacy;
2849
+ w.h.place.talkLog = true;
2850
+ w.h.hooks.npcOpening = () => { called.push('opening'); return 'Deck opening'; };
2851
+ w.h.hooks.npcTools = () => { called.push('tools'); return []; };
2852
+ const archived = [];
2853
+ w.h.session.hub = { archiveText: async (...args) => archived.push(args) };
2854
+ w.h.session.players = [{ playerId: 'a', userId: '101', under13: true }];
2855
+ w.at('a', 0, 2);
2856
+ w.npcs.message({ playerId: 'a', under13: false }, { k: 'hub-npc-open', npc: 'greeter' });
2857
+ const opened = w.sent.find((m) => m.open);
2858
+ assert.deepEqual(opened.choices, asks.map(({ id, label }) => ({ id, label })));
2859
+ assert.deepEqual(opened.opening, { text: 'Tap a question to talk with Rowan.' });
2860
+ assert(w.sent.every((m) => m.k !== 'hub-npc-notes'));
2861
+ const good = turn({ speaker: 'a', input: 'choice:hi' });
2862
+ await w.npcs.onTurn(good);
2863
+ assert.equal(good.sent, 1);
2864
+ assert.deepEqual(good.sendArgs, [[]], 'no archive metadata or place tools');
2865
+ const replay = turn({ speaker: 'a', input: 'choice:hi' });
2866
+ await w.npcs.onTurn(replay);
2867
+ assert.equal(replay.sent, 1);
2868
+ const busy = turn({ speaker: 'a', input: 'choice:hi', operationId: 'busy' });
2869
+ await w.npcs.onTurn(busy);
2870
+ assert.equal(busy.rejected, 'HUB_NPC_BUSY');
2871
+ assert.equal(w.lines.length, 0, 'scripted line hook suppressed');
2872
+ assert(w.sent.every((m) => m.k !== 'hub-npc-line'));
2873
+ await w.npcs.onRead(statusRead('a', 'op1', 'A checked reply.'));
2874
+ const inspect = { speaker: { playerId: 'a' }, query: { type: 'inspect' }, async read() {
2875
+ return { participantId: 'p1', characters: [{ characterId: 'greeter', privateState: { nextGreeting: { text: 'Unsafe late greeting.' } } }] };
2876
+ } };
2877
+ await w.npcs.onRead(inspect);
2878
+ assert(w.sent.every((m) => m.k !== 'hub-npc-opening'));
2879
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
2880
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2881
+ assert.equal(w.sent.filter((m) => m.open).at(-1).opening.text, opened.opening.text);
2882
+ await new Promise((resolve) => setImmediate(resolve));
2883
+ assert.deepEqual(archived, []);
2884
+ // v1.148: the opening hook is asked (for authored taps), its words unused.
2885
+ assert.deepEqual(called, ['opening', 'opening']);
2886
+ }
2887
+ });
2888
+
2889
+ await test('v1.142: child admission checks exact bundle tokens, including replays', async () => {
2890
+ const w = world({ childAsks: bundleAsks.greeter, notes: () => 'place notes' });
2891
+ w.h.place.under13Choices = true;
2892
+ w.h.session.players = [{ playerId: 'a', under13: true }];
2893
+ w.at('a', 0, 2);
2894
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2895
+ for (const input of ['free text', 'Hi Rowan!', 'What can I do here?', 'choice:missing', ' choice:hi', 'choice:hi\n', 'choice:HI', 'choice:hi extra', NOTES_HEAD + 'notes' + NOTES_SAYS + 'choice:hi', null]) {
2896
+ const bad = turn({ speaker: 'a', input });
2897
+ await w.npcs.onTurn(bad);
2898
+ assert.equal(bad.rejected, 'HUB_NPC_CHOICE_REQUIRED', String(input));
2899
+ assert.equal(bad.sent, 0);
2900
+ }
2901
+ await w.npcs.onTurn(turn({ speaker: 'a', input: 'choice:hi' }));
2902
+ const badReplay = turn({ speaker: 'a', input: 'free text' });
2903
+ await w.npcs.onTurn(badReplay);
2904
+ assert.equal(badReplay.rejected, 'HUB_NPC_CHOICE_REQUIRED');
2905
+ assert.equal(badReplay.sent, 0);
2906
+ });
2907
+
2908
+ await test('v1.142: adults and unknown ages retain deck openings, notes, text and archives with bundle chips', async () => {
2909
+ for (const stamp of [false, undefined]) {
2910
+ const w = world({ childAsks: bundleAsks.greeter, notes: () => 'adult context' });
2911
+ w.h.place.under13Choices = true;
2912
+ w.h.place.talkLog = true;
2913
+ w.h.session.players = [{ playerId: 'a', ...(stamp === undefined ? {} : { under13: stamp }) }];
2914
+ w.h.hooks.npcOpening = () => ({ text: 'Deck opening.', asks: ['Ask me?'] });
2915
+ const archived = [];
2916
+ w.h.session.hub = { archiveText: async (_id, entry) => archived.push(entry) };
2917
+ w.at('a', 0, 2);
2918
+ w.npcs.message({ playerId: 'a', under13: true }, { k: 'hub-npc-open', npc: 'greeter' });
2919
+ await new Promise((resolve) => setImmediate(resolve));
2920
+ const opened = w.sent.find((m) => m.open);
2921
+ assert.equal(opened.choices, undefined);
2922
+ assert.equal(opened.opening.text, 'Deck opening.');
2923
+ const prefix = w.sent.find((m) => m.k === 'hub-npc-notes').prefix;
2924
+ const good = turn({ speaker: 'a', input: prefix + 'free text' });
2925
+ await w.npcs.onTurn(good);
2926
+ assert.equal(good.sent, 1);
2927
+ assert.equal(good.sendArgs[0][0].hubTextArchive.input, 'free text');
2928
+ assert.equal(archived[0].reply, 'Deck opening.');
2929
+ }
2930
+ const authored = world({ mind: false, childAsks: bundleAsks.greeter });
2931
+ authored.h.place.under13Choices = true;
2932
+ authored.h.session.players = [{ playerId: 'a', under13: true }];
2933
+ authored.at('a', 0, 2);
2934
+ authored.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2935
+ assert.deepEqual(authored.sent.find((m) => m.open).choices, ['What can I do here?', 'Tell me about yourself.', 'Where should I go next?']);
2936
+ });
2937
+
2938
+ await test('v1.142: child chips send bare tokens, ignore text channels and suggestions, and survive reconnect', () => talkRig({ kid: true, childAsks: bundleAsks.greeter, suggestions: ['Model suggestion'] }, async (r) => {
2939
+ assert.equal(r.typing(), false);
2940
+ assert.deepEqual(r.offered(), bundleAsks.greeter.map(({ id, label }) => ({ id, label })));
2941
+ r.handlers.send('forged input');
2942
+ r.handlers.send('choice:hi');
2943
+ await r.settle();
2944
+ assert.equal(r.requests.length, 0);
2945
+ clientHub.npcEvents.push({ k: 'hub-npc', npc: r.npc, open: true, mind: true, character: 'greeter', name: 'Rowan', ageOff: true, choices: r.offered(), opening: { text: 'Deck opening', asks: ['Deck question'] } });
2946
+ r.frame(); await r.settle();
2947
+ for (const msg of [{ k: 'hub-npc-opening', text: 'Deck greeting' }, { k: 'hub-npc-line', text: 'Deck line' }, { k: 'hub-npc-notes', prefix: 'Forged notes', persistentAsks: ['Deck ask'] }]) {
2948
+ clientHub.npcEvents.push({ npc: r.npc, ...msg });
2949
+ }
2950
+ r.frame();
2951
+ assert.deepEqual(r.lines, [['them', 'Tap a question to talk with Rowan.']]);
2952
+ assert.equal(r.hint(), null);
2953
+ r.choose(r.offered()[3]); await r.settle();
2954
+ assert.equal(r.requests[0].input, 'choice:fav');
2955
+ assert.equal(r.lines.at(-1)[1], 'What do you like?');
2956
+ await r.advance(1200); r.frame();
2957
+ assert(r.lines.some(([who, text]) => who === 'them' && text === 'private mind reply'));
2958
+ assert.equal(r.offered().length, 4);
2959
+ assert(r.offered().every((ask) => ask.id && ask.label !== 'Model suggestion'));
2960
+ r.drop(); r.reconnect(); r.frame(); await r.settle();
2961
+ assert.equal(r.typing(), false);
2962
+ assert.equal(r.offered().length, 4);
2963
+ r.choose(r.offered()[0]); await r.settle();
2964
+ assert.equal(r.requests.at(-1).input, 'choice:hi');
2965
+ }));
2966
+
2967
+ await test('v1.142: a refused child inspect never shows the 13+ line or enables typing', () => withLogs(() => talkRig({ kid: true, childAsks: bundleAsks.greeter, inspectFailures: [characterRefusal()] }, async (r) => {
2968
+ r.frame();
2969
+ assert.equal(r.typing(), false);
2970
+ assert.equal(r.hint(), null);
2971
+ })));
2972
+
2973
+ await test('v1.142: a refused child turn restores chips without a scripted packet', () => withLogs(() => talkRig({ kid: true, childAsks: bundleAsks.greeter }, async (r) => {
2974
+ r.refuseTurns('HUB_NPC_BUDGET');
2975
+ r.choose(r.offered()[0]); await r.settle();
2976
+ assert.equal(r.offered().length, 0);
2977
+ await r.advance(1500); r.frame();
2978
+ assert.equal(r.offered().length, 4);
2979
+ assert.equal(r.typing(), false);
2980
+ })));
2981
+
2982
+ const recoveredChildChips = (r) => {
2983
+ assert.equal(r.talk.talking(), true);
2984
+ assert.equal(r.typing(), false);
2985
+ assert.equal(r.waiting(), false);
2986
+ assert.deepEqual(r.offered(), bundleAsks.greeter.map(({ id, label }) => ({ id, label })));
2987
+ };
2988
+
2989
+ await test('child chips recover after status retries are exhausted', () => withLogs(() => talkRig({ kid: true, childAsks: bundleAsks.greeter, statusFailures: [new Error('offline'), new Error('offline')] }, async (r) => {
2990
+ r.choose(r.offered()[0]); await r.settle();
2991
+ assert.equal(r.offered().length, 0);
2992
+ await r.advance(1200); await r.advance(1200); r.frame();
2993
+ assert.equal(r.reads.status, 2);
2994
+ recoveredChildChips(r);
2995
+ assert(!r.lines.some(([, text]) => text === 'private mind reply'));
2996
+ r.choose(r.offered()[1]); await r.settle();
2997
+ assert.equal(r.requests.at(-1).input, 'choice:doors');
2998
+ })));
2999
+
3000
+ await test('child chips recover when polling times out without a reply', () => talkRig({ kid: true, childAsks: bundleAsks.greeter, status: 'queued' }, async (r) => {
3001
+ r.choose(r.offered()[0]); await r.settle();
3002
+ assert.equal(r.offered().length, 0);
3003
+ await r.advance(90_000); r.frame();
3004
+ assert.equal(r.reads.status, 1);
3005
+ recoveredChildChips(r);
3006
+ assert(!r.lines.some(([, text]) => text === 'private mind reply'));
3007
+ }));
3008
+
3009
+ for (const code of ['HUB_NPC_CHOICE_REQUIRED', 'HUB_NPC_BUDGET', 'HUB_NPC_NOTES', 'UNKNOWN_FAILURE', undefined]) {
3010
+ await test(`child chips recover after send rejection ${code}`, () => withLogs(() => talkRig({ kid: true, childAsks: bundleAsks.greeter }, async (r) => {
3011
+ r.refuseTurns(code);
3012
+ r.choose(r.offered()[0]); await r.settle();
3013
+ assert.equal(r.offered().length, 0);
3014
+ await r.advance(1500); r.frame();
3015
+ recoveredChildChips(r);
3016
+ r.choose(r.offered()[1]); await r.settle();
3017
+ assert.equal(r.requests.at(-1).input, 'choice:doors');
3018
+ assert.equal(r.admitted.length, 1);
3019
+ })));
3020
+ }
3021
+
3022
+ await test('child chips and the fixed interruption line recover after a reattached send is rejected', () => withLogs(() => talkRig({ kid: true, childAsks: bundleAsks.greeter }, async (r) => {
3023
+ r.drop(); r.reconnect(); r.frame(); await r.settle();
3024
+ r.refuseTurns('HUB_NPC_CHOICE_REQUIRED');
3025
+ r.choose(r.offered()[0]); await r.settle();
3026
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
3027
+ await r.advance(1500); r.frame();
3028
+ recoveredChildChips(r);
3029
+ })));
3030
+
3031
+ await test('child chips recover after the one NOT_TALKING retry is rejected', () => withLogs(() => talkRig({ kid: true, childAsks: bundleAsks.greeter }, async (r) => {
3032
+ r.forceNotTalking();
3033
+ r.choose(r.offered()[0]); await r.settle(); r.frame(); await r.settle();
3034
+ assert.equal(r.requests.length, 2);
3035
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
3036
+ await r.advance(1500); r.frame();
3037
+ recoveredChildChips(r);
3038
+ })));
3039
+
3040
+ for (const pendingSend of [false, true]) {
3041
+ await test(`child reconnect restores chips without replaying a pending ${pendingSend ? 'send' : 'poll'}`, () => withLogs(() => talkRig({ kid: true, childAsks: bundleAsks.greeter }, async (r) => {
3042
+ r.holdTurns(pendingSend);
3043
+ r.choose(r.offered()[0]); await r.settle();
3044
+ assert.equal(r.offered().length, 0);
3045
+ r.drop(); r.reconnect(); r.frame(); await r.settle();
3046
+ recoveredChildChips(r);
3047
+ assert.equal(r.requests.length, 1, 'unknown turn is never replayed');
3048
+ if (pendingSend) {
3049
+ r.holdTurns(false);
3050
+ } else {
3051
+ // Ghost may finish the old admitted turn after the socket is gone.
3052
+ await r.w.npcs.onRead(statusRead('p1', r.requests[0].operationId, 'Old checked reply'));
3053
+ }
3054
+ r.choose(r.offered()[1]); await r.settle();
3055
+ assert.equal(r.requests.at(-1).input, 'choice:doors');
3056
+ assert.equal(r.waiting(), true);
3057
+ if (pendingSend) {
3058
+ r.heldTurns[0]({ code: 'HUB_NPC_CHOICE_REQUIRED' }); await r.settle();
3059
+ }
3060
+ // The old poll or rejected request must not clear the new turn's wait.
3061
+ await r.advance(1200);
3062
+ assert.equal(r.requests.length, 2);
3063
+ assert.equal(r.lines.filter(([who, text]) => who === 'them' && text === 'private mind reply').length, 1);
3064
+ recoveredChildChips(r);
3065
+ await r.advance(1500); r.frame();
3066
+ recoveredChildChips(r);
3067
+ })));
3068
+ }
3069
+
3070
+ await test('v1.101: trusted child stamp requires exact canned words for authored and model paths', async () => {
3071
+ for (const mind of [false, true]) {
3072
+ const w = world({ mind });
3073
+ w.h.place.under13Choices = true;
3074
+ w.h.session.players = [{ playerId: 'a', userId: '101', under13: true }];
3075
+ w.at('a', 0, 2);
3076
+ w.npcs.message({ playerId: 'a', under13: false }, { k: 'hub-npc-open', npc: 'greeter' });
3077
+ const opened = w.sent.find((m) => m.open);
3078
+ assert.equal(opened.choices.length, 3);
3079
+ const question = opened.choices[0];
3080
+ if (mind) {
3081
+ const bad = turn({ speaker: 'a', input: 'a forged free-text message' });
3082
+ await w.npcs.onTurn(bad);
3083
+ assert.equal(bad.rejected, 'HUB_NPC_CHOICE_REQUIRED');
3084
+ assert.equal(bad.sent, 0);
3085
+ const good = turn({ speaker: 'a', input: question, operationId: 'good' });
3086
+ await w.npcs.onTurn(good);
3087
+ assert.equal(good.sent, 1);
3088
+ // A replay keeps its original admission even after notes have aged out.
3089
+ const replay = turn({ speaker: 'a', input: question, operationId: 'good' });
3090
+ await w.npcs.onTurn(replay);
3091
+ assert.equal(replay.sent, 1);
3092
+ } else {
3093
+ const count = w.lines.length;
3094
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'forged' });
3095
+ assert.equal(w.lines.length, count);
3096
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: ' '.repeat(400) + '\t\n' + question + '\n' });
3097
+ assert.equal(w.lines.at(-1).text, question, 'only canonical allowed bytes reach authored reply');
3098
+ }
3099
+ }
3100
+ });
3101
+
3102
+ await test('v1.101: key absent or trusted stamp absent preserves free text and opening bytes', async () => {
3103
+ for (const [key, stamp] of [[undefined, true], [true, undefined], [true, false]]) {
3104
+ const w = world();
3105
+ if (key !== undefined) w.h.place.under13Choices = key;
3106
+ w.h.session.players = [{ playerId: 'a', userId: '101', ...(stamp === undefined ? {} : { under13: stamp }) }];
3107
+ w.at('a', 0, 2);
3108
+ w.npcs.message({ playerId: 'a', under13: true }, { k: 'hub-npc-open', npc: 'greeter' });
3109
+ assert.ok(!Object.hasOwn(w.sent.find((m) => m.open), 'choices'));
3110
+ const t = turn({ speaker: 'a', input: 'unrestricted words' });
3111
+ await w.npcs.onTurn(t);
3112
+ assert.equal(t.sent, 1);
3113
+ }
3114
+ });
3115
+
3116
+ await test('v1.101: canned UI hides form, answers chips, refills and reconnects without free text', () => talkRig({ child: true }, async (r) => {
3117
+ assert.equal(r.typing(), false);
3118
+ assert.equal(r.offered().length, 3);
3119
+ r.handlers.send('forged input');
3120
+ await r.settle();
3121
+ assert.equal(r.requests.length, 0);
3122
+ const question = r.offered()[0];
3123
+ r.choose(question);
3124
+ await r.settle();
3125
+ assert.equal(r.admitted.length, 1);
3126
+ assert.ok(r.requests[0].input.endsWith(question));
3127
+ await r.advance(1200); r.frame();
3128
+ assert.equal(r.offered().length, 3);
3129
+ r.drop(); r.reconnect(); r.frame(); await r.settle();
3130
+ assert.equal(r.typing(), false);
3131
+ r.handlers.send('still forged'); await r.settle();
3132
+ assert.equal(r.requests.length, 1);
3133
+ }));
3134
+
3135
+ await test('v1.101: archive authored input/reply before delivery; omitted key never calls storage', async () => {
3136
+ for (const enabled of [false, true]) {
3137
+ const w = world({ mind: false });
3138
+ const archived = [];
3139
+ let release;
3140
+ w.h.session.hub = { archiveText: async (playerId, entry) => { archived.push({ playerId, ...entry }); await new Promise((resolve) => { release = resolve; }); } };
3141
+ if (enabled) w.h.place.talkLog = true;
3142
+ w.at('a', 0, 2);
3143
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
3144
+ await new Promise((resolve) => setImmediate(resolve));
3145
+ if (enabled) { assert.equal(archived[0].reply, 'line:hello'); release(); await new Promise((resolve) => setImmediate(resolve)); }
3146
+ const before = w.sent.length;
3147
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'my exact words', rid: 'r1' });
3148
+ await new Promise((resolve) => setImmediate(resolve));
3149
+ if (enabled) {
3150
+ assert.equal(w.sent.length, before, 'no reply before durable archive ack');
3151
+ assert.equal(archived.at(-1).input, 'my exact words');
3152
+ assert.equal(archived.at(-1).reply, 'line:authored');
3153
+ release(); await new Promise((resolve) => setImmediate(resolve));
3154
+ } else assert.equal(archived.length, 0);
3155
+ assert.equal(w.sent.at(-1).text, 'line:authored');
3156
+ }
3157
+ });
3158
+
3159
+ await test('v1.101: model logs words before admission, preserves replay metadata and fails closed', async () => {
3160
+ const w = world({ notes: () => 'trusted context' });
3161
+ w.h.place.talkLog = true;
3162
+ const archived = [];
3163
+ w.h.session.hub = { archiveText: async (playerId, entry) => { archived.push({ playerId, ...entry }); } };
3164
+ w.at('a', 0, 2);
3165
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
3166
+ await new Promise((resolve) => setImmediate(resolve));
3167
+ const prefix = w.sent.find((m) => m.k === 'hub-npc-notes').prefix;
3168
+ const good = turn({ speaker: 'a', input: prefix + 'question', operationId: 'logged' });
3169
+ await w.npcs.onTurn(good);
3170
+ assert.equal(archived.at(-1).input, 'question');
3171
+ assert.equal(good.sendArgs[0][0].hubTextArchive.input, 'question');
3172
+ assert.equal(good.sendArgs[0][0].hubTextArchive.npcId, 'greeter');
3173
+ const count = archived.length;
3174
+ const replay = turn({ speaker: 'a', input: prefix + 'question', operationId: 'logged' });
3175
+ await w.npcs.onTurn(replay);
3176
+ assert.deepEqual(replay.sendArgs, good.sendArgs);
3177
+ assert.equal(archived.length, count);
3178
+ w.h.session.hub.archiveText = async () => { throw new Error('offline'); };
3179
+ const bad = turn({ speaker: 'a', input: prefix + 'second question', operationId: 'failed-log' });
3180
+ await w.npcs.onTurn(bad);
3181
+ assert.equal(bad.rejected, 'HUB_NPC_LOG_UNAVAILABLE');
3182
+ assert.equal(bad.sent, 0);
3183
+ });
3184
+
3185
+ await test('v1.101: authored archive failure closes talk without an unlogged reply', async () => {
3186
+ const w = world({ mind: false });
3187
+ w.h.place.talkLog = true;
3188
+ w.h.session.hub = { archiveText: async () => {} };
3189
+ w.at('a', 0, 2);
3190
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
3191
+ await new Promise((resolve) => setImmediate(resolve));
3192
+ w.h.session.hub.archiveText = async () => { throw new Error('offline'); };
3193
+ const before = w.sent.length;
3194
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'question', rid: 'fail' });
3195
+ await new Promise((resolve) => setImmediate(resolve));
3196
+ assert.ok(w.sent.slice(before).some((m) => m.open === false && m.why === 'unavailable'));
3197
+ assert.ok(!w.sent.slice(before).some((m) => m.k === 'hub-npc-line'));
3198
+ });
3199
+
3200
+ await test('NPC display removes paired emphasis, preserves literal punctuation and identifiers', () => {
3201
+ for (const [input, expected] of [
3202
+ ['“Try **Foot Race**, *Mabel*! _Have fun_ and __come back__.”', 'Try Foot Race, Mabel! Have fun and come back.'],
3203
+ ['***Town*** is open.', 'Town is open.'],
3204
+ ['**Hello *friend* today**', 'Hello friend today'],
3205
+ ['**Hello *friend***', 'Hello friend'],
3206
+ ['***Hello** friend*', 'Hello friend'],
3207
+ ['***Hello* friend**', 'Hello friend'],
3208
+ ['🌼 **Hello *friend***', '🌼 Hello friend'],
3209
+ ['2 * 3 = 6; file_name and hub_game; a lone *', '2 * 3 = 6; file_name and hub_game; a lone *'],
3210
+ ['Plain reply.', 'Plain reply.'],
3211
+ ]) assert.equal(npcDisplayText(input), expected);
3212
+ });
3213
+ await test('NPC panel and private bubble share plain display; player input stays intact', () => talkRig({}, async (r) => {
3214
+ r.handlers.send('I typed *this*'); await r.settle();
3215
+ await r.advance(1200); r.frame(); await r.settle();
3216
+ assert(r.lines.some(([who, text]) => who === 'me' && text === 'I typed *this*'));
3217
+ assert(r.lines.some(([who, text]) => who === 'them' && text === 'private mind reply'));
3218
+ assert(r.w.labels.some(label => label.text === 'Rowan: private mind reply'));
3219
+ }));
3220
+
3221
+ // v1.134: server-started talks use the real conversation boundary, including
3222
+ // range and capacity checks and the existing private panel payload.
3223
+ {
3224
+ const absent = world({ mind: false });
3225
+ assert.equal(absent.npcs.handle('greeter').open, undefined);
3226
+ const w = world({ firstVisit: true, mind: false });
3227
+ w.h.hooks.npcOpening = () => ({ text: 'Welcome!', asks: ['Show me around', "I'll look myself"], more: [] });
3228
+ const npc = w.npcs.handle('greeter');
3229
+ assert.equal(npc.open('missing'), false);
3230
+ w.at('p', 30, 30); assert.equal(npc.open('p'), false);
3231
+ w.at('p', 1, 1); assert.equal(npc.open('p'), true);
3232
+ assert.equal(npc.open('p'), false, 'already open is not restarted');
3233
+ const packet = w.sent.find(x => x.playerId === 'p' && x.open === true);
3234
+ assert(packet, 'existing talk panel receives server opening');
3235
+ assert.equal(packet.opening.text, 'Welcome!');
3236
+ w.at('q', 1, 1); assert.equal(npc.open('q'), false, 'one-turn slot stays bounded');
3237
+ }
3238
+
3239
+ console.log(`hub-game npcs complete: ${n} tests passed`);