@earendil-works/pi-session-backend-sqlite-node 0.84.1 → 0.84.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +10 -3
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +6 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/sqlite/migrations/001_initial.sql +4 -8
  7. package/dist/sqlite/repo.d.ts.map +1 -1
  8. package/dist/sqlite/repo.js +16 -21
  9. package/dist/sqlite/repo.js.map +1 -1
  10. package/dist/sqlite/search-backend.d.ts +7 -2
  11. package/dist/sqlite/search-backend.d.ts.map +1 -1
  12. package/dist/sqlite/search-backend.js +71 -34
  13. package/dist/sqlite/search-backend.js.map +1 -1
  14. package/dist/sqlite/sql.d.ts +1 -0
  15. package/dist/sqlite/sql.d.ts.map +1 -1
  16. package/dist/sqlite/sql.js +3 -0
  17. package/dist/sqlite/sql.js.map +1 -1
  18. package/dist/sqlite/storage/branch-entries.d.ts +2 -2
  19. package/dist/sqlite/storage/branch-entries.d.ts.map +1 -1
  20. package/dist/sqlite/storage/branch-entries.js +39 -22
  21. package/dist/sqlite/storage/branch-entries.js.map +1 -1
  22. package/dist/sqlite/storage/entries.d.ts +6 -2
  23. package/dist/sqlite/storage/entries.d.ts.map +1 -1
  24. package/dist/sqlite/storage/entries.js +9 -2
  25. package/dist/sqlite/storage/entries.js.map +1 -1
  26. package/dist/sqlite/storage/facts.d.ts.map +1 -1
  27. package/dist/sqlite/storage/facts.js +13 -11
  28. package/dist/sqlite/storage/facts.js.map +1 -1
  29. package/dist/sqlite/storage/records.d.ts +2 -2
  30. package/dist/sqlite/storage/records.d.ts.map +1 -1
  31. package/dist/sqlite/storage/records.js.map +1 -1
  32. package/dist/sqlite/storage/sessions.d.ts +2 -2
  33. package/dist/sqlite/storage/sessions.d.ts.map +1 -1
  34. package/dist/sqlite/storage/sessions.js +3 -4
  35. package/dist/sqlite/storage/sessions.js.map +1 -1
  36. package/dist/sqlite/types.d.ts +1 -0
  37. package/dist/sqlite/types.d.ts.map +1 -1
  38. package/dist/sqlite/types.js.map +1 -1
  39. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## [Unreleased]
4
+
5
+ ## [0.84.3] - 2026-08-24
6
+
7
+ ## [0.84.2] - 2026-08-14
8
+
3
9
  ## [0.84.1] - 2026-08-07
4
10
 
5
11
  ### Added
package/README.md CHANGED
@@ -8,8 +8,15 @@ migrations, materialized views, and optional FTS search.
8
8
  await using repository = new SqliteSessionRepository(options);
9
9
  const search = createSqliteSessionSearch(options);
10
10
  const session = await repository.create({ cwd });
