Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NodeSqlite from "node:sqlite";
4import { assert, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as SqlClient from "effect/sql/SqlClient";
10
11import { runMigrations } from "../src/persistence/Migrations.ts";
12import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
13import { dropResumableFamilies, runMigrateDevDb } from "./migrate-dev-db.ts";
14
15const withDatabase = <A, E, R>(
16 databasePath: string,
17 effect: Effect.Effect<A, E, R | SqlClient.SqlClient>,
18) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
19
20const insertPeerLink = (sql: SqlClient.SqlClient) => sql`INSERT INTO peer_environment_links
21 (environment_id, secret_name, label, urls_json, access, linked_at, expires_at)
22 VALUES ('environment-box', 'peer-link-box', 'Box', '["https://box.example"]', 'auto',
23 '2026-08-01', '2027-08-01')`;
24
25const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* (
26 baseDir: string,
27 toMigrationInclusive?: number,
28) {
29 const fs = yield* FileSystem.FileSystem;
30 const path = yield* Path.Path;
31 const stateDir = path.join(baseDir, "userdata");
32 const databasePath = path.join(stateDir, "statev2.sqlite");
33 yield* fs.makeDirectory(stateDir, { recursive: true });
34 yield* withDatabase(
35 databasePath,
36 Effect.gen(function* () {
37 const sql = yield* SqlClient.SqlClient;
38 yield* runMigrations({ toMigrationInclusive });
39
40 const scripts = JSON.stringify([
41 { id: "lint", name: "Lint", command: "vp lint", icon: "lint", runOnWorktreeCreate: false },
42 {
43 id: "teardown",
44 name: "Teardown",
45 command: "./teardown",
46 icon: "configure",
47 runOnWorktreeCreate: false,
48 runOnSettle: true,
49 },
50 ]);
51 yield* sql`INSERT INTO projection_projects
52 (project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at)
53 VALUES
54 ('project-kept', 'Kept', '/tmp/kept', ${scripts}, '2026-08-01', '2026-08-01', NULL),
55 ('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`;
56
57 const forkPayload =
58 '{"lineage":{"parentThreadId":"stopped-thread","relationshipToParent":"fork","rootThreadId":"stopped-thread"}}';
59 const subagentPayload =
60 '{"lineage":{"parentThreadId":"subagent-parent","relationshipToParent":"subagent","rootThreadId":"subagent-parent"},"forkedFrom":{"type":"node","nodeId":"node-1"}}';
61 const watchedPayload = JSON.stringify({
62 pullRequests: [
63 {
64 host: "github.com",
65 repository: "owner/repo",
66 number: 7,
67 url: "https://github.com/owner/repo/pull/7",
68 source: "agent",
69 linkedAt: "2026-08-01T00:00:00.000Z",
70 snapshot: null,
71 stack: null,
72 watch: {
73 startedAt: "2026-08-01T00:00:00.000Z",
74 headSha: null,
75 failedChecks: [],
76 passed: false,
77 passedChecks: [],
78 remarksThrough: "2026-08-01T00:00:00.000Z",
79 remarkIds: [],
80 conflicting: false,
81 wakes: 0,
82 },
83 },
84 ],
85 });
86 const threads = [
87 ["stopped-thread", "project-kept", "completed", watchedPayload, "2026-08-01"],
88 ["fork-thread", "project-kept", "completed", forkPayload, "2026-08-02"],
89 ["running-thread", "project-kept", "running", "{}", "2026-08-05"],
90 ["settled-thread", "project-kept", "completed", '{"settledAt":"2026-08-01"}', "2026-08-05"],
91 [
92 "archived-thread",
93 "project-kept",
94 "completed",
95 '{"archivedAt":"2026-08-01"}',
96 "2026-08-05",
97 ],
98 [
99 "limit-thread",
100 "project-kept",
101 "completed",
102 '{"limitRecovery":{"autoResume":true}}',
103 "2026-08-05",
104 ],
105 ["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"],
106 ["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"],
107 ["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"],
108 // Finished, but startup recovery would deliver its unread steer and start a turn.
109 ["steer-thread", "project-kept", "completed", "{}", "2026-08-09"],
110 ] as const;
111 for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) {
112 yield* sql`INSERT INTO orchestration_v2_projection_threads
113 (thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, payload_json)
114 VALUES (${threadId}, ${projectId}, ${threadId}, 'codex', 'full-access', 'default', '2026-08-01', ${updatedAt}, ${payload})`;
115 yield* sql`INSERT INTO orchestration_v2_projection_runs
116 (run_id, thread_id, ordinal, provider, status, requested_at, payload_json)
117 VALUES (${`run-${threadId}`}, ${threadId}, 1, 'codex', ${runStatus}, '2026-08-01', '{}')`;
118 yield* sql`INSERT INTO orchestration_events
119 (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version)
120 VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}', 2)`;
121 }
122 yield* sql`INSERT INTO orchestration_v2_projection_turn_items
123 (turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json)
124 VALUES ('steer-item', 'steer-thread', 'run-steer-thread', 2, 'user_message', 'pending',
125 '2026-08-09', '{"inputIntent":"steer"}')`;
126 // A V1 thread the server already imported must not trip the legacy guard.
127 yield* sql`INSERT INTO projection_threads
128 (thread_id, project_id, title, model_selection_json, runtime_mode, created_at, updated_at)
129 VALUES ('stopped-thread', 'project-kept', 'stopped-thread',
130 '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', '2026-08-01', '2026-08-01')`;
131 yield* sql`INSERT INTO orchestration_v2_projection_provider_sessions
132 (provider_session_id, thread_id, provider, status, updated_at, payload_json)
133 VALUES ('session-shared', 'running-thread', 'codex', 'stopped', '2026-08-01', '{}')`;
134 yield* sql`INSERT INTO orchestration_v2_projection_provider_session_bindings
135 (provider_session_id, thread_id)
136 VALUES ('session-shared', 'running-thread'), ('session-shared', 'stopped-thread')`;
137 yield* sql`INSERT INTO orchestration_v2_projection_context_transfers
138 (context_transfer_id, source_thread_id, target_thread_id, type, status, updated_at, payload_json)
139 VALUES ('transfer-1', 'archived-thread', 'stopped-thread', 'provider_handoff', 'completed', '2026-08-01', '{}')`;
140 yield* sql`INSERT INTO scheduled_tasks
141 (task_id, title, prompt, enabled, schedule_json, project_id, workspace_strategy_json,
142 model_selection_json, runtime_mode, interaction_mode, created_by, creation_source,
143 created_at, updated_at, last_run_status, run_count)
144 VALUES ('task-1', 'Nightly', 'Run it', 1, '{}', 'project-kept', '{}', '{}',
145 'full-access', 'default', 'user', 'user', '2026-08-01', '2026-08-01', 'never', 0)`;
146 yield* sql`INSERT INTO scheduled_task_webhook_replay_keys
147 (task_id, replay_key, delivery_id, expires_at)
148 VALUES ('task-1', 'replay-1', 'delivery-1', 1900000000000)`;
149 yield* sql`INSERT INTO scheduled_task_webhook_pending
150 (delivery_id, task_id, coalesce_key, due_at, task_json, request_json, delivery_ids_json)
151 VALUES ('delivery-1', 'task-1', 'key-1', 1900000000000, '{}', '{}', '[]')`;
152 yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
153 VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
154 if (toMigrationInclusive === undefined) yield* insertPeerLink(sql);
155 }),
156 );
157 return databasePath;
158});
159
160it.layer(Layer.merge(NodeServices.layer, NodeCrypto.layerDigest))("migrate-dev-db", (it) => {
161 it.effect("keeps stopped and settled thread families and clears pending work", () =>
162 Effect.gen(function* () {
163 const fs = yield* FileSystem.FileSystem;
164 const path = yield* Path.Path;
165 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
166 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
167 const source = yield* createFixtureSource(sourceDir);
168
169 const result = yield* runMigrateDevDb(
170 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
171 { sharedHome: sourceDir },
172 );
173
174 assert.equal(result.databasePath, path.join(destDir, "userdata", "statev2.sqlite"));
175 const kept = yield* withDatabase(
176 result.databasePath,
177 Effect.gen(function* () {
178 const sql = yield* SqlClient.SqlClient;
179 const threads = yield* sql<{ thread_id: string }>`
180 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
181 const events = yield* sql<{ stream_id: string }>`
182 SELECT stream_id FROM orchestration_events ORDER BY stream_id`;
183 const sessions = yield* sql<{ provider_session_id: string }>`
184 SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`;
185 const [pullRequest] = yield* sql<{ url: string | null; watch: string | null }>`
186 SELECT
187 json_extract(payload_json, '$.pullRequests[0].url') AS url,
188 json_extract(payload_json, '$.pullRequests[0].watch') AS watch
189 FROM orchestration_v2_projection_threads WHERE thread_id = 'stopped-thread'`;
190 const [project] = yield* sql<{ scripts_json: string }>`
191 SELECT scripts_json FROM projection_projects WHERE project_id = 'project-kept'`;
192 const [leftovers] = yield* sql<{
193 auth: number;
194 tasks: number;
195 webhooks: number;
196 transfers: number;
197 links: number;
198 }>`
199 SELECT
200 (SELECT COUNT(*) FROM auth_sessions) AS auth,
201 (SELECT COUNT(*) FROM scheduled_tasks) AS tasks,
202 (SELECT COUNT(*) FROM scheduled_task_webhook_replay_keys) +
203 (SELECT COUNT(*) FROM scheduled_task_webhook_pending) AS webhooks,
204 (SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers,
205 (SELECT COUNT(*) FROM peer_environment_links) AS links`;
206 return { threads, events, sessions, pullRequest, project, leftovers };
207 }),
208 );
209 assert.deepStrictEqual(
210 kept.threads.map((row) => row.thread_id),
211 ["fork-thread", "settled-thread", "stopped-thread"],
212 );
213 assert.deepStrictEqual(
214 kept.events.map((row) => row.stream_id),
215 ["fork-thread", "settled-thread", "stopped-thread"],
216 );
217 assert.deepStrictEqual(
218 kept.sessions.map((row) => row.provider_session_id),
219 ["session-shared"],
220 );
221 assert.deepStrictEqual(
222 kept.pullRequest,
223 { url: "https://github.com/owner/repo/pull/7", watch: null },
224 "copied pull request links keep their history but stop being watched",
225 );
226 assert.deepStrictEqual(
227 JSON.parse(kept.project?.scripts_json ?? "[]"),
228 [
229 {
230 id: "lint",
231 name: "Lint",
232 command: "vp lint",
233 icon: "lint",
234 runOnWorktreeCreate: false,
235 },
236 {
237 id: "teardown",
238 name: "Teardown",
239 command: "./teardown",
240 icon: "configure",
241 runOnWorktreeCreate: false,
242 },
243 ],
244 "copied project scripts stay listed but never run on settle in the original checkout",
245 );
246 assert.deepStrictEqual(kept.leftovers, {
247 auth: 0,
248 tasks: 0,
249 webhooks: 0,
250 transfers: 0,
251 links: 0,
252 });
253 }),
254 );
255
256 it.effect("drops resumable families from a seed in place, the pending steer included", () =>
257 Effect.gen(function* () {
258 const fs = yield* FileSystem.FileSystem;
259 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-resumable-" });
260 const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-home-" });
261 const database = yield* createFixtureSource(dir);
262
263 assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 4);
264 const { threads, sessions } = yield* withDatabase(
265 database,
266 Effect.gen(function* () {
267 const sql = yield* SqlClient.SqlClient;
268 return {
269 threads: yield* sql<{ thread_id: string }>`
270 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`,
271 sessions: yield* sql<{ provider_session_id: string }>`
272 SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`,
273 };
274 }),
275 );
276 assert.deepStrictEqual(
277 threads.map((row) => row.thread_id),
278 [
279 "archived-thread",
280 "deleted-project-thread",
281 "fork-thread",
282 "settled-thread",
283 "stopped-thread",
284 ],
285 );
286 assert.deepStrictEqual(
287 sessions.map((row) => row.provider_session_id),
288 ["session-shared"],
289 "a session the kept stopped-thread still binds stays with it",
290 );
291 assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 0);
292 }),
293 );
294
295 it.effect("refuses to drop from the shared database through a symlink or a hard link", () =>
296 Effect.gen(function* () {
297 const fs = yield* FileSystem.FileSystem;
298 const path = yield* Path.Path;
299 const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
300 const elsewhere = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-link-" });
301 const fixture = yield* createFixtureSource(sharedHome);
302 const live = path.join(sharedHome, "userdata", "statev2.sqlite");
303 yield* fs.makeDirectory(path.dirname(live), { recursive: true });
304 yield* fs.rename(fixture, live);
305 const symlink = path.join(elsewhere, "statev2.sqlite");
306 yield* fs.symlink(live, symlink);
307 // A hard link has its own path; only the file's identity gives it away.
308 const hardLink = path.join(elsewhere, "copy.sqlite");
309 yield* fs.link(live, hardLink);
310
311 for (const link of [symlink, hardLink]) {
312 const refused = yield* Effect.flip(dropResumableFamilies(link, { sharedHome }));
313 assert.equal(refused._tag, "MigrateDevDbSharedHomeError", link);
314 }
315 const threads = yield* withDatabase(
316 live,
317 Effect.gen(function* () {
318 const sql = yield* SqlClient.SqlClient;
319 const [row] = yield* sql<{ n: number }>`
320 SELECT COUNT(*) AS n FROM orchestration_v2_projection_threads`;
321 return Number(row?.n ?? 0);
322 }),
323 );
324 assert.equal(threads, 10, "the shared database is untouched");
325 }),
326 );
327
328 it.effect("never copies an archived thread, and new events append after the source's", () =>
329 Effect.gen(function* () {
330 const fs = yield* FileSystem.FileSystem;
331 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-" });
332 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-dest-" });
333 const source = yield* createFixtureSource(sourceDir);
334 const [sourceSequence] = yield* withDatabase(
335 source,
336 Effect.gen(function* () {
337 const sql = yield* SqlClient.SqlClient;
338 return yield* sql<{ seq: number }>`
339 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
340 }),
341 );
342
343 const result = yield* runMigrateDevDb(
344 { baseDir: destDir, source, projects: 5, threadsPerProject: 100 },
345 { sharedHome: sourceDir },
346 );
347
348 const copied = yield* withDatabase(
349 result.databasePath,
350 Effect.gen(function* () {
351 const sql = yield* SqlClient.SqlClient;
352 const [archivedRows] = yield* sql<{ count: number }>`
353 SELECT
354 (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = 'archived-thread')
355 + (SELECT COUNT(*) FROM orchestration_events WHERE stream_id = 'archived-thread')
356 AS count`;
357 const [sequence] = yield* sql<{ seq: number }>`
358 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
359 return { archivedRows: archivedRows?.count, sequence: sequence?.seq };
360 }),
361 );
362 assert.equal(copied.archivedRows, 0);
363 assert.equal(copied.sequence, sourceSequence?.seq);
364 }),
365 );
366
367 it.effect("skips a thread family larger than the per-project limit", () =>
368 Effect.gen(function* () {
369 const fs = yield* FileSystem.FileSystem;
370 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-" });
371 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-dest-" });
372 const source = yield* createFixtureSource(sourceDir);
373
374 // stopped-thread and its fork are 2 threads; settled-thread is 1.
375 const result = yield* runMigrateDevDb(
376 { baseDir: destDir, source, projects: 5, threadsPerProject: 1 },
377 { sharedHome: sourceDir },
378 );
379 const threads = yield* withDatabase(
380 result.databasePath,
381 Effect.gen(function* () {
382 const sql = yield* SqlClient.SqlClient;
383 return yield* sql<{ thread_id: string }>`
384 SELECT thread_id FROM orchestration_v2_projection_threads`;
385 }),
386 );
387 assert.deepStrictEqual(
388 threads.map((row) => row.thread_id),
389 ["settled-thread"],
390 );
391 }),
392 );
393
394 it.effect("upgrades a source from before the V2 thread tables", () =>
395 Effect.gen(function* () {
396 const fs = yield* FileSystem.FileSystem;
397 const path = yield* Path.Path;
398 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-" });
399 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-dest-" });
400 const stateDir = path.join(sourceDir, "userdata");
401 const source = path.join(stateDir, "statev2.sqlite");
402 yield* fs.makeDirectory(stateDir, { recursive: true });
403 yield* withDatabase(source, runMigrations({ toMigrationInclusive: 54 }));
404
405 const result = yield* runMigrateDevDb(
406 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
407 { sharedHome: sourceDir },
408 );
409 assert.include(result.executedMigrations, "55_OrchestrationV2");
410 }),
411 );
412
413 // The server imports V1 threads at boot, not in a migration, so a source can
414 // reach the V2 schema with its legacy threads still unimported.
415 it.effect.each([
416 { name: "a pre-V2 source", migrateToLatest: false },
417 { name: "a V2 source whose legacy threads were never imported", migrateToLatest: true },
418 ])("refuses $name", ({ migrateToLatest }) =>
419 Effect.gen(function* () {
420 const fs = yield* FileSystem.FileSystem;
421 const path = yield* Path.Path;
422 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-data-" });
423 const destDir = yield* fs.makeTempDirectoryScoped({
424 prefix: "migrate-dev-db-v1-data-dest-",
425 });
426 const stateDir = path.join(sourceDir, "userdata");
427 const source = path.join(stateDir, "statev2.sqlite");
428 yield* fs.makeDirectory(stateDir, { recursive: true });
429 yield* withDatabase(
430 source,
431 Effect.gen(function* () {
432 const sql = yield* SqlClient.SqlClient;
433 yield* runMigrations({ toMigrationInclusive: 54 });
434 yield* sql`INSERT INTO projection_projects
435 (project_id, title, workspace_root, scripts_json, created_at, updated_at)
436 VALUES ('project-legacy', 'Legacy', '/tmp/legacy', '[]', '2026-08-01', '2026-08-01')`;
437 yield* sql`INSERT INTO projection_threads
438 (thread_id, project_id, title, model_selection_json, runtime_mode, created_at, updated_at)
439 VALUES ('thread-legacy', 'project-legacy', 'Legacy thread',
440 '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', '2026-08-01', '2026-08-01')`;
441 if (migrateToLatest) yield* runMigrations();
442 }),
443 );
444
445 // A live destination connection keeps uncheckpointed rows in the WAL;
446 // the rejected run must leave those bytes alone.
447 const destination = yield* createFixtureSource(destDir);
448 yield* withDatabase(
449 destination,
450 Effect.gen(function* () {
451 const sql = yield* SqlClient.SqlClient;
452 yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
453 yield* sql`UPDATE projection_projects SET title = 'Edited' WHERE project_id = 'project-kept'`;
454 const walBefore = yield* fs.readFile(`${destination}-wal`);
455 assert.isAbove(walBefore.length, 0);
456
457 const error = yield* runMigrateDevDb(
458 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
459 { sharedHome: sourceDir },
460 ).pipe(Effect.flip);
461 assert.equal(error._tag, "MigrateDevDbLegacySourceError");
462 assert.deepStrictEqual(yield* fs.readFile(`${destination}-wal`), walBefore);
463 }),
464 );
465 }),
466 );
467
468 it.effect("seeds from a source that recorded another migration below V2", () =>
469 Effect.gen(function* () {
470 const fs = yield* FileSystem.FileSystem;
471 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-local-" });
472 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-local-dest-" });
473 const source = yield* createFixtureSource(sourceDir);
474 yield* withDatabase(
475 source,
476 Effect.gen(function* () {
477 const sql = yield* SqlClient.SqlClient;
478 yield* sql`UPDATE effect_sql_migrations SET name = 'SiteLocalMigration'
479 WHERE migration_id = 51`;
480 }),
481 );
482
483 const result = yield* runMigrateDevDb(
484 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
485 { sharedHome: sourceDir },
486 );
487 const threads = yield* withDatabase(
488 result.databasePath,
489 Effect.gen(function* () {
490 const sql = yield* SqlClient.SqlClient;
491 return yield* sql<{ thread_id: string }>`
492 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
493 }),
494 );
495 assert.deepStrictEqual(
496 threads.map((row) => row.thread_id),
497 ["fork-thread", "settled-thread", "stopped-thread"],
498 );
499 }),
500 );
501
502 it.effect("refuses a source whose V2 migration history clashes with this checkout", () =>
503 Effect.gen(function* () {
504 const fs = yield* FileSystem.FileSystem;
505 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-clash-" });
506 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-clash-dest-" });
507 const source = yield* createFixtureSource(sourceDir);
508 yield* withDatabase(
509 source,
510 Effect.gen(function* () {
511 const sql = yield* SqlClient.SqlClient;
512 yield* sql`UPDATE effect_sql_migrations SET name = 'OtherBuildMigration'
513 WHERE migration_id = 60`;
514 }),
515 );
516
517 const destination = yield* createFixtureSource(destDir);
518 const sourceBefore = yield* fs.readFile(source);
519 const destinationBefore = yield* fs.readFile(destination);
520
521 const error = yield* runMigrateDevDb(
522 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
523 { sharedHome: sourceDir },
524 ).pipe(Effect.flip);
525 assert.equal(error._tag, "MigrateDevDbPhaseError");
526 if (error._tag === "MigrateDevDbPhaseError") {
527 assert.equal(error.phase, "migrate");
528 assert.include(String(error.cause), "60_ThreadSnapshotWindowIndexes");
529 }
530 assert.deepStrictEqual(yield* fs.readFile(source), sourceBefore);
531 assert.deepStrictEqual(yield* fs.readFile(destination), destinationBefore);
532 }),
533 );
534
535 it.effect("imports a dev seed whose ids after 67 came from the peer links branch", () =>
536 Effect.gen(function* () {
537 const fs = yield* FileSystem.FileSystem;
538 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-peer-" });
539 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-peer-dest-" });
540 const source = yield* createFixtureSource(sourceDir, 67);
541 // Mirrors a real ~/.t3 seed written by a build whose 68-70 differ from main's.
542 yield* withDatabase(
543 source,
544 Effect.gen(function* () {
545 const sql = yield* SqlClient.SqlClient;
546 yield* sql`CREATE TABLE peer_environment_links (
547 environment_id TEXT PRIMARY KEY,
548 secret_name TEXT NOT NULL,
549 label TEXT NOT NULL,
550 urls_json TEXT NOT NULL,
551 access TEXT NOT NULL,
552 linked_at TEXT NOT NULL,
553 expires_at TEXT NOT NULL,
554 last_reached_at TEXT,
555 last_error TEXT,
556 fenced INTEGER NOT NULL DEFAULT 0)`;
557 yield* sql`CREATE INDEX orchestration_v2_projection_turn_items_waiting_link_idx
558 ON orchestration_v2_projection_turn_items(thread_id, updated_at DESC, turn_item_id DESC)
559 WHERE type = 'link_request' AND status = 'waiting'`;
560 yield* insertPeerLink(sql);
561 yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES
562 (68, 'PeerLinks'), (69, 'PeerLinkFence'), (70, 'WaitingLinkRequestIndex')`;
563 }),
564 );
565
566 const result = yield* runMigrateDevDb(
567 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
568 { sharedHome: sourceDir },
569 );
570
571 const imported = yield* withDatabase(
572 result.databasePath,
573 Effect.gen(function* () {
574 const sql = yield* SqlClient.SqlClient;
575 const threads = yield* sql<{ thread_id: string }>`
576 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
577 const schema = yield* sql<{ name: string }>`
578 SELECT name FROM sqlite_master WHERE name IN (
579 'orchestration_v2_projection_turn_items_stop_request_idx',
580 'orchestration_v2_message_search')
581 ORDER BY name`;
582 return { threads, schema };
583 }),
584 );
585 assert.deepStrictEqual(
586 imported.threads.map((row) => row.thread_id),
587 ["fork-thread", "settled-thread", "stopped-thread"],
588 );
589 assert.deepStrictEqual(
590 imported.schema.map((row) => row.name),
591 [
592 "orchestration_v2_message_search",
593 "orchestration_v2_projection_turn_items_stop_request_idx",
594 ],
595 );
596 }),
597 );
598
599 it.effect("refuses while a dev server holds the destination", () =>
600 Effect.gen(function* () {
601 const fs = yield* FileSystem.FileSystem;
602 const path = yield* Path.Path;
603 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
604 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
605 const source = yield* createFixtureSource(sourceDir);
606 const stateDir = path.join(destDir, "userdata");
607 yield* fs.makeDirectory(stateDir, { recursive: true });
608 yield* fs.writeFileString(
609 path.join(stateDir, "server-runtime.json"),
610 `{"version":1,"pid":${process.pid}}`,
611 );
612
613 const error = yield* runMigrateDevDb(
614 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
615 { sharedHome: sourceDir },
616 ).pipe(Effect.flip);
617 assert.equal(error._tag, "MigrateDevDbServerRunningError");
618 if (error._tag === "MigrateDevDbServerRunningError") {
619 assert.equal(error.pid, process.pid);
620 }
621 }),
622 );
623
624 it.effect("refuses while another seed holds the destination lock", () =>
625 Effect.gen(function* () {
626 const fs = yield* FileSystem.FileSystem;
627 const path = yield* Path.Path;
628 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-seed-" });
629 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-seed-dest-" });
630 const source = yield* createFixtureSource(sourceDir);
631 const stateDir = path.join(destDir, "userdata");
632 const inFlightSnapshot = path.join(stateDir, "statev2.sqlite.migrate-dev-db-tmp");
633 yield* fs.makeDirectory(stateDir, { recursive: true });
634 yield* fs.writeFileString(inFlightSnapshot, "first seed's snapshot");
635 const otherSeed = yield* Effect.acquireRelease(
636 Effect.sync(
637 () => new NodeSqlite.DatabaseSync(path.join(stateDir, "migrate-dev-db-lock.sqlite")),
638 ),
639 (db) => Effect.sync(() => db.close()),
640 );
641 otherSeed.exec("BEGIN IMMEDIATE");
642
643 const error = yield* runMigrateDevDb(
644 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
645 { sharedHome: sourceDir },
646 ).pipe(Effect.flip);
647 assert.equal(error._tag, "MigrateDevDbDestinationBusyError");
648 if (error._tag === "MigrateDevDbDestinationBusyError") {
649 assert.equal(error.reason, "seed-running");
650 }
651 assert.equal(yield* fs.readFileString(inFlightSnapshot), "first seed's snapshot");
652 }),
653 );
654
655 it.effect("refuses a source that resolves to a destination path", () =>
656 Effect.gen(function* () {
657 const fs = yield* FileSystem.FileSystem;
658 const path = yield* Path.Path;
659 const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
660 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
661 const leftoverSnapshot = path.join(destDir, "userdata", "statev2.sqlite.migrate-dev-db-tmp");
662 yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
663 yield* fs.writeFileString(leftoverSnapshot, "not a real db");
664
665 const error = yield* runMigrateDevDb(
666 { baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
667 { sharedHome: sharedDir },
668 ).pipe(Effect.flip);
669 assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
670 assert.equal(yield* fs.exists(leftoverSnapshot), true);
671 }),
672 );
673
674 it.effect("refuses to rebuild the shared home", () =>
675 Effect.gen(function* () {
676 const fs = yield* FileSystem.FileSystem;
677 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
678 const source = yield* createFixtureSource(sourceDir);
679
680 const error = yield* runMigrateDevDb(
681 { baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
682 { sharedHome: sourceDir },
683 ).pipe(Effect.flip);
684 assert.equal(error._tag, "MigrateDevDbSharedHomeError");
685 }),
686 );
687});