@spellkave/session 0.0.0-bootstrap

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 (44) hide show
  1. package/LICENSE +89 -0
  2. package/bin/spellkave-session-daemon.js +5 -0
  3. package/package.json +60 -0
  4. package/src/acting-context.ts +222 -0
  5. package/src/authoring/caller-tools.ts +227 -0
  6. package/src/authoring/index.ts +28 -0
  7. package/src/authoring/live-applyset-port.ts +432 -0
  8. package/src/authoring/live-author-target.ts +995 -0
  9. package/src/authoring/live-can-i-port.ts +152 -0
  10. package/src/authoring/live-exploration-port.ts +274 -0
  11. package/src/authoring/live-grants-port.ts +172 -0
  12. package/src/authoring/live-scenes-port.ts +84 -0
  13. package/src/authoring/live-scoped-instance-port.ts +355 -0
  14. package/src/binding.ts +125 -0
  15. package/src/index.ts +24 -0
  16. package/src/live/discovery-closure-walk.ts +318 -0
  17. package/src/live/kernel-convergence-support.ts +122 -0
  18. package/src/live/seed.ts +37 -0
  19. package/src/live/support.ts +82 -0
  20. package/src/node/client.ts +233 -0
  21. package/src/node/connection-controller.ts +469 -0
  22. package/src/node/daemon-entry.ts +57 -0
  23. package/src/node/daemon.ts +629 -0
  24. package/src/node/index.ts +110 -0
  25. package/src/node/live-delta.ts +229 -0
  26. package/src/node/observability.ts +481 -0
  27. package/src/node/paths.ts +83 -0
  28. package/src/node/player-run-observer.ts +122 -0
  29. package/src/node/protocol.ts +200 -0
  30. package/src/node/spawn.ts +225 -0
  31. package/src/node/world-events.ts +270 -0
  32. package/src/player-tools/delta-tracker.ts +1 -0
  33. package/src/player-tools/index.ts +10 -0
  34. package/src/player-tools/node-adapter.ts +9 -0
  35. package/src/player-tools/observation.ts +1 -0
  36. package/src/player-tools/player-host.ts +92 -0
  37. package/src/player-tools/push-events.ts +1 -0
  38. package/src/player-tools/query-protocol.ts +1 -0
  39. package/src/player-tools/refusal-prose.ts +1 -0
  40. package/src/player-tools/resolution.ts +1 -0
  41. package/src/player-tools/tool-registry.ts +1 -0
  42. package/src/player-tools/tools.ts +42 -0
  43. package/src/player-tools/world-events.ts +119 -0
  44. package/src/session.ts +604 -0
