Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

migrate-dev-db.test.ts

653 lines29.2 KB

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