@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,44 +0,0 @@
1
- import type { SessionRow } from "../../binding_rows";
2
- import type { SnapshotDb } from "../../reader-manifest";
3
- import { rows } from "./_helpers";
4
- import {
5
- isLiveSessionLifecycle,
6
- readSessionParticipants,
7
- type SessionParticipant,
8
- type SessionSnapshot,
9
- } from "./session";
10
-
11
- /** Find the active session (if any) that `actorId` participates in. */
12
- export function activeSessionForParticipant(
13
- db: SnapshotDb,
14
- actorId: string,
15
- ): { session: SessionSnapshot; participants: SessionParticipant[] } | null {
16
- const active = rows<SessionRow>(db, "visible_session", "session")
17
- .map((row) => {
18
- const r = row as unknown as {
19
- sessionId: unknown;
20
- sessionDefId: string;
21
- lifecycle: string;
22
- currentActor: string;
23
- stateJson: unknown;
24
- openedBy: unknown;
25
- };
26
- return {
27
- sessionId: typeof r.sessionId === "bigint" ? r.sessionId : BigInt(String(r.sessionId ?? 0)),
28
- sessionDefId: r.sessionDefId,
29
- lifecycle: r.lifecycle,
30
- currentActor: r.currentActor,
31
- stateJson: String(r.stateJson ?? ""),
32
- openedBy: String(r.openedBy ?? ""),
33
- };
34
- })
35
- .filter((session) => isLiveSessionLifecycle(session.lifecycle))
36
- .sort((a, b) => (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
37
- for (const session of active) {
38
- const participants = readSessionParticipants(db, session.sessionId);
39
- if (participants.some((participant) => participant.actorId === actorId)) {
40
- return { session, participants };
41
- }
42
- }
43
- return null;
44
- }
@@ -1,37 +0,0 @@
1
- import type { EvaluationProvenanceRow, WorldEventRow } from "../../binding_rows";
2
- import { asNumber, asString, tagString } from "./_helpers";
3
- import type { CombatFeedback } from "./combat_session_types";
4
-
5
- export function latestFeedback(
6
- heroId: string,
7
- provenanceRows: EvaluationProvenanceRow[],
8
- eventRows: WorldEventRow[],
9
- ): CombatFeedback {
10
- const failure = provenanceRows
11
- .filter((row) => asString(row.subjectId) === heroId && failureStatus(row.status))
12
- .sort((a, b) => Number(asNumber(a.createdAtTick) - asNumber(b.createdAtTick)))
13
- .at(-1);
14
- if (failure) {
15
- return {
16
- kind: "rejection",
17
- text: playerFacingFailure(asString(failure.failureKind), asString(failure.failureDetail)),
18
- };
19
- }
20
- const event = eventRows
21
- .filter((row) => asString(row.summary).length > 0)
22
- .sort((a, b) => Number(asNumber(a.tick) - asNumber(b.tick) || asNumber(a.id) - asNumber(b.id)))
23
- .at(-1);
24
- if (event) return { kind: "event", text: asString(event.summary) };
25
- return { kind: "none", text: "No combat outcome observed yet." };
26
- }
27
-
28
- function failureStatus(status: unknown): boolean {
29
- const normalized = tagString(status).toLowerCase();
30
- return normalized === "failed" || normalized === "failure" || normalized === "rolledback";
31
- }
32
-
33
- function playerFacingFailure(kind: string, detail: string): string {
34
- if (kind === "not_your_turn") return detail || "It is not your turn.";
35
- if (kind.length > 0 && detail.length > 0) return `${kind}: ${detail}`;
36
- return detail || kind || "Action rejected.";
37
- }
@@ -1,117 +0,0 @@
1
- import type {
2
- PlaceEdgeAffordanceRow,
3
- PlaceEdgeRow,
4
- PlaceGraphDefinitionRow,
5
- PlaceNodeRow,
6
- } from "../../binding_rows";
7
- import { asNumber, asString } from "./_helpers";
8
- import type { CombatMove, CombatRosterEntry, CombatSessionView } from "./combat_session_types";
9
-
10
- export function gridForSession(
11
- sessionId: bigint,
12
- heroId: string,
13
- graphs: PlaceGraphDefinitionRow[],
14
- nodes: PlaceNodeRow[],
15
- edges: PlaceEdgeRow[],
16
- edgeAffordances: PlaceEdgeAffordanceRow[],
17
- roster: CombatRosterEntry[],
18
- positions: Map<string, string>,
19
- ): CombatSessionView["grid"] {
20
- const graphId = `session_grid_${sessionId.toString()}`;
21
- const graph = graphs.find(
22
- (row) => row.placeGraphId === graphId && Boolean(row.isEphemeralInstance),
23
- );
24
- if (!graph) return null;
25
- const cells = nodes
26
- .filter((node) => node.placeGraphId === graphId)
27
- .map((node) => ({
28
- nodeId: asString(node.nodeId),
29
- x: asNumber(node.posX),
30
- y: asNumber(node.posY),
31
- occupants: roster
32
- .filter((entry) => entry.nodeId === node.nodeId)
33
- .map((entry) => entry.actorId),
34
- }))
35
- .sort((a, b) => (a.y !== b.y ? a.y - b.y : a.x - b.x));
36
- const width = cells.reduce((max, cell) => Math.max(max, cell.x + 1), 0);
37
- const height = cells.reduce((max, cell) => Math.max(max, cell.y + 1), 0);
38
- const heroNodeId = positions.get(heroId);
39
- const moves =
40
- heroNodeId === undefined
41
- ? []
42
- : edges
43
- .filter((edge) => edge.placeGraphId === graphId && edge.fromNodeId === heroNodeId)
44
- .map((edge) => {
45
- const to = nodes.find((node) => node.nodeId === edge.toNodeId);
46
- const from = nodes.find((node) => node.nodeId === edge.fromNodeId);
47
- return {
48
- edgeId: asString(edge.edgeId),
49
- toNodeId: asString(edge.toNodeId),
50
- direction: directionFor(from, to),
51
- ...movePolicyFor(edge, edgeAffordances),
52
- };
53
- })
54
- .sort(
55
- (a, b) =>
56
- a.direction.localeCompare(b.direction) || a.toNodeId.localeCompare(b.toNodeId),
57
- );
58
- return {
59
- graphId,
60
- anchorNodeId: asString(graph.anchorNodeId),
61
- width,
62
- height,
63
- cells,
64
- moves,
65
- };
66
- }
67
-
68
- function movePolicyFor(
69
- edge: PlaceEdgeRow,
70
- edgeAffordances: PlaceEdgeAffordanceRow[],
71
- ): Pick<CombatMove, "label" | "costCells" | "blocked"> {
72
- const bindings = edgeAffordances
73
- .filter((row) => row.edgeKey === edge.edgeKey)
74
- .map((row) => bindingsObject(row.bindingsJson))
75
- .reduce<Record<string, string>>((acc, row) => Object.assign(acc, row), {});
76
- const costCells = Number(bindings.movement_cost_cells ?? "1");
77
- const blocked = bindings.blocked === "true" || (Number.isFinite(costCells) && costCells >= 9999);
78
- return {
79
- label:
80
- bindings.movement_label ||
81
- (Number.isFinite(costCells) && costCells > 1 ? `Cost ${formatCost(costCells)} cells` : ""),
82
- costCells: Number.isFinite(costCells) && costCells > 0 ? costCells : 1,
83
- blocked,
84
- };
85
- }
86
-
87
- function formatCost(value: number): string {
88
- return Number.isInteger(value) ? value.toString() : value.toFixed(1);
89
- }
90
-
91
- function bindingsObject(raw: unknown): Record<string, string> {
92
- if (typeof raw !== "string" || raw.trim().length === 0) return {};
93
- try {
94
- const parsed = JSON.parse(raw) as unknown;
95
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
96
- return Object.fromEntries(
97
- Object.entries(parsed as Record<string, unknown>).map(([key, value]) => [key, String(value)]),
98
- );
99
- } catch {
100
- return {};
101
- }
102
- }
103
-
104
- function directionFor(from: PlaceNodeRow | undefined, to: PlaceNodeRow | undefined): string {
105
- if (!from?.posPresent || !to?.posPresent) return "move";
106
- const dx = asNumber(to.posX) - asNumber(from.posX);
107
- const dy = asNumber(to.posY) - asNumber(from.posY);
108
- if (dx === 0 && dy < 0) return "north";
109
- if (dx === 0 && dy > 0) return "south";
110
- if (dx > 0 && dy === 0) return "east";
111
- if (dx < 0 && dy === 0) return "west";
112
- if (dx > 0 && dy < 0) return "northeast";
113
- if (dx > 0 && dy > 0) return "southeast";
114
- if (dx < 0 && dy < 0) return "northwest";
115
- if (dx < 0 && dy > 0) return "southwest";
116
- return "move";
117
- }
@@ -1,98 +0,0 @@
1
- import type { EntityRow, ObjectStateRow, PlaceNodeRow } from "../../binding_rows";
2
- import { asNumber, asString, tagString } from "./_helpers";
3
- import type { CombatRosterEntry } from "./combat_session_types";
4
- import type { SessionParticipant } from "./session";
5
-
6
- /** Build the disambiguated combat roster for a session's participants. */
7
- export function buildRoster(
8
- participants: SessionParticipant[],
9
- currentActor: string,
10
- heroId: string,
11
- entityRows: EntityRow[],
12
- stateRows: ObjectStateRow[],
13
- positions: Map<string, string>,
14
- nodes: PlaceNodeRow[],
15
- ): CombatRosterEntry[] {
16
- return disambiguateDuplicateNames(
17
- participants.map((participant) =>
18
- rosterEntry(participant, currentActor, heroId, entityRows, stateRows, positions, nodes),
19
- ),
20
- );
21
- }
22
-
23
- export function nextRosterEntry(
24
- roster: CombatRosterEntry[],
25
- currentActor: string,
26
- ): CombatRosterEntry | null {
27
- const live = roster.filter((entry) => !entry.defeated);
28
- const currentIndex = live.findIndex((entry) => entry.actorId === currentActor);
29
- if (live.length === 0 || currentIndex < 0) return null;
30
- return live[(currentIndex + 1) % live.length] ?? null;
31
- }
32
-
33
- function disambiguateDuplicateNames(roster: CombatRosterEntry[]): CombatRosterEntry[] {
34
- const totals = new Map<string, number>();
35
- for (const entry of roster) {
36
- if (entry.isHero) continue;
37
- totals.set(entry.name, (totals.get(entry.name) ?? 0) + 1);
38
- }
39
- const seen = new Map<string, number>();
40
- return roster.map((entry) => {
41
- if (entry.isHero || (totals.get(entry.name) ?? 0) < 2) return entry;
42
- const index = (seen.get(entry.name) ?? 0) + 1;
43
- seen.set(entry.name, index);
44
- return { ...entry, name: `${entry.name} ${index}` };
45
- });
46
- }
47
-
48
- function rosterEntry(
49
- participant: SessionParticipant,
50
- currentActor: string,
51
- heroId: string,
52
- entityRows: EntityRow[],
53
- stateRows: ObjectStateRow[],
54
- positions: Map<string, string>,
55
- nodes: PlaceNodeRow[],
56
- ): CombatRosterEntry {
57
- const name = entityRows.find((row) => String(row.entityId) === participant.actorId)?.name;
58
- const hp = hpFor(participant.actorId, stateRows);
59
- const nodeId = positions.get(participant.actorId);
60
- const node =
61
- nodeId === undefined ? undefined : nodes.find((candidate) => candidate.nodeId === nodeId);
62
- return {
63
- actorId: participant.actorId,
64
- name: asString(name) || `entity:${participant.actorId}`,
65
- hp,
66
- defeated: hp !== undefined && hp <= 0,
67
- isCurrent: participant.actorId === currentActor,
68
- isHero: participant.actorId === heroId,
69
- nodeId,
70
- cell: node?.posPresent ? { x: asNumber(node.posX), y: asNumber(node.posY) } : undefined,
71
- };
72
- }
73
-
74
- function hpFor(actorId: string, rows: ObjectStateRow[]): number | undefined {
75
- const row = rows.find(
76
- (candidate) =>
77
- targetKindMatches(candidate.targetKind, "entity") &&
78
- String(candidate.targetId) === actorId &&
79
- asString(candidate.stateId).endsWith("/hp"),
80
- );
81
- const value = row ? dslIntValue(row.value) : null;
82
- return value === null ? undefined : Number(value);
83
- }
84
-
85
- function targetKindMatches(actual: unknown, expected: string): boolean {
86
- return tagString(actual).replace(/_/g, "").toLowerCase() === expected;
87
- }
88
-
89
- function dslIntValue(value: unknown): bigint | null {
90
- if (typeof value === "bigint") return value;
91
- if (typeof value === "number") return BigInt(value);
92
- if (typeof value === "string" && /^-?\d+$/.test(value)) return BigInt(value);
93
- if (!value || typeof value !== "object") return null;
94
- const record = value as Record<string, unknown>;
95
- if (tagString(record.tag) === "Int") return dslIntValue(record.value);
96
- if ("Int" in record) return dslIntValue(record.Int);
97
- return null;
98
- }
@@ -1,51 +0,0 @@
1
- import type { SessionSnapshot } from "./session";
2
-
3
- export interface CombatRosterEntry {
4
- actorId: string;
5
- name: string;
6
- hp?: number;
7
- defeated: boolean;
8
- isCurrent: boolean;
9
- isHero: boolean;
10
- nodeId?: string;
11
- cell?: { x: number; y: number };
12
- }
13
-
14
- export interface CombatGridCell {
15
- nodeId: string;
16
- x: number;
17
- y: number;
18
- occupants: string[];
19
- }
20
-
21
- export interface CombatMove {
22
- edgeId: string;
23
- toNodeId: string;
24
- direction: string;
25
- label: string;
26
- costCells: number;
27
- blocked: boolean;
28
- }
29
-
30
- export interface CombatFeedback {
31
- text: string;
32
- kind: "event" | "rejection" | "none";
33
- }
34
-
35
- export interface CombatSessionView {
36
- session: SessionSnapshot;
37
- roster: CombatRosterEntry[];
38
- currentActorName: string;
39
- nextActorName: string | null;
40
- isHeroTurn: boolean;
41
- waitingReason: string | null;
42
- grid: {
43
- graphId: string;
44
- anchorNodeId: string;
45
- width: number;
46
- height: number;
47
- cells: CombatGridCell[];
48
- moves: CombatMove[];
49
- } | null;
50
- feedback: CombatFeedback;
51
- }
@@ -1,53 +0,0 @@
1
- import type { EventConditionDeltaRow as DbEventConditionDeltaRow } from "../../binding_rows";
2
- import {
3
- type RequiredTables,
4
- registerReaderManifest,
5
- type SnapshotDb,
6
- } from "../../reader-manifest";
7
- import { asNumber, asString, optString, rows } from "./_helpers";
8
-
9
- // `event_condition_delta` is private (ADR-0120, K-B Part B — #1332-precedent
10
- // sibling of event_resource_delta). Subscribe + read the per-caller
11
- // `visible_event_condition_delta` view instead (owner/DM-extent-bounded),
12
- // same shape as resource_deltas.ts.
13
- export const requiredTables: RequiredTables<["visible_event_condition_delta"]> = [
14
- "visible_event_condition_delta",
15
- ];
16
- registerReaderManifest({ requiredTables });
17
-
18
- export interface ConditionDeltaEventRow {
19
- event_id: string;
20
- entity_id: string;
21
- condition_definition_id: string;
22
- /** `true` for an insert/reapply, `false` for a removal (explicit, cascade,
23
- * or expiry — one shape, server side). */
24
- applied: boolean;
25
- /** ADR-0093 B2-style attribution: the acting entity that caused this
26
- * change, denormalised onto the row at emit time (mirrors
27
- * `event_resource_delta.source_entity_ref`). `undefined` for an
28
- * ambient/ownerless change (expiry sweep, cascade child, seed/clone —
29
- * those never reach this table at all) — the server carries this as an
30
- * empty string (`String`, not `Option<u64>`), so an empty value maps to
31
- * `undefined` here, never `""`. */
32
- source_entity_ref?: string;
33
- /** The `consequence_template` that authored this write, when one exists.
34
- * Empty for an implicit/cascade/expiry write with no originating
35
- * template. */
36
- template_id: string;
37
- expires_at_tick: number;
38
- }
39
-
40
- export function readRecentConditionDeltas(db: SnapshotDb, n: number): ConditionDeltaEventRow[] {
41
- if (n <= 0) return [];
42
- const all = rows<DbEventConditionDeltaRow>(db, "visible_event_condition_delta").map((row) => ({
43
- event_id: asString(row.eventId),
44
- entity_id: asString(row.entityId),
45
- condition_definition_id: row.conditionDefinitionId,
46
- applied: Boolean(row.applied),
47
- source_entity_ref: optString(row.sourceEntityRef),
48
- template_id: row.templateId,
49
- expires_at_tick: asNumber(row.expiresAtTick),
50
- }));
51
- all.sort((a, b) => b.event_id.localeCompare(a.event_id, undefined, { numeric: true }));
52
- return all.slice(0, n);
53
- }
@@ -1,92 +0,0 @@
1
- // Reads the server-admitted direct-child projection; never infers containment.
2
- import type { ObservedContainerContentRow, ObservedContainerCoverageRow } from "../../binding_rows";
3
- import {
4
- type RequiredTables,
5
- registerReaderManifest,
6
- type SnapshotDb,
7
- } from "../../reader-manifest";
8
- import type { EntityRef } from "../ids";
9
- import { asString, resolveEntityId, rows } from "./_helpers";
10
-
11
- export const requiredTables: RequiredTables<
12
- [
13
- "visible_observed_container_content",
14
- "visible_observed_container_coverage",
15
- "visible_manifest_authored_entity",
16
- "visible_manifest_authored_entity_coverage",
17
- ]
18
- > = [
19
- "visible_observed_container_content",
20
- "visible_observed_container_coverage",
21
- "visible_manifest_authored_entity",
22
- "visible_manifest_authored_entity_coverage",
23
- ];
24
- registerReaderManifest({ requiredTables });
25
-
26
- export interface ObservedContainerItem {
27
- target_ref: string;
28
- parent_ref: string;
29
- name: string;
30
- quantity: number;
31
- entity_def_id: string;
32
- }
33
-
34
- export interface ObservedContainerContents {
35
- container_ref: string;
36
- scope: "direct";
37
- revision: string;
38
- status: "available" | "empty" | "unavailable" | "truncated";
39
- items: ObservedContainerItem[];
40
- }
41
-
42
- /** Older modules or absent coverage return the same unavailable envelope. */
43
- export function readContainerContents(
44
- db: SnapshotDb,
45
- actor: EntityRef,
46
- containerRef: string,
47
- ): ObservedContainerContents {
48
- const result: ObservedContainerContents = {
49
- container_ref: containerRef,
50
- scope: "direct",
51
- revision: "unavailable",
52
- status: "unavailable",
53
- items: [],
54
- };
55
- const actorId = resolveEntityId(db, actor);
56
- const containerId = /^(?:entity|item):(\d+)$/.exec(containerRef)?.[1];
57
- if (!actorId || !containerId) return result;
58
- const coverage = rows<ObservedContainerCoverageRow>(
59
- db,
60
- "visibleObservedContainerCoverage",
61
- "visible_observed_container_coverage",
62
- ).find(
63
- (row) =>
64
- asString(row.perceiverEntityId) === asString(actorId) &&
65
- asString(row.containerEntityId) === containerId,
66
- );
67
- if (!coverage) return result;
68
- const items = rows<ObservedContainerContentRow>(
69
- db,
70
- "visibleObservedContainerContent",
71
- "visible_observed_container_content",
72
- )
73
- .filter(
74
- (row) =>
75
- asString(row.perceiverEntityId) === asString(actorId) &&
76
- asString(row.containerEntityId) === containerId,
77
- )
78
- .sort((a, b) => (a.entityId < b.entityId ? -1 : a.entityId > b.entityId ? 1 : 0))
79
- .map((row) => ({
80
- target_ref: `item:${row.entityId}`,
81
- parent_ref: containerRef,
82
- name: row.name,
83
- quantity: Number(row.quantity),
84
- entity_def_id: row.entityDefId,
85
- }));
86
- return {
87
- ...result,
88
- revision: coverage.revision,
89
- status: !coverage.complete ? "truncated" : items.length ? "available" : "empty",
90
- items,
91
- };
92
- }
@@ -1,99 +0,0 @@
1
- /**
2
- * The machine side of one guided question: where a guided dialogue stands,
3
- * for a client that remembers nothing. An NPC sends it beside the spoken
4
- * question; the shape is built by `crates/spellkave-npc-host/src/guide.rs`
5
- * (design: `ledger/designs/guided-dialogue-tree.md`).
6
- *
7
- * Presentation only. It never decides what may be answered: admission checks
8
- * the prompt occurrence's captured action set (ADR-0073 D-1). A reader shows
9
- * titles and labels and must not branch on a step id.
10
- */
11
- export interface DialogueGuideAnswer {
12
- label: string;
13
- /** A definition id, when the answer names one. */
14
- ref?: string;
15
- }
16
-
17
- export interface DialogueGuideEntry {
18
- /** Opaque step id. Several entries share it when a step asks several questions. */
19
- step: string;
20
- title: string;
21
- state: "answered" | "open" | "ahead";
22
- answers: DialogueGuideAnswer[];
23
- }
24
-
25
- export interface DialogueGuide {
26
- /** Version of this shape. */
27
- guide: 1;
28
- /** The step the open question belongs to. */
29
- step: string;
30
- /** The question was answered before and is shown again. */
31
- reopened: boolean;
32
- /** Picks left on this question, this one included. Absent on a single pick. */
33
- remaining?: number;
34
- /** The draft so far and the way ahead, in the NPC's order. */
35
- outline: DialogueGuideEntry[];
36
- /** Parallel to the question's options, for options without a definition. */
37
- descriptions?: (string | null)[];
38
- /** The NPC cut the outline to stay inside its bound. */
39
- truncated?: true;
40
- }
41
-
42
- const STATES = new Set(["answered", "open", "ahead"]);
43
- const MAX_ENTRIES = 48;
44
-
45
- function isRecord(value: unknown): value is Record<string, unknown> {
46
- return typeof value === "object" && value !== null && !Array.isArray(value);
47
- }
48
-
49
- function parseEntry(value: unknown): DialogueGuideEntry | undefined {
50
- if (!isRecord(value)) return undefined;
51
- const { step, title, state, answers } = value;
52
- if (typeof step !== "string" || step === "" || typeof title !== "string") return undefined;
53
- if (typeof state !== "string" || !STATES.has(state)) return undefined;
54
- if (answers !== undefined && !Array.isArray(answers)) return undefined;
55
- const parsed: DialogueGuideAnswer[] = [];
56
- for (const answer of answers ?? []) {
57
- if (!isRecord(answer) || typeof answer.label !== "string") return undefined;
58
- if (answer.ref !== undefined && typeof answer.ref !== "string") return undefined;
59
- parsed.push({ label: answer.label, ...(answer.ref ? { ref: answer.ref } : {}) });
60
- }
61
- return { step, title, state: state as DialogueGuideEntry["state"], answers: parsed };
62
- }
63
-
64
- /**
65
- * Reads a machine side. An unknown version or any malformed part yields
66
- * `undefined`: the question then shows without an outline, it is never shown
67
- * with a half-read one.
68
- */
69
- export function parseDialogueGuide(value: unknown): DialogueGuide | undefined {
70
- if (!isRecord(value) || value.guide !== 1) return undefined;
71
- const { step, reopened, remaining, outline, descriptions, truncated } = value;
72
- if (typeof step !== "string" || step === "") return undefined;
73
- if (!Array.isArray(outline) || outline.length > MAX_ENTRIES) return undefined;
74
- const entries: DialogueGuideEntry[] = [];
75
- for (const raw of outline) {
76
- const entry = parseEntry(raw);
77
- if (entry === undefined) return undefined;
78
- entries.push(entry);
79
- }
80
- if (remaining !== undefined && !(Number.isInteger(remaining) && (remaining as number) > 0))
81
- return undefined;
82
- if (
83
- descriptions !== undefined &&
84
- !(
85
- Array.isArray(descriptions) &&
86
- descriptions.every((text) => text === null || typeof text === "string")
87
- )
88
- )
89
- return undefined;
90
- return {
91
- guide: 1,
92
- step,
93
- reopened: reopened === true,
94
- ...(remaining === undefined ? {} : { remaining: remaining as number }),
95
- outline: entries,
96
- ...(descriptions === undefined ? {} : { descriptions: descriptions as (string | null)[] }),
97
- ...(truncated === true ? { truncated: true as const } : {}),
98
- };
99
- }
@@ -1,90 +0,0 @@
1
- import {
2
- type RequiredTables,
3
- registerReaderManifest,
4
- type SnapshotDb,
5
- } from "../../reader-manifest";
6
- import { asString } from "./_helpers";
7
- import type { DialogueGuide } from "./dialogue_guide";
8
- import { readMetadataAttachmentRows } from "./metadata_rows";
9
-
10
- export const requiredTables: RequiredTables<
11
- ["public_metadata_attachment", "visible_metadata_attachment"]
12
- > = ["public_metadata_attachment", "visible_metadata_attachment"];
13
- registerReaderManifest({ requiredTables });
14
-
15
- const PUBLIC_AUDIENCE = "public";
16
- const PROMPT_DEFINITION_TARGET_KIND = "prompt_definition";
17
- const DIALOGUE_PROMPT_NAMESPACE = "dialogue.prompt";
18
-
19
- /** A prompt's authored presentation or audience-trace marker. Static question
20
- * and labels remain metadata; scripted menus resolve the occurrence's captured
21
- * trace in manipulation_context. Neither changes response admission, which
22
- * checks the occurrence's captured action set (ADR-0073 D-1). */
23
- export interface DialoguePromptPresentation {
24
- presentation?: "audience_trace";
25
- question?: string;
26
- labels: Record<string, string>;
27
- /** Static authored definition refs keyed by response identity. */
28
- response_refs?: Record<string, string>;
29
- /** Picks still to make on a multi-pick menu, this one included — the
30
- * "(N more)" of the question as a number. Absent on a single-pick prompt. */
31
- picks_remaining?: number;
32
- /** The machine side of a guided question: outline, draft so far, picks
33
- * left. Present only on a prompt whose speaker sends one. */
34
- guide?: DialogueGuide;
35
- }
36
-
37
- function parsePresentationPayload(payloadJson: unknown): DialoguePromptPresentation | undefined {
38
- let parsed: unknown;
39
- try {
40
- parsed = JSON.parse(asString(payloadJson));
41
- } catch {
42
- return undefined;
43
- }
44
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
45
- const { question, responses, picks_remaining, presentation } = parsed as Record<string, unknown>;
46
- const labels: Record<string, string> = {};
47
- if (typeof responses === "object" && responses !== null && !Array.isArray(responses)) {
48
- for (const [actionId, label] of Object.entries(responses as Record<string, unknown>)) {
49
- if (typeof label === "string" && label.length > 0) labels[actionId] = label;
50
- }
51
- }
52
- if (question !== undefined && typeof question !== "string") return undefined;
53
- const picksRemaining =
54
- typeof picks_remaining === "number" && Number.isInteger(picks_remaining) && picks_remaining > 0
55
- ? picks_remaining
56
- : undefined;
57
- return {
58
- ...(presentation === "audience_trace" ? { presentation: "audience_trace" as const } : {}),
59
- ...(typeof question === "string" ? { question } : {}),
60
- labels,
61
- ...(picksRemaining === undefined ? {} : { picks_remaining: picksRemaining }),
62
- };
63
- }
64
-
65
- /**
66
- * Reads authored dialogue-prompt presentation text: `metadata_attachment`
67
- * rows with `target_kind = "prompt_definition"`, `target_ref = <prompt_def_id>`,
68
- * namespace `dialogue.prompt`, payload `{ "question": string?, "responses":
69
- * { "<action_id>": "<label>" } }`. Public-audience only, the same rule
70
- * {@link readAffordanceGroupMembership}/{@link readAffordanceDefinitionRefs}
71
- * apply: `visible_metadata_attachment` can carry non-public rows this caller
72
- * happens to be admitted to, and a PLAYER-facing reader must not trust
73
- * "present in the union" to mean "public". Deliberately optional per
74
- * `prompt_def_id`: a prompt with no authored presentation still opens and
75
- * closes normally — `r_manipulate`'s prompt gate never reads this namespace.
76
- */
77
- export function readDialoguePromptPresentation(
78
- db: SnapshotDb,
79
- ): Map<string, DialoguePromptPresentation> {
80
- const out = new Map<string, DialoguePromptPresentation>();
81
- for (const row of readMetadataAttachmentRows(db)) {
82
- if (asString(row.namespace) !== DIALOGUE_PROMPT_NAMESPACE) continue;
83
- if (asString(row.targetKind) !== PROMPT_DEFINITION_TARGET_KIND) continue;
84
- if (asString(row.audience) !== PUBLIC_AUDIENCE) continue;
85
- const presentation = parsePresentationPayload(row.payloadJson);
86
- if (presentation === undefined) continue;
87
- out.set(asString(row.targetRef), presentation);
88
- }
89
- return out;
90
- }