Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Path from "effect/Path";
6import * as SqlClient from "effect/sql/SqlClient";
7
8import { runMigrations } from "../src/persistence/Migrations.ts";
9import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
10import { runMigrateDevDb } from "./migrate-dev-db.ts";
11
12const withDatabase = <A, E>(
13 databasePath: string,
14 effect: Effect.Effect<A, E, SqlClient.SqlClient>,
15) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
16
17const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* (
18 baseDir: string,
19) {
20 const fs = yield* FileSystem.FileSystem;
21 const path = yield* Path.Path;
22 const stateDir = path.join(baseDir, "userdata");
23 const databasePath = path.join(stateDir, "statev2.sqlite");
24 yield* fs.makeDirectory(stateDir, { recursive: true });
25 yield* withDatabase(
26 databasePath,
27 Effect.gen(function* () {
28 const sql = yield* SqlClient.SqlClient;
29 yield* runMigrations();
30
31 yield* sql`INSERT INTO projection_projects
32 (project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at)
33 VALUES
34 ('project-kept', 'Kept', '/tmp/kept', '[]', '2026-08-01', '2026-08-01', NULL),
35 ('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`;
36
37 const forkPayload =
38 '{"lineage":{"parentThreadId":"stopped-thread","relationshipToParent":"fork","rootThreadId":"stopped-thread"}}';
39 const subagentPayload =
40 '{"lineage":{"parentThreadId":"subagent-parent","relationshipToParent":"subagent","rootThreadId":"subagent-parent"},"forkedFrom":{"type":"node","nodeId":"node-1"}}';
41 const watchedPayload = JSON.stringify({
42 pullRequests: [
43 {
44 host: "github.com",
45 repository: "owner/repo",
46 number: 7,
47 url: "https://github.com/owner/repo/pull/7",
48 source: "agent",
49 linkedAt: "2026-08-01T00:00:00.000Z",
50 snapshot: null,
51 stack: null,
52 watch: {
53 startedAt: "2026-08-01T00:00:00.000Z",
54 headSha: null,
55 failedChecks: [],
56 passed: false,
57 passedChecks: [],
58 remarksThrough: "2026-08-01T00:00:00.000Z",
59 remarkIds: [],
60 conflicting: false,
61 wakes: 0,
62 },
63 },
64 ],
65 });
66 const threads = [
67 ["stopped-thread", "project-kept", "completed", watchedPayload, "2026-08-01"],
68 ["fork-thread", "project-kept", "completed", forkPayload, "2026-08-02"],
69 ["running-thread", "project-kept", "running", "{}", "2026-08-05"],
70 ["settled-thread", "project-kept", "completed", '{"settledAt":"2026-08-01"}', "2026-08-05"],
71 [
72 "archived-thread",
73 "project-kept",
74 "completed",
75 '{"archivedAt":"2026-08-01"}',
76 "2026-08-05",
77 ],
78 [
79 "limit-thread",
80 "project-kept",
81 "completed",
82 '{"limitRecovery":{"autoResume":true}}',
83 "2026-08-05",
84 ],
85 ["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"],
86 ["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"],
87 ["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"],
88 ] as const;
89 for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) {
90 yield* sql`INSERT INTO orchestration_v2_projection_threads
91 (thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, payload_json)
92 VALUES (${threadId}, ${projectId}, ${threadId}, 'codex', 'full-access', 'default', '2026-08-01', ${updatedAt}, ${payload})`;
93 yield* sql`INSERT INTO orchestration_v2_projection_runs
94 (run_id, thread_id, ordinal, provider, status, requested_at, payload_json)
95 VALUES (${`run-${threadId}`}, ${threadId}, 1, 'codex', ${runStatus}, '2026-08-01', '{}')`;
96 yield* sql`INSERT INTO orchestration_events
97 (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json)
98 VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`;
99 }
100 yield* sql`INSERT INTO orchestration_v2_projection_provider_sessions
101 (provider_session_id, thread_id, provider, status, updated_at, payload_json)
102 VALUES ('session-shared', 'running-thread', 'codex', 'stopped', '2026-08-01', '{}')`;
103 yield* sql`INSERT INTO orchestration_v2_projection_provider_session_bindings
104 (provider_session_id, thread_id)
105 VALUES ('session-shared', 'running-thread'), ('session-shared', 'stopped-thread')`;
106 yield* sql`INSERT INTO orchestration_v2_projection_context_transfers
107 (context_transfer_id, source_thread_id, target_thread_id, type, status, updated_at, payload_json)
108 VALUES ('transfer-1', 'archived-thread', 'stopped-thread', 'provider_handoff', 'completed', '2026-08-01', '{}')`;
109 yield* sql`INSERT INTO scheduled_tasks
110 (task_id, title, prompt, enabled, schedule_json, project_id, workspace_strategy_json,
111 model_selection_json, runtime_mode, interaction_mode, created_by, creation_source,
112 created_at, updated_at, last_run_status, run_count)
113 VALUES ('task-1', 'Nightly', 'Run it', 1, '{}', 'project-kept', '{}', '{}',
114 'full-access', 'default', 'user', 'user', '2026-08-01', '2026-08-01', 'never', 0)`;
115 yield* sql`INSERT INTO scheduled_task_webhook_replay_keys
116 (task_id, replay_key, delivery_id, expires_at)
117 VALUES ('task-1', 'replay-1', 'delivery-1', 1900000000000)`;
118 yield* sql`INSERT INTO scheduled_task_webhook_pending
119 (delivery_id, task_id, coalesce_key, due_at, task_json, request_json, delivery_ids_json)
120 VALUES ('delivery-1', 'task-1', 'key-1', 1900000000000, '{}', '{}', '[]')`;
121 yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
122 VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
123 yield* sql`INSERT INTO peer_environment_links
124 (environment_id, secret_name, label, urls_json, access, linked_at, expires_at)
125 VALUES ('environment-box', 'peer-link-box', 'Box', '["https://box.example"]', 'auto',
126 '2026-08-01', '2027-08-01')`;
127 }),
128 );
129 return databasePath;
130});
131
132it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
133 it.effect("keeps stopped and settled thread families and clears pending work", () =>
134 Effect.gen(function* () {
135 const fs = yield* FileSystem.FileSystem;
136 const path = yield* Path.Path;
137 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
138 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
139 const source = yield* createFixtureSource(sourceDir);
140
141 const result = yield* runMigrateDevDb(
142 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
143 { sharedHome: sourceDir },
144 );
145
146 assert.equal(result.databasePath, path.join(destDir, "userdata", "statev2.sqlite"));
147 const kept = yield* withDatabase(
148 result.databasePath,
149 Effect.gen(function* () {
150 const sql = yield* SqlClient.SqlClient;
151 const threads = yield* sql<{ thread_id: string }>`
152 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
153 const events = yield* sql<{ stream_id: string }>`
154 SELECT stream_id FROM orchestration_events ORDER BY stream_id`;
155 const sessions = yield* sql<{ provider_session_id: string }>`
156 SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`;
157 const [pullRequest] = yield* sql<{ url: string | null; watch: string | null }>`
158 SELECT
159 json_extract(payload_json, '$.pullRequests[0].url') AS url,
160 json_extract(payload_json, '$.pullRequests[0].watch') AS watch
161 FROM orchestration_v2_projection_threads WHERE thread_id = 'stopped-thread'`;
162 const [leftovers] = yield* sql<{
163 auth: number;
164 tasks: number;
165 webhooks: number;
166 transfers: number;
167 links: number;
168 }>`
169 SELECT
170 (SELECT COUNT(*) FROM auth_sessions) AS auth,
171 (SELECT COUNT(*) FROM scheduled_tasks) AS tasks,
172 (SELECT COUNT(*) FROM scheduled_task_webhook_replay_keys) +
173 (SELECT COUNT(*) FROM scheduled_task_webhook_pending) AS webhooks,
174 (SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers,
175 (SELECT COUNT(*) FROM peer_environment_links) AS links`;
176 return { threads, events, sessions, pullRequest, leftovers };
177 }),
178 );
179 assert.deepStrictEqual(
180 kept.threads.map((row) => row.thread_id),
181 ["fork-thread", "settled-thread", "stopped-thread"],
182 );
183 assert.deepStrictEqual(
184 kept.events.map((row) => row.stream_id),
185 ["fork-thread", "settled-thread", "stopped-thread"],
186 );
187 assert.deepStrictEqual(
188 kept.sessions.map((row) => row.provider_session_id),
189 ["session-shared"],
190 );
191 assert.deepStrictEqual(
192 kept.pullRequest,
193 { url: "https://github.com/owner/repo/pull/7", watch: null },
194 "copied pull request links keep their history but stop being watched",
195 );
196 assert.deepStrictEqual(kept.leftovers, {
197 auth: 0,
198 tasks: 0,
199 webhooks: 0,
200 transfers: 0,
201 links: 0,
202 });
203 }),
204 );
205
206 it.effect("never copies an archived thread, and new events append after the source's", () =>
207 Effect.gen(function* () {
208 const fs = yield* FileSystem.FileSystem;
209 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-" });
210 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-dest-" });
211 const source = yield* createFixtureSource(sourceDir);
212 const [sourceSequence] = yield* withDatabase(
213 source,
214 Effect.gen(function* () {
215 const sql = yield* SqlClient.SqlClient;
216 return yield* sql<{ seq: number }>`
217 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
218 }),
219 );
220
221 const result = yield* runMigrateDevDb(
222 { baseDir: destDir, source, projects: 5, threadsPerProject: 100 },
223 { sharedHome: sourceDir },
224 );
225
226 const copied = yield* withDatabase(
227 result.databasePath,
228 Effect.gen(function* () {
229 const sql = yield* SqlClient.SqlClient;
230 const [archivedRows] = yield* sql<{ count: number }>`
231 SELECT
232 (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = 'archived-thread')
233 + (SELECT COUNT(*) FROM orchestration_events WHERE stream_id = 'archived-thread')
234 AS count`;
235 const [sequence] = yield* sql<{ seq: number }>`
236 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
237 return { archivedRows: archivedRows?.count, sequence: sequence?.seq };
238 }),
239 );
240 assert.equal(copied.archivedRows, 0);
241 assert.equal(copied.sequence, sourceSequence?.seq);
242 }),
243 );
244
245 it.effect("skips a thread family larger than the per-project limit", () =>
246 Effect.gen(function* () {
247 const fs = yield* FileSystem.FileSystem;
248 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-" });
249 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-dest-" });
250 const source = yield* createFixtureSource(sourceDir);
251
252 // stopped-thread and its fork are 2 threads; settled-thread is 1.
253 const result = yield* runMigrateDevDb(
254 { baseDir: destDir, source, projects: 5, threadsPerProject: 1 },
255 { sharedHome: sourceDir },
256 );
257 const threads = yield* withDatabase(
258 result.databasePath,
259 Effect.gen(function* () {
260 const sql = yield* SqlClient.SqlClient;
261 return yield* sql<{ thread_id: string }>`
262 SELECT thread_id FROM orchestration_v2_projection_threads`;
263 }),
264 );
265 assert.deepStrictEqual(
266 threads.map((row) => row.thread_id),
267 ["settled-thread"],
268 );
269 }),
270 );
271
272 it.effect("upgrades a source from before the V2 thread tables", () =>
273 Effect.gen(function* () {
274 const fs = yield* FileSystem.FileSystem;
275 const path = yield* Path.Path;
276 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-" });
277 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-dest-" });
278 const stateDir = path.join(sourceDir, "userdata");
279 const source = path.join(stateDir, "statev2.sqlite");
280 yield* fs.makeDirectory(stateDir, { recursive: true });
281 yield* withDatabase(source, runMigrations({ toMigrationInclusive: 54 }));
282
283 const result = yield* runMigrateDevDb(
284 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
285 { sharedHome: sourceDir },
286 );
287 assert.include(result.executedMigrations, "55_OrchestrationV2");
288 }),
289 );
290
291 it.effect("seeds from a source that recorded another migration below V2", () =>
292 Effect.gen(function* () {
293 const fs = yield* FileSystem.FileSystem;
294 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-local-" });
295 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-local-dest-" });
296 const source = yield* createFixtureSource(sourceDir);
297 yield* withDatabase(
298 source,
299 Effect.gen(function* () {
300 const sql = yield* SqlClient.SqlClient;
301 yield* sql`UPDATE effect_sql_migrations SET name = 'SiteLocalMigration'
302 WHERE migration_id = 51`;
303 }),
304 );
305
306 const result = yield* runMigrateDevDb(
307 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
308 { sharedHome: sourceDir },
309 );
310 const threads = yield* withDatabase(
311 result.databasePath,
312 Effect.gen(function* () {
313 const sql = yield* SqlClient.SqlClient;
314 return yield* sql<{ thread_id: string }>`
315 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
316 }),
317 );
318 assert.deepStrictEqual(
319 threads.map((row) => row.thread_id),
320 ["fork-thread", "settled-thread", "stopped-thread"],
321 );
322 }),
323 );
324
325 it.effect("refuses a source whose V2 migration history clashes with this checkout", () =>
326 Effect.gen(function* () {
327 const fs = yield* FileSystem.FileSystem;
328 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-clash-" });
329 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-clash-dest-" });
330 const source = yield* createFixtureSource(sourceDir);
331 yield* withDatabase(
332 source,
333 Effect.gen(function* () {
334 const sql = yield* SqlClient.SqlClient;
335 yield* sql`UPDATE effect_sql_migrations SET name = 'OtherBuildMigration'
336 WHERE migration_id = 60`;
337 }),
338 );
339
340 const destination = yield* createFixtureSource(destDir);
341 const sourceBefore = yield* fs.readFile(source);
342 const destinationBefore = yield* fs.readFile(destination);
343
344 const error = yield* runMigrateDevDb(
345 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
346 { sharedHome: sourceDir },
347 ).pipe(Effect.flip);
348 assert.equal(error._tag, "MigrateDevDbPhaseError");
349 if (error._tag === "MigrateDevDbPhaseError") {
350 assert.equal(error.phase, "migrate");
351 assert.include(String(error.cause), "60_ThreadSnapshotWindowIndexes");
352 }
353 assert.deepStrictEqual(yield* fs.readFile(source), sourceBefore);
354 assert.deepStrictEqual(yield* fs.readFile(destination), destinationBefore);
355 }),
356 );
357
358 it.effect("refuses while a dev server holds the destination", () =>
359 Effect.gen(function* () {
360 const fs = yield* FileSystem.FileSystem;
361 const path = yield* Path.Path;
362 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
363 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
364 const source = yield* createFixtureSource(sourceDir);
365 const stateDir = path.join(destDir, "userdata");
366 yield* fs.makeDirectory(stateDir, { recursive: true });
367 yield* fs.writeFileString(
368 path.join(stateDir, "server-runtime.json"),
369 `{"version":1,"pid":${process.pid}}`,
370 );
371
372 const error = yield* runMigrateDevDb(
373 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
374 { sharedHome: sourceDir },
375 ).pipe(Effect.flip);
376 assert.equal(error._tag, "MigrateDevDbServerRunningError");
377 if (error._tag === "MigrateDevDbServerRunningError") {
378 assert.equal(error.pid, process.pid);
379 }
380 }),
381 );
382
383 it.effect("refuses a source that resolves to a destination path", () =>
384 Effect.gen(function* () {
385 const fs = yield* FileSystem.FileSystem;
386 const path = yield* Path.Path;
387 const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
388 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
389 const leftoverSnapshot = path.join(destDir, "userdata", "statev2.sqlite.migrate-dev-db-tmp");
390 yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
391 yield* fs.writeFileString(leftoverSnapshot, "not a real db");
392
393 const error = yield* runMigrateDevDb(
394 { baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
395 { sharedHome: sharedDir },
396 ).pipe(Effect.flip);
397 assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
398 assert.equal(yield* fs.exists(leftoverSnapshot), true);
399 }),
400 );
401
402 it.effect("refuses to rebuild the shared home", () =>
403 Effect.gen(function* () {
404 const fs = yield* FileSystem.FileSystem;
405 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
406 const source = yield* createFixtureSource(sourceDir);
407
408 const error = yield* runMigrateDevDb(
409 { baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
410 { sharedHome: sourceDir },
411 ).pipe(Effect.flip);
412 assert.equal(error._tag, "MigrateDevDbSharedHomeError");
413 }),
414 );
415});