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

PullRequestSyncReactor.test.ts

1,319 lines48.4 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Stream from "effect/Stream";
3import {
4 EventId,
5 MessageId,
6 ProjectId,
7 ProviderInstanceId,
8 PullRequestOperationError,
9 RunId,
10 ThreadId,
11 TurnItemId,
12 type OrchestrationV2Command as OrchestrationCommand,
13 type OrchestrationV2DomainEvent,
14 type OrchestrationV2Run,
15 type OrchestrationProjectShell,
16 type PullRequestRef,
17 type PullRequestStack,
18 type PullRequestSummary,
19 type ThreadPullRequestKey,
20 type ThreadPullRequestLink,
21 type ThreadPullRequestSnapshot,
22} from "@t3tools/contracts";
23import { assert, describe, it } from "@effect/vitest";
24import * as Clock from "effect/Clock";
25import * as Crypto from "effect/Crypto";
26import * as DateTime from "effect/DateTime";
27import * as Deferred from "effect/Deferred";
28import * as Effect from "effect/Effect";
29import * as Layer from "effect/Layer";
30import * as Logger from "effect/Logger";
31import * as Queue from "effect/Queue";
32import * as Ref from "effect/Ref";
33import { TestClock } from "effect/testing";
34​
35import { PullRequestProviderError } from "@t3tools/source-control-core/server/PullRequestProvider";
36import * as GitManager from "../git/GitManager.ts";
37import * as PullRequestService from "../pullRequest/PullRequestService.ts";
38import * as ServerActivation from "../serverActivation.ts";
39import * as Orchestrator from "./Orchestrator.ts";
40import * as ProjectionStore from "./ProjectionStore.ts";
41import * as PullRequestSyncReactor from "./PullRequestSyncReactor.ts";
42import type { PullRequestTestThread } from "./testkit/pullRequestFixtures.ts";
43​
44const NOW = "2026-08-28T12:00:00.000Z";
45const PROJECT_ID = ProjectId.make("sync-project");
46​
47type SyncCommand = Extract<
48 OrchestrationCommand,
49 { readonly type: "thread.pull-request-link.sync" }
50>;
51type LinkCommand = Extract<OrchestrationCommand, { readonly type: "thread.pull-request.link" }>;
52​
53const testCrypto = Crypto.make({
54 randomBytes: (size) => new Uint8Array(size).fill(1),
55 digest: (_algorithm, data) => Effect.succeed(data),
56});
57​
58function makeProject(id: ProjectId = PROJECT_ID): OrchestrationProjectShell {
59 return {
60 id,
61 title: `Project ${id}`,
62 workspaceRoot: "/workspace/project",
63 defaultModelSelection: null,
64 scripts: [],
65 createdAt: "2026-08-01T00:00:00.000Z",
66 updatedAt: NOW,
67 };
69​
70function makeThread(
71 id: string,
72 overrides: Partial<PullRequestTestThread> = {},
73): PullRequestTestThread {
74 return {
75 id: ThreadId.make(id),
76 projectId: PROJECT_ID,
77 title: id,
78 modelSelection: {
79 instanceId: ProviderInstanceId.make("codex"),
80 model: "gpt-5",
81 },
82 runtimeMode: "full-access",
83 interactionMode: "default",
84 branch: null,
85 worktreePath: null,
86 pullRequests: [],
87 createdAt: "2026-08-01T00:00:00.000Z",
88 updatedAt: "2026-08-20T00:00:00.000Z",
89 archivedAt: null,
90 settledOverride: null,
91 settledAt: null,
92 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
93 ...overrides,
94 };
96​
97function makeLink(
98 number: number,
99 snapshot: Partial<ThreadPullRequestSnapshot> | null = null,
100 overrides: Partial<ThreadPullRequestLink> = {},
101): ThreadPullRequestLink {
102 return {
103 host: "github.com",
104 repository: "owner/repository",
105 number,
106 url: `https://github.com/owner/repository/pull/${number}`,
107 source: "manual",
108 linkedAt: "2026-08-10T00:00:00.000Z",
109 snapshot:
110 snapshot === null
111 ? null
112 : {
113 state: "open",
114 title: "Pull request",
115 headBranch: "feature",
116 baseBranch: "main",
117 isDraft: false,
118 updatedAt: "2026-08-27T00:00:00.000Z",
119 syncedAt: "2026-08-27T00:00:00.000Z",
120 ...snapshot,
121 },
122 stack: null,
123 ...overrides,
124 };
126​
127interface TestShellSnapshot {
128 readonly snapshotSequence: number;
129 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
130 readonly threads: ReadonlyArray<PullRequestTestThread>;
131 readonly updatedAt: string;
133​
134function makeSnapshot(
135 threads: ReadonlyArray<PullRequestTestThread>,
136 snapshotSequence = 1,
137): TestShellSnapshot {
138 return {
139 snapshotSequence,
140 projects: [makeProject()],
141 threads,
142 updatedAt: NOW,
143 };
145​
146function makeSummary(
147 input: PullRequestRef,
148 overrides: Partial<PullRequestSummary> = {},
149): PullRequestSummary {
150 return {
151 provider: SourceControlProviderKind.make("github"),
152 projectId: input.projectId,
153 repository: input.repository,
154 number: input.number,
155 title: "Pull request",
156 url: `https://github.com/${input.repository}/pull/${input.number}`,
157 state: "open",
158 headBranch: "feature",
159 baseBranch: "main",
160 updatedAt: "2026-08-27T00:00:00.000Z",
161 ...overrides,
162 };
164​
165interface HarnessOptions {
166 readonly invalidate?: PullRequestService.PullRequestService["Service"]["invalidate"];
167 readonly snapshot: TestShellSnapshot;
168 readonly summary?: (
169 input: PullRequestRef,
170 ) => Effect.Effect<PullRequestSummary, PullRequestOperationError>;
171 readonly stack?: (
172 input: PullRequestRef,
173 ) => Effect.Effect<PullRequestStack | null, PullRequestOperationError>;
175​
176const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: HarnessOptions) {
177 const activation = yield* Deferred.make<void>();
178 const snapshots = yield* Ref.make(options.snapshot);
179 const snapshotReads = yield* Queue.unbounded<void>();
180 const shellSnapshotReads = yield* Ref.make(0);
181 const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
182 const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]);
183 const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
184 const stackCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
185 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
186 const stateChanges = yield* Queue.unbounded<ThreadPullRequestKey>();
187​
188 const summary: PullRequestService.PullRequestService["Service"]["summary"] = (
189 input,
190 readOptions,
191 ) =>
192 Effect.gen(function* () {
193 assert.strictEqual(readOptions?.recoverTransientFailure, false);
194 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
195 return yield* options.summary?.(input) ?? Effect.succeed(makeSummary(input));
196 });
197​
198 const stack: PullRequestService.PullRequestService["Service"]["stack"] = (input, readOptions) =>
199 Effect.gen(function* () {
200 assert.strictEqual(readOptions?.includeDetails, false);
201 yield* Ref.update(stackCalls, (calls) => [...calls, input]);
202 return yield* options.stack?.(input) ?? Effect.succeed(null);
203 });
204​
205 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
206 if (command.type === "thread.pull-request-link.sync") {
207 return Ref.update(syncCommands, (recorded) => [...recorded, command]).pipe(
208 Effect.as({ sequence: 1, storedEvents: [] }),
209 );
210 }
211 if (command.type === "thread.pull-request.link") {
212 return Ref.update(linkCommands, (recorded) => [...recorded, command]).pipe(
213 Effect.as({ sequence: 1, storedEvents: [] }),
214 );
215 }
216 return Effect.die(new Error(`Unexpected command: ${command.type}`));
217 };
218​
219 const layerDependencies = Layer.mergeAll(
220 Layer.mock(PullRequestService.PullRequestService)({
221 summary,
222 stack,
223 invalidate: options.invalidate ?? (() => Effect.void),
224 subscribeStateChanges: Effect.succeed(Stream.fromQueue(stateChanges)),
225 }),
226 Layer.mock(GitManager.GitManager)({
227 subscribePullRequestStateChanges: Effect.succeed(Stream.empty),
228 }),
229 Layer.mock(ProjectionStore.ProjectionStoreV2)({
230 getThreadsWithPullRequests: (threadId) =>
231 Queue.offer(snapshotReads, undefined).pipe(
232 Effect.andThen(Ref.get(snapshots)),
233 Effect.map((snapshot) =>
234 snapshot.threads
235 .filter(
236 (thread) =>
237 (threadId === undefined || thread.id === threadId) &&
238 thread.archivedAt === null &&
239 thread.pullRequests.length > 0,
240 )
241 .map((thread) => ({
242 id: thread.id,
243 projectId: thread.projectId,
244 lineage: {
245 parentThreadId: null,
246 relationshipToParent: null,
247 rootThreadId: thread.id,
248 },
249 settledOverride: thread.settledOverride,
250 settledAt: thread.settledAt === null ? null : DateTime.makeUnsafe(thread.settledAt),
251 pullRequests: thread.pullRequests,
252 })),
253 ),
254 ),
255 }),
256 Layer.mock(Orchestrator.OrchestratorV2)({
257 getShellSnapshot: () =>
258 Ref.update(shellSnapshotReads, (count) => count + 1).pipe(
259 Effect.andThen(Effect.die(new Error("pull request sync must not read the shell"))),
260 ),
261 dispatch,
262 streamDomainEvents: Stream.fromQueue(domainEvents),
263 }),
264 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
265 Layer.succeed(Crypto.Crypto, testCrypto),
266 );
267​
268 return {
269 activation,
270 snapshots,
271 snapshotReads,
272 shellSnapshotReads,
273 syncCommands,
274 linkCommands,
275 summaryCalls,
276 stackCalls,
277 domainEvents,
278 stateChanges,
279 layer: PullRequestSyncReactor.layer.pipe(Layer.provide(layerDependencies)),
280 };
281});
282​
283type Harness = Effect.Success<ReturnType<typeof makeHarness>>;
284​
285const startAndSweep = Effect.fn("startPullRequestSyncHarness")(function* (fixture: Harness) {
286 const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
287 yield* reactor.start();
288 yield* Deferred.succeed(fixture.activation, undefined);
289 yield* Queue.take(fixture.snapshotReads);
290 yield* reactor.drain;
291 return reactor;
292});
293​
294const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* (
295 fixture: Harness,
296 reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
297) {
298 yield* TestClock.adjust("1 minute");
299 yield* Queue.take(fixture.snapshotReads);
300 yield* reactor.drain;
301});
302​
303function runUpdated(
304 threadId: ThreadId,
305 status: OrchestrationV2Run["status"],
306): OrchestrationV2DomainEvent {
307 const runId = RunId.make(`run:${threadId}:1`);
308 const at = DateTime.makeUnsafe(NOW);
309 return {
310 type: "run.updated",
311 id: EventId.make(`event:${threadId}:${status}`),
312 threadId,
313 runId,
314 occurredAt: at,
315 payload: {
316 id: runId,
317 threadId,
318 ordinal: 1,
319 providerInstanceId: ProviderInstanceId.make("codex"),
320 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
321 providerThreadId: null,
322 userMessageId: MessageId.make(`message:${threadId}:1`),
323 rootNodeId: null,
324 activeAttemptId: null,
325 status,
326 requestedAt: at,
327 startedAt: at,
328 completedAt: at,
329 checkpointId: null,
330 contextHandoffId: null,
331 },
332 };
334​
335function commandRan(threadId: ThreadId, input: string): OrchestrationV2DomainEvent {
336 const runId = RunId.make(`run:${threadId}:1`);
337 const at = DateTime.makeUnsafe(NOW);
338 return {
339 type: "turn-item.updated",
340 id: EventId.make(`event:${threadId}:command`),
341 threadId,
342 runId,
343 occurredAt: at,
344 payload: {
345 id: TurnItemId.make(`item:${threadId}:command`),
346 threadId,
347 runId,
348 nodeId: null,
349 providerThreadId: null,
350 providerTurnId: null,
351 nativeItemRef: null,
352 parentItemId: null,
353 ordinal: 1,
354 status: "completed",
355 title: null,
356 startedAt: at,
357 completedAt: at,
358 updatedAt: at,
359 type: "command_execution",
360 input,
361 },
362 };
364​
365function applySync(
366 snapshot: TestShellSnapshot,
367 commands: ReadonlyArray<SyncCommand>,
368): TestShellSnapshot {
369 return {
370 ...snapshot,
371 snapshotSequence: snapshot.snapshotSequence + 1,
372 threads: snapshot.threads.map((thread) => ({
373 ...thread,
374 pullRequests: thread.pullRequests.map((link) => {
375 const command = commands.findLast(
376 (candidate) => candidate.threadId === thread.id && candidate.number === link.number,
377 );
378 return command === undefined
379 ? link
380 : { ...link, snapshot: command.snapshot, stack: command.stack };
381 }),
382 })),
383 };
385​
386describe("PullRequestSyncReactor", () => {
387 it.effect("retries a failed stack read after the summary becomes terminal", () =>
388 Effect.scoped(
389 Effect.gen(function* () {
390 yield* TestClock.setTime(Date.parse(NOW));
391 let attempts = 0;
392 const nativeStack: PullRequestStack = {
393 id: "stack",
394 number: 7,
395 url: "https://github.com/owner/repository/stacks/7",
396 base: "main",
397 layers: [{ number: 7, headBranch: "feature", state: "merged" }],
398 };
399 const fixture = yield* makeHarness({
400 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]),
401 summary: (input) =>
402 Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
403 stack: () =>
404 ++attempts === 1
405 ? Effect.fail(
406 new PullRequestOperationError({
407 operation: "stack",
408 detail: "temporary failure",
409 }),
410 )
411 : Effect.succeed(nativeStack),
412 });
413 yield* Effect.gen(function* () {
414 const reactor = yield* startAndSweep(fixture);
415 const commands = yield* Ref.get(fixture.syncCommands);
416 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
417 yield* sweepAgain(fixture, reactor);
418 assert.strictEqual(attempts, 2);
419 assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, {
420 kind: "native",
421 ...nativeStack,
422 });
423 }).pipe(Effect.provide(fixture.layer));
424 }),
425 ),
426 );
427​
428 it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () =>
429 Effect.scoped(
430 Effect.gen(function* () {
431 yield* TestClock.setTime(Date.parse(NOW));
432 const fixture = yield* makeHarness({
433 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]),
434 });
435 yield* Effect.gen(function* () {
436 const reactor = yield* startAndSweep(fixture);
437 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0);
438 yield* reactor.requestSync({
439 host: "github.com",
440 repository: "owner/repository",
441 number: 7,
442 });
443 yield* Queue.take(fixture.snapshotReads);
444 yield* reactor.drain;
445 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
446 }).pipe(Effect.provide(fixture.layer));
447 }),
448 ),
449 );
450 it.effect("snapshots an unsynced link once and writes it to the thread", () =>
451 Effect.scoped(
452 Effect.gen(function* () {
453 yield* TestClock.setTime(Date.parse(NOW));
454 const fixture = yield* makeHarness({
455 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
456 summary: (input) =>
457 Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })),
458 });
459​
460 yield* Effect.gen(function* () {
461 yield* startAndSweep(fixture);
462​
463 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
464 {
465 projectId: PROJECT_ID,
466 host: "github.com",
467 repository: "owner/repository",
468 number: 42,
469 },
470 ]);
471 assert.deepStrictEqual(
472 (yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest),
473 [
474 {
475 type: "thread.pull-request-link.sync",
476 threadId: ThreadId.make("one"),
477 host: "github.com",
478 repository: "owner/repository",
479 number: 42,
480 snapshot: {
481 state: "open",
482 title: "Ship it",
483 headBranch: "feature",
484 baseBranch: "main",
485 isDraft: true,
486 updatedAt: "2026-08-27T00:00:00.000Z",
487 syncedAt: NOW,
488 closedAt: null,
489 mergedAt: null,
490 },
491 stack: null,
492 },
493 ],
494 );
495 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
496 assert.strictEqual(yield* Ref.get(fixture.shellSnapshotReads), 0);
497 }).pipe(Effect.provide(fixture.layer));
498 }),
499 ),
500 );
501​
502 it.effect("asks the host once for a pull request shared by two threads in one project", () =>
503 Effect.scoped(
504 Effect.gen(function* () {
505 yield* TestClock.setTime(Date.parse(NOW));
506 const fixture = yield* makeHarness({
507 snapshot: makeSnapshot([
508 makeThread("one", { pullRequests: [makeLink(42)] }),
509 makeThread("two", {
510 pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })],
511 }),
512 ]),
513 });
514​
515 yield* Effect.gen(function* () {
516 yield* startAndSweep(fixture);
517​
518 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
519 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
520 const commands = yield* Ref.get(fixture.syncCommands);
521 assert.deepStrictEqual(
522 commands
523 .map((command) => [command.threadId, command.repository] as const)
524 .sort((left, right) => left[0].localeCompare(right[0])),
525 [
526 [ThreadId.make("one"), "owner/repository"],
527 [ThreadId.make("two"), "Owner/Repository"],
528 ],
529 );
530 }).pipe(Effect.provide(fixture.layer));
531 }),
532 ),
533 );
534​
535 it.effect.each(["summary", "stack"] as const)(
536 "isolates a failed project %s refresh and retries it after the other project succeeds",
537 (operation) =>
538 Effect.scoped(
539 Effect.gen(function* () {
540 yield* TestClock.setTime(Date.parse(NOW));
541 const otherProject = ProjectId.make("other-project");
542 const link = makeLink(42, { state: "merged", mergedAt: NOW });
543 let failing = true;
544 const failure = new PullRequestOperationError({ operation, detail: "checkout missing" });
545 const fixture = yield* makeHarness({
546 snapshot: makeSnapshot([
547 makeThread("failing", { pullRequests: [link] }),
548 makeThread("healthy", { projectId: otherProject, pullRequests: [link] }),
549 makeThread("same-project", { projectId: otherProject, pullRequests: [link] }),
550 ]),
551 summary: (input) =>
552 failing && input.projectId === PROJECT_ID && operation === "summary"
553 ? Effect.fail(failure)
554 : Effect.succeed(
555 makeSummary(input, {
556 state: "merged",
557 mergedAt: NOW,
558 title: input.projectId,
559 }),
560 ),
561 stack: (input) =>
562 failing && input.projectId === PROJECT_ID && operation === "stack"
563 ? Effect.fail(failure)
564 : Effect.succeed({
565 id: input.projectId,
566 number: 42,
567 url: "https://github.com/owner/repository/stacks/42",
568 base: "main",
569 layers: [{ number: 42, headBranch: "feature", state: "merged" }],
570 }),
571 });
572 yield* Effect.gen(function* () {
573 const reactor = yield* startAndSweep(fixture);
574 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
575 yield* reactor.requestSync(link);
576 yield* Queue.take(fixture.snapshotReads);
577 yield* reactor.drain;
578 const commands = yield* Ref.get(fixture.syncCommands);
579 assert.sameDeepMembers(
580 commands.map((command) => [
581 command.threadId,
582 command.snapshot.title,
583 command.stack?.id,
584 ]),
585 [
586 ["healthy", otherProject, otherProject],
587 ["same-project", otherProject, otherProject],
588 ],
589 );
590 assert.sameMembers(
591 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.projectId),
592 [PROJECT_ID, otherProject],
593 );
594 assert.sameMembers(
595 (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
596 operation === "stack" ? [PROJECT_ID, otherProject] : [otherProject],
597 );
598 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
599 failing = false;
600 yield* sweepAgain(fixture, reactor);
601 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3);
602 assert.strictEqual(
603 (yield* Ref.get(fixture.summaryCalls)).at(-1)?.projectId,
604 PROJECT_ID,
605 );
606 const retried = (yield* Ref.get(fixture.syncCommands)).at(-1);
607 assert.strictEqual(retried?.threadId, ThreadId.make("failing"));
608 assert.strictEqual(retried?.snapshot.title, PROJECT_ID);
609 assert.strictEqual(retried?.stack?.id, PROJECT_ID);
610 }).pipe(Effect.provide(fixture.layer));
611 }),
612 ),
613 );
614​
615 it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>
616 Effect.scoped(
617 Effect.gen(function* () {
618 const fixture = yield* makeHarness({
619 snapshot: makeSnapshot([
620 makeThread("one", {
621 pullRequests: [
622 makeLink(42, null, {
623 host: "forge.example",
624 url: "http://forge.example:3000/owner/repository/pulls/42",
625 }),
626 ],
627 }),
628 ]),
629 summary: (input) => Effect.succeed(makeSummary(input)),
630 });
631 yield* Effect.gen(function* () {
632 yield* startAndSweep(fixture);
633 assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");
634 assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");
635 }).pipe(Effect.provide(fixture.layer));
636 }),
637 ),
638 );
639​
640 it.effect("dispatches nothing when the host snapshot is unchanged", () =>
641 Effect.scoped(
642 Effect.gen(function* () {
643 yield* TestClock.setTime(Date.parse(NOW));
644 const fixture = yield* makeHarness({
645 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
646 summary: (input) => Effect.succeed(makeSummary(input, { updatedAt: NOW })),
647 });
648​
649 yield* Effect.gen(function* () {
650 const reactor = yield* startAndSweep(fixture);
651 const firstSweep = yield* Ref.get(fixture.syncCommands);
652 assert.strictEqual(firstSweep.length, 1);
653 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
654​
655 yield* sweepAgain(fixture, reactor);
656​
657 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
658 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
659 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
660 }).pipe(Effect.provide(fixture.layer));
661 }),
662 ),
663 );
664​
665 it.effect("refreshes closed links through each project after reopening elsewhere", () =>
666 Effect.scoped(
667 Effect.gen(function* () {
668 yield* TestClock.setTime(Date.parse(NOW));
669 const invalidated = yield* Ref.make<ReadonlyArray<ProjectId>>([]);
670 const fixture = yield* makeHarness({
671 snapshot: makeSnapshot([
672 makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
673 makeThread("second", {
674 projectId: ProjectId.make("second-project"),
675 pullRequests: [makeLink(42, { state: "closed" })],
676 }),
677 ]),
678 invalidate: ({ reference }) =>
679 reference !== undefined
680 ? Ref.update(invalidated, (projects) => [...projects, reference.projectId])
681 : Effect.void,
682 summary: (input) =>
683 Ref.get(invalidated).pipe(
684 Effect.map((projects) =>
685 makeSummary(input, {
686 state: projects.includes(input.projectId) ? "open" : "closed",
687 }),
688 ),
689 ),
690 });
691 yield* Effect.gen(function* () {
692 const reactor = yield* startAndSweep(fixture);
693 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
694 yield* reactor.requestSync({
695 host: "github.com",
696 repository: "owner/repository",
697 number: 42,
698 });
699 yield* Queue.take(fixture.snapshotReads);
700 yield* reactor.drain;
701 assert.sameMembers(
702 [...(yield* Ref.get(invalidated))],
703 [PROJECT_ID, ProjectId.make("second-project")],
704 );
705 assert.sameMembers(
706 (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
707 [PROJECT_ID, ProjectId.make("second-project")],
708 );
709 const commands = yield* Ref.get(fixture.syncCommands);
710 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
711 const snapshot = yield* Ref.get(fixture.snapshots);
712 assert.deepStrictEqual(
713 snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
714 ["open", "open"],
715 );
716 }).pipe(Effect.provide(fixture.layer));
717 }),
718 ),
719 );
720​
721 it.effect("stops asking the host once a pull request is merged", () =>
722 Effect.scoped(
723 Effect.gen(function* () {
724 yield* TestClock.setTime(Date.parse(NOW));
725 const fixture = yield* makeHarness({
726 snapshot: makeSnapshot([
727 makeThread("merged", {
728 pullRequests: [
729 makeLink(1, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
730 ],
731 }),
732 ]),
733 });
734​
735 yield* Effect.gen(function* () {
736 const reactor = yield* startAndSweep(fixture);
737 yield* sweepAgain(fixture, reactor);
738​
739 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
740 assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
741​
742 yield* reactor.requestSync({
743 host: "github.com",
744 repository: "owner/repository",
745 number: 1,
746 });
747 yield* Queue.take(fixture.snapshotReads);
748 yield* reactor.drain;
749​
750 assert.deepStrictEqual(
751 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
752 [1],
753 );
754 }).pipe(Effect.provide(fixture.layer));
755 }),
756 ),
757 );
758​
759 it.effect("re-reads a merged pull request until the host supplies its merge time", () =>
760 Effect.scoped(
761 Effect.gen(function* () {
762 yield* TestClock.setTime(Date.parse(NOW));
763 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
764 const fixture = yield* makeHarness({
765 snapshot: makeSnapshot([
766 makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
767 ]),
768 invalidate: ({ reference }) =>
769 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
770 summary: (input) =>
771 Effect.succeed(
772 makeSummary(input, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
773 ),
774 });
775​
776 yield* Effect.gen(function* () {
777 const reactor = yield* startAndSweep(fixture);
778 const firstSweep = yield* Ref.get(fixture.syncCommands);
779 // The held merged summary is dropped so the read reaches the host.
780 assert.deepStrictEqual(yield* Ref.get(invalidated), [1]);
781 assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z");
782 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
783​
784 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
785 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
786 }).pipe(Effect.provide(fixture.layer));
787 }),
788 ),
789 );
790​
791 it.effect("syncs a pull request a reader saw merge without waiting for the sweep", () =>
792 Effect.scoped(
793 Effect.gen(function* () {
794 yield* TestClock.setTime(Date.parse(NOW));
795 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
796 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
797 const fixture = yield* makeHarness({
798 snapshot: makeSnapshot([
799 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
800 ]),
801 summary: (input) =>
802 Ref.get(state).pipe(
803 Effect.map((current) =>
804 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
805 ),
806 ),
807 invalidate: ({ reference }) =>
808 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
809 });
810​
811 yield* Effect.gen(function* () {
812 const reactor = yield* startAndSweep(fixture);
813 yield* Ref.set(state, "merged");
814​
815 yield* Queue.offer(fixture.stateChanges, {
816 host: "github.com",
817 repository: "owner/repository",
818 number: 7,
819 });
820 yield* Queue.take(fixture.snapshotReads);
821 yield* reactor.drain;
822​
823 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
824 assert.deepStrictEqual(
825 (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state),
826 ["merged"],
827 );
828 }).pipe(Effect.provide(fixture.layer));
829 }),
830 ),
831 );
832​
833 it.effect("discovers externally reopened pull requests after fifteen minutes", () =>
834 Effect.scoped(
835 Effect.gen(function* () {
836 yield* TestClock.setTime(Date.parse(NOW));
837 const state = yield* Ref.make<"closed" | "open">("closed");
838 const fixture = yield* makeHarness({
839 snapshot: makeSnapshot([
840 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
841 ]),
842 summary: (input) =>
843 Ref.get(state).pipe(Effect.map((state) => makeSummary(input, { state }))),
844 });
845 yield* Effect.gen(function* () {
846 const reactor = yield* startAndSweep(fixture);
847 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
848 yield* Ref.set(state, "open");
849 for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
850 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
851 yield* sweepAgain(fixture, reactor);
852 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
853 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
854 }).pipe(Effect.provide(fixture.layer));
855 }),
856 ),
857 );
858​
859 it.effect("reads a quiet open pull request every five minutes until it changes", () =>
860 Effect.scoped(
861 Effect.gen(function* () {
862 yield* TestClock.setTime(Date.parse(NOW));
863 const updatedAt = yield* Ref.make("2026-08-27T00:00:00.000Z");
864 const fixture = yield* makeHarness({
865 snapshot: makeSnapshot([makeThread("quiet", { pullRequests: [makeLink(5)] })]),
866 summary: (input) =>
867 Ref.get(updatedAt).pipe(Effect.map((updatedAt) => makeSummary(input, { updatedAt }))),
868 });
869 yield* Effect.gen(function* () {
870 const reactor = yield* startAndSweep(fixture);
871 const applySyncs = Effect.flatMap(Ref.get(fixture.syncCommands), (commands) =>
872 Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)),
873 );
874 yield* applySyncs;
875 const reads = Ref.get(fixture.summaryCalls).pipe(Effect.map((calls) => calls.length));
876 assert.strictEqual(yield* reads, 1);
877 for (let index = 0; index < 4; index += 1) yield* sweepAgain(fixture, reactor);
878 assert.strictEqual(yield* reads, 1);
879​
880 // Someone comments: the five-minute read sees it, and the next sweep reads it again.
881 yield* Ref.set(updatedAt, "2026-08-28T12:04:00.000Z");
882 yield* sweepAgain(fixture, reactor);
883 assert.strictEqual(yield* reads, 2);
884 yield* applySyncs;
885 yield* sweepAgain(fixture, reactor);
886 assert.strictEqual(yield* reads, 3);
887 }).pipe(Effect.provide(fixture.layer));
888 }),
889 ),
890 );
891​
892 it.effect("preserves a refresh requested while an older host read is in flight", () =>
893 Effect.scoped(
894 Effect.gen(function* () {
895 yield* TestClock.setTime(Date.parse(NOW));
896 const reading = yield* Deferred.make<void>();
897 const release = yield* Deferred.make<void>();
898 let calls = 0;
899 const fixture = yield* makeHarness({
900 snapshot: makeSnapshot([]),
901 summary: (input) =>
902 Effect.gen(function* () {
903 calls += 1;
904 if (calls === 1) {
905 yield* Deferred.succeed(reading, undefined);
906 yield* Deferred.await(release);
907 }
908 return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
909 }),
910 });
911 yield* Effect.gen(function* () {
912 const reactor = yield* startAndSweep(fixture);
913 yield* Ref.set(
914 fixture.snapshots,
915 makeSnapshot([
916 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
917 ]),
918 );
919 const key = { host: "github.com", repository: "owner/repository", number: 2 };
920 yield* reactor.requestSync(key);
921 yield* Deferred.await(reading);
922 yield* reactor.requestSync(key);
923 yield* Deferred.succeed(release, undefined);
924 yield* reactor.drain;
925 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
926 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
927 }).pipe(Effect.provide(fixture.layer));
928 }),
929 ),
930 );
931​
932 it.effect("reads a burst of requested links in one sweep", () =>
933 Effect.scoped(
934 Effect.gen(function* () {
935 yield* TestClock.setTime(Date.parse(NOW));
936 const reading = yield* Deferred.make<void>();
937 const release = yield* Deferred.make<void>();
938 const fixture = yield* makeHarness({
939 snapshot: makeSnapshot([]),
940 summary: (input) =>
941 Effect.gen(function* () {
942 if (input.number === 1) {
943 yield* Deferred.succeed(reading, undefined);
944 yield* Deferred.await(release);
945 }
946 return makeSummary(input);
947 }),
948 });
949 yield* Effect.gen(function* () {
950 const reactor = yield* startAndSweep(fixture);
951 yield* Ref.set(
952 fixture.snapshots,
953 makeSnapshot(
954 [1, 2, 3, 4].map((number) =>
955 makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
956 ),
957 ),
958 );
959 const request = (number: number) =>
960 reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
961 yield* request(1);
962 yield* Deferred.await(reading);
963 yield* Effect.forEach([2, 3, 4], request, { discard: true });
964 yield* Deferred.succeed(release, undefined);
965 yield* reactor.drain;
966 assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
967 assert.deepStrictEqual(
968 (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
969 [1, 2, 3, 4],
970 );
971 }).pipe(Effect.provide(fixture.layer));
972 }),
973 ),
974 );
975​
976 it.effect("skips the stack read for a pull request the summary places in no stack", () =>
977 Effect.scoped(
978 Effect.gen(function* () {
979 yield* TestClock.setTime(Date.parse(NOW));
980 const fixture = yield* makeHarness({
981 snapshot: makeSnapshot([
982 makeThread("unstacked", { pullRequests: [makeLink(1)] }),
983 makeThread("stacked", { pullRequests: [makeLink(2)] }),
984 makeThread("unknown", { pullRequests: [makeLink(3)] }),
985 ]),
986 summary: (input) =>
987 Effect.succeed(
988 makeSummary(
989 input,
990 input.number === 1
991 ? { stack: null }
992 : input.number === 2
993 ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
994 : {},
995 ),
996 ),
997 });
998 yield* Effect.gen(function* () {
999 yield* startAndSweep(fixture);
1000 assert.deepStrictEqual(
1001 (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
1002 [2, 3],
1003 );
1004 assert.deepStrictEqual(
1005 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
1006 [1, 2, 3],
1007 );
1008 }).pipe(Effect.provide(fixture.layer));
1009 }),
1010 ),
1011 );
1012​
1013 it.effect("leaves a settled thread's links unread until the thread is unsettled", () =>
1014 Effect.scoped(
1015 Effect.gen(function* () {
1016 yield* TestClock.setTime(Date.parse(NOW));
1017 const fixture = yield* makeHarness({
1018 snapshot: makeSnapshot([
1019 makeThread("settled", {
1020 settledOverride: "settled",
1021 settledAt: "2026-08-21T00:00:00.000Z",
1022 pullRequests: [makeLink(5, { state: "open" }), makeLink(6, { state: "closed" })],
1023 }),
1024 ]),
1025 });
1026​
1027 yield* Effect.gen(function* () {
1028 const reactor = yield* startAndSweep(fixture);
1029 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1030 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1031​
1032 yield* Ref.update(fixture.snapshots, (snapshot) => ({
1033 ...snapshot,
1034 threads: snapshot.threads.map((thread) => ({
1035 ...thread,
1036 settledOverride: null,
1037 settledAt: null,
1038 })),
1039 }));
1040 yield* sweepAgain(fixture, reactor);
1041 assert.deepStrictEqual(
1042 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
1043 [5, 6],
1044 );
1045 }).pipe(Effect.provide(fixture.layer));
1046 }),
1047 ),
1048 );
1049​
1050 it.effect("auto-links missing native stack layers on active threads only", () =>
1051 Effect.scoped(
1052 Effect.gen(function* () {
1053 yield* TestClock.setTime(Date.parse(NOW));
1054 const stack: PullRequestStack = {
1055 id: "stack-1",
1056 number: 42,
1057 url: "https://github.com/owner/repository/stack/1",
1058 base: "main",
1059 layers: [
1060 { number: 41, headBranch: "layer-1", state: "merged" },
1061 { number: 42, headBranch: "layer-2", state: "open" },
1062 { number: 43, headBranch: "layer-3", state: "open" },
1063 ],
1064 };
1065 const fixture = yield* makeHarness({
1066 snapshot: makeSnapshot([
1067 makeThread("one", {
1068 pullRequests: [
1069 makeLink(42),
1070 makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
1071 ],
1072 }),
1073 makeThread("settled", {
1074 settledOverride: "settled",
1075 settledAt: "2026-08-21T00:00:00.000Z",
1076 pullRequests: [makeLink(42)],
1077 }),
1078 ]),
1079 stack: () => Effect.succeed(stack),
1080 });
1081​
1082 yield* Effect.gen(function* () {
1083 yield* startAndSweep(fixture);
1084​
1085 const syncCommands = yield* Ref.get(fixture.syncCommands);
1086 assert.deepStrictEqual(
1087 syncCommands.map((command) => [command.threadId, command.stack] as const),
1089 [ThreadId.make("one"), { kind: "native", ...stack }],
1090 [ThreadId.make("settled"), { kind: "native", ...stack }],
1091 ],
1092 );
1093 assert.deepStrictEqual(
1094 (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
1097 type: "thread.pull-request.link",
1098 threadId: ThreadId.make("one"),
1099 host: "github.com",
1100 repository: "owner/repository",
1101 number: 43,
1102 url: "https://github.com/owner/repository/pull/43",
1103 source: "stack",
1104 },
1105 ],
1106 );
1107 }).pipe(Effect.provide(fixture.layer));
1108 }),
1109 ),
1110 );
1111​
1112 it.effect("keeps existing snapshots and continues when the host fails", () =>
1113 Effect.scoped(
1114 Effect.gen(function* () {
1115 yield* TestClock.setTime(Date.parse(NOW));
1116 const fixture = yield* makeHarness({
1117 snapshot: makeSnapshot([
1118 makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
1119 makeThread("fine", { pullRequests: [makeLink(8)] }),
1120 ]),
1121 summary: (input) =>
1122 input.number === 7
1123 ? Effect.fail(
1124 new PullRequestOperationError({ operation: "summary", detail: "host down" }),
1126 : Effect.succeed(makeSummary(input)),
1127 });
1128​
1129 yield* Effect.gen(function* () {
1130 yield* startAndSweep(fixture);
1131​
1132 assert.deepStrictEqual(
1133 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1134 [8],
1135 );
1136 }).pipe(Effect.provide(fixture.layer));
1137 }),
1138 ),
1139 );
1140​
1141 it.effect("leaves a rate limited host unread until its pause ends", () => {
1142 const skips: Array<ReadonlyArray<unknown>> = [];
1143 const logger = Logger.make(({ logLevel, message }) => {
1144 const parts = Array.isArray(message) ? message : [message];
1145 if (logLevel === "Warn" && parts[0] === "pull request sync skipped") skips.push(parts);
1146 });
1147 const retryAt = Date.parse(NOW) + 3 * 60_000;
1148 return Effect.scoped(
1149 Effect.gen(function* () {
1150 yield* TestClock.setTime(Date.parse(NOW));
1151 const fixture = yield* makeHarness({
1152 snapshot: makeSnapshot([
1153 makeThread("first", { pullRequests: [makeLink(7, { state: "open", updatedAt: NOW })] }),
1154 makeThread("second", {
1155 pullRequests: [makeLink(8, { state: "open", updatedAt: NOW })],
1156 }),
1157 makeThread("third", {
1158 pullRequests: [
1159 makeLink(
1160 9,
1161 { state: "open", updatedAt: NOW },
1162 { host: "forge.example", url: "https://forge.example/owner/repository/pulls/9" },
1163 ),
1164 ],
1165 }),
1166 ]),
1167 summary: (input) =>
1168 Effect.gen(function* () {
1169 if (input.host === "github.com" && (yield* Clock.currentTimeMillis) < retryAt) {
1170 const paused = new PullRequestProviderError({
1171 provider: SourceControlProviderKind.make("github"),
1172 operation: "getChangeRequestSummary",
1173 reason: "rate-limited",
1174 detail: "paused",
1175 retryAt,
1176 });
1177 return yield* new PullRequestOperationError({
1178 operation: "summary",
1179 detail: "paused",
1180 cause: paused,
1181 });
1183 return makeSummary(input, { state: "open" });
1184 }),
1185 });
1186 const githubReads = Ref.get(fixture.summaryCalls).pipe(
1187 Effect.map((calls) =>
1188 calls.filter((call) => call.host === "github.com").map((call) => call.number),
1189 ),
1190 );
1191​
1192 yield* Effect.gen(function* () {
1193 const reactor = yield* startAndSweep(fixture);
1194 assert.deepStrictEqual(yield* githubReads, [7]);
1195 assert.strictEqual(skips.length, 1);
1196 assert.deepInclude(skips[0]![1], { count: 1 });
1197​
1198 yield* reactor.requestSync({
1199 host: "github.com",
1200 repository: "owner/repository",
1201 number: 7,
1202 });
1203 yield* Queue.take(fixture.snapshotReads);
1204 yield* reactor.drain;
1205 yield* sweepAgain(fixture, reactor);
1206 yield* sweepAgain(fixture, reactor);
1207 assert.deepStrictEqual(yield* githubReads, [7]);
1208 assert.strictEqual(skips.length, 1);
1209 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4);
1210​
1211 yield* sweepAgain(fixture, reactor);
1212 assert.sameMembers((yield* githubReads).slice(1), [7, 8]);
1213 }).pipe(
1214 // The reactor forks its worker while its layer builds, so the logger must reach it there.
1215 Effect.provide(
1216 fixture.layer.pipe(Layer.provide(Logger.layer([logger], { mergeWithExisting: false }))),
1217 ),
1218 );
1219 }),
1220 );
1221 });
1222​
1223 it.effect("pauses the host when only its stack read is rate limited", () =>
1224 Effect.scoped(
1225 Effect.gen(function* () {
1226 yield* TestClock.setTime(Date.parse(NOW));
1227 const retryAt = Date.parse(NOW) + 3 * 60_000;
1228 const fixture = yield* makeHarness({
1229 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, null)] })]),
1230 summary: (input) => Effect.succeed(makeSummary(input, { state: "open" })),
1231 stack: () =>
1232 Effect.gen(function* () {
1233 if ((yield* Clock.currentTimeMillis) >= retryAt) return null;
1234 return yield* new PullRequestOperationError({
1235 operation: "stack",
1236 detail: "paused",
1237 cause: new PullRequestProviderError({
1238 provider: SourceControlProviderKind.make("github"),
1239 operation: "getChangeRequestStack",
1240 reason: "rate-limited",
1241 detail: "paused",
1242 retryAt,
1243 }),
1244 });
1245 }),
1246 });
1247 const reads = Effect.all([
1248 Ref.get(fixture.summaryCalls).pipe(Effect.map((calls) => calls.length)),
1249 Ref.get(fixture.stackCalls).pipe(Effect.map((calls) => calls.length)),
1250 ]);
1251​
1252 yield* Effect.gen(function* () {
1253 const reactor = yield* startAndSweep(fixture);
1254 assert.deepStrictEqual(yield* reads, [1, 1]);
1255 yield* sweepAgain(fixture, reactor);
1256 yield* sweepAgain(fixture, reactor);
1257 assert.deepStrictEqual(yield* reads, [1, 1]);
1258​
1259 yield* sweepAgain(fixture, reactor);
1260 assert.deepStrictEqual(yield* reads, [2, 2]);
1261 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
1262 }).pipe(Effect.provide(fixture.layer));
1263 }),
1264 ),
1265 );
1266​
1267 it.effect("reads open links fresh only when a run that ran a merge command ends", () =>
1268 Effect.scoped(
1269 Effect.gen(function* () {
1270 yield* TestClock.setTime(Date.parse(NOW));
1271 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1272 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1273 const fixture = yield* makeHarness({
1274 snapshot: makeSnapshot([
1275 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1276 makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }),
1277 ]),
1278 summary: (input) =>
1279 Ref.get(state).pipe(
1280 Effect.map((current) =>
1281 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1282 ),
1283 ),
1284 invalidate: ({ reference }) =>
1285 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1286 });
1287​
1288 yield* Effect.gen(function* () {
1289 const reactor = yield* startAndSweep(fixture);
1290 yield* Ref.set(state, "merged");
1291 yield* Ref.set(fixture.summaryCalls, []);
1292​
1293 yield* Queue.offerAll(fixture.domainEvents, [
1294 commandRan(ThreadId.make("other"), "gh pr view 9"),
1295 runUpdated(ThreadId.make("other"), "completed"),
1296 commandRan(ThreadId.make("agent"), "gh pr merge 7 --squash 2>&1 | tail -3"),
1297 runUpdated(ThreadId.make("agent"), "completed"),
1298 ]);
1299 yield* Queue.take(fixture.snapshotReads);
1300 yield* Queue.take(fixture.snapshotReads);
1301 yield* reactor.drain;
1302​
1303 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1304 assert.deepStrictEqual(
1305 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
1306 [7],
1307 );
1308 assert.deepStrictEqual(
1309 (yield* Ref.get(fixture.syncCommands)).map((command) => [
1310 command.number,
1311 command.snapshot.state,
1312 ]),
1313 [[7, "merged"]],
1314 );
1315 }).pipe(Effect.provide(fixture.layer));
1316 }),
1317 ),
1318 );
1319});