Add dev:seed to populate an isolated dev database

An isolated dev database starts empty, which makes any list- or
thread-shaped UI impossible to look at without hand-writing fixtures.
`dev:seed` copies the newest threads and their projects out of the
shared home into the worktree's own database.

Projections only — `orchestration_events` is never copied. The projector
cursor is exclusive, so an empty event log means bootstrap streams
nothing and leaves the copied rows alone; a partial event range is the
real hazard, since the projector would replay a tail whose creating
events are missing.

Details that matter for a usable copy:
- writes all nine projection_state rows, or computeSnapshotSequence
  reports 0 for every shell snapshot
- forces sessions to stopped with no active turn, since a copied
  "running" session has no agent behind it and the reaper skips
  anything with an active turn
- zeroes pending approval/input counts, as approvals are not copied
- copies the intersection of columns, because the two databases are
  routinely on different migrations
- refuses to write to the shared home

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5 committed 2026-07-25 19:27:47 -07:00
1 parent dcae11d6fb
commit 18aadeff7c
7 files changed
+898

No files matched your search

+175
View File
@@ -0,0 +1,175 @@
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeOS from "node:os";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { Command, Flag } from "effect/unstable/cli";
import { DevSeedError, seedDevDatabase } from "./lib/dev-seed.ts";
const DEFAULT_THREAD_LIMIT = 25;
const DEFAULT_ACTIVITY_LIMIT = 200;
class DevSeedTargetError extends Schema.TaggedErrorClass<DevSeedTargetError>()(
"DevSeedTargetError",
{
reason: Schema.Literals(["shared-home", "missing-target", "not-a-worktree"]),
detail: Schema.String,
},
) {
override get message(): string {
switch (this.reason) {
case "shared-home":
return [
`Refusing to seed ${this.detail}: that is the shared T3 Code home.`,
"This command overwrites projection tables. Run it from a worktree, or pass --to <base-dir>.",
].join("\n");
case "missing-target":
return [
`No database at ${this.detail}.`,
"Start the dev server once so migrations run (`bun run dev`), then seed.",
].join("\n");
case "not-a-worktree":
return [
"Not inside a git worktree, so there is no worktree-local data directory to seed.",
"Pass --to <base-dir> to choose one explicitly.",
].join("\n");
}
}
}
const stateDbPath = (path: Path.Path, baseDir: string) =>
path.join(baseDir, "userdata", "state.sqlite");
/** The worktree's own `.t3`, matching what the dev runner uses. */
const resolveDefaultTarget = Effect.fn("devSeed.resolveDefaultTarget")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = process.cwd();
const gitInfo = yield* fileSystem.stat(path.join(cwd, ".git")).pipe(Effect.option);
if (Option.isNone(gitInfo) || gitInfo.value.type !== "File") {
return undefined;
}
return path.join(cwd, ".t3");
});
const devSeedCli = Command.make("dev-seed", {
from: Flag.string("from").pipe(
Flag.withDescription(
"Base directory to copy from (default: the shared T3 Code home, ~/.t3). Read-only.",
),
Flag.optional,
Flag.map(Option.getOrUndefined),
),
to: Flag.string("to").pipe(
Flag.withDescription(
"Base directory to seed (default: this worktree's .t3). Its projection tables are replaced.",
),
Flag.optional,
Flag.map(Option.getOrUndefined),
),
threads: Flag.integer("threads").pipe(
Flag.withDescription(
`How many recent threads to copy (default ${String(DEFAULT_THREAD_LIMIT)}).`,
),
Flag.withDefault(DEFAULT_THREAD_LIMIT),
),
activities: Flag.integer("activities").pipe(
Flag.withDescription(
`Newest activities kept per thread (default ${String(DEFAULT_ACTIVITY_LIMIT)}).`,
),
Flag.withDefault(DEFAULT_ACTIVITY_LIMIT),
),
}).pipe(
Command.withDescription(
"Copy recent projects and threads from a T3 Code data directory into an isolated dev one.",
),
Command.withHandler((input) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedHome = path.join(NodeOS.homedir(), ".t3");
const sourceBaseDir = input.from ? path.resolve(input.from) : sharedHome;
const defaultTarget = yield* resolveDefaultTarget();
const targetBaseDir = input.to ? path.resolve(input.to) : defaultTarget;
if (targetBaseDir === undefined) {
return yield* new DevSeedTargetError({ reason: "not-a-worktree", detail: process.cwd() });
}
// The whole point is to keep dev data off the real home; overwriting it
// here would be the exact accident this command exists to avoid.
const [canonicalTarget, canonicalShared] = yield* Effect.all([
fileSystem.realPath(targetBaseDir).pipe(Effect.orElseSucceed(() => targetBaseDir)),
fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
]);
if (canonicalTarget === canonicalShared) {
return yield* new DevSeedTargetError({ reason: "shared-home", detail: targetBaseDir });
}
const targetDbPath = stateDbPath(path, targetBaseDir);
if (!(yield* fileSystem.exists(targetDbPath))) {
return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });
}
const seededAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
const summary = yield* Effect.try({
try: () =>
seedDevDatabase({
sourceDbPath: stateDbPath(path, sourceBaseDir),
targetDbPath,
threadLimit: input.threads,
activityLimit: input.activities,
seededAt,
}),
catch: (cause) => cause as DevSeedError,
});
yield* Console.log(
[
`Seeded ${targetDbPath}`,
` from ${stateDbPath(path, sourceBaseDir)}`,
` projects ${String(summary.projects)}`,
` threads ${String(summary.threads)}`,
` messages ${String(summary.messages)}`,
` activity ${String(summary.activities)}`,
` turns ${String(summary.turns)} sessions ${String(summary.sessions)}`,
...(summary.skippedColumns.length > 0
? [
` note: skipped ${String(summary.skippedColumns.length)} column(s) absent from the target schema`,
` (${summary.skippedColumns.join(", ")})`,
]
: []),
"",
"Restart the dev server to pick it up.",
].join("\n"),
);
}).pipe(
Effect.tapError((error) =>
Effect.logError(
error instanceof DevSeedError
? `${error.message}${error.hint ? `\n${error.hint}` : ""}`
: error.message,
),
),
),
),
);
if (import.meta.main) {
Command.run(devSeedCli, { version: "0.0.0" }).pipe(
Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
NodeRuntime.runMain,
);
}
+326
View File
@@ -0,0 +1,326 @@
// @effect-diagnostics nodeBuiltinImport:off - test fixtures build real SQLite files on disk.
import { assert, describe, it } from "@effect/vitest";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeSqlite from "node:sqlite";
import { DevSeedError, seedDevDatabase } from "./dev-seed.ts";
const SEEDED_AT = "2026-07-26T00:00:00.000Z";
/**
* The subset of the real schema the seeder touches. `monitor_json` is included
* only in the source, to stand in for the migration drift between an installed
* app and a worktree that is a migration behind.
*/
function createSchema(
database: NodeSqlite.DatabaseSync,
options: { readonly withMonitor: boolean },
) {
database.exec(`CREATE TABLE projection_projects (
project_id TEXT PRIMARY KEY, title TEXT NOT NULL, workspace_root TEXT NOT NULL,
scripts_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT)`);
database.exec(`CREATE TABLE projection_threads (
thread_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, title TEXT NOT NULL,
latest_turn_id TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
deleted_at TEXT, archived_at TEXT, latest_user_message_at TEXT,
pending_approval_count INTEGER NOT NULL DEFAULT 0,
pending_user_input_count INTEGER NOT NULL DEFAULT 0
${options.withMonitor ? ", monitor_json TEXT" : ""})`);
database.exec(`CREATE TABLE projection_thread_messages (
message_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, role TEXT NOT NULL,
text TEXT NOT NULL, is_streaming INTEGER NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL)`);
database.exec(`CREATE TABLE projection_thread_activities (
activity_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, tone TEXT NOT NULL,
kind TEXT NOT NULL, summary TEXT NOT NULL, payload_json TEXT NOT NULL,
created_at TEXT NOT NULL)`);
database.exec(`CREATE TABLE projection_thread_sessions (
thread_id TEXT PRIMARY KEY, status TEXT NOT NULL, provider_name TEXT,
active_turn_id TEXT, last_error TEXT, updated_at TEXT NOT NULL)`);
database.exec(`CREATE TABLE projection_turns (
row_id INTEGER PRIMARY KEY AUTOINCREMENT, thread_id TEXT NOT NULL, turn_id TEXT,
state TEXT NOT NULL, requested_at TEXT NOT NULL, checkpoint_files_json TEXT NOT NULL,
UNIQUE (thread_id, turn_id))`);
database.exec(`CREATE TABLE projection_thread_proposed_plans (
plan_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, plan_markdown TEXT NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL)`);
database.exec(`CREATE TABLE projection_pending_approvals (
request_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, status TEXT NOT NULL,
created_at TEXT NOT NULL)`);
database.exec(`CREATE TABLE projection_state (
projector TEXT PRIMARY KEY, last_applied_sequence INTEGER NOT NULL, updated_at TEXT NOT NULL)`);
}
/** Source DB with `threadCount` threads, oldest first so recency ordering is testable. */
function makeSource(path: string, threadCount: number, activitiesPerThread = 3) {
const database = new NodeSqlite.DatabaseSync(path);
createSchema(database, { withMonitor: true });
database
.prepare(
`INSERT INTO projection_projects VALUES ('p1','Project','/repo','[]','${SEEDED_AT}','${SEEDED_AT}',NULL)`,
)
.run();
for (let index = 0; index < threadCount; index += 1) {
const threadId = `t${String(index)}`;
// Later index → later timestamp → more recent.
const at = `2026-07-${String(10 + index).padStart(2, "0")}T00:00:00.000Z`;
database
.prepare(
`INSERT INTO projection_threads (thread_id, project_id, title, latest_turn_id,
created_at, updated_at, latest_user_message_at, pending_approval_count,
pending_user_input_count, monitor_json)
VALUES (?,?,?,?,?,?,?,?,?,?)`,
)
.run(threadId, "p1", `Thread ${String(index)}`, `turn-${threadId}`, at, at, at, 4, 2, "{}");
database
.prepare(
`INSERT INTO projection_turns (thread_id, turn_id, state, requested_at, checkpoint_files_json)
VALUES (?,?,?,?,'[]')`,
)
.run(threadId, `turn-${threadId}`, "completed", at);
database
.prepare(`INSERT INTO projection_thread_sessions VALUES (?,'running','claude',?,'boom',?)`)
.run(threadId, `turn-${threadId}`, at);
database
.prepare(`INSERT INTO projection_thread_messages VALUES (?,?, 'user','hello',0,?,?)`)
.run(`m-${threadId}`, threadId, at, at);
for (let a = 0; a < activitiesPerThread; a += 1) {
database
.prepare(`INSERT INTO projection_thread_activities VALUES (?,?,'neutral','tool','ran',?,?)`)
.run(`a-${threadId}-${String(a)}`, threadId, "{}", `2026-07-10T00:00:0${String(a)}.000Z`);
}
}
database.close();
}
function makeTarget(path: string) {
const database = new NodeSqlite.DatabaseSync(path);
// No monitor_json: the target is a migration behind, as a worktree often is.
createSchema(database, { withMonitor: false });
database
.prepare(
`INSERT INTO projection_projects VALUES ('stale','Stale','/old','[]','${SEEDED_AT}','${SEEDED_AT}',NULL)`,
)
.run();
database.close();
}
const withDatabases = <A>(
run: (paths: { readonly source: string; readonly target: string }) => A,
options?: { readonly threads?: number; readonly activities?: number },
): A => {
const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-dev-seed-"));
const source = NodePath.join(directory, "source.sqlite");
const target = NodePath.join(directory, "target.sqlite");
makeSource(source, options?.threads ?? 5, options?.activities ?? 3);
makeTarget(target);
try {
return run({ source, target });
} finally {
NodeFS.rmSync(directory, { recursive: true, force: true });
}
};
const query = <T>(path: string, sql: string): Array<T> => {
const database = new NodeSqlite.DatabaseSync(path, { readOnly: true });
try {
return database.prepare(sql).all() as Array<T>;
} finally {
database.close();
}
};
describe("seedDevDatabase", () => {
it("copies the most recent threads and their project", () => {
withDatabases(({ source, target }) => {
const summary = seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 2,
activityLimit: 10,
seededAt: SEEDED_AT,
});
assert.equal(summary.threads, 2);
assert.equal(summary.projects, 1);
const titles = query<{ title: string }>(
target,
"SELECT title FROM projection_threads ORDER BY latest_user_message_at DESC",
).map((row) => row.title);
// Threads 4 and 3 are the newest of the five.
assert.deepStrictEqual(titles, ["Thread 4", "Thread 3"]);
});
});
it("replaces whatever the target held before", () => {
withDatabases(({ source, target }) => {
seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 1,
activityLimit: 10,
seededAt: SEEDED_AT,
});
const projects = query<{ project_id: string }>(
target,
"SELECT project_id FROM projection_projects",
).map((row) => row.project_id);
assert.deepStrictEqual(projects, ["p1"]);
});
});
// The target can be a migration behind the source; copying its columns
// blindly would fail on the first schema change.
it("skips columns the target does not have", () => {
withDatabases(({ source, target }) => {
const summary = seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 1,
activityLimit: 10,
seededAt: SEEDED_AT,
});
assert.deepStrictEqual(summary.skippedColumns, ["projection_threads.monitor_json"]);
assert.equal(summary.threads, 1);
});
});
// A copied "running" session has no agent behind it, so the thread would spin
// forever and the session reaper would skip it.
it("neutralizes live session state", () => {
withDatabases(({ source, target }) => {
seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 3,
activityLimit: 10,
seededAt: SEEDED_AT,
});
const sessions = query<{ status: string; active_turn_id: string | null }>(
target,
"SELECT status, active_turn_id FROM projection_thread_sessions",
);
assert.isAbove(sessions.length, 0);
for (const session of sessions) {
assert.equal(session.status, "stopped");
assert.isNull(session.active_turn_id);
}
});
});
// Approvals are not copied, so the badge counts must not survive.
it("clears pending counts that have no rows behind them", () => {
withDatabases(({ source, target }) => {
seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 3,
activityLimit: 10,
seededAt: SEEDED_AT,
});
const [counts] = query<{ approvals: number; inputs: number }>(
target,
"SELECT SUM(pending_approval_count) approvals, SUM(pending_user_input_count) inputs FROM projection_threads",
);
assert.equal(counts?.approvals, 0);
assert.equal(counts?.inputs, 0);
});
});
it("caps activities per thread, keeping the newest", () => {
withDatabases(
({ source, target }) => {
const summary = seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 2,
activityLimit: 2,
seededAt: SEEDED_AT,
});
assert.equal(summary.activities, 4); // 2 threads × 2 kept
const ids = query<{ activity_id: string }>(
target,
"SELECT activity_id FROM projection_thread_activities ORDER BY activity_id",
).map((row) => row.activity_id);
// Of a-*-0/1/2, the newest two are 1 and 2.
assert.deepStrictEqual(ids, ["a-t3-1", "a-t3-2", "a-t4-1", "a-t4-2"]);
},
{ activities: 3 },
);
});
// Required, or computeSnapshotSequence reports 0 for every shell snapshot.
it("writes a cursor row for every projector", () => {
withDatabases(({ source, target }) => {
seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 1,
activityLimit: 10,
seededAt: SEEDED_AT,
});
const rows = query<{ projector: string; last_applied_sequence: number }>(
target,
"SELECT projector, last_applied_sequence FROM projection_state ORDER BY last_applied_sequence",
);
assert.equal(rows.length, 9);
assert.equal(rows[0]?.last_applied_sequence, 1);
assert.equal(rows[8]?.last_applied_sequence, 9);
});
});
it("reports a source with nothing to copy", () => {
withDatabases(
({ source, target }) => {
assert.throws(
() =>
seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 5,
activityLimit: 10,
seededAt: SEEDED_AT,
}),
DevSeedError,
);
},
{ threads: 0 },
);
});
it("leaves the target untouched when the source cannot be opened", () => {
withDatabases(({ target }) => {
assert.throws(
() =>
seedDevDatabase({
sourceDbPath: NodePath.join(NodePath.dirname(target), "missing.sqlite"),
targetDbPath: target,
threadLimit: 5,
activityLimit: 10,
seededAt: SEEDED_AT,
}),
DevSeedError,
);
// The pre-existing row survives: nothing was deleted before the failure.
const projects = query<{ project_id: string }>(
target,
"SELECT project_id FROM projection_projects",
);
assert.deepStrictEqual(
projects.map((row) => row.project_id),
["stale"],
);
});
});
});
+354
View File
@@ -0,0 +1,354 @@
/**
* Copies recent projects and threads from one T3 Code database into another, so
* an isolated dev server opens on something recognisable instead of an empty
* sidebar.
*
* Projections only — never `orchestration_events`. The projector cursor is
* exclusive (`WHERE sequence > cursor`), so an empty event log means bootstrap
* streams nothing and leaves the copied rows alone. Copying a *partial* event
* range is the actual hazard: the projector would replay a tail whose creating
* events are missing. See .agents/skills/test-t3-app/references/sqlite-fixtures.md.
*/
import * as NodeSqlite from "node:sqlite";
/** Must match ORCHESTRATION_PROJECTOR_NAMES in apps/server/src/orchestration/Layers/ProjectionPipeline.ts. */
const PROJECTOR_NAMES = [
"projection.projects",
"projection.threads",
"projection.thread-messages",
"projection.thread-proposed-plans",
"projection.thread-activities",
"projection.thread-sessions",
"projection.thread-turns",
"projection.checkpoints",
"projection.pending-approvals",
] as const;
/** Deleted in this order so a row never outlives what it points at. */
const TABLES_IN_DEPENDENCY_ORDER = [
"projection_pending_approvals",
"projection_thread_proposed_plans",
"projection_thread_activities",
"projection_thread_messages",
"projection_thread_sessions",
"projection_turns",
"projection_threads",
"projection_projects",
"projection_state",
] as const;
export interface DevSeedOptions {
readonly sourceDbPath: string;
readonly targetDbPath: string;
/** How many recent threads to copy. */
readonly threadLimit: number;
/**
* Newest activities kept per thread. The real table runs to six figures, and
* the tail is what makes a thread look alive, so a cap keeps the copy quick
* without making it look empty.
*/
readonly activityLimit: number;
/** ISO-8601 timestamp stamped on the projector cursor rows. */
readonly seededAt: string;
}
export interface DevSeedSummary {
readonly projects: number;
readonly threads: number;
readonly messages: number;
readonly activities: number;
readonly turns: number;
readonly sessions: number;
readonly skippedColumns: ReadonlyArray<string>;
}
export class DevSeedError extends Error {
override readonly name = "DevSeedError";
readonly hint: string | undefined;
constructor(message: string, hint?: string) {
super(message);
this.hint = hint;
}
}
const columnsOf = (database: NodeSqlite.DatabaseSync, table: string): ReadonlyArray<string> =>
database
.prepare(`SELECT name FROM pragma_table_info(?)`)
.all(table)
.map((row) => String((row as { name: unknown }).name));
/**
* Columns present in both databases. The two can sit on different migrations —
* a dev worktree is often a migration behind or ahead of the installed app — so
* `SELECT *` would fail on the first schema change. Copying the intersection
* degrades gracefully instead: a column only the target knows about keeps its
* default.
*/
function sharedColumns(
source: NodeSqlite.DatabaseSync,
target: NodeSqlite.DatabaseSync,
table: string,
): { readonly shared: ReadonlyArray<string>; readonly skipped: ReadonlyArray<string> } {
const sourceColumns = columnsOf(source, table);
const targetColumns = new Set(columnsOf(target, table));
const shared = sourceColumns.filter((column) => targetColumns.has(column));
const skipped = sourceColumns
.filter((column) => !targetColumns.has(column))
.map((column) => `${table}.${column}`);
return { shared, skipped };
}
const placeholders = (count: number) => Array.from({ length: count }, () => "?").join(", ");
const quote = (values: ReadonlyArray<string>) => values.map((value) => `'${value}'`).join(", ");
/**
* Copies rows for `table` whose `keyColumn` is in `keys`, optionally keeping
* only the newest `perKeyLimit` rows per key.
*/
function copyRows(input: {
readonly source: NodeSqlite.DatabaseSync;
readonly target: NodeSqlite.DatabaseSync;
readonly table: string;
readonly keyColumn: string;
readonly keys: ReadonlyArray<string>;
readonly omitColumns?: ReadonlyArray<string>;
readonly perKeyLimit?: { readonly orderBy: string; readonly limit: number };
readonly overrides?: Readonly<Record<string, unknown>>;
}): { readonly copied: number; readonly skipped: ReadonlyArray<string> } {
if (input.keys.length === 0) {
return { copied: 0, skipped: [] };
}
const { shared, skipped } = sharedColumns(input.source, input.target, input.table);
const omit = new Set(input.omitColumns ?? []);
const columns = shared.filter((column) => !omit.has(column));
if (columns.length === 0) {
return { copied: 0, skipped };
}
const selectList = columns.map((column) => `"${column}"`).join(", ");
const rows: Array<Record<string, unknown>> = [];
if (input.perKeyLimit) {
// Per-key cap: one bounded query per key beats a window function, and keeps
// this working on any SQLite build.
const statement = input.source.prepare(
`SELECT ${selectList} FROM ${input.table} WHERE "${input.keyColumn}" = ?
ORDER BY ${input.perKeyLimit.orderBy} DESC LIMIT ?`,
);
for (const key of input.keys) {
rows.push(...(statement.all(key, input.perKeyLimit.limit) as Array<Record<string, unknown>>));
}
} else {
rows.push(
...(input.source
.prepare(
`SELECT ${selectList} FROM ${input.table} WHERE "${input.keyColumn}" IN (${quote(input.keys)})`,
)
.all() as Array<Record<string, unknown>>),
);
}
if (rows.length === 0) {
return { copied: 0, skipped };
}
const insert = input.target.prepare(
`INSERT OR REPLACE INTO ${input.table} (${selectList}) VALUES (${placeholders(columns.length)})`,
);
for (const row of rows) {
insert.run(
...columns.map((column) => {
const value = Object.hasOwn(input.overrides ?? {}, column)
? (input.overrides ?? {})[column]
: row[column];
// node:sqlite binds only null/number/bigint/string/Uint8Array; every
// projection column is one of those, and undefined means "absent".
return (value ?? null) as null | number | bigint | string | Uint8Array;
}),
);
}
return { copied: rows.length, skipped };
}
export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
let source: NodeSqlite.DatabaseSync;
try {
source = new NodeSqlite.DatabaseSync(options.sourceDbPath, { readOnly: true });
} catch (cause) {
throw new DevSeedError(
`could not open the source database at ${options.sourceDbPath}`,
`${String(cause)}. Has T3 Code run at least once?`,
);
}
let target: NodeSqlite.DatabaseSync;
try {
target = new NodeSqlite.DatabaseSync(options.targetDbPath);
} catch (cause) {
source.close();
throw new DevSeedError(
`could not open the target database at ${options.targetDbPath}`,
`${String(cause)}. Start the dev server once so migrations run, then retry.`,
);
}
try {
// Threads the user actually touched most recently. Mirrors the sidebar's own
// ordering (packages/client-runtime/src/state/threadSort.ts).
const threadIds = (
source
.prepare(
`SELECT thread_id FROM projection_threads
WHERE deleted_at IS NULL AND archived_at IS NULL
ORDER BY COALESCE(latest_user_message_at, updated_at, created_at) DESC
LIMIT ?`,
)
.all(options.threadLimit) as Array<{ thread_id: string }>
).map((row) => row.thread_id);
if (threadIds.length === 0) {
throw new DevSeedError(
"the source database has no active threads to copy",
"Use T3 Code normally first, or point --from at a different data directory.",
);
}
const projectIds = (
source
.prepare(
`SELECT DISTINCT project_id FROM projection_threads
WHERE thread_id IN (${quote(threadIds)})`,
)
.all() as Array<{ project_id: string }>
).map((row) => row.project_id);
const skipped: Array<string> = [];
const record = (result: {
readonly copied: number;
readonly skipped: ReadonlyArray<string>;
}) => {
skipped.push(...result.skipped);
return result.copied;
};
target.exec("BEGIN IMMEDIATE");
for (const table of TABLES_IN_DEPENDENCY_ORDER) {
target.exec(`DELETE FROM ${table}`);
}
const projects = record(
copyRows({
source,
target,
table: "projection_projects",
keyColumn: "project_id",
keys: projectIds,
}),
);
const threads = record(
copyRows({
source,
target,
table: "projection_threads",
keyColumn: "thread_id",
keys: threadIds,
// Approvals are not copied (see below), so the badge must not claim any.
overrides: { pending_approval_count: 0, pending_user_input_count: 0 },
}),
);
// row_id is an AUTOINCREMENT surrogate; let the target assign its own.
const turns = record(
copyRows({
source,
target,
table: "projection_turns",
keyColumn: "thread_id",
keys: threadIds,
omitColumns: ["row_id"],
}),
);
const messages = record(
copyRows({
source,
target,
table: "projection_thread_messages",
keyColumn: "thread_id",
keys: threadIds,
}),
);
const activities = record(
copyRows({
source,
target,
table: "projection_thread_activities",
keyColumn: "thread_id",
keys: threadIds,
perKeyLimit: { orderBy: "created_at", limit: options.activityLimit },
}),
);
const sessions = record(
copyRows({
source,
target,
table: "projection_thread_sessions",
keyColumn: "thread_id",
keys: threadIds,
// No agent process is attached in the copy. A carried-over "running"
// status with an active turn renders a thread that spins forever, and
// ProviderSessionReaper skips reaping anything with an active turn.
overrides: { status: "stopped", active_turn_id: null, last_error: null },
}),
);
record(
copyRows({
source,
target,
table: "projection_thread_proposed_plans",
keyColumn: "thread_id",
keys: threadIds,
}),
);
// projection_pending_approvals is deliberately skipped: migration 025 deletes
// approvals with no matching `approval.requested` activity, and the activity
// cap above can easily drop it.
// Required: computeSnapshotSequence returns 0 unless every projector has a
// row, which makes every shell snapshot advertise sequence 0.
const insertState = target.prepare(
`INSERT OR REPLACE INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES (?, ?, ?)`,
);
for (const [index, projector] of PROJECTOR_NAMES.entries()) {
insertState.run(projector, index + 1, options.seededAt);
}
target.exec("COMMIT");
return {
projects,
threads,
messages,
activities,
turns,
sessions,
skippedColumns: [...new Set(skipped)].sort(),
};
} catch (cause) {
try {
target.exec("ROLLBACK");
} catch {
// Already rolled back, or the transaction never opened.
}
throw cause instanceof DevSeedError
? cause
: new DevSeedError(`could not seed the dev database: ${String(cause)}`);
} finally {
source.close();
target.close();
}
}