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:
Theo BrowneandClaude Opus 5 committed 2026-07-25 21:59:16 -07:00
1 parent 02594421d2
commit 93f0f96b3f
7 files changed
+295 -57

No files matched your search

+4
View File
@@ -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
View File
@@ -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
View File
@@ -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");