@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,28 +0,0 @@
1
- // Caller-visible spatial niche attachments. Consumers may join a visible row
2
- // to public topology geometry without promoting its anchor into perceived map
3
- // knowledge.
4
- import type { VisibleSpatialNicheAttachmentRow } from "../../binding_rows";
5
- import {
6
- type RequiredTables,
7
- registerReaderManifest,
8
- type SnapshotDb,
9
- } from "../../reader-manifest";
10
- import { asString, rows } from "./_helpers";
11
-
12
- export const requiredTables: RequiredTables<["visible_spatial_niche_attachment"]> = [
13
- "visible_spatial_niche_attachment",
14
- ];
15
- registerReaderManifest({ requiredTables });
16
-
17
- export function readVisibleSpatialNicheAttachments(db: SnapshotDb): Record<string, unknown>[] {
18
- return rows<VisibleSpatialNicheAttachmentRow>(db, "visible_spatial_niche_attachment").map(
19
- (row) => ({
20
- attachment_id: row.attachmentId,
21
- niche_id: asString(row.nicheId),
22
- place_node_id: asString(row.placeNodeId),
23
- place_edge_id: row.placeEdgeId,
24
- target_kind: asString(row.targetKind),
25
- visibility: row.visibility,
26
- }),
27
- );
28
- }
@@ -1,27 +0,0 @@
1
- // Reader: public `substrate_definition` catalog (substrate_id → coordinate_kind_id).
2
- // Used by the OSM projection (ADR-0123 D-2 indoor/outdoor class) so the exporter
3
- // does not fall back to the kernel bootstrap seed when live rows are available.
4
-
5
- import type { SubstrateDefinitionRow } from "../../binding_rows";
6
- import {
7
- type RequiredTables,
8
- registerReaderManifest,
9
- type SnapshotDb,
10
- } from "../../reader-manifest";
11
- import { asString, rows } from "./_helpers";
12
-
13
- export const requiredTables: RequiredTables<["substrate_definition"]> = ["substrate_definition"];
14
- registerReaderManifest({ requiredTables });
15
-
16
- /**
17
- * Read every substrate_definition row in the manifest's snake_case shape
18
- * (`substrate_id`, `bundle_id`, `coordinate_kind_id`, `description`).
19
- */
20
- export function readSubstrateDefinitions(db: SnapshotDb): Record<string, unknown>[] {
21
- return rows<SubstrateDefinitionRow>(db, "substrate_definition").map((row) => ({
22
- substrate_id: asString(row.substrateId),
23
- bundle_id: asString(row.bundleId),
24
- coordinate_kind_id: asString(row.coordinateKindId),
25
- description: asString(row.description),
26
- }));
27
- }
@@ -1,72 +0,0 @@
1
- // Reader: suggested next action — deterministic movement hint from live state.
2
- // Direct action attempts are intentionally not pre-composed here: clients use
3
- // actor-scoped factual context and let the reducer admit each typed attempt.
4
-
5
- import {
6
- type RequiredTables,
7
- registerReaderManifest,
8
- type SnapshotDb,
9
- } from "../../reader-manifest";
10
- import type { EntityRef } from "../ids";
11
- import { readActorSnapshot } from "./actor_snapshot";
12
- import { readLocationSnapshot } from "./location_snapshot";
13
-
14
- export const requiredTables: RequiredTables<
15
- [
16
- "visible_actor_spatial_location",
17
- "visible_target_condition",
18
- "visible_manifest_authored_entity",
19
- "visible_manifest_authored_entity_coverage",
20
- "visible_place_node",
21
- "visible_place_edge",
22
- "place_edge_affordance",
23
- "visible_place_graph_definition",
24
- // Read transitively via readActorSnapshot, which now surfaces the actor's own
25
- // object-state pools enriched with definitions + tags (#1229).
26
- "owned_object_state",
27
- "resource_definition",
28
- "resource_definition_tag",
29
- // Read transitively via readActorSnapshot.
30
- "entity",
31
- "visible_entity_tag",
32
- "visible_entity_tag_coverage",
33
- ]
34
- > = [
35
- "visible_actor_spatial_location",
36
- "visible_target_condition",
37
- "visible_manifest_authored_entity",
38
- "visible_manifest_authored_entity_coverage",
39
- "visible_place_node",
40
- "visible_place_edge",
41
- "place_edge_affordance",
42
- "visible_place_graph_definition",
43
- "owned_object_state",
44
- "resource_definition",
45
- "resource_definition_tag",
46
- "entity",
47
- "visible_entity_tag",
48
- "visible_entity_tag_coverage",
49
- ];
50
- registerReaderManifest({ requiredTables });
51
-
52
- export type SuggestedNextAction = { kind: "move"; edge_id: string; to_node_id: string };
53
-
54
- /**
55
- * Deterministic read-first suggestion. DOES NOT submit a reducer. Callers approve+invoke.
56
- *
57
- * Priority: first outgoing edge from the actor's current node (alphabetical
58
- * edge id), or null when there is none.
59
- */
60
- export function suggestNextAction(
61
- db: SnapshotDb,
62
- perceiverEntityId: EntityRef,
63
- ): SuggestedNextAction | null {
64
- const actor = readActorSnapshot(db, perceiverEntityId);
65
- if (actor === null || actor.current_node_id === undefined) return null;
66
- const loc = readLocationSnapshot(db, actor.current_node_id);
67
- if (loc === null || loc.outgoing_edges.length === 0) return null;
68
- const sortedEdges = loc.outgoing_edges.slice().sort((a, b) => a.edge_id.localeCompare(b.edge_id));
69
- const first = sortedEdges[0];
70
- if (first === undefined) return null;
71
- return { kind: "move", edge_id: first.edge_id, to_node_id: first.to_node_id };
72
- }
@@ -1,78 +0,0 @@
1
- import {
2
- type RequiredTables,
3
- registerReaderManifest,
4
- type SnapshotDb,
5
- } from "../../reader-manifest";
6
- import { asString } from "./_helpers";
7
- import { readMetadataAttachmentRows } from "./metadata_rows";
8
-
9
- export const requiredTables: RequiredTables<
10
- ["public_metadata_attachment", "visible_metadata_attachment"]
11
- > = ["public_metadata_attachment", "visible_metadata_attachment"];
12
- registerReaderManifest({ requiredTables });
13
-
14
- const PUBLIC_AUDIENCE = "public";
15
-
16
- export interface SurfaceMembership {
17
- slot: string;
18
- order: number;
19
- }
20
-
21
- /** Reader-owned payload schema for `ui.*` surface-membership namespaces
22
- * (ADR-0073 G-2: the server never owns namespace payload key schemas — the
23
- * consuming reader does). `{"slot": "vitals", "order": 10}` is the whole
24
- * contract; anything else is malformed and the row is skipped. */
25
- function parseMembershipPayload(payloadJson: unknown): SurfaceMembership | undefined {
26
- let parsed: unknown;
27
- try {
28
- parsed = JSON.parse(asString(payloadJson));
29
- } catch {
30
- return undefined;
31
- }
32
- if (typeof parsed !== "object" || parsed === null) return undefined;
33
- const { slot, order } = parsed as Record<string, unknown>;
34
- if (typeof slot !== "string" || slot.length === 0) return undefined;
35
- if (typeof order !== "number" || !Number.isFinite(order)) return undefined;
36
- return { slot, order };
37
- }
38
-
39
- /**
40
- * ADR-0073 metadata-attachment membership for one `(namespace, target_kind)`
41
- * pair — e.g. which `resource_definition` rows belong to `ui.self_summary`
42
- * and at what slot/order (#2119). Union over every `bundle_id`: additive
43
- * across bundles, matching the attachment upsert identity
44
- * `(target_kind, target_ref, namespace, bundle_id)` (#1968 G-1). A
45
- * malformed `payload_json` row (not JSON, not an object, missing/mistyped
46
- * `slot`/`order`) is skipped rather than thrown — one bad attachment must
47
- * not break the whole surface. A `target_ref` attached twice (two bundles
48
- * both claiming the same membership) keeps the LOWEST `order` — deterministic
49
- * precedence, not "last bundle iterated wins".
50
- *
51
- * Filters to `public`-audience rows only: `visible_metadata_attachment`
52
- * (ADR-0130 D-5) can carry non-public rows this caller is admitted to
53
- * (visibility-class relations like `hidden`/`internal`, the strict `owned`
54
- * relation, or capability audiences), so a PLAYER-facing reader must not
55
- * trust "present in the union" to mean "public" — the explicit check stays
56
- * load-bearing (ADR-0073 D-2/D-3 — player clients never read non-`public`
57
- * metadata through this surface).
58
- */
59
- export function readSurfaceMembership(
60
- db: SnapshotDb,
61
- namespace: string,
62
- targetKind: string,
63
- ): Map<string, SurfaceMembership> {
64
- const out = new Map<string, SurfaceMembership>();
65
- for (const row of readMetadataAttachmentRows(db)) {
66
- if (asString(row.namespace) !== namespace) continue;
67
- if (asString(row.targetKind) !== targetKind) continue;
68
- if (asString(row.audience) !== PUBLIC_AUDIENCE) continue;
69
- const membership = parseMembershipPayload(row.payloadJson);
70
- if (membership === undefined) continue;
71
- const targetRef = asString(row.targetRef);
72
- const existing = out.get(targetRef);
73
- if (existing === undefined || membership.order < existing.order) {
74
- out.set(targetRef, membership);
75
- }
76
- }
77
- return out;
78
- }
@@ -1,54 +0,0 @@
1
- import type { ActionDefinitionTagRow, EntityTagRow } from "../../binding_rows";
2
- import {
3
- type RequiredTables,
4
- registerReaderManifest,
5
- type SnapshotDb,
6
- } from "../../reader-manifest";
7
- import { rows } from "./_helpers";
8
-
9
- // Readers over the relational tag tables. Both are type-level reads (SDK §1) —
10
- // they surface author-given tags so a host (e.g. the world-explorer NPC bot) can
11
- // classify by tag instead of by hard-coded identity:
12
- //
13
- // - visible_entity_tag (X11/CR-4): admitted instance tags (by numeric entity_id).
14
- // The bot reads `faction:*` here to know whom to oppose.
15
- // - action_definition_tag: tags on an action (by action_id string). The bot
16
- // reads `combat` / `attack:*` here to know which affordances are hostile.
17
- //
18
- // Definition-level tags (entity_definition_tag) are deliberately NOT unioned in
19
- // here: that union is the server-side `has_tag` DSL fact's job (ADR-0038 D-3).
20
- // These readers expose admitted instance rows and public action tag rows; a host that needs the
21
- // def-tag union should gate through an affordance predicate, not re-derive it.
22
-
23
- export const entityTagTables: RequiredTables<
24
- ["visible_entity_tag", "visible_entity_tag_coverage"]
25
- > = ["visible_entity_tag", "visible_entity_tag_coverage"];
26
- export const actionTagTables: RequiredTables<["action_definition_tag"]> = ["action_definition_tag"];
27
- registerReaderManifest({ requiredTables: entityTagTables });
28
- registerReaderManifest({ requiredTables: actionTagTables });
29
-
30
- /** All admitted instance tags set on an entity, by its numeric entity id. */
31
- export function readEntityTags(db: SnapshotDb, entityId: string | bigint): string[] {
32
- const target = String(entityId);
33
- return rows<EntityTagRow>(db, "visible_entity_tag")
34
- .filter((row) => String((row as unknown as { entityId: unknown }).entityId) === target)
35
- .map((row) => (row as unknown as { tag: string }).tag);
36
- }
37
-
38
- /** The first `srd.faction.<name>` or legacy `faction:<name>` tag on an entity, or null if it has no faction.
39
- * The "<name>" suffix is returned (e.g. "monsters", "cragmaw"), not the full tag. */
40
- export function readEntityFaction(db: SnapshotDb, entityId: string | bigint): string | null {
41
- const tags = readEntityTags(db, entityId);
42
- for (const t of tags) {
43
- if (t.startsWith("srd.faction.")) return t.slice("srd.faction.".length);
44
- if (t.startsWith("faction:")) return t.slice("faction:".length);
45
- }
46
- return null;
47
- }
48
-
49
- /** All tags on an action definition, by its action_id. */
50
- export function readActionTags(db: SnapshotDb, actionId: string): string[] {
51
- return rows<ActionDefinitionTagRow>(db, "action_definition_tag")
52
- .filter((row) => (row as unknown as { actionId: string }).actionId === actionId)
53
- .map((row) => (row as unknown as { tag: string }).tag);
54
- }
@@ -1,120 +0,0 @@
1
- import type { ActorSpatialLocationRow, TraceRow as DbTraceRow } 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, optNumber, resolveEntityId, rows, tagString } from "./_helpers";
9
- import { readTraceResponse, type TraceResponse } from "./trace_response";
10
-
11
- export const requiredTables: RequiredTables<
12
- [
13
- "visible_actor_spatial_location",
14
- "visible_manifest_authored_entity",
15
- "visible_manifest_authored_entity_coverage",
16
- "visible_trace",
17
- "action_definition_tag",
18
- "visible_prompt_occurrence",
19
- "public_metadata_attachment",
20
- "visible_metadata_attachment",
21
- ]
22
- > = [
23
- "visible_actor_spatial_location",
24
- "visible_manifest_authored_entity",
25
- "visible_manifest_authored_entity_coverage",
26
- "visible_trace",
27
- "action_definition_tag",
28
- "visible_prompt_occurrence",
29
- "public_metadata_attachment",
30
- "visible_metadata_attachment",
31
- ];
32
- registerReaderManifest({ requiredTables });
33
-
34
- export interface TraceQueryEntry {
35
- trace_id: string;
36
- kind: string;
37
- location_kind: string;
38
- location_ref: string;
39
- payload_json: string;
40
- payload: unknown;
41
- response?: TraceResponse;
42
- inscribed_at: number;
43
- expires_at: number | null;
44
- inscribed_by: string | null;
45
- visibility: string;
46
- bundle_id: string;
47
- }
48
-
49
- export interface CurrentTraceProjection {
50
- actor_entity_id: string;
51
- current_node_id: string;
52
- entries: TraceQueryEntry[];
53
- }
54
-
55
- export interface ReadCurrentTraceProjectionOptions {
56
- kind?: string;
57
- kindPrefix?: string;
58
- inscribedBy?: string;
59
- visibility?: string;
60
- }
61
-
62
- export function readCurrentTraceProjection(
63
- db: SnapshotDb,
64
- actorId: EntityRef,
65
- options: ReadCurrentTraceProjectionOptions = {},
66
- ): CurrentTraceProjection | null {
67
- const entityId = resolveEntityId(db, actorId);
68
- if (entityId === undefined) return null;
69
- const location = rows<ActorSpatialLocationRow>(db, "visible_actor_spatial_location").find(
70
- (row) => String(row.entityId) === String(entityId),
71
- );
72
- if (location === undefined) return null;
73
- const currentNodeId = asString(location.placeNodeId);
74
- const entries = rows<DbTraceRow>(db, "visible_trace")
75
- .filter((row) => asString(row.locationKind) === "place_node")
76
- .filter((row) => asString(row.locationRef) === currentNodeId)
77
- .map((row) => toTraceQueryEntry(row, db))
78
- .filter((row) => options.kind === undefined || row.kind === options.kind)
79
- .filter((row) => options.kindPrefix === undefined || row.kind.startsWith(options.kindPrefix))
80
- .filter((row) => options.inscribedBy === undefined || row.inscribed_by === options.inscribedBy)
81
- .filter((row) => options.visibility === undefined || row.visibility === options.visibility)
82
- // Trace IDs are u64 decimal strings. Numeric collation preserves their
83
- // order at equal ticks without rounding through JavaScript numbers.
84
- .sort(
85
- (a, b) =>
86
- a.inscribed_at - b.inscribed_at ||
87
- a.trace_id.localeCompare(b.trace_id, undefined, { numeric: true }),
88
- );
89
- return { actor_entity_id: String(entityId), current_node_id: currentNodeId, entries };
90
- }
91
-
92
- function toTraceQueryEntry(row: DbTraceRow, db: SnapshotDb): TraceQueryEntry {
93
- const payloadJson = asString(row.payloadJson);
94
- const payload = parsePayload(payloadJson);
95
- const response = readTraceResponse(db, payload);
96
- const inscribedBy = asString(row.inscribedBy);
97
- return {
98
- trace_id: asString(row.traceId),
99
- kind: asString(row.kind),
100
- location_kind: asString(row.locationKind),
101
- location_ref: asString(row.locationRef),
102
- payload_json: payloadJson,
103
- payload,
104
- ...(response === undefined ? {} : { response }),
105
- inscribed_at: asNumber(row.inscribedAt),
106
- expires_at: optNumber(row.expiresAt) ?? null,
107
- inscribed_by: inscribedBy === "" ? null : inscribedBy,
108
- visibility: tagString(row.visibility),
109
- bundle_id: asString(row.bundleId),
110
- };
111
- }
112
-
113
- function parsePayload(raw: string): unknown {
114
- if (raw.trim() === "") return null;
115
- try {
116
- return JSON.parse(raw);
117
- } catch {
118
- return null;
119
- }
120
- }
@@ -1,80 +0,0 @@
1
- /** Causal answer history. Never infer the answered occurrence from current prompts or time. */
2
- import type { ActionDefinitionTagRow, PromptOccurrenceRow } from "../../binding_rows";
3
- import {
4
- type RequiredTables,
5
- registerReaderManifest,
6
- type SnapshotDb,
7
- } from "../../reader-manifest";
8
- import { rows } from "./_helpers";
9
- import { readAudienceTracePresentation } from "./audience_trace_presentation";
10
- import { readDialoguePromptPresentation } from "./dialogue_prompt_presentation";
11
-
12
- export const requiredTables: RequiredTables<
13
- [
14
- "action_definition_tag",
15
- "visible_prompt_occurrence",
16
- "public_metadata_attachment",
17
- "visible_metadata_attachment",
18
- "visible_trace",
19
- ]
20
- > = [
21
- "action_definition_tag",
22
- "visible_prompt_occurrence",
23
- "public_metadata_attachment",
24
- "visible_metadata_attachment",
25
- "visible_trace",
26
- ];
27
- registerReaderManifest({ requiredTables });
28
-
29
- export interface TraceResponse {
30
- action_id: string;
31
- slot: number;
32
- occurrence_id?: string;
33
- label?: string;
34
- }
35
-
36
- /** Public authored syntax marker, independent of target admission. */
37
- export function responseSlot(tags: readonly string[]): number | undefined {
38
- for (const tag of tags) {
39
- if (!tag.startsWith("ui.response-slot=")) continue;
40
- const value = Number(tag.slice("ui.response-slot=".length));
41
- if (Number.isSafeInteger(value) && value > 0) return value;
42
- }
43
- return undefined;
44
- }
45
-
46
- export function responseSlotFields(tags: readonly string[]): { response_slot?: number } {
47
- const slot = responseSlot(tags);
48
- return slot === undefined ? {} : { response_slot: slot };
49
- }
50
-
51
- export function readTraceResponse(db: SnapshotDb, payload: unknown): TraceResponse | undefined {
52
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return undefined;
53
- const body = payload as Record<string, unknown>;
54
- if (typeof body.action_id !== "string") return undefined;
55
- const actionId = body.action_id;
56
- const slot = responseSlot(
57
- rows<ActionDefinitionTagRow>(db, "action_definition_tag")
58
- .filter((row) => row.actionId === actionId)
59
- .map((row) => row.tag),
60
- );
61
- if (slot === undefined) return undefined;
62
- const response: TraceResponse = { action_id: actionId, slot };
63
- // u64 identities travel as decimal strings, avoiding JavaScript precision loss.
64
- if (typeof body.occurrence_id !== "string" || !/^\d+$/.test(body.occurrence_id)) return response;
65
- response.occurrence_id = body.occurrence_id;
66
- const occurrence = rows<PromptOccurrenceRow>(db, "visible_prompt_occurrence").find(
67
- (row) => String(row.occurrenceId) === body.occurrence_id,
68
- );
69
- if (!occurrence || occurrence.responseActionIds[slot - 1] !== actionId) return response;
70
- const authored = readDialoguePromptPresentation(db).get(occurrence.promptDefId);
71
- const presentation = readAudienceTracePresentation(
72
- db,
73
- String(occurrence.audienceTraceId),
74
- occurrence.responseActionIds,
75
- authored,
76
- );
77
- const label = presentation?.labels[actionId];
78
- if (label !== undefined && label !== String(slot)) response.label = label;
79
- return response;
80
- }
@@ -1,124 +0,0 @@
1
- import type { TraceRow as DbTraceRow } from "../../binding_rows";
2
- import {
3
- type RequiredTables,
4
- registerReaderManifest,
5
- type SnapshotDb,
6
- } from "../../reader-manifest";
7
- import { asNumber, asString, optNumber, rows, tagString } from "./_helpers";
8
- import { readTraceResponse, type TraceResponse } from "./trace_response";
9
-
10
- // `trace` is private (ADR-0120, #915); subscribe + read the per-caller
11
- // `visible_trace` view — a body sees only the traces it has perceived
12
- // (bounded by observer_trace_knowledge). Raw god-view → operator `just sql`.
13
- export const requiredTables: RequiredTables<
14
- [
15
- "action_definition_tag",
16
- "visible_prompt_occurrence",
17
- "public_metadata_attachment",
18
- "visible_metadata_attachment",
19
- "visible_trace",
20
- ]
21
- > = [
22
- "action_definition_tag",
23
- "visible_prompt_occurrence",
24
- "public_metadata_attachment",
25
- "visible_metadata_attachment",
26
- "visible_trace",
27
- ];
28
- registerReaderManifest({ requiredTables });
29
-
30
- export interface TraceRow {
31
- trace_id: string;
32
- kind: string;
33
- location_kind: string;
34
- location_ref: string;
35
- payload_json: string;
36
- payload: unknown;
37
- response?: TraceResponse;
38
- inscribed_at: number;
39
- // decay_rate / decay_bound removed — Item 9 (09-decay-as-condition.md)
40
- // dissolved these columns into the condition machinery; they no longer
41
- // appear in the generated trace_table binding.
42
- expires_at: number | null;
43
- inscribed_by: string | null;
44
- visibility: string;
45
- bundle_id: string;
46
- }
47
-
48
- export interface ReadTracesAtOpts {
49
- kind?: string;
50
- inscribedBy?: string;
51
- }
52
-
53
- export function readTracesAt(
54
- db: SnapshotDb,
55
- locationKind: string,
56
- locationRef: string,
57
- opts: ReadTracesAtOpts = {},
58
- ): TraceRow[] {
59
- return rows<DbTraceRow>(db, "visible_trace")
60
- .filter((r) => asString(r.locationKind) === locationKind)
61
- .filter((r) => asString(r.locationRef) === locationRef)
62
- .filter((r) => opts.kind === undefined || asString(r.kind) === opts.kind)
63
- .filter((r) => opts.inscribedBy === undefined || asString(r.inscribedBy) === opts.inscribedBy)
64
- .map((row) => toTraceRow(row, db))
65
- .sort(
66
- (a, b) =>
67
- a.inscribed_at - b.inscribed_at ||
68
- a.trace_id.localeCompare(b.trace_id, undefined, { numeric: true }),
69
- );
70
- }
71
-
72
- /**
73
- * The `n` most recent traces this caller currently perceives, UNFILTERED by
74
- * location — the location-scoped `readTracesAt` above cannot see an
75
- * entity-anchored trace (ADR-0095 D-1, e.g. `srd/speak-to`'s addressee
76
- * anchor) unless the caller already knows which node OR which entity to ask
77
- * for. `visible_trace` (module header) is already per-caller bounded by
78
- * `observer_trace_knowledge` (ADR-0040) — this is the same "read window,
79
- * unfiltered" shape `readRecentResourceDeltas` (`resource_deltas.ts`) uses
80
- * over the sibling `visible_event_resource_delta` view, for the same reason:
81
- * a caller diffing this view call-to-call (shared tool runtime's push-events.ts)
82
- * wants a bounded recent slice, not a full unbounded scan every cycle, and
83
- * has no single location to scope to.
84
- */
85
- export function readRecentTraces(db: SnapshotDb, n: number): TraceRow[] {
86
- if (n <= 0) return [];
87
- const all = rows<DbTraceRow>(db, "visible_trace")
88
- .map((row) => toTraceRow(row, db))
89
- .sort((a, b) => b.trace_id.localeCompare(a.trace_id, undefined, { numeric: true }));
90
- return all.slice(0, n);
91
- }
92
-
93
- function toTraceRow(r: DbTraceRow, db: SnapshotDb): TraceRow {
94
- const payloadJson = asString(r.payloadJson);
95
- const payload = parsePayload(payloadJson);
96
- const response = readTraceResponse(db, payload);
97
- const inscribedBy = asString(r.inscribedBy);
98
- return {
99
- trace_id: asString(r.traceId),
100
- kind: asString(r.kind),
101
- location_kind: asString(r.locationKind),
102
- location_ref: asString(r.locationRef),
103
- payload_json: payloadJson,
104
- payload,
105
- ...(response === undefined ? {} : { response }),
106
- inscribed_at: asNumber(r.inscribedAt),
107
- expires_at: optNumber(r.expiresAt) ?? null,
108
- inscribed_by: inscribedBy === "" ? null : inscribedBy,
109
- // `trace.visibility` is the `VisibilityClass` tagged enum ({ tag: "Public" }),
110
- // not a plain string — `asString` would collapse it to "[object Object]"
111
- // (surfaced by the world-explorer wanderer reading back an inscribed trace).
112
- visibility: tagString(r.visibility),
113
- bundle_id: asString(r.bundleId),
114
- };
115
- }
116
-
117
- function parsePayload(raw: string): unknown {
118
- if (raw.trim() === "") return null;
119
- try {
120
- return JSON.parse(raw);
121
- } catch {
122
- return null;
123
- }
124
- }
@@ -1,88 +0,0 @@
1
- import type { SessionRow } from "../../binding_rows";
2
- import type { SnapshotDb } from "../../reader-manifest";
3
- import { rows } from "./_helpers";
4
- import { isLiveSessionLifecycle, readSessionParticipants } from "./session";
5
-
6
- export interface TravelSession {
7
- /** The session walking this actor. */
8
- sessionId: bigint;
9
- /** World tick the walk was admitted on. */
10
- openedAt: bigint;
11
- /** Total ticks the server priced the walk at, computed once at admission. */
12
- durationTicks: bigint;
13
- /** `openedAt + durationTicks` — the tick the actor is put down on. */
14
- arrivesAtTick: bigint;
15
- /** Ticks still to go from `now`, floored at 0. */
16
- arrivesInTicks: bigint;
17
- /** The action that was promoted into this session, when the server named one. */
18
- originatingAction: string;
19
- }
20
-
21
- /** The open long-running session `actorId` is currently being walked by, or
22
- * `null` when they are not in transit.
23
- *
24
- * A session qualifies only when `promotedDurationTicks > 0`: that field is the
25
- * §5.10 auto-promotion marker, and a session opened directly through
26
- * `r_session_open` (a combat, say) always carries 0. So this never mistakes a
27
- * fight for a walk.
28
- *
29
- * `now` defaults to the world tick this snapshot can see. Pass it explicitly
30
- * when the caller already holds a tick it wants the answer relative to. */
31
- /** The world tick this snapshot can see. Read straight off `world_time`
32
- * rather than through `currentWorldTickOrZero` — that helper is typed against
33
- * the root entry's `SnapshotDb`, and this reader lives on the browser-safe
34
- * reader subpath, which names a different (structurally compatible) one. */
35
- function visibleWorldTick(db: SnapshotDb): bigint {
36
- for (const row of rows<{ tick?: bigint | number | string }>(db, "world_time")) {
37
- const tick = (row as { tick?: bigint | number | string }).tick;
38
- return typeof tick === "bigint" ? tick : BigInt(String(tick ?? 0));
39
- }
40
- return 0n;
41
- }
42
-
43
- export function travelSessionForActor(
44
- db: SnapshotDb,
45
- actorId: string,
46
- now?: bigint,
47
- ): TravelSession | null {
48
- const tick = now ?? visibleWorldTick(db);
49
- const candidates = rows<SessionRow>(db, "visible_session", "session")
50
- .map((row) => {
51
- const r = row as unknown as {
52
- sessionId: unknown;
53
- lifecycle: string;
54
- openedAt: unknown;
55
- promotedDurationTicks: unknown;
56
- originatingAction: unknown;
57
- };
58
- const big = (value: unknown): bigint =>
59
- typeof value === "bigint" ? value : BigInt(String(value ?? 0));
60
- return {
61
- sessionId: big(r.sessionId),
62
- lifecycle: r.lifecycle,
63
- openedAt: big(r.openedAt),
64
- durationTicks: big(r.promotedDurationTicks),
65
- originatingAction: String(r.originatingAction ?? ""),
66
- };
67
- })
68
- .filter((session) => isLiveSessionLifecycle(session.lifecycle) && session.durationTicks > 0n)
69
- // Newest first: an actor should never be in two walks at once, but if a
70
- // stale row ever lingered, the walk they just started is the honest answer.
71
- .sort((a, b) => (a.sessionId < b.sessionId ? 1 : a.sessionId > b.sessionId ? -1 : 0));
72
-
73
- for (const session of candidates) {
74
- const participants = readSessionParticipants(db, session.sessionId);
75
- if (!participants.some((participant) => participant.actorId === actorId)) continue;
76
- const arrivesAtTick = session.openedAt + session.durationTicks;
77
- const remaining = arrivesAtTick - tick;
78
- return {
79
- sessionId: session.sessionId,
80
- openedAt: session.openedAt,
81
- durationTicks: session.durationTicks,
82
- arrivesAtTick,
83
- arrivesInTicks: remaining > 0n ? remaining : 0n,
84
- originatingAction: session.originatingAction,
85
- };
86
- }
87
- return null;
88
- }