Skip to content

Commit 2187054

Browse files
committed
Keep seeded development state internally consistent
1 parent 200774a commit 2187054

3 files changed

Lines changed: 125 additions & 26 deletions

File tree

‎scripts/dev-seed.ts‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -166,16 +166,23 @@ const copyAttachments = Effect.fn("devSeed.copyAttachments")(function* (input: {
166166
return 0;
167167
}
168168

169-
yield* fileSystem.makeDirectory(input.targetDir, { recursive: true });
170169
// Attachments are decoration on a dev fixture: one unreadable file should
171-
// leave the rest of the seed intact rather than fail a completed copy.
172-
const copied = yield* Effect.forEach(matches, (entry) =>
173-
fileSystem.copyFile(path.join(input.sourceDir, entry), path.join(input.targetDir, entry)).pipe(
174-
Effect.as(1),
175-
Effect.orElseSucceed(() => 0),
170+
// leave the rest of the seed intact rather than fail a completed database
171+
// copy. The directory itself is subject to the same rule.
172+
return yield* fileSystem.makeDirectory(input.targetDir, { recursive: true }).pipe(
173+
Effect.andThen(
174+
Effect.forEach(matches, (entry) =>
175+
fileSystem
176+
.copyFile(path.join(input.sourceDir, entry), path.join(input.targetDir, entry))
177+
.pipe(
178+
Effect.as(1),
179+
Effect.orElseSucceed(() => 0),
180+
),
181+
),
176182
),
183+
Effect.map((copied) => copied.reduce((total, one) => total + one, 0)),
184+
Effect.orElseSucceed(() => 0),
177185
);
178-
return copied.reduce((total, one) => total + one, 0);
179186
});
180187

181188
const devSeedCli = Command.make("dev-seed", {

‎scripts/lib/dev-seed.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,11 @@ describe("seedDevDatabase", () => {
324324
assert.equal(session.status, "stopped");
325325
assert.isNull(session.active_turn_id);
326326
}
327+
const [threadsWithLatestTurn] = query<{ count: number }>(
328+
target,
329+
"SELECT COUNT(*) count FROM projection_threads WHERE latest_turn_id IS NOT NULL",
330+
);
331+
assert.equal(threadsWithLatestTurn?.count, 0);
327332
});
328333
});
329334

@@ -437,6 +442,35 @@ describe("seedDevDatabase", () => {
437442
});
438443
});
439444

445+
it("uses activity id as the final cap tiebreaker", () => {
446+
withDatabases(({ source, target }) => {
447+
const sourceDatabase = new NodeSqlite.DatabaseSync(source);
448+
sourceDatabase.exec("DELETE FROM projection_thread_activities");
449+
const insert = sourceDatabase.prepare(
450+
`INSERT INTO projection_thread_activities
451+
VALUES (?, 't4', 'neutral', 'tool', 'ran', '{}', 7, ?)`,
452+
);
453+
const tied = "2026-07-10T00:00:00.000Z";
454+
insert.run("tie-a", tied);
455+
insert.run("tie-z", tied);
456+
sourceDatabase.close();
457+
458+
seedDevDatabase({
459+
sourceDbPath: source,
460+
targetDbPath: target,
461+
threadLimit: 1,
462+
activityLimit: 1,
463+
seededAt: SEEDED_AT,
464+
});
465+
466+
const kept = query<{ activity_id: string }>(
467+
target,
468+
"SELECT activity_id FROM projection_thread_activities",
469+
);
470+
assert.deepStrictEqual(kept, [{ activity_id: "tie-z" }]);
471+
});
472+
});
473+
440474
// The delete mirrors the server's predicate, which spares rows carrying a
441475
// checkpoint. Without the `checkpoint_turn_count IS NULL` clause a checkpoint
442476
// row that happened to be pending would be destroyed along with the starts.
@@ -650,6 +684,35 @@ describe("seedDevDatabase", () => {
650684
);
651685
});
652686

687+
it("falls back to user messages when stored recency is missing", () => {
688+
withDatabases(({ source, target }) => {
689+
const sourceDatabase = new NodeSqlite.DatabaseSync(source);
690+
sourceDatabase.exec("UPDATE projection_threads SET latest_user_message_at = NULL");
691+
sourceDatabase
692+
.prepare(
693+
`UPDATE projection_thread_messages
694+
SET created_at = '2099-01-01T00:00:00.000Z'
695+
WHERE thread_id = 't0' AND role = 'user'`,
696+
)
697+
.run();
698+
sourceDatabase.close();
699+
700+
seedDevDatabase({
701+
sourceDbPath: source,
702+
targetDbPath: target,
703+
threadLimit: 1,
704+
activityLimit: 10,
705+
seededAt: SEEDED_AT,
706+
});
707+
708+
const threads = query<{ thread_id: string }>(
709+
target,
710+
"SELECT thread_id FROM projection_threads",
711+
);
712+
assert.deepStrictEqual(threads, [{ thread_id: "t0" }]);
713+
});
714+
});
715+
653716
// Every statement keyed on thread ids must cost exactly one bound variable
654717
// per thread: the limit *is* SQLite's ceiling, so a single extra binding
655718
// makes the maximum fail — after the target has already been emptied. Runs

‎scripts/lib/dev-seed.ts‎

Lines changed: 48 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -411,31 +411,51 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
411411
}
412412