@@ -0,0 +1,995 @@
1
+ // The connection-level `AuthorTarget` (#1968 "Decision: connection-level
2
+ // target for the author tools"): a uniform backend interface every AUTHOR
3
+ // write verb's reference checks and `spellkave_apply_manifest_delta` flush
4
+ // against, replacing the ad hoc "check the workspace, then optionally check
5
+ // `context.db` if it's wired" pattern each verb used to hand-roll.
6
+ //
7
+ // This session adapter owns only `live`: it reads through the connected SDK
8
+ // snapshot thunk and dispatches `applyBatch` through the optional
9
+ // `r_apply_manifest_delta` port. The filesystem-backed `local` adapter is
10
+ // exclusively `@spellkave/tool-node/authoring`.
11
+ //
12
+ // Dependency-direction note: `resolveRef`/`lookup` take a manifest ROW-KIND
13
+ // name (a key of `@spellkave/world-author`'s `ROW_KIND_NATURAL_KEY`) — the
14
+ // SAME vocabulary the workspace's own upsert-by-key merge already uses
15
+ // (`authoring-verbs.ts`), not a new verb-facing enum. `live` is a BOUNDED,
16
+ // honestly-documented table (`LIVE_TABLE_ACCESSORS` below) —
17
+ // only the row kinds an actual AUTHOR-tool ref-check or `spellkave_lookup`
18
+ // kind needs, because (unlike `local`, which just returns parsed TOML rows
19
+ // verbatim) mapping a LIVE table's camelCase SDK row shape back to the
20
+ // manifest's snake_case row shape needs a per-table accessor, and inventing
21
+ // one for a row kind nothing currently queries would be untested guesswork.
22
+
23
+ import type { AuthorSnapshotDb, AuthorTarget, ManifestRow } from "@spellkave/tool-authoring";
24
+ import {
25
+ type ScopedInstanceSnapshot,
26
+ type ScopedSnapshotPort,
27
+ scopedInlineDeltaPreflight,
28
+ } from "@spellkave/world-author/tooling";
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // `live` driver
32
+ // ---------------------------------------------------------------------------
33
+
34
+ interface TableHandleLike {
35
+ iter(): Iterable<Record<string, unknown>>;
36
+ }
37
+
38
+ /**
39
+ * SpacetimeDB no-payload-enum shape: a client-side row field for a Rust
40
+ * `#[derive(SpacetimeType)]` unit-variant enum (e.g. `ModifierTargetShape`,
41
+ * `ModifierDeltaTag`) surfaces as a tagged object `{ tag: "VariantName" }`,
42
+ * never a bare string — confirmed against the generated bindings
43
+ * (`packages/spellkave-bindings/src/module_bindings/types.ts`'s
44
+ * `__t.enum(...)` builders for both types) and the repo-wide convention
45
+ * `@spellkave/sdk`'s own internal `core/readers/_helpers.ts` `tagString`
46
+ * documents ("SpacetimeDB tagged-enum shape: `{ tag: "VariantName", value?:
47
+ * ... }`. Used by world_event.kind, evaluation_provenance.kind/status,
48
+ * etc."). Duplicated here (not imported — that helper is `@spellkave/sdk`
49
+ * package-internal, not part of its public surface) rather than widening a
50
+ * cross-package dependency for four lines of tag-unwrapping.
51
+ */
52
+ function liveEnumTag(value: unknown): string {
53
+ if (typeof value === "string") return value;
54
+ if (value !== null && typeof value === "object") {
55
+ const tag = (value as { tag?: unknown }).tag;
56
+ if (typeof tag === "string") return tag;
57
+ }
58
+ return String(value);
59
+ }
60
+
61
+ /** Optional u64 wire values remain exact beyond the JSON safe-integer range. */
62
+ function optionalTick(value: unknown): number | string | null {
63
+ if (value === undefined || value === null) return null;
64
+ if (typeof value === "bigint")
65
+ return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : String(value);
66
+ return typeof value === "number" ? value : String(value);
67
+ }
68
+
69
+ /**
70
+ * Unwrap a live `i64`/`u64` column back to a plain JS number. The manifest
71
+ * schema's own integer fields are never BigInt-typed, but the generated SDK
72
+ * surfaces every i64/u64 column as a genuine `bigint` — confirmed empirically
73
+ * against a real live connection (`resource_definition.minValue`/
74
+ * `action_definition.costTimeMs` etc. are `typeof value === "bigint"`, never
75
+ * `"number"`), NOT against `i32`/`u8`-shaped columns (`modifier_template.
76
+ * priority`, `economy_channel_definitions.pool_ms_per_round`), which the same
77
+ * probe showed already surface as plain `number`. Executable finding #44
78
+ * (`@spellkave/srd-cc`'s `ledger/findings.md`): `toolResult`'s
79
+ * `JSON.stringify` (`authoring-verbs.ts`) throws outright on a raw `bigint`
80
+ * ("Do not know how to serialize a BigInt") — this was never exercised
81
+ * before the DISCOVERY-CLOSURE test's live tier, because no prior test drove
82
+ * `spellkave_query`'s own JSON-serializing tool-result path against a REAL
83
+ * connected db (`fixtures-author-tool.test.ts` only exercises the `local`
84
+ * target, whose parsed-TOML rows are already plain numbers). Safe to
85
+ * `Number(...)`: every value these columns carry in practice (resource
86
+ * bounds, ms-scoped time costs, DC integers) sits far under
87
+ * `Number.MAX_SAFE_INTEGER`.
88
+ */
89
+ function liveInt(value: unknown): number | undefined {
90
+ if (value === undefined || value === null) return undefined;
91
+ if (typeof value === "bigint") {
92
+ // Fail CLOSED on precision loss instead of silently narrowing: every
93
+ // current consumer's domain sits far under 2^53 (doc note above), so a
94
+ // violation here means the domain assumption broke — surface it loudly.
95
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < -BigInt(Number.MAX_SAFE_INTEGER)) {
96
+ throw new Error(
97
+ `liveInt: bigint ${value} exceeds Number.MAX_SAFE_INTEGER — refusing silent precision loss.`,
98
+ );
99
+ }
100
+ return Number(value);
101
+ }
102
+ if (typeof value === "number") return value;
103
+ return Number(value);
104
+ }
105
+
106
+ /** Convert the generated SDK's tag-prefix mirror back to manifest field names. */
107
+ function liveTagPrefixes(value: unknown): ManifestRow[] | undefined {
108
+ if (!Array.isArray(value)) return undefined;
109
+ return value
110
+ .filter(
111
+ (entry): entry is Record<string, unknown> => entry !== null && typeof entry === "object",
112
+ )
113
+ .map((entry) => ({
114
+ prefix: entry.prefix,
115
+ target_kind: entry.targetKind ?? entry.target_kind,
116
+ natural_key_field: entry.naturalKeyField ?? entry.natural_key_field,
117
+ }));
118
+ }
119
+
120
+ /**
121
+ * Read a live table by its snake_case accessor — finding ledger entry
122
+ * #5: the real generated `DbConnection.db` keys every table accessor by its
123
+ * schema object-literal key verbatim, always snake_case; there is no
124
+ * camelCase table accessor on any current surface (live connection or
125
+ * `SnapshotDb` fixture/replay — audited repo-wide). Throws (never silently
126
+ * returns `[]`) when `table` resolves to nothing, naming the row kind and the
127
+ * accessor tried, so a typo'd or stale table name fails loudly instead of
128
+ * looking like an empty live world.
129
+ */
130
+ function liveTableRows(
131
+ db: AuthorSnapshotDb,
132
+ table: string,
133
+ rowKind: string,
134
+ ): Record<string, unknown>[] {
135
+ const bag = db as Record<string, TableHandleLike | undefined>;
136
+ // Prefer snake_case (generated schema name); some snapshot wrappers also expose camelCase.
137
+ const camel = table.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
138
+ const handle = bag[table] ?? bag[camel];
139
+ if (handle === undefined) {
140
+ throw new Error(
141
+ `liveTableRows: rowKind "${rowKind}" has no live accessor "${table}" (or "${camel}") on the connected db — ` +
142
+ "check the table name against the schema.",
143
+ );
144
+ }
145
+ return Array.from(handle.iter());
146
+ }
147
+
148
+ /**
149
+ * `rowKind` -> live-table accessor (the accessor is ALWAYS the live table's
150
+ * real snake_case name — see `liveTableRows`'s header; there is no camelCase
151
+ * variant to fall back to) + the shape mapper back to the manifest's own row
152
+ * fields. BOUNDED, not exhaustive over `ROW_KIND_NATURAL_KEY` — see this
153
+ * file's header note. Grow this table only when a real verb/lookup consumer
154
+ * needs another row kind resolved live.
155
+ */
156
+ export const LIVE_TABLE_ACCESSORS: Readonly<
157
+ Record<string, { table: string; toManifestRow: (live: Record<string, unknown>) => ManifestRow }>
158
+ > = {
159
+ area_shape_definitions: {
160
+ table: "area_shape_definition",
161
+ toManifestRow: (live) => ({
162
+ shape_id: live.shapeId ?? live.shape_id,
163
+ bundle_id: live.bundleId ?? live.bundle_id,
164
+ description: live.description,
165
+ }),
166
+ },
167
+ economy_channel_definitions: {
168
+ table: "economy_channel_definitions",
169
+ toManifestRow: (live) => ({
170
+ id: live.id,
171
+ bundle_id: live.bundleId ?? live.bundle_id,
172
+ pool_ms_per_round: live.poolMsPerRound ?? live.pool_ms_per_round,
173
+ resets_on: live.resetsOn ?? live.resets_on,
174
+ off_turn_eligible: live.offTurnEligible ?? live.off_turn_eligible ?? false,
175
+ }),
176
+ },
177
+ resource_definitions: {
178
+ table: "resource_definition",
179
+ toManifestRow: (live) => ({
180
+ resource_definition_id: live.resourceDefinitionId ?? live.resource_definition_id,
181
+ bundle_id: live.bundleId ?? live.bundle_id,
182
+ display_name: live.displayName ?? live.display_name,
183
+ value_kind: live.valueKind ?? live.value_kind,
184
+ // `recovery_rule` is REQUIRED (ResourceDefinitionRow, no serde default) —
185
+ // #1968 gap② surfaced this mapping was missing it: `spellkave_lookup`
186
+ // never rendered these rows through the schema (harmless there), but
187
+ // `commitOrReport`'s target-aware validation augmentation DOES render
188
+ // them, so an omitted `recovery_rule` broke the render outright.
189
+ recovery_rule: live.recoveryRule ?? live.recovery_rule,
190
+ min_value: liveInt(live.minValue ?? live.min_value),
191
+ max_value: liveInt(live.maxValue ?? live.max_value),
192
+ initial_value: liveInt(live.initialValue ?? live.initial_value),
193
+ description: live.description,
194
+ }),
195
+ },
196
+ object_state_definitions: {
197
+ table: "object_state_definition",
198
+ toManifestRow: (live) => ({
199
+ state_id: live.stateId ?? live.state_id,
200
+ bundle_id: live.bundleId ?? live.bundle_id,
201
+ target_kind: live.targetKind ?? live.target_kind,
202
+ display_name: live.displayName ?? live.display_name,
203
+ default_visibility: liveEnumTag(live.defaultVisibility ?? live.default_visibility),
204
+ description: live.description,
205
+ }),
206
+ },
207
+ // Exact tag values are description-only vocabulary rows. Their `tag`
208
+ // natural key is a complete dotted value, so the generic target/query path
209
+ // can resolve them without a vocabulary-specific fallback.
210
+ tag_value_definitions: {
211
+ table: "tag_value_definition",
212
+ toManifestRow: (live) => ({
213
+ tag: live.tag,
214
+ prefix: live.prefix,
215
+ bundle_id: live.bundleId ?? live.bundle_id,
216
+ description: live.description,
217
+ }),
218
+ },
219
+ containment_policy_definition: {
220
+ table: "containment_policy_definition",
221
+ toManifestRow: (live) => ({
222
+ policy_id: live.policyId ?? live.policy_id,
223
+ bundle_id: live.bundleId ?? live.bundle_id,
224
+ exposure_predicate_source: live.exposurePredicateSource ?? live.exposure_predicate_source,
225
+ access_predicate_source: live.accessPredicateSource ?? live.access_predicate_source,
226
+ }),
227
+ },
228
+ entity_definitions: {
229
+ table: "entity_definition",
230
+ toManifestRow: (live) => ({
231
+ entity_def_id: live.entityDefId ?? live.entity_def_id,
232
+ bundle_id: live.bundleId ?? live.bundle_id,
233
+ display_name: live.displayName ?? live.display_name,
234
+ description: live.description,
235
+ slot_compatibility_predicate:
236
+ live.slotCompatibilityPredicate ?? live.slot_compatibility_predicate,
237
+ stackable: live.stackable,
238
+ }),
239
+ },
240
+ place_nodes: {
241
+ table: "visible_place_node",
242
+ // Full spatial projection so map_graph / preferred list can draw live nodes
243
+ // (pos_*, substrate, display_name) — thin id-only rows left the map empty.
244
+ toManifestRow: (live) => ({
245
+ node_id: live.nodeId ?? live.node_id,
246
+ bundle_id: live.bundleId ?? live.bundle_id,
247
+ place_graph_id: live.placeGraphId ?? live.place_graph_id,
248
+ local_id: live.localId ?? live.local_id,
249
+ substrate_id: live.substrateId ?? live.substrate_id,
250
+ display_name: live.displayName ?? live.display_name,
251
+ description: live.description,
252
+ pos_x: live.posX ?? live.pos_x,
253
+ pos_y: live.posY ?? live.pos_y,
254
+ pos_present: live.posPresent ?? live.pos_present,
255
+ pose_elevation: live.poseElevation ?? live.pose_elevation,
256
+ pose_elevation_present: live.poseElevationPresent ?? live.pose_elevation_present,
257
+ extent_shape_id: live.extentShapeId ?? live.extent_shape_id,
258
+ extent_params_json: live.extentParamsJson ?? live.extent_params_json,
259
+ }),
260
+ },
261
+ // Edges for map_graph routes when reading live.
262
+ place_edges: {
263
+ table: "visible_place_edge",
264
+ toManifestRow: (live) => ({
265
+ edge_key: live.edgeKey ?? live.edge_key,
266
+ bundle_id: live.bundleId ?? live.bundle_id,
267
+ place_graph_id: live.placeGraphId ?? live.place_graph_id,
268
+ from_node_id: live.fromNodeId ?? live.from_node_id,
269
+ to_node_id: live.toNodeId ?? live.to_node_id,
270
+ description: live.description,
271
+ }),
272
+ },
273
+ place_graphs: {
274
+ table: "visible_place_graph_definition",
275
+ toManifestRow: (live) => ({
276
+ place_graph_id: live.placeGraphId ?? live.place_graph_id,
277
+ bundle_id: live.bundleId ?? live.bundle_id,
278
+ substrate_id: live.substrateId ?? live.substrate_id,
279
+ display_name: live.displayName ?? live.display_name,
280
+ description: live.description,
281
+ // `live.metresPerUnit` is the generated binding field (sk-yze);
282
+ // `live.metres_per_unit` covers a raw manifest-shaped row, which this
283
+ // same function is also fed. Both spellings are live, neither is stale.
284
+ metres_per_unit: live.metresPerUnit ?? live.metres_per_unit,
285
+ bearing: live.bearing,
286
+ anchor_node_id: live.anchorNodeId ?? live.anchor_node_id,
287
+ parent_graph_id: live.parentGraphId ?? live.parent_graph_id,
288
+ blueprint_id: live.blueprintId ?? live.blueprint_id,
289
+ is_ephemeral_instance: live.isEphemeralInstance ?? live.is_ephemeral_instance,
290
+ }),
291
+ },
292
+ substrate_definitions: {
293
+ table: "substrate_definition",
294
+ toManifestRow: (live) => ({
295
+ substrate_id: live.substrateId ?? live.substrate_id,
296
+ bundle_id: live.bundleId ?? live.bundle_id,
297
+ coordinate_kind_id: live.coordinateKindId ?? live.coordinate_kind_id,
298
+ description: live.description,
299
+ }),
300
+ },
301
+ coordinate_kind_definitions: {
302
+ table: "coordinate_kind_definition",
303
+ toManifestRow: (live) => ({
304
+ coordinate_kind_id: live.coordinateKindId ?? live.coordinate_kind_id,
305
+ bundle_id: live.bundleId ?? live.bundle_id,
306
+ description: live.description,
307
+ }),
308
+ },
309
+ session_definitions: {
310
+ table: "session_definition",
311
+ toManifestRow: (live) => ({
312
+ session_def_id: live.sessionDefId ?? live.session_def_id,
313
+ bundle_id: live.bundleId ?? live.bundle_id,
314
+ participants_pred: live.participantsPred ?? live.participants_pred,
315
+ initial_state: live.initialState ?? live.initial_state,
316
+ legal_moves_csv: live.legalMovesCsv ?? live.legal_moves_csv,
317
+ turn_rule: live.turnRule ?? live.turn_rule,
318
+ visibility_policy: live.visibilityPolicy ?? live.visibility_policy,
319
+ termination_pred: live.terminationPred ?? live.termination_pred,
320
+ on_terminate: live.onTerminate ?? live.on_terminate,
321
+ stakes_required: live.stakesRequired ?? live.stakes_required,
322
+ winner_predicate: live.winnerPredicate ?? live.winner_predicate,
323
+ turn_scheduler_id: live.turnSchedulerId ?? live.turn_scheduler_id,
324
+ round_duration_ms: liveInt(live.roundDurationMs ?? live.round_duration_ms),
325
+ auto_join_on_targeting: live.autoJoinOnTargeting ?? live.auto_join_on_targeting,
326
+ combat_grid_blueprint_id: live.combatGridBlueprintId ?? live.combat_grid_blueprint_id,
327
+ grid_edge_affordance_template_id:
328
+ live.gridEdgeAffordanceTemplateId ?? live.grid_edge_affordance_template_id,
329
+ grid_edge_affordance_bindings_json:
330
+ live.gridEdgeAffordanceBindingsJson ?? live.grid_edge_affordance_bindings_json,
331
+ }),
332
+ },
333
+ turn_scheduler: {
334
+ table: "turn_scheduler",
335
+ toManifestRow: (live) => ({
336
+ id: live.id,
337
+ bundle_id: live.bundleId ?? live.bundle_id,
338
+ // `scheduler_kind` is a no-payload `SchedulerKind` enum — same
339
+ // `{tag: ...}` client shape as the other enum columns above.
340
+ scheduler_kind: liveEnumTag(live.schedulerKind ?? live.scheduler_kind),
341
+ order_roll_source: live.orderRollSource ?? live.order_roll_source,
342
+ active: live.active,
343
+ }),
344
+ },
345
+ // srd-cc executable finding #69: `session_definitions.combat_grid_
346
+ // blueprint_id` is a genuinely authored outbound ref, but this map had no
347
+ // entry for its target kind, so the live-detail path started blind —
348
+ // identical failure class to the five accessors added for findings
349
+ // #42-44 above. Column shape mirrors the generated binding
350
+ // (`packages/spellkave-bindings/src/module_bindings/
351
+ // combat_grid_blueprint_table.ts`) 1:1; `cell_size` is an f32 and passes
352
+ // through as a plain number (NOT liveInt — 1.524m cells are legal).
353
+ combat_grid_blueprints: {
354
+ table: "combat_grid_blueprint",
355
+ toManifestRow: (live) => ({
356
+ blueprint_id: live.blueprintId ?? live.blueprint_id,
357
+ bundle_id: live.bundleId ?? live.bundle_id,
358
+ width: liveInt(live.width),
359
+ height: liveInt(live.height),
360
+ topology: live.topology,
361
+ cell_size: live.cellSize ?? live.cell_size,
362
+ edge_affordance_template_id:
363
+ live.edgeAffordanceTemplateId ?? live.edge_affordance_template_id,
364
+ edge_affordance_bindings_json:
365
+ live.edgeAffordanceBindingsJson ?? live.edge_affordance_bindings_json,
366
+ edge_overrides_json: live.edgeOverridesJson ?? live.edge_overrides_json,
367
+ }),
368
+ },
369
+ role_definitions: {
370
+ table: "role_definition",
371
+ toManifestRow: (live) => ({
372
+ role_id: live.roleId ?? live.role_id,
373
+ bundle_id: live.bundleId ?? live.bundle_id,
374
+ display_name: live.displayName ?? live.display_name,
375
+ description: live.description,
376
+ capability_ids: live.capabilityIds ?? live.capability_ids,
377
+ }),
378
+ },
379
+ place_seals: {
380
+ table: "visible_place_seal",
381
+ toManifestRow: (live) => ({
382
+ place_graph_id: live.placeGraphId ?? live.place_graph_id,
383
+ bundle_id: live.bundleId ?? live.bundle_id,
384
+ description: live.description,
385
+ }),
386
+ },
387
+ role_bindings: {
388
+ table: "visible_role_binding",
389
+ toManifestRow: (live) => ({
390
+ binding_id: live.bindingId ?? live.binding_id,
391
+ bundle_id: live.bundleId ?? live.bundle_id,
392
+ subject: live.subject,
393
+ role_id: live.roleId ?? live.role_id,
394
+ extent_kind_ref: live.extentKindRef ?? live.extent_kind_ref,
395
+ extent_ref: live.extentRef ?? live.extent_ref,
396
+ expires_at_tick: optionalTick(live.expiresAtTick ?? live.expires_at_tick),
397
+ description: live.description,
398
+ presence_entity_id: String(live.presenceEntityId ?? live.presence_entity_id ?? 0),
399
+ realised_at_tick: optionalTick(live.realisedAtTick ?? live.realised_at_tick),
400
+ }),
401
+ },
402
+ role_aggregations: {
403
+ table: "role_aggregation",
404
+ toManifestRow: (live) => ({
405
+ role_id: live.roleId ?? live.role_id,
406
+ bundle_id: live.bundleId ?? live.bundle_id,
407
+ description: live.description,
408
+ capability_ids: live.capabilityIds ?? live.capability_ids,
409
+ }),
410
+ },
411
+ extent_kind_definitions: {
412
+ table: "extent_kind_definition",
413
+ toManifestRow: (live) => ({
414
+ kind_id: live.kindId ?? live.kind_id,
415
+ bundle_id: live.bundleId ?? live.bundle_id,
416
+ description: live.description,
417
+ resolution_shape: liveEnumTag(live.resolutionShape ?? live.resolution_shape),
418
+ }),
419
+ },
420
+ capability_definitions: {
421
+ table: "capability_definition",
422
+ toManifestRow: (live) => ({
423
+ capability_id: live.capabilityId ?? live.capability_id,
424
+ bundle_id: live.bundleId ?? live.bundle_id,
425
+ actor_kind: live.actorKind ?? live.actor_kind,
426
+ display_name: live.displayName ?? live.display_name,
427
+ description: live.description,
428
+ // VisibilityClass is a no-payload enum `{ tag: "Public" | ... }` on the wire.
429
+ default_visibility: liveEnumTag(live.defaultVisibility ?? live.default_visibility),
430
+ }),
431
+ },
432
+ metadata_namespaces: {
433
+ table: "metadata_namespace_definition",
434
+ toManifestRow: (live) => ({
435
+ namespace: live.namespace,
436
+ audience: live.audience,
437
+ bundle_id: live.bundleId ?? live.bundle_id,
438
+ description: live.description,
439
+ on_demand: live.onDemand ?? live.on_demand,
440
+ }),
441
+ },
442
+ // `metadata_attachments` deliberately has NO entry here (ADR-0130 D-1):
443
+ // `metadata_attachment` is now a private table read through three views
444
+ // (`public_metadata_attachment`, `visible_metadata_attachment`,
445
+ // `public_reference_metadata`) that share this row shape but have no
446
+ // single table name a LIVE_TABLE_ACCESSORS entry can point at —
447
+ // `lookupLiveMetadataAttachments` below unions all three and is
448
+ // special-cased in `lookup()`, the same pattern `actor_spatial_locations`
449
+ // already uses (no accessor entry, no LIVE_ID_FIELD entry: attachment
450
+ // rows have no single-column natural id (their key is composite), so
451
+ // resolveRef stays unsupported for this kind).
452
+ affordance_templates: {
453
+ table: "affordance_template",
454
+ toManifestRow: (live) => ({
455
+ template_id: live.templateId ?? live.template_id,
456
+ bundle_id: live.bundleId ?? live.bundle_id,
457
+ niche_id: live.nicheId ?? live.niche_id,
458
+ capability_id: live.capabilityId ?? live.capability_id,
459
+ display_name: live.displayName ?? live.display_name,
460
+ predicate_source: live.predicateSource ?? live.predicate_source,
461
+ outcome_template_id: live.outcomeTemplateId ?? live.outcome_template_id,
462
+ range_m: live.rangeM ?? live.range_m,
463
+ // `locality_class` is a no-payload `LocalityClass` enum — same
464
+ // `{tag: ...}` client-side shape as `modifier_target_definitions.shape`
465
+ // (executable finding #44).
466
+ locality_class: liveEnumTag(live.localityClass ?? live.locality_class),
467
+ reads_occupancy: live.readsOccupancy ?? live.reads_occupancy,
468
+ spends_channel: live.spendsChannel ?? live.spends_channel,
469
+ recharges_on: live.rechargesOn ?? live.recharges_on,
470
+ composes: live.composes,
471
+ description: live.description,
472
+ }),
473
+ },
474
+ action_definitions: {
475
+ table: "action_definition",
476
+ toManifestRow: (live) => ({
477
+ // NOTE: no `description` mapping — the live `action_definition` table
478
+ // has no `description` column (unlike the manifest schema's row,
479
+ // which defaults it to `""` when absent); this is an honest gap in
480
+ // the live SDK bindings, not an oversight here.
481
+ action_id: live.actionId ?? live.action_id,
482
+ bundle_id: live.bundleId ?? live.bundle_id,
483
+ required_capability: live.requiredCapability ?? live.required_capability,
484
+ on_success: live.onSuccess ?? live.on_success,
485
+ on_failure: live.onFailure ?? live.on_failure,
486
+ // `resolution_mode` is a no-payload `ActionResolutionMode` enum — same
487
+ // `{tag: ...}` client-side shape as `modifier_target_definitions.shape`
488
+ // (executable finding #44).
489
+ resolution_mode: liveEnumTag(live.resolutionMode ?? live.resolution_mode),
490
+ resolution_predicate_source:
491
+ live.resolutionPredicateSource ?? live.resolution_predicate_source ?? "",
492
+ resolution_scope: live.resolutionScope ?? live.resolution_scope ?? "",
493
+ non_steering: Boolean(live.nonSteering ?? live.non_steering),
494
+ display_name: live.displayName ?? live.display_name,
495
+ cost_time_ms: liveInt(live.costTimeMs ?? live.cost_time_ms),
496
+ session_def_id: live.sessionDefId ?? live.session_def_id,
497
+ reaction_eligibility: live.reactionEligibility ?? live.reaction_eligibility,
498
+ reaction_window_ms: liveInt(live.reactionWindowMs ?? live.reaction_window_ms),
499
+ reaction_trigger: live.reactionTrigger ?? live.reaction_trigger,
500
+ self_eligible: live.selfEligible ?? live.self_eligible,
501
+ self_only: live.selfOnly ?? live.self_only,
502
+ spends_channel: live.spendsChannel ?? live.spends_channel,
503
+ }),
504
+ },
505
+ outcome_templates: {
506
+ table: "outcome_template",
507
+ toManifestRow: (live) => ({
508
+ outcome_template_id: live.outcomeTemplateId ?? live.outcome_template_id,
509
+ bundle_id: live.bundleId ?? live.bundle_id,
510
+ display_name: live.displayName ?? live.display_name,
511
+ outcome_expression_source: live.outcomeExpressionSource ?? live.outcome_expression_source,
512
+ manipulation_action_id: live.manipulationActionId ?? live.manipulation_action_id,
513
+ communication_speech_act_id:
514
+ live.communicationSpeechActId ?? live.communication_speech_act_id,
515
+ movement_descriptor: live.movementDescriptor ?? live.movement_descriptor,
516
+ sense_query_kind: live.senseQueryKind ?? live.sense_query_kind,
517
+ sense_visibility: live.senseVisibility ?? live.sense_visibility,
518
+ consequence_template_id: live.consequenceTemplateId ?? live.consequence_template_id,
519
+ discovery_validated: live.discoveryValidated ?? live.discovery_validated,
520
+ description: live.description,
521
+ }),
522
+ },
523
+ bundles: {
524
+ table: "mod_bundle",
525
+ toManifestRow: (live) => ({
526
+ bundle_id: live.bundleId ?? live.bundle_id,
527
+ display_name: live.displayName ?? live.display_name,
528
+ author: live.author,
529
+ version: live.version,
530
+ tag_prefixes: liveTagPrefixes(live.tagPrefixes ?? live.tag_prefixes),
531
+ allow_flat_tags: live.allowFlatTags ?? live.allow_flat_tags,
532
+ // Server-side `depends_on` is a comma-joined STRING column
533
+ // (`bundle.rs`'s own `deps` module splits it), unlike the manifest
534
+ // schema's `array<string>` — left as the live shape rather than
535
+ // invented-split here (no current consumer parses this field
536
+ // through a live target; `resolveQueryDetail`'s ref heuristic never
537
+ // treats `depends_on` as a ref field either way, since it doesn't
538
+ // carry an `_id`/`_key`/`_ref` suffix).
539
+ depends_on: live.dependsOn ?? live.depends_on,
540
+ description: live.description,
541
+ default_extent_shape_id: live.defaultExtentShapeId ?? live.default_extent_shape_id,
542
+ default_extent_params_json: live.defaultExtentParamsJson ?? live.default_extent_params_json,
543
+ }),
544
+ },
545
+ condition_definitions: {
546
+ table: "condition_definition",
547
+ toManifestRow: (live) => ({
548
+ // Prose is NOT on the catalog row (binary-compat satellite
549
+ // `condition_definition_description`). Overlay in lookup().
550
+ description: "",
551
+ condition_definition_id: live.conditionDefinitionId ?? live.condition_definition_id,
552
+ bundle_id: live.bundleId ?? live.bundle_id,
553
+ display_name: live.displayName ?? live.display_name,
554
+ stacking_rule: live.stackingRule ?? live.stacking_rule,
555
+ remove_time_policy: live.removeTimePolicy ?? live.remove_time_policy,
556
+ gate_predicate_source: live.gatePredicateSource ?? live.gate_predicate_source,
557
+ modifier_template_id: live.modifierTemplateId ?? live.modifier_template_id,
558
+ observable: live.observable,
559
+ grants_capability_while_active:
560
+ live.grantsCapabilityWhileActive ?? live.grants_capability_while_active,
561
+ suppresses_capability_while_active:
562
+ live.suppressesCapabilityWhileActive ?? live.suppresses_capability_while_active,
563
+ implies: live.implies,
564
+ }),
565
+ },
566
+ consequence_templates: {
567
+ table: "consequence_template",
568
+ toManifestRow: (live) => ({
569
+ // NOTE: no `description` mapping — `consequence_template` has no
570
+ // catalog column and no prose satellite (unlike condition_definitions).
571
+ template_id: live.templateId ?? live.template_id,
572
+ bundle_id: live.bundleId ?? live.bundle_id,
573
+ effect_refs_csv: live.effectRefsCsv ?? live.effect_refs_csv,
574
+ traces_json: live.tracesJson ?? live.traces_json,
575
+ }),
576
+ },
577
+ modifier_target_definitions: {
578
+ table: "modifier_target_definition",
579
+ toManifestRow: (live) => ({
580
+ target_id: live.targetId ?? live.target_id,
581
+ // `shape` is a no-payload `ModifierTargetShape` enum — unwrap its
582
+ // `{tag: "Numeric"|"Mode"|"Reference"}` client shape to the plain
583
+ // string the manifest schema's own `shape` field carries.
584
+ shape: liveEnumTag(live.shape),
585
+ display_name: live.displayName ?? live.display_name,
586
+ bundle_id: live.bundleId ?? live.bundle_id,
587
+ }),
588
+ },
589
+ // sk-9ll.3: bundle-scoped catalog vocabulary, same shape/rationale as
590
+ // `modifier_target_definitions` above — backs the NEW `spellkave_equip_item`
591
+ // verb's `slot_id` existence pre-check (dual-source lookup) and the shared
592
+ // `MF_VAL_ACTOR_EQUIP_SLOT_DEF_REF` validator rule's target-augmentation
593
+ // (`VALIDATION_AUGMENT_KINDS`, `authoring-verbs.ts`).
594
+ equipment_slot_definitions: {
595
+ table: "equipment_slot_definition",
596
+ toManifestRow: (live) => ({
597
+ slot_id: live.slotId ?? live.slot_id,
598
+ bundle_id: live.bundleId ?? live.bundle_id,
599
+ label: live.label,
600
+ default_compatibility_predicate:
601
+ live.defaultCompatibilityPredicate ?? live.default_compatibility_predicate,
602
+ }),
603
+ },
604
+ modifier_templates: {
605
+ table: "modifier_template",
606
+ toManifestRow: (live) => ({
607
+ modifier_template_id: live.modifierTemplateId ?? live.modifier_template_id,
608
+ bundle_id: live.bundleId ?? live.bundle_id,
609
+ applies_to: live.appliesTo ?? live.applies_to,
610
+ display_name: live.displayName ?? live.display_name,
611
+ predicate_source: live.predicateSource ?? live.predicate_source,
612
+ modifier_expression_source: live.modifierExpressionSource ?? live.modifier_expression_source,
613
+ priority: live.priority,
614
+ // `delta_kind` is a no-payload `ModifierDeltaTag` enum — same
615
+ // `{tag: ...}` unwrap as `modifier_target_definitions.shape` above.
616
+ delta_kind: liveEnumTag(live.deltaKind ?? live.delta_kind),
617
+ replace_template_id: live.replaceTemplateId ?? live.replace_template_id,
618
+ }),
619
+ },
620
+ dsl_macro_definitions: {
621
+ table: "dsl_macro_definition",
622
+ toManifestRow: (live) => ({
623
+ macro_id: live.macroId ?? live.macro_id,
624
+ bundle_id: live.bundleId ?? live.bundle_id,
625
+ return_type: liveEnumTag(live.returnType ?? live.return_type),
626
+ parameters: JSON.parse(String(live.parametersJson ?? live.parameters_json ?? "[]")),
627
+ body_source: live.bodySource ?? live.body_source,
628
+ description: live.description,
629
+ }),
630
+ },
631
+ capability_definition_tag: {
632
+ table: "capability_definition_tag",
633
+ toManifestRow: (live) => ({
634
+ capability_id: live.capabilityId ?? live.capability_id,
635
+ tag: live.tag,
636
+ bundle_id: live.bundleId ?? live.bundle_id,
637
+ source: live.source,
638
+ }),
639
+ },
640
+ resource_definition_tag: {
641
+ table: "resource_definition_tag",
642
+ toManifestRow: (live) => ({
643
+ resource_definition_id: live.resourceDefinitionId ?? live.resource_definition_id,
644
+ tag: live.tag,
645
+ bundle_id: live.bundleId ?? live.bundle_id,
646
+ source: live.source,
647
+ }),
648
+ },
649
+ entity_definition_tag: {
650
+ table: "entity_definition_tag",
651
+ toManifestRow: (live) => ({
652
+ entity_def_id: live.entityDefId ?? live.entity_def_id,
653
+ tag: live.tag,
654
+ bundle_id: live.bundleId ?? live.bundle_id,
655
+ source: live.source,
656
+ }),
657
+ },
658
+ modifier_template_tag: {
659
+ table: "modifier_template_tag",
660
+ toManifestRow: (live) => ({
661
+ modifier_template_id: live.modifierTemplateId ?? live.modifier_template_id,
662
+ tag: live.tag,
663
+ bundle_id: live.bundleId ?? live.bundle_id,
664
+ source: live.source,
665
+ }),
666
+ },
667
+ };
668
+
669
+ /**
670
+ * The `rowKind`'s own natural-key field, verified against the live row
671
+ * shapes above (never inferred). Deliberately has NO entries for the four
672
+ * `ROW_KIND_COMPOSITE_KEY` kinds added above (finding #42) — a composite-key
673
+ * kind's identity is the ORDERED PAIR `[parent_field, "tag"]`, not a single
674
+ * field, so it has nothing to put here; `resolveRef` (this file's only
675
+ * `LIVE_ID_FIELD` consumer) is never called with a composite-keyed `rowKind`
676
+ * anywhere in `authoring-verbs.ts` (grep-verified — every call site names a
677
+ * natural-key kind), and `lookup()` (the composite kinds' only live
678
+ * consumer, via `spellkave_query`'s list/detail/summary paths) never reads
679
+ * `LIVE_ID_FIELD` at all.
680
+ */
681
+ const LIVE_ID_FIELD: Readonly<Record<string, string>> = {
682
+ area_shape_definitions: "shape_id",
683
+ economy_channel_definitions: "id",
684
+ resource_definitions: "resource_definition_id",
685
+ object_state_definitions: "state_id",
686
+ tag_value_definitions: "tag",
687
+ entity_definitions: "entity_def_id",
688
+ containment_policy_definition: "policy_id",
689
+ place_nodes: "node_id",
690
+ place_graphs: "place_graph_id",
691
+ place_edges: "edge_key",
692
+ substrate_definitions: "substrate_id",
693
+ coordinate_kind_definitions: "coordinate_kind_id",
694
+ session_definitions: "session_def_id",
695
+ turn_scheduler: "id",
696
+ combat_grid_blueprints: "blueprint_id",
697
+ capability_definitions: "capability_id",
698
+ role_definitions: "role_id",
699
+ role_bindings: "binding_id",
700
+ place_seals: "place_graph_id",
701
+ extent_kind_definitions: "kind_id",
702
+ affordance_templates: "template_id",
703
+ action_definitions: "action_id",
704
+ outcome_templates: "outcome_template_id",
705
+ bundles: "bundle_id",
706
+ condition_definitions: "condition_definition_id",
707
+ consequence_templates: "template_id",
708
+ modifier_target_definitions: "target_id",
709
+ modifier_templates: "modifier_template_id",
710
+ dsl_macro_definitions: "macro_id",
711
+ equipment_slot_definitions: "slot_id",
712
+ };
713
+
714
+ export interface LiveAuthorTargetDeps {
715
+ readsAsPublisher?: () => boolean;
716
+ scopedSnapshot?: ScopedSnapshotPort;
717
+ /** A value or a thunk (mirrors `SpellkaveToolContext.db`/`AuthorToolContext.db`). */
718
+ db: AuthorSnapshotDb | (() => AuthorSnapshotDb | undefined) | undefined;
719
+ /** `r_apply_manifest_delta` port (ADR-0085) — absent = `applyBatch` rejects (no live driver wired). */
720
+ applyDelta?: (toml: string) => Promise<{ ok: boolean; detail?: string }>;
721
+ /**
722
+ * Memoise `lookup` results for the life of this target. Every uncached `lookup`
723
+ * copies and re-maps a whole table, so a full read-only walk (one query per row)
724
+ * is quadratic in world size. Only for a target created for one read-only walk
725
+ * over a quiescent world: the cache is never invalidated, so a live target that
726
+ * outlives writes must leave this off (the default).
727
+ */
728
+ cacheRows?: boolean;
729
+ }
730
+
731
+ function resolveDb(db: LiveAuthorTargetDeps["db"]): AuthorSnapshotDb | undefined {
732
+ if (db === undefined) return undefined;
733
+ try {
734
+ return typeof db === "function" ? db() : db;
735
+ } catch {
736
+ // Mirrors `spellkave_lookup`'s own `currentDb` seam: a host's `db` thunk
737
+ // may throw "not connected" rather than being absent.
738
+ return undefined;
739
+ }
740
+ }
741
+
742
+ function liveTableRowsOptional(db: AuthorSnapshotDb, table: string): Record<string, unknown>[] {
743
+ const bag = db as Record<string, TableHandleLike | undefined>;
744
+ const camel = table.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
745
+ const handle = bag[table] ?? bag[camel];
746
+ if (handle === undefined) return [];
747
+ return Array.from(handle.iter());
748
+ }
749
+
750
+ function authoredEntityKey(manifestKey: unknown): string {
751
+ const key = String(manifestKey ?? "");
752
+ const colon = key.indexOf(":");
753
+ return colon >= 0 ? key.slice(colon + 1) : key;
754
+ }
755
+
756
+ /**
757
+ * Live `actor_spatial_location` is id-keyed (`entity_id`) and the public view
758
+ * is visibility-filtered — an operator snapshot often has no `entity_key` and
759
+ * no row for anyone except the bound sender. Authoring verbs still name actors
760
+ * by `entity_key`. Join the operator or coverage-checked admitted authored mapping + `entity` so lookup can
761
+ * answer "is this player/npc already live?" without inventing an `entities`
762
+ * LIVE_TABLE_ACCESSORS entry (that kind stays local-only; see authoring-verbs
763
+ * ENTITY_INSTANCE_AUGMENT_KINDS_LOCAL_ONLY).
764
+ */
765
+ function lookupLiveActorSpatialLocations(
766
+ db: AuthorSnapshotDb,
767
+ filter: { bundle?: string } | undefined,
768
+ publisher: boolean,
769
+ ): ManifestRow[] {
770
+ if (!publisher) {
771
+ const coverage = liveTableRows(
772
+ db,
773
+ "visible_manifest_authored_entity_coverage",
774
+ "actor_spatial_locations",
775
+ );
776
+ if (
777
+ coverage.length !== 1 ||
778
+ coverage[0]?.status !== "complete" ||
779
+ coverage[0]?.projectionVersion !== 1
780
+ )
781
+ throw new Error("reader_unavailable: authored mapping coverage missing or incomplete");
782
+ }
783
+ const authored = liveTableRows(
784
+ db,
785
+ publisher ? "operator_manifest_authored_entity" : "visible_manifest_authored_entity",
786
+ "actor_spatial_locations",
787
+ );
788
+ const entities = liveTableRows(db, "entity", "actor_spatial_locations");
789
+ const visible = liveTableRowsOptional(db, "visible_actor_spatial_location");
790
+ const entityById = new Map<string, Record<string, unknown>>();
791
+ for (const row of entities) {
792
+ entityById.set(String(row.entityId ?? row.entity_id), row);
793
+ }
794
+ const visibleById = new Map<string, Record<string, unknown>>();
795
+ for (const row of visible) {
796
+ visibleById.set(String(row.entityId ?? row.entity_id), row);
797
+ }
798
+ const out: ManifestRow[] = [];
799
+ for (const row of authored) {
800
+ const entityId = String(row.entityId ?? row.entity_id);
801
+ const entity = entityById.get(entityId);
802
+ if (entity === undefined) continue;
803
+ const kind = String(entity.kind ?? "");
804
+ if (kind !== "player" && kind !== "npc") continue;
805
+ const bundleId = String(row.bundleId ?? row.bundle_id ?? "");
806
+ if (filter?.bundle !== undefined && bundleId !== filter.bundle) continue;
807
+ const asl = visibleById.get(entityId);
808
+ out.push({
809
+ entity_key: authoredEntityKey(row.manifestKey ?? row.manifest_key),
810
+ bundle_id: bundleId,
811
+ place_node_id: String(asl?.placeNodeId ?? asl?.place_node_id ?? ""),
812
+ entity_def_id: String(entity.entityDefId ?? entity.entity_def_id ?? ""),
813
+ name: String(entity.name ?? ""),
814
+ kind,
815
+ });
816
+ }
817
+ return out;
818
+ }
819
+
820
+ /**
821
+ * ADR-0130 D-6: a live target's `lookup("metadata_attachments", ...)` unions
822
+ * `public_metadata_attachment`, `visible_metadata_attachment`, and
823
+ * `public_reference_metadata` — authors need reference rows
824
+ * (`srd.advancement_grant`/`srd.advancement_choice`/`srd.spell_slot_grant`/
825
+ * `srd.spellcasting_profile`/`srd.equipment_*`/`srd.background_origin_feat`,
826
+ * ADR-0130 Context) alongside the play-session metadata the two other views
827
+ * carry, and this is the ONE seam every DM-runtime reader in
828
+ * `@spellkave/adventure-runtime`'s `src/dm/**` goes through (never the SDK
829
+ * directly, see `dm/data/advancement.ts`'s own header). Deduped by `key`
830
+ * — the three views are disjoint by construction (D-5), so this is
831
+ * defensive, matching `@spellkave/sdk`'s sibling
832
+ * `readMetadataAttachmentRows` (`core/readers/metadata_rows.ts`).
833
+ */
834
+ function lookupLiveMetadataAttachments(
835
+ db: AuthorSnapshotDb,
836
+ filter: { bundle?: string } | undefined,
837
+ ): ManifestRow[] {
838
+ const seen = new Set<string>();
839
+ const out: ManifestRow[] = [];
840
+ for (const table of [
841
+ "public_metadata_attachment",
842
+ "visible_metadata_attachment",
843
+ "public_reference_metadata",
844
+ ]) {
845
+ for (const row of liveTableRowsOptional(db, table)) {
846
+ const rowKey = String(row.key ?? "");
847
+ if (rowKey !== "") {
848
+ if (seen.has(rowKey)) continue;
849
+ seen.add(rowKey);
850
+ }
851
+ const bundleId = String(row.bundleId ?? row.bundle_id ?? "");
852
+ if (filter?.bundle !== undefined && bundleId !== filter.bundle) continue;
853
+ out.push({
854
+ target_kind: row.targetKind ?? row.target_kind,
855
+ target_ref: row.targetRef ?? row.target_ref,
856
+ namespace: row.namespace,
857
+ payload_json: row.payloadJson ?? row.payload_json,
858
+ audience: row.audience,
859
+ bundle_id: bundleId,
860
+ source: row.source,
861
+ });
862
+ }
863
+ }
864
+ return out;
865
+ }
866
+
867
+ /**
868
+ * `live`: reads via the DB snapshot thunk (generalizing what `spellkave_lookup`
869
+ * already did per-kind, #1968), commits via the `applyDelta` port
870
+ * (`r_apply_manifest_delta`, ADR-0085, unchanged).
871
+ */
872
+ function overlayConditionDefinitionDescriptions(db: AuthorSnapshotDb, rows: ManifestRow[]): void {
873
+ const prose = new Map<string, string>();
874
+ for (const sat of liveTableRowsOptional(db, "condition_definition_description")) {
875
+ const id = String(sat.conditionDefinitionId ?? sat.condition_definition_id ?? "");
876
+ const text = String(sat.description ?? "");
877
+ if (id !== "" && text.trim() !== "") prose.set(id, text);
878
+ }
879
+ for (const row of rows) {
880
+ row.description = prose.get(String(row.condition_definition_id ?? "")) ?? "";
881
+ }
882
+ }
883
+
884
+ /**
885
+ * ADR-0143 D-5: `turn_eligibility_pred` is NOT on the `session_definition`
886
+ * row (binary-compat satellite `session_turn_eligibility`). Overlay it so a
887
+ * live edit that re-declares a session row keeps its predicate — omitting the
888
+ * field on a redeclare deletes the satellite. Set only when authored, so a
889
+ * reconstructed row never carries the field to a module that predates it.
890
+ */
891
+ function overlaySessionTurnEligibility(db: AuthorSnapshotDb, rows: ManifestRow[]): void {
892
+ const predicates = new Map<string, string>();
893
+ for (const sat of liveTableRowsOptional(db, "session_turn_eligibility")) {
894
+ const id = String(sat.sessionDefId ?? sat.session_def_id ?? "");
895
+ const source = String(sat.predicateSource ?? sat.predicate_source ?? "");
896
+ if (id !== "" && source.trim() !== "") predicates.set(id, source);
897
+ }
898
+ for (const row of rows) {
899
+ const source = predicates.get(String(row.session_def_id ?? ""));
900
+ if (source !== undefined) row.turn_eligibility_pred = source;
901
+ }
902
+ }
903
+
904
+ export function createLiveAuthorTarget(deps: LiveAuthorTargetDeps): AuthorTarget {
905
+ const rowCache = deps.cacheRows === true ? new Map<string, ManifestRow[]>() : undefined;
906
+ return {
907
+ kind: "live",
908
+ resolveRef(rowKind, id) {
909
+ const db = resolveDb(deps.db);
910
+ if (db !== undefined && rowKind === "actor_spatial_locations") {
911
+ return lookupLiveActorSpatialLocations(
912
+ db,
913
+ undefined,
914
+ deps.readsAsPublisher?.() === true,
915
+ ).some((row) => String(row.entity_key) === id);
916
+ }
917
+ const accessor = LIVE_TABLE_ACCESSORS[rowKind];
918
+ const idField = LIVE_ID_FIELD[rowKind];
919
+ if (db === undefined || accessor === undefined || idField === undefined) return false;
920
+ const rows =
921
+ rowKind === "containment_policy_definition"
922
+ ? deps.readsAsPublisher?.() === false
923
+ ? []
924
+ : liveTableRowsOptional(db, accessor.table)
925
+ : liveTableRows(db, accessor.table, rowKind);
926
+ return rows.some((row) => String(accessor.toManifestRow(row)[idField]) === id);
927
+ },
928
+ lookup(rowKind, filter) {
929
+ const db = resolveDb(deps.db);
930
+ if (db === undefined) return [];
931
+ // Check before the request-local row cache, including a changed seat.
932
+ if (rowKind === "containment_policy_definition" && deps.readsAsPublisher?.() === false)
933
+ return [];
934
+ if (rowKind === "actor_spatial_locations") {
935
+ return lookupLiveActorSpatialLocations(db, filter, deps.readsAsPublisher?.() === true);
936
+ }
937
+ if (rowKind === "metadata_attachments") {
938
+ return lookupLiveMetadataAttachments(db, filter);
939
+ }
940
+ const accessor = LIVE_TABLE_ACCESSORS[rowKind];
941
+ if (accessor === undefined) return [];
942
+ const cacheKey = `${rowKind}\u0000${filter?.bundle ?? ""}`;
943
+ const cached = rowCache?.get(cacheKey);
944
+ if (cached !== undefined) return cached;
945
+ const sourceRows =
946
+ rowKind === "containment_policy_definition"
947
+ ? liveTableRowsOptional(db, accessor.table)
948
+ : liveTableRows(db, accessor.table, rowKind);
949
+ const rows = sourceRows
950
+ .map(accessor.toManifestRow)
951
+ .filter((row) => filter?.bundle === undefined || row.bundle_id === filter.bundle);
952
+ if (rowKind === "place_seals") {
953
+ const breaks = liveTableRowsOptional(db, "visible_place_seal_break");
954
+ for (const row of rows) {
955
+ const broken = breaks.find(
956
+ (b) => (b.placeGraphId ?? b.place_graph_id) === row.place_graph_id,
957
+ );
958
+ if (broken !== undefined) {
959
+ row.broken = true;
960
+ row.break_reason = broken.breakReason ?? broken.break_reason;
961
+ }
962
+ }
963
+ }
964
+ if (rowKind === "condition_definitions") {
965
+ overlayConditionDefinitionDescriptions(db, rows);
966
+ }
967
+ if (rowKind === "session_definitions") {
968
+ overlaySessionTurnEligibility(db, rows);
969
+ }
970
+ rowCache?.set(cacheKey, rows);
971
+ return rows;
972
+ },
973
+ async applyBatch(toml) {
974
+ if (deps.applyDelta === undefined) {
975
+ return {
976
+ ok: false,
977
+ detail: "live target has no applyDelta port wired — not connected.",
978
+ };
979
+ }
980
+ if (deps.readsAsPublisher?.() === false) {
981
+ let captured: ScopedInstanceSnapshot | undefined;
982
+ try {
983
+ captured = await deps.scopedSnapshot?.read();
984
+ } catch {
985
+ /* unavailable is a refusal */
986
+ }
987
+ const refusal = scopedInlineDeltaPreflight(toml, captured);
988
+ if (refusal) return { ok: false, detail: refusal };
989
+ }
990
+ return deps.applyDelta(toml);
991
+ },
992
+ };
993
+ }
994
+
995
+ // ---------------------------------------------------------------------------