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

decider.pullRequests.test.ts

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