Skip to content
TypeScript

fix(server): migrate legacy thread pull request links (#19129)

Yash Singhcab362d45866
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 2c512b5336a..29ba67bdf6e 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -2272,6 +2272,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
branch: command.branch,
worktreePath: command.worktreePath,
activeProviderThreadId: null,
+ pullRequests: [],
lineage: {
parentThreadId: null,
relationshipToParent: null,
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 73c991d42dd..2b4981e04d1 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -66,6 +66,7 @@ import Migration0060 from "./Migrations/060_ThreadSnapshotWindowIndexes.ts";
import Migration0061 from "./Migrations/061_PullRequestReviewGuides.ts";
import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";
import Migration0063 from "./Migrations/063_DropUnusedV1Projections.ts";
+import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.ts";
export const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
@@ -132,6 +133,7 @@ export const migrationEntries = [
[61, "PullRequestReviewGuides", Migration0061],
[62, "ThreadFailureLookupIndex", Migration0062],
[63, "DropUnusedV1Projections", Migration0063],
+ [64, "CanonicalizeThreadPullRequestLinks", Migration0064],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts b/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
index 01371684cdf..447c365082f 100644
--- a/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
+++ b/apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
@@ -13,7 +13,7 @@ layer("055_OrchestrationV2", (it) => {
Effect.sync(() => {
assert.deepStrictEqual(
migrationEntries.map(([id]) => id),
- Array.from({ length: 63 }, (_, index) => index + 1),
+ Array.from({ length: 64 }, (_, index) => index + 1),
);
}),
);
@@ -35,6 +35,7 @@ layer("055_OrchestrationV2", (it) => {
[61, "PullRequestReviewGuides"],
[62, "ThreadFailureLookupIndex"],
[63, "DropUnusedV1Projections"],
+ [64, "CanonicalizeThreadPullRequestLinks"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
@@ -64,6 +65,7 @@ layer("055_OrchestrationV2", (it) => {
{ migration_id: 61, name: "PullRequestReviewGuides" },
{ migration_id: 62, name: "ThreadFailureLookupIndex" },
{ migration_id: 63, name: "DropUnusedV1Projections" },
+ { migration_id: 64, name: "CanonicalizeThreadPullRequestLinks" },
]);
const tables = yield* sql<{ readonly name: string }>`
diff --git a/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts
new file mode 100644
index 00000000000..706cc02760e
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts
@@ -0,0 +1,173 @@
+import { assert, it } from "@effect/vitest";
+import { OrchestrationV2AppThreadJson, ThreadId } from "@t3tools/contracts";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
+import * as Effect from "effect/Effect";
+import * as DateTime from "effect/DateTime";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
+
+import * as EventStore from "../../orchestration-v2/EventStore.ts";
+import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts";
+import * as ProjectionMaintenance from "../../orchestration-v2/ProjectionMaintenance.ts";
+import { listLinkedPullRequestThreads } from "../../pullRequest/linkedThreads.ts";
+import { runMigrations } from "../Migrations.ts";
+
+const decodeThread = Schema.decodeSync(Schema.fromJsonString(OrchestrationV2AppThreadJson));
+const updatedAt = "2026-09-01T00:00:00.000Z";
+const linked = {
+ projectId: "project-1",
+ repository: "Acme/Web",
+ number: 42,
+ url: "https://github.com/acme/web/pull/42",
+};
+const currentLink = {
+ host: "github.com",
+ repository: "acme/web",
+ number: 43,
+ url: "https://github.com/acme/web/pull/43",
+ source: "agent" as const,
+ linkedAt: updatedAt,
+ snapshot: null,
+ stack: null,
+};
+const thread = (id: string) => ({
+ id,
+ projectId: "project-1",
+ title: id,
+ providerInstanceId: "codex",
+ modelSelection: { instanceId: "codex", model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy: "user",
+ creationSource: "web",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: null,
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
+ forkedFrom: null,
+ createdAt: updatedAt,
+ updatedAt,
+ archivedAt: null,
+ deletedAt: null,
+});
+
+const layer = it.layer(
+ ProjectionMaintenance.layer.pipe(
+ Layer.provideMerge(
+ Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
+ Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })),
+ ),
+ ),
+ ),
+);
+
+layer("064_CanonicalizeThreadPullRequestLinks", (it) => {
+ it.effect("migrates single links once, preserves arrays, and keeps links after a rebuild", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ yield* runMigrations({ toMigrationInclusive: 63 });
+ const fixtures = [
+ { ...thread("github"), linkedPullRequest: linked },
+ {
+ ...thread("forgejo"),
+ linkedPullRequest: { ...linked, url: "http://forge.example:3000/acme/web/pulls/42" },
+ },
+ {
+ ...thread("azure"),
+ linkedPullRequest: {
+ ...linked,
+ repository: "project/_git/web",
+ url: "https://dev.azure.com/org/project/_git/web/pullrequest/42",
+ },
+ },
+ { ...thread("empty"), linkedPullRequest: linked, pullRequests: [] },
+ { ...thread("current"), linkedPullRequest: linked, pullRequests: [currentLink] },
+ { ...thread("unlinked"), linkedPullRequest: null },
+ ...Array.from({ length: 501 }, (_, index) => ({
+ ...thread(`page-${String(index).padStart(3, "0")}`),
+ linkedPullRequest: {
+ ...linked,
+ number: 9000,
+ url: "https://github.com/acme/web/pull/9000",
+ },
+ })),
+ ];
+ for (const fixture of fixtures) {
+ const payload = JSON.stringify(fixture);
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_threads (
+ thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
+ created_at, updated_at, payload_json
+ ) VALUES (
+ ${fixture.id}, 'project-1', ${fixture.title}, 'codex', 'full-access', 'default',
+ ${updatedAt}, ${updatedAt}, ${payload}
+ )
+ `;
+ yield* sql`
+ INSERT INTO orchestration_events (
+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
+ actor_kind, payload_json, metadata_json, application_event_version
+ ) VALUES (
+ ${`event:${fixture.id}`}, 'thread', ${fixture.id}, 0, 'thread.created', ${updatedAt},
+ 'user', ${payload}, '{}', 2
+ )
+ `;
+ }
+ const v1Payload = JSON.stringify({ linkedPullRequest: linked });
+ yield* sql`
+ INSERT INTO orchestration_events (
+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
+ actor_kind, payload_json, metadata_json, application_event_version
+ ) VALUES ('event:v1', 'thread', 'v1', 0, 'thread.created', ${updatedAt},
+ 'user', ${v1Payload}, '{}', 1)
+ `;
+
+ assert.deepEqual(yield* runMigrations(), [[64, "CanonicalizeThreadPullRequestLinks"]]);
+ assert.deepEqual(yield* runMigrations(), []);
+ const rows = yield* sql<{ readonly thread_id: string; readonly payload_json: string }>`
+ SELECT thread_id, payload_json FROM orchestration_v2_projection_threads
+ `;
+ const migrated = new Map(rows.map((row) => [row.thread_id, decodeThread(row.payload_json)]));
+ assert.deepEqual(migrated.get("github")?.pullRequests, [
+ { ...currentLink, number: 42, url: linked.url, source: "manual" },
+ ]);
+ assert.equal(migrated.get("forgejo")?.pullRequests?.[0]?.host, "forge.example:3000");
+ assert.equal(migrated.get("azure")?.pullRequests?.[0]?.host, "dev.azure.com");
+ assert.equal(migrated.get("azure")?.pullRequests?.[0]?.repository, "org/project/_git/web");
+ assert.deepEqual(migrated.get("empty")?.pullRequests, []);
+ assert.deepEqual(migrated.get("current")?.pullRequests, [currentLink]);
+ assert.isUndefined(migrated.get("unlinked")?.pullRequests);
+ assert.equal(migrated.get("page-500")?.pullRequests?.[0]?.number, 9000);
+ assert.isTrue(
+ [...migrated.values()].every((value) => DateTime.formatIso(value.updatedAt) === updatedAt),
+ );
+ const events = yield* sql<{ readonly stream_id: string; readonly payload_json: string }>`
+ SELECT stream_id, payload_json FROM orchestration_events WHERE application_event_version = 2
+ `;
+ assert.deepEqual(
+ new Map(events.map((event) => [event.stream_id, decodeThread(event.payload_json)])),
+ migrated,
+ );
+ const [v1] = yield* sql<{ readonly payload_json: string }>`
+ SELECT payload_json FROM orchestration_events WHERE event_id = 'event:v1'
+ `;
+ assert.equal(v1?.payload_json, v1Payload);
+
+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
+ assert.isTrue((yield* maintenance.rebuild).valid);
+ for (const [host, repository, id] of [
+ ["github.com", "acme/web", "github"],
+ ["forge.example:3000", "acme/web", "forgejo"],
+ ["dev.azure.com", "org/project/_git/web", "azure"],
+ ] as const) {
+ assert.deepEqual(
+ (yield* listLinkedPullRequestThreads({ host, repository, number: 42 })).threads.map(
+ (value) => value.id,
+ ),
+ [ThreadId.make(id)],
+ );
+ }
+ }),
+ );
+});
diff --git a/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.ts b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.ts
new file mode 100644
index 00000000000..7135696246c
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.ts
@@ -0,0 +1,84 @@
+import { ThreadLinkedPullRequest, ThreadPullRequestLink } from "@t3tools/contracts";
+import { legacyThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+import * as SqlClient from "effect/sql/SqlClient";
+
+const decodeLegacyLink = Schema.decodeEffect(Schema.fromJsonString(ThreadLinkedPullRequest));
+const encodeLinks = Schema.encodeSync(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink)));
+const linksJson = Effect.fnUntraced(function* (linkedPullRequestJson: string, linkedAt: string) {
+ const linked = yield* decodeLegacyLink(linkedPullRequestJson);
+ return encodeLinks([
+ {
+ ...legacyThreadPullRequestKey(linked),
+ url: linked.url,
+ source: "manual",
+ linkedAt,
+ snapshot: null,
+ stack: null,
+ },
+ ]);
+});
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const pageSize = 500;
+ let afterThreadId = "";
+ while (true) {
+ const rows = yield* sql<{
+ readonly thread_id: string;
+ readonly linked_pull_request_json: string;
+ readonly updated_at: string;
+ }>`
+ SELECT thread_id, json_extract(payload_json, '$.linkedPullRequest') AS linked_pull_request_json,
+ updated_at
+ FROM orchestration_v2_projection_threads
+ WHERE thread_id > ${afterThreadId}
+ AND json_type(payload_json, '$.pullRequests') IS NULL
+ AND json_type(payload_json, '$.linkedPullRequest') = 'object'
+ ORDER BY thread_id
+ LIMIT ${pageSize}
+ `;
+ for (const row of rows) {
+ const pullRequests = yield* linksJson(row.linked_pull_request_json, row.updated_at);
+ yield* sql`
+ UPDATE orchestration_v2_projection_threads
+ SET payload_json = json_set(payload_json, '$.pullRequests', json(${pullRequests}))
+ WHERE thread_id = ${row.thread_id}
+ `;
+ }
+ if (rows.length < pageSize) break;
+ afterThreadId = rows.at(-1)!.thread_id;
+ }
+
+ // Normalize the source events too, so rebuilding projections cannot restore the old shape.
+ let afterSequence = 0;
+ while (true) {
+ const rows = yield* sql<{
+ readonly sequence: number;
+ readonly linked_pull_request_json: string;
+ readonly updated_at: string;
+ }>`
+ SELECT sequence, json_extract(payload_json, '$.linkedPullRequest') AS linked_pull_request_json,
+ json_extract(payload_json, '$.updatedAt') AS updated_at
+ FROM orchestration_events
+ WHERE sequence > ${afterSequence}
+ AND application_event_version = 2 AND aggregate_kind = 'thread'
+ AND event_type LIKE 'thread.%'
+ AND json_type(payload_json, '$.pullRequests') IS NULL
+ AND json_type(payload_json, '$.linkedPullRequest') = 'object'
+ ORDER BY sequence
+ LIMIT ${pageSize}
+ `;
+ for (const row of rows) {
+ const pullRequests = yield* linksJson(row.linked_pull_request_json, row.updated_at);
+ yield* sql`
+ UPDATE orchestration_events
+ SET payload_json = json_set(payload_json, '$.pullRequests', json(${pullRequests}))
+ WHERE sequence = ${row.sequence}
+ `;
+ }
+ if (rows.length < pageSize) break;
+ afterSequence = rows.at(-1)!.sequence;
+ }
+});
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index ac21403c489..802c5110490 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -43,6 +43,7 @@ describe("V2 preview upgrade", () => {
[61, "PullRequestReviewGuides"],
[62, "ThreadFailureLookupIndex"],
[63, "DropUnusedV1Projections"],
+ [64, "CanonicalizeThreadPullRequestLinks"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -129,6 +130,7 @@ describe("V2 preview upgrade", () => {
[61, "PullRequestReviewGuides"],
[62, "ThreadFailureLookupIndex"],
[63, "DropUnusedV1Projections"],
+ [64, "CanonicalizeThreadPullRequestLinks"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
diff --git a/apps/server/src/pullRequest/linkedThreads.test.ts b/apps/server/src/pullRequest/linkedThreads.test.ts
index 8b1d2764202..230758714b3 100644
--- a/apps/server/src/pullRequest/linkedThreads.test.ts
+++ b/apps/server/src/pullRequest/linkedThreads.test.ts
@@ -101,16 +101,6 @@ it.effect(
)
`;
}
- yield* sql`
- INSERT INTO orchestration_v2_projection_threads (
- thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
- created_at, updated_at, payload_json
- ) VALUES (
- 'legacy-single', 'project-1', 'legacy-single', 'codex', 'full-access', 'default',
- ${createdAt}, ${createdAt},
- '{"linkedPullRequest":{"projectId":"project-1","repository":"acme/web","number":7,"url":"https://github.com/acme/web/pull/7"}}'
- )
- `;
yield* sql`
INSERT INTO orchestration_v2_projection_threads (
thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
@@ -169,7 +159,6 @@ it.effect(
threads: [
{ id: "archived", projectId: "project-1", title: "archived", archivedAt },
{ id: "active", projectId: "project-1", title: "active", archivedAt: null },
- { id: "legacy-single", projectId: "project-1", title: "legacy-single", archivedAt: null },
],
});
assert.deepStrictEqual(
diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.ts
index f5bf1d9c286..b250ef4a6c6 100644
--- a/apps/server/src/pullRequest/linkedThreads.ts
+++ b/apps/server/src/pullRequest/linkedThreads.ts
@@ -1,5 +1,4 @@
import {
- legacyThreadPullRequestKey,
normalizeThreadPullRequestKey,
threadPullRequestKeysEqual,
} from "@t3tools/shared/threadPullRequests";
@@ -23,7 +22,7 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre
projectId: string;
title: string;
archivedAt: string | null;
- host: string | null;
+ host: string;
repository: string;
number: number;
url: string;
@@ -39,27 +38,10 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre
WHERE json_extract(link.value, '$.number') = ${key.number}
AND json_extract(link.value, '$.source') != 'stack-dismissed'
AND t.deleted_at IS NULL
- UNION ALL
- SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,
- t.archived_at AS "archivedAt", NULL AS host,
- json_extract(t.payload_json, '$.linkedPullRequest.repository') AS repository,
- json_extract(t.payload_json, '$.linkedPullRequest.number') AS number,
- json_extract(t.payload_json, '$.linkedPullRequest.url') AS url,
- t.updated_at AS "updatedAt"
- FROM orchestration_v2_projection_threads AS t
- WHERE json_type(t.payload_json, '$.pullRequests') IS NULL
- AND json_type(t.payload_json, '$.linkedPullRequest') = 'object'
- AND json_extract(t.payload_json, '$.linkedPullRequest.number') = ${key.number}
- AND t.deleted_at IS NULL
ORDER BY "updatedAt" DESC, id ASC
`;
const threads = rows
- .filter((row) =>
- threadPullRequestKeysEqual(
- row.host === null ? legacyThreadPullRequestKey(row) : { ...row, host: row.host },
- key,
- ),
- )
+ .filter((row) => threadPullRequestKeysEqual(row, key))
.map(({ id, projectId, title, archivedAt }) => ({ id, projectId, title, archivedAt }));
return yield* decodeLinkedThreads({ threads });
},