@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.
Files changed (144) hide show
  1. package/LICENSE +89 -0
  2. package/README.md +155 -2
  3. package/package.json +63 -4
  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,112 @@
1
+ // Reader: direct sensing syntax from independently observable world facts.
2
+ //
3
+ // This deliberately joins an actor's visible place, visible niche attachments,
4
+ // and public authored template/outcome metadata. It never evaluates a template
5
+ // predicate or binds a query to a target; r_sense remains the sole authority.
6
+
7
+ import type {
8
+ ActorSpatialLocationRow,
9
+ AffordanceTemplateRow,
10
+ OutcomeTemplateRow,
11
+ VisibleCapabilityRow,
12
+ VisibleSpatialNicheAttachmentRow,
13
+ } from "../../binding_rows";
14
+ import {
15
+ type RequiredTables,
16
+ registerReaderManifest,
17
+ type SnapshotDb,
18
+ } from "../../reader-manifest";
19
+ import type { EntityRef } from "../ids";
20
+ import { asString, resolveEntityId, rows, tagString } from "./_helpers";
21
+
22
+ export const requiredTables: RequiredTables<
23
+ [
24
+ "visible_actor_spatial_location",
25
+ "visible_spatial_niche_attachment",
26
+ "visible_capability",
27
+ "affordance_template",
28
+ "outcome_template",
29
+ ]
30
+ > = [
31
+ "visible_actor_spatial_location",
32
+ "visible_spatial_niche_attachment",
33
+ "visible_capability",
34
+ "affordance_template",
35
+ "outcome_template",
36
+ ];
37
+ registerReaderManifest({ requiredTables });
38
+
39
+ export interface SenseQueryDescriptor {
40
+ query_kind: string;
41
+ visibility: string;
42
+ display_name: string;
43
+ outcome_template_id: string;
44
+ }
45
+
46
+ /** Missing place knowledge is unavailable, distinct from a known place with
47
+ * no authored sensing queries. Queries are unassessed candidates, never offers. */
48
+ export function readSenseContext(
49
+ db: SnapshotDb,
50
+ perceiverEntityId: EntityRef,
51
+ ): { status: "unavailable" } | { status: "ready"; queries: SenseQueryDescriptor[] } {
52
+ const perceiverId = resolveEntityId(db, perceiverEntityId);
53
+ if (perceiverId === undefined) return { status: "unavailable" };
54
+ const location = rows<ActorSpatialLocationRow>(db, "visible_actor_spatial_location").find(
55
+ (row) => String(row.entityId) === String(perceiverId),
56
+ );
57
+ if (location === undefined) return { status: "unavailable" };
58
+ const placeNodeId = asString(location.placeNodeId);
59
+ const visibleNiches = new Set(
60
+ rows<VisibleSpatialNicheAttachmentRow>(db, "visible_spatial_niche_attachment")
61
+ .filter((row) => asString(row.placeNodeId) === placeNodeId)
62
+ .map((row) => asString(row.nicheId)),
63
+ );
64
+ const capabilities = new Set(
65
+ rows<VisibleCapabilityRow>(db, "visible_capability")
66
+ .filter((row) => String(row.entityId) === String(perceiverId))
67
+ .map((row) => asString(row.capabilityId)),
68
+ );
69
+ const outcomesById = new Map(
70
+ rows<OutcomeTemplateRow>(db, "outcome_template").map((row) => [
71
+ asString(row.outcomeTemplateId),
72
+ row,
73
+ ]),
74
+ );
75
+ const deduplicated = new Map<string, SenseQueryDescriptor>();
76
+ for (const template of rows<AffordanceTemplateRow>(db, "affordance_template")) {
77
+ const capability = asString(template.capabilityId).trim();
78
+ // A capability-free sensing template is authored global syntax (the
79
+ // baseline Look query is the concrete case). It has no hidden target or
80
+ // predicate result to disclose, so it must not be accidentally hidden
81
+ // behind a spatial-niche attachment. Capability-bound templates still
82
+ // require their independently visible place/niche anchor.
83
+ if (capability === "" && !visibleNiches.has(asString(template.nicheId))) {
84
+ // No capability is necessary, but a world may still deliberately bind
85
+ // the query to a visible place niche. Only the unbound form is global.
86
+ const hasAnyPlaceAnchor = rows<VisibleSpatialNicheAttachmentRow>(
87
+ db,
88
+ "visible_spatial_niche_attachment",
89
+ ).some((row) => asString(row.nicheId) === asString(template.nicheId));
90
+ if (hasAnyPlaceAnchor) continue;
91
+ } else if (capability !== "" && !visibleNiches.has(asString(template.nicheId))) {
92
+ continue;
93
+ }
94
+ if (capability !== "" && !capabilities.has(capability)) continue;
95
+ const outcome = outcomesById.get(asString(template.outcomeTemplateId));
96
+ if (outcome === undefined) continue;
97
+ const queryKind = asString(outcome.senseQueryKind).trim();
98
+ if (queryKind === "") continue;
99
+ deduplicated.set(queryKind, {
100
+ query_kind: queryKind,
101
+ visibility: tagString(outcome.senseVisibility),
102
+ display_name: asString(outcome.displayName),
103
+ outcome_template_id: asString(outcome.outcomeTemplateId),
104
+ });
105
+ }
106
+ return {
107
+ status: "ready",
108
+ queries: [...deduplicated.values()].sort((left, right) =>
109
+ left.query_kind.localeCompare(right.query_kind),
110
+ ),
111
+ };
112
+ }
@@ -0,0 +1,207 @@
1
+ import type { SessionParticipantRow, SessionRow } from "../../binding_rows";
2
+ import {
3
+ type RequiredTables,
4
+ registerReaderManifest,
5
+ type SnapshotDb,
6
+ } from "../../reader-manifest";
7
+ import { asNumber, asString, rows } from "./_helpers";
8
+
9
+ // Reader over the (already-subscribed) `visible_session` view (raw `session` is
10
+ // private, ADR-0057 / sk-2qt). The turn kernel mirrors
11
+ // the active turn's actor onto `session.current_actor` (server
12
+ // `r_advance_turn` D-2), so a turn-gated client can answer "is it my turn?"
13
+ // from this reader alone, without needing `turn_state` for that specific
14
+ // question. `turn_state` itself now has its own reader (`core/readers/
15
+ // turn_state.ts`, ADR-0093 D-6) — the push-event builder's `turn_transition`
16
+ // domain reads the kernel-authoritative singleton directly rather than this
17
+ // mirror. Type-level read only — no runtime semantic validation (SDK §1).
18
+
19
+ export const requiredTables: RequiredTables<["visible_session"]> = ["visible_session"];
20
+ registerReaderManifest({ requiredTables });
21
+
22
+ export interface SessionSnapshot {
23
+ sessionId: bigint;
24
+ sessionDefId: string;
25
+ lifecycle: string;
26
+ /** The actor whose turn it currently is (the kernel-mirrored active actor). */
27
+ currentActor: string;
28
+ /** Raw session state. On a session terminated by the authored
29
+ * `termination_pred`, `state_json.termination` carries the neutral winner
30
+ * facts (participant tag-group counts + winner_predicate result) that
31
+ * clients derive outcome labels from — the substrate never names them. */
32
+ stateJson: string;
33
+ /** Actor entity id that originated the session open. */
34
+ openedBy: string;
35
+ /** Monotonic turn-advance marker written with current_actor (u64).
36
+ * `null` when the row has not projected the field yet — 0 is a real tick. */
37
+ lastAdvancedAt?: bigint | null;
38
+ }
39
+
40
+ function lastAdvancedAtFromRow(value: unknown): bigint | null {
41
+ if (value === undefined || value === null) return null;
42
+ if (typeof value === "bigint") return value;
43
+ if (typeof value === "number" && Number.isFinite(value)) return BigInt(value);
44
+ if (typeof value === "string" && value.length > 0) {
45
+ try {
46
+ return BigInt(value);
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ return null;
52
+ }
53
+
54
+ function toSnapshot(row: SessionRow): SessionSnapshot {
55
+ const r = row as unknown as {
56
+ sessionId: unknown;
57
+ sessionDefId: string;
58
+ lifecycle: string;
59
+ currentActor: string;
60
+ stateJson: unknown;
61
+ openedBy: unknown;
62
+ lastAdvancedAt: unknown;
63
+ };
64
+ return {
65
+ sessionId: typeof r.sessionId === "bigint" ? r.sessionId : BigInt(String(r.sessionId ?? 0)),
66
+ sessionDefId: r.sessionDefId,
67
+ lifecycle: r.lifecycle,
68
+ currentActor: r.currentActor,
69
+ stateJson: asString(r.stateJson),
70
+ openedBy: asString(r.openedBy),
71
+ lastAdvancedAt: lastAdvancedAtFromRow(r.lastAdvancedAt),
72
+ };
73
+ }
74
+
75
+ /** Session lifecycles in which the actor is still IN the session: the world is
76
+ * waiting on a turn or a reaction, not finished. A reader that collapses any of
77
+ * these to "no session" tells a player mid-fight there is no fight — the
78
+ * player-facing dishonesty measured in sk-awlo.16, where `awaiting-reactions`
79
+ * (a 5e opportunity-attack window opened by walking away) read as a closed
80
+ * session. The complement — `completed` / `abandoned` / `failed` — is terminal.
81
+ *
82
+ * Deliberately EXCLUDES two of the eight canonical lifecycles: `initiated` (a
83
+ * pre-validation transient, not yet accepting moves) and `waiting-on-external`
84
+ * (§7 external-process deferral, not part of the measured player surface —
85
+ * whether it should also read as live is filed as a follow-up, not silently
86
+ * decided here). Canonical vocabulary: server
87
+ * `world_interaction/layer3/session.rs` module docstring. */
88
+ export const LIVE_SESSION_LIFECYCLES = ["active", "awaiting-turn", "awaiting-reactions"] as const;
89
+
90
+ /** True when a session lifecycle means the actor is still in the session. */
91
+ export function isLiveSessionLifecycle(lifecycle: string): boolean {
92
+ return (LIVE_SESSION_LIFECYCLES as readonly string[]).includes(lifecycle);
93
+ }
94
+
95
+ /** Sessions in a terminal lifecycle (`completed` / `failed`), most recent
96
+ * first. Pure read over subscribed rows (SDK §1). */
97
+ export function readTerminalSessions(db: SnapshotDb): SessionSnapshot[] {
98
+ return rows<SessionRow>(db, "visible_session", "session")
99
+ .map(toSnapshot)
100
+ .filter((s) => s.lifecycle === "completed" || s.lifecycle === "failed")
101
+ .sort((a, b) => (a.sessionId < b.sessionId ? 1 : a.sessionId > b.sessionId ? -1 : 0));
102
+ }
103
+
104
+ /** The open session for a given definition id, if one exists. */
105
+ export function readSession(db: SnapshotDb, sessionDefId: string): SessionSnapshot | null {
106
+ const row = rows<SessionRow>(db, "visible_session", "session").find(
107
+ (candidate) => (candidate as unknown as { sessionDefId: string }).sessionDefId === sessionDefId,
108
+ );
109
+ return row ? toSnapshot(row) : null;
110
+ }
111
+
112
+ /** The session row by its numeric id, if present. */
113
+ export function readSessionById(db: SnapshotDb, sessionId: bigint): SessionSnapshot | null {
114
+ const row = rows<SessionRow>(db, "visible_session", "session").find((candidate) => {
115
+ const raw = (candidate as unknown as { sessionId: unknown }).sessionId;
116
+ const id = typeof raw === "bigint" ? raw : BigInt(String(raw ?? 0));
117
+ return id === sessionId;
118
+ });
119
+ return row ? toSnapshot(row) : null;
120
+ }
121
+
122
+ /** The actor whose turn it currently is in the named session, or null if the
123
+ * session is absent. The turn-gating predicate compares this to the caller's
124
+ * own actor id. */
125
+ export function readSessionCurrentActor(db: SnapshotDb, sessionDefId: string): string | null {
126
+ return readSession(db, sessionDefId)?.currentActor ?? null;
127
+ }
128
+
129
+ /** The active session in which it is currently `actorEntityId`'s turn, if any.
130
+ *
131
+ * Pure read over subscribed `visible_session` rows (SDK §1 — no validation). Lets a host
132
+ * resolve "the session I am taking my turn in" without knowing its numeric id:
133
+ * `r_advance_turn` is scoped to a specific session, and an actor can only end the
134
+ * turn of a session where it is the current actor, so matching on `current_actor`
135
+ * picks that session unambiguously even if several sessions are open. Returns the
136
+ * lowest-id match for determinism. */
137
+ export function readActiveSessionForActor(
138
+ db: SnapshotDb,
139
+ actorEntityId: string,
140
+ ): SessionSnapshot | null {
141
+ const matches = rows<SessionRow>(db, "visible_session", "session")
142
+ .map(toSnapshot)
143
+ .filter((s) => isLiveSessionLifecycle(s.lifecycle) && s.currentActor === String(actorEntityId))
144
+ .sort((a, b) => (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
145
+ return matches[0] ?? null;
146
+ }
147
+
148
+ // session_participant carries the turn roster (ordinal order). A turn-gated
149
+ // client reads it to render "who is in this fight and in what order" — the
150
+ // current actor is `session.current_actor`, mirrored by the turn kernel.
151
+ export const participantRequiredTables: RequiredTables<["visible_session_participant"]> = [
152
+ "visible_session_participant",
153
+ ];
154
+ registerReaderManifest({ requiredTables: participantRequiredTables });
155
+
156
+ export interface SessionParticipant {
157
+ actorId: string;
158
+ ordinal: number;
159
+ joinedAt: number;
160
+ }
161
+
162
+ /** Participants of a session, sorted by the authoritative `(ordinal ASC,
163
+ * actor_id ASC)` turn order (server D-I3). Pure read over subscribed rows. */
164
+ export function readSessionParticipants(db: SnapshotDb, sessionId: bigint): SessionParticipant[] {
165
+ const wanted = String(sessionId);
166
+ return rows<SessionParticipantRow>(db, "visible_session_participant", "session_participant")
167
+ .filter((row) => String((row as unknown as { sessionId: unknown }).sessionId) === wanted)
168
+ .map((row) => {
169
+ const r = row as unknown as { actorId: unknown; ordinal: unknown; joinedAt: unknown };
170
+ return {
171
+ actorId: asString(r.actorId),
172
+ ordinal: asNumber(r.ordinal),
173
+ joinedAt: asNumber(r.joinedAt),
174
+ };
175
+ })
176
+ .sort((a, b) =>
177
+ a.ordinal !== b.ordinal
178
+ ? a.ordinal - b.ordinal
179
+ : a.actorId < b.actorId
180
+ ? -1
181
+ : a.actorId > b.actorId
182
+ ? 1
183
+ : 0,
184
+ );
185
+ }
186
+
187
+ /** The active session a given actor is a PARTICIPANT of (whether or not it is
188
+ * currently their turn), with its participant roster. Lets the combat panel
189
+ * render the fight the player is in even while a goblin is acting. Returns the
190
+ * lowest-id active match. */
191
+ export function readActiveSessionWithRosterForParticipant(
192
+ db: SnapshotDb,
193
+ actorEntityId: string,
194
+ ): { session: SessionSnapshot; participants: SessionParticipant[] } | null {
195
+ const wanted = String(actorEntityId);
196
+ const active = rows<SessionRow>(db, "visible_session", "session")
197
+ .map(toSnapshot)
198
+ .filter((s) => isLiveSessionLifecycle(s.lifecycle))
199
+ .sort((a, b) => (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
200
+ for (const session of active) {
201
+ const participants = readSessionParticipants(db, session.sessionId);
202
+ if (participants.some((p) => p.actorId === wanted)) {
203
+ return { session, participants };
204
+ }
205
+ }
206
+ return null;
207
+ }
@@ -0,0 +1,211 @@
1
+ import type {
2
+ ActionDefinitionRow,
3
+ EntityRow,
4
+ SessionDefinitionRow,
5
+ SessionRow,
6
+ WorldTimeRow,
7
+ } 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 { targetRefToString } from "../reducers/transport";
15
+ import { asString, resolveEntityId, rows } from "./_helpers";
16
+ import { readInventoryProjection } from "./inventory_query";
17
+ import { readObserverKnowledge } from "./observer_knowledge";
18
+ import { readObserverPlaceKnowledge } from "./observer_place_knowledge";
19
+ import { readSessionParticipants } from "./session";
20
+
21
+ export const requiredTables: RequiredTables<
22
+ ["visible_session", "session_definition", "action_definition"]
23
+ > = ["visible_session", "session_definition", "action_definition"];
24
+ registerReaderManifest({ requiredTables });
25
+
26
+ const TERMINAL_PHASES = new Set(["completed", "failed", "abandoned"]);
27
+
28
+ export interface ParticipantSessionSummary {
29
+ session_id: string;
30
+ lifecycle: string;
31
+ label: string | null;
32
+ }
33
+
34
+ /** Stable authorized domain rows; PLAYER tools own bounded pagination. */
35
+ export function readParticipantSessionSummaries(
36
+ db: SnapshotDb,
37
+ actor: EntityRef,
38
+ ): ParticipantSessionSummary[] {
39
+ const resolved = resolveEntityId(db, actor);
40
+ if (resolved === undefined) return [];
41
+ const actorId = String(resolved);
42
+ const actions = new Map(
43
+ rows<ActionDefinitionRow>(db, "action_definition").map((row) => [row.actionId, row]),
44
+ );
45
+ return rows<SessionRow>(db, "visible_session", "session")
46
+ .filter(
47
+ (row) =>
48
+ !TERMINAL_PHASES.has(row.lifecycle) &&
49
+ readSessionParticipants(db, row.sessionId).some(
50
+ (participant) => participant.actorId === actorId,
51
+ ),
52
+ )
53
+ .sort((a, b) => (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0))
54
+ .map((row) => ({
55
+ session_id: String(row.sessionId),
56
+ lifecycle: row.lifecycle,
57
+ label: actions.get(row.originatingAction)?.displayName?.trim() || null,
58
+ }));
59
+ }
60
+
61
+ export interface ParticipantSessionDetail {
62
+ session_id: string;
63
+ session_definition_id: string;
64
+ lifecycle: string;
65
+ label: string | null;
66
+ description: string | null;
67
+ turn_rule: string | null;
68
+ round_duration_ms: string | null;
69
+ opened_by: string | null;
70
+ /** `name` is the participant's entity name when the caller can see that
71
+ * entity (`visible_entity`), else `null` — a client renders the id
72
+ * otherwise, which is what a fight roster of "145, 143, 147" looked like. */
73
+ roster: Array<{ actor_id: string; ordinal: number; name: string | null }>;
74
+ current_actor: string | null;
75
+ my_turn: boolean;
76
+ originating_action: string | null;
77
+ originating_target: string | null;
78
+ timing: {
79
+ basis: "world_ticks";
80
+ observed_at: string | null;
81
+ last_tick_at_micros: string | null;
82
+ opened_at: string | null;
83
+ last_advanced_at: string | null;
84
+ duration_ticks: string | null;
85
+ estimated_completion_at: string | null;
86
+ estimated_remaining_ticks: string | null;
87
+ };
88
+ }
89
+
90
+ /** Missing snapshot fields are unknown, never fabricated tick zero. */
91
+ function tick(value: unknown): bigint | null {
92
+ if (typeof value === "bigint") return value >= 0n ? value : null;
93
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) return BigInt(value);
94
+ if (typeof value === "string" && /^\d+$/.test(value)) return BigInt(value);
95
+ return null;
96
+ }
97
+
98
+ function knownOriginTarget(
99
+ db: SnapshotDb,
100
+ actor: EntityRef,
101
+ actorId: string,
102
+ row: SessionRow,
103
+ ): string | null {
104
+ const target = row.originatingTarget;
105
+ if (!target) return null;
106
+ if (target.tag === "World") return "world";
107
+ if (target.tag === "Entity" || target.tag === "Item") {
108
+ const id = String(target.value);
109
+ const known =
110
+ id === actorId ||
111
+ readObserverKnowledge(db, actorId).some((entry) => entry.known_entity_id === id) ||
112
+ readInventoryProjection(db, actor)?.items.some((item) => item.entity_id === id);
113
+ return known ? targetRefToString(target) : null;
114
+ }
115
+ if (target.tag === "PlaceNode") {
116
+ return readObserverPlaceKnowledge(db, actorId).some(
117
+ (entry) => entry.known_node_id === target.value,
118
+ )
119
+ ? targetRefToString(target)
120
+ : null;
121
+ }
122
+ // Other target variants need an equivalent authorized disclosure reader.
123
+ return null;
124
+ }
125
+
126
+ /** Read only a caller-visible session in which this actor participates.
127
+ * Explicit selection follows a session through terminal states; the default
128
+ * selects the lowest-id nonterminal session, including external waits.
129
+ * This does not broaden the compact combat reader or decide action admission.
130
+ */
131
+ export function readParticipantSessionDetail(
132
+ db: SnapshotDb,
133
+ actor: EntityRef,
134
+ sessionId?: string,
135
+ ): ParticipantSessionDetail | null {
136
+ const resolved = resolveEntityId(db, actor);
137
+ if (resolved === undefined) return null;
138
+ const actorId = String(resolved);
139
+ const candidates = rows<SessionRow>(db, "visible_session", "session")
140
+ .filter((row) =>
141
+ sessionId === undefined
142
+ ? !TERMINAL_PHASES.has(row.lifecycle)
143
+ : String(row.sessionId) === sessionId,
144
+ )
145
+ .sort((a, b) => (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
146
+ const row = candidates.find((candidate) =>
147
+ readSessionParticipants(db, candidate.sessionId).some(
148
+ (participant) => participant.actorId === actorId,
149
+ ),
150
+ );
151
+ if (!row) return null;
152
+ const definition = rows<SessionDefinitionRow>(db, "session_definition").find(
153
+ (candidate) => candidate.sessionDefId === row.sessionDefId,
154
+ );
155
+ const action = rows<ActionDefinitionRow>(db, "action_definition").find(
156
+ (candidate) => candidate.actionId === row.originatingAction,
157
+ );
158
+ const worldTime = rows<WorldTimeRow>(db, "world_time")[0];
159
+ const now = tick(worldTime?.tick);
160
+ const participants = readSessionParticipants(db, row.sessionId);
161
+ const entityRows = rows<EntityRow>(db, "entity");
162
+ const openedBy = row.openedBy;
163
+ const knownOpener =
164
+ openedBy === actorId ||
165
+ participants.some((entry) => entry.actorId === openedBy) ||
166
+ readObserverKnowledge(db, actorId).some((entry) => entry.known_entity_id === openedBy);
167
+ const roundDuration = tick(definition?.roundDurationMs);
168
+ const opened = tick(row.openedAt);
169
+ const duration = tick(row.promotedDurationTicks);
170
+ const positiveDuration = duration !== null && duration > 0n ? duration : null;
171
+ const completion =
172
+ opened !== null && positiveDuration !== null ? opened + positiveDuration : null;
173
+ const remaining =
174
+ completion !== null && now !== null ? (completion > now ? completion - now : 0n) : null;
175
+ return {
176
+ session_id: String(row.sessionId),
177
+ session_definition_id: row.sessionDefId,
178
+ lifecycle: row.lifecycle,
179
+ label: action?.displayName?.trim() || null,
180
+ // Neither SessionDefinition nor ActionDefinition persists description prose.
181
+ description: null,
182
+ turn_rule: definition?.turnRule || null,
183
+ round_duration_ms: roundDuration !== null && roundDuration > 0n ? String(roundDuration) : null,
184
+ opened_by: openedBy && knownOpener ? openedBy : null,
185
+ roster: participants.map((entry) => ({
186
+ actor_id: entry.actorId,
187
+ ordinal: entry.ordinal,
188
+ name: participantName(entityRows, entry.actorId),
189
+ })),
190
+ current_actor: row.currentActor || null,
191
+ my_turn: row.currentActor === actorId,
192
+ originating_action: row.originatingAction || null,
193
+ originating_target: row.originatingAction ? knownOriginTarget(db, actor, actorId, row) : null,
194
+ timing: {
195
+ basis: "world_ticks",
196
+ observed_at: now?.toString() ?? null,
197
+ last_tick_at_micros: worldTime?.lastTickAt?.microsSinceUnixEpoch?.toString() ?? null,
198
+ opened_at: opened?.toString() ?? null,
199
+ last_advanced_at: tick(row.lastAdvancedAt)?.toString() ?? null,
200
+ duration_ticks: positiveDuration?.toString() ?? null,
201
+ estimated_completion_at: completion?.toString() ?? null,
202
+ estimated_remaining_ticks: remaining?.toString() ?? null,
203
+ },
204
+ };
205
+ }
206
+
207
+ function participantName(entityRows: readonly EntityRow[], actorId: string): string | null {
208
+ const name = entityRows.find((row) => String(row.entityId) === actorId)?.name;
209
+ const text = asString(name);
210
+ return text === "" ? null : text;
211
+ }
@@ -0,0 +1,68 @@
1
+ import type { EntityRow } from "../../binding_rows";
2
+ import {
3
+ type RequiredTables,
4
+ registerReaderManifest,
5
+ type SnapshotDb,
6
+ } from "../../reader-manifest";
7
+ import { asEntityRef, type EntityRef } from "../ids";
8
+ import { asString, resolveEntityId, rows } from "./_helpers";
9
+ import { readActiveSessionWithRosterForParticipant } from "./session";
10
+
11
+ export const requiredTables: RequiredTables<
12
+ ["visible_manifest_authored_entity", "visible_manifest_authored_entity_coverage"]
13
+ > = ["visible_manifest_authored_entity", "visible_manifest_authored_entity_coverage"];
14
+ registerReaderManifest({ requiredTables });
15
+
16
+ export interface ParticipantSessionStatus {
17
+ /** Explicitly distinguishes an active session from the `null` no-session result.
18
+ * PLAYER orientation consumes this field directly, rather than inferring it
19
+ * from a presentation status string. */
20
+ in_session: true;
21
+ session_id: string;
22
+ session_definition_id: string;
23
+ lifecycle: string;
24
+ current_actor: string;
25
+ my_turn: boolean;
26
+ participant_count: number;
27
+ /** `name` is the participant's entity name when the caller can see that
28
+ * entity, else `null` — without it a client's fight roster read
29
+ * "145, 143, 147". */
30
+ roster: Array<{ actor_id: EntityRef; ordinal: number; name: string | null }>;
31
+ }
32
+
33
+ /** Compact active-session projection for one participant.
34
+ *
35
+ * The caller supplies its already-authenticated actor/body id. No session id is
36
+ * accepted: the lowest-id active session containing that participant is selected
37
+ * deterministically, and its roster keeps authoritative ordinal/actor ordering.
38
+ */
39
+ export function readParticipantSessionStatus(
40
+ db: SnapshotDb,
41
+ actorEntityRef: EntityRef,
42
+ ): ParticipantSessionStatus | null {
43
+ const actorEntityId = resolveEntityId(db, actorEntityRef);
44
+ const entityRows = rows<EntityRow>(db, "entity");
45
+ if (actorEntityId === undefined) return null;
46
+ const actorEntityIdText = String(actorEntityId);
47
+ const active = readActiveSessionWithRosterForParticipant(db, actorEntityIdText);
48
+ if (active === null) return null;
49
+ return {
50
+ in_session: true,
51
+ session_id: String(active.session.sessionId),
52
+ session_definition_id: active.session.sessionDefId,
53
+ lifecycle: active.session.lifecycle,
54
+ current_actor: active.session.currentActor,
55
+ my_turn: active.session.currentActor === actorEntityIdText,
56
+ participant_count: active.participants.length,
57
+ roster: active.participants.map((participant) => ({
58
+ actor_id: asEntityRef(participant.actorId),
59
+ ordinal: participant.ordinal,
60
+ name: participantName(entityRows, participant.actorId),
61
+ })),
62
+ };
63
+ }
64
+
65
+ function participantName(entityRows: readonly EntityRow[], actorId: string): string | null {
66
+ const name = asString(entityRows.find((row) => String(row.entityId) === actorId)?.name);
67
+ return name === "" ? null : name;
68
+ }
@@ -0,0 +1,74 @@
1
+ // Reader: spatial_environment_state (room/edge-topology env-state, ADR-0056).
2
+ // The carrier for the ActorReachableNodes N-hop fanout (ADR-0076) —
3
+ // e.g. an alarm bool cascaded across every place-node within a hop radius.
4
+ // Generic over state vocabulary: a modder's own topology-scoped bool/int/text
5
+ // marker reads the same way as a phandelver-authored one.
6
+ //
7
+ // `spatial_environment_state` is private (ADR-0120, #915 sweep PR-4); read
8
+ // the per-caller `visible_spatial_environment_state` view.
9
+
10
+ import { resolveEffectiveSpatialEnvironmentStates } from "../effective_environment_state";
11
+
12
+ export { resolveEffectiveSpatialEnvironmentStates } from "../effective_environment_state";
13
+
14
+ import type { SpatialEnvironmentStateRow } from "../../binding_rows";
15
+ import {
16
+ type RequiredTables,
17
+ registerReaderManifest,
18
+ type SnapshotDb,
19
+ } from "../../reader-manifest";
20
+ import { rows, tagString } from "./_helpers";
21
+
22
+ export const requiredTables: RequiredTables<["visible_spatial_environment_state"]> = [
23
+ "visible_spatial_environment_state",
24
+ ];
25
+ registerReaderManifest({ requiredTables });
26
+
27
+ /** The projected identity/rank columns, derived from generated bindings. */
28
+ export type EnvironmentStateCandidate = Partial<
29
+ Pick<
30
+ SpatialEnvironmentStateRow,
31
+ | "bundleId"
32
+ | "stateId"
33
+ | "stateRowId"
34
+ | "updatedTick"
35
+ | "targetKind"
36
+ | "targetRef"
37
+ | "placeNodeId"
38
+ | "placeEdgeId"
39
+ | "locationDefId"
40
+ | "cellRes10"
41
+ | "cellRes7"
42
+ | "cellRes4"
43
+ | "substrateId"
44
+ >
45
+ >;
46
+
47
+ export interface SpatialNodeStateRef {
48
+ placeNodeId: string;
49
+ stateId: string;
50
+ }
51
+
52
+ function dslBoolValue(value: unknown): boolean | null {
53
+ if (typeof value === "boolean") return value;
54
+ if (!value || typeof value !== "object") return null;
55
+ const record = value as Record<string, unknown>;
56
+ if (tagString(record.tag) === "Bool") return Boolean(record.value);
57
+ if ("Bool" in record) return Boolean((record as { Bool: unknown }).Bool);
58
+ return null;
59
+ }
60
+
61
+ /**
62
+ * Read a single place-node's topology-scoped bool env-state
63
+ * (`spatial_environment_state`, `target_kind = "place_node"`). Returns `null` when
64
+ * no row exists for `(placeNodeId, stateId)` (never cascaded there) or the
65
+ * row's value is not a `DslValue::Bool` carrier.
66
+ */
67
+ export function readSpatialNodeStateBool(db: SnapshotDb, ref: SpatialNodeStateRef): boolean | null {
68
+ const row = resolveEffectiveSpatialEnvironmentStates(
69
+ rows<SpatialEnvironmentStateRow>(db, "visible_spatial_environment_state"),
70
+ ).find(
71
+ (candidate) => candidate.placeNodeId === ref.placeNodeId && candidate.stateId === ref.stateId,
72
+ );
73
+ return row === undefined ? null : dslBoolValue(row.value);
74
+ }