castle-web-cli 0.4.231 → 0.4.233

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 (368) 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/castle-host/host.d.ts +1 -0
  8. package/dist/castle-host/host.js +51 -3
  9. package/dist/castleJson.d.ts +4 -2
  10. package/dist/castleJson.js +2 -0
  11. package/dist/check.d.ts +3 -1
  12. package/dist/check.js +11 -1
  13. package/dist/devSessionStorage.js +47 -1
  14. package/dist/importPinMismatch.d.ts +22 -0
  15. package/dist/importPinMismatch.js +77 -0
  16. package/dist/importRegression.js +3 -15
  17. package/dist/imports.d.ts +10 -3
  18. package/dist/imports.js +88 -20
  19. package/dist/index.js +5 -4
  20. package/dist/init.js +1 -1
  21. package/dist/platformDoc.js +22 -0
  22. package/dist/routerFences.d.ts +5 -0
  23. package/dist/routerFences.js +12 -2
  24. package/dist/save-deck.d.ts +5 -0
  25. package/dist/save-deck.js +37 -4
  26. package/dist/serve.js +3 -0
  27. package/dist/serverBundle.js +5 -3
  28. package/dist/shell/assets/{index-D2tWM896.js → index-BjOxR-lW.js} +4 -4
  29. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  30. package/dist/shell/index.html +2 -2
  31. package/dist/taskSteer.d.ts +13 -0
  32. package/dist/taskSteer.js +22 -2
  33. package/kits/base/castle.json +1 -1
  34. package/kits/base/package-lock.json +1 -1
  35. package/kits/base/sdk/README.md +79 -2
  36. package/kits/base/sdk/avatar.d.ts +6 -2
  37. package/kits/base/sdk/avatar.js +12 -4
  38. package/kits/base/sdk/castle.d.ts +1 -1
  39. package/kits/base/sdk/commands.d.ts +14 -0
  40. package/kits/base/sdk/hub.d.ts +6 -2
  41. package/kits/base/sdk/hub.js +13 -0
  42. package/kits/base/sdk/multiplayer.js +17 -1
  43. package/kits/base/sdk/save.js +2 -1
  44. package/kits/base/sdk/server/hub.d.ts +87 -0
  45. package/kits/base/sdk/server/hub.js +70 -0
  46. package/kits/base/sdk/server/platformHandle.d.ts +31 -1
  47. package/kits/base/sdk/server/storage.d.ts +13 -0
  48. package/kits/base/sdk/server/storage.js +46 -0
  49. package/kits/base/sdk/server/wrapper.d.ts +36 -5
  50. package/kits/base/sdk/server/wrapper.js +83 -8
  51. package/kits/hub-game/CLAUDE.md +352 -12
  52. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  53. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  54. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  55. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  56. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  57. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  58. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  59. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  60. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  61. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  62. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  63. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  64. package/kits/hub-game/code/client/actorBudget.js +47 -0
  65. package/kits/hub-game/code/client/attention.js +11 -2
  66. package/kits/hub-game/code/client/avatar.js +345 -32
  67. package/kits/hub-game/code/client/avatarCap.js +228 -0
  68. package/kits/hub-game/code/client/avatarColors.js +70 -0
  69. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  70. package/kits/hub-game/code/client/avatarShare.js +251 -0
  71. package/kits/hub-game/code/client/ballot.js +467 -0
  72. package/kits/hub-game/code/client/build.js +22 -0
  73. package/kits/hub-game/code/client/chat.js +12 -0
  74. package/kits/hub-game/code/client/chrome.js +1334 -50
  75. package/kits/hub-game/code/client/companion.js +716 -0
  76. package/kits/hub-game/code/client/companionDress.js +99 -0
  77. package/kits/hub-game/code/client/decor.js +509 -0
  78. package/kits/hub-game/code/client/earned.js +131 -0
  79. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  80. package/kits/hub-game/code/client/grab.js +363 -20
  81. package/kits/hub-game/code/client/hats.js +26 -0
  82. package/kits/hub-game/code/client/hookLayer.js +328 -15
  83. package/kits/hub-game/code/client/hudClear.js +126 -0
  84. package/kits/hub-game/code/client/idle.js +163 -22
  85. package/kits/hub-game/code/client/interestCap.js +81 -0
  86. package/kits/hub-game/code/client/keys.js +36 -0
  87. package/kits/hub-game/code/client/labelsNear.js +205 -0
  88. package/kits/hub-game/code/client/menuIcons.js +34 -0
  89. package/kits/hub-game/code/client/pack.js +6 -2
  90. package/kits/hub-game/code/client/packFormat.js +3 -3
  91. package/kits/hub-game/code/client/rehello.js +167 -0
  92. package/kits/hub-game/code/client/shot.js +92 -0
  93. package/kits/hub-game/code/client/sound.js +63 -8
  94. package/kits/hub-game/code/client/soundscape.js +1151 -0
  95. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  96. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  97. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  98. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  99. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  100. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  101. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  102. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  103. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  104. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  105. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  106. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  107. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  108. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  109. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  110. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  111. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  112. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  113. package/kits/hub-game/code/client/spin.js +101 -0
  114. package/kits/hub-game/code/client/state.js +131 -1
  115. package/kits/hub-game/code/client/stuck.js +259 -0
  116. package/kits/hub-game/code/client/talk.js +538 -47
  117. package/kits/hub-game/code/client/tiers.js +541 -27
  118. package/kits/hub-game/code/client/toastBand.js +37 -0
  119. package/kits/hub-game/code/client/together.js +98 -1
  120. package/kits/hub-game/code/client/visibility.js +43 -0
  121. package/kits/hub-game/code/client/wear.js +470 -97
  122. package/kits/hub-game/code/client/yours.js +199 -0
  123. package/kits/hub-game/code/companionSpec.js +45 -0
  124. package/kits/hub-game/code/privateText.js +7 -0
  125. package/kits/hub-game/code/server/actions.js +133 -0
  126. package/kits/hub-game/code/server/actors.js +14 -1
  127. package/kits/hub-game/code/server/ask.js +155 -0
  128. package/kits/hub-game/code/server/ballot.js +539 -0
  129. package/kits/hub-game/code/server/cells.js +100 -0
  130. package/kits/hub-game/code/server/companion.js +82 -0
  131. package/kits/hub-game/code/server/cues.js +70 -0
  132. package/kits/hub-game/code/server/decor.js +269 -0
  133. package/kits/hub-game/code/server/earned.js +461 -0
  134. package/kits/hub-game/code/server/friendBests.js +166 -0
  135. package/kits/hub-game/code/server/friendsAmong.js +232 -0
  136. package/kits/hub-game/code/server/grab.js +296 -11
  137. package/kits/hub-game/code/server/history.js +5 -0
  138. package/kits/hub-game/code/server/hub.js +1317 -52
  139. package/kits/hub-game/code/server/idle.js +30 -11
  140. package/kits/hub-game/code/server/index.js +2 -2
  141. package/kits/hub-game/code/server/labels.js +28 -2
  142. package/kits/hub-game/code/server/manifest.js +424 -8
  143. package/kits/hub-game/code/server/menu.js +133 -0
  144. package/kits/hub-game/code/server/npcs.js +830 -80
  145. package/kits/hub-game/code/server/party.js +13 -2
  146. package/kits/hub-game/code/server/players.js +22 -0
  147. package/kits/hub-game/code/server/say.js +8 -2
  148. package/kits/hub-game/code/server/shot.js +110 -0
  149. package/kits/hub-game/code/server/standing.js +124 -0
  150. package/kits/hub-game/code/server/vis.js +113 -0
  151. package/kits/hub-game/code/server/wear.js +128 -11
  152. package/kits/hub-game/code/server/yours.js +59 -0
  153. package/kits/hub-game/code/shared/cues.js +9 -0
  154. package/kits/hub-game/code/shared/decor.js +41 -0
  155. package/kits/hub-game/code/shared/shot.js +19 -0
  156. package/kits/hub-game/code/shared/spin.js +57 -0
  157. package/kits/hub-game/code/systems/hub.js +1083 -85
  158. package/kits/hub-game/docs/content-pack.md +1 -1
  159. package/kits/hub-game/docs/contract.md +2440 -61
  160. package/kits/hub-game/docs/home-pieces.md +64 -0
  161. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  162. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  163. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  164. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  165. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  166. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  167. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  168. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  169. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  170. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  171. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  172. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  173. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  174. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  175. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  176. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  177. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  178. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  179. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  180. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  181. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  182. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  183. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  184. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  185. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  186. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  187. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  188. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  189. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  190. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  191. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  192. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  193. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  194. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  195. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  196. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  197. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  198. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  199. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  200. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  201. package/kits/hub-game/package-lock.json +2 -0
  202. package/kits/hub-game/package.json +2 -1
  203. package/kits/hub-game/scripts/check.mjs +78 -11
  204. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  205. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +121 -0
  206. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  207. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +23 -0
  208. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +107 -0
  209. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  210. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  211. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  212. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  213. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  214. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  215. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  216. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  217. package/kits/hub-game/scripts/test-actions-client.mjs +488 -0
  218. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  219. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  220. package/kits/hub-game/scripts/test-actors.mjs +19 -17
  221. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  222. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  223. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  224. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  225. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  226. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  227. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  228. package/kits/hub-game/scripts/test-avatar-wire.mjs +753 -0
  229. package/kits/hub-game/scripts/test-avatar.mjs +540 -7
  230. package/kits/hub-game/scripts/test-ballot.mjs +1001 -0
  231. package/kits/hub-game/scripts/test-build.mjs +31 -0
  232. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  233. package/kits/hub-game/scripts/test-chat.mjs +694 -0
  234. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  235. package/kits/hub-game/scripts/test-companion-chat.mjs +198 -0
  236. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  237. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  238. package/kits/hub-game/scripts/test-decor-client.mjs +303 -0
  239. package/kits/hub-game/scripts/test-decor.mjs +457 -0
  240. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  241. package/kits/hub-game/scripts/test-earned.mjs +1194 -0
  242. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  243. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  244. package/kits/hub-game/scripts/test-grab-client.mjs +186 -3
  245. package/kits/hub-game/scripts/test-grab-orbit.mjs +918 -0
  246. package/kits/hub-game/scripts/test-grab.mjs +864 -3
  247. package/kits/hub-game/scripts/test-hats.mjs +483 -0
  248. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  249. package/kits/hub-game/scripts/test-hub-ops.mjs +439 -2
  250. package/kits/hub-game/scripts/test-hub-trip.mjs +1228 -1
  251. package/kits/hub-game/scripts/test-hud-clear.mjs +1000 -0
  252. package/kits/hub-game/scripts/test-idle.mjs +361 -1
  253. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  254. package/kits/hub-game/scripts/test-interest-cells.mjs +493 -0
  255. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  256. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  257. package/kits/hub-game/scripts/test-labels.mjs +596 -0
  258. package/kits/hub-game/scripts/test-manifest.mjs +282 -0
  259. package/kits/hub-game/scripts/test-menu-client.mjs +480 -0
  260. package/kits/hub-game/scripts/test-menu.mjs +296 -0
  261. package/kits/hub-game/scripts/test-npcs.mjs +1718 -12
  262. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  263. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  264. package/kits/hub-game/scripts/test-party.mjs +22 -1
  265. package/kits/hub-game/scripts/test-picker.mjs +314 -0
  266. package/kits/hub-game/scripts/test-rehello.mjs +1039 -0
  267. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  268. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  269. package/kits/hub-game/scripts/test-say.mjs +59 -2
  270. package/kits/hub-game/scripts/test-shot.mjs +756 -0
  271. package/kits/hub-game/scripts/test-soundscape.mjs +5432 -0
  272. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  273. package/kits/hub-game/scripts/test-standing.mjs +416 -0
  274. package/kits/hub-game/scripts/test-stuck.mjs +1903 -0
  275. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  276. package/kits/hub-game/scripts/test-tiers-render.mjs +339 -0
  277. package/kits/hub-game/scripts/test-tiers.mjs +666 -3
  278. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  279. package/kits/hub-game/scripts/test-try-on.mjs +940 -0
  280. package/kits/hub-game/scripts/test-vis.mjs +343 -0
  281. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  282. package/kits/hub-game/scripts/test-yours-chrome.mjs +166 -0
  283. package/kits/hub-game/scripts/test-yours.mjs +372 -0
  284. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  285. package/kits/multiplayer-3d/castle.json +5 -5
  286. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  287. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  288. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  289. package/kits/multiplayer-3d/code/options.js +5 -0
  290. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  291. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  292. package/kits/multiplayer-3d/code/server/world.js +7 -0
  293. package/kits/multiplayer-3d/code/systems/multiplayer.js +74 -4
  294. package/kits/multiplayer-3d/package.json +2 -1
  295. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  296. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  297. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  298. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  299. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  300. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  301. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  302. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  303. package/kits/physics-2d/CLAUDE.md +9 -0
  304. package/kits/physics-2d/castle.json +2 -2
  305. package/kits/physics-2d/engine/scene.js +288 -1
  306. package/kits/physics-2d/engine/skyKey.js +129 -0
  307. package/kits/physics-2d/engine/stillClock.js +106 -0
  308. package/kits/physics-2d/engine/updateBudget.js +21 -0
  309. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +370 -1
  310. package/kits/physics-3d/CLAUDE.md +1391 -0
  311. package/kits/physics-3d/behaviors/Player.jsx +921 -3
  312. package/kits/physics-3d/castle.json +3 -3
  313. package/kits/physics-3d/docs/pxmodel-format.md +12 -0
  314. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +98 -10
  315. package/kits/physics-3d/engine3d/actornode.js +86 -0
  316. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  317. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  318. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  319. package/kits/physics-3d/engine3d/framecap.js +96 -0
  320. package/kits/physics-3d/engine3d/gait.js +118 -0
  321. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  322. package/kits/physics-3d/engine3d/look.js +507 -48
  323. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  324. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  325. package/kits/physics-3d/engine3d/motion.js +39 -10
  326. package/kits/physics-3d/engine3d/nearshadows.js +37 -19
  327. package/kits/physics-3d/engine3d/optimize.js +58 -5
  328. package/kits/physics-3d/engine3d/orbitinput.js +755 -0
  329. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  330. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  331. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  332. package/kits/physics-3d/engine3d/shadowfade.js +882 -0
  333. package/kits/physics-3d/engine3d/sky.js +547 -0
  334. package/kits/physics-3d/engine3d/skylife.js +306 -0
  335. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  336. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  337. package/kits/physics-3d/engine3d/world3d.js +870 -87
  338. package/kits/physics-3d/main.jsx +5 -0
  339. package/kits/physics-3d/package.json +1 -1
  340. package/kits/physics-3d/scripts/Player.before-orbit.mjs +310 -0
  341. package/kits/physics-3d/scripts/Scene3DPlayer.before-orbit.jsx +337 -0
  342. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  343. package/kits/physics-3d/scripts/test-camera-follow.mjs +12 -2
  344. package/kits/physics-3d/scripts/test-camera-orbit.mjs +4588 -0
  345. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +787 -0
  346. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +435 -0
  347. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  348. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  349. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  350. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  351. package/kits/physics-3d/scripts/test-near-shadows.mjs +3 -0
  352. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1920 -0
  353. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +545 -0
  354. package/kits/physics-3d/scripts/test-orbit-shot.mjs +583 -0
  355. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  356. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  357. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  358. package/kits/physics-3d/scripts/test-static-actors.mjs +13 -1
  359. package/kits/physics-3d/scripts/test-static-passes.mjs +1 -1
  360. package/kits/physics-3d/scripts/test-static-scenery.mjs +2171 -0
  361. package/kits/physics-3d/scripts/test-steady-hover.mjs +635 -0
  362. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  363. package/kits/physics-3d/systems/physics3d.js +474 -12
  364. package/kits/real-time/castle.json +2 -2
  365. package/kits/real-time/code/server/gameHooks.js +7 -0
  366. package/kits/real-time/code/server/session.js +97 -19
  367. package/package.json +2 -2
  368. package/dist/shell/assets/index-Cf61cNfT.css +0 -1
@@ -4,9 +4,14 @@
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 { readFileSync } from 'node:fs';
7
8
  import { setLabel, wireLabel } from '../code/server/labels.js';
8
9
  import { firstJoinFor } from '../code/client/firstJoin.js';
9
10
  import { NOTES_HEAD, NOTES_MAX, NOTES_SAYS, makeNpcs } from '../code/server/npcs.js';
