Open History to see the last commit
1import * as Stream from "effect/Stream";
2import {
3 ProjectId,
4 ProviderInstanceId,
5 PullRequestOperationError,
6 ThreadId,
7 type OrchestrationV2Command as OrchestrationCommand,
8 type OrchestrationProjectShell,
9 type PullRequestRef,
10 type PullRequestStack,
11 type PullRequestSummary,
12 type ThreadPullRequestLink,
13 type ThreadPullRequestSnapshot,
14} from "@t3tools/contracts";
15import { assert, describe, it } from "@effect/vitest";
16import * as Crypto from "effect/Crypto";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Queue from "effect/Queue";
22import * as Ref from "effect/Ref";
23import { TestClock } from "effect/testing";
24
25import * as PullRequestService from "../pullRequest/PullRequestService.ts";
26import * as ServerActivation from "../serverActivation.ts";
27import * as Orchestrator from "./Orchestrator.ts";
28import * as ProjectionStore from "./ProjectionStore.ts";
29import * as PullRequestSyncReactor from "./PullRequestSyncReactor.ts";
30import type { PullRequestTestThread } from "./testkit/pullRequestFixtures.ts";
31
32const NOW = "2026-08-28T12:00:00.000Z";
33const PROJECT_ID = ProjectId.make("sync-project");
34
35type SyncCommand = Extract<
36 OrchestrationCommand,
37 { readonly type: "thread.pull-request-link.sync" }
38>;
39type LinkCommand = Extract<OrchestrationCommand, { readonly type: "thread.pull-request.link" }>;
40
41const testCrypto = Crypto.make({
42 randomBytes: (size) => new Uint8Array(size).fill(1),
43 digest: (_algorithm, data) => Effect.succeed(data),
44});
45
46function makeProject(id: ProjectId = PROJECT_ID): OrchestrationProjectShell {
47 return {
48 id,
49 title: `Project ${id}`,
50 workspaceRoot: "/workspace/project",
51 defaultModelSelection: null,
52 scripts: [],
53 createdAt: "2026-08-01T00:00:00.000Z",
54 updatedAt: NOW,
55 };
56}
57
58function makeThread(
59 id: string,
60 overrides: Partial<PullRequestTestThread> = {},
61): PullRequestTestThread {
62 return {
63 id: ThreadId.make(id),
64 projectId: PROJECT_ID,
65 title: id,
66 modelSelection: {
67 instanceId: ProviderInstanceId.make("codex"),
68 model: "gpt-5",
69 },
70 runtimeMode: "full-access",
71 interactionMode: "default",
72 branch: null,
73 worktreePath: null,
74 pullRequests: [],
75 createdAt: "2026-08-01T00:00:00.000Z",
76 updatedAt: "2026-08-20T00:00:00.000Z",
77 archivedAt: null,
78 settledOverride: null,
79 settledAt: null,
80 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
81 ...overrides,
82 };
83}
84
85function makeLink(
86 number: number,
87 snapshot: Partial<ThreadPullRequestSnapshot> | null = null,
88 overrides: Partial<ThreadPullRequestLink> = {},
89): ThreadPullRequestLink {
90 return {
91 host: "github.com",
92 repository: "owner/repository",
93 number,
94 url: `https://github.com/owner/repository/pull/${number}`,
95 source: "manual",
96 linkedAt: "2026-08-10T00:00:00.000Z",
97 snapshot:
98 snapshot === null
99 ? null
100 : {
101 state: "open",
102 title: "Pull request",
103 headBranch: "feature",
104 baseBranch: "main",
105 isDraft: false,
106 updatedAt: "2026-08-27T00:00:00.000Z",
107 syncedAt: "2026-08-27T00:00:00.000Z",
108 ...snapshot,
109 },
110 stack: null,
111 ...overrides,
112 };
113}
114
115/** The shell the fake projection store serves: one project and its threads. */
116interface TestShellSnapshot {
117 readonly snapshotSequence: number;
118 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
119 readonly threads: ReadonlyArray<PullRequestTestThread>;
120 readonly updatedAt: string;
121}
122
123function makeSnapshot(
124 threads: ReadonlyArray<PullRequestTestThread>,
125 snapshotSequence = 1,
126): TestShellSnapshot {
127 return {
128 snapshotSequence,
129 projects: [makeProject()],
130 threads,
131 updatedAt: NOW,
132 };
133}
134
135function makeSummary(
136 input: PullRequestRef,
137 overrides: Partial<PullRequestSummary> = {},
138): PullRequestSummary {
139 return {
140 provider: "github",
141 projectId: input.projectId,
142 repository: input.repository,
143 number: input.number,
144 title: "Pull request",
145 url: `https://github.com/${input.repository}/pull/${input.number}`,
146 state: "open",
147 headBranch: "feature",
148 baseBranch: "main",
149 updatedAt: "2026-08-27T00:00:00.000Z",
150 ...overrides,
151 };
152}
153
154interface HarnessOptions {
155 readonly invalidate?: PullRequestService.PullRequestService["Service"]["invalidate"];
156 readonly snapshot: TestShellSnapshot;
157 readonly summary?: (
158 input: PullRequestRef,
159 ) => Effect.Effect<PullRequestSummary, PullRequestOperationError>;
160 readonly stack?: (
161 input: PullRequestRef,
162 ) => Effect.Effect<PullRequestStack | null, PullRequestOperationError>;
163}
164
165const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: HarnessOptions) {
166 const activation = yield* Deferred.make<void>();
167 const snapshots = yield* Ref.make(options.snapshot);
168 const snapshotReads = yield* Queue.unbounded<void>();
169 const shellSnapshotReads = yield* Ref.make(0);
170 const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
171 const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]);
172 const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
173 const stackCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
174
175 const summary: PullRequestService.PullRequestService["Service"]["summary"] = (
176 input,
177 readOptions,
178 ) =>
179 Effect.gen(function* () {
180 assert.strictEqual(readOptions?.recoverTransientFailure, false);
181 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
182 return yield* options.summary?.(input) ?? Effect.succeed(makeSummary(input));
183 });
184
185 const stack: PullRequestService.PullRequestService["Service"]["stack"] = (input, readOptions) =>
186 Effect.gen(function* () {
187 assert.strictEqual(readOptions?.includeDetails, false);
188 yield* Ref.update(stackCalls, (calls) => [...calls, input]);
189 return yield* options.stack?.(input) ?? Effect.succeed(null);
190 });
191
192 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
193 if (command.type === "thread.pull-request-link.sync") {
194 return Ref.update(syncCommands, (recorded) => [...recorded, command]).pipe(
195 Effect.as({ sequence: 1, storedEvents: [] }),
196 );
197 }
198 if (command.type === "thread.pull-request.link") {
199 return Ref.update(linkCommands, (recorded) => [...recorded, command]).pipe(
200 Effect.as({ sequence: 1, storedEvents: [] }),
201 );
202 }
203 return Effect.die(new Error(`Unexpected command: ${command.type}`));
204 };
205
206 const dependencies = Layer.mergeAll(
207 Layer.mock(PullRequestService.PullRequestService)({
208 summary,
209 stack,
210 invalidate: options.invalidate ?? (() => Effect.void),
211 }),
212 Layer.mock(ProjectionStore.ProjectionStoreV2)({
213 // Mirrors the store's filter: active threads that have at least one link.
214 getThreadsWithPullRequests: () =>
215 Queue.offer(snapshotReads, undefined).pipe(
216 Effect.andThen(Ref.get(snapshots)),
217 Effect.map((snapshot) =>
218 snapshot.threads
219 .filter((thread) => thread.archivedAt === null && thread.pullRequests.length > 0)
220 .map((thread) => ({
221 id: thread.id,
222 projectId: thread.projectId,
223 settledOverride: thread.settledOverride,
224 settledAt: thread.settledAt === null ? null : DateTime.makeUnsafe(thread.settledAt),
225 pullRequests: thread.pullRequests,
226 })),
227 ),
228 ),
229 }),
230 Layer.mock(Orchestrator.OrchestratorV2)({
231 getShellSnapshot: () =>
232 Ref.update(shellSnapshotReads, (count) => count + 1).pipe(
233 Effect.andThen(Effect.die(new Error("pull request sync must not read the shell"))),
234 ),
235 dispatch,
236 streamDomainEvents: Stream.empty,
237 }),
238 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
239 Layer.succeed(Crypto.Crypto, testCrypto),
240 );
241
242 return {
243 activation,
244 snapshots,
245 snapshotReads,
246 shellSnapshotReads,
247 syncCommands,
248 linkCommands,
249 summaryCalls,
250 stackCalls,
251 layer: PullRequestSyncReactor.layer.pipe(Layer.provide(dependencies)),
252 };
253});
254
255type Harness = Effect.Success<ReturnType<typeof makeHarness>>;
256
257const startAndSweep = Effect.fn("startPullRequestSyncHarness")(function* (fixture: Harness) {
258 const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
259 yield* reactor.start();
260 yield* Deferred.succeed(fixture.activation, undefined);
261 yield* Queue.take(fixture.snapshotReads);
262 yield* reactor.drain;
263 return reactor;
264});
265
266const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* (
267 fixture: Harness,
268 reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
269) {
270 yield* TestClock.adjust("1 minute");
271 yield* Queue.take(fixture.snapshotReads);
272 yield* reactor.drain;
273});
274
275/** What the reactor would have persisted, so the next sweep sees its own writes. */
276function applySync(
277 snapshot: TestShellSnapshot,
278 commands: ReadonlyArray<SyncCommand>,
279): TestShellSnapshot {
280 return {
281 ...snapshot,
282 snapshotSequence: snapshot.snapshotSequence + 1,
283 threads: snapshot.threads.map((thread) => ({
284 ...thread,
285 pullRequests: thread.pullRequests.map((link) => {
286 const command = commands.findLast(
287 (candidate) => candidate.threadId === thread.id && candidate.number === link.number,
288 );
289 return command === undefined
290 ? link
291 : { ...link, snapshot: command.snapshot, stack: command.stack };
292 }),
293 })),
294 };
295}
296
297describe("PullRequestSyncReactor", () => {
298 it.effect("retries a failed stack read after the summary becomes terminal", () =>
299 Effect.scoped(
300 Effect.gen(function* () {
301 yield* TestClock.setTime(Date.parse(NOW));
302 let attempts = 0;
303 const nativeStack: PullRequestStack = {
304 id: "stack",
305 number: 7,
306 url: "https://github.com/owner/repository/stacks/7",
307 base: "main",
308 layers: [{ number: 7, headBranch: "feature", state: "merged" }],
309 };
310 const fixture = yield* makeHarness({
311 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]),
312 summary: (input) =>
313 Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
314 stack: () =>
315 ++attempts === 1
316 ? Effect.fail(
317 new PullRequestOperationError({
318 operation: "stack",
319 detail: "temporary failure",
320 }),
321 )
322 : Effect.succeed(nativeStack),
323 });
324 yield* Effect.gen(function* () {
325 const reactor = yield* startAndSweep(fixture);
326 const commands = yield* Ref.get(fixture.syncCommands);
327 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
328 yield* sweepAgain(fixture, reactor);
329 assert.strictEqual(attempts, 2);
330 assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, {
331 kind: "native",
332 ...nativeStack,
333 });
334 }).pipe(Effect.provide(fixture.layer));
335 }),
336 ),
337 );
338
339 it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () =>
340 Effect.scoped(
341 Effect.gen(function* () {
342 yield* TestClock.setTime(Date.parse(NOW));
343 const fixture = yield* makeHarness({
344 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]),
345 });
346 yield* Effect.gen(function* () {
347 const reactor = yield* startAndSweep(fixture);
348 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0);
349 yield* reactor.requestSync({
350 host: "github.com",
351 repository: "owner/repository",
352 number: 7,
353 });
354 yield* Queue.take(fixture.snapshotReads);
355 yield* reactor.drain;
356 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
357 }).pipe(Effect.provide(fixture.layer));
358 }),
359 ),
360 );
361 it.effect("snapshots an unsynced link once and writes it to the thread", () =>
362 Effect.scoped(
363 Effect.gen(function* () {
364 yield* TestClock.setTime(Date.parse(NOW));
365 const fixture = yield* makeHarness({
366 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
367 summary: (input) =>
368 Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })),
369 });
370
371 yield* Effect.gen(function* () {
372 yield* startAndSweep(fixture);
373
374 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
375 {
376 projectId: PROJECT_ID,
377 host: "github.com",
378 repository: "owner/repository",
379 number: 42,
380 },
381 ]);
382 assert.deepStrictEqual(
383 (yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest),
384 [
385 {
386 type: "thread.pull-request-link.sync",
387 threadId: ThreadId.make("one"),
388 host: "github.com",
389 repository: "owner/repository",
390 number: 42,
391 snapshot: {
392 state: "open",
393 title: "Ship it",
394 headBranch: "feature",
395 baseBranch: "main",
396 isDraft: true,
397 updatedAt: "2026-08-27T00:00:00.000Z",
398 syncedAt: NOW,
399 closedAt: null,
400 mergedAt: null,
401 },
402 stack: null,
403 },
404 ],
405 );
406 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
407 // Reads only linked threads, never the full shell snapshot of every thread.
408 assert.strictEqual(yield* Ref.get(fixture.shellSnapshotReads), 0);
409 }).pipe(Effect.provide(fixture.layer));
410 }),
411 ),
412 );
413
414 it.effect("asks the host once for a pull request shared by two threads", () =>
415 Effect.scoped(
416 Effect.gen(function* () {
417 yield* TestClock.setTime(Date.parse(NOW));
418 const fixture = yield* makeHarness({
419 snapshot: makeSnapshot([
420 makeThread("one", { pullRequests: [makeLink(42)] }),
421 makeThread("two", {
422 pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })],
423 }),
424 ]),
425 });
426
427 yield* Effect.gen(function* () {
428 yield* startAndSweep(fixture);
429
430 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
431 const commands = yield* Ref.get(fixture.syncCommands);
432 assert.deepStrictEqual(
433 commands
434 .map((command) => [command.threadId, command.repository] as const)
435 .sort((left, right) => left[0].localeCompare(right[0])),
436 [
437 [ThreadId.make("one"), "owner/repository"],
438 [ThreadId.make("two"), "Owner/Repository"],
439 ],
440 );
441 }).pipe(Effect.provide(fixture.layer));
442 }),
443 ),
444 );
445
446 it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>
447 Effect.scoped(
448 Effect.gen(function* () {
449 const fixture = yield* makeHarness({
450 snapshot: makeSnapshot([
451 makeThread("one", {
452 pullRequests: [
453 makeLink(42, null, {
454 host: "forge.example",
455 url: "http://forge.example:3000/owner/repository/pulls/42",
456 }),
457 ],
458 }),
459 ]),
460 summary: (input) => Effect.succeed(makeSummary(input)),
461 });
462 yield* Effect.gen(function* () {
463 yield* startAndSweep(fixture);
464 assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");
465 assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");
466 }).pipe(Effect.provide(fixture.layer));
467 }),
468 ),
469 );
470
471 it.effect("dispatches nothing when the host snapshot is unchanged", () =>
472 Effect.scoped(
473 Effect.gen(function* () {
474 yield* TestClock.setTime(Date.parse(NOW));
475 const fixture = yield* makeHarness({
476 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
477 });
478
479 yield* Effect.gen(function* () {
480 const reactor = yield* startAndSweep(fixture);
481 const firstSweep = yield* Ref.get(fixture.syncCommands);
482 assert.strictEqual(firstSweep.length, 1);
483 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
484
485 yield* sweepAgain(fixture, reactor);
486
487 // Still open on an active thread, so the host was asked again, but nothing changed.
488 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
489 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
490 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
491 }).pipe(Effect.provide(fixture.layer));
492 }),
493 ),
494 );
495
496 it.effect("refreshes closed links through the reactor's project after reopening elsewhere", () =>
497 Effect.scoped(
498 Effect.gen(function* () {
499 yield* TestClock.setTime(Date.parse(NOW));
500 const stale = yield* Ref.make(true);
501 const fixture = yield* makeHarness({
502 snapshot: makeSnapshot([
503 makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
504 makeThread("second", {
505 projectId: ProjectId.make("second-project"),
506 pullRequests: [makeLink(42, { state: "closed" })],
507 }),
508 ]),
509 invalidate: ({ reference }) =>
510 reference?.projectId === makeProject().id && reference.host === "github.com"
511 ? Ref.set(stale, false)
512 : Effect.void,
513 summary: (input) =>
514 Ref.get(stale).pipe(
515 Effect.map((cached) => makeSummary(input, { state: cached ? "closed" : "open" })),
516 ),
517 });
518 yield* Effect.gen(function* () {
519 const reactor = yield* startAndSweep(fixture);
520 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
521 yield* reactor.requestSync({
522 host: "github.com",
523 repository: "owner/repository",
524 number: 42,
525 });
526 yield* Queue.take(fixture.snapshotReads);
527 yield* reactor.drain;
528 const commands = yield* Ref.get(fixture.syncCommands);
529 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
530 const snapshot = yield* Ref.get(fixture.snapshots);
531 assert.deepStrictEqual(
532 snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
533 ["open", "open"],
534 );
535 }).pipe(Effect.provide(fixture.layer));
536 }),
537 ),
538 );
539
540 it.effect("stops asking the host once a pull request is merged", () =>
541 Effect.scoped(
542 Effect.gen(function* () {
543 yield* TestClock.setTime(Date.parse(NOW));
544 const fixture = yield* makeHarness({
545 snapshot: makeSnapshot([
546 makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
547 ]),
548 });
549
550 yield* Effect.gen(function* () {
551 const reactor = yield* startAndSweep(fixture);
552 yield* sweepAgain(fixture, reactor);
553
554 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
555 assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
556
557 yield* reactor.requestSync({
558 host: "github.com",
559 repository: "owner/repository",
560 number: 1,
561 });
562 yield* Queue.take(fixture.snapshotReads);
563 yield* reactor.drain;
564
565 assert.deepStrictEqual(
566 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
567 [1],
568 );
569 }).pipe(Effect.provide(fixture.layer));
570 }),
571 ),
572 );
573
574 it.effect("discovers externally reopened pull requests after fifteen minutes", () =>
575 Effect.scoped(
576 Effect.gen(function* () {
577 yield* TestClock.setTime(Date.parse(NOW));
578 const state = yield* Ref.make<"closed" | "open">("closed");
579 const fixture = yield* makeHarness({
580 snapshot: makeSnapshot([
581 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
582 ]),
583 summary: (input) =>
584 Ref.get(state).pipe(Effect.map((state) => makeSummary(input, { state }))),
585 });
586 yield* Effect.gen(function* () {
587 const reactor = yield* startAndSweep(fixture);
588 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
589 yield* Ref.set(state, "open");
590 for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
591 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
592 yield* sweepAgain(fixture, reactor);
593 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
594 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
595 }).pipe(Effect.provide(fixture.layer));
596 }),
597 ),
598 );
599
600 it.effect("preserves a refresh requested while an older host read is in flight", () =>
601 Effect.scoped(
602 Effect.gen(function* () {
603 yield* TestClock.setTime(Date.parse(NOW));
604 const reading = yield* Deferred.make<void>();
605 const release = yield* Deferred.make<void>();
606 let calls = 0;
607 const fixture = yield* makeHarness({
608 snapshot: makeSnapshot([]),
609 summary: (input) =>
610 Effect.gen(function* () {
611 calls += 1;
612 if (calls === 1) {
613 yield* Deferred.succeed(reading, undefined);
614 yield* Deferred.await(release);
615 }
616 return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
617 }),
618 });
619 yield* Effect.gen(function* () {
620 const reactor = yield* startAndSweep(fixture);
621 yield* Ref.set(
622 fixture.snapshots,
623 makeSnapshot([
624 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
625 ]),
626 );
627 const key = { host: "github.com", repository: "owner/repository", number: 2 };
628 yield* reactor.requestSync(key);
629 yield* Deferred.await(reading);
630 yield* reactor.requestSync(key);
631 yield* Deferred.succeed(release, undefined);
632 yield* reactor.drain;
633 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
634 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
635 }).pipe(Effect.provide(fixture.layer));
636 }),
637 ),
638 );
639
640 it.effect("reads a burst of requested links in one sweep", () =>
641 Effect.scoped(
642 Effect.gen(function* () {
643 yield* TestClock.setTime(Date.parse(NOW));
644 const reading = yield* Deferred.make<void>();
645 const release = yield* Deferred.make<void>();
646 const fixture = yield* makeHarness({
647 snapshot: makeSnapshot([]),
648 summary: (input) =>
649 Effect.gen(function* () {
650 if (input.number === 1) {
651 yield* Deferred.succeed(reading, undefined);
652 yield* Deferred.await(release);
653 }
654 return makeSummary(input);
655 }),
656 });
657 yield* Effect.gen(function* () {
658 const reactor = yield* startAndSweep(fixture);
659 yield* Ref.set(
660 fixture.snapshots,
661 makeSnapshot(
662 [1, 2, 3, 4].map((number) =>
663 makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
664 ),
665 ),
666 );
667 const request = (number: number) =>
668 reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
669 yield* request(1);
670 yield* Deferred.await(reading);
671 yield* Effect.forEach([2, 3, 4], request, { discard: true });
672 yield* Deferred.succeed(release, undefined);
673 yield* reactor.drain;
674 // One sweep for the first link and one for the three that arrived while it read.
675 assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
676 assert.deepStrictEqual(
677 (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
678 [1, 2, 3, 4],
679 );
680 }).pipe(Effect.provide(fixture.layer));
681 }),
682 ),
683 );
684
685 it.effect("skips the stack read for a pull request the summary places in no stack", () =>
686 Effect.scoped(
687 Effect.gen(function* () {
688 yield* TestClock.setTime(Date.parse(NOW));
689 const fixture = yield* makeHarness({
690 snapshot: makeSnapshot([
691 makeThread("unstacked", { pullRequests: [makeLink(1)] }),
692 makeThread("stacked", { pullRequests: [makeLink(2)] }),
693 makeThread("unknown", { pullRequests: [makeLink(3)] }),
694 ]),
695 summary: (input) =>
696 Effect.succeed(
697 makeSummary(
698 input,
699 input.number === 1
700 ? { stack: null }
701 : input.number === 2
702 ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
703 : {},
704 ),
705 ),
706 });
707 yield* Effect.gen(function* () {
708 yield* startAndSweep(fixture);
709 assert.deepStrictEqual(
710 (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
711 [2, 3],
712 );
713 assert.deepStrictEqual(
714 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
715 [1, 2, 3],
716 );
717 }).pipe(Effect.provide(fixture.layer));
718 }),
719 ),
720 );
721
722 it.effect("polls open pull requests on settled threads every fifteen minutes", () =>
723 Effect.scoped(
724 Effect.gen(function* () {
725 yield* TestClock.setTime(Date.parse(NOW));
726 const fixture = yield* makeHarness({
727 snapshot: makeSnapshot([
728 makeThread("settled", {
729 settledOverride: "settled",
730 settledAt: "2026-08-21T00:00:00.000Z",
731 pullRequests: [makeLink(5, { state: "open" })],
732 }),
733 ]),
734 });
735
736 yield* Effect.gen(function* () {
737 const reactor = yield* startAndSweep(fixture);
738 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
739
740 yield* sweepAgain(fixture, reactor);
741 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
742
743 for (let index = 0; index < 13; index += 1) yield* sweepAgain(fixture, reactor);
744 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
745
746 yield* sweepAgain(fixture, reactor);
747 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
748 }).pipe(Effect.provide(fixture.layer));
749 }),
750 ),
751 );
752
753 it.effect("auto-links missing native stack layers and leaves dismissed ones alone", () =>
754 Effect.scoped(
755 Effect.gen(function* () {
756 yield* TestClock.setTime(Date.parse(NOW));
757 const stack: PullRequestStack = {
758 id: "stack-1",
759 number: 42,
760 url: "https://github.com/owner/repository/stack/1",
761 base: "main",
762 layers: [
763 { number: 41, headBranch: "layer-1", state: "merged" },
764 { number: 42, headBranch: "layer-2", state: "open" },
765 { number: 43, headBranch: "layer-3", state: "open" },
766 ],
767 };
768 const fixture = yield* makeHarness({
769 snapshot: makeSnapshot([
770 makeThread("one", {
771 pullRequests: [
772 makeLink(42),
773 makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
774 ],
775 }),
776 ]),
777 stack: () => Effect.succeed(stack),
778 });
779
780 yield* Effect.gen(function* () {
781 yield* startAndSweep(fixture);
782
783 const syncCommands = yield* Ref.get(fixture.syncCommands);
784 assert.deepStrictEqual(
785 syncCommands.map((command) => [command.number, command.stack] as const),
786 [[42, { kind: "native", ...stack }]],
787 );
788 assert.deepStrictEqual(
789 (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
790 [
791 {
792 type: "thread.pull-request.link",
793 threadId: ThreadId.make("one"),
794 host: "github.com",
795 repository: "owner/repository",
796 number: 43,
797 url: "https://github.com/owner/repository/pull/43",
798 source: "stack",
799 },
800 ],
801 );
802 }).pipe(Effect.provide(fixture.layer));
803 }),
804 ),
805 );
806
807 it.effect("keeps existing snapshots and continues when the host fails", () =>
808 Effect.scoped(
809 Effect.gen(function* () {
810 yield* TestClock.setTime(Date.parse(NOW));
811 const fixture = yield* makeHarness({
812 snapshot: makeSnapshot([
813 makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
814 makeThread("fine", { pullRequests: [makeLink(8)] }),
815 ]),
816 summary: (input) =>
817 input.number === 7
818 ? Effect.fail(
819 new PullRequestOperationError({ operation: "summary", detail: "host down" }),
820 )
821 : Effect.succeed(makeSummary(input)),
822 });
823
824 yield* Effect.gen(function* () {
825 yield* startAndSweep(fixture);
826
827 assert.deepStrictEqual(
828 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
829 [8],
830 );
831 }).pipe(Effect.provide(fixture.layer));
832 }),
833 ),
834 );
835});