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 threads = [
42 ["stopped-thread", "project-kept", "completed", "{}", "2026-08-01"],
43 ["fork-thread", "project-kept", "completed", forkPayload, "2026-08-02"],
44 ["running-thread", "project-kept", "running", "{}", "2026-08-05"],
45 ["settled-thread", "project-kept", "completed", '{"settledAt":"2026-08-01"}', "2026-08-05"],
46 [
47 "archived-thread",
48 "project-kept",
49 "completed",
50 '{"archivedAt":"2026-08-01"}',
51 "2026-08-05",
52 ],
53 [
54 "limit-thread",
55 "project-kept",
56 "completed",
57 '{"limitRecovery":{"autoResume":true}}',
58 "2026-08-05",
59 ],
60 ["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"],
61 ["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"],
62 ["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"],
63 ] as const;
64 for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) {
65 yield* sql`INSERT INTO orchestration_v2_projection_threads
66 (thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, payload_json)
67 VALUES (${threadId}, ${projectId}, ${threadId}, 'codex', 'full-access', 'default', '2026-08-01', ${updatedAt}, ${payload})`;
68 yield* sql`INSERT INTO orchestration_v2_projection_runs
69 (run_id, thread_id, ordinal, provider, status, requested_at, payload_json)
70 VALUES (${`run-${threadId}`}, ${threadId}, 1, 'codex', ${runStatus}, '2026-08-01', '{}')`;
71 yield* sql`INSERT INTO orchestration_events
72 (event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json)
73 VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`;
74 }
75 yield* sql`INSERT INTO orchestration_v2_projection_provider_sessions
76 (provider_session_id, thread_id, provider, status, updated_at, payload_json)
77 VALUES ('session-shared', 'running-thread', 'codex', 'stopped', '2026-08-01', '{}')`;
78 yield* sql`INSERT INTO orchestration_v2_projection_provider_session_bindings
79 (provider_session_id, thread_id)
80 VALUES ('session-shared', 'running-thread'), ('session-shared', 'stopped-thread')`;
81 yield* sql`INSERT INTO orchestration_v2_projection_context_transfers
82 (context_transfer_id, source_thread_id, target_thread_id, type, status, updated_at, payload_json)
83 VALUES ('transfer-1', 'archived-thread', 'stopped-thread', 'provider_handoff', 'completed', '2026-08-01', '{}')`;
84 yield* sql`INSERT INTO scheduled_tasks
85 (task_id, title, prompt, enabled, schedule_json, project_id, workspace_strategy_json,
86 model_selection_json, runtime_mode, interaction_mode, created_by, creation_source,
87 created_at, updated_at, last_run_status, run_count)
88 VALUES ('task-1', 'Nightly', 'Run it', 1, '{}', 'project-kept', '{}', '{}',
89 'full-access', 'default', 'user', 'user', '2026-08-01', '2026-08-01', 'never', 0)`;
90 yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
91 VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
92 }),
93 );
94 return databasePath;
95});
96
97it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
98 it.effect("keeps stopped and settled thread families and clears pending work", () =>
99 Effect.gen(function* () {
100 const fs = yield* FileSystem.FileSystem;
101 const path = yield* Path.Path;
102 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
103 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
104 const source = yield* createFixtureSource(sourceDir);
105
106 const result = yield* runMigrateDevDb(
107 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
108 { sharedHome: sourceDir },
109 );
110
111 assert.equal(result.databasePath, path.join(destDir, "userdata", "statev2.sqlite"));
112 const kept = yield* withDatabase(
113 result.databasePath,
114 Effect.gen(function* () {
115 const sql = yield* SqlClient.SqlClient;
116 const threads = yield* sql<{ thread_id: string }>`
117 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
118 const events = yield* sql<{ stream_id: string }>`
119 SELECT stream_id FROM orchestration_events ORDER BY stream_id`;
120 const sessions = yield* sql<{ provider_session_id: string }>`
121 SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`;
122 const [leftovers] = yield* sql<{ auth: number; tasks: number; transfers: number }>`
123 SELECT
124 (SELECT COUNT(*) FROM auth_sessions) AS auth,
125 (SELECT COUNT(*) FROM scheduled_tasks) AS tasks,
126 (SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers`;
127 return { threads, events, sessions, leftovers };
128 }),
129 );
130 assert.deepStrictEqual(
131 kept.threads.map((row) => row.thread_id),
132 ["fork-thread", "settled-thread", "stopped-thread"],
133 );
134 assert.deepStrictEqual(
135 kept.events.map((row) => row.stream_id),
136 ["fork-thread", "settled-thread", "stopped-thread"],
137 );
138 assert.deepStrictEqual(
139 kept.sessions.map((row) => row.provider_session_id),
140 ["session-shared"],
141 );
142 assert.deepStrictEqual(kept.leftovers, { auth: 0, tasks: 0, transfers: 0 });
143 }),
144 );
145
146 it.effect("never copies an archived thread, and new events append after the source's", () =>
147 Effect.gen(function* () {
148 const fs = yield* FileSystem.FileSystem;
149 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-" });
150 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-dest-" });
151 const source = yield* createFixtureSource(sourceDir);
152 const [sourceSequence] = yield* withDatabase(
153 source,
154 Effect.gen(function* () {
155 const sql = yield* SqlClient.SqlClient;
156 return yield* sql<{ seq: number }>`
157 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
158 }),
159 );
160
161 const result = yield* runMigrateDevDb(
162 { baseDir: destDir, source, projects: 5, threadsPerProject: 100 },
163 { sharedHome: sourceDir },
164 );
165
166 const copied = yield* withDatabase(
167 result.databasePath,
168 Effect.gen(function* () {
169 const sql = yield* SqlClient.SqlClient;
170 const [archivedRows] = yield* sql<{ count: number }>`
171 SELECT
172 (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = 'archived-thread')
173 + (SELECT COUNT(*) FROM orchestration_events WHERE stream_id = 'archived-thread')
174 AS count`;
175 const [sequence] = yield* sql<{ seq: number }>`
176 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
177 return { archivedRows: archivedRows?.count, sequence: sequence?.seq };
178 }),
179 );
180 assert.equal(copied.archivedRows, 0);
181 assert.equal(copied.sequence, sourceSequence?.seq);
182 }),
183 );
184
185 it.effect("skips a thread family larger than the per-project limit", () =>
186 Effect.gen(function* () {
187 const fs = yield* FileSystem.FileSystem;
188 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-" });
189 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-dest-" });
190 const source = yield* createFixtureSource(sourceDir);
191
192 // stopped-thread and its fork are 2 threads; settled-thread is 1.
193 const result = yield* runMigrateDevDb(
194 { baseDir: destDir, source, projects: 5, threadsPerProject: 1 },
195 { sharedHome: sourceDir },
196 );
197 const threads = yield* withDatabase(
198 result.databasePath,
199 Effect.gen(function* () {
200 const sql = yield* SqlClient.SqlClient;
201 return yield* sql<{ thread_id: string }>`
202 SELECT thread_id FROM orchestration_v2_projection_threads`;
203 }),
204 );
205 assert.deepStrictEqual(
206 threads.map((row) => row.thread_id),
207 ["settled-thread"],
208 );
209 }),
210 );
211
212 it.effect("upgrades a source from before the V2 thread tables", () =>
213 Effect.gen(function* () {
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-" });
217 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-dest-" });
218 const stateDir = path.join(sourceDir, "userdata");
219 const source = path.join(stateDir, "statev2.sqlite");
220 yield* fs.makeDirectory(stateDir, { recursive: true });
221 yield* withDatabase(source, runMigrations({ toMigrationInclusive: 54 }));
222
223 const result = yield* runMigrateDevDb(
224 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
225 { sharedHome: sourceDir },
226 );
227 assert.include(result.executedMigrations, "55_OrchestrationV2");
228 }),
229 );
230
231 it.effect("refuses while a dev server holds the destination", () =>
232 Effect.gen(function* () {
233 const fs = yield* FileSystem.FileSystem;
234 const path = yield* Path.Path;
235 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
236 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
237 const source = yield* createFixtureSource(sourceDir);
238 const stateDir = path.join(destDir, "userdata");
239 yield* fs.makeDirectory(stateDir, { recursive: true });
240 yield* fs.writeFileString(
241 path.join(stateDir, "server-runtime.json"),
242 `{"version":1,"pid":${process.pid}}`,
243 );
244
245 const error = yield* runMigrateDevDb(
246 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
247 { sharedHome: sourceDir },
248 ).pipe(Effect.flip);
249 assert.equal(error._tag, "MigrateDevDbServerRunningError");
250 if (error._tag === "MigrateDevDbServerRunningError") {
251 assert.equal(error.pid, process.pid);
252 }
253 }),
254 );
255
256 it.effect("refuses a source that resolves to a destination path", () =>
257 Effect.gen(function* () {
258 const fs = yield* FileSystem.FileSystem;
259 const path = yield* Path.Path;
260 const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
261 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
262 const leftoverSnapshot = path.join(destDir, "userdata", "statev2.sqlite.migrate-dev-db-tmp");
263 yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
264 yield* fs.writeFileString(leftoverSnapshot, "not a real db");
265
266 const error = yield* runMigrateDevDb(
267 { baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
268 { sharedHome: sharedDir },
269 ).pipe(Effect.flip);
270 assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
271 assert.equal(yield* fs.exists(leftoverSnapshot), true);
272 }),
273 );
274
275 it.effect("refuses to rebuild the shared home", () =>
276 Effect.gen(function* () {
277 const fs = yield* FileSystem.FileSystem;
278 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
279 const source = yield* createFixtureSource(sourceDir);
280
281 const error = yield* runMigrateDevDb(
282 { baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
283 { sharedHome: sourceDir },
284 ).pipe(Effect.flip);
285 assert.equal(error._tag, "MigrateDevDbSharedHomeError");
286 }),
287 );
288});