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