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