@spellkave/sdk 0.0.0-stage → 0.1.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.
- package/LICENSE +89 -0
- package/README.md +155 -2
- package/package.json +63 -4
- package/src/binding_rows.ts +186 -0
- package/src/connection.ts +964 -0
- package/src/core/actor.ts +62 -0
- package/src/core/actor_control.ts +193 -0
- package/src/core/actor_control_query_methods.ts +101 -0
- package/src/core/actor_control_reaction_methods.ts +79 -0
- package/src/core/actor_control_sense_methods.ts +81 -0
- package/src/core/actor_control_source.ts +57 -0
- package/src/core/actor_session_methods.ts +226 -0
- package/src/core/binding_drift.ts +301 -0
- package/src/core/credential.ts +259 -0
- package/src/core/driver_control.ts +54 -0
- package/src/core/effective_environment_state.ts +71 -0
- package/src/core/factored_manipulation_attempt.ts +158 -0
- package/src/core/ids.ts +60 -0
- package/src/core/interaction/canonical.ts +15 -0
- package/src/core/interaction/fingerprint.ts +118 -0
- package/src/core/interaction/index.ts +31 -0
- package/src/core/interaction/intent.ts +284 -0
- package/src/core/interaction/outcome.ts +67 -0
- package/src/core/interaction/rejection_ledger.ts +108 -0
- package/src/core/kernel_contract.generated.ts +10 -0
- package/src/core/log.ts +23 -0
- package/src/core/movement.ts +111 -0
- package/src/core/node-io.ts +208 -0
- package/src/core/paths.ts +220 -0
- package/src/core/profile.ts +270 -0
- package/src/core/profiles.ts +9 -0
- package/src/core/provenance_buffer.ts +102 -0
- package/src/core/readers/_helpers.ts +273 -0
- package/src/core/readers/action_description.ts +17 -0
- package/src/core/readers/action_economy_events.ts +149 -0
- package/src/core/readers/actor_body_swaps.ts +62 -0
- package/src/core/readers/actor_snapshot.ts +197 -0
- package/src/core/readers/actor_states.ts +163 -0
- package/src/core/readers/actors_and_bodies.ts +179 -0
- package/src/core/readers/affordance_cue.ts +59 -0
- package/src/core/readers/affordance_defaults.ts +158 -0
- package/src/core/readers/affordance_group_membership.ts +67 -0
- package/src/core/readers/affordance_input.ts +129 -0
- package/src/core/readers/affordance_reference.ts +41 -0
- package/src/core/readers/apply_consequences.ts +54 -0
- package/src/core/readers/audience_trace_presentation.ts +62 -0
- package/src/core/readers/bounded_collection.ts +29 -0
- package/src/core/readers/bundle_definitions.ts +74 -0
- package/src/core/readers/bundle_entities.ts +62 -0
- package/src/core/readers/co_location.ts +71 -0
- package/src/core/readers/combat_session.ts +124 -0
- package/src/core/readers/combat_session_active.ts +44 -0
- package/src/core/readers/combat_session_feedback.ts +37 -0
- package/src/core/readers/combat_session_grid.ts +117 -0
- package/src/core/readers/combat_session_roster.ts +98 -0
- package/src/core/readers/combat_session_types.ts +51 -0
- package/src/core/readers/condition_deltas.ts +53 -0
- package/src/core/readers/container_contents.ts +92 -0
- package/src/core/readers/dialogue_guide.ts +99 -0
- package/src/core/readers/dialogue_prompt_presentation.ts +90 -0
- package/src/core/readers/driver_control.ts +64 -0
- package/src/core/readers/entity_art.ts +219 -0
- package/src/core/readers/entity_containment.ts +119 -0
- package/src/core/readers/equipment.ts +99 -0
- package/src/core/readers/intervention_windows.ts +136 -0
- package/src/core/readers/inventory_query.ts +145 -0
- package/src/core/readers/item_detail.ts +198 -0
- package/src/core/readers/location_snapshot.ts +216 -0
- package/src/core/readers/manifest_apply_provenance.ts +32 -0
- package/src/core/readers/manifest_export.ts +81 -0
- package/src/core/readers/manipulation_context.ts +475 -0
- package/src/core/readers/map_layers.ts +49 -0
- package/src/core/readers/metadata_rows.ts +56 -0
- package/src/core/readers/object_state.ts +124 -0
- package/src/core/readers/observer_knowledge.ts +41 -0
- package/src/core/readers/observer_place_knowledge.ts +37 -0
- package/src/core/readers/observer_trace_knowledge.ts +45 -0
- package/src/core/readers/outcome_template.ts +41 -0
- package/src/core/readers/place_topology.ts +109 -0
- package/src/core/readers/reaction_options.ts +156 -0
- package/src/core/readers/resource_deltas.ts +47 -0
- package/src/core/readers/scene.ts +275 -0
- package/src/core/readers/seats.ts +33 -0
- package/src/core/readers/self.ts +245 -0
- package/src/core/readers/self_capabilities.ts +159 -0
- package/src/core/readers/self_economy.ts +101 -0
- package/src/core/readers/self_economy_budget.ts +93 -0
- package/src/core/readers/self_evaluations.ts +128 -0
- package/src/core/readers/self_identity.ts +104 -0
- package/src/core/readers/sense_context.ts +112 -0
- package/src/core/readers/session.ts +207 -0
- package/src/core/readers/session_detail.ts +211 -0
- package/src/core/readers/session_status.ts +68 -0
- package/src/core/readers/spatial_environment_state.ts +74 -0
- package/src/core/readers/spatial_niche_attachments.ts +28 -0
- package/src/core/readers/substrate_definitions.ts +27 -0
- package/src/core/readers/suggest_next_action.ts +72 -0
- package/src/core/readers/surface_membership.ts +78 -0
- package/src/core/readers/tag_reads.ts +54 -0
- package/src/core/readers/trace_query.ts +120 -0
- package/src/core/readers/trace_response.ts +80 -0
- package/src/core/readers/traces.ts +124 -0
- package/src/core/readers/travel_session.ts +88 -0
- package/src/core/readers/turn_state.ts +34 -0
- package/src/core/readers/world_events.ts +43 -0
- package/src/core/readers/world_status.ts +63 -0
- package/src/core/reducers/manipulation_args.ts +239 -0
- package/src/core/reducers/manipulation_receipt.ts +66 -0
- package/src/core/reducers/r_actor_wake_up.ts +32 -0
- package/src/core/reducers/r_inscribe_trace.ts +109 -0
- package/src/core/reducers/r_manipulate.ts +163 -0
- package/src/core/reducers/r_move.ts +155 -0
- package/src/core/reducers/r_react.ts +143 -0
- package/src/core/reducers/r_release_claim.ts +81 -0
- package/src/core/reducers/r_sense.ts +84 -0
- package/src/core/reducers/r_session_close.ts +130 -0
- package/src/core/reducers/r_session_move.ts +116 -0
- package/src/core/reducers/r_session_open.ts +91 -0
- package/src/core/reducers/session_lookup.ts +64 -0
- package/src/core/reducers/tick.ts +65 -0
- package/src/core/reducers/trace_lookup.ts +29 -0
- package/src/core/reducers/transport.ts +84 -0
- package/src/core/resolve.ts +228 -0
- package/src/core/shape_telemetry.ts +146 -0
- package/src/core/snapshot_rows.ts +109 -0
- package/src/core/tick_cadence.ts +61 -0
- package/src/core/types.ts +501 -0
- package/src/core/watch_provenance.ts +113 -0
- package/src/core/world-contract/classify.ts +38 -0
- package/src/core/world-contract/index.ts +12 -0
- package/src/core/world-contract/normalise.ts +574 -0
- package/src/core/world-contract/runtime.ts +144 -0
- package/src/core/world-contract/served.ts +173 -0
- package/src/core/world-contract/strict-reducers.ts +14 -0
- package/src/core/world-contract/typetext.ts +94 -0
- package/src/core/world_time.ts +22 -0
- package/src/index.ts +262 -0
- package/src/manifest-apply.ts +497 -0
- package/src/provenance.ts +568 -0
- package/src/reader-manifest.ts +338 -0
- package/src/readers.ts +392 -0
- package/src/replay.ts +515 -0
- package/src/watch-buffer.ts +438 -0
- package/src/world-events/builder.ts +1042 -0
package/src/replay.ts
ADDED
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
// Pure snapshot replay helpers.
|
|
2
|
+
//
|
|
3
|
+
// This entry intentionally has no live SpacetimeDB connection import and no
|
|
4
|
+
// reducer surface. Reviewer/demo apps can replay captured rows without pulling
|
|
5
|
+
// in connection construction or mutation-capable handles.
|
|
6
|
+
|
|
7
|
+
interface TableHandle {
|
|
8
|
+
iter(): Iterable<Record<string, unknown>>;
|
|
9
|
+
/** Optional host delivery context and inserted row; snapshot-only hosts may omit both. */
|
|
10
|
+
onInsert?: (cb: (context?: unknown, row?: unknown) => void) => void;
|
|
11
|
+
removeOnInsert?: (cb: (context?: unknown, row?: unknown) => void) => void;
|
|
12
|
+
onDelete?: (cb: () => void) => void;
|
|
13
|
+
removeOnDelete?: (cb: () => void) => void;
|
|
14
|
+
onUpdate?: (cb: () => void) => void;
|
|
15
|
+
removeOnUpdate?: (cb: () => void) => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SnapshotDb {
|
|
19
|
+
[accessor: string]: TableHandle | undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type SnapshotFixtureTables = Record<string, Iterable<Record<string, unknown>>>;
|
|
23
|
+
|
|
24
|
+
export interface SnapshotCaptureFrame {
|
|
25
|
+
kind: "spellkave.snapshot_frame";
|
|
26
|
+
version: 1;
|
|
27
|
+
/** Logical world tick represented by this checkpoint. */
|
|
28
|
+
tick: number;
|
|
29
|
+
/** Binding-layer table rows, keyed by generated table accessor name. */
|
|
30
|
+
tables: Record<string, Record<string, unknown>[]>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface WorldEventRow {
|
|
34
|
+
id: string;
|
|
35
|
+
tick: number;
|
|
36
|
+
kind: string;
|
|
37
|
+
summary?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ── Portable UI recordings ───────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A deliberately small, host-neutral envelope for a bounded client-side
|
|
44
|
+
* recording. Surface adapters own the payload schema: this module only owns
|
|
45
|
+
* retention, cursor semantics, JSON safety and the outer version marker.
|
|
46
|
+
*/
|
|
47
|
+
export const RECORDING_ENVELOPE_KIND = "spellkave.recording" as const;
|
|
48
|
+
export const RECORDING_ENVELOPE_VERSION = 2 as const;
|
|
49
|
+
|
|
50
|
+
export type JsonPrimitive = string | number | boolean | null;
|
|
51
|
+
export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
|
52
|
+
|
|
53
|
+
export interface RecordingFrame<T extends JsonValue> {
|
|
54
|
+
/** Stable reference for authored scenario transitions. */
|
|
55
|
+
id: string;
|
|
56
|
+
/** Monotonic insertion sequence. It disambiguates equal wall-clock times. */
|
|
57
|
+
sequence: number;
|
|
58
|
+
/** Client wall-clock time for retention and display, never world truth. */
|
|
59
|
+
capturedAt: number;
|
|
60
|
+
payload: T;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Deliberately allowlisted capture context. Never place account or credential data here. */
|
|
64
|
+
export interface RecordingProvenance {
|
|
65
|
+
source: "live" | "legacy" | "fixture";
|
|
66
|
+
build?: string;
|
|
67
|
+
title?: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export type RecordingCursor = { kind: "live" } | { kind: "paused"; sequence: number };
|
|
71
|
+
|
|
72
|
+
export interface RecordingEnvelope<T extends JsonValue> {
|
|
73
|
+
kind: typeof RECORDING_ENVELOPE_KIND;
|
|
74
|
+
version: typeof RECORDING_ENVELOPE_VERSION;
|
|
75
|
+
/** Stable recording identity; scenario layers refer to frame ids beneath it. */
|
|
76
|
+
id: string;
|
|
77
|
+
surface: string;
|
|
78
|
+
capturedAt: number;
|
|
79
|
+
provenance?: RecordingProvenance;
|
|
80
|
+
frames: RecordingFrame<T>[];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface BoundedRecordingOptions {
|
|
84
|
+
/** Maximum retained frames. Must be a positive integer. */
|
|
85
|
+
limit: number;
|
|
86
|
+
/** Optional wall-clock retention window. Omit for count-only retention. */
|
|
87
|
+
maxAgeMs?: number;
|
|
88
|
+
/** Test seam; defaults to Date.now. */
|
|
89
|
+
now?: () => number;
|
|
90
|
+
/** Stable identity to retain across exports. Omit to derive one at first export. */
|
|
91
|
+
id?: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface RecordingExportOptions {
|
|
95
|
+
/** Pins the recording identity when the buffer was constructed without one. */
|
|
96
|
+
id?: string;
|
|
97
|
+
/** Optional, safe capture context for checked-in recordings. */
|
|
98
|
+
provenance?: RecordingProvenance;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A small FIFO timeline. Pausing changes only which retained frame is read;
|
|
103
|
+
* new live frames still enter the buffer, just like the Maps watch radar.
|
|
104
|
+
* Every public payload is JSON-cloned at the boundary so callers cannot
|
|
105
|
+
* mutate the history by retaining a reference.
|
|
106
|
+
*/
|
|
107
|
+
export class BoundedRecording<T extends JsonValue> {
|
|
108
|
+
private readonly limit: number;
|
|
109
|
+
private readonly maxAgeMs: number | undefined;
|
|
110
|
+
private readonly now: () => number;
|
|
111
|
+
private stored: RecordingFrame<T>[] = [];
|
|
112
|
+
private nextSequence = 1;
|
|
113
|
+
private mode: RecordingCursor = { kind: "live" };
|
|
114
|
+
private id: string | undefined;
|
|
115
|
+
|
|
116
|
+
constructor(options: BoundedRecordingOptions) {
|
|
117
|
+
if (!Number.isInteger(options.limit) || options.limit < 1) {
|
|
118
|
+
throw new Error("recording limit must be a positive integer");
|
|
119
|
+
}
|
|
120
|
+
if (
|
|
121
|
+
options.maxAgeMs !== undefined &&
|
|
122
|
+
(!Number.isFinite(options.maxAgeMs) || options.maxAgeMs < 0)
|
|
123
|
+
) {
|
|
124
|
+
throw new Error("recording maxAgeMs must be a non-negative finite number");
|
|
125
|
+
}
|
|
126
|
+
this.limit = options.limit;
|
|
127
|
+
this.maxAgeMs = options.maxAgeMs;
|
|
128
|
+
this.now = options.now ?? (() => Date.now());
|
|
129
|
+
if (options.id !== undefined && !isStableId(options.id)) {
|
|
130
|
+
throw new Error("recording id must be a bounded stable identifier");
|
|
131
|
+
}
|
|
132
|
+
this.id = options.id;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
record(payload: T): RecordingFrame<T> {
|
|
136
|
+
const sequence = this.nextSequence++;
|
|
137
|
+
const capturedAt = this.now();
|
|
138
|
+
const frame: RecordingFrame<T> = {
|
|
139
|
+
id: `frame_${stableHash(canonicalJson({ sequence, capturedAt, payload }))}`,
|
|
140
|
+
sequence,
|
|
141
|
+
capturedAt,
|
|
142
|
+
payload: cloneJson(payload),
|
|
143
|
+
};
|
|
144
|
+
if (this.stored.some((stored) => stored.id === frame.id)) {
|
|
145
|
+
throw new Error("recording generated a duplicate frame id");
|
|
146
|
+
}
|
|
147
|
+
this.stored.push(frame);
|
|
148
|
+
this.prune(frame.capturedAt);
|
|
149
|
+
return cloneJson(frame);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
pause(): void {
|
|
153
|
+
const latest = this.stored.at(-1);
|
|
154
|
+
if (latest !== undefined) this.mode = { kind: "paused", sequence: latest.sequence };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
play(): void {
|
|
158
|
+
this.mode = { kind: "live" };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
scrub(sequence: number): void {
|
|
162
|
+
if (!Number.isInteger(sequence) || this.stored.length === 0) return;
|
|
163
|
+
const first = this.stored[0]?.sequence ?? 0;
|
|
164
|
+
const last = this.stored.at(-1)?.sequence ?? 0;
|
|
165
|
+
this.mode = { kind: "paused", sequence: Math.max(first, Math.min(last, sequence)) };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
cursor(): RecordingCursor {
|
|
169
|
+
return { ...this.mode };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
frames(): RecordingFrame<T>[] {
|
|
173
|
+
return cloneJson(this.stored);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
frameAtCursor(): RecordingFrame<T> | null {
|
|
177
|
+
if (this.stored.length === 0) return null;
|
|
178
|
+
if (this.mode.kind === "live") return cloneJson(this.stored.at(-1) as RecordingFrame<T>);
|
|
179
|
+
let found: RecordingFrame<T> | undefined;
|
|
180
|
+
for (const frame of this.stored) {
|
|
181
|
+
if (frame.sequence <= this.mode.sequence) found = frame;
|
|
182
|
+
if (frame.sequence === this.mode.sequence) break;
|
|
183
|
+
}
|
|
184
|
+
return found === undefined ? null : cloneJson(found);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export(surface: string, options: RecordingExportOptions = {}): RecordingEnvelope<T> {
|
|
188
|
+
if (!isSurface(surface))
|
|
189
|
+
throw new Error("recording surface must be a bounded non-empty string");
|
|
190
|
+
if (options.id !== undefined && !isStableId(options.id)) {
|
|
191
|
+
throw new Error("recording id must be a bounded stable identifier");
|
|
192
|
+
}
|
|
193
|
+
if (this.id !== undefined && options.id !== undefined && this.id !== options.id) {
|
|
194
|
+
throw new Error("recording id cannot change after it is established");
|
|
195
|
+
}
|
|
196
|
+
this.id ??= options.id ?? generatedRecordingId();
|
|
197
|
+
if (!isProvenance(options.provenance))
|
|
198
|
+
throw new Error("recording provenance is not allowlisted");
|
|
199
|
+
const frames = this.frames();
|
|
200
|
+
return {
|
|
201
|
+
kind: RECORDING_ENVELOPE_KIND,
|
|
202
|
+
version: RECORDING_ENVELOPE_VERSION,
|
|
203
|
+
id: this.id,
|
|
204
|
+
surface,
|
|
205
|
+
capturedAt: this.now(),
|
|
206
|
+
...(options.provenance === undefined ? {} : { provenance: cloneJson(options.provenance) }),
|
|
207
|
+
frames,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private prune(now: number): void {
|
|
212
|
+
while (this.stored.length > this.limit) this.stored.shift();
|
|
213
|
+
if (this.maxAgeMs !== undefined) {
|
|
214
|
+
const oldestAllowed = now - this.maxAgeMs;
|
|
215
|
+
while ((this.stored[0]?.capturedAt ?? oldestAllowed) < oldestAllowed) this.stored.shift();
|
|
216
|
+
}
|
|
217
|
+
if (
|
|
218
|
+
this.mode.kind === "paused" &&
|
|
219
|
+
this.stored.length > 0 &&
|
|
220
|
+
this.mode.sequence < (this.stored[0]?.sequence ?? 0)
|
|
221
|
+
) {
|
|
222
|
+
this.mode = { kind: "paused", sequence: this.stored[0]?.sequence ?? this.mode.sequence };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Parse the shared envelope, then delegate the surface-specific payload check. */
|
|
228
|
+
export function parseRecordingEnvelope<T extends JsonValue>(
|
|
229
|
+
value: unknown,
|
|
230
|
+
options: { surface: string; parsePayload: (value: JsonValue) => T | null },
|
|
231
|
+
): RecordingEnvelope<T> | null {
|
|
232
|
+
if (!isJsonRecord(value)) return null;
|
|
233
|
+
if (value.kind !== RECORDING_ENVELOPE_KIND || !isJsonValue(value.version)) return null;
|
|
234
|
+
if (value.version === 1) return migrateV1(value, options);
|
|
235
|
+
if (
|
|
236
|
+
value.version !== RECORDING_ENVELOPE_VERSION ||
|
|
237
|
+
!hasOnlyKeys(value, ["kind", "version", "id", "surface", "capturedAt", "provenance", "frames"])
|
|
238
|
+
)
|
|
239
|
+
return null;
|
|
240
|
+
const { id, capturedAt } = value;
|
|
241
|
+
if (
|
|
242
|
+
!isStableId(id) ||
|
|
243
|
+
value.surface !== options.surface ||
|
|
244
|
+
!isSurface(value.surface) ||
|
|
245
|
+
!isFiniteNumber(capturedAt) ||
|
|
246
|
+
!isProvenance(value.provenance) ||
|
|
247
|
+
!Array.isArray(value.frames)
|
|
248
|
+
)
|
|
249
|
+
return null;
|
|
250
|
+
return parseFrames(value.frames, options, { id, capturedAt, provenance: value.provenance });
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function migrateV1<T extends JsonValue>(
|
|
254
|
+
value: { [key: string]: JsonValue },
|
|
255
|
+
options: { surface: string; parsePayload: (value: JsonValue) => T | null },
|
|
256
|
+
): RecordingEnvelope<T> | null {
|
|
257
|
+
if (!hasOnlyKeys(value, ["kind", "version", "surface", "capturedAt", "frames"])) return null;
|
|
258
|
+
const { capturedAt } = value;
|
|
259
|
+
if (
|
|
260
|
+
value.surface !== options.surface ||
|
|
261
|
+
!isSurface(value.surface) ||
|
|
262
|
+
!isFiniteNumber(capturedAt) ||
|
|
263
|
+
!Array.isArray(value.frames)
|
|
264
|
+
)
|
|
265
|
+
return null;
|
|
266
|
+
const id = `legacy_${stableHash(canonicalJson(value))}`;
|
|
267
|
+
return parseFrames(value.frames, options, {
|
|
268
|
+
id,
|
|
269
|
+
capturedAt,
|
|
270
|
+
provenance: { source: "legacy" },
|
|
271
|
+
migrateLegacyFrames: true,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function parseFrames<T extends JsonValue>(
|
|
276
|
+
rawFrames: JsonValue[],
|
|
277
|
+
options: { surface: string; parsePayload: (value: JsonValue) => T | null },
|
|
278
|
+
envelope: {
|
|
279
|
+
id: string;
|
|
280
|
+
capturedAt: number;
|
|
281
|
+
provenance: RecordingProvenance | undefined;
|
|
282
|
+
migrateLegacyFrames?: boolean;
|
|
283
|
+
},
|
|
284
|
+
): RecordingEnvelope<T> | null {
|
|
285
|
+
if (rawFrames.length > MAX_RECORDING_FRAMES) return null;
|
|
286
|
+
let previous = 0;
|
|
287
|
+
const ids = new Set<string>();
|
|
288
|
+
const frames: RecordingFrame<T>[] = [];
|
|
289
|
+
for (const raw of rawFrames) {
|
|
290
|
+
if (!isJsonRecord(raw)) return null;
|
|
291
|
+
const allowedKeys = envelope.migrateLegacyFrames
|
|
292
|
+
? ["sequence", "capturedAt", "payload"]
|
|
293
|
+
: ["id", "sequence", "capturedAt", "payload"];
|
|
294
|
+
if (!hasOnlyKeys(raw, allowedKeys)) return null;
|
|
295
|
+
const frameId = envelope.migrateLegacyFrames
|
|
296
|
+
? `legacy_frame_${stableHash(`${envelope.id}:${canonicalJson(raw)}`)}`
|
|
297
|
+
: raw.id;
|
|
298
|
+
const sequence = raw.sequence;
|
|
299
|
+
const capturedAt = raw.capturedAt;
|
|
300
|
+
if (
|
|
301
|
+
!isStableId(frameId) ||
|
|
302
|
+
ids.has(frameId) ||
|
|
303
|
+
typeof sequence !== "number" ||
|
|
304
|
+
!Number.isInteger(sequence) ||
|
|
305
|
+
sequence <= previous ||
|
|
306
|
+
typeof capturedAt !== "number" ||
|
|
307
|
+
!Number.isFinite(capturedAt)
|
|
308
|
+
)
|
|
309
|
+
return null;
|
|
310
|
+
if (!("payload" in raw) || !isJsonValue(raw.payload)) return null;
|
|
311
|
+
const payload = options.parsePayload(raw.payload);
|
|
312
|
+
if (payload === null) return null;
|
|
313
|
+
frames.push({ id: frameId, sequence, capturedAt, payload: cloneJson(payload) });
|
|
314
|
+
ids.add(frameId);
|
|
315
|
+
previous = sequence;
|
|
316
|
+
}
|
|
317
|
+
return {
|
|
318
|
+
kind: RECORDING_ENVELOPE_KIND,
|
|
319
|
+
version: RECORDING_ENVELOPE_VERSION,
|
|
320
|
+
id: envelope.id,
|
|
321
|
+
surface: options.surface,
|
|
322
|
+
capturedAt: envelope.capturedAt,
|
|
323
|
+
...(envelope.provenance === undefined ? {} : { provenance: cloneJson(envelope.provenance) }),
|
|
324
|
+
frames,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function isJsonRecord(value: unknown): value is { [key: string]: JsonValue } {
|
|
329
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function isJsonValue(value: unknown): value is JsonValue {
|
|
333
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
334
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
335
|
+
if (Array.isArray(value)) return value.every(isJsonValue);
|
|
336
|
+
if (!isJsonRecord(value)) return false;
|
|
337
|
+
return Object.values(value).every(isJsonValue);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const STABLE_ID = /^[a-z][a-z0-9_-]{0,127}$/;
|
|
341
|
+
const MAX_METADATA_TEXT_LENGTH = 200;
|
|
342
|
+
const MAX_RECORDING_FRAMES = 10_000;
|
|
343
|
+
let generatedRecordingCount = 0;
|
|
344
|
+
|
|
345
|
+
function isStableId(value: unknown): value is string {
|
|
346
|
+
return typeof value === "string" && STABLE_ID.test(value);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function isSurface(value: unknown): value is string {
|
|
350
|
+
return (
|
|
351
|
+
typeof value === "string" && value.trim() !== "" && value.length <= MAX_METADATA_TEXT_LENGTH
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function isFiniteNumber(value: unknown): value is number {
|
|
356
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function hasOnlyKeys(value: { [key: string]: JsonValue }, allowed: readonly string[]): boolean {
|
|
360
|
+
return Object.keys(value).every((key) => allowed.includes(key));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function isProvenance(value: unknown): value is RecordingProvenance | undefined {
|
|
364
|
+
if (value === undefined) return true;
|
|
365
|
+
if (!isJsonRecord(value) || !hasOnlyKeys(value, ["source", "build", "title"])) return false;
|
|
366
|
+
if (value.source !== "live" && value.source !== "legacy" && value.source !== "fixture")
|
|
367
|
+
return false;
|
|
368
|
+
return [value.build, value.title].every(
|
|
369
|
+
(part) =>
|
|
370
|
+
part === undefined ||
|
|
371
|
+
(typeof part === "string" && part.trim() !== "" && part.length <= MAX_METADATA_TEXT_LENGTH),
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function generatedRecordingId(): string {
|
|
376
|
+
const uuid = globalThis.crypto?.randomUUID?.();
|
|
377
|
+
if (uuid !== undefined) return `recording_${uuid}`;
|
|
378
|
+
generatedRecordingCount += 1;
|
|
379
|
+
return `recording_${stableHash(`${Date.now()}:${generatedRecordingCount}:${Math.random()}`)}`;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** Canonical object order keeps v1 migration ids stable across JSON reformatting. */
|
|
383
|
+
function canonicalJson(value: JsonValue): string {
|
|
384
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
385
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
386
|
+
return `{${Object.keys(value)
|
|
387
|
+
.sort()
|
|
388
|
+
.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key] as JsonValue)}`)
|
|
389
|
+
.join(",")}}`;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Small deterministic identifier hash; this is an identity aid, not a security primitive. */
|
|
393
|
+
function stableHash(value: string): string {
|
|
394
|
+
let first = 0x811c9dc5;
|
|
395
|
+
let second = 0x01000193;
|
|
396
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
397
|
+
const code = value.charCodeAt(index);
|
|
398
|
+
first = Math.imul(first ^ code, 0x01000193);
|
|
399
|
+
second = Math.imul(second ^ code, 0x811c9dc5);
|
|
400
|
+
}
|
|
401
|
+
return `${(first >>> 0).toString(36)}${(second >>> 0).toString(36)}`;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function cloneJson<T>(value: T): T {
|
|
405
|
+
return JSON.parse(JSON.stringify(value)) as T;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Build a host-neutral reader snapshot from plain fixture rows. */
|
|
409
|
+
export function snapshotDbFromFixture(tables: SnapshotFixtureTables): SnapshotDb {
|
|
410
|
+
const db: SnapshotDb = {};
|
|
411
|
+
for (const [tableName, rows] of Object.entries(tables)) {
|
|
412
|
+
db[tableName] = {
|
|
413
|
+
iter: () => rows,
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
return db;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
export function captureSnapshotFrame(
|
|
420
|
+
db: SnapshotDb,
|
|
421
|
+
args: { tick: number; tables: readonly string[] },
|
|
422
|
+
): SnapshotCaptureFrame {
|
|
423
|
+
const tables: SnapshotCaptureFrame["tables"] = {};
|
|
424
|
+
for (const tableName of args.tables) {
|
|
425
|
+
tables[tableName] = Array.from(db[tableName]?.iter() ?? []).map(
|
|
426
|
+
(row) => toFixtureValue(row) as Record<string, unknown>,
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
return {
|
|
430
|
+
kind: "spellkave.snapshot_frame",
|
|
431
|
+
version: 1,
|
|
432
|
+
tick: args.tick,
|
|
433
|
+
tables,
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function snapshotDbFromCaptureFrame(frame: SnapshotCaptureFrame): SnapshotDb {
|
|
438
|
+
return snapshotDbFromFixture(frame.tables);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
export function readRecentEvents(db: SnapshotDb, n: number): WorldEventRow[] {
|
|
442
|
+
if (n <= 0) return [];
|
|
443
|
+
// `world_event` is private (#915 PR-8); a live connection populates the
|
|
444
|
+
// per-caller `visible_world_event` view instead. Try the new accessor
|
|
445
|
+
// first, falling back to the raw name so pre-#915-PR-8 frozen captures
|
|
446
|
+
// (e.g. apps/world-review/src/fixtures/review-capture.json) keyed under
|
|
447
|
+
// the old accessor still replay correctly.
|
|
448
|
+
const all = rows(db, "visible_world_event", "world_event").map(toEventRow);
|
|
449
|
+
all.sort((a, b) => (b.tick !== a.tick ? b.tick - a.tick : b.id.localeCompare(a.id)));
|
|
450
|
+
return all.slice(0, n);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function rows(db: SnapshotDb, ...accessors: string[]): Record<string, unknown>[] {
|
|
454
|
+
for (const accessor of accessors) {
|
|
455
|
+
const handle = db[accessor];
|
|
456
|
+
if (handle !== undefined) return Array.from(handle.iter());
|
|
457
|
+
}
|
|
458
|
+
return [];
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function toEventRow(row: Record<string, unknown>): WorldEventRow {
|
|
462
|
+
const summary = optString(row.summary);
|
|
463
|
+
const out: WorldEventRow = {
|
|
464
|
+
id: asString(row.id),
|
|
465
|
+
tick: asNumber(row.tick),
|
|
466
|
+
kind: kindToString(row.kind),
|
|
467
|
+
};
|
|
468
|
+
if (summary !== undefined) out.summary = summary;
|
|
469
|
+
return out;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function asString(value: unknown): string {
|
|
473
|
+
return value === undefined || value === null ? "" : String(value);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function asNumber(value: unknown, fallback = 0): number {
|
|
477
|
+
if (typeof value === "number") return value;
|
|
478
|
+
if (typeof value === "bigint") return Number(value);
|
|
479
|
+
if (typeof value === "string") {
|
|
480
|
+
const n = Number(value);
|
|
481
|
+
return Number.isFinite(n) ? n : fallback;
|
|
482
|
+
}
|
|
483
|
+
return fallback;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function optString(value: unknown): string | undefined {
|
|
487
|
+
if (value === undefined || value === null) return undefined;
|
|
488
|
+
if (value && typeof value === "object") {
|
|
489
|
+
const some = (value as { some?: unknown }).some;
|
|
490
|
+
if (some !== undefined && some !== null) return String(some);
|
|
491
|
+
}
|
|
492
|
+
const s = String(value);
|
|
493
|
+
return s.length > 0 ? s : undefined;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function kindToString(value: unknown): string {
|
|
497
|
+
if (typeof value === "string") return value;
|
|
498
|
+
if (value && typeof value === "object") {
|
|
499
|
+
const tag = (value as { tag?: unknown }).tag;
|
|
500
|
+
if (typeof tag === "string") return tag;
|
|
501
|
+
}
|
|
502
|
+
return asString(value);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function toFixtureValue(value: unknown): unknown {
|
|
506
|
+
if (typeof value === "bigint") {
|
|
507
|
+
const asNumber = Number(value);
|
|
508
|
+
return Number.isSafeInteger(asNumber) ? asNumber : value.toString();
|
|
509
|
+
}
|
|
510
|
+
if (Array.isArray(value)) return value.map((item) => toFixtureValue(item));
|
|
511
|
+
if (value === null || typeof value !== "object") return value;
|
|
512
|
+
return Object.fromEntries(
|
|
513
|
+
Object.entries(value).map(([key, item]) => [key, toFixtureValue(item)]),
|
|
514
|
+
);
|
|
515
|
+
}
|