Open History to see the last commit
1#!/usr/bin/env node
2
3/**
4 * Rebuild an isolated dev database from a pruned snapshot of the real
5 * ~/.t3 database, then run this checkout's migrations against it.
6 *
7 * `vp run migrate-dev-db` from a worktree:
8 * 1. Nukes `<worktree>/.t3/userdata/state.sqlite`.
9 * 2. Snapshots the real db (read-only VACUUM INTO) and prunes it to the
10 * most recently updated projects and, per project, the most recent
11 * threads that have fully stopped. Working, settled, and monitored
12 * threads are skipped so the dev server never adopts live work.
13 * Auth sessions, pairing links, command receipts, and provider
14 * runtime rows are dropped — pair a fresh browser against dev.
15 * 3. Runs migrations on the result. Because the clone carries the real
16 * `effect_sql_migrations` table, this proves a new migration applies
17 * on top of the real applied set, and the slot check below catches
18 * the silent failure where two branches claim the same
19 * `Migrations/NNN_` id (the second one's CREATE TABLE is skipped).
20 *
21 * The event log (`orchestration_events`) is pruned per stream while
22 * `sqlite_sequence` and `projection_state` carry over untouched, so new
23 * events keep appending after the old high-water mark and projection
24 * cursors never rewind.
25 */
26
27import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
28import * as NodeServices from "@effect/platform-node/NodeServices";
29import * as NodeOS from "node:os";
30import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
31import * as Console from "effect/Console";
32import * as Effect from "effect/Effect";
33import * as FileSystem from "effect/FileSystem";
34import * as Option from "effect/Option";
35import * as Path from "effect/Path";
36import * as Schema from "effect/Schema";
37import * as SqlClient from "effect/unstable/sql/SqlClient";
38import { Command, Flag } from "effect/unstable/cli";
39
40import { migrationManifest, runMigrations } from "../src/persistence/Migrations.ts";
41import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
42
43export class MigrateDevDbNotInWorktreeError extends Schema.TaggedErrorClass<MigrateDevDbNotInWorktreeError>()(
44 "MigrateDevDbNotInWorktreeError",
45 {},
46) {
47 override get message(): string {
48 return "Not inside a linked git worktree. Pass --base-dir to target an isolated .t3 directory.";
49 }
50}
51
52export class MigrateDevDbSharedHomeError extends Schema.TaggedErrorClass<MigrateDevDbSharedHomeError>()(
53 "MigrateDevDbSharedHomeError",
54 {},
55) {
56 override get message(): string {
57 return "Refusing to rebuild the shared ~/.t3 database. Use an isolated --base-dir.";
58 }
59}
60
61export class MigrateDevDbSourceMissingError extends Schema.TaggedErrorClass<MigrateDevDbSourceMissingError>()(
62 "MigrateDevDbSourceMissingError",
63 {
64 sourcePath: Schema.String,
65 },
66) {
67 override get message(): string {
68 return `Source database does not exist at '${this.sourcePath}'.`;
69 }
70}
71
72export class MigrateDevDbSourceIsDestinationError extends Schema.TaggedErrorClass<MigrateDevDbSourceIsDestinationError>()(
73 "MigrateDevDbSourceIsDestinationError",
74 {
75 sourcePath: Schema.String,
76 },
77) {
78 override get message(): string {
79 return `Source database '${this.sourcePath}' resolves to a path this command rewrites. Pick a different --source or --base-dir.`;
80 }
81}
82
83export class MigrateDevDbServerRunningError extends Schema.TaggedErrorClass<MigrateDevDbServerRunningError>()(
84 "MigrateDevDbServerRunningError",
85 {
86 databasePath: Schema.String,
87 pid: Schema.Number,
88 },
89) {
90 override get message(): string {
91 return `Dev database at '${this.databasePath}' is open by a running server (pid ${this.pid} per server-runtime.json). Stop that server first; if that pid is not actually a T3 server (stale descriptor, reused pid), delete the server-runtime.json next to the database and retry.`;
92 }
93}
94
95export class MigrateDevDbDestinationBusyError extends Schema.TaggedErrorClass<MigrateDevDbDestinationBusyError>()(
96 "MigrateDevDbDestinationBusyError",
97 {
98 databasePath: Schema.String,
99 reason: Schema.Literals(["write-locked", "wal-held"]),
100 cause: Schema.optional(Schema.Defect()),
101 },
102) {
103 override get message(): string {
104 const detail =
105 this.reason === "write-locked"
106 ? "the database is write-locked"
107 : "another connection is holding its WAL";
108 return `Dev database at '${this.databasePath}' looks in use (${detail}). Stop the dev server first; if none is running, delete the -wal/-shm files next to it.`;
109 }
110}
111
112/**
113 * Two branches claimed the same Migrations/NNN_ slot: the id was already
114 * recorded under a different name, so this checkout's migration was
115 * silently skipped and its schema changes never applied.
116 */
117export class MigrateDevDbSlotCollisionError extends Schema.TaggedErrorClass<MigrateDevDbSlotCollisionError>()(
118 "MigrateDevDbSlotCollisionError",
119 {
120 slot: Schema.Number,
121 codeName: Schema.String,
122 appliedName: Schema.String,
123 },
124) {
125 override get message(): string {
126 return `Migration slot collision at ${this.slot}: this checkout registers '${this.codeName}' but the database already applied '${this.appliedName}' in that slot. Renumber the new migration to a free slot.`;
127 }
128}
129
130export class MigrateDevDbPhaseError extends Schema.TaggedErrorClass<MigrateDevDbPhaseError>()(
131 "MigrateDevDbPhaseError",
132 {
133 phase: Schema.Literals(["snapshot", "prune", "compact", "migrate", "verify"]),
134 databasePath: Schema.String,
135 cause: Schema.Defect(),
136 },
137) {
138 override get message(): string {
139 return `migrate-dev-db failed during ${this.phase} on '${this.databasePath}'.`;
140 }
141}
142
143export interface RunMigrateDevDbInput {
144 /** Isolated .t3 directory. Defaults to `<worktree>/.t3` of the cwd. */
145 readonly baseDir?: string | undefined;
146 /** Source database. Defaults to `~/.t3/userdata/state.sqlite`. */
147 readonly source?: string | undefined;
148 readonly projects: number;
149 readonly threadsPerProject: number;
150}
151
152export interface RunMigrateDevDbOptions {
153 /** Overridable for tests; the directory writes must never target. */
154 readonly sharedHome?: string | undefined;
155}
156
157interface KeptProject {
158 readonly title: string;
159 readonly threads: number;
160}
161
162const removeDatabaseFiles = Effect.fn("removeDatabaseFiles")(function* (databasePath: string) {
163 const fs = yield* FileSystem.FileSystem;
164 for (const suffix of ["", "-wal", "-shm"]) {
165 yield* fs.remove(`${databasePath}${suffix}`).pipe(Effect.orElseSucceed(() => undefined));
166 }
167});
168
169/** The slice of server-runtime.json this script cares about. */
170const ServerRuntimeState = Schema.fromJsonString(Schema.Struct({ pid: Schema.Number }));
171const decodeServerRuntimeState = Schema.decodeEffect(ServerRuntimeState);
172
173const isProcessAlive = (pid: number): boolean => {
174 try {
175 process.kill(pid, 0);
176 return true;
177 } catch (error) {
178 // EPERM means the process exists but belongs to someone else.
179 return (error as NodeJS.ErrnoException).code === "EPERM";
180 }
181};
182
183/** Liveness probe for a running dev server. The server writes its pid to
184 * server-runtime.json next to the database, which also catches an idle
185 * server holding an open-but-inactive connection. The SQL probes below back
186 * that up: BEGIN IMMEDIATE fails while a writer is active, and
187 * wal_checkpoint(TRUNCATE) reports busy while another connection holds the
188 * WAL. A leftover -shm alone is not a signal — read-only connections cannot
189 * clean it up on close. */
190const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {
191 const fs = yield* FileSystem.FileSystem;
192 const path = yield* Path.Path;
193
194 const runtimeStatePath = path.join(path.dirname(databasePath), "server-runtime.json");
195 const runtimeState = yield* fs.readFileString(runtimeStatePath).pipe(
196 Effect.flatMap(decodeServerRuntimeState),
197 // A missing or malformed descriptor is not a liveness signal.
198 Effect.option,
199 );
200 if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
201 return yield* new MigrateDevDbServerRunningError({
202 databasePath,
203 pid: runtimeState.value.pid,
204 });
205 }
206
207 if (!(yield* fs.exists(databasePath))) {
208 return;
209 }
210 const checkpoint = yield* Effect.gen(function* () {
211 const sql = yield* SqlClient.SqlClient;
212 yield* sql.unsafe("PRAGMA busy_timeout = 0").unprepared;
213 yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;
214 yield* sql.unsafe("ROLLBACK").unprepared;
215 return yield* sql.unsafe<{ busy: number }>("PRAGMA wal_checkpoint(TRUNCATE)").unprepared;
216 }).pipe(
217 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
218 Effect.mapError(
219 (cause) =>
220 new MigrateDevDbDestinationBusyError({
221 databasePath,
222 reason: "write-locked",
223 cause,
224 }),
225 ),
226 );
227 if (checkpoint[0] !== undefined && Number(checkpoint[0].busy) !== 0) {
228 return yield* new MigrateDevDbDestinationBusyError({
229 databasePath,
230 reason: "wal-held",
231 });
232 }
233});
234
235const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
236 const sql = yield* SqlClient.SqlClient;
237
238 // The shared db can carry monitor_json from a branch build even though no
239 // migration in this checkout creates it, so filter it only when present.
240 const threadColumns = yield* sql<{ name: string }>`
241 SELECT name FROM pragma_table_info('projection_threads')`;
242 const monitorFilter = threadColumns.some((column) => column.name === "monitor_json")
243 ? "AND t.monitor_json IS NULL"
244 : "";
245
246 // "Stopped" is the persisted subset of the UI's thread status: the session
247 // reached status 'stopped' and nothing marks the thread settled or
248 // monitored. The in-memory working/monitoring liveness never persists, so
249 // filtering the session status is sufficient.
250 yield* sql.unsafe(`CREATE TEMP TABLE stopped_threads AS
251 SELECT t.thread_id, t.project_id, t.updated_at
252 FROM projection_threads t
253 JOIN projection_thread_sessions s ON s.thread_id = t.thread_id
254 WHERE t.deleted_at IS NULL
255 AND t.archived_at IS NULL
256 AND t.settled_at IS NULL
257 AND (t.settled_override IS NULL OR t.settled_override <> 'settled')
258 ${monitorFilter}
259 AND s.status = 'stopped'`).unprepared;
260
261 // Projects with clonable threads outrank empty-but-recent ones: the point
262 // of the exercise is thread data, not the project list.
263 yield* sql`CREATE TEMP TABLE kept_projects AS
264 SELECT p.project_id
265 FROM projection_projects p
266 LEFT JOIN (
267 SELECT project_id, MAX(updated_at) AS last_stopped_at
268 FROM stopped_threads
269 GROUP BY project_id
270 ) q ON q.project_id = p.project_id
271 WHERE p.deleted_at IS NULL
272 ORDER BY (q.last_stopped_at IS NULL) ASC,
273 COALESCE(q.last_stopped_at, p.updated_at) DESC
274 LIMIT ${input.projects}`;
275
276 yield* sql`CREATE TEMP TABLE kept_threads AS
277 SELECT thread_id FROM (
278 SELECT
279 st.thread_id,
280 ROW_NUMBER() OVER (
281 PARTITION BY st.project_id
282 ORDER BY st.updated_at DESC
283 ) AS recency_rank
284 FROM stopped_threads st
285 JOIN kept_projects kp ON kp.project_id = st.project_id
286 )
287 WHERE recency_rank <= ${input.threadsPerProject}`;
288
289 yield* sql.withTransaction(
290 Effect.gen(function* () {
291 yield* sql`DELETE FROM projection_projects
292 WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
293 yield* sql`DELETE FROM projection_threads
294 WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
295 for (const table of [
296 "projection_thread_messages",
297 "projection_thread_activities",
298 "projection_thread_sessions",
299 "projection_turns",
300 "projection_pending_approvals",
301 "projection_thread_proposed_plans",
302 "checkpoint_diff_blobs",
303 ]) {
304 yield* sql.unsafe(
305 `DELETE FROM ${table} WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
306 ).unprepared;
307 }
308 yield* sql`DELETE FROM orchestration_events
309 WHERE (aggregate_kind = 'thread'
310 AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
311 OR (aggregate_kind = 'project'
312 AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
313 yield* sql`DELETE FROM orchestration_command_receipts`;
314 yield* sql`DELETE FROM provider_session_runtime`;
315 yield* sql`DELETE FROM auth_sessions`;
316 yield* sql`DELETE FROM auth_pairing_links`;
317 }),
318 );
319
320 const keptProjects = yield* sql<{ title: string; threads: number }>`
321 SELECT
322 p.title,
323 (SELECT COUNT(*) FROM projection_threads t WHERE t.project_id = p.project_id) AS threads
324 FROM projection_projects p
325 ORDER BY p.updated_at DESC`;
326 const [events] = yield* sql<{ count: number }>`
327 SELECT COUNT(*) AS count FROM orchestration_events`;
328
329 return {
330 projects: keptProjects as ReadonlyArray<KeptProject>,
331 eventCount: events?.count ?? 0,
332 };
333});
334
335/** Compare this checkout's migration registry against what the cloned
336 * database recorded: same slot under a different name means the migration
337 * was skipped, not applied. */
338const verifyMigrationSlots = Effect.fn("verifyMigrationSlots")(function* () {
339 const sql = yield* SqlClient.SqlClient;
340 const applied = yield* sql<{ migration_id: number; name: string }>`
341 SELECT migration_id, name FROM effect_sql_migrations`;
342 const appliedById = new Map(applied.map((row) => [Number(row.migration_id), row.name]));
343 for (const [slot, codeName] of migrationManifest) {
344 const appliedName = appliedById.get(slot);
345 if (appliedName !== undefined && appliedName !== codeName) {
346 return yield* new MigrateDevDbSlotCollisionError({ slot, codeName, appliedName });
347 }
348 }
349});
350
351export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
352 input: RunMigrateDevDbInput,
353 options: RunMigrateDevDbOptions = {},
354) {
355 // SQLite treats a negative LIMIT as "no limit", which would clone
356 // everything. The CLI flags validate this too; this covers direct callers.
357 if (input.projects < 1 || input.threadsPerProject < 0) {
358 return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
359 }
360 const fs = yield* FileSystem.FileSystem;
361 const path = yield* Path.Path;
362
363 const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
364 const sourcePath = path.resolve(
365 input.source ?? path.join(sharedHome, "userdata", "state.sqlite"),
366 );
367
368 const baseDir =
369 input.baseDir !== undefined
370 ? path.resolve(input.baseDir)
371 : yield* resolveWorktreeT3Home(process.cwd());
372 if (baseDir === undefined) {
373 return yield* new MigrateDevDbNotInWorktreeError();
374 }
375 const stateDir = path.join(baseDir, "userdata");
376 const databasePath = path.join(stateDir, "state.sqlite");
377 const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
378
379 if (!(yield* fs.exists(sourcePath))) {
380 return yield* new MigrateDevDbSourceMissingError({ sourcePath });
381 }
382 const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
383 fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
384 fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
385 ]);
386 if (canonicalBaseDir === canonicalSharedHome) {
387 return yield* new MigrateDevDbSharedHomeError();
388 }
389 // The destination db and snapshot both get deleted below; a --source that
390 // resolves to either (e.g. a leftover snapshot file) would be destroyed
391 // before it is ever read.
392 const canonicalSourcePath = yield* fs
393 .realPath(sourcePath)
394 .pipe(Effect.orElseSucceed(() => sourcePath));
395 for (const destination of [databasePath, snapshotPath]) {
396 const canonicalDestination = yield* fs
397 .realPath(destination)
398 .pipe(Effect.orElseSucceed(() => destination));
399 if (canonicalSourcePath === canonicalDestination) {
400 return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
401 }
402 }
403
404 yield* fs.makeDirectory(stateDir, { recursive: true });
405 yield* ensureNotInUse(databasePath);
406
407 const wrapPhase =
408 (phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
409 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
410 effect.pipe(
411 Effect.mapError(
412 (cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
413 ),
414 );
415
416 yield* removeDatabaseFiles(snapshotPath);
417 // The snapshot is a full-size copy of the source; make sure it is removed
418 // even when a phase fails partway through.
419 const { executedMigrations, pruned } = yield* Effect.gen(function* () {
420 yield* Console.log(`Snapshotting ${sourcePath} (read-only)...`);
421 yield* Effect.gen(function* () {
422 const sql = yield* SqlClient.SqlClient;
423 yield* sql`VACUUM INTO ${snapshotPath}`;
424 }).pipe(
425 Effect.provide(NodeSqliteClient.layer({ filename: sourcePath, readonly: true })),
426 wrapPhase("snapshot", sourcePath),
427 );
428
429 // Migrate before pruning: a source older than this checkout would
430 // otherwise crash the prune queries on columns that don't exist yet.
431 // Running against the full snapshot also exercises new migrations on the
432 // same data volume the real database would face.
433 yield* Console.log("Running migrations on the snapshot...");
434 const executed = yield* Effect.gen(function* () {
435 const sql = yield* SqlClient.SqlClient;
436 // Mirror server boot (persistence/Layers/Sqlite.ts).
437 yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
438 return yield* runMigrations();
439 }).pipe(
440 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
441 wrapPhase("migrate", snapshotPath),
442 );
443
444 // Verify while the snapshot is still the only thing touched: a slot
445 // collision must abort before the old worktree db gets replaced with a
446 // schema whose colliding migration was silently skipped.
447 yield* verifyMigrationSlots().pipe(
448 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
449 Effect.catchTags({
450 SqlError: (cause) =>
451 Effect.fail(
452 new MigrateDevDbPhaseError({ phase: "verify", databasePath: snapshotPath, cause }),
453 ),
454 }),
455 );
456
457 yield* Console.log(
458 `Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
459 );
460 const result = yield* pruneSnapshot(input).pipe(
461 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
462 wrapPhase("prune", snapshotPath),
463 );
464
465 yield* Console.log(`Compacting into ${databasePath}...`);
466 // Re-check right before the swap: a dev server started while the
467 // snapshot was migrating and pruning must not lose its database.
468 yield* ensureNotInUse(databasePath);
469 yield* removeDatabaseFiles(databasePath);
470 yield* Effect.gen(function* () {
471 const sql = yield* SqlClient.SqlClient;
472 yield* sql`VACUUM INTO ${databasePath}`;
473 }).pipe(
474 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
475 wrapPhase("compact", databasePath),
476 );
477 return { executedMigrations: executed, pruned: result };
478 }).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
479 yield* fs.chmod(databasePath, 0o600);
480
481 yield* Effect.gen(function* () {
482 const sql = yield* SqlClient.SqlClient;
483 // WAL does not survive VACUUM INTO; set it so first `vp run dev` finds
484 // the database exactly as server boot would have left it.
485 yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
486 }).pipe(
487 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
488 wrapPhase("compact", databasePath),
489 );
490
491 const size = (yield* fs.stat(databasePath)).size;
492 return {
493 databasePath,
494 sizeBytes: Number(size),
495 projects: pruned.projects,
496 eventCount: pruned.eventCount,
497 executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
498 };
499});
500
501const formatSize = (bytes: number): string =>
502 bytes >= 1024 * 1024
503 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
504 : `${(bytes / 1024).toFixed(0)} KB`;
505
506export const migrateDevDbCommand = Command.make(
507 "migrate-dev-db",
508 {
509 projects: Flag.integer("projects").pipe(
510 Flag.withDefault(5),
511 Flag.withDescription("How many recently updated projects to keep."),
512 ),
513 threadsPerProject: Flag.integer("threads-per-project").pipe(
514 Flag.withDefault(10),
515 Flag.withDescription("How many recent stopped threads to keep per project."),
516 ),
517 baseDir: Flag.string("base-dir").pipe(
518 Flag.optional,
519 Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
520 ),
521 source: Flag.string("source").pipe(
522 Flag.optional,
523 Flag.withDescription("Source database. Defaults to ~/.t3/userdata/state.sqlite."),
524 ),
525 },
526 ({ projects, threadsPerProject, baseDir, source }) =>
527 Effect.gen(function* () {
528 const result = yield* runMigrateDevDb({
529 projects,
530 threadsPerProject,
531 baseDir: Option.getOrUndefined(baseDir),
532 source: Option.getOrUndefined(source),
533 });
534 yield* Console.log("");
535 yield* Console.log(
536 `Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
537 );
538 for (const project of result.projects) {
539 yield* Console.log(` ${project.title}: ${project.threads} threads`);
540 }
541 yield* Console.log(` ${result.eventCount} orchestration events kept`);
542 yield* Console.log(
543 result.executedMigrations.length === 0
544 ? " Migrations: already current (no new migrations in this checkout)"
545 : ` Migrations applied: ${result.executedMigrations.join(", ")}`,
546 );
547 }),
548).pipe(
549 Command.withDescription(
550 "Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
551 ),
552);
553
554if (import.meta.main) {
555 Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
556 Effect.provide(NodeServices.layer),
557 NodeRuntime.runMain,
558 );
559}