11
- const hits = await search.search({ text: "needle" });
11
+ await session.appendMessage(message);
12
+
13
+ const hits = [];
14
+ for await (const hit of search.search("needle")) hits.push(hit);
12
15
  ```
13
16
 
14
- The repository lazily owns one shared database connection. Search is an independent,
15
- query-only projection over the same canonical database.
17
+ The repository lazily owns one shared database connection. Search is an independent
18
+ service over the same canonical database: repositories do not expose `search()`.
19
+ The FTS table and triggers are created lazily on the first non-blank search; when
20
+ FTS is first created, search performs a one-time rebuild from canonical entries.
21
+ After that, SQLite triggers keep FTS in sync with canonical entry inserts, deletes,
22
+ and payload updates.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAoC,MAAM,mBAAmB,CAAC;AAwFjH,wBAAgB,sBAAsB,CAAC,EAAE,EAAE,YAAY,GAAG,cAAc,CAEvE;AAED,wBAAgB,uBAAuB,IAAI,qBAAqB,CAM/D;AAGD,cAAc,mBAAmB,CAAC","sourcesContent":["import type { SQLInputValue } from \"node:sqlite\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { sql } from \"./sqlite/sql.ts\";\nimport type { SqliteDatabase, SqliteDatabaseFactory, SqliteRunResult, SqliteStatement } from \"./sqlite/types.ts\";\n\nfunction isNamedParameters(value: unknown): value is Record<string, SQLInputValue> {\n\tif (value === null || typeof value !== \"object\") return false;\n\tif (Array.isArray(value) || ArrayBuffer.isView(value)) return false;\n\treturn true;\n}\n\nfunction isAsyncResult(value: unknown): boolean {\n\treturn value !== null && (typeof value === \"object\" || typeof value === \"function\") && \"then\" in value;\n}\n\nclass NodeSqliteStatement implements SqliteStatement {\n\tprivate readonly statement: ReturnType<DatabaseSync[\"prepare\"]>;\n\n\tconstructor(statement: ReturnType<DatabaseSync[\"prepare\"]>) {\n\t\tthis.statement = statement;\n\t}\n\n\trun(...params: unknown[]): SqliteRunResult {\n\t\tconst [first, ...rest] = params;\n\t\tconst result = isNamedParameters(first)\n\t\t\t? this.statement.run(first, ...(rest as SQLInputValue[]))\n\t\t\t: this.statement.run(...(params as SQLInputValue[]));\n\t\treturn {\n\t\t\tchanges: Number(result.changes),\n\t\t\tlastInsertRowid: result.lastInsertRowid === undefined ? undefined : Number(result.lastInsertRowid),\n\t\t};\n\t}\n\n\tget<TRow extends object>(...params: unknown[]): TRow | undefined {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.get(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.get(...(params as SQLInputValue[]))\n\t\t) as TRow | undefined;\n\t}\n\n\tall<TRow extends object>(...params: unknown[]): TRow[] {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.all(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.all(...(params as SQLInputValue[]))\n\t\t) as TRow[];\n\t}\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\tprivate readonly db: DatabaseSync;\n\n\tconstructor(db: DatabaseSync) {\n\t\tthis.db = db;\n\t}\n\n\texec(sql: string): void {\n\t\tthis.db.exec(sql);\n\t}\n\n\tprepare(sql: string): SqliteStatement {\n\t\treturn new NodeSqliteStatement(this.db.prepare(sql));\n\t}\n\n\ttransaction<T>(fn: () => T): T {\n\t\tsql`BEGIN IMMEDIATE`.exec(this);\n\t\ttry {\n\t\t\tconst result = fn();\n\t\t\tif (isAsyncResult(result)) {\n\t\t\t\tthrow new TypeError(\"SQLite transaction callbacks must be synchronous\");\n\t\t\t}\n\t\t\tsql`COMMIT`.exec(this);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tsql`ROLLBACK`.exec(this);\n\t\t\t} catch {\n\t\t\t\t// Ignore rollback errors to rethrow original error.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tclose(): void {\n\t\tthis.db.close();\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(db: DatabaseSync): SqliteDatabase {\n\treturn new NodeSqliteDatabase(db);\n}\n\nexport function createNodeSqliteFactory(): SqliteDatabaseFactory {\n\treturn {\n\t\tasync open(path: string): Promise<SqliteDatabase> {\n\t\t\treturn new NodeSqliteDatabase(new DatabaseSync(path));\n\t\t},\n\t};\n}\n\n// Re-export the SQLite session backend and types so this package is a complete node-sqlite backend.\nexport * from \"./sqlite/index.ts\";\n"]}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAoC,MAAM,mBAAmB,CAAC;AAiGjH,wBAAgB,sBAAsB,CAAC,EAAE,EAAE,YAAY,GAAG,cAAc,CAEvE;AAED,wBAAgB,uBAAuB,IAAI,qBAAqB,CAM/D;AAGD,cAAc,mBAAmB,CAAC","sourcesContent":["import type { SQLInputValue } from \"node:sqlite\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { sql } from \"./sqlite/sql.ts\";\nimport type { SqliteDatabase, SqliteDatabaseFactory, SqliteRunResult, SqliteStatement } from \"./sqlite/types.ts\";\n\nfunction isNamedParameters(value: unknown): value is Record<string, SQLInputValue> {\n\tif (value === null || typeof value !== \"object\") return false;\n\tif (Array.isArray(value) || ArrayBuffer.isView(value)) return false;\n\treturn true;\n}\n\nfunction isAsyncResult(value: unknown): boolean {\n\treturn value !== null && (typeof value === \"object\" || typeof value === \"function\") && \"then\" in value;\n}\n\nclass NodeSqliteStatement implements SqliteStatement {\n\tprivate readonly statement: ReturnType<DatabaseSync[\"prepare\"]>;\n\n\tconstructor(statement: ReturnType<DatabaseSync[\"prepare\"]>) {\n\t\tthis.statement = statement;\n\t}\n\n\trun(...params: unknown[]): SqliteRunResult {\n\t\tconst [first, ...rest] = params;\n\t\tconst result = isNamedParameters(first)\n\t\t\t? this.statement.run(first, ...(rest as SQLInputValue[]))\n\t\t\t: this.statement.run(...(params as SQLInputValue[]));\n\t\treturn {\n\t\t\tchanges: Number(result.changes),\n\t\t\tlastInsertRowid: result.lastInsertRowid === undefined ? undefined : Number(result.lastInsertRowid),\n\t\t};\n\t}\n\n\tget<TRow extends object>(...params: unknown[]): TRow | undefined {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.get(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.get(...(params as SQLInputValue[]))\n\t\t) as TRow | undefined;\n\t}\n\n\tall<TRow extends object>(...params: unknown[]): TRow[] {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.all(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.all(...(params as SQLInputValue[]))\n\t\t) as TRow[];\n\t}\n\n\titerate<TRow extends object>(...params: unknown[]): Iterable<TRow> {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.iterate(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.iterate(...(params as SQLInputValue[]))\n\t\t) as Iterable<TRow>;\n\t}\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\tprivate readonly db: DatabaseSync;\n\n\tconstructor(db: DatabaseSync) {\n\t\tthis.db = db;\n\t}\n\n\texec(sql: string): void {\n\t\tthis.db.exec(sql);\n\t}\n\n\tprepare(sql: string): SqliteStatement {\n\t\treturn new NodeSqliteStatement(this.db.prepare(sql));\n\t}\n\n\ttransaction<T>(fn: () => T): T {\n\t\tsql`BEGIN IMMEDIATE`.exec(this);\n\t\ttry {\n\t\t\tconst result = fn();\n\t\t\tif (isAsyncResult(result)) {\n\t\t\t\tthrow new TypeError(\"SQLite transaction callbacks must be synchronous\");\n\t\t\t}\n\t\t\tsql`COMMIT`.exec(this);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tsql`ROLLBACK`.exec(this);\n\t\t\t} catch {\n\t\t\t\t// Ignore rollback errors to rethrow original error.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tclose(): void {\n\t\tthis.db.close();\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(db: DatabaseSync): SqliteDatabase {\n\treturn new NodeSqliteDatabase(db);\n}\n\nexport function createNodeSqliteFactory(): SqliteDatabaseFactory {\n\treturn {\n\t\tasync open(path: string): Promise<SqliteDatabase> {\n\t\t\treturn new NodeSqliteDatabase(new DatabaseSync(path));\n\t\t},\n\t};\n}\n\n// Re-export the SQLite session backend and types so this package is a complete node-sqlite backend.\nexport * from \"./sqlite/index.ts\";\n"]}
package/dist/index.js CHANGED
@@ -37,6 +37,12 @@ class NodeSqliteStatement {
37
37
  ? this.statement.all(first, ...rest)
38
38
  : this.statement.all(...params));
39
39
  }
40
+ iterate(...params) {
41
+ const [first, ...rest] = params;
42
+ return (isNamedParameters(first)
43
+ ? this.statement.iterate(first, ...rest)
44
+ : this.statement.iterate(...params));
45
+ }
40
46
  }
41
47
  class NodeSqliteDatabase {
42
48
  db;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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","sourcesContent":["import type { SQLInputValue } from \"node:sqlite\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { sql } from \"./sqlite/sql.ts\";\nimport type { SqliteDatabase, SqliteDatabaseFactory, SqliteRunResult, SqliteStatement } from \"./sqlite/types.ts\";\n\nfunction isNamedParameters(value: unknown): value is Record<string, SQLInputValue> {\n\tif (value === null || typeof value !== \"object\") return false;\n\tif (Array.isArray(value) || ArrayBuffer.isView(value)) return false;\n\treturn true;\n}\n\nfunction isAsyncResult(value: unknown): boolean {\n\treturn value !== null && (typeof value === \"object\" || typeof value === \"function\") && \"then\" in value;\n}\n\nclass NodeSqliteStatement implements SqliteStatement {\n\tprivate readonly statement: ReturnType<DatabaseSync[\"prepare\"]>;\n\n\tconstructor(statement: ReturnType<DatabaseSync[\"prepare\"]>) {\n\t\tthis.statement = statement;\n\t}\n\n\trun(...params: unknown[]): SqliteRunResult {\n\t\tconst [first, ...rest] = params;\n\t\tconst result = isNamedParameters(first)\n\t\t\t? this.statement.run(first, ...(rest as SQLInputValue[]))\n\t\t\t: this.statement.run(...(params as SQLInputValue[]));\n\t\treturn {\n\t\t\tchanges: Number(result.changes),\n\t\t\tlastInsertRowid: result.lastInsertRowid === undefined ? undefined : Number(result.lastInsertRowid),\n\t\t};\n\t}\n\n\tget<TRow extends object>(...params: unknown[]): TRow | undefined {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.get(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.get(...(params as SQLInputValue[]))\n\t\t) as TRow | undefined;\n\t}\n\n\tall<TRow extends object>(...params: unknown[]): TRow[] {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.all(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.all(...(params as SQLInputValue[]))\n\t\t) as TRow[];\n\t}\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\tprivate readonly db: DatabaseSync;\n\n\tconstructor(db: DatabaseSync) {\n\t\tthis.db = db;\n\t}\n\n\texec(sql: string): void {\n\t\tthis.db.exec(sql);\n\t}\n\n\tprepare(sql: string): SqliteStatement {\n\t\treturn new NodeSqliteStatement(this.db.prepare(sql));\n\t}\n\n\ttransaction<T>(fn: () => T): T {\n\t\tsql`BEGIN IMMEDIATE`.exec(this);\n\t\ttry {\n\t\t\tconst result = fn();\n\t\t\tif (isAsyncResult(result)) {\n\t\t\t\tthrow new TypeError(\"SQLite transaction callbacks must be synchronous\");\n\t\t\t}\n\t\t\tsql`COMMIT`.exec(this);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tsql`ROLLBACK`.exec(this);\n\t\t\t} catch {\n\t\t\t\t// Ignore rollback errors to rethrow original error.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tclose(): void {\n\t\tthis.db.close();\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(db: DatabaseSync): SqliteDatabase {\n\treturn new NodeSqliteDatabase(db);\n}\n\nexport function createNodeSqliteFactory(): SqliteDatabaseFactory {\n\treturn {\n\t\tasync open(path: string): Promise<SqliteDatabase> {\n\t\t\treturn new NodeSqliteDatabase(new DatabaseSync(path));\n\t\t},\n\t};\n}\n\n// Re-export the SQLite session backend and types so this package is a complete node-sqlite backend.\nexport * from \"./sqlite/index.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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","sourcesContent":["import type { SQLInputValue } from \"node:sqlite\";\nimport { DatabaseSync } from \"node:sqlite\";\nimport { sql } from \"./sqlite/sql.ts\";\nimport type { SqliteDatabase, SqliteDatabaseFactory, SqliteRunResult, SqliteStatement } from \"./sqlite/types.ts\";\n\nfunction isNamedParameters(value: unknown): value is Record<string, SQLInputValue> {\n\tif (value === null || typeof value !== \"object\") return false;\n\tif (Array.isArray(value) || ArrayBuffer.isView(value)) return false;\n\treturn true;\n}\n\nfunction isAsyncResult(value: unknown): boolean {\n\treturn value !== null && (typeof value === \"object\" || typeof value === \"function\") && \"then\" in value;\n}\n\nclass NodeSqliteStatement implements SqliteStatement {\n\tprivate readonly statement: ReturnType<DatabaseSync[\"prepare\"]>;\n\n\tconstructor(statement: ReturnType<DatabaseSync[\"prepare\"]>) {\n\t\tthis.statement = statement;\n\t}\n\n\trun(...params: unknown[]): SqliteRunResult {\n\t\tconst [first, ...rest] = params;\n\t\tconst result = isNamedParameters(first)\n\t\t\t? this.statement.run(first, ...(rest as SQLInputValue[]))\n\t\t\t: this.statement.run(...(params as SQLInputValue[]));\n\t\treturn {\n\t\t\tchanges: Number(result.changes),\n\t\t\tlastInsertRowid: result.lastInsertRowid === undefined ? undefined : Number(result.lastInsertRowid),\n\t\t};\n\t}\n\n\tget<TRow extends object>(...params: unknown[]): TRow | undefined {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.get(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.get(...(params as SQLInputValue[]))\n\t\t) as TRow | undefined;\n\t}\n\n\tall<TRow extends object>(...params: unknown[]): TRow[] {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.all(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.all(...(params as SQLInputValue[]))\n\t\t) as TRow[];\n\t}\n\n\titerate<TRow extends object>(...params: unknown[]): Iterable<TRow> {\n\t\tconst [first, ...rest] = params;\n\t\treturn (\n\t\t\tisNamedParameters(first)\n\t\t\t\t? this.statement.iterate(first, ...(rest as SQLInputValue[]))\n\t\t\t\t: this.statement.iterate(...(params as SQLInputValue[]))\n\t\t) as Iterable<TRow>;\n\t}\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\tprivate readonly db: DatabaseSync;\n\n\tconstructor(db: DatabaseSync) {\n\t\tthis.db = db;\n\t}\n\n\texec(sql: string): void {\n\t\tthis.db.exec(sql);\n\t}\n\n\tprepare(sql: string): SqliteStatement {\n\t\treturn new NodeSqliteStatement(this.db.prepare(sql));\n\t}\n\n\ttransaction<T>(fn: () => T): T {\n\t\tsql`BEGIN IMMEDIATE`.exec(this);\n\t\ttry {\n\t\t\tconst result = fn();\n\t\t\tif (isAsyncResult(result)) {\n\t\t\t\tthrow new TypeError(\"SQLite transaction callbacks must be synchronous\");\n\t\t\t}\n\t\t\tsql`COMMIT`.exec(this);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tsql`ROLLBACK`.exec(this);\n\t\t\t} catch {\n\t\t\t\t// Ignore rollback errors to rethrow original error.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tclose(): void {\n\t\tthis.db.close();\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(db: DatabaseSync): SqliteDatabase {\n\treturn new NodeSqliteDatabase(db);\n}\n\nexport function createNodeSqliteFactory(): SqliteDatabaseFactory {\n\treturn {\n\t\tasync open(path: string): Promise<SqliteDatabase> {\n\t\t\treturn new NodeSqliteDatabase(new DatabaseSync(path));\n\t\t},\n\t};\n}\n\n// Re-export the SQLite session backend and types so this package is a complete node-sqlite backend.\nexport * from \"./sqlite/index.ts\";\n"]}
@@ -1,6 +1,6 @@
1
1
  CREATE TABLE IF NOT EXISTS sessions (
2
2
  id TEXT PRIMARY KEY,
3
- created_at TEXT NOT NULL,
3
+ created_at INTEGER NOT NULL,
4
4
  cwd TEXT NOT NULL,
5
5
  parent_session_id TEXT NULL,
6
6
  metadata TEXT NULL
@@ -8,7 +8,6 @@ CREATE TABLE IF NOT EXISTS sessions (
8
8
 
9
9
  CREATE INDEX IF NOT EXISTS idx_sessions_created_at ON sessions(created_at DESC);
10
10
  CREATE INDEX IF NOT EXISTS idx_sessions_cwd_created_at ON sessions(cwd, created_at DESC);
11
- CREATE INDEX IF NOT EXISTS idx_sessions_parent ON sessions(parent_session_id);
12
11
 
13
12
  CREATE TABLE IF NOT EXISTS entries (
14
13
  session_id TEXT NOT NULL,
@@ -16,13 +15,12 @@ CREATE TABLE IF NOT EXISTS entries (
16
15
  id TEXT NOT NULL,
17
16
  parent_id TEXT NULL,
18
17
  type TEXT NOT NULL,
19
- timestamp TEXT NOT NULL,
18
+ timestamp INTEGER NOT NULL,
20
19
  payload TEXT NOT NULL,
21
20
  PRIMARY KEY (session_id, id),
22
21
  UNIQUE (session_id, seq)
23
22
  );
24
23
 
25
- CREATE INDEX IF NOT EXISTS idx_entries_session_seq ON entries(session_id, seq);
26
24
  CREATE INDEX IF NOT EXISTS idx_entries_session_parent ON entries(session_id, parent_id);
27
25
  CREATE INDEX IF NOT EXISTS idx_entries_session_type_seq ON entries(session_id, type, seq);
28
26
 
@@ -73,13 +71,12 @@ CREATE TABLE IF NOT EXISTS records (
73
71
  run_id TEXT NULL,
74
72
  type TEXT NOT NULL,
75
73
  op_kind TEXT NULL,
76
- timestamp TEXT NOT NULL,
74
+ timestamp INTEGER NOT NULL,
77
75
  payload TEXT NOT NULL,
78
76
  PRIMARY KEY (session_id, id),
79
77
  UNIQUE (session_id, seq)
80
78
  ) WITHOUT ROWID;
81
79
 
82
- CREATE INDEX IF NOT EXISTS idx_records_session_seq ON records(session_id, seq);
83
80
  CREATE INDEX IF NOT EXISTS idx_records_session_lane_seq ON records(session_id, lane, seq);
84
81
  CREATE INDEX IF NOT EXISTS idx_records_session_type_seq ON records(session_id, type, seq);
85
82
  CREATE INDEX IF NOT EXISTS idx_records_session_type_op_kind_seq ON records(session_id, type, op_kind, seq);
@@ -95,7 +92,6 @@ CREATE TABLE IF NOT EXISTS lane_moves (
95
92
  PRIMARY KEY (session_id, seq)
96
93
  ) WITHOUT ROWID;
97
94
 
98
- CREATE INDEX IF NOT EXISTS idx_lane_moves_session_lane_seq ON lane_moves(session_id, lane, seq);
99
95
 
100
96
  CREATE TABLE IF NOT EXISTS facts (
101
97
  session_id TEXT NOT NULL,
@@ -110,8 +106,8 @@ CREATE INDEX IF NOT EXISTS idx_facts_session_kind_key_seq ON facts(session_id, k
110
106
 
111
107
  CREATE TABLE IF NOT EXISTS branch_tips (
112
108
  session_id TEXT NOT NULL,
113
- tip_id TEXT NOT NULL,
114
109
  branch_id TEXT NOT NULL,
110
+ tip_id TEXT NOT NULL,
115
111
  PRIMARY KEY (session_id, tip_id),
116
112
  UNIQUE (session_id, branch_id)
117
113
  ) WITHOUT ROWID;
@@ -1 +1 @@
1
- {"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../src/sqlite/repo.ts"],"names":[],"mappings":"AACA,OAAO,EAIN,KAAK,WAAW,EAQhB,OAAO,EAEP,KAAK,WAAW,IAAI,iBAAiB,EAGrC,MAAM,+BAA+B,CAAC;AAmEvC,OAAO,KAAK,EAEX,qBAAqB,EACrB,0BAA0B,EAC1B,wBAAwB,EACxB,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,wBAAwB;IACxC,oGAAoG;IACpG,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,8BAA8B;IAC9C,GAAG,EAAE,0BAA0B,CAAC;IAChC,MAAM,EAAE,qBAAqB,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,wBAAwB,CAAC;CACvC;AAujBD,qBAAa,uBACZ,YACC,iBAAiB,CAAC,qBAAqB,EAAE,0BAA0B,EAAE,wBAAwB,CAAC,EAC9F,eAAe;IAEhB,OAAO,CAAC,YAAY,CAAqB;IACzC,OAAO,CAAC,QAAQ,CAA6B;IAC7C,OAAO,CAAC,eAAe,CAAsC;IAC7D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA8B;IACzD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAmC;IAClE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAiC;IACzD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA6B;IAE1D,YAAY,OAAO,EAAE,8BAA8B,EAGlD;YAEa,yBAAyB;IAMvC,OAAO,CAAC,gBAAgB;IAaxB,OAAO,CAAC,YAAY;IAcd,MAAM,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC,CAuBzF;IAEK,IAAI,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC,CAEnF;IAED,2FAA2F;IACrF,iBAAiB,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAWtE;IAED,yFAAyF;IACnF,IAAI,CAAC,OAAO,GAAE,wBAA6B,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAQnF;IAEK,MAAM,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAqB3D;IAEK,IAAI,CACT,MAAM,EAAE,qBAAqB,EAC7B,OAAO,EAAE,WAAW,GAAG,0BAA0B,GAC/C,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC,CA6GzC;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAM3B;IAEK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3C;YAEa,eAAe;YAQf,WAAW;YAMX,YAAY;CAgB1B","sourcesContent":["import type { FileError, Result } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype BranchBounds,\n\ttype Entry,\n\ttype EntryQuery,\n\ttype ForkOptions,\n\ttype LaneRecord,\n\ttype LogItem,\n\ttype LogOptions,\n\ttype NewRecord,\n\ttype OperationStartedRecord,\n\ttype ProvisionedEntry,\n\ttype RecordQuery,\n\tSession,\n\tSessionError,\n\ttype SessionRepo as SessionRepository,\n\ttype SessionStats,\n\ttype SessionStorage,\n} from \"@earendil-works/pi-agent-core\";\nimport { uuidv7 } from \"@earendil-works/pi-ai\";\nimport { appendEntryToBranchCache, buildCachedBranch, deleteBranchCache, rebuildBranchCache } from \"./branch-cache.ts\";\nimport { applyMigrations } from \"./migrations.ts\";\nimport { sql } from \"./sql.ts\";\nimport { type CachedBranchEntryRow, queryCachedBranchRows, readCachedBranch } from \"./storage/branch-entries.ts\";\nimport { readBranchTipIds } from \"./storage/branch-tips.ts\";\nimport {\n\tdeleteEntryRows,\n\ttype EntryRow,\n\tentryPayload,\n\tidExistsInEntries,\n\tinsertEntryRow,\n\treadEntryRow,\n\treadEntryRows,\n} from \"./storage/entries.ts\";\nimport { appendFact, deleteFactRows, readFactRows, readLatestFact, readLatestLabelFacts } from \"./storage/facts.ts\";\nimport {\n\tcreateInitialLane,\n\tdeleteLaneRows,\n\tfinishLaneOperation,\n\tcreateLane as insertLane,\n\treadLane,\n\treadLaneHead,\n\treadLaneMoveRows,\n\treadLanes,\n\tsetLaneLeaf,\n\tstartLaneOperation,\n\tmoveLane as updateLane,\n} from \"./storage/lanes.ts\";\nimport {\n\tappendRecordRow,\n\tdeleteRecordRows,\n\tidExistsInRecords,\n\treadOpenOperationRows,\n\treadRecordRows,\n} from \"./storage/records.ts\";\nimport {\n\tadvanceSequence,\n\tcreateSequence,\n\tdeleteSequence,\n\tgetNextSequence,\n\tsetNextSequence,\n} from \"./storage/session-sequences.ts\";\nimport {\n\taddUsageToStats,\n\tcreateStats,\n\tdeleteStats,\n\tincrementMessageCount,\n\treadStats,\n} from \"./storage/session-stats.ts\";\nimport {\n\tdecodeSessionMetadata,\n\tdeleteSessionRow,\n\tinsertSessionRow,\n\treadSessionRow,\n\treadSessionRows,\n\ttype SessionRow,\n\tsessionExists,\n} from \"./storage/sessions.ts\";\nimport {\n\tacquireWriterLease,\n\tdeleteWriterLease,\n\treleaseWriterLease,\n\trenewWriterLease,\n\ttype WriterLease,\n} from \"./storage/writer-leases.ts\";\nimport type {\n\tSqliteDatabase,\n\tSqliteDatabaseFactory,\n\tSqliteSessionCreateOptions,\n\tSqliteSessionListOptions,\n\tSqliteSessionMetadata,\n\tSqliteSessionRepositoryEnv,\n} from \"./types.ts\";\n\nexport interface SqliteWriterLeaseOptions {\n\t/** Time without a successful heartbeat before another writer may take over. Default: 30 seconds. */\n\tttlMs?: number;\n\t/** Idle heartbeat cadence. Default: 10 seconds. Must be less than ttlMs. */\n\theartbeatIntervalMs?: number;\n}\n\nexport interface SqliteSessionRepositoryOptions {\n\tenv: SqliteSessionRepositoryEnv;\n\tsqlite: SqliteDatabaseFactory;\n\tdatabasePath: string;\n\twriterLease?: SqliteWriterLeaseOptions;\n}\n\ninterface ResolvedWriterLeaseOptions {\n\tttlMs: number;\n\theartbeatIntervalMs: number;\n}\n\nfunction resolveWriterLeaseOptions(options: SqliteWriterLeaseOptions | undefined): ResolvedWriterLeaseOptions {\n\tconst ttlMs = options?.ttlMs ?? 30_000;\n\tconst heartbeatIntervalMs = options?.heartbeatIntervalMs ?? 10_000;\n\tif (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) throw new RangeError(\"writerLease.ttlMs must be positive\");\n\tif (!Number.isSafeInteger(heartbeatIntervalMs) || heartbeatIntervalMs <= 0 || heartbeatIntervalMs >= ttlMs) {\n\t\tthrow new RangeError(\"writerLease.heartbeatIntervalMs must be positive and less than ttlMs\");\n\t}\n\treturn { ttlMs, heartbeatIntervalMs };\n}\n\nfunction activeWriterError(sessionId: string): SessionError {\n\treturn new SessionError(\"storage\", `SQLite session ${sessionId} already has an active writer`);\n}\n\nfunction lostWriterError(sessionId: string): SessionError {\n\treturn new SessionError(\"storage\", `SQLite session ${sessionId} writer lease was lost`);\n}\n\nfunction claimWriterLease(db: SqliteDatabase, sessionId: string, options: ResolvedWriterLeaseOptions): WriterLease {\n\tconst now = Date.now();\n\tconst lease = acquireWriterLease(db, sessionId, uuidv7(), now, now + options.ttlMs);\n\tif (!lease) throw activeWriterError(sessionId);\n\treturn lease;\n}\n\nclass SerialOperationQueue {\n\tprivate tail: Promise<void> = Promise.resolve();\n\n\tenqueue<T>(operation: () => Promise<T> | T): Promise<T> {\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync drain(): Promise<void> {\n\t\tawait this.tail;\n\t}\n}\n\nfunction resultOrThrow<T>(result: Result<T, FileError>, message: string): T {\n\tif (!result.ok) {\n\t\tconst code = result.error.code === \"not_found\" ? \"not_found\" : \"storage\";\n\t\tthrow new SessionError(code, `${message}: ${result.error.message}`, result.error);\n\t}\n\treturn result.value;\n}\n\nfunction getParentPath(path: string): string {\n\tconst normalized = path.replace(/[\\\\/]+$/, \"\");\n\tconst lastSlash = Math.max(normalized.lastIndexOf(\"/\"), normalized.lastIndexOf(\"\\\\\"));\n\tif (lastSlash < 0) return \".\";\n\tif (lastSlash === 0) return normalized.slice(0, 1);\n\treturn normalized.slice(0, lastSlash);\n}\n\nfunction configureSqliteDatabase(db: SqliteDatabase): void {\n\tsql`PRAGMA journal_mode=WAL`.exec(db);\n\tsql`PRAGMA synchronous=FULL`.exec(db);\n\tsql`PRAGMA busy_timeout=5000`.exec(db);\n}\n\nfunction timestampToText(timestamp: number): string {\n\treturn new Date(timestamp).toISOString();\n}\n\nfunction timestampFromText(timestamp: string): number {\n\treturn Date.parse(timestamp);\n}\n\nfunction entryRowFromCached(row: CachedBranchEntryRow): EntryRow {\n\treturn { ...row, seq: row.entry_seq, type: row.type as Entry[\"type\"] };\n}\n\nfunction readObjectPayload(row: EntryRow): Record<string, unknown> {\n\tconst payload = JSON.parse(row.payload) as unknown;\n\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n\t\tthrow new Error(\"Payload is not an object\");\n\t}\n\treturn payload as Record<string, unknown>;\n}\n\nfunction decodeEntry(row: EntryRow): Entry {\n\ttry {\n\t\tconst payload = readObjectPayload(row);\n\t\tconst timestamp = timestampFromText(row.timestamp);\n\t\tif (!Number.isFinite(timestamp)) throw new Error(`Invalid timestamp ${row.timestamp}`);\n\t\tconst base = { id: row.id, seq: row.seq, parentId: row.parent_id, timestamp };\n\t\tswitch (row.type) {\n\t\t\tcase \"message\":\n\t\t\t\tif (typeof payload.message !== \"object\" || payload.message === null) throw new Error(\"Missing message\");\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\tmessage: payload.message as Extract<Entry, { type: \"message\" }>[\"message\"],\n\t\t\t\t\t...(payload.terminate === true ? { terminate: true as const } : {}),\n\t\t\t\t};\n\t\t\tcase \"model_change\":\n\t\t\t\tif (typeof payload.provider !== \"string\" || typeof payload.modelId !== \"string\") {\n\t\t\t\t\tthrow new Error(\"Invalid model_change payload\");\n\t\t\t\t}\n\t\t\t\treturn { ...base, type: \"model_change\", provider: payload.provider, modelId: payload.modelId };\n\t\t\tcase \"thinking_level_change\":\n\t\t\t\tif (typeof payload.thinkingLevel !== \"string\") throw new Error(\"Invalid thinking_level_change payload\");\n\t\t\t\treturn { ...base, type: \"thinking_level_change\", thinkingLevel: payload.thinkingLevel };\n\t\t\tcase \"active_tools_change\":\n\t\t\t\tif (!Array.isArray(payload.activeToolNames)) throw new Error(\"Invalid active_tools_change payload\");\n\t\t\t\tif (payload.activeToolNames.some((value) => typeof value !== \"string\")) {\n\t\t\t\t\tthrow new Error(\"Invalid active_tools_change payload\");\n\t\t\t\t}\n\t\t\t\treturn { ...base, type: \"active_tools_change\", activeToolNames: payload.activeToolNames };\n\t\t\tcase \"compaction\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof payload.summary !== \"string\" ||\n\t\t\t\t\t!Array.isArray(payload.retainedTail) ||\n\t\t\t\t\ttypeof payload.tokensBefore !== \"number\"\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"Invalid compaction payload\");\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"compaction\",\n\t\t\t\t\tsummary: payload.summary,\n\t\t\t\t\tretainedTail: payload.retainedTail as Extract<Entry, { type: \"compaction\" }>[\"retainedTail\"],\n\t\t\t\t\ttokensBefore: payload.tokensBefore,\n\t\t\t\t\t...(Object.hasOwn(payload, \"details\") ? { details: payload.details } : {}),\n\t\t\t\t\t...(Object.hasOwn(payload, \"usage\")\n\t\t\t\t\t\t? { usage: payload.usage as Extract<Entry, { type: \"compaction\" }>[\"usage\"] }\n\t\t\t\t\t\t: {}),\n\t\t\t\t};\n\t\t\tcase \"branch_summary\":\n\t\t\t\tif (typeof payload.fromId !== \"string\" || typeof payload.summary !== \"string\") {\n\t\t\t\t\tthrow new Error(\"Invalid branch_summary payload\");\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"branch_summary\",\n\t\t\t\t\tfromId: payload.fromId,\n\t\t\t\t\tsummary: payload.summary,\n\t\t\t\t\t...(Object.hasOwn(payload, \"details\") ? { details: payload.details } : {}),\n\t\t\t\t\t...(Object.hasOwn(payload, \"usage\")\n\t\t\t\t\t\t? { usage: payload.usage as Extract<Entry, { type: \"branch_summary\" }>[\"usage\"] }\n\t\t\t\t\t\t: {}),\n\t\t\t\t};\n\t\t\tcase \"custom\":\n\t\t\t\tif (typeof payload.customType !== \"string\") throw new Error(\"Invalid custom payload\");\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\tcustomType: payload.customType,\n\t\t\t\t\t...(Object.hasOwn(payload, \"data\") ? { data: payload.data } : {}),\n\t\t\t\t};\n\t\t}\n\t} catch (error) {\n\t\tthrow new SessionError(\n\t\t\t\"invalid_entry\",\n\t\t\t`Invalid SQLite session entry ${row.id}: failed to decode entry ${row.id}`,\n\t\t\terror instanceof Error ? error : undefined,\n\t\t);\n\t}\n}\n\nfunction recordRunId(record: NewRecord): string | undefined {\n\treturn record.type === \"operation_started\" ? record.id : \"runId\" in record ? record.runId : undefined;\n}\n\nfunction recordOpKind(record: NewRecord): string | undefined {\n\treturn record.type === \"operation_started\" ? record.intent.kind : undefined;\n}\n\nfunction decodeRecord(row: { seq: number; timestamp: string; payload: string }): LaneRecord {\n\ttry {\n\t\tconst timestamp = timestampFromText(row.timestamp);\n\t\tif (!Number.isFinite(timestamp)) throw new Error(`Invalid timestamp ${row.timestamp}`);\n\t\treturn {\n\t\t\t...(JSON.parse(row.payload) as object),\n\t\t\tseq: row.seq,\n\t\t\ttimestamp,\n\t\t} as LaneRecord;\n\t} catch (error) {\n\t\tthrow new SessionError(\n\t\t\t\"storage\",\n\t\t\t`Invalid SQLite session record at sequence ${row.seq}: failed to decode payload`,\n\t\t\terror instanceof Error ? error : undefined,\n\t\t);\n\t}\n}\n\nfunction validateCachedBranchRows(rows: readonly CachedBranchEntryRow[], query: BranchBounds & EntryQuery): void {\n\tif (rows.length === 0 || query.type !== undefined || query.customType !== undefined) return;\n\tconst path = [...rows].sort((left, right) => left.entry_seq - right.entry_seq);\n\tconst shouldIncludeRoot =\n\t\tquery.stopAtId === undefined &&\n\t\tquery.stopAtType === undefined &&\n\t\tquery.cursor === undefined &&\n\t\t(query.order === \"oldestFirst\" || query.limit === undefined);\n\tif (shouldIncludeRoot && path[0]?.parent_id !== null) {\n\t\tthrow new SessionError(\"invalid_entry\", `Entry ${path[0]?.parent_id} not found`);\n\t}\n\tfor (let index = 1; index < path.length; index++) {\n\t\tconst previous = path[index - 1]!;\n\t\tconst current = path[index]!;\n\t\tif (current.parent_id !== previous.id) {\n\t\t\tthrow new SessionError(\"invalid_entry\", `Entry ${current.parent_id} not found`);\n\t\t}\n\t}\n}\n\nfunction matchesEntryQuery(entry: Entry, query: EntryQuery): boolean {\n\treturn (\n\t\t(query.type === undefined || entry.type === query.type) &&\n\t\t(query.customType === undefined || (entry.type === \"custom\" && entry.customType === query.customType)) &&\n\t\t(query.cursor === undefined ||\n\t\t\t(query.order === \"oldestFirst\" ? entry.seq > query.cursor.afterSeq : entry.seq < query.cursor.afterSeq))\n\t);\n}\n\nfunction assertUnusedId(db: SqliteDatabase, sessionId: string, id: string): void {\n\tif (idExistsInEntries(db, sessionId, id) || idExistsInRecords(db, sessionId, id)) {\n\t\tthrow new SessionError(\"already_exists\", `ID already exists: ${id}`);\n\t}\n}\n\nfunction requireSessionRow(db: SqliteDatabase, sessionId: string): SessionRow {\n\tconst row = readSessionRow(db, sessionId);\n\tif (!row) throw new SessionError(\"not_found\", `Session not found: ${sessionId}`);\n\treturn row;\n}\n\nclass SqliteSessionStorage implements SessionStorage<SqliteSessionMetadata> {\n\tprivate readonly db: SqliteDatabase;\n\tprivate readonly metadata: SqliteSessionMetadata;\n\tprivate readonly lease: WriterLease;\n\tprivate readonly leaseOptions: ResolvedWriterLeaseOptions;\n\tprivate readonly onRelease: () => void;\n\tprivate readonly operations = new SerialOperationQueue();\n\tprivate heartbeatTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate leaseError: SessionError | undefined;\n\tprivate closing = false;\n\tprivate releasePromise: Promise<void> | undefined;\n\n\tconstructor(\n\t\tdb: SqliteDatabase,\n\t\tmetadata: SqliteSessionMetadata,\n\t\tlease: WriterLease,\n\t\tleaseOptions: ResolvedWriterLeaseOptions,\n\t\tonRelease: () => void,\n\t) {\n\t\tthis.db = db;\n\t\tthis.metadata = metadata;\n\t\tthis.lease = lease;\n\t\tthis.leaseOptions = leaseOptions;\n\t\tthis.onRelease = onRelease;\n\t\tthis.scheduleHeartbeat();\n\t}\n\n\tasync release(): Promise<void> {\n\t\tthis.releasePromise ??= this.finishRelease();\n\t\tawait this.releasePromise;\n\t}\n\n\tprivate async finishRelease(): Promise<void> {\n\t\tthis.closing = true;\n\t\tif (this.heartbeatTimer !== undefined) clearTimeout(this.heartbeatTimer);\n\t\ttry {\n\t\t\tawait this.operations.enqueue(() =>\n\t\t\t\tthis.db.transaction(() => releaseWriterLease(this.db, this.metadata.id, this.lease)),\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.onRelease();\n\t\t}\n\t}\n\n\tprivate enqueueWrite<T>(operation: () => T): Promise<T> {\n\t\tif (this.closing)\n\t\t\treturn Promise.reject(new SessionError(\"storage\", `SQLite session ${this.metadata.id} is closed`));\n\t\treturn this.operations.enqueue(() => {\n\t\t\tif (this.leaseError) throw this.leaseError;\n\t\t\treturn this.db.transaction(() => {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tif (!renewWriterLease(this.db, this.metadata.id, this.lease, now, now + this.leaseOptions.ttlMs)) {\n\t\t\t\t\tthis.leaseError = lostWriterError(this.metadata.id);\n\t\t\t\t\tif (this.heartbeatTimer !== undefined) clearTimeout(this.heartbeatTimer);\n\t\t\t\t\tthrow this.leaseError;\n\t\t\t\t}\n\t\t\t\treturn operation();\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate scheduleHeartbeat(): void {\n\t\tif (this.closing || this.leaseError) return;\n\t\tthis.heartbeatTimer = setTimeout(async () => {\n\t\t\tthis.heartbeatTimer = undefined;\n\t\t\ttry {\n\t\t\t\tawait this.operations.enqueue(() => {\n\t\t\t\t\tif (this.closing || this.leaseError) return;\n\t\t\t\t\tthis.db.transaction(() => {\n\t\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\t\tif (!renewWriterLease(this.db, this.metadata.id, this.lease, now, now + this.leaseOptions.ttlMs)) {\n\t\t\t\t\t\t\tthis.leaseError = lostWriterError(this.metadata.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// A transient heartbeat failure is retried. Every write still verifies ownership transactionally.\n\t\t\t} finally {\n\t\t\t\tthis.scheduleHeartbeat();\n\t\t\t}\n\t\t}, this.leaseOptions.heartbeatIntervalMs);\n\t\tthis.heartbeatTimer.unref();\n\t}\n\n\tasync getMetadata(): Promise<SqliteSessionMetadata> {\n\t\treturn decodeSessionMetadata(requireSessionRow(this.db, this.metadata.id), this.metadata.path);\n\t}\n\n\tisForSession(sessionId: string): boolean {\n\t\treturn this.metadata.id === sessionId;\n\t}\n\n\tasync getLanes(): Promise<{ lane: string; leafId: string | null }[]> {\n\t\treturn readLanes(this.db, this.metadata.id).map((row) => ({ lane: row.lane, leafId: row.leaf_id }));\n\t}\n\n\tasync createLane(lane: string, at: string | null): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (readLane(this.db, this.metadata.id, lane)) {\n\t\t\t\tthrow new SessionError(\"already_exists\", `Lane already exists: ${lane}`);\n\t\t\t}\n\t\t\tif (at !== null && !readEntryRow(this.db, this.metadata.id, at)) {\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${at}`);\n\t\t\t}\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tinsertLane(this.db, this.metadata.id, seq, lane, at);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync moveLane(lane: string, to: string | null): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (!readLane(this.db, this.metadata.id, lane))\n\t\t\t\tthrow new SessionError(\"invalid_lane\", `Lane not found: ${lane}`);\n\t\t\tif (to !== null && !readEntryRow(this.db, this.metadata.id, to)) {\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${to}`);\n\t\t\t}\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tupdateLane(this.db, this.metadata.id, seq, lane, to);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync appendEntry<TEntry extends Entry>(entry: ProvisionedEntry<TEntry>, lane: string): Promise<TEntry> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tconst parentId = readLaneHead(this.db, this.metadata.id, lane).leafId;\n\t\t\tassertUnusedId(this.db, this.metadata.id, entry.id);\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tconst committed = { ...entry, parentId, seq, timestamp: Date.now() } as Entry;\n\t\t\tinsertEntryRow(this.db, this.metadata.id, {\n\t\t\t\tseq,\n\t\t\t\tid: committed.id,\n\t\t\t\tparentId: committed.parentId,\n\t\t\t\ttype: committed.type,\n\t\t\t\ttimestamp: timestampToText(committed.timestamp),\n\t\t\t\tpayload: JSON.stringify(entryPayload(committed)),\n\t\t\t});\n\t\t\tsetLaneLeaf(this.db, this.metadata.id, lane, committed.id);\n\t\t\tappendEntryToBranchCache(\n\t\t\t\tthis.db,\n\t\t\t\tthis.metadata.id,\n\t\t\t\tcommitted.id,\n\t\t\t\tseq,\n\t\t\t\tcommitted.type,\n\t\t\t\tcommitted.type === \"custom\" ? committed.customType : null,\n\t\t\t\tcommitted.parentId,\n\t\t\t);\n\t\t\tif (committed.type === \"message\") incrementMessageCount(this.db, this.metadata.id);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t\treturn structuredClone(committed as TEntry);\n\t\t});\n\t}\n\n\tasync appendRecord<TRecord extends LaneRecord>(record: NewRecord<TRecord>): Promise<TRecord>;\n\tasync appendRecord(record: NewRecord): Promise<LaneRecord> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (!readLane(this.db, this.metadata.id, record.lane)) {\n\t\t\t\tthrow new SessionError(\"invalid_lane\", `Lane not found: ${record.lane}`);\n\t\t\t}\n\t\t\tassertUnusedId(this.db, this.metadata.id, record.id);\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tconst committed: LaneRecord = { ...record, seq, timestamp: Date.now() };\n\t\t\tif (record.type === \"operation_started\") {\n\t\t\t\tstartLaneOperation(this.db, this.metadata.id, record.lane, record.id);\n\t\t\t}\n\t\t\tappendRecordRow(this.db, this.metadata.id, {\n\t\t\t\tseq,\n\t\t\t\tid: record.id,\n\t\t\t\tlane: record.lane,\n\t\t\t\trunId: recordRunId(record),\n\t\t\t\ttype: record.type,\n\t\t\t\topKind: recordOpKind(record),\n\t\t\t\ttimestamp: timestampToText(committed.timestamp),\n\t\t\t\tpayload: JSON.stringify(record),\n\t\t\t});\n\t\t\tif (record.type === \"operation_finished\") {\n\t\t\t\tfinishLaneOperation(this.db, this.metadata.id, record.lane, record.runId);\n\t\t\t}\n\t\t\tif (record.type === \"usage\") addUsageToStats(this.db, this.metadata.id, record.usage);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t\treturn structuredClone(committed);\n\t\t});\n\t}\n\n\tasync getEntry(id: string): Promise<Entry | undefined> {\n\t\tconst row = readEntryRow(this.db, this.metadata.id, id);\n\t\treturn row ? decodeEntry(row) : undefined;\n\t}\n\n\tasync findEntries(query: EntryQuery = {}): Promise<Entry[]> {\n\t\tconst rows = readEntryRows(this.db, this.metadata.id, { order: query.order });\n\t\tconst entries = rows.map(decodeEntry).filter((entry) => matchesEntryQuery(entry, query));\n\t\treturn query.limit === undefined ? entries : entries.slice(0, query.limit);\n\t}\n\n\tasync findEntriesOnBranch(query: EntryQuery & BranchBounds & { start: string }): Promise<Entry[]> {\n\t\tconst cached = readCachedBranch(this.db, this.metadata.id, query.start);\n\t\tif (!cached) {\n\t\t\tif (!readEntryRow(this.db, this.metadata.id, query.start))\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${query.start}`);\n\t\t\tthrow new SessionError(\"invalid_entry\", `Branch cache missing entry ${query.start}`);\n\t\t}\n\t\tconst rows = queryCachedBranchRows(this.db, this.metadata.id, cached, query);\n\t\tvalidateCachedBranchRows(rows, query);\n\t\tconst entries = rows\n\t\t\t.map(entryRowFromCached)\n\t\t\t.map(decodeEntry)\n\t\t\t.filter((entry) => matchesEntryQuery(entry, query));\n\t\treturn query.limit === undefined ? entries : entries.slice(0, query.limit);\n\t}\n\n\tasync findRecords(query: RecordQuery = {}): Promise<LaneRecord[]> {\n\t\tconst rows = readRecordRows(this.db, this.metadata.id, query);\n\t\treturn rows.map(decodeRecord);\n\t}\n\n\tasync findOpenOperations(lane: string, options?: { limit?: number }): Promise<OperationStartedRecord[]> {\n\t\tconst rows = readOpenOperationRows(this.db, this.metadata.id, lane, options);\n\n\t\treturn rows.map((row) => {\n\t\t\tconst record = decodeRecord(row);\n\t\t\tif (record.type !== \"operation_started\") {\n\t\t\t\tthrow new SessionError(\"storage\", \"Expected operation_started record\");\n\t\t\t}\n\t\t\treturn record;\n\t\t});\n\t}\n\n\tasync getLog(options: LogOptions = {}): Promise<LogItem[]> {\n\t\tconst afterSeq = options.afterSeq ?? 0;\n\t\tconst limit = options.limit;\n\t\tconst entryRows = readEntryRows(this.db, this.metadata.id, { afterSeq, order: \"oldestFirst\", limit });\n\t\tconst recordRows = readRecordRows(this.db, this.metadata.id, { afterSeq, order: \"oldestFirst\", limit });\n\t\tconst laneRows = readLaneMoveRows(this.db, this.metadata.id, { afterSeq, limit });\n\t\tconst factRows = readFactRows(this.db, this.metadata.id, { afterSeq, limit });\n\n\t\tconst logRows: { seq: number; decode: () => LogItem }[] = [\n\t\t\t...entryRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => ({ kind: \"entry\" as const, seq: row.seq, entry: decodeEntry(row) }),\n\t\t\t})),\n\t\t\t...recordRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => ({ kind: \"record\" as const, seq: row.seq, record: decodeRecord(row) }),\n\t\t\t})),\n\t\t\t...laneRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => ({ kind: \"lane\" as const, seq: row.seq, lane: row.lane, leafId: row.leaf_id }),\n\t\t\t})),\n\t\t\t...factRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => {\n\t\t\t\t\tif (row.kind === \"name\")\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: \"fact\" as const,\n\t\t\t\t\t\t\tseq: row.seq,\n\t\t\t\t\t\t\tfact: \"name\" as const,\n\t\t\t\t\t\t\tname: JSON.parse(row.value ?? \"null\") as string,\n\t\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"fact\" as const,\n\t\t\t\t\t\tseq: row.seq,\n\t\t\t\t\t\tfact: \"label\" as const,\n\t\t\t\t\t\ttargetId: row.key ?? \"\",\n\t\t\t\t\t\tlabel: row.value === null ? undefined : (JSON.parse(row.value) as string),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t})),\n\t\t].sort((left, right) => left.seq - right.seq);\n\t\tconst selectedRows = options.limit === undefined ? logRows : logRows.slice(0, options.limit);\n\t\treturn selectedRows.map((row) => row.decode());\n\t}\n\n\tasync getName(): Promise<string | undefined> {\n\t\tconst row = readLatestFact(this.db, this.metadata.id, \"name\", null);\n\t\treturn row?.value === undefined || row.value === null ? undefined : (JSON.parse(row.value) as string);\n\t}\n\n\tasync setName(name: string): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tappendFact(this.db, this.metadata.id, seq, \"name\", null, JSON.stringify(name));\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\tconst row = readLatestFact(this.db, this.metadata.id, \"label\", id);\n\t\treturn row?.value === undefined || row.value === null ? undefined : (JSON.parse(row.value) as string);\n\t}\n\n\tasync setLabel(id: string, label: string | undefined): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (!readEntryRow(this.db, this.metadata.id, id)) {\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${id}`);\n\t\t\t}\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tappendFact(this.db, this.metadata.id, seq, \"label\", id, label === undefined ? null : JSON.stringify(label));\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync getStats(): Promise<SessionStats> {\n\t\treturn readStats(this.db, this.metadata.id);\n\t}\n}\n\nfunction claimStorage(\n\tdb: SqliteDatabase,\n\tmetadata: SqliteSessionMetadata,\n\tleaseOptions: ResolvedWriterLeaseOptions,\n\tonRelease: () => void,\n): SqliteSessionStorage {\n\trequireSessionRow(db, metadata.id);\n\tconst claimed = db.transaction(() => {\n\t\tconst lease = claimWriterLease(db, metadata.id, leaseOptions);\n\t\tconst row = requireSessionRow(db, metadata.id);\n\t\treadLanes(db, metadata.id);\n\t\treturn { lease, row };\n\t});\n\treturn new SqliteSessionStorage(\n\t\tdb,\n\t\tdecodeSessionMetadata(claimed.row, metadata.path),\n\t\tclaimed.lease,\n\t\tleaseOptions,\n\t\tonRelease,\n\t);\n}\n\nexport class SqliteSessionRepository\n\timplements\n\t\tSessionRepository<SqliteSessionMetadata, SqliteSessionCreateOptions, SqliteSessionListOptions>,\n\t\tAsyncDisposable\n{\n\tprivate databasePath: string | undefined;\n\tprivate database: SqliteDatabase | undefined;\n\tprivate databasePromise: Promise<SqliteDatabase> | undefined;\n\tprivate readonly operations = new SerialOperationQueue();\n\tprivate readonly activeStorages = new Set<SqliteSessionStorage>();\n\tprivate readonly options: SqliteSessionRepositoryOptions;\n\tprivate readonly leaseOptions: ResolvedWriterLeaseOptions;\n\n\tconstructor(options: SqliteSessionRepositoryOptions) {\n\t\tthis.options = options;\n\t\tthis.leaseOptions = resolveWriterLeaseOptions(options.writerLease);\n\t}\n\n\tprivate async releaseStoragesForSession(sessionId: string): Promise<void> {\n\t\tfor (const storage of [...this.activeStorages]) {\n\t\t\tif (storage.isForSession(sessionId)) await storage.release();\n\t\t}\n\t}\n\n\tprivate sessionFromLease(\n\t\tdb: SqliteDatabase,\n\t\tmetadata: SqliteSessionMetadata,\n\t\tlease: WriterLease,\n\t): Session<SqliteSessionMetadata> {\n\t\tlet storage: SqliteSessionStorage;\n\t\tstorage = new SqliteSessionStorage(db, metadata, lease, this.leaseOptions, () => {\n\t\t\tthis.activeStorages.delete(storage);\n\t\t});\n\t\tthis.activeStorages.add(storage);\n\t\treturn new Session(storage);\n\t}\n\n\tprivate claimSession(db: SqliteDatabase, metadata: SqliteSessionMetadata): Session<SqliteSessionMetadata> {\n\t\tconst active = [...this.activeStorages].find((storage) => storage.isForSession(metadata.id));\n\t\tif (active) {\n\t\t\treadLanes(db, metadata.id);\n\t\t\treturn new Session(active);\n\t\t}\n\t\tlet storage: SqliteSessionStorage;\n\t\tstorage = claimStorage(db, metadata, this.leaseOptions, () => {\n\t\t\tthis.activeStorages.delete(storage);\n\t\t});\n\t\tthis.activeStorages.add(storage);\n\t\treturn new Session(storage);\n\t}\n\n\tasync create(options: SqliteSessionCreateOptions): Promise<Session<SqliteSessionMetadata>> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tconst db = await this.getDatabase();\n\t\t\tconst path = await this.getDatabasePath();\n\t\t\tconst id = options.id ?? uuidv7();\n\t\t\tif (sessionExists(db, id)) throw new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\t\t\tconst createdAt = Date.now();\n\t\t\tconst lease = db.transaction(() => {\n\t\t\t\tinsertSessionRow(db, {\n\t\t\t\t\tid,\n\t\t\t\t\tcreatedAt: timestampToText(createdAt),\n\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\tparentSessionId: options.parentSessionId,\n\t\t\t\t\tmetadata: options.metadata,\n\t\t\t\t});\n\t\t\t\tcreateSequence(db, id);\n\t\t\t\tcreateStats(db, id);\n\t\t\t\tcreateInitialLane(db, id);\n\t\t\t\treturn claimWriterLease(db, id, this.leaseOptions);\n\t\t\t});\n\t\t\tconst row = requireSessionRow(db, id);\n\t\t\treturn this.sessionFromLease(db, decodeSessionMetadata(row, path), lease);\n\t\t});\n\t}\n\n\tasync open(metadata: SqliteSessionMetadata): Promise<Session<SqliteSessionMetadata>> {\n\t\treturn this.operations.enqueue(async () => this.claimSession(await this.getDatabase(), metadata));\n\t}\n\n\t/** Rebuilds this session's private branch-read cache from canonical entry parent links. */\n\tasync repairBranchCache(metadata: SqliteSessionMetadata): Promise<void> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tawait this.releaseStoragesForSession(metadata.id);\n\t\t\tconst db = await this.getDatabase();\n\t\t\tdb.transaction(() => {\n\t\t\t\tconst lease = claimWriterLease(db, metadata.id, this.leaseOptions);\n\t\t\t\trequireSessionRow(db, metadata.id);\n\t\t\t\trebuildBranchCache(db, metadata.id);\n\t\t\t\treleaseWriterLease(db, metadata.id, lease);\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Reads the session catalog without acquiring or renewing per-session writer leases. */\n\tasync list(options: SqliteSessionListOptions = {}): Promise<SqliteSessionMetadata[]> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tconst path = await this.getDatabasePath();\n\t\t\tif (!resultOrThrow(await this.options.env.exists(path), `Failed to check database ${path}`)) return [];\n\t\t\tconst db = await this.getDatabase();\n\t\t\tconst rows = readSessionRows(db, options);\n\t\t\treturn rows.map((row) => decodeSessionMetadata(row, path));\n\t\t});\n\t}\n\n\tasync delete(metadata: SqliteSessionMetadata): Promise<void> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tawait this.releaseStoragesForSession(metadata.id);\n\t\t\tconst db = await this.getDatabase();\n\t\t\tdb.transaction(() => {\n\t\t\t\tif (!sessionExists(db, metadata.id)) {\n\t\t\t\t\tdeleteWriterLease(db, metadata.id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclaimWriterLease(db, metadata.id, this.leaseOptions);\n\t\t\t\tdeleteBranchCache(db, metadata.id);\n\t\t\t\tdeleteFactRows(db, metadata.id);\n\t\t\t\tdeleteLaneRows(db, metadata.id);\n\t\t\t\tdeleteRecordRows(db, metadata.id);\n\t\t\t\tdeleteEntryRows(db, metadata.id);\n\t\t\t\tdeleteWriterLease(db, metadata.id);\n\t\t\t\tdeleteStats(db, metadata.id);\n\t\t\t\tdeleteSequence(db, metadata.id);\n\t\t\t\tdeleteSessionRow(db, metadata.id);\n\t\t\t});\n\t\t});\n\t}\n\n\tasync fork(\n\t\tsource: SqliteSessionMetadata,\n\t\toptions: ForkOptions & SqliteSessionCreateOptions,\n\t): Promise<Session<SqliteSessionMetadata>> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tconst db = await this.getDatabase();\n\t\t\tconst path = await this.getDatabasePath();\n\t\t\tconst sourceMetadata = decodeSessionMetadata(requireSessionRow(db, source.id), path);\n\t\t\tconst id = options.id ?? uuidv7();\n\t\t\tif (sessionExists(db, id)) throw new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\n\t\t\tconst entries: EntryRow[] = [];\n\t\t\tconst lanes: { lane: string; leafId: string | null }[] = [];\n\t\t\tconst branchTips: string[] = [];\n\t\t\tlet branchForkTargetId: string | null = null;\n\n\t\t\tif (options.scope === \"tree\") {\n\t\t\t\tentries.push(...readEntryRows(db, source.id, { order: \"oldestFirst\" }));\n\t\t\t\tlanes.push(...readLanes(db, source.id).map((row) => ({ lane: row.lane, leafId: row.leaf_id })));\n\t\t\t\tbranchTips.push(...readBranchTipIds(db, source.id));\n\t\t\t} else {\n\t\t\t\tconst main = readLane(db, source.id, \"main\");\n\t\t\t\tif (!main) throw new SessionError(\"invalid_lane\", \"Lane not found: main\");\n\t\t\t\tconst selectedEntryId = options.entryId ?? main.leaf_id;\n\t\t\t\tif (selectedEntryId !== null) {\n\t\t\t\t\tconst target = readEntryRow(db, source.id, selectedEntryId);\n\t\t\t\t\tif (!target || target.type !== \"message\") {\n\t\t\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\t\t\"invalid_fork_target\",\n\t\t\t\t\t\t\t`Fork target is not a message entry: ${selectedEntryId}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst position = options.position ?? (options.entryId === undefined ? \"at\" : \"before\");\n\t\t\t\t\tbranchForkTargetId = position === \"at\" ? target.id : target.parent_id;\n\t\t\t\t}\n\t\t\t\tlanes.push({ lane: \"main\", leafId: branchForkTargetId });\n\t\t\t\tif (branchForkTargetId !== null) {\n\t\t\t\t\tconst cached = readCachedBranch(db, source.id, branchForkTargetId);\n\t\t\t\t\tif (!cached) {\n\t\t\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\t\t\"invalid_fork_target\",\n\t\t\t\t\t\t\t`Fork target is not on a cached branch: ${branchForkTargetId}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst rows = queryCachedBranchRows(db, source.id, cached, { order: \"oldestFirst\" });\n\t\t\t\t\tentries.push(...rows.map(entryRowFromCached));\n\t\t\t\t\tbranchTips.push(branchForkTargetId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst copiedIds = new Set(entries.map((entry) => entry.id));\n\t\t\tconst latestName = readLatestFact(db, source.id, \"name\", null);\n\t\t\tconst latestLabels = readLatestLabelFacts(db, source.id);\n\t\t\tconst labelsToCopy = latestLabels.filter(\n\t\t\t\t(row) => options.scope === \"tree\" || (row.key !== null && copiedIds.has(row.key)),\n\t\t\t);\n\t\t\tconst createdAt = Date.now();\n\t\t\tconst metadata = options.metadata ?? sourceMetadata.metadata;\n\t\t\tlet lease: WriterLease;\n\n\t\t\ttry {\n\t\t\t\tlease = db.transaction(() => {\n\t\t\t\t\tinsertSessionRow(db, {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tcreatedAt: timestampToText(createdAt),\n\t\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\t\tparentSessionId: options.parentSessionId ?? source.id,\n\t\t\t\t\t\tmetadata,\n\t\t\t\t\t});\n\t\t\t\t\tcreateSequence(db, id);\n\t\t\t\t\tcreateStats(db, id, entries.filter((entry) => entry.type === \"message\").length);\n\n\t\t\t\t\tlet nextSeq = 1;\n\t\t\t\t\tconst allocateSeq = () => nextSeq++;\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tinsertEntryRow(db, id, {\n\t\t\t\t\t\t\tseq: allocateSeq(),\n\t\t\t\t\t\t\tid: entry.id,\n\t\t\t\t\t\t\tparentId: entry.parent_id,\n\t\t\t\t\t\t\ttype: entry.type,\n\t\t\t\t\t\t\ttimestamp: entry.timestamp,\n\t\t\t\t\t\t\tpayload: entry.payload,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tif (options.scope === \"tree\") {\n\t\t\t\t\t\tfor (const lane of lanes) insertLane(db, id, allocateSeq(), lane.lane, lane.leafId);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcreateInitialLane(db, id, \"main\", branchForkTargetId);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (latestName?.value !== undefined && latestName.value !== null) {\n\t\t\t\t\t\tappendFact(db, id, allocateSeq(), \"name\", null, latestName.value);\n\t\t\t\t\t}\n\t\t\t\t\tfor (const label of labelsToCopy) appendFact(db, id, allocateSeq(), \"label\", label.key, label.value);\n\n\t\t\t\t\tsetNextSequence(db, id, nextSeq);\n\t\t\t\t\tfor (const tip of branchTips) buildCachedBranch(db, id, tip);\n\t\t\t\t\treturn claimWriterLease(db, id, this.leaseOptions);\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof SessionError) throw error;\n\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\"storage\",\n\t\t\t\t\t`Failed to fork SQLite session ${id}`,\n\t\t\t\t\terror instanceof Error ? error : undefined,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst row = requireSessionRow(db, id);\n\t\t\treturn this.sessionFromLease(db, decodeSessionMetadata(row, path), lease);\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tawait this.operations.drain();\n\t\tfor (const storage of [...this.activeStorages]) await storage.release();\n\t\tif (this.database) this.database.close();\n\t\tthis.database = undefined;\n\t\tthis.databasePromise = undefined;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.close();\n\t}\n\n\tprivate async getDatabasePath(): Promise<string> {\n\t\tthis.databasePath ??= resultOrThrow(\n\t\t\tawait this.options.env.absolutePath(this.options.databasePath),\n\t\t\t`Failed to resolve SQLite sessions database ${this.options.databasePath}`,\n\t\t);\n\t\treturn this.databasePath;\n\t}\n\n\tprivate async getDatabase(): Promise<SqliteDatabase> {\n\t\tif (!this.databasePromise) this.databasePromise = this.openDatabase();\n\t\tthis.database = await this.databasePromise;\n\t\treturn this.database;\n\t}\n\n\tprivate async openDatabase(): Promise<SqliteDatabase> {\n\t\tconst path = await this.getDatabasePath();\n\t\tresultOrThrow(\n\t\t\tawait this.options.env.createDir(getParentPath(path), { recursive: true }),\n\t\t\t`Failed to create SQLite sessions directory ${path}`,\n\t\t);\n\t\tconst db = await this.options.sqlite.open(path);\n\t\ttry {\n\t\t\tconfigureSqliteDatabase(db);\n\t\t\tawait applyMigrations(db);\n\t\t\treturn db;\n\t\t} catch (error) {\n\t\t\tdb.close();\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../src/sqlite/repo.ts"],"names":[],"mappings":"AACA,OAAO,EAIN,KAAK,WAAW,EAQhB,OAAO,EAEP,KAAK,WAAW,IAAI,iBAAiB,EAGrC,MAAM,+BAA+B,CAAC;AAmEvC,OAAO,KAAK,EAEX,qBAAqB,EACrB,0BAA0B,EAC1B,wBAAwB,EACxB,qBAAqB,EACrB,0BAA0B,EAC1B,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,wBAAwB;IACxC,oGAAoG;IACpG,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,8BAA8B;IAC9C,GAAG,EAAE,0BAA0B,CAAC;IAChC,MAAM,EAAE,qBAAqB,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,wBAAwB,CAAC;CACvC;AAkjBD,qBAAa,uBACZ,YACC,iBAAiB,CAAC,qBAAqB,EAAE,0BAA0B,EAAE,wBAAwB,CAAC,EAC9F,eAAe;IAEhB,OAAO,CAAC,YAAY,CAAqB;IACzC,OAAO,CAAC,QAAQ,CAA6B;IAC7C,OAAO,CAAC,eAAe,CAAsC;IAC7D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA8B;IACzD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAmC;IAClE,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAiC;IACzD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA6B;IAE1D,YAAY,OAAO,EAAE,8BAA8B,EAGlD;YAEa,yBAAyB;IAMvC,OAAO,CAAC,gBAAgB;IAaxB,OAAO,CAAC,YAAY;IAcd,MAAM,CAAC,OAAO,EAAE,0BAA0B,GAAG,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC,CAuBzF;IAEK,IAAI,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC,CAEnF;IAED,2FAA2F;IACrF,iBAAiB,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAWtE;IAED,yFAAyF;IACnF,IAAI,CAAC,OAAO,GAAE,wBAA6B,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC,CAQnF;IAEK,MAAM,CAAC,QAAQ,EAAE,qBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAqB3D;IAEK,IAAI,CACT,MAAM,EAAE,qBAAqB,EAC7B,OAAO,EAAE,WAAW,GAAG,0BAA0B,GAC/C,OAAO,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAC,CA6GzC;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAM3B;IAEK,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3C;YAEa,eAAe;YAQf,WAAW;YAMX,YAAY;CAgB1B","sourcesContent":["import type { FileError, Result } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype BranchBounds,\n\ttype Entry,\n\ttype EntryQuery,\n\ttype ForkOptions,\n\ttype LaneRecord,\n\ttype LogItem,\n\ttype LogOptions,\n\ttype NewRecord,\n\ttype OperationStartedRecord,\n\ttype ProvisionedEntry,\n\ttype RecordQuery,\n\tSession,\n\tSessionError,\n\ttype SessionRepo as SessionRepository,\n\ttype SessionStats,\n\ttype SessionStorage,\n} from \"@earendil-works/pi-agent-core\";\nimport { uuidv7 } from \"@earendil-works/pi-ai\";\nimport { appendEntryToBranchCache, buildCachedBranch, deleteBranchCache, rebuildBranchCache } from \"./branch-cache.ts\";\nimport { applyMigrations } from \"./migrations.ts\";\nimport { sql } from \"./sql.ts\";\nimport { type CachedBranchEntryRow, queryCachedBranchRows, readCachedBranch } from \"./storage/branch-entries.ts\";\nimport { readBranchTipIds } from \"./storage/branch-tips.ts\";\nimport {\n\tdeleteEntryRows,\n\ttype EntryRow,\n\tentryPayload,\n\tidExistsInEntries,\n\tinsertEntryRow,\n\treadEntryRow,\n\treadEntryRows,\n} from \"./storage/entries.ts\";\nimport { appendFact, deleteFactRows, readFactRows, readLatestFact, readLatestLabelFacts } from \"./storage/facts.ts\";\nimport {\n\tcreateInitialLane,\n\tdeleteLaneRows,\n\tfinishLaneOperation,\n\tcreateLane as insertLane,\n\treadLane,\n\treadLaneHead,\n\treadLaneMoveRows,\n\treadLanes,\n\tsetLaneLeaf,\n\tstartLaneOperation,\n\tmoveLane as updateLane,\n} from \"./storage/lanes.ts\";\nimport {\n\tappendRecordRow,\n\tdeleteRecordRows,\n\tidExistsInRecords,\n\treadOpenOperationRows,\n\treadRecordRows,\n} from \"./storage/records.ts\";\nimport {\n\tadvanceSequence,\n\tcreateSequence,\n\tdeleteSequence,\n\tgetNextSequence,\n\tsetNextSequence,\n} from \"./storage/session-sequences.ts\";\nimport {\n\taddUsageToStats,\n\tcreateStats,\n\tdeleteStats,\n\tincrementMessageCount,\n\treadStats,\n} from \"./storage/session-stats.ts\";\nimport {\n\tdecodeSessionMetadata,\n\tdeleteSessionRow,\n\tinsertSessionRow,\n\treadSessionRow,\n\treadSessionRows,\n\ttype SessionRow,\n\tsessionExists,\n} from \"./storage/sessions.ts\";\nimport {\n\tacquireWriterLease,\n\tdeleteWriterLease,\n\treleaseWriterLease,\n\trenewWriterLease,\n\ttype WriterLease,\n} from \"./storage/writer-leases.ts\";\nimport type {\n\tSqliteDatabase,\n\tSqliteDatabaseFactory,\n\tSqliteSessionCreateOptions,\n\tSqliteSessionListOptions,\n\tSqliteSessionMetadata,\n\tSqliteSessionRepositoryEnv,\n} from \"./types.ts\";\n\nexport interface SqliteWriterLeaseOptions {\n\t/** Time without a successful heartbeat before another writer may take over. Default: 30 seconds. */\n\tttlMs?: number;\n\t/** Idle heartbeat cadence. Default: 10 seconds. Must be less than ttlMs. */\n\theartbeatIntervalMs?: number;\n}\n\nexport interface SqliteSessionRepositoryOptions {\n\tenv: SqliteSessionRepositoryEnv;\n\tsqlite: SqliteDatabaseFactory;\n\tdatabasePath: string;\n\twriterLease?: SqliteWriterLeaseOptions;\n}\n\ninterface ResolvedWriterLeaseOptions {\n\tttlMs: number;\n\theartbeatIntervalMs: number;\n}\n\nfunction resolveWriterLeaseOptions(options: SqliteWriterLeaseOptions | undefined): ResolvedWriterLeaseOptions {\n\tconst ttlMs = options?.ttlMs ?? 30_000;\n\tconst heartbeatIntervalMs = options?.heartbeatIntervalMs ?? 10_000;\n\tif (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) throw new RangeError(\"writerLease.ttlMs must be positive\");\n\tif (!Number.isSafeInteger(heartbeatIntervalMs) || heartbeatIntervalMs <= 0 || heartbeatIntervalMs >= ttlMs) {\n\t\tthrow new RangeError(\"writerLease.heartbeatIntervalMs must be positive and less than ttlMs\");\n\t}\n\treturn { ttlMs, heartbeatIntervalMs };\n}\n\nfunction activeWriterError(sessionId: string): SessionError {\n\treturn new SessionError(\"storage\", `SQLite session ${sessionId} already has an active writer`);\n}\n\nfunction lostWriterError(sessionId: string): SessionError {\n\treturn new SessionError(\"storage\", `SQLite session ${sessionId} writer lease was lost`);\n}\n\nfunction claimWriterLease(db: SqliteDatabase, sessionId: string, options: ResolvedWriterLeaseOptions): WriterLease {\n\tconst now = Date.now();\n\tconst lease = acquireWriterLease(db, sessionId, uuidv7(), now, now + options.ttlMs);\n\tif (!lease) throw activeWriterError(sessionId);\n\treturn lease;\n}\n\nclass SerialOperationQueue {\n\tprivate tail: Promise<void> = Promise.resolve();\n\n\tenqueue<T>(operation: () => Promise<T> | T): Promise<T> {\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync drain(): Promise<void> {\n\t\tawait this.tail;\n\t}\n}\n\nfunction resultOrThrow<T>(result: Result<T, FileError>, message: string): T {\n\tif (!result.ok) {\n\t\tconst code = result.error.code === \"not_found\" ? \"not_found\" : \"storage\";\n\t\tthrow new SessionError(code, `${message}: ${result.error.message}`, result.error);\n\t}\n\treturn result.value;\n}\n\nfunction getParentPath(path: string): string {\n\tconst normalized = path.replace(/[\\\\/]+$/, \"\");\n\tconst lastSlash = Math.max(normalized.lastIndexOf(\"/\"), normalized.lastIndexOf(\"\\\\\"));\n\tif (lastSlash < 0) return \".\";\n\tif (lastSlash === 0) return normalized.slice(0, 1);\n\treturn normalized.slice(0, lastSlash);\n}\n\nfunction configureSqliteDatabase(db: SqliteDatabase): void {\n\tsql`PRAGMA journal_mode=WAL`.exec(db);\n\tsql`PRAGMA synchronous=FULL`.exec(db);\n\tsql`PRAGMA busy_timeout=5000`.exec(db);\n}\n\nfunction entryRowFromCached(row: CachedBranchEntryRow): EntryRow {\n\treturn { ...row, seq: row.entry_seq, type: row.type as Entry[\"type\"] };\n}\n\nfunction readObjectPayload(row: EntryRow): Record<string, unknown> {\n\tconst payload = JSON.parse(row.payload) as unknown;\n\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n\t\tthrow new Error(\"Payload is not an object\");\n\t}\n\treturn payload as Record<string, unknown>;\n}\n\nfunction decodeEntry(row: EntryRow): Entry {\n\ttry {\n\t\tconst payload = readObjectPayload(row);\n\t\tconst base = { id: row.id, seq: row.seq, parentId: row.parent_id, timestamp: row.timestamp };\n\t\tswitch (row.type) {\n\t\t\tcase \"message\":\n\t\t\t\tif (typeof payload.message !== \"object\" || payload.message === null) throw new Error(\"Missing message\");\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\tmessage: payload.message as Extract<Entry, { type: \"message\" }>[\"message\"],\n\t\t\t\t\t...(payload.terminate === true ? { terminate: true as const } : {}),\n\t\t\t\t};\n\t\t\tcase \"model_change\":\n\t\t\t\tif (typeof payload.provider !== \"string\" || typeof payload.modelId !== \"string\") {\n\t\t\t\t\tthrow new Error(\"Invalid model_change payload\");\n\t\t\t\t}\n\t\t\t\treturn { ...base, type: \"model_change\", provider: payload.provider, modelId: payload.modelId };\n\t\t\tcase \"thinking_level_change\":\n\t\t\t\tif (typeof payload.thinkingLevel !== \"string\") throw new Error(\"Invalid thinking_level_change payload\");\n\t\t\t\treturn { ...base, type: \"thinking_level_change\", thinkingLevel: payload.thinkingLevel };\n\t\t\tcase \"active_tools_change\":\n\t\t\t\tif (!Array.isArray(payload.activeToolNames)) throw new Error(\"Invalid active_tools_change payload\");\n\t\t\t\tif (payload.activeToolNames.some((value) => typeof value !== \"string\")) {\n\t\t\t\t\tthrow new Error(\"Invalid active_tools_change payload\");\n\t\t\t\t}\n\t\t\t\treturn { ...base, type: \"active_tools_change\", activeToolNames: payload.activeToolNames };\n\t\t\tcase \"compaction\":\n\t\t\t\tif (\n\t\t\t\t\ttypeof payload.summary !== \"string\" ||\n\t\t\t\t\t!Array.isArray(payload.retainedTail) ||\n\t\t\t\t\ttypeof payload.tokensBefore !== \"number\"\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"Invalid compaction payload\");\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"compaction\",\n\t\t\t\t\tsummary: payload.summary,\n\t\t\t\t\tretainedTail: payload.retainedTail as Extract<Entry, { type: \"compaction\" }>[\"retainedTail\"],\n\t\t\t\t\ttokensBefore: payload.tokensBefore,\n\t\t\t\t\t...(Object.hasOwn(payload, \"details\") ? { details: payload.details } : {}),\n\t\t\t\t\t...(Object.hasOwn(payload, \"usage\")\n\t\t\t\t\t\t? { usage: payload.usage as Extract<Entry, { type: \"compaction\" }>[\"usage\"] }\n\t\t\t\t\t\t: {}),\n\t\t\t\t};\n\t\t\tcase \"branch_summary\":\n\t\t\t\tif (typeof payload.fromId !== \"string\" || typeof payload.summary !== \"string\") {\n\t\t\t\t\tthrow new Error(\"Invalid branch_summary payload\");\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"branch_summary\",\n\t\t\t\t\tfromId: payload.fromId,\n\t\t\t\t\tsummary: payload.summary,\n\t\t\t\t\t...(Object.hasOwn(payload, \"details\") ? { details: payload.details } : {}),\n\t\t\t\t\t...(Object.hasOwn(payload, \"usage\")\n\t\t\t\t\t\t? { usage: payload.usage as Extract<Entry, { type: \"branch_summary\" }>[\"usage\"] }\n\t\t\t\t\t\t: {}),\n\t\t\t\t};\n\t\t\tcase \"custom\":\n\t\t\t\tif (typeof payload.customType !== \"string\") throw new Error(\"Invalid custom payload\");\n\t\t\t\treturn {\n\t\t\t\t\t...base,\n\t\t\t\t\ttype: \"custom\",\n\t\t\t\t\tcustomType: payload.customType,\n\t\t\t\t\t...(Object.hasOwn(payload, \"data\") ? { data: payload.data } : {}),\n\t\t\t\t};\n\t\t}\n\t} catch (error) {\n\t\tthrow new SessionError(\n\t\t\t\"invalid_entry\",\n\t\t\t`Invalid SQLite session entry ${row.id}: failed to decode entry ${row.id}`,\n\t\t\terror instanceof Error ? error : undefined,\n\t\t);\n\t}\n}\n\nfunction recordRunId(record: NewRecord): string | undefined {\n\treturn record.type === \"operation_started\" ? record.id : \"runId\" in record ? record.runId : undefined;\n}\n\nfunction recordOpKind(record: NewRecord): string | undefined {\n\treturn record.type === \"operation_started\" ? record.intent.kind : undefined;\n}\n\nfunction decodeRecord(row: { seq: number; timestamp: number; payload: string }): LaneRecord {\n\ttry {\n\t\treturn {\n\t\t\t...(JSON.parse(row.payload) as object),\n\t\t\tseq: row.seq,\n\t\t\ttimestamp: row.timestamp,\n\t\t} as LaneRecord;\n\t} catch (error) {\n\t\tthrow new SessionError(\n\t\t\t\"storage\",\n\t\t\t`Invalid SQLite session record at sequence ${row.seq}: failed to decode payload`,\n\t\t\terror instanceof Error ? error : undefined,\n\t\t);\n\t}\n}\n\nfunction validateCachedBranchRows(rows: readonly CachedBranchEntryRow[], query: BranchBounds & EntryQuery): void {\n\tif (rows.length === 0 || query.type !== undefined || query.customType !== undefined) return;\n\tconst path = [...rows].sort((left, right) => left.entry_seq - right.entry_seq);\n\tconst shouldIncludeRoot =\n\t\tquery.stopAtId === undefined &&\n\t\tquery.stopAtType === undefined &&\n\t\tquery.cursor === undefined &&\n\t\t(query.order === \"oldestFirst\" || query.limit === undefined);\n\tif (shouldIncludeRoot && path[0]?.parent_id !== null) {\n\t\tthrow new SessionError(\"invalid_entry\", `Entry ${path[0]?.parent_id} not found`);\n\t}\n\tfor (let index = 1; index < path.length; index++) {\n\t\tconst previous = path[index - 1]!;\n\t\tconst current = path[index]!;\n\t\tif (current.parent_id !== previous.id) {\n\t\t\tthrow new SessionError(\"invalid_entry\", `Entry ${current.parent_id} not found`);\n\t\t}\n\t}\n}\n\nfunction matchesEntryQuery(entry: Entry, query: EntryQuery): boolean {\n\treturn (\n\t\t(query.type === undefined || entry.type === query.type) &&\n\t\t(query.customType === undefined || (entry.type === \"custom\" && entry.customType === query.customType)) &&\n\t\t(query.cursor === undefined ||\n\t\t\t(query.order === \"oldestFirst\" ? entry.seq > query.cursor.afterSeq : entry.seq < query.cursor.afterSeq))\n\t);\n}\n\nfunction assertUnusedId(db: SqliteDatabase, sessionId: string, id: string): void {\n\tif (idExistsInEntries(db, sessionId, id) || idExistsInRecords(db, sessionId, id)) {\n\t\tthrow new SessionError(\"already_exists\", `ID already exists: ${id}`);\n\t}\n}\n\nfunction requireSessionRow(db: SqliteDatabase, sessionId: string): SessionRow {\n\tconst row = readSessionRow(db, sessionId);\n\tif (!row) throw new SessionError(\"not_found\", `Session not found: ${sessionId}`);\n\treturn row;\n}\n\nclass SqliteSessionStorage implements SessionStorage<SqliteSessionMetadata> {\n\tprivate readonly db: SqliteDatabase;\n\tprivate readonly metadata: SqliteSessionMetadata;\n\tprivate readonly lease: WriterLease;\n\tprivate readonly leaseOptions: ResolvedWriterLeaseOptions;\n\tprivate readonly onRelease: () => void;\n\tprivate readonly operations = new SerialOperationQueue();\n\tprivate heartbeatTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate leaseError: SessionError | undefined;\n\tprivate closing = false;\n\tprivate releasePromise: Promise<void> | undefined;\n\n\tconstructor(\n\t\tdb: SqliteDatabase,\n\t\tmetadata: SqliteSessionMetadata,\n\t\tlease: WriterLease,\n\t\tleaseOptions: ResolvedWriterLeaseOptions,\n\t\tonRelease: () => void,\n\t) {\n\t\tthis.db = db;\n\t\tthis.metadata = metadata;\n\t\tthis.lease = lease;\n\t\tthis.leaseOptions = leaseOptions;\n\t\tthis.onRelease = onRelease;\n\t\tthis.scheduleHeartbeat();\n\t}\n\n\tasync release(): Promise<void> {\n\t\tthis.releasePromise ??= this.finishRelease();\n\t\tawait this.releasePromise;\n\t}\n\n\tprivate async finishRelease(): Promise<void> {\n\t\tthis.closing = true;\n\t\tif (this.heartbeatTimer !== undefined) clearTimeout(this.heartbeatTimer);\n\t\ttry {\n\t\t\tawait this.operations.enqueue(() =>\n\t\t\t\tthis.db.transaction(() => releaseWriterLease(this.db, this.metadata.id, this.lease)),\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.onRelease();\n\t\t}\n\t}\n\n\tprivate enqueueWrite<T>(operation: () => T): Promise<T> {\n\t\tif (this.closing)\n\t\t\treturn Promise.reject(new SessionError(\"storage\", `SQLite session ${this.metadata.id} is closed`));\n\t\treturn this.operations.enqueue(() => {\n\t\t\tif (this.leaseError) throw this.leaseError;\n\t\t\treturn this.db.transaction(() => {\n\t\t\t\tconst now = Date.now();\n\t\t\t\tif (!renewWriterLease(this.db, this.metadata.id, this.lease, now, now + this.leaseOptions.ttlMs)) {\n\t\t\t\t\tthis.leaseError = lostWriterError(this.metadata.id);\n\t\t\t\t\tif (this.heartbeatTimer !== undefined) clearTimeout(this.heartbeatTimer);\n\t\t\t\t\tthrow this.leaseError;\n\t\t\t\t}\n\t\t\t\treturn operation();\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate scheduleHeartbeat(): void {\n\t\tif (this.closing || this.leaseError) return;\n\t\tthis.heartbeatTimer = setTimeout(async () => {\n\t\t\tthis.heartbeatTimer = undefined;\n\t\t\ttry {\n\t\t\t\tawait this.operations.enqueue(() => {\n\t\t\t\t\tif (this.closing || this.leaseError) return;\n\t\t\t\t\tthis.db.transaction(() => {\n\t\t\t\t\t\tconst now = Date.now();\n\t\t\t\t\t\tif (!renewWriterLease(this.db, this.metadata.id, this.lease, now, now + this.leaseOptions.ttlMs)) {\n\t\t\t\t\t\t\tthis.leaseError = lostWriterError(this.metadata.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// A transient heartbeat failure is retried. Every write still verifies ownership transactionally.\n\t\t\t} finally {\n\t\t\t\tthis.scheduleHeartbeat();\n\t\t\t}\n\t\t}, this.leaseOptions.heartbeatIntervalMs);\n\t\tthis.heartbeatTimer.unref();\n\t}\n\n\tasync getMetadata(): Promise<SqliteSessionMetadata> {\n\t\treturn decodeSessionMetadata(requireSessionRow(this.db, this.metadata.id), this.metadata.path);\n\t}\n\n\tisForSession(sessionId: string): boolean {\n\t\treturn this.metadata.id === sessionId;\n\t}\n\n\tasync getLanes(): Promise<{ lane: string; leafId: string | null }[]> {\n\t\treturn readLanes(this.db, this.metadata.id).map((row) => ({ lane: row.lane, leafId: row.leaf_id }));\n\t}\n\n\tasync createLane(lane: string, at: string | null): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (readLane(this.db, this.metadata.id, lane)) {\n\t\t\t\tthrow new SessionError(\"already_exists\", `Lane already exists: ${lane}`);\n\t\t\t}\n\t\t\tif (at !== null && !readEntryRow(this.db, this.metadata.id, at)) {\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${at}`);\n\t\t\t}\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tinsertLane(this.db, this.metadata.id, seq, lane, at);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync moveLane(lane: string, to: string | null): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (!readLane(this.db, this.metadata.id, lane))\n\t\t\t\tthrow new SessionError(\"invalid_lane\", `Lane not found: ${lane}`);\n\t\t\tif (to !== null && !readEntryRow(this.db, this.metadata.id, to)) {\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${to}`);\n\t\t\t}\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tupdateLane(this.db, this.metadata.id, seq, lane, to);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync appendEntry<TEntry extends Entry>(entry: ProvisionedEntry<TEntry>, lane: string): Promise<TEntry> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tconst parentId = readLaneHead(this.db, this.metadata.id, lane).leafId;\n\t\t\tassertUnusedId(this.db, this.metadata.id, entry.id);\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tconst committed = { ...entry, parentId, seq, timestamp: Date.now() } as Entry;\n\t\t\tinsertEntryRow(this.db, this.metadata.id, {\n\t\t\t\tseq,\n\t\t\t\tid: committed.id,\n\t\t\t\tparentId: committed.parentId,\n\t\t\t\ttype: committed.type,\n\t\t\t\ttimestamp: committed.timestamp,\n\t\t\t\tpayload: JSON.stringify(entryPayload(committed)),\n\t\t\t});\n\t\t\tsetLaneLeaf(this.db, this.metadata.id, lane, committed.id);\n\t\t\tappendEntryToBranchCache(\n\t\t\t\tthis.db,\n\t\t\t\tthis.metadata.id,\n\t\t\t\tcommitted.id,\n\t\t\t\tseq,\n\t\t\t\tcommitted.type,\n\t\t\t\tcommitted.type === \"custom\" ? committed.customType : null,\n\t\t\t\tcommitted.parentId,\n\t\t\t);\n\t\t\tif (committed.type === \"message\") incrementMessageCount(this.db, this.metadata.id);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t\treturn structuredClone(committed as TEntry);\n\t\t});\n\t}\n\n\tasync appendRecord<TRecord extends LaneRecord>(record: NewRecord<TRecord>): Promise<TRecord>;\n\tasync appendRecord(record: NewRecord): Promise<LaneRecord> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (!readLane(this.db, this.metadata.id, record.lane)) {\n\t\t\t\tthrow new SessionError(\"invalid_lane\", `Lane not found: ${record.lane}`);\n\t\t\t}\n\t\t\tassertUnusedId(this.db, this.metadata.id, record.id);\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tconst committed: LaneRecord = { ...record, seq, timestamp: Date.now() };\n\t\t\tif (record.type === \"operation_started\") {\n\t\t\t\tstartLaneOperation(this.db, this.metadata.id, record.lane, record.id);\n\t\t\t}\n\t\t\tappendRecordRow(this.db, this.metadata.id, {\n\t\t\t\tseq,\n\t\t\t\tid: record.id,\n\t\t\t\tlane: record.lane,\n\t\t\t\trunId: recordRunId(record),\n\t\t\t\ttype: record.type,\n\t\t\t\topKind: recordOpKind(record),\n\t\t\t\ttimestamp: committed.timestamp,\n\t\t\t\tpayload: JSON.stringify(record),\n\t\t\t});\n\t\t\tif (record.type === \"operation_finished\") {\n\t\t\t\tfinishLaneOperation(this.db, this.metadata.id, record.lane, record.runId);\n\t\t\t}\n\t\t\tif (record.type === \"usage\") addUsageToStats(this.db, this.metadata.id, record.usage);\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t\treturn structuredClone(committed);\n\t\t});\n\t}\n\n\tasync getEntry(id: string): Promise<Entry | undefined> {\n\t\tconst row = readEntryRow(this.db, this.metadata.id, id);\n\t\treturn row ? decodeEntry(row) : undefined;\n\t}\n\n\tasync findEntries(query: EntryQuery = {}): Promise<Entry[]> {\n\t\tconst sqlType = query.type ?? (query.customType === undefined ? undefined : \"custom\");\n\t\tconst sqlLimit = query.customType === undefined ? query.limit : undefined;\n\t\tconst rows = readEntryRows(this.db, this.metadata.id, {\n\t\t\tcursor: query.cursor,\n\t\t\tlimit: sqlLimit,\n\t\t\torder: query.order,\n\t\t\ttype: sqlType,\n\t\t});\n\t\tconst entries = rows.map(decodeEntry).filter((entry) => matchesEntryQuery(entry, query));\n\t\treturn query.limit === undefined ? entries : entries.slice(0, query.limit);\n\t}\n\n\tasync findEntriesOnBranch(query: EntryQuery & BranchBounds & { start: string }): Promise<Entry[]> {\n\t\tconst cached = readCachedBranch(this.db, this.metadata.id, query.start);\n\t\tif (!cached) {\n\t\t\tif (!readEntryRow(this.db, this.metadata.id, query.start))\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${query.start}`);\n\t\t\tthrow new SessionError(\"invalid_entry\", `Branch cache missing entry ${query.start}`);\n\t\t}\n\t\tconst rows = queryCachedBranchRows(this.db, this.metadata.id, cached, query);\n\t\tvalidateCachedBranchRows(rows, query);\n\t\tconst entries = rows\n\t\t\t.map(entryRowFromCached)\n\t\t\t.map(decodeEntry)\n\t\t\t.filter((entry) => matchesEntryQuery(entry, query));\n\t\treturn query.limit === undefined ? entries : entries.slice(0, query.limit);\n\t}\n\n\tasync findRecords(query: RecordQuery = {}): Promise<LaneRecord[]> {\n\t\tconst rows = readRecordRows(this.db, this.metadata.id, query);\n\t\treturn rows.map(decodeRecord);\n\t}\n\n\tasync findOpenOperations(lane: string, options?: { limit?: number }): Promise<OperationStartedRecord[]> {\n\t\tconst rows = readOpenOperationRows(this.db, this.metadata.id, lane, options);\n\n\t\treturn rows.map((row) => {\n\t\t\tconst record = decodeRecord(row);\n\t\t\tif (record.type !== \"operation_started\") {\n\t\t\t\tthrow new SessionError(\"storage\", \"Expected operation_started record\");\n\t\t\t}\n\t\t\treturn record;\n\t\t});\n\t}\n\n\tasync getLog(options: LogOptions = {}): Promise<LogItem[]> {\n\t\tconst afterSeq = options.afterSeq ?? 0;\n\t\tconst limit = options.limit;\n\t\tconst entryRows = readEntryRows(this.db, this.metadata.id, { afterSeq, order: \"oldestFirst\", limit });\n\t\tconst recordRows = readRecordRows(this.db, this.metadata.id, { afterSeq, order: \"oldestFirst\", limit });\n\t\tconst laneRows = readLaneMoveRows(this.db, this.metadata.id, { afterSeq, limit });\n\t\tconst factRows = readFactRows(this.db, this.metadata.id, { afterSeq, limit });\n\n\t\tconst logRows: { seq: number; decode: () => LogItem }[] = [\n\t\t\t...entryRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => ({ kind: \"entry\" as const, seq: row.seq, entry: decodeEntry(row) }),\n\t\t\t})),\n\t\t\t...recordRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => ({ kind: \"record\" as const, seq: row.seq, record: decodeRecord(row) }),\n\t\t\t})),\n\t\t\t...laneRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => ({ kind: \"lane\" as const, seq: row.seq, lane: row.lane, leafId: row.leaf_id }),\n\t\t\t})),\n\t\t\t...factRows.map((row) => ({\n\t\t\t\tseq: row.seq,\n\t\t\t\tdecode: () => {\n\t\t\t\t\tif (row.kind === \"name\")\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: \"fact\" as const,\n\t\t\t\t\t\t\tseq: row.seq,\n\t\t\t\t\t\t\tfact: \"name\" as const,\n\t\t\t\t\t\t\tname: row.value === null ? undefined : (JSON.parse(row.value) as string),\n\t\t\t\t\t\t};\n\t\t\t\t\treturn {\n\t\t\t\t\t\tkind: \"fact\" as const,\n\t\t\t\t\t\tseq: row.seq,\n\t\t\t\t\t\tfact: \"label\" as const,\n\t\t\t\t\t\ttargetId: row.key ?? \"\",\n\t\t\t\t\t\tlabel: row.value === null ? undefined : (JSON.parse(row.value) as string),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t})),\n\t\t].sort((left, right) => left.seq - right.seq);\n\t\tconst selectedRows = options.limit === undefined ? logRows : logRows.slice(0, options.limit);\n\t\treturn selectedRows.map((row) => row.decode());\n\t}\n\n\tasync getName(): Promise<string | undefined> {\n\t\tconst row = readLatestFact(this.db, this.metadata.id, \"name\", null);\n\t\treturn row?.value === undefined || row.value === null ? undefined : (JSON.parse(row.value) as string);\n\t}\n\n\tasync setName(name: string | undefined): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tappendFact(this.db, this.metadata.id, seq, \"name\", null, name === undefined ? null : JSON.stringify(name));\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync getLabel(id: string): Promise<string | undefined> {\n\t\tconst row = readLatestFact(this.db, this.metadata.id, \"label\", id);\n\t\treturn row?.value === undefined || row.value === null ? undefined : (JSON.parse(row.value) as string);\n\t}\n\n\tasync setLabel(id: string, label: string | undefined): Promise<void> {\n\t\treturn this.enqueueWrite(() => {\n\t\t\tif (!readEntryRow(this.db, this.metadata.id, id)) {\n\t\t\t\tthrow new SessionError(\"not_found\", `Entry not found: ${id}`);\n\t\t\t}\n\t\t\tconst seq = getNextSequence(this.db, this.metadata.id);\n\t\t\tappendFact(this.db, this.metadata.id, seq, \"label\", id, label === undefined ? null : JSON.stringify(label));\n\t\t\tadvanceSequence(this.db, this.metadata.id, seq);\n\t\t});\n\t}\n\n\tasync getStats(): Promise<SessionStats> {\n\t\treturn readStats(this.db, this.metadata.id);\n\t}\n}\n\nfunction claimStorage(\n\tdb: SqliteDatabase,\n\tmetadata: SqliteSessionMetadata,\n\tleaseOptions: ResolvedWriterLeaseOptions,\n\tonRelease: () => void,\n): SqliteSessionStorage {\n\trequireSessionRow(db, metadata.id);\n\tconst claimed = db.transaction(() => {\n\t\tconst lease = claimWriterLease(db, metadata.id, leaseOptions);\n\t\tconst row = requireSessionRow(db, metadata.id);\n\t\treadLanes(db, metadata.id);\n\t\treturn { lease, row };\n\t});\n\treturn new SqliteSessionStorage(\n\t\tdb,\n\t\tdecodeSessionMetadata(claimed.row, metadata.path),\n\t\tclaimed.lease,\n\t\tleaseOptions,\n\t\tonRelease,\n\t);\n}\n\nexport class SqliteSessionRepository\n\timplements\n\t\tSessionRepository<SqliteSessionMetadata, SqliteSessionCreateOptions, SqliteSessionListOptions>,\n\t\tAsyncDisposable\n{\n\tprivate databasePath: string | undefined;\n\tprivate database: SqliteDatabase | undefined;\n\tprivate databasePromise: Promise<SqliteDatabase> | undefined;\n\tprivate readonly operations = new SerialOperationQueue();\n\tprivate readonly activeStorages = new Set<SqliteSessionStorage>();\n\tprivate readonly options: SqliteSessionRepositoryOptions;\n\tprivate readonly leaseOptions: ResolvedWriterLeaseOptions;\n\n\tconstructor(options: SqliteSessionRepositoryOptions) {\n\t\tthis.options = options;\n\t\tthis.leaseOptions = resolveWriterLeaseOptions(options.writerLease);\n\t}\n\n\tprivate async releaseStoragesForSession(sessionId: string): Promise<void> {\n\t\tfor (const storage of [...this.activeStorages]) {\n\t\t\tif (storage.isForSession(sessionId)) await storage.release();\n\t\t}\n\t}\n\n\tprivate sessionFromLease(\n\t\tdb: SqliteDatabase,\n\t\tmetadata: SqliteSessionMetadata,\n\t\tlease: WriterLease,\n\t): Session<SqliteSessionMetadata> {\n\t\tlet storage: SqliteSessionStorage;\n\t\tstorage = new SqliteSessionStorage(db, metadata, lease, this.leaseOptions, () => {\n\t\t\tthis.activeStorages.delete(storage);\n\t\t});\n\t\tthis.activeStorages.add(storage);\n\t\treturn new Session(storage);\n\t}\n\n\tprivate claimSession(db: SqliteDatabase, metadata: SqliteSessionMetadata): Session<SqliteSessionMetadata> {\n\t\tconst active = [...this.activeStorages].find((storage) => storage.isForSession(metadata.id));\n\t\tif (active) {\n\t\t\treadLanes(db, metadata.id);\n\t\t\treturn new Session(active);\n\t\t}\n\t\tlet storage: SqliteSessionStorage;\n\t\tstorage = claimStorage(db, metadata, this.leaseOptions, () => {\n\t\t\tthis.activeStorages.delete(storage);\n\t\t});\n\t\tthis.activeStorages.add(storage);\n\t\treturn new Session(storage);\n\t}\n\n\tasync create(options: SqliteSessionCreateOptions): Promise<Session<SqliteSessionMetadata>> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tconst db = await this.getDatabase();\n\t\t\tconst path = await this.getDatabasePath();\n\t\t\tconst id = options.id ?? uuidv7();\n\t\t\tif (sessionExists(db, id)) throw new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\t\t\tconst createdAt = Date.now();\n\t\t\tconst lease = db.transaction(() => {\n\t\t\t\tinsertSessionRow(db, {\n\t\t\t\t\tid,\n\t\t\t\t\tcreatedAt,\n\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\tparentSessionId: options.parentSessionId,\n\t\t\t\t\tmetadata: options.metadata,\n\t\t\t\t});\n\t\t\t\tcreateSequence(db, id);\n\t\t\t\tcreateStats(db, id);\n\t\t\t\tcreateInitialLane(db, id);\n\t\t\t\treturn claimWriterLease(db, id, this.leaseOptions);\n\t\t\t});\n\t\t\tconst row = requireSessionRow(db, id);\n\t\t\treturn this.sessionFromLease(db, decodeSessionMetadata(row, path), lease);\n\t\t});\n\t}\n\n\tasync open(metadata: SqliteSessionMetadata): Promise<Session<SqliteSessionMetadata>> {\n\t\treturn this.operations.enqueue(async () => this.claimSession(await this.getDatabase(), metadata));\n\t}\n\n\t/** Rebuilds this session's private branch-read cache from canonical entry parent links. */\n\tasync repairBranchCache(metadata: SqliteSessionMetadata): Promise<void> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tawait this.releaseStoragesForSession(metadata.id);\n\t\t\tconst db = await this.getDatabase();\n\t\t\tdb.transaction(() => {\n\t\t\t\tconst lease = claimWriterLease(db, metadata.id, this.leaseOptions);\n\t\t\t\trequireSessionRow(db, metadata.id);\n\t\t\t\trebuildBranchCache(db, metadata.id);\n\t\t\t\treleaseWriterLease(db, metadata.id, lease);\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Reads the session catalog without acquiring or renewing per-session writer leases. */\n\tasync list(options: SqliteSessionListOptions = {}): Promise<SqliteSessionMetadata[]> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tconst path = await this.getDatabasePath();\n\t\t\tif (!resultOrThrow(await this.options.env.exists(path), `Failed to check database ${path}`)) return [];\n\t\t\tconst db = await this.getDatabase();\n\t\t\tconst rows = readSessionRows(db, options);\n\t\t\treturn rows.map((row) => decodeSessionMetadata(row, path));\n\t\t});\n\t}\n\n\tasync delete(metadata: SqliteSessionMetadata): Promise<void> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tawait this.releaseStoragesForSession(metadata.id);\n\t\t\tconst db = await this.getDatabase();\n\t\t\tdb.transaction(() => {\n\t\t\t\tif (!sessionExists(db, metadata.id)) {\n\t\t\t\t\tdeleteWriterLease(db, metadata.id);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclaimWriterLease(db, metadata.id, this.leaseOptions);\n\t\t\t\tdeleteBranchCache(db, metadata.id);\n\t\t\t\tdeleteFactRows(db, metadata.id);\n\t\t\t\tdeleteLaneRows(db, metadata.id);\n\t\t\t\tdeleteRecordRows(db, metadata.id);\n\t\t\t\tdeleteEntryRows(db, metadata.id);\n\t\t\t\tdeleteWriterLease(db, metadata.id);\n\t\t\t\tdeleteStats(db, metadata.id);\n\t\t\t\tdeleteSequence(db, metadata.id);\n\t\t\t\tdeleteSessionRow(db, metadata.id);\n\t\t\t});\n\t\t});\n\t}\n\n\tasync fork(\n\t\tsource: SqliteSessionMetadata,\n\t\toptions: ForkOptions & SqliteSessionCreateOptions,\n\t): Promise<Session<SqliteSessionMetadata>> {\n\t\treturn this.operations.enqueue(async () => {\n\t\t\tconst db = await this.getDatabase();\n\t\t\tconst path = await this.getDatabasePath();\n\t\t\tconst sourceMetadata = decodeSessionMetadata(requireSessionRow(db, source.id), path);\n\t\t\tconst id = options.id ?? uuidv7();\n\t\t\tif (sessionExists(db, id)) throw new SessionError(\"already_exists\", `Session already exists: ${id}`);\n\n\t\t\tconst entries: EntryRow[] = [];\n\t\t\tconst lanes: { lane: string; leafId: string | null }[] = [];\n\t\t\tconst branchTips: string[] = [];\n\t\t\tlet branchForkTargetId: string | null = null;\n\n\t\t\tif (options.scope === \"tree\") {\n\t\t\t\tentries.push(...readEntryRows(db, source.id, { order: \"oldestFirst\" }));\n\t\t\t\tlanes.push(...readLanes(db, source.id).map((row) => ({ lane: row.lane, leafId: row.leaf_id })));\n\t\t\t\tbranchTips.push(...readBranchTipIds(db, source.id));\n\t\t\t} else {\n\t\t\t\tconst main = readLane(db, source.id, \"main\");\n\t\t\t\tif (!main) throw new SessionError(\"invalid_lane\", \"Lane not found: main\");\n\t\t\t\tconst selectedEntryId = options.entryId ?? main.leaf_id;\n\t\t\t\tif (selectedEntryId !== null) {\n\t\t\t\t\tconst target = readEntryRow(db, source.id, selectedEntryId);\n\t\t\t\t\tif (!target || target.type !== \"message\") {\n\t\t\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\t\t\"invalid_fork_target\",\n\t\t\t\t\t\t\t`Fork target is not a message entry: ${selectedEntryId}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst position = options.position ?? (options.entryId === undefined ? \"at\" : \"before\");\n\t\t\t\t\tbranchForkTargetId = position === \"at\" ? target.id : target.parent_id;\n\t\t\t\t}\n\t\t\t\tlanes.push({ lane: \"main\", leafId: branchForkTargetId });\n\t\t\t\tif (branchForkTargetId !== null) {\n\t\t\t\t\tconst cached = readCachedBranch(db, source.id, branchForkTargetId);\n\t\t\t\t\tif (!cached) {\n\t\t\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\t\t\"invalid_fork_target\",\n\t\t\t\t\t\t\t`Fork target is not on a cached branch: ${branchForkTargetId}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst rows = queryCachedBranchRows(db, source.id, cached, { order: \"oldestFirst\" });\n\t\t\t\t\tentries.push(...rows.map(entryRowFromCached));\n\t\t\t\t\tbranchTips.push(branchForkTargetId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst copiedIds = new Set(entries.map((entry) => entry.id));\n\t\t\tconst latestName = readLatestFact(db, source.id, \"name\", null);\n\t\t\tconst latestLabels = readLatestLabelFacts(db, source.id);\n\t\t\tconst labelsToCopy = latestLabels.filter(\n\t\t\t\t(row) => options.scope === \"tree\" || (row.key !== null && copiedIds.has(row.key)),\n\t\t\t);\n\t\t\tconst createdAt = Date.now();\n\t\t\tconst metadata = options.metadata ?? sourceMetadata.metadata;\n\t\t\tlet lease: WriterLease;\n\n\t\t\ttry {\n\t\t\t\tlease = db.transaction(() => {\n\t\t\t\t\tinsertSessionRow(db, {\n\t\t\t\t\t\tid,\n\t\t\t\t\t\tcreatedAt,\n\t\t\t\t\t\tcwd: options.cwd,\n\t\t\t\t\t\tparentSessionId: options.parentSessionId ?? source.id,\n\t\t\t\t\t\tmetadata,\n\t\t\t\t\t});\n\t\t\t\t\tcreateSequence(db, id);\n\t\t\t\t\tcreateStats(db, id, entries.filter((entry) => entry.type === \"message\").length);\n\n\t\t\t\t\tlet nextSeq = 1;\n\t\t\t\t\tconst allocateSeq = () => nextSeq++;\n\t\t\t\t\tfor (const entry of entries) {\n\t\t\t\t\t\tinsertEntryRow(db, id, {\n\t\t\t\t\t\t\tseq: allocateSeq(),\n\t\t\t\t\t\t\tid: entry.id,\n\t\t\t\t\t\t\tparentId: entry.parent_id,\n\t\t\t\t\t\t\ttype: entry.type,\n\t\t\t\t\t\t\ttimestamp: entry.timestamp,\n\t\t\t\t\t\t\tpayload: entry.payload,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tif (options.scope === \"tree\") {\n\t\t\t\t\t\tfor (const lane of lanes) insertLane(db, id, allocateSeq(), lane.lane, lane.leafId);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcreateInitialLane(db, id, \"main\", branchForkTargetId);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (latestName?.value !== undefined && latestName.value !== null) {\n\t\t\t\t\t\tappendFact(db, id, allocateSeq(), \"name\", null, latestName.value);\n\t\t\t\t\t}\n\t\t\t\t\tfor (const label of labelsToCopy) appendFact(db, id, allocateSeq(), \"label\", label.key, label.value);\n\n\t\t\t\t\tsetNextSequence(db, id, nextSeq);\n\t\t\t\t\tfor (const tip of branchTips) buildCachedBranch(db, id, tip);\n\t\t\t\t\treturn claimWriterLease(db, id, this.leaseOptions);\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof SessionError) throw error;\n\t\t\t\tthrow new SessionError(\n\t\t\t\t\t\"storage\",\n\t\t\t\t\t`Failed to fork SQLite session ${id}`,\n\t\t\t\t\terror instanceof Error ? error : undefined,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst row = requireSessionRow(db, id);\n\t\t\treturn this.sessionFromLease(db, decodeSessionMetadata(row, path), lease);\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tawait this.operations.drain();\n\t\tfor (const storage of [...this.activeStorages]) await storage.release();\n\t\tif (this.database) this.database.close();\n\t\tthis.database = undefined;\n\t\tthis.databasePromise = undefined;\n\t}\n\n\tasync [Symbol.asyncDispose](): Promise<void> {\n\t\tawait this.close();\n\t}\n\n\tprivate async getDatabasePath(): Promise<string> {\n\t\tthis.databasePath ??= resultOrThrow(\n\t\t\tawait this.options.env.absolutePath(this.options.databasePath),\n\t\t\t`Failed to resolve SQLite sessions database ${this.options.databasePath}`,\n\t\t);\n\t\treturn this.databasePath;\n\t}\n\n\tprivate async getDatabase(): Promise<SqliteDatabase> {\n\t\tif (!this.databasePromise) this.databasePromise = this.openDatabase();\n\t\tthis.database = await this.databasePromise;\n\t\treturn this.database;\n\t}\n\n\tprivate async openDatabase(): Promise<SqliteDatabase> {\n\t\tconst path = await this.getDatabasePath();\n\t\tresultOrThrow(\n\t\t\tawait this.options.env.createDir(getParentPath(path), { recursive: true }),\n\t\t\t`Failed to create SQLite sessions directory ${path}`,\n\t\t);\n\t\tconst db = await this.options.sqlite.open(path);\n\t\ttry {\n\t\t\tconfigureSqliteDatabase(db);\n\t\t\tawait applyMigrations(db);\n\t\t\treturn db;\n\t\t} catch (error) {\n\t\t\tdb.close();\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n"]}
@@ -68,12 +68,6 @@ function configureSqliteDatabase(db) {
68
68
  sql `PRAGMA synchronous=FULL`.exec(db);
69
69
  sql `PRAGMA busy_timeout=5000`.exec(db);
70
70
  }
