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

PullRequestSyncReactor.test.ts

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