Open History to see the last commit
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 };
68}
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 };
95}
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 };
125}
126
127interface TestShellSnapshot {
128 readonly snapshotSequence: number;
129 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
130 readonly threads: ReadonlyArray<PullRequestTestThread>;
131 readonly updatedAt: string;
132}
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 };
144}
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 };
163}
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>;
174}
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 };
333}
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 };
363}
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 };
384}
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", {
634 pullRequests: [
635 makeLink(1, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
636 ],
637 }),
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("re-reads a merged pull request until the host supplies its merge time", () =>
666 Effect.scoped(
667 Effect.gen(function* () {
668 yield* TestClock.setTime(Date.parse(NOW));
669 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
670 const fixture = yield* makeHarness({
671 snapshot: makeSnapshot([
672 makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
673 ]),
674 invalidate: ({ reference }) =>
675 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
676 summary: (input) =>
677 Effect.succeed(
678 makeSummary(input, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
679 ),
680 });
681
682 yield* Effect.gen(function* () {
683 const reactor = yield* startAndSweep(fixture);
684 const firstSweep = yield* Ref.get(fixture.syncCommands);
685 // The held merged summary is dropped so the read reaches the host.
686 assert.deepStrictEqual(yield* Ref.get(invalidated), [1]);
687 assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z");
688 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
689
690 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
691 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
692 }).pipe(Effect.provide(fixture.layer));
693 }),
694 ),
695 );
696
697 it.effect("syncs a pull request a reader saw merge without waiting for the sweep", () =>
698 Effect.scoped(
699 Effect.gen(function* () {
700 yield* TestClock.setTime(Date.parse(NOW));
701 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
702 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
703 const fixture = yield* makeHarness({
704 snapshot: makeSnapshot([
705 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
706 ]),
707 summary: (input) =>
708 Ref.get(state).pipe(
709 Effect.map((current) =>
710 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
711 ),
712 ),
713 invalidate: ({ reference }) =>
714 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
715 });
716
717 yield* Effect.gen(function* () {
718 const reactor = yield* startAndSweep(fixture);
719 yield* Ref.set(state, "merged");
720
721 yield* Queue.offer(fixture.stateChanges, {
722 host: "github.com",
723 repository: "owner/repository",
724 number: 7,
725 });
726 yield* Queue.take(fixture.snapshotReads);
727 yield* reactor.drain;
728
729 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
730 assert.deepStrictEqual(
731 (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state),
732 ["merged"],
733 );
734 }).pipe(Effect.provide(fixture.layer));
735 }),
736 ),
737 );
738
739 it.effect("discovers externally reopened pull requests after fifteen minutes", () =>
740 Effect.scoped(
741 Effect.gen(function* () {
742 yield* TestClock.setTime(Date.parse(NOW));
743 const state = yield* Ref.make<"closed" | "open">("closed");
744 const fixture = yield* makeHarness({
745 snapshot: makeSnapshot([
746 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
747 ]),
748 summary: (input) =>
749 Ref.get(state).pipe(Effect.map((state) => makeSummary(input, { state }))),
750 });
751 yield* Effect.gen(function* () {
752 const reactor = yield* startAndSweep(fixture);
753 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
754 yield* Ref.set(state, "open");
755 for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
756 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
757 yield* sweepAgain(fixture, reactor);
758 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
759 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
760 }).pipe(Effect.provide(fixture.layer));
761 }),
762 ),
763 );
764
765 it.effect("preserves a refresh requested while an older host read is in flight", () =>
766 Effect.scoped(
767 Effect.gen(function* () {
768 yield* TestClock.setTime(Date.parse(NOW));
769 const reading = yield* Deferred.make<void>();
770 const release = yield* Deferred.make<void>();
771 let calls = 0;
772 const fixture = yield* makeHarness({
773 snapshot: makeSnapshot([]),
774 summary: (input) =>
775 Effect.gen(function* () {
776 calls += 1;
777 if (calls === 1) {
778 yield* Deferred.succeed(reading, undefined);
779 yield* Deferred.await(release);
780 }
781 return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
782 }),
783 });
784 yield* Effect.gen(function* () {
785 const reactor = yield* startAndSweep(fixture);
786 yield* Ref.set(
787 fixture.snapshots,
788 makeSnapshot([
789 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
790 ]),
791 );
792 const key = { host: "github.com", repository: "owner/repository", number: 2 };
793 yield* reactor.requestSync(key);
794 yield* Deferred.await(reading);
795 yield* reactor.requestSync(key);
796 yield* Deferred.succeed(release, undefined);
797 yield* reactor.drain;
798 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
799 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
800 }).pipe(Effect.provide(fixture.layer));
801 }),
802 ),
803 );
804
805 it.effect("reads a burst of requested links in one sweep", () =>
806 Effect.scoped(
807 Effect.gen(function* () {
808 yield* TestClock.setTime(Date.parse(NOW));
809 const reading = yield* Deferred.make<void>();
810 const release = yield* Deferred.make<void>();
811 const fixture = yield* makeHarness({
812 snapshot: makeSnapshot([]),
813 summary: (input) =>
814 Effect.gen(function* () {
815 if (input.number === 1) {
816 yield* Deferred.succeed(reading, undefined);
817 yield* Deferred.await(release);
818 }
819 return makeSummary(input);
820 }),
821 });
822 yield* Effect.gen(function* () {
823 const reactor = yield* startAndSweep(fixture);
824 yield* Ref.set(
825 fixture.snapshots,
826 makeSnapshot(
827 [1, 2, 3, 4].map((number) =>
828 makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
829 ),
830 ),
831 );
832 const request = (number: number) =>
833 reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
834 yield* request(1);
835 yield* Deferred.await(reading);
836 yield* Effect.forEach([2, 3, 4], request, { discard: true });
837 yield* Deferred.succeed(release, undefined);
838 yield* reactor.drain;
839 assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
840 assert.deepStrictEqual(
841 (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
842 [1, 2, 3, 4],
843 );
844 }).pipe(Effect.provide(fixture.layer));
845 }),
846 ),
847 );
848
849 it.effect("skips the stack read for a pull request the summary places in no stack", () =>
850 Effect.scoped(
851 Effect.gen(function* () {
852 yield* TestClock.setTime(Date.parse(NOW));
853 const fixture = yield* makeHarness({
854 snapshot: makeSnapshot([
855 makeThread("unstacked", { pullRequests: [makeLink(1)] }),
856 makeThread("stacked", { pullRequests: [makeLink(2)] }),
857 makeThread("unknown", { pullRequests: [makeLink(3)] }),
858 ]),
859 summary: (input) =>
860 Effect.succeed(
861 makeSummary(
862 input,
863 input.number === 1
864 ? { stack: null }
865 : input.number === 2
866 ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
867 : {},
868 ),
869 ),
870 });
871 yield* Effect.gen(function* () {
872 yield* startAndSweep(fixture);
873 assert.deepStrictEqual(
874 (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
875 [2, 3],
876 );
877 assert.deepStrictEqual(
878 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
879 [1, 2, 3],
880 );
881 }).pipe(Effect.provide(fixture.layer));
882 }),
883 ),
884 );
885
886 it.effect("leaves a settled thread's links unread until the thread is unsettled", () =>
887 Effect.scoped(
888 Effect.gen(function* () {
889 yield* TestClock.setTime(Date.parse(NOW));
890 const fixture = yield* makeHarness({
891 snapshot: makeSnapshot([
892 makeThread("settled", {
893 settledOverride: "settled",
894 settledAt: "2026-08-21T00:00:00.000Z",
895 pullRequests: [makeLink(5, { state: "open" }), makeLink(6, { state: "closed" })],
896 }),
897 ]),
898 });
899
900 yield* Effect.gen(function* () {
901 const reactor = yield* startAndSweep(fixture);
902 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
903 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
904
905 yield* Ref.update(fixture.snapshots, (snapshot) => ({
906 ...snapshot,
907 threads: snapshot.threads.map((thread) => ({
908 ...thread,
909 settledOverride: null,
910 settledAt: null,
911 })),
912 }));
913 yield* sweepAgain(fixture, reactor);
914 assert.deepStrictEqual(
915 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
916 [5, 6],
917 );
918 }).pipe(Effect.provide(fixture.layer));
919 }),
920 ),
921 );
922
923 it.effect("auto-links missing native stack layers on active threads only", () =>
924 Effect.scoped(
925 Effect.gen(function* () {
926 yield* TestClock.setTime(Date.parse(NOW));
927 const stack: PullRequestStack = {
928 id: "stack-1",
929 number: 42,
930 url: "https://github.com/owner/repository/stack/1",
931 base: "main",
932 layers: [
933 { number: 41, headBranch: "layer-1", state: "merged" },
934 { number: 42, headBranch: "layer-2", state: "open" },
935 { number: 43, headBranch: "layer-3", state: "open" },
936 ],
937 };
938 const fixture = yield* makeHarness({
939 snapshot: makeSnapshot([
940 makeThread("one", {
941 pullRequests: [
942 makeLink(42),
943 makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
944 ],
945 }),
946 makeThread("settled", {
947 settledOverride: "settled",
948 settledAt: "2026-08-21T00:00:00.000Z",
949 pullRequests: [makeLink(42)],
950 }),
951 ]),
952 stack: () => Effect.succeed(stack),
953 });
954
955 yield* Effect.gen(function* () {
956 yield* startAndSweep(fixture);
957
958 const syncCommands = yield* Ref.get(fixture.syncCommands);
959 assert.deepStrictEqual(
960 syncCommands.map((command) => [command.threadId, command.stack] as const),
961 [
962 [ThreadId.make("one"), { kind: "native", ...stack }],
963 [ThreadId.make("settled"), { kind: "native", ...stack }],
964 ],
965 );
966 assert.deepStrictEqual(
967 (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
968 [
969 {
970 type: "thread.pull-request.link",
971 threadId: ThreadId.make("one"),
972 host: "github.com",
973 repository: "owner/repository",
974 number: 43,
975 url: "https://github.com/owner/repository/pull/43",
976 source: "stack",
977 },
978 ],
979 );
980 }).pipe(Effect.provide(fixture.layer));
981 }),
982 ),
983 );
984
985 it.effect("keeps existing snapshots and continues when the host fails", () =>
986 Effect.scoped(
987 Effect.gen(function* () {
988 yield* TestClock.setTime(Date.parse(NOW));
989 const fixture = yield* makeHarness({
990 snapshot: makeSnapshot([
991 makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
992 makeThread("fine", { pullRequests: [makeLink(8)] }),
993 ]),
994 summary: (input) =>
995 input.number === 7
996 ? Effect.fail(
997 new PullRequestOperationError({ operation: "summary", detail: "host down" }),
998 )
999 : Effect.succeed(makeSummary(input)),
1000 });
1001
1002 yield* Effect.gen(function* () {
1003 yield* startAndSweep(fixture);
1004
1005 assert.deepStrictEqual(
1006 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1007 [8],
1008 );
1009 }).pipe(Effect.provide(fixture.layer));
1010 }),
1011 ),
1012 );
1013
1014 it.effect("leaves a rate limited host unread until its pause ends", () => {
1015 const skips: Array<ReadonlyArray<unknown>> = [];
1016 const logger = Logger.make(({ logLevel, message }) => {
1017 const parts = Array.isArray(message) ? message : [message];
1018 if (logLevel === "Warn" && parts[0] === "pull request sync skipped") skips.push(parts);
1019 });
1020 const retryAt = Date.parse(NOW) + 3 * 60_000;
1021 return Effect.scoped(
1022 Effect.gen(function* () {
1023 yield* TestClock.setTime(Date.parse(NOW));
1024 const fixture = yield* makeHarness({
1025 snapshot: makeSnapshot([
1026 makeThread("first", { pullRequests: [makeLink(7, { state: "open" })] }),
1027 makeThread("second", { pullRequests: [makeLink(8, { state: "open" })] }),
1028 makeThread("third", {
1029 pullRequests: [
1030 makeLink(
1031 9,
1032 { state: "open" },
1033 { host: "forge.example", url: "https://forge.example/owner/repository/pulls/9" },
1034 ),
1035 ],
1036 }),
1037 ]),
1038 summary: (input) =>
1039 Effect.gen(function* () {
1040 if (input.host === "github.com" && (yield* Clock.currentTimeMillis) < retryAt) {
1041 const paused = new PullRequestProviderError({
1042 provider: SourceControlProviderKind.make("github"),
1043 operation: "getChangeRequestSummary",
1044 reason: "rate-limited",
1045 detail: "paused",
1046 retryAt,
1047 });
1048 return yield* new PullRequestOperationError({
1049 operation: "summary",
1050 detail: "paused",
1051 cause: paused,
1052 });
1053 }
1054 return makeSummary(input, { state: "open" });
1055 }),
1056 });
1057 const githubReads = Ref.get(fixture.summaryCalls).pipe(
1058 Effect.map((calls) =>
1059 calls.filter((call) => call.host === "github.com").map((call) => call.number),
1060 ),
1061 );
1062
1063 yield* Effect.gen(function* () {
1064 const reactor = yield* startAndSweep(fixture);
1065 assert.deepStrictEqual(yield* githubReads, [7]);
1066 assert.strictEqual(skips.length, 1);
1067 assert.deepInclude(skips[0]![1], { count: 1 });
1068
1069 yield* reactor.requestSync({
1070 host: "github.com",
1071 repository: "owner/repository",
1072 number: 7,
1073 });
1074 yield* Queue.take(fixture.snapshotReads);
1075 yield* reactor.drain;
1076 yield* sweepAgain(fixture, reactor);
1077 yield* sweepAgain(fixture, reactor);
1078 assert.deepStrictEqual(yield* githubReads, [7]);
1079 assert.strictEqual(skips.length, 1);
1080 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4);
1081
1082 yield* sweepAgain(fixture, reactor);
1083 assert.sameMembers((yield* githubReads).slice(1), [7, 8]);
1084 }).pipe(
1085 // The reactor forks its worker while its layer builds, so the logger must reach it there.
1086 Effect.provide(
1087 fixture.layer.pipe(Layer.provide(Logger.layer([logger], { mergeWithExisting: false }))),
1088 ),
1089 );
1090 }),
1091 );
1092 });
1093
1094 it.effect("pauses the host when only its stack read is rate limited", () =>
1095 Effect.scoped(
1096 Effect.gen(function* () {
1097 yield* TestClock.setTime(Date.parse(NOW));
1098 const retryAt = Date.parse(NOW) + 3 * 60_000;
1099 const fixture = yield* makeHarness({
1100 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, null)] })]),
1101 summary: (input) => Effect.succeed(makeSummary(input, { state: "open" })),
1102 stack: () =>
1103 Effect.gen(function* () {
1104 if ((yield* Clock.currentTimeMillis) >= retryAt) return null;
1105 return yield* new PullRequestOperationError({
1106 operation: "stack",
1107 detail: "paused",
1108 cause: new PullRequestProviderError({
1109 provider: SourceControlProviderKind.make("github"),
1110 operation: "getChangeRequestStack",
1111 reason: "rate-limited",
1112 detail: "paused",
1113 retryAt,
1114 }),
1115 });
1116 }),
1117 });
1118 const reads = Effect.all([
1119 Ref.get(fixture.summaryCalls).pipe(Effect.map((calls) => calls.length)),
1120 Ref.get(fixture.stackCalls).pipe(Effect.map((calls) => calls.length)),
1121 ]);
1122
1123 yield* Effect.gen(function* () {
1124 const reactor = yield* startAndSweep(fixture);
1125 assert.deepStrictEqual(yield* reads, [1, 1]);
1126 yield* sweepAgain(fixture, reactor);
1127 yield* sweepAgain(fixture, reactor);
1128 assert.deepStrictEqual(yield* reads, [1, 1]);
1129
1130 yield* sweepAgain(fixture, reactor);
1131 assert.deepStrictEqual(yield* reads, [2, 2]);
1132 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
1133 }).pipe(Effect.provide(fixture.layer));
1134 }),
1135 ),
1136 );
1137
1138 it.effect("reads open links fresh only when a run that ran a merge command ends", () =>
1139 Effect.scoped(
1140 Effect.gen(function* () {
1141 yield* TestClock.setTime(Date.parse(NOW));
1142 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1143 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1144 const fixture = yield* makeHarness({
1145 snapshot: makeSnapshot([
1146 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1147 makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }),
1148 ]),
1149 summary: (input) =>
1150 Ref.get(state).pipe(
1151 Effect.map((current) =>
1152 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1153 ),
1154 ),
1155 invalidate: ({ reference }) =>
1156 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1157 });
1158
1159 yield* Effect.gen(function* () {
1160 const reactor = yield* startAndSweep(fixture);
1161 yield* Ref.set(state, "merged");
1162 yield* Ref.set(fixture.summaryCalls, []);
1163
1164 yield* Queue.offerAll(fixture.domainEvents, [
1165 commandRan(ThreadId.make("other"), "gh pr view 9"),
1166 runUpdated(ThreadId.make("other"), "completed"),
1167 commandRan(ThreadId.make("agent"), "gh pr merge 7 --squash 2>&1 | tail -3"),
1168 runUpdated(ThreadId.make("agent"), "completed"),
1169 ]);
1170 yield* Queue.take(fixture.snapshotReads);
1171 yield* Queue.take(fixture.snapshotReads);
1172 yield* reactor.drain;
1173
1174 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1175 assert.deepStrictEqual(
1176 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
1177 [7],
1178 );
1179 assert.deepStrictEqual(
1180 (yield* Ref.get(fixture.syncCommands)).map((command) => [
1181 command.number,
1182 command.snapshot.state,
1183 ]),
1184 [[7, "merged"]],
1185 );
1186 }).pipe(Effect.provide(fixture.layer));
1187 }),
1188 ),
1189 );
1190});