Address review findings on seeding and worktree resolution
- dev:seed wrote projector cursors at 1..9 while leaving the target's event log intact. The cursor is exclusive and a fresh log restarts at sequence 1, so every projector would skip a different slice of the user's first real events; the retained events would also replay over the copied projections and resurrect the target's deleted threads. All nine cursors now start at 0, and the event log and command receipts are emptied with the projections. - The thread-selection query referenced archived_at and latest_user_message_at unconditionally, so a source older than migrations 017/023 threw before copying anything. It now builds its filter and ordering from the columns the source actually has, matching how the rest of the copy handles drift. A table missing from the target is likewise skipped rather than aborting the seed. - --threads/--activities accepted negatives, which SQLite reads as "no limit" — a capped copy silently became a full-table one. Both now require a positive integer. - resolveGitWorktreePath only looked at cwd, so running dev:pair from a subdirectory fell through to the shared home. It walks up to the repository root now. - resolveWorktreeT3Home no longer returns undefined when .t3 is absent: inside a worktree that is the answer, and falling back to the shared home is precisely the accident the default prevents. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
02594421d2
commit
93f0f96b3f
7 files changed
+295
-57
No files matched your search
@@ -204,11 +204,7 @@ const pairingUrlCommand = Command.make("url", {
|
||||
// here" — which the dev runner puts in the worktree's own `.t3`. Falling
|
||||
// through to the shared home would mint a credential into the database
|
||||
// the user's installed T3 Code is running against.
|
||||
// requireExisting: only claim the worktree home once the dev runner has
|
||||
// created it; otherwise report "no running server" against the real home.
|
||||
const worktreeBaseDir = yield* resolveWorktreeT3Home(process.cwd(), {
|
||||
requireExisting: true,
|
||||
});
|
||||
const worktreeBaseDir = yield* resolveWorktreeT3Home(process.cwd());
|
||||
const resolvedFlags =
|
||||
Option.isSome(flags.baseDir) || worktreeBaseDir === undefined
|
||||
? flags
|
||||
|
||||
+12
-11
@@ -68,21 +68,22 @@ vp run dev --share
|
||||
|
||||
What it does, and why:
|
||||
|
||||
- **Projections only.** `orchestration_events` is never copied. 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.
|
||||
- **Writes all nine `projection_state` rows.** Without them
|
||||
`computeSnapshotSequence` returns 0 and every shell snapshot advertises
|
||||
sequence 0.
|
||||
- **Projections only.** `orchestration_events` is never copied, and the target's
|
||||
own event log is emptied: the copied projections describe a different world,
|
||||
so replaying the target's retained history over them would resurrect threads
|
||||
and projects it had deleted.
|
||||
- **Writes all nine `projection_state` rows, at sequence 0.** Without the rows
|
||||
`computeSnapshotSequence` returns 0 anyway; with a _positive_ cursor each
|
||||
projector would skip that many of the first real events — a different count
|
||||
each — since the cursor is exclusive and the emptied log restarts at 1.
|
||||
- **Neutralizes live state.** Sessions are forced to `stopped` with no active
|
||||
turn (a copied `running` session has no agent behind it and would spin
|
||||
forever, and the session reaper skips anything with an active turn), and
|
||||
pending approval/input counts are zeroed since approvals are not copied.
|
||||
- **Copies the intersection of columns.** The two databases are often on
|
||||
different migrations; a column only one side has is skipped and reported
|
||||
rather than failing the copy.
|
||||
- **Tolerates migration drift both ways.** The two databases are often on
|
||||
different migrations, so a column only one side has is skipped and reported,
|
||||
a table the target lacks is passed over, and an older source is read with
|
||||
whichever recency columns it actually has.
|
||||
- **Refuses to write to `~/.t3`.** It replaces projection tables wholesale, so
|
||||
the shared home is rejected outright.
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - builds real worktree layouts on disk.
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
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 Effect from "effect/Effect";
|
||||
|
||||
import { resolveGitWorktreePath, resolveWorktreeT3Home } from "./devHome.ts";
|
||||
|
||||
/**
|
||||
* Git marks a linked worktree with a `.git` *file*; a main checkout has a
|
||||
* `.git` directory. Both are built for real so the distinction is exercised
|
||||
* rather than mocked. Torn down by the scope, after the effect has run.
|
||||
*/
|
||||
const makeRepo = (kind: "worktree" | "checkout" | "bare") =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-devhome-"));
|
||||
if (kind === "worktree") {
|
||||
NodeFS.writeFileSync(NodePath.join(root, ".git"), "gitdir: /elsewhere/.git/worktrees/x\n");
|
||||
} else if (kind === "checkout") {
|
||||
NodeFS.mkdirSync(NodePath.join(root, ".git"));
|
||||
}
|
||||
const nested = NodePath.join(root, "apps", "web", "src");
|
||||
NodeFS.mkdirSync(nested, { recursive: true });
|
||||
return { root, nested };
|
||||
}),
|
||||
({ root }) => Effect.sync(() => NodeFS.rmSync(root, { recursive: true, force: true })),
|
||||
);
|
||||
|
||||
describe("resolveGitWorktreePath", () => {
|
||||
it.effect("finds the worktree root from the top", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root } = yield* makeRepo("worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(root), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// Running `dev:pair` from apps/web must resolve the same worktree as from the
|
||||
// repo root; otherwise it falls through to the shared home.
|
||||
it.effect("finds the worktree root from a subdirectory", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("worktree");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), NodePath.resolve(root));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a main checkout as not a worktree", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("checkout");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a directory outside any repository", () =>
|
||||
Effect.gen(function* () {
|
||||
const { nested } = yield* makeRepo("bare");
|
||||
assert.equal(yield* resolveGitWorktreePath(nested), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
|
||||
describe("resolveWorktreeT3Home", () => {
|
||||
// Deliberately does not require the directory to exist: answering "undefined"
|
||||
// would send callers at the user's real database.
|
||||
it.effect("answers with .t3 even before the dev runner creates it", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root, nested } = yield* makeRepo("worktree");
|
||||
const home = yield* resolveWorktreeT3Home(nested);
|
||||
assert.equal(home, NodePath.join(NodePath.resolve(root), ".t3"));
|
||||
assert.isFalse(NodeFS.existsSync(home ?? ""));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("leaves a main checkout on the shared home", () =>
|
||||
Effect.gen(function* () {
|
||||
const { root } = yield* makeRepo("checkout");
|
||||
assert.equal(yield* resolveWorktreeT3Home(root), undefined);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -14,9 +14,12 @@ import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
/**
|
||||
* The path of the linked git worktree containing `cwd`'s root, or undefined
|
||||
* for a main checkout. Git marks a linked worktree by making `.git` a file
|
||||
* The path of the linked git worktree containing `cwd`, or undefined when
|
||||
* `cwd` is not inside one. Git marks a linked worktree by making `.git` a file
|
||||
* (`gitdir: …`) rather than a directory.
|
||||
*
|
||||
* Walks up to the repository root, so running from a subdirectory (`apps/web`,
|
||||
* say) resolves the same worktree as running from the top.
|
||||
*/
|
||||
export const resolveGitWorktreePath = (
|
||||
cwd: string,
|
||||
@@ -24,19 +27,36 @@ export const resolveGitWorktreePath = (
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const info = yield* fileSystem.stat(path.join(cwd, ".git")).pipe(Effect.option);
|
||||
return Option.isSome(info) && info.value.type === "File" ? cwd : undefined;
|
||||
|
||||
let directory = path.resolve(cwd);
|
||||
for (;;) {
|
||||
const info = yield* fileSystem.stat(path.join(directory, ".git")).pipe(Effect.option);
|
||||
if (Option.isSome(info)) {
|
||||
// A directory means the main checkout: not a linked worktree, and the
|
||||
// search stops either way — nesting one repo inside another does not
|
||||
// make the outer one this worktree's root.
|
||||
return info.value.type === "File" ? directory : undefined;
|
||||
}
|
||||
const parent = path.dirname(directory);
|
||||
if (parent === directory) {
|
||||
return undefined;
|
||||
}
|
||||
directory = parent;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The worktree-local data directory for `cwd`, or undefined outside a linked
|
||||
* worktree. With `requireExisting`, also undefined until something (normally
|
||||
* the dev runner) has created it — for tools that should fall back to normal
|
||||
* resolution rather than inventing an empty data directory.
|
||||
* worktree.
|
||||
*
|
||||
* Deliberately does not check whether the directory exists yet. Inside a
|
||||
* worktree this is *the* answer; falling back to the shared home because it
|
||||
* happens to be missing would send a tool at the user's real database, which
|
||||
* is the accident the worktree default exists to prevent. A caller that needs
|
||||
* a different directory should be told so explicitly (`--base-dir`).
|
||||
*/
|
||||
export const resolveWorktreeT3Home = (
|
||||
cwd: string,
|
||||
options?: { readonly requireExisting?: boolean },
|
||||
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
|
||||
Effect.gen(function* () {
|
||||
const worktreePath = yield* resolveGitWorktreePath(cwd);
|
||||
@@ -44,11 +64,5 @@ export const resolveWorktreeT3Home = (
|
||||
return undefined;
|
||||
}
|
||||
const path = yield* Path.Path;
|
||||
const home = path.join(worktreePath, ".t3");
|
||||
if (options?.requireExisting) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fileSystem.exists(home).pipe(Effect.orElseSucceed(() => false));
|
||||
return exists ? home : undefined;
|
||||
}
|
||||
return home;
|
||||
return path.join(worktreePath, ".t3");
|
||||
});
|
||||
@@ -68,13 +68,17 @@ const devSeedCli = Command.make("dev-seed", {
|
||||
Flag.optional,
|
||||
Flag.map(Option.getOrUndefined),
|
||||
),
|
||||
// Bounded: SQLite reads a negative LIMIT as "no limit", which would quietly
|
||||
// turn a capped copy into a full-table one.
|
||||
threads: Flag.integer("threads").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isGreaterThan(0))),
|
||||
Flag.withDescription(
|
||||
`How many recent threads to copy (default ${String(DEFAULT_THREAD_LIMIT)}).`,
|
||||
),
|
||||
Flag.withDefault(DEFAULT_THREAD_LIMIT),
|
||||
),
|
||||
activities: Flag.integer("activities").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isGreaterThan(0))),
|
||||
Flag.withDescription(
|
||||
`Newest activities kept per thread (default ${String(DEFAULT_ACTIVITY_LIMIT)}).`,
|
||||
),
|
||||
|
||||
+124
-19
@@ -16,15 +16,16 @@ const SEEDED_AT = "2026-07-26T00:00:00.000Z";
|
||||
*/
|
||||
function createSchema(
|
||||
database: NodeSqlite.DatabaseSync,
|
||||
options: { readonly withMonitor: boolean },
|
||||
options: { readonly withMonitor: boolean; readonly legacyThreads?: 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)`);
|
||||
// A pre-017/023 source has neither archived_at nor latest_user_message_at.
|
||||
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,
|
||||
deleted_at TEXT${options.legacyThreads ? "" : ", 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" : ""})`);
|
||||
@@ -51,12 +52,21 @@ function createSchema(
|
||||
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)`);
|
||||
database.exec(`CREATE TABLE orchestration_events (
|
||||
sequence INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT NOT NULL UNIQUE,
|
||||
stream_id TEXT NOT NULL, event_type TEXT NOT NULL, payload_json TEXT NOT NULL)`);
|
||||
}
|
||||
|
||||
/** Source DB with `threadCount` threads, oldest first so recency ordering is testable. */
|
||||
function makeSource(path: string, threadCount: number, activitiesPerThread = 3) {
|
||||
function makeSource(
|
||||
path: string,
|
||||
threadCount: number,
|
||||
activitiesPerThread = 3,
|
||||
options?: { readonly legacyThreads?: boolean },
|
||||
) {
|
||||
const legacyThreads = options?.legacyThreads ?? false;
|
||||
const database = new NodeSqlite.DatabaseSync(path);
|
||||
createSchema(database, { withMonitor: true });
|
||||
createSchema(database, { withMonitor: true, legacyThreads });
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_projects VALUES ('p1','Project','/repo','[]','${SEEDED_AT}','${SEEDED_AT}',NULL)`,
|
||||
@@ -67,14 +77,24 @@ function makeSource(path: string, threadCount: number, activitiesPerThread = 3)
|
||||
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, "{}");
|
||||
if (legacyThreads) {
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_threads (thread_id, project_id, title, latest_turn_id,
|
||||
created_at, updated_at, pending_approval_count, pending_user_input_count, monitor_json)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)`,
|
||||
)
|
||||
.run(threadId, "p1", `Thread ${String(index)}`, `turn-${threadId}`, at, at, 4, 2, "{}");
|
||||
} else {
|
||||
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)
|
||||
@@ -96,7 +116,7 @@ function makeSource(path: string, threadCount: number, activitiesPerThread = 3)
|
||||
database.close();
|
||||
}
|
||||
|
||||
function makeTarget(path: string) {
|
||||
function makeTarget(path: string, options?: { readonly dropProposedPlans?: boolean }) {
|
||||
const database = new NodeSqlite.DatabaseSync(path);
|
||||
// No monitor_json: the target is a migration behind, as a worktree often is.
|
||||
createSchema(database, { withMonitor: false });
|
||||
@@ -105,18 +125,34 @@ function makeTarget(path: string) {
|
||||
`INSERT INTO projection_projects VALUES ('stale','Stale','/old','[]','${SEEDED_AT}','${SEEDED_AT}',NULL)`,
|
||||
)
|
||||
.run();
|
||||
// History from the target's own past life, which must not survive the seed.
|
||||
database
|
||||
.prepare(`INSERT INTO orchestration_events (event_id, stream_id, event_type, payload_json)
|
||||
VALUES ('old-event','stale-thread','thread.created','{}')`)
|
||||
.run();
|
||||
if (options?.dropProposedPlans) {
|
||||
// A target far enough behind that a whole table is missing (migration 013).
|
||||
database.exec("DROP TABLE projection_thread_proposed_plans");
|
||||
}
|
||||
database.close();
|
||||
}
|
||||
|
||||
const withDatabases = <A>(
|
||||
run: (paths: { readonly source: string; readonly target: string }) => A,
|
||||
options?: { readonly threads?: number; readonly activities?: number },
|
||||
options?: {
|
||||
readonly threads?: number;
|
||||
readonly activities?: number;
|
||||
readonly dropProposedPlans?: boolean;
|
||||
readonly legacySource?: boolean;
|
||||
},
|
||||
): 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);
|
||||
makeSource(source, options?.threads ?? 5, options?.activities ?? 3, {
|
||||
legacyThreads: options?.legacySource ?? false,
|
||||
});
|
||||
makeTarget(target, { dropProposedPlans: options?.dropProposedPlans ?? false });
|
||||
try {
|
||||
return run({ source, target });
|
||||
} finally {
|
||||
@@ -272,14 +308,83 @@ describe("seedDevDatabase", () => {
|
||||
|
||||
const rows = query<{ projector: string; last_applied_sequence: number }>(
|
||||
target,
|
||||
"SELECT projector, last_applied_sequence FROM projection_state ORDER BY last_applied_sequence",
|
||||
"SELECT projector, last_applied_sequence FROM projection_state",
|
||||
);
|
||||
assert.equal(rows.length, 9);
|
||||
assert.equal(rows[0]?.last_applied_sequence, 1);
|
||||
assert.equal(rows[8]?.last_applied_sequence, 9);
|
||||
// All at 0. The cursor is exclusive and the event log was emptied, so
|
||||
// any positive value would make each projector skip that many of the
|
||||
// user's first real events — a different count each, which desynchronizes
|
||||
// the projections permanently.
|
||||
for (const row of rows) {
|
||||
assert.equal(row.last_applied_sequence, 0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// The copied projections describe a different world than whatever history
|
||||
// the target still holds; replaying it would resurrect the target's own
|
||||
// deleted threads and projects over the seed.
|
||||
it("empties the target event log", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const [events] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM orchestration_events",
|
||||
);
|
||||
assert.equal(events?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// A target behind on migrations can be missing a table outright; that should
|
||||
// degrade like column drift does, not abort the seed.
|
||||
it("tolerates a table the target does not have", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, 2);
|
||||
},
|
||||
{ dropProposedPlans: true },
|
||||
);
|
||||
});
|
||||
|
||||
// The recency columns arrived in migrations 017 and 023; a source older than
|
||||
// those must still be readable, since the rest of the copy tolerates drift.
|
||||
it("reads a source that predates the recency columns", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.equal(summary.threads, 2);
|
||||
const titles = query<{ title: string }>(
|
||||
target,
|
||||
"SELECT title FROM projection_threads ORDER BY updated_at DESC",
|
||||
).map((row) => row.title);
|
||||
assert.deepStrictEqual(titles, ["Thread 4", "Thread 3"]);
|
||||
},
|
||||
{ legacySource: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a source with nothing to copy", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
|
||||
+43
-7
@@ -77,6 +77,12 @@ function sharedColumns(
|
||||
|
||||
const placeholders = (count: number) => Array.from({ length: count }, () => "?").join(", ");
|
||||
|
||||
const hasTable = (database: NodeSqlite.DatabaseSync, table: string): boolean =>
|
||||
database.prepare(`SELECT 1 FROM pragma_table_info(?)`).get(table) !== undefined;
|
||||
|
||||
const hasColumn = (database: NodeSqlite.DatabaseSync, table: string, column: string): boolean =>
|
||||
columnsOf(database, table).includes(column);
|
||||
|
||||
/**
|
||||
* Copies rows for `table` whose `keyColumn` is in `keys`, optionally keeping
|
||||
* only the newest `perKeyLimit` rows per key.
|
||||
@@ -175,13 +181,22 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
|
||||
try {
|
||||
// Threads the user actually touched most recently. Mirrors the sidebar's own
|
||||
// ordering (packages/client-runtime/src/state/threadSort.ts).
|
||||
// ordering (packages/client-runtime/src/state/threadSort.ts). Both recency
|
||||
// columns arrived in later migrations, so an older source database is read
|
||||
// with whichever of them it actually has — the rest of the copy tolerates
|
||||
// schema drift, and this query must too.
|
||||
const recencyColumns = ["latest_user_message_at", "updated_at", "created_at"].filter((column) =>
|
||||
hasColumn(source, "projection_threads", column),
|
||||
);
|
||||
const activeFilters = ["deleted_at", "archived_at"]
|
||||
.filter((column) => hasColumn(source, "projection_threads", column))
|
||||
.map((column) => `${column} IS NULL`);
|
||||
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
|
||||
${activeFilters.length > 0 ? `WHERE ${activeFilters.join(" AND ")}` : ""}
|
||||
ORDER BY COALESCE(${recencyColumns.join(", ")}) DESC
|
||||
LIMIT ?`,
|
||||
)
|
||||
.all(options.threadLimit) as Array<{ thread_id: string }>
|
||||
@@ -215,7 +230,21 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
target.exec("BEGIN IMMEDIATE");
|
||||
|
||||
for (const table of PROJECTION_TABLES_IN_DEPENDENCY_ORDER) {
|
||||
target.exec(`DELETE FROM ${table}`);
|
||||
// A target behind on migrations may not have every table yet; skipping is
|
||||
// consistent with how column drift is handled, and beats aborting the seed.
|
||||
if (hasTable(target, table)) {
|
||||
target.exec(`DELETE FROM ${table}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Projections are copied wholesale, so any event history the target still
|
||||
// holds describes a different world. Replaying it over the copied rows
|
||||
// would resurrect the target's own deleted threads and projects.
|
||||
if (hasTable(target, "orchestration_events")) {
|
||||
target.exec("DELETE FROM orchestration_events");
|
||||
}
|
||||
if (hasTable(target, "orchestration_command_receipts")) {
|
||||
target.exec("DELETE FROM orchestration_command_receipts");
|
||||
}
|
||||
|
||||
const projects = record(
|
||||
@@ -296,12 +325,19 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
|
||||
// Required: computeSnapshotSequence returns 0 unless every projector has a
|
||||
// row, which makes every shell snapshot advertise sequence 0.
|
||||
//
|
||||
// The cursor is exclusive (`WHERE sequence > cursor`) and the event log was
|
||||
// just emptied, so `sequence` restarts at 1. Any positive cursor would make
|
||||
// each projector skip that many of the user's first real events — and a
|
||||
// different count per projector, leaving the projections permanently
|
||||
// inconsistent. Every projector starts at 0: nothing to skip, nothing to
|
||||
// replay.
|
||||
const insertState = target.prepare(
|
||||
`INSERT OR REPLACE INTO projection_state (projector, last_applied_sequence, updated_at)
|
||||
VALUES (?, ?, ?)`,
|
||||
VALUES (?, 0, ?)`,
|
||||
);
|
||||
for (const [index, projector] of PROJECTOR_NAMES.entries()) {
|
||||
insertState.run(projector, index + 1, options.seededAt);
|
||||
for (const projector of PROJECTOR_NAMES) {
|
||||
insertState.run(projector, options.seededAt);
|
||||
}
|
||||
|
||||
target.exec("COMMIT");
|
||||
|
||||
Reference in new issue
Block a user