Open History to see the last commit
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 }
29}
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 }
38}
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 }
49}
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 }
60}
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 }
72}
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 }
89}
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 }
102}
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 }
115}
116
117export interface RunMigrateDevDbInput {
118 readonly baseDir?: string | undefined;
119 readonly source?: string | undefined;
120 readonly projects: number;
121 readonly threadsPerProject: number;
122}
123
124export interface RunMigrateDevDbOptions {
125 /** Overridable for tests; the directory writes must never target. */
126 readonly sharedHome?: string | undefined;
127}
128
129interface KeptProject {
130 readonly title: string;
131 readonly threads: number;
132}
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 // Threads the server would resume or start work on by itself. Its own
284 // recovery queries find most of them; usage-limit recovery also depends on
285 // settings, so any thread whose latest run failed or that has a recovery
286 // choice counts as live too.
287 const projections = yield* ProjectionStore.ProjectionStoreV2;
288 const recoveryThreadIds = yield* Effect.forEach(RECOVERY_KINDS, (kind) =>
289 projections.getRecoveryThreadIds(kind),
290 );
291 yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`;
292 for (const threadId of new Set(recoveryThreadIds.flat())) {
293 yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`;
294 }
295 yield* sql`INSERT OR IGNORE INTO live_threads (thread_id)
296 SELECT r.thread_id FROM orchestration_v2_projection_runs r
297 WHERE r.status = 'failed' AND r.ordinal = (
298 SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest
299 WHERE latest.thread_id = r.thread_id)
300 UNION
301 SELECT thread_id FROM orchestration_v2_projection_threads
302 WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`;
303
304 // Forks and subagents read history and results through their lineage, so a
305 // thread family is cloned or dropped as a whole.
306 yield* sql`CREATE TEMP TABLE thread_families AS
307 SELECT thread_id, updated_at,
308 COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id) AS root_id
309 FROM orchestration_v2_projection_threads`;
310
311 yield* sql`CREATE TEMP TABLE stopped_families AS
312 SELECT f.root_id, root.project_id, MAX(f.updated_at) AS updated_at
313 FROM thread_families f
314 JOIN orchestration_v2_projection_threads root ON root.thread_id = f.root_id
315 WHERE ${rootIsVisible(sql)}
316 GROUP BY f.root_id, root.project_id
317 HAVING SUM(f.thread_id IN (SELECT thread_id FROM live_threads)) = 0`;
318
319 yield* sql`CREATE TEMP TABLE kept_projects AS
320 SELECT p.project_id
321 FROM projection_projects p
322 LEFT JOIN (
323 SELECT project_id, MAX(updated_at) AS last_stopped_at
324 FROM stopped_families
325 GROUP BY project_id
326 ) q ON q.project_id = p.project_id
327 WHERE p.deleted_at IS NULL
328 ORDER BY (q.last_stopped_at IS NULL) ASC,
329 COALESCE(q.last_stopped_at, p.updated_at) DESC
330 LIMIT ${input.projects}`;
331
332 yield* sql`CREATE TEMP TABLE kept_threads AS
333 SELECT f.thread_id FROM thread_families f
334 WHERE f.root_id IN (
335 SELECT root_id FROM (
336 SELECT
337 sf.root_id,
338 ROW_NUMBER() OVER (
339 PARTITION BY sf.project_id
340 ORDER BY sf.updated_at DESC
341 ) AS recency_rank
342 FROM stopped_families sf
343 JOIN kept_projects kp ON kp.project_id = sf.project_id
344 )
345 WHERE recency_rank <= ${input.threadsPerProject}
346 )`;
347
348 const threadTables = yield* sql<{ name: string }>`
349 SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c
350 WHERE m.type = 'table' AND c.name = 'thread_id'
351 AND m.name <> ${PROVIDER_SESSIONS_TABLE}`;
352
353 yield* sql.withTransaction(
354 Effect.gen(function* () {
355 yield* sql`DELETE FROM projection_projects
356 WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
357 yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)}
358 WHERE COALESCE(thread_id, '') NOT IN (SELECT thread_id FROM kept_threads)
359 AND provider_session_id NOT IN (
360 SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings
361 WHERE thread_id IN (SELECT thread_id FROM kept_threads)
362 )`;
363 for (const { name } of threadTables) {
364 yield* sql.unsafe(
365 `DELETE FROM "${name}" WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
366 ).unprepared;
367 }
368 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers
369 WHERE source_thread_id NOT IN (SELECT thread_id FROM kept_threads)
370 OR target_thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
371 yield* sql`DELETE FROM orchestration_events
372 WHERE (aggregate_kind = 'thread'
373 AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
374 OR (aggregate_kind = 'project'
375 AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
376 for (const table of CLEARED_TABLES) {
377 yield* sql`DELETE FROM ${sql(table)}`;
378 }
379 }),
380 );
381
382 const keptProjects = yield* sql<{ title: string; threads: number }>`
383 SELECT
384 p.title,
385 (SELECT COUNT(*) FROM orchestration_v2_projection_threads t
386 WHERE t.project_id = p.project_id) AS threads
387 FROM projection_projects p
388 ORDER BY p.updated_at DESC`;
389 const [events] = yield* sql<{ count: number }>`
390 SELECT COUNT(*) AS count FROM orchestration_events`;
391
392 return {
393 projects: keptProjects as ReadonlyArray<KeptProject>,
394 eventCount: events?.count ?? 0,
395 };
396});
397
398const verifyMigrationSlots = Effect.fn("verifyMigrationSlots")(function* () {
399 const sql = yield* SqlClient.SqlClient;
400 const applied = yield* sql<{ migration_id: number; name: string }>`
401 SELECT migration_id, name FROM effect_sql_migrations`;
402 const appliedById = new Map(applied.map((row) => [Number(row.migration_id), row.name]));
403 for (const [slot, codeName] of migrationManifest) {
404 const appliedName = appliedById.get(slot);
405 if (appliedName !== undefined && appliedName !== codeName) {
406 return yield* new MigrateDevDbSlotCollisionError({ slot, codeName, appliedName });
407 }
408 }
409});
410
411export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
412 input: RunMigrateDevDbInput,
413 options: RunMigrateDevDbOptions = {},
414) {
415 // SQLite treats a negative LIMIT as "no limit", which would clone
416 // everything. The CLI flags validate this too; this covers direct callers.
417 if (input.projects < 1 || input.threadsPerProject < 0) {
418 return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
419 }
420 const fs = yield* FileSystem.FileSystem;
421 const path = yield* Path.Path;
422
423 const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
424 const sourcePath = path.resolve(
425 input.source ?? path.join(sharedHome, "userdata", "statev2.sqlite"),
426 );
427
428 const baseDir =
429 input.baseDir !== undefined
430 ? path.resolve(input.baseDir)
431 : yield* resolveWorktreeT3Home(process.cwd());
432 if (baseDir === undefined) {
433 return yield* new MigrateDevDbNotInWorktreeError();
434 }
435 const stateDir = path.join(baseDir, "userdata");
436 const databasePath = path.join(stateDir, "statev2.sqlite");
437 const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
438
439 if (!(yield* fs.exists(sourcePath))) {
440 return yield* new MigrateDevDbSourceMissingError({ sourcePath });
441 }
442 const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
443 fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
444 fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
445 ]);
446 if (canonicalBaseDir === canonicalSharedHome) {
447 return yield* new MigrateDevDbSharedHomeError();
448 }
449 // The destination db and snapshot both get deleted below; a --source that
450 // resolves to either (e.g. a leftover snapshot file) would be destroyed
451 // before it is ever read.
452 const canonicalSourcePath = yield* fs
453 .realPath(sourcePath)
454 .pipe(Effect.orElseSucceed(() => sourcePath));
455 for (const destination of [databasePath, snapshotPath]) {
456 const canonicalDestination = yield* fs
457 .realPath(destination)
458 .pipe(Effect.orElseSucceed(() => destination));
459 if (canonicalSourcePath === canonicalDestination) {
460 return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
461 }
462 }
463
464 yield* fs.makeDirectory(stateDir, { recursive: true });
465 yield* ensureNotInUse(databasePath);
466
467 const wrapPhase =
468 (phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
469 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
470 effect.pipe(
471 Effect.mapError(
472 (cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
473 ),
474 );
475
476 yield* removeDatabaseFiles(snapshotPath);
477 const { executedMigrations, pruned } = yield* Effect.gen(function* () {
478 yield* Console.log(`Copying visible threads from ${sourcePath} (read-only)...`);
479 yield* copySourceSlice(sourcePath).pipe(
480 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
481 wrapPhase("snapshot", sourcePath),
482 );
483
484 // Migrate before pruning: a source older than this checkout would
485 // otherwise crash the prune queries on columns that don't exist yet.
486 yield* Console.log("Running migrations on the snapshot...");
487 const executed = yield* Effect.gen(function* () {
488 const sql = yield* SqlClient.SqlClient;
489 // Mirror server boot (persistence/Sqlite.ts).
490 yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
491 return yield* runMigrations();
492 }).pipe(
493 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
494 wrapPhase("migrate", snapshotPath),
495 );
496
497 // Verify while the snapshot is still the only thing touched: a slot
498 // collision must abort before the old worktree db gets replaced with a
499 // schema whose colliding migration was silently skipped.
500 yield* verifyMigrationSlots().pipe(
501 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
502 Effect.catchTags({
503 SqlError: (cause) =>
504 Effect.fail(
505 new MigrateDevDbPhaseError({ phase: "verify", databasePath: snapshotPath, cause }),
506 ),
507 }),
508 );
509
510 yield* Console.log(
511 `Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
512 );
513 const result = yield* pruneSnapshot(input).pipe(
514 Effect.provide(
515 ProjectionStore.layer.pipe(
516 Layer.provideMerge(NodeSqliteClient.layer({ filename: snapshotPath })),
517 ),
518 ),
519 wrapPhase("prune", snapshotPath),
520 );
521
522 yield* Console.log(`Compacting into ${databasePath}...`);
523 // Re-check right before the swap: a dev server started while the
524 // snapshot was migrating and pruning must not lose its database.
525 yield* ensureNotInUse(databasePath);
526 yield* removeDatabaseFiles(databasePath);
527 yield* Effect.gen(function* () {
528 const sql = yield* SqlClient.SqlClient;
529 yield* sql`VACUUM INTO ${databasePath}`;
530 }).pipe(
531 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
532 wrapPhase("compact", databasePath),
533 );
534 return { executedMigrations: executed, pruned: result };
535 }).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
536 yield* fs.chmod(databasePath, 0o600);
537
538 yield* Effect.gen(function* () {
539 const sql = yield* SqlClient.SqlClient;
540 // WAL does not survive VACUUM INTO; set it so first `vp run dev` finds
541 // the database exactly as server boot would have left it.
542 yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
543 }).pipe(
544 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
545 wrapPhase("compact", databasePath),
546 );
547
548 const size = (yield* fs.stat(databasePath)).size;
549 return {
550 databasePath,
551 sizeBytes: Number(size),
552 projects: pruned.projects,
553 eventCount: pruned.eventCount,
554 executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
555 };
556});
557
558const formatSize = (bytes: number): string =>
559 bytes >= 1024 * 1024
560 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
561 : `${(bytes / 1024).toFixed(0)} KB`;
562
563export const migrateDevDbCommand = Command.make(
564 "migrate-dev-db",
565 {
566 projects: Flag.Int("projects").pipe(
567 Flag.withDefault(5),
568 Flag.withDescription("How many recently updated projects to keep."),
569 ),
570 threadsPerProject: Flag.Int("threads-per-project").pipe(
571 Flag.withDefault(10),
572 Flag.withDescription(
573 "How many recent stopped threads, with their forks and subagents, to keep per project.",
574 ),
575 ),
576 baseDir: Flag.String("base-dir").pipe(
577 Flag.optional,
578 Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
579 ),
580 source: Flag.String("source").pipe(
581 Flag.optional,
582 Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),
583 ),
584 },
585 ({ projects, threadsPerProject, baseDir, source }) =>
586 Effect.gen(function* () {
587 const result = yield* runMigrateDevDb({
588 projects,
589 threadsPerProject,
590 baseDir: Option.getOrUndefined(baseDir),
591 source: Option.getOrUndefined(source),
592 });
593 yield* Console.log("");
594 yield* Console.log(
595 `Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
596 );
597 for (const project of result.projects) {
598 yield* Console.log(` ${project.title}: ${project.threads} threads`);
599 }
600 yield* Console.log(` ${result.eventCount} orchestration events kept`);
601 yield* Console.log(
602 result.executedMigrations.length === 0
603 ? " Migrations: already current (no new migrations in this checkout)"
604 : ` Migrations applied: ${result.executedMigrations.join(", ")}`,
605 );
606 }),
607).pipe(
608 Command.withDescription(
609 "Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
610 ),
611);
612
613if (import.meta.main) {
614 Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
615 Effect.provide(NodeServices.layer),
616 NodeRuntime.runMain,
617 );
618}