@saturn-universe/storage 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,157 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { setTimeout as delay } from 'node:timers/promises';
6
+ import { RuntimeError, validateArtifactRef } from '@saturn-universe/core';
7
+ const artifactKeys = ['artifactId', 'sha256', 'mediaType', 'byteLength'];
8
+ const directoryRenameRetryMs = [25, 50, 100, 200];
9
+ export const artifactObjectsDirectory = 'sha256';
10
+ export async function claimArtifactDirectory(destination, operation) {
11
+ try {
12
+ await mkdir(destination);
13
+ }
14
+ catch (error) {
15
+ if (error.code === 'EEXIST' || existsSync(destination))
16
+ throw new RuntimeError('DESTINATION_EXISTS', `${operation} destination exists`);
17
+ throw error;
18
+ }
19
+ }
20
+ export async function publishArtifactDirectory(source, destination) {
21
+ for (let attempt = 0;; attempt++) {
22
+ try {
23
+ await rename(source, destination);
24
+ return;
25
+ }
26
+ catch (error) {
27
+ const wait = directoryRenameRetryMs[attempt];
28
+ // Windows can reject a directory move briefly while a file inside it is still open.
29
+ if (process.platform !== 'win32' ||
30
+ error?.code !== 'EPERM' ||
31
+ wait === undefined ||
32
+ existsSync(destination)) {
33
+ throw error;
34
+ }
35
+ await delay(wait);
36
+ if (existsSync(destination))
37
+ throw error;
38
+ }
39
+ }
40
+ }
41
+ export class LocalArtifactStore {
42
+ root;
43
+ objectsRoot;
44
+ constructor(root) {
45
+ this.root = path.resolve(root);
46
+ this.objectsRoot = path.join(this.root, artifactObjectsDirectory);
47
+ }
48
+ async put(content, mediaType) {
49
+ if (!(content instanceof Uint8Array))
50
+ throw new RuntimeError('ARTIFACT_INPUT_INVALID', 'artifact content must be Uint8Array');
51
+ if (!Number.isSafeInteger(content.byteLength) || content.byteLength < 0)
52
+ throw new RuntimeError('ARTIFACT_INPUT_INVALID', 'artifact byteLength is invalid');
53
+ if (typeof mediaType !== 'string' ||
54
+ mediaType.length === 0 ||
55
+ mediaType.length > 200 ||
56
+ /\s/.test(mediaType))
57
+ throw new RuntimeError('ARTIFACT_INPUT_INVALID', 'artifact mediaType is invalid');
58
+ const bytes = new Uint8Array(content);
59
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
60
+ const ref = validateArtifactRef({
61
+ artifactId: `sha256:${sha256}`,
62
+ sha256,
63
+ mediaType,
64
+ byteLength: bytes.byteLength,
65
+ });
66
+ const target = this.pathFor(ref);
67
+ await mkdir(this.objectsRoot, { recursive: true });
68
+ try {
69
+ await this.read(ref);
70
+ return ref;
71
+ }
72
+ catch (error) {
73
+ if (!(error instanceof RuntimeError) || error.code !== 'ARTIFACT_NOT_FOUND')
74
+ throw error;
75
+ }
76
+ const temporary = path.join(this.objectsRoot, `.tmp-${randomUUID()}`);
77
+ let ownsTemporary = false;
78
+ try {
79
+ const file = await open(temporary, 'wx');
80
+ ownsTemporary = true;
81
+ await file.writeFile(bytes).finally(() => file.close());
82
+ try {
83
+ await rename(temporary, target);
84
+ ownsTemporary = false;
85
+ }
86
+ catch (error) {
87
+ if (!isAlreadyExists(error))
88
+ throw error;
89
+ await this.read(ref);
90
+ }
91
+ return ref;
92
+ }
93
+ catch (error) {
94
+ if (error instanceof RuntimeError)
95
+ throw error;
96
+ throw new RuntimeError('ARTIFACT_WRITE_FAILED', error instanceof Error ? error.message : 'artifact write failed');
97
+ }
98
+ finally {
99
+ if (ownsTemporary)
100
+ await unlink(temporary).catch(() => undefined);
101
+ }
102
+ }
103
+ async read(value) {
104
+ const ref = validateArtifactRef(value);
105
+ let bytes;
106
+ try {
107
+ bytes = await readFile(this.pathFor(ref));
108
+ }
109
+ catch (error) {
110
+ if (isMissing(error))
111
+ throw new RuntimeError('ARTIFACT_NOT_FOUND', 'artifact object is missing');
112
+ throw new RuntimeError('ARTIFACT_READ_FAILED', error instanceof Error ? error.message : 'artifact read failed');
113
+ }
114
+ if (bytes.byteLength !== ref.byteLength)
115
+ throw new RuntimeError('ARTIFACT_CORRUPT', 'artifact byteLength mismatch');
116
+ if (createHash('sha256').update(bytes).digest('hex') !== ref.sha256)
117
+ throw new RuntimeError('ARTIFACT_CORRUPT', 'artifact sha256 mismatch');
118
+ return new Uint8Array(bytes);
119
+ }
120
+ pathFor(value) {
121
+ const ref = validateArtifactRef(value);
122
+ return path.join(this.objectsRoot, ref.sha256);
123
+ }
124
+ }
125
+ export function createArtifactStore(root) {
126
+ return new LocalArtifactStore(root);
127
+ }
128
+ export function collectArtifactRefs(value) {
129
+ const refs = new Map();
130
+ const visit = (current) => {
131
+ if (!current || typeof current !== 'object')
132
+ return;
133
+ if (artifactKeys.every((key) => Object.prototype.hasOwnProperty.call(current, key))) {
134
+ const ref = validateArtifactRef(current);
135
+ refs.set(artifactRefKey(ref), ref);
136
+ return;
137
+ }
138
+ for (const child of Object.values(current))
139
+ visit(child);
140
+ };
141
+ visit(value);
142
+ return [...refs.values()].sort((a, b) => artifactRefKey(a).localeCompare(artifactRefKey(b)));
143
+ }
144
+ export function artifactRefKey(ref) {
145
+ return JSON.stringify([ref.artifactId, ref.sha256, ref.mediaType, ref.byteLength]);
146
+ }
147
+ export const artifactBundleDirectory = 'artifacts';
148
+ export function artifactBundlePath(ref) {
149
+ const checked = validateArtifactRef(ref);
150
+ return path.posix.join(artifactBundleDirectory, artifactObjectsDirectory, checked.sha256);
151
+ }
152
+ function isMissing(error) {
153
+ return Boolean(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT');
154
+ }
155
+ function isAlreadyExists(error) {
156
+ return Boolean(error && typeof error === 'object' && 'code' in error && ['EEXIST', 'EPERM'].includes(String(error.code)));
157
+ }
@@ -0,0 +1,32 @@
1
+ import type { ArtifactRef, EventPosition } from '@saturn-universe/core';
2
+ export declare function hashBackupDatabase(filename: string): Promise<string>;
3
+ export declare function backupPaths(databasePath: string): {
4
+ manifestPath: string;
5
+ markerPath: string;
6
+ bundlePath: string;
7
+ };
8
+ export declare function writeBackupManifest(manifestPath: string, markerPath: string, { through, eventCount, integrity, stateDigest, databaseSha256, artifacts }: BackupManifestInput): Promise<void>;
9
+ export declare function readBackupManifest(databasePath: string): Promise<{
10
+ manifest: BackupManifest;
11
+ bundlePath: string;
12
+ }>;
13
+ interface BackupArtifactEntry extends ArtifactRef {
14
+ readonly path: string;
15
+ }
16
+ export interface BackupManifest {
17
+ readonly through: EventPosition;
18
+ readonly eventCount: number;
19
+ readonly stateDigest: string;
20
+ readonly databaseSha256: string;
21
+ readonly artifactCoverage: 'complete' | 'no_artifacts_referenced';
22
+ readonly artifacts: readonly BackupArtifactEntry[];
23
+ }
24
+ export interface BackupManifestInput extends Pick<BackupManifest, 'through' | 'eventCount' | 'databaseSha256' | 'stateDigest'> {
25
+ readonly artifacts: readonly ArtifactRef[];
26
+ readonly integrity: {
27
+ readonly sqliteVersion: string;
28
+ readonly quickCheck: string;
29
+ readonly compileOptions: readonly unknown[];
30
+ };
31
+ }
32
+ export {};
@@ -0,0 +1,138 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { readFile, writeFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { isEventPosition, RuntimeError, validateArtifactRef } from '@saturn-universe/core';
6
+ import { artifactBundlePath, artifactRefKey } from './artifacts.js';
7
+ const currentBackupManifestVersion = 3;
8
+ const completionMarkerVersion = 1;
9
+ const sha256Pattern = /^[a-f0-9]{64}$/;
10
+ export async function hashBackupDatabase(filename) {
11
+ const hash = createHash('sha256');
12
+ for await (const chunk of createReadStream(filename))
13
+ hash.update(chunk);
14
+ return hash.digest('hex');
15
+ }
16
+ export function backupPaths(databasePath) {
17
+ return {
18
+ manifestPath: databasePath + '.manifest.json',
19
+ markerPath: databasePath + '.complete',
20
+ bundlePath: databasePath + '.artifacts',
21
+ };
22
+ }
23
+ function completionMarker(bytes) {
24
+ return {
25
+ version: completionMarkerVersion,
26
+ manifestSha256: createHash('sha256').update(bytes).digest('hex'),
27
+ };
28
+ }
29
+ export async function writeBackupManifest(manifestPath, markerPath, { through, eventCount, integrity, stateDigest, databaseSha256, artifacts }) {
30
+ const manifest = {
31
+ version: currentBackupManifestVersion,
32
+ through,
33
+ eventCount,
34
+ integrity,
35
+ stateDigest,
36
+ databaseSha256,
37
+ artifactCoverage: coverageForArtifacts(artifacts),
38
+ artifacts: artifacts.map((ref) => ({ ...ref, path: artifactBundlePath(ref) })),
39
+ externalEffectsRestored: false,
40
+ };
41
+ const bytes = Buffer.from(JSON.stringify(manifest, null, 2) + '\n', 'utf8');
42
+ await writeFile(manifestPath, bytes, { flag: 'wx' });
43
+ await writeFile(markerPath, JSON.stringify(completionMarker(bytes)) + '\n', {
44
+ encoding: 'utf8',
45
+ flag: 'wx',
46
+ });
47
+ }
48
+ export async function readBackupManifest(databasePath) {
49
+ const { manifestPath, markerPath, bundlePath } = backupPaths(databasePath);
50
+ const manifestBytes = await readFile(manifestPath).catch(() => {
51
+ throw new RuntimeError('INVALID_BACKUP', 'backup manifest is unreadable');
52
+ });
53
+ const { declaredCoverage, entries, ...metadata } = decodeManifest(manifestBytes);
54
+ await verifyCompletionMarker(markerPath, manifestBytes);
55
+ const artifacts = parseManifestArtifacts(entries);
56
+ const artifactCoverage = coverageForArtifacts(artifacts);
57
+ if (declaredCoverage !== artifactCoverage) {
58
+ if (declaredCoverage === 'complete')
59
+ throw new RuntimeError('INVALID_BACKUP', 'complete artifact backup has no artifact entries');
60
+ if (declaredCoverage === 'no_artifacts_referenced')
61
+ throw new RuntimeError('INVALID_BACKUP', 'artifact manifest coverage is inconsistent');
62
+ throw new RuntimeError('INVALID_BACKUP', 'unsupported artifact coverage');
63
+ }
64
+ const manifest = { ...metadata, artifactCoverage, artifacts };
65
+ return { manifest, bundlePath };
66
+ }
67
+ function coverageForArtifacts(artifacts) {
68
+ return artifacts.length ? 'complete' : 'no_artifacts_referenced';
69
+ }
70
+ async function verifyCompletionMarker(filename, manifestBytes) {
71
+ let value;
72
+ try {
73
+ value = JSON.parse(await readFile(filename, 'utf8'));
74
+ }
75
+ catch {
76
+ throw new RuntimeError('INVALID_BACKUP', 'backup completion marker is unreadable');
77
+ }
78
+ if (!value ||
79
+ typeof value !== 'object' ||
80
+ value.version !== completionMarkerVersion ||
81
+ value.manifestSha256 !== completionMarker(manifestBytes).manifestSha256)
82
+ throw new RuntimeError('INVALID_BACKUP', 'backup completion marker does not match manifest');
83
+ }
84
+ function decodeManifest(bytes) {
85
+ let value;
86
+ try {
87
+ value = JSON.parse(bytes.toString('utf8'));
88
+ }
89
+ catch {
90
+ throw new RuntimeError('INVALID_BACKUP', 'backup manifest is unreadable');
91
+ }
92
+ if (!value || typeof value !== 'object')
93
+ throw new RuntimeError('INVALID_BACKUP', 'backup manifest is not an object');
94
+ const { version, through, eventCount, databaseSha256, stateDigest, externalEffectsRestored, artifactCoverage: declaredCoverage, artifacts: entries, } = value;
95
+ if (version !== currentBackupManifestVersion)
96
+ throw new RuntimeError('INVALID_BACKUP', 'unsupported backup manifest version');
97
+ if (!isEventPosition(through) ||
98
+ typeof eventCount !== 'number' ||
99
+ !Number.isSafeInteger(eventCount) ||
100
+ eventCount < 0 ||
101
+ typeof databaseSha256 !== 'string' ||
102
+ !sha256Pattern.test(databaseSha256) ||
103
+ externalEffectsRestored !== false ||
104
+ typeof declaredCoverage !== 'string')
105
+ throw new RuntimeError('INVALID_BACKUP', 'backup manifest schema mismatch');
106
+ if (typeof stateDigest !== 'string' || !sha256Pattern.test(stateDigest))
107
+ throw new RuntimeError('INVALID_BACKUP', 'backup state digest is missing or invalid');
108
+ return {
109
+ through,
110
+ eventCount,
111
+ databaseSha256,
112
+ stateDigest,
113
+ declaredCoverage,
114
+ entries,
115
+ };
116
+ }
117
+ function parseManifestArtifacts(values) {
118
+ if (!Array.isArray(values))
119
+ throw new RuntimeError('INVALID_BACKUP', 'backup manifest artifact list is missing');
120
+ const entries = values.map((value) => {
121
+ if (!value || typeof value !== 'object')
122
+ throw new RuntimeError('INVALID_BACKUP', 'invalid artifact manifest entry');
123
+ const entry = value;
124
+ const ref = validateArtifactRef(entry);
125
+ if (typeof entry.path !== 'string' ||
126
+ path.posix.isAbsolute(entry.path) ||
127
+ entry.path.includes('\\') ||
128
+ entry.path.split('/').some((part) => part === '..' || part === ''))
129
+ throw new RuntimeError('INVALID_BACKUP', 'invalid artifact manifest path');
130
+ if (entry.path !== artifactBundlePath(ref))
131
+ throw new RuntimeError('INVALID_BACKUP', 'artifact path does not match its content address');
132
+ return { ...ref, path: entry.path };
133
+ });
134
+ const keys = new Set(entries.map((entry) => artifactRefKey(entry)));
135
+ if (keys.size !== entries.length)
136
+ throw new RuntimeError('INVALID_BACKUP', 'duplicate artifact manifest entry');
137
+ return entries;
138
+ }
@@ -0,0 +1,2 @@
1
+ import type { Database } from './driver.js';
2
+ export declare function initializeDatabaseSchema(database: Database): boolean;
@@ -0,0 +1,36 @@
1
+ import { RuntimeError } from '@saturn-universe/core';
2
+ import { canonicalDigest } from './integrity.js';
3
+ import { migration } from './migration.js';
4
+ import { teamProjectionMigration } from './team-migration.js';
5
+ // The current format retains both ledger rows. Connection settings belong to the worker.
6
+ const schemaLedger = [
7
+ [1, migration],
8
+ [2, teamProjectionMigration],
9
+ ].map(([version, sql]) => ({
10
+ version,
11
+ checksum: canonicalDigest(sql),
12
+ sql: version === 1 ? sql.replace(/^PRAGMA .*;\n/gm, '') : sql,
13
+ }));
14
+ // The caller holds a write transaction through schema initialization and lease acquisition.
15
+ export function initializeDatabaseSchema(database) {
16
+ const initialized = Boolean(database.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='schema_migrations'").get());
17
+ if (initialized) {
18
+ const applied = database.prepare('SELECT version,checksum FROM schema_migrations ORDER BY version').all();
19
+ if (applied.length !== schemaLedger.length ||
20
+ schemaLedger.some(({ version, checksum }, index) => {
21
+ const record = applied[index];
22
+ return record.version !== version || record.checksum !== checksum;
23
+ })) {
24
+ throw new RuntimeError('MIGRATION_REQUIRED', 'unsupported schema version or checksum');
25
+ }
26
+ return false;
27
+ }
28
+ if (database.prepare('SELECT 1 FROM sqlite_schema LIMIT 1').get())
29
+ throw new RuntimeError('MIGRATION_REQUIRED', 'database has no Saturn schema ledger');
30
+ database.exec(schemaLedger.map(({ sql }) => sql).join('\n'));
31
+ const record = database.prepare('INSERT INTO schema_migrations (version,checksum,applied_at) VALUES(?,?,?)');
32
+ const appliedAt = new Date().toISOString();
33
+ for (const { version, checksum } of schemaLedger)
34
+ record.run(version, checksum, appliedAt);
35
+ return true;
36
+ }
@@ -0,0 +1,27 @@
1
+ export type Row = Record<string, string | number | bigint | null>;
2
+ export type SqlValue = string | number | bigint | null;
3
+ export interface Statement {
4
+ run(...values: SqlValue[]): {
5
+ lastInsertRowid: number | bigint;
6
+ changes: number;
7
+ };
8
+ get(...values: SqlValue[]): Row | undefined;
9
+ all(...values: SqlValue[]): Row[];
10
+ iterate(...values: SqlValue[]): IterableIterator<Row>;
11
+ safeIntegers(value?: boolean): Statement;
12
+ }
13
+ export interface Database {
14
+ prepare(sql: string): Statement;
15
+ exec(sql: string): void;
16
+ pragma(sql: string): unknown;
17
+ transaction<T>(fn: () => T): {
18
+ (): T;
19
+ immediate(): T;
20
+ };
21
+ backup(destination: string): Promise<unknown>;
22
+ close(): void;
23
+ }
24
+ export declare const Sqlite: new (path: string, options?: {
25
+ readonly?: boolean;
26
+ fileMustExist?: boolean;
27
+ }) => Database;
package/dist/driver.js ADDED
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'node:module';
2
+ export const Sqlite = createRequire(import.meta.url)('better-sqlite3');
@@ -0,0 +1,8 @@
1
+ import type { SqliteStore, SqliteStoreOptions } from './store.js';
2
+ export type { RunDetails } from './queries.js';
3
+ export type { SessionExportPage, SessionExportRecord } from '@saturn-universe/core';
4
+ export type { SessionDetails, SessionListItem, SessionUsageBucket, SessionUsageSummary, } from '@saturn-universe/core';
5
+ export { restoreSqliteBackup } from './restore.js';
6
+ export { LocalArtifactStore, createArtifactStore, collectArtifactRefs, artifactBundlePath, } from './artifacts.js';
7
+ export type { SqliteStore } from './store.js';
8
+ export declare const openSqliteStore: (options: SqliteStoreOptions) => Promise<SqliteStore>;
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { openSqliteWorkerStore } from './store.js';
2
+ export { restoreSqliteBackup } from './restore.js';
3
+ export { LocalArtifactStore, createArtifactStore, collectArtifactRefs, artifactBundlePath, } from './artifacts.js';
4
+ export const openSqliteStore = openSqliteWorkerStore;
@@ -0,0 +1 @@
1
+ export declare function canonicalDigest(value: unknown): string;
@@ -0,0 +1,5 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonicalJson } from '@saturn-universe/core';
3
+ export function canonicalDigest(value) {
4
+ return createHash('sha256').update(canonicalJson(value)).digest('hex');
5
+ }
@@ -0,0 +1 @@
1
+ export declare const migration = "PRAGMA foreign_keys = ON;\nPRAGMA journal_mode = WAL;\nPRAGMA synchronous = FULL;\nPRAGMA busy_timeout = 5000;\n\nCREATE TABLE schema_migrations (\n version INTEGER PRIMARY KEY,\n checksum TEXT NOT NULL,\n applied_at TEXT NOT NULL\n) STRICT;\n\nCREATE TABLE events (\n position INTEGER PRIMARY KEY AUTOINCREMENT CHECK(position > 0),\n event_id TEXT NOT NULL UNIQUE,\n envelope_version INTEGER NOT NULL CHECK(envelope_version = 1),\n event_type TEXT NOT NULL,\n event_version INTEGER NOT NULL CHECK(event_version >= 1),\n workspace_id TEXT NOT NULL,\n scope_kind TEXT NOT NULL CHECK(scope_kind IN ('workspace','session','run','agent_session')),\n session_id TEXT,\n run_id TEXT,\n agent_id TEXT,\n agent_session_id TEXT,\n stream_id TEXT NOT NULL,\n stream_seq INTEGER NOT NULL CHECK(stream_seq > 0),\n occurred_at TEXT NOT NULL,\n recorded_at TEXT NOT NULL,\n correlation_id TEXT NOT NULL,\n causation_id TEXT,\n command_id TEXT NOT NULL,\n command_hash TEXT NOT NULL,\n command_event_index INTEGER NOT NULL CHECK(command_event_index >= 0),\n command_event_count INTEGER NOT NULL CHECK(command_event_count > command_event_index),\n actor_json TEXT NOT NULL CHECK(json_valid(actor_json)),\n traceparent TEXT,\n links_json TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(links_json)),\n payload_json TEXT NOT NULL CHECK(json_valid(payload_json)),\n UNIQUE(scope_kind, stream_id, stream_seq),\n UNIQUE(command_id, command_event_index),\n CHECK (\n (scope_kind='workspace' AND stream_id=workspace_id AND session_id IS NULL\n AND run_id IS NULL AND agent_id IS NULL AND agent_session_id IS NULL)\n OR (scope_kind='session' AND stream_id=session_id AND session_id IS NOT NULL\n AND run_id IS NULL AND agent_id IS NULL AND agent_session_id IS NULL)\n OR (scope_kind='run' AND stream_id=run_id AND session_id IS NOT NULL\n AND run_id IS NOT NULL AND agent_id IS NULL AND agent_session_id IS NULL)\n OR (scope_kind='agent_session' AND stream_id=agent_session_id\n AND agent_id IS NOT NULL AND agent_session_id IS NOT NULL\n AND (run_id IS NULL OR session_id IS NOT NULL))\n )\n) STRICT;\nCREATE INDEX events_session_position ON events(session_id, position) WHERE session_id IS NOT NULL;\nCREATE INDEX events_run_position ON events(run_id, position) WHERE run_id IS NOT NULL;\nCREATE INDEX events_agent_session_position ON events(agent_session_id, position) WHERE agent_session_id IS NOT NULL;\nCREATE INDEX events_correlation_position ON events(correlation_id, position);\nCREATE INDEX events_causation ON events(causation_id) WHERE causation_id IS NOT NULL;\nCREATE INDEX events_type_position ON events(event_type, position);\nCREATE TRIGGER events_no_update BEFORE UPDATE ON events BEGIN\n SELECT RAISE(ABORT, 'events are append-only');\nEND;\nCREATE TRIGGER events_no_delete BEFORE DELETE ON events BEGIN\n SELECT RAISE(ABORT, 'events are append-only');\nEND;\n\nCREATE TABLE event_streams (\n scope_kind TEXT NOT NULL,\n stream_id TEXT NOT NULL,\n last_seq INTEGER NOT NULL CHECK(last_seq >= 0),\n PRIMARY KEY(scope_kind, stream_id)\n) STRICT;\nCREATE TABLE command_receipts (\n command_id TEXT PRIMARY KEY,\n command_hash TEXT NOT NULL,\n event_count INTEGER NOT NULL CHECK(event_count > 0),\n first_position INTEGER NOT NULL REFERENCES events(position),\n last_position INTEGER NOT NULL REFERENCES events(position)\n) STRICT;\nCREATE TABLE host_leases (\n singleton INTEGER PRIMARY KEY CHECK(singleton=1),\n epoch INTEGER NOT NULL CHECK(epoch > 0),\n owner_instance_id TEXT NOT NULL,\n acquired_at TEXT NOT NULL\n) STRICT;\n\nCREATE TABLE projection_generations (\n generation INTEGER PRIMARY KEY,\n status TEXT NOT NULL CHECK(status IN ('building','active','retired')),\n through_position INTEGER NOT NULL CHECK(through_position >= 0),\n versions_json TEXT NOT NULL CHECK(json_valid(versions_json)),\n digest TEXT\n) STRICT;\nCREATE UNIQUE INDEX one_active_generation ON projection_generations(status) WHERE status='active';\nCREATE TABLE projection_meta (\n singleton INTEGER PRIMARY KEY CHECK(singleton=1),\n active_generation INTEGER NOT NULL REFERENCES projection_generations(generation)\n) STRICT;\nCREATE TABLE projection_checkpoints (\n generation INTEGER NOT NULL REFERENCES projection_generations(generation),\n projection_name TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n projection_version INTEGER NOT NULL CHECK(projection_version > 0),\n last_stream_seq INTEGER NOT NULL CHECK(last_stream_seq >= 0),\n last_position INTEGER NOT NULL CHECK(last_position >= 0),\n PRIMARY KEY(generation, projection_name, scope_key)\n) STRICT;\n\nCREATE TABLE workspaces (\n generation INTEGER NOT NULL REFERENCES projection_generations(generation),\n workspace_id TEXT NOT NULL,\n root_uri TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('open','archived')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, workspace_id)\n) STRICT;\nCREATE TABLE sessions (\n generation INTEGER NOT NULL,\n session_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n title TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('open','archived')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, session_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id)\n) STRICT;\nCREATE INDEX sessions_workspace ON sessions(generation, workspace_id, created_at);\nCREATE TABLE agents (\n generation INTEGER NOT NULL,\n agent_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('main','worker','specialist')),\n default_scope TEXT NOT NULL CHECK(default_scope IN ('run','session','project')),\n mode_ref TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, agent_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id)\n) STRICT;\nCREATE TABLE runs (\n generation INTEGER NOT NULL,\n run_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n input_message_id TEXT NOT NULL,\n working_directory_uri TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('created','running','paused','cancelling','completed','failed','cancelled')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, run_id),\n FOREIGN KEY(generation, session_id) REFERENCES sessions(generation, session_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id)\n) STRICT;\nCREATE INDEX runs_session_status ON runs(generation, session_id, status, created_at);\nCREATE TABLE agent_sessions (\n generation INTEGER NOT NULL,\n agent_session_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n owner_kind TEXT NOT NULL CHECK(owner_kind IN ('run','session','project')),\n owner_session_id TEXT,\n owner_run_id TEXT,\n status TEXT NOT NULL CHECK(status IN ('open','archived')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, agent_session_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id),\n FOREIGN KEY(generation, agent_id) REFERENCES agents(generation, agent_id),\n FOREIGN KEY(generation, owner_session_id) REFERENCES sessions(generation, session_id),\n FOREIGN KEY(generation, owner_run_id) REFERENCES runs(generation, run_id),\n CHECK((owner_kind='project' AND owner_session_id IS NULL AND owner_run_id IS NULL)\n OR (owner_kind='session' AND owner_session_id IS NOT NULL AND owner_run_id IS NULL)\n OR (owner_kind='run' AND owner_session_id IS NOT NULL AND owner_run_id IS NOT NULL))\n) STRICT;\nCREATE INDEX agent_sessions_owner ON agent_sessions(generation, owner_kind, owner_session_id, owner_run_id);\nCREATE INDEX agent_sessions_agent ON agent_sessions(generation, agent_id, status);\nCREATE TABLE session_agent_bindings (\n generation INTEGER NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('main','participant')),\n PRIMARY KEY(generation, session_id, agent_session_id),\n FOREIGN KEY(generation, session_id) REFERENCES sessions(generation, session_id),\n FOREIGN KEY(generation, agent_id) REFERENCES agents(generation, agent_id),\n FOREIGN KEY(generation, agent_session_id) REFERENCES agent_sessions(generation, agent_session_id)\n) STRICT;\nCREATE UNIQUE INDEX one_main_per_session ON session_agent_bindings(generation, session_id) WHERE role='main';\nCREATE TABLE run_agents (\n generation INTEGER NOT NULL,\n run_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('main','worker')),\n config_json TEXT NOT NULL CHECK(json_valid(config_json)),\n PRIMARY KEY(generation, run_id, agent_session_id),\n FOREIGN KEY(generation, run_id) REFERENCES runs(generation, run_id),\n FOREIGN KEY(generation, agent_id) REFERENCES agents(generation, agent_id),\n FOREIGN KEY(generation, agent_session_id) REFERENCES agent_sessions(generation, agent_session_id)\n) STRICT;\nCREATE UNIQUE INDEX one_main_per_run ON run_agents(generation, run_id) WHERE role='main';\nCREATE TABLE agent_session_occupancy (\n generation INTEGER NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n PRIMARY KEY(generation, agent_session_id),\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id)\n) STRICT;\n\nCREATE TABLE turns (\n generation INTEGER NOT NULL,\n turn_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n input_message_id TEXT NOT NULL,\n ordinal INTEGER NOT NULL CHECK(ordinal > 0),\n status TEXT NOT NULL CHECK(status IN ('queued','running','paused','completed','failed','interrupted')),\n terminal_json TEXT CHECK(terminal_json IS NULL OR json_valid(terminal_json)),\n PRIMARY KEY(generation, turn_id),\n UNIQUE(generation, agent_session_id, ordinal),\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id)\n) STRICT;\nCREATE UNIQUE INDEX one_live_turn_per_stream ON turns(generation, agent_session_id)\n WHERE status IN ('queued','running','paused');\nCREATE TABLE steps (\n generation INTEGER NOT NULL,\n step_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n ordinal INTEGER NOT NULL CHECK(ordinal > 0),\n kind TEXT NOT NULL CHECK(kind IN ('model','tool','runtime')),\n status TEXT NOT NULL CHECK(status IN ('running','completed','failed','interrupted')),\n error_json TEXT CHECK(error_json IS NULL OR json_valid(error_json)),\n PRIMARY KEY(generation, step_id),\n UNIQUE(generation, turn_id, ordinal),\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id)\n) STRICT;\nCREATE TABLE run_states (\n generation INTEGER NOT NULL,\n run_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('created','running','paused','cancelling','completed','failed','cancelled')),\n pause_reason TEXT CHECK(pause_reason IS NULL OR pause_reason IN ('approval','tool_outcome_unknown','recovery_review')),\n last_run_seq INTEGER NOT NULL CHECK(last_run_seq >= 0),\n through_position INTEGER NOT NULL CHECK(through_position >= 0),\n model_attempts INTEGER NOT NULL CHECK(model_attempts >= 0),\n tool_calls_started INTEGER NOT NULL CHECK(tool_calls_started >= 0),\n steps_started INTEGER NOT NULL CHECK(steps_started >= 0),\n reserved_tokens INTEGER NOT NULL CHECK(reserved_tokens >= 0),\n usage_json TEXT NOT NULL CHECK(json_valid(usage_json)),\n active_turn_ids_json TEXT NOT NULL CHECK(json_valid(active_turn_ids_json)),\n blocked_turn_ids_json TEXT NOT NULL CHECK(json_valid(blocked_turn_ids_json)),\n unresolved_call_ids_json TEXT NOT NULL CHECK(json_valid(unresolved_call_ids_json)),\n deadline_at TEXT,\n PRIMARY KEY(generation, run_id),\n FOREIGN KEY(generation, run_id) REFERENCES runs(generation, run_id)\n) STRICT;\n\nCREATE TABLE session_messages (\n generation INTEGER NOT NULL,\n message_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('user','assistant','tool')),\n source_event_id TEXT NOT NULL REFERENCES events(event_id),\n order_seq INTEGER NOT NULL CHECK(order_seq > 0),\n order_part INTEGER NOT NULL CHECK(order_part >= 0),\n active INTEGER NOT NULL CHECK(active IN (0,1)),\n superseded_by TEXT REFERENCES events(event_id),\n message_json TEXT NOT NULL CHECK(json_valid(message_json)),\n PRIMARY KEY(generation, message_id),\n FOREIGN KEY(generation, agent_session_id) REFERENCES agent_sessions(generation, agent_session_id),\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id),\n FOREIGN KEY(generation, run_id) REFERENCES runs(generation, run_id),\n CHECK((active=1 AND superseded_by IS NULL) OR (active=0 AND superseded_by IS NOT NULL))\n) STRICT;\nCREATE UNIQUE INDEX surface_active_order ON session_messages(generation, agent_session_id, order_seq, order_part) WHERE active=1;\nCREATE INDEX messages_surface ON session_messages(generation, agent_session_id, active, order_seq, order_part);\nCREATE TABLE tool_calls (\n generation INTEGER NOT NULL,\n tool_call_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n assistant_message_id TEXT NOT NULL,\n provider_call_id TEXT NOT NULL,\n call_index INTEGER NOT NULL CHECK(call_index >= 0),\n execution_key TEXT NOT NULL,\n policy_version TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('requested','waiting_approval','running','retry_wait','outcome_unknown','settled')),\n call_json TEXT NOT NULL CHECK(json_valid(call_json)),\n definition_json TEXT CHECK(definition_json IS NULL OR json_valid(definition_json)),\n result_message_id TEXT,\n result_json TEXT CHECK(result_json IS NULL OR json_valid(result_json)),\n PRIMARY KEY(generation, tool_call_id),\n UNIQUE(generation, assistant_message_id, call_index),\n UNIQUE(generation, assistant_message_id, provider_call_id),\n UNIQUE(generation, execution_key),\n UNIQUE(generation, result_message_id),\n FOREIGN KEY(generation, assistant_message_id) REFERENCES session_messages(generation, message_id),\n FOREIGN KEY(generation, result_message_id) REFERENCES session_messages(generation, message_id) DEFERRABLE INITIALLY DEFERRED,\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id),\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id),\n CHECK((status='settled' AND result_message_id IS NOT NULL AND result_json IS NOT NULL)\n OR (status<>'settled' AND result_message_id IS NULL AND result_json IS NULL))\n) STRICT;\nCREATE INDEX calls_pending ON tool_calls(generation, run_id, status);\nCREATE INDEX calls_stream_pending ON tool_calls(generation, agent_session_id, status);\nCREATE TABLE tool_executions (\n generation INTEGER NOT NULL,\n attempt_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n step_id TEXT NOT NULL,\n attempt_number INTEGER NOT NULL CHECK(attempt_number > 0),\n execution_key TEXT NOT NULL,\n executor_instance_id TEXT NOT NULL,\n host_epoch INTEGER NOT NULL CHECK(host_epoch > 0),\n started_at TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('running','completed','failed','outcome_unknown','reconciled')),\n observation_json TEXT CHECK(observation_json IS NULL OR json_valid(observation_json)),\n retry_at TEXT,\n PRIMARY KEY(generation, attempt_id),\n UNIQUE(generation, tool_call_id, attempt_number),\n FOREIGN KEY(generation, tool_call_id) REFERENCES tool_calls(generation, tool_call_id),\n FOREIGN KEY(generation, step_id) REFERENCES steps(generation, step_id)\n) STRICT;\nCREATE TABLE tool_approvals (\n generation INTEGER NOT NULL,\n approval_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('pending','approved','denied')),\n request_json TEXT NOT NULL CHECK(json_valid(request_json)),\n decision_json TEXT CHECK(decision_json IS NULL OR json_valid(decision_json)),\n expires_at TEXT NOT NULL,\n PRIMARY KEY(generation, approval_id),\n FOREIGN KEY(generation, tool_call_id) REFERENCES tool_calls(generation, tool_call_id)\n) STRICT;\nCREATE UNIQUE INDEX one_pending_approval_per_call ON tool_approvals(generation, tool_call_id) WHERE status='pending';\nCREATE TABLE model_requests (\n generation INTEGER NOT NULL,\n request_id TEXT NOT NULL,\n requested_event_id TEXT NOT NULL REFERENCES events(event_id),\n responded_event_id TEXT REFERENCES events(event_id),\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n step_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('requested','responded','failed')),\n request_json TEXT NOT NULL CHECK(json_valid(request_json)),\n response_json TEXT CHECK(response_json IS NULL OR json_valid(response_json)),\n assistant_message_id TEXT,\n failure_json TEXT CHECK(failure_json IS NULL OR json_valid(failure_json)),\n charged_usage_json TEXT CHECK(charged_usage_json IS NULL OR json_valid(charged_usage_json)),\n reserved_tokens INTEGER NOT NULL CHECK(reserved_tokens >= 0),\n retry_at TEXT,\n PRIMARY KEY(generation, request_id),\n UNIQUE(generation, step_id),\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id),\n FOREIGN KEY(generation, step_id) REFERENCES steps(generation, step_id),\n FOREIGN KEY(generation, assistant_message_id) REFERENCES session_messages(generation, message_id) DEFERRABLE INITIALLY DEFERRED,\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id)\n) STRICT;\nCREATE INDEX model_requests_recovery ON model_requests(generation, run_id, status);\nCREATE TABLE checkpoints (\n generation INTEGER NOT NULL REFERENCES projection_generations(generation),\n projection_name TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n projection_version INTEGER NOT NULL CHECK(projection_version > 0),\n through_position INTEGER NOT NULL CHECK(through_position >= 0),\n through_stream_seq INTEGER NOT NULL CHECK(through_stream_seq >= 0),\n snapshot_json TEXT NOT NULL CHECK(json_valid(snapshot_json)),\n snapshot_hash TEXT NOT NULL,\n PRIMARY KEY(generation, projection_name, scope_key, through_position)\n) STRICT;\n";
@@ -0,0 +1,2 @@
1
+ // Initial SQLite migration.
2
+ export const migration = "PRAGMA foreign_keys = ON;\nPRAGMA journal_mode = WAL;\nPRAGMA synchronous = FULL;\nPRAGMA busy_timeout = 5000;\n\nCREATE TABLE schema_migrations (\n version INTEGER PRIMARY KEY,\n checksum TEXT NOT NULL,\n applied_at TEXT NOT NULL\n) STRICT;\n\nCREATE TABLE events (\n position INTEGER PRIMARY KEY AUTOINCREMENT CHECK(position > 0),\n event_id TEXT NOT NULL UNIQUE,\n envelope_version INTEGER NOT NULL CHECK(envelope_version = 1),\n event_type TEXT NOT NULL,\n event_version INTEGER NOT NULL CHECK(event_version >= 1),\n workspace_id TEXT NOT NULL,\n scope_kind TEXT NOT NULL CHECK(scope_kind IN ('workspace','session','run','agent_session')),\n session_id TEXT,\n run_id TEXT,\n agent_id TEXT,\n agent_session_id TEXT,\n stream_id TEXT NOT NULL,\n stream_seq INTEGER NOT NULL CHECK(stream_seq > 0),\n occurred_at TEXT NOT NULL,\n recorded_at TEXT NOT NULL,\n correlation_id TEXT NOT NULL,\n causation_id TEXT,\n command_id TEXT NOT NULL,\n command_hash TEXT NOT NULL,\n command_event_index INTEGER NOT NULL CHECK(command_event_index >= 0),\n command_event_count INTEGER NOT NULL CHECK(command_event_count > command_event_index),\n actor_json TEXT NOT NULL CHECK(json_valid(actor_json)),\n traceparent TEXT,\n links_json TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(links_json)),\n payload_json TEXT NOT NULL CHECK(json_valid(payload_json)),\n UNIQUE(scope_kind, stream_id, stream_seq),\n UNIQUE(command_id, command_event_index),\n CHECK (\n (scope_kind='workspace' AND stream_id=workspace_id AND session_id IS NULL\n AND run_id IS NULL AND agent_id IS NULL AND agent_session_id IS NULL)\n OR (scope_kind='session' AND stream_id=session_id AND session_id IS NOT NULL\n AND run_id IS NULL AND agent_id IS NULL AND agent_session_id IS NULL)\n OR (scope_kind='run' AND stream_id=run_id AND session_id IS NOT NULL\n AND run_id IS NOT NULL AND agent_id IS NULL AND agent_session_id IS NULL)\n OR (scope_kind='agent_session' AND stream_id=agent_session_id\n AND agent_id IS NOT NULL AND agent_session_id IS NOT NULL\n AND (run_id IS NULL OR session_id IS NOT NULL))\n )\n) STRICT;\nCREATE INDEX events_session_position ON events(session_id, position) WHERE session_id IS NOT NULL;\nCREATE INDEX events_run_position ON events(run_id, position) WHERE run_id IS NOT NULL;\nCREATE INDEX events_agent_session_position ON events(agent_session_id, position) WHERE agent_session_id IS NOT NULL;\nCREATE INDEX events_correlation_position ON events(correlation_id, position);\nCREATE INDEX events_causation ON events(causation_id) WHERE causation_id IS NOT NULL;\nCREATE INDEX events_type_position ON events(event_type, position);\nCREATE TRIGGER events_no_update BEFORE UPDATE ON events BEGIN\n SELECT RAISE(ABORT, 'events are append-only');\nEND;\nCREATE TRIGGER events_no_delete BEFORE DELETE ON events BEGIN\n SELECT RAISE(ABORT, 'events are append-only');\nEND;\n\nCREATE TABLE event_streams (\n scope_kind TEXT NOT NULL,\n stream_id TEXT NOT NULL,\n last_seq INTEGER NOT NULL CHECK(last_seq >= 0),\n PRIMARY KEY(scope_kind, stream_id)\n) STRICT;\nCREATE TABLE command_receipts (\n command_id TEXT PRIMARY KEY,\n command_hash TEXT NOT NULL,\n event_count INTEGER NOT NULL CHECK(event_count > 0),\n first_position INTEGER NOT NULL REFERENCES events(position),\n last_position INTEGER NOT NULL REFERENCES events(position)\n) STRICT;\nCREATE TABLE host_leases (\n singleton INTEGER PRIMARY KEY CHECK(singleton=1),\n epoch INTEGER NOT NULL CHECK(epoch > 0),\n owner_instance_id TEXT NOT NULL,\n acquired_at TEXT NOT NULL\n) STRICT;\n\nCREATE TABLE projection_generations (\n generation INTEGER PRIMARY KEY,\n status TEXT NOT NULL CHECK(status IN ('building','active','retired')),\n through_position INTEGER NOT NULL CHECK(through_position >= 0),\n versions_json TEXT NOT NULL CHECK(json_valid(versions_json)),\n digest TEXT\n) STRICT;\nCREATE UNIQUE INDEX one_active_generation ON projection_generations(status) WHERE status='active';\nCREATE TABLE projection_meta (\n singleton INTEGER PRIMARY KEY CHECK(singleton=1),\n active_generation INTEGER NOT NULL REFERENCES projection_generations(generation)\n) STRICT;\nCREATE TABLE projection_checkpoints (\n generation INTEGER NOT NULL REFERENCES projection_generations(generation),\n projection_name TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n projection_version INTEGER NOT NULL CHECK(projection_version > 0),\n last_stream_seq INTEGER NOT NULL CHECK(last_stream_seq >= 0),\n last_position INTEGER NOT NULL CHECK(last_position >= 0),\n PRIMARY KEY(generation, projection_name, scope_key)\n) STRICT;\n\nCREATE TABLE workspaces (\n generation INTEGER NOT NULL REFERENCES projection_generations(generation),\n workspace_id TEXT NOT NULL,\n root_uri TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('open','archived')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, workspace_id)\n) STRICT;\nCREATE TABLE sessions (\n generation INTEGER NOT NULL,\n session_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n title TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('open','archived')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, session_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id)\n) STRICT;\nCREATE INDEX sessions_workspace ON sessions(generation, workspace_id, created_at);\nCREATE TABLE agents (\n generation INTEGER NOT NULL,\n agent_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('main','worker','specialist')),\n default_scope TEXT NOT NULL CHECK(default_scope IN ('run','session','project')),\n mode_ref TEXT NOT NULL,\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, agent_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id)\n) STRICT;\nCREATE TABLE runs (\n generation INTEGER NOT NULL,\n run_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n input_message_id TEXT NOT NULL,\n working_directory_uri TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('created','running','paused','cancelling','completed','failed','cancelled')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, run_id),\n FOREIGN KEY(generation, session_id) REFERENCES sessions(generation, session_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id)\n) STRICT;\nCREATE INDEX runs_session_status ON runs(generation, session_id, status, created_at);\nCREATE TABLE agent_sessions (\n generation INTEGER NOT NULL,\n agent_session_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n owner_kind TEXT NOT NULL CHECK(owner_kind IN ('run','session','project')),\n owner_session_id TEXT,\n owner_run_id TEXT,\n status TEXT NOT NULL CHECK(status IN ('open','archived')),\n created_at TEXT NOT NULL,\n PRIMARY KEY(generation, agent_session_id),\n FOREIGN KEY(generation, workspace_id) REFERENCES workspaces(generation, workspace_id),\n FOREIGN KEY(generation, agent_id) REFERENCES agents(generation, agent_id),\n FOREIGN KEY(generation, owner_session_id) REFERENCES sessions(generation, session_id),\n FOREIGN KEY(generation, owner_run_id) REFERENCES runs(generation, run_id),\n CHECK((owner_kind='project' AND owner_session_id IS NULL AND owner_run_id IS NULL)\n OR (owner_kind='session' AND owner_session_id IS NOT NULL AND owner_run_id IS NULL)\n OR (owner_kind='run' AND owner_session_id IS NOT NULL AND owner_run_id IS NOT NULL))\n) STRICT;\nCREATE INDEX agent_sessions_owner ON agent_sessions(generation, owner_kind, owner_session_id, owner_run_id);\nCREATE INDEX agent_sessions_agent ON agent_sessions(generation, agent_id, status);\nCREATE TABLE session_agent_bindings (\n generation INTEGER NOT NULL,\n session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('main','participant')),\n PRIMARY KEY(generation, session_id, agent_session_id),\n FOREIGN KEY(generation, session_id) REFERENCES sessions(generation, session_id),\n FOREIGN KEY(generation, agent_id) REFERENCES agents(generation, agent_id),\n FOREIGN KEY(generation, agent_session_id) REFERENCES agent_sessions(generation, agent_session_id)\n) STRICT;\nCREATE UNIQUE INDEX one_main_per_session ON session_agent_bindings(generation, session_id) WHERE role='main';\nCREATE TABLE run_agents (\n generation INTEGER NOT NULL,\n run_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('main','worker')),\n config_json TEXT NOT NULL CHECK(json_valid(config_json)),\n PRIMARY KEY(generation, run_id, agent_session_id),\n FOREIGN KEY(generation, run_id) REFERENCES runs(generation, run_id),\n FOREIGN KEY(generation, agent_id) REFERENCES agents(generation, agent_id),\n FOREIGN KEY(generation, agent_session_id) REFERENCES agent_sessions(generation, agent_session_id)\n) STRICT;\nCREATE UNIQUE INDEX one_main_per_run ON run_agents(generation, run_id) WHERE role='main';\nCREATE TABLE agent_session_occupancy (\n generation INTEGER NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n PRIMARY KEY(generation, agent_session_id),\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id)\n) STRICT;\n\nCREATE TABLE turns (\n generation INTEGER NOT NULL,\n turn_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n input_message_id TEXT NOT NULL,\n ordinal INTEGER NOT NULL CHECK(ordinal > 0),\n status TEXT NOT NULL CHECK(status IN ('queued','running','paused','completed','failed','interrupted')),\n terminal_json TEXT CHECK(terminal_json IS NULL OR json_valid(terminal_json)),\n PRIMARY KEY(generation, turn_id),\n UNIQUE(generation, agent_session_id, ordinal),\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id)\n) STRICT;\nCREATE UNIQUE INDEX one_live_turn_per_stream ON turns(generation, agent_session_id)\n WHERE status IN ('queued','running','paused');\nCREATE TABLE steps (\n generation INTEGER NOT NULL,\n step_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n ordinal INTEGER NOT NULL CHECK(ordinal > 0),\n kind TEXT NOT NULL CHECK(kind IN ('model','tool','runtime')),\n status TEXT NOT NULL CHECK(status IN ('running','completed','failed','interrupted')),\n error_json TEXT CHECK(error_json IS NULL OR json_valid(error_json)),\n PRIMARY KEY(generation, step_id),\n UNIQUE(generation, turn_id, ordinal),\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id)\n) STRICT;\nCREATE TABLE run_states (\n generation INTEGER NOT NULL,\n run_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('created','running','paused','cancelling','completed','failed','cancelled')),\n pause_reason TEXT CHECK(pause_reason IS NULL OR pause_reason IN ('approval','tool_outcome_unknown','recovery_review')),\n last_run_seq INTEGER NOT NULL CHECK(last_run_seq >= 0),\n through_position INTEGER NOT NULL CHECK(through_position >= 0),\n model_attempts INTEGER NOT NULL CHECK(model_attempts >= 0),\n tool_calls_started INTEGER NOT NULL CHECK(tool_calls_started >= 0),\n steps_started INTEGER NOT NULL CHECK(steps_started >= 0),\n reserved_tokens INTEGER NOT NULL CHECK(reserved_tokens >= 0),\n usage_json TEXT NOT NULL CHECK(json_valid(usage_json)),\n active_turn_ids_json TEXT NOT NULL CHECK(json_valid(active_turn_ids_json)),\n blocked_turn_ids_json TEXT NOT NULL CHECK(json_valid(blocked_turn_ids_json)),\n unresolved_call_ids_json TEXT NOT NULL CHECK(json_valid(unresolved_call_ids_json)),\n deadline_at TEXT,\n PRIMARY KEY(generation, run_id),\n FOREIGN KEY(generation, run_id) REFERENCES runs(generation, run_id)\n) STRICT;\n\nCREATE TABLE session_messages (\n generation INTEGER NOT NULL,\n message_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n role TEXT NOT NULL CHECK(role IN ('user','assistant','tool')),\n source_event_id TEXT NOT NULL REFERENCES events(event_id),\n order_seq INTEGER NOT NULL CHECK(order_seq > 0),\n order_part INTEGER NOT NULL CHECK(order_part >= 0),\n active INTEGER NOT NULL CHECK(active IN (0,1)),\n superseded_by TEXT REFERENCES events(event_id),\n message_json TEXT NOT NULL CHECK(json_valid(message_json)),\n PRIMARY KEY(generation, message_id),\n FOREIGN KEY(generation, agent_session_id) REFERENCES agent_sessions(generation, agent_session_id),\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id),\n FOREIGN KEY(generation, run_id) REFERENCES runs(generation, run_id),\n CHECK((active=1 AND superseded_by IS NULL) OR (active=0 AND superseded_by IS NOT NULL))\n) STRICT;\nCREATE UNIQUE INDEX surface_active_order ON session_messages(generation, agent_session_id, order_seq, order_part) WHERE active=1;\nCREATE INDEX messages_surface ON session_messages(generation, agent_session_id, active, order_seq, order_part);\nCREATE TABLE tool_calls (\n generation INTEGER NOT NULL,\n tool_call_id TEXT NOT NULL,\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n assistant_message_id TEXT NOT NULL,\n provider_call_id TEXT NOT NULL,\n call_index INTEGER NOT NULL CHECK(call_index >= 0),\n execution_key TEXT NOT NULL,\n policy_version TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('requested','waiting_approval','running','retry_wait','outcome_unknown','settled')),\n call_json TEXT NOT NULL CHECK(json_valid(call_json)),\n definition_json TEXT CHECK(definition_json IS NULL OR json_valid(definition_json)),\n result_message_id TEXT,\n result_json TEXT CHECK(result_json IS NULL OR json_valid(result_json)),\n PRIMARY KEY(generation, tool_call_id),\n UNIQUE(generation, assistant_message_id, call_index),\n UNIQUE(generation, assistant_message_id, provider_call_id),\n UNIQUE(generation, execution_key),\n UNIQUE(generation, result_message_id),\n FOREIGN KEY(generation, assistant_message_id) REFERENCES session_messages(generation, message_id),\n FOREIGN KEY(generation, result_message_id) REFERENCES session_messages(generation, message_id) DEFERRABLE INITIALLY DEFERRED,\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id),\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id),\n CHECK((status='settled' AND result_message_id IS NOT NULL AND result_json IS NOT NULL)\n OR (status<>'settled' AND result_message_id IS NULL AND result_json IS NULL))\n) STRICT;\nCREATE INDEX calls_pending ON tool_calls(generation, run_id, status);\nCREATE INDEX calls_stream_pending ON tool_calls(generation, agent_session_id, status);\nCREATE TABLE tool_executions (\n generation INTEGER NOT NULL,\n attempt_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n step_id TEXT NOT NULL,\n attempt_number INTEGER NOT NULL CHECK(attempt_number > 0),\n execution_key TEXT NOT NULL,\n executor_instance_id TEXT NOT NULL,\n host_epoch INTEGER NOT NULL CHECK(host_epoch > 0),\n started_at TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('running','completed','failed','outcome_unknown','reconciled')),\n observation_json TEXT CHECK(observation_json IS NULL OR json_valid(observation_json)),\n retry_at TEXT,\n PRIMARY KEY(generation, attempt_id),\n UNIQUE(generation, tool_call_id, attempt_number),\n FOREIGN KEY(generation, tool_call_id) REFERENCES tool_calls(generation, tool_call_id),\n FOREIGN KEY(generation, step_id) REFERENCES steps(generation, step_id)\n) STRICT;\nCREATE TABLE tool_approvals (\n generation INTEGER NOT NULL,\n approval_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('pending','approved','denied')),\n request_json TEXT NOT NULL CHECK(json_valid(request_json)),\n decision_json TEXT CHECK(decision_json IS NULL OR json_valid(decision_json)),\n expires_at TEXT NOT NULL,\n PRIMARY KEY(generation, approval_id),\n FOREIGN KEY(generation, tool_call_id) REFERENCES tool_calls(generation, tool_call_id)\n) STRICT;\nCREATE UNIQUE INDEX one_pending_approval_per_call ON tool_approvals(generation, tool_call_id) WHERE status='pending';\nCREATE TABLE model_requests (\n generation INTEGER NOT NULL,\n request_id TEXT NOT NULL,\n requested_event_id TEXT NOT NULL REFERENCES events(event_id),\n responded_event_id TEXT REFERENCES events(event_id),\n agent_session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n step_id TEXT NOT NULL,\n status TEXT NOT NULL CHECK(status IN ('requested','responded','failed')),\n request_json TEXT NOT NULL CHECK(json_valid(request_json)),\n response_json TEXT CHECK(response_json IS NULL OR json_valid(response_json)),\n assistant_message_id TEXT,\n failure_json TEXT CHECK(failure_json IS NULL OR json_valid(failure_json)),\n charged_usage_json TEXT CHECK(charged_usage_json IS NULL OR json_valid(charged_usage_json)),\n reserved_tokens INTEGER NOT NULL CHECK(reserved_tokens >= 0),\n retry_at TEXT,\n PRIMARY KEY(generation, request_id),\n UNIQUE(generation, step_id),\n FOREIGN KEY(generation, turn_id) REFERENCES turns(generation, turn_id),\n FOREIGN KEY(generation, step_id) REFERENCES steps(generation, step_id),\n FOREIGN KEY(generation, assistant_message_id) REFERENCES session_messages(generation, message_id) DEFERRABLE INITIALLY DEFERRED,\n FOREIGN KEY(generation, run_id, agent_session_id) REFERENCES run_agents(generation, run_id, agent_session_id)\n) STRICT;\nCREATE INDEX model_requests_recovery ON model_requests(generation, run_id, status);\nCREATE TABLE checkpoints (\n generation INTEGER NOT NULL REFERENCES projection_generations(generation),\n projection_name TEXT NOT NULL,\n scope_key TEXT NOT NULL,\n projection_version INTEGER NOT NULL CHECK(projection_version > 0),\n through_position INTEGER NOT NULL CHECK(through_position >= 0),\n through_stream_seq INTEGER NOT NULL CHECK(through_stream_seq >= 0),\n snapshot_json TEXT NOT NULL CHECK(json_valid(snapshot_json)),\n snapshot_hash TEXT NOT NULL,\n PRIMARY KEY(generation, projection_name, scope_key, through_position)\n) STRICT;\n";
@@ -0,0 +1,3 @@
1
+ import type { ProjectionState, ProjectionChanges } from '@saturn-universe/projections';
2
+ import type { Database } from './driver.js';
3
+ export declare function writeProjectionRows(db: Database, s: ProjectionState, generation: number, changes?: ProjectionChanges): void;