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

PullRequestSyncReactor.test.ts

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