The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 03:00 UTC
fix(server): migrate legacy thread pull request links (#19129)
Yash Singh committed
Oct 18, 2026 at 19:09 UTC
cab362d45866302c576f705a4c34101d42d19a62
8 files changed
+267
-32
apps/server/src/orchestration-v2/Orchestrator.ts
+1
@@ -2272,6 +2272,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2272
branch: command.branch,
2273
worktreePath: command.worktreePath,
2274
activeProviderThreadId: null,
2275
+ pullRequests: [],
2276
lineage: {
2277
parentThreadId: null,
2278
relationshipToParent: null,
apps/server/src/persistence/Migrations.ts
+2
@@ -66,6 +66,7 @@ import Migration0060 from "./Migrations/060_ThreadSnapshotWindowIndexes.ts";
66
import Migration0061 from "./Migrations/061_PullRequestReviewGuides.ts";
67
import Migration0062 from "./Migrations/062_ThreadFailureLookupIndex.ts";
68
import Migration0063 from "./Migrations/063_DropUnusedV1Projections.ts";
69
+import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.ts";
70
71
export const migrationEntries = [
72
[1, "OrchestrationEvents", Migration0001],
@@ -132,6 +133,7 @@ export const migrationEntries = [
133
[61, "PullRequestReviewGuides", Migration0061],
134
[62, "ThreadFailureLookupIndex", Migration0062],
135
[63, "DropUnusedV1Projections", Migration0063],
136
+ [64, "CanonicalizeThreadPullRequestLinks", Migration0064],
137
] as const;
138
139
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/055_OrchestrationV2.test.ts
+3
-1
@@ -13,7 +13,7 @@ layer("055_OrchestrationV2", (it) => {
13
Effect.sync(() => {
14
assert.deepStrictEqual(
15
migrationEntries.map(([id]) => id),
16
- Array.from({ length: 63 }, (_, index) => index + 1),
16
+ Array.from({ length: 64 }, (_, index) => index + 1),
17
);
18
}),
19
);
@@ -35,6 +35,7 @@ layer("055_OrchestrationV2", (it) => {
35
[61, "PullRequestReviewGuides"],
36
[62, "ThreadFailureLookupIndex"],
37
[63, "DropUnusedV1Projections"],
38
+ [64, "CanonicalizeThreadPullRequestLinks"],
39
]);
40
assert.deepStrictEqual(yield* runMigrations(), []);
41
@@ -64,6 +65,7 @@ layer("055_OrchestrationV2", (it) => {
65
{ migration_id: 61, name: "PullRequestReviewGuides" },
66
{ migration_id: 62, name: "ThreadFailureLookupIndex" },
67
{ migration_id: 63, name: "DropUnusedV1Projections" },
68
+ { migration_id: 64, name: "CanonicalizeThreadPullRequestLinks" },
69
]);
70
71
const tables = yield* sql<{ readonly name: string }>`
apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.test.ts
new
+173
@@ -0,0 +1,173 @@
1
+import { assert, it } from "@effect/vitest";
2
+import { OrchestrationV2AppThreadJson, ThreadId } from "@t3tools/contracts";
3
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
4
+import * as Effect from "effect/Effect";
5
+import * as DateTime from "effect/DateTime";
6
+import * as Layer from "effect/Layer";
7
+import * as Schema from "effect/Schema";
8
+import * as SqlClient from "effect/sql/SqlClient";
9
+
10
+import * as EventStore from "../../orchestration-v2/EventStore.ts";
11
+import * as ProjectionStore from "../../orchestration-v2/ProjectionStore.ts";
12
+import * as ProjectionMaintenance from "../../orchestration-v2/ProjectionMaintenance.ts";
13
+import { listLinkedPullRequestThreads } from "../../pullRequest/linkedThreads.ts";
14
+import { runMigrations } from "../Migrations.ts";
15
+
16
+const decodeThread = Schema.decodeSync(Schema.fromJsonString(OrchestrationV2AppThreadJson));
17
+const updatedAt = "2026-09-01T00:00:00.000Z";
18
+const linked = {
19
+ projectId: "project-1",
20
+ repository: "Acme/Web",
21
+ number: 42,
22
+ url: "https://github.com/acme/web/pull/42",
23
+};
24
+const currentLink = {
25
+ host: "github.com",
26
+ repository: "acme/web",
27
+ number: 43,
28
+ url: "https://github.com/acme/web/pull/43",
29
+ source: "agent" as const,
30
+ linkedAt: updatedAt,
31
+ snapshot: null,
32
+ stack: null,
33
+};
34
+const thread = (id: string) => ({
35
+ id,
36
+ projectId: "project-1",
37
+ title: id,
38
+ providerInstanceId: "codex",
39
+ modelSelection: { instanceId: "codex", model: "gpt-5.4" },
40
+ runtimeMode: "full-access",
41
+ interactionMode: "default",
42
+ createdBy: "user",
43
+ creationSource: "web",
44
+ branch: null,
45
+ worktreePath: null,
46
+ activeProviderThreadId: null,
47
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id },
48
+ forkedFrom: null,
49
+ createdAt: updatedAt,
50
+ updatedAt,
51
+ archivedAt: null,
52
+ deletedAt: null,
53
+});
54
+
55
+const layer = it.layer(
56
+ ProjectionMaintenance.layer.pipe(
57
+ Layer.provideMerge(
58
+ Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe(
59
+ Layer.provideMerge(NodeSqliteClient.layer({ filename: ":memory:" })),
60
+ ),
61
+ ),
62
+ ),
63
+);
64
+
65
+layer("064_CanonicalizeThreadPullRequestLinks", (it) => {
66
+ it.effect("migrates single links once, preserves arrays, and keeps links after a rebuild", () =>
67
+ Effect.gen(function* () {
68
+ const sql = yield* SqlClient.SqlClient;
69
+ yield* runMigrations({ toMigrationInclusive: 63 });
70
+ const fixtures = [
71
+ { ...thread("github"), linkedPullRequest: linked },
72
+ {
73
+ ...thread("forgejo"),
74
+ linkedPullRequest: { ...linked, url: "http://forge.example:3000/acme/web/pulls/42" },
75
+ },
76
+ {
77
+ ...thread("azure"),
78
+ linkedPullRequest: {
79
+ ...linked,
80
+ repository: "project/_git/web",
81
+ url: "https://dev.azure.com/org/project/_git/web/pullrequest/42",
82
+ },
83
+ },
84
+ { ...thread("empty"), linkedPullRequest: linked, pullRequests: [] },
85
+ { ...thread("current"), linkedPullRequest: linked, pullRequests: [currentLink] },
86
+ { ...thread("unlinked"), linkedPullRequest: null },
87
+ ...Array.from({ length: 501 }, (_, index) => ({
88
+ ...thread(`page-${String(index).padStart(3, "0")}`),
89
+ linkedPullRequest: {
90
+ ...linked,
91
+ number: 9000,
92
+ url: "https://github.com/acme/web/pull/9000",
93
+ },
94
+ })),
95
+ ];
96
+ for (const fixture of fixtures) {
97
+ const payload = JSON.stringify(fixture);
98
+ yield* sql`
99
+ INSERT INTO orchestration_v2_projection_threads (
100
+ thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
101
+ created_at, updated_at, payload_json
102
+ ) VALUES (
103
+ ${fixture.id}, 'project-1', ${fixture.title}, 'codex', 'full-access', 'default',
104
+ ${updatedAt}, ${updatedAt}, ${payload}
105
+ )
106
+ `;
107
+ yield* sql`
108
+ INSERT INTO orchestration_events (
109
+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
110
+ actor_kind, payload_json, metadata_json, application_event_version
111
+ ) VALUES (
112
+ ${`event:${fixture.id}`}, 'thread', ${fixture.id}, 0, 'thread.created', ${updatedAt},
113
+ 'user', ${payload}, '{}', 2
114
+ )
115
+ `;
116
+ }
117
+ const v1Payload = JSON.stringify({ linkedPullRequest: linked });
118
+ yield* sql`
119
+ INSERT INTO orchestration_events (
120
+ event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at,
121
+ actor_kind, payload_json, metadata_json, application_event_version
122
+ ) VALUES ('event:v1', 'thread', 'v1', 0, 'thread.created', ${updatedAt},
123
+ 'user', ${v1Payload}, '{}', 1)
124
+ `;
125
+
126
+ assert.deepEqual(yield* runMigrations(), [[64, "CanonicalizeThreadPullRequestLinks"]]);
127
+ assert.deepEqual(yield* runMigrations(), []);
128
+ const rows = yield* sql<{ readonly thread_id: string; readonly payload_json: string }>`
129
+ SELECT thread_id, payload_json FROM orchestration_v2_projection_threads
130
+ `;
131
+ const migrated = new Map(rows.map((row) => [row.thread_id, decodeThread(row.payload_json)]));
132
+ assert.deepEqual(migrated.get("github")?.pullRequests, [
133
+ { ...currentLink, number: 42, url: linked.url, source: "manual" },
134
+ ]);
135
+ assert.equal(migrated.get("forgejo")?.pullRequests?.[0]?.host, "forge.example:3000");
136
+ assert.equal(migrated.get("azure")?.pullRequests?.[0]?.host, "dev.azure.com");
137
+ assert.equal(migrated.get("azure")?.pullRequests?.[0]?.repository, "org/project/_git/web");
138
+ assert.deepEqual(migrated.get("empty")?.pullRequests, []);
139
+ assert.deepEqual(migrated.get("current")?.pullRequests, [currentLink]);
140
+ assert.isUndefined(migrated.get("unlinked")?.pullRequests);
141
+ assert.equal(migrated.get("page-500")?.pullRequests?.[0]?.number, 9000);
142
+ assert.isTrue(
143
+ [...migrated.values()].every((value) => DateTime.formatIso(value.updatedAt) === updatedAt),
144
+ );
145
+ const events = yield* sql<{ readonly stream_id: string; readonly payload_json: string }>`
146
+ SELECT stream_id, payload_json FROM orchestration_events WHERE application_event_version = 2
147
+ `;
148
+ assert.deepEqual(
149
+ new Map(events.map((event) => [event.stream_id, decodeThread(event.payload_json)])),
150
+ migrated,
151
+ );
152
+ const [v1] = yield* sql<{ readonly payload_json: string }>`
153
+ SELECT payload_json FROM orchestration_events WHERE event_id = 'event:v1'
154
+ `;
155
+ assert.equal(v1?.payload_json, v1Payload);
156
+
157
+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
158
+ assert.isTrue((yield* maintenance.rebuild).valid);
159
+ for (const [host, repository, id] of [
160
+ ["github.com", "acme/web", "github"],
161
+ ["forge.example:3000", "acme/web", "forgejo"],
162
+ ["dev.azure.com", "org/project/_git/web", "azure"],
163
+ ] as const) {
164
+ assert.deepEqual(
165
+ (yield* listLinkedPullRequestThreads({ host, repository, number: 42 })).threads.map(
166
+ (value) => value.id,
167
+ ),
168
+ [ThreadId.make(id)],
169
+ );
170
+ }
171
+ }),
172
+ );
173
+});
apps/server/src/persistence/Migrations/064_CanonicalizeThreadPullRequestLinks.ts
new
+84
@@ -0,0 +1,84 @@
1
+import { ThreadLinkedPullRequest, ThreadPullRequestLink } from "@t3tools/contracts";
2
+import { legacyThreadPullRequestKey } from "@t3tools/shared/threadPullRequests";
3
+import * as Effect from "effect/Effect";
4
+import * as Schema from "effect/Schema";
5
+import * as SqlClient from "effect/sql/SqlClient";
6
+
7
+const decodeLegacyLink = Schema.decodeEffect(Schema.fromJsonString(ThreadLinkedPullRequest));
8
+const encodeLinks = Schema.encodeSync(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink)));
9
+const linksJson = Effect.fnUntraced(function* (linkedPullRequestJson: string, linkedAt: string) {
10
+ const linked = yield* decodeLegacyLink(linkedPullRequestJson);
11
+ return encodeLinks([
12
+ {
13
+ ...legacyThreadPullRequestKey(linked),
14
+ url: linked.url,
15
+ source: "manual",
16
+ linkedAt,
17
+ snapshot: null,
18
+ stack: null,
19
+ },
20
+ ]);
21
+});
22
+
23
+export default Effect.gen(function* () {
24
+ const sql = yield* SqlClient.SqlClient;
25
+ const pageSize = 500;
26
+ let afterThreadId = "";
27
+ while (true) {
28
+ const rows = yield* sql<{
29
+ readonly thread_id: string;
30
+ readonly linked_pull_request_json: string;
31
+ readonly updated_at: string;
32
+ }>`
33
+ SELECT thread_id, json_extract(payload_json, '$.linkedPullRequest') AS linked_pull_request_json,
34
+ updated_at
35
+ FROM orchestration_v2_projection_threads
36
+ WHERE thread_id > ${afterThreadId}
37
+ AND json_type(payload_json, '$.pullRequests') IS NULL
38
+ AND json_type(payload_json, '$.linkedPullRequest') = 'object'
39
+ ORDER BY thread_id
40
+ LIMIT ${pageSize}
41
+ `;
42
+ for (const row of rows) {
43
+ const pullRequests = yield* linksJson(row.linked_pull_request_json, row.updated_at);
44
+ yield* sql`
45
+ UPDATE orchestration_v2_projection_threads
46
+ SET payload_json = json_set(payload_json, '$.pullRequests', json(${pullRequests}))
47
+ WHERE thread_id = ${row.thread_id}
48
+ `;
49
+ }
50
+ if (rows.length < pageSize) break;
51
+ afterThreadId = rows.at(-1)!.thread_id;
52
+ }
53
+
54
+ // Normalize the source events too, so rebuilding projections cannot restore the old shape.
55
+ let afterSequence = 0;
56
+ while (true) {
57
+ const rows = yield* sql<{
58
+ readonly sequence: number;
59
+ readonly linked_pull_request_json: string;
60
+ readonly updated_at: string;
61
+ }>`
62
+ SELECT sequence, json_extract(payload_json, '$.linkedPullRequest') AS linked_pull_request_json,
63
+ json_extract(payload_json, '$.updatedAt') AS updated_at
64
+ FROM orchestration_events
65
+ WHERE sequence > ${afterSequence}
66
+ AND application_event_version = 2 AND aggregate_kind = 'thread'
67
+ AND event_type LIKE 'thread.%'
68
+ AND json_type(payload_json, '$.pullRequests') IS NULL
69
+ AND json_type(payload_json, '$.linkedPullRequest') = 'object'
70
+ ORDER BY sequence
71
+ LIMIT ${pageSize}
72
+ `;
73
+ for (const row of rows) {
74
+ const pullRequests = yield* linksJson(row.linked_pull_request_json, row.updated_at);
75
+ yield* sql`
76
+ UPDATE orchestration_events
77
+ SET payload_json = json_set(payload_json, '$.pullRequests', json(${pullRequests}))
78
+ WHERE sequence = ${row.sequence}
79
+ `;
80
+ }
81
+ if (rows.length < pageSize) break;
82
+ afterSequence = rows.at(-1)!.sequence;
83
+ }
84
+});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -43,6 +43,7 @@ describe("V2 preview upgrade", () => {
43
[61, "PullRequestReviewGuides"],
44
[62, "ThreadFailureLookupIndex"],
45
[63, "DropUnusedV1Projections"],
46
+ [64, "CanonicalizeThreadPullRequestLinks"],
47
]);
48
assert.deepStrictEqual(yield* runMigrations(), []);
49
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -129,6 +130,7 @@ describe("V2 preview upgrade", () => {
130
[61, "PullRequestReviewGuides"],
131
[62, "ThreadFailureLookupIndex"],
132
[63, "DropUnusedV1Projections"],
133
+ [64, "CanonicalizeThreadPullRequestLinks"],
134
]);
135
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
136
);
apps/server/src/pullRequest/linkedThreads.test.ts
-11
@@ -101,16 +101,6 @@ it.effect(
101
)
102
`;
103
}
104
- yield* sql`
105
- INSERT INTO orchestration_v2_projection_threads (
106
- thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
107
- created_at, updated_at, payload_json
108
- ) VALUES (
109
- 'legacy-single', 'project-1', 'legacy-single', 'codex', 'full-access', 'default',
110
- ${createdAt}, ${createdAt},
111
- '{"linkedPullRequest":{"projectId":"project-1","repository":"acme/web","number":7,"url":"https://github.com/acme/web/pull/7"}}'
112
- )
113
- `;
104
yield* sql`
105
INSERT INTO orchestration_v2_projection_threads (
106
thread_id, project_id, title, default_provider, runtime_mode, interaction_mode,
@@ -169,7 +159,6 @@ it.effect(
159
threads: [
160
{ id: "archived", projectId: "project-1", title: "archived", archivedAt },
161
{ id: "active", projectId: "project-1", title: "active", archivedAt: null },
172
- { id: "legacy-single", projectId: "project-1", title: "legacy-single", archivedAt: null },
162
],
163
});
164
assert.deepStrictEqual(
apps/server/src/pullRequest/linkedThreads.ts
+2
-20
@@ -1,5 +1,4 @@
1
import {
2
- legacyThreadPullRequestKey,
2
normalizeThreadPullRequestKey,
3
threadPullRequestKeysEqual,
4
} from "@t3tools/shared/threadPullRequests";
@@ -23,7 +22,7 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre
22
projectId: string;
23
title: string;
24
archivedAt: string | null;
26
- host: string | null;
25
+ host: string;
26
repository: string;
27
number: number;
28
url: string;
@@ -39,27 +38,10 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre
38
WHERE json_extract(link.value, '$.number') = ${key.number}
39
AND json_extract(link.value, '$.source') != 'stack-dismissed'
40
AND t.deleted_at IS NULL
42
- UNION ALL
43
- SELECT t.thread_id AS id, t.project_id AS "projectId", t.title,
44
- t.archived_at AS "archivedAt", NULL AS host,
45
- json_extract(t.payload_json, '$.linkedPullRequest.repository') AS repository,
46
- json_extract(t.payload_json, '$.linkedPullRequest.number') AS number,
47
- json_extract(t.payload_json, '$.linkedPullRequest.url') AS url,
48
- t.updated_at AS "updatedAt"
49
- FROM orchestration_v2_projection_threads AS t
50
- WHERE json_type(t.payload_json, '$.pullRequests') IS NULL
51
- AND json_type(t.payload_json, '$.linkedPullRequest') = 'object'
52
- AND json_extract(t.payload_json, '$.linkedPullRequest.number') = ${key.number}
53
- AND t.deleted_at IS NULL
41
ORDER BY "updatedAt" DESC, id ASC
42
`;
43
const threads = rows
57
- .filter((row) =>
58
- threadPullRequestKeysEqual(
59
- row.host === null ? legacyThreadPullRequestKey(row) : { ...row, host: row.host },
60
- key,
61
- ),
62
- )
44
+ .filter((row) => threadPullRequestKeysEqual(row, key))
45
.map(({ id, projectId, title, archivedAt }) => ({ id, projectId, title, archivedAt }));
46
return yield* decodeLinkedThreads({ threads });
47
},