@myclaw163/game-agent-runtime 0.1.3 → 0.1.4

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.
package/README.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  GAR 不包含具体游戏规则、地图、账号或后端协议。龙虾杀客户端 CCL 是一个接入实现;其他游戏可以独立使用 GAR,无须安装 CCL。
6
6
 
7
+ `removeHistory(paths, scopes)` 是独立的离线运行历史清理入口:只删除已关闭 scope 的历史帧、输入与插件记录,保留事件、Mailbox、投递和会话元数据。`compact(paths, { includeEvents: false })` 只回收两份运行历史库。调用方负责确认业务终局与归档完成;删除遵循先引用、后正文的顺序,可幂等重试。
8
+
7
9
  ## 安装
8
10
 
9
11
  需要 Node.js **24.12.0 或更高版本**,建议使用 Node.js 24。
@@ -47,8 +49,20 @@ import { createGridGame } from '@myclaw163/game-agent-runtime/examples/grid-game
47
49
 
48
50
  ## 接入自己的游戏
49
51
 
52
+ 默认 memory-first 持久化把同一 epoch 的完整状态正文保存在输入日志中,历史帧保存作用域和序号引用。所有历史读取仍返回完整 State;独立历史帧及旧行继续内联保存。直接打开历史库时,应向 `SqliteStateHistoryRepository` 的第二个参数传入 `serializedState`,使用关联输入库的 `serializedState(epochSeq, scope)` 解析;缺少引用正文会明确报错。迁移或清理必须先处理历史引用,再处理输入正文。
53
+
54
+ 接入方可通过 `createMemoryFirstPersistence({ inputStorage: { sharedStatePaths, completedOutcomeEpochs } })` 选择共享的 JSON 对象字段路径,以及磁盘上保留多少个已完成轮次的插件结果。默认不拆分字段、完整保留结果;`'all'` 保留全部,数字窗口只收缩 closed epoch 的旧结果,不删除输入、State、Event、插件进度或检查点。`retainCompletedDiagnostics(scope)` 可将 scope 升级为完整留档,不能降级。旧策略未知的 scope 保守保留。共享内容、引用和输入行在同一事务内提交;读取自动恢复原始 JSON,清理只移除已无引用的正文。
55
+
56
+ 三个持久化路径可以指向同一文件;同线程的 Repository 共用连接,历史表使用独立的 `history_schema_migrations`。同库时写入 Worker 将整批事件、输入和历史操作放进同一事务,嵌套 Repository 操作用保存点。独立文件模式仍保持先正文后引用的顺序。首次持久化失败后停止后续批次写入并报告 degraded,不改变内存中的游戏计算流程。
57
+
58
+ 应用自己的表可通过 `extensions: { name: { moduleUrl, databasePath } }` 接入同一写入 Worker;模块导出 `createSqliteMirrorStore(path)`,返回同步存储方法和 `close()`。模块使用 `framework/persistence/sqlite-connection.js` 的连接租约及事务函数共享连接,不把应用表或业务语义放进 GAR。`persistence.extensionWriter(name)` 提供 `enqueue(method, args)`、`flush()`、`health()`、`close()`;应用写入方必须关闭自己的租约,最后一个租约关闭时才退出 Worker。扩展要求与 Runtime 共用文件。
59
+
60
+ 独立生产线程通过 `writer.createPort()` 获得可转移的 MessagePort,直接向同一个写入 Worker 发送 `{ id, method, args }`,收到 `{ id, error? }` 后释放自身缓冲。生产端结束时发送 `{ id, close: true }` 并等待确认;写入 Worker 会等所有生产端端口关闭,再完成最终关闭。该通道不经过 Owner 主线程,网络接收与心跳可独立继续。
61
+
50
62
  离线数据库维护通过 `framework/persistence/sqlite-maintenance.js` 的 `tryAcquireRuntimeSqliteMaintenance(runtimeDirectory)` 使用。它与 Owner 共用系统锁,Owner 运行时返回 `null`;成功后可调用 `inspect(paths)`、`remove(paths, scopes, { inactiveBefore })` 和 `compact(paths)`,最后必须 `close()`。删除覆盖事件、投递、Mailbox、State 历史和插件 epoch 的关联记录,并保留全局自增序号。默认拒绝未关闭或最近活动的 scope;接入方确认过期异常退出数据后可显式设置 `allowInactiveOpenScopes`。保留时间、容量上限、整局分组和中断重试由接入方管理,GAR 不规定业务清理策略。
