@spellkave/sdk 0.0.0-bootstrap → 0.0.0-stage

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/README.md +2 -155
  2. package/package.json +4 -63
  3. package/LICENSE +0 -89
  4. package/src/binding_rows.ts +0 -186
  5. package/src/connection.ts +0 -964
  6. package/src/core/actor.ts +0 -62
  7. package/src/core/actor_control.ts +0 -193
  8. package/src/core/actor_control_query_methods.ts +0 -101
  9. package/src/core/actor_control_reaction_methods.ts +0 -79
  10. package/src/core/actor_control_sense_methods.ts +0 -81
  11. package/src/core/actor_control_source.ts +0 -57
  12. package/src/core/actor_session_methods.ts +0 -226
  13. package/src/core/binding_drift.ts +0 -301
  14. package/src/core/credential.ts +0 -259
  15. package/src/core/driver_control.ts +0 -54
  16. package/src/core/effective_environment_state.ts +0 -71
  17. package/src/core/factored_manipulation_attempt.ts +0 -158
  18. package/src/core/ids.ts +0 -60
  19. package/src/core/interaction/canonical.ts +0 -15
  20. package/src/core/interaction/fingerprint.ts +0 -118
  21. package/src/core/interaction/index.ts +0 -31
  22. package/src/core/interaction/intent.ts +0 -284
  23. package/src/core/interaction/outcome.ts +0 -67
  24. package/src/core/interaction/rejection_ledger.ts +0 -108
  25. package/src/core/kernel_contract.generated.ts +0 -10
  26. package/src/core/log.ts +0 -23
  27. package/src/core/movement.ts +0 -111
  28. package/src/core/node-io.ts +0 -208
  29. package/src/core/paths.ts +0 -220
  30. package/src/core/profile.ts +0 -270
  31. package/src/core/profiles.ts +0 -9
  32. package/src/core/provenance_buffer.ts +0 -102
  33. package/src/core/readers/_helpers.ts +0 -273
  34. package/src/core/readers/action_description.ts +0 -17
  35. package/src/core/readers/action_economy_events.ts +0 -149
  36. package/src/core/readers/actor_body_swaps.ts +0 -62
  37. package/src/core/readers/actor_snapshot.ts +0 -197
  38. package/src/core/readers/actor_states.ts +0 -163
  39. package/src/core/readers/actors_and_bodies.ts +0 -179
  40. package/src/core/readers/affordance_cue.ts +0 -59
  41. package/src/core/readers/affordance_defaults.ts +0 -158
  42. package/src/core/readers/affordance_group_membership.ts +0 -67
  43. package/src/core/readers/affordance_input.ts +0 -129
  44. package/src/core/readers/affordance_reference.ts +0 -41
  45. package/src/core/readers/apply_consequences.ts +0 -54
  46. package/src/core/readers/audience_trace_presentation.ts +0 -62
  47. package/src/core/readers/bounded_collection.ts +0 -29
  48. package/src/core/readers/bundle_definitions.ts +0 -74
  49. package/src/core/readers/bundle_entities.ts +0 -62
  50. package/src/core/readers/co_location.ts +0 -71
  51. package/src/core/readers/combat_session.ts +0 -124
  52. package/src/core/readers/combat_session_active.ts +0 -44
  53. package/src/core/readers/combat_session_feedback.ts +0 -37
  54. package/src/core/readers/combat_session_grid.ts +0 -117
  55. package/src/core/readers/combat_session_roster.ts +0 -98
  56. package/src/core/readers/combat_session_types.ts +0 -51
  57. package/src/core/readers/condition_deltas.ts +0 -53
  58. package/src/core/readers/container_contents.ts +0 -92
  59. package/src/core/readers/dialogue_guide.ts +0 -99
  60. package/src/core/readers/dialogue_prompt_presentation.ts +0 -90
  61. package/src/core/readers/driver_control.ts +0 -64
  62. package/src/core/readers/entity_art.ts +0 -219
  63. package/src/core/readers/entity_containment.ts +0 -119
  64. package/src/core/readers/equipment.ts +0 -99
  65. package/src/core/readers/intervention_windows.ts +0 -136
  66. package/src/core/readers/inventory_query.ts +0 -145
  67. package/src/core/readers/item_detail.ts +0 -198
  68. package/src/core/readers/location_snapshot.ts +0 -216
  69. package/src/core/readers/manifest_apply_provenance.ts +0 -32
  70. package/src/core/readers/manifest_export.ts +0 -81
  71. package/src/core/readers/manipulation_context.ts +0 -475
  72. package/src/core/readers/map_layers.ts +0 -49
  73. package/src/core/readers/metadata_rows.ts +0 -56
  74. package/src/core/readers/object_state.ts +0 -124
  75. package/src/core/readers/observer_knowledge.ts +0 -41
  76. package/src/core/readers/observer_place_knowledge.ts +0 -37
  77. package/src/core/readers/observer_trace_knowledge.ts +0 -45
  78. package/src/core/readers/outcome_template.ts +0 -41
  79. package/src/core/readers/place_topology.ts +0 -109
  80. package/src/core/readers/reaction_options.ts +0 -156
  81. package/src/core/readers/resource_deltas.ts +0 -47
  82. package/src/core/readers/scene.ts +0 -275
  83. package/src/core/readers/seats.ts +0 -33
  84. package/src/core/readers/self.ts +0 -245
  85. package/src/core/readers/self_capabilities.ts +0 -159
  86. package/src/core/readers/self_economy.ts +0 -101
  87. package/src/core/readers/self_economy_budget.ts +0 -93
  88. package/src/core/readers/self_evaluations.ts +0 -128
  89. package/src/core/readers/self_identity.ts +0 -104
  90. package/src/core/readers/sense_context.ts +0 -112
  91. package/src/core/readers/session.ts +0 -207
  92. package/src/core/readers/session_detail.ts +0 -211
  93. package/src/core/readers/session_status.ts +0 -68
  94. package/src/core/readers/spatial_environment_state.ts +0 -74
  95. package/src/core/readers/spatial_niche_attachments.ts +0 -28
  96. package/src/core/readers/substrate_definitions.ts +0 -27
  97. package/src/core/readers/suggest_next_action.ts +0 -72
  98. package/src/core/readers/surface_membership.ts +0 -78
  99. package/src/core/readers/tag_reads.ts +0 -54
  100. package/src/core/readers/trace_query.ts +0 -120
  101. package/src/core/readers/trace_response.ts +0 -80
  102. package/src/core/readers/traces.ts +0 -124
  103. package/src/core/readers/travel_session.ts +0 -88
  104. package/src/core/readers/turn_state.ts +0 -34
  105. package/src/core/readers/world_events.ts +0 -43
  106. package/src/core/readers/world_status.ts +0 -63
  107. package/src/core/reducers/manipulation_args.ts +0 -239
  108. package/src/core/reducers/manipulation_receipt.ts +0 -66
  109. package/src/core/reducers/r_actor_wake_up.ts +0 -32
  110. package/src/core/reducers/r_inscribe_trace.ts +0 -109
  111. package/src/core/reducers/r_manipulate.ts +0 -163
  112. package/src/core/reducers/r_move.ts +0 -155
  113. package/src/core/reducers/r_react.ts +0 -143
  114. package/src/core/reducers/r_release_claim.ts +0 -81
  115. package/src/core/reducers/r_sense.ts +0 -84
  116. package/src/core/reducers/r_session_close.ts +0 -130
  117. package/src/core/reducers/r_session_move.ts +0 -116
  118. package/src/core/reducers/r_session_open.ts +0 -91
  119. package/src/core/reducers/session_lookup.ts +0 -64
  120. package/src/core/reducers/tick.ts +0 -65
  121. package/src/core/reducers/trace_lookup.ts +0 -29
  122. package/src/core/reducers/transport.ts +0 -84
  123. package/src/core/resolve.ts +0 -228
  124. package/src/core/shape_telemetry.ts +0 -146
  125. package/src/core/snapshot_rows.ts +0 -109
  126. package/src/core/tick_cadence.ts +0 -61
  127. package/src/core/types.ts +0 -501
  128. package/src/core/watch_provenance.ts +0 -113
  129. package/src/core/world-contract/classify.ts +0 -38
  130. package/src/core/world-contract/index.ts +0 -12
  131. package/src/core/world-contract/normalise.ts +0 -574
  132. package/src/core/world-contract/runtime.ts +0 -144
  133. package/src/core/world-contract/served.ts +0 -173
  134. package/src/core/world-contract/strict-reducers.ts +0 -14
  135. package/src/core/world-contract/typetext.ts +0 -94
  136. package/src/core/world_time.ts +0 -22
  137. package/src/index.ts +0 -262
  138. package/src/manifest-apply.ts +0 -497
  139. package/src/provenance.ts +0 -568
  140. package/src/reader-manifest.ts +0 -338
  141. package/src/readers.ts +0 -392
  142. package/src/replay.ts +0 -515
  143. package/src/watch-buffer.ts +0 -438
  144. package/src/world-events/builder.ts +0 -1042
