Open History to see the last commit
1import * as Migrator from "effect/sql/Migrator";
2import * as Effect from "effect/Effect";
3import * as SqlClient from "effect/sql/SqlClient";
4import {
5 DATABASE_MIGRATION_PROGRESS_MESSAGE,
6 DATABASE_MIGRATIONS_FINISHED_MESSAGE,
7 DATABASE_MIGRATIONS_STARTED_MESSAGE,
8} from "@t3tools/shared/databaseMigrationLog";
9import { reconcileV2PreviewMigration } from "./reconcileV2PreviewMigration.ts";
10
11import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
12import Migration0002 from "./Migrations/002_OrchestrationCommandReceipts.ts";
13import Migration0003 from "./Migrations/003_CheckpointDiffBlobs.ts";
14import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
15import Migration0005 from "./Migrations/005_Projections.ts";
16import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
17import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
18import Migration0008 from "./Migrations/008_ProjectionThreadActivitySequence.ts";
19import Migration0009 from "./Migrations/009_ProviderSessionRuntimeMode.ts";
20import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
21import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
22import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
23import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
24import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
25import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
26import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
27import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
28import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
29import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
30import Migration0020 from "./Migrations/020_AuthAccessManagement.ts";
31import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts";
32import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts";
33import Migration0023 from "./Migrations/023_ProjectionThreadShellSummary.ts";
34import Migration0024 from "./Migrations/024_BackfillProjectionThreadShellSummary.ts";
35import Migration0025 from "./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts";
36import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts";
37import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
38import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
39import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
40import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
41import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
42import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
43import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
44import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
45import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
46import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
47import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
48import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
49import Migration0039 from "./Migrations/039_ProjectionProjectsDefaultThreadEnvMode.ts";
50import Migration0040 from "./Migrations/040_ProjectionProjectFaviconPath.ts";
51import Migration0041 from "./Migrations/041_AuthSessionClientConnection.ts";
52import Migration0042 from "./Migrations/042_ProjectionThreadLinkedPullRequest.ts";
53import Migration0043 from "./Migrations/043_ProjectionThreadsUnsettledAt.ts";
54import Migration0044 from "./Migrations/044_ClearAutomaticProjectModelDefaults.ts";
55import Migration0045 from "./Migrations/045_ProjectionProjectsAutoPull.ts";
56import Migration0046 from "./Migrations/046_RepairAutomaticSettlementTimestamps.ts";
57import Migration0047 from "./Migrations/047_ProjectionProjectIcon.ts";
58import Migration0048 from "./Migrations/048_ProjectionThreadBranchPullRequest.ts";
59import Migration0049 from "./Migrations/049_ProjectionThreadsActiveOrderKey.ts";
60import Migration0050 from "./Migrations/050_ProjectionThreadPullRequests.ts";
61import Migration0051 from "./Migrations/051_ProjectionThreadMessageContext.ts";
62import Migration0052 from "./Migrations/052_ProjectionThreadTitleState.ts";
63import Migration0053 from "./Migrations/053_PullRequestFilesViewed.ts";
64import Migration0054 from "./Migrations/054_ProjectionThreadsAutoSettleDisabledAt.ts";
65import Migration0055 from "./Migrations/055_OrchestrationV2.ts";
66import Migration0056 from "./Migrations/056_RemoveRedundantProjectionIndexes.ts";
67import Migration0057 from "./Migrations/057_ScheduledTaskWebhooks.ts";
68import Migration0058 from "./Migrations/058_WebhookRelayDeliveries.ts";
69import Migration0059 from "./Migrations/059_McpAppModelContext.ts";
70import Migration0060 from "./Migrations/060_ThreadSnapshotWindowIndexes.ts";
71import Migration0061 from "./Migrations/061_PullRequestReviewGuides.ts";
72import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";
73import Migration0063 from "./Migrations/063_DropUnusedV1Projections.ts";
74import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.ts";
75import Migration0065 from "./Migrations/065_CodexUsageNativeTurnIndex.ts";
76import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts";
77import Migration0067 from "./Migrations/067_WebhookDedupe.ts";
78import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
79import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
80import Migration0070 from "./Migrations/070_PeerLinks.ts";
81import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
82import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
83import Migration0073 from "./Migrations/073_ActiveTurnItemIndexes.ts";
84import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts";
85import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts";
86import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts";
87import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts";
88import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts";
89import Migration0079 from "./Migrations/079_DelegatedRecoveryIndexes.ts";
90import Migration0080 from "./Migrations/080_ScheduledTaskThreadMode.ts";
91import Migration0081 from "./Migrations/081_ProjectionMessageSearchText.ts";
92import Migration0082 from "./Migrations/082_TurnItemConversationIndex.ts";
93import Migration0083 from "./Migrations/083_CommandReadIndexes.ts";
94import Migration0084 from "./Migrations/084_LastExecutedRunIndex.ts";
95import Migration0085 from "./Migrations/085_TurnItemCounts.ts";
96import Migration0086 from "./Migrations/086_QueuedTurnInputIndex.ts";
97import Migration0087 from "./Migrations/087_ProjectionProjectsCustomTitle.ts";
98import Migration0088 from "./Migrations/088_TurnItemTypeStatusIndex.ts";
99import Migration0089 from "./Migrations/089_ShellThreadReadIndexes.ts";
100
101const migrationEntries = [
102 [1, "OrchestrationEvents", Migration0001],
103 [2, "OrchestrationCommandReceipts", Migration0002],
104 [3, "CheckpointDiffBlobs", Migration0003],
105 [4, "ProviderSessionRuntime", Migration0004],
106 [5, "Projections", Migration0005],
107 [6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006],
108 [7, "ProjectionThreadMessageAttachments", Migration0007],
109 [8, "ProjectionThreadActivitySequence", Migration0008],
110 [9, "ProviderSessionRuntimeMode", Migration0009],
111 [10, "ProjectionThreadsRuntimeMode", Migration0010],
112 [11, "OrchestrationThreadCreatedRuntimeMode", Migration0011],
113 [12, "ProjectionThreadsInteractionMode", Migration0012],
114 [13, "ProjectionThreadProposedPlans", Migration0013],
115 [14, "ProjectionThreadProposedPlanImplementation", Migration0014],
116 [15, "ProjectionTurnsSourceProposedPlan", Migration0015],
117 [16, "CanonicalizeModelSelections", Migration0016],
118 [17, "ProjectionThreadsArchivedAt", Migration0017],
119 [18, "ProjectionThreadsArchivedAtIndex", Migration0018],
120 [19, "ProjectionSnapshotLookupIndexes", Migration0019],
121 [20, "AuthAccessManagement", Migration0020],
122 [21, "AuthSessionClientMetadata", Migration0021],
123 [22, "AuthSessionLastConnectedAt", Migration0022],
124 [23, "ProjectionThreadShellSummary", Migration0023],
125 [24, "BackfillProjectionThreadShellSummary", Migration0024],
126 [25, "CleanupInvalidProjectionPendingApprovals", Migration0025],
127 [26, "CanonicalizeModelSelectionOptions", Migration0026],
128 [27, "ProviderSessionRuntimeInstanceId", Migration0027],
129 [28, "ProjectionThreadSessionInstanceId", Migration0028],
130 [29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
131 [30, "ProjectionThreadShellArchiveIndexes", Migration0030],
132 [31, "AuthAuthorizationScopes", Migration0031],
133 [32, "AuthPairingProofKeyThumbprint", Migration0032],
134 [33, "ProjectionThreadsSettled", Migration0033],
135 [34, "ProjectionThreadsSnoozed", Migration0034],
136 [35, "ProjectionThreadTitleRegeneration", Migration0035],
137 [36, "ProjectionThreadsPinned", Migration0036],
138 [37, "ProjectionTurnsKeysetIndex", Migration0037],
139 [38, "ProjectionThreadsPinOrderKey", Migration0038],
140 [39, "ProjectionProjectsDefaultThreadEnvMode", Migration0039],
141 [40, "ProjectionProjectFaviconPath", Migration0040],
142 [41, "AuthSessionClientConnection", Migration0041],
143 [42, "ProjectionThreadLinkedPullRequest", Migration0042],
144 [43, "ProjectionThreadsUnsettledAt", Migration0043],
145 [44, "ClearAutomaticProjectModelDefaults", Migration0044],
146 [45, "ProjectionProjectsAutoPull", Migration0045],
147 [46, "RepairAutomaticSettlementTimestamps", Migration0046],
148 [47, "ProjectionProjectIcon", Migration0047],
149 [48, "ProjectionThreadBranchPullRequest", Migration0048],
150 [49, "ProjectionThreadsActiveOrderKey", Migration0049],
151 [50, "ProjectionThreadPullRequests", Migration0050],
152 [51, "ProjectionThreadMessageContext", Migration0051],
153 [52, "ProjectionThreadTitleState", Migration0052],
154 [53, "PullRequestFilesViewed", Migration0053],
155 [54, "ProjectionThreadsAutoSettleDisabledAt", Migration0054],
156 // Preserve this migration's schema. Future V2 schema changes need new migrations.
157 [55, "OrchestrationV2", Migration0055],
158 [56, "RemoveRedundantProjectionIndexes", Migration0056],
159 [57, "ScheduledTaskWebhooks", Migration0057],
160 [58, "WebhookRelayDeliveries", Migration0058],
161 [59, "McpAppModelContext", Migration0059],
162 [60, "ThreadSnapshotWindowIndexes", Migration0060],
163 [61, "PullRequestReviewGuides", Migration0061],
164 [62, "ThreadFailureLookupIndex", Migration0062],
165 [63, "DropUnusedV1Projections", Migration0063],
166 [64, "CanonicalizeThreadPullRequestLinks", Migration0064],
167 [65, "CodexUsageNativeTurnIndex", Migration0065],
168 [66, "RepairClientSettlementTimestamps", Migration0066],
169 [67, "WebhookDedupe", Migration0067],
170 [68, "ShellStopRequestIndex", Migration0068],
171 [69, "ThreadMessageSearch", Migration0069],
172 [70, "PeerLinks", Migration0070],
173 [71, "PeerLinkFence", Migration0071],
174 [72, "WaitingLinkRequestIndex", Migration0072],
175 [73, "ActiveTurnItemIndexes", Migration0073],
176 [74, "ExcludeAttachmentPlaceholdersFromSearch", Migration0074],
177 [75, "SubagentDeliveryState", Migration0075],
178 [76, "ProjectionProjectsPinArchive", Migration0076],
179 [77, "RepairBooleanSettledOverride", Migration0077],
180 [78, "DropOrchestrationEventCorrelationIndex", Migration0078],
181 [79, "DelegatedRecoveryIndexes", Migration0079],
182 [80, "ScheduledTaskThreadMode", Migration0080],
183 [81, "ProjectionMessageSearchText", Migration0081],
184 [82, "TurnItemConversationIndex", Migration0082],
185 [83, "CommandReadIndexes", Migration0083],
186 [84, "LastExecutedRunIndex", Migration0084],
187 [85, "TurnItemCounts", Migration0085],
188 [86, "QueuedTurnInputIndex", Migration0086],
189 [87, "ProjectionProjectsCustomTitle", Migration0087],
190 [88, "TurnItemTypeStatusIndex", Migration0088],
191 [89, "ShellThreadReadIndexes", Migration0089],
192] as const;
193
194export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
195
196const makeMigrationLoader = (throughId?: number) =>
197 Migrator.fromRecord(
198 Object.fromEntries(
199 migrationEntries
200 .filter(([id]) => throughId === undefined || id <= throughId)
201 .map(([id, name, migration]) => [`${id}_${name}`, migration]),
202 ),
203 );
204
205const FIRST_V2_MIGRATION_ID = 55;
206
207export function skippedV2Migrations(
208 recorded: ReadonlyArray<{ readonly id: number; readonly name: string }>,
209 throughId?: number,
210): string[] {
211 const latestRecordedId = Math.max(0, ...recorded.map((row) => row.id));
212 const recordedNames = new Map(recorded.map((row) => [row.id, row.name]));
213 return migrationManifest.flatMap(([id, name]) => {
214 if (
215 id < FIRST_V2_MIGRATION_ID ||
216 id > latestRecordedId ||
217 (throughId !== undefined && id > throughId)
218 )
219 return [];
220 const recordedName = recordedNames.get(id);
221 return recordedName === name ? [] : [`${id}_${name} (recorded: ${recordedName ?? "nothing"})`];
222 });
223}
224
225// Migrators skip ids up to the highest recorded; reject collisions that would skip V2 schema.
226const assertV2MigrationsCanRun = Effect.fn("assertV2MigrationsCanRun")(function* (
227 throughId?: number,
228) {
229 const sql = yield* SqlClient.SqlClient;
230 const tables = yield* sql`
231 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
232 `;
233 if (tables.length === 0) return;
234 const recorded = yield* sql<{
235 readonly migration_id: number;
236 readonly name: string;
237 }>`SELECT migration_id, name FROM effect_sql_migrations`;
238 const skipped = skippedV2Migrations(
239 recorded.map((row) => ({ id: row.migration_id, name: row.name })),
240 throughId,
241 );
242 const latestRecordedId = Math.max(0, ...recorded.map((row) => row.migration_id));
243 if (skipped.length === 0) return;
244 return yield* new Migrator.MigrationError({
245 kind: "BadState",
246 message: `This database's migration history would skip required schema migrations: ${skipped.join(", ")}. The migrator skips every id up to the highest recorded id (${latestRecordedId}), regardless of name. It was probably written by a different build. Start the build that wrote it, or report this migration history so an upgrade path can be added.`,
247 });
248});
249
250const latestMigrationId = Math.max(...migrationEntries.map(([id]) => id));
251
252// Mirrors the Migrator, which runs only ids above the highest recorded, plus the V2-preview reconciliation.
253export const hasPendingMigrations = Effect.fn("hasPendingMigrations")(function* () {
254 const sql = yield* SqlClient.SqlClient;
255 const tables = yield* sql`
256 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
257 `;
258 if (tables.length === 0) return true;
259 const rows = yield* sql<{ readonly latestId: number | null; readonly previewRows: number }>`
260 SELECT
261 MAX(migration_id) AS latestId,
262 SUM(name = 'OrchestrationV2' AND migration_id IN (53, 54)) AS previewRows
263 FROM effect_sql_migrations
264 `;
265 const row = rows[0];
266 return (row?.latestId ?? 0) < latestMigrationId || (row?.previewRows ?? 0) > 0;
267});
268
269const run = Migrator.make({});
270
271export interface RunMigrationsOptions {
272 readonly toMigrationInclusive?: number | undefined;
273}
274
275export const runMigrations = Effect.fn("runMigrations")(function* ({
276 toMigrationInclusive,
277}: RunMigrationsOptions = {}) {
278 // The desktop waits past its readiness budget until the finished line follows this one.
279 if (yield* hasPendingMigrations()) yield* Effect.log(DATABASE_MIGRATIONS_STARTED_MESSAGE);
280 const includesV2 =
281 toMigrationInclusive === undefined || toMigrationInclusive >= FIRST_V2_MIGRATION_ID;
282 const previewMigrations = includesV2 ? yield* reconcileV2PreviewMigration() : [];
283 if (includesV2) {
284 yield* assertV2MigrationsCanRun(toMigrationInclusive);
285 }
286 const sql = yield* SqlClient.SqlClient;
287 const ledger = yield* sql`
288 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'
289 `;
290 const [latest] =
291 ledger.length === 0
292 ? []
293 : yield* sql<{
294 readonly id: number | null;
295 }>`SELECT MAX(migration_id) AS id FROM effect_sql_migrations`;
296 const latestRecordedId = latest?.id ?? 0;
297 const pending = migrationEntries.filter(
298 ([id]) =>
299 id > latestRecordedId && (toMigrationInclusive === undefined || id <= toMigrationInclusive),
300 );
301 // One transaction per migration: an index build on a large database can take minutes, and a
302 // restart then resumes after the last finished migration instead of rolling all of them back.
303 const executedMigrations: Array<readonly [id: number, name: string]> = [...previewMigrations];
304 for (const [index, [id, name]] of pending.entries()) {
305 if (latestRecordedId > 0) {
306 yield* Effect.log(DATABASE_MIGRATION_PROGRESS_MESSAGE).pipe(
307 Effect.annotateLogs({
308 migration: `${id}_${name}`,
309 progress: `${index + 1} of ${pending.length}`,
310 }),
311 );
312 }
313 executedMigrations.push(...(yield* run({ loader: makeMigrationLoader(id) })));
314 }
315 const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);
316 yield* migrations.length === 0
317 ? Effect.logDebug("Database schema is current")
318 : Effect.log(DATABASE_MIGRATIONS_FINISHED_MESSAGE).pipe(Effect.annotateLogs({ migrations }));
319
320 const recorded = yield* sql<{
321 readonly migration_id: number;
322 readonly name: string;
323 }>`SELECT migration_id, name FROM effect_sql_migrations`;
324 const manifestNames = new Map<number, string>(migrationEntries.map(([id, name]) => [id, name]));
325 const divergent = recorded.flatMap((row) => {
326 const expected = manifestNames.get(row.migration_id);
327 if (expected === undefined) {
328 return [`${row.migration_id}:${row.name} (unknown to this build)`];
329 }
330 return expected === row.name
331 ? []
332 : [`${row.migration_id}:${row.name} (this build: ${expected})`];
333 });
334 if (divergent.length > 0) {
335 yield* Effect.logWarning(
336 "Database migration history diverges from this build; recorded migration ids are skipped, not reconciled by name.",
337 ).pipe(Effect.annotateLogs({ divergent }));
338 }
339 return executedMigrations;
340});