Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

decider.pullRequests.test.ts

532 lines18.2 KB

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">;
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 };
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 };
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("legacy unlink cannot remove a newer cross-host link", () =>
119 Effect.gen(function* () {
120 const own = makeLink();
121 const foreign = makeLink({
122 host: "github.enterprise.test",
123 url: "https://github.enterprise.test/t3tools/t3code/pull/42",
124 linkedAt: "2026-01-02T00:00:00Z",
125 });
126 const command = yield* decodeCommand({
127 type: "thread.meta.update",
128 commandId: "unlink",
129 threadId: THREAD_ID,
130 linkedPullRequest: null,
131 });
132 const decided = yield* decideOrchestrationCommand({
133 readModel: makeReadModel([own, foreign]),
134 command,
135 });
136 const event = expectSingleEvent(decided, "thread.pull-request-unlinked");
137 expect(event.payload.host).toBe("github.com");
138 }),
139 );
140​
141 it.effect("legacy replacement preserves unrelated manual links", () =>
142 Effect.gen(function* () {
143 const other = makeLink({ number: 7, snapshot: { ...snapshot, state: "merged" } });
144 const current = makeLink({ linkedAt: "2026-01-02T00:00:00Z" });
145 let model = makeReadModel([other, current]);
146 const command = yield* decodeCommand({
147 type: "thread.meta.update",
148 commandId: "replace",
149 threadId: THREAD_ID,
150 linkedPullRequest: {
151 projectId: "project-1",
152 repository: "t3tools/t3code",
153 number: 99,
154 url: "https://github.com/t3tools/t3code/pull/99",
155 },
156 });
157 const decided = yield* decideOrchestrationCommand({ readModel: model, command });
158 const events = Array.isArray(decided) ? decided : [decided];
159 expect(events.map((event) => event.type)).toEqual([
160 "thread.pull-request-unlinked",
161 "thread.pull-request-linked",
162 ]);
163 for (const event of events)
164 model = yield* projectEvent(model, { ...event, sequence: model.snapshotSequence + 1 });
165 expect(model.threads[0]!.pullRequests.map((link) => link.number)).toEqual([7, 99]);
166 }),
167 );
168 it.effect("round-trips an Azure legacy link and unlinks only its organization", () =>
169 Effect.gen(function* () {
170 const foreign = makeLink({
171 host: "dev.azure.com",
172 repository: "org-b/project/_git/web",
173 number: 7,
174 url: "https://dev.azure.com/org-b/project/_git/web/pullrequest/7",
175 });
176 let model = makeReadModel([foreign]);
177 model = {
178 ...model,
179 projects: model.projects.map((project) => ({
180 ...project,
181 repositoryIdentity: {
182 ...project.repositoryIdentity!,
183 provider: "azure-devops",
184 canonicalKey: "ssh.dev.azure.com/v3/org-a/project/web",
185 displayName: "v3/org-a/project/web",
186 name: "web",
187 },
188 })),
189 };
190 const legacy = {
191 projectId: "project-1",
192 repository: "web",
193 number: 7,
194 url: "https://dev.azure.com/org-a/project/_git/web/pullrequest/7",
195 };
196 for (const linkedPullRequest of [legacy, null]) {
197 const command = yield* decodeCommand({
198 type: "thread.meta.update",
199 commandId: linkedPullRequest === null ? "unlink-azure" : "link-azure",
200 threadId: THREAD_ID,
201 linkedPullRequest,
202 });
203 const decided = yield* decideOrchestrationCommand({ readModel: model, command });
204 for (const event of Array.isArray(decided) ? decided : [decided]) {
205 model = yield* projectEvent(model, { ...event, sequence: model.snapshotSequence + 1 });
206 }
207 if (linkedPullRequest !== null) {
208 expect(model.threads[0]!.linkedPullRequest).toEqual(legacy);
209 expect(model.threads[0]!.pullRequests.map((link) => link.repository)).toEqual([
210 "org-b/project/_git/web",
211 "org-a/project/_git/web",
212 ]);
213 }
214 }
215 expect(model.threads[0]!.pullRequests).toEqual([foreign]);
216 expect(model.threads[0]!.linkedPullRequest).toBeNull();
217 }),
218 );
219 it.effect("legacy unlink alone does not emit an empty metadata event", () =>
220 Effect.gen(function* () {
221 const command = yield* decodeCommand({
222 type: "thread.meta.update",
223 commandId: "unlink",
224 threadId: THREAD_ID,
225 linkedPullRequest: null,
226 });
227 const decided = yield* decideOrchestrationCommand({
228 readModel: makeReadModel([makeLink()]),
229 command,
230 });
231 const events = Array.isArray(decided) ? decided : [decided];
232 expect(events.map((event) => event.type)).toEqual(["thread.pull-request-unlinked"]);
233 }),
234 );
235​
236 for (const source of ["manual", "agent", "created", "stack"] as const) {
237 it.effect(`legacy unlink removes the visible ${source} link and preserves other requests`, () =>
238 Effect.gen(function* () {
239 const other = makeLink({ number: 7, snapshot: { ...snapshot, state: "merged" } });
240 const current = makeLink({ source, linkedAt: "2026-01-02T00:00:00.000Z" });
241 let model = makeReadModel([other, current]);
242 // This is the pre-array command shape sent by older clients.
243 const command = yield* decodeCommand({
244 type: "thread.meta.update",
245 commandId: "legacy-unlink",
246 threadId: THREAD_ID,
247 linkedPullRequest: null,
248 title: "Renamed by old client",
249 });
250 const decided = yield* decideOrchestrationCommand({ readModel: model, command });
251 const events = Array.isArray(decided) ? decided : [decided];
252 for (const planned of events) {
253 const event = { ...planned, sequence: model.snapshotSequence + 1 };
254 const encoded = yield* Schema.encodeEffect(OrchestrationEvent)(event);
255 const decoded = yield* Schema.decodeUnknownEffect(OrchestrationEvent)(encoded);
256 // Older detail-event unions must never receive the new PR discriminants.
257 expect(isThreadDetailEvent(decoded)).toBe(false);
258 model = yield* projectEvent(model, decoded);
259 }
260 const thread = model.threads[0]!;
261 expect(thread.title).toBe("Renamed by old client");
262 expect(thread.pullRequests).toEqual(
263 source === "stack" ? [other, { ...current, source: "stack-dismissed" }] : [other],
264 );
265 // The old single-link field continues to track the remaining visible request.
266 expect(thread.linkedPullRequest?.number).toBe(7);
267 }),
268 );
269 }
270​
271 it.effect("links a pull request with a normalized key and empty host state", () =>
272 Effect.gen(function* () {
273 const decided = yield* decideOrchestrationCommand({
274 command: {
275 type: "thread.pull-request.link",
276 commandId: CommandId.make("cmd-link"),
277 threadId: THREAD_ID,
278 host: " GitHub.com ",
279 repository: "T3Tools/T3Code",
280 number: 42,
281 url: "https://github.com/t3tools/t3code/pull/42",
282 source: "manual",
283 },
284 readModel: makeReadModel([]),
285 });
286 expect(Array.isArray(decided)).toBe(false);
287 const event = expectSingleEvent(decided, "thread.pull-request-linked");
288 expect(event.payload.link).toEqual({
289 host: "github.com",
290 repository: "t3tools/t3code",
291 number: 42,
292 url: "https://github.com/t3tools/t3code/pull/42",
293 source: "manual",
294 linkedAt: event.payload.updatedAt,
295 snapshot: null,
296 stack: null,
297 });
298 expect(event.payload.updatedAt).not.toBe(NOW);
299 }),
300 );
301​
302 it.effect("rejects linking a pull request that is already linked", () =>
303 Effect.gen(function* () {
304 const error = yield* decideOrchestrationCommand({
305 command: {
306 type: "thread.pull-request.link",
307 commandId: CommandId.make("cmd-link-dup"),
308 threadId: THREAD_ID,
309 host: "GITHUB.COM",
310 repository: "t3tools/t3code",
311 number: 42,
312 url: "https://github.com/t3tools/t3code/pull/42",
313 source: "agent",
314 },
315 readModel: makeReadModel([makeLink()]),
316 }).pipe(Effect.flip);
317 expect(error._tag).toBe("OrchestrationCommandInvariantError");
318 }),
319 );
320​
321 it.effect("re-linking a dismissed stack member un-dismisses it", () =>
322 Effect.gen(function* () {
323 const dismissed = makeLink({
324 source: "stack-dismissed",
325 snapshot,
326 stack: {
327 kind: "native",
328 id: "stack-1",
329 number: 1,
330 url: "https://github.com/t3tools/t3code/stack/1",
331 base: "main",
332 layers: [{ number: 42, headBranch: "feat/links", state: "open" }],
333 },
334 });
335 const decided = yield* decideOrchestrationCommand({
336 command: {
337 type: "thread.pull-request.link",
338 commandId: CommandId.make("cmd-relink"),
339 threadId: THREAD_ID,
340 host: "github.com",
341 repository: "t3tools/t3code",
342 number: 42,
343 url: "https://github.com/t3tools/t3code/pull/42",
344 source: "manual",
345 },
346 readModel: makeReadModel([dismissed]),
347 });
348 const event = expectSingleEvent(decided, "thread.pull-request-linked");
349 // Host state survives the flip; only the source changes.
350 expect(event.payload.link).toEqual({ ...dismissed, source: "manual" });
351 }),
352 );
353​
354 it.effect("rejects a stack sync re-adding a dismissed stack member", () =>
355 Effect.gen(function* () {
356 const error = yield* decideOrchestrationCommand({
357 command: {
358 type: "thread.pull-request.link",
359 commandId: CommandId.make("cmd-stack-readd"),
360 threadId: THREAD_ID,
361 host: "github.com",
362 repository: "t3tools/t3code",
363 number: 42,
364 url: "https://github.com/t3tools/t3code/pull/42",
365 source: "stack",
366 },
367 readModel: makeReadModel([makeLink({ source: "stack-dismissed" })]),
368 }).pipe(Effect.flip);
369 expect(error._tag).toBe("OrchestrationCommandInvariantError");
370 }),
371 );
372​
373 it.effect("unlinks a manual pull request", () =>
374 Effect.gen(function* () {
375 const decided = yield* decideOrchestrationCommand({
376 command: {
377 type: "thread.pull-request.unlink",
378 commandId: CommandId.make("cmd-unlink"),
379 threadId: THREAD_ID,
380 host: "GitHub.com",
381 repository: "t3tools/t3code",
382 number: 42,
383 },
384 readModel: makeReadModel([makeLink()]),
385 });
386 const event = expectSingleEvent(decided, "thread.pull-request-unlinked");
387 expect(event.payload).toMatchObject({
388 threadId: THREAD_ID,
389 host: "github.com",
390 repository: "t3tools/t3code",
391 number: 42,
392 });
393 }),
394 );
395​
396 it.effect("unlinking a stack member leaves a stack-dismissed tombstone", () =>
397 Effect.gen(function* () {
398 const member = makeLink({ source: "stack", snapshot });
399 const decided = yield* decideOrchestrationCommand({
400 command: {
401 type: "thread.pull-request.unlink",
402 commandId: CommandId.make("cmd-unlink-stack"),
403 threadId: THREAD_ID,
404 host: "github.com",
405 repository: "t3tools/t3code",
406 number: 42,
407 },
408 readModel: makeReadModel([member]),
409 });
410 const event = expectSingleEvent(decided, "thread.pull-request-linked");
411 expect(event.payload.link).toEqual({ ...member, source: "stack-dismissed" });
412 }),
413 );
414​
415 for (const source of ["manual", "agent", "created"] as const) {
416 it.effect(`unlinking a ${source} member prevents its sibling rediscovering it`, () =>
417 Effect.gen(function* () {
418 const member = makeLink({ source });
419 const sibling = makeLink({
420 number: 43,
421 source: "stack",
422 stack: {
423 kind: "native",
424 id: "stack-1",
425 number: 1,
426 url: "https://github.com/t3tools/t3code/stack/1",
427 base: "main",
428 layers: [
429 { number: 42, headBranch: "first", state: "open" },
430 { number: 43, headBranch: "second", state: "open" },
431 ],
432 },
433 });
434 let model = makeReadModel([member, sibling]);
435 const decided = yield* decideOrchestrationCommand({
436 readModel: model,
437 command: {
438 type: "thread.pull-request.unlink",
439 commandId: CommandId.make("remove"),
440 threadId: THREAD_ID,
441 host: member.host,
442 repository: member.repository,
443 number: member.number,
444 },
445 });
446 const event = expectSingleEvent(decided, "thread.pull-request-linked");
447 model = yield* projectEvent(model, { ...event, sequence: 1 });
448 expect(model.threads[0]!.pullRequests).toEqual([
449 { ...member, source: "stack-dismissed" },
450 sibling,
451 ]);
452 const rediscovered = yield* decideOrchestrationCommand({
453 readModel: model,
454 command: {
455 type: "thread.pull-request.link",
456 commandId: CommandId.make("rediscovered"),
457 threadId: THREAD_ID,
458 host: member.host,
459 repository: member.repository,
460 number: member.number,
461 url: member.url,
462 source: "stack",
463 },
464 }).pipe(Effect.result);
465 expect(rediscovered._tag).toBe("Failure");
466 }),
467 );
468 }
469​
470 it.effect("rejects unlinking a pull request that is not linked", () =>
471 Effect.gen(function* () {
472 const error = yield* decideOrchestrationCommand({
473 command: {
474 type: "thread.pull-request.unlink",
475 commandId: CommandId.make("cmd-unlink-missing"),
476 threadId: THREAD_ID,
477 host: "github.com",
478 repository: "t3tools/t3code",
479 number: 7,
480 },
481 readModel: makeReadModel([makeLink()]),
482 }).pipe(Effect.flip);
483 expect(error._tag).toBe("OrchestrationCommandInvariantError");
484 }),
485 );
486​
487 it.effect("rejects syncing a pull request that is not linked", () =>
488 Effect.gen(function* () {
489 const error = yield* decideOrchestrationCommand({
490 command: {
491 type: "thread.pull-request-link.sync",
492 commandId: CommandId.make("cmd-sync-missing"),
493 threadId: THREAD_ID,
494 host: "github.com",
495 repository: "t3tools/t3code",
496 number: 42,
497 snapshot,
498 stack: null,
499 },
500 readModel: makeReadModel([]),
501 }).pipe(Effect.flip);
502 expect(error._tag).toBe("OrchestrationCommandInvariantError");
503 }),
504 );
505​
506 it.effect("sync emits the host snapshot for a linked pull request", () =>
507 Effect.gen(function* () {
508 const decided = yield* decideOrchestrationCommand({
509 command: {
510 type: "thread.pull-request-link.sync",
511 commandId: CommandId.make("cmd-sync"),
512 threadId: THREAD_ID,
513 host: "GitHub.com",
514 repository: "t3tools/t3code",
515 number: 42,
516 snapshot,
517 stack: null,
518 },
519 readModel: makeReadModel([makeLink()]),
520 });
521 const event = expectSingleEvent(decided, "thread.pull-request-synced");
522 expect(event.payload).toMatchObject({
523 threadId: THREAD_ID,
524 host: "github.com",
525 repository: "t3tools/t3code",
526 number: 42,
527 snapshot,
528 stack: null,
529 });
530 }),
531 );
532});