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

migrate-dev-db.ts

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