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