Open History to see the last commit
1import {
2 CommandId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 OrchestrationEvent,
7 OrchestrationCommand,
8 type OrchestrationReadModel,
9 type ThreadPullRequestLink,
10 type ThreadPullRequestSnapshot,
11} from "@t3tools/contracts";
12import * as NodeServices from "@effect/platform-node/NodeServices";
13import { expect, it } from "@effect/vitest";
14import * as Effect from "effect/Effect";
15import * as Schema from "effect/Schema";
16
17import { decideOrchestrationCommand } from "./decider.ts";
18import { projectEvent } from "./projector.ts";
19
20const decodeCommand = Schema.decodeUnknownEffect(OrchestrationCommand);
21
22type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
23
24function expectSingleEvent<Type extends OrchestrationEvent["type"]>(
25 decided: PlannedEvent | ReadonlyArray<PlannedEvent>,
26 type: Type,
27): Omit<Extract<OrchestrationEvent, { type: Type }>, "sequence"> {
28 const event = Array.isArray(decided) ? decided[0] : (decided as PlannedEvent);
29 if (event === undefined || event.type !== type) {
30 throw new Error(`expected ${type}, got ${String(event?.type)}`);
31 }
32 return event as Omit<Extract<OrchestrationEvent, { type: Type }>, "sequence">;
33}
34
35const NOW = "2026-01-01T00:00:00.000Z";
36const THREAD_ID = ThreadId.make("thread-1");
37
38function makeLink(overrides: Partial<ThreadPullRequestLink> = {}): ThreadPullRequestLink {
39 return {
40 host: "github.com",
41 repository: "t3tools/t3code",
42 number: 42,
43 url: "https://github.com/t3tools/t3code/pull/42",
44 source: "manual",
45 linkedAt: NOW,
46 snapshot: null,
47 stack: null,
48 ...overrides,
49 };
50}
51
52function makeReadModel(pullRequests: ReadonlyArray<ThreadPullRequestLink>): OrchestrationReadModel {
53 return {
54 snapshotSequence: 0,
55 projects: [
56 {
57 id: ProjectId.make("project-1"),
58 title: "Project",
59 workspaceRoot: "/repo",
60 defaultModelSelection: null,
61 scripts: [],
62 createdAt: NOW,
63 updatedAt: NOW,
64 deletedAt: null,
65 repositoryIdentity: {
66 canonicalKey: "github.com/t3tools/t3code",
67 provider: "github",
68 displayName: "t3tools/t3code",
69 locator: {
70 source: "git-remote",
71 remoteName: "origin",
72 remoteUrl: "https://github.com/t3tools/t3code.git",
73 },
74 },
75 },
76 ],
77 threads: [
78 {
79 id: THREAD_ID,
80 projectId: ProjectId.make("project-1"),
81 title: "Thread",
82 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
83 runtimeMode: "full-access",
84 interactionMode: "default",
85 branch: null,
86 worktreePath: null,
87 pullRequests,
88 latestTurn: null,
89 createdAt: NOW,
90 updatedAt: NOW,
91 archivedAt: null,
92 settledOverride: null,
93 settledAt: null,
94 deletedAt: null,
95 messages: [],
96 proposedPlans: [],
97 activities: [],
98 checkpoints: [],
99 session: null,
100 },
101 ],
102 updatedAt: NOW,
103 };
104}
105
106const snapshot: ThreadPullRequestSnapshot = {
107 state: "open",
108 title: "Add links",
109 headBranch: "feat/links",
110 baseBranch: "main",
111 isDraft: false,
112 updatedAt: NOW,
113 syncedAt: NOW,
114};
115
116it.layer(NodeServices.layer)("pull request link decider", (it) => {
117 it.effect("legacy unlink cannot remove a newer cross-host link", () =>
118 Effect.gen(function* () {
119 const own = makeLink();
120 const foreign = makeLink({
121 host: "github.enterprise.test",
122 url: "https://github.enterprise.test/t3tools/t3code/pull/42",
123 linkedAt: "2026-01-02T00:00:00Z",
124 });
125 const command = yield* decodeCommand({
126 type: "thread.meta.update",
127 commandId: "unlink",
128 threadId: THREAD_ID,
129 linkedPullRequest: null,
130 });
131 const decided = yield* decideOrchestrationCommand({
132 readModel: makeReadModel([own, foreign]),
133 command,
134 });
135 const event = expectSingleEvent(decided, "thread.pull-request-unlinked");
136 expect(event.payload.host).toBe("github.com");
137 }),
138 );
139
140 it.effect("legacy replacement preserves unrelated manual links", () =>
141 Effect.gen(function* () {
142 const other = makeLink({ number: 7, snapshot: { ...snapshot, state: "merged" } });
143 const current = makeLink({ linkedAt: "2026-01-02T00:00:00Z" });
144 let model = makeReadModel([other, current]);
145 const command = yield* decodeCommand({
146 type: "thread.meta.update",
147 commandId: "replace",
148 threadId: THREAD_ID,
149 linkedPullRequest: {
150 projectId: "project-1",
151 repository: "t3tools/t3code",
152 number: 99,
153 url: "https://github.com/t3tools/t3code/pull/99",
154 },
155 });
156 const decided = yield* decideOrchestrationCommand({ readModel: model, command });
157 const events = Array.isArray(decided) ? decided : [decided];
158 expect(events.map((event) => event.type)).toEqual([
159 "thread.pull-request-unlinked",
160 "thread.pull-request-linked",
161 ]);
162 for (const event of events)
163 model = yield* projectEvent(model, { ...event, sequence: model.snapshotSequence + 1 });
164 expect(model.threads[0]!.pullRequests.map((link) => link.number)).toEqual([7, 99]);
165 }),
166 );
167 it.effect("round-trips an Azure legacy link and unlinks only its organization", () =>
168 Effect.gen(function* () {
169 const foreign = makeLink({
170 host: "dev.azure.com",
171 repository: "org-b/project/_git/web",
172 number: 7,
173 url: "https://dev.azure.com/org-b/project/_git/web/pullrequest/7",
174 });
175 let model = makeReadModel([foreign]);
176 model = {
177 ...model,
178 projects: model.projects.map((project) => ({
179 ...project,
180 repositoryIdentity: {
181 ...project.repositoryIdentity!,
182 provider: "azure-devops",
183 canonicalKey: "ssh.dev.azure.com/v3/org-a/project/web",
184 displayName: "v3/org-a/project/web",
185 name: "web",
186 },
187 })),
188 };
189 const legacy = {
190 projectId: "project-1",
191 repository: "web",
192 number: 7,
193 url: "https://dev.azure.com/org-a/project/_git/web/pullrequest/7",
194 };
195 for (const linkedPullRequest of [legacy, null]) {
196 const command = yield* decodeCommand({
197 type: "thread.meta.update",
198 commandId: linkedPullRequest === null ? "unlink-azure" : "link-azure",
199 threadId: THREAD_ID,
200 linkedPullRequest,
201 });
202 const decided = yield* decideOrchestrationCommand({ readModel: model, command });
203 for (const event of Array.isArray(decided) ? decided : [decided]) {
204 model = yield* projectEvent(model, { ...event, sequence: model.snapshotSequence + 1 });
205 }
206 if (linkedPullRequest !== null) {
207 expect(model.threads[0]!.linkedPullRequest).toEqual(legacy);
208 expect(model.threads[0]!.pullRequests.map((link) => link.repository)).toEqual([
209 "org-b/project/_git/web",
210 "org-a/project/_git/web",
211 ]);
212 }
213 }
214 expect(model.threads[0]!.pullRequests).toEqual([foreign]);
215 expect(model.threads[0]!.linkedPullRequest).toBeNull();
216 }),
217 );
218 it.effect("legacy unlink alone does not emit an empty metadata event", () =>
219 Effect.gen(function* () {
220 const command = yield* decodeCommand({
221 type: "thread.meta.update",
222 commandId: "unlink",
223 threadId: THREAD_ID,
224 linkedPullRequest: null,
225 });
226 const decided = yield* decideOrchestrationCommand({
227 readModel: makeReadModel([makeLink()]),
228 command,
229 });
230 const events = Array.isArray(decided) ? decided : [decided];
231 expect(events.map((event) => event.type)).toEqual(["thread.pull-request-unlinked"]);
232 }),
233 );
234
235 for (const source of ["manual", "agent", "created", "stack"] as const) {
236 it.effect(`legacy unlink removes the visible ${source} link and preserves other requests`, () =>
237 Effect.gen(function* () {
238 const other = makeLink({ number: 7, snapshot: { ...snapshot, state: "merged" } });
239 const current = makeLink({ source, linkedAt: "2026-01-02T00:00:00.000Z" });
240 let model = makeReadModel([other, current]);
241 // This is the pre-array command shape sent by older clients.
242 const command = yield* decodeCommand({
243 type: "thread.meta.update",
244 commandId: "legacy-unlink",
245 threadId: THREAD_ID,
246 linkedPullRequest: null,
247 title: "Renamed by old client",
248 });
249 const decided = yield* decideOrchestrationCommand({ readModel: model, command });
250 const events = Array.isArray(decided) ? decided : [decided];
251 for (const planned of events) {
252 const event = { ...planned, sequence: model.snapshotSequence + 1 };
253 const encoded = yield* Schema.encodeEffect(OrchestrationEvent)(event);
254 const decoded = yield* Schema.decodeUnknownEffect(OrchestrationEvent)(encoded);
255 // Older detail-event unions must never receive the new PR discriminants.
256 expect(
257 decoded.type.startsWith("thread.pull-request-") ||
258 decoded.type === "thread.meta-updated",
259 ).toBe(true);
260 model = yield* projectEvent(model, decoded);
261 }
262 const thread = model.threads[0]!;
263 expect(thread.title).toBe("Renamed by old client");
264 expect(thread.pullRequests).toEqual(
265 source === "stack" ? [other, { ...current, source: "stack-dismissed" }] : [other],
266 );
267 // The old single-link field continues to track the remaining visible request.
268 expect(thread.linkedPullRequest?.number).toBe(7);
269 }),
270 );
271 }
272
273 it.effect("links a pull request with a normalized key and empty host state", () =>
274 Effect.gen(function* () {
275 const decided = yield* decideOrchestrationCommand({
276 command: {
277 type: "thread.pull-request.link",
278 commandId: CommandId.make("cmd-link"),
279 threadId: THREAD_ID,
280 host: " GitHub.com ",
281 repository: "T3Tools/T3Code",
282 number: 42,
283 url: "https://github.com/t3tools/t3code/pull/42",
284 source: "manual",
285 },
286 readModel: makeReadModel([]),
287 });
288 expect(Array.isArray(decided)).toBe(false);
289 const event = expectSingleEvent(decided, "thread.pull-request-linked");
290 expect(event.payload.link).toEqual({
291 host: "github.com",
292 repository: "t3tools/t3code",
293 number: 42,
294 url: "https://github.com/t3tools/t3code/pull/42",
295 source: "manual",
296 linkedAt: event.payload.updatedAt,
297 snapshot: null,
298 stack: null,
299 });
300 expect(event.payload.updatedAt).not.toBe(NOW);
301 }),
302 );
303
304 it.effect("rejects linking a pull request that is already linked", () =>
305 Effect.gen(function* () {
306 const error = yield* decideOrchestrationCommand({
307 command: {
308 type: "thread.pull-request.link",
309 commandId: CommandId.make("cmd-link-dup"),
310 threadId: THREAD_ID,
311 host: "GITHUB.COM",
312 repository: "t3tools/t3code",
313 number: 42,
314 url: "https://github.com/t3tools/t3code/pull/42",
315 source: "agent",
316 },
317 readModel: makeReadModel([makeLink()]),
318 }).pipe(Effect.flip);
319 expect(error._tag).toBe("OrchestrationCommandInvariantError");
320 }),
321 );
322
323 it.effect("re-linking a dismissed stack member un-dismisses it", () =>
324 Effect.gen(function* () {
325 const dismissed = makeLink({
326 source: "stack-dismissed",
327 snapshot,
328 stack: {
329 kind: "native",
330 id: "stack-1",
331 number: 1,
332 url: "https://github.com/t3tools/t3code/stack/1",
333 base: "main",
334 layers: [{ number: 42, headBranch: "feat/links", state: "open" }],
335 },
336 });
337 const decided = yield* decideOrchestrationCommand({
338 command: {
339 type: "thread.pull-request.link",
340 commandId: CommandId.make("cmd-relink"),
341 threadId: THREAD_ID,
342 host: "github.com",
343 repository: "t3tools/t3code",
344 number: 42,
345 url: "https://github.com/t3tools/t3code/pull/42",
346 source: "manual",
347 },
348 readModel: makeReadModel([dismissed]),
349 });
350 const event = expectSingleEvent(decided, "thread.pull-request-linked");
351 // Host state survives the flip; only the source changes.
352 expect(event.payload.link).toEqual({ ...dismissed, source: "manual" });
353 }),
354 );
355
356 it.effect("rejects a stack sync re-adding a dismissed stack member", () =>
357 Effect.gen(function* () {
358 const error = yield* decideOrchestrationCommand({
359 command: {
360 type: "thread.pull-request.link",
361 commandId: CommandId.make("cmd-stack-readd"),
362 threadId: THREAD_ID,
363 host: "github.com",
364 repository: "t3tools/t3code",
365 number: 42,
366 url: "https://github.com/t3tools/t3code/pull/42",
367 source: "stack",
368 },
369 readModel: makeReadModel([makeLink({ source: "stack-dismissed" })]),
370 }).pipe(Effect.flip);
371 expect(error._tag).toBe("OrchestrationCommandInvariantError");
372 }),
373 );
374
375 it.effect("unlinks a manual pull request", () =>
376 Effect.gen(function* () {
377 const decided = yield* decideOrchestrationCommand({
378 command: {
379 type: "thread.pull-request.unlink",
380 commandId: CommandId.make("cmd-unlink"),
381 threadId: THREAD_ID,
382 host: "GitHub.com",
383 repository: "t3tools/t3code",
384 number: 42,
385 },
386 readModel: makeReadModel([makeLink()]),
387 });
388 const event = expectSingleEvent(decided, "thread.pull-request-unlinked");
389 expect(event.payload).toMatchObject({
390 threadId: THREAD_ID,
391 host: "github.com",
392 repository: "t3tools/t3code",
393 number: 42,
394 });
395 }),
396 );
397
398 it.effect("unlinking a stack member leaves a stack-dismissed tombstone", () =>
399 Effect.gen(function* () {
400 const member = makeLink({ source: "stack", snapshot });
401 const decided = yield* decideOrchestrationCommand({
402 command: {
403 type: "thread.pull-request.unlink",
404 commandId: CommandId.make("cmd-unlink-stack"),
405 threadId: THREAD_ID,
406 host: "github.com",
407 repository: "t3tools/t3code",
408 number: 42,
409 },
410 readModel: makeReadModel([member]),
411 });
412 const event = expectSingleEvent(decided, "thread.pull-request-linked");
413 expect(event.payload.link).toEqual({ ...member, source: "stack-dismissed" });
414 }),
415 );
416
417 for (const source of ["manual", "agent", "created"] as const) {
418 it.effect(`unlinking a ${source} member prevents its sibling rediscovering it`, () =>
419 Effect.gen(function* () {
420 const member = makeLink({ source });
421 const sibling = makeLink({
422 number: 43,
423 source: "stack",
424 stack: {
425 kind: "native",
426 id: "stack-1",
427 number: 1,
428 url: "https://github.com/t3tools/t3code/stack/1",
429 base: "main",
430 layers: [
431 { number: 42, headBranch: "first", state: "open" },
432 { number: 43, headBranch: "second", state: "open" },
433 ],
434 },
435 });
436 let model = makeReadModel([member, sibling]);
437 const decided = yield* decideOrchestrationCommand({
438 readModel: model,
439 command: {
440 type: "thread.pull-request.unlink",
441 commandId: CommandId.make("remove"),
442 threadId: THREAD_ID,
443 host: member.host,
444 repository: member.repository,
445 number: member.number,
446 },
447 });
448 const event = expectSingleEvent(decided, "thread.pull-request-linked");
449 model = yield* projectEvent(model, { ...event, sequence: 1 });
450 expect(model.threads[0]!.pullRequests).toEqual([
451 { ...member, source: "stack-dismissed" },
452 sibling,
453 ]);
454 const rediscovered = yield* decideOrchestrationCommand({
455 readModel: model,
456 command: {
457 type: "thread.pull-request.link",
458 commandId: CommandId.make("rediscovered"),
459 threadId: THREAD_ID,
460 host: member.host,
461 repository: member.repository,
462 number: member.number,
463 url: member.url,
464 source: "stack",
465 },
466 }).pipe(Effect.result);
467 expect(rediscovered._tag).toBe("Failure");
468 }),
469 );
470 }
471
472 it.effect("rejects unlinking a pull request that is not linked", () =>
473 Effect.gen(function* () {
474 const error = yield* decideOrchestrationCommand({
475 command: {
476 type: "thread.pull-request.unlink",
477 commandId: CommandId.make("cmd-unlink-missing"),
478 threadId: THREAD_ID,
479 host: "github.com",
480 repository: "t3tools/t3code",
481 number: 7,
482 },
483 readModel: makeReadModel([makeLink()]),
484 }).pipe(Effect.flip);
485 expect(error._tag).toBe("OrchestrationCommandInvariantError");
486 }),
487 );
488
489 it.effect("rejects syncing a pull request that is not linked", () =>
490 Effect.gen(function* () {
491 const error = yield* decideOrchestrationCommand({
492 command: {
493 type: "thread.pull-request-link.sync",
494 commandId: CommandId.make("cmd-sync-missing"),
495 threadId: THREAD_ID,
496 host: "github.com",
497 repository: "t3tools/t3code",
498 number: 42,
499 snapshot,
500 stack: null,
501 },
502 readModel: makeReadModel([]),
503 }).pipe(Effect.flip);
504 expect(error._tag).toBe("OrchestrationCommandInvariantError");
505 }),
506 );
507
508 it.effect("sync emits the host snapshot for a linked pull request", () =>
509 Effect.gen(function* () {
510 const decided = yield* decideOrchestrationCommand({
511 command: {
512 type: "thread.pull-request-link.sync",
513 commandId: CommandId.make("cmd-sync"),
514 threadId: THREAD_ID,
515 host: "GitHub.com",
516 repository: "t3tools/t3code",
517 number: 42,
518 snapshot,
519 stack: null,
520 },
521 readModel: makeReadModel([makeLink()]),
522 });
523 const event = expectSingleEvent(decided, "thread.pull-request-synced");
524 expect(event.payload).toMatchObject({
525 threadId: THREAD_ID,
526 host: "github.com",
527 repository: "t3tools/t3code",
528 number: 42,
529 snapshot,
530 stack: null,
531 });
532 }),
533 );
534});