11
+ import * as Idle from '../code/server/idle.js';
12
+ import { makeTalk } from '../code/client/talk.js';
13
+ import { hub as clientHub, clear as clearClientHub } from '../code/client/state.js';
14
+ import * as Rehello from '../code/client/rehello.js';
10
15
 
11
16
  function body(x, z) {
12
17
  const b = {
@@ -29,7 +34,7 @@ function body(x, z) {
29
34
  // through the route on an older SDK (`session.world.characters` only),
30
35
  // 'layer' a layer of the place (`session.characters`, `session.world` null),
31
36
  // 'world' a world on an SDK with place characters (both, the same object).
32
- function world({ mind = true, turnsPerMinute = 6, inspect, notes = null, extra = [] } = {}) {
37
+ function world({ mind = true, turnsPerMinute = 6, turnsAtOnce, bodyTurnsAtOnce, inspect, notes = null, extra = [] } = {}) {
33
38
  const sent = [];
34
39
  const labels = [];
35
40
  const lines = [];
@@ -38,11 +43,13 @@ function world({ mind = true, turnsPerMinute = 6, inspect, notes = null, extra =
38
43
  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
44
  const h = {
40
45
  sim,
46
+ players: new Map(),
47
+ ...Idle.newIdleState(),
41
48
  actors: [
42
- { id: 'greeter', components: { HubNpc: { name: 'Rowan', character: 'greeter', follow: 'greeterFollow' }, Transform: { x: 0, y: 1, z: 0 } } },
49
+ { id: 'greeter', components: { HubNpc: { name: 'Rowan', character: 'greeter', follow: 'greeterFollow', ...(bodyTurnsAtOnce !== undefined ? { turnsAtOnce: bodyTurnsAtOnce } : {}) }, Transform: { x: 0, y: 1, z: 0 } } },
43
50
  ...extra.map((e) => ({ id: e.id, components: { HubNpc: { name: e.name, character: e.character }, Transform: { x: e.x, y: 1, z: e.z } } })),
44
51
  ],
45
- place: { npcs: mind ? { route: 'town', slot: 'main', turnsPerMinute, disclosure: 'participants', followSec: 120 } : null },
52
+ place: { npcs: mind ? { route: 'town', slot: 'main', turnsPerMinute, ...(turnsAtOnce !== undefined ? { turnsAtOnce } : {}), disclosure: 'participants', followSec: 120 } : null },
46
53
  session: sessionFor(mind, {
47
54
  publicInspect: async () => {
48
55
  reads.inspect += 1;
@@ -70,7 +77,10 @@ function world({ mind = true, turnsPerMinute = 6, inspect, notes = null, extra =
70
77
  h.npcLabel = (id, text, options) => labels.push({ id, text, to: options?.to ?? null, about: options?.about ?? null });
71
78
  h.npcs = makeNpcs(h);
72
79
  h.npcs.ready();
73
- const at = (playerId, x, z) => sim.players.set(playerId, { at: { x, y: 1, z } });
80
+ const at = (playerId, x, z) => {
81
+ h.players.set(playerId, { arrived: true, ended: false });
82
+ sim.players.set(playerId, { at: { x, y: 1, z } });
83
+ };
74
84
  const tick = (ms = 100) => {
75
85
  sim.timeMs += ms;
76
86
  h.npcs.place(ms / 1000);
@@ -101,9 +111,11 @@ function turn({ speaker, audience = [], disclosure = 'participants', operationId
101
111
  input,
102
112
  audience: { disclosure, players: audience.map((playerId) => ({ playerId })), characterIds: [] },
103
113
  sent: 0,
114
+ sendArgs: [],
104
115
  rejected: null,
105
- async send() {
116
+ async send(...args) {
106
117
  t.sent += 1;
118
+ t.sendArgs.push(args);
107
119
  return { operationId, status: 'queued', replayed: false };
108
120
  },
109
121
  reject(code) {
@@ -175,7 +187,7 @@ await test('without a mind the place answers, and no turn is admitted', async ()
175
187
  assert.equal(w.sent.find((m) => m.k === 'hub-npc').mind, false);
176
188
  assert.equal(w.lines.at(-1).why, 'hello');
177
189
  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' });
190
+ assert.deepEqual(w.lines.at(-1), { npc: 'greeter', playerId: 'a', why: 'authored', text: 'hi there', conversation: 1 });
179
191
  // Authored lines are the place's own words, for everyone.
180
192
  assert.equal(w.labels.at(-1).to, null);
181
193
  assert.equal(w.sent.at(-1).k, 'hub-npc-line');
@@ -278,6 +290,7 @@ await test('over budget the place answers, no model is called', async () => {
278
290
  assert.equal(t.rejected, 'HUB_NPC_BUDGET');
279
291
  assert.equal(t.sent, 0);
280
292
  assert.equal(w.lines.at(-1).why, 'budget');
293
+ assert.equal(w.sent.findLast((m) => m.k === 'hub-npc-line').op, 'op9');
281
294
  });
282
295
 
283
296
  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,6 +308,7 @@ await test("a full place-mind queue is the place's busy line, a spent town-wide
295
308
  };
296
309
  await w.npcs.onTurn(t).catch(() => {});
297
310
  assert.equal(w.lines.at(-1).why, why, code);
311
+ assert.equal(w.sent.findLast((m) => m.k === 'hub-npc-line').op, t.operationId, code);
298
312
  }
299
313
  });
300
314
 
@@ -387,6 +401,7 @@ await test('ending the conversation does not free the body from an unanswered tu
387
401
  const t = turn({ speaker: 'b', operationId: 'b1' });
388
402
  await w.npcs.onTurn(t);
389
403
  assert.equal(t.rejected, 'HUB_NPC_BUSY');
404
+ assert.equal(w.sent.findLast((m) => m.k === 'hub-npc-line').op, 'b1');
390
405
  // Nor does a's leaving.
391
406
  w.npcs.leave('a');
392
407
  const again = turn({ speaker: 'b', operationId: 'b2' });
@@ -571,6 +586,146 @@ await test("blocks: the kit's line naming a player is marked as about them", asy
571
586
  assert.equal(hello.to, null);
572
587
  });
573
588
 
589
+ await test('v1.80: without npcAsks the notes trace is byte-identical to the captured v1.77 fixture', async () => {
590
+ let ledger = 'one';
591
+ const w = world({ notes: () => ledger });
592
+ w.at('a', 0, 2);
593
+ w.at('b', 2, 0);
594
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
595
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
596
+ w.tick(1100);
597
+ ledger = 'two';
598
+ w.tick(1100);
599
+ await w.npcs.onTurn(turn({ speaker: 'a', input: 'missing notes' }));
600
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
601
+ ledger = 'three';
602
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
603
+ const trace = w.sent.filter((m) => m.k === 'hub-npc-notes').map((m) => JSON.stringify(m)).join('\n') + '\n';
604
+ assert.equal(trace, readFileSync(new URL('./fixtures/npc-notes-v1.77.jsonl', import.meta.url), 'utf8'));
605
+ });
606
+
607
+ await test('v1.80: persistent asks trim, cap at forty, deduplicate after cutting, and keep at most two strings', () => {
608
+ const w = world({ notes: () => 'Same notes.' });
609
+ w.h.hooks.npcAsks = (hub, npc, playerId) => {
610
+ assert.equal(hub, w.h.ctx);
611
+ assert.equal(npc.id, 'greeter');
612
+ assert.equal(playerId, 'a');
613
+ return { persistentAsks: [null, 7, {}, '', ' ', ' x'.padEnd(70, 'x'), 'x'.repeat(50), ' Gift? ', 'Gift?', 'Third?'] };
614
+ };
615
+ w.at('a', 0, 2);
616
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
617
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, ['x'.repeat(40), 'Gift?']);
618
+ for (const value of [null, undefined, 'Gift?', ['Gift?'], { persistentAsks: 'Gift?' }, { persistentAsks: [false, {}, [], '', ' '] }]) {
619
+ const bare = world({ notes: () => 'Same notes.' });
620
+ bare.h.hooks.npcAsks = () => value;
621
+ bare.at('a', 0, 2);
622
+ bare.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
623
+ assert.deepEqual(bare.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, []);
624
+ }
625
+ });
626
+
627
+ await test('v1.80: unchanged notes re-read the offer, send chip-only changes and clear a stopped offer', () => {
628
+ const w = world({ notes: () => 'Same notes.' });
629
+ let offered = { persistentAsks: ['Gift?'] };
630
+ let calls = 0;
631
+ w.h.hooks.npcAsks = () => { calls += 1; return offered; };
632
+ w.at('a', 0, 2);
633
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
634
+ const first = w.sent.findLast((m) => m.k === 'hub-npc-notes');
635
+ const count = () => w.sent.filter((m) => m.k === 'hub-npc-notes').length;
636
+ w.tick(1100);
637
+ assert.equal(calls, 2);
638
+ assert.equal(count(), 1, 'an unchanged offer sends nothing');
639
+ offered = { persistentAsks: ['Another?'] };
640
+ w.tick(1100);
641
+ assert.equal(count(), 2);
642
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes'), { ...first, persistentAsks: ['Another?'] });
643
+ offered = null;
644
+ w.tick(1100);
645
+ assert.equal(count(), 3);
646
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes'), { ...first, persistentAsks: [] });
647
+ w.tick(1100);
648
+ assert.equal(count(), 3);
649
+ });
650
+
651
+ await test('v1.80: persistent asks work with a null prefix without inventing mind notes', async () => {
652
+ const w = world();
653
+ w.h.hooks.npcAsks = () => ({ persistentAsks: ['Gift?'] });
654
+ w.at('a', 0, 2);
655
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
656
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes'), { playerId: 'a', k: 'hub-npc-notes', npc: 'greeter', prefix: null, persistentAsks: ['Gift?'] });
657
+ const t = turn({ speaker: 'a', input: 'Gift?' });
658
+ await w.npcs.onTurn(t);
659
+ assert.equal(t.sent, 1);
660
+ w.h.hooks.npcAsks = () => null;
661
+ w.tick(1100);
662
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, []);
663
+ });
664
+
665
+ await test('v1.80: a refused turn re-reads and carries the latest persistent asks with fresh notes', async () => {
666
+ const w = world({ notes: () => 'Same notes.' });
667
+ let asks = ['Gift?'];
668
+ w.h.hooks.npcAsks = () => ({ persistentAsks: asks });
669
+ w.at('a', 0, 2);
670
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
671
+ asks = ['Changed?'];
672
+ const t = turn({ speaker: 'a', input: 'missing notes' });
673
+ await w.npcs.onTurn(t);
674
+ assert.equal(t.rejected, 'HUB_NPC_NOTES');
675
+ assert.equal(t.sent, 0);
676
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, ['Changed?']);
677
+ });
678
+
679
+ await test('v1.80: offers reach only their talking player, never a spectator or another conversation', () => {
680
+ const w = world({ notes: (_npc, playerId) => `Notes for ${playerId}.`, extra: [{ id: 'other', name: 'Other', character: 'other', x: 1, z: 0 }] });
681
+ const calls = [];
682
+ w.h.hooks.npcAsks = (_hub, npc, playerId) => { calls.push([npc.id, playerId]); return { persistentAsks: [`private:${playerId}`] }; };
683
+ for (const playerId of ['a', 'b', 'spectator']) w.at(playerId, 0, 2);
684
+ for (const [playerId, npc] of [['a', 'greeter'], ['b', 'other'], ['spectator', 'greeter']]) {
685
+ w.npcs.message({ playerId }, { k: 'hub-npc-open', npc });
686
+ }
687
+ w.tick(1100);
688
+ assert.deepEqual(calls, [['greeter', 'a'], ['other', 'b'], ['greeter', 'a'], ['other', 'b']]);
689
+ const notes = w.sent.filter((m) => m.k === 'hub-npc-notes');
690
+ assert.equal(notes.length, 2);
691
+ for (const msg of notes) assert.deepEqual(msg.persistentAsks, [`private:${msg.playerId}`]);
692
+ assert.ok(w.labels.every((label) => !label.text.includes('private:')));
693
+ });
694
+
695
+ await test('v1.80: throwing or rejected async npcAsks is contained, logged once without private words', async () => {
696
+ const w = world({ notes: () => 'Same notes.' });
697
+ const logs = [];
698
+ const warn = console.warn;
699
+ console.warn = (...args) => logs.push(args.join(' '));
700
+ try {
701
+ w.h.hooks.npcAsks = () => { throw new Error('Private gift words.'); };
702
+ w.at('a', 0, 2);
703
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
704
+ w.tick(1100);
705
+ assert.deepEqual(logs, ['[hub] npcAsks failed']);
706
+ assert.deepEqual(w.sent.findLast((m) => m.k === 'hub-npc-notes').persistentAsks, []);
707
+ w.h.hooks.npcAsks = async () => { throw new Error('Private async words.'); };
708
+ w.tick(1100);
709
+ w.tick(1100);
710
+ await new Promise((done) => setImmediate(done));
711
+ assert.deepEqual(logs, ['[hub] npcAsks failed', '[hub] npcAsks async hook failed; using the default']);
712
+ } finally {
713
+ console.warn = warn;
714
+ }
715
+ });
716
+
717
+ await test('v1.80: the speaker binding is rechecked after npcAsks before private delivery', () => {
718
+ const w = world({ notes: () => 'Same notes.' });
719
+ w.at('a', 0, 2);
720
+ w.h.hooks.npcAsks = () => {
721
+ w.at('a', 0, 2); // Replace the exact player body inside the hook.
722
+ return { persistentAsks: ['private:old body'] };
723
+ };
724
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
725
+ assert.equal(w.sent.some((m) => m.k === 'hub-npc-notes'), false);
726
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
727
+ });
728
+
574
729
  await test("a mind's turn carries the place's notes, which only the server writes", async () => {
575
730
  let ledger = 'Task: beat Rowan at Foot Race.';
576
731
  const w = world({ notes: (npc, playerId) => (npc.id === 'greeter' ? `${ledger} For ${playerId}.` : null) });
@@ -578,7 +733,7 @@ await test("a mind's turn carries the place's notes, which only the server write
578
733
  w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
579
734
  const first = w.sent.find((m) => m.k === 'hub-npc-notes');
580
735
  assert.equal(first.playerId, 'a');
581
- assert.equal(first.prefix, `${NOTES_HEAD}Task: beat Rowan at Foot Race. For a.${NOTES_SAYS}`);
736
+ 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
737
  // Without the notes, or with notes of the player's own, nothing reaches ghost.
583
738
  const bare = turn({ speaker: 'a', input: 'what now?' });
584
739
  await w.npcs.onTurn(bare);
@@ -594,7 +749,7 @@ await test("a mind's turn carries the place's notes, which only the server write
594
749
  await w.npcs.onTurn(ok);
595
750
  assert.equal(ok.rejected, null);
596
751
  assert.equal(ok.sent, 1);
597
- assert.deepEqual(w.heard, [{ npc: 'greeter', playerId: 'a', text: 'what now?' }]);
752
+ assert.deepEqual(w.heard, [{ npc: 'greeter', playerId: 'a', text: 'what now?', conversation: 1 }]);
598
753
  });
599
754
 
600
755
  await test('changed notes are sent again; the previous ones stay good for a while', async () => {
@@ -638,12 +793,13 @@ await test("notes are capped and can't close their own frame", async () => {
638
793
  assert.ok(!/[[\]]/.test(body));
639
794
  });
640
795
 
641
- await test('a place with no notes admits the words alone', async () => {
796
+ await test('v1.46: null place notes still carry the default opening', async () => {
642
797
  const w = world({ notes: () => null });
643
798
  w.at('a', 0, 2);
644
799
  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' });
800
+ const prefix = w.sent.find((m) => m.k === 'hub-npc-notes').prefix;
801
+ assert.ok(prefix.includes("Hi, I'm Rowan! Ask me anything."));
802
+ const t = turn({ speaker: 'a', input: `${prefix}hello` });
647
803
  await w.npcs.onTurn(t);
648
804
  assert.equal(t.rejected, null);
649
805
  const framed = turn({ speaker: 'a', operationId: 'op2', input: `${NOTES_HEAD}x${NOTES_SAYS}hello` });
@@ -694,7 +850,7 @@ await test('review: notes gone and back again; the newest notes win over an empt
694
850
  const t = turn({ speaker: 'a', input: `${prefix}hi` });
695
851
  await w.npcs.onTurn(t);
696
852
  assert.equal(t.rejected, null);
697
- assert.deepEqual(w.heard.at(-1), { npc: 'greeter', playerId: 'a', text: 'hi' });
853
+ assert.deepEqual(w.heard.at(-1), { npc: 'greeter', playerId: 'a', text: 'hi', conversation: 1 });
698
854
  });
699
855
 
700
856
  await test('review: a turn refused for its notes is sent the current ones again, even unchanged', async () => {
@@ -721,4 +877,1554 @@ await test('review: without npcContext a turn is the words as they came, markers
721
877
  assert.equal(t.sent, 1);
722
878
  });
723
879
 
880
+ // v1.37: an NPC speaks first. A mindless body still needs the place's words.
881
+ await test('v1.37: npcOpening gives the first words and what to ask, cut to size; mindless bodies without it keep their hello', async () => {
882
+ // No hook: the open message has no `opening` key, and a body without a mind says its hello.
883
+ const plain = world({ mind: false });
884
+ plain.at('a', 0, 2);
885
+ plain.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
886
+ const was = plain.sent.find((m) => m.k === 'hub-npc' && m.open);
887
+ assert.equal('opening' in was, false);
888
+ assert.equal(plain.lines.at(-1).why, 'hello');
889
+
890
+ // With the hook, no mind: the opening is its hello (no `npcLine` hello too).
891
+ const w = world({ mind: false });
892
+ const asked = [];
893
+ w.h.hooks.npcOpening = (_hub, npc, playerId, info) => {
894
+ asked.push({ npc: npc.id, playerId, ...info });
895
+ 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'] };
896
+ };
897
+ w.at('a', 0, 2);
898
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
899
+ const opened = w.sent.find((m) => m.k === 'hub-npc' && m.open);
900
+ assert.equal(opened.opening.text.length, 240);
901
+ assert.ok(opened.opening.text.startsWith('Welcome!'));
902
+ assert.deepEqual(opened.opening.asks, ['What can I do here?', 'x'.repeat(40), 'Where is the inn?']);
903
+ assert.deepEqual(asked, [{ npc: 'greeter', playerId: 'a', met: false, greeting: null, conversation: 1 }]);
904
+ assert.equal(w.lines.length, 0, 'no hello line beside the opening');
905
+ // The opening goes to the one who opened, and to nobody else.
906
+ assert.deepEqual(w.sent.filter((m) => m.opening).map((m) => m.playerId), ['a']);
907
+ // Having said something, they have met: the next opening is told so.
908
+ w.tick(1000);
909
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'hi' });
910
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
911
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
912
+ assert.equal(asked.at(-1).met, true);
913
+ w.at('b', 1, 1);
914
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
915
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
916
+ assert.equal(asked.at(-1).met, false, 'someone else has not');
917
+ // A guest who leaves is forgotten; the record is bounded; a place with no hook keeps none.
918
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-say', npc: 'greeter', text: 'hi' });
919
+ assert.equal(w.npcs.metCount?.('greeter') ?? null, 2);
920
+ w.npcs.leave('b');
921
+ assert.equal(w.npcs.metCount('greeter'), 1);
922
+ assert.equal(plain.npcs.metCount('greeter'), 0);
923
+ plain.tick(1000);
924
+ plain.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'hi' });
925
+ assert.equal(plain.npcs.metCount('greeter'), 0, 'no hook: nobody is kept');
926
+
927
+ // A string is the words alone; null, a thrown error or nothing usable is no opening.
928
+ for (const [given, want] of [['Hello there.', { text: 'Hello there.', asks: [] }], [null, null], [{ asks: ['Why?'] }, null], [{ text: 5 }, null], [() => { throw new Error('boom'); }, null]]) {
929
+ const v = world({ mind: false });
930
+ v.h.hooks.npcOpening = typeof given === 'function' ? given : () => given;
931
+ v.at('a', 0, 2);
932
+ v.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
933
+ const msg = v.sent.find((m) => m.k === 'hub-npc' && m.open);
934
+ assert.deepEqual(msg.opening ?? null, want);
935
+ assert.equal(v.lines.some((l) => l.why === 'hello'), want === null, 'the hello line only when there is no opening');
936
+ }
937
+ });
938
+
939
+ await test('v1.37: with a mind, the opening is in that conversation\'s notes; v1.46: the next can get the default', async () => {
940
+ const w = world({ notes: () => 'The pad is empty.' });
941
+ w.h.hooks.npcOpening = () => ({ text: 'I am Rowan [the] greeter.', asks: ['Where do I go?'] });
942
+ w.at('a', 0, 2);
943
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
944
+ assert.equal(w.sent.find((m) => m.k === 'hub-npc' && m.open).opening.text, 'I am Rowan [the] greeter.');
945
+ const first = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
946
+ assert.ok(first.includes('The pad is empty.') && first.includes('You opened this conversation by saying: "I am Rowan the greeter."'), first);
947
+ // v1.46: null now gives a mind the kit's opening in the next conversation.
948
+ w.h.hooks.npcOpening = () => null;
949
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
950
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
951
+ const next = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
952
+ assert.ok(next.includes('The pad is empty.') && next.includes("Hi, I'm Rowan! Ask me anything.") && !next.includes('I am Rowan'), next);
953
+
954
+ // The place's notes come first and whole; the opening has what is left of
955
+ // NOTES_MAX, and is left out where that is too little.
956
+ for (const [size, wantOpening] of [[NOTES_MAX, false], [NOTES_MAX - 30, false], [NOTES_MAX - 120, true], [100, true]]) {
957
+ const full = world({ notes: () => 'n'.repeat(size) });
958
+ full.h.hooks.npcOpening = () => 'W'.repeat(240);
959
+ full.at('a', 0, 2);
960
+ full.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
961
+ const prefix = full.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
962
+ const bodyOf = prefix.slice(NOTES_HEAD.length, prefix.length - NOTES_SAYS.length);
963
+ assert.ok(bodyOf.length <= NOTES_MAX, `notes of ${bodyOf.length} characters for a context of ${size}`);
964
+ assert.ok(bodyOf.startsWith('n'.repeat(size)), 'the place\'s notes whole');
965
+ assert.equal(bodyOf.includes('You opened'), wantOpening, `context ${size}`);
966
+ }
967
+
968
+ // A place with no notes of its own sends its turns as the words alone: the opening adds none.
969
+ const bare = world();
970
+ bare.h.hooks.npcOpening = () => 'Hello.';
971
+ bare.at('a', 0, 2);
972
+ bare.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
973
+ assert.equal(bare.sent.find((m) => m.k === 'hub-npc' && m.open).opening.text, 'Hello.');
974
+ assert.ok(bare.sent.filter((m) => m.k === 'hub-npc-notes').every((m) => m.prefix === null));
975
+ });
976
+
977
+ await test('v1.46: a mind without opening words speaks first; a place opening stays its own', () => {
978
+ for (const hook of [undefined, () => null, () => '', () => ({ text: ' ', asks: ['Ignored?'] })]) {
979
+ const w = world({ notes: () => 'The pad is empty.', extra: [{ id: 'puppy', name: 'Biscuit, the puppy', character: 'puppy', x: 1, z: 0 }] });
980
+ if (hook) {
981
+ w.h.hooks.npcOpening = hook;
982
+ }
983
+ w.at('a', 0, 2);
984
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'puppy' });
985
+ const opened = w.sent.find((m) => m.k === 'hub-npc' && m.open);
986
+ assert.deepEqual(opened.opening, {
987
+ text: "Hi, I'm Biscuit! Ask me anything.",
988
+ asks: ['Who are you?', 'What do you do here?', 'Tell me a secret!'],
989
+ 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?'],
990
+ });
991
+ const prefix = w.sent.find((m) => m.k === 'hub-npc-notes').prefix;
992
+ assert.ok(prefix.includes(opened.opening.text));
993
+ assert.ok(prefix.includes('You opened this conversation by saying:'));
994
+ assert.equal(w.lines.length, 0);
995
+ }
996
+ for (const given of ['My own words.', { text: 'My own words.' }, { text: 'My own words.', asks: ['My own question?'] }]) {
997
+ const w = world();
998
+ w.h.hooks.npcOpening = () => given;
999
+ w.at('a', 0, 2);
1000
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1001
+ assert.deepEqual(w.sent.find((m) => m.k === 'hub-npc' && m.open).opening, { text: 'My own words.', asks: given.asks ?? [] });
1002
+ assert.equal(w.sent.filter((m) => m.k === 'hub-npc-notes').length, 0, 'no npcContext still means no notes');
1003
+ }
1004
+ const bare = world();
1005
+ bare.at('a', 0, 2);
1006
+ bare.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1007
+ assert.equal(bare.sent.filter((m) => m.k === 'hub-npc-notes').length, 0, 'the default follows the same notes rule');
1008
+ const mindless = world({ mind: false });
1009
+ mindless.at('a', 0, 2);
1010
+ mindless.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1011
+ assert.equal('opening' in mindless.sent.find((m) => m.k === 'hub-npc' && m.open), false);
1012
+ assert.equal(mindless.lines.at(-1).why, 'hello');
1013
+ });
1014
+
1015
+ await test('v1.46: more questions are cut, deduped and bounded; empty more is not sent', () => {
1016
+ for (const mind of [true, false]) {
1017
+ const w = world({ mind });
1018
+ 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}?`)] });
1019
+ w.at('a', 0, 2);
1020
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1021
+ const opening = w.sent.find((m) => m.k === 'hub-npc' && m.open).opening;
1022
+ assert.deepEqual(opening.asks, ['Why?', 'x'.repeat(40)]);
1023
+ assert.deepEqual(opening.more, ['Later?', 'y'.repeat(40), ...Array.from({ length: 7 }, (_, i) => `Question ${i}?`)]);
1024
+ for (const more of [undefined, [], ['Why?', 'x'.repeat(41), null, ' ']]) {
1025
+ w.h.hooks.npcOpening = () => ({ text: 'Hello.', asks: ['Why?', 'x'.repeat(40)], more });
1026
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1027
+ assert.equal('more' in w.sent.findLast((m) => m.k === 'hub-npc' && m.open).opening, false);
1028
+ }
1029
+ }
1030
+ });
1031
+
1032
+ await test('v1.46: authored replies keep no operation id and cooldown drops send no reply', () => {
1033
+ const w = world({ mind: false });
1034
+ w.at('a', 0, 2);
1035
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1036
+ assert.equal('op' in w.sent.findLast((m) => m.k === 'hub-npc-line'), false);
1037
+ assert.equal('rid' in w.sent.at(-1), false);
1038
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'One?', rid: 'say-a' });
1039
+ const count = w.sent.filter((m) => m.k === 'hub-npc-line').length;
1040
+ assert.equal(w.sent.at(-1).why, 'authored');
1041
+ assert.equal('op' in w.sent.at(-1), false);
1042
+ assert.equal(w.sent.at(-1).rid, 'say-a');
1043
+ w.tick(899);
1044
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Two?', rid: 'dropped' });
1045
+ assert.equal(w.sent.filter((m) => m.k === 'hub-npc-line').length, count);
1046
+ assert.equal(w.sent.some((m) => m.rid === 'dropped'), false);
1047
+ w.tick(1);
1048
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Two?', rid: 'say-b' });
1049
+ assert.equal(w.sent.filter((m) => m.k === 'hub-npc-line').length, count + 1);
1050
+ assert.equal(w.sent.at(-1).rid, 'say-b');
1051
+ w.tick(900);
1052
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Legacy client' });
1053
+ assert.equal('rid' in w.sent.at(-1), false, 'an older client gets no added request id');
1054
+ for (const rid of [5, {}, 'x'.repeat(65)]) {
1055
+ w.tick(900);
1056
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Hello', rid });
1057
+ assert.equal('rid' in w.sent.at(-1), false, 'only short string request ids are echoed');
1058
+ }
1059
+ });
1060
+
1061
+ function reacting(options = {}) {
1062
+ const w = world(options);
1063
+ w.h.place.idle = { emotes: true, seats: false, sounds: [] };
1064
+ w.at('a', 0, 2);
1065
+ // The speech choice is tested separately from the emote cooldown.
1066
+ w.h.hooks.npcReact = () => ({ line: null });
1067
+ return w;
1068
+ }
1069
+
1070
+ await test('v1.47: the nearest three free bodies within six flat metres answer and face the player', () => {
1071
+ const w = reacting({ extra: [
1072
+ { id: 'far', x: 0, z: 8.01 }, { id: 'edge', x: 0, z: 8 },
1073
+ { id: 'near', x: 0, z: 3 }, { id: 'next', x: 2, z: 2 },
1074
+ ] });
1075
+ w.sim.bodies.get('near').p.y = 100;
1076
+ assert.deepEqual(Idle.fields(w.h), { hubEmotes: {} });
1077
+ Idle.emoteMessage(w.h, 'a', { id: 'wave' });
1078
+ assert.deepEqual(Object.keys(Idle.fields(w.h).hubNpcEmotes).sort(), ['greeter', 'near', 'next']);
1079
+ assert.deepEqual(Idle.fields(w.h).hubNpcEmotes.near, { id: 'wave', at: 0, until: Idle.EMOTES.wave });
1080
+ assert.ok(Math.abs(w.sim.bodies.get('near').rot.y - 1) < 1e-9, 'near faces -z');
1081
+ w.tick(Idle.EMOTES.wave);
1082
+ assert.deepEqual(Idle.fields(w.h).hubNpcEmotes, {}, 'expiry is latched too');
1083
+ const edge = reacting({ extra: [{ id: 'edge', x: 0, z: 8 }, { id: 'far', x: 0, z: 8.01 }] });
1084
+ Idle.emote(edge.h, 'a', 'spin');
1085
+ assert.deepEqual(Object.keys(Idle.fields(edge.h).hubNpcEmotes), ['greeter', 'edge']);
1086
+ assert.equal(Idle.fields(edge.h).hubNpcEmotes.edge.id, 'cheer');
1087
+ });
1088
+
1089
+ await test('v1.47: player reactions wait four seconds and each NPC waits eight, even for place emotes', () => {
1090
+ const w = reacting();
1091
+ w.at('b', 0, 1);
1092
+ let asked = 0;
1093
+ w.h.hooks.npcReact = () => { asked += 1; return { line: null }; };
1094
+ Idle.emote(w.h, 'a', 'wave');
1095
+ w.sim.timeMs = 2000;
1096
+ Idle.emoteMessage(w.h, 'a', { id: 'dance' });
1097
+ assert.equal(w.h.emotes.get('a').id, 'dance', 'the player still emotes');
1098
+ assert.equal(asked, 1);
1099
+ Idle.emote(w.h, 'b', 'cheer');
1100
+ assert.equal(asked, 1, 'a second player cannot restart the NPC');
1101
+ w.sim.timeMs = 4000;
1102
+ Idle.emote(w.h, 'a', 'bow');
1103
+ assert.equal(asked, 1);
1104
+ w.sim.timeMs = 8000;
1105
+ Idle.emote(w.h, 'a', 'bow');
1106
+ assert.equal(asked, 2);
1107
+ assert.equal(Idle.fields(w.h).hubNpcEmotes.greeter.at, 8000);
1108
+ // A fresh body is still protected by the player's own reaction cooldown.
1109
+ const p = reacting({ extra: [{ id: 'second', x: 100, z: 0 }] });
1110
+ Idle.emote(p.h, 'a', 'wave');
1111
+ p.sim.bodies.get('second').p = { x: 0, y: 1, z: 2 };
1112
+ p.sim.timeMs = 3999;
1113
+ Idle.emote(p.h, 'a', 'wave');
1114
+ assert.equal(p.npcs.emoteFields().hubNpcEmotes.second, undefined);
1115
+ p.sim.timeMs = 4000;
1116
+ Idle.emote(p.h, 'a', 'wave');
1117
+ assert.equal(p.npcs.emoteFields().hubNpcEmotes.second.at, 4000);
1118
+ });
1119
+
1120
+ await test('v1.47: conversations, pending speech, follows, walks and place moves are left alone', () => {
1121
+ for (const busy of [
1122
+ (w) => w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' }),
1123
+ (w) => w.npcs.handle('greeter').follow('a'),
1124
+ (w) => w.npcs.handle('greeter').walkTo({ x: 5, z: 0 }),
1125
+ (w) => w.npcs.handle('greeter').say('Working.'),
1126
+ (w) => { w.h.moves = new Map([['greeter', {}]]); },
1127
+ (w) => { w.h.held = new Map([['greeter', {}]]); },
1128
+ (w) => { w.h.resetHolds = new Map([['greeter', {}]]); },
1129
+ ]) {
1130
+ const w = reacting();
1131
+ busy(w);
1132
+ Idle.emote(w.h, 'a', 'wave');
1133
+ assert.deepEqual(w.npcs.emoteFields(), {});
1134
+ }
1135
+ const w = reacting();
1136
+ w.npcs.handle('greeter').say('Just a moment.', { to: ['a'], ttlMs: 5000 });
1137
+ Idle.emote(w.h, 'a', 'wave');
1138
+ w.sim.timeMs = 5000;
1139
+ Idle.emote(w.h, 'a', 'wave');
1140
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave');
1141
+ });
1142
+
1143
+ await test('v1.47: props and hook overrides choose bounded public words and kit emotes; false skips a body', () => {
1144
+ const w = reacting({ extra: [{ id: 'second', x: 0, z: 1 }] });
1145
+ const asked = [];
1146
+ w.h.hooks.npcReact = (_hub, npc, playerId, info) => {
1147
+ asked.push({ npc: npc.id, playerId, ...info });
1148
+ return npc.id === 'second' ? false : { emote: 'dance', line: ` ${'x'.repeat(100)}\u0000` };
1149
+ };
1150
+ Idle.emote(w.h, 'a', 'wave');
1151
+ assert.deepEqual(asked.map((a) => a.npc), ['second', 'greeter']);
1152
+ assert.deepEqual(asked[1], { npc: 'greeter', playerId: 'a', emote: 'wave' });
1153
+ assert.deepEqual(Object.keys(w.npcs.emoteFields().hubNpcEmotes), ['greeter']);
1154
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'dance');
1155
+ assert.deepEqual(w.labels.at(-1), { id: 'greeter', text: `Rowan: ${'x'.repeat(80)}`, to: null, about: null });
1156
+ for (const override of [undefined, null, { line: null }]) {
1157
+ const p = reacting();
1158
+ p.h.hooks.npcReact = () => override;
1159
+ p.npcs.handle('greeter').props.reactions = { wave: { emote: 'bow', lines: ['Only my words.'] } };
1160
+ // Find a tick that speaks; other ticks keep just the emote.
1161
+ for (let ms = 0; ms < 3; ms++) {
1162
+ p.sim.timeMs = ms * 8000;
1163
+ Idle.emote(p.h, 'a', 'wave');
1164
+ assert.equal(p.npcs.emoteFields().hubNpcEmotes.greeter.id, 'bow');
1165
+ }
1166
+ if (override?.line === null) {
1167
+ assert.equal(p.labels.length, 0);
1168
+ } else {
1169
+ assert.ok(p.labels.some((l) => l.text === 'Rowan: Only my words.' && l.to === null));
1170
+ }
1171
+ }
1172
+ const quiet = reacting();
1173
+ quiet.npcs.handle('greeter').props.reactions = { wave: { emote: null, lines: [] } };
1174
+ quiet.h.hooks.npcReact = () => undefined;
1175
+ Idle.emote(quiet.h, 'a', 'wave');
1176
+ assert.deepEqual(quiet.npcs.emoteFields(), {});
1177
+ assert.equal(quiet.labels.length, 0);
1178
+ });
1179
+
1180
+ await test('v1.47: hook errors log once and fall back; absent players and NPC emotes cannot react', () => {
1181
+ const w = reacting();
1182
+ const warned = [];
1183
+ const warn = console.warn;
1184
+ console.warn = (...args) => warned.push(args.join(' '));
1185
+ try {
1186
+ w.h.hooks.npcReact = () => { throw new Error('private detail'); };
1187
+ Idle.emote(w.h, 'a', 'dance');
1188
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'dance');
1189
+ w.sim.timeMs = 8000;
1190
+ Idle.emote(w.h, 'a', 'dance');
1191
+ assert.equal(warned.length, 1);
1192
+ assert.ok(!warned[0].includes('private detail'));
1193
+ } finally {
1194
+ console.warn = warn;
1195
+ }
1196
+ const absent = reacting();
1197
+ absent.h.players.get('a').arrived = false;
1198
+ Idle.emote(absent.h, 'a', 'wave');
1199
+ absent.npcs.react('greeter', 'wave');
1200
+ Idle.emoteMessage(absent.h, 'gone', { id: 'wave' });
1201
+ assert.deepEqual(absent.npcs.emoteFields(), {});
1202
+ const empty = reacting();
1203
+ empty.h.actors = [];
1204
+ empty.h.npcs = makeNpcs(empty.h);
1205
+ empty.h.npcs.ready();
1206
+ Idle.emote(empty.h, 'a', 'wave');
1207
+ assert.deepEqual(Idle.fields(empty.h), { hubEmotes: { a: { id: 'wave', at: 0, until: Idle.EMOTES.wave } } });
1208
+ const refused = reacting();
1209
+ refused.h.hooks.npcReact = () => false;
1210
+ Idle.emote(refused.h, 'a', 'wave');
1211
+ assert.equal('hubNpcEmotes' in Idle.fields(refused.h), false);
1212
+ });
1213
+
1214
+ await test('v1.47: each default answers with a kit emote and sometimes its own public line', () => {
1215
+ const lines = {
1216
+ wave: ['Hello there!', 'Hi!', 'Hey, hi!'], dance: ['Nice moves!', 'Ooh, let me try!'],
1217
+ cheer: ['Woo!', 'Yay!'], bow: ['Likewise!', 'Oh, how polite!'], spin: ['Whee!', 'Dizzy yet?'],
1218
+ };
1219
+ for (const emote of Object.keys(lines)) {
1220
+ const w = reacting();
1221
+ delete w.h.hooks.npcReact;
1222
+ for (let tick = 0; tick < 6; tick++) {
1223
+ w.sim.timeMs = tick * 8000;
1224
+ Idle.emote(w.h, 'a', emote);
1225
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, emote === 'spin' ? 'cheer' : emote);
1226
+ }
1227
+ assert.ok(w.labels.length > 0 && w.labels.length < 6, 'speech is occasional');
1228
+ assert.ok(w.labels.every((l) => l.to === null && lines[emote].some((line) => l.text === `Rowan: ${line}`)));
1229
+ }
1230
+ const w = reacting();
1231
+ delete w.h.hooks.npcReact;
1232
+ w.npcs.handle('greeter').props.reactions = { wave: { lines: Array.from({ length: 10 }, (_, i) => `${i}: ${'x'.repeat(100)}\u0000`) } };
1233
+ for (let tick = 0; tick < 18; tick++) {
1234
+ w.sim.timeMs = tick * 8000;
1235
+ Idle.emote(w.h, 'a', 'wave');
1236
+ }
1237
+ assert.ok(w.labels.length > 0);
1238
+ assert.ok(w.labels.every((l) => /^Rowan: [0-5]: /.test(l.text) && l.text.length === 87));
1239
+ });
1240
+
1241
+ const inspectGreeting = (w, playerId, characters) => w.npcs.onRead({
1242
+ speaker: { playerId }, query: { type: 'inspect' },
1243
+ read: async () => ({ participantId: `p-${playerId}`, characters }), reject() {},
1244
+ });
1245
+
1246
+ function signIn(w, playerId, userId = `user-${playerId}`) {
1247
+ w.h.session.players ??= [];
1248
+ w.h.session.players = w.h.session.players.filter((p) => p.playerId !== playerId);
1249
+ w.h.session.players.push({ playerId, userId });
1250
+ }
1251
+
1252
+ await test('v1.47: a greeting is private to its speaker, character and opening notes; hooks keep their questions', async () => {
1253
+ const w = world({ notes: () => 'The pad is empty.', extra: [{ id: 'other', character: 'other', x: 1, z: 0 }] });
1254
+ signIn(w, 'a');
1255
+ w.at('a', 0, 2);
1256
+ w.at('b', 0, 2);
1257
+ await inspectGreeting(w, 'a', [{ characterId: 'greeter', privateState: { nextGreeting: { text: ' How is\u0000 your hamster?\n ', at: 10 } } }]);
1258
+ const asked = [];
1259
+ w.h.hooks.npcOpening = (_hub, npc, playerId, info) => {
1260
+ asked.push({ npc: npc.id, playerId, ...info });
1261
+ return { text: 'Place words.', asks: ['Where now?'], more: ['Then what?'] };
1262
+ };
1263
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1264
+ assert.deepEqual(w.sent.findLast((m) => m.open).opening, { text: 'How is your hamster?', asks: ['Where now?'], more: ['Then what?'] });
1265
+ assert.equal(asked.at(-1).greeting, 'How is your hamster?');
1266
+ assert.ok(w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix.includes('How is your hamster?'));
1267
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1268
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
1269
+ assert.equal(asked.at(-1).greeting, null);
1270
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Place words.');
1271
+ assert.ok(w.sent.filter((m) => JSON.stringify(m).includes('hamster')).every((m) => m.playerId === 'a'));
1272
+ assert.equal(w.labels.length, 0, 'the greeting is never a speech bubble');
1273
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'other' });
1274
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Place words.');
1275
+ w.npcs.leave('a');
1276
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-end', npc: 'greeter' });
1277
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1278
+ assert.equal(asked.at(-1).greeting, null, 'departure clears the cache');
1279
+ });
1280
+
1281
+ await test('v1.47: old or empty inspect clears greetings; a late inspect after leave cannot restore them', async () => {
1282
+ const w = world();
1283
+ signIn(w, 'a');
1284
+ w.at('a', 0, 2);
1285
+ const read = (text) => inspectGreeting(w, 'a', [{ characterId: 'greeter', privateState: { nextGreeting: { text } } }]);
1286
+ await read(` \u007f${'x'.repeat(300)}\u009f `);
1287
+ const open = () => w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1288
+ open();
1289
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'x'.repeat(240));
1290
+ assert.equal(w.sent.findLast((m) => m.open).opening.asks.length, 3);
1291
+ for (const characters of [undefined, [], [{ characterId: 'greeter', privateState: {} }]]) {
1292
+ await inspectGreeting(w, 'a', characters);
1293
+ open();
1294
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1295
+ }
1296
+ let finish;
1297
+ const pending = w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: () => new Promise((resolve) => { finish = resolve; }), reject() {} });
1298
+ w.npcs.leave('a');
1299
+ finish({ participantId: 'p-a', characters: [{ characterId: 'greeter', privateState: { nextGreeting: { text: 'Late private words.' } } }] });
1300
+ await pending;
1301
+ open();
1302
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1303
+ });
1304
+
1305
+ await test('v1.47: a hook error cannot log the greeting it was given', async () => {
1306
+ const w = world();
1307
+ signIn(w, 'a');
1308
+ w.at('a', 0, 2);
1309
+ await inspectGreeting(w, 'a', [{ characterId: 'greeter', privateState: { nextGreeting: { text: 'Private hamster.' } } }]);
1310
+ w.h.hooks.npcOpening = (_hub, _npc, _player, info) => { throw new Error(info.greeting); };
1311
+ const warn = console.warn;
1312
+ const logs = [];
1313
+ console.warn = (...args) => logs.push(args.join(' '));
1314
+ try {
1315
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1316
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Private hamster.');
1317
+ assert.deepEqual(logs, ['[hub] npcOpening failed']);
1318
+ assert.equal(w.labels.length, 0);
1319
+ } finally {
1320
+ console.warn = warn;
1321
+ }
1322
+ });
1323
+
1324
+ const greetingCharacters = (text = 'Private returning words.') => [{ characterId: 'greeter', privateState: { nextGreeting: { text } } }];
1325
+ const openGreeter = (w, playerId = 'a') => w.npcs.message({ playerId }, { k: 'hub-npc-open', npc: 'greeter' });
1326
+
1327
+ await test('review: greetings stay bound to the authenticated account and the exact body, never a guest', async () => {
1328
+ for (const change of [
1329
+ (w) => signIn(w, 'a', 'other-account'),
1330
+ (w) => w.at('a', 0, 2),
1331
+ (w) => signIn(w, 'a', null),
1332
+ ]) {
1333
+ const w = world();
1334
+ w.at('a', 0, 2);
1335
+ signIn(w, 'a');
1336
+ await inspectGreeting(w, 'a', greetingCharacters());
1337
+ change(w);
1338
+ const greetings = [];
1339
+ w.h.hooks.npcOpening = (_h, _n, _p, info) => { greetings.push(info.greeting); return null; };
1340
+ openGreeter(w);
1341
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1342
+ assert.deepEqual(greetings, [null]);
1343
+ signIn(w, 'a');
1344
+ openGreeter(w);
1345
+ assert.equal(greetings.at(-1), null, 'an invalid cache stays invalid');
1346
+ assert.ok(!JSON.stringify(w.sent).includes('Private returning words.'));
1347
+ }
1348
+ const guest = world();
1349
+ guest.at('a', 0, 2);
1350
+ await inspectGreeting(guest, 'a', greetingCharacters());
1351
+ signIn(guest, 'a');
1352
+ openGreeter(guest);
1353
+ assert.equal(guest.sent.findLast((m) => m.open).opening.text, "Hi, I'm Rowan! Ask me anything.");
1354
+ });
1355
+
1356
+ await test('review: an inspect cannot cache a greeting across an account change during the read', async () => {
1357
+ const w = world();
1358
+ w.at('a', 0, 2);
1359
+ signIn(w, 'a');
1360
+ let finish;
1361
+ const pending = w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: () => new Promise((resolve) => { finish = resolve; }), reject() {} });
1362
+ signIn(w, 'a', 'other-account');
1363
+ finish({ participantId: 'p-a', characters: greetingCharacters() });
1364
+ await pending;
1365
+ openGreeter(w);
1366
+ signIn(w, 'a');
1367
+ openGreeter(w);
1368
+ assert.ok(!JSON.stringify(w.sent).includes('Private returning words.'));
1369
+ });
1370
+
1371
+ await test('review: rejected hook promises and thenables are caught, ignored and logged once without their text', async () => {
1372
+ const logs = [];
1373
+ const unhandled = [];
1374
+ const onUnhandled = (err) => unhandled.push(err);
1375
+ const warn = console.warn;
1376
+ console.warn = (...args) => logs.push(args.join(' '));
1377
+ process.on('unhandledRejection', onUnhandled);
1378
+ try {
1379
+ const w = world();
1380
+ w.at('a', 0, 2);
1381
+ signIn(w, 'a');
1382
+ await inspectGreeting(w, 'a', greetingCharacters('Secret hamster.'));
1383
+ w.h.hooks.npcOpening = async (_h, _n, _p, info) => { throw new Error(info.greeting); };
1384
+ openGreeter(w);
1385
+ openGreeter(w);
1386
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Secret hamster.');
1387
+ assert.equal(w.sent.findLast((m) => m.open).opening.asks.length, 3);
1388
+ w.h.hooks.npcOpening = () => ({ text: 'Ignored words.', then(_resolve, reject) { reject(new Error('Secret thenable.')); } });
1389
+ openGreeter(w);
1390
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'Secret hamster.');
1391
+ const r = reacting();
1392
+ r.h.hooks.npcReact = async () => { throw new Error('Secret reaction.'); };
1393
+ Idle.emote(r.h, 'a', 'wave');
1394
+ r.sim.timeMs = 8000;
1395
+ Idle.emote(r.h, 'a', 'wave');
1396
+ assert.equal(r.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave');
1397
+ r.h.hooks.npcReact = () => ({ emote: 'dance', then(resolve) { resolve({ emote: 'dance' }); } });
1398
+ r.sim.timeMs = 16000;
1399
+ Idle.emote(r.h, 'a', 'wave');
1400
+ assert.equal(r.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave', 'fulfilled thenables are ignored too');
1401
+ await new Promise((resolve) => setImmediate(resolve));
1402
+ assert.deepEqual(unhandled, []);
1403
+ assert.deepEqual(logs.sort(), ['[hub] npcOpening async hook failed; using the default', '[hub] npcReact async hook failed; using the default']);
1404
+ } finally {
1405
+ console.warn = warn;
1406
+ process.off('unhandledRejection', onUnhandled);
1407
+ }
1408
+ });
1409
+
1410
+ await test('review: a late inspect replaces only an unsent opening and reissues its private notes', async () => {
1411
+ for (const spoke of [false, true, 'stale']) {
1412
+ const w = world({ notes: () => 'The pad is empty.' });
1413
+ w.at('a', 0, 2);
1414
+ w.at('b', 0, 2);
1415
+ signIn(w, 'a');
1416
+ w.h.hooks.npcOpening = () => ({ text: 'First words.', asks: ['Place question?'], more: ['Next?'] });
1417
+ let finish;
1418
+ const pending = w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: () => new Promise((resolve) => { finish = resolve; }), reject() {} });
1419
+ openGreeter(w);
1420
+ const opening = w.sent.findLast((m) => m.open).opening;
1421
+ assert.deepEqual(opening, { text: 'First words.', asks: ['Place question?'], more: ['Next?'] });
1422
+ const firstPrefix = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1423
+ if (spoke) {
1424
+ const sent = turn({ speaker: 'a', input: `${spoke === 'stale' ? '' : firstPrefix}Hello!` });
1425
+ await w.npcs.onTurn(sent);
1426
+ assert.equal(sent.rejected, spoke === 'stale' ? 'HUB_NPC_NOTES' : null);
1427
+ }
1428
+ finish({ participantId: 'p-a', characters: greetingCharacters('How is your hamster?') });
1429
+ await pending;
1430
+ const updates = w.sent.filter((m) => m.k === 'hub-npc-opening');
1431
+ assert.deepEqual(updates, spoke ? [] : [{ playerId: 'a', k: 'hub-npc-opening', npc: 'greeter', text: 'How is your hamster?' }]);
1432
+ const prefix = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1433
+ assert.equal(prefix.includes('How is your hamster?'), !spoke);
1434
+ assert.equal(prefix.includes('First words.'), Boolean(spoke));
1435
+ assert.equal(w.labels.length, 0);
1436
+ assert.deepEqual(opening.asks, ['Place question?']);
1437
+ assert.ok(w.sent.filter((m) => JSON.stringify(m).includes('hamster')).every((m) => m.playerId === 'a'));
1438
+ }
1439
+ const closed = world();
1440
+ closed.at('a', 0, 2);
1441
+ signIn(closed, 'a');
1442
+ openGreeter(closed);
1443
+ closed.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1444
+ await inspectGreeting(closed, 'a', greetingCharacters());
1445
+ assert.equal(closed.sent.some((m) => m.k === 'hub-npc-opening'), false);
1446
+ });
1447
+
1448
+ await test('review: a later short line cannot shorten another listener\'s active speech deadline', () => {
1449
+ const w = reacting();
1450
+ w.npcs.handle('greeter').say('Long public words.', { ttlMs: 12000 });
1451
+ w.sim.timeMs = 1000;
1452
+ w.npcs.handle('greeter').say('Short private words.', { to: ['a'], ttlMs: 1000 });
1453
+ w.sim.timeMs = 4000;
1454
+ Idle.emote(w.h, 'a', 'wave');
1455
+ assert.deepEqual(w.npcs.emoteFields(), {});
1456
+ w.sim.timeMs = 12000;
1457
+ Idle.emote(w.h, 'a', 'wave');
1458
+ assert.equal(w.npcs.emoteFields().hubNpcEmotes.greeter.id, 'wave');
1459
+ });
1460
+
1461
+ await test('review: a replacement speaker cannot force-send the old conversation\'s greeting notes', async () => {
1462
+ for (const change of [
1463
+ (w) => signIn(w, 'a', 'replacement-account'),
1464
+ (w) => w.at('a', 0, 2),
1465
+ (w) => signIn(w, 'a', null),
1466
+ ]) {
1467
+ for (const replay of [false, true]) {
1468
+ const w = world({ notes: () => 'The pad is empty.' });
1469
+ w.at('a', 0, 2);
1470
+ signIn(w, 'a');
1471
+ await inspectGreeting(w, 'a', greetingCharacters('Only the original account knows this.'));
1472
+ openGreeter(w);
1473
+ const prefix = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix;
1474
+ assert.ok(prefix.includes('Only the original account knows this.'));
1475
+ if (replay) {
1476
+ const original = turn({ speaker: 'a', input: `${prefix}Hello.` });
1477
+ await w.npcs.onTurn(original);
1478
+ assert.equal(original.sent, 1);
1479
+ }
1480
+ // Reuse the id before leave() runs: no new open, no valid old prefix.
1481
+ change(w);
1482
+ w.sent.length = 0;
1483
+ const replacement = turn({ speaker: 'a', operationId: replay ? 'op1' : 'replacement', input: 'Hello.' });
1484
+ await w.npcs.onTurn(replacement);
1485
+ assert.equal(replacement.rejected, 'HUB_NPC_NOT_TALKING');
1486
+ assert.equal(replacement.sent, 0);
1487
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
1488
+ assert.deepEqual(w.sent, [{ playerId: 'a', k: 'hub-npc', npc: 'greeter', open: false, why: 'left' }]);
1489
+ w.tick(1000);
1490
+ assert.equal(w.sent.some((m) => m.k === 'hub-npc-notes' || m.k === 'hub-npc-opening'), false);
1491
+ // Reopening creates fresh notes for the replacement, never the old copy.
1492
+ openGreeter(w);
1493
+ assert.ok(!JSON.stringify(w.sent).includes('Only the original account knows this.'));
1494
+ }
1495
+ }
1496
+ });
1497
+
1498
+ await test('review: periodic notes and late opening updates end conversations bound to a replaced speaker', async () => {
1499
+ for (const path of ['tick', 'inspect']) {
1500
+ for (const change of [(w) => signIn(w, 'a', 'replacement-account'), (w) => w.at('a', 0, 2)]) {
1501
+ const w = world({ notes: () => 'The pad is empty.' });
1502
+ w.at('a', 0, 2);
1503
+ signIn(w, 'a');
1504
+ await inspectGreeting(w, 'a', greetingCharacters('Original private greeting.'));
1505
+ openGreeter(w);
1506
+ change(w);
1507
+ w.sent.length = 0;
1508
+ if (path === 'tick') {
1509
+ w.tick(1000);
1510
+ } else {
1511
+ await inspectGreeting(w, 'a', greetingCharacters('Replacement private greeting.'));
1512
+ }
1513
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
1514
+ assert.deepEqual(w.sent, [
1515
+ { playerId: 'a', k: 'hub-npc', npc: 'greeter', open: false, why: 'left' },
1516
+ ...(path === 'inspect' ? [{ playerId: 'a', k: 'hub-npc-hooks', hooks: [{ npc: 'greeter', character: 'greeter' }] }] : []),
1517
+ ]);
1518
+ }
1519
+ }
1520
+ });
1521
+
1522
+ await test('review: speaker identity is checked again after opening and context hooks before any private send', async () => {
1523
+ for (const hook of ['npcOpening', 'npcContext']) {
1524
+ const w = world({ notes: () => 'Original private context.' });
1525
+ w.at('a', 0, 2);
1526
+ signIn(w, 'a');
1527
+ await inspectGreeting(w, 'a', greetingCharacters('Original private greeting.'));
1528
+ if (hook === 'npcContext') {
1529
+ openGreeter(w);
1530
+ }
1531
+ w.h.hooks[hook] = () => {
1532
+ signIn(w, 'a', 'replacement-account');
1533
+ return 'Original private words.';
1534
+ };
1535
+ w.sent.length = 0;
1536
+ if (hook === 'npcOpening') {
1537
+ openGreeter(w);
1538
+ } else {
1539
+ w.tick(1000);
1540
+ }
1541
+ assert.equal(w.npcs.handle('greeter').talkingTo, null);
1542
+ assert.deepEqual(w.sent, [{ playerId: 'a', k: 'hub-npc', npc: 'greeter', open: false, why: 'left' }]);
1543
+ }
1544
+ });
1545
+
1546
+ await test('v1.47: admitted words report the opening conversation only while its bound speaker still owns it', async () => {
1547
+ for (const change of ['same', 'close', 'reopen', 'handoff', 'account', 'body']) {
1548
+ const w = world();
1549
+ w.at('a', 0, 2);
1550
+ w.at('b', 0, 2);
1551
+ signIn(w, 'a');
1552
+ const openings = [];
1553
+ const heard = [];
1554
+ w.h.hooks.npcOpening = (_h, _n, playerId, info) => {
1555
+ openings.push({ playerId, conversation: info.conversation });
1556
+ return 'What would you like?';
1557
+ };
1558
+ w.h.hooks.npcHeard = (_h, _n, playerId, info) => heard.push({ playerId, ...info });
1559
+ openGreeter(w);
1560
+ const conversation = openings[0].conversation;
1561
+ assert.ok(Number.isInteger(conversation));
1562
+ assert.equal(conversation, 1);
1563
+ const admitted = turn({ speaker: 'a', input: 'My private answer.' });
1564
+ let finish;
1565
+ admitted.send = () => new Promise((resolve) => { finish = resolve; });
1566
+ const pending = w.npcs.onTurn(admitted);
1567
+ assert.equal(typeof finish, 'function', 'the turn reached its awaited send');
1568
+ assert.deepEqual(heard, [], 'the hook waits for send to settle');
1569
+ if (['close', 'reopen', 'handoff'].includes(change)) {
1570
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1571
+ if (change !== 'close') {
1572
+ openGreeter(w, change === 'handoff' ? 'b' : 'a');
1573
+ assert.equal(openings.at(-1).conversation, conversation + 1);
1574
+ }
1575
+ } else if (change === 'account') {
1576
+ // Keep the exact body, reusing only the player id for another account.
1577
+ signIn(w, 'a', 'replacement-account');
1578
+ } else if (change === 'body') {
1579
+ // Keep the account, replacing only the body before leave runs.
1580
+ w.at('a', 0, 2);
1581
+ }
1582
+ const logs = [];
1583
+ const warn = console.warn;
1584
+ console.warn = (...args) => logs.push(args.join(' '));
1585
+ try {
1586
+ finish({ status: 'queued' });
1587
+ await pending;
1588
+ } finally {
1589
+ console.warn = warn;
1590
+ }
1591
+ assert.deepEqual(heard, change === 'same' ? [{ playerId: 'a', text: 'My private answer.', conversation }] : [], change);
1592
+ assert.deepEqual(logs, [], 'dropping old words logs none of them');
1593
+ if (change === 'reopen' || change === 'handoff') {
1594
+ assert.equal(w.npcs.handle('greeter').talkingTo, change === 'handoff' ? 'b' : 'a', 'the old send leaves the new conversation intact');
1595
+ }
1596
+ }
1597
+ });
1598
+
1599
+ await test('v1.47: authored words match their opening; sequences increase independently per NPC', () => {
1600
+ const w = world({ mind: false, extra: [{ id: 'other', character: 'other', x: 1, z: 0 }] });
1601
+ w.at('a', 0, 2);
1602
+ signIn(w, 'a');
1603
+ const openings = [];
1604
+ w.h.hooks.npcOpening = (_h, npc, _p, info) => { openings.push({ npc: npc.id, conversation: info.conversation }); return 'Question?'; };
1605
+ for (const conversation of [1, 2]) {
1606
+ openGreeter(w);
1607
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Answer.' });
1608
+ assert.equal(w.lines.at(-1).conversation, conversation);
1609
+ assert.equal(w.lines.at(-1).conversation, openings.at(-1).conversation);
1610
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1611
+ w.tick(1000);
1612
+ }
1613
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'other' });
1614
+ assert.deepEqual(openings, [{ npc: 'greeter', conversation: 1 }, { npc: 'greeter', conversation: 2 }, { npc: 'other', conversation: 1 }]);
1615
+ openGreeter(w);
1616
+ signIn(w, 'a', 'replacement-account');
1617
+ const count = w.lines.length;
1618
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Replacement answer.' });
1619
+ assert.equal(w.lines.length, count, 'a reused player id cannot submit authored words in the old conversation');
1620
+ });
1621
+
1622
+
1623
+ await test('v1.66: without npcTools a turn is sent exactly as before, and nothing answers a lookup', async () => {
1624
+ const w = world();
1625
+ w.at('a', 0, 2);
1626
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1627
+ const t = turn({ speaker: 'a' });
1628
+ await w.npcs.onTurn(t);
1629
+ assert.deepEqual(t.sendArgs, [[]]);
1630
+ assert.deepEqual(await w.npcs.onTool({ operationId: 'op1', characterId: 'greeter', playerId: 'a', name: 'x', input: {} }), { error: 'not available' });
1631
+ });
1632
+
1633
+ await test('v1.66: npcTools rides with a new turn; npcTool answers one lookup for that turn only', async () => {
1634
+ const w = world();
1635
+ const calls = [];
1636
+ const good = { name: 'findGames', description: 'Find doors.', input_schema: { type: 'object', properties: { kind: { type: 'string' } } } };
1637
+ w.h.hooks.npcTools = () => [
1638
+ good,
1639
+ { ...good },
1640
+ { name: 'bad name', description: 'x', input_schema: {} },
1641
+ { name: 'perform_action', description: 'x', input_schema: {} },
1642
+ { name: 'long', description: 'x'.repeat(301), input_schema: {} },
1643
+ { name: 'bigSchema', description: 'x', input_schema: { d: 'x'.repeat(1100) } },
1644
+ { name: 'noSchema', description: 'x' },
1645
+ { name: 'today', description: 'Today.', input_schema: { type: 'object' } },
1646
+ ];
1647
+ w.h.hooks.npcTool = async (_hub, npc, playerId, name, input) => {
1648
+ calls.push({ npc: npc.id, playerId, name, input });
1649
+ return { games: [] };
1650
+ };
1651
+ w.at('a', 0, 2);
1652
+ w.at('b', 1, 1);
1653
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1654
+ const t = turn({ speaker: 'a' });
1655
+ await w.npcs.onTurn(t);
1656
+ assert.equal(t.rejected, null);
1657
+ assert.deepEqual(t.sendArgs[0][0].tools.map((x) => x.name), ['findGames', 'today']);
1658
+ const ask = { operationId: 'op1', characterId: 'greeter', playerId: 'a', name: 'findGames', input: { kind: 'farm' } };
1659
+ // Another player, another character, an undeclared tool, another turn: no hook runs.
1660
+ for (const wrong of [{ playerId: 'b' }, { characterId: 'innkeeper' }, { name: 'whereIs' }, { operationId: 'op9' }]) {
1661
+ assert.deepEqual(await w.npcs.onTool({ ...ask, ...wrong }), { error: 'not available' });
1662
+ }
1663
+ assert.equal(calls.length, 0);
1664
+ assert.deepEqual(await w.npcs.onTool(ask), { games: [] });
1665
+ assert.deepEqual(calls, [{ npc: 'greeter', playerId: 'a', name: 'findGames', input: { kind: 'farm' } }]);
1666
+ // Once per turn.
1667
+ assert.deepEqual(await w.npcs.onTool({ ...ask, name: 'today' }), { error: 'not available' });
1668
+ assert.equal(calls.length, 1);
1669
+ });
1670
+
1671
+ await test('v1.66: a throwing or empty npcTools sends the plain turn; a throwing npcTool answers an error', async () => {
1672
+ for (const npcTools of [() => { throw new Error('x'); }, () => [], () => 'nope', () => [{ name: 'a' }]]) {
1673
+ const w = world();
1674
+ w.h.hooks.npcTools = npcTools;
1675
+ w.at('a', 0, 2);
1676
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1677
+ const t = turn({ speaker: 'a' });
1678
+ await w.npcs.onTurn(t);
1679
+ assert.equal(t.rejected, null);
1680
+ assert.deepEqual(t.sendArgs, [[]]);
1681
+ }
1682
+ const w = world();
1683
+ w.h.hooks.npcTools = () => [{ name: 'today', description: 'Today.', input_schema: { type: 'object' } }];
1684
+ w.h.hooks.npcTool = () => { throw new Error('boom'); };
1685
+ w.at('a', 0, 2);
1686
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1687
+ await w.npcs.onTurn(turn({ speaker: 'a' }));
1688
+ assert.deepEqual(await w.npcs.onTool({ operationId: 'op1', characterId: 'greeter', playerId: 'a', name: 'today', input: {} }), { error: 'tool failed' });
1689
+ });
1690
+
1691
+ await test('v1.66: an async or rejecting npcTools, or a schema that serializes to nothing, still sends the turn', async () => {
1692
+ let unhandled = 0;
1693
+ const onUnhandled = () => { unhandled += 1; };
1694
+ process.on('unhandledRejection', onUnhandled);
1695
+ const good = { name: 'today', description: 'Today.', input_schema: { type: 'object' } };
1696
+ for (const npcTools of [
1697
+ async () => { throw new Error('x'); },
1698
+ async () => [good],
1699
+ () => [{ name: 'odd', description: 'x', input_schema: { toJSON() { return undefined; } } }, good],
1700
+ () => [{ name: 'odd', description: 'x', input_schema: { toJSON() { return 'text'; } } }],
1701
+ ]) {
1702
+ const w = world();
1703
+ w.h.hooks.npcTools = npcTools;
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.equal(t.rejected, null);
1709
+ assert.equal(t.sent, 1);
1710
+ const names = t.sendArgs[0][0]?.tools?.map((x) => x.name) ?? [];
1711
+ assert.ok(names.every((n) => n === 'today'), JSON.stringify(names));
1712
+ }
1713
+ await new Promise((r) => setTimeout(r, 20));
1714
+ process.off('unhandledRejection', onUnhandled);
1715
+ assert.equal(unhandled, 0);
1716
+ });
1717
+
1718
+ const greetingRead = (playerId = 'a', result = { characterId: 'greeter', greeting: { text: 'How did your test go?', at: 10 } }, character = 'greeter') => ({
1719
+ speaker: { playerId }, query: { type: 'status', operationId: `greeting:${character}` },
1720
+ read: async () => result, reject(code) { assert.fail(code); },
1721
+ });
1722
+
1723
+ await test('v1.76: inspect privately offers physical mind ids only, never guests or companions', async () => {
1724
+ const w = world({ extra: [
1725
+ { id: 'other', character: 'greeter', x: 1, z: 0 },
1726
+ { id: 'empty', character: null, x: 1, z: 0 },
1727
+ { id: 'quiet', character: 'quiet', x: 1, z: 0 },
1728
+ ] });
1729
+ w.at('a', 0, 2);
1730
+ w.at('b', 0, 2);
1731
+ signIn(w, 'a');
1732
+ w.h.place.companionChat = { character: 'pet', name: 'Chirp' };
1733
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'companion:a' });
1734
+ const characters = [...greetingCharacters(), { characterId: 'pet', privateState: { nextGreeting: { text: 'Owner words.' } } }];
1735
+ await inspectGreeting(w, 'a', characters);
1736
+ assert.deepEqual(w.sent.filter((m) => m.k === 'hub-npc-hooks'), [{
1737
+ playerId: 'a', k: 'hub-npc-hooks', hooks: [{ npc: 'greeter', character: 'greeter' }, { npc: 'other', character: 'greeter' }],
1738
+ }]);
1739
+ const count = w.sent.length;
1740
+ await inspectGreeting(w, 'b', characters);
1741
+ await inspectGreeting(w, 'a', []);
1742
+ assert.equal(w.sent.length, count, 'guests and empty lists send nothing');
1743
+ const plain = world({ mind: false });
1744
+ plain.at('a', 0, 2); signIn(plain, 'a');
1745
+ await inspectGreeting(plain, 'a', characters);
1746
+ assert.deepEqual(plain.sent, [], 'no mind means no new wire bytes');
1747
+ });
1748
+
1749
+ await test('v1.76: a walk-up greeting uses only the nearest private label and stays cached for chat', async () => {
1750
+ const w = world({ notes: () => 'The pad.', extra: [{ id: 'other', character: 'greeter', name: 'Other', x: 0, z: 1 }] });
1751
+ w.at('a', 0, 2); w.at('b', 0, 2); signIn(w, 'a');
1752
+ await inspectGreeting(w, 'a', greetingCharacters('How did your test go?'));
1753
+ w.h.labels = new Map(); w.h.labelsMe = new Map();
1754
+ w.h.npcLabel = (id, text, options) => {
1755
+ w.labels.push({ id, text, ...options });
1756
+ setLabel(w.h, id, text, options, true);
1757
+ };
1758
+ await w.npcs.onRead(greetingRead('a', { characterId: 'greeter', greeting: { text: ' How did\u0000 your test go?\n ', at: 10 } }));
1759
+ assert.deepEqual(w.labels, [{ id: 'other', text: 'Other: How did your test go?', style: 'speech', ttlMs: 7000, to: ['a'], about: 'a' }]);
1760
+ assert.deepEqual([...w.h.labels], [], 'public snapshots have no greeting');
1761
+ assert.equal(w.h.labelsMe.has('b'), false, 'the nearby player has no greeting label');
1762
+ assert.deepEqual(wireLabel(w.h.labelsMe.get('a').get('other')), { text: 'Other: How did your test go?', style: 'speech', npc: true });
1763
+ assert.equal(w.lines.length, 0, 'no place line hook');
1764
+ openGreeter(w);
1765
+ assert.equal(w.sent.findLast((m) => m.open).opening.text, 'How did your test go?');
1766
+ assert.ok(w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix.includes('How did your test go?'));
1767
+ await w.npcs.onRead(greetingRead('a', { characterId: 'greeter', greeting: null }));
1768
+ assert.equal(w.labels.length, 1, 'a consumed hook says nothing');
1769
+ });
1770
+
1771
+ await test('v1.76: null, malformed, far, busy and mindless greeting results say nothing', async () => {
1772
+ for (const [result, character, change] of [
1773
+ [null],
1774
+ [{ characterId: 'greeter', greeting: null }],
1775
+ [{ characterId: 'other', greeting: { text: 'Private.' } }],
1776
+ [{ characterId: 'greeter', greeting: { text: ' \u0000\n ' } }],
1777
+ [{ characterId: 'greeter', greeting: { text: 10 } }],
1778
+ [undefined, ''],
1779
+ [undefined, 'greeter', (w) => { w.sim.players.get('a').at.z = 5.51; }],
1780
+ [undefined, 'greeter', (w) => { w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' }); }],
1781
+ [undefined, 'greeter', (w) => { w.h.place.npcs = null; }],
1782
+ [undefined, 'greeter', (w) => { w.h.session.world.characters = null; }],
1783
+ [undefined, 'greeter', (w) => { w.sim.bodies.delete('greeter'); }],
1784
+ ]) {
1785
+ const w = world(); w.at('a', 0, 2); w.at('b', 0, 2); signIn(w, 'a');
1786
+ change?.(w);
1787
+ w.labels.length = 0;
1788
+ await w.npcs.onRead(greetingRead('a', result, character));
1789
+ assert.deepEqual(w.labels, []);
1790
+ }
1791
+ const guest = world(); guest.at('a', 0, 2);
1792
+ await guest.npcs.onRead(greetingRead());
1793
+ assert.deepEqual(guest.labels, []);
1794
+ const pet = world(); pet.at('a', 0, 2); signIn(pet, 'a');
1795
+ pet.h.place.companionChat = { character: 'pet', name: 'Chirp' };
1796
+ pet.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'companion:a' });
1797
+ assert.equal(pet.npcs.handle('companion:a').owner, 'a');
1798
+ await pet.npcs.onRead(greetingRead('a', { characterId: 'pet', greeting: { text: 'Owner only.' } }, 'pet'));
1799
+ assert.deepEqual(pet.labels, [], 'owner/virtual records never draw a bubble');
1800
+ });
1801
+
1802
+ await test('v1.76: greeting reads recheck departure, exact body and account after the await', async () => {
1803
+ for (const change of [
1804
+ (w) => { w.npcs.leave('a'); w.sim.players.delete('a'); },
1805
+ (w) => { w.at('a', 0, 2); },
1806
+ (w) => { signIn(w, 'a', 'other-account'); },
1807
+ (w) => { w.h.session.players = []; },
1808
+ (w) => { w.sim.players.get('a').at.z = 100; },
1809
+ (w) => { w.sim.bodies.delete('greeter'); },
1810
+ ]) {
1811
+ const w = world(); w.at('a', 0, 2); signIn(w, 'a');
1812
+ let finish;
1813
+ const request = greetingRead();
1814
+ request.read = () => new Promise((resolve) => { finish = resolve; });
1815
+ const pending = w.npcs.onRead(request);
1816
+ change(w);
1817
+ finish({ characterId: 'greeter', greeting: { text: 'Private.' } });
1818
+ await pending;
1819
+ assert.deepEqual(w.labels, []);
1820
+ }
1821
+ });
1822
+
1823
+ await test('v1.76: reserved greeting ids never deliver turns; real turn status still works', async () => {
1824
+ const w = world(); w.at('a', 0, 2); signIn(w, 'a'); openGreeter(w);
1825
+ for (const operationId of ['greeting:greeter', 'greeting:', 'greeting:other']) {
1826
+ const reserved = turn({ speaker: 'a', operationId });
1827
+ await w.npcs.onTurn(reserved);
1828
+ assert.equal(reserved.rejected, 'HUB_NPC_OPERATION_RESERVED');
1829
+ assert.equal(reserved.sent, 0);
1830
+ await w.npcs.onRead(statusRead('a', operationId, 'A turn must never be drawn.'));
1831
+ assert.deepEqual(w.labels, []);
1832
+ }
1833
+ const real = turn({ speaker: 'a', operationId: 'af4dd2b6-40ee-4d43-99e9-9479d8e21856' });
1834
+ await w.npcs.onTurn(real);
1835
+ assert.equal(real.sent, 1);
1836
+ await w.npcs.onRead(statusRead('a', real.operationId, 'Real reply.'));
1837
+ assert.deepEqual(w.labels, [{ id: 'greeter', text: 'Rowan: Real reply.', to: ['a'], about: 'a' }]);
1838
+ const disallowed = { ...greetingRead(), query: { type: 'greeting', characterId: 'greeter' }, rejected: null, reject(code) { this.rejected = code; } };
1839
+ await w.npcs.onRead(disallowed);
1840
+ assert.equal(disallowed.rejected, 'HUB_NPC_READ_NOT_ALLOWED', 'the live host still uses status');
1841
+ });
1842
+
1843
+ await test('v1.83: three simultaneous sends, speaker-only replies, notes and panels; slots free independently', async () => {
1844
+ const w = world({ turnsAtOnce: 3, notes: (_npc, playerId) => `Private notes for ${playerId}` });
1845
+ const labelState = { sim: w.sim, labels: new Map(), labelsMe: new Map() };
1846
+ const capture = w.h.npcLabel;
1847
+ w.h.npcLabel = (id, text, options) => { capture(id, text, options); setLabel(labelState, id, text, options, true); };
1848
+ w.h.hooks.npcOpening = (_hub, _npc, playerId) => ({ text: `Private opening for ${playerId}`, asks: [`Ask ${playerId}?`] });
1849
+ w.h.hooks.npcAsks = (_hub, _npc, playerId) => ({ persistentAsks: [`Private chip ${playerId}?`] });
1850
+ const open = (id) => w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' });
1851
+ const end = (id) => w.npcs.message({ playerId: id }, { k: 'hub-npc-end', npc: 'greeter' });
1852
+ for (const id of ['a', 'b', 'c', 'd']) w.at(id, 0, 2);
1853
+ for (const id of ['a', 'b', 'c']) open(id);
1854
+ const handle = w.npcs.handle('greeter');
1855
+ assert.deepEqual(handle.talkingWith, ['a', 'b', 'c']);
1856
+ assert.equal(handle.talkingTo, 'a');
1857
+ assert.equal(handle.busy, true);
1858
+ const starts = [], releases = [], tasks = [];
1859
+ for (const id of ['a', 'b', 'c']) {
1860
+ const prefix = w.sent.findLast((m) => m.playerId === id && m.k === 'hub-npc-notes').prefix;
1861
+ const request = turn({ speaker: id, operationId: `op-${id}`, input: `${prefix}Private words ${id}` });
1862
+ request.send = () => { starts.push(id); return new Promise((resolve) => releases.push(resolve)); };
1863
+ tasks.push(w.npcs.onTurn(request));
1864
+ }
1865
+ assert.deepEqual(starts, ['a', 'b', 'c'], 'all three sends run before any finishes');
1866
+ const duplicate = turn({ speaker: 'b', operationId: 'duplicate-b', input: w.sent.findLast((m) => m.playerId === 'b' && m.k === 'hub-npc-notes').prefix + 'Again' });
1867
+ await w.npcs.onTurn(duplicate);
1868
+ assert.equal(duplicate.rejected, 'HUB_NPC_BUSY', 'the same speaker cannot send a second pending turn');
1869
+ open('d');
1870
+ assert.equal(w.sent.findLast((m) => m.playerId === 'd' && m.k === 'hub-npc').why, 'busy');
1871
+ const fourth = turn({ speaker: 'd', operationId: 'fourth' });
1872
+ await w.npcs.onTurn(fourth);
1873
+ assert.equal(fourth.rejected, 'HUB_NPC_BUSY');
1874
+ assert.equal(w.lines.at(-1).why, 'busy');
1875
+ end('a');
1876
+ assert.deepEqual(handle.talkingWith, ['b', 'c']);
1877
+ assert.equal(handle.talkingTo, 'b');
1878
+ assert.equal(handle.busy, false);
1879
+ open('d');
1880
+ assert.deepEqual(handle.talkingWith, ['b', 'c', 'd']);
1881
+ w.npcs.leave('b');
1882
+ assert.deepEqual(handle.talkingWith, ['c', 'd']);
1883
+ open('a');
1884
+ assert.deepEqual(handle.talkingWith, ['c', 'd', 'a']);
1885
+ releases.forEach((resolve) => resolve());
1886
+ await Promise.all(tasks);
1887
+ for (const id of ['a', 'b', 'c']) {
1888
+ await w.npcs.onRead(statusRead(id, `op-${id}`, `Private reply ${id}`));
1889
+ }
1890
+ w.tick(1000);
1891
+ for (const id of ['a', 'b', 'c', 'd']) {
1892
+ const privateMessages = w.sent.filter((m) => m.playerId === id);
1893
+ const visibleLabels = w.labels.filter((label) => !label.to || label.to.includes(id));
1894
+ const visible = JSON.stringify([...privateMessages, ...visibleLabels]);
1895
+ for (const other of ['a', 'b', 'c', 'd'].filter((other) => other !== id)) {
1896
+ for (const kind of ['notes for', 'opening for', 'chip', 'reply', 'words']) {
1897
+ assert.ok(!visible.includes(`Private ${kind} ${other}`), `${id} must never receive ${other}'s ${kind}`);
1898
+ }
1899
+ }
1900
+ }
1901
+ assert.deepEqual(w.labels.filter((label) => label.text.includes('Private reply')).map((label) => label.to), [['a'], ['b'], ['c']]);
1902
+ assert.ok([...labelState.labels.values()].every((label) => !label.text.includes('Private')));
1903
+ for (const id of ['a', 'b', 'c']) {
1904
+ assert.equal(wireLabel(labelState.labelsMe.get(id).get('greeter')).text, `Rowan: Private reply ${id}`);
1905
+ }
1906
+ assert.equal(w.sent.filter((m) => m.playerId === 'c' && m.open === false).length, 0, 'another player ending/leaving never closes my panel');
1907
+ assert.ok(w.heard.every((entry) => entry.playerId === 'c'), 'only the unchanged conversation gets the admitted words');
1908
+ handle.end();
1909
+ assert.deepEqual(handle.talkingWith, []);
1910
+ assert.equal(handle.talkingTo, null);
1911
+ });
1912
+
1913
+ await test('v1.83: notes cannot cross speakers and the budget is shared across slots', async () => {
1914
+ const w = world({ turnsAtOnce: 3, turnsPerMinute: 2, notes: (_npc, id) => `Notes ${id}` });
1915
+ const prefix = (id) => w.sent.findLast((m) => m.playerId === id && m.k === 'hub-npc-notes').prefix;
1916
+ for (const id of ['a', 'b', 'c']) { w.at(id, 0, 2); w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' }); }
1917
+ const wrong = turn({ speaker: 'b', operationId: 'wrong', input: prefix('a') + 'hello' });
1918
+ await w.npcs.onTurn(wrong);
1919
+ assert.equal(wrong.rejected, 'HUB_NPC_NOTES');
1920
+ for (const id of ['a', 'b']) {
1921
+ const request = turn({ speaker: id, operationId: id, input: prefix(id) + 'hello' });
1922
+ await w.npcs.onTurn(request);
1923
+ assert.equal(request.sent, 1);
1924
+ }
1925
+ const over = turn({ speaker: 'c', input: prefix('c') + 'hello' });
1926
+ await w.npcs.onTurn(over);
1927
+ assert.equal(over.rejected, 'HUB_NPC_BUDGET');
1928
+ assert.equal(w.lines.at(-1).why, 'budget');
1929
+ assert.equal(over.sent, 0);
1930
+ });
1931
+
1932
+ await test('v1.83: multi-slot walks and follows continue, one-slot override holds them; override beats place', async () => {
1933
+ for (const [slots, override, capacity] of [[3, undefined, 3], [3, 1, 1], [1, 3, 3], [3, 2, 2], [undefined, 3, 3]]) {
1934
+ for (const movement of ['walk', 'follow']) {
1935
+ const w = world({ turnsAtOnce: slots, bodyTurnsAtOnce: override });
1936
+ w.at('a', 0, 2); w.at('leader', 6, 0);
1937
+ const handle = w.npcs.handle('greeter');
1938
+ if (movement === 'walk') handle.walkTo({ x: 10, z: 0 }); else handle.follow('leader');
1939
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1940
+ w.tick(100);
1941
+ assert.equal(w.greeter().p.x > 0, capacity > 1, `${slots}/${override}: ${movement}`);
1942
+ for (let i = 1; i <= capacity; i++) {
1943
+ w.at(`other-${i}`, 0, 2);
1944
+ w.npcs.message({ playerId: `other-${i}` }, { k: 'hub-npc-open', npc: 'greeter' });
1945
+ assert.equal(w.sent.findLast((m) => m.playerId === `other-${i}` && m.k === 'hub-npc').open, i < capacity);
1946
+ }
1947
+ assert.equal(handle.talkingWith.length, capacity);
1948
+ }
1949
+ }
1950
+ });
1951
+
1952
+ await test('v1.83: absent and explicit one slot have byte-identical protocol and timing', async () => {
1953
+ const traces = [];
1954
+ for (const config of [{}, { turnsAtOnce: 1 }, { bodyTurnsAtOnce: 1 }, { turnsAtOnce: 1, bodyTurnsAtOnce: 1 }]) {
1955
+ const w = world({ ...config, notes: () => 'Same notes' });
1956
+ const handle = w.npcs.handle('greeter');
1957
+ w.at('a', 0, 2); w.at('b', 2, 0);
1958
+ handle.walkTo({ x: 10, z: 0 });
1959
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
1960
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-open', npc: 'greeter' });
1961
+ const input = w.sent.findLast((m) => m.k === 'hub-npc-notes').prefix + 'hello';
1962
+ await w.npcs.onTurn(turn({ speaker: 'a', input }));
1963
+ w.tick(1000);
1964
+ await w.npcs.onRead(statusRead('a', 'op1', 'Same reply'));
1965
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1966
+ w.tick(1000);
1967
+ 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 }));
1968
+ }
1969
+ assert.ok(traces.every((trace) => trace === traces[0]));
1970
+ });
1971
+
1972
+ await test('v1.83: per-speaker timeouts and authored replies stay private', async () => {
1973
+ const w = world({ turnsAtOnce: 3 });
1974
+ w.h.session = { world: null };
1975
+ w.h.hooks.npcLine = (_hub, _npc, _id, info) => info.text ?? `line:${info.why}`;
1976
+ for (const id of ['a', 'b', 'c']) { w.at(id, 0, 2); w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' }); }
1977
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Only A typed this' });
1978
+ assert.deepEqual(w.labels.findLast((label) => label.text.includes('Only A')).to, ['a']);
1979
+ w.tick(80_000);
1980
+ w.npcs.message({ playerId: 'b' }, { k: 'hub-npc-say', npc: 'greeter', text: 'Only B typed this' });
1981
+ w.sim.players.delete('c');
1982
+ w.tick(11_000);
1983
+ assert.deepEqual(w.npcs.handle('greeter').talkingWith, ['b']);
1984
+ assert.equal(w.sent.findLast((m) => m.playerId === 'a' && m.open === false).why, 'idle');
1985
+ assert.equal(w.sent.findLast((m) => m.playerId === 'c' && m.open === false).why, 'left');
1986
+ });
1987
+
1988
+ await test('v1.83: reopened speakers retain their in-flight turn, and send failure clears only their pending state', async () => {
1989
+ const w = world({ turnsAtOnce: 3 });
1990
+ const open = (id) => w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: 'greeter' });
1991
+ for (const id of ['a', 'b']) { w.at(id, 0, 2); open(id); }
1992
+ let fail;
1993
+ const first = turn({ speaker: 'a', operationId: 'a-first' });
1994
+ first.send = () => new Promise((_resolve, reject) => { fail = reject; });
1995
+ const sending = w.npcs.onTurn(first);
1996
+ const observed = assert.rejects(sending, (err) => err.code === 'CAULDRON_SHARED_CHARACTER_BUSY');
1997
+ await w.npcs.onTurn(turn({ speaker: 'b', operationId: 'b-first' }));
1998
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
1999
+ open('a');
2000
+ const blocked = turn({ speaker: 'a', operationId: 'a-blocked' });
2001
+ await w.npcs.onTurn(blocked);
2002
+ assert.equal(blocked.rejected, 'HUB_NPC_BUSY');
2003
+ fail(Object.assign(new Error('capacity'), { code: 'CAULDRON_SHARED_CHARACTER_BUSY' }));
2004
+ await observed;
2005
+ assert.equal(w.lines.at(-1).why, 'busy', 'ghost mapping stays unchanged');
2006
+ const retry = turn({ speaker: 'a', operationId: 'a-retry' });
2007
+ await w.npcs.onTurn(retry);
2008
+ assert.equal(retry.sent, 1);
2009
+ const stillBlocked = turn({ speaker: 'b', operationId: 'b-blocked' });
2010
+ await w.npcs.onTurn(stillBlocked);
2011
+ assert.equal(stillBlocked.rejected, 'HUB_NPC_BUSY', "A's failure does not release B's turn");
2012
+ assert.deepEqual(w.npcs.handle('greeter').talkingWith, ['b', 'a']);
2013
+ });
2014
+
2015
+ await test('v1.83: handle exposes effective capacity without changing the protocol', () => {
2016
+ for (const [place, override, expected] of [[undefined, undefined, 1], [1, undefined, 1], [3, undefined, 3], [3, 1, 1], [1, 3, 3], [undefined, 2, 2]]) {
2017
+ const w = world({ turnsAtOnce: place, bodyTurnsAtOnce: override });
2018
+ const handle = w.npcs.handle('greeter');
2019
+ assert.equal(handle.turnsAtOnce, expected);
2020
+ assert.equal(w.npcs.list()[0].turnsAtOnce, expected);
2021
+ w.at('a', 0, 2);
2022
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2023
+ assert.ok(w.sent.every((msg) => !Object.hasOwn(msg, 'turnsAtOnce')));
2024
+ }
2025
+ });
2026
+
2027
+ // The actual panel and NPC server, with the socket's WORLD re-admission
2028
+ // signal and a controlled clock. No private question uses net.send.
2029
+ async function talkRig(options, run) {
2030
+ const realSetTimeout = globalThis.setTimeout;
2031
+ const realClearTimeout = globalThis.clearTimeout;
2032
+ const timers = new Map();
2033
+ let now = 0, timerId = 0;
2034
+ globalThis.setTimeout = (fn, ms) => { timers.set(++timerId, { fn, at: now + ms }); return timerId; };
2035
+ globalThis.clearTimeout = (id) => timers.delete(id);
2036
+ const settle = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); };
2037
+ const advance = async (ms) => {
2038
+ now += ms;
2039
+ for (const [id, timer] of [...timers]) {
2040
+ if (timer.at <= now && timers.delete(id)) timer.fn();
2041
+ }
2042
+ await settle();
2043
+ };
2044
+ clearClientHub();
2045
+ const w = world({ turnsAtOnce: options.slots, notes: options.noNotes ? null : () => 'fresh place notes' });
2046
+ w.at('p1', 0, 2);
2047
+ const npc = options.companion ? 'companion:p1' : 'greeter';
2048
+ const character = options.companion ? 'companion' : 'greeter';
2049
+ if (options.companion) {
2050
+ w.h.place.companionChat = { name: 'Chirp', character };
2051
+ w.h.session.players = [{ playerId: 'p1', userId: 'owner' }];
2052
+ clientHub.place = { companionChat: { name: 'Chirp' } };
2053
+ clientHub.companion = { c: { look: 'bird' } };
2054
+ }
2055
+ let handlers, cursor = 0, queue = [], closed = 0, opened = 0, draft = '', forceNotTalking = false;
2056
+ let held = [], recoveryRefusal = null, releaseRefusal;
2057
+ let turnRefusals = [];
2058
+ const lines = [], wire = [], requests = [], admitted = [];
2059
+ const chrome = {
2060
+ onTalk(value) { handlers = value; },
2061
+ openTalk() { opened++; lines.length = 0; draft = ''; },
2062
+ closeTalk() { closed++; }, talkPrompt() {}, talkAsks() {}, talkWaiting() {}, talkTyping() {},
2063
+ talkFocused: () => false, talkLine: (who, text) => lines.push([who, text]),
2064
+ talkDraft(text) { if (text !== undefined) draft = text; return draft; },
2065
+ };
2066
+ const net = {
2067
+ selfId: () => 'p1', drain: () => { const messages = queue; queue = []; return messages; },
2068
+ send(msg) { wire.push(msg); w.npcs.message({ playerId: 'p1' }, msg); },
2069
+ characters: {
2070
+ async requestCharacterTurn(request) {
2071
+ requests.push(request);
2072
+ if (forceNotTalking) throw { code: 'HUB_NPC_NOT_TALKING' };
2073
+ if (turnRefusals.length) throw { code: turnRefusals.shift() };
2074
+ const event = turn({ speaker: 'p1', ...request, audience: request.audience.playerIds, disclosure: request.audience.disclosure });
2075
+ if (recoveryRefusal && wire.filter((msg) => msg.k === 'hub-npc-open').length > 1) {
2076
+ event.send = async () => { throw { code: recoveryRefusal }; };
2077
+ }
2078
+ try {
2079
+ await w.npcs.onTurn(event);
2080
+ } catch (err) {
2081
+ if (recoveryRefusal) await new Promise((resolve) => { releaseRefusal = resolve; });
2082
+ throw err;
2083
+ }
2084
+ if (event.rejected) throw { code: event.rejected };
2085
+ assert.equal(event.sent, 1);
2086
+ admitted.push(event);
2087
+ },
2088
+ async readCharacters({ query }) {
2089
+ if (query.type === 'inspect') return {};
2090
+ const event = statusRead('p1', query.operationId, 'private mind reply');
2091
+ await w.npcs.onRead(event);
2092
+ return { status: 'completed', response: 'private mind reply' };
2093
+ },
2094
+ },
2095
+ };
2096
+ const mp = { net, joined: true };
2097
+ const scene = { multiplayer: mp, actorWith: () => ({ components: { Transform: { x: 0, z: 2 } } }), getActors: () => [] };
2098
+ const talk = makeTalk(chrome);
2099
+ const frame = (accept = () => true) => {
2100
+ const incoming = [...held, ...w.sent.slice(cursor).filter((msg) => msg.playerId === 'p1')];
2101
+ held = incoming.filter((msg) => !accept(msg));
2102
+ clientHub.npcEvents.push(...incoming.filter(accept));
2103
+ cursor = w.sent.length;
2104
+ talk.frame(scene, mp, false);
2105
+ };
2106
+ try {
2107
+ frame();
2108
+ net.send({ k: 'hub-npc-open', npc }); frame(); await settle();
2109
+ const mark = Rehello.mark(mp, net);
2110
+ const drop = () => {
2111
+ w.sim.players.delete('p1'); w.tick(30_000); w.npcs.leave('p1');
2112
+ // The closing packet was sent to the dead socket.
2113
+ cursor = w.sent.length;
2114
+ };
2115
+ const reconnect = () => {
2116
+ w.at('p1', 0, 2); queue.push({ k: 'w' }); net.drain();
2117
+ assert.equal(Rehello.resumed(mp, net, mark), 'world');
2118
+ talk.resume();
2119
+ };
2120
+ await run({ w, npc, talk, handlers, frame, settle, advance, drop, reconnect, net, lines, wire, requests, admitted,
2121
+ opened: () => opened, closed: () => closed, draft: () => draft, setDraft: (text) => { draft = text; }, forceNotTalking: () => { forceNotTalking = true; },
2122
+ skipMessages: () => { held = []; cursor = w.sent.length; },
2123
+ refuseTurns: (...codes) => { turnRefusals = codes; },
2124
+ deferRecoveryRefusal: (code) => { recoveryRefusal = code; }, releaseRefusal: () => releaseRefusal() });
2125
+ } finally {
2126
+ talk.reset(); clearClientHub();
2127
+ globalThis.setTimeout = realSetTimeout;
2128
+ globalThis.clearTimeout = realClearTimeout;
2129
+ }
2130
+ }
2131
+
2132
+ for (const options of [{ slots: 1 }, { slots: 3 }, { companion: true }]) {
2133
+ await test(`same-id WORLD re-attach sends first question once (${JSON.stringify(options)})`, () => talkRig(options, async (r) => {
2134
+ r.drop(); r.reconnect();
2135
+ r.handlers.send('private first question'); r.handlers.send('duplicate tap');
2136
+ assert.equal(r.requests.length, 0, 'question waits for the open and fresh notes');
2137
+ r.frame(); await r.settle();
2138
+ assert.equal(r.opened(), 1, 'reattach does not clear or rebuild the transcript');
2139
+ assert.equal(r.admitted.length, 1);
2140
+ assert.equal(r.requests.length, 1);
2141
+ assert(r.requests[0].input.endsWith('private first question'));
2142
+ assert(r.requests[0].input.startsWith(NOTES_HEAD));
2143
+ assert.deepEqual(r.requests[0].audience, { disclosure: 'participants', playerIds: [], characterIds: [] });
2144
+ assert.equal(r.lines.filter(([who]) => who === 'me').length, 1);
2145
+ assert(r.lines.some(([who]) => who === 'them'), 'opening remains visible');
2146
+ await r.advance(1200); r.frame();
2147
+ assert.equal(r.requests.length, 1);
2148
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, 2);
2149
+ assert(r.w.labels.every((label) => !JSON.stringify(label).includes('private first question')));
2150
+ assert(r.w.sent.every((msg) => !JSON.stringify(msg).includes('private first question')));
2151
+ }));
2152
+ }
2153
+
2154
+ await test('NOT_TALKING fallback re-attaches and retries exactly once', () => talkRig({ slots: 1 }, async (r) => {
2155
+ r.drop(); r.w.at('p1', 0, 2);
2156
+ r.handlers.send('private fallback'); await r.settle();
2157
+ assert.equal(r.requests.length, 1); assert.equal(r.admitted.length, 0);
2158
+ r.frame(); await r.settle();
2159
+ assert.equal(r.requests.length, 2); assert.equal(r.admitted.length, 1);
2160
+ assert.equal(r.opened(), 1); assert.equal(r.lines.filter(([who]) => who === 'me').length, 1);
2161
+ await r.advance(1200); r.frame(); assert.equal(r.requests.length, 2);
2162
+ }));
2163
+
2164
+ await test('old body close queued before NOT_TALKING is not an open refusal', () => talkRig({}, async (r) => {
2165
+ // No gone/leave tick: the body was replaced before the conversation's
2166
+ // identity check ran. Its close precedes the refused receipt and new open.
2167
+ r.w.at('p1', 0, 2);
2168
+ r.handlers.send('question after body replacement'); await r.settle();
2169
+ r.frame(); await r.settle();
2170
+ assert.equal(r.requests.length, 2); assert.equal(r.admitted.length, 1);
2171
+ assert.equal(r.opened(), 1); assert.equal(r.talk.talking(), true);
2172
+ }));
2173
+
2174
+ await test('ordinary conversation preserves open/turn traffic', () => talkRig({}, async (r) => {
2175
+ r.handlers.send('ordinary question'); await r.settle();
2176
+ await r.advance(1200); r.frame();
2177
+ assert.deepEqual(r.wire, [{ k: 'hub-npc-open', npc: 'greeter' }]);
2178
+ assert.equal(r.requests.length, 1); assert.equal(r.admitted.length, 1);
2179
+ assert.deepEqual(Object.keys(r.requests[0]), ['requestId', 'operationId', 'characterId', 'input', 'audience']);
2180
+ assert.deepEqual(r.requests[0].audience, { disclosure: 'participants', playerIds: [], characterIds: [] });
2181
+ }));
2182
+
2183
+ for (const slots of [1, 3]) {
2184
+ await test(`full body re-attach shows place busy line, closes and restores draft (${slots} slots)`, () => talkRig({ slots }, async (r) => {
2185
+ r.drop();
2186
+ for (let i = 0; i < slots; i++) {
2187
+ const id = `other${i}`; r.w.at(id, 0, 1); r.w.npcs.message({ playerId: id }, { k: 'hub-npc-open', npc: r.npc });
2188
+ }
2189
+ r.reconnect(); r.handlers.send('private unsent question'); r.frame(); await r.settle();
2190
+ assert.equal(r.requests.length, 0); assert.equal(r.lines.at(-1)[1], 'line:busy');
2191
+ assert.equal(r.talk.talking(), true, 'interruption line is visible before closing');
2192
+ assert.equal(r.draft(), 'private unsent question');
2193
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2194
+ for (let i = 0; i < slots; i++) r.w.npcs.leave(`other${i}`);
2195
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame();
2196
+ assert.equal(r.draft(), 'private unsent question');
2197
+ assert(r.w.sent.every((msg) => !JSON.stringify(msg).includes('private unsent question')));
2198
+ }));
2199
+ }
2200
+
2201
+ for (const refusal of ['gone', 'far', 'signed out']) {
2202
+ await test(`refused re-attach explains ${refusal} and closes`, () => talkRig({ companion: refusal === 'signed out' }, async (r) => {
2203
+ r.drop(); r.w.at('p1', 0, 2);
2204
+ if (refusal === 'gone') r.w.sim.players.delete('p1');
2205
+ if (refusal === 'far') r.w.sim.players.get('p1').at.x = 50;
2206
+ if (refusal === 'signed out') r.w.h.players.get('p1').arrived = false;
2207
+ r.talk.resume(); r.handlers.send('keep this question'); r.frame(); await r.settle();
2208
+ assert.equal(r.requests.length, 0);
2209
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2210
+ assert.equal(r.draft(), 'keep this question');
2211
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2212
+ }));
2213
+ }
2214
+
2215
+ await test('second NOT_TALKING cannot loop; late opens and Done cannot resend', () => talkRig({}, async (r) => {
2216
+ r.forceNotTalking(); r.handlers.send('only one retry'); await r.settle();
2217
+ r.frame(); await r.settle();
2218
+ assert.equal(r.requests.length, 2); assert.equal(r.wire.filter((m) => m.k === 'hub-npc-open').length, 2);
2219
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2220
+ r.handlers.send('duplicate'); await r.advance(1800); r.frame();
2221
+ assert.equal(r.talk.talking(), false); assert.equal(r.requests.length, 2);
2222
+ }));
2223
+
2224
+ await test('reattach timeout explains interruption; late open cannot resurrect panel', () => talkRig({}, async (r) => {
2225
+ r.drop(); r.reconnect(); r.handlers.send('draft');
2226
+ await r.advance(8000); assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2227
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2228
+ r.frame(); await r.settle(); assert.equal(r.requests.length, 0);
2229
+ assert.equal(r.talk.talking(), false, 'late open stays closed after the interruption deadline');
2230
+ }));
2231
+
2232
+ await test('Done while reattaching cancels queued send and discards late open', () => talkRig({}, async (r) => {
2233
+ r.drop(); r.reconnect(); r.handlers.send('cancel this'); r.handlers.end();
2234
+ r.frame(); await r.settle(); assert.equal(r.requests.length, 0); assert.equal(r.talk.talking(), false);
2235
+ }));
2236
+
2237
+ await test('place unavailable line split across frames wins over interruption fallback', () => talkRig({}, async (r) => {
2238
+ r.drop(); r.reconnect(); r.handlers.send('draft');
2239
+ r.w.sent.length = 0;
2240
+ clientHub.npcEvents.push({ k: 'hub-npc', npc: r.npc, open: false, why: 'unavailable' });
2241
+ r.talk.frame(null, { net: r.net }, false); await r.settle();
2242
+ clientHub.npcEvents.push({ k: 'hub-npc-line', npc: r.npc, text: 'Place unavailable words', why: 'unavailable' });
2243
+ r.talk.frame(null, { net: r.net }, false);
2244
+ assert.equal(r.lines.at(-1)[1], 'Place unavailable words');
2245
+ await r.advance(1800); assert.equal(r.talk.talking(), false);
2246
+ }));
2247
+
2248
+ await test('reattach cannot downgrade private question to authored/public speech', () => talkRig({}, async (r) => {
2249
+ r.drop(); r.w.h.place.npcs = null; r.reconnect(); r.handlers.send('private draft');
2250
+ r.frame(); await r.settle(); assert.equal(r.requests.length, 0);
2251
+ assert(!r.wire.some((msg) => msg.k === 'hub-npc-say'));
2252
+ assert.equal(r.draft(), 'private draft');
2253
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2254
+ }));
2255
+
2256
+ await test('refused proactive reattach retains a question still being composed', () => talkRig({}, async (r) => {
2257
+ r.setDraft('not submitted yet'); r.drop(); r.w.at('p1', 50, 0);
2258
+ r.talk.resume(); r.frame(); await r.settle();
2259
+ assert.equal(r.requests.length, 0); assert.equal(r.draft(), 'not submitted yet');
2260
+ await r.advance(1800); r.w.at('p1', 0, 2);
2261
+ r.net.send({ k: 'hub-npc-open', npc: r.npc }); r.frame();
2262
+ assert.equal(r.draft(), 'not submitted yet');
2263
+ }));
2264
+
2265
+ await test('reconnect never replays an admitted turn; reset cancels queued question and draft', () => talkRig({}, async (r) => {
2266
+ r.handlers.send('already admitted'); await r.settle(); assert.equal(r.admitted.length, 1);
2267
+ r.drop(); r.reconnect(); r.frame(); await r.settle(); assert.equal(r.requests.length, 1);
2268
+ await r.advance(1200); r.frame();
2269
+ r.handlers.send('new pending'); r.talk.reset(); r.frame(); await r.settle();
2270
+ assert.equal(r.requests.length, 1, 'reset cancels a question waiting for reattach');
2271
+ assert.equal(r.draft(), '');
2272
+ }));
2273
+
2274
+ // v1.84 review regressions: independently verify packet frames and receipt
2275
+ // ordering instead of draining every server response in one frame.
2276
+ const followupCases = [];
2277
+ for (const options of [{ slots: 1 }, { slots: 3 }, { companion: true }]) {
2278
+ for (const fallback of [false, true]) {
2279
+ followupCases.push([`recovery waits for fresh notes delayed beyond 400 ms (${JSON.stringify(options)}, fallback=${fallback})`, () => talkRig(options, async (r) => {
2280
+ if (options.companion && fallback) {
2281
+ // Idle/end leaves the virtual body known; leave forgets it entirely
2282
+ // and that separate server refusal is UNKNOWN, not NOT_TALKING.
2283
+ r.w.npcs.handle(r.npc).end(); r.skipMessages();
2284
+ } else {
2285
+ r.drop();
2286
+ }
2287
+ if (fallback) {
2288
+ r.w.at('p1', 0, 2); r.handlers.send('delayed notes question'); await r.settle();
2289
+ } else {
2290
+ r.reconnect(); r.handlers.send('delayed notes question');
2291
+ }
2292
+ const before = fallback ? 1 : 0;
2293
+ r.frame((msg) => msg.k !== 'hub-npc-notes'); await r.settle();
2294
+ assert.equal(r.requests.length, before, 'open acknowledgement alone cannot send the question');
2295
+ await r.advance(600);
2296
+ assert.equal(r.requests.length, before, 'recovery keeps waiting past the old notes retry delay');
2297
+ r.frame(); await r.settle();
2298
+ assert.equal(r.requests.length, before + 1); assert.equal(r.admitted.length, 1);
2299
+ assert(r.requests.at(-1).input.startsWith(NOTES_HEAD));
2300
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, 2);
2301
+ await r.advance(1200); r.frame();
2302
+ assert.equal(r.requests.length, before + 1); assert.equal(r.talk.talking(), true);
2303
+ })]);
2304
+ }
2305
+ }
2306
+ for (const code of ['CAULDRON_SHARED_CHARACTER_BUSY', 'CAULDRON_SHARED_CHARACTER_BUDGET']) {
2307
+ for (const lineFirst of [true, false]) {
2308
+ followupCases.push([`recovered turn closes after ${code} (lineFirst=${lineFirst})`, () => talkRig({}, async (r) => {
2309
+ r.drop(); r.w.at('p1', 0, 2);
2310
+ r.deferRecoveryRefusal(code); r.handlers.send('refused recovered question'); await r.settle();
2311
+ r.frame(); await r.settle();
2312
+ if (lineFirst) r.frame();
2313
+ r.releaseRefusal(); await r.settle();
2314
+ if (!lineFirst) r.frame();
2315
+ assert.equal(r.lines.at(-1)[1], code.endsWith('BUSY') ? 'line:busy' : 'line:budget');
2316
+ await r.advance(1800);
2317
+ assert.equal(r.talk.talking(), false, 'the place line cannot cancel refusal cleanup');
2318
+ assert.equal(r.draft(), 'refused recovered question');
2319
+ assert.equal(r.requests.length, 2);
2320
+ assert.equal(r.lines.filter(([, text]) => text === 'line:busy' || text === 'line:budget').length, 1);
2321
+ })]);
2322
+ }
2323
+ }
2324
+ followupCases.push(['no-note conversation reattaches without waiting for a packet the server never sends', () => talkRig({ noNotes: true }, async (r) => {
2325
+ assert(!r.w.sent.some((msg) => msg.k === 'hub-npc-notes'));
2326
+ r.drop(); r.reconnect(); r.handlers.send('no notes needed'); r.frame(); await r.settle();
2327
+ assert.equal(r.requests.length, 1); assert.equal(r.admitted.length, 1);
2328
+ assert.equal(r.requests[0].input, 'no notes needed');
2329
+ await r.advance(1200); r.frame(); assert.equal(r.talk.talking(), true);
2330
+ })]);
2331
+ followupCases.push(['open acknowledgement without required notes times out without sending the question', () => talkRig({}, async (r) => {
2332
+ r.drop(); r.reconnect(); r.handlers.send('keep waiting question');
2333
+ r.frame((msg) => msg.k !== 'hub-npc-notes'); await r.settle();
2334
+ await r.advance(8000); assert.equal(r.requests.length, 0);
2335
+ assert.equal(r.draft(), 'keep waiting question');
2336
+ assert.equal(r.lines.at(-1)[1], 'Lost the thread there. Tap to talk again.');
2337
+ await r.advance(1800); r.frame(); await r.settle();
2338
+ assert.equal(r.talk.talking(), false); assert.equal(r.requests.length, 0);
2339
+ })]);
2340
+ for (const codes of [['HUB_NPC_NOT_TALKING', 'HUB_NPC_NOTES'], ['HUB_NPC_NOTES', 'HUB_NPC_NOT_TALKING']]) {
2341
+ followupCases.push([`notes and attachment share one resend limit (${codes.join(' -> ')})`, () => talkRig({}, async (r) => {
2342
+ r.refuseTurns(...codes); r.handlers.send('one resend total'); await r.settle();
2343
+ r.frame(); await r.settle(); await r.advance(400); r.frame(); await r.settle();
2344
+ assert.equal(r.requests.length, 2, 'different refusal codes cannot each spend a resend');
2345
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, codes[0] === 'HUB_NPC_NOT_TALKING' ? 2 : 1);
2346
+ assert.equal(r.draft(), 'one resend total');
2347
+ await r.advance(8000); r.frame(); await r.settle();
2348
+ assert.equal(r.requests.length, 2); assert.equal(r.talk.talking(), false);
2349
+ })]);
2350
+ }
2351
+ followupCases.push(['recovery notes retry waits for newer notes instead of resending at 400 ms', () => talkRig({}, async (r) => {
2352
+ r.drop(); r.reconnect(); r.frame(); await r.settle();
2353
+ r.refuseTurns('HUB_NPC_NOTES'); r.handlers.send('changed notes question'); await r.settle();
2354
+ await r.advance(600); assert.equal(r.requests.length, 1);
2355
+ r.w.h.hooks.npcContext = () => 'newer notes'; r.w.tick(1000);
2356
+ r.frame(); await r.settle();
2357
+ assert.equal(r.requests.length, 2); assert.equal(r.admitted.length, 1);
2358
+ assert(r.requests.at(-1).input.includes('newer notes'));
2359
+ assert.equal(r.wire.filter((msg) => msg.k === 'hub-npc-open').length, 2);
2360
+ })]);
2361
+ for (const [name, run] of followupCases) {
2362
+ await test(name, run);
2363
+ }
2364
+
724
2365
  console.log(`hub-game npcs: ${n} tests passed`);
2366
+
2367
+ // v1.90: a delayed real follow-token read cannot restart a held body between
2368
+ // place ticks; nor can a queued physics step or a later place errand.
2369
+ await test('movement hold gates queued steps, commands and asynchronous token follows', async () => {
2370
+ let releaseInspect;
2371
+ const w = world({ inspect: () => new Promise((resolve) => { releaseInspect = resolve; }) });
2372
+ const npc = w.npcs.handle('greeter');
2373
+ w.at('a', 0, 2);
2374
+ await w.npcs.onRead({ speaker: { playerId: 'a' }, query: { type: 'inspect' }, read: async () => ({ participantId: 'p-a' }), reject() {} });
2375
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-open', npc: 'greeter' });
2376
+ await w.npcs.onTurn(turn({ speaker: 'a' }));
2377
+ await w.npcs.onRead(statusRead('a', 'op1', 'Lead the way!'));
2378
+ w.npcs.message({ playerId: 'a' }, { k: 'hub-npc-end', npc: 'greeter' });
2379
+ w.at('a', 30, 0);
2380
+ npc.walkTo({ x: 30, z: 0 });
2381
+ w.sim.timeMs += 100;
2382
+ w.npcs.place(0.1); // Queues movement and starts the public inspect read.
2383
+ assert.ok(w.greeter().next.x > 0);
2384
+ assert.equal(typeof releaseInspect, 'function');
2385
+ npc.holdMovement(true);
2386
+ const post = { ...w.greeter().p };
2387
+ assert.deepEqual(w.greeter().next, post, 'hold cancels a step queued before physics');
2388
+ releaseInspect({ gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } });
2389
+ await new Promise((resolve) => setImmediate(resolve));
2390
+ assert.equal(npc.following, null, 'pending token result cannot restart following');
2391
+ for (let i = 0; i < 60; i++) {
2392
+ npc.walkTo({ x: 30, z: 0 }); npc.home(); npc.follow('a');
2393
+ w.tick(100);
2394
+ if (releaseInspect) releaseInspect({ gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } });
2395
+ await new Promise((resolve) => setImmediate(resolve));
2396
+ assert.deepEqual(w.greeter().p, post);
2397
+ assert.equal(npc.walking, false);
2398
+ assert.equal(npc.following, null);
2399
+ }
2400
+ npc.holdMovement(false);
2401
+ w.tick(3000);
2402
+ releaseInspect({ gameplay: { objects: { greeterFollow: { holderId: 'p-a' } } } });
2403
+ await new Promise((resolve) => setImmediate(resolve));
2404
+ assert.equal(npc.following, 'a', 'new token read resumes after release');
2405
+ w.tick(100);
2406
+ assert.ok(w.greeter().p.x > post.x);
2407
+ });
2408
+
2409
+ // v1.90: preference is private, opt-in, idempotent and replayed only as needed.
2410
+ {
2411
+ const w = world();
2412
+ w.at('a', 0, 0); w.at('b', 0, 0);
2413
+ w.npcs.replayPreferred('a');
2414
+ assert.deepEqual(w.sent, []);
2415
+ assert.equal(w.npcs.prefer('missing', 'greeter'), false);
2416
+ assert.equal(w.npcs.prefer('a', 'missing'), false);
2417
+ assert.equal(w.npcs.prefer('a', 'greeter'), true);
2418
+ w.npcs.prefer('a', 'greeter');
2419
+ assert.deepEqual(w.sent, [{ playerId: 'a', k: 'hub-npc-preferred', npc: 'greeter' }]);
2420
+ w.npcs.replayPreferred('a');
2421
+ assert.equal(w.sent.length, 2);
2422
+ w.npcs.prefer('a', null);
2423
+ w.npcs.replayPreferred('a');
2424
+ assert.equal(w.sent.length, 3, 'fresh client needs no empty hint');
2425
+ w.npcs.replayPreferred('a', true);
2426
+ assert.equal(w.sent.length, 4, 'retained client receives missed clear');
2427
+ w.npcs.leave('a');
2428
+ w.npcs.replayPreferred('a', true);
2429
+ assert.equal(w.sent.length, 4, 'departure forgets preference');
2430
+ }