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

PullRequestSyncReactor.test.ts

888 lines32.0 KB

1import {
2 EventId,
3 ProjectId,
4 ProviderInstanceId,
5 PullRequestOperationError,
6 ThreadId,
7 type OrchestrationCommand,
8 type OrchestrationEvent,
9 type OrchestrationProjectShell,
10 type OrchestrationShellSnapshot,
11 type OrchestrationThreadShell,
12 type PullRequestRef,
13 type PullRequestStack,
14 type PullRequestSummary,
15 type ThreadPullRequestLink,
16 type ThreadPullRequestSnapshot,
17} from "@t3tools/contracts";
18import { assert, describe, it } from "@effect/vitest";
19import * as Crypto from "effect/Crypto";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as PubSub from "effect/PubSub";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as Stream from "effect/Stream";
27import { TestClock } from "effect/testing";
28​
29import { PullRequestService } from "../pullRequest/PullRequestService.ts";
30import { ServerActivation } from "../serverActivation.ts";
31import {
32 OrchestrationEngineService,
33 type OrchestrationEngineShape,
34} from "./Services/OrchestrationEngine.ts";
35import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
36import * as PullRequestSyncReactor from "./PullRequestSyncReactor.ts";
37import { resolveAutoSettlementAt } from "./ThreadSettlementPolicy.ts";
38​
39const NOW = "2026-08-28T12:00:00.000Z";
40const PROJECT_ID = ProjectId.make("sync-project");
41​
42type SyncCommand = Extract<
43 OrchestrationCommand,
44 { readonly type: "thread.pull-request-link.sync" }
45>;
46type LinkCommand = Extract<OrchestrationCommand, { readonly type: "thread.pull-request.link" }>;
47​
48const testCrypto = Crypto.make({
49 randomBytes: (size) => new Uint8Array(size).fill(1),
50 digest: (_algorithm, data) => Effect.succeed(data),
51});
52​
53function makeProject(id: ProjectId = PROJECT_ID): OrchestrationProjectShell {
54 return {
55 id,
56 title: `Project ${id}`,
57 workspaceRoot: "/workspace/project",
58 defaultModelSelection: null,
59 scripts: [],
60 createdAt: "2026-08-01T00:00:00.000Z",
61 updatedAt: NOW,
62 };
64​
65function makeThread(
66 id: string,
67 overrides: Partial<OrchestrationThreadShell> = {},
68): OrchestrationThreadShell {
69 return {
70 id: ThreadId.make(id),
71 projectId: PROJECT_ID,
72 title: id,
73 modelSelection: {
74 instanceId: ProviderInstanceId.make("codex"),
75 model: "gpt-5",
76 },
77 runtimeMode: "full-access",
78 interactionMode: "default",
79 branch: null,
80 worktreePath: null,
81 pullRequests: [],
82 latestTurn: null,
83 createdAt: "2026-08-01T00:00:00.000Z",
84 updatedAt: "2026-08-20T00:00:00.000Z",
85 archivedAt: null,
86 settledOverride: null,
87 settledAt: null,
88 session: null,
89 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
90 hasPendingApprovals: false,
91 hasPendingUserInput: false,
92 hasActionableProposedPlan: false,
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​
127function makeSnapshot(
128 threads: ReadonlyArray<OrchestrationThreadShell>,
129 snapshotSequence = 1,
130): OrchestrationShellSnapshot {
131 return {
132 snapshotSequence,
133 projects: [makeProject()],
134 threads,
135 updatedAt: NOW,
136 };
138​
139function makeSummary(
140 input: PullRequestRef,
141 overrides: Partial<PullRequestSummary> = {},
142): PullRequestSummary {
143 return {
144 provider: "github",
145 projectId: input.projectId,
146 repository: input.repository,
147 number: input.number,
148 title: "Pull request",
149 url: `https://github.com/${input.repository}/pull/${input.number}`,
150 state: "open",
151 headBranch: "feature",
152 baseBranch: "main",
153 updatedAt: "2026-08-27T00:00:00.000Z",
154 ...overrides,
155 };
157​
158interface HarnessOptions {
159 readonly onDispatch?: (command: SyncCommand | LinkCommand) => Effect.Effect<void>;
160 readonly invalidate?: PullRequestService["Service"]["invalidate"];
161 readonly snapshot: OrchestrationShellSnapshot;
162 readonly summary?: (
163 input: PullRequestRef,
164 ) => Effect.Effect<PullRequestSummary, PullRequestOperationError>;
165 readonly stack?: (
166 input: PullRequestRef,
167 ) => Effect.Effect<PullRequestStack | null, PullRequestOperationError>;
169​
170const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: HarnessOptions) {
171 const activation = yield* Deferred.make<void>();
172 const snapshots = yield* Ref.make(options.snapshot);
173 const events = yield* PubSub.unbounded<OrchestrationEvent>();
174 const snapshotReads = yield* Queue.unbounded<void>();
175 const shellSnapshotReads = yield* Ref.make(0);
176 const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
177 const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]);
178 const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
179 const stackCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
180​
181 const summary: PullRequestService["Service"]["summary"] = (input, readOptions) =>
182 Effect.gen(function* () {
183 assert.strictEqual(readOptions?.recoverTransientFailure, false);
184 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
185 return yield* options.summary?.(input) ?? Effect.succeed(makeSummary(input));
186 });
187​
188 const stack: PullRequestService["Service"]["stack"] = (input, readOptions) =>
189 Effect.gen(function* () {
190 assert.strictEqual(readOptions?.includeDetails, false);
191 yield* Ref.update(stackCalls, (calls) => [...calls, input]);
192 return yield* options.stack?.(input) ?? Effect.succeed(null);
193 });
194​
195 const dispatch: OrchestrationEngineShape["dispatch"] = (command) => {
196 if (command.type === "thread.pull-request-link.sync") {
197 return Ref.update(syncCommands, (recorded) => [...recorded, command]).pipe(
198 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
199 Effect.as({ sequence: 1 }),
200 );
201 }
202 if (command.type === "thread.pull-request.link") {
203 return Ref.update(linkCommands, (recorded) => [...recorded, command]).pipe(
204 Effect.andThen(options.onDispatch?.(command) ?? Effect.void),
205 Effect.as({ sequence: 1 }),
206 );
207 }
208 return Effect.die(new Error(`Unexpected command: ${command.type}`));
209 };
210​
211 const dependencies = Layer.mergeAll(
212 Layer.mock(ProjectionSnapshotQuery)({
213 listThreadsWithPullRequests: () =>
214 Queue.offer(snapshotReads, undefined).pipe(
215 Effect.andThen(Ref.get(snapshots)),
216 Effect.map((snapshot) => snapshot.threads),
217 ),
218 getShellSnapshot: () =>
219 Ref.update(shellSnapshotReads, (count) => count + 1).pipe(
220 Effect.andThen(Queue.offer(snapshotReads, undefined)),
221 Effect.andThen(Ref.get(snapshots)),
222 ),
223 }),
224 Layer.mock(PullRequestService)({
225 summary,
226 stack,
227 invalidate: options.invalidate ?? (() => Effect.void),
228 }),
229 Layer.mock(OrchestrationEngineService)({
230 readEvents: () => Stream.empty,
231 dispatch,
232 streamDomainEvents: Stream.empty,
233 subscribeDomainEvents: PubSub.subscribe(events).pipe(
234 Effect.map((subscription) => Stream.fromSubscription(subscription)),
235 ),
236 latestSequence: Effect.succeed(0),
237 }),
238 Layer.succeed(ServerActivation, Deferred.await(activation)),
239 Layer.succeed(Crypto.Crypto, testCrypto),
240 );
241​
242 return {
243 events,
244 activation,
245 snapshots,
246 snapshotReads,
247 shellSnapshotReads,
248 syncCommands,
249 linkCommands,
250 summaryCalls,
251 stackCalls,
252 layer: PullRequestSyncReactor.layer.pipe(Layer.provide(dependencies)),
253 };
254});
255​
256type Harness = Effect.Success<ReturnType<typeof makeHarness>>;
257​
258const startAndSweep = Effect.fn("startPullRequestSyncHarness")(function* (fixture: Harness) {
259 const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
260 yield* reactor.start();
261 yield* Deferred.succeed(fixture.activation, undefined);
262 yield* Queue.take(fixture.snapshotReads);
263 yield* reactor.drain;
264 return reactor;
265});
266​
267const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* (
268 fixture: Harness,
269 reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
270) {
271 yield* TestClock.adjust("1 minute");
272 yield* Queue.take(fixture.snapshotReads);
273 yield* reactor.drain;
274});
275​
276/** What the reactor would have persisted, so the next sweep sees its own writes. */
277function applySync(
278 snapshot: OrchestrationShellSnapshot,
279 commands: ReadonlyArray<SyncCommand>,
280): OrchestrationShellSnapshot {
281 return {
282 ...snapshot,
283 snapshotSequence: snapshot.snapshotSequence + 1,
284 threads: snapshot.threads.map((thread) => ({
285 ...thread,
286 pullRequests: thread.pullRequests.map((link) => {
287 const command = commands.findLast(
288 (candidate) => candidate.threadId === thread.id && candidate.number === link.number,
289 );
290 return command === undefined
291 ? link
292 : { ...link, snapshot: command.snapshot, stack: command.stack };
293 }),
294 })),
295 };
297​
298describe("PullRequestSyncReactor", () => {
299 it.effect("syncs a newly linked merged PR without waiting for the periodic sweep", () =>
300 Effect.scoped(
301 Effect.gen(function* () {
302 yield* TestClock.setTime(Date.parse(NOW));
303 const fixture = yield* makeHarness({
304 snapshot: makeSnapshot([makeThread("one")]),
305 summary: (input) =>
306 Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
307 });
308 yield* Effect.gen(function* () {
309 const reactor = yield* startAndSweep(fixture);
310 const link = makeLink(42);
311 yield* Ref.set(
312 fixture.snapshots,
313 makeSnapshot([makeThread("one", { pullRequests: [link] })]),
314 );
315 yield* PubSub.publish(fixture.events, {
316 type: "thread.pull-request-linked",
317 sequence: 2,
318 eventId: EventId.make("linked"),
319 aggregateKind: "thread",
320 aggregateId: ThreadId.make("one"),
321 occurredAt: NOW,
322 commandId: null,
323 causationEventId: null,
324 correlationId: null,
325 metadata: {},
326 payload: { threadId: ThreadId.make("one"), link, updatedAt: NOW },
327 });
328 yield* Queue.take(fixture.snapshotReads);
329 yield* reactor.drain;
330 assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.snapshot.state, "merged");
331 }).pipe(Effect.provide(fixture.layer));
332 }),
333 ),
334 );
335 it.effect("retries a failed stack read after the summary becomes terminal", () =>
336 Effect.scoped(
337 Effect.gen(function* () {
338 yield* TestClock.setTime(Date.parse(NOW));
339 let attempts = 0;
340 const nativeStack: PullRequestStack = {
341 id: "stack",
342 number: 7,
343 url: "https://github.com/owner/repository/stacks/7",
344 base: "main",
345 layers: [{ number: 7, headBranch: "feature", state: "merged" }],
346 };
347 const fixture = yield* makeHarness({
348 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]),
349 summary: (input) =>
350 Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
351 stack: () =>
352 ++attempts === 1
353 ? Effect.fail(
354 new PullRequestOperationError({
355 operation: "stack",
356 detail: "temporary failure",
357 }),
358 )
359 : Effect.succeed(nativeStack),
360 });
361 yield* Effect.gen(function* () {
362 const reactor = yield* startAndSweep(fixture);
363 const commands = yield* Ref.get(fixture.syncCommands);
364 assert.deepStrictEqual(commands, []);
365 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
366 yield* sweepAgain(fixture, reactor);
367 assert.strictEqual(attempts, 2);
368 assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, {
369 kind: "native",
370 ...nativeStack,
371 });
372 }).pipe(Effect.provide(fixture.layer));
373 }),
374 ),
375 );
376​
377 it.effect("retries a failed sibling link before publishing a terminal snapshot", () =>
378 Effect.scoped(
379 Effect.gen(function* () {
380 yield* TestClock.setTime(Date.parse(NOW));
381 let failSibling = true;
382 const fixture = yield* makeHarness({
383 snapshot: makeSnapshot([
384 makeThread("one", { pullRequests: [makeLink(7, { state: "closed" })] }),
385 ]),
386 summary: (input) =>
387 Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
388 stack: () =>
389 Effect.succeed({
390 id: "stack",
391 number: 7,
392 url: "https://github.com/owner/repository/stacks/7",
393 base: "main",
394 layers: [
395 { number: 7, headBranch: "feature", state: "merged" },
396 { number: 8, headBranch: "sibling", state: "open" },
397 ],
398 }),
399 onDispatch: (command) =>
400 command.type === "thread.pull-request.link" && failSibling
401 ? Effect.die("temporary link failure")
402 : Effect.void,
403 });
404 yield* Effect.gen(function* () {
405 const reactor = yield* startAndSweep(fixture);
406 assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
407 failSibling = false;
408 yield* sweepAgain(fixture, reactor);
409 assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.snapshot.state, "merged");
410 assert.strictEqual((yield* Ref.get(fixture.linkCommands)).at(-1)?.number, 8);
411 }).pipe(Effect.provide(fixture.layer));
412 }),
413 ),
414 );
415​
416 it.effect("concurrent stack reads persist a shared sibling once before syncing both roots", () =>
417 Effect.scoped(
418 Effect.gen(function* () {
419 const readsReady = yield* Deferred.make<void>();
420 let reads = 0;
421 let linked = false;
422 const fixture = yield* makeHarness({
423 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7), makeLink(8)] })]),
424 stack: () =>
425 Effect.gen(function* () {
426 if (++reads === 2) yield* Deferred.succeed(readsReady, undefined);
427 yield* Deferred.await(readsReady);
428 return {
429 id: "stack",
430 number: 7,
431 url: "https://github.com/owner/repository/stacks/7",
432 base: "main",
433 layers: [{ number: 9, headBranch: "sibling", state: "open" as const }],
434 };
435 }),
436 onDispatch: (command) =>
437 Effect.gen(function* () {
438 if (command.type === "thread.pull-request.link") {
439 yield* Effect.yieldNow;
440 assert.strictEqual(linked, false);
441 linked = true;
442 } else {
443 assert.strictEqual(linked, true);
444 }
445 }),
446 });
447 yield* Effect.gen(function* () {
448 yield* startAndSweep(fixture);
449 assert.strictEqual((yield* Ref.get(fixture.linkCommands)).length, 1);
450 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 2);
451 }).pipe(Effect.provide(fixture.layer));
452 }),
453 ),
454 );
455​
456 it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () =>
457 Effect.scoped(
458 Effect.gen(function* () {
459 yield* TestClock.setTime(Date.parse(NOW));
460 const fixture = yield* makeHarness({
461 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]),
462 });
463 yield* Effect.gen(function* () {
464 const reactor = yield* startAndSweep(fixture);
465 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0);
466 yield* reactor.requestSync({
467 host: "github.com",
468 repository: "owner/repository",
469 number: 7,
470 });
471 yield* Queue.take(fixture.snapshotReads);
472 yield* reactor.drain;
473 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
474 }).pipe(Effect.provide(fixture.layer));
475 }),
476 ),
477 );
478 it.effect("snapshots an unsynced link once and writes it to the thread", () =>
479 Effect.scoped(
480 Effect.gen(function* () {
481 yield* TestClock.setTime(Date.parse(NOW));
482 const fixture = yield* makeHarness({
483 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
484 summary: (input) =>
485 Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })),
486 });
487​
488 yield* Effect.gen(function* () {
489 yield* startAndSweep(fixture);
490​
491 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
492 {
493 projectId: PROJECT_ID,
494 host: "github.com",
495 repository: "owner/repository",
496 number: 42,
497 },
498 ]);
499 assert.deepStrictEqual(
500 (yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest),
501 [
502 {
503 type: "thread.pull-request-link.sync",
504 threadId: ThreadId.make("one"),
505 host: "github.com",
506 repository: "owner/repository",
507 number: 42,
508 snapshot: {
509 state: "open",
510 title: "Ship it",
511 headBranch: "feature",
512 baseBranch: "main",
513 isDraft: true,
514 updatedAt: "2026-08-27T00:00:00.000Z",
515 syncedAt: NOW,
516 closedAt: null,
517 mergedAt: null,
518 },
519 stack: null,
520 },
521 ],
522 );
523 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
524 // Reads only linked threads, never the full shell snapshot of every thread.
525 assert.strictEqual(yield* Ref.get(fixture.shellSnapshotReads), 0);
526 }).pipe(Effect.provide(fixture.layer));
527 }),
528 ),
529 );
530​
531 it.effect("asks the host once for a pull request shared by two threads", () =>
532 Effect.scoped(
533 Effect.gen(function* () {
534 yield* TestClock.setTime(Date.parse(NOW));
535 const fixture = yield* makeHarness({
536 snapshot: makeSnapshot([
537 makeThread("one", { pullRequests: [makeLink(42)] }),
538 makeThread("two", {
539 pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })],
540 }),
541 ]),
542 });
543​
544 yield* Effect.gen(function* () {
545 yield* startAndSweep(fixture);
546​
547 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
548 const commands = yield* Ref.get(fixture.syncCommands);
549 assert.deepStrictEqual(
550 commands
551 .map((command) => [command.threadId, command.repository] as const)
552 .sort((left, right) => left[0].localeCompare(right[0])),
553 [
554 [ThreadId.make("one"), "owner/repository"],
555 [ThreadId.make("two"), "Owner/Repository"],
556 ],
557 );
558 }).pipe(Effect.provide(fixture.layer));
559 }),
560 ),
561 );
562​
563 it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>
564 Effect.scoped(
565 Effect.gen(function* () {
566 const fixture = yield* makeHarness({
567 snapshot: makeSnapshot([
568 makeThread("one", {
569 pullRequests: [
570 makeLink(42, null, {
571 host: "forge.example",
572 url: "http://forge.example:3000/owner/repository/pulls/42",
573 }),
574 ],
575 }),
576 ]),
577 summary: (input) => Effect.succeed(makeSummary(input)),
578 });
579 yield* Effect.gen(function* () {
580 yield* startAndSweep(fixture);
581 assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");
582 assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");
583 }).pipe(Effect.provide(fixture.layer));
584 }),
585 ),
586 );
587​
588 it.effect("dispatches nothing when the host snapshot is unchanged", () =>
589 Effect.scoped(
590 Effect.gen(function* () {
591 yield* TestClock.setTime(Date.parse(NOW));
592 const fixture = yield* makeHarness({
593 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
594 });
595​
596 yield* Effect.gen(function* () {
597 const reactor = yield* startAndSweep(fixture);
598 const firstSweep = yield* Ref.get(fixture.syncCommands);
599 assert.strictEqual(firstSweep.length, 1);
600 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
601​
602 yield* sweepAgain(fixture, reactor);
603​
604 // Still open on an active thread, so the host was asked again, but nothing changed.
605 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
606 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
607 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
608 }).pipe(Effect.provide(fixture.layer));
609 }),
610 ),
611 );
612​
613 it.effect("refreshes closed links through the reactor's project after reopening elsewhere", () =>
614 Effect.scoped(
615 Effect.gen(function* () {
616 yield* TestClock.setTime(Date.parse(NOW));
617 const stale = yield* Ref.make(true);
618 const fixture = yield* makeHarness({
619 snapshot: makeSnapshot([
620 makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
621 makeThread("second", {
622 projectId: ProjectId.make("second-project"),
623 pullRequests: [makeLink(42, { state: "closed" })],
624 }),
625 ]),
626 invalidate: ({ reference }) =>
627 reference?.projectId === makeProject().id && reference.host === "github.com"
628 ? Ref.set(stale, false)
629 : Effect.void,
630 summary: (input) =>
631 Ref.get(stale).pipe(
632 Effect.map((cached) => makeSummary(input, { state: cached ? "closed" : "open" })),
633 ),
634 });
635 yield* Effect.gen(function* () {
636 const reactor = yield* startAndSweep(fixture);
637 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
638 yield* reactor.requestSync({
639 host: "github.com",
640 repository: "owner/repository",
641 number: 42,
642 });
643 yield* Queue.take(fixture.snapshotReads);
644 yield* reactor.drain;
645 const commands = yield* Ref.get(fixture.syncCommands);
646 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
647 const snapshot = yield* Ref.get(fixture.snapshots);
648 assert.deepStrictEqual(
649 snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
650 ["open", "open"],
651 );
652 }).pipe(Effect.provide(fixture.layer));
653 }),
654 ),
655 );
656​
657 it.effect("stops asking the host once a pull request is merged", () =>
658 Effect.scoped(
659 Effect.gen(function* () {
660 yield* TestClock.setTime(Date.parse(NOW));
661 const fixture = yield* makeHarness({
662 snapshot: makeSnapshot([
663 makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
664 ]),
665 });
666​
667 yield* Effect.gen(function* () {
668 const reactor = yield* startAndSweep(fixture);
669 yield* sweepAgain(fixture, reactor);
670​
671 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
672 assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
673​
674 yield* reactor.requestSync({
675 host: "github.com",
676 repository: "owner/repository",
677 number: 1,
678 });
679 yield* Queue.take(fixture.snapshotReads);
680 yield* reactor.drain;
681​
682 assert.deepStrictEqual(
683 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
684 [1],
685 );
686 }).pipe(Effect.provide(fixture.layer));
687 }),
688 ),
689 );
690​
691 it.effect("discovers externally reopened pull requests after fifteen minutes", () =>
692 Effect.scoped(
693 Effect.gen(function* () {
694 yield* TestClock.setTime(Date.parse(NOW));
695 const state = yield* Ref.make<"closed" | "open">("closed");
696 const fixture = yield* makeHarness({
697 snapshot: makeSnapshot([
698 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
699 ]),
700 summary: (input) =>
701 Ref.get(state).pipe(Effect.map((state) => makeSummary(input, { state }))),
702 });
703 yield* Effect.gen(function* () {
704 const reactor = yield* startAndSweep(fixture);
705 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
706 yield* Ref.set(state, "open");
707 for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
708 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
709 yield* sweepAgain(fixture, reactor);
710 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
711 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
712 }).pipe(Effect.provide(fixture.layer));
713 }),
714 ),
715 );
716​
717 it.effect("preserves a refresh requested while an older host read is in flight", () =>
718 Effect.scoped(
719 Effect.gen(function* () {
720 yield* TestClock.setTime(Date.parse(NOW));
721 const reading = yield* Deferred.make<void>();
722 const release = yield* Deferred.make<void>();
723 let calls = 0;
724 const fixture = yield* makeHarness({
725 snapshot: makeSnapshot([]),
726 summary: (input) =>
727 Effect.gen(function* () {
728 calls += 1;
729 if (calls === 1) {
730 yield* Deferred.succeed(reading, undefined);
731 yield* Deferred.await(release);
732 }
733 return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
734 }),
735 });
736 yield* Effect.gen(function* () {
737 const reactor = yield* startAndSweep(fixture);
738 yield* Ref.set(
739 fixture.snapshots,
740 makeSnapshot([
741 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
742 ]),
743 );
744 const key = { host: "github.com", repository: "owner/repository", number: 2 };
745 yield* reactor.requestSync(key);
746 yield* Deferred.await(reading);
747 yield* reactor.requestSync(key);
748 yield* Deferred.succeed(release, undefined);
749 yield* reactor.drain;
750 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
751 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
752 }).pipe(Effect.provide(fixture.layer));
753 }),
754 ),
755 );
756​
757 it.effect("polls open pull requests on settled threads every fifteen minutes", () =>
758 Effect.scoped(
759 Effect.gen(function* () {
760 yield* TestClock.setTime(Date.parse(NOW));
761 const fixture = yield* makeHarness({
762 snapshot: makeSnapshot([
763 makeThread("settled", {
764 settledOverride: "settled",
765 settledAt: "2026-08-21T00:00:00.000Z",
766 pullRequests: [makeLink(5, { state: "open" })],
767 }),
768 ]),
769 });
770​
771 yield* Effect.gen(function* () {
772 const reactor = yield* startAndSweep(fixture);
773 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
774​
775 yield* sweepAgain(fixture, reactor);
776 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
777​
778 for (let index = 0; index < 13; index += 1) yield* sweepAgain(fixture, reactor);
779 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
780​
781 yield* sweepAgain(fixture, reactor);
782 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
783 }).pipe(Effect.provide(fixture.layer));
784 }),
785 ),
786 );
787​
788 it.effect("auto-links missing native stack layers and leaves dismissed ones alone", () =>
789 Effect.scoped(
790 Effect.gen(function* () {
791 yield* TestClock.setTime(Date.parse(NOW));
792 const stack: PullRequestStack = {
793 id: "stack-1",
794 number: 42,
795 url: "https://github.com/owner/repository/stack/1",
796 base: "main",
797 layers: [
798 { number: 41, headBranch: "layer-1", state: "merged" },
799 { number: 42, headBranch: "layer-2", state: "merged" },
800 { number: 43, headBranch: "layer-3", state: "open" },
801 ],
802 };
803 let thread = makeThread("one", {
804 pullRequests: [
805 makeLink(42, { state: "open" }),
806 makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
807 ],
808 });
809 const fixture = yield* makeHarness({
810 snapshot: makeSnapshot([thread]),
811 summary: (input) =>
812 Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
813 stack: () => Effect.succeed(stack),
814 onDispatch: (command) =>
815 Effect.sync(() => {
816 thread =
817 command.type === "thread.pull-request.link"
818 ? { ...thread, pullRequests: [...thread.pullRequests, makeLink(command.number)] }
819 : applySync(makeSnapshot([thread]), [command]).threads[0]!;
820 // Every projected event may wake settlement, including the terminal root update.
821 assert.isNull(
822 resolveAutoSettlementAt({
823 thread,
824 pullRequest: null,
825 now: NOW,
826 autoSettleAfterDays: null,
827 autoSettleOnMerge: true,
828 }),
829 );
830 }),
831 });
832​
833 yield* Effect.gen(function* () {
834 yield* startAndSweep(fixture);
835​
836 const syncCommands = yield* Ref.get(fixture.syncCommands);
837 assert.deepStrictEqual(
838 syncCommands.map((command) => [command.number, command.stack] as const),
839 [[42, { kind: "native", ...stack }]],
840 );
841 assert.deepStrictEqual(
842 (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
843 [
844 {
845 type: "thread.pull-request.link",
846 threadId: ThreadId.make("one"),
847 host: "github.com",
848 repository: "owner/repository",
849 number: 43,
850 url: "https://github.com/owner/repository/pull/43",
851 source: "stack",
852 },
853 ],
854 );
855 }).pipe(Effect.provide(fixture.layer));
856 }),
857 ),
858 );
859​
860 it.effect("keeps existing snapshots and continues when the host fails", () =>
861 Effect.scoped(
862 Effect.gen(function* () {
863 yield* TestClock.setTime(Date.parse(NOW));
864 const fixture = yield* makeHarness({
865 snapshot: makeSnapshot([
866 makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
867 makeThread("fine", { pullRequests: [makeLink(8)] }),
868 ]),
869 summary: (input) =>
870 input.number === 7
871 ? Effect.fail(
872 new PullRequestOperationError({ operation: "summary", detail: "host down" }),
873 )
874 : Effect.succeed(makeSummary(input)),
875 });
876​
877 yield* Effect.gen(function* () {
878 yield* startAndSweep(fixture);
879​
880 assert.deepStrictEqual(
881 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
882 [8],
883 );
884 }).pipe(Effect.provide(fixture.layer));
885 }),
886 ),
887 );
888});