413413
try {
414-
// Threads the user actually touched most recently. Mirrors the sidebar's own
415-
// ordering (packages/client-runtime/src/state/threadSort.ts). Both recency
416-
// columns arrived in later migrations, so an older source database is read
417-
// with whichever of them it actually has — the rest of the copy tolerates
418-
// schema drift, and this query must too.
419-
const recencyColumns = ["latest_user_message_at", "updated_at", "created_at"].filter((column) =>
420-
hasColumn(source, "projection_threads", column),
421-
);
414+
// Threads the user actually touched most recently. Mirrors the sidebar's
415+
// own ordering (packages/client-runtime/src/state/threadSort.ts), including
416+
// its user-message scan when the materialized timestamp is null. Both
417+
// recency columns arrived in later migrations, so an older source database
418+
// is read with whichever inputs it actually has.
419+
const recencyExpressions: Array<string> = [];
420+
if (hasColumn(source, "projection_threads", "latest_user_message_at")) {
421+
recencyExpressions.push('threads."latest_user_message_at"');
422+
}
423+
if (
424+
hasTable(source, "projection_thread_messages") &&
425+
["thread_id", "role", "created_at"].every((column) =>
426+
hasColumn(source, "projection_thread_messages", column),
427+
)
428+
) {
429+
recencyExpressions.push(`(
430+
SELECT MAX(messages."created_at")
431+
FROM projection_thread_messages AS messages
432+
WHERE messages."thread_id" = threads."thread_id"
433+
AND messages."role" = 'user'
434+
)`);
435+
}
436+
for (const column of ["updated_at", "created_at"]) {
437+
if (hasColumn(source, "projection_threads", column)) {
438+
recencyExpressions.push(`threads."${column}"`);
439+
}
440+
}
422441
// SQLite's COALESCE requires at least two arguments, so a source down to a
423442
// single recency column — the pre-migration-017 case this filter exists to
424443
// support — would throw rather than degrade. `created_at` is NOT NULL from
425444
// migration 005 on, so there is always at least one.
426445
const recencyOrder =
427-
recencyColumns.length > 1
428-
? `COALESCE(${recencyColumns.join(", ")})`
429-
: (recencyColumns[0] ?? "rowid");
446+
recencyExpressions.length > 1
447+
? `COALESCE(${recencyExpressions.join(", ")})`
448+
: (recencyExpressions[0] ?? "threads.rowid");
430449
const activeFilters = ["deleted_at", "archived_at"]
431450
.filter((column) => hasColumn(source, "projection_threads", column))
432-
.map((column) => `${column} IS NULL`);
451+
.map((column) => `threads."${column}" IS NULL`);
433452
const threadIds = (
434453
source
435454
.prepare(
436-
`SELECT thread_id FROM projection_threads
455+
`SELECT threads."thread_id" AS thread_id
456+
FROM projection_threads AS threads
437457
${activeFilters.length > 0 ? `WHERE ${activeFilters.join(" AND ")}` : ""}
438-
ORDER BY ${recencyOrder} DESC
458+
ORDER BY ${recencyOrder} DESC, threads."thread_id" DESC
439459
LIMIT ?`,
440460
)
441461
.all(options.threadLimit) as Array<{ thread_id: string }>
@@ -512,7 +532,13 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
512532
keyColumn: "thread_id",
513533
keys: threadIds,
514534
// Approvals are not copied (see below), so the badge must not claim any.
515-
overrides: { pending_approval_count: 0, pending_user_input_count: 0 },
535+
// Sessions are copied as stopped with no active turn, matching the
536+
// thread.session-set projection by clearing its latest turn pointer.
537+
overrides: {
538+
latest_turn_id: null,
539+
pending_approval_count: 0,
540+
pending_user_input_count: 0,
541+
},
516542
}),
517543
);
518544
// row_id is an AUTOINCREMENT surrogate; let the target assign its own.
@@ -553,8 +579,8 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
553579
table: "projection_thread_activities",
554580
keyColumn: "thread_id",
555581
keys: threadIds,
556-
// Ordered the way the app reads these back — `sequence` first, then
557-
// `created_at` (ProjectionSnapshotQuery). Any other key order can keep
582+
// Ordered the way the app reads these back — `sequence`, `created_at`,
583+
// then `activity_id` (ProjectionSnapshotQuery). Any other key order can keep
558584
// rows the timeline treats as oldest: timestamps tie within a burst of
559585
// tool activity, and can even disagree with `sequence` outright when
560586
// events arrive with skewed clocks. Descending, a NULL `sequence`
@@ -564,8 +590,8 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
564590
// back to the timestamp — same drift tolerance as the rest of the copy.
565591
perKeyLimit: {
566592
orderBy: hasColumn(source, "projection_thread_activities", "sequence")
567-
? `"sequence" DESC, "created_at"`
568-
: `"created_at"`,
593+
? `"sequence" DESC, "created_at" DESC, "activity_id"`
594+
: `"created_at" DESC, "activity_id"`,
569595
limit: options.activityLimit,
570596
},
571597
}),
@@ -580,6 +606,9 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
580606
// No agent process is attached in the copy. A carried-over "running"
581607
// status with an active turn renders a thread that spins forever, and
582608
// ProviderSessionReaper skips reaping anything with an active turn.
609+
// "ready"/"idle" are live-session completion signals to agent
610+
// awareness, so preserving those would publish historical fixtures as
611+
// newly completed work. Every copied session is intentionally stopped.
583612
overrides: { status: "stopped", active_turn_id: null, last_error: null },
584613
}),
585614
);

0 commit comments

Comments
 (0)