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