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

PullRequestSyncReactor.test.ts

1,399 lines51.2 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.each([
666 {
667 change: "ghe.com token rotation",
668 host: "avatars.example.ghe.com",
669 nextPath: "/u/1?token=new&v=4&s=40&format=png",
670 expectedSyncs: 1,
671 },
672 {
673 change: "avatar version",
674 host: "avatars.example.ghe.com",
675 nextPath: "/u/1?token=old&v=5&s=40&format=png",
676 expectedSyncs: 2,
677 },
678 {
679 change: "avatar size",
680 host: "avatars.example.ghe.com",
681 nextPath: "/u/1?token=old&v=4&s=80&format=png",
682 expectedSyncs: 2,
683 },
684 {
685 change: "another avatar query parameter",
686 host: "avatars.example.ghe.com",
687 nextPath: "/u/1?token=old&v=4&s=40&format=webp",
688 expectedSyncs: 2,
689 },
690 {
691 change: "avatar path",
692 host: "avatars.example.ghe.com",
693 nextPath: "/u/2?token=old&v=4&s=40&format=png",
694 expectedSyncs: 2,
695 },
696 {
697 change: "token outside ghe.com",
698 host: "avatars.example.com",
699 nextPath: "/u/1?token=new&v=4&s=40&format=png",
700 expectedSyncs: 2,
701 },
702 ])("syncs avatar changes selectively: $change", ({ host, nextPath, expectedSyncs }) =>
703 Effect.scoped(
704 Effect.gen(function* () {
705 yield* TestClock.setTime(Date.parse(NOW));
706 const avatarUrl = yield* Ref.make(`https://${host}/u/1?token=old&v=4&s=40&format=png`);
707 const fixture = yield* makeHarness({
708 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
709 summary: (input) =>
710 Ref.get(avatarUrl).pipe(
711 Effect.map((avatarUrl) =>
712 makeSummary(input, {
713 updatedAt: NOW,
714 author: { login: "octocat", name: null, avatarUrl },
715 }),
716 ),
717 ),
718 });
719​
720 yield* Effect.gen(function* () {
721 const reactor = yield* startAndSweep(fixture);
722 const firstSweep = yield* Ref.get(fixture.syncCommands);
723 assert.strictEqual(firstSweep.length, 1);
724 assert.strictEqual(firstSweep[0]?.snapshot.author?.avatarUrl, yield* Ref.get(avatarUrl));
725 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
726​
727 yield* Ref.set(avatarUrl, `https://${host}${nextPath}`);
728 yield* sweepAgain(fixture, reactor);
729​
730 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
731 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, expectedSyncs);
732 const commands = yield* Ref.get(fixture.syncCommands);
733 assert.strictEqual(commands.length, expectedSyncs);
734 if (expectedSyncs === 2) {
735 assert.strictEqual(
736 commands.at(-1)?.snapshot.author?.avatarUrl,
737 yield* Ref.get(avatarUrl),
738 );
739 }
740 }).pipe(Effect.provide(fixture.layer));
741 }),
742 ),
743 );
744​
745 it.effect("refreshes closed links through each project after reopening elsewhere", () =>
746 Effect.scoped(
747 Effect.gen(function* () {
748 yield* TestClock.setTime(Date.parse(NOW));
749 const invalidated = yield* Ref.make<ReadonlyArray<ProjectId>>([]);
750 const fixture = yield* makeHarness({
751 snapshot: makeSnapshot([
752 makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
753 makeThread("second", {
754 projectId: ProjectId.make("second-project"),
755 pullRequests: [makeLink(42, { state: "closed" })],
756 }),
757 ]),
758 invalidate: ({ reference }) =>
759 reference !== undefined
760 ? Ref.update(invalidated, (projects) => [...projects, reference.projectId])
761 : Effect.void,
762 summary: (input) =>
763 Ref.get(invalidated).pipe(
764 Effect.map((projects) =>
765 makeSummary(input, {
766 state: projects.includes(input.projectId) ? "open" : "closed",
767 }),
768 ),
769 ),
770 });
771 yield* Effect.gen(function* () {
772 const reactor = yield* startAndSweep(fixture);
773 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
774 yield* reactor.requestSync({
775 host: "github.com",
776 repository: "owner/repository",
777 number: 42,
778 });
779 yield* Queue.take(fixture.snapshotReads);
780 yield* reactor.drain;
781 assert.sameMembers(
782 [...(yield* Ref.get(invalidated))],
783 [PROJECT_ID, ProjectId.make("second-project")],
784 );
785 assert.sameMembers(
786 (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
787 [PROJECT_ID, ProjectId.make("second-project")],
788 );
789 const commands = yield* Ref.get(fixture.syncCommands);
790 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
791 const snapshot = yield* Ref.get(fixture.snapshots);
792 assert.deepStrictEqual(
793 snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
794 ["open", "open"],
795 );
796 }).pipe(Effect.provide(fixture.layer));
797 }),
798 ),
799 );
800​
801 it.effect("stops asking the host once a pull request is merged", () =>
802 Effect.scoped(
803 Effect.gen(function* () {
804 yield* TestClock.setTime(Date.parse(NOW));
805 const fixture = yield* makeHarness({
806 snapshot: makeSnapshot([
807 makeThread("merged", {
808 pullRequests: [
809 makeLink(1, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
810 ],
811 }),
812 ]),
813 });
814​
815 yield* Effect.gen(function* () {
816 const reactor = yield* startAndSweep(fixture);
817 yield* sweepAgain(fixture, reactor);
818​
819 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
820 assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
821​
822 yield* reactor.requestSync({
823 host: "github.com",
824 repository: "owner/repository",
825 number: 1,
826 });
827 yield* Queue.take(fixture.snapshotReads);
828 yield* reactor.drain;
829​
830 assert.deepStrictEqual(
831 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
832 [1],
833 );
834 }).pipe(Effect.provide(fixture.layer));
835 }),
836 ),
837 );
838​
839 it.effect("re-reads a merged pull request until the host supplies its merge time", () =>
840 Effect.scoped(
841 Effect.gen(function* () {
842 yield* TestClock.setTime(Date.parse(NOW));
843 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
844 const fixture = yield* makeHarness({
845 snapshot: makeSnapshot([
846 makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
847 ]),
848 invalidate: ({ reference }) =>
849 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
850 summary: (input) =>
851 Effect.succeed(
852 makeSummary(input, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
853 ),
854 });
855​
856 yield* Effect.gen(function* () {
857 const reactor = yield* startAndSweep(fixture);
858 const firstSweep = yield* Ref.get(fixture.syncCommands);
859 // The held merged summary is dropped so the read reaches the host.
860 assert.deepStrictEqual(yield* Ref.get(invalidated), [1]);
861 assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z");
862 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
863​
864 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
865 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
866 }).pipe(Effect.provide(fixture.layer));
867 }),
868 ),
869 );
870​
871 it.effect("syncs a pull request a reader saw merge without waiting for the sweep", () =>
872 Effect.scoped(
873 Effect.gen(function* () {
874 yield* TestClock.setTime(Date.parse(NOW));
875 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
876 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
877 const fixture = yield* makeHarness({
878 snapshot: makeSnapshot([
879 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
880 ]),
881 summary: (input) =>
882 Ref.get(state).pipe(
883 Effect.map((current) =>
884 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
885 ),
886 ),
887 invalidate: ({ reference }) =>
888 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
889 });
890​
891 yield* Effect.gen(function* () {
892 const reactor = yield* startAndSweep(fixture);
893 yield* Ref.set(state, "merged");
894​
895 yield* Queue.offer(fixture.stateChanges, {
896 host: "github.com",
897 repository: "owner/repository",
898 number: 7,
899 });
900 yield* Queue.take(fixture.snapshotReads);
901 yield* reactor.drain;
902​
903 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
904 assert.deepStrictEqual(
905 (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state),
906 ["merged"],
907 );
908 }).pipe(Effect.provide(fixture.layer));
909 }),
910 ),
911 );
912​
913 it.effect("discovers externally reopened pull requests after fifteen minutes", () =>
914 Effect.scoped(
915 Effect.gen(function* () {
916 yield* TestClock.setTime(Date.parse(NOW));
917 const state = yield* Ref.make<"closed" | "open">("closed");
918 const fixture = yield* makeHarness({
919 snapshot: makeSnapshot([
920 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
921 ]),
922 summary: (input) =>
923 Ref.get(state).pipe(Effect.map((state) => makeSummary(input, { state }))),
924 });
925 yield* Effect.gen(function* () {
926 const reactor = yield* startAndSweep(fixture);
927 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
928 yield* Ref.set(state, "open");
929 for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
930 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
931 yield* sweepAgain(fixture, reactor);
932 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
933 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
934 }).pipe(Effect.provide(fixture.layer));
935 }),
936 ),
937 );
938​
939 it.effect("reads a quiet open pull request every five minutes until it changes", () =>
940 Effect.scoped(
941 Effect.gen(function* () {
942 yield* TestClock.setTime(Date.parse(NOW));
943 const updatedAt = yield* Ref.make("2026-08-27T00:00:00.000Z");
944 const fixture = yield* makeHarness({
945 snapshot: makeSnapshot([makeThread("quiet", { pullRequests: [makeLink(5)] })]),
946 summary: (input) =>
947 Ref.get(updatedAt).pipe(Effect.map((updatedAt) => makeSummary(input, { updatedAt }))),
948 });
949 yield* Effect.gen(function* () {
950 const reactor = yield* startAndSweep(fixture);
951 const applySyncs = Effect.flatMap(Ref.get(fixture.syncCommands), (commands) =>
952 Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)),
953 );
954 yield* applySyncs;
955 const reads = Ref.get(fixture.summaryCalls).pipe(Effect.map((calls) => calls.length));
956 assert.strictEqual(yield* reads, 1);
957 for (let index = 0; index < 4; index += 1) yield* sweepAgain(fixture, reactor);
958 assert.strictEqual(yield* reads, 1);
959​
960 // Someone comments: the five-minute read sees it, and the next sweep reads it again.
961 yield* Ref.set(updatedAt, "2026-08-28T12:04:00.000Z");
962 yield* sweepAgain(fixture, reactor);
963 assert.strictEqual(yield* reads, 2);
964 yield* applySyncs;
965 yield* sweepAgain(fixture, reactor);
966 assert.strictEqual(yield* reads, 3);
967 }).pipe(Effect.provide(fixture.layer));
968 }),
969 ),
970 );
971​
972 it.effect("preserves a refresh requested while an older host read is in flight", () =>
973 Effect.scoped(
974 Effect.gen(function* () {
975 yield* TestClock.setTime(Date.parse(NOW));
976 const reading = yield* Deferred.make<void>();
977 const release = yield* Deferred.make<void>();
978 let calls = 0;
979 const fixture = yield* makeHarness({
980 snapshot: makeSnapshot([]),
981 summary: (input) =>
982 Effect.gen(function* () {
983 calls += 1;
984 if (calls === 1) {
985 yield* Deferred.succeed(reading, undefined);
986 yield* Deferred.await(release);
987 }
988 return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
989 }),
990 });
991 yield* Effect.gen(function* () {
992 const reactor = yield* startAndSweep(fixture);
993 yield* Ref.set(
994 fixture.snapshots,
995 makeSnapshot([
996 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
997 ]),
998 );
999 const key = { host: "github.com", repository: "owner/repository", number: 2 };
1000 yield* reactor.requestSync(key);
1001 yield* Deferred.await(reading);
1002 yield* reactor.requestSync(key);
1003 yield* Deferred.succeed(release, undefined);
1004 yield* reactor.drain;
1005 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1006 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
1007 }).pipe(Effect.provide(fixture.layer));
1008 }),
1009 ),
1010 );
1011​
1012 it.effect("reads a burst of requested links in one sweep", () =>
1013 Effect.scoped(
1014 Effect.gen(function* () {
1015 yield* TestClock.setTime(Date.parse(NOW));
1016 const reading = yield* Deferred.make<void>();
1017 const release = yield* Deferred.make<void>();
1018 const fixture = yield* makeHarness({
1019 snapshot: makeSnapshot([]),
1020 summary: (input) =>
1021 Effect.gen(function* () {
1022 if (input.number === 1) {
1023 yield* Deferred.succeed(reading, undefined);
1024 yield* Deferred.await(release);
1026 return makeSummary(input);
1027 }),
1028 });
1029 yield* Effect.gen(function* () {
1030 const reactor = yield* startAndSweep(fixture);
1031 yield* Ref.set(
1032 fixture.snapshots,
1033 makeSnapshot(
1034 [1, 2, 3, 4].map((number) =>
1035 makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
1036 ),
1037 ),
1038 );
1039 const request = (number: number) =>
1040 reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
1041 yield* request(1);
1042 yield* Deferred.await(reading);
1043 yield* Effect.forEach([2, 3, 4], request, { discard: true });
1044 yield* Deferred.succeed(release, undefined);
1045 yield* reactor.drain;
1046 assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
1047 assert.deepStrictEqual(
1048 (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
1049 [1, 2, 3, 4],
1050 );
1051 }).pipe(Effect.provide(fixture.layer));
1052 }),
1053 ),
1054 );
1055​
1056 it.effect("skips the stack read for a pull request the summary places in no stack", () =>
1057 Effect.scoped(
1058 Effect.gen(function* () {
1059 yield* TestClock.setTime(Date.parse(NOW));
1060 const fixture = yield* makeHarness({
1061 snapshot: makeSnapshot([
1062 makeThread("unstacked", { pullRequests: [makeLink(1)] }),
1063 makeThread("stacked", { pullRequests: [makeLink(2)] }),
1064 makeThread("unknown", { pullRequests: [makeLink(3)] }),
1065 ]),
1066 summary: (input) =>
1067 Effect.succeed(
1068 makeSummary(
1069 input,
1070 input.number === 1
1071 ? { stack: null }
1072 : input.number === 2
1073 ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
1074 : {},
1075 ),
1076 ),
1077 });
1078 yield* Effect.gen(function* () {
1079 yield* startAndSweep(fixture);
1080 assert.deepStrictEqual(
1081 (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
1082 [2, 3],
1083 );
1084 assert.deepStrictEqual(
1085 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
1086 [1, 2, 3],
1087 );
1088 }).pipe(Effect.provide(fixture.layer));
1089 }),
1090 ),
1091 );
1092​
1093 it.effect("leaves a settled thread's links unread until the thread is unsettled", () =>
1094 Effect.scoped(
1095 Effect.gen(function* () {
1096 yield* TestClock.setTime(Date.parse(NOW));
1097 const fixture = yield* makeHarness({
1098 snapshot: makeSnapshot([
1099 makeThread("settled", {
1100 settledOverride: "settled",
1101 settledAt: "2026-08-21T00:00:00.000Z",
1102 pullRequests: [makeLink(5, { state: "open" }), makeLink(6, { state: "closed" })],
1103 }),
1104 ]),
1105 });
1106​
1107 yield* Effect.gen(function* () {
1108 const reactor = yield* startAndSweep(fixture);
1109 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1110 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1111​
1112 yield* Ref.update(fixture.snapshots, (snapshot) => ({
1113 ...snapshot,
1114 threads: snapshot.threads.map((thread) => ({
1115 ...thread,
1116 settledOverride: null,
1117 settledAt: null,
1118 })),
1119 }));
1120 yield* sweepAgain(fixture, reactor);
1121 assert.deepStrictEqual(
1122 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
1123 [5, 6],
1124 );
1125 }).pipe(Effect.provide(fixture.layer));
1126 }),
1127 ),
1128 );
1129​
1130 it.effect("auto-links missing native stack layers on active threads only", () =>
1131 Effect.scoped(
1132 Effect.gen(function* () {
1133 yield* TestClock.setTime(Date.parse(NOW));
1134 const stack: PullRequestStack = {
1135 id: "stack-1",
1136 number: 42,
1137 url: "https://github.com/owner/repository/stack/1",
1138 base: "main",
1139 layers: [
1140 { number: 41, headBranch: "layer-1", state: "merged" },
1141 { number: 42, headBranch: "layer-2", state: "open" },
1142 { number: 43, headBranch: "layer-3", state: "open" },
1143 ],
1144 };
1145 const fixture = yield* makeHarness({
1146 snapshot: makeSnapshot([
1147 makeThread("one", {
1148 pullRequests: [
1149 makeLink(42),
1150 makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
1151 ],
1152 }),
1153 makeThread("settled", {
1154 settledOverride: "settled",
1155 settledAt: "2026-08-21T00:00:00.000Z",
1156 pullRequests: [makeLink(42)],
1157 }),
1158 ]),
1159 stack: () => Effect.succeed(stack),
1160 });
1161​
1162 yield* Effect.gen(function* () {
1163 yield* startAndSweep(fixture);
1164​
1165 const syncCommands = yield* Ref.get(fixture.syncCommands);
1166 assert.deepStrictEqual(
1167 syncCommands.map((command) => [command.threadId, command.stack] as const),
1169 [ThreadId.make("one"), { kind: "native", ...stack }],
1170 [ThreadId.make("settled"), { kind: "native", ...stack }],
1171 ],
1172 );
1173 assert.deepStrictEqual(
1174 (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
1177 type: "thread.pull-request.link",
1178 threadId: ThreadId.make("one"),
1179 host: "github.com",
1180 repository: "owner/repository",
1181 number: 43,
1182 url: "https://github.com/owner/repository/pull/43",
1183 source: "stack",
1184 },
1185 ],
1186 );
1187 }).pipe(Effect.provide(fixture.layer));
1188 }),
1189 ),
1190 );
1191​
1192 it.effect("keeps existing snapshots and continues when the host fails", () =>
1193 Effect.scoped(
1194 Effect.gen(function* () {
1195 yield* TestClock.setTime(Date.parse(NOW));
1196 const fixture = yield* makeHarness({
1197 snapshot: makeSnapshot([
1198 makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
1199 makeThread("fine", { pullRequests: [makeLink(8)] }),
1200 ]),
1201 summary: (input) =>
1202 input.number === 7
1203 ? Effect.fail(
1204 new PullRequestOperationError({ operation: "summary", detail: "host down" }),
1206 : Effect.succeed(makeSummary(input)),
1207 });
1208​
1209 yield* Effect.gen(function* () {
1210 yield* startAndSweep(fixture);
1211​
1212 assert.deepStrictEqual(
1213 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1214 [8],
1215 );
1216 }).pipe(Effect.provide(fixture.layer));
1217 }),
1218 ),
1219 );
1220​
1221 it.effect("leaves a rate limited host unread until its pause ends", () => {
1222 const skips: Array<ReadonlyArray<unknown>> = [];
1223 const logger = Logger.make(({ logLevel, message }) => {
1224 const parts = Array.isArray(message) ? message : [message];
1225 if (logLevel === "Warn" && parts[0] === "pull request sync skipped") skips.push(parts);
1226 });
1227 const retryAt = Date.parse(NOW) + 3 * 60_000;
1228 return Effect.scoped(
1229 Effect.gen(function* () {
1230 yield* TestClock.setTime(Date.parse(NOW));
1231 const fixture = yield* makeHarness({
1232 snapshot: makeSnapshot([
1233 makeThread("first", { pullRequests: [makeLink(7, { state: "open", updatedAt: NOW })] }),
1234 makeThread("second", {
1235 pullRequests: [makeLink(8, { state: "open", updatedAt: NOW })],
1236 }),
1237 makeThread("third", {
1238 pullRequests: [
1239 makeLink(
1240 9,
1241 { state: "open", updatedAt: NOW },
1242 { host: "forge.example", url: "https://forge.example/owner/repository/pulls/9" },
1243 ),
1244 ],
1245 }),
1246 ]),
1247 summary: (input) =>
1248 Effect.gen(function* () {
1249 if (input.host === "github.com" && (yield* Clock.currentTimeMillis) < retryAt) {
1250 const paused = new PullRequestProviderError({
1251 provider: SourceControlProviderKind.make("github"),
1252 operation: "getChangeRequestSummary",
1253 reason: "rate-limited",
1254 detail: "paused",
1255 retryAt,
1256 });
1257 return yield* new PullRequestOperationError({
1258 operation: "summary",
1259 detail: "paused",
1260 cause: paused,
1261 });
1263 return makeSummary(input, { state: "open" });
1264 }),
1265 });
1266 const githubReads = Ref.get(fixture.summaryCalls).pipe(
1267 Effect.map((calls) =>
1268 calls.filter((call) => call.host === "github.com").map((call) => call.number),
1269 ),
1270 );
1271​
1272 yield* Effect.gen(function* () {
1273 const reactor = yield* startAndSweep(fixture);
1274 assert.deepStrictEqual(yield* githubReads, [7]);
1275 assert.strictEqual(skips.length, 1);
1276 assert.deepInclude(skips[0]![1], { count: 1 });
1277​
1278 yield* reactor.requestSync({
1279 host: "github.com",
1280 repository: "owner/repository",
1281 number: 7,
1282 });
1283 yield* Queue.take(fixture.snapshotReads);
1284 yield* reactor.drain;
1285 yield* sweepAgain(fixture, reactor);
1286 yield* sweepAgain(fixture, reactor);
1287 assert.deepStrictEqual(yield* githubReads, [7]);
1288 assert.strictEqual(skips.length, 1);
1289 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4);
1290​
1291 yield* sweepAgain(fixture, reactor);
1292 assert.sameMembers((yield* githubReads).slice(1), [7, 8]);
1293 }).pipe(
1294 // The reactor forks its worker while its layer builds, so the logger must reach it there.
1295 Effect.provide(
1296 fixture.layer.pipe(Layer.provide(Logger.layer([logger], { mergeWithExisting: false }))),
1297 ),
1298 );
1299 }),
1300 );
1301 });
1302​
1303 it.effect("pauses the host when only its stack read is rate limited", () =>
1304 Effect.scoped(
1305 Effect.gen(function* () {
1306 yield* TestClock.setTime(Date.parse(NOW));
1307 const retryAt = Date.parse(NOW) + 3 * 60_000;
1308 const fixture = yield* makeHarness({
1309 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, null)] })]),
1310 summary: (input) => Effect.succeed(makeSummary(input, { state: "open" })),
1311 stack: () =>
1312 Effect.gen(function* () {
1313 if ((yield* Clock.currentTimeMillis) >= retryAt) return null;
1314 return yield* new PullRequestOperationError({
1315 operation: "stack",
1316 detail: "paused",
1317 cause: new PullRequestProviderError({
1318 provider: SourceControlProviderKind.make("github"),
1319 operation: "getChangeRequestStack",
1320 reason: "rate-limited",
1321 detail: "paused",
1322 retryAt,
1323 }),
1324 });
1325 }),
1326 });
1327 const reads = Effect.all([
1328 Ref.get(fixture.summaryCalls).pipe(Effect.map((calls) => calls.length)),
1329 Ref.get(fixture.stackCalls).pipe(Effect.map((calls) => calls.length)),
1330 ]);
1331​
1332 yield* Effect.gen(function* () {
1333 const reactor = yield* startAndSweep(fixture);
1334 assert.deepStrictEqual(yield* reads, [1, 1]);
1335 yield* sweepAgain(fixture, reactor);
1336 yield* sweepAgain(fixture, reactor);
1337 assert.deepStrictEqual(yield* reads, [1, 1]);
1338​
1339 yield* sweepAgain(fixture, reactor);
1340 assert.deepStrictEqual(yield* reads, [2, 2]);
1341 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
1342 }).pipe(Effect.provide(fixture.layer));
1343 }),
1344 ),
1345 );
1346​
1347 it.effect("reads open links fresh only when a run that ran a merge command ends", () =>
1348 Effect.scoped(
1349 Effect.gen(function* () {
1350 yield* TestClock.setTime(Date.parse(NOW));
1351 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1352 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1353 const fixture = yield* makeHarness({
1354 snapshot: makeSnapshot([
1355 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1356 makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }),
1357 ]),
1358 summary: (input) =>
1359 Ref.get(state).pipe(
1360 Effect.map((current) =>
1361 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1362 ),
1363 ),
1364 invalidate: ({ reference }) =>
1365 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1366 });
1367​
1368 yield* Effect.gen(function* () {
1369 const reactor = yield* startAndSweep(fixture);
1370 yield* Ref.set(state, "merged");
1371 yield* Ref.set(fixture.summaryCalls, []);
1372​
1373 yield* Queue.offerAll(fixture.domainEvents, [
1374 commandRan(ThreadId.make("other"), "gh pr view 9"),
1375 runUpdated(ThreadId.make("other"), "completed"),
1376 commandRan(ThreadId.make("agent"), "gh pr merge 7 --squash 2>&1 | tail -3"),
1377 runUpdated(ThreadId.make("agent"), "completed"),
1378 ]);
1379 yield* Queue.take(fixture.snapshotReads);
1380 yield* Queue.take(fixture.snapshotReads);
1381 yield* reactor.drain;
1382​
1383 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1384 assert.deepStrictEqual(
1385 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
1386 [7],
1387 );
1388 assert.deepStrictEqual(
1389 (yield* Ref.get(fixture.syncCommands)).map((command) => [
1390 command.number,
1391 command.snapshot.state,
1392 ]),
1393 [[7, "merged"]],
1394 );
1395 }).pipe(Effect.provide(fixture.layer));
1396 }),
1397 ),
1398 );
1399});