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

PullRequestSyncReactor.test.ts

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