@pretty-chitty/core 1.2.17 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/dist/components/ClientTrustMatchViewer.d.ts +14 -1
  2. package/dist/components/ClientTrustMatchViewer.d.ts.map +1 -1
  3. package/dist/components/ClientTrustMatchViewer.js +25 -2
  4. package/dist/components/ClientTrustMatchViewer.js.map +1 -1
  5. package/dist/components/DemoWrapper.d.ts.map +1 -1
  6. package/dist/components/DemoWrapper.js +4 -11
  7. package/dist/components/DemoWrapper.js.map +1 -1
  8. package/dist/components/Gallery/BuiltItem.d.ts.map +1 -1
  9. package/dist/components/Gallery/BuiltItem.js +3 -0
  10. package/dist/components/Gallery/BuiltItem.js.map +1 -1
  11. package/dist/components/Gallery/GalleryController.d.ts.map +1 -1
  12. package/dist/components/Gallery/GalleryController.js +3 -1
  13. package/dist/components/Gallery/GalleryController.js.map +1 -1
  14. package/dist/components/PanelSpark.js +1 -1
  15. package/dist/components/PlayerImage.d.ts.map +1 -1
  16. package/dist/components/PlayerImage.js +21 -1
  17. package/dist/components/PlayerImage.js.map +1 -1
  18. package/dist/components/Playground.d.ts.map +1 -1
  19. package/dist/components/Playground.js +37 -11
  20. package/dist/components/Playground.js.map +1 -1
  21. package/dist/components/TokenizedMessage.d.ts +2 -6
  22. package/dist/components/TokenizedMessage.d.ts.map +1 -1
  23. package/dist/components/TokenizedMessage.js +1 -35
  24. package/dist/components/TokenizedMessage.js.map +1 -1
  25. package/dist/components/TopBarPlayers.d.ts.map +1 -1
  26. package/dist/components/TopBarPlayers.js +1 -1
  27. package/dist/components/TopBarPlayers.js.map +1 -1
  28. package/dist/game/Chit.js +2 -2
  29. package/dist/game/Chit.js.map +1 -1
  30. package/dist/game/ConnectionTransport.d.ts +3 -0
  31. package/dist/game/ConnectionTransport.d.ts.map +1 -1
  32. package/dist/game/ConnectionTransport.js +13 -4
  33. package/dist/game/ConnectionTransport.js.map +1 -1
  34. package/dist/game/Game.d.ts +8 -1
  35. package/dist/game/Game.d.ts.map +1 -1
  36. package/dist/game/Match.d.ts +66 -0
  37. package/dist/game/Match.d.ts.map +1 -1
  38. package/dist/game/Match.js +151 -3
  39. package/dist/game/Match.js.map +1 -1
  40. package/dist/game/MatchStorage.d.ts +8 -1
  41. package/dist/game/MatchStorage.d.ts.map +1 -1
  42. package/dist/game/MatchStorage.js +11 -3
  43. package/dist/game/MatchStorage.js.map +1 -1
  44. package/dist/game/Pick.d.ts +14 -0
  45. package/dist/game/Pick.d.ts.map +1 -1
  46. package/dist/game/Pick.js +15 -0
  47. package/dist/game/Pick.js.map +1 -1
  48. package/dist/game/PlayerChit.d.ts +4 -0
  49. package/dist/game/PlayerChit.d.ts.map +1 -1
  50. package/dist/game/PlayerChit.js +8 -2
  51. package/dist/game/PlayerChit.js.map +1 -1
  52. package/dist/game/PlayerInfo.d.ts +8 -0
  53. package/dist/game/PlayerInfo.d.ts.map +1 -1
  54. package/dist/game/PlayerInfo.js +6 -3
  55. package/dist/game/PlayerInfo.js.map +1 -1
  56. package/dist/game/PlayerPromptStatusChit.d.ts.map +1 -1
  57. package/dist/game/PlayerPromptStatusChit.js +3 -1
  58. package/dist/game/PlayerPromptStatusChit.js.map +1 -1
  59. package/dist/game/Turn.d.ts +11 -2
  60. package/dist/game/Turn.d.ts.map +1 -1
  61. package/dist/game/Turn.js +118 -68
  62. package/dist/game/Turn.js.map +1 -1
  63. package/dist/game/TurnState.d.ts +8 -0
  64. package/dist/game/TurnState.d.ts.map +1 -1
  65. package/dist/game/TurnState.js +7 -0
  66. package/dist/game/TurnState.js.map +1 -1
  67. package/dist/game/ai/AiClientPrompts.d.ts +160 -0
  68. package/dist/game/ai/AiClientPrompts.d.ts.map +1 -0
  69. package/dist/game/ai/AiClientPrompts.js +525 -0
  70. package/dist/game/ai/AiClientPrompts.js.map +1 -0
  71. package/dist/game/ai/AiLiveView.d.ts +2 -0
  72. package/dist/game/ai/AiLiveView.d.ts.map +1 -0
  73. package/dist/game/ai/AiLiveView.js +48 -0
  74. package/dist/game/ai/AiLiveView.js.map +1 -0
  75. package/dist/game/ai/AiPlayerView.d.ts +2 -0
  76. package/dist/game/ai/AiPlayerView.d.ts.map +1 -0
  77. package/dist/game/ai/AiPlayerView.js +89 -0
  78. package/dist/game/ai/AiPlayerView.js.map +1 -0
  79. package/dist/game/ai/connectAiPlayer.d.ts +43 -0
  80. package/dist/game/ai/connectAiPlayer.d.ts.map +1 -0
  81. package/dist/game/ai/connectAiPlayer.js +58 -0
  82. package/dist/game/ai/connectAiPlayer.js.map +1 -0
  83. package/dist/game/ai/defineAi.d.ts +119 -0
  84. package/dist/game/ai/defineAi.d.ts.map +1 -0
  85. package/dist/game/ai/defineAi.js +122 -0
  86. package/dist/game/ai/defineAi.js.map +1 -0
  87. package/dist/game/ai/simulateMatches.d.ts +62 -0
  88. package/dist/game/ai/simulateMatches.d.ts.map +1 -0
  89. package/dist/game/ai/simulateMatches.js +108 -0
  90. package/dist/game/ai/simulateMatches.js.map +1 -0
  91. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts +3 -0
  92. package/dist/game/badAiTransport/BadAIClientPrompts.d.ts.map +1 -1
  93. package/dist/game/badAiTransport/BadAIClientPrompts.js +3 -0
  94. package/dist/game/badAiTransport/BadAIClientPrompts.js.map +1 -1
  95. package/dist/hooks/useTokenMap.d.ts +2 -4
  96. package/dist/hooks/useTokenMap.d.ts.map +1 -1
  97. package/dist/hooks/useTokenMap.js +2 -5
  98. package/dist/hooks/useTokenMap.js.map +1 -1
  99. package/dist/hooks/useWebGlRenderer.d.ts +1 -0
  100. package/dist/hooks/useWebGlRenderer.d.ts.map +1 -1
  101. package/dist/hooks/useWebGlRenderer.js +33 -21
  102. package/dist/hooks/useWebGlRenderer.js.map +1 -1
  103. package/dist/index.d.ts +21 -1
  104. package/dist/index.d.ts.map +1 -1
  105. package/dist/index.js +8 -1
  106. package/dist/index.js.map +1 -1
  107. package/dist/utilities/CanvasStack/CanvasOperations.d.ts +15 -1
  108. package/dist/utilities/CanvasStack/CanvasOperations.d.ts.map +1 -1
  109. package/dist/utilities/CanvasStack/CanvasOperations.js +65 -6
  110. package/dist/utilities/CanvasStack/CanvasOperations.js.map +1 -1
  111. package/dist/utilities/CanvasStack/CanvasStack.d.ts +18 -1
  112. package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
  113. package/dist/utilities/CanvasStack/CanvasStack.js +119 -6
  114. package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
  115. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts +2 -1
  116. package/dist/utilities/CanvasStack/PlayerCanvas.d.ts.map +1 -1
  117. package/dist/utilities/CanvasStack/PlayerCanvas.js +3 -2
  118. package/dist/utilities/CanvasStack/PlayerCanvas.js.map +1 -1
  119. package/dist/utilities/CanvasStack/ReactCanvas.d.ts +2 -1
  120. package/dist/utilities/CanvasStack/ReactCanvas.d.ts.map +1 -1
  121. package/dist/utilities/CanvasStack/ReactCanvas.js +2 -2
  122. package/dist/utilities/CanvasStack/ReactCanvas.js.map +1 -1
  123. package/dist/utilities/ParameterizedCanvas.d.ts +1 -0
  124. package/dist/utilities/ParameterizedCanvas.d.ts.map +1 -1
  125. package/dist/utilities/ParameterizedCanvas.js +4 -1
  126. package/dist/utilities/ParameterizedCanvas.js.map +1 -1
  127. package/dist/utilities/TokenizedText.d.ts +49 -0
  128. package/dist/utilities/TokenizedText.d.ts.map +1 -0
  129. package/dist/utilities/TokenizedText.js +47 -0
  130. package/dist/utilities/TokenizedText.js.map +1 -0
  131. package/package.json +1 -1
  132. package/src/library/components/ClientTrustMatchViewer.tsx +32 -2
  133. package/src/library/components/DemoWrapper.tsx +4 -12
  134. package/src/library/components/Gallery/BuiltItem.ts +4 -0
  135. package/src/library/components/Gallery/GalleryController.ts +3 -1
  136. package/src/library/components/PanelSpark.tsx +1 -1
  137. package/src/library/components/PlayerImage.tsx +26 -2
  138. package/src/library/components/Playground.tsx +77 -12
  139. package/src/library/components/TokenizedMessage.tsx +2 -63
  140. package/src/library/components/TopBarPlayers.tsx +6 -1
  141. package/src/library/game/Chit.ts +2 -2
  142. package/src/library/game/ConnectionTransport.ts +12 -3
  143. package/src/library/game/Game.ts +9 -1
  144. package/src/library/game/Match.ts +162 -3
  145. package/src/library/game/MatchStorage.ts +14 -4
  146. package/src/library/game/Pick.ts +20 -0
  147. package/src/library/game/PlayerChit.ts +10 -3
  148. package/src/library/game/PlayerInfo.ts +13 -3
  149. package/src/library/game/PlayerPromptStatusChit.ts +3 -1
  150. package/src/library/game/Turn.ts +131 -76
  151. package/src/library/game/TurnState.ts +8 -0
  152. package/src/library/game/ai/AI_GUIDE.md +434 -0
  153. package/src/library/game/ai/AiClientPrompts.ts +681 -0
  154. package/src/library/game/ai/AiLiveView.ts +63 -0
  155. package/src/library/game/ai/AiPlayerView.ts +112 -0
  156. package/src/library/game/ai/ai.test.ts +475 -0
  157. package/src/library/game/ai/connectAiPlayer.ts +88 -0
  158. package/src/library/game/ai/defineAi.ts +230 -0
  159. package/src/library/game/ai/simulateMatches.ts +172 -0
  160. package/src/library/game/badAiTransport/BadAIClientPrompts.ts +3 -0
  161. package/src/library/hooks/useTokenMap.ts +2 -6
  162. package/src/library/hooks/useWebGlRenderer.tsx +44 -24
  163. package/src/library/index.ts +34 -2
  164. package/src/library/utilities/CanvasStack/CanvasOperations.tsx +87 -17
  165. package/src/library/utilities/CanvasStack/CanvasStack.ts +119 -5
  166. package/src/library/utilities/CanvasStack/PlayerCanvas.tsx +5 -2
  167. package/src/library/utilities/CanvasStack/ReactCanvas.tsx +2 -2
  168. package/src/library/utilities/ParameterizedCanvas.ts +5 -1
  169. package/src/library/utilities/TokenizedText.test.ts +32 -0
  170. package/src/library/utilities/TokenizedText.ts +97 -0