51
63
 
64
+ 同库维护的 `remove` / `removeHistory` 可接收 `afterRemove(database)`,在同一事务内删除应用关联记录或更新清理标记;回调失败时全部回滚。`compact` 按物理文件去重,只回收一次空间。
65
+
52
66
  1. 用 Source 接入权威 State 和 Event,并保留输入时间及来源。
53
67
  2. 实现感知/策略适配器:整理脚本输入、游戏执行条件和 SDK。
54
68
  3. 注册 Action 和只读 Query,连接游戏后端。
@@ -20,6 +20,7 @@ export declare function detectSqliteAvailability(): SqliteUnavailable | null;
20
20
  export declare class SqliteEventRepository implements EventRepository, MailboxRepository {
21
21
  private readonly db;
22
22
  private readonly compatibility;
23
+ private readonly release;
23
24
  static open(path: string, compatibility?: EventStoreCompatibility): SqliteRepositoryOpenResult;
24
25
  private constructor();
25
26
  close(): void;
@@ -1,3 +1,4 @@
1
+ import { acquireSqliteConnection, sqliteTransaction } from '../persistence/sqlite-connection.js';
1
2
  import { eventStoreCompatibility, sqlValueList } from './store-compatibility.js';
2
3
  import { createRequire } from 'module';
3
4
  import { randomUUID } from 'crypto';
@@ -173,11 +174,12 @@ function placeholders(count) {
173
174
  export class SqliteEventRepository {
174
175
  db;
175
176
  compatibility;
177
+ release;
176
178
  static open(path, compatibility) {
177
179
  const loaded = loadSqlite();
178
180
  if (!loaded.ok)
179
181
  return loaded;
180
- let db;
182
+ let lease;
181
183
  try {
182
184
  if (path !== ':memory:')
183
185
  mkdirSync(dirname(path), { recursive: true });
@@ -191,15 +193,15 @@ export class SqliteEventRepository {
191
193
  },
192
194
  };
193
195
  }
194
- db = new DatabaseSync(path);
195
- const repository = new SqliteEventRepository(db, eventStoreCompatibility(compatibility));
196
+ lease = acquireSqliteConnection(path);
197
+ const repository = new SqliteEventRepository(lease.db, eventStoreCompatibility(compatibility), lease.release);
196
198
  repository.configure();
197
199
  repository.migrate();
198
200
  return { ok: true, repository };
199
201
  }
200
202
  catch (error) {
201
203
  try {
202
- db?.close();
204
+ lease?.release();
203
205
  }
204
206
  catch { }
205
207
  return {
@@ -212,12 +214,13 @@ export class SqliteEventRepository {
212
214
  };
213
215
  }
214
216
  }
215
- constructor(db, compatibility) {
217
+ constructor(db, compatibility, release) {
216
218
  this.db = db;
217
219
  this.compatibility = compatibility;
220
+ this.release = release;
218
221
  }
219
222
  close() {
220
- this.db.close();
223
+ this.release();
221
224
  }
222
225
  /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
223
226
  snapshot(sessionId) {
@@ -2027,18 +2030,6 @@ export class SqliteEventRepository {
2027
2030
  throw new DeliveryLeaseLostError(lease);
2028
2031
  }
2029
2032
  transaction(fn) {
2030
- this.db.exec('BEGIN IMMEDIATE');
2031
- try {
2032
- const result = fn();
2033
- this.db.exec('COMMIT');
2034
- return result;
2035
- }
2036
- catch (error) {
2037
- try {
2038
- this.db.exec('ROLLBACK');
2039
- }
2040
- catch { }
2041
- throw error;
2042
- }
2033
+ return sqliteTransaction(this.db, fn);
2043
2034
  }
2044
2035
  }
@@ -3,15 +3,28 @@ import { getHeapStatistics } from 'v8';
3
3
  import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
4
4
  import { SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
5
5
  import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
6
+ import { resolve } from 'node:path';
6
7
  const paths = workerData;
7
8
  const opened = SqliteEventRepository.open(paths.eventLedgerPath, paths.eventStoreCompatibility);
8
9
  if (!opened.ok)
9
10
  throw new Error(`${opened.unavailable.code}: ${opened.unavailable.message}`);
11
+ const input = new SqliteRuntimeInputJournal(paths.inputJournalPath, paths.inputStorage);
10
12
  const stores = {
11
13
  events: opened.repository,
12
- history: new SqliteStateHistoryRepository(paths.stateHistoryPath),
13
- input: new SqliteRuntimeInputJournal(paths.inputJournalPath),
14
+ history: new SqliteStateHistoryRepository(paths.stateHistoryPath, {
15
+ serializedState: (epoch, scope) => input.serializedState(epoch, scope),
16
+ }),
17
+ input,
14
18
  };
19
+ const extensions = {};
20
+ for (const [name, extension] of Object.entries(paths.extensions ?? {})) {
21
+ if (resolve(extension.databasePath) !== resolve(paths.inputJournalPath))
22
+ throw new Error('sqlite_extension_requires_shared_database');
23
+ const module = await import(extension.moduleUrl);
24
+ extensions[`extension:${name}`] = module.createSqliteMirrorStore(extension.databasePath);
25
+ }
26
+ const unified = paths.inputJournalPath !== ':memory:' && [paths.eventLedgerPath, paths.stateHistoryPath].every(path => resolve(path) === resolve(paths.inputJournalPath));
27
+ let failed;
15
28
  function reportMemory() {
16
29
  if (!paths.diagnostics)
17
30
  return;
@@ -27,16 +40,79 @@ function reportMemory() {
27
40
  reportMemory();
28
41
  const memoryTimer = paths.diagnostics ? setInterval(reportMemory, 5_000) : undefined;
29
42
  memoryTimer?.unref();
43
+ const producerPorts = new Set();
44
+ let closingId;
45
+ function finishClose() {
46
+ if (closingId === undefined || producerPorts.size)
47
+ return;
48
+ if (memoryTimer)
49
+ clearInterval(memoryTimer);
50
+ reportMemory();
51
+ for (const extension of Object.values(extensions))
52
+ extension.close();
53
+ stores.history.close();
54
+ stores.input.close();
55
+ stores.events.close();
56
+ parentPort?.postMessage({ type: 'closed', id: closingId });
57
+ closingId = undefined;
58
+ }
59
+ function attachProducer(name, port) {
60
+ producerPorts.add(port);
61
+ port.on('close', () => { producerPorts.delete(port); finishClose(); });
62
+ port.on('message', (message) => {
63
+ try {
64
+ if (message.close) {
65
+ port.postMessage({ id: message.id });
66
+ port.close();
67
+ return;
68
+ }
69
+ if (failed)
70
+ throw failed;
71
+ const store = extensions[`extension:${name}`], method = store?.[message.method ?? ''];
72
+ if (typeof method !== 'function')
73
+ throw new Error('unknown_sqlite_extension_operation');
74
+ input.withTransaction(() => method.apply(store, message.args ?? []));
75
+ port.postMessage({ id: message.id });
76
+ }
77
+ catch (error) {
78
+ failed ??= error instanceof Error ? error : new Error(String(error));
79
+ port.postMessage({ id: message.id, error: failed.message });
80
+ parentPort?.postMessage({ type: 'error', id: 0, error: failed.message });
81
+ }
82
+ });
83
+ }
30
84
  parentPort?.on('message', (message) => {
31
85
  try {
86
+ if (message.type === 'extension_port') {
87
+ attachProducer(message.name, message.port);
88
+ return;
89
+ }
90
+ if (failed && message.type !== 'close')
91
+ throw failed;
32
92
  if (message.type === 'batch') {
33
- for (const operation of message.operations ?? []) {
34
- const store = stores[operation.store];
35
- const method = store[operation.method];
93
+ const operations = message.operations ?? [];
94
+ const apply = (operation) => {
95
+ const store = stores[operation.store] ?? extensions[operation.store];
96
+ const method = store?.[operation.method];
36
97
  if (typeof method !== 'function')
37
98
  throw new Error(`Unknown persistence operation: ${operation.store}.${operation.method}`);
38
99
  method.apply(store, operation.args);
39
- }
100
+ };
101
+ if (unified)
102
+ input.withTransaction(() => { for (const operation of operations)
103
+ apply(operation); });
104
+ else
105
+ for (let index = 0; index < operations.length;) {
106
+ if (operations[index].store !== 'input') {
107
+ apply(operations[index++]);
108
+ continue;
109
+ }
110
+ // Do not span another store: an input body commits before history can reference it.
111
+ input.withTransaction(() => {
112
+ while (index < operations.length && operations[index].store === 'input')
113
+ apply(operations[index++]);
114
+ });
115
+ }
40
116
  parentPort?.postMessage({ type: 'ack', id: message.id });
41
117
  return;
42
118
  }
@@ -44,15 +120,11 @@ parentPort?.on('message', (message) => {
44
120
  parentPort?.postMessage({ type: 'barrier', id: message.id });
45
121
  return;
46
122
  }
47
- if (memoryTimer)
48
- clearInterval(memoryTimer);
49
- reportMemory();
50
- stores.history.close();
51
- stores.input.close();
52
- stores.events.close();
53
- parentPort?.postMessage({ type: 'closed', id: message.id });
123
+ closingId = message.id;
124
+ finishClose();
54
125
  }
55
126
  catch (error) {
127
+ failed ??= error instanceof Error ? error : new Error(String(error));
56
128
  parentPort?.postMessage({
57
129
  type: 'error',
58
130
  id: message.id,
@@ -1,11 +1,28 @@
1
1
  import type { EventStoreCompatibility } from '../events/store-compatibility.js';
2
+ import { type MessagePort } from 'worker_threads';
2
3
  import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
3
4
  import { type RuntimeResumeSelection } from '../events/runtime-resume.js';
4
5
  import type { EventRepository } from '../events/event-repository.js';
5
6
  import type { EventAccountScope } from '../events/types.js';
6
7
  import type { RuntimePersistenceStore } from '../plugins/contracts.js';
8
+ import { type SqliteInputJournalOptions } from '../plugins/runtime-input-journal.js';
7
9
  import type { StateHistoryRepository } from '../state/history/contracts.js';
10
+ /** Application-owned tables may share the Runtime writer without importing the application into GAR. */
11
+ export interface SqliteMirrorExtension {
12
+ moduleUrl: string;
13
+ databasePath: string;
14
+ }
15
+ export interface SqliteMirrorWriter {
16
+ /** Transfer to another producer thread; calls are serialized by the same SQLite writer. */
17
+ createPort(): MessagePort;
18
+ enqueue(method: string, args: unknown[]): boolean;
19
+ flush(): Promise<void>;
20
+ health(): AsyncPersistenceHealth;
21
+ close(): Promise<void>;
22
+ }
8
23
  export interface MemoryFirstPersistenceOptions {
24
+ extensions?: Record<string, SqliteMirrorExtension>;
25
+ inputStorage?: SqliteInputJournalOptions;
9
26
  eventLedgerPath: string;
10
27
  eventStoreCompatibility?: EventStoreCompatibility;
11
28
  stateHistoryPath: string;
@@ -28,6 +45,7 @@ export interface AsyncPersistenceHealth {
28
45
  workerMemory?: Readonly<Record<string, number>>;
29
46
  }
30
47
  export interface MemoryFirstPersistence<TPosition = unknown, TState extends Record<string, unknown> = Record<string, unknown>, TEvent extends Record<string, unknown> = Record<string, unknown>> {
48
+ extensionWriter(name: string): SqliteMirrorWriter;
31
49
  eventRepository: EventRepository & MailboxRepository;
32
50
  stateHistoryRepository: StateHistoryRepository<TPosition, TState>;
33
51
  inputJournal: RuntimePersistenceStore<TState, TEvent>;
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from 'crypto';
2
2
  import { statSync } from 'fs';
3
+ import { resolve } from 'node:path';
3
4
  import { getHeapStatistics } from 'v8';
4
5
  import { canReuseParticipationSegment } from '../participation-manager.js';
5
6
  import { createRequire } from 'module';
6
7
  import { pathToFileURL } from 'url';
7
- import { Worker } from 'worker_threads';
8
+ import { Worker, MessageChannel } from 'worker_threads';
8
9
  import { MemoryEventRepository } from '../events/memory-event-repository.js';
9
10
  import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
10
11
  import { canResumeRuntimeScope } from '../events/runtime-resume.js';
@@ -63,7 +64,9 @@ class AsyncSqliteMirror {
63
64
  eventStoreCompatibility: options.eventStoreCompatibility,
64
65
  stateHistoryPath: options.stateHistoryPath,
65
66
  inputJournalPath: options.inputJournalPath,
67
+ inputStorage: options.inputStorage,
66
68
  diagnostics: !!options.onDiagnostic,
69
+ extensions: options.extensions,
67
70
  },
68
71
  });
69
72
  this.worker.on('message', (message) => {
@@ -99,19 +102,48 @@ class AsyncSqliteMirror {
99
102
  enqueue(operation) {
100
103
  if (this.degradedError || this.closing) {
101
104
  this.droppedOperations += 1;
102
- return;
105
+ return false;
103
106
  }
104
107
  if (this.pendingCount() >= this.options.maxPendingOperations) {
105
108
  this.degrade(new Error(`Async SQLite queue exceeded ${this.options.maxPendingOperations} operations.`));
106
109
  this.droppedOperations += 1;
107
110
  this.local.length = 0;
108
- return;
111
+ return false;
109
112
  }
110
113
  this.local.push(structuredClone(operation));
111
114
  if (this.local.length >= this.options.batchSize)
112
115
  this.dispatch();
113
116
  else
114
117
  this.timer ??= setTimeout(() => this.dispatch(), this.options.flushIntervalMs);
118
+ return true;
119
+ }
120
+ extensionWriter(name) {
121
+ if (!this.options.extensions?.[name])
122
+ throw new Error(`Unknown SQLite extension: ${name}`);
123
+ this.references++;
124
+ let closed = false;
125
+ return {
126
+ createPort: () => {
127
+ if (closed || this.degradedError || this.closing)
128
+ throw new Error('sqlite_writer_closed');
129
+ const { port1, port2 } = new MessageChannel();
130
+ try {
131
+ this.worker.postMessage({ type: 'extension_port', name, port: port1 }, [port1]);
132
+ }
133
+ catch (error) {
134
+ port1.close();
135
+ port2.close();
136
+ throw error;
137
+ }
138
+ return port2;
139
+ },
140
+ enqueue: (method, args) => !closed && this.enqueue({ store: `extension:${name}`, method, args }),
141
+ flush: () => this.flush(), health: () => this.health(),
142
+ close: async () => { if (!closed) {
143
+ closed = true;
144
+ await this.release();
145
+ } },
146
+ };
115
147
  }
116
148
  health() {
117
149
  return {
@@ -148,7 +180,7 @@ class AsyncSqliteMirror {
148
180
  }
149
181
  async flush() {
150
182
  if (this.degradedError)
151
- return;
183
+ throw this.degradedError;
152
184
  while (this.local.length > 0)
153
185
  this.dispatch();
154
186
  const id = this.nextMessageId++;
@@ -165,7 +197,8 @@ class AsyncSqliteMirror {
165
197
  clearTimeout(this.timer);
166
198
  this.timer = undefined;
167
199
  try {
168
- await this.flush();
200
+ if (!this.degradedError)
201
+ await this.flush();
169
202
  if (!this.degradedError) {
170
203
  const id = this.nextMessageId++;
171
204
  await new Promise((resolve, reject) => {
@@ -351,8 +384,13 @@ class MemoryFirstInputJournal extends MirroredStore {
351
384
  savePluginProgress(progress, scope) { this.memory.savePluginProgress(progress, scope); this.persist('input', 'savePluginProgress', progress, scope); }
352
385
  saveStates(records) { this.memory.saveStates(records); this.persist('input', 'saveStates', records); }
353
386
  states(epochSeq) { return this.memory.states(epochSeq); }
387
+ retainCompletedDiagnostics(scope) { this.persist('input', 'retainCompletedDiagnostics', scope); }
354
388
  }
355
389
  export function createMemoryFirstPersistence(options) {
390
+ if (Object.keys(options.extensions ?? {}).length && (options.inputJournalPath === ':memory:'
391
+ || ![options.eventLedgerPath, options.stateHistoryPath, ...Object.values(options.extensions).map(item => item.databasePath)]
392
+ .every(path => resolve(path) === resolve(options.inputJournalPath))))
393
+ throw new Error('sqlite_extension_requires_shared_database');
356
394
  const startedAt = performance.now();
357
395
  const diagnostic = (stage, attributes = {}) => {
358
396
  if (!options.onDiagnostic)
@@ -385,8 +423,10 @@ export function createMemoryFirstPersistence(options) {
385
423
  let inputMemory;
386
424
  let hydrated = false;
387
425
  try {
388
- historySqlite = new SqliteStateHistoryRepository(options.stateHistoryPath);
389
- inputSqlite = new SqliteRuntimeInputJournal(options.inputJournalPath);
426
+ inputSqlite = new SqliteRuntimeInputJournal(options.inputJournalPath, options.inputStorage);
427
+ historySqlite = new SqliteStateHistoryRepository(options.stateHistoryPath, {
428
+ serializedState: (epoch, scope) => inputSqlite.serializedState(epoch, scope),
429
+ });
390
430
  const current = eventSqlite.repository.currentScope(options.recovery?.account);
391
431
  const restore = options.recovery
392
432
  ? canResumeRuntimeScope(current, options.recovery)
@@ -399,6 +439,9 @@ export function createMemoryFirstPersistence(options) {
399
439
  sessionId: current.session.sessionId, segmentId: current.segment.segmentId,
400
440
  segmentSeq: current.segment.sequence,
401
441
  } : null;
442
+ if (scope && (options.inputStorage?.completedOutcomeEpochs === undefined || options.inputStorage.completedOutcomeEpochs === 'all')) {
443
+ inputSqlite.retainCompletedDiagnostics(scope);
444
+ }
402
445
  diagnostic('selected', {
403
446
  restore_session: !!sessionId, event_selection: sessionId ? 'current_session' : 'metadata_only',
404
447
  state_selection: scope ? 'current_segment' : 'none',
@@ -455,5 +498,6 @@ export function createMemoryFirstPersistence(options) {
455
498
  stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
456
499
  inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
457
500
  health: () => mirror.health(),
501
+ extensionWriter: (name) => mirror.extensionWriter(name),
458
502
  };
459
503
  }
@@ -0,0 +1,25 @@
1
+ export interface SharedStateReader {
2
+ prepare(sql: string): {
3
+ get(...args: any[]): Record<string, any> | undefined;
4
+ };
5
+ }
6
+ export interface SharedStateDatabase extends SharedStateReader {
7
+ prepare(sql: string): {
8
+ get(...args: any[]): Record<string, any> | undefined;
9
+ all(...args: any[]): Record<string, any>[];
10
+ run(...args: any[]): unknown;
11
+ };
12
+ }
13
+ export declare function validateSharedStatePaths(paths: readonly (readonly string[])[]): void;
14
+ /** Content storage only: the application chooses fields; no game rules or field names live here. */
15
+ export declare function splitStateJson(db: SharedStateDatabase, serialized: string, paths: readonly (readonly string[])[]): {
16
+ stateJson: string;
17
+ references: null;
18
+ } | {
19
+ stateJson: string;
20
+ references: string;
21
+ };
22
+ /** Also accepts legacy inline rows. Missing references fail explicitly, never use current State. */
23
+ export declare function materializeStateJson(db: SharedStateReader, row: Record<string, any>): string;
24
+ /** Run inside the same database transaction as epoch deletion. Other scopes' bodies remain referenced. */
25
+ export declare function removeUnreferencedStatePayloads(db: SharedStateDatabase, schema?: string): void;
@@ -0,0 +1,81 @@
1
+ import { createHash } from 'node:crypto';
2
+ function parentAt(root, path) {
3
+ if (!path.length || path.some(key => typeof key !== 'string' || !key || ['__proto__', 'prototype', 'constructor'].includes(key)))
4
+ throw Error('invalid_shared_state_path');
5
+ let current = root;
6
+ for (const key of path.slice(0, -1)) {
7
+ if (!current || typeof current !== 'object' || Array.isArray(current) || !Object.hasOwn(current, key))
8
+ throw Error('missing_shared_state_path');
9
+ current = current[key];
10
+ }
11
+ if (!current || typeof current !== 'object' || Array.isArray(current) || !Object.hasOwn(current, path.at(-1)))
12
+ throw Error('missing_shared_state_path');
13
+ return current;
14
+ }
15
+ export function validateSharedStatePaths(paths) {
16
+ for (const path of paths) {
17
+ if (!path.length || path.some(key => typeof key !== 'string' || !key || ['__proto__', 'prototype', 'constructor'].includes(key)))
18
+ throw Error('invalid_shared_state_path');
19
+ if (paths.some(other => other !== path && other.length <= path.length && other.every((key, i) => path[i] === key)))
20
+ throw Error('overlapping_shared_state_paths');
21
+ }
22
+ }
23
+ /** Content storage only: the application chooses fields; no game rules or field names live here. */
24
+ export function splitStateJson(db, serialized, paths) {
25
+ if (!paths.length)
26
+ return { stateJson: serialized, references: null };
27
+ const envelope = JSON.parse(serialized);
28
+ const references = [];
29
+ for (const path of paths) {
30
+ let parent;
31
+ try {
32
+ parent = parentAt(envelope, path);
33
+ }
34
+ catch {
35
+ continue;
36
+ }
37
+ const key = path.at(-1);
38
+ const value = parent[key];
39
+ if (!value || typeof value !== 'object')
40
+ continue;
41
+ const body = JSON.stringify(value);
42
+ const id = createHash('sha256').update(body).digest('hex');
43
+ db.prepare('INSERT OR IGNORE INTO runtime_state_payloads(payload_id,body_json) VALUES (?,?)').run(id, body);
44
+ if (db.prepare('SELECT body_json FROM runtime_state_payloads WHERE payload_id=?').get(id)?.body_json !== body)
45
+ throw Error('shared_state_hash_conflict');
46
+ // Replace rather than delete the key, preserving JSON property order on reconstruction.
47
+ parent[key] = null;
48
+ references.push({ path: [...path], id });
49
+ }
50
+ return references.length ? { stateJson: JSON.stringify(envelope), references: JSON.stringify(references) }
51
+ : { stateJson: serialized, references: null };
52
+ }
53
+ /** Also accepts legacy inline rows. Missing references fail explicitly, never use current State. */
54
+ export function materializeStateJson(db, row) {
55
+ if (!row.state_refs_json)
56
+ return row.state_json;
57
+ const envelope = JSON.parse(row.state_json);
58
+ const references = JSON.parse(row.state_refs_json);
59
+ if (!Array.isArray(references) || !references.length)
60
+ throw Error('invalid_shared_state_references');
61
+ for (const ref of references) {
62
+ if (!Array.isArray(ref.path) || typeof ref.id !== 'string')
63
+ throw Error('invalid_shared_state_reference');
64
+ const parent = parentAt(envelope, ref.path);
65
+ const body = db.prepare('SELECT body_json FROM runtime_state_payloads WHERE payload_id=?').get(ref.id)?.body_json;
66
+ if (typeof body !== 'string')
67
+ throw Error(`Shared state body unavailable: ${ref.id}`);
68
+ parent[ref.path.at(-1)] = JSON.parse(body);
69
+ }
70
+ return JSON.stringify(envelope);
71
+ }
72
+ /** Run inside the same database transaction as epoch deletion. Other scopes' bodies remain referenced. */
73
+ export function removeUnreferencedStatePayloads(db, schema = 'main') {
74
+ if (!/^[a-z]+$/.test(schema))
75
+ throw Error('invalid_shared_state_schema');
76
+ if (!db.prepare(`SELECT 1 FROM ${schema}.sqlite_schema WHERE name='runtime_state_payloads' AND type='table'`).get())
77
+ return;
78
+ db.prepare(`DELETE FROM ${schema}.runtime_state_payloads WHERE payload_id NOT IN (
79
+ SELECT json_extract(ref.value,'$.id') FROM ${schema}.runtime_epochs e, json_each(e.state_refs_json) ref
80
+ )`).run();
81
+ }
@@ -0,0 +1,20 @@
1
+ export interface SqliteDatabase {
2
+ exec(sql: string): void;
3
+ prepare(sql: string): {
4
+ run(...args: any[]): {
5
+ changes: number | bigint;
6
+ lastInsertRowid?: number | bigint;
7
+ };
8
+ get(...args: any[]): Record<string, any> | undefined;
9
+ all(...args: any[]): Record<string, any>[];
10
+ iterate(...args: any[]): Iterable<Record<string, any>>;
11
+ };
12
+ close(): void;
13
+ }
14
+ /** One connection per physical file in this thread. Leases own close, repositories own their tables. */
15
+ export declare function acquireSqliteConnection(path: string): {
16
+ db: SqliteDatabase;
17
+ release(): void;
18
+ };
19
+ /** Nested store operations use savepoints inside the writer's shared batch transaction. */
20
+ export declare function sqliteTransaction<T>(db: Pick<SqliteDatabase, 'exec'>, operation: () => T): T;
@@ -0,0 +1,60 @@
1
+ import { createRequire } from 'node:module';
2
+ import { mkdirSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import { loadNodeSqliteModule } from '../load-node-sqlite.js';
5
+ const connections = new Map();
6
+ const depths = new WeakMap();
7
+ let sequence = 0;
8
+ /** One connection per physical file in this thread. Leases own close, repositories own their tables. */
9
+ export function acquireSqliteConnection(path) {
10
+ const key = path === ':memory:' ? `memory:${++sequence}` : resolve(path);
11
+ let entry = connections.get(key);
12
+ if (!entry) {
13
+ if (path !== ':memory:')
14
+ mkdirSync(dirname(path), { recursive: true });
15
+ const { DatabaseSync } = loadNodeSqliteModule(createRequire(import.meta.url));
16
+ const db = new DatabaseSync(path);
17
+ try {
18
+ db.exec('PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL');
19
+ }
20
+ catch (error) {
21
+ db.close();
22
+ throw error;
23
+ }
24
+ entry = { db, references: 0 };
25
+ connections.set(key, entry);
26
+ }
27
+ entry.references++;
28
+ let released = false;
29
+ return { db: entry.db, release() {
30
+ if (released)
31
+ return;
32
+ released = true;
33
+ if (--entry.references === 0) {
34
+ connections.delete(key);
35
+ entry.db.close();
36
+ }
37
+ } };
38
+ }
39
+ /** Nested store operations use savepoints inside the writer's shared batch transaction. */
40
+ export function sqliteTransaction(db, operation) {
41
+ const depth = depths.get(db) ?? 0;
42
+ const name = `store_${++sequence}`;
43
+ db.exec(depth ? `SAVEPOINT ${name}` : 'BEGIN IMMEDIATE');
44
+ depths.set(db, depth + 1);
45
+ try {
46
+ const result = operation();
47
+ db.exec(depth ? `RELEASE ${name}` : 'COMMIT');
48
+ return result;
49
+ }
50
+ catch (error) {
51
+ try {
52
+ db.exec(depth ? `ROLLBACK TO ${name}; RELEASE ${name}` : 'ROLLBACK');
53
+ }
54
+ catch { }
55
+ throw error;
56
+ }
57
+ finally {
58
+ depths.set(db, depth);
59
+ }
60
+ }
@@ -1,3 +1,4 @@
1
+ import { type SqliteDatabase } from './sqlite-connection.js';
1
2
  export interface RuntimeSqlitePaths {
2
3
  eventLedger: string;
3
4
  stateHistory: string;
@@ -13,14 +14,21 @@ export interface ArchivedScope {
13
14
  lastActivityAt: string | null;
14
15
  open: boolean;
15
16
  }
17
+ interface RemovalExtension {
18
+ afterRemove?: (database: SqliteDatabase) => void;
19
+ }
16
20
  export interface RuntimeSqliteMaintenance {
17
21
  inspect(paths: RuntimeSqlitePaths): ArchivedScope[];
18
22
  remove(paths: RuntimeSqlitePaths, scopes: readonly Pick<ArchivedScope, 'sessionId' | 'segmentId'>[], options: {
19
23
  inactiveBefore: string;
20
24
  allowInactiveOpenScopes?: boolean;
25
+ } & RemovalExtension): void;
26
+ removeHistory(paths: RuntimeSqlitePaths, scopes: readonly Pick<ArchivedScope, 'sessionId' | 'segmentId'>[], options?: RemovalExtension): void;
27
+ compact(paths: RuntimeSqlitePaths, options?: {
28
+ includeEvents?: boolean;
21
29
  }): void;
22
- compact(paths: RuntimeSqlitePaths): void;
23
30
  close(): void;
24
31
  }
25
- /** Acquires the SAME OS lock used by a Runtime Owner. No live store is modified. */
32
+ /** Offline maintenance owns the same OS lock as the Runtime; application rows may join its transaction. */
26
33
  export declare function tryAcquireRuntimeSqliteMaintenance(directory: string): RuntimeSqliteMaintenance | null;
34
+ export {};