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

PullRequestSyncReactor.test.ts

1,163 lines41.8 KB

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