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

migrate-dev-db.ts

608 lines24.1 KB

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