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

migrate-dev-db.ts

629 lines24.5 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 { 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 }
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 }
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 }
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 }
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 }
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 }
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 }
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 }
117​
118export interface RunMigrateDevDbInput {
119 readonly baseDir?: string | undefined;
120 readonly source?: string | undefined;
121 readonly projects: number;
122 readonly threadsPerProject: number;
124​
125export interface RunMigrateDevDbOptions {
126 /** Test override for the directory writes must never target. */
127 readonly sharedHome?: string | undefined;
129​
130interface KeptProject {
131 readonly title: string;
132 readonly threads: number;
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// The runtime PID catches idle servers; leftover -shm files can come from read-only connections.
156const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {
157 const fs = yield* FileSystem.FileSystem;
158 const path = yield* Path.Path;
159​
160 const runtimeStatePath = path.join(path.dirname(databasePath), "server-runtime.json");
161 const runtimeState = yield* fs
162 .readFileString(runtimeStatePath)
163 .pipe(Effect.flatMap(decodeServerRuntimeState), Effect.option);
164 if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
165 return yield* new MigrateDevDbServerRunningError({
166 databasePath,
167 pid: runtimeState.value.pid,
168 });
169 }
170​
171 if (!(yield* fs.exists(databasePath))) {
172 return;
173 }
174 const checkpoint = yield* Effect.gen(function* () {
175 const sql = yield* SqlClient.SqlClient;
176 yield* sql.unsafe("PRAGMA busy_timeout = 0").unprepared;
177 yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;
178 yield* sql.unsafe("ROLLBACK").unprepared;
179 return yield* sql.unsafe<{ busy: number }>("PRAGMA wal_checkpoint(TRUNCATE)").unprepared;
180 }).pipe(
181 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
182 Effect.mapError(
183 (cause) =>
184 new MigrateDevDbDestinationBusyError({
185 databasePath,
186 reason: "write-locked",
187 cause,
188 }),
189 ),
190 );
191 if (checkpoint[0] !== undefined && Number(checkpoint[0].busy) !== 0) {
192 return yield* new MigrateDevDbDestinationBusyError({
193 databasePath,
194 reason: "wal-held",
195 });
196 }
197});
198​
199const RECOVERY_KINDS: ReadonlyArray<ProjectionStore.ProjectionRecoveryKind> = [
200 "queued-runs",
201 "runtime",
202 "subagent-results",
203 "delegated-completions",
204];
205​
206const CLEARED_TABLES: ReadonlyArray<string> = [
207 "scheduled_tasks",
208 "orchestration_v2_effect_outbox",
209 "orchestration_v2_thread_launch_workflows",
210 "orchestration_command_receipts",
211 "provider_session_runtime",
212 "auth_sessions",
213 "auth_pairing_links",
214];
215​
216const PROVIDER_SESSIONS_TABLE = "orchestration_v2_projection_provider_sessions";
217const FTS5_SHADOW_SUFFIXES = ["_data", "_idx", "_content", "_docsize", "_config"];
218​
219// Settled threads stay: they are most of real history, and the UI shows them.
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​
225// A single read transaction keeps the copy consistent with concurrent server writes.
226const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: string) {
227 const sql = yield* SqlClient.SqlClient;
228 yield* sql`ATTACH DATABASE ${`${NodeURL.pathToFileURL(sourcePath).href}?mode=ro`} AS src`;
229 const schema = yield* sql<{ type: string; name: string; sql: string }>`
230 SELECT type, name, sql FROM src.sqlite_master
231 WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'`;
232 const threadColumns = yield* sql<{ name: string; notnull: number }>`
233 SELECT m.name, c."notnull" FROM src.sqlite_master m, pragma_table_info(m.name, 'src') c
234 WHERE m.type = 'table' AND c.name = 'thread_id'`;
235 const threadIdNullable = new Map(threadColumns.map((row) => [row.name, row.notnull === 0]));
236 // FTS5 makes its own shadow tables and contentless rows cannot be copied:
237 // create the virtual table, skip its shadow tables and rows, and rebuild the
238 // index once the messages and triggers are in.
239 const virtualTables = schema
240 .filter((entry) => entry.type === "table" && /^CREATE VIRTUAL TABLE/i.test(entry.sql))
241 .map((entry) => entry.name);
242 const isShadowTable = (name: string) =>
243 virtualTables.some((virtual) =>
244 FTS5_SHADOW_SUFFIXES.some((suffix) => name === `${virtual}${suffix}`),
245 );
246 const tables = schema.filter((entry) => entry.type === "table" && !isShadowTable(entry.name));
247 const filtered = tables.some((table) => table.name === "orchestration_v2_projection_threads");
248 // A row that points into a cleared table cannot be copied, so whatever references one is
249 // cleared with it, however far down the chain a newer migration added it.
250 const references = yield* sql<{ name: string; parent: string }>`
251 SELECT m.name, f."table" AS parent FROM src.sqlite_master m, pragma_foreign_key_list(m.name, 'src') f
252 WHERE m.type = 'table'`;
253 const cleared = new Set(CLEARED_TABLES);
254 for (let grew = true; grew;) {
255 grew = false;
256 for (const { name, parent } of references) {
257 if (cleared.has(parent) && !cleared.has(name)) {
258 cleared.add(name);
259 grew = true;
260 }
261 }
262 }
263​
264 yield* sql.withTransaction(
265 Effect.gen(function* () {
266 for (const table of tables) yield* sql.unsafe(table.sql).unprepared;
267 if (filtered) {
268 yield* sql`CREATE TEMP TABLE copied_threads (thread_id TEXT PRIMARY KEY)`;
269 yield* sql`INSERT OR IGNORE INTO copied_threads
270 SELECT family.thread_id FROM src.orchestration_v2_projection_threads family
271 JOIN src.orchestration_v2_projection_threads root ON root.thread_id =
272 COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id)
273 WHERE ${rootIsVisible(sql)}`;
274 }
275 for (const { name } of tables) {
276 if (cleared.has(name) || virtualTables.includes(name)) continue;
277 const nullable = threadIdNullable.get(name);
278 const filter = !filtered
279 ? ""
280 : name === "orchestration_events"
281 ? // Two ranges let SQLite seek the (aggregate_kind, stream_id) index instead of scanning.
282 `WHERE (aggregate_kind = 'thread' AND stream_id IN (SELECT thread_id FROM copied_threads))
283 OR aggregate_kind < 'thread' OR aggregate_kind > 'thread'`
284 : nullable === undefined || name === PROVIDER_SESSIONS_TABLE
285 ? ""
286 : `WHERE thread_id IN (SELECT thread_id FROM copied_threads)${nullable ? " OR thread_id IS NULL" : ""}`;
287 yield* sql.unsafe(`INSERT INTO main."${name}" SELECT * FROM src."${name}" ${filter}`)
288 .unprepared;
289 }
290 yield* sql`DELETE FROM main.sqlite_sequence`;
291 yield* sql`INSERT INTO main.sqlite_sequence SELECT name, seq FROM src.sqlite_sequence`;
292 for (const entry of schema) {
293 if (entry.type !== "table") yield* sql.unsafe(entry.sql).unprepared;
294 }
295 yield* rebuildMessageSearch(sql);
296 }),
297 );
298 yield* sql`DETACH DATABASE src`;
299});
300​
301const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
302 const sql = yield* SqlClient.SqlClient;
303​
304 // Usage-limit recovery also depends on settings; exclude latest-run failures and recovery choices.
305 const projections = yield* ProjectionStore.ProjectionStoreV2;
306 const recoveryThreadIds = yield* Effect.forEach(RECOVERY_KINDS, (kind) =>
307 projections.getRecoveryThreadIds(kind),
308 );
309 yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`;
310 for (const threadId of new Set(recoveryThreadIds.flat())) {
311 yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`;
312 }
313 yield* sql`INSERT OR IGNORE INTO live_threads (thread_id)
314 SELECT r.thread_id FROM orchestration_v2_projection_runs r
315 WHERE r.status = 'failed' AND r.ordinal = (
316 SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest
317 WHERE latest.thread_id = r.thread_id)
318 UNION
319 SELECT thread_id FROM orchestration_v2_projection_threads
320 WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`;
321​
322 // Clone or drop whole thread families to preserve fork and subagent lineage reads.
323 yield* sql`CREATE TEMP TABLE thread_families AS
324 SELECT thread_id, updated_at,
325 COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id) AS root_id
326 FROM orchestration_v2_projection_threads`;
327​
328 yield* sql`CREATE TEMP TABLE stopped_families AS
329 SELECT f.root_id, root.project_id, MAX(f.updated_at) AS updated_at, COUNT(*) AS size
330 FROM thread_families f
331 JOIN orchestration_v2_projection_threads root ON root.thread_id = f.root_id
332 WHERE ${rootIsVisible(sql)}
333 GROUP BY f.root_id, root.project_id
334 HAVING SUM(f.thread_id IN (SELECT thread_id FROM live_threads)) = 0`;
335​
336 yield* sql`CREATE TEMP TABLE kept_projects AS
337 SELECT p.project_id
338 FROM projection_projects p
339 LEFT JOIN (
340 SELECT project_id, MAX(updated_at) AS last_stopped_at
341 FROM stopped_families
342 GROUP BY project_id
343 ) q ON q.project_id = p.project_id
344 WHERE p.deleted_at IS NULL
345 ORDER BY (q.last_stopped_at IS NULL) ASC,
346 COALESCE(q.last_stopped_at, p.updated_at) DESC
347 LIMIT ${input.projects}`;
348​
349 yield* sql`CREATE TEMP TABLE kept_threads AS
350 SELECT f.thread_id FROM thread_families f
351 WHERE f.root_id IN (
352 SELECT root_id FROM (
353 SELECT
354 sf.root_id,
355 ROW_NUMBER() OVER (
356 PARTITION BY sf.project_id
357 ORDER BY sf.updated_at DESC
358 ) AS recency_rank
359 FROM stopped_families sf
360 JOIN kept_projects kp ON kp.project_id = sf.project_id
361 -- One orchestrator family can hold hundreds of subagents and most of
362 -- the database, so a family larger than the limit is skipped.
363 WHERE sf.size <= ${input.threadsPerProject}
364 )
365 WHERE recency_rank <= ${input.threadsPerProject}
366 )`;
367​
368 const threadTables = yield* sql<{ name: string }>`
369 SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c
370 WHERE m.type = 'table' AND c.name = 'thread_id'
371 AND m.name <> ${PROVIDER_SESSIONS_TABLE}`;
372​
373 yield* sql.withTransaction(
374 Effect.gen(function* () {
375 yield* sql`DELETE FROM projection_projects
376 WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
377 yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)}
378 WHERE COALESCE(thread_id, '') NOT IN (SELECT thread_id FROM kept_threads)
379 AND provider_session_id NOT IN (
380 SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings
381 WHERE thread_id IN (SELECT thread_id FROM kept_threads)
382 )`;
383 for (const { name } of threadTables) {
384 yield* sql.unsafe(
385 `DELETE FROM "${name}" WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
386 ).unprepared;
387 }
388 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers
389 WHERE source_thread_id NOT IN (SELECT thread_id FROM kept_threads)
390 OR target_thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
391 yield* sql`DELETE FROM orchestration_events
392 WHERE (aggregate_kind = 'thread'
393 AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
394 OR (aggregate_kind = 'project'
395 AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
396 for (const table of CLEARED_TABLES) {
397 yield* sql`DELETE FROM ${sql(table)}`;
398 }
399 }),
400 );
401​
402 const keptProjects = yield* sql<{ title: string; threads: number }>`
403 SELECT
404 p.title,
405 (SELECT COUNT(*) FROM orchestration_v2_projection_threads t
406 WHERE t.project_id = p.project_id) AS threads
407 FROM projection_projects p
408 ORDER BY p.updated_at DESC`;
409 const [events] = yield* sql<{ count: number }>`
410 SELECT COUNT(*) AS count FROM orchestration_events`;
411​
412 return {
413 projects: keptProjects as ReadonlyArray<KeptProject>,
414 eventCount: events?.count ?? 0,
415 };
416});
417​
418const verifyMigrationSlots = Effect.fn("verifyMigrationSlots")(function* () {
419 const sql = yield* SqlClient.SqlClient;
420 const applied = yield* sql<{ migration_id: number; name: string }>`
421 SELECT migration_id, name FROM effect_sql_migrations`;
422 const appliedById = new Map(applied.map((row) => [Number(row.migration_id), row.name]));
423 for (const [slot, codeName] of migrationManifest) {
424 const appliedName = appliedById.get(slot);
425 if (appliedName !== undefined && appliedName !== codeName) {
426 return yield* new MigrateDevDbSlotCollisionError({ slot, codeName, appliedName });
427 }
428 }
429});
430​
431export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
432 input: RunMigrateDevDbInput,
433 options: RunMigrateDevDbOptions = {},
434) {
435 // Negative SQLite LIMITs mean unlimited; validate direct callers as well as CLI flags.
436 if (input.projects < 1 || input.threadsPerProject < 0) {
437 return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
438 }
439 const fs = yield* FileSystem.FileSystem;
440 const path = yield* Path.Path;
441​
442 const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
443 const sourcePath = path.resolve(
444 input.source ?? path.join(sharedHome, "userdata", "statev2.sqlite"),
445 );
446​
447 const baseDir =
448 input.baseDir !== undefined
449 ? path.resolve(input.baseDir)
450 : yield* resolveWorktreeT3Home(process.cwd());
451 if (baseDir === undefined) {
452 return yield* new MigrateDevDbNotInWorktreeError();
453 }
454 const stateDir = path.join(baseDir, "userdata");
455 const databasePath = path.join(stateDir, "statev2.sqlite");
456 const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
457​
458 if (!(yield* fs.exists(sourcePath))) {
459 return yield* new MigrateDevDbSourceMissingError({ sourcePath });
460 }
461 const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
462 fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
463 fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
464 ]);
465 if (canonicalBaseDir === canonicalSharedHome) {
466 return yield* new MigrateDevDbSharedHomeError();
467 }
468 // Both destination and snapshot are deleted below; reject sources resolving to either.
469 const canonicalSourcePath = yield* fs
470 .realPath(sourcePath)
471 .pipe(Effect.orElseSucceed(() => sourcePath));
472 for (const destination of [databasePath, snapshotPath]) {
473 const canonicalDestination = yield* fs
474 .realPath(destination)
475 .pipe(Effect.orElseSucceed(() => destination));
476 if (canonicalSourcePath === canonicalDestination) {
477 return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
478 }
479 }
480​
481 yield* fs.makeDirectory(stateDir, { recursive: true });
482 yield* ensureNotInUse(databasePath);
483​
484 const wrapPhase =
485 (phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
486 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
487 effect.pipe(
488 Effect.mapError(
489 (cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
490 ),
491 );
492​
493 yield* removeDatabaseFiles(snapshotPath);
494 const { executedMigrations, pruned } = yield* Effect.gen(function* () {
495 yield* Console.log(`Copying visible threads from ${sourcePath} (read-only)...`);
496 yield* copySourceSlice(sourcePath).pipe(
497 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
498 wrapPhase("snapshot", sourcePath),
499 );
500​
501 // Migrate first so prune queries can use columns missing from older sources.
502 yield* Console.log("Running migrations on the snapshot...");
503 const executed = yield* Effect.gen(function* () {
504 const sql = yield* SqlClient.SqlClient;
505 yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
506 return yield* runMigrations();
507 }).pipe(
508 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
509 wrapPhase("migrate", snapshotPath),
510 );
511​
512 // Detect migration slot collisions before replacing the worktree database.
513 yield* verifyMigrationSlots().pipe(
514 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
515 Effect.catchTags({
516 SqlError: (cause) =>
517 Effect.fail(
518 new MigrateDevDbPhaseError({ phase: "verify", databasePath: snapshotPath, cause }),
519 ),
520 }),
521 );
522​
523 yield* Console.log(
524 `Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
525 );
526 const result = yield* pruneSnapshot(input).pipe(
527 Effect.provide(
528 ProjectionStore.layer.pipe(
529 Layer.provideMerge(NodeSqliteClient.layer({ filename: snapshotPath })),
530 ),
531 ),
532 wrapPhase("prune", snapshotPath),
533 );
534​
535 yield* Console.log(`Compacting into ${databasePath}...`);
536 // A server may have started during pruning; re-check before replacing its database.
537 yield* ensureNotInUse(databasePath);
538 yield* removeDatabaseFiles(databasePath);
539 yield* Effect.gen(function* () {
540 const sql = yield* SqlClient.SqlClient;
541 yield* sql`VACUUM INTO ${databasePath}`;
542 }).pipe(
543 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
544 wrapPhase("compact", databasePath),
545 );
546 return { executedMigrations: executed, pruned: result };
547 }).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
548 yield* fs.chmod(databasePath, 0o600);
549​
550 yield* Effect.gen(function* () {
551 const sql = yield* SqlClient.SqlClient;
552 // VACUUM INTO loses WAL mode; restore the server boot setting.
553 yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
554 }).pipe(
555 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
556 wrapPhase("compact", databasePath),
557 );
558​
559 const size = (yield* fs.stat(databasePath)).size;
560 return {
561 databasePath,
562 sizeBytes: Number(size),
563 projects: pruned.projects,
564 eventCount: pruned.eventCount,
565 executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
566 };
567});
568​
569const formatSize = (bytes: number): string =>
570 bytes >= 1024 * 1024
571 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
572 : `${(bytes / 1024).toFixed(0)} KB`;
573​
574export const migrateDevDbCommand = Command.make(
575 "migrate-dev-db",
576 {
577 projects: Flag.Int("projects").pipe(
578 Flag.withDefault(5),
579 Flag.withDescription("How many recently updated projects to keep."),
580 ),
581 threadsPerProject: Flag.Int("threads-per-project").pipe(
582 Flag.withDefault(10),
583 Flag.withDescription(
584 "How many recent stopped threads, with their forks and subagents, to keep per project. A family with more threads than this is skipped.",
585 ),
586 ),
587 baseDir: Flag.String("base-dir").pipe(
588 Flag.optional,
589 Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
590 ),
591 source: Flag.String("source").pipe(
592 Flag.optional,
593 Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),
594 ),
595 },
596 ({ projects, threadsPerProject, baseDir, source }) =>
597 Effect.gen(function* () {
598 const result = yield* runMigrateDevDb({
599 projects,
600 threadsPerProject,
601 baseDir: Option.getOrUndefined(baseDir),
602 source: Option.getOrUndefined(source),
603 });
604 yield* Console.log("");
605 yield* Console.log(
606 `Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
607 );
608 for (const project of result.projects) {
609 yield* Console.log(` ${project.title}: ${project.threads} threads`);
610 }
611 yield* Console.log(` ${result.eventCount} orchestration events kept`);
612 yield* Console.log(
613 result.executedMigrations.length === 0
614 ? " Migrations: already current (no new migrations in this checkout)"
615 : ` Migrations applied: ${result.executedMigrations.join(", ")}`,
616 );
617 }),
618).pipe(
619 Command.withDescription(
620 "Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
621 ),
622);
623​
624if (import.meta.main) {
625 Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
626 Effect.provide(NodeServices.layer),
627 NodeRuntime.runMain,
628 );