Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as NodeOS from "node:os";
7import * as NodeSqlite from "node:sqlite";
8import * as NodeURL from "node:url";
9import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
10import * as Console from "effect/Console";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as Schema from "effect/Schema";
17import * as SqlClient from "effect/sql/SqlClient";
18import { Command, Flag } from "effect/cli";
19
20import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
21import { rebuildMessageSearch } from "../src/orchestration-v2/messageSearchIndex.ts";
22import { runMigrations } from "../src/persistence/Migrations.ts";
23import * as HostProcess from "@t3tools/shared/HostProcess";
24import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
25
26export class MigrateDevDbNotInWorktreeError extends Schema.TaggedError<MigrateDevDbNotInWorktreeError>()(
27 "MigrateDevDbNotInWorktreeError",
28 {},
29) {
30 override get message(): string {
31 return "Not inside a linked git worktree. Pass --base-dir to target an isolated .t3 directory.";
32 }
33}
34
35export class MigrateDevDbSharedHomeError extends Schema.TaggedError<MigrateDevDbSharedHomeError>()(
36 "MigrateDevDbSharedHomeError",
37 {},
38) {
39 override get message(): string {
40 return "Refusing to rebuild the shared ~/.t3 database. Use an isolated --base-dir.";
41 }
42}
43
44export class MigrateDevDbSourceMissingError extends Schema.TaggedError<MigrateDevDbSourceMissingError>()(
45 "MigrateDevDbSourceMissingError",
46 {
47 sourcePath: Schema.String,
48 },
49) {
50 override get message(): string {
51 return `Source database does not exist at '${this.sourcePath}'.`;
52 }
53}
54
55export class MigrateDevDbSourceIsDestinationError extends Schema.TaggedError<MigrateDevDbSourceIsDestinationError>()(
56 "MigrateDevDbSourceIsDestinationError",
57 {
58 sourcePath: Schema.String,
59 },
60) {
61 override get message(): string {
62 return `Source database '${this.sourcePath}' resolves to a path this command rewrites. Pick a different --source or --base-dir.`;
63 }
64}
65
66export class MigrateDevDbLegacySourceError extends Schema.TaggedError<MigrateDevDbLegacySourceError>()(
67 "MigrateDevDbLegacySourceError",
68 {
69 sourcePath: Schema.String,
70 legacyThreads: Schema.Number,
71 },
72) {
73 override get message(): string {
74 return `Source database '${this.sourcePath}' holds ${this.legacyThreads} legacy threads the server has not imported into V2 yet, which this command cannot carry over. Start a server once on a T3 home holding a copy of it so it imports them, then pass the userdata/statev2.sqlite that server leaves behind as --source.`;
75 }
76}
77
78export class MigrateDevDbServerRunningError extends Schema.TaggedError<MigrateDevDbServerRunningError>()(
79 "MigrateDevDbServerRunningError",
80 {
81 databasePath: Schema.String,
82 pid: Schema.Number,
83 },
84) {
85 override get message(): string {
86 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.`;
87 }
88}
89
90export class MigrateDevDbDestinationBusyError extends Schema.TaggedError<MigrateDevDbDestinationBusyError>()(
91 "MigrateDevDbDestinationBusyError",
92 {
93 databasePath: Schema.String,
94 reason: Schema.Literals(["write-locked", "wal-held", "seed-running"]),
95 cause: Schema.optional(Schema.Defect()),
96 },
97) {
98 override get message(): string {
99 if (this.reason === "seed-running") {
100 return `Dev database at '${this.databasePath}' is busy: another seed is running. Try again after it finishes.`;
101 }
102 const detail =
103 this.reason === "write-locked"
104 ? "the database is write-locked"
105 : "another connection is holding its WAL";
106 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.`;
107 }
108}
109
110export class MigrateDevDbPhaseError extends Schema.TaggedError<MigrateDevDbPhaseError>()(
111 "MigrateDevDbPhaseError",
112 {
113 phase: Schema.Literals(["lock", "snapshot", "prune", "compact", "migrate"]),
114 databasePath: Schema.String,
115 cause: Schema.Defect(),
116 },
117) {
118 override get message(): string {
119 return `migrate-dev-db failed during ${this.phase} on '${this.databasePath}'.`;
120 }
121}
122
123export interface RunMigrateDevDbInput {
124 readonly baseDir?: string | undefined;
125 readonly source?: string | undefined;
126 readonly projects: number;
127 readonly threadsPerProject: number;
128}
129
130export interface RunMigrateDevDbOptions {
131 /** Test override for the directory writes must never target. */
132 readonly sharedHome?: string | undefined;
133}
134
135interface KeptProject {
136 readonly title: string;
137 readonly threads: number;
138}
139
140const removeDatabaseFiles = Effect.fn("removeDatabaseFiles")(function* (databasePath: string) {
141 const fs = yield* FileSystem.FileSystem;
142 for (const suffix of ["", "-wal", "-shm"]) {
143 yield* fs.remove(`${databasePath}${suffix}`).pipe(Effect.orElseSucceed(() => undefined));
144 }
145});
146
147const ServerRuntimeState = Schema.fromJsonString(Schema.Struct({ pid: Schema.Number }));
148const decodeServerRuntimeState = Schema.decodeEffect(ServerRuntimeState);
149
150const isProcessAlive = (pid: number): boolean => {
151 try {
152 process.kill(pid, 0);
153 return true;
154 } catch (error) {
155 // EPERM means the process exists but belongs to someone else.
156 return (error as NodeJS.ErrnoException).code === "EPERM";
157 }
158};
159
160// The runtime PID catches idle servers; leftover -shm files can come from read-only connections.
161const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {
162 const fs = yield* FileSystem.FileSystem;
163 const path = yield* Path.Path;
164
165 const runtimeStatePath = path.join(path.dirname(databasePath), "server-runtime.json");
166 const runtimeState = yield* fs
167 .readFileString(runtimeStatePath)
168 .pipe(Effect.flatMap(decodeServerRuntimeState), Effect.option);
169 if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
170 return yield* new MigrateDevDbServerRunningError({
171 databasePath,
172 pid: runtimeState.value.pid,
173 });
174 }
175
176 if (!(yield* fs.exists(databasePath))) {
177 return;
178 }
179 const checkpoint = yield* Effect.gen(function* () {
180 const sql = yield* SqlClient.SqlClient;
181 yield* sql.unsafe("PRAGMA busy_timeout = 0").unprepared;
182 yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;
183 yield* sql.unsafe("ROLLBACK").unprepared;
184 return yield* sql.unsafe<{ busy: number }>("PRAGMA wal_checkpoint(TRUNCATE)").unprepared;
185 }).pipe(
186 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
187 Effect.mapError(
188 (cause) =>
189 new MigrateDevDbDestinationBusyError({
190 databasePath,
191 reason: "write-locked",
192 cause,
193 }),
194 ),
195 );
196 if (checkpoint[0] !== undefined && Number(checkpoint[0].busy) !== 0) {
197 return yield* new MigrateDevDbDestinationBusyError({
198 databasePath,
199 reason: "wal-held",
200 });
201 }
202});
203
204// Every kind startup recovery resumes, so a copied family never starts work by itself. The record
205// fails typecheck when a kind is added and not listed here.
206const RECOVERY_KIND_SET = {
207 "queued-runs": true,
208 runtime: true,
209 "restart-continuations": true,
210 "subagent-results": true,
211 "delegated-completions": true,
212 "unread-steers": true,
213} satisfies Record<ProjectionStore.ProjectionRecoveryKind, true>;
214const RECOVERY_KINDS = Object.keys(
215 RECOVERY_KIND_SET,
216) as ReadonlyArray<ProjectionStore.ProjectionRecoveryKind>;
217
218const CLEARED_TABLES: ReadonlyArray<string> = [
219 "scheduled_tasks",
220 "orchestration_v2_effect_outbox",
221 "orchestration_v2_thread_launch_workflows",
222 "orchestration_command_receipts",
223 "provider_session_runtime",
224 "auth_sessions",
225 "auth_pairing_links",
226 "peer_environment_links",
227];
228
229const PROVIDER_SESSIONS_TABLE = "orchestration_v2_projection_provider_sessions";
230const FTS5_SHADOW_SUFFIXES = ["_data", "_idx", "_content", "_docsize", "_config"];
231
232// Settled threads stay: they are most of real history, and the UI shows them.
233const rootIsVisible = (sql: SqlClient.SqlClient) => sql`
234 root.deleted_at IS NULL
235 AND json_extract(root.payload_json, '$.deletedAt') IS NULL
236 AND json_extract(root.payload_json, '$.archivedAt') IS NULL`;
237
238// One read transaction keeps the copy, and its legacy-thread guard, consistent with concurrent
239// server writes. The server imports V1 threads at boot, and the copy keeps only threads with V2
240// rows, so unimported ones would vanish silently (see LegacyV1ThreadImporter.pendingThreadCount).
241const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath: string) {
242 const sql = yield* SqlClient.SqlClient;
243 yield* sql`ATTACH DATABASE ${`${NodeURL.pathToFileURL(sourcePath).href}?mode=ro`} AS src`;
244
245 yield* sql.withTransaction(
246 Effect.gen(function* () {
247 const schema = yield* sql<{ type: string; name: string; sql: string }>`
248 SELECT type, name, sql FROM src.sqlite_master
249 WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'`;
250 const threadColumns = yield* sql<{ name: string; notnull: number }>`
251 SELECT m.name, c."notnull" FROM src.sqlite_master m, pragma_table_info(m.name, 'src') c
252 WHERE m.type = 'table' AND c.name = 'thread_id'`;
253 const threadIdNullable = new Map(threadColumns.map((row) => [row.name, row.notnull === 0]));
254 // FTS5 makes its own shadow tables and contentless rows cannot be copied:
255 // create the virtual table, skip its shadow tables and rows, and rebuild the
256 // index once the messages and triggers are in.
257 const virtualTables = schema
258 .filter((entry) => entry.type === "table" && /^CREATE VIRTUAL TABLE/i.test(entry.sql))
259 .map((entry) => entry.name);
260 const isShadowTable = (name: string) =>
261 virtualTables.some((virtual) =>
262 FTS5_SHADOW_SUFFIXES.some((suffix) => name === `${virtual}${suffix}`),
263 );
264 const tables = schema.filter((entry) => entry.type === "table" && !isShadowTable(entry.name));
265 const filtered = tables.some((table) => table.name === "orchestration_v2_projection_threads");
266 // A row that points into a cleared table cannot be copied, so whatever references one is
267 // cleared with it, however far down the chain a newer migration added it.
268 const references = yield* sql<{ name: string; parent: string }>`
269 SELECT m.name, f."table" AS parent FROM src.sqlite_master m, pragma_foreign_key_list(m.name, 'src') f
270 WHERE m.type = 'table'`;
271 const cleared = new Set(CLEARED_TABLES);
272 for (let grew = true; grew;) {
273 grew = false;
274 for (const { name, parent } of references) {
275 if (cleared.has(parent) && !cleared.has(name)) {
276 cleared.add(name);
277 grew = true;
278 }
279 }
280 }
281
282 if (tables.some((table) => table.name === "projection_threads")) {
283 // The V2 tables, application_event_version, and the partial index arrive in
284 // the same migration. Without the hint SQLite scans each thread's stream.
285 const [pending] = filtered
286 ? yield* sql<{ count: number }>`
287 SELECT COUNT(*) AS count FROM src.projection_threads AS thread
288 WHERE NOT EXISTS (
289 SELECT 1
290 FROM src.orchestration_events AS event INDEXED BY orchestration_events_v2_created_threads_idx
291 WHERE event.application_event_version = 2
292 AND event.aggregate_kind = 'thread'
293 AND event.stream_id = thread.thread_id
294 AND event.event_type = 'thread.created'
295 )`
296 : yield* sql<{ count: number }>`SELECT COUNT(*) AS count FROM src.projection_threads`;
297 const legacyThreads = Number(pending?.count ?? 0);
298 if (legacyThreads > 0) {
299 return yield* new MigrateDevDbLegacySourceError({ sourcePath, legacyThreads });
300 }
301 }
302
303 for (const table of tables) yield* sql.unsafe(table.sql).unprepared;
304 if (filtered) {
305 yield* sql`CREATE TEMP TABLE copied_threads (thread_id TEXT PRIMARY KEY)`;
306 yield* sql`INSERT OR IGNORE INTO copied_threads
307 SELECT family.thread_id FROM src.orchestration_v2_projection_threads family
308 JOIN src.orchestration_v2_projection_threads root ON root.thread_id =
309 COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id)
310 WHERE ${rootIsVisible(sql)}`;
311 }
312 for (const { name } of tables) {
313 if (cleared.has(name) || virtualTables.includes(name)) continue;
314 const nullable = threadIdNullable.get(name);
315 const filter = !filtered
316 ? ""
317 : name === "orchestration_events"
318 ? // Two ranges let SQLite seek the (aggregate_kind, stream_id) index instead of scanning.
319 `WHERE (aggregate_kind = 'thread' AND stream_id IN (SELECT thread_id FROM copied_threads))
320 OR aggregate_kind < 'thread' OR aggregate_kind > 'thread'`
321 : nullable === undefined || name === PROVIDER_SESSIONS_TABLE
322 ? ""
323 : `WHERE thread_id IN (SELECT thread_id FROM copied_threads)${nullable ? " OR thread_id IS NULL" : ""}`;
324 yield* sql.unsafe(`INSERT INTO main."${name}" SELECT * FROM src."${name}" ${filter}`)
325 .unprepared;
326 }
327 yield* sql`DELETE FROM main.sqlite_sequence`;
328 yield* sql`INSERT INTO main.sqlite_sequence SELECT name, seq FROM src.sqlite_sequence`;
329 for (const entry of schema) {
330 if (entry.type !== "table") yield* sql.unsafe(entry.sql).unprepared;
331 }
332 yield* rebuildMessageSearch(sql);
333 }),
334 );
335 yield* sql`DETACH DATABASE src`;
336});
337
338/**
339 * Threads a server started on this database would resume by itself: every startup recovery kind,
340 * plus latest-run failures and recovery choices, which usage-limit recovery can resume.
341 */
342export const resumableThreadIds = Effect.fn("resumableDevDbThreadIds")(function* () {
343 const sql = yield* SqlClient.SqlClient;
344 const projections = yield* ProjectionStore.ProjectionStoreV2;
345 const recovery = yield* Effect.forEach(RECOVERY_KINDS, (kind) =>
346 projections.getRecoveryThreadIds(kind),
347 );
348 const failedOrRecovering = yield* sql<{ thread_id: string }>`
349 SELECT r.thread_id FROM orchestration_v2_projection_runs r
350 WHERE r.status = 'failed' AND r.ordinal = (
351 SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest
352 WHERE latest.thread_id = r.thread_id)
353 UNION
354 SELECT thread_id FROM orchestration_v2_projection_threads
355 WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`;
356 return [
357 ...new Set<string>([...recovery.flat(), ...failedOrRecovering.map((row) => row.thread_id)]),
358 ];
359});
360
361export class MigrateDevDbResumableWorkError extends Schema.TaggedError<MigrateDevDbResumableWorkError>()(
362 "MigrateDevDbResumableWorkError",
363 { databasePath: Schema.String, threads: Schema.Number },
364) {
365 override get message() {
366 return `${this.databasePath} still holds ${this.threads} threads a server would resume.`;
367 }
368}
369
370/**
371 * Drops, in place, every thread family a server started on `databasePath` would resume, and fails
372 * if any remain. A database seeded by an older checkout can miss a recovery kind added since.
373 */
374export const dropResumableFamilies = Effect.fn("dropResumableDevDbFamilies")(function* (
375 databasePath: string,
376 options: RunMigrateDevDbOptions = {},
377) {
378 const fs = yield* FileSystem.FileSystem;
379 const path = yield* Path.Path;
380 const platform = yield* HostProcess.Platform;
381 // A symlink, `..` or another letter case can name the live database; compare where they lead.
382 const resolve = (file: string) =>
383 fs.realPath(file).pipe(
384 Effect.catch(() =>
385 fs
386 .realPath(path.dirname(file))
387 .pipe(Effect.map((dir) => path.join(dir, path.basename(file)))),
388 ),
389 Effect.orElseSucceed(() => path.resolve(file)),
390 );
391 const comparable = (resolved: string) =>
392 platform === "linux" ? resolved : resolved.toLowerCase();
393 // A hard link has its own path, so the file itself is compared too.
394 const identity = (file: string) =>
395 fs.stat(file).pipe(
396 Effect.map((info) => Option.map(info.ino, (ino) => `${info.dev}:${ino}`)),
397 Effect.orElseSucceed(() => Option.none<string>()),
398 );
399 const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
400 const liveDatabase = path.join(sharedHome, "userdata", "statev2.sqlite");
401 const [target, live] = yield* Effect.all([resolve(databasePath), resolve(liveDatabase)]);
402 const targetIdentity = yield* identity(target);
403 const liveIdentities = yield* Effect.forEach(
404 [liveDatabase, `${liveDatabase}-wal`, `${liveDatabase}-shm`],
405 identity,
406 );
407 if (
408 comparable(target) === comparable(live) ||
409 (Option.isSome(targetIdentity) &&
410 liveIdentities.some(
411 (candidate) => Option.isSome(candidate) && candidate.value === targetIdentity.value,
412 ))
413 ) {
414 return yield* new MigrateDevDbSharedHomeError();
415 }
416 // Beside the real file, where a running server keeps its runtime state.
417 yield* ensureNotInUse(target);
418 return yield* Effect.gen(function* () {
419 const sql = yield* SqlClient.SqlClient;
420 const resumable = yield* resumableThreadIds();
421 if (resumable.length > 0) {
422 yield* sql`CREATE TEMP TABLE resumable_families (thread_id TEXT PRIMARY KEY)`;
423 yield* sql`INSERT OR IGNORE INTO resumable_families
424 SELECT family.thread_id FROM orchestration_v2_projection_threads family
425 WHERE COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id) IN (
426 SELECT COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id)
427 FROM orchestration_v2_projection_threads WHERE thread_id IN ${sql.in(resumable)})`;
428 yield* sql.withTransaction(
429 Effect.gen(function* () {
430 for (const { name } of yield* sql<{ name: string }>`
431 SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c
432 WHERE m.type = 'table' AND c.name = 'thread_id'
433 AND m.name <> ${PROVIDER_SESSIONS_TABLE}`) {
434 yield* sql`DELETE FROM ${sql(name)}
435 WHERE thread_id IN (SELECT thread_id FROM resumable_families)`;
436 }
437 // A session a kept thread still binds stays, as pruning keeps it.
438 yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)}
439 WHERE thread_id IN (SELECT thread_id FROM resumable_families)
440 AND provider_session_id NOT IN (
441 SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings
442 WHERE thread_id NOT IN (SELECT thread_id FROM resumable_families)
443 )`;
444 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers
445 WHERE source_thread_id IN (SELECT thread_id FROM resumable_families)
446 OR target_thread_id IN (SELECT thread_id FROM resumable_families)`;
447 yield* sql`DELETE FROM orchestration_events WHERE aggregate_kind = 'thread'
448 AND stream_id IN (SELECT thread_id FROM resumable_families)`;
449 }),
450 );
451 }
452 const left = yield* resumableThreadIds();
453 if (left.length > 0) {
454 return yield* new MigrateDevDbResumableWorkError({ databasePath, threads: left.length });
455 }
456 return resumable.length;
457 }).pipe(
458 Effect.provide(
459 ProjectionStore.layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename: target }))),
460 ),
461 );
462});
463
464const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
465 const sql = yield* SqlClient.SqlClient;
466
467 yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`;
468 for (const threadId of yield* resumableThreadIds()) {
469 yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`;
470 }
471
472 // Clone or drop whole thread families to preserve fork and subagent lineage reads.
473 yield* sql`CREATE TEMP TABLE thread_families AS
474 SELECT thread_id, updated_at,
475 COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id) AS root_id
476 FROM orchestration_v2_projection_threads`;
477
478 yield* sql`CREATE TEMP TABLE stopped_families AS
479 SELECT f.root_id, root.project_id, MAX(f.updated_at) AS updated_at, COUNT(*) AS size
480 FROM thread_families f
481 JOIN orchestration_v2_projection_threads root ON root.thread_id = f.root_id
482 WHERE ${rootIsVisible(sql)}
483 GROUP BY f.root_id, root.project_id
484 HAVING SUM(f.thread_id IN (SELECT thread_id FROM live_threads)) = 0`;
485
486 yield* sql`CREATE TEMP TABLE kept_projects AS
487 SELECT p.project_id
488 FROM projection_projects p
489 LEFT JOIN (
490 SELECT project_id, MAX(updated_at) AS last_stopped_at
491 FROM stopped_families
492 GROUP BY project_id
493 ) q ON q.project_id = p.project_id
494 WHERE p.deleted_at IS NULL
495 ORDER BY (q.last_stopped_at IS NULL) ASC,
496 COALESCE(q.last_stopped_at, p.updated_at) DESC
497 LIMIT ${input.projects}`;
498
499 yield* sql`CREATE TEMP TABLE kept_threads AS
500 SELECT f.thread_id FROM thread_families f
501 WHERE f.root_id IN (
502 SELECT root_id FROM (
503 SELECT
504 sf.root_id,
505 ROW_NUMBER() OVER (
506 PARTITION BY sf.project_id
507 ORDER BY sf.updated_at DESC
508 ) AS recency_rank
509 FROM stopped_families sf
510 JOIN kept_projects kp ON kp.project_id = sf.project_id
511 -- One orchestrator family can hold hundreds of subagents and most of
512 -- the database, so a family larger than the limit is skipped.
513 WHERE sf.size <= ${input.threadsPerProject}
514 )
515 WHERE recency_rank <= ${input.threadsPerProject}
516 )`;
517
518 const threadTables = yield* sql<{ name: string }>`
519 SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c
520 WHERE m.type = 'table' AND c.name = 'thread_id'
521 AND m.name <> ${PROVIDER_SESSIONS_TABLE}`;
522
523 yield* sql.withTransaction(
524 Effect.gen(function* () {
525 yield* sql`DELETE FROM projection_projects
526 WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
527 yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)}
528 WHERE COALESCE(thread_id, '') NOT IN (SELECT thread_id FROM kept_threads)
529 AND provider_session_id NOT IN (
530 SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings
531 WHERE thread_id IN (SELECT thread_id FROM kept_threads)
532 )`;
533 for (const { name } of threadTables) {
534 yield* sql.unsafe(
535 `DELETE FROM "${name}" WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
536 ).unprepared;
537 }
538 yield* sql`DELETE FROM orchestration_v2_projection_context_transfers
539 WHERE source_thread_id NOT IN (SELECT thread_id FROM kept_threads)
540 OR target_thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
541 yield* sql`DELETE FROM orchestration_events
542 WHERE (aggregate_kind = 'thread'
543 AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
544 OR (aggregate_kind = 'project'
545 AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
546 yield* sql`UPDATE orchestration_v2_projection_threads
547 SET payload_json = json_set(payload_json, '$.pullRequests', json((
548 SELECT json_group_array(json_remove(link.value, '$.watch') ORDER BY link.key)
549 FROM json_each(payload_json, '$.pullRequests') AS link)))
550 WHERE EXISTS (
551 SELECT 1 FROM json_each(payload_json, '$.pullRequests') AS link
552 WHERE json_extract(link.value, '$.watch') IS NOT NULL)`;
553 // Copied threads keep their real worktree paths, where a settle script would run.
554 yield* sql`UPDATE projection_projects
555 SET scripts_json = (
556 SELECT json_group_array(json_remove(script.value, '$.runOnSettle') ORDER BY script.key)
557 FROM json_each(scripts_json) AS script)
558 WHERE EXISTS (
559 SELECT 1 FROM json_each(scripts_json) AS script
560 WHERE json_extract(script.value, '$.runOnSettle') IS NOT NULL)`;
561 for (const table of CLEARED_TABLES) {
562 yield* sql`DELETE FROM ${sql(table)}`;
563 }
564 }),
565 );
566
567 const keptProjects = yield* sql<{ title: string; threads: number }>`
568 SELECT
569 p.title,
570 (SELECT COUNT(*) FROM orchestration_v2_projection_threads t
571 WHERE t.project_id = p.project_id) AS threads
572 FROM projection_projects p
573 ORDER BY p.updated_at DESC`;
574 const [events] = yield* sql<{ count: number }>`
575 SELECT COUNT(*) AS count FROM orchestration_events`;
576
577 return {
578 projects: keptProjects as ReadonlyArray<KeptProject>,
579 eventCount: events?.count ?? 0,
580 };
581});
582
583// Peer links preview builds recorded 68-70 before main took those slots for other migrations.
584// A snapshot with exactly that history drops the preview's schema so main's 68+ can run.
585const PEER_LINKS_PREVIEW_HISTORY = [
586 "68:PeerLinks",
587 "69:PeerLinkFence",
588 "70:WaitingLinkRequestIndex",
589];
590
591const forgetPeerLinksPreviewHistory = Effect.fn("forgetPeerLinksPreviewHistory")(function* () {
592 const sql = yield* SqlClient.SqlClient;
593 const tables = yield* sql`
594 SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'`;
595 if (tables.length === 0) return;
596 const tail = yield* sql<{ migration_id: number; name: string }>`
597 SELECT migration_id, name FROM effect_sql_migrations WHERE migration_id >= 68
598 ORDER BY migration_id`;
599 const history = tail.map((row) => `${row.migration_id}:${row.name}`);
600 if (history.join() !== PEER_LINKS_PREVIEW_HISTORY.join()) return;
601 yield* sql.withTransaction(
602 Effect.gen(function* () {
603 yield* sql`DROP INDEX IF EXISTS orchestration_v2_projection_turn_items_waiting_link_idx`;
604 yield* sql`DROP TABLE IF EXISTS peer_environment_links`;
605 yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id >= 68`;
606 }),
607 );
608});
609
610const SQLITE_BUSY = 5;
611
612export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
613 input: RunMigrateDevDbInput,
614 options: RunMigrateDevDbOptions = {},
615) {
616 // Negative SQLite LIMITs mean unlimited; validate direct callers as well as CLI flags.
617 if (input.projects < 1 || input.threadsPerProject < 0) {
618 return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
619 }
620 const fs = yield* FileSystem.FileSystem;
621 const path = yield* Path.Path;
622
623 const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
624 const sourcePath = path.resolve(
625 input.source ?? path.join(sharedHome, "userdata", "statev2.sqlite"),
626 );
627
628 const baseDir =
629 input.baseDir !== undefined
630 ? path.resolve(input.baseDir)
631 : yield* resolveWorktreeT3Home(process.cwd());
632 if (baseDir === undefined) {
633 return yield* new MigrateDevDbNotInWorktreeError();
634 }
635 const stateDir = path.join(baseDir, "userdata");
636 const databasePath = path.join(stateDir, "statev2.sqlite");
637 const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
638 const lockPath = path.join(stateDir, "migrate-dev-db-lock.sqlite");
639
640 if (!(yield* fs.exists(sourcePath))) {
641 return yield* new MigrateDevDbSourceMissingError({ sourcePath });
642 }
643 const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
644 fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
645 fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
646 ]);
647 if (canonicalBaseDir === canonicalSharedHome) {
648 return yield* new MigrateDevDbSharedHomeError();
649 }
650 // The seed deletes or writes each of these paths; reject sources resolving to any of them.
651 const canonicalSourcePath = yield* fs
652 .realPath(sourcePath)
653 .pipe(Effect.orElseSucceed(() => sourcePath));
654 for (const destination of [databasePath, snapshotPath, lockPath]) {
655 const canonicalDestination = yield* fs
656 .realPath(destination)
657 .pipe(Effect.orElseSucceed(() => destination));
658 if (canonicalSourcePath === canonicalDestination) {
659 return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
660 }
661 }
662
663 yield* fs.makeDirectory(stateDir, { recursive: true });
664 // Held until the seed exits so a second seed cannot delete this one's snapshot or destination.
665 const seedLock = yield* Effect.acquireRelease(
666 Effect.try({
667 try: () => new NodeSqlite.DatabaseSync(lockPath, { timeout: 0 }),
668 catch: (cause) => new MigrateDevDbPhaseError({ phase: "lock", databasePath, cause }),
669 }),
670 (db) => Effect.sync(() => db.close()),
671 );
672 yield* Effect.try({
673 try: () => seedLock.exec("BEGIN IMMEDIATE"),
674 catch: (cause) =>
675 cause instanceof Error && "errcode" in cause && cause.errcode === SQLITE_BUSY
676 ? new MigrateDevDbDestinationBusyError({ databasePath, reason: "seed-running", cause })
677 : new MigrateDevDbPhaseError({ phase: "lock", databasePath, cause }),
678 });
679
680 const wrapPhase =
681 (phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
682 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
683 effect.pipe(
684 Effect.mapError(
685 (cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
686 ),
687 );
688
689 yield* removeDatabaseFiles(snapshotPath);
690 const { executedMigrations, pruned } = yield* Effect.gen(function* () {
691 yield* Console.log(`Copying visible threads from ${sourcePath} (read-only)...`);
692 yield* copySourceSlice(sourcePath).pipe(
693 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
694 Effect.catchTags({
695 SqlError: (cause) =>
696 Effect.fail(
697 new MigrateDevDbPhaseError({ phase: "snapshot", databasePath: sourcePath, cause }),
698 ),
699 }),
700 );
701 // Checkpoints the destination, so it runs after the copy's legacy guard.
702 yield* ensureNotInUse(databasePath);
703
704 // Migrate first so prune queries can use columns missing from older sources.
705 yield* Console.log("Running migrations on the snapshot...");
706 const executed = yield* Effect.gen(function* () {
707 const sql = yield* SqlClient.SqlClient;
708 yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
709 yield* forgetPeerLinksPreviewHistory();
710 return yield* runMigrations();
711 }).pipe(
712 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
713 wrapPhase("migrate", snapshotPath),
714 );
715
716 yield* Console.log(
717 `Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
718 );
719 const result = yield* pruneSnapshot(input).pipe(
720 Effect.provide(
721 ProjectionStore.layer.pipe(
722 Layer.provideMerge(NodeSqliteClient.layer({ filename: snapshotPath })),
723 ),
724 ),
725 wrapPhase("prune", snapshotPath),
726 );
727
728 yield* Console.log(`Compacting into ${databasePath}...`);
729 // A server may have started during pruning; re-check before replacing its database.
730 yield* ensureNotInUse(databasePath);
731 yield* removeDatabaseFiles(databasePath);
732 yield* Effect.gen(function* () {
733 const sql = yield* SqlClient.SqlClient;
734 yield* sql`VACUUM INTO ${databasePath}`;
735 }).pipe(
736 Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
737 wrapPhase("compact", databasePath),
738 );
739 return { executedMigrations: executed, pruned: result };
740 }).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
741 yield* fs.chmod(databasePath, 0o600);
742
743 yield* Effect.gen(function* () {
744 const sql = yield* SqlClient.SqlClient;
745 // VACUUM INTO loses WAL mode; restore the server boot setting.
746 yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
747 }).pipe(
748 Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
749 wrapPhase("compact", databasePath),
750 );
751
752 const size = (yield* fs.stat(databasePath)).size;
753 return {
754 databasePath,
755 sizeBytes: Number(size),
756 projects: pruned.projects,
757 eventCount: pruned.eventCount,
758 executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
759 };
760}, Effect.scoped);
761
762const formatSize = (bytes: number): string =>
763 bytes >= 1024 * 1024
764 ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
765 : `${(bytes / 1024).toFixed(0)} KB`;
766
767export const migrateDevDbCommand = Command.make(
768 "migrate-dev-db",
769 {
770 projects: Flag.Int("projects").pipe(
771 Flag.withDefault(5),
772 Flag.withDescription("How many recently updated projects to keep."),
773 ),
774 threadsPerProject: Flag.Int("threads-per-project").pipe(
775 Flag.withDefault(10),
776 Flag.withDescription(
777 "How many recent stopped threads, with their forks and subagents, to keep per project. A family with more threads than this is skipped.",
778 ),
779 ),
780 baseDir: Flag.String("base-dir").pipe(
781 Flag.optional,
782 Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
783 ),
784 source: Flag.String("source").pipe(
785 Flag.optional,
786 Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),
787 ),
788 dropResumable: Flag.String("drop-resumable").pipe(
789 Flag.optional,
790 Flag.withDescription(
791 "Only drop, in place, the thread families a server started on this database would resume, and fail if any remain. Copies only; never the live database.",
792 ),
793 ),
794 },
795 ({ projects, threadsPerProject, baseDir, source, dropResumable }) =>
796 Effect.gen(function* () {
797 if (Option.isSome(dropResumable)) {
798 const dropped = yield* dropResumableFamilies(dropResumable.value);
799 yield* Console.log(`Dropped ${dropped} resumable threads.`);
800 return;
801 }
802 const result = yield* runMigrateDevDb({
803 projects,
804 threadsPerProject,
805 baseDir: Option.getOrUndefined(baseDir),
806 source: Option.getOrUndefined(source),
807 });
808 yield* Console.log("");
809 yield* Console.log(
810 `Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
811 );
812 for (const project of result.projects) {
813 yield* Console.log(` ${project.title}: ${project.threads} threads`);
814 }
815 yield* Console.log(` ${result.eventCount} orchestration events kept`);
816 yield* Console.log(
817 result.executedMigrations.length === 0
818 ? " Migrations: already current (no new migrations in this checkout)"
819 : ` Migrations applied: ${result.executedMigrations.join(", ")}`,
820 );
821 }),
822).pipe(
823 Command.withDescription(
824 "Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
825 ),
826);
827
828if (import.meta.main) {
829 Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
830 Effect.provide(Layer.merge(NodeServices.layer, NodeCrypto.layerDigest)),
831 NodeRuntime.runMain,
832 );
833}