From ba0a08f03be19fe3f95e292b89f85b09545f141c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 20 Feb 2026 10:21:59 +0000 Subject: [PATCH] Remove legacy SQL fallback paths from persistence service Co-authored-by: Julius Marminge --- apps/server/src/persistence/documentsRepo.ts | 259 --------------- apps/server/src/persistence/metadataRepo.ts | 39 --- .../src/persistence/providerEventsRepo.ts | 124 -------- .../src/persistence/repos/documentsRepo.ts | 260 ++++++++++++++- .../src/persistence/repos/metadataRepo.ts | 40 ++- .../persistence/repos/providerEventsRepo.ts | 125 +++++++- .../persistence/repos/stateEventsRepo.test.ts | 10 +- .../src/persistence/repos/stateEventsRepo.ts | 91 +++++- apps/server/src/persistence/runtime.ts | 4 +- apps/server/src/persistence/schema.ts | 28 ++ .../server/src/persistence/stateEventsRepo.ts | 90 ------ apps/server/src/persistenceService.ts | 298 ++---------------- 12 files changed, 563 insertions(+), 805 deletions(-) delete mode 100644 apps/server/src/persistence/documentsRepo.ts delete mode 100644 apps/server/src/persistence/metadataRepo.ts delete mode 100644 apps/server/src/persistence/providerEventsRepo.ts create mode 100644 apps/server/src/persistence/schema.ts delete mode 100644 apps/server/src/persistence/stateEventsRepo.ts diff --git a/apps/server/src/persistence/documentsRepo.ts b/apps/server/src/persistence/documentsRepo.ts deleted file mode 100644 index 8121e77d4d..0000000000 --- a/apps/server/src/persistence/documentsRepo.ts +++ /dev/null @@ -1,259 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -export interface DocumentRow { - id: string; - kind: string; - project_id: string | null; - thread_id: string | null; - sort_key: number | null; - created_at: string; - updated_at: string; - data_json: string; -} - -interface DataJsonRow { - data_json: string; -} - -export interface PaginatedMessagePayloadsRow { - data_json: string; -} - -export interface TotalCountRow { - total?: number | bigint; -} - -function toSafeInteger(value: unknown, fallback = 0): number { - if (typeof value === "number" && Number.isFinite(value)) { - return Math.trunc(value); - } - if (typeof value === "bigint") { - return Number(value); - } - return fallback; -} - -export const getDocumentRowById = ( - id: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe( - "SELECT id, kind, project_id, thread_id, sort_key, created_at, updated_at, data_json FROM documents WHERE id = ? LIMIT 1;", - [id], - ) - .unprepared) as DocumentRow[]; - return rows[0] ?? null; - }); - -export const upsertDocument = (input: { - id: string; - kind: "project" | "thread" | "message" | "turn_summary"; - projectId: string | null; - threadId: string | null; - sortKey: number | null; - createdAt: string; - updatedAt: string; - dataJson: string; -}): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - yield* sql - .unsafe( - `INSERT INTO documents ( - id, - kind, - project_id, - thread_id, - sort_key, - schema_version, - created_at, - updated_at, - data_json - ) VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?) - ON CONFLICT(id) DO UPDATE SET - kind = excluded.kind, - project_id = excluded.project_id, - thread_id = excluded.thread_id, - sort_key = excluded.sort_key, - schema_version = excluded.schema_version, - updated_at = excluded.updated_at, - data_json = excluded.data_json;`, - [ - input.id, - input.kind, - input.projectId, - input.threadId, - input.sortKey, - input.createdAt, - input.updatedAt, - input.dataJson, - ], - ) - .raw; - }).pipe(Effect.asVoid); - -export const readNextSortKey = ( - kind: "message" | "turn_summary", - threadId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe<{ next_sort_key?: number }>( - "SELECT COALESCE(MAX(sort_key), 0) + 1 AS next_sort_key FROM documents WHERE kind = ? AND thread_id = ?;", - [kind, threadId], - ) - .unprepared) as Array<{ next_sort_key?: number }>; - return rows[0]?.next_sort_key ?? 1; - }); - -export const listProjectPayloads = (): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe( - "SELECT data_json FROM documents WHERE kind = 'project' ORDER BY updated_at DESC, created_at DESC;", - ) - .unprepared) as DataJsonRow[]; - return rows.map((row) => row.data_json); - }); - -export const listThreadPayloads = (): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe( - "SELECT data_json FROM documents WHERE kind = 'thread' ORDER BY updated_at DESC, created_at DESC;", - ) - .unprepared) as DataJsonRow[]; - return rows.map((row) => row.data_json); - }); - -export const listThreadPayloadsByProject = ( - projectId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe("SELECT data_json FROM documents WHERE kind = 'thread' AND project_id = ?;", [ - projectId, - ]) - .unprepared) as DataJsonRow[]; - return rows.map((row) => row.data_json); - }); - -export const findThreadPayloadByRuntimeThreadId = ( - runtimeThreadId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe( - "SELECT data_json FROM documents WHERE kind = 'thread' AND json_extract(data_json, '$.codexThreadId') = ? LIMIT 1;", - [runtimeThreadId], - ) - .unprepared) as DataJsonRow[]; - return rows[0]?.data_json ?? null; - }); - -export const deleteDocumentsByProjectId = ( - projectId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - yield* sql.unsafe("DELETE FROM documents WHERE project_id = ?;", [projectId]).raw; - }).pipe(Effect.asVoid); - -export const deleteDocumentsByThreadId = ( - threadId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - yield* sql.unsafe("DELETE FROM documents WHERE thread_id = ?;", [threadId]).raw; - }).pipe(Effect.asVoid); - -export const deleteDocumentByIdAndKind = ( - id: string, - kind: "thread" | "message" | "turn_summary", -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - yield* sql.unsafe("DELETE FROM documents WHERE id = ? AND kind = ?;", [id, kind]).raw; - }).pipe(Effect.asVoid); - -export const listMessagePayloadsForThread = ( - threadId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe<{ data_json: string }>( - "SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC;", - [threadId], - ) - .unprepared) as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }); - -export const listPaginatedMessagePayloadsForThread = (input: { - threadId: string; - limit: number; - offset: number; -}): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe( - "SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC LIMIT ? OFFSET ?;", - [input.threadId, input.limit, input.offset], - ) - .unprepared) as PaginatedMessagePayloadsRow[]; - return rows.map((row) => row.data_json); - }); - -export const countMessagesForThread = ( - threadId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe("SELECT COUNT(1) AS total FROM documents WHERE kind = 'message' AND thread_id = ?;", [ - threadId, - ]) - .unprepared) as TotalCountRow[]; - return toSafeInteger(rows[0]?.total, 0); - }); - -export const listMessagePayloadsForThreadDesc = ( - threadId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe<{ data_json: string }>( - `SELECT data_json - FROM documents - WHERE kind = 'message' AND thread_id = ? - ORDER BY sort_key DESC, updated_at DESC;`, - [threadId], - ) - .unprepared) as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }); - -export const listTurnSummaryPayloadsForThread = ( - threadId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe<{ data_json: string }>( - "SELECT data_json FROM documents WHERE kind = 'turn_summary' AND thread_id = ? ORDER BY sort_key DESC, updated_at DESC;", - [threadId], - ) - .unprepared) as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }); diff --git a/apps/server/src/persistence/metadataRepo.ts b/apps/server/src/persistence/metadataRepo.ts deleted file mode 100644 index e9c45518e8..0000000000 --- a/apps/server/src/persistence/metadataRepo.ts +++ /dev/null @@ -1,39 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -function tryParseJson(value: string): unknown { - try { - return JSON.parse(value) as unknown; - } catch { - return null; - } -} - -export const readMetadataValue = ( - key: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe<{ value_json: string }>("SELECT value_json FROM metadata WHERE key = ? LIMIT 1;", [key]) - .unprepared) as Array<{ value_json: string }>; - const row = rows[0]; - if (!row) { - return null; - } - return tryParseJson(row.value_json); - }); - -export const writeMetadataValue = ( - key: string, - value: unknown, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - yield* sql - .unsafe( - "INSERT INTO metadata (key, value_json) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json;", - [key, JSON.stringify(value)], - ) - .raw; - }).pipe(Effect.asVoid); diff --git a/apps/server/src/persistence/providerEventsRepo.ts b/apps/server/src/persistence/providerEventsRepo.ts deleted file mode 100644 index ab3af0c0a6..0000000000 --- a/apps/server/src/persistence/providerEventsRepo.ts +++ /dev/null @@ -1,124 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -function toSafeInteger(value: unknown, fallback = 0): number { - if (typeof value === "number" && Number.isFinite(value)) { - return Math.trunc(value); - } - if (typeof value === "bigint") { - return Number(value); - } - return fallback; -} - -export interface CompletedProviderItemRow { - item_id: string | null; - payload_json: string | null; -} - -export const insertProviderEvent = (input: { - id: string; - sessionId: string; - provider: string; - kind: string; - method: string; - runtimeThreadId: string | null; - turnId: string | null; - itemId: string | null; - requestId: string | null; - requestKind: string | null; - textDelta: string | null; - message: string | null; - payloadJson: string | null; - createdAt: string; -}): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rawResult = (yield* sql - .unsafe<{ changes?: number | bigint }>( - `INSERT OR IGNORE INTO provider_events ( - id, - session_id, - provider, - kind, - method, - thread_id, - turn_id, - item_id, - request_id, - request_kind, - text_delta, - message, - payload_json, - created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, - [ - input.id, - input.sessionId, - input.provider, - input.kind, - input.method, - input.runtimeThreadId, - input.turnId, - input.itemId, - input.requestId, - input.requestKind, - input.textDelta, - input.message, - input.payloadJson, - input.createdAt, - ], - ) - .raw) as { changes?: number | bigint }; - return toSafeInteger(rawResult.changes, 0); - }); - -export const listCompletedItemEventsBySessionTurn = (input: { - sessionId: string; - turnId: string; -}): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - return (yield* sql - .unsafe( - `SELECT item_id, payload_json - FROM provider_events - WHERE session_id = ? AND turn_id = ? AND method = 'item/completed' - ORDER BY created_at DESC;`, - [input.sessionId, input.turnId], - ) - .unprepared) as CompletedProviderItemRow[]; - }); - -export const listCompletedItemEventsByThreadTurn = (input: { - runtimeThreadId: string; - turnId: string; -}): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - return (yield* sql - .unsafe( - `SELECT item_id, payload_json - FROM provider_events - WHERE thread_id = ? AND turn_id = ? AND method = 'item/completed' - ORDER BY created_at DESC;`, - [input.runtimeThreadId, input.turnId], - ) - .unprepared) as CompletedProviderItemRow[]; - }); - -export const listCompletedItemEventsByTurn = ( - turnId: string, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - return (yield* sql - .unsafe( - `SELECT item_id, payload_json - FROM provider_events - WHERE turn_id = ? AND method = 'item/completed' - ORDER BY created_at DESC;`, - [turnId], - ) - .unprepared) as CompletedProviderItemRow[]; - }); diff --git a/apps/server/src/persistence/repos/documentsRepo.ts b/apps/server/src/persistence/repos/documentsRepo.ts index dd53bc3275..8121e77d4d 100644 --- a/apps/server/src/persistence/repos/documentsRepo.ts +++ b/apps/server/src/persistence/repos/documentsRepo.ts @@ -1 +1,259 @@ -export * from "../documentsRepo"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export interface DocumentRow { + id: string; + kind: string; + project_id: string | null; + thread_id: string | null; + sort_key: number | null; + created_at: string; + updated_at: string; + data_json: string; +} + +interface DataJsonRow { + data_json: string; +} + +export interface PaginatedMessagePayloadsRow { + data_json: string; +} + +export interface TotalCountRow { + total?: number | bigint; +} + +function toSafeInteger(value: unknown, fallback = 0): number { + if (typeof value === "number" && Number.isFinite(value)) { + return Math.trunc(value); + } + if (typeof value === "bigint") { + return Number(value); + } + return fallback; +} + +export const getDocumentRowById = ( + id: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe( + "SELECT id, kind, project_id, thread_id, sort_key, created_at, updated_at, data_json FROM documents WHERE id = ? LIMIT 1;", + [id], + ) + .unprepared) as DocumentRow[]; + return rows[0] ?? null; + }); + +export const upsertDocument = (input: { + id: string; + kind: "project" | "thread" | "message" | "turn_summary"; + projectId: string | null; + threadId: string | null; + sortKey: number | null; + createdAt: string; + updatedAt: string; + dataJson: string; +}): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + yield* sql + .unsafe( + `INSERT INTO documents ( + id, + kind, + project_id, + thread_id, + sort_key, + schema_version, + created_at, + updated_at, + data_json + ) VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + kind = excluded.kind, + project_id = excluded.project_id, + thread_id = excluded.thread_id, + sort_key = excluded.sort_key, + schema_version = excluded.schema_version, + updated_at = excluded.updated_at, + data_json = excluded.data_json;`, + [ + input.id, + input.kind, + input.projectId, + input.threadId, + input.sortKey, + input.createdAt, + input.updatedAt, + input.dataJson, + ], + ) + .raw; + }).pipe(Effect.asVoid); + +export const readNextSortKey = ( + kind: "message" | "turn_summary", + threadId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe<{ next_sort_key?: number }>( + "SELECT COALESCE(MAX(sort_key), 0) + 1 AS next_sort_key FROM documents WHERE kind = ? AND thread_id = ?;", + [kind, threadId], + ) + .unprepared) as Array<{ next_sort_key?: number }>; + return rows[0]?.next_sort_key ?? 1; + }); + +export const listProjectPayloads = (): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe( + "SELECT data_json FROM documents WHERE kind = 'project' ORDER BY updated_at DESC, created_at DESC;", + ) + .unprepared) as DataJsonRow[]; + return rows.map((row) => row.data_json); + }); + +export const listThreadPayloads = (): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe( + "SELECT data_json FROM documents WHERE kind = 'thread' ORDER BY updated_at DESC, created_at DESC;", + ) + .unprepared) as DataJsonRow[]; + return rows.map((row) => row.data_json); + }); + +export const listThreadPayloadsByProject = ( + projectId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe("SELECT data_json FROM documents WHERE kind = 'thread' AND project_id = ?;", [ + projectId, + ]) + .unprepared) as DataJsonRow[]; + return rows.map((row) => row.data_json); + }); + +export const findThreadPayloadByRuntimeThreadId = ( + runtimeThreadId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe( + "SELECT data_json FROM documents WHERE kind = 'thread' AND json_extract(data_json, '$.codexThreadId') = ? LIMIT 1;", + [runtimeThreadId], + ) + .unprepared) as DataJsonRow[]; + return rows[0]?.data_json ?? null; + }); + +export const deleteDocumentsByProjectId = ( + projectId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + yield* sql.unsafe("DELETE FROM documents WHERE project_id = ?;", [projectId]).raw; + }).pipe(Effect.asVoid); + +export const deleteDocumentsByThreadId = ( + threadId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + yield* sql.unsafe("DELETE FROM documents WHERE thread_id = ?;", [threadId]).raw; + }).pipe(Effect.asVoid); + +export const deleteDocumentByIdAndKind = ( + id: string, + kind: "thread" | "message" | "turn_summary", +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + yield* sql.unsafe("DELETE FROM documents WHERE id = ? AND kind = ?;", [id, kind]).raw; + }).pipe(Effect.asVoid); + +export const listMessagePayloadsForThread = ( + threadId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe<{ data_json: string }>( + "SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC;", + [threadId], + ) + .unprepared) as Array<{ data_json: string }>; + return rows.map((row) => row.data_json); + }); + +export const listPaginatedMessagePayloadsForThread = (input: { + threadId: string; + limit: number; + offset: number; +}): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe( + "SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC LIMIT ? OFFSET ?;", + [input.threadId, input.limit, input.offset], + ) + .unprepared) as PaginatedMessagePayloadsRow[]; + return rows.map((row) => row.data_json); + }); + +export const countMessagesForThread = ( + threadId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe("SELECT COUNT(1) AS total FROM documents WHERE kind = 'message' AND thread_id = ?;", [ + threadId, + ]) + .unprepared) as TotalCountRow[]; + return toSafeInteger(rows[0]?.total, 0); + }); + +export const listMessagePayloadsForThreadDesc = ( + threadId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe<{ data_json: string }>( + `SELECT data_json + FROM documents + WHERE kind = 'message' AND thread_id = ? + ORDER BY sort_key DESC, updated_at DESC;`, + [threadId], + ) + .unprepared) as Array<{ data_json: string }>; + return rows.map((row) => row.data_json); + }); + +export const listTurnSummaryPayloadsForThread = ( + threadId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe<{ data_json: string }>( + "SELECT data_json FROM documents WHERE kind = 'turn_summary' AND thread_id = ? ORDER BY sort_key DESC, updated_at DESC;", + [threadId], + ) + .unprepared) as Array<{ data_json: string }>; + return rows.map((row) => row.data_json); + }); diff --git a/apps/server/src/persistence/repos/metadataRepo.ts b/apps/server/src/persistence/repos/metadataRepo.ts index 8247746003..e9c45518e8 100644 --- a/apps/server/src/persistence/repos/metadataRepo.ts +++ b/apps/server/src/persistence/repos/metadataRepo.ts @@ -1 +1,39 @@ -export * from "../metadataRepo"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +function tryParseJson(value: string): unknown { + try { + return JSON.parse(value) as unknown; + } catch { + return null; + } +} + +export const readMetadataValue = ( + key: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe<{ value_json: string }>("SELECT value_json FROM metadata WHERE key = ? LIMIT 1;", [key]) + .unprepared) as Array<{ value_json: string }>; + const row = rows[0]; + if (!row) { + return null; + } + return tryParseJson(row.value_json); + }); + +export const writeMetadataValue = ( + key: string, + value: unknown, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + yield* sql + .unsafe( + "INSERT INTO metadata (key, value_json) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json;", + [key, JSON.stringify(value)], + ) + .raw; + }).pipe(Effect.asVoid); diff --git a/apps/server/src/persistence/repos/providerEventsRepo.ts b/apps/server/src/persistence/repos/providerEventsRepo.ts index 07548915a6..ab3af0c0a6 100644 --- a/apps/server/src/persistence/repos/providerEventsRepo.ts +++ b/apps/server/src/persistence/repos/providerEventsRepo.ts @@ -1 +1,124 @@ -export * from "../providerEventsRepo"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +function toSafeInteger(value: unknown, fallback = 0): number { + if (typeof value === "number" && Number.isFinite(value)) { + return Math.trunc(value); + } + if (typeof value === "bigint") { + return Number(value); + } + return fallback; +} + +export interface CompletedProviderItemRow { + item_id: string | null; + payload_json: string | null; +} + +export const insertProviderEvent = (input: { + id: string; + sessionId: string; + provider: string; + kind: string; + method: string; + runtimeThreadId: string | null; + turnId: string | null; + itemId: string | null; + requestId: string | null; + requestKind: string | null; + textDelta: string | null; + message: string | null; + payloadJson: string | null; + createdAt: string; +}): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rawResult = (yield* sql + .unsafe<{ changes?: number | bigint }>( + `INSERT OR IGNORE INTO provider_events ( + id, + session_id, + provider, + kind, + method, + thread_id, + turn_id, + item_id, + request_id, + request_kind, + text_delta, + message, + payload_json, + created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + input.id, + input.sessionId, + input.provider, + input.kind, + input.method, + input.runtimeThreadId, + input.turnId, + input.itemId, + input.requestId, + input.requestKind, + input.textDelta, + input.message, + input.payloadJson, + input.createdAt, + ], + ) + .raw) as { changes?: number | bigint }; + return toSafeInteger(rawResult.changes, 0); + }); + +export const listCompletedItemEventsBySessionTurn = (input: { + sessionId: string; + turnId: string; +}): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + return (yield* sql + .unsafe( + `SELECT item_id, payload_json + FROM provider_events + WHERE session_id = ? AND turn_id = ? AND method = 'item/completed' + ORDER BY created_at DESC;`, + [input.sessionId, input.turnId], + ) + .unprepared) as CompletedProviderItemRow[]; + }); + +export const listCompletedItemEventsByThreadTurn = (input: { + runtimeThreadId: string; + turnId: string; +}): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + return (yield* sql + .unsafe( + `SELECT item_id, payload_json + FROM provider_events + WHERE thread_id = ? AND turn_id = ? AND method = 'item/completed' + ORDER BY created_at DESC;`, + [input.runtimeThreadId, input.turnId], + ) + .unprepared) as CompletedProviderItemRow[]; + }); + +export const listCompletedItemEventsByTurn = ( + turnId: string, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + return (yield* sql + .unsafe( + `SELECT item_id, payload_json + FROM provider_events + WHERE turn_id = ? AND method = 'item/completed' + ORDER BY created_at DESC;`, + [turnId], + ) + .unprepared) as CompletedProviderItemRow[]; + }); diff --git a/apps/server/src/persistence/repos/stateEventsRepo.test.ts b/apps/server/src/persistence/repos/stateEventsRepo.test.ts index 344b11caeb..11670912ef 100644 --- a/apps/server/src/persistence/repos/stateEventsRepo.test.ts +++ b/apps/server/src/persistence/repos/stateEventsRepo.test.ts @@ -35,9 +35,6 @@ describe("stateEventsRepo", () => { }, createdAt, }), - () => { - throw new Error("Expected Effect SQL client to be available"); - }, ); const second = runWithSqlClient( db, @@ -47,13 +44,10 @@ describe("stateEventsRepo", () => { payload: { projectId: "project-1" }, createdAt, }), - () => { - throw new Error("Expected Effect SQL client to be available"); - }, ); - const lastSeq = runWithSqlClient(db, readLastStateSeq, () => 0); - const events = runWithSqlClient(db, listStateEventsAfterSeq(first.seq - 1), () => []); + const lastSeq = runWithSqlClient(db, readLastStateSeq); + const events = runWithSqlClient(db, listStateEventsAfterSeq(first.seq - 1)); expect(first.seq).toBeGreaterThan(0); expect(second.seq).toBeGreaterThan(first.seq); diff --git a/apps/server/src/persistence/repos/stateEventsRepo.ts b/apps/server/src/persistence/repos/stateEventsRepo.ts index b8477467fb..81b1fbb56c 100644 --- a/apps/server/src/persistence/repos/stateEventsRepo.ts +++ b/apps/server/src/persistence/repos/stateEventsRepo.ts @@ -1 +1,90 @@ -export * from "../stateEventsRepo"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import { stateEventSchema, type StateEvent } from "@t3tools/contracts"; + +interface StateEventRow { + seq: number; + event_type: string; + entity_id: string; + payload_json: string; + created_at: string; +} + +function toSafeInteger(value: unknown, fallback = 0): number { + if (typeof value === "number" && Number.isFinite(value)) { + return Math.trunc(value); + } + if (typeof value === "bigint") { + return Number(value); + } + return fallback; +} + +function tryParseJson(value: string): unknown { + try { + return JSON.parse(value) as unknown; + } catch { + return null; + } +} + +export const appendStateEvent = (input: { + eventType: string; + entityId: string; + payload: unknown; + createdAt: string; +}): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const result = (yield* sql + .unsafe<{ changes?: number | bigint; lastInsertRowid?: number | bigint }>( + "INSERT INTO state_events (event_type, entity_id, payload_json, created_at) VALUES (?, ?, ?, ?);", + [input.eventType, input.entityId, JSON.stringify(input.payload), input.createdAt], + ) + .raw) as { + changes?: number | bigint; + lastInsertRowid?: number | bigint; + }; + + return stateEventSchema.parse({ + seq: toSafeInteger(result.lastInsertRowid, 0), + eventType: input.eventType, + entityId: input.entityId, + payload: input.payload, + createdAt: input.createdAt, + }); + }); + +export const readLastStateSeq: Effect.Effect = Effect.gen( + function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe<{ seq?: number | bigint }>( + "SELECT COALESCE(MAX(seq), 0) AS seq FROM state_events;", + ) + .unprepared) as Array<{ seq?: number | bigint }>; + return toSafeInteger(rows[0]?.seq, 0); + }, +); + +export const listStateEventsAfterSeq = ( + afterSeq: number, +): Effect.Effect => + Effect.gen(function*() { + const sql = yield* SqlClient.SqlClient; + const rows = (yield* sql + .unsafe( + "SELECT seq, event_type, entity_id, payload_json, created_at FROM state_events WHERE seq > ? ORDER BY seq ASC;", + [afterSeq], + ) + .unprepared) as StateEventRow[]; + return rows.map((row) => + stateEventSchema.parse({ + seq: row.seq, + eventType: row.event_type, + entityId: row.entity_id, + payload: tryParseJson(row.payload_json), + createdAt: row.created_at, + }), + ); + }); diff --git a/apps/server/src/persistence/runtime.ts b/apps/server/src/persistence/runtime.ts index 5b91a5b5b7..cfd5bd7cee 100644 --- a/apps/server/src/persistence/runtime.ts +++ b/apps/server/src/persistence/runtime.ts @@ -2,6 +2,7 @@ import type * as Effect from "effect/Effect"; import type * as SqlClient from "effect/unstable/sql/SqlClient"; import type { EffectSqliteDatabaseAdapter, SqliteDatabase } from "../sqliteAdapter"; +import { PersistenceInitializationError } from "./errors"; function isEffectSqliteDatabase(db: SqliteDatabase): db is EffectSqliteDatabaseAdapter { return "runWithSqlClient" in db && typeof db.runWithSqlClient === "function"; @@ -10,10 +11,9 @@ function isEffectSqliteDatabase(db: SqliteDatabase): db is EffectSqliteDatabaseA export function runWithSqlClient( db: SqliteDatabase, effect: Effect.Effect, - fallback: () => A, ): A { if (isEffectSqliteDatabase(db)) { return db.runWithSqlClient(effect); } - return fallback(); + throw new PersistenceInitializationError("Expected Effect-backed sqlite adapter"); } diff --git a/apps/server/src/persistence/schema.ts b/apps/server/src/persistence/schema.ts new file mode 100644 index 0000000000..9b90147de6 --- /dev/null +++ b/apps/server/src/persistence/schema.ts @@ -0,0 +1,28 @@ +import * as Schema from "effect/Schema"; + +export const DocumentRowSchema = Schema.Struct({ + id: Schema.String, + kind: Schema.String, + project_id: Schema.NullOr(Schema.String), + thread_id: Schema.NullOr(Schema.String), + sort_key: Schema.NullOr(Schema.Number), + created_at: Schema.String, + updated_at: Schema.String, + data_json: Schema.String, +}); + +export const ProviderEventInsertStatsSchema = Schema.Struct({ + changes: Schema.NullOr(Schema.Number), +}); + +export const StateEventRowSchema = Schema.Struct({ + seq: Schema.Number, + event_type: Schema.String, + entity_id: Schema.String, + payload_json: Schema.String, + created_at: Schema.String, +}); + +export const MetadataRowSchema = Schema.Struct({ + value_json: Schema.String, +}); diff --git a/apps/server/src/persistence/stateEventsRepo.ts b/apps/server/src/persistence/stateEventsRepo.ts deleted file mode 100644 index 81b1fbb56c..0000000000 --- a/apps/server/src/persistence/stateEventsRepo.ts +++ /dev/null @@ -1,90 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; -import { stateEventSchema, type StateEvent } from "@t3tools/contracts"; - -interface StateEventRow { - seq: number; - event_type: string; - entity_id: string; - payload_json: string; - created_at: string; -} - -function toSafeInteger(value: unknown, fallback = 0): number { - if (typeof value === "number" && Number.isFinite(value)) { - return Math.trunc(value); - } - if (typeof value === "bigint") { - return Number(value); - } - return fallback; -} - -function tryParseJson(value: string): unknown { - try { - return JSON.parse(value) as unknown; - } catch { - return null; - } -} - -export const appendStateEvent = (input: { - eventType: string; - entityId: string; - payload: unknown; - createdAt: string; -}): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const result = (yield* sql - .unsafe<{ changes?: number | bigint; lastInsertRowid?: number | bigint }>( - "INSERT INTO state_events (event_type, entity_id, payload_json, created_at) VALUES (?, ?, ?, ?);", - [input.eventType, input.entityId, JSON.stringify(input.payload), input.createdAt], - ) - .raw) as { - changes?: number | bigint; - lastInsertRowid?: number | bigint; - }; - - return stateEventSchema.parse({ - seq: toSafeInteger(result.lastInsertRowid, 0), - eventType: input.eventType, - entityId: input.entityId, - payload: input.payload, - createdAt: input.createdAt, - }); - }); - -export const readLastStateSeq: Effect.Effect = Effect.gen( - function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe<{ seq?: number | bigint }>( - "SELECT COALESCE(MAX(seq), 0) AS seq FROM state_events;", - ) - .unprepared) as Array<{ seq?: number | bigint }>; - return toSafeInteger(rows[0]?.seq, 0); - }, -); - -export const listStateEventsAfterSeq = ( - afterSeq: number, -): Effect.Effect => - Effect.gen(function*() { - const sql = yield* SqlClient.SqlClient; - const rows = (yield* sql - .unsafe( - "SELECT seq, event_type, entity_id, payload_json, created_at FROM state_events WHERE seq > ? ORDER BY seq ASC;", - [afterSeq], - ) - .unprepared) as StateEventRow[]; - return rows.map((row) => - stateEventSchema.parse({ - seq: row.seq, - eventType: row.event_type, - entityId: row.entity_id, - payload: tryParseJson(row.payload_json), - createdAt: row.created_at, - }), - ); - }); diff --git a/apps/server/src/persistenceService.ts b/apps/server/src/persistenceService.ts index 69bbd14cec..8f144cae81 100644 --- a/apps/server/src/persistenceService.ts +++ b/apps/server/src/persistenceService.ts @@ -44,7 +44,6 @@ import { projectScriptsSchema, projectUpdateScriptsInputSchema, stateCatchUpInputSchema, - stateEventSchema, stateListMessagesInputSchema, stateMessageSchema, stateProjectSchema, @@ -131,14 +130,6 @@ const METADATA_KEY_APP_SETTINGS = "app.settings.v1"; const DEFAULT_TERMINAL_ID = "default"; const DEFAULT_TERMINAL_HEIGHT = 280; -interface StateEventRow { - seq: number; - event_type: string; - entity_id: string; - payload_json: string; - created_at: string; -} - interface ProviderEventInsertResult { inserted: boolean; runtimeThreadId: string | null; @@ -235,14 +226,7 @@ export class PersistenceService extends EventEmitter { } listProjects(): ProjectListResult { - const payloads = this.runWithEffectSql(listProjectPayloadsEffect(), () => { - const rows = this.db - .prepare( - "SELECT data_json FROM documents WHERE kind = 'project' ORDER BY updated_at DESC, created_at DESC;", - ) - .all() as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }); + const payloads = this.runWithEffectSql(listProjectPayloadsEffect()); const projects: StateProject[] = []; for (const payload of payloads) { @@ -292,12 +276,7 @@ export class PersistenceService extends EventEmitter { } this.withTransaction((pendingEvents) => { - const threadPayloads = this.runWithEffectSql(listThreadPayloadsByProjectEffect(input.id), () => { - const threadRows = this.db - .prepare("SELECT data_json FROM documents WHERE kind = 'thread' AND project_id = ?;") - .all(input.id) as Array<{ data_json: string }>; - return threadRows.map((row) => row.data_json); - }); + const threadPayloads = this.runWithEffectSql(listThreadPayloadsByProjectEffect(input.id)); const threadIds: string[] = []; for (const payload of threadPayloads) { const parsed = this.parseJson(payload, stateThreadSchema); @@ -306,9 +285,7 @@ export class PersistenceService extends EventEmitter { } } - this.runWithEffectSql(deleteDocumentsByProjectIdEffect(input.id), () => { - this.db.prepare("DELETE FROM documents WHERE project_id = ?;").run(input.id); - }); + this.runWithEffectSql(deleteDocumentsByProjectIdEffect(input.id)); const eventTime = nowIso(); for (const threadId of threadIds) { @@ -457,28 +434,15 @@ export class PersistenceService extends EventEmitter { } this.withTransaction((pendingEvents) => { - this.runWithEffectSql(deleteDocumentsByThreadIdEffect(thread.id), () => { - this.db.prepare("DELETE FROM documents WHERE thread_id = ?;").run(thread.id); - }); - this.runWithEffectSql(deleteDocumentByIdAndKindEffect(threadDocId(thread.id), "thread"), () => { - this.db - .prepare("DELETE FROM documents WHERE id = ? AND kind = 'thread';") - .run(threadDocId(thread.id)); - }); + this.runWithEffectSql(deleteDocumentsByThreadIdEffect(thread.id)); + this.runWithEffectSql(deleteDocumentByIdAndKindEffect(threadDocId(thread.id), "thread")); this.appendStateEvent(pendingEvents, "thread.delete", thread.id, { threadId: thread.id }, nowIso()); }); } loadSnapshot(): StateBootstrapResult { const projects = this.listProjects(); - const threadPayloads = this.runWithEffectSql(listThreadPayloadsEffect(), () => { - const threadRows = this.db - .prepare( - "SELECT data_json FROM documents WHERE kind = 'thread' ORDER BY updated_at DESC, created_at DESC;", - ) - .all() as Array<{ data_json: string }>; - return threadRows.map((row) => row.data_json); - }); + const threadPayloads = this.runWithEffectSql(listThreadPayloadsEffect()); const threads: StateBootstrapThread[] = []; for (const payload of threadPayloads) { @@ -518,31 +482,7 @@ export class PersistenceService extends EventEmitter { catchUp(raw: StateCatchUpInput): StateCatchUpResult { const input = stateCatchUpInputSchema.parse(raw); - const events = this.runWithEffectSql( - listStateEventsAfterSeqEffect(input.afterSeq), - () => { - const rows = this.db - .prepare( - "SELECT seq, event_type, entity_id, payload_json, created_at FROM state_events WHERE seq > ? ORDER BY seq ASC;", - ) - .all(input.afterSeq) as unknown as StateEventRow[]; - - const fallbackEvents: StateEvent[] = []; - for (const row of rows) { - const payload = this.tryParseJson(row.payload_json); - fallbackEvents.push( - stateEventSchema.parse({ - seq: row.seq, - eventType: row.event_type, - entityId: row.entity_id, - payload, - createdAt: row.created_at, - }), - ); - } - return fallbackEvents; - }, - ); + const events = this.runWithEffectSql(listStateEventsAfterSeqEffect(input.afterSeq)); return buildStateCatchUpResult({ events, @@ -558,21 +498,8 @@ export class PersistenceService extends EventEmitter { limit: input.limit, offset: input.offset, }), - () => { - const rows = this.db - .prepare( - "SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC LIMIT ? OFFSET ?;", - ) - .all(input.threadId, input.limit, input.offset) as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }, ); - const total = this.runWithEffectSql(countMessagesForThreadEffect(input.threadId), () => { - const totalRow = this.db - .prepare("SELECT COUNT(1) AS total FROM documents WHERE kind = 'message' AND thread_id = ?;") - .get(input.threadId) as { total: number } | undefined; - return totalRow?.total ?? 0; - }); + const total = this.runWithEffectSql(countMessagesForThreadEffect(input.threadId)); const messages: StateMessage[] = []; for (const payload of payloads) { @@ -995,11 +922,6 @@ export class PersistenceService extends EventEmitter { if (!message) continue; this.runWithEffectSql( deleteDocumentByIdAndKindEffect(messageDocId(thread.id, message.id), "message"), - () => { - this.db - .prepare("DELETE FROM documents WHERE id = ? AND kind = 'message';") - .run(messageDocId(thread.id, message.id)); - }, ); this.appendStateEvent( pendingEvents, @@ -1019,11 +941,6 @@ export class PersistenceService extends EventEmitter { ) { this.runWithEffectSql( deleteDocumentByIdAndKindEffect(turnSummaryDocId(thread.id, summary.turnId), "turn_summary"), - () => { - this.db - .prepare("DELETE FROM documents WHERE id = ? AND kind = 'turn_summary';") - .run(turnSummaryDocId(thread.id, summary.turnId)); - }, ); this.appendStateEvent( pendingEvents, @@ -1138,12 +1055,7 @@ export class PersistenceService extends EventEmitter { } private readLastStateSeq(): number { - return this.runWithEffectSql(readLastStateSeqEffect, () => { - const row = this.db - .prepare("SELECT COALESCE(MAX(seq), 0) AS seq FROM state_events;") - .get() as { seq: number } | undefined; - return row?.seq ?? 0; - }); + return this.runWithEffectSql(readLastStateSeqEffect); } private runDbTransaction(fn: () => T): T { @@ -1189,23 +1101,6 @@ export class PersistenceService extends EventEmitter { payload, createdAt, }), - () => { - const result = this.db - .prepare( - "INSERT INTO state_events (event_type, entity_id, payload_json, created_at) VALUES (?, ?, ?, ?);", - ) - .run(eventType, entityId, JSON.stringify(payload), createdAt) as { - lastInsertRowid?: number | bigint; - }; - const seq = toSafeInteger(result.lastInsertRowid, 0); - return stateEventSchema.parse({ - seq, - eventType, - entityId, - payload, - createdAt, - }); - }, ); pendingEvents.push(nextEvent); } @@ -1330,14 +1225,7 @@ export class PersistenceService extends EventEmitter { } private findThreadByRuntimeThreadId(runtimeThreadId: string): StateThread | null { - const payload = this.runWithEffectSql(findThreadPayloadByRuntimeThreadIdEffect(runtimeThreadId), () => { - const row = this.db - .prepare( - "SELECT data_json FROM documents WHERE kind = 'thread' AND json_extract(data_json, '$.codexThreadId') = ? LIMIT 1;", - ) - .get(runtimeThreadId) as { data_json: string } | undefined; - return row?.data_json ?? null; - }); + const payload = this.runWithEffectSql(findThreadPayloadByRuntimeThreadIdEffect(runtimeThreadId)); if (!payload) return null; const parsed = this.parseJson(payload, stateThreadSchema); return parsed ? normalizeThread(parsed) : null; @@ -1368,13 +1256,6 @@ export class PersistenceService extends EventEmitter { sessionId: input.sessionId, turnId: input.turnId, }), - () => - this.db.prepare( - `SELECT item_id, payload_json - FROM provider_events - WHERE session_id = ? AND turn_id = ? AND method = 'item/completed' - ORDER BY created_at DESC;`, - ).all(input.sessionId, input.turnId) as CompletedProviderItemRow[], ), ); } @@ -1385,27 +1266,11 @@ export class PersistenceService extends EventEmitter { runtimeThreadId: input.runtimeThreadId, turnId: input.turnId, }), - () => - this.db.prepare( - `SELECT item_id, payload_json - FROM provider_events - WHERE thread_id = ? AND turn_id = ? AND method = 'item/completed' - ORDER BY created_at DESC;`, - ).all(input.runtimeThreadId, input.turnId) as CompletedProviderItemRow[], ), ); } rowGroups.push( - this.runWithEffectSql( - listCompletedItemEventsByTurnEffect(input.turnId), - () => - this.db.prepare( - `SELECT item_id, payload_json - FROM provider_events - WHERE turn_id = ? AND method = 'item/completed' - ORDER BY created_at DESC;`, - ).all(input.turnId) as CompletedProviderItemRow[], - ), + this.runWithEffectSql(listCompletedItemEventsByTurnEffect(input.turnId)), ); for (const rows of rowGroups) { @@ -1427,17 +1292,7 @@ export class PersistenceService extends EventEmitter { } private findLatestAssistantMessageIdForThread(threadId: string): string | undefined { - const payloads = this.runWithEffectSql(listMessagePayloadsForThreadDescEffect(threadId), () => { - const rows = this.db - .prepare( - `SELECT data_json - FROM documents - WHERE kind = 'message' AND thread_id = ? - ORDER BY sort_key DESC, updated_at DESC;`, - ) - .all(threadId) as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }); + const payloads = this.runWithEffectSql(listMessagePayloadsForThreadDescEffect(threadId)); for (const payload of payloads) { const message = this.parseJson(payload, stateMessageSchema); @@ -1453,14 +1308,7 @@ export class PersistenceService extends EventEmitter { } private listMessagesForThread(threadId: string): StateMessage[] { - const payloads = this.runWithEffectSql(listMessagePayloadsForThreadEffect(threadId), () => { - const rows = this.db - .prepare( - "SELECT data_json FROM documents WHERE kind = 'message' AND thread_id = ? ORDER BY sort_key ASC;", - ) - .all(threadId) as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }); + const payloads = this.runWithEffectSql(listMessagePayloadsForThreadEffect(threadId)); const messages: StateMessage[] = []; for (const payload of payloads) { const parsed = this.parseJson(payload, stateMessageSchema); @@ -1472,14 +1320,7 @@ export class PersistenceService extends EventEmitter { } private listTurnSummariesForThread(threadId: string): StateTurnSummary[] { - const payloads = this.runWithEffectSql(listTurnSummaryPayloadsForThreadEffect(threadId), () => { - const rows = this.db - .prepare( - "SELECT data_json FROM documents WHERE kind = 'turn_summary' AND thread_id = ? ORDER BY sort_key DESC, updated_at DESC;", - ) - .all(threadId) as Array<{ data_json: string }>; - return rows.map((row) => row.data_json); - }); + const payloads = this.runWithEffectSql(listTurnSummaryPayloadsForThreadEffect(threadId)); const summaries: StateTurnSummary[] = []; for (const payload of payloads) { const parsed = this.parseJson(payload, stateTurnSummarySchema); @@ -1502,63 +1343,15 @@ export class PersistenceService extends EventEmitter { updatedAt: input.updatedAt, dataJson: JSON.stringify(input.data), }), - () => { - this.db - .prepare( - `INSERT INTO documents ( - id, - kind, - project_id, - thread_id, - sort_key, - schema_version, - created_at, - updated_at, - data_json - ) VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?) - ON CONFLICT(id) DO UPDATE SET - kind = excluded.kind, - project_id = excluded.project_id, - thread_id = excluded.thread_id, - sort_key = excluded.sort_key, - schema_version = excluded.schema_version, - updated_at = excluded.updated_at, - data_json = excluded.data_json;`, - ) - .run( - input.id, - input.kind, - input.projectId, - input.threadId, - input.sortKey, - input.createdAt, - input.updatedAt, - JSON.stringify(input.data), - ); - }, ); } private getDocumentRowById(id: string): DocumentRow | null { - return this.runWithEffectSql(getDocumentRowByIdEffect(id), () => { - const row = this.db - .prepare( - "SELECT id, kind, project_id, thread_id, sort_key, created_at, updated_at, data_json FROM documents WHERE id = ? LIMIT 1;", - ) - .get(id) as DocumentRow | undefined; - return row ?? null; - }); + return this.runWithEffectSql(getDocumentRowByIdEffect(id)); } private readNextSortKey(kind: "message" | "turn_summary", threadId: string): number { - return this.runWithEffectSql(readNextSortKeyEffect(kind, threadId), () => { - const row = this.db - .prepare( - "SELECT COALESCE(MAX(sort_key), 0) + 1 AS next_sort_key FROM documents WHERE kind = ? AND thread_id = ?;", - ) - .get(kind, threadId) as { next_sort_key: number } | undefined; - return row?.next_sort_key ?? 1; - }); + return this.runWithEffectSql(readNextSortKeyEffect(kind, threadId)); } private resolveThreadIdForEvent(event: ProviderEvent, runtimeThreadId: string | null): string | null { @@ -1607,44 +1400,6 @@ export class PersistenceService extends EventEmitter { payloadJson, createdAt: event.createdAt, }), - () => { - const result = this.db - .prepare( - `INSERT OR IGNORE INTO provider_events ( - id, - session_id, - provider, - kind, - method, - thread_id, - turn_id, - item_id, - request_id, - request_kind, - text_delta, - message, - payload_json, - created_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, - ) - .run( - event.id, - event.sessionId, - event.provider, - event.kind, - event.method, - runtimeThreadId, - event.turnId ?? null, - event.itemId ?? null, - event.requestId ?? null, - event.requestKind ?? null, - event.textDelta ?? null, - event.message ?? null, - payloadJson, - event.createdAt, - ) as { changes?: number | bigint }; - return toSafeInteger(result.changes, 0); - }, ); return { inserted: changes > 0, @@ -1689,26 +1444,12 @@ export class PersistenceService extends EventEmitter { } private readMetadata(key: string): unknown { - return this.runWithEffectSql(readMetadataValueEffect(key), () => { - const row = this.db - .prepare("SELECT value_json FROM metadata WHERE key = ? LIMIT 1;") - .get(key) as { value_json: string } | undefined; - if (!row) { - return null; - } - return this.tryParseJson(row.value_json); - }); + return this.runWithEffectSql(readMetadataValueEffect(key)); } private writeMetadata(key: string, value: unknown, inTransaction = false): void { const write = () => { - this.runWithEffectSql(writeMetadataValueEffect(key, value), () => { - this.db - .prepare( - "INSERT INTO metadata (key, value_json) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json;", - ) - .run(key, JSON.stringify(value)); - }); + this.runWithEffectSql(writeMetadataValueEffect(key, value)); }; if (inTransaction) { write(); @@ -1719,8 +1460,7 @@ export class PersistenceService extends EventEmitter { private runWithEffectSql( effect: Effect.Effect, - fallback: () => A, ): A { - return runWithSqlClient(this.db, effect, fallback); + return runWithSqlClient(this.db, effect); } }