@@ -1,273 +0,0 @@
1
- // Cache-row conversion helpers shared across reader files.
2
- // Mechanical split from readers.ts; no new functionality.
3
- // Snake-case-only: camelCase fallback removed in Phase 2 (D-C).
4
- // NOT subject to per-reader LOC ceiling (D4, design.md:112).
5
-
6
- import type {
7
- EntityDescriptionRow,
8
- EntityRow,
9
- EntityTagRow,
10
- ManifestAuthoredEntityRow,
11
- } from "../../binding_rows";
12
- import type { SnapshotDb } from "../../reader-manifest";
13
- import type { EntityRef } from "../ids";
14
-
15
- export function asString(v: unknown): string {
16
- return v === undefined || v === null ? "" : String(v);
17
- }
18
-
19
- export function optString(v: unknown): string | undefined {
20
- if (v === undefined || v === null) return undefined;
21
- if (v && typeof v === "object") {
22
- const some = (v as { some?: unknown }).some;
23
- if (some !== undefined && some !== null) return String(some);
24
- }
25
- const s = String(v);
26
- return s.length > 0 ? s : undefined;
27
- }
28
-
29
- export function asNumber(v: unknown, fallback = 0): number {
30
- if (typeof v === "number") return v;
31
- if (typeof v === "bigint") return Number(v);
32
- if (typeof v === "string") {
33
- const n = Number(v);
34
- return Number.isFinite(n) ? n : fallback;
35
- }
36
- return fallback;
37
- }
38
-
39
- export function optNumber(v: unknown): number | undefined {
40
- if (v === undefined || v === null) return undefined;
41
- return asNumber(v, NaN);
42
- }
43
-
44
- /** SpacetimeDB `Option<i64>` / tagged `{tag:'some', value}` / bare number. */
45
- export function optionNumber(v: unknown): number | undefined {
46
- if (v === undefined || v === null) return undefined;
47
- if (typeof v === "number" || typeof v === "bigint") return asNumber(v);
48
- if (typeof v === "string") {
49
- const n = Number(v);
50
- return Number.isFinite(n) ? n : undefined;
51
- }
52
- if (typeof v === "object") {
53
- const record = v as { tag?: unknown; value?: unknown; some?: unknown };
54
- if (record.tag === "none" || record.tag === "None") return undefined;
55
- if (record.tag === "some" || record.tag === "Some")
56
- return optionNumber(record.value ?? record.some);
57
- if ("some" in record) return optionNumber(record.some);
58
- }
59
- return undefined;
60
- }
61
-
62
- export function rows<T>(db: SnapshotDb, ...accessors: string[]): T[] {
63
- if (accessors.includes("visible_manifest_authored_entity")) {
64
- const coverage = Array.from(db.visible_manifest_authored_entity_coverage?.iter() ?? []);
65
- if (
66
- !db.visible_manifest_authored_entity ||
67
- coverage.length !== 1 ||
68
- coverage[0]?.status !== "complete" ||
69
- coverage[0]?.projectionVersion !== 1
70
- )
71
- throw new Error("reader_unavailable: authored mapping coverage missing or incomplete");
72
- }
73
- if (accessors.includes("visible_entity_tag")) {
74
- const coverage = Array.from(db.visible_entity_tag_coverage?.iter() ?? []);
75
- if (
76
- !db.visible_entity_tag ||
77
- coverage.length !== 1 ||
78
- coverage[0]?.status !== "complete" ||
79
- coverage[0]?.projectionVersion !== 1
80
- )
81
- throw new Error(
82
- "reader_unavailable: runtime tag membership coverage is missing or incomplete",
83
- );
84
- }
85
- let empty: T[] | undefined;
86
- for (const a of accessors) {
87
- const handle = db[a];
88
- if (!handle) continue;
89
- const out = Array.from(handle.iter()) as T[];
90
- // Prefer the first populated handle so unit fixtures that still
91
- // inject the pre-privacy `session` / `session_participant` names keep
92
- // working against always-present empty proxies, while live clients
93
- // (only `visible_*` subscribed) stay on the view.
94
- if (out.length > 0 || accessors.length === 1) return out;
95
- empty = out;
96
- }
97
- return empty ?? [];
98
- }
99
-
100
- // SpacetimeDB tagged-enum shape: `{ tag: "VariantName", value?: ... }`.
101
- // Used by world_event.kind, evaluation_provenance.kind/status, etc.
102
- export function tagString(v: unknown): string {
103
- if (typeof v === "string") return v;
104
- if (v && typeof v === "object") {
105
- const tag = (v as { tag?: unknown }).tag;
106
- if (typeof tag === "string") return tag;
107
- }
108
- return asString(v);
109
- }
110
-
111
- // Alias: readers.ts uses kindToString; connection.ts uses tagString. Same logic.
112
- export const kindToString = tagString;
113
-
114
- export function verbClassFromDescriptor(descriptor: string): string {
115
- const key = descriptor.split("=")[0] ?? "";
116
- const namespace = key.split(".")[0] ?? "";
117
- switch (namespace) {
118
- case "manipulation":
119
- case "action_id":
120
- return "manipulate";
121
- case "communication":
122
- return "communicate";
123
- default:
124
- return namespace || "unknown";
125
- }
126
- }
127
-
128
- /** The descriptor's value (the part after the first `=`); "" if none. */
129
- export function descriptorValue(descriptor: string): string {
130
- const eq = descriptor.indexOf("=");
131
- return eq >= 0 ? descriptor.slice(eq + 1) : "";
132
- }
133
-
134
- /**
135
- * Resolve an agent-facing entity reference to its numeric entity id.
136
- *
137
- * Accepts a numeric id (`"11"`), an `entity:`-prefixed numeric ref
138
- * (`"entity:11"`), or a manifest authored-entity key suffix (`"core/player"`,
139
- * matched against `visible_manifest_authored_entity.manifestKey` after its `bundle:`
140
- * prefix). Complete delivery with no matching key returns `undefined`; missing,
141
- * incomplete, or unsupported mapping coverage throws `reader_unavailable`.
142
- *
143
- * Shared because every perceive reader that takes such a ref needs it: the
144
- * per-reader `BigInt(ref)` reimplementation threw on manifest keys and the
145
- * helper had drifted into three private copies (tracker #504, L1 finding #1).
146
- * Readers declare both admitted mapping and coverage tables. Numeric references
147
- * remain usable when authored-key delivery is unavailable.
148
- */
149
- export function resolveEntityId(db: SnapshotDb, entityRef: EntityRef): bigint | undefined {
150
- // Read the authored-entity table unconditionally (not lazily after the
151
- // numeric fast-path): a reader that *declares* visible_manifest_authored_entity in
152
- // requiredTables must *access* it on every call, or the manifest-completeness
153
- // proxy harness flags it as under-declared and the subscription is unhonest.
154
- const authoredHandle = db.visible_manifest_authored_entity;
155
- const coverage = Array.from(db.visible_manifest_authored_entity_coverage?.iter() ?? []);
156
- const numeric = parseEntityIdRef(entityRef);
157
- if (numeric !== undefined) return numeric;
158
- if (
159
- !authoredHandle ||
160
- coverage.length !== 1 ||
161
- coverage[0]?.status !== "complete" ||
162
- coverage[0]?.projectionVersion !== 1
163
- )
164
- throw new Error("reader_unavailable: authored mapping coverage missing or incomplete");
165
- const authoredRows = Array.from(authoredHandle.iter()) as ManifestAuthoredEntityRow[];
166
- const authored = authoredRows.find((r) => {
167
- const idx = r.manifestKey.indexOf(":");
168
- return idx >= 0 && r.manifestKey.slice(idx + 1) === entityRef;
169
- });
170
- return authored ? toBigInt(authored.entityId) : undefined;
171
- }
172
-
173
- export function parseEntityIdRef(ref: string): bigint | undefined {
174
- // ADR-0033 typed target refs: entity:<id> and item:<id> both name a body
175
- // entity id (Item is still an entity row). sk-h13: inspect on inventory
176
- // targets arrives as item:N — leaving the prefix stripped is required so
177
- // observation `{target_name}` can resolve via buildEntityNameMap.
178
- let trimmed = ref;
179
- if (trimmed.startsWith("entity:")) trimmed = trimmed.slice("entity:".length);
180
- else if (trimmed.startsWith("item:")) trimmed = trimmed.slice("item:".length);
181
- if (trimmed === "" || !/^\d+$/.test(trimmed)) return undefined;
182
- try {
183
- return BigInt(trimmed);
184
- } catch {
185
- return undefined;
186
- }
187
- }
188
-
189
- function toBigInt(v: number | bigint): bigint {
190
- return typeof v === "bigint" ? v : BigInt(v);
191
- }
192
-
193
- const FACTION_TAG_PREFIX = "srd.faction.";
194
- const LEGACY_FACTION_TAG_PREFIX = "faction:";
195
-
196
- /**
197
- * Map of entity id (string) -> authored instance name, from the `entity` table.
198
- * Batch join for a reader that enriches many entities per call (actor list,
199
- * location roster, affordance targets — #1849); single-entity callers should
200
- * use `readActorSnapshot`'s own lookup pattern instead of building a whole map.
201
- */
202
- export function buildEntityNameMap(db: SnapshotDb): Map<string, string> {
203
- const out = new Map<string, string>();
204
- for (const e of rows<EntityRow>(db, "entity")) {
205
- out.set(String(e.entityId), asString(e.name));
206
- }
207
- return out;
208
- }
209
-
210
- /**
211
- * Map of entity id (string) -> its first `srd.faction.<name>` or legacy `faction:<name>`
212
- * tag suffix (e.g. "monsters", "cragmaw"), built from admitted `visible_entity_tag` rows.
213
- * Batch form of `readEntityFaction` (tag_reads.ts) for readers that enrich many entities
214
- * per call. Entities with no faction tag are absent from the map.
215
- */
216
- export function buildEntityFactionMap(db: SnapshotDb): Map<string, string> {
217
- const out = new Map<string, string>();
218
- for (const t of rows<EntityTagRow>(db, "visible_entity_tag")) {
219
- const id = String(t.entityId);
220
- if (out.has(id)) continue;
221
- const tag = asString(t.tag);
222
- if (tag.startsWith(FACTION_TAG_PREFIX)) {
223
- out.set(id, tag.slice(FACTION_TAG_PREFIX.length));
224
- } else if (tag.startsWith(LEGACY_FACTION_TAG_PREFIX)) {
225
- out.set(id, tag.slice(LEGACY_FACTION_TAG_PREFIX.length));
226
- }
227
- }
228
- return out;
229
- }
230
-
231
- /**
232
- * Map of entity id (string) -> authored sideband description (`entity_description`,
233
- * #1968), from the `entity_description` table. Batch join for a reader that
234
- * enriches many entities per call — same pattern as `buildEntityNameMap`.
235
- * An entity with no authored row is absent from the map (server's own
236
- * "absent row -> empty description" canonical shape); callers default with
237
- * `?? ""`.
238
- */
239
- export function buildEntityDescriptionMap(db: SnapshotDb): Map<string, string> {
240
- const out = new Map<string, string>();
241
- for (const e of rows<EntityDescriptionRow>(db, "entity_description")) {
242
- out.set(String(e.entityId), asString(e.description));
243
- }
244
- return out;
245
- }
246
-
247
- export interface EntitySummary {
248
- name: string;
249
- entity_def_id: string;
250
- kind: string;
251
- quantity: number;
252
- }
253
-
254
- /**
255
- * Map of entity id (string) -> identity summary (name/entity_def_id/kind/
256
- * quantity), from the `entity` table. Batch join for a reader that enriches
257
- * many entities per call — e.g. containment rows (#1227: `spellkave_inventory`
258
- * returned bare ids, forcing a per-item `spellkave_object_state` follow-up
259
- * loop that dead-ends on `[]` for unnamed items and burns a session's dry-streak
260
- * budget before combat).
261
- */
262
- export function buildEntitySummaryMap(db: SnapshotDb): Map<string, EntitySummary> {
263
- const out = new Map<string, EntitySummary>();
264
- for (const e of rows<EntityRow>(db, "entity")) {
265
- out.set(String(e.entityId), {
266
- name: asString(e.name),
267
- entity_def_id: asString(e.entityDefId),
268
- kind: asString(e.kind),
269
- quantity: asNumber(e.quantity),
270
- });
271
- }
272
- return out;
273
- }
@@ -1,17 +0,0 @@
1
- /** Public authored prose only; template specialization precedes action prose. */
2
- import type { AffordanceTemplateRow } from "../../binding_rows";
3
- import { asString } from "./_helpers";
4
-
5
- export function actionDescriptionFields(
6
- actionText: unknown,
7
- templateIds: readonly string[],
8
- templates: ReadonlyMap<string, AffordanceTemplateRow>,
9
- ): { description?: string } {
10
- const description =
11
- templateIds
12
- .map((id) => asString(templates.get(id)?.description).trim())
13
- .find((text) => text.length > 0) ||
14
- asString(actionText).trim() ||
15
- undefined;
16
- return description === undefined ? {} : { description };
17
- }
@@ -1,149 +0,0 @@
1
- import type {
2
- ConditionBoundaryExpiryRow as DbConditionBoundaryExpiryRow,
3
- EventActionRechargeFiredRow as DbEventActionRechargeFiredRow,
4
- EventBoundaryFiredRow as DbEventBoundaryFiredRow,
5
- EventChannelSpendRow as DbEventChannelSpendRow,
6
- EventChannelWindowRefreshRow as DbEventChannelWindowRefreshRow,
7
- } from "../../binding_rows";
8
- import {
9
- type RequiredTables,
10
- registerReaderManifest,
11
- type SnapshotDb,
12
- } from "../../reader-manifest";
13
- import { asString, rows } from "./_helpers";
14
-
15
- export const channelSpendRequiredTables: RequiredTables<["event_channel_spend"]> = [
16
- "event_channel_spend",
17
- ];
18
- export const boundaryFiredRequiredTables: RequiredTables<["event_boundary_fired"]> = [
19
- "event_boundary_fired",
20
- ];
21
- export const channelWindowRefreshRequiredTables: RequiredTables<["event_channel_window_refresh"]> =
22
- ["event_channel_window_refresh"];
23
- export const actionRechargeFiredRequiredTables: RequiredTables<["event_action_recharge_fired"]> = [
24
- "event_action_recharge_fired",
25
- ];
26
- export const conditionBoundaryExpiryRequiredTables: RequiredTables<
27
- ["visible_condition_boundary_expiry"]
28
- > = ["visible_condition_boundary_expiry"];
29
- registerReaderManifest({ requiredTables: channelSpendRequiredTables });
30
- registerReaderManifest({ requiredTables: boundaryFiredRequiredTables });
31
- registerReaderManifest({ requiredTables: channelWindowRefreshRequiredTables });
32
- registerReaderManifest({ requiredTables: actionRechargeFiredRequiredTables });
33
- registerReaderManifest({ requiredTables: conditionBoundaryExpiryRequiredTables });
34
-
35
- export interface ChannelSpendEventRow {
36
- event_id: string;
37
- actor: string;
38
- channel: string;
39
- cost_ms: string;
40
- remaining_ms: string;
41
- window: string;
42
- }
43
-
44
- export interface BoundaryFiredEventRow {
45
- event_id: string;
46
- boundary: string;
47
- owner: string;
48
- source: string;
49
- window: string;
50
- }
51
-
52
- export interface ChannelWindowRefreshEventRow {
53
- event_id: string;
54
- actor: string;
55
- boundary: string;
56
- window: string;
57
- }
58
-
59
- export interface ActionRechargeFiredEventRow {
60
- event_id: string;
61
- actor: string;
62
- affordance: string;
63
- boundary: string;
64
- }
65
-
66
- export interface ConditionBoundaryExpiryRow {
67
- target_condition_row_id: string;
68
- owner_actor: string;
69
- boundary_id: string;
70
- armed_at_window_ms: string;
71
- out_of_session_due_tick: string;
72
- }
73
-
74
- function newestFirst<T extends { event_id: string }>(values: T[], n: number): T[] {
75
- if (n <= 0) return [];
76
- values.sort((a, b) => b.event_id.localeCompare(a.event_id, undefined, { numeric: true }));
77
- return values.slice(0, n);
78
- }
79
-
80
- export function readRecentChannelSpends(db: SnapshotDb, n: number): ChannelSpendEventRow[] {
81
- const values = rows<DbEventChannelSpendRow>(db, "event_channel_spend").map((row) => ({
82
- event_id: asString(row.eventId),
83
- actor: asString(row.actor),
84
- channel: row.channel,
85
- cost_ms: asString(row.costMs),
86
- remaining_ms: asString(row.remainingMs),
87
- window: asString(row.window),
88
- }));
89
- return newestFirst(values, n);
90
- }
91
-
92
- export function readRecentBoundaryFirings(db: SnapshotDb, n: number): BoundaryFiredEventRow[] {
93
- const values = rows<DbEventBoundaryFiredRow>(db, "event_boundary_fired").map((row) => ({
94
- event_id: asString(row.eventId),
95
- boundary: row.boundary,
96
- owner: asString(row.owner),
97
- source: row.source,
98
- window: asString(row.window),
99
- }));
100
- return newestFirst(values, n);
101
- }
102
-
103
- export function readRecentChannelWindowRefreshes(
104
- db: SnapshotDb,
105
- n: number,
106
- ): ChannelWindowRefreshEventRow[] {
107
- const values = rows<DbEventChannelWindowRefreshRow>(db, "event_channel_window_refresh").map(
108
- (row) => ({
109
- event_id: asString(row.eventId),
110
- actor: asString(row.actor),
111
- boundary: row.boundary,
112
- window: asString(row.window),
113
- }),
114
- );
115
- return newestFirst(values, n);
116
- }
117
-
118
- export function readRecentActionRechargeFirings(
119
- db: SnapshotDb,
120
- n: number,
121
- ): ActionRechargeFiredEventRow[] {
122
- const values = rows<DbEventActionRechargeFiredRow>(db, "event_action_recharge_fired").map(
123
- (row) => ({
124
- event_id: asString(row.eventId),
125
- actor: asString(row.actor),
126
- affordance: row.affordance,
127
- boundary: row.boundary,
128
- }),
129
- );
130
- return newestFirst(values, n);
131
- }
132
-
133
- /** Owner-scoped condition expiry arms. A caller never receives another
134
- * actor's rows because the server view applies the visibility boundary. */
135
- export function readConditionBoundaryExpiries(db: SnapshotDb): ConditionBoundaryExpiryRow[] {
136
- return rows<DbConditionBoundaryExpiryRow>(db, "visible_condition_boundary_expiry")
137
- .map((row) => ({
138
- target_condition_row_id: asString(row.targetConditionRowId),
139
- owner_actor: asString(row.ownerActor),
140
- boundary_id: row.boundaryId,
141
- armed_at_window_ms: asString(row.armedAtWindowMs),
142
- out_of_session_due_tick: asString(row.outOfSessionDueTick),
143
- }))
144
- .sort((a, b) =>
145
- a.target_condition_row_id.localeCompare(b.target_condition_row_id, undefined, {
146
- numeric: true,
147
- }),
148
- );
149
- }
@@ -1,62 +0,0 @@
1
- // Reader: typed body-swap event details joined to their world_event headers.
2
-
3
- import type {
4
- EventActorBodySwappedRow as DbEventActorBodySwappedRow,
5
- WorldEventRow as DbWorldEventRow,
6
- } from "../../binding_rows";
7
- import {
8
- type RequiredTables,
9
- registerReaderManifest,
10
- type SnapshotDb,
11
- } from "../../reader-manifest";
12
- import { type ActorId, asActorId, asEntityId, type EntityId } from "../ids";
13
- import { asNumber, asString, kindToString, rows } from "./_helpers";
14
-
15
- // `event_actor_body_swapped` is private (ADR-0120, #915) — subscribe + read
16
- // the per-caller `visible_event_actor_body_swapped` view instead
17
- // (owner/DM-extent-bounded on the previous/new body). `world_event` is also
18
- // private (#915 PR-8); its per-caller dispatch view admits the header
19
- // whenever the caller is admitted to this detail row (same OR-set the
20
- // header side reuses), so joining the two here stays consistent.
21
- export const requiredTables: RequiredTables<
22
- ["visible_event_actor_body_swapped", "visible_world_event"]
23
- > = ["visible_event_actor_body_swapped", "visible_world_event"];
24
- registerReaderManifest({ requiredTables });
25
-
26
- export interface ActorBodySwapEventRow {
27
- event_id: string;
28
- tick: number;
29
- event_kind: string;
30
- actor_id: ActorId;
31
- previous_body_entity_id: EntityId;
32
- new_body_entity_id: EntityId;
33
- consequence_template_id: string;
34
- }
35
-
36
- /**
37
- * Read body-swap event details ordered by event tick, then event id.
38
- */
39
- export function readActorBodySwapEvents(db: SnapshotDb): ActorBodySwapEventRow[] {
40
- const eventsById = new Map(
41
- rows<DbWorldEventRow>(db, "visible_world_event").map((row) => [asString(row.id), row]),
42
- );
43
-
44
- return rows<DbEventActorBodySwappedRow>(db, "visible_event_actor_body_swapped")
45
- .map((row) => toActorBodySwapEventRow(row, eventsById.get(asString(row.eventId))))
46
- .sort((a, b) => a.tick - b.tick || a.event_id.localeCompare(b.event_id));
47
- }
48
-
49
- function toActorBodySwapEventRow(
50
- row: DbEventActorBodySwappedRow,
51
- event: DbWorldEventRow | undefined,
52
- ): ActorBodySwapEventRow {
53
- return {
54
- event_id: asString(row.eventId),
55
- tick: event ? asNumber(event.tick) : 0,
56
- event_kind: event ? kindToString(event.kind) : "",
57
- actor_id: asActorId(asString(row.actorId)),
58
- previous_body_entity_id: asEntityId(asString(row.previousBodyEntityId)),
59
- new_body_entity_id: asEntityId(asString(row.newBodyEntityId)),
60
- consequence_template_id: asString(row.consequenceTemplateId),
61
- };
62
- }
@@ -1,197 +0,0 @@
1
- // Reader: actor snapshot (actor_spatial_location + visible_target_condition).
2
- // Conditions on an actor are stored in the server-filtered `visible_target_condition`
3
- // table keyed by (target_kind="entity", target_id=<entity_id u64>). The
4
- // reader resolves the caller's actor_id string to a numeric entity_id by
5
- // accepting "entity:N", bare N, or a manifest-authored entity key suffix.
6
-
7
- import type { ActorSpatialLocationRow, TargetConditionRow } from "../../binding_rows";
8
- import {
9
- type RequiredTables,
10
- registerReaderManifest,
11
- type SnapshotDb,
12
- } from "../../reader-manifest";
13
- import type { EntityRef } from "../ids";
14
- import {
15
- asNumber,
16
- buildEntityFactionMap,
17
- buildEntityNameMap,
18
- optNumber,
19
- optString,
20
- resolveEntityId,
21
- rows,
22
- } from "./_helpers";
23
- import { type ActorStateEntry, type ReadActorStatesOptions, readActorStates } from "./actor_states";
24
-
25
- export const requiredTables: RequiredTables<
26
- [
27
- "visible_actor_spatial_location",
28
- "visible_target_condition",
29
- "visible_manifest_authored_entity",
30
- "visible_manifest_authored_entity_coverage",
31
- "owned_object_state",
32
- "resource_definition",
33
- "resource_definition_tag",
34
- "entity",
35
- "visible_entity_tag",
36
- "visible_entity_tag_coverage",
37
- ]
38
- > = [
39
- "visible_actor_spatial_location",
40
- "visible_target_condition",
41
- "visible_manifest_authored_entity",
42
- "visible_manifest_authored_entity_coverage",
43
- "owned_object_state",
44
- "resource_definition",
45
- "resource_definition_tag",
46
- "entity",
47
- "visible_entity_tag",
48
- "visible_entity_tag_coverage",
49
- ];
50
- registerReaderManifest({ requiredTables });
51
-
52
- // §11.8 (2026-05-23): the server now types `target_kind` as the SpacetimeType
53
- // enum `TargetKind { Entity, Item, WorldObject }`. The generated SDK binding
54
- // represents the column as a tagged union `{ tag: "Entity" | "Item" |
55
- // "WorldObject" }` rather than a lowercase string. Comparison uses the tag
56
- // PascalCase, not the legacy "entity"/"item"/"world_object" wire form.
57
- const TARGET_KIND_ENTITY_TAG = "Entity" as const;
58
-
59
- export interface ActorConditionRow {
60
- condition_definition_id: string;
61
- applied_at_tick: number;
62
- expires_at_tick?: number;
63
- stack_count: number;
64
- bundle_id: string;
65
- source_id: string;
66
- }
67
-
68
- export interface ActorSnapshot {
69
- actor_id: EntityRef;
70
- current_node_id?: string;
71
- /**
72
- * Authored instance name from the `entity` table (#1849). Empty string is
73
- * unreachable in practice — every seeded entity carries a name — but is the
74
- * fallback if a snapshot host somehow lacks the row.
75
- */
76
- entity_name: string;
77
- /**
78
- * The actor's first `faction:<name>` tag suffix (e.g. "cragmaw"), or `null`
79
- * if it carries no faction tag (#1849 — was previously unreadable from this
80
- * snapshot, leaving combat targets anonymous/faction-blind).
81
- */
82
- faction: string | null;
83
- conditions: ActorConditionRow[];
84
- /**
85
- * The actor's own object-state pools (hp, ability scores, quest stages, …),
86
- * enumerated and enriched with authored display names + tags (#1229). Lets a
87
- * player read its own sheet — including a `quest`-tagged objective's progress
88
- * — without already knowing any state-id. Empty when the actor carries none.
89
- */
90
- states: ActorStateEntry[];
91
- }
92
-
93
- /**
94
- * Read per-actor snapshot. Returns `null` if actor has no `actor_spatial_location` row.
95
- * `stateOpts` passes through to {@link readActorStates} (#1839 bounded view) —
96
- * omitted by default, so existing callers see the full `states` list unchanged.
97
- */
98
- export function readActorSnapshot(
99
- db: SnapshotDb,
100
- actorId: EntityRef,
101
- stateOpts: ReadActorStatesOptions = {},
102
- ): ActorSnapshot | null {
103
- const entityId = resolveEntityId(db, actorId);
104
- if (entityId === undefined) return null;
105
- const locRows = rows<ActorSpatialLocationRow>(db, "visible_actor_spatial_location");
106
- const entityIdText = String(entityId);
107
- const loc = locRows.find((r) => String(r.entityId) === entityIdText);
108
- if (!loc) return null;
109
-
110
- const conditions = buildEntityConditionsMap(db).get(entityIdText) ?? [];
111
-
112
- const node = optString(loc.placeNodeId);
113
- const entityName = buildEntityNameMap(db).get(entityIdText) ?? "";
114
- const faction = buildEntityFactionMap(db).get(entityIdText) ?? null;
115
- const out: ActorSnapshot = {
116
- actor_id: actorId,
117
- entity_name: entityName,
118
- faction,
119
- conditions,
120
- states: readActorStates(db, actorId, stateOpts),
121
- };
122
- if (node !== undefined) out.current_node_id = node;
123
- return out;
124
- }
125
-
126
- /**
127
- * Server-filtered conditions on an entity, independent of whether its place
128
- * node is currently in the caller's location projection.
129
- *
130
- * `readActorSnapshot` is location-gated (co-located scene roster). Act receipts
131
- * must not be: targeting reach can outrun co-location (ranged), while
132
- * `visible_target_condition` already discloses what the caller is entitled to
133
- * know about that body (Public/`observable` conditions such as `dead`).
134
- * Returns `null` only when `actorId` does not resolve to an entity id.
135
- */
136
- export function readActorConditions(
137
- db: SnapshotDb,
138
- actorId: EntityRef,
139
- ): ActorConditionRow[] | null {
140
- const entityId = resolveEntityId(db, actorId);
141
- if (entityId === undefined) return null;
142
- return buildEntityConditionsMap(db).get(String(entityId)) ?? [];
143
- }
144
-
145
- /**
146
- * Map of entity id (string) -> its visible conditions, built once from
147
- * `visible_target_condition` — batch form of the per-entity filter above
148
- * (same "batch join" pattern as `buildEntityFactionMap`/`buildEntityNameMap`,
149
- * `_helpers.ts`), for a reader that enriches many entities per call (scene
150
- * actor detail, U4 — `tool-ux-decision-log.md`). `readActorSnapshot` itself
151
- * uses this too rather than duplicating the filter.
152
- */
153
- export function buildEntityConditionsMap(db: SnapshotDb): Map<string, ActorConditionRow[]> {
154
- const out = new Map<string, ActorConditionRow[]>();
155
- for (const r of rows<TargetConditionRow>(db, "visible_target_condition")) {
156
- const tk = r.targetKind as unknown as { tag?: string } | string;
157
- // Accept either the new tagged shape (live SDK) or the legacy
158
- // lowercase string (snapshot-host fakes that haven't regenerated).
159
- const tag = typeof tk === "string" ? tk : (tk?.tag ?? "");
160
- if (tag !== TARGET_KIND_ENTITY_TAG && tag !== "entity") continue;
161
- const id = String(r.targetId);
162
- const bucket = out.get(id);
163
- if (bucket === undefined) out.set(id, [toConditionRow(r)]);
164
- else bucket.push(toConditionRow(r));
165
- }
166
- for (const bucket of out.values()) bucket.sort(compareConditionRows);
167
- return out;
168
- }
169
-
170
- function compareText(left: string, right: string): number {
171
- return left < right ? -1 : left > right ? 1 : 0;
172
- }
173
-
174
- function compareConditionRows(left: ActorConditionRow, right: ActorConditionRow): number {
175
- return (
176
- compareText(left.condition_definition_id, right.condition_definition_id) ||
177
- left.applied_at_tick - right.applied_at_tick ||
178
- compareText(left.bundle_id, right.bundle_id) ||
179
- compareText(left.source_id, right.source_id) ||
180
- left.stack_count - right.stack_count ||
181
- (left.expires_at_tick ?? Number.MAX_SAFE_INTEGER) -
182
- (right.expires_at_tick ?? Number.MAX_SAFE_INTEGER)
183
- );
184
- }
185
-
186
- function toConditionRow(r: TargetConditionRow): ActorConditionRow {
187
- const expires = optNumber(r.expiresAtTick);
188
- const out: ActorConditionRow = {
189
- condition_definition_id: r.conditionDefinitionId,
190
- applied_at_tick: asNumber(r.appliedAtTick),
191
- stack_count: asNumber(r.stackCount),
192
- bundle_id: r.bundleId,
193
- source_id: r.sourceId,
194
- };
195
- if (expires !== undefined && Number.isFinite(expires)) out.expires_at_tick = expires;
196
- return out;
197
- }