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