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

PullRequestSyncReactor.test.ts

1,154 lines41.0 KB

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