71
- function timestampToText(timestamp) {
72
- return new Date(timestamp).toISOString();
73
- }
74
- function timestampFromText(timestamp) {
75
- return Date.parse(timestamp);
76
- }
77
71
  function entryRowFromCached(row) {
78
72
  return { ...row, seq: row.entry_seq, type: row.type };
79
73
  }
@@ -87,10 +81,7 @@ function readObjectPayload(row) {
87
81
  function decodeEntry(row) {
88
82
  try {
89
83
  const payload = readObjectPayload(row);
90
- const timestamp = timestampFromText(row.timestamp);
91
- if (!Number.isFinite(timestamp))
92
- throw new Error(`Invalid timestamp ${row.timestamp}`);
93
- const base = { id: row.id, seq: row.seq, parentId: row.parent_id, timestamp };
84
+ const base = { id: row.id, seq: row.seq, parentId: row.parent_id, timestamp: row.timestamp };
94
85
  switch (row.type) {
95
86
  case "message":
96
87
  if (typeof payload.message !== "object" || payload.message === null)
@@ -171,13 +162,10 @@ function recordOpKind(record) {
171
162
  }
172
163
  function decodeRecord(row) {
173
164
  try {
174
- const timestamp = timestampFromText(row.timestamp);
175
- if (!Number.isFinite(timestamp))
176
- throw new Error(`Invalid timestamp ${row.timestamp}`);
177
165
  return {
178
166
  ...JSON.parse(row.payload),
179
167
  seq: row.seq,
180
- timestamp,
168
+ timestamp: row.timestamp,
181
169
  };
182
170
  }
183
171
  catch (error) {
@@ -343,7 +331,7 @@ class SqliteSessionStorage {
343
331
  id: committed.id,
344
332
  parentId: committed.parentId,
345
333
  type: committed.type,
346
- timestamp: timestampToText(committed.timestamp),
334
+ timestamp: committed.timestamp,
347
335
  payload: JSON.stringify(entryPayload(committed)),
348
336
  });
349
337
  setLaneLeaf(this.db, this.metadata.id, lane, committed.id);
@@ -372,7 +360,7 @@ class SqliteSessionStorage {
372
360
  runId: recordRunId(record),
373
361
  type: record.type,
374
362
  opKind: recordOpKind(record),
375
- timestamp: timestampToText(committed.timestamp),
363
+ timestamp: committed.timestamp,
376
364
  payload: JSON.stringify(record),
377
365
  });
378
366
  if (record.type === "operation_finished") {
@@ -389,7 +377,14 @@ class SqliteSessionStorage {
389
377
  return row ? decodeEntry(row) : undefined;
390
378
  }
391
379
  async findEntries(query = {}) {
392
- const rows = readEntryRows(this.db, this.metadata.id, { order: query.order });
380
+ const sqlType = query.type ?? (query.customType === undefined ? undefined : "custom");
381
+ const sqlLimit = query.customType === undefined ? query.limit : undefined;
382
+ const rows = readEntryRows(this.db, this.metadata.id, {
383
+ cursor: query.cursor,
384
+ limit: sqlLimit,
385
+ order: query.order,
386
+ type: sqlType,
387
+ });
393
388
  const entries = rows.map(decodeEntry).filter((entry) => matchesEntryQuery(entry, query));
394
389
  return query.limit === undefined ? entries : entries.slice(0, query.limit);
395
390
  }
@@ -450,7 +445,7 @@ class SqliteSessionStorage {
450
445
  kind: "fact",
451
446
  seq: row.seq,
452
447
  fact: "name",
453
- name: JSON.parse(row.value ?? "null"),
448
+ name: row.value === null ? undefined : JSON.parse(row.value),
454
449
  };
455
450
  return {
456
451
  kind: "fact",
@@ -472,7 +467,7 @@ class SqliteSessionStorage {
472
467
  async setName(name) {
473
468
  return this.enqueueWrite(() => {
474
469
  const seq = getNextSequence(this.db, this.metadata.id);
475
- appendFact(this.db, this.metadata.id, seq, "name", null, JSON.stringify(name));
470
+ appendFact(this.db, this.metadata.id, seq, "name", null, name === undefined ? null : JSON.stringify(name));
476
471
  advanceSequence(this.db, this.metadata.id, seq);
477
472
  });
478
473
  }
@@ -554,7 +549,7 @@ export class SqliteSessionRepository {
554
549
  const lease = db.transaction(() => {
555
550
  insertSessionRow(db, {
556
551
  id,
557
- createdAt: timestampToText(createdAt),
552
+ createdAt,
558
553
  cwd: options.cwd,
559
554
  parentSessionId: options.parentSessionId,
560
555
  metadata: options.metadata,
@@ -669,7 +664,7 @@ export class SqliteSessionRepository {
669
664
  lease = db.transaction(() => {
670
665
  insertSessionRow(db, {
671
666
  id,
672
- createdAt: timestampToText(createdAt),
667
+ createdAt,
673
668
  cwd: options.cwd,
674
669
  parentSessionId: options.parentSessionId ?? source.id,
675
670
  metadata,