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

PullRequestSyncReactor.test.ts

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