@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,159 @@
1
+ import type {
2
+ CapabilityDefinitionRow,
3
+ ConditionDefinitionRow,
4
+ EntityDefinitionTagRow,
5
+ EntityRow,
6
+ TagCapabilityGrantRow,
7
+ TargetConditionRow,
8
+ VisibleCapabilityRow,
9
+ WorldTimeRow,
10
+ } from "../../binding_rows";
11
+ import {
12
+ type RequiredTables,
13
+ registerReaderManifest,
14
+ type SnapshotDb,
15
+ } from "../../reader-manifest";
16
+ import type { EntityRef } from "../ids";
17
+ import { asString, optNumber, resolveEntityId, rows, tagString } from "./_helpers";
18
+ import { isDirectlyControlled } from "./self";
19
+ import { readEntityTags } from "./tag_reads";
20
+
21
+ export const requiredTables: RequiredTables<
22
+ [
23
+ "visible_capability",
24
+ "capability_definition",
25
+ "visible_manifest_authored_entity",
26
+ "visible_manifest_authored_entity_coverage",
27
+ "directly_controlled_actor_spatial_location",
28
+ "actor",
29
+ "entity",
30
+ "entity_definition_tag",
31
+ "tag_capability_grant",
32
+ "visible_entity_tag",
33
+ "visible_entity_tag_coverage",
34
+ "visible_target_condition",
35
+ "condition_definition",
36
+ "world_time",
37
+ "visible_actor_identity",
38
+ ]
39
+ > = [
40
+ "visible_capability",
41
+ "capability_definition",
42
+ "visible_manifest_authored_entity",
43
+ "visible_manifest_authored_entity_coverage",
44
+ "directly_controlled_actor_spatial_location",
45
+ "actor",
46
+ "entity",
47
+ "entity_definition_tag",
48
+ "tag_capability_grant",
49
+ "visible_entity_tag",
50
+ "visible_entity_tag_coverage",
51
+ "visible_target_condition",
52
+ "condition_definition",
53
+ "world_time",
54
+ "visible_actor_identity",
55
+ ];
56
+ registerReaderManifest({ requiredTables });
57
+
58
+ export interface CompactSelfCapability {
59
+ capability_id: string;
60
+ display_name: string;
61
+ /** Authored catalog prose; absent when unavailable or blank. */
62
+ description?: string;
63
+ source: string;
64
+ extent_ref?: string;
65
+ extent_kind_ref?: string;
66
+ elevation_class?: string;
67
+ expires_at_tick?: number;
68
+ }
69
+
70
+ export interface SelfCapabilityReadOptions {
71
+ /** Include authored grant scope needed by account navigation. Off by default
72
+ * so existing player-facing projections keep their stable compact shape. */
73
+ includeAuthoredGrantMetadata?: boolean;
74
+ }
75
+
76
+ /** Descriptive self-capability projection: direct grants and grants from this
77
+ * body's admitted tags, blueprint tags and active conditions. The server still
78
+ * decides whether an attempted act is admitted. Joins the public
79
+ * `capability_definition` catalog for `display_name`. Falls back to the bare
80
+ * `capability_id` when no catalog row exists (never drops the row).
81
+ * Gated behind `isDirectlyControlled`, matching `readSelfStates`/
82
+ * `readSelfConditions`'s own posture — perceiving a capability grant is
83
+ * self-perception of the body's own affordance-relevant properties, the
84
+ * same category `self_states` already occupies for resource pools
85
+ * (finding #11, `ledger/findings.md`). */
86
+ export function readSelfCapabilities(
87
+ db: SnapshotDb,
88
+ actorId: EntityRef,
89
+ options: SelfCapabilityReadOptions = {},
90
+ ): CompactSelfCapability[] {
91
+ if (!isDirectlyControlled(db, actorId)) return [];
92
+ const entityId = resolveEntityId(db, actorId);
93
+ if (entityId === undefined) return [];
94
+ const definitions = rows<CapabilityDefinitionRow>(db, "capability_definition");
95
+ const direct = rows<VisibleCapabilityRow>(db, "visible_capability")
96
+ .filter((row) => String(row.entityId) === String(entityId))
97
+ .map((row) => {
98
+ const def = definitions.find((d) => d.capabilityId === row.capabilityId);
99
+ const expires = optNumber(row.expiresAtTick);
100
+ const description = asString(def?.description);
101
+ const grantMetadata = options.includeAuthoredGrantMetadata
102
+ ? {
103
+ extent_ref: asString(row.extentRef),
104
+ extent_kind_ref: asString(row.extentKindRef),
105
+ elevation_class: tagString(row.elevationClass),
106
+ }
107
+ : {};
108
+ return {
109
+ capability_id: asString(row.capabilityId),
110
+ display_name: def ? asString(def.displayName) : asString(row.capabilityId),
111
+ ...(description.trim() ? { description } : {}),
112
+ source: asString(row.source),
113
+ ...grantMetadata,
114
+ ...(expires === undefined ? {} : { expires_at_tick: expires }),
115
+ };
116
+ });
117
+ const compact = (id: string, source: string): CompactSelfCapability => {
118
+ const def = definitions.find((row) => row.capabilityId === id);
119
+ const description = asString(def?.description);
120
+ return {
121
+ capability_id: id,
122
+ display_name: def ? asString(def.displayName) : id,
123
+ ...(description.trim() ? { description } : {}),
124
+ source,
125
+ };
126
+ };
127
+ const body = rows<EntityRow>(db, "entity").find(
128
+ (row) => String(row.entityId) === String(entityId),
129
+ );
130
+ const tags = new Set(readEntityTags(db, String(entityId)));
131
+ if (body)
132
+ for (const row of rows<EntityDefinitionTagRow>(db, "entity_definition_tag")) {
133
+ if (row.entityDefId === body.entityDefId) tags.add(row.tag);
134
+ }
135
+ const derived: CompactSelfCapability[] = [];
136
+ for (const row of rows<TagCapabilityGrantRow>(db, "tag_capability_grant")) {
137
+ if (tags.has(row.tag)) derived.push(compact(row.capabilityId, `tag:${row.tag}`));
138
+ }
139
+ const tick = rows<WorldTimeRow>(db, "world_time")[0]?.tick;
140
+ const conditions = rows<ConditionDefinitionRow>(db, "condition_definition");
141
+ for (const row of rows<TargetConditionRow>(db, "visible_target_condition")) {
142
+ if (
143
+ tagString(row.targetKind) !== "Entity" ||
144
+ String(row.targetId) !== String(entityId) ||
145
+ row.stackCount <= 0
146
+ )
147
+ continue;
148
+ if (row.expiresAtTick !== 0n && (tick === undefined || row.expiresAtTick <= tick)) continue;
149
+ const definition = conditions.find(
150
+ (def) => def.conditionDefinitionId === row.conditionDefinitionId,
151
+ );
152
+ for (const id of definition?.grantsCapabilityWhileActive ?? []) {
153
+ derived.push(compact(id, `condition:${row.conditionDefinitionId}`));
154
+ }
155
+ }
156
+ return [...direct, ...derived].sort(
157
+ (a, b) => a.capability_id.localeCompare(b.capability_id) || a.source.localeCompare(b.source),
158
+ );
159
+ }
@@ -0,0 +1,101 @@
1
+ import type { VisibleEconomyChannelSpendRow } from "../../binding_rows";
2
+ import {
3
+ type RequiredTables,
4
+ registerReaderManifest,
5
+ type SnapshotDb,
6
+ } from "../../reader-manifest";
7
+ import type { EntityRef } from "../ids";
8
+ import { asString, resolveEntityId, rows } from "./_helpers";
9
+ import { readRecentChannelSpends } from "./action_economy_events";
10
+ import { isDirectlyControlled } from "./self";
11
+
12
+ export const requiredTables: RequiredTables<
13
+ [
14
+ "visible_economy_channel_spend",
15
+ "event_channel_spend",
16
+ "visible_manifest_authored_entity",
17
+ "visible_manifest_authored_entity_coverage",
18
+ "directly_controlled_actor_spatial_location",
19
+ ]
20
+ > = [
21
+ "visible_economy_channel_spend",
22
+ "event_channel_spend",
23
+ "visible_manifest_authored_entity",
24
+ "visible_manifest_authored_entity_coverage",
25
+ "directly_controlled_actor_spatial_location",
26
+ ];
27
+ registerReaderManifest({ requiredTables });
28
+
29
+ const RECENT_EVENT_SCAN_CAP = 2_000;
30
+
31
+ export interface CompactSelfEconomyLastSpend {
32
+ event_id: string;
33
+ cost_ms: string;
34
+ remaining_ms: string;
35
+ }
36
+
37
+ export interface CompactSelfEconomySpend {
38
+ channel_id: string;
39
+ /** Cumulative fiction-ms spent from this channel in `window_start_ms`
40
+ * (current-window standing, `visible_economy_channel_spend`). */
41
+ spent_ms: string;
42
+ window_start_ms: string;
43
+ /** The most recent same-window `event_channel_spend` line for this
44
+ * channel — the exact `cost_ms` an action drew and the `remaining_ms`
45
+ * left afterward (#2096: "how much of my turn is left"). Absent when no
46
+ * matching event is present in the reader's scan window (should not
47
+ * happen for a live connection: every `consume()` call writes both rows
48
+ * in the same reducer transaction). Sourced from a table the server does
49
+ * NOT scope per caller (see the `RECENT_EVENT_SCAN_CAP` comment above) —
50
+ * client-side filtering only, tracked for a proper view in #2110. */
51
+ last_spend?: CompactSelfEconomyLastSpend;
52
+ }
53
+
54
+ /** Full authorized self-economy projection: the connected actor's OWN
55
+ * `visible_economy_channel_spend` current-window standing (owner-body-bounded
56
+ * by the server view, ADR-0120, #915), one row per channel the actor has
57
+ * touched, joined against the latest same-window `event_channel_spend` row
58
+ * for that channel's exact `cost_ms`/`remaining_ms` (#2083's typed-reader-home
59
+ * ask plus #2096's quantitative budget projection, in one place). Gated
60
+ * behind `isDirectlyControlled`, matching `readSelfCapabilities`/
61
+ * `readSelfRecentEvaluations`'s own posture for the `spent_ms`/`window_start_ms`
62
+ * half — but see `last_spend`'s own doc comment and the `RECENT_EVENT_SCAN_CAP`
63
+ * comment above: that half's actor scoping is this reader's own filter, not a
64
+ * server-enforced boundary (#2110). */
65
+ export function readSelfEconomyChannelSpends(
66
+ db: SnapshotDb,
67
+ actorId: EntityRef,
68
+ ): CompactSelfEconomySpend[] {
69
+ if (!isDirectlyControlled(db, actorId)) return [];
70
+ const entityId = resolveEntityId(db, actorId);
71
+ if (entityId === undefined) return [];
72
+ const state = rows<VisibleEconomyChannelSpendRow>(db, "visible_economy_channel_spend").filter(
73
+ (row) => String(row.actorId) === String(entityId),
74
+ );
75
+ const events = readRecentChannelSpends(db, RECENT_EVENT_SCAN_CAP).filter(
76
+ (row) => row.actor === String(entityId),
77
+ );
78
+ return state
79
+ .map((row) => {
80
+ const channelId = asString(row.channelId);
81
+ const windowStartMs = asString(row.windowStartMs);
82
+ const lastEvent = events.find(
83
+ (event) => event.channel === channelId && event.window === windowStartMs,
84
+ );
85
+ return {
86
+ channel_id: channelId,
87
+ spent_ms: asString(row.spentMs),
88
+ window_start_ms: windowStartMs,
89
+ ...(lastEvent === undefined
90
+ ? {}
91
+ : {
92
+ last_spend: {
93
+ event_id: lastEvent.event_id,
94
+ cost_ms: lastEvent.cost_ms,
95
+ remaining_ms: lastEvent.remaining_ms,
96
+ },
97
+ }),
98
+ };
99
+ })
100
+ .sort((a, b) => a.channel_id.localeCompare(b.channel_id));
101
+ }
@@ -0,0 +1,93 @@
1
+ import type { VisibleEconomyChannelBudgetRow } from "../../binding_rows";
2
+ import {
3
+ type RequiredTables,
4
+ registerReaderManifest,
5
+ type SnapshotDb,
6
+ } from "../../reader-manifest";
7
+ import type { EntityRef } from "../ids";
8
+ import { asString, resolveEntityId, rows } from "./_helpers";
9
+ import { isDirectlyControlled } from "./self";
10
+
11
+ export const requiredTables: RequiredTables<
12
+ [
13
+ "visible_economy_channel_budget",
14
+ "world_time",
15
+ "visible_manifest_authored_entity",
16
+ "visible_manifest_authored_entity_coverage",
17
+ "directly_controlled_actor_spatial_location",
18
+ ]
19
+ > = [
20
+ "visible_economy_channel_budget",
21
+ "world_time",
22
+ "visible_manifest_authored_entity",
23
+ "visible_manifest_authored_entity_coverage",
24
+ "directly_controlled_actor_spatial_location",
25
+ ];
26
+ registerReaderManifest({ requiredTables });
27
+
28
+ export type EconomyBudgetEnvelopeStatus = "ok" | "pending_boundary" | "unavailable";
29
+
30
+ export interface CompactEconomyBudgetChannel {
31
+ actor_id: string;
32
+ channel_id: string;
33
+ pool_ms_per_round: string;
34
+ resets_on: string;
35
+ off_turn_eligible: boolean;
36
+ current_window_start_ms: string;
37
+ spent_ms: string;
38
+ grant_ms: string;
39
+ effective_pool_ms?: string;
40
+ remaining_ms?: string;
41
+ status: string;
42
+ }
43
+
44
+ export interface CompactEconomyBudget {
45
+ status: EconomyBudgetEnvelopeStatus;
46
+ reason?: "world_time";
47
+ channels: CompactEconomyBudgetChannel[];
48
+ }
49
+
50
+ function mapChannel(row: VisibleEconomyChannelBudgetRow): CompactEconomyBudgetChannel {
51
+ const disclosed = Boolean(row.remainingDisclosed);
52
+ const status = asString(row.status);
53
+ return {
54
+ actor_id: asString(row.actorId),
55
+ channel_id: asString(row.channelId),
56
+ pool_ms_per_round: asString(row.poolMsPerRound),
57
+ resets_on: asString(row.resetsOn),
58
+ off_turn_eligible: Boolean(row.offTurnEligible),
59
+ current_window_start_ms: asString(row.currentWindowStartMs),
60
+ spent_ms: asString(row.spentMs),
61
+ grant_ms: asString(row.grantMs),
62
+ ...(disclosed && status === "ok"
63
+ ? {
64
+ effective_pool_ms: asString(row.effectivePoolMs),
65
+ remaining_ms: asString(row.remainingMs),
66
+ }
67
+ : {}),
68
+ status,
69
+ };
70
+ }
71
+
72
+ /** Authoritative remaining. Does not replace kind=economy spend history. */
73
+ export function readSelfEconomyBudget(db: SnapshotDb, actorId: EntityRef): CompactEconomyBudget {
74
+ if (!isDirectlyControlled(db, actorId)) {
75
+ return { status: "ok", channels: [] };
76
+ }
77
+ const timeRows = rows(db, "world_time");
78
+ if (timeRows.length === 0) {
79
+ return { status: "unavailable", reason: "world_time", channels: [] };
80
+ }
81
+ const entityId = resolveEntityId(db, actorId);
82
+ if (entityId === undefined) {
83
+ return { status: "ok", channels: [] };
84
+ }
85
+ const channels = rows<VisibleEconomyChannelBudgetRow>(db, "visible_economy_channel_budget")
86
+ .filter((row) => String(row.actorId) === String(entityId))
87
+ .map(mapChannel)
88
+ .sort((a, b) => a.channel_id.localeCompare(b.channel_id));
89
+ if (channels.some((row) => row.status === "pending_boundary")) {
90
+ return { status: "pending_boundary", channels };
91
+ }
92
+ return { status: "ok", channels };
93
+ }
@@ -0,0 +1,128 @@
1
+ import type { EvaluationProvenanceRow } from "../../binding_rows";
2
+ import {
3
+ type RequiredTables,
4
+ registerReaderManifest,
5
+ type SnapshotDb,
6
+ } from "../../reader-manifest";
7
+ import type { EntityRef } from "../ids";
8
+ import { asNumber, asString, resolveEntityId, rows, tagString } from "./_helpers";
9
+ import { isDirectlyControlled } from "./self";
10
+
11
+ export const requiredTables: RequiredTables<
12
+ [
13
+ "visible_evaluation_provenance",
14
+ "visible_manifest_authored_entity",
15
+ "visible_manifest_authored_entity_coverage",
16
+ "directly_controlled_actor_spatial_location",
17
+ ]
18
+ > = [
19
+ "visible_evaluation_provenance",
20
+ "visible_manifest_authored_entity",
21
+ "visible_manifest_authored_entity_coverage",
22
+ "directly_controlled_actor_spatial_location",
23
+ ];
24
+ registerReaderManifest({ requiredTables });
25
+
26
+ /** `evaluation_provenance` grows unboundedly (a row per action-evaluation,
27
+ * forever) — unlike a capability grant set, there is no natural cap. This is
28
+ * a reader-level safety ceiling, applied before the caller's own paging/
29
+ * bounded-collection slicing, most-recent-first. */
30
+ const SELF_EVALUATION_HISTORY_CAP = 50;
31
+
32
+ export interface CompactSelfEvaluationDraw {
33
+ source_id: string;
34
+ draw_index: number;
35
+ value: number;
36
+ }
37
+
38
+ export interface CompactSelfEvaluation {
39
+ provenance_id: string;
40
+ created_at_tick: number;
41
+ status: string;
42
+ subject_id: string;
43
+ selected_template_ids: string[];
44
+ draws: CompactSelfEvaluationDraw[];
45
+ record_kind?: string;
46
+ expression_ids?: string[];
47
+ failure_kind?: string;
48
+ failure_detail?: string;
49
+ }
50
+
51
+ export function toCompactSelfEvaluation(row: EvaluationProvenanceRow): CompactSelfEvaluation {
52
+ const recordKind = tagString(row.kind);
53
+ const expressionIds = Array.isArray(row.expressionIds)
54
+ ? row.expressionIds.map((id) => String(id)).filter((id) => id.length > 0)
55
+ : [];
56
+ const failureKind = asString(row.failureKind);
57
+ const failureDetail = asString(row.failureDetail);
58
+
59
+ return {
60
+ provenance_id: asString(row.provenanceId),
61
+ created_at_tick: asNumber(row.createdAtTick),
62
+ status: tagString(row.status),
63
+ subject_id: asString(row.subjectId),
64
+ selected_template_ids: Array.isArray(row.selectedTemplateIds)
65
+ ? row.selectedTemplateIds.map((id) => String(id))
66
+ : [],
67
+ draws: Array.isArray(row.stochasticDraws)
68
+ ? row.stochasticDraws.map((draw) => ({
69
+ source_id: asString(draw.sourceId),
70
+ draw_index: asNumber(draw.drawIndex),
71
+ value: asNumber(draw.value),
72
+ }))
73
+ : [],
74
+ ...(recordKind ? { record_kind: recordKind } : {}),
75
+ ...(expressionIds.length > 0 ? { expression_ids: expressionIds } : {}),
76
+ ...(failureKind ? { failure_kind: failureKind } : {}),
77
+ ...(failureDetail ? { failure_detail: failureDetail } : {}),
78
+ };
79
+ }
80
+
81
+ /** Full authorized self-evaluation projection: the connected actor's OWN
82
+ * body's recent `visible_evaluation_provenance` rows, most-recent-first,
83
+ * capped at `SELF_EVALUATION_HISTORY_CAP`. Content-neutral — projects
84
+ * whatever `stochastic_draws` the row carries (possibly empty) without
85
+ * interpreting them; the consumer knows whether a draw is a d20 or
86
+ * something else. Gated behind `isDirectlyControlled`, matching
87
+ * `readSelfCapabilities`/`readSelfStates`'s own posture — perceiving the
88
+ * die faces behind one's own recent checks is self-perception of the body's
89
+ * own affordance resolution (finding #22(b), `ledger/findings.md`). Scopes
90
+ * on `owner_body_entity_id`, not `subject_id`: every `r_manipulate` call site
91
+ * writes the ACTOR's own entity id there, on both success and failure rows
92
+ * (finding #22(a)'s own grounding). */
93
+ export function readSelfRecentEvaluations(
94
+ db: SnapshotDb,
95
+ actorId: EntityRef,
96
+ ): CompactSelfEvaluation[] {
97
+ if (!isDirectlyControlled(db, actorId)) return [];
98
+ const entityId = resolveEntityId(db, actorId);
99
+ if (entityId === undefined) return [];
100
+ return rows<EvaluationProvenanceRow>(db, "visible_evaluation_provenance")
101
+ .filter((row) => String(row.ownerBodyEntityId) === String(entityId))
102
+ .map(toCompactSelfEvaluation)
103
+ .sort((a, b) => {
104
+ if (a.created_at_tick !== b.created_at_tick) return b.created_at_tick - a.created_at_tick;
105
+ return a.provenance_id < b.provenance_id ? 1 : a.provenance_id > b.provenance_id ? -1 : 0;
106
+ })
107
+ .slice(0, SELF_EVALUATION_HISTORY_CAP);
108
+ }
109
+
110
+ /**
111
+ * Lookup one evaluation row by provenance_id over all evaluation rows the
112
+ * client holds for the connected body (not capped to history ceiling).
113
+ */
114
+ export function readSelfEvaluationById(
115
+ db: SnapshotDb,
116
+ actorId: EntityRef,
117
+ provenanceId: string,
118
+ ): CompactSelfEvaluation | null {
119
+ if (!isDirectlyControlled(db, actorId)) return null;
120
+ const entityId = resolveEntityId(db, actorId);
121
+ if (entityId === undefined) return null;
122
+ const targetId = provenanceId.trim();
123
+ const match = rows<EvaluationProvenanceRow>(db, "visible_evaluation_provenance").find(
124
+ (row) =>
125
+ String(row.ownerBodyEntityId) === String(entityId) && asString(row.provenanceId) === targetId,
126
+ );
127
+ return match ? toCompactSelfEvaluation(match) : null;
128
+ }
@@ -0,0 +1,104 @@
1
+ import type {
2
+ EntityDefinitionTagRow,
3
+ EntityTagRow,
4
+ TagValueDefinitionRow,
5
+ } from "../../binding_rows";
6
+ import {
7
+ type RequiredTables,
8
+ registerReaderManifest,
9
+ type SnapshotDb,
10
+ } from "../../reader-manifest";
11
+ import type { EntityRef } from "../ids";
12
+ import { asString, buildEntitySummaryMap, resolveEntityId, rows } from "./_helpers";
13
+ import { isDirectlyControlled } from "./self";
14
+
15
+ // This reader's own direct table access: resolving an actor's identity
16
+ // facets needs its `entity_def_id` (via `buildEntitySummaryMap`, which reads
17
+ // `entity`), the tags authored against that definition (`entity_definition_tag`),
18
+ // the instance tags on this body (`entity_tag`, #2232 / same axis as #2228),
19
+ // and the bundle-authored catalog metadata for any of those exact tag
20
+ // values (`tag_value_definition`).
21
+ export const requiredTables: RequiredTables<
22
+ [
23
+ "entity",
24
+ "entity_definition_tag",
25
+ "visible_entity_tag",
26
+ "visible_entity_tag_coverage",
27
+ "tag_value_definition",
28
+ ]
29
+ > = [
30
+ "entity",
31
+ "entity_definition_tag",
32
+ "visible_entity_tag",
33
+ "visible_entity_tag_coverage",
34
+ "tag_value_definition",
35
+ ];
36
+ registerReaderManifest({ requiredTables });
37
+
38
+ export interface SelfIdentityFacet {
39
+ /** The authored dotted tag verbatim (e.g. `"srd.species.human"`, or a
40
+ * bare tag like `"creature"`). */
41
+ tag: string;
42
+ /** The tag's declared facet prefix (e.g. `"srd.species"`), present only
43
+ * when a `tag_value_definition` row exists for this exact tag. */
44
+ prefix?: string;
45
+ /** Source-derived discovery prose for this exact tag value, present only
46
+ * when a `tag_value_definition` row exists for this exact tag. */
47
+ description?: string;
48
+ }
49
+
50
+ /**
51
+ * The connected actor's own authored identity tags (species, class,
52
+ * background, …): definition tags union instance `entity_tag` (#2232),
53
+ * LEFT-joined against the bundle's `tag_value_definition` catalog for
54
+ * `prefix`/`description` where a definition was authored. A bare tag with
55
+ * no catalog row (e.g. `"creature"`) is still returned, just without those
56
+ * two fields — never an empty string in their place.
57
+ *
58
+ * This is the detailed "who am I" surface (#2119 follow-up, 2026-08-03): the
59
+ * ENRICHED facets (tag + catalog prefix + description) are served here at
60
+ * `self_states kind=identity`. #2119 had also removed identity from the
61
+ * recurring glance on the reasoning that it is static and belongs at session
62
+ * start; live play (sk-0m4.120.34) reversed that call — the player-tool
63
+ * `self_summary` now re-surfaces a COMPACT form of these facets (tag + prefix,
64
+ * no description), keeping this reader as the enriched drill-down that carries
65
+ * the descriptions. Content-neutral like
66
+ * `readActorStates`' own `tags` field: this reader does NOT parse a dotted
67
+ * tag into facet/value or mint `species`/`class`/`background` as first-class
68
+ * fields — rendering a phrase like "Human Fighter (Soldier)" from these rows
69
+ * stays the consumer's job.
70
+ *
71
+ * Gated behind `isDirectlyControlled`, matching every other self reader.
72
+ */
73
+ export function readSelfIdentity(db: SnapshotDb, actorId: EntityRef): SelfIdentityFacet[] {
74
+ if (!isDirectlyControlled(db, actorId)) return [];
75
+ const entityId = resolveEntityId(db, actorId);
76
+ if (entityId === undefined) return [];
77
+ const entityDefId = buildEntitySummaryMap(db).get(String(entityId))?.entity_def_id;
78
+ if (entityDefId === undefined) return [];
79
+ const definitions = new Map(
80
+ rows<TagValueDefinitionRow>(db, "tag_value_definition").map((row) => [asString(row.tag), row]),
81
+ );
82
+ const tags = new Set<string>();
83
+ for (const row of rows<EntityDefinitionTagRow>(db, "entity_definition_tag")) {
84
+ if (asString(row.entityDefId) === entityDefId) tags.add(asString(row.tag));
85
+ }
86
+ const instanceId = String(entityId);
87
+ for (const row of rows<EntityTagRow>(db, "visible_entity_tag")) {
88
+ if (String(row.entityId) === instanceId) tags.add(asString(row.tag));
89
+ }
90
+ return [...tags]
91
+ .map((tag) => {
92
+ const definition = definitions.get(tag);
93
+ return {
94
+ tag,
95
+ ...(definition === undefined
96
+ ? {}
97
+ : {
98
+ prefix: asString(definition.prefix),
99
+ description: asString(definition.description),
100
+ }),
101
+ };
102
+ })
103
+ .sort((a, b) => (a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0));
104
+ }