@spellkave/sdk 0.0.0-bootstrap

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 (144) hide show
  1. package/LICENSE +89 -0
  2. package/README.md +156 -0
  3. package/package.json +65 -0
  4. package/src/binding_rows.ts +186 -0
  5. package/src/connection.ts +964 -0
  6. package/src/core/actor.ts +62 -0
  7. package/src/core/actor_control.ts +193 -0
  8. package/src/core/actor_control_query_methods.ts +101 -0
  9. package/src/core/actor_control_reaction_methods.ts +79 -0
  10. package/src/core/actor_control_sense_methods.ts +81 -0
  11. package/src/core/actor_control_source.ts +57 -0
  12. package/src/core/actor_session_methods.ts +226 -0
  13. package/src/core/binding_drift.ts +301 -0
  14. package/src/core/credential.ts +259 -0
  15. package/src/core/driver_control.ts +54 -0
  16. package/src/core/effective_environment_state.ts +71 -0
  17. package/src/core/factored_manipulation_attempt.ts +158 -0
  18. package/src/core/ids.ts +60 -0
  19. package/src/core/interaction/canonical.ts +15 -0
  20. package/src/core/interaction/fingerprint.ts +118 -0
  21. package/src/core/interaction/index.ts +31 -0
  22. package/src/core/interaction/intent.ts +284 -0
  23. package/src/core/interaction/outcome.ts +67 -0
  24. package/src/core/interaction/rejection_ledger.ts +108 -0
  25. package/src/core/kernel_contract.generated.ts +10 -0
  26. package/src/core/log.ts +23 -0
  27. package/src/core/movement.ts +111 -0
  28. package/src/core/node-io.ts +208 -0
  29. package/src/core/paths.ts +220 -0
  30. package/src/core/profile.ts +270 -0
  31. package/src/core/profiles.ts +9 -0
  32. package/src/core/provenance_buffer.ts +102 -0
  33. package/src/core/readers/_helpers.ts +273 -0
  34. package/src/core/readers/action_description.ts +17 -0
  35. package/src/core/readers/action_economy_events.ts +149 -0
  36. package/src/core/readers/actor_body_swaps.ts +62 -0
  37. package/src/core/readers/actor_snapshot.ts +197 -0
  38. package/src/core/readers/actor_states.ts +163 -0
  39. package/src/core/readers/actors_and_bodies.ts +179 -0
  40. package/src/core/readers/affordance_cue.ts +59 -0
  41. package/src/core/readers/affordance_defaults.ts +158 -0
  42. package/src/core/readers/affordance_group_membership.ts +67 -0
  43. package/src/core/readers/affordance_input.ts +129 -0
  44. package/src/core/readers/affordance_reference.ts +41 -0
  45. package/src/core/readers/apply_consequences.ts +54 -0
  46. package/src/core/readers/audience_trace_presentation.ts +62 -0
  47. package/src/core/readers/bounded_collection.ts +29 -0
  48. package/src/core/readers/bundle_definitions.ts +74 -0
  49. package/src/core/readers/bundle_entities.ts +62 -0
  50. package/src/core/readers/co_location.ts +71 -0
  51. package/src/core/readers/combat_session.ts +124 -0
  52. package/src/core/readers/combat_session_active.ts +44 -0
  53. package/src/core/readers/combat_session_feedback.ts +37 -0
  54. package/src/core/readers/combat_session_grid.ts +117 -0
  55. package/src/core/readers/combat_session_roster.ts +98 -0
  56. package/src/core/readers/combat_session_types.ts +51 -0
  57. package/src/core/readers/condition_deltas.ts +53 -0
  58. package/src/core/readers/container_contents.ts +92 -0
  59. package/src/core/readers/dialogue_guide.ts +99 -0
  60. package/src/core/readers/dialogue_prompt_presentation.ts +90 -0
  61. package/src/core/readers/driver_control.ts +64 -0
  62. package/src/core/readers/entity_art.ts +219 -0
  63. package/src/core/readers/entity_containment.ts +119 -0
  64. package/src/core/readers/equipment.ts +99 -0
  65. package/src/core/readers/intervention_windows.ts +136 -0
  66. package/src/core/readers/inventory_query.ts +145 -0
  67. package/src/core/readers/item_detail.ts +198 -0
  68. package/src/core/readers/location_snapshot.ts +216 -0
  69. package/src/core/readers/manifest_apply_provenance.ts +32 -0
  70. package/src/core/readers/manifest_export.ts +81 -0
  71. package/src/core/readers/manipulation_context.ts +475 -0
  72. package/src/core/readers/map_layers.ts +49 -0
  73. package/src/core/readers/metadata_rows.ts +56 -0
  74. package/src/core/readers/object_state.ts +124 -0
  75. package/src/core/readers/observer_knowledge.ts +41 -0
  76. package/src/core/readers/observer_place_knowledge.ts +37 -0
  77. package/src/core/readers/observer_trace_knowledge.ts +45 -0
  78. package/src/core/readers/outcome_template.ts +41 -0
  79. package/src/core/readers/place_topology.ts +109 -0
  80. package/src/core/readers/reaction_options.ts +156 -0
  81. package/src/core/readers/resource_deltas.ts +47 -0
  82. package/src/core/readers/scene.ts +275 -0
  83. package/src/core/readers/seats.ts +33 -0
  84. package/src/core/readers/self.ts +245 -0
  85. package/src/core/readers/self_capabilities.ts +159 -0
  86. package/src/core/readers/self_economy.ts +101 -0
  87. package/src/core/readers/self_economy_budget.ts +93 -0
  88. package/src/core/readers/self_evaluations.ts +128 -0
  89. package/src/core/readers/self_identity.ts +104 -0
  90. package/src/core/readers/sense_context.ts +112 -0
  91. package/src/core/readers/session.ts +207 -0
  92. package/src/core/readers/session_detail.ts +211 -0
  93. package/src/core/readers/session_status.ts +68 -0
  94. package/src/core/readers/spatial_environment_state.ts +74 -0
  95. package/src/core/readers/spatial_niche_attachments.ts +28 -0
  96. package/src/core/readers/substrate_definitions.ts +27 -0
  97. package/src/core/readers/suggest_next_action.ts +72 -0
  98. package/src/core/readers/surface_membership.ts +78 -0
  99. package/src/core/readers/tag_reads.ts +54 -0
  100. package/src/core/readers/trace_query.ts +120 -0
  101. package/src/core/readers/trace_response.ts +80 -0
  102. package/src/core/readers/traces.ts +124 -0
  103. package/src/core/readers/travel_session.ts +88 -0
  104. package/src/core/readers/turn_state.ts +34 -0
  105. package/src/core/readers/world_events.ts +43 -0
  106. package/src/core/readers/world_status.ts +63 -0
  107. package/src/core/reducers/manipulation_args.ts +239 -0
  108. package/src/core/reducers/manipulation_receipt.ts +66 -0
  109. package/src/core/reducers/r_actor_wake_up.ts +32 -0
  110. package/src/core/reducers/r_inscribe_trace.ts +109 -0
  111. package/src/core/reducers/r_manipulate.ts +163 -0
  112. package/src/core/reducers/r_move.ts +155 -0
  113. package/src/core/reducers/r_react.ts +143 -0
  114. package/src/core/reducers/r_release_claim.ts +81 -0
  115. package/src/core/reducers/r_sense.ts +84 -0
  116. package/src/core/reducers/r_session_close.ts +130 -0
  117. package/src/core/reducers/r_session_move.ts +116 -0
  118. package/src/core/reducers/r_session_open.ts +91 -0
  119. package/src/core/reducers/session_lookup.ts +64 -0
  120. package/src/core/reducers/tick.ts +65 -0
  121. package/src/core/reducers/trace_lookup.ts +29 -0
  122. package/src/core/reducers/transport.ts +84 -0
  123. package/src/core/resolve.ts +228 -0
  124. package/src/core/shape_telemetry.ts +146 -0
  125. package/src/core/snapshot_rows.ts +109 -0
  126. package/src/core/tick_cadence.ts +61 -0
  127. package/src/core/types.ts +501 -0
  128. package/src/core/watch_provenance.ts +113 -0
  129. package/src/core/world-contract/classify.ts +38 -0
  130. package/src/core/world-contract/index.ts +12 -0
  131. package/src/core/world-contract/normalise.ts +574 -0
  132. package/src/core/world-contract/runtime.ts +144 -0
  133. package/src/core/world-contract/served.ts +173 -0
  134. package/src/core/world-contract/strict-reducers.ts +14 -0
  135. package/src/core/world-contract/typetext.ts +94 -0
  136. package/src/core/world_time.ts +22 -0
  137. package/src/index.ts +262 -0
  138. package/src/manifest-apply.ts +497 -0
  139. package/src/provenance.ts +568 -0
  140. package/src/reader-manifest.ts +338 -0
  141. package/src/readers.ts +392 -0
  142. package/src/replay.ts +515 -0
  143. package/src/watch-buffer.ts +438 -0
  144. package/src/world-events/builder.ts +1042 -0
