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