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

migrate-dev-db.ts

626 lines24.3 KB

1#!/usr/bin/env node
2​
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as NodeOS from "node:os";
6import * as NodeURL from "node:url";
7import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
8import * as Console from "effect/Console";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Schema from "effect/Schema";
15import * as SqlClient from "effect/sql/SqlClient";
16import { Command, Flag } from "effect/cli";
17​
18import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
19import { migrationManifest, runMigrations } from "../src/persistence/Migrations.ts";
20import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
21​
22export class MigrateDevDbNotInWorktreeError extends Schema.TaggedError<MigrateDevDbNotInWorktreeError>()(
23 "MigrateDevDbNotInWorktreeError",
24 {},
25) {
26 override get message(): string {
27 return "Not inside a linked git worktree. Pass --base-dir to target an isolated .t3 directory.";
28 }
30​
31export class MigrateDevDbSharedHomeError extends Schema.TaggedError<MigrateDevDbSharedHomeError>()(
32 "MigrateDevDbSharedHomeError",
33 {},
34) {
35 override get message(): string {
36 return "Refusing to rebuild the shared ~/.t3 database. Use an isolated --base-dir.";
37 }
39​
40export class MigrateDevDbSourceMissingError extends Schema.TaggedError<MigrateDevDbSourceMissingError>()(
41 "MigrateDevDbSourceMissingError",
42 {
43 sourcePath: Schema.String,
44 },
45) {
46 override get message(): string {
47 return `Source database does not exist at '${this.sourcePath}'.`;
48 }
50​
51export class MigrateDevDbSourceIsDestinationError extends Schema.TaggedError<MigrateDevDbSourceIsDestinationError>()(
52 "MigrateDevDbSourceIsDestinationError",
53 {
54 sourcePath: Schema.String,
55 },
56) {
57 override get message(): string {
58 return `Source database '${this.sourcePath}' resolves to a path this command rewrites. Pick a different --source or --base-dir.`;
59 }
61​
62export class MigrateDevDbServerRunningError extends Schema.TaggedError<MigrateDevDbServerRunningError>()(
63 "MigrateDevDbServerRunningError",
64 {
65 databasePath: Schema.String,
66 pid: Schema.Number,
67 },
68) {
69 override get message(): string {
70 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.`;
71 }
73​
74export class MigrateDevDbDestinationBusyError extends Schema.TaggedError<MigrateDevDbDestinationBusyError>()(
75 "MigrateDevDbDestinationBusyError",
76 {
77 databasePath: Schema.String,
78 reason: Schema.Literals(["write-locked", "wal-held"]),
79 cause: Schema.optional(Schema.Defect()),
80 },
81) {
82 override get message(): string {
83 const detail =
84 this.reason === "write-locked"
85 ? "the database is write-locked"
86 : "another connection is holding its WAL";
87 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.`;
88 }
90​
91export class MigrateDevDbSlotCollisionError extends Schema.TaggedError<MigrateDevDbSlotCollisionError>()(
92 "MigrateDevDbSlotCollisionError",
93 {
94 slot: Schema.Number,
95 codeName: Schema.String,
96 appliedName: Schema.String,
97 },
98) {
99 override get message(): string {
100 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.`;
101 }
103​
104export class MigrateDevDbPhaseError extends Schema.TaggedError<MigrateDevDbPhaseError>()(
105 "MigrateDevDbPhaseError",
106 {
107 phase: Schema.Literals(["snapshot", "prune", "compact", "migrate", "verify"]),
108 databasePath: Schema.String,
109 cause: Schema.Defect(),
110 },
111) {
112 override get message(): string {
113 return `migrate-dev-db failed during ${this.phase} on '${this.databasePath}'.`;
114 }
116​
117export interface RunMigrateDevDbInput {
118 readonly baseDir?: string | undefined;
119 readonly source?: string | undefined;
120 readonly projects: number;
121 readonly threadsPerProject: number;
123​
124export interface RunMigrateDevDbOptions {
125 /** Overridable for tests; the directory writes must never target. */
126 readonly sharedHome?: string | undefined;
128​
129interface KeptProject {
130 readonly title: string;
131 readonly threads: number;
133​
134const removeDatabaseFiles = Effect.fn("removeDatabaseFiles")(function* (databasePath: string) {
135 const fs = yield* FileSystem.FileSystem;
136 for (const suffix of ["", "-wal", "-shm"]) {
137 yield* fs.remove(`${databasePath}${suffix}`).pipe(Effect.orElseSucceed(() => undefined));
138 }
139});
140​
141const ServerRuntimeState = Schema.fromJsonString(Schema.Struct({ pid: Schema.Number }));
142const decodeServerRuntimeState = Schema.decodeEffect(ServerRuntimeState);
143​
144const isProcessAlive = (pid: number): boolean => {
145 try {
146 process.kill(pid, 0);
147 return true;
148 } catch (error) {
149 // EPERM means the process exists but belongs to someone else.
150 return (error as NodeJS.ErrnoException).code === "EPERM";
151 }
152};
153​
154/**
155 * The server writes its pid to server-runtime.json next to the database, which also catches an idle server holding an open-but-inactive
156 * connection. A leftover -shm alone is not a signal — read-only connections cannot clean it up on close.
157 */
158const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {
159 const fs = yield* FileSystem.FileSystem;
160 const path = yield* Path.Path;
161​
162 const runtimeStatePath = path.join(path.dirname(databasePath), "server-runtime.json");
163 const runtimeState = yield* fs
164 .readFileString(runtimeStatePath)
165 .pipe(Effect.flatMap(decodeServerRuntimeState), Effect.option);
166 if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
167 return yield* new MigrateDevDbServerRunningError({
168 databasePath,
169 pid: runtimeState.value.pid,
170 });
171 }
172​
173 if (!(yield* fs.exists(databasePath))) {
174 return;
175 }
176 const checkpoint = yield* Effect.gen(function* () {
177 const sql = yield* SqlClient.SqlClient;
178 yield* sql.unsafe("PRAGMA busy_timeout = 0").unprepared;
179 yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;
180 yield* sql.unsafe("ROLLBACK").unprepared;
181 return yield* sql.unsafe<{ busy: number }>("PRAGMA wal_checkpoint(TRUNCATE)").unprepared;
182 }).pipe(
183 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
184 Effect.mapError(
185 (cause) =>
186 new MigrateDevDbDestinationBusyError({
187 databasePath,
188 reason: "write-locked",
189 cause,
190 }),
191 ),
192 );
193 if (checkpoint[0] !== undefined && Number(checkpoint[0].busy) !== 0) {
194 return yield* new MigrateDevDbDestinationBusyError({
195 databasePath,
196 reason: "wal-held",
197 });
198 }
199});
200​
201const RECOVERY_KINDS: ReadonlyArray<ProjectionStore.ProjectionRecoveryKind> = [
202 "queued-runs",
203 "runtime",
204 "subagent-results",
205 "delegated-completions",
206];
207​
208const CLEARED_TABLES: ReadonlyArray<string> = [
209 "scheduled_tasks",
210 "orchestration_v2_effect_outbox",
211 "orchestration_v2_thread_launch_workflows",
212 "orchestration_command_receipts",
213 "provider_session_runtime",
214 "auth_sessions",
215 "auth_pairing_links",
216];
217​
218const PROVIDER_SESSIONS_TABLE = "orchestration_v2_projection_provider_sessions";
219​
220const rootIsVisible = (sql: SqlClient.SqlClient) => sql`
221 root.deleted_at IS NULL
222 AND json_extract(root.payload_json, '$.deletedAt') IS NULL
223 AND json_extract(root.payload_json, '$.archivedAt') IS NULL
224 AND json_extract(root.payload_json, '$.settledAt') IS NULL
225 AND json_extract(root.payload_json, '$.settledOverride') IS NOT 'settled'`;
226​
227/**
228 * One transaction reads the source, so the copy is consistent while the real server writes.
229 */
230const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: string) {
231 const sql = yield* SqlClient.SqlClient;
232 yield* sql`ATTACH DATABASE ${`${NodeURL.pathToFileURL(sourcePath).href}?mode=ro`} AS src`;
233 const schema = yield* sql<{ type: string; name: string; sql: string }>`
234 SELECT type, name, sql FROM src.sqlite_master
235 WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'`;
236 const threadColumns = yield* sql<{ name: string; notnull: number }>`
237 SELECT m.name, c."notnull" FROM src.sqlite_master m, pragma_table_info(m.name, 'src') c
238 WHERE m.type = 'table' AND c.name = 'thread_id'`;
239 const threadIdNullable = new Map(threadColumns.map((row) => [row.name, row.notnull === 0]));
240 const tables = schema.filter((entry) => entry.type === "table");
241 const filtered = tables.some((table) => table.name === "orchestration_v2_projection_threads");
242​
243 yield* sql.withTransaction(
244 Effect.gen(function* () {
245 for (const table of tables) yield* sql.unsafe(table.sql).unprepared;
246 if (filtered) {
247 yield* sql`CREATE TEMP TABLE copied_threads (thread_id TEXT PRIMARY KEY)`;
248 yield* sql`INSERT OR IGNORE INTO copied_threads
249 SELECT family.thread_id FROM src.orchestration_v2_projection_threads family
250 JOIN src.orchestration_v2_projection_threads root ON root.thread_id =
251 COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id)
252 WHERE ${rootIsVisible(sql)}`;
253 }
254 for (const { name } of tables) {
255 if (CLEARED_TABLES.includes(name)) continue;
256 const nullable = threadIdNullable.get(name);
257 const filter = !filtered
258 ? ""
259 : name === "orchestration_events"
260 ? // Two ranges rather than `<>`, so SQLite seeks the (aggregate_kind, stream_id)
261 // index instead of scanning every event.
262 `WHERE (aggregate_kind = 'thread' AND stream_id IN (SELECT thread_id FROM copied_threads))
263 OR aggregate_kind < 'thread' OR aggregate_kind > 'thread'`
264 : nullable === undefined || name === PROVIDER_SESSIONS_TABLE
265 ? ""
266 : `WHERE thread_id IN (SELECT thread_id FROM copied_threads)${nullable ? " OR thread_id IS NULL" : ""}`;
267 yield* sql.unsafe(`INSERT INTO main."${name}" SELECT * FROM src."${name}" ${filter}`)
268 .unprepared;
269 }
270 yield* sql`DELETE FROM main.sqlite_sequence`;
271 yield* sql`INSERT INTO main.sqlite_sequence SELECT name, seq FROM src.sqlite_sequence`;
272 for (const entry of schema) {
273 if (entry.type !== "table") yield* sql.unsafe(entry.sql).unprepared;
274 }
275 }),
276 );
277 yield* sql`DETACH DATABASE src`;
278});
279​
280const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
281 const sql = yield* SqlClient.SqlClient;
282​
283 // A ready session is an idle reusable provider handle, not executing work.
284 // Old installs bind that handle to many completed threads. Stop only those
285 // idle handles in the copy before asking the runtime recovery queries which
286 // threads could resume work; active runs/provider threads still exclude them.
287 yield* sql`UPDATE orchestration_v2_projection_provider_sessions
288 SET status = 'stopped', payload_json = json_set(payload_json, '$.status', 'stopped')
289 WHERE status = 'ready'`;
290​
291 // Threads the server would resume or start work on by itself. Its own
292 // recovery queries find most of them; usage-limit recovery also depends on
293 // settings, so any thread whose latest run failed or that has a recovery
294 // choice counts as live too.
295 const projections = yield* ProjectionStore.ProjectionStoreV2;
296 const recoveryThreadIds = yield* Effect.forEach(RECOVERY_KINDS, (kind) =>
297 projections.getRecoveryThreadIds(kind),
298 );
299 yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`;
300 for (const threadId of new Set(recoveryThreadIds.flat())) {
301 yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`;
302 }
303 yield* sql`INSERT OR IGNORE INTO live_threads (thread_id)
304 SELECT r.thread_id FROM orchestration_v2_projection_runs r
305 WHERE r.status = 'failed' AND r.ordinal = (
306 SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest
307 WHERE latest.thread_id = r.thread_id)
308 UNION
309 SELECT thread_id FROM orchestration_v2_projection_threads
310 WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`;
311​
312 // Forks and subagents read history and results through their lineage, so a
313 // thread family is cloned or dropped as a whole.
314 yield* sql`CREATE TEMP TABLE thread_families AS
315 SELECT thread_id, updated_at,
316 COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id) AS root_id
317 FROM orchestration_v2_projection_threads`;
318​
319 yield* sql`CREATE TEMP TABLE stopped_families AS
320 SELECT f.root_id, root.project_id, MAX(f.updated_at) AS updated_at
321 FROM thread_families f
322 JOIN orchestration_v2_projection_threads root ON root.thread_id = f.root_id
323 WHERE ${rootIsVisible(sql)}
324 GROUP BY f.root_id, root.project_id
325 HAVING SUM(f.thread_id IN (SELECT thread_id FROM live_threads)) = 0`;
326​
327 yield* sql`CREATE TEMP TABLE kept_projects AS
328 SELECT p.project_id
329 FROM projection_projects p
330 LEFT JOIN (
331 SELECT project_id, MAX(updated_at) AS last_stopped_at
332 FROM stopped_families
333 GROUP BY project_id
334 ) q ON q.project_id = p.project_id
335 WHERE p.deleted_at IS NULL
336 ORDER BY (q.last_stopped_at IS NULL) ASC,
337 COALESCE(q.last_stopped_at, p.updated_at) DESC
338 LIMIT ${input.projects}`;
339​
340 yield* sql`CREATE TEMP TABLE kept_threads AS
341 SELECT f.thread_id FROM thread_families f
342 WHERE f.root_id IN (
343 SELECT root_id FROM (
344 SELECT
345 sf.root_id,
346 ROW_NUMBER() OVER (
347 PARTITION BY sf.project_id
348 ORDER BY sf.updated_at DESC
349 ) AS recency_rank
350 FROM stopped_families sf
351 JOIN kept_projects kp ON kp.project_id = sf.project_id
352 )
353 WHERE recency_rank <= ${input.threadsPerProject}
354 )`;
355​
356 const threadTables = yield* sql<{ name: string }>`
357 SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c
358 WHERE m.type = 'table' AND c.name = 'thread_id'
359 AND m.name <> ${PROVIDER_SESSIONS_TABLE}`;
360​
361 yield* sql.withTransaction(
362 Effect.gen(function* () {
363 yield* sql`DELETE FROM projection_projects
364 WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
365 yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)}
366 WHERE COALESCE(thread_id, '') NOT IN (SELECT thread_id FROM kept_threads)
367 AND provider_session_id NOT IN (
368 SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings
369 WHERE thread_id IN (SELECT thread_id FROM kept_threads)
370 )`;
371 for (const { name } of threadTables) {
372 yield* sql.unsafe(
373 `DELETE FROM "${name}" WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
374 ).unprepared;
375 }
376 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers
377 WHERE source_thread_id NOT IN (SELECT thread_id FROM kept_threads)
378 OR target_thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
379 yield* sql`DELETE FROM orchestration_events
380 WHERE (aggregate_kind = 'thread'
381 AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
382 OR (aggregate_kind = 'project'
383 AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
384 for (const table of CLEARED_TABLES) {
385 yield* sql`DELETE FROM ${sql(table)}`;
386 }
387 }),
388 );
389​
390 const keptProjects = yield* sql<{ title: string; threads: number }>`
391 SELECT
392 p.title,
393 (SELECT COUNT(*) FROM orchestration_v2_projection_threads t
394 WHERE t.project_id = p.project_id) AS threads
395 FROM projection_projects p
396 ORDER BY p.updated_at DESC`;
397 const [events] = yield* sql<{ count: number }>`
398 SELECT COUNT(*) AS count FROM orchestration_events`;
399​
400 return {
401 projects: keptProjects as ReadonlyArray<KeptProject>,
402 eventCount: events?.count ?? 0,
403 };
404});
405​
406const verifyMigrationSlots = Effect.fn("verifyMigrationSlots")(function* () {
407 const sql = yield* SqlClient.SqlClient;
408 const applied = yield* sql<{ migration_id: number; name: string }>`
409 SELECT migration_id, name FROM effect_sql_migrations`;
410 const appliedById = new Map(applied.map((row) => [Number(row.migration_id), row.name]));
411 for (const [slot, codeName] of migrationManifest) {
412 const appliedName = appliedById.get(slot);
413 if (appliedName !== undefined && appliedName !== codeName) {
414 return yield* new MigrateDevDbSlotCollisionError({ slot, codeName, appliedName });
415 }
416 }
417});
418​
419export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
420 input: RunMigrateDevDbInput,
421 options: RunMigrateDevDbOptions = {},
422) {
423 // SQLite treats a negative LIMIT as "no limit", which would clone
424 // everything. The CLI flags validate this too; this covers direct callers.
425 if (input.projects < 1 || input.threadsPerProject < 0) {
426 return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
427 }
428 const fs = yield* FileSystem.FileSystem;
429 const path = yield* Path.Path;
430​
431 const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
432 const sourcePath = path.resolve(
433 input.source ?? path.join(sharedHome, "userdata", "statev2.sqlite"),
434 );
435​
436 const baseDir =
437 input.baseDir !== undefined
438 ? path.resolve(input.baseDir)
439 : yield* resolveWorktreeT3Home(process.cwd());
440 if (baseDir === undefined) {
441 return yield* new MigrateDevDbNotInWorktreeError();
442 }
443 const stateDir = path.join(baseDir, "userdata");
444 const databasePath = path.join(stateDir, "statev2.sqlite");
445 const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
446​
447 if (!(yield* fs.exists(sourcePath))) {
448 return yield* new MigrateDevDbSourceMissingError({ sourcePath });
449 }
450 const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
451 fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
452 fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
453 ]);
454 if (canonicalBaseDir === canonicalSharedHome) {
455 return yield* new MigrateDevDbSharedHomeError();
456 }
457 // The destination db and snapshot both get deleted below; a --source that
458 // resolves to either (e.g. a leftover snapshot file) would be destroyed
459 // before it is ever read.
460 const canonicalSourcePath = yield* fs
461 .realPath(sourcePath)
462 .pipe(Effect.orElseSucceed(() => sourcePath));
463 for (const destination of [databasePath, snapshotPath]) {
464 const canonicalDestination = yield* fs
465 .realPath(destination)
466 .pipe(Effect.orElseSucceed(() => destination));
467 if (canonicalSourcePath === canonicalDestination) {
468 return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
469 }
470 }
471​
472 yield* fs.makeDirectory(stateDir, { recursive: true });
473 yield* ensureNotInUse(databasePath);
474​
475 const wrapPhase =
476 (phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
477 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
478 effect.pipe(
479 Effect.mapError(
480 (cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
481 ),
482 );
483​
484 yield* removeDatabaseFiles(snapshotPath);
485 const { executedMigrations, pruned } = yield* Effect.gen(function* () {
486 yield* Console.log(`Copying visible threads from ${sourcePath} (read-only)...`);
487 yield* copySourceSlice(sourcePath).pipe(
488 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
489 wrapPhase("snapshot", sourcePath),
490 );
491​
492 // Migrate before pruning: a source older than this checkout would
493 // otherwise crash the prune queries on columns that don't exist yet.
494 yield* Console.log("Running migrations on the snapshot...");
495 const executed = yield* Effect.gen(function* () {
496 const sql = yield* SqlClient.SqlClient;
497 // Mirror server boot (persistence/Sqlite.ts).
498 yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
499 return yield* runMigrations();
500 }).pipe(
501 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
502 wrapPhase("migrate", snapshotPath),
503 );
504​
505 // Verify while the snapshot is still the only thing touched: a slot
506 // collision must abort before the old worktree db gets replaced with a
507 // schema whose colliding migration was silently skipped.
508 yield* verifyMigrationSlots().pipe(
509 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
510 Effect.catchTags({
511 SqlError: (cause) =>
512 Effect.fail(
513 new MigrateDevDbPhaseError({ phase: "verify", databasePath: snapshotPath, cause }),
514 ),
515 }),
516 );
517​
518 yield* Console.log(
519 `Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
520 );
521 const result = yield* pruneSnapshot(input).pipe(
522 Effect.provide(
523 ProjectionStore.layer.pipe(
524 Layer.provideMerge(NodeSqliteClient.layer({ filename: snapshotPath })),
525 ),
526 ),
527 wrapPhase("prune", snapshotPath),
528 );
529​
530 yield* Console.log(`Compacting into ${databasePath}...`);
531 // Re-check right before the swap: a dev server started while the
532 // snapshot was migrating and pruning must not lose its database.
533 yield* ensureNotInUse(databasePath);
534 yield* removeDatabaseFiles(databasePath);
535 yield* Effect.gen(function* () {
536 const sql = yield* SqlClient.SqlClient;
537 yield* sql`VACUUM INTO ${databasePath}`;
538 }).pipe(
539 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
540 wrapPhase("compact", databasePath),
541 );
542 return { executedMigrations: executed, pruned: result };
543 }).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
544 yield* fs.chmod(databasePath, 0o600);
545​
546 yield* Effect.gen(function* () {
547 const sql = yield* SqlClient.SqlClient;
548 // WAL does not survive VACUUM INTO; set it so first `vp run dev` finds
549 // the database exactly as server boot would have left it.
550 yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
551 }).pipe(
552 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
553 wrapPhase("compact", databasePath),
554 );
555​
556 const size = (yield* fs.stat(databasePath)).size;
557 return {
558 databasePath,
559 sizeBytes: Number(size),
560 projects: pruned.projects,
561 eventCount: pruned.eventCount,
562 executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
563 };
564});
565​
566const formatSize = (bytes: number): string =>
567 bytes >= 1024 * 1024
568 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
569 : `${(bytes / 1024).toFixed(0)} KB`;
570​
571export const migrateDevDbCommand = Command.make(
572 "migrate-dev-db",
573 {
574 projects: Flag.Int("projects").pipe(
575 Flag.withDefault(5),
576 Flag.withDescription("How many recently updated projects to keep."),
577 ),
578 threadsPerProject: Flag.Int("threads-per-project").pipe(
579 Flag.withDefault(10),
580 Flag.withDescription(
581 "How many recent stopped threads, with their forks and subagents, to keep per project.",
582 ),
583 ),
584 baseDir: Flag.String("base-dir").pipe(
585 Flag.optional,
586 Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
587 ),
588 source: Flag.String("source").pipe(
589 Flag.optional,
590 Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),
591 ),
592 },
593 ({ projects, threadsPerProject, baseDir, source }) =>
594 Effect.gen(function* () {
595 const result = yield* runMigrateDevDb({
596 projects,
597 threadsPerProject,
598 baseDir: Option.getOrUndefined(baseDir),
599 source: Option.getOrUndefined(source),
600 });
601 yield* Console.log("");
602 yield* Console.log(
603 `Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
604 );
605 for (const project of result.projects) {
606 yield* Console.log(` ${project.title}: ${project.threads} threads`);
607 }
608 yield* Console.log(` ${result.eventCount} orchestration events kept`);
609 yield* Console.log(
610 result.executedMigrations.length === 0
611 ? " Migrations: already current (no new migrations in this checkout)"
612 : ` Migrations applied: ${result.executedMigrations.join(", ")}`,
613 );
614 }),
615).pipe(
616 Command.withDescription(
617 "Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
618 ),
619);
620​
621if (import.meta.main) {
622 Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
623 Effect.provide(NodeServices.layer),
624 NodeRuntime.runMain,
625 );