@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.
@@ -1,177 +1,200 @@
1
- import { createRequire } from 'node:module';
2
1
  import { existsSync, realpathSync } from 'node:fs';
3
2
  import { isAbsolute, relative, resolve } from 'node:path';
4
3
  import { tryAcquireRuntimeLock } from '../../owner/runtime-lock.js';
5
- import { loadNodeSqliteModule } from '../load-node-sqlite.js';
6
- /** Acquires the SAME OS lock used by a Runtime Owner. No live store is modified. */
4
+ import { removeUnreferencedStatePayloads } from './shared-state.js';
5
+ import { acquireSqliteConnection, sqliteTransaction } from './sqlite-connection.js';
6
+ function table(db, schema, name) {
7
+ return db.prepare('PRAGMA database_list').all().some(row => row.name === schema)
8
+ && !!db.prepare(`SELECT 1 FROM ${schema}.sqlite_schema WHERE type='table' AND name=?`).get(name);
9
+ }
10
+ function inspect({ db, aliases: a }) {
11
+ const scopes = new Map();
12
+ const merge = (sessionId, segmentId, at) => {
13
+ const key = JSON.stringify([sessionId, segmentId]);
14
+ let scope = scopes.get(key);
15
+ if (!scope) {
16
+ scope = { sessionId, segmentId, kind: 'unknown', identity: null, openedAt: null, closedAt: null, lastActivityAt: null, open: false };
17
+ scopes.set(key, scope);
18
+ }
19
+ if (at && Number.isFinite(Date.parse(at)) && (!scope.lastActivityAt || Date.parse(at) > Date.parse(scope.lastActivityAt)))
20
+ scope.lastActivityAt = at;
21
+ return scope;
22
+ };
23
+ if (table(db, a.events, 'event_segments'))
24
+ for (const row of db.prepare(`SELECT * FROM ${a.events}.event_segments`).all()) {
25
+ const scope = merge(row.session_id, row.segment_id, row.closed_at ?? row.opened_at);
26
+ Object.assign(scope, { kind: row.kind, identity: row.scope_ref ?? null, openedAt: row.opened_at,
27
+ closedAt: row.closed_at ?? null, open: row.status === 'open' || row.is_current === 1 });
28
+ }
29
+ for (const [schema, name, time] of [[a.events, 'events', 'MAX(received_at)'],
30
+ [a.input, 'runtime_epochs', 'MAX(received_at)'], [a.input, 'runtime_plugin_progress', 'MAX(updated_at)']]) {
31
+ if (table(db, schema, name))
32
+ for (const row of db.prepare(`SELECT session_id,segment_id,${time} AS at FROM ${schema}.${name} GROUP BY session_id,segment_id`).all()) {
33
+ merge(row.session_id, row.segment_id, row.at);
34
+ }
35
+ }
36
+ if (table(db, a.history, 'history_scopes'))
37
+ for (const row of db.prepare(`SELECT * FROM ${a.history}.history_scopes`).all()) {
38
+ const scope = merge(row.session_id, row.segment_id, new Date(row.sealed_at_ms ?? row.opened_at_ms).toISOString());
39
+ scope.open ||= row.status === 'OPEN';
40
+ }
41
+ for (const name of ['state_frames', 'trajectory_records'])
42
+ if (table(db, a.history, name)) {
43
+ for (const row of db.prepare(`SELECT session_id,segment_id,MAX(received_at_ms) AS at FROM ${a.history}.${name} GROUP BY session_id,segment_id`).all()) {
44
+ merge(row.session_id, row.segment_id, Number.isFinite(Number(row.at)) ? new Date(Number(row.at)).toISOString() : null);
45
+ }
46
+ }
47
+ return [...scopes.values()];
48
+ }
49
+ /** Offline maintenance owns the same OS lock as the Runtime; application rows may join its transaction. */
7
50
  export function tryAcquireRuntimeSqliteMaintenance(directory) {
8
- const lease = tryAcquireRuntimeLock(directory);
9
- if (!lease)
51
+ const lock = tryAcquireRuntimeLock(directory);
52
+ if (!lock)
10
53
  return null;
11
54
  let root;
12
- let closed = false;
13
- let module;
14
55
  try {
15
56
  root = realpathSync(directory);
16
- module = loadNodeSqliteModule(createRequire(import.meta.url));
17
57
  }
18
58
  catch (error) {
19
- lease.release();
59
+ lock.release();
20
60
  throw error;
21
61
  }
62
+ let closed = false;
22
63
  const connection = (paths) => {
23
64
  if (closed)
24
65
  throw Error('runtime_maintenance_closed');
25
- const db = new module.DatabaseSync(':memory:');
66
+ const selected = [];
67
+ for (const [key, path] of [['events', paths.eventLedger], ['history', paths.stateHistory], ['input', paths.inputJournal]]) {
68
+ if (!existsSync(path))
69
+ continue;
70
+ const target = realpathSync(path), child = relative(root, target);
71
+ if (!child || isAbsolute(child) || child === '..' || child.startsWith('../') || child.startsWith('..\\'))
72
+ throw Error('runtime_maintenance_path_outside_lock');
73
+ selected.push([key, resolve(target)]);
74
+ }
75
+ const unique = [...new Set(selected.map(([, path]) => path))];
76
+ const unified = unique.length === 1 && new Set(Object.values(paths).map(path => resolve(path))).size === 1;
77
+ const lease = acquireSqliteConnection(unified ? unique[0] : ':memory:');
78
+ const aliases = { events: 'eventsdb', history: 'historydb', input: 'epochsdb' };
26
79
  try {
27
- db.exec('PRAGMA foreign_keys=ON; PRAGMA busy_timeout=1000');
28
- for (const [alias, path] of [['eventsdb', paths.eventLedger], ['historydb', paths.stateHistory], ['epochsdb', paths.inputJournal]]) {
29
- if (!existsSync(path))
30
- continue;
31
- const target = realpathSync(path);
32
- const child = relative(root, target);
33
- if (!child || isAbsolute(child) || child === '..' || child.startsWith('../') || child.startsWith('..\\')) {
34
- throw Error('runtime_maintenance_path_outside_lock');
80
+ if (unified)
81
+ for (const key of Object.keys(aliases))
82
+ aliases[key] = 'main';
83
+ else {
84
+ const attached = new Map();
85
+ for (const [key, path] of selected) {
86
+ const prior = attached.get(path);
87
+ if (prior) {
88
+ aliases[key] = prior;
89
+ continue;
90
+ }
91
+ lease.db.prepare(`ATTACH DATABASE ? AS ${aliases[key]}`).run(path);
92
+ attached.set(path, aliases[key]);
35
93
  }
36
- db.prepare(`ATTACH DATABASE ? AS ${alias}`).run(resolve(target));
37
94
  }
38
- return db;
95
+ return { ...lease, aliases, unified };
39
96
  }
40
97
  catch (error) {
41
- db.close();
98
+ lease.release();
42
99
  throw error;
43
100
  }
44
101
  };
45
- const table = (db, alias, name) => {
46
- if (!db.prepare('PRAGMA database_list').all().some(row => row.name === alias))
47
- return false;
48
- return !!db.prepare(`SELECT 1 FROM ${alias}.sqlite_schema WHERE type='table' AND name=?`).get(name);
49
- };
50
- const inspect = (db) => {
51
- const scopes = new Map();
52
- const merge = (sessionId, segmentId, at) => {
53
- const key = JSON.stringify([sessionId, segmentId]);
54
- let scope = scopes.get(key);
55
- if (!scope) {
56
- scope = { sessionId, segmentId, kind: 'unknown', identity: null, openedAt: null, closedAt: null, lastActivityAt: null, open: false };
57
- scopes.set(key, scope);
58
- }
59
- if (at && Number.isFinite(Date.parse(at)) && (!scope.lastActivityAt || Date.parse(at) > Date.parse(scope.lastActivityAt)))
60
- scope.lastActivityAt = at;
61
- return scope;
62
- };
63
- if (table(db, 'eventsdb', 'event_segments')) {
64
- for (const row of db.prepare('SELECT * FROM eventsdb.event_segments').all()) {
65
- const scope = merge(row.session_id, row.segment_id, row.closed_at ?? row.opened_at);
66
- Object.assign(scope, { kind: row.kind, identity: row.scope_ref ?? null, openedAt: row.opened_at,
67
- closedAt: row.closed_at ?? null, open: row.status === 'open' || row.is_current === 1 });
68
- }
69
- }
70
- for (const [alias, name, time] of [
71
- ['eventsdb', 'events', 'MAX(received_at)'],
72
- ['epochsdb', 'runtime_epochs', 'MAX(received_at)'],
73
- ['epochsdb', 'runtime_plugin_progress', 'MAX(updated_at)'],
74
- ])
75
- if (table(db, alias, name)) {
76
- for (const row of db.prepare(`SELECT session_id,segment_id,${time} AS at FROM ${alias}.${name} GROUP BY session_id,segment_id`).all()) {
77
- merge(row.session_id, row.segment_id, row.at);
78
- }
79
- }
80
- if (table(db, 'historydb', 'history_scopes')) {
81
- for (const row of db.prepare('SELECT * FROM historydb.history_scopes').all()) {
82
- const scope = merge(row.session_id, row.segment_id, new Date(row.sealed_at_ms ?? row.opened_at_ms).toISOString());
83
- scope.open ||= row.status === 'OPEN';
84
- }
85
- }
86
- for (const name of ['state_frames', 'trajectory_records'])
87
- if (table(db, 'historydb', name)) {
88
- for (const row of db.prepare(`SELECT session_id,segment_id,MAX(received_at_ms) AS at FROM historydb.${name} GROUP BY session_id,segment_id`).all()) {
89
- merge(row.session_id, row.segment_id, Number.isFinite(Number(row.at)) ? new Date(Number(row.at)).toISOString() : null);
90
- }
91
- }
92
- return [...scopes.values()];
93
- };
94
- return {
95
- inspect(paths) { const db = connection(paths); try {
96
- return inspect(db);
97
- }
98
- finally {
99
- db.close();
100
- } },
101
- remove(paths, selected, options) {
102
- const cutoff = Date.parse(options.inactiveBefore);
103
- if (!Number.isFinite(cutoff))
104
- throw Error('runtime_maintenance_invalid_cutoff');
105
- const db = connection(paths);
106
- try {
107
- db.exec('BEGIN IMMEDIATE');
108
- const current = inspect(db);
102
+ const remove = (paths, selected, historyOnly, options) => {
103
+ const cutoff = Date.parse(options.inactiveBefore ?? '');
104
+ if (!historyOnly && !Number.isFinite(cutoff))
105
+ throw Error('runtime_maintenance_invalid_cutoff');
106
+ const c = connection(paths), { db, aliases: a } = c;
107
+ try {
108
+ if (options.afterRemove && !c.unified)
109
+ throw Error('runtime_maintenance_extension_requires_shared_database');
110
+ const validate = () => {
111
+ const current = inspect(c);
109
112
  for (const scope of selected) {
110
113
  const actual = current.find(row => row.sessionId === scope.sessionId && row.segmentId === scope.segmentId);
111
- if (actual && (!actual.lastActivityAt || Date.parse(actual.lastActivityAt) >= cutoff
114
+ if (actual && (historyOnly ? actual.open : !actual.lastActivityAt || Date.parse(actual.lastActivityAt) >= cutoff
112
115
  || actual.open && !options.allowInactiveOpenScopes))
113
116
  throw Error('runtime_maintenance_scope_protected');
114
117
  }
115
- const remove = (alias, name, where, args) => {
116
- if (table(db, alias, name))
117
- db.prepare(`DELETE FROM ${alias}.${name} WHERE ${where}`).run(...args);
118
- };
118
+ };
119
+ const erase = (schema, name, where, args) => {
120
+ if (table(db, schema, name))
121
+ db.prepare(`DELETE FROM ${schema}.${name} WHERE ${where}`).run(...args);
122
+ };
123
+ const references = () => {
124
+ for (const scope of selected)
125
+ for (const name of ['trajectory_records', 'state_frames', 'history_scopes']) {
126
+ erase(a.history, name, 'session_id=? AND segment_id=?', [scope.sessionId, scope.segmentId]);
127
+ }
128
+ };
129
+ const bodies = () => {
119
130
  for (const scope of selected) {
120
131
  const args = [scope.sessionId, scope.segmentId];
121
- const eventIds = 'SELECT event_id FROM eventsdb.events WHERE session_id=? AND segment_id=?';
122
- if (table(db, 'eventsdb', 'events')) {
123
- remove('eventsdb', 'mailbox_items', 'session_id=? AND segment_id=?', args);
124
- remove('eventsdb', 'event_deliveries', `event_id IN (${eventIds})`, args);
125
- remove('eventsdb', 'source_checkpoints', `event_id IN (${eventIds})`, args);
126
- remove('eventsdb', 'events', 'session_id=? AND segment_id=?', args);
132
+ if (!historyOnly) {
133
+ if (table(db, a.events, 'events')) {
134
+ const eventIds = `SELECT event_id FROM ${a.events}.events WHERE session_id=? AND segment_id=?`;
135
+ erase(a.events, 'mailbox_items', 'session_id=? AND segment_id=?', args);
136
+ erase(a.events, 'event_deliveries', `event_id IN (${eventIds})`, args);
137
+ erase(a.events, 'source_checkpoints', `event_id IN (${eventIds})`, args);
138
+ erase(a.events, 'events', 'session_id=? AND segment_id=?', args);
139
+ }
140
+ erase(a.events, 'event_segments', 'session_id=? AND segment_id=?', args);
127
141
  }
128
- remove('eventsdb', 'event_segments', 'session_id=? AND segment_id=?', args);
129
- for (const name of ['trajectory_records', 'state_frames', 'history_scopes'])
130
- remove('historydb', name, 'session_id=? AND segment_id=?', args);
131
- if (table(db, 'epochsdb', 'runtime_epochs')) {
142
+ if (table(db, a.input, 'runtime_epochs')) {
132
143
  for (const name of ['runtime_plugin_outcomes', 'runtime_plugin_states']) {
133
- remove('epochsdb', name, 'epoch_seq IN (SELECT epoch_seq FROM epochsdb.runtime_epochs WHERE session_id=? AND segment_id=?)', args);
144
+ erase(a.input, name, `epoch_seq IN (SELECT epoch_seq FROM ${a.input}.runtime_epochs WHERE session_id=? AND segment_id=?)`, args);
134
145
  }
135
- remove('epochsdb', 'runtime_epochs', 'session_id=? AND segment_id=?', args);
146
+ erase(a.input, 'runtime_epochs', 'session_id=? AND segment_id=?', args);
136
147
  }
137
- remove('epochsdb', 'runtime_plugin_progress', 'session_id=? AND segment_id=?', args);
148
+ erase(a.input, 'runtime_plugin_progress', 'session_id=? AND segment_id=?', args);
149
+ erase(a.input, 'runtime_scope_storage_policy', 'session_id=? AND segment_id=?', args);
138
150
  }
139
- if (table(db, 'eventsdb', 'play_sessions')) {
151
+ if (table(db, a.input, 'runtime_state_payloads'))
152
+ removeUnreferencedStatePayloads(db, a.input);
153
+ if (!historyOnly && table(db, a.events, 'play_sessions'))
140
154
  for (const sessionId of new Set(selected.map(scope => scope.sessionId))) {
141
- remove('eventsdb', 'play_sessions', 'session_id=? AND NOT EXISTS (SELECT 1 FROM eventsdb.event_segments s WHERE s.session_id=play_sessions.session_id)', [sessionId]);
155
+ erase(a.events, 'play_sessions', `session_id=? AND NOT EXISTS (SELECT 1 FROM ${a.events}.event_segments s WHERE s.session_id=play_sessions.session_id)`, [sessionId]);
142
156
  }
143
- }
144
- db.exec('COMMIT');
145
- }
146
- catch (error) {
147
- try {
148
- db.exec('ROLLBACK');
149
- }
150
- catch { }
151
- throw error;
152
- }
153
- finally {
154
- db.close();
157
+ options.afterRemove?.(db);
158
+ };
159
+ if (c.unified)
160
+ sqliteTransaction(db, () => { validate(); references(); bodies(); });
161
+ else {
162
+ // Standalone GAR callers can still use separate files: commit references before bodies.
163
+ sqliteTransaction(db, () => { validate(); references(); });
164
+ sqliteTransaction(db, bodies);
155
165
  }
156
- },
157
- compact(paths) {
158
- const db = connection(paths);
166
+ }
167
+ finally {
168
+ c.release();
169
+ }
170
+ };
171
+ return {
172
+ inspect(paths) { const c = connection(paths); try {
173
+ return inspect(c);
174
+ }
175
+ finally {
176
+ c.release();
177
+ } },
178
+ remove(paths, selected, options) { remove(paths, selected, false, options); },
179
+ removeHistory(paths, selected, options = {}) { remove(paths, selected, true, options); },
180
+ compact(paths, options = {}) {
181
+ const c = connection(paths);
159
182
  try {
160
- for (const row of db.prepare('PRAGMA database_list').all()) {
161
- if (!['eventsdb', 'historydb', 'epochsdb'].includes(row.name))
162
- continue;
163
- db.exec(`PRAGMA ${row.name}.wal_checkpoint(TRUNCATE)`);
164
- db.exec(`VACUUM ${row.name}`);
165
- db.exec(`PRAGMA ${row.name}.wal_checkpoint(TRUNCATE)`);
166
- }
183
+ const schemas = new Set([c.aliases.history, c.aliases.input, ...(options.includeEvents === false ? [] : [c.aliases.events])]);
184
+ for (const { name } of c.db.prepare('PRAGMA database_list').all())
185
+ if (schemas.has(name)) {
186
+ c.db.exec(`PRAGMA ${name}.wal_checkpoint(TRUNCATE)`);
187
+ c.db.exec(`VACUUM ${name}`);
188
+ c.db.exec(`PRAGMA ${name}.wal_checkpoint(TRUNCATE)`);
189
+ }
167
190
  }
168
191
  finally {
169
- db.close();
192
+ c.release();
170
193
  }
171
194
  },
172
195
  close() { if (!closed) {
173
196
  closed = true;
174
- lease.release();
197
+ lock.release();
175
198
  } },
176
199
  };
177
200
  }
@@ -333,6 +333,8 @@ export interface RuntimePluginStore {
333
333
  }
334
334
  /** One physical database may implement both logical persistence contracts. */
335
335
  export interface RuntimePersistenceStore<TState = Record<string, unknown>, TEvent = Record<string, unknown>> extends RuntimeInputJournal<TState, TEvent>, RuntimePluginStore {
336
+ /** Optional disk-policy escalation; does not change computation or history availability. */
337
+ retainCompletedDiagnostics?(scope: RuntimeScope): void;
336
338
  }
337
339
  export interface RuntimeEpochExecutionResult {
338
340
  readonly epochSeq: number;
@@ -58,14 +58,29 @@ export declare class MemoryRuntimeInputJournal<TState = Record<string, unknown>,
58
58
  private indexPluginRecord;
59
59
  private indexStateRecord;
60
60
  }
61
+ export interface SqliteInputJournalOptions {
62
+ sharedStatePaths?: readonly (readonly string[])[];
63
+ /** Disk-only diagnostic retention. Open epochs and all State/Event/checkpoint data are retained. */
64
+ completedOutcomeEpochs?: number | 'all';
65
+ }
61
66
  export declare class SqliteRuntimeInputJournal<TState = Record<string, unknown>, TEvent = Record<string, unknown>> implements RuntimePersistenceStore<TState, TEvent> {
67
+ private readonly options;
62
68
  private readonly db;
63
- constructor(path: string);
69
+ private readonly release;
70
+ constructor(path: string, options?: SqliteInputJournalOptions);
71
+ /** Synchronous transaction shared with other stores on the same connection. */
72
+ withTransaction<T>(operation: () => T): T;
64
73
  accept(batch: RuntimeInputBatch<TState, TEvent>): RuntimeInputAcceptance<TState, TEvent>;
65
74
  epoch(epochSeq: number): RuntimeEpoch<TState, TEvent> | null;
75
+ /** Immutable body lookup for history references; scope identity must match exactly. */
76
+ serializedState(epochSeq: number, scope: RuntimeScope): string | undefined;
66
77
  list(scope: RuntimeScope, afterEpochSeq?: number, limit?: number): RuntimeEpoch<TState, TEvent>[];
67
78
  listOpen(scope: RuntimeScope, afterEpochSeq?: number, limit?: number): RuntimeEpoch<TState, TEvent>[];
68
79
  markClosed(epochSeq: number, closedAt?: string, durationMs?: number): void;
80
+ private registerDiagnosticPolicy;
81
+ /** Escalation only; switching back to normal diagnostics never discards a full segment. */
82
+ retainCompletedDiagnostics(scope: RuntimeScope): void;
83
+ private pruneCompletedOutcomes;
69
84
  inputEventsCommitted(epochSeq: number): boolean;
70
85
  markInputEventsCommitted(epochSeq: number, eventWatermark: number, committedAt?: string): void;
71
86
  eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number;
@@ -1,8 +1,10 @@
1
+ import { acquireSqliteConnection, sqliteTransaction } from '../persistence/sqlite-connection.js';
1
2
  import { createHash } from 'crypto';
2
3
  import { createRequire } from 'module';
3
4
  import { mkdirSync } from 'fs';
4
5
  import { dirname } from 'path';
5
6
  import { loadNodeSqliteModule } from '../load-node-sqlite.js';
7
+ import { materializeStateJson, splitStateJson, validateSharedStatePaths } from '../persistence/shared-state.js';
6
8
  import { cloneCanonical, runtimeScopeKey } from '../state/types.js';
7
9
  const localRequire = createRequire(import.meta.url);
8
10
  function canonicalPayload(batch) {
@@ -341,43 +343,73 @@ function numberValue(value) {
341
343
  return typeof value === 'bigint' ? Number(value) : Number(value ?? 0);
342
344
  }
343
345
  export class SqliteRuntimeInputJournal {
346
+ options;
344
347
  db;
345
- constructor(path) {
348
+ release;
349
+ constructor(path, options = {}) {
350
+ this.options = options;
346
351
  const sqlite = loadNodeSqliteModule(localRequire);
347
352
  if (typeof sqlite.DatabaseSync !== 'function')
348
353
  throw new Error('node:sqlite is unavailable in this Node.js runtime');
349
354
  if (path !== ':memory:')
350
355
  mkdirSync(dirname(path), { recursive: true });
351
- this.db = new sqlite.DatabaseSync(path);
352
- this.initialize();
356
+ const lease = acquireSqliteConnection(path);
357
+ this.db = lease.db;
358
+ this.release = lease.release;
359
+ try {
360
+ validateSharedStatePaths(options.sharedStatePaths ?? []);
361
+ if (options.completedOutcomeEpochs !== undefined && options.completedOutcomeEpochs !== 'all'
362
+ && (!Number.isSafeInteger(options.completedOutcomeEpochs) || options.completedOutcomeEpochs < 1))
363
+ throw Error('invalid_completed_outcome_window');
364
+ this.initialize();
365
+ }
366
+ catch (error) {
367
+ this.release();
368
+ throw error;
369
+ }
370
+ }
371
+ /** Synchronous transaction shared with other stores on the same connection. */
372
+ withTransaction(operation) {
373
+ return sqliteTransaction(this.db, operation);
353
374
  }
354
375
  accept(batch) {
355
376
  assertRuntimeInputBatch(batch);
356
377
  const hash = payloadHash(batch);
357
- const existing = this.findByIdentity(batch.scope, batch.sourceId, batch.sourceKey);
358
- if (existing) {
359
- if (String(existing.payload_hash) !== hash)
360
- throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
361
- return { inserted: false, epoch: this.fromRow(existing) };
362
- }
363
- const result = this.db.prepare(`
364
- INSERT INTO runtime_epochs(
365
- adapter_id, account_id, session_id, segment_id, segment_seq,
366
- source_id, connection_id, source_key, source_seq_json, domain_tick_json,
367
- state_json, events_json, event_watermark_json, completeness, coalescing,
368
- observed_at, received_at, payload_hash, status
369
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'accepted')
370
- `).run(batch.scope.adapterId, batch.scope.accountId, batch.scope.sessionId, batch.scope.segmentId, batch.scope.segmentSeq ?? null, batch.sourceId, batch.connectionId, batch.sourceKey, batch.sourceSeq === undefined ? null : JSON.stringify(batch.sourceSeq), batch.domainTick === undefined ? null : JSON.stringify(batch.domainTick), JSON.stringify(batch.state), JSON.stringify(batch.events), batch.eventWatermark === undefined ? null : JSON.stringify(batch.eventWatermark), batch.completeness, batch.coalescing ?? 'allowed', batch.observedAt ?? null, batch.receivedAt, hash);
371
- const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?')
372
- .get(numberValue(result.lastInsertRowid));
373
- if (!row)
374
- throw new Error('Runtime epoch was inserted but could not be read.');
375
- return { inserted: true, epoch: this.fromRow(row) };
378
+ return this.withTransaction(() => {
379
+ const existing = this.findByIdentity(batch.scope, batch.sourceId, batch.sourceKey);
380
+ if (existing) {
381
+ if (String(existing.payload_hash) !== hash)
382
+ throw new RuntimeInputConflictError(batch.sourceId, batch.sourceKey);
383
+ return { inserted: false, epoch: this.fromRow(existing) };
384
+ }
385
+ const split = splitStateJson(this.db, JSON.stringify(batch.state), this.options.sharedStatePaths ?? []);
386
+ this.registerDiagnosticPolicy(batch.scope);
387
+ const result = this.db.prepare(`
388
+ INSERT INTO runtime_epochs(
389
+ adapter_id, account_id, session_id, segment_id, segment_seq,
390
+ source_id, connection_id, source_key, source_seq_json, domain_tick_json,
391
+ state_json, events_json, event_watermark_json, completeness, coalescing,
392
+ observed_at, received_at, payload_hash, state_refs_json, status
393
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'accepted')
394
+ `).run(batch.scope.adapterId, batch.scope.accountId, batch.scope.sessionId, batch.scope.segmentId, batch.scope.segmentSeq ?? null, batch.sourceId, batch.connectionId, batch.sourceKey, batch.sourceSeq === undefined ? null : JSON.stringify(batch.sourceSeq), batch.domainTick === undefined ? null : JSON.stringify(batch.domainTick), split.stateJson, JSON.stringify(batch.events), batch.eventWatermark === undefined ? null : JSON.stringify(batch.eventWatermark), batch.completeness, batch.coalescing ?? 'allowed', batch.observedAt ?? null, batch.receivedAt, hash, split.references);
395
+ const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?')
396
+ .get(numberValue(result.lastInsertRowid));
397
+ if (!row)
398
+ throw new Error('Runtime epoch was inserted but could not be read.');
399
+ return { inserted: true, epoch: this.fromRow(row) };
400
+ });
376
401
  }
377
402
  epoch(epochSeq) {
378
403
  const row = this.db.prepare('SELECT * FROM runtime_epochs WHERE epoch_seq = ?').get(epochSeq);
379
404
  return row ? this.fromRow(row) : null;
380
405
  }
406
+ /** Immutable body lookup for history references; scope identity must match exactly. */
407
+ serializedState(epochSeq, scope) {
408
+ const row = this.db.prepare(`SELECT state_json,state_refs_json FROM runtime_epochs WHERE epoch_seq=?
409
+ AND adapter_id=? AND account_id=? AND session_id=? AND segment_id=?`)
410
+ .get(epochSeq, scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId);
411
+ return typeof row?.state_json === 'string' ? materializeStateJson(this.db, row) : undefined;
412
+ }
381
413
  list(scope, afterEpochSeq = 0, limit = 100) {
382
414
  return this.db.prepare(`
383
415
  SELECT * FROM runtime_epochs
@@ -395,11 +427,46 @@ export class SqliteRuntimeInputJournal {
395
427
  `).all(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, afterEpochSeq, Math.max(1, Math.min(limit, 10_000))).map((row) => this.fromRow(row));
396
428
  }
397
429
  markClosed(epochSeq, closedAt = new Date().toISOString(), durationMs) {
398
- this.db.prepare(`
399
- UPDATE runtime_epochs
400
- SET status = 'closed', closed_at = ?, processing_duration_ms = ?
401
- WHERE epoch_seq = ?
402
- `).run(closedAt, durationMs ?? null, epochSeq);
430
+ this.withTransaction(() => {
431
+ this.db.prepare(`
432
+ UPDATE runtime_epochs
433
+ SET status = 'closed', closed_at = ?, processing_duration_ms = ?
434
+ WHERE epoch_seq = ?
435
+ `).run(closedAt, durationMs ?? null, epochSeq);
436
+ this.pruneCompletedOutcomes(epochSeq);
437
+ });
438
+ }
439
+ registerDiagnosticPolicy(scope, forceFull = false) {
440
+ const window = this.options.completedOutcomeEpochs;
441
+ this.db.prepare(`INSERT INTO runtime_scope_storage_policy(adapter_id,account_id,session_id,segment_id,retain_all,retained_completed_epochs)
442
+ VALUES (?,?,?,?,?,?) ON CONFLICT(adapter_id,account_id,session_id,segment_id) DO UPDATE SET
443
+ retain_all=MAX(retain_all,excluded.retain_all),retained_completed_epochs=MAX(retained_completed_epochs,excluded.retained_completed_epochs)
444
+ WHERE retain_all<excluded.retain_all OR retained_completed_epochs<excluded.retained_completed_epochs`)
445
+ .run(scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId, forceFull || window === undefined || window === 'all' ? 1 : 0, typeof window === 'number' ? window : 256);
446
+ }
447
+ /** Escalation only; switching back to normal diagnostics never discards a full segment. */
448
+ retainCompletedDiagnostics(scope) { this.registerDiagnosticPolicy(scope, true); }
449
+ pruneCompletedOutcomes(epochSeq) {
450
+ if (this.options.completedOutcomeEpochs === undefined || this.options.completedOutcomeEpochs === 'all')
451
+ return;
452
+ const scope = this.db.prepare(`SELECT p.* FROM runtime_epochs e JOIN runtime_scope_storage_policy p
453
+ USING(adapter_id,account_id,session_id,segment_id) WHERE e.epoch_seq=?`).get(epochSeq);
454
+ if (!scope || scope.retain_all || epochSeq - numberValue(scope.last_sweep_epoch) < 64)
455
+ return;
456
+ const args = [scope.adapter_id, scope.account_id, scope.session_id, scope.segment_id];
457
+ const cutoff = this.db.prepare(`SELECT e.epoch_seq FROM runtime_epochs e
458
+ WHERE e.adapter_id=? AND e.account_id=? AND e.session_id=? AND e.segment_id=? AND e.status='closed'
459
+ AND EXISTS(SELECT 1 FROM runtime_plugin_outcomes o WHERE o.epoch_seq=e.epoch_seq)
460
+ ORDER BY e.epoch_seq DESC LIMIT 1 OFFSET ?`).get(...args, scope.retained_completed_epochs);
461
+ let removed = 0;
462
+ if (cutoff)
463
+ removed = numberValue(this.db.prepare(`DELETE FROM runtime_plugin_outcomes WHERE epoch_seq IN
464
+ (SELECT epoch_seq FROM runtime_epochs WHERE adapter_id=? AND account_id=? AND session_id=? AND segment_id=?
465
+ AND status='closed' AND epoch_seq<=?)`).run(...args, cutoff.epoch_seq).changes);
466
+ this.db.prepare(`UPDATE runtime_scope_storage_policy SET last_sweep_epoch=?,
467
+ pruned_through_epoch=MAX(pruned_through_epoch,?),pruned_outcome_rows=pruned_outcome_rows+?
468
+ WHERE adapter_id=? AND account_id=? AND session_id=? AND segment_id=?`)
469
+ .run(epochSeq, cutoff?.epoch_seq ?? 0, removed, ...args);
403
470
  }
404
471
  inputEventsCommitted(epochSeq) {
405
472
  const row = this.db.prepare('SELECT input_events_committed_at FROM runtime_epochs WHERE epoch_seq = ?')
@@ -498,17 +565,11 @@ export class SqliteRuntimeInputJournal {
498
565
  INSERT OR REPLACE INTO runtime_plugin_states(epoch_seq, plugin_id, topic, value_json)
499
566
  VALUES (?, ?, ?, ?)
500
567
  `);
501
- this.db.exec('BEGIN IMMEDIATE');
502
- try {
568
+ this.withTransaction(() => {
503
569
  for (const record of records) {
504
570
  statement.run(record.epochSeq, record.pluginId, record.topic, JSON.stringify(record.value));
505
571
  }
506
- this.db.exec('COMMIT');
507
- }
508
- catch (error) {
509
- this.db.exec('ROLLBACK');
510
- throw error;
511
- }
572
+ });
512
573
  }
513
574
  states(epochSeq) {
514
575
  return this.db.prepare(`
@@ -522,7 +583,7 @@ export class SqliteRuntimeInputJournal {
522
583
  }));
523
584
  }
524
585
  close() {
525
- this.db.close();
586
+ this.release();
526
587
  }
527
588
  /** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
528
589
  snapshot(scope) {
@@ -606,7 +667,7 @@ export class SqliteRuntimeInputJournal {
606
667
  sourceKey: String(row.source_key),
607
668
  ...(row.source_seq_json === null ? {} : { sourceSeq: parseJson(row.source_seq_json) }),
608
669
  ...(row.domain_tick_json === null ? {} : { domainTick: parseJson(row.domain_tick_json) }),
609
- state: parseJson(row.state_json),
670
+ state: parseJson(materializeStateJson(this.db, row)),
610
671
  events: parseJson(row.events_json),
611
672
  ...(row.event_watermark_json === null
612
673
  ? {}
@@ -620,6 +681,7 @@ export class SqliteRuntimeInputJournal {
620
681
  initialize() {
621
682
  this.db.exec(`
622
683
  PRAGMA journal_mode = WAL;
684
+ PRAGMA busy_timeout = 1000;
623
685
  CREATE TABLE IF NOT EXISTS runtime_epochs(
624
686
  epoch_seq INTEGER PRIMARY KEY AUTOINCREMENT,
625
687
  adapter_id TEXT NOT NULL,
@@ -712,5 +774,25 @@ export class SqliteRuntimeInputJournal {
712
774
  if (!progressColumns.has('checkpoint_json')) {
713
775
  this.db.exec('ALTER TABLE runtime_plugin_progress ADD COLUMN checkpoint_json TEXT;');
714
776
  }
777
+ const hadPolicy = !!this.db.prepare("SELECT 1 FROM sqlite_schema WHERE name='runtime_scope_storage_policy' AND type='table'").get();
778
+ const hadPayloads = !!this.db.prepare("SELECT 1 FROM sqlite_schema WHERE name='runtime_state_payloads' AND type='table'").get();
779
+ if (!hadPolicy || !hadPayloads || !epochColumns.has('state_refs_json'))
780
+ this.withTransaction(() => {
781
+ if (!epochColumns.has('state_refs_json'))
782
+ this.db.exec('ALTER TABLE runtime_epochs ADD COLUMN state_refs_json TEXT');
783
+ this.db.exec(`CREATE TABLE IF NOT EXISTS runtime_state_payloads(payload_id TEXT PRIMARY KEY, body_json TEXT NOT NULL);
784
+ CREATE TABLE IF NOT EXISTS runtime_scope_storage_policy(
785
+ adapter_id TEXT NOT NULL,account_id TEXT NOT NULL,session_id TEXT NOT NULL,segment_id TEXT NOT NULL,
786
+ retain_all INTEGER NOT NULL,retained_completed_epochs INTEGER NOT NULL,
787
+ last_sweep_epoch INTEGER NOT NULL DEFAULT 0,pruned_through_epoch INTEGER NOT NULL DEFAULT 0,
788
+ pruned_outcome_rows INTEGER NOT NULL DEFAULT 0,
789
+ PRIMARY KEY(adapter_id,account_id,session_id,segment_id)
790
+ );`);
791
+ // Earlier versions did not record the effective detail policy. Never infer it retrospectively.
792
+ if (!hadPolicy)
793
+ this.db.exec(`INSERT OR IGNORE INTO runtime_scope_storage_policy
794
+ (adapter_id,account_id,session_id,segment_id,retain_all,retained_completed_epochs)
795
+ SELECT DISTINCT adapter_id,account_id,session_id,segment_id,1,256 FROM runtime_epochs`);
796
+ });
715
797
  }
716
798
  }
@@ -191,7 +191,10 @@ export class Runtime {
191
191
  }
192
192
  else if (options.stateHistoryPath) {
193
193
  try {
194
- this.stateHistoryRepository = new SqliteStateHistoryRepository(options.stateHistoryPath);
194
+ this.stateHistoryRepository = new SqliteStateHistoryRepository(options.stateHistoryPath, {
195
+ serializedState: (epoch, scope) => this.inputJournal instanceof SqliteRuntimeInputJournal
196
+ ? this.inputJournal.serializedState(epoch, scope) : undefined,
197
+ });
195
198
  historyPersistence = 'sqlite';
196
199
  }
197
200
  catch (error) {
@@ -1,10 +1,16 @@
1
1
  import { type RuntimeScope } from '../types.js';
2
2
  import type { AppendHistoryResult, AppendStateFrameResult, HistoryQuery, HistoryQueryResult, HistoryScopeRecord, StateFrameQuery, StateFrameQueryResult, StateFrameRecord, StateHistoryRepository, StateHistorySnapshot, StoredStateFrame, TrajectoryRecord } from './contracts.js';
3
+ export interface StateHistoryReferenceOptions {
4
+ /** Only enable when the input journal is durably written before the history row. */
5
+ serializedState?: (epochSeq: number, scope: RuntimeScope) => string | undefined;
6
+ }
3
7
  export declare class SqliteStateHistoryRepository<TPosition = unknown, TState = Record<string, unknown>> implements StateHistoryRepository<TPosition, TState> {
8
+ private readonly references;
4
9
  private readonly db;
10
+ private readonly release;
5
11
  private readonly recentStateFrames;
6
12
  static isSupported(): boolean;
7
- constructor(path: string);
13
+ constructor(path: string, references?: StateHistoryReferenceOptions);
8
14
  openScope(scope: RuntimeScope, openedAtMs?: number, historyComplete?: boolean): HistoryScopeRecord;
9
15
  sealScope(scope: RuntimeScope, sealedAtMs?: number): void;
10
16
  markScopeIncomplete(scope: RuntimeScope): void;