@@ -0,0 +1,438 @@
1
+ // Client-side rain-radar buffer over an already-authorized SnapshotDb.
2
+ //
3
+ // Bootstrap from the live subscription at connect time (now). Fold later
4
+ // onUpdate snapshots into a bounded tick-indexed ring. Pause/scrub/play
5
+ // only move a VIEW cursor — the world keeps ticking. Reconnect discards.
6
+ //
7
+ // Pattern (TTL cap, rebuild from current perception, no history hydrate)
8
+ // matches npc-brains combat-picture / perceived-map, but this module reads
9
+ // visible_* tables for an observer/DM see-as grant. Do not import
10
+ // @spellkave/npc-brains.
11
+
12
+ import type { VisibleCapabilityRow } from "./binding_rows";
13
+ import {
14
+ asString,
15
+ buildEntityDescriptionMap,
16
+ buildEntityFactionMap,
17
+ buildEntityNameMap,
18
+ buildEntitySummaryMap,
19
+ optNumber,
20
+ rows,
21
+ tagString,
22
+ } from "./core/readers/_helpers";
23
+ import { buildEntityConditionsMap } from "./core/readers/actor_snapshot";
24
+ import { readActorIdentityBindings, readActorPrincipals } from "./core/readers/actors_and_bodies";
25
+ import {
26
+ buildPublicArtIndex,
27
+ type EntityArt,
28
+ lookupPublicEntityArt,
29
+ } from "./core/readers/entity_art";
30
+ import { readEntityIntStates } from "./core/readers/object_state";
31
+ import { readRecentEvents } from "./core/readers/world_events";
32
+ import { readWorldStatus } from "./core/readers/world_status";
33
+ import type { SnapshotDb } from "./replay";
34
+
35
+ /** Forget frames older than this many ticks. Same order as combat-picture TTL. */
36
+ export const WATCH_BUFFER_CAP = 600;
37
+
38
+ /**
39
+ * Tables a maps/observer connection must subscribe in addition to seat
40
+ * catalogs. Union with CONNECTION_BASELINE at connect(); never include
41
+ * FILTERED_SUBSCRIPTION_TABLES.
42
+ */
43
+ export const WATCH_BUFFER_REQUIRED_TABLES = [
44
+ "visible_actor_spatial_location",
45
+ "actor",
46
+ "visible_actor_identity",
47
+ "entity",
48
+ "visible_entity_tag",
49
+ "visible_entity_tag_coverage",
50
+ "visible_manifest_authored_entity",
51
+ "visible_manifest_authored_entity_coverage",
52
+ "visible_object_state",
53
+ "visible_target_condition",
54
+ "visible_world_event",
55
+ "visible_capability",
56
+ "resource_definition",
57
+ "visible_entity_containment",
58
+ "visible_entity_equipment_slot",
59
+ "visible_entity_location",
60
+ "public_metadata_attachment",
61
+ "visible_metadata_attachment",
62
+ "entity_description",
63
+ ] as const;
64
+
65
+ export interface WatchActorState {
66
+ state_id: string;
67
+ display_name: string;
68
+ value: string;
69
+ }
70
+
71
+ export interface WatchActorCondition {
72
+ id: string;
73
+ stack_count: number;
74
+ }
75
+
76
+ export interface WatchActor {
77
+ entityId: string;
78
+ actorId: string | null;
79
+ name: string;
80
+ placeNodeId: string;
81
+ faction: string | null;
82
+ description: string | null;
83
+ conditions: WatchActorCondition[];
84
+ states: WatchActorState[];
85
+ /** Public subject art (ADR-0073 <bundle>.art.image), when authored. */
86
+ art: EntityArt | null;
87
+ }
88
+
89
+ export interface WatchEvent {
90
+ id: string;
91
+ tick: number;
92
+ kind: string;
93
+ summary?: string;
94
+ }
95
+
96
+ export interface WatchItem {
97
+ entityId: string;
98
+ name: string;
99
+ placeNodeId: string;
100
+ holderEntityId: string | null;
101
+ holderName: string | null;
102
+ /** Containment slot ("" = loose carriage; e.g. "core/main_hand" when
103
+ * equipped). Leaf-humanized by callers for display — the readable
104
+ * equipment_slot label lives in a table the watch buffer does not
105
+ * subscribe (sk-jay0.4.4.3). */
106
+ slotId: string;
107
+ /** entity_description text for this item, when authored (sk-jay0.4.4.5). */
108
+ description: string | null;
109
+ /** Int object states for this item (same shape as WatchActor.states). */
110
+ states: WatchActorState[];
111
+ /** Instance entity_tag list (author-facing, small). */
112
+ tags: string[];
113
+ /** Public subject art (ADR-0073), instance or definition fallback. */
114
+ art: EntityArt | null;
115
+ }
116
+
117
+ export interface WatchFrame {
118
+ tick: number;
119
+ actors: WatchActor[];
120
+ events: WatchEvent[];
121
+ items: WatchItem[];
122
+ }
123
+
124
+ export type WatchCursor = { kind: "live" } | { kind: "paused"; tick: number };
125
+
126
+ export function readWatchTick(db: SnapshotDb): number {
127
+ return readWorldStatus(db)?.tick ?? 0;
128
+ }
129
+
130
+ function isItemKind(kind: string): boolean {
131
+ const k = kind.toLowerCase();
132
+ return k === "item" || k.endsWith(".item");
133
+ }
134
+
135
+ /** Current bodies of the self-only identity bindings, including role presences.
136
+ * Requires actor + visible_actor_identity in this caller's subscription. */
137
+ export function readWatchOwnBodies(db: SnapshotDb): string[] {
138
+ const actors = new Set(readActorIdentityBindings(db).map((row) => String(row.actor_id)));
139
+ return readActorPrincipals(db)
140
+ .filter((row) => actors.has(String(row.actor_id)) && String(row.current_body) !== "0")
141
+ .map((row) => String(row.current_body));
142
+ }
143
+
144
+ /** Live oversight on the caller's own bodies. Scalar depth remains a migration bridge. */
145
+ export function hasOversightGrant(db: SnapshotDb, ownBodies: readonly string[] = []): boolean {
146
+ const own = new Set(ownBodies);
147
+ const now = readWorldStatus(db)?.tick;
148
+ for (const row of rows<VisibleCapabilityRow>(db, "visible_capability")) {
149
+ if (!own.has(String(row.entityId))) continue;
150
+ const expires = optNumber(row.expiresAtTick);
151
+ if (expires !== undefined && (now === undefined || expires <= now)) continue;
152
+ const extent = asString(row.extentRef);
153
+ const elevation = tagString(row.elevationClass).toLowerCase();
154
+ if (
155
+ extent !== "" &&
156
+ (row.capabilityId === "frontier.read_internal" || elevation === "internal")
157
+ )
158
+ return true;
159
+ }
160
+ return false;
161
+ }
162
+
163
+ export function watchOverlayAdmitted(db: SnapshotDb, ownBodies: readonly string[] = []): boolean {
164
+ return hasOversightGrant(db, ownBodies);
165
+ }
166
+
167
+ export function projectWatchFrame(db: SnapshotDb, tick: number): WatchFrame {
168
+ const names = buildEntityNameMap(db);
169
+ const descriptions = buildEntityDescriptionMap(db);
170
+ const factions = buildEntityFactionMap(db);
171
+ const conditions = buildEntityConditionsMap(db);
172
+ const bodyToActor = new Map<string, string>();
173
+ for (const principal of readActorPrincipals(db)) {
174
+ bodyToActor.set(String(principal.current_body), String(principal.actor_id));
175
+ }
176
+
177
+ const summaries = buildEntitySummaryMap(db);
178
+ // One art index per projection; per-entity lookups hit the cache.
179
+ const artIndex = buildPublicArtIndex(db);
180
+
181
+ const actors: WatchActor[] = [];
182
+ const seen = new Set<string>();
183
+ for (const row of rows<Record<string, unknown>>(db, "visible_actor_spatial_location")) {
184
+ const entityId =
185
+ row.entityId !== undefined && row.entityId !== null
186
+ ? String(row.entityId)
187
+ : row.entity_id !== undefined && row.entity_id !== null
188
+ ? String(row.entity_id)
189
+ : "";
190
+ if (entityId === "" || seen.has(entityId)) continue;
191
+ const placeNodeId =
192
+ row.placeNodeId !== undefined && row.placeNodeId !== null
193
+ ? String(row.placeNodeId)
194
+ : row.place_node_id !== undefined && row.place_node_id !== null
195
+ ? String(row.place_node_id)
196
+ : "";
197
+ if (placeNodeId === "") continue;
198
+ seen.add(entityId);
199
+ const actorConditions = (conditions.get(entityId) ?? []).map((c) => ({
200
+ id: c.condition_definition_id,
201
+ stack_count: c.stack_count,
202
+ }));
203
+ const states = readEntityIntStates(db, entityId).map((s) => ({
204
+ state_id: s.stateId,
205
+ display_name: s.stateId,
206
+ value: String(s.value),
207
+ }));
208
+ actors.push({
209
+ entityId,
210
+ actorId: bodyToActor.get(entityId) ?? null,
211
+ name: names.get(entityId) ?? entityId,
212
+ placeNodeId,
213
+ faction: factions.get(entityId) ?? null,
214
+ description: descriptions.get(entityId) || null,
215
+ conditions: actorConditions,
216
+ states,
217
+ art:
218
+ lookupPublicEntityArt(artIndex, entityId, summaries.get(entityId)?.entity_def_id ?? "") ??
219
+ null,
220
+ });
221
+ }
222
+ actors.sort((a, b) => a.entityId.localeCompare(b.entityId));
223
+
224
+ // Per-entity tags (author-facing) — one pass, reused by both item loops.
225
+ const tagsByEntity = new Map<string, string[]>();
226
+ for (const row of rows<Record<string, unknown>>(db, "visible_entity_tag")) {
227
+ const entityId =
228
+ row.entityId !== undefined && row.entityId !== null
229
+ ? String(row.entityId)
230
+ : row.entity_id !== undefined && row.entity_id !== null
231
+ ? String(row.entity_id)
232
+ : "";
233
+ const tag = row.tag !== undefined && row.tag !== null ? String(row.tag) : "";
234
+ if (entityId === "" || tag === "") continue;
235
+ const list = tagsByEntity.get(entityId) ?? [];
236
+ list.push(tag);
237
+ tagsByEntity.set(entityId, list);
238
+ }
239
+ // Equipped items live in their own table (entity_equipment_slot: wearer
240
+ // entity_id + slot_id + equipped_entity_id), not in containment slot_id
241
+ // (machine ports only). Keyed by the EQUIPPED item so the items loop can
242
+ // override loose carriage (sk-jay0.4.4.3).
243
+ const equippedSlot = new Map<string, string>();
244
+ for (const row of rows<Record<string, unknown>>(db, "visible_entity_equipment_slot")) {
245
+ const equippedEntityId =
246
+ row.equippedEntityId !== undefined && row.equippedEntityId !== null
247
+ ? String(row.equippedEntityId)
248
+ : row.equipped_entity_id !== undefined && row.equipped_entity_id !== null
249
+ ? String(row.equipped_entity_id)
250
+ : "";
251
+ const slot =
252
+ row.slotId !== undefined && row.slotId !== null
253
+ ? String(row.slotId)
254
+ : row.slot_id !== undefined && row.slot_id !== null
255
+ ? String(row.slot_id)
256
+ : "";
257
+ if (equippedEntityId !== "" && slot !== "") equippedSlot.set(equippedEntityId, slot);
258
+ }
259
+ const actorPlace = new Map<string, string>();
260
+ for (const actor of actors) actorPlace.set(actor.entityId, actor.placeNodeId);
261
+ const groundPlace = new Map<string, string>();
262
+ for (const row of rows<Record<string, unknown>>(db, "visible_entity_location")) {
263
+ const entityId =
264
+ row.entityId !== undefined && row.entityId !== null
265
+ ? String(row.entityId)
266
+ : row.entity_id !== undefined && row.entity_id !== null
267
+ ? String(row.entity_id)
268
+ : "";
269
+ const placeNodeId =
270
+ row.placeNodeId !== undefined && row.placeNodeId !== null
271
+ ? String(row.placeNodeId)
272
+ : row.place_node_id !== undefined && row.place_node_id !== null
273
+ ? String(row.place_node_id)
274
+ : "";
275
+ if (entityId !== "" && placeNodeId !== "") groundPlace.set(entityId, placeNodeId);
276
+ }
277
+ const items: WatchItem[] = [];
278
+ const seenItem = new Set<string>();
279
+ for (const row of rows<Record<string, unknown>>(db, "visible_entity_containment")) {
280
+ const entityId =
281
+ row.entityId !== undefined && row.entityId !== null
282
+ ? String(row.entityId)
283
+ : row.entity_id !== undefined && row.entity_id !== null
284
+ ? String(row.entity_id)
285
+ : "";
286
+ const containerId =
287
+ row.containerId !== undefined && row.containerId !== null
288
+ ? String(row.containerId)
289
+ : row.container_id !== undefined && row.container_id !== null
290
+ ? String(row.container_id)
291
+ : "";
292
+ const slotId =
293
+ row.slotId !== undefined && row.slotId !== null
294
+ ? String(row.slotId)
295
+ : row.slot_id !== undefined && row.slot_id !== null
296
+ ? String(row.slot_id)
297
+ : "";
298
+ if (entityId === "" || seenItem.has(entityId)) continue;
299
+ const summary = summaries.get(entityId);
300
+ if (summary === undefined || !isItemKind(summary.kind)) continue;
301
+ const placeNodeId =
302
+ actorPlace.get(containerId) ??
303
+ groundPlace.get(containerId) ??
304
+ groundPlace.get(entityId) ??
305
+ "";
306
+ if (placeNodeId === "") continue;
307
+ seenItem.add(entityId);
308
+ const holder = summaries.get(containerId);
309
+ items.push({
310
+ entityId,
311
+ name: summary.name || entityId,
312
+ placeNodeId,
313
+ holderEntityId: containerId,
314
+ holderName: holder?.name ?? containerId,
315
+ slotId: equippedSlot.get(entityId) ?? slotId,
316
+ description: descriptions.get(entityId) || null,
317
+ states: readEntityIntStates(db, entityId).map((s) => ({
318
+ state_id: s.stateId,
319
+ display_name: s.stateId,
320
+ value: String(s.value),
321
+ })),
322
+ tags: tagsByEntity.get(entityId) ?? [],
323
+ art:
324
+ lookupPublicEntityArt(artIndex, entityId, summaries.get(entityId)?.entity_def_id ?? "") ??
325
+ null,
326
+ });
327
+ }
328
+ for (const [entityId, placeNodeId] of groundPlace) {
329
+ if (seenItem.has(entityId)) continue;
330
+ const summary = summaries.get(entityId);
331
+ if (summary === undefined || !isItemKind(summary.kind)) continue;
332
+ seenItem.add(entityId);
333
+ items.push({
334
+ entityId,
335
+ name: summary.name || entityId,
336
+ placeNodeId,
337
+ holderEntityId: null,
338
+ holderName: null,
339
+ slotId: "",
340
+ description: descriptions.get(entityId) || null,
341
+ states: readEntityIntStates(db, entityId).map((s) => ({
342
+ state_id: s.stateId,
343
+ display_name: s.stateId,
344
+ value: String(s.value),
345
+ })),
346
+ tags: tagsByEntity.get(entityId) ?? [],
347
+ art:
348
+ lookupPublicEntityArt(artIndex, entityId, summaries.get(entityId)?.entity_def_id ?? "") ??
349
+ null,
350
+ });
351
+ }
352
+ items.sort((a, b) => a.entityId.localeCompare(b.entityId));
353
+
354
+ const events: WatchEvent[] = readRecentEvents(db, 64)
355
+ .filter((event) => event.tick === tick)
356
+ .map((event) => {
357
+ const out: WatchEvent = { id: event.id, tick: event.tick, kind: event.kind };
358
+ if (event.summary !== undefined) out.summary = event.summary;
359
+ return out;
360
+ });
361
+
362
+ return { tick, actors, events, items };
363
+ }
364
+
365
+ export class WatchBuffer {
366
+ private readonly cap: number;
367
+ private readonly frames: WatchFrame[] = [];
368
+ private mode: WatchCursor = { kind: "live" };
369
+
370
+ constructor(cap = WATCH_BUFFER_CAP) {
371
+ this.cap = Math.max(1, cap);
372
+ }
373
+
374
+ bootstrap(db: SnapshotDb, tick = readWatchTick(db)): WatchFrame {
375
+ this.frames.length = 0;
376
+ this.mode = { kind: "live" };
377
+ const frame = projectWatchFrame(db, tick);
378
+ this.frames.push(frame);
379
+ return frame;
380
+ }
381
+
382
+ observe(db: SnapshotDb, tick = readWatchTick(db)): WatchFrame {
383
+ const frame = projectWatchFrame(db, tick);
384
+ const last = this.frames[this.frames.length - 1];
385
+ if (last !== undefined && last.tick === tick) {
386
+ this.frames[this.frames.length - 1] = frame;
387
+ } else {
388
+ this.frames.push(frame);
389
+ while (this.frames.length > this.cap) this.frames.shift();
390
+ }
391
+ return frame;
392
+ }
393
+
394
+ pause(): void {
395
+ const tick = this.latestTick();
396
+ if (tick === null) return;
397
+ this.mode = { kind: "paused", tick };
398
+ }
399
+
400
+ play(): void {
401
+ this.mode = { kind: "live" };
402
+ }
403
+
404
+ scrub(tick: number): void {
405
+ const latest = this.latestTick();
406
+ const oldest = this.oldestTick();
407
+ if (latest === null || oldest === null) return;
408
+ const clamped = Math.min(latest, Math.max(oldest, tick));
409
+ this.mode = { kind: "paused", tick: clamped };
410
+ }
411
+
412
+ cursor(): WatchCursor {
413
+ return this.mode;
414
+ }
415
+
416
+ latestTick(): number | null {
417
+ return this.frames[this.frames.length - 1]?.tick ?? null;
418
+ }
419
+
420
+ oldestTick(): number | null {
421
+ return this.frames[0]?.tick ?? null;
422
+ }
423
+
424
+ frameAtCursor(): WatchFrame | null {
425
+ if (this.frames.length === 0) return null;
426
+ if (this.mode.kind === "live") return this.frames[this.frames.length - 1] ?? null;
427
+ return this.frameAt(this.mode.tick);
428
+ }
429
+
430
+ frameAt(tick: number): WatchFrame | null {
431
+ let found: WatchFrame | null = null;
432
+ for (const frame of this.frames) {
433
+ if (frame.tick <= tick) found = frame;
434
+ if (frame.tick === tick) return frame;
435
+ }
436
+ return found;
437
+ }
438
+ }