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 scheduled_task_webhook_replay_keys
91 (task_id, replay_key, delivery_id, expires_at)
92 VALUES ('task-1', 'replay-1', 'delivery-1', 1900000000000)`;
93 yield* sql`INSERT INTO scheduled_task_webhook_pending
94 (delivery_id, task_id, coalesce_key, due_at, task_json, request_json, delivery_ids_json)
95 VALUES ('delivery-1', 'task-1', 'key-1', 1900000000000, '{}', '{}', '[]')`;
96 yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
97 VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
98 }),
99 );
100 return databasePath;
101});
102
103it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
104 it.effect("keeps stopped and settled thread families and clears pending work", () =>
105 Effect.gen(function* () {
106 const fs = yield* FileSystem.FileSystem;
107 const path = yield* Path.Path;
108 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
109 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
110 const source = yield* createFixtureSource(sourceDir);
111
112 const result = yield* runMigrateDevDb(
113 { baseDir: destDir, source, projects: 5, threadsPerProject: 2 },
114 { sharedHome: sourceDir },
115 );
116
117 assert.equal(result.databasePath, path.join(destDir, "userdata", "statev2.sqlite"));
118 const kept = yield* withDatabase(
119 result.databasePath,
120 Effect.gen(function* () {
121 const sql = yield* SqlClient.SqlClient;
122 const threads = yield* sql<{ thread_id: string }>`
123 SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`;
124 const events = yield* sql<{ stream_id: string }>`
125 SELECT stream_id FROM orchestration_events ORDER BY stream_id`;
126 const sessions = yield* sql<{ provider_session_id: string }>`
127 SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`;
128 const [leftovers] = yield* sql<{
129 auth: number;
130 tasks: number;
131 webhooks: number;
132 transfers: number;
133 }>`
134 SELECT
135 (SELECT COUNT(*) FROM auth_sessions) AS auth,
136 (SELECT COUNT(*) FROM scheduled_tasks) AS tasks,
137 (SELECT COUNT(*) FROM scheduled_task_webhook_replay_keys) +
138 (SELECT COUNT(*) FROM scheduled_task_webhook_pending) AS webhooks,
139 (SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers`;
140 return { threads, events, sessions, leftovers };
141 }),
142 );
143 assert.deepStrictEqual(
144 kept.threads.map((row) => row.thread_id),
145 ["fork-thread", "settled-thread", "stopped-thread"],
146 );
147 assert.deepStrictEqual(
148 kept.events.map((row) => row.stream_id),
149 ["fork-thread", "settled-thread", "stopped-thread"],
150 );
151 assert.deepStrictEqual(
152 kept.sessions.map((row) => row.provider_session_id),
153 ["session-shared"],
154 );
155 assert.deepStrictEqual(kept.leftovers, { auth: 0, tasks: 0, webhooks: 0, transfers: 0 });
156 }),
157 );
158
159 it.effect("never copies an archived thread, and new events append after the source's", () =>
160 Effect.gen(function* () {
161 const fs = yield* FileSystem.FileSystem;
162 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-" });
163 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slice-dest-" });
164 const source = yield* createFixtureSource(sourceDir);
165 const [sourceSequence] = yield* withDatabase(
166 source,
167 Effect.gen(function* () {
168 const sql = yield* SqlClient.SqlClient;
169 return yield* sql<{ seq: number }>`
170 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
171 }),
172 );
173
174 const result = yield* runMigrateDevDb(
175 { baseDir: destDir, source, projects: 5, threadsPerProject: 100 },
176 { sharedHome: sourceDir },
177 );
178
179 const copied = yield* withDatabase(
180 result.databasePath,
181 Effect.gen(function* () {
182 const sql = yield* SqlClient.SqlClient;
183 const [archivedRows] = yield* sql<{ count: number }>`
184 SELECT
185 (SELECT COUNT(*) FROM orchestration_v2_projection_runs WHERE thread_id = 'archived-thread')
186 + (SELECT COUNT(*) FROM orchestration_events WHERE stream_id = 'archived-thread')
187 AS count`;
188 const [sequence] = yield* sql<{ seq: number }>`
189 SELECT seq FROM sqlite_sequence WHERE name = 'orchestration_events'`;
190 return { archivedRows: archivedRows?.count, sequence: sequence?.seq };
191 }),
192 );
193 assert.equal(copied.archivedRows, 0);
194 assert.equal(copied.sequence, sourceSequence?.seq);
195 }),
196 );
197
198 it.effect("skips a thread family larger than the per-project limit", () =>
199 Effect.gen(function* () {
200 const fs = yield* FileSystem.FileSystem;
201 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-" });
202 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-family-dest-" });
203 const source = yield* createFixtureSource(sourceDir);
204
205 // stopped-thread and its fork are 2 threads; settled-thread is 1.
206 const result = yield* runMigrateDevDb(
207 { baseDir: destDir, source, projects: 5, threadsPerProject: 1 },
208 { sharedHome: sourceDir },
209 );
210 const threads = yield* withDatabase(
211 result.databasePath,
212 Effect.gen(function* () {
213 const sql = yield* SqlClient.SqlClient;
214 return yield* sql<{ thread_id: string }>`
215 SELECT thread_id FROM orchestration_v2_projection_threads`;
216 }),
217 );
218 assert.deepStrictEqual(
219 threads.map((row) => row.thread_id),
220 ["settled-thread"],
221 );
222 }),
223 );
224
225 it.effect("upgrades a source from before the V2 thread tables", () =>
226 Effect.gen(function* () {
227 const fs = yield* FileSystem.FileSystem;
228 const path = yield* Path.Path;
229 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-" });
230 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-v1-dest-" });
231 const stateDir = path.join(sourceDir, "userdata");
232 const source = path.join(stateDir, "statev2.sqlite");
233 yield* fs.makeDirectory(stateDir, { recursive: true });
234 yield* withDatabase(source, runMigrations({ toMigrationInclusive: 54 }));
235
236 const result = yield* runMigrateDevDb(
237 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
238 { sharedHome: sourceDir },
239 );
240 assert.include(result.executedMigrations, "55_OrchestrationV2");
241 }),
242 );
243
244 it.effect("refuses while a dev server holds the destination", () =>
245 Effect.gen(function* () {
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
249 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
250 const source = yield* createFixtureSource(sourceDir);
251 const stateDir = path.join(destDir, "userdata");
252 yield* fs.makeDirectory(stateDir, { recursive: true });
253 yield* fs.writeFileString(
254 path.join(stateDir, "server-runtime.json"),
255 `{"version":1,"pid":${process.pid}}`,
256 );
257
258 const error = yield* runMigrateDevDb(
259 { baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
260 { sharedHome: sourceDir },
261 ).pipe(Effect.flip);
262 assert.equal(error._tag, "MigrateDevDbServerRunningError");
263 if (error._tag === "MigrateDevDbServerRunningError") {
264 assert.equal(error.pid, process.pid);
265 }
266 }),
267 );
268
269 it.effect("refuses a source that resolves to a destination path", () =>
270 Effect.gen(function* () {
271 const fs = yield* FileSystem.FileSystem;
272 const path = yield* Path.Path;
273 const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
274 const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
275 const leftoverSnapshot = path.join(destDir, "userdata", "statev2.sqlite.migrate-dev-db-tmp");
276 yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
277 yield* fs.writeFileString(leftoverSnapshot, "not a real db");
278
279 const error = yield* runMigrateDevDb(
280 { baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
281 { sharedHome: sharedDir },
282 ).pipe(Effect.flip);
283 assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
284 assert.equal(yield* fs.exists(leftoverSnapshot), true);
285 }),
286 );
287
288 it.effect("refuses to rebuild the shared home", () =>
289 Effect.gen(function* () {
290 const fs = yield* FileSystem.FileSystem;
291 const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
292 const source = yield* createFixtureSource(sourceDir);
293
294 const error = yield* runMigrateDevDb(
295 { baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
296 { sharedHome: sourceDir },
297 ).pipe(Effect.flip);
298 assert.equal(error._tag, "MigrateDevDbSharedHomeError");
299 }),
300 );
301});