@@ -8,12 +8,15 @@ import { MismatchError, Turn } from "./Turn";
8
8
 
9
9
  export type FindChit = (id: string) => Chit;
10
10
  export type PickType = "ChitPick" | "ButtonPick" | "DragPick";
11
+ /** Links a pick to a rule in the game's AI (see {@link Pick.ai}). `d` must be JSON and public. */
12
+ export type PickAiTag = { k: string; d?: unknown };
11
13
  export type PickSerialization = {
12
14
  type: PickType;
13
15
  message?: string;
14
16
  help?: string;
15
17
  details: any;
16
18
  context?: string;
19
+ ai?: PickAiTag;
17
20
  };
18
21
 
19
22
  export abstract class Pick {
@@ -30,6 +33,9 @@ export abstract class Pick {
30
33
  /** @internal */
31
34
  public contextChit?: Chit;
32
35
 
36
+ /** @internal */
37
+ public aiTag?: PickAiTag;
38
+
33
39
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
34
40
  /** @internal */
35
41
  confirmLock(_turn: Turn<any, any, any>) {
@@ -75,6 +81,18 @@ export abstract class Pick {
75
81
  return this;
76
82
  }
77
83
 
84
+ /**
85
+ * Tags this pick so AI players score its options with the rule named `key` in the game's
86
+ * `ai` (see `defineAi`). Untagged picks fall back to the AI's `default` rule, or random.
87
+ * @param key Rule name, e.g. "market.buy"
88
+ * @param data Optional JSON hint passed to the rule. It is sent to every client, so it must
89
+ * only contain information the prompted player is allowed to see.
90
+ */
91
+ ai(key: string, data?: unknown): this {
92
+ this.aiTag = data === undefined ? { k: key } : { k: key, d: data };
93
+ return this;
94
+ }
95
+
78
96
  /** @internal */
79
97
  serialize(): PickSerialization {
80
98
  return {
@@ -83,6 +101,7 @@ export abstract class Pick {
83
101
  message: this.messageContents,
84
102
  details: this.serializeDetails(),
85
103
  context: this.contextChit ? this.contextChit.id : undefined,
104
+ ai: this.aiTag,
86
105
  };
87
106
  }
88
107
 
@@ -108,6 +127,7 @@ export abstract class Pick {
108
127
  p.contextChit = pick.context ? findChit(pick.context) : undefined;
109
128
  p.messageContents = pick.message;
110
129
  p.helpContents = pick.help;
130
+ p.aiTag = pick.ai;
111
131
  p.deserializeDetails(pick.details, findChit, buttonLibrary);
112
132
  return p;
113
133
  }
@@ -1,7 +1,7 @@
1
1
  import { ChildOutlet, NonEditable } from "../utilities/Annotations";
2
2
  import { PlayerCanvas } from "../utilities/CanvasStack/PlayerCanvas";
3
3
  import { Chit } from "./Chit";
4
- import { PlayerInfo } from "./PlayerInfo";
4
+ import { AiSeatInfo, PlayerInfo } from "./PlayerInfo";
5
5
  import { PlayerPromptStatusChit } from "./PlayerPromptStatusChit";
6
6
 
7
7
  export class PlayerChit extends Chit {
@@ -11,6 +11,8 @@ export class PlayerChit extends Chit {
11
11
  public playerId: string = "no id";
12
12
  public name: string = "no name";
13
13
  public color: string = "#000000";
14
+ /** Set when this seat is played by the engine's AI (copied from `PlayerInfo.ai`; public, so UIs can mark the seat) */
15
+ public ai?: AiSeatInfo = undefined;
14
16
 
15
17
  /** @internal */
16
18
  private myImageUrl?: string = undefined;
@@ -33,12 +35,16 @@ export class PlayerChit extends Chit {
33
35
  public get panelTab() {
34
36
  return {
35
37
  color: this.color,
36
- icon: new PlayerCanvas(this).get(),
38
+ icon: new PlayerCanvas(this, this.colorBlend).get(),
37
39
  };
38
40
  }
39
41
 
40
42
  public get icon() {
41
- return new PlayerCanvas(this).get();
43
+ return new PlayerCanvas(this, this.colorBlend).get();
44
+ }
45
+
46
+ public get colorBlend() {
47
+ return 0;
42
48
  }
43
49
 
44
50
  public get logKey() {
@@ -51,5 +57,6 @@ export class PlayerChit extends Chit {
51
57
  this.name = playerInfo.name;
52
58
  this.id = playerInfo.id;
53
59
  this.imageUrl = playerInfo.imageUrl;
60
+ this.ai = playerInfo.ai;
54
61
  }
55
62
  }
@@ -1,19 +1,28 @@
1
1
  import multiavatar from "@multiavatar/multiavatar";
2
2
  import base64 from "base-64";
3
3
 
4
+ /** Marks a seat as played by the engine's AI (see `connectAiPlayer`). */
5
+ export type AiSeatInfo = {
6
+ /** 0–1; lower plays less predictably. Default 0.85 */
7
+ difficulty?: number;
8
+ };
9
+
4
10
  export interface IPlayerInfo {
5
11
  id: string;
6
12
  name: string;
7
13
  imageUrl?: string;
14
+ ai?: AiSeatInfo;
8
15
  }
9
16
 
10
17
  export class PlayerInfo {
11
18
  public id: string;
12
19
  public name: string;
20
+ /** Set when this seat is an AI player */
21
+ public ai?: AiSeatInfo;
13
22
 
14
23
  /** @internal */
15
24
  public generateAvatar() {
16
- if (!this.myImageUrl && window?.URL) {
25
+ if (!this.myImageUrl && typeof window !== "undefined" && window.URL) {
17
26
  const data = multiavatar(`${this.name} ${this.id}`, true).replace("<svg", '<svg width="231" height="231"');
18
27
  return `data:image/svg+xml;base64,${base64.encode(data)}`;
19
28
  }
@@ -23,7 +32,7 @@ export class PlayerInfo {
23
32
  /** @internal */
24
33
  private myImageUrl?: string;
25
34
  get imageUrl() {
26
- if (!this.myImageUrl && window?.URL) {
35
+ if (!this.myImageUrl && typeof window !== "undefined" && window.URL) {
27
36
  return this.generateAvatar();
28
37
  }
29
38
  return this.myImageUrl;
@@ -40,9 +49,10 @@ export class PlayerInfo {
40
49
  this.id = idOrPlayerInfo.id;
41
50
  this.name = idOrPlayerInfo.name;
42
51
  this.imageUrl = idOrPlayerInfo.imageUrl;
52
+ this.ai = idOrPlayerInfo.ai;
43
53
  }
44
54
 
45
- if (!this.imageUrl && window?.URL) {
55
+ if (!this.imageUrl && typeof window !== "undefined" && window.URL) {
46
56
  this.imageUrl = this.generateAvatar();
47
57
  }
48
58
  }
@@ -5,8 +5,10 @@ import { Prompt } from "./Prompt";
5
5
  import StaticChitTypeRegistry from "./StaticChitTypeRegistry";
6
6
 
7
7
  export class PlayerPromptStatusChit extends Chit {
8
- /** @internal */
8
+ /** The prompt the player is currently being asked to answer, with `:token:` markup intact. @internal */
9
9
  public latestPromptMessage?: string;
10
+ /** Plain-text form of {@link latestPromptMessage} for storage, match lists and notifications. @internal */
11
+ public latestPromptMessageText?: string;
10
12
  /** @internal */
11
13
  @NonEditable public latestPrompt = new EventChannel<Prompt | undefined>(undefined, 50);
12
14
  /** @internal */
@@ -1,4 +1,5 @@
1
1
  import { Chit } from "./Chit";
2
+ import { buildTokenMap, tokenizedMessageToText } from "../utilities/TokenizedText";
2
3
  import { Match } from "./Match";
3
4
  import { NoValidMovesPrompt, PickPrompt, Prompt } from "./Prompt";
4
5
  import { PromptResponse, RngResponse, TurnState } from "./TurnState";
@@ -94,6 +95,16 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
94
95
  private dirtyChitIds = new Set<string>();
95
96
  private pendingNewChits = new Set<Chit>();
96
97
  private _statePool?: Map<string, string>;
98
+ private _serializeCache?: SerializeCache;
99
+
100
+ /**
101
+ * Drop any cached serialize() reconstruction on this turn and every ancestor,
102
+ * since their snapshots include our contribution.
103
+ */
104
+ private invalidateSerializeCache() {
105
+ this._serializeCache = undefined;
106
+ this.parent?.invalidateSerializeCache();
107
+ }
97
108
 
98
109
  private get statePool(): Map<string, string> {
99
110
  if (this.parent) return this.parent.statePool;
@@ -233,6 +244,20 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
233
244
  };
234
245
  }
235
246
 
247
+ /**
248
+ * Records what a player is being asked for: the tokenized message for the in-game UI, and a plain-text version
249
+ * (player tokens become names, etc.) for anything that can only show text.
250
+ */
251
+ private setPromptMessage(player: P, message: string | undefined) {
252
+ player.promptStatus.latestPromptMessage = message;
253
+ if (message === undefined) {
254
+ player.promptStatus.latestPromptMessageText = undefined;
255
+ return;
256
+ }
257
+ const tokenMap = buildTokenMap(this.match.game.tokenMap, this.rootChit.players.map((p) => p));
258
+ player.promptStatus.latestPromptMessageText = tokenizedMessageToText(message, tokenMap);
259
+ }
260
+
236
261
  /**
237
262
  * Add a game log message to the last flush step
238
263
  * @param message
@@ -305,8 +330,12 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
305
330
  }
306
331
 
307
332
  if (hasChange) {
333
+ // Pops and in-place merges can leave any cached walk pointing into invalid territory.
334
+ this.invalidateSerializeCache();
308
335
  this.pass++;
309
- this.flush(true);
336
+ // No trailing force-flush: it would only push an empty FlushClockStep (no chit
337
+ // diff, no log) that the client has to walk through for no visual change. The
338
+ // bumped `pass` is read live from `clockDetails` on the next notify.
310
339
  }
311
340
  }
312
341
 
@@ -360,7 +389,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
360
389
  }
361
390
  }
362
391
 
363
- // 2. Serialize only dirty chits
392
+ // 2. Serialize only dirty chits. `newStates` now stores only the diff against the
393
+ // previous flush — unchanged-after-dirty-check chits are dropped from the step.
364
394
  for (const id of this.dirtyChitIds) {
365
395
  const chit = this.chitLookup[id];
366
396
  if (!chit) continue;
@@ -369,20 +399,11 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
369
399
  if (serialized !== lastState) {
370
400
  this.lastChitStates[id] = newStates[id] = serialized;
371
401
  sawChange = true;
372
- } else {
373
- newStates[id] = serialized;
374
402
  }
375
403
  }
376
404
  this.dirtyChitIds.clear();
377
405
 
378
- // 4. Carry forward all non-dirty chit states
379
- for (const id of Object.keys(this.lastChitStates)) {
380
- if (newStates[id] === undefined) {
381
- newStates[id] = this.lastChitStates[id];
382
- }
383
- }
384
-
385
- // 5. Detect deleted chits — orphans in lastChitStates that weren't serialized above
406
+ // 3. Detect deleted chits — orphans in lastChitStates that weren't serialized above
386
407
  const deletedRoots: Chit[] = [];
387
408
  for (const id of Object.keys(this.lastChitStates)) {
388
409
  if (this.lastChitStates[id] === Chit.deletedIfSerialized()) continue;
@@ -416,6 +437,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
416
437
  }
417
438
 
418
439
  this.clockSteps.push(new FlushClockStep(this.clock, newStates));
440
+ // Ancestors' caches included our prior contribution; the new step makes them stale.
441
+ this.parent?.invalidateSerializeCache();
419
442
  }
420
443
  }
421
444
 
@@ -479,6 +502,8 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
479
502
  }
480
503
  lastStep.turns.push(turn);
481
504
  }
505
+ // Either case mutates a step our own cache (or an ancestor's) may have already walked past.
506
+ this.invalidateSerializeCache();
482
507
 
483
508
  this.activeSubTurns.push(turn);
484
509
 
@@ -501,17 +526,34 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
501
526
  });
502
527
 
503
528
  this.lastChitStates = { ...this.lastChitStates, ...turn.lastChitStates };
529
+ turn.releasePostAbsorptionRefs();
504
530
 
505
531
  return result;
506
532
  }
507
533
 
534
+ /**
535
+ * Called by the parent right after it has absorbed our `chitLookup` and `lastChitStates`.
536
+ * After this we will only ever be walked via `serialize` / `chitsHistory` / `gameLog`,
537
+ * which only need `clockSteps` and `lockedChitStates` — so drop the heavy per-chit
538
+ * bookkeeping to keep finished sub-turns from pinning hundreds of chit references.
539
+ * @internal
540
+ */
541
+ private releasePostAbsorptionRefs() {
542
+ this.chitLookup = {};
543
+ this.chitsToLock = [];
544
+ this.lastChitStates = {};
545
+ this.pendingNewChits.clear();
546
+ this.dirtyChitIds.clear();
547
+ this._serializeCache = undefined;
548
+ }
549
+
508
550
  public async runParallelTurns<A>(
509
551
  players: P[],
510
552
  chits: (p: P) => Chit[],
511
553
  action: (p: P, turn: Turn<A, P, R>) => Promise<A>,
512
554
  ): Promise<A[]> {
513
555
  // the whole point of this function is so we can mark all players as having a prompt waiting for them
514
- players.forEach((player) => (player.promptStatus.latestPromptMessage = "Waiting for turn to complete"));
556
+ players.forEach((player) => this.setPromptMessage(player, "Waiting for turn to complete"));
515
557
 
516
558
  const turns = players.map((player) =>
517
559
  this.createTurn(chits(player), player, (turn: Turn<A, P, R>) => action(player, turn)),
@@ -761,31 +803,6 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
761
803
  return result;
762
804
  }
763
805
 
764
- private findIndexOfLastFlushStepBefore(clock: number): number {
765
- for (let j = this.clockSteps.length - 1; j >= 0; j--) {
766
- if (this.clockSteps[j] instanceof FlushClockStep && this.clockSteps[j].startClock < clock) {
767
- return j;
768
- }
769
- }
770
- return 0;
771
- }
772
- private findIndexOfLastFlushStepWithLogMessageBefore(clock: number): number {
773
- for (let j = this.clockSteps.length - 1; j >= 0; j--) {
774
- if (
775
- this.clockSteps[j] instanceof FlushClockStep &&
776
- this.clockSteps[j].startClock < clock &&
777
- (this.clockSteps[j] as FlushClockStep).log
778
- ) {
779
- return j;
780
- }
781
- if (this.clockSteps[j].startClock < clock && this.clockSteps[j] instanceof SubTurnsClockStep) {
782
- // logs cannot be inside subturns
783
- break;
784
- }
785
- }
786
- return -1;
787
- }
788
-
789
806
  /** @internal */
790
807
  chitsHistory(playerId: string, ids: string[]): ChitHistoryResponse {
791
808
  const result: ChitHistoryResponse = {};
@@ -803,6 +820,15 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
803
820
  }
804
821
  };
805
822
 
823
+ // Seed with the initial locked state so chits that never diff in this turn still
824
+ // surface their starting form (flush steps now hold diffs only).
825
+ ids.forEach((id) => {
826
+ const initial = this.lockedChitStates[id];
827
+ if (initial !== undefined) {
828
+ appendLog(id, 0, initial);
829
+ }
830
+ });
831
+
806
832
  this.clockSteps.forEach((step) => {
807
833
  if (step instanceof FlushClockStep) {
808
834
  ids.forEach((id) => appendLog(id, step.startClock, step.state[id]));
@@ -824,51 +850,51 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
824
850
  serialize(playerId: string, clock: number): ChitSerializationResponse {
825
851
  clock = Math.max(0, Math.min(clock, this.playerVisibleClockTime(playerId)));
826
852
 
827
- let chits = {};
828
- let resultingClock = -1;
829
-
830
- // going forwards
831
- let index = this.findIndexOfLastFlushStepBefore(clock);
832
- const lastLogIndex = this.findIndexOfLastFlushStepWithLogMessageBefore(clock);
833
-
834
- // set up logs
853
+ let chits: ChitStateLookup;
854
+ let subTurns: { [turnId: string]: ClockDetails } | undefined;
835
855
  let log: LogMessageSerializationResponse | undefined;
836
- if (lastLogIndex >= 0) {
837
- const messageStep = this.clockSteps[lastLogIndex] as FlushClockStep;
838
- log = {
839
- message: messageStep.log!,
840
- clock: messageStep.startClock,
841
- };
856
+ let resultingClock: number;
857
+ let index: number;
858
+
859
+ const cache = this._serializeCache;
860
+ if (cache && cache.playerId === playerId && clock >= cache.resultingClock) {
861
+ chits = { ...cache.chits };
862
+ subTurns = cache.subTurns ? { ...cache.subTurns } : undefined;
863
+ log = cache.log ? { ...cache.log } : undefined;
864
+ resultingClock = cache.resultingClock;
865
+ index = cache.nextIndex;
866
+ } else {
867
+ // Diff-replay: seed with the initial locked snapshot and merge every flush diff
868
+ // up to (but not including) the target clock.
869
+ chits = { ...this.lockedChitStates };
870
+ subTurns = undefined;
871
+ log = undefined;
872
+ resultingClock = -1;
873
+ index = 0;
842
874
  }
843
- let subTurns: { [turnId: string]: ClockDetails } | undefined = undefined;
844
875
 
845
- // eslint-disable-next-line no-constant-condition
846
- while (true) {
876
+ let cacheable = true;
877
+ while (index < this.clockSteps.length) {
847
878
  const clockStep = this.clockSteps[index];
848
- index++;
849
- if (!clockStep) {
850
- break;
851
- }
852
-
853
- if (clockStep.startClock >= clock) {
854
- break;
855
- }
879
+ if (clockStep.startClock >= clock) break;
856
880
 
857
881
  if (clockStep instanceof FlushClockStep) {
858
882
  subTurns = undefined;
859
- chits = { ...clockStep.state };
883
+ Object.assign(chits, clockStep.state);
860
884
  resultingClock = clockStep.endClock();
885
+ if (clockStep.log) {
886
+ log = { message: clockStep.log, clock: clockStep.startClock };
887
+ }
888
+ index++;
861
889
  } else if (clockStep instanceof SubTurnsClockStep) {
862
890
  subTurns = {};
863
891
  resultingClock = clockStep.startClock;
864
892
  let remainingClocksToSpend = clock - clockStep.startClock;
865
893
  for (const turn of clockStep.visibleTurns(playerId)) {
866
894
  const time = Math.max(remainingClocksToSpend, 0);
867
- if (time <= 0) {
868
- break;
869
- }
895
+ if (time <= 0) break;
870
896
 
871
- // we are going forward so we never want to have a turn go backwards. ever.
897
+ // we are going forward so we never want to have a turn go backwards. ever.
872
898
  const serialized = turn.serialize(playerId, time);
873
899
  Object.assign(chits, serialized.chits);
874
900
 
@@ -876,13 +902,35 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
876
902
  remainingClocksToSpend -= serialized.clockDetails.clock;
877
903
  subTurns[turn.id] = serialized.clockDetails;
878
904
  if (serialized.log) {
879
- log = serialized.log;
880
- log.clock += clockStep.startClock;
905
+ log = { message: serialized.log.message, clock: serialized.log.clock + clockStep.startClock };
881
906
  }
882
907
  }
908
+ // We can only advance `index` past this step (and cache from here) if the
909
+ // requested `clock` consumed this step's *entire* extent — i.e. every visible
910
+ // sub-turn was asked for at least its full clock time. Otherwise a future
911
+ // request at a higher `clock` needs to re-ask the sub-turn for more time,
912
+ // which means re-processing this same step.
913
+ if (clock < clockStep.endClock(playerId)) {
914
+ cacheable = false;
915
+ break;
916
+ }
917
+ index++;
918
+ } else {
919
+ index++;
883
920
  }
884
921
  }
885
922
 
923
+ if (cacheable) {
924
+ this._serializeCache = {
925
+ playerId,
926
+ nextIndex: index,
927
+ chits: { ...chits },
928
+ subTurns: subTurns ? { ...subTurns } : undefined,
929
+ log: log ? { ...log } : undefined,
930
+ resultingClock: resultingClock === -1 ? clock : resultingClock,
931
+ };
932
+ }
933
+
886
934
  return {
887
935
  log,
888
936
  chits,
@@ -938,10 +986,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
938
986
  prompt.id = `${this.id} prompt ${this.decisionIndex}`;
939
987
  prompt.clock = this.clock;
940
988
  prompt.canReset = this.state.hasUserMadeChoiceSinceUserContextChangedOrRng(this.decisionIndex - 1);
941
- this.player.promptStatus.latestPromptMessage = prompt.message;
942
- if (!this.player.promptStatus.latestPromptMessage.length) {
943
- this.player.promptStatus.latestPromptMessage = "No prompt set";
944
- }
989
+ this.setPromptMessage(this.player, prompt.message.length ? prompt.message : "No prompt set");
945
990
 
946
991
  this.flush();
947
992
 
@@ -1006,7 +1051,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1006
1051
  this.state.setOrCreatePromptResponse(this.decisionIndex, resolution);
1007
1052
 
1008
1053
  this.player.promptStatus.latestPromptResponseTime = this.absoluteClock(this.player.id);
1009
- this.player.promptStatus.latestPromptMessage = undefined;
1054
+ this.setPromptMessage(this.player, undefined);
1010
1055
  this.decisionIndex++;
1011
1056
  }
1012
1057
 
@@ -1112,7 +1157,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1112
1157
 
1113
1158
  private cleanUp() {
1114
1159
  if (this.player) {
1115
- this.player.promptStatus.latestPromptMessage = undefined;
1160
+ this.setPromptMessage(this.player, undefined);
1116
1161
  }
1117
1162
  this.completed = true;
1118
1163
  this.flush();
@@ -1202,6 +1247,7 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1202
1247
  this.unresolvedPrompt = undefined;
1203
1248
  this.activeSubTurns = [];
1204
1249
  this.pass++;
1250
+ this.invalidateSerializeCache();
1205
1251
  }
1206
1252
  }
1207
1253
 
@@ -1212,6 +1258,15 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
1212
1258
  type ChitLookup = { [id: string]: Chit };
1213
1259
  type ChitStateLookup = { [id: string]: string };
1214
1260
 
1261
+ type SerializeCache = {
1262
+ playerId: string;
1263
+ nextIndex: number;
1264
+ chits: ChitStateLookup;
1265
+ subTurns?: { [turnId: string]: ClockDetails };
1266
+ log?: { message: string; clock: number };
1267
+ resultingClock: number;
1268
+ };
1269
+
1215
1270
  abstract class ClockStep {
1216
1271
  abstract get startClock(): number;
1217
1272
  abstract endClock(playerId?: string): number;
@@ -20,6 +20,13 @@ export class TurnState {
20
20
 
21
21
  decisions: Decision[] = [];
22
22
 
23
+ /**
24
+ * AI players' plan memory, keyed by player id. Only the root turn state carries it. It rides
25
+ * along with the decisions so a bot that is re-seated after a reload (or in another process)
26
+ * picks up where it left off. Absent when no bot has committed a plan.
27
+ */
28
+ ai?: { [playerId: string]: unknown };
29
+
23
30
  private parentTurnState: TurnState | undefined;
24
31
  private parentTurnIndex = 0;
25
32
 
@@ -120,6 +127,7 @@ export class TurnState {
120
127
  this.playerId = serialized.playerId;
121
128
  this.id = serialized.id;
122
129
  this.createdDate = serialized.createdDate ?? Date.now();
130
+ this.ai = serialized.ai;
123
131
  this.decisions = (serialized.decisions ?? []).map((d: Decision, i: number) => {
124
132
  if (d.type === "turn") {
125
133
  const existing = this.decisions[i];