@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,228 +0,0 @@
1
- // Profile + connection resolution precedence.
2
- //
3
- // Mirrors the Rust contract in `client/src/resolve.rs` exactly:
4
- //
5
- // Profile selection precedence:
6
- // 1. explicit override (CLI --profile, or `/spellkave <name>` argument)
7
- // 2. last-used profile from state
8
- // 3. default_profile in app config
9
- // 4. None
10
- //
11
- // Connection field precedence (per field):
12
- // 1. explicit override (--url / --db; pi has no equivalent yet, but the
13
- // slot exists for parity with the Rust contract)
14
- // 2. selected profile's connection.{url, db}
15
- // 3. built-in default
16
- //
17
- // A last-used pointer whose profile file is gone is skipped (sk-sol) rather
18
- // than failing the whole connection — switching adventures must not inherit a
19
- // dead seat. Explicit `--profile` still fails closed.
20
- //
21
- // Source-of-truth tags follow the Rust enum ordering for diagnostics.
22
- //
23
- // Browser-reachable through the `@spellkave/sdk` barrel: NO top-level `node:*`
24
- // imports. File reads come in through injected `io` readers; Node hosts get the
25
- // `node:fs`-backed defaults from `@spellkave/sdk/node` (`node-io.ts`).
26
-
27
- import {
28
- appConfigFile,
29
- type CliPaths,
30
- checkedProfileFile,
31
- lastUsedProfileFile,
32
- scopedCurrentContextFile,
33
- scopedLastUsedProfileFile,
34
- validateProfileName,
35
- } from "./paths";
36
- import type { AppConfig, PersonaProfile } from "./profile";
37
- import { loadAppConfigFromDisk, loadProfileFromDisk } from "./profile";
38
-
39
- export type Source = "flag" | "profile" | "built_in";
40
- export type ProfileSource = "flag" | "last_used" | "app_config_default" | "none";
41
-
42
- export interface ResolvedConnection {
43
- url: string;
44
- db: string;
45
- profile: string | undefined;
46
- url_source: Source;
47
- db_source: Source;
48
- profile_source: ProfileSource;
49
- }
50
-
51
- export interface CliOverrides {
52
- url?: string;
53
- db?: string;
54
- /**
55
- * Explicit profile override. For pi this comes from the optional argument
56
- * to `/spellkave <profile-name>`; for the Rust CLI it is `--profile`.
57
- */
58
- profile?: string;
59
- }
60
-
61
- export interface ResolutionInputs {
62
- paths: CliPaths;
63
- built_in_url: string;
64
- built_in_db: string;
65
- /**
66
- * Last-used profile name. Pass `undefined` for invocations that should
67
- * NOT honor remembered state (e.g. one-shot scripted reads).
68
- */
69
- last_used_profile: string | undefined;
70
- /**
71
- * Test/override hooks for fs reads. Production callers leave undefined.
72
- */
73
- io?: { readFileSync?: (path: string) => string };
74
- }
75
-
76
- export function resolveConnection(
77
- overrides: CliOverrides,
78
- inputs: ResolutionInputs,
79
- ): ResolvedConnection {
80
- const io = inputs.io ?? {};
81
- const appCfg = loadAppConfigFromDisk(appConfigFile(inputs.paths), io);
82
- let selected = pickProfile(overrides, appCfg, inputs.last_used_profile);
83
- if (selected.name !== undefined) {
84
- validateProfileName(selected.name);
85
- }
86
- let profile: PersonaProfile | undefined;
87
- if (selected.name !== undefined) {
88
- try {
89
- profile = loadProfileFromDisk(checkedProfileFile(inputs.paths, selected.name), io);
90
- } catch (err) {
91
- if (selected.source !== "last_used") throw err;
92
- // Dead last-used pointer from a previous adventure/worktree: skip it.
93
- selected = pickProfile(overrides, appCfg, undefined);
94
- if (selected.name !== undefined) {
95
- validateProfileName(selected.name);
96
- profile = loadProfileFromDisk(checkedProfileFile(inputs.paths, selected.name), io);
97
- }
98
- }
99
- }
100
- const [url, urlSource] = pickField(overrides.url, profile?.connection.url, inputs.built_in_url);
101
- const [db, dbSource] = pickField(overrides.db, profile?.connection.db, inputs.built_in_db);
102
- return {
103
- url,
104
- db,
105
- profile: selected.name,
106
- url_source: urlSource,
107
- db_source: dbSource,
108
- profile_source: selected.source,
109
- };
110
- }
111
-
112
- function pickProfile(
113
- overrides: CliOverrides,
114
- appCfg: AppConfig,
115
- lastUsed: string | undefined,
116
- ): { name: string | undefined; source: ProfileSource } {
117
- if (overrides.profile !== undefined) {
118
- return { name: overrides.profile, source: "flag" };
119
- }
120
- if (lastUsed !== undefined) {
121
- return { name: lastUsed, source: "last_used" };
122
- }
123
- if (appCfg.default_profile !== undefined) {
124
- return { name: appCfg.default_profile, source: "app_config_default" };
125
- }
126
- return { name: undefined, source: "none" };
127
- }
128
-
129
- function pickField(
130
- flag: string | undefined,
131
- profileValue: string | undefined,
132
- builtIn: string,
133
- ): [string, Source] {
134
- if (flag !== undefined) return [flag, "flag"];
135
- if (profileValue !== undefined) return [profileValue, "profile"];
136
- return [builtIn, "built_in"];
137
- }
138
-
139
- /**
140
- * Read last-used profile state. Returns `undefined` for missing or empty
141
- * file (normal first-run). Pass `worktreeRoot` to read the per-worktree
142
- * pointer (`last_used_profiles/by_worktree/<hash>`); omit it only to inspect
143
- * the legacy app-global file.
144
- */
145
- export function readLastUsedProfile(
146
- paths: CliPaths,
147
- io: { readFileSync?: (p: string) => string } = {},
148
- worktreeRoot?: string,
149
- ): string | undefined {
150
- const reader = io.readFileSync;
151
- if (reader === undefined) {
152
- throw new Error(
153
- "readLastUsedProfile requires io.readFileSync; use @spellkave/sdk/node for the Node-bound default",
154
- );
155
- }
156
- const file =
157
- worktreeRoot === undefined
158
- ? lastUsedProfileFile(paths)
159
- : scopedLastUsedProfileFile(paths, worktreeRoot);
160
- try {
161
- const raw = reader(file);
162
- const trimmed = raw.trim();
163
- return trimmed.length === 0 ? undefined : trimmed;
164
- } catch (err: unknown) {
165
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return undefined;
166
- throw err;
167
- }
168
- }
169
-
170
- /**
171
- * Read the per-worktree current context (`current_context/by_worktree/<hash>`).
172
- * Returns `undefined` for a missing or empty file. Never falls back to the
173
- * last-used pointer: the two are separate on purpose (sk-config-contexts D1).
174
- */
175
- export function readCurrentContext(
176
- paths: CliPaths,
177
- io: { readFileSync?: (p: string) => string },
178
- worktreeRoot: string,
179
- ): string | undefined {
180
- const reader = io.readFileSync;
181
- if (reader === undefined) {
182
- throw new Error(
183
- "readCurrentContext requires io.readFileSync; use @spellkave/sdk/node for the Node-bound default",
184
- );
185
- }
186
- try {
187
- const trimmed = reader(scopedCurrentContextFile(paths, worktreeRoot)).trim();
188
- return trimmed.length === 0 ? undefined : trimmed;
189
- } catch (err: unknown) {
190
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return undefined;
191
- throw err;
192
- }
193
- }
194
-
195
- /**
196
- * List candidate profile names by reading the `profiles/` dir.
197
- * Used by the `/spellkave <profile-name>` argument completer.
198
- * Returns names sorted alphabetically; missing dir → empty array.
199
- */
200
- export function listProfileNames(
201
- paths: CliPaths,
202
- io: { readdirSync?: (p: string) => string[] } = {},
203
- ): string[] {
204
- const reader = io.readdirSync;
205
- if (reader === undefined) {
206
- throw new Error(
207
- "listProfileNames requires io.readdirSync; use @spellkave/sdk/node for the Node-bound default",
208
- );
209
- }
210
- try {
211
- const entries = reader(`${paths.config}/profiles`);
212
- return entries
213
- .filter((e) => e.endsWith(".toml"))
214
- .map((e) => e.slice(0, -".toml".length))
215
- .filter((n) => {
216
- try {
217
- validateProfileName(n);
218
- return true;
219
- } catch {
220
- return false;
221
- }
222
- })
223
- .sort();
224
- } catch (err: unknown) {
225
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return [];
226
- throw err;
227
- }
228
- }
@@ -1,146 +0,0 @@
1
- // Telemetry for the connect-time shape check in "warn" mode (sk-jay0.7.389.3).
2
- //
3
- // One `contract_shape_mismatch` event per breaking change the client connected
4
- // past. Two carriers, one shape:
5
- // - always: a diagnostic line through connect()'s `onDiagnostic` sink
6
- // (a browser app forwards it to its own telemetry, e.g. Play's RUM);
7
- // - in a Node host with `SPELLKAVE_AGENT_OBS_OTLP_ENDPOINT` set (every hosted
8
- // pod that already ships `world_actor_run_events`): the same event as an
9
- // `agent-run-events/v1` OTLP log record, so it lands in OpenObserve with no
10
- // host wiring.
11
- import {
12
- AGENT_RUN_EVENTS_VERSION,
13
- type AgentRunEvent,
14
- createOtlpHttpSink,
15
- } from "@spellkave/agent-observability";
16
- import {
17
- logSinkResourceAttributesFromEnv,
18
- parseOtelPairs,
19
- serviceVersionFromEnv,
20
- } from "@spellkave/agent-observability/resource";
21
- import type { RuntimeChange } from "./world-contract/index.ts";
22
-
23
- export const CONTRACT_SHAPE_MISMATCH = "contract_shape_mismatch";
24
-
25
- /** The fields of one mismatch, as the diagnostic line and the OTLP event carry them. */
26
- export interface ShapeMismatchFields {
27
- readonly shape_mode: "warn";
28
- readonly shape_database: string;
29
- readonly shape_item: string;
30
- readonly shape_detail: string;
31
- readonly client_epoch: number;
32
- }
33
-
34
- /** Longest `shape_detail` carried; a shifted row can list many columns. */
35
- export const SHAPE_DETAIL_MAX = 1000;
36
-
37
- /** One entry per mismatched ITEM (its changes joined), not per shifted column. */
38
- export function shapeMismatchFields(
39
- changes: readonly RuntimeChange[],
40
- database: string,
41
- clientEpoch: number,
42
- ): ShapeMismatchFields[] {
43
- const byItem = new Map<string, string[]>();
44
- for (const c of changes) byItem.set(c.item, [...(byItem.get(c.item) ?? []), c.detail]);
45
- return [...byItem.entries()].map(([item, details]) => {
46
- const detail = details.join("; ");
47
- return {
48
- shape_mode: "warn",
49
- shape_database: database,
50
- shape_item: item,
51
- shape_detail:
52
- detail.length > SHAPE_DETAIL_MAX ? `${detail.slice(0, SHAPE_DETAIL_MAX - 1)}…` : detail,
53
- client_epoch: clientEpoch,
54
- };
55
- });
56
- }
57
-
58
- const reported = new Set<string>();
59
-
60
- /**
61
- * The mismatches this process has not reported yet. Hosts such as the api and
62
- * the gateway connect per request; one report per distinct mismatch per
63
- * process keeps the volume independent of the request rate.
64
- */
65
- export function unreportedShapeMismatches(
66
- fields: readonly ShapeMismatchFields[],
67
- ): ShapeMismatchFields[] {
68
- const fresh = fields.filter(
69
- (f) => !reported.has(JSON.stringify([f.shape_database, f.shape_item, f.shape_detail])),
70
- );
71
- for (const f of fresh)
72
- reported.add(JSON.stringify([f.shape_database, f.shape_item, f.shape_detail]));
73
- return fresh;
74
- }
75
-
76
- /** Test seam: forget what this process reported. */
77
- export function resetReportedShapeMismatches(): void {
78
- reported.clear();
79
- }
80
-
81
- /** The `agent-run-events/v1` form of the mismatches (a service row, no actor decision). */
82
- export function shapeMismatchEvents(
83
- fields: readonly ShapeMismatchFields[],
84
- envelope: {
85
- readonly runId: string;
86
- readonly actorId: string;
87
- readonly driver: string;
88
- readonly now: Date;
89
- },
90
- ): AgentRunEvent[] {
91
- return fields.map((data) => ({
92
- v: AGENT_RUN_EVENTS_VERSION,
93
- run_id: envelope.runId,
94
- run_kind: "contract_check",
95
- actor_id: envelope.actorId,
96
- role: "SERVICE",
97
- controller_kind: "service",
98
- driver: envelope.driver,
99
- seed: "",
100
- ts: envelope.now.toISOString(),
101
- type: CONTRACT_SHAPE_MISMATCH,
102
- data: { ...data },
103
- }));
104
- }
105
-
106
- type Env = Record<string, string | undefined>;
107
-
108
- function processEnv(): Env | undefined {
109
- return (globalThis as { process?: { env?: Env } }).process?.env;
110
- }
111
-
112
- /**
113
- * Ships the events to the world-actor OTLP logs endpoint when the host has
114
- * one configured; resolves `false` (and sends nothing) otherwise. Never
115
- * throws: a lost telemetry copy must not change whether the client connects.
116
- */
117
- export async function exportShapeMismatches(
118
- events: readonly AgentRunEvent[],
119
- env: Env | undefined = processEnv(),
120
- fetchFn?: typeof fetch,
121
- ): Promise<boolean> {
122
- const endpoint = env?.SPELLKAVE_AGENT_OBS_OTLP_ENDPOINT?.trim();
123
- if (!endpoint || events.length === 0) return false;
124
- try {
125
- const serviceVersion = serviceVersionFromEnv(env as NodeJS.ProcessEnv);
126
- const sink = createOtlpHttpSink({
127
- endpoint,
128
- headers: parseOtelPairs(
129
- env?.OTEL_EXPORTER_OTLP_LOGS_HEADERS ?? env?.OTEL_EXPORTER_OTLP_HEADERS,
130
- ),
131
- resourceAttributes: logSinkResourceAttributesFromEnv(env as NodeJS.ProcessEnv),
132
- ...(serviceVersion === undefined ? {} : { serviceVersion }),
133
- ...(fetchFn === undefined ? {} : { fetchFn }),
134
- });
135
- for (const event of events) sink.write(event);
136
- await sink.close?.();
137
- return true;
138
- } catch {
139
- return false;
140
- }
141
- }
142
-
143
- /** The driver name for the OTLP envelope: the host's own service name when set. */
144
- export function shapeTelemetryDriver(env: Env | undefined = processEnv()): string {
145
- return env?.OTEL_SERVICE_NAME?.trim() || env?.SPELLKAVE_SERVICE_NAME?.trim() || "spellkave-sdk";
146
- }
@@ -1,109 +0,0 @@
1
- // Camel/snake-tolerant raw-row helpers over a `SnapshotDb`, plus the two
2
- // content-free reads built on them (dead entity ids, entity-key resolution).
3
- //
4
- // This module knows NO bundle or condition id: a caller that needs "the dead
5
- // condition" passes its id in. The sdk stays id-free.
6
-
7
- import type { SnapshotDb } from "../reader-manifest";
8
- import type { EntityRef } from "./ids";
9
- import { asEntityRef } from "./ids";
10
- import { resolveEntityId } from "./readers/_helpers";
11
-
12
- /** Rows of the FIRST table handle that exists on `db` under any of `names`
13
- * (the generated accessors are camelCase, fixtures and some raw handles are
14
- * snake_case). Empty when none exists. For private tables callers MUST list the
15
- * visible view first: `--include-private` leaves an unsubscribed empty raw
16
- * handle that would shadow it. */
17
- export function tableRows(db: SnapshotDb, ...names: string[]): Iterable<unknown> {
18
- const record = db as unknown as Record<string, unknown>;
19
- for (const name of names) {
20
- const handle = record[name];
21
- if (handle && typeof handle === "object" && "iter" in handle) {
22
- return (handle as { iter(): Iterable<unknown> }).iter();
23
- }
24
- }
25
- return [];
26
- }
27
-
28
- /** The first non-null, non-empty value among `names` on `row`, stringified;
29
- * `""` when none. */
30
- export function fieldOf(row: Record<string, unknown>, ...names: string[]): string {
31
- for (const name of names) {
32
- const value = row[name];
33
- if (value !== undefined && value !== null && String(value).length > 0) return String(value);
34
- }
35
- return "";
36
- }
37
-
38
- /**
39
- * Entity ids currently carrying the dead condition.
40
- *
41
- * `deadConditionId` is required: the sdk cannot know the ruleset's id. A
42
- * condition counts as dead when it equals `deadConditionId`, or - only when the
43
- * caller passes `deadConditionSuffix` - ends with it (bundle-prefixed copies of
44
- * the same condition, e.g. `"/condition/dead"`).
45
- */
46
- export function readDeadEntityIds(
47
- db: SnapshotDb,
48
- options: { deadConditionId: string; deadConditionSuffix?: string },
49
- ): Set<string> {
50
- const { deadConditionId, deadConditionSuffix } = options;
51
- const dead = new Set<string>();
52
- for (const raw of tableRows(
53
- db,
54
- "visibleTargetCondition",
55
- "visible_target_condition",
56
- "target_condition",
57
- )) {
58
- const row = raw as Record<string, unknown>;
59
- const conditionId = fieldOf(
60
- row,
61
- "conditionId",
62
- "condition_id",
63
- "conditionDefinitionId",
64
- "condition_definition_id",
65
- );
66
- const isDead =
67
- conditionId === deadConditionId ||
68
- (deadConditionSuffix !== undefined &&
69
- deadConditionSuffix !== "" &&
70
- conditionId.endsWith(deadConditionSuffix));
71
- if (!isDead) continue;
72
- const entityId = fieldOf(
73
- row,
74
- "entityId",
75
- "entity_id",
76
- "targetEntityId",
77
- "target_entity_id",
78
- "targetBodyEntityId",
79
- "target_body_entity_id",
80
- "targetId",
81
- "target_id",
82
- );
83
- if (entityId !== "") dead.add(entityId);
84
- }
85
- return dead;
86
- }
87
-
88
- /**
89
- * Map each authored entity key to its live numeric entity id (as a string),
90
- * omitting keys that are not placed.
91
- *
92
- * `resolveEntityId` matches the bare key against
93
- * `visible_manifest_authored_entity.manifest_key` after its first `bundle:` colon, so a
94
- * key that itself carries a `bundle:` prefix is tried bare first, then verbatim.
95
- * Do not strip path segments.
96
- */
97
- export function resolveEntityKeys(db: SnapshotDb, keys: readonly EntityRef[]): Map<string, string> {
98
- const out = new Map<string, string>();
99
- for (const key of keys) {
100
- try {
101
- const bare = key.includes(":") ? asEntityRef(key.slice(key.indexOf(":") + 1)) : key;
102
- const id = resolveEntityId(db, bare) ?? resolveEntityId(db, key);
103
- if (id !== undefined) out.set(key, String(id));
104
- } catch {
105
- /* not placed */
106
- }
107
- }
108
- return out;
109
- }
@@ -1,61 +0,0 @@
1
- // D7 tick-interval estimator (design.md:167; spec.md "Floor applies before five deltas").
2
-
3
- export class TickIntervalEstimator {
4
- private readonly _window = 5;
5
- private readonly _floor = 200;
6
- // Ring buffer of the last 5 (tick, wallMs) observations.
7
- private _obs: Array<{ tick: bigint; ms: number }> = [];
8
-
9
- /** Wall-clock ms of the most recent recorded observation, or null if no observations. */
10
- lastObservedAtMs(): number | null {
11
- if (this._obs.length === 0) return null;
12
- // biome-ignore lint/style/noNonNullAssertion: pre-existing debt from #1368 biome onboarding, tracked in #1455
13
- return this._obs[this._obs.length - 1]!.ms;
14
- }
15
-
16
- record(tick: bigint, observedAtMs: number): void {
17
- this._obs.push({ tick, ms: observedAtMs });
18
- if (this._obs.length > this._window + 1) {
19
- this._obs.shift();
20
- }
21
- }
22
-
23
- /** True once five tick-to-tick deltas have been recorded. Until then
24
- * {@link estimateMs} returns the 200ms floor, which is *not* a measured
25
- * cadence — callers that scale an observation window from it must treat
26
- * a cold estimator as unknown rather than as a 200ms world. */
27
- hasMeasuredCadence(): boolean {
28
- return this.measuredDeltas() !== null;
29
- }
30
-
31
- estimateMs(): number {
32
- const deltas = this.measuredDeltas();
33
- if (deltas === null) return this._floor;
34
-
35
- const sorted = deltas.slice().sort((a, b) => a - b);
36
- // biome-ignore lint/style/noNonNullAssertion: pre-existing debt from #1368 biome onboarding, tracked in #1455
37
- const median = sorted[Math.floor(sorted.length / 2)]!;
38
- // Floor applies only before 5 deltas are observed; once we have enough data,
39
- // return the measured median directly (spec.md "Floor applies before five deltas").
40
- return median;
41
- }
42
-
43
- private measuredDeltas(): number[] | null {
44
- // Need at least 2 observations to compute 1 delta; 6 to get 5 deltas.
45
- if (this._obs.length < this._window + 1) return null;
46
-
47
- const deltas: number[] = [];
48
- for (let i = 1; i < this._obs.length; i++) {
49
- // biome-ignore lint/style/noNonNullAssertion: pre-existing debt from #1368 biome onboarding, tracked in #1455
50
- const prev = this._obs[i - 1]!;
51
- // biome-ignore lint/style/noNonNullAssertion: pre-existing debt from #1368 biome onboarding, tracked in #1455
52
- const curr = this._obs[i]!;
53
- if (curr.tick > prev.tick) {
54
- const tickSpan = Number(curr.tick - prev.tick);
55
- deltas.push((curr.ms - prev.ms) / tickSpan);
56
- }
57
- }
58
- if (deltas.length < this._window) return null;
59
- return deltas;
60
- }
61
- }