Open History to see the last commit
1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Stream from "effect/Stream";
3import {
4 EventId,
5 MessageId,
6 ProjectId,
7 ProviderInstanceId,
8 PullRequestOperationError,
9 RunId,
10 ThreadId,
11 TurnItemId,
12 type OrchestrationV2Command as OrchestrationCommand,
13 type OrchestrationV2DomainEvent,
14 type OrchestrationV2Run,
15 type OrchestrationProjectShell,
16 type PullRequestRef,
17 type PullRequestStack,
18 type PullRequestSummary,
19 type ThreadPullRequestKey,
20 type ThreadPullRequestLink,
21 type ThreadPullRequestSnapshot,
22} from "@t3tools/contracts";
23import { assert, describe, it } from "@effect/vitest";
24import * as Clock from "effect/Clock";
25import * as Crypto from "effect/Crypto";
26import * as DateTime from "effect/DateTime";
27import * as Deferred from "effect/Deferred";
28import * as Effect from "effect/Effect";
29import * as Layer from "effect/Layer";
30import * as Queue from "effect/Queue";
31import * as Ref from "effect/Ref";
32import { TestClock } from "effect/testing";
33
34import * as GitManager from "../git/GitManager.ts";
35import * as PullRequestService from "../pullRequest/PullRequestService.ts";
36import * as ServerActivation from "../serverActivation.ts";
37import * as Orchestrator from "./Orchestrator.ts";
38import * as ProjectionStore from "./ProjectionStore.ts";
39import * as PullRequestSyncReactor from "./PullRequestSyncReactor.ts";
40import type { PullRequestTestThread } from "./testkit/pullRequestFixtures.ts";
41
42const NOW = "2026-08-28T12:00:00.000Z";
43const PROJECT_ID = ProjectId.make("sync-project");
44
45type SyncCommand = Extract<
46 OrchestrationCommand,
47 { readonly type: "thread.pull-request-link.sync" }
48>;
49type LinkCommand = Extract<OrchestrationCommand, { readonly type: "thread.pull-request.link" }>;
50
51const testCrypto = Crypto.make({
52 randomBytes: (size) => new Uint8Array(size).fill(1),
53 digest: (_algorithm, data) => Effect.succeed(data),
54});
55
56function makeProject(id: ProjectId = PROJECT_ID): OrchestrationProjectShell {
57 return {
58 id,
59 title: `Project ${id}`,
60 workspaceRoot: "/workspace/project",
61 defaultModelSelection: null,
62 scripts: [],
63 createdAt: "2026-08-01T00:00:00.000Z",
64 updatedAt: NOW,
65 };
66}
67
68function makeThread(
69 id: string,
70 overrides: Partial<PullRequestTestThread> = {},
71): PullRequestTestThread {
72 return {
73 id: ThreadId.make(id),
74 projectId: PROJECT_ID,
75 title: id,
76 modelSelection: {
77 instanceId: ProviderInstanceId.make("codex"),
78 model: "gpt-5",
79 },
80 runtimeMode: "full-access",
81 interactionMode: "default",
82 branch: null,
83 worktreePath: null,
84 pullRequests: [],
85 createdAt: "2026-08-01T00:00:00.000Z",
86 updatedAt: "2026-08-20T00:00:00.000Z",
87 archivedAt: null,
88 settledOverride: null,
89 settledAt: null,
90 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
91 ...overrides,
92 };
93}
94
95function makeLink(
96 number: number,
97 snapshot: Partial<ThreadPullRequestSnapshot> | null = null,
98 overrides: Partial<ThreadPullRequestLink> = {},
99): ThreadPullRequestLink {
100 return {
101 host: "github.com",
102 repository: "owner/repository",
103 number,
104 url: `https://github.com/owner/repository/pull/${number}`,
105 source: "manual",
106 linkedAt: "2026-08-10T00:00:00.000Z",
107 snapshot:
108 snapshot === null
109 ? null
110 : {
111 state: "open",
112 title: "Pull request",
113 headBranch: "feature",
114 baseBranch: "main",
115 isDraft: false,
116 updatedAt: "2026-08-27T00:00:00.000Z",
117 syncedAt: "2026-08-27T00:00:00.000Z",
118 ...snapshot,
119 },
120 stack: null,
121 ...overrides,
122 };
123}
124
125interface TestShellSnapshot {
126 readonly snapshotSequence: number;
127 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
128 readonly threads: ReadonlyArray<PullRequestTestThread>;
129 readonly updatedAt: string;
130}
131
132function makeSnapshot(
133 threads: ReadonlyArray<PullRequestTestThread>,
134 snapshotSequence = 1,
135): TestShellSnapshot {
136 return {
137 snapshotSequence,
138 projects: [makeProject()],
139 threads,
140 updatedAt: NOW,
141 };
142}
143
144function makeSummary(
145 input: PullRequestRef,
146 overrides: Partial<PullRequestSummary> = {},
147): PullRequestSummary {
148 return {
149 provider: SourceControlProviderKind.make("github"),
150 projectId: input.projectId,
151 repository: input.repository,
152 number: input.number,
153 title: "Pull request",
154 url: `https://github.com/${input.repository}/pull/${input.number}`,
155 state: "open",
156 headBranch: "feature",
157 baseBranch: "main",
158 updatedAt: "2026-08-27T00:00:00.000Z",
159 ...overrides,
160 };
161}
162
163interface HarnessOptions {
164 readonly invalidate?: PullRequestService.PullRequestService["Service"]["invalidate"];
165 readonly snapshot: TestShellSnapshot;
166 readonly summary?: (
167 input: PullRequestRef,
168 ) => Effect.Effect<PullRequestSummary, PullRequestOperationError>;
169 readonly stack?: (
170 input: PullRequestRef,
171 ) => Effect.Effect<PullRequestStack | null, PullRequestOperationError>;
172 readonly onSync?: (command: SyncCommand) => Effect.Effect<unknown>;
173}
174
175const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: HarnessOptions) {
176 const activation = yield* Deferred.make<void>();
177 const snapshots = yield* Ref.make(options.snapshot);
178 const snapshotReads = yield* Queue.unbounded<void>();
179 const shellSnapshotReads = yield* Ref.make(0);
180 const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
181 const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]);
182 const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
183 const stackCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
184 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
185 const stateChanges = yield* Queue.unbounded<ThreadPullRequestKey>();
186
187 const summary: PullRequestService.PullRequestService["Service"]["summary"] = (
188 input,
189 readOptions,
190 ) =>
191 Effect.gen(function* () {
192 assert.strictEqual(readOptions?.recoverTransientFailure, false);
193 yield* Ref.update(summaryCalls, (calls) => [...calls, input]);
194 return yield* options.summary?.(input) ?? Effect.succeed(makeSummary(input));
195 });
196
197 const stack: PullRequestService.PullRequestService["Service"]["stack"] = (input, readOptions) =>
198 Effect.gen(function* () {
199 assert.strictEqual(readOptions?.includeDetails, false);
200 yield* Ref.update(stackCalls, (calls) => [...calls, input]);
201 return yield* options.stack?.(input) ?? Effect.succeed(null);
202 });
203
204 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => {
205 if (command.type === "thread.pull-request-link.sync") {
206 return Ref.update(syncCommands, (recorded) => [...recorded, command]).pipe(
207 Effect.andThen(options.onSync?.(command) ?? Effect.void),
208 Effect.as({ sequence: 1, storedEvents: [] }),
209 );
210 }
211 if (command.type === "thread.pull-request.link") {
212 return Ref.update(linkCommands, (recorded) => [...recorded, command]).pipe(
213 Effect.as({ sequence: 1, storedEvents: [] }),
214 );
215 }
216 return Effect.die(new Error(`Unexpected command: ${command.type}`));
217 };
218
219 const layerDependencies = Layer.mergeAll(
220 Layer.mock(PullRequestService.PullRequestService)({
221 summary,
222 stack,
223 invalidate: options.invalidate ?? (() => Effect.void),
224 subscribeStateChanges: Effect.succeed(Stream.fromQueue(stateChanges)),
225 }),
226 Layer.mock(GitManager.GitManager)({
227 subscribePullRequestStateChanges: Effect.succeed(Stream.empty),
228 }),
229 Layer.mock(ProjectionStore.ProjectionStoreV2)({
230 getThreadsWithPullRequests: (threadId) =>
231 Queue.offer(snapshotReads, undefined).pipe(
232 Effect.andThen(Ref.get(snapshots)),
233 Effect.map((snapshot) =>
234 snapshot.threads
235 .filter(
236 (thread) =>
237 (threadId === undefined || thread.id === threadId) &&
238 thread.archivedAt === null &&
239 thread.pullRequests.length > 0,
240 )
241 .map((thread) => ({
242 id: thread.id,
243 projectId: thread.projectId,
244 lineage: {
245 parentThreadId: null,
246 relationshipToParent: null,
247 rootThreadId: thread.id,
248 },
249 settledOverride: thread.settledOverride,
250 settledAt: thread.settledAt === null ? null : DateTime.makeUnsafe(thread.settledAt),
251 pullRequests: thread.pullRequests,
252 })),
253 ),
254 ),
255 }),
256 Layer.mock(Orchestrator.OrchestratorV2)({
257 getShellSnapshot: () =>
258 Ref.update(shellSnapshotReads, (count) => count + 1).pipe(
259 Effect.andThen(Effect.die(new Error("pull request sync must not read the shell"))),
260 ),
261 dispatch,
262 streamDomainEvents: Stream.fromQueue(domainEvents),
263 }),
264 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
265 Layer.succeed(Crypto.Crypto, testCrypto),
266 );
267
268 return {
269 activation,
270 snapshots,
271 snapshotReads,
272 shellSnapshotReads,
273 syncCommands,
274 linkCommands,
275 summaryCalls,
276 stackCalls,
277 domainEvents,
278 stateChanges,
279 layer: PullRequestSyncReactor.layer.pipe(Layer.provide(layerDependencies)),
280 };
281});
282
283type Harness = Effect.Success<ReturnType<typeof makeHarness>>;
284
285const startAndSweep = Effect.fn("startPullRequestSyncHarness")(function* (fixture: Harness) {
286 const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
287 yield* reactor.start();
288 yield* Deferred.succeed(fixture.activation, undefined);
289 yield* Queue.take(fixture.snapshotReads);
290 yield* reactor.drain;
291 return reactor;
292});
293
294const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* (
295 fixture: Harness,
296 reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
297) {
298 yield* TestClock.adjust("1 minute");
299 yield* Queue.take(fixture.snapshotReads);
300 yield* reactor.drain;
301});
302
303function runUpdated(
304 threadId: ThreadId,
305 status: OrchestrationV2Run["status"],
306): OrchestrationV2DomainEvent {
307 const runId = RunId.make(`run:${threadId}:1`);
308 const at = DateTime.makeUnsafe(NOW);
309 return {
310 type: "run.updated",
311 id: EventId.make(`event:${threadId}:${status}`),
312 threadId,
313 runId,
314 occurredAt: at,
315 payload: {
316 id: runId,
317 threadId,
318 ordinal: 1,
319 providerInstanceId: ProviderInstanceId.make("codex"),
320 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
321 providerThreadId: null,
322 userMessageId: MessageId.make(`message:${threadId}:1`),
323 rootNodeId: null,
324 activeAttemptId: null,
325 status,
326 requestedAt: at,
327 startedAt: at,
328 completedAt: at,
329 checkpointId: null,
330 contextHandoffId: null,
331 },
332 };
333}
334
335function commandRan(threadId: ThreadId, input: string): OrchestrationV2DomainEvent {
336 const runId = RunId.make(`run:${threadId}:1`);
337 const at = DateTime.makeUnsafe(NOW);
338 return {
339 type: "turn-item.updated",
340 id: EventId.make(`event:${threadId}:command`),
341 threadId,
342 runId,
343 occurredAt: at,
344 payload: {
345 id: TurnItemId.make(`item:${threadId}:command`),
346 threadId,
347 runId,
348 nodeId: null,
349 providerThreadId: null,
350 providerTurnId: null,
351 nativeItemRef: null,
352 parentItemId: null,
353 ordinal: 1,
354 status: "completed",
355 title: null,
356 startedAt: at,
357 completedAt: at,
358 updatedAt: at,
359 type: "command_execution",
360 input,
361 },
362 };
363}
364
365function applySync(
366 snapshot: TestShellSnapshot,
367 commands: ReadonlyArray<SyncCommand>,
368): TestShellSnapshot {
369 return {
370 ...snapshot,
371 snapshotSequence: snapshot.snapshotSequence + 1,
372 threads: snapshot.threads.map((thread) => ({
373 ...thread,
374 pullRequests: thread.pullRequests.map((link) => {
375 const command = commands.findLast(
376 (candidate) => candidate.threadId === thread.id && candidate.number === link.number,
377 );
378 return command === undefined
379 ? link
380 : { ...link, snapshot: command.snapshot, stack: command.stack };
381 }),
382 })),
383 };
384}
385
386const stackLayer = (number: number) => ({
387 number,
388 headBranch: `layer-${number}`,
389 state: "open" as const,
390});
391
392/**
393 * Stack 80 starts as #18 and #20; `grow` pushes #83 on top. `cachedRead` behaves like
394 * `PullRequestReadCache`: a read is kept for 60 s and invalidating the reference drops it.
395 */
396function makeGrowingStack() {
397 let layers = [stackLayer(18), stackLayer(20)];
398 const entries = new Map<number, { readonly layers: typeof layers; expiresAt: number }>();
399 const invalidated: Array<number> = [];
400 const stackOf = (stackLayers: typeof layers): PullRequestStack => ({
401 id: "stack-80",
402 number: 80,
403 url: "https://github.com/owner/repository/stack/80",
404 base: "main",
405 layers: stackLayers,
406 });
407 return {
408 invalidated,
409 grow: () => {
410 layers = [...layers, stackLayer(83)];
411 },
412 read: () => Effect.sync(() => stackOf(layers)),
413 invalidate: (({ reference }) =>
414 Effect.sync(() => {
415 invalidated.push(reference?.number ?? -1);
416 entries.delete(reference?.number ?? -1);
417 })) satisfies PullRequestService.PullRequestService["Service"]["invalidate"],
418 cachedRead: (input: PullRequestRef) =>
419 Clock.currentTimeMillis.pipe(
420 Effect.map((now) => {
421 let entry = entries.get(input.number);
422 if (entry === undefined || entry.expiresAt <= now) {
423 entry = { layers, expiresAt: now + 60_000 };
424 entries.set(input.number, entry);
425 }
426 return stackOf(entry.layers);
427 }),
428 ),
429 };
430}
431
432const applyRecordedSyncs = (fixture: Harness) =>
433 Ref.get(fixture.syncCommands).pipe(
434 Effect.flatMap((commands) =>
435 Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)),
436 ),
437 );
438
439const linkPullRequest83 = (fixture: Harness) =>
440 Ref.update(fixture.snapshots, (snapshot) => ({
441 ...snapshot,
442 threads: snapshot.threads.map((thread) => ({
443 ...thread,
444 pullRequests: [...thread.pullRequests, makeLink(83)],
445 })),
446 }));
447
448const storedStackLayers = (fixture: Harness) =>
449 Ref.get(fixture.snapshots).pipe(
450 Effect.map((snapshot) =>
451 snapshot.threads[0]!.pullRequests.map((link) => [
452 link.number,
453 link.stack?.layers.map((layer) => layer.number),
454 ]),
455 ),
456 );
457
458const requestAndApply = Effect.fn("requestPullRequestSyncHarness")(function* (
459 fixture: Harness,
460 reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"],
461 number: number,
462) {
463 yield* reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
464 yield* Queue.take(fixture.snapshotReads);
465 yield* reactor.drain;
466 yield* applyRecordedSyncs(fixture);
467});
468
469describe("PullRequestSyncReactor", () => {
470 it.effect("retries a failed stack read after the summary becomes terminal", () =>
471 Effect.scoped(
472 Effect.gen(function* () {
473 yield* TestClock.setTime(Date.parse(NOW));
474 let attempts = 0;
475 const nativeStack: PullRequestStack = {
476 id: "stack",
477 number: 7,
478 url: "https://github.com/owner/repository/stacks/7",
479 base: "main",
480 layers: [{ number: 7, headBranch: "feature", state: "merged" }],
481 };
482 const fixture = yield* makeHarness({
483 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]),
484 summary: (input) =>
485 Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
486 stack: () =>
487 ++attempts === 1
488 ? Effect.fail(
489 new PullRequestOperationError({
490 operation: "stack",
491 detail: "temporary failure",
492 }),
493 )
494 : Effect.succeed(nativeStack),
495 });
496 yield* Effect.gen(function* () {
497 const reactor = yield* startAndSweep(fixture);
498 const commands = yield* Ref.get(fixture.syncCommands);
499 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
500 yield* sweepAgain(fixture, reactor);
501 assert.strictEqual(attempts, 2);
502 assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, {
503 kind: "native",
504 ...nativeStack,
505 });
506 }).pipe(Effect.provide(fixture.layer));
507 }),
508 ),
509 );
510
511 it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () =>
512 Effect.scoped(
513 Effect.gen(function* () {
514 yield* TestClock.setTime(Date.parse(NOW));
515 const fixture = yield* makeHarness({
516 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]),
517 });
518 yield* Effect.gen(function* () {
519 const reactor = yield* startAndSweep(fixture);
520 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0);
521 yield* reactor.requestSync({
522 host: "github.com",
523 repository: "owner/repository",
524 number: 7,
525 });
526 yield* Queue.take(fixture.snapshotReads);
527 yield* reactor.drain;
528 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
529 }).pipe(Effect.provide(fixture.layer));
530 }),
531 ),
532 );
533 it.effect("snapshots an unsynced link once and writes it to the thread", () =>
534 Effect.scoped(
535 Effect.gen(function* () {
536 yield* TestClock.setTime(Date.parse(NOW));
537 const fixture = yield* makeHarness({
538 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
539 summary: (input) =>
540 Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })),
541 });
542
543 yield* Effect.gen(function* () {
544 yield* startAndSweep(fixture);
545
546 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
547 {
548 projectId: PROJECT_ID,
549 host: "github.com",
550 repository: "owner/repository",
551 number: 42,
552 },
553 ]);
554 assert.deepStrictEqual(
555 (yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest),
556 [
557 {
558 type: "thread.pull-request-link.sync",
559 threadId: ThreadId.make("one"),
560 host: "github.com",
561 repository: "owner/repository",
562 number: 42,
563 snapshot: {
564 state: "open",
565 title: "Ship it",
566 headBranch: "feature",
567 baseBranch: "main",
568 isDraft: true,
569 updatedAt: "2026-08-27T00:00:00.000Z",
570 syncedAt: NOW,
571 closedAt: null,
572 mergedAt: null,
573 },
574 stack: null,
575 },
576 ],
577 );
578 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
579 assert.strictEqual(yield* Ref.get(fixture.shellSnapshotReads), 0);
580 }).pipe(Effect.provide(fixture.layer));
581 }),
582 ),
583 );
584
585 it.effect("asks the host once for a pull request shared by two threads in one project", () =>
586 Effect.scoped(
587 Effect.gen(function* () {
588 yield* TestClock.setTime(Date.parse(NOW));
589 const fixture = yield* makeHarness({
590 snapshot: makeSnapshot([
591 makeThread("one", { pullRequests: [makeLink(42)] }),
592 makeThread("two", {
593 pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })],
594 }),
595 ]),
596 });
597
598 yield* Effect.gen(function* () {
599 yield* startAndSweep(fixture);
600
601 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
602 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
603 const commands = yield* Ref.get(fixture.syncCommands);
604 assert.deepStrictEqual(
605 commands
606 .map((command) => [command.threadId, command.repository] as const)
607 .sort((left, right) => left[0].localeCompare(right[0])),
608 [
609 [ThreadId.make("one"), "owner/repository"],
610 [ThreadId.make("two"), "Owner/Repository"],
611 ],
612 );
613 }).pipe(Effect.provide(fixture.layer));
614 }),
615 ),
616 );
617
618 it.effect.each(["summary", "stack"] as const)(
619 "isolates a failed project %s refresh and retries it after the other project succeeds",
620 (operation) =>
621 Effect.scoped(
622 Effect.gen(function* () {
623 yield* TestClock.setTime(Date.parse(NOW));
624 const otherProject = ProjectId.make("other-project");
625 const link = makeLink(42, { state: "merged", mergedAt: NOW });
626 let failing = true;
627 const failure = new PullRequestOperationError({ operation, detail: "checkout missing" });
628 const fixture = yield* makeHarness({
629 snapshot: makeSnapshot([
630 makeThread("failing", { pullRequests: [link] }),
631 makeThread("healthy", { projectId: otherProject, pullRequests: [link] }),
632 makeThread("same-project", { projectId: otherProject, pullRequests: [link] }),
633 ]),
634 summary: (input) =>
635 failing && input.projectId === PROJECT_ID && operation === "summary"
636 ? Effect.fail(failure)
637 : Effect.succeed(
638 makeSummary(input, {
639 state: "merged",
640 mergedAt: NOW,
641 title: input.projectId,
642 }),
643 ),
644 stack: (input) =>
645 failing && input.projectId === PROJECT_ID && operation === "stack"
646 ? Effect.fail(failure)
647 : Effect.succeed({
648 id: input.projectId,
649 number: 42,
650 url: "https://github.com/owner/repository/stacks/42",
651 base: "main",
652 layers: [{ number: 42, headBranch: "feature", state: "merged" }],
653 }),
654 });
655 yield* Effect.gen(function* () {
656 const reactor = yield* startAndSweep(fixture);
657 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
658 yield* reactor.requestSync(link);
659 yield* Queue.take(fixture.snapshotReads);
660 yield* reactor.drain;
661 const commands = yield* Ref.get(fixture.syncCommands);
662 assert.sameDeepMembers(
663 commands.map((command) => [
664 command.threadId,
665 command.snapshot.title,
666 command.stack?.id,
667 ]),
668 [
669 ["healthy", otherProject, otherProject],
670 ["same-project", otherProject, otherProject],
671 ],
672 );
673 assert.sameMembers(
674 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.projectId),
675 [PROJECT_ID, otherProject],
676 );
677 assert.sameMembers(
678 (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
679 operation === "stack" ? [PROJECT_ID, otherProject] : [otherProject],
680 );
681 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
682 failing = false;
683 yield* sweepAgain(fixture, reactor);
684 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3);
685 assert.strictEqual(
686 (yield* Ref.get(fixture.summaryCalls)).at(-1)?.projectId,
687 PROJECT_ID,
688 );
689 const retried = (yield* Ref.get(fixture.syncCommands)).at(-1);
690 assert.strictEqual(retried?.threadId, ThreadId.make("failing"));
691 assert.strictEqual(retried?.snapshot.title, PROJECT_ID);
692 assert.strictEqual(retried?.stack?.id, PROJECT_ID);
693 }).pipe(Effect.provide(fixture.layer));
694 }),
695 ),
696 );
697
698 it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>
699 Effect.scoped(
700 Effect.gen(function* () {
701 const fixture = yield* makeHarness({
702 snapshot: makeSnapshot([
703 makeThread("one", {
704 pullRequests: [
705 makeLink(42, null, {
706 host: "forge.example",
707 url: "http://forge.example:3000/owner/repository/pulls/42",
708 }),
709 ],
710 }),
711 ]),
712 summary: (input) => Effect.succeed(makeSummary(input)),
713 });
714 yield* Effect.gen(function* () {
715 yield* startAndSweep(fixture);
716 assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");
717 assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");
718 }).pipe(Effect.provide(fixture.layer));
719 }),
720 ),
721 );
722
723 it.effect("dispatches nothing when the host snapshot is unchanged", () =>
724 Effect.scoped(
725 Effect.gen(function* () {
726 yield* TestClock.setTime(Date.parse(NOW));
727 const fixture = yield* makeHarness({
728 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
729 summary: (input) => Effect.succeed(makeSummary(input, { updatedAt: NOW })),
730 });
731
732 yield* Effect.gen(function* () {
733 const reactor = yield* startAndSweep(fixture);
734 const firstSweep = yield* Ref.get(fixture.syncCommands);
735 assert.strictEqual(firstSweep.length, 1);
736 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
737
738 yield* sweepAgain(fixture, reactor);
739
740 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
741 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
742 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
743 }).pipe(Effect.provide(fixture.layer));
744 }),
745 ),
746 );
747
748 it.effect("refreshes closed links through each project after reopening elsewhere", () =>
749 Effect.scoped(
750 Effect.gen(function* () {
751 yield* TestClock.setTime(Date.parse(NOW));
752 const invalidated = yield* Ref.make<ReadonlyArray<ProjectId>>([]);
753 const fixture = yield* makeHarness({
754 snapshot: makeSnapshot([
755 makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
756 makeThread("second", {
757 projectId: ProjectId.make("second-project"),
758 pullRequests: [makeLink(42, { state: "closed" })],
759 }),
760 ]),
761 invalidate: ({ reference }) =>
762 reference !== undefined
763 ? Ref.update(invalidated, (projects) => [...projects, reference.projectId])
764 : Effect.void,
765 summary: (input) =>
766 Ref.get(invalidated).pipe(
767 Effect.map((projects) =>
768 makeSummary(input, {
769 state: projects.includes(input.projectId) ? "open" : "closed",
770 }),
771 ),
772 ),
773 });
774 yield* Effect.gen(function* () {
775 const reactor = yield* startAndSweep(fixture);
776 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
777 yield* reactor.requestSync({
778 host: "github.com",
779 repository: "owner/repository",
780 number: 42,
781 });
782 yield* Queue.take(fixture.snapshotReads);
783 yield* reactor.drain;
784 assert.sameMembers(
785 [...(yield* Ref.get(invalidated))],
786 [PROJECT_ID, ProjectId.make("second-project")],
787 );
788 assert.sameMembers(
789 (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
790 [PROJECT_ID, ProjectId.make("second-project")],
791 );
792 const commands = yield* Ref.get(fixture.syncCommands);
793 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
794 const snapshot = yield* Ref.get(fixture.snapshots);
795 assert.deepStrictEqual(
796 snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
797 ["open", "open"],
798 );
799 }).pipe(Effect.provide(fixture.layer));
800 }),
801 ),
802 );
803
804 it.effect("stops asking the host once a pull request is merged", () =>
805 Effect.scoped(
806 Effect.gen(function* () {
807 yield* TestClock.setTime(Date.parse(NOW));
808 const fixture = yield* makeHarness({
809 snapshot: makeSnapshot([
810 makeThread("merged", {
811 pullRequests: [
812 makeLink(1, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
813 ],
814 }),
815 ]),
816 });
817
818 yield* Effect.gen(function* () {
819 const reactor = yield* startAndSweep(fixture);
820 yield* sweepAgain(fixture, reactor);
821
822 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
823 assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
824
825 yield* reactor.requestSync({
826 host: "github.com",
827 repository: "owner/repository",
828 number: 1,
829 });
830 yield* Queue.take(fixture.snapshotReads);
831 yield* reactor.drain;
832
833 assert.deepStrictEqual(
834 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
835 [1],
836 );
837 }).pipe(Effect.provide(fixture.layer));
838 }),
839 ),
840 );
841
842 it.effect("re-reads a merged pull request until the host supplies its merge time", () =>
843 Effect.scoped(
844 Effect.gen(function* () {
845 yield* TestClock.setTime(Date.parse(NOW));
846 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
847 const fixture = yield* makeHarness({
848 snapshot: makeSnapshot([
849 makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
850 ]),
851 invalidate: ({ reference }) =>
852 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
853 summary: (input) =>
854 Effect.succeed(
855 makeSummary(input, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
856 ),
857 });
858
859 yield* Effect.gen(function* () {
860 const reactor = yield* startAndSweep(fixture);
861 const firstSweep = yield* Ref.get(fixture.syncCommands);
862 // The held merged summary is dropped so the read reaches the host.
863 assert.deepStrictEqual(yield* Ref.get(invalidated), [1]);
864 assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z");
865 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
866
867 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
868 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
869 }).pipe(Effect.provide(fixture.layer));
870 }),
871 ),
872 );
873
874 it.effect("syncs a pull request a reader saw merge without waiting for the sweep", () =>
875 Effect.scoped(
876 Effect.gen(function* () {
877 yield* TestClock.setTime(Date.parse(NOW));
878 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
879 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
880 const fixture = yield* makeHarness({
881 snapshot: makeSnapshot([
882 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
883 ]),
884 summary: (input) =>
885 Ref.get(state).pipe(
886 Effect.map((current) =>
887 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
888 ),
889 ),
890 invalidate: ({ reference }) =>
891 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
892 });
893
894 yield* Effect.gen(function* () {
895 const reactor = yield* startAndSweep(fixture);
896 yield* Ref.set(state, "merged");
897
898 yield* Queue.offer(fixture.stateChanges, {
899 host: "github.com",
900 repository: "owner/repository",
901 number: 7,
902 });
903 yield* Queue.take(fixture.snapshotReads);
904 yield* reactor.drain;
905
906 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
907 assert.deepStrictEqual(
908 (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state),
909 ["merged"],
910 );
911 }).pipe(Effect.provide(fixture.layer));
912 }),
913 ),
914 );
915
916 it.effect("preserves a refresh requested while an older host read is in flight", () =>
917 Effect.scoped(
918 Effect.gen(function* () {
919 yield* TestClock.setTime(Date.parse(NOW));
920 const reading = yield* Deferred.make<void>();
921 const release = yield* Deferred.make<void>();
922 let calls = 0;
923 const fixture = yield* makeHarness({
924 snapshot: makeSnapshot([]),
925 summary: (input) =>
926 Effect.gen(function* () {
927 calls += 1;
928 if (calls === 1) {
929 yield* Deferred.succeed(reading, undefined);
930 yield* Deferred.await(release);
931 }
932 return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
933 }),
934 });
935 yield* Effect.gen(function* () {
936 const reactor = yield* startAndSweep(fixture);
937 yield* Ref.set(
938 fixture.snapshots,
939 makeSnapshot([
940 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
941 ]),
942 );
943 const key = { host: "github.com", repository: "owner/repository", number: 2 };
944 yield* reactor.requestSync(key);
945 yield* Deferred.await(reading);
946 yield* reactor.requestSync(key);
947 yield* Deferred.succeed(release, undefined);
948 yield* reactor.drain;
949 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
950 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
951 }).pipe(Effect.provide(fixture.layer));
952 }),
953 ),
954 );
955
956 it.effect("reads a burst of requested links in one sweep", () =>
957 Effect.scoped(
958 Effect.gen(function* () {
959 yield* TestClock.setTime(Date.parse(NOW));
960 const reading = yield* Deferred.make<void>();
961 const release = yield* Deferred.make<void>();
962 const fixture = yield* makeHarness({
963 snapshot: makeSnapshot([]),
964 summary: (input) =>
965 Effect.gen(function* () {
966 if (input.number === 1) {
967 yield* Deferred.succeed(reading, undefined);
968 yield* Deferred.await(release);
969 }
970 return makeSummary(input);
971 }),
972 });
973 yield* Effect.gen(function* () {
974 const reactor = yield* startAndSweep(fixture);
975 yield* Ref.set(
976 fixture.snapshots,
977 makeSnapshot(
978 [1, 2, 3, 4].map((number) =>
979 makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
980 ),
981 ),
982 );
983 const request = (number: number) =>
984 reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
985 yield* request(1);
986 yield* Deferred.await(reading);
987 yield* Effect.forEach([2, 3, 4], request, { discard: true });
988 yield* Deferred.succeed(release, undefined);
989 yield* reactor.drain;
990 assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
991 assert.deepStrictEqual(
992 (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
993 [1, 2, 3, 4],
994 );
995 }).pipe(Effect.provide(fixture.layer));
996 }),
997 ),
998 );
999
1000 it.effect("skips the stack read for a pull request the summary places in no stack", () =>
1001 Effect.scoped(
1002 Effect.gen(function* () {
1003 yield* TestClock.setTime(Date.parse(NOW));
1004 const fixture = yield* makeHarness({
1005 snapshot: makeSnapshot([
1006 makeThread("unstacked", { pullRequests: [makeLink(1)] }),
1007 makeThread("stacked", { pullRequests: [makeLink(2)] }),
1008 makeThread("unknown", { pullRequests: [makeLink(3)] }),
1009 ]),
1010 summary: (input) =>
1011 Effect.succeed(
1012 makeSummary(
1013 input,
1014 input.number === 1
1015 ? { stack: null }
1016 : input.number === 2
1017 ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
1018 : {},
1019 ),
1020 ),
1021 });
1022 yield* Effect.gen(function* () {
1023 yield* startAndSweep(fixture);
1024 assert.deepStrictEqual(
1025 (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
1026 [2, 3],
1027 );
1028 assert.deepStrictEqual(
1029 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
1030 [1, 2, 3],
1031 );
1032 }).pipe(Effect.provide(fixture.layer));
1033 }),
1034 ),
1035 );
1036
1037 it.effect("leaves a settled thread's links unread until the thread is unsettled", () =>
1038 Effect.scoped(
1039 Effect.gen(function* () {
1040 yield* TestClock.setTime(Date.parse(NOW));
1041 const fixture = yield* makeHarness({
1042 snapshot: makeSnapshot([
1043 makeThread("settled", {
1044 settledOverride: "settled",
1045 settledAt: "2026-08-21T00:00:00.000Z",
1046 pullRequests: [makeLink(5, { state: "open" }), makeLink(6, { state: "closed" })],
1047 }),
1048 ]),
1049 });
1050
1051 yield* Effect.gen(function* () {
1052 const reactor = yield* startAndSweep(fixture);
1053 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1054 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1055
1056 yield* Ref.update(fixture.snapshots, (snapshot) => ({
1057 ...snapshot,
1058 threads: snapshot.threads.map((thread) => ({
1059 ...thread,
1060 settledOverride: null,
1061 settledAt: null,
1062 })),
1063 }));
1064 yield* sweepAgain(fixture, reactor);
1065 assert.deepStrictEqual(
1066 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
1067 [5, 6],
1068 );
1069 }).pipe(Effect.provide(fixture.layer));
1070 }),
1071 ),
1072 );
1073
1074 it.effect("auto-links missing native stack layers on active threads only", () =>
1075 Effect.scoped(
1076 Effect.gen(function* () {
1077 yield* TestClock.setTime(Date.parse(NOW));
1078 const stack: PullRequestStack = {
1079 id: "stack-1",
1080 number: 42,
1081 url: "https://github.com/owner/repository/stack/1",
1082 base: "main",
1083 layers: [
1084 { number: 41, headBranch: "layer-1", state: "merged" },
1085 { number: 42, headBranch: "layer-2", state: "open" },
1086 { number: 43, headBranch: "layer-3", state: "open" },
1087 ],
1088 };
1089 const fixture = yield* makeHarness({
1090 snapshot: makeSnapshot([
1091 makeThread("one", {
1092 pullRequests: [
1093 makeLink(42),
1094 makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
1095 ],
1096 }),
1097 makeThread("settled", {
1098 settledOverride: "settled",
1099 settledAt: "2026-08-21T00:00:00.000Z",
1100 pullRequests: [makeLink(42)],
1101 }),
1102 ]),
1103 stack: () => Effect.succeed(stack),
1104 });
1105
1106 yield* Effect.gen(function* () {
1107 yield* startAndSweep(fixture);
1108
1109 const syncCommands = yield* Ref.get(fixture.syncCommands);
1110 assert.deepStrictEqual(
1111 syncCommands.map((command) => [command.threadId, command.stack] as const),
1112 [
1113 [ThreadId.make("one"), { kind: "native", ...stack }],
1114 [ThreadId.make("settled"), { kind: "native", ...stack }],
1115 ],
1116 );
1117 assert.deepStrictEqual(
1118 (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
1119 [
1120 {
1121 type: "thread.pull-request.link",
1122 threadId: ThreadId.make("one"),
1123 host: "github.com",
1124 repository: "owner/repository",
1125 number: 43,
1126 url: "https://github.com/owner/repository/pull/43",
1127 source: "stack",
1128 },
1129 ],
1130 );
1131 }).pipe(Effect.provide(fixture.layer));
1132 }),
1133 ),
1134 );
1135
1136 it.effect("re-reads every member's layers once a new layer joins the stack", () =>
1137 Effect.scoped(
1138 Effect.gen(function* () {
1139 yield* TestClock.setTime(Date.parse(NOW));
1140 const stack = makeGrowingStack();
1141 const fixture = yield* makeHarness({
1142 snapshot: makeSnapshot([
1143 makeThread("one", { pullRequests: [makeLink(18), makeLink(20)] }),
1144 ]),
1145 stack: stack.read,
1146 });
1147 const sweepAndApply = (reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"]) =>
1148 sweepAgain(fixture, reactor).pipe(Effect.andThen(applyRecordedSyncs(fixture)));
1149
1150 yield* Effect.gen(function* () {
1151 const reactor = yield* startAndSweep(fixture);
1152 yield* applyRecordedSyncs(fixture);
1153 assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1154 [18, [18, 20]],
1155 [20, [18, 20]],
1156 ]);
1157 const readsBeforeGrowth = (yield* Ref.get(fixture.stackCalls)).length;
1158
1159 // #83 is pushed on top and linked; only its own link starts without a snapshot.
1160 stack.grow();
1161 yield* linkPullRequest83(fixture);
1162 yield* sweepAndApply(reactor);
1163 yield* sweepAndApply(reactor);
1164
1165 assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1166 [18, [18, 20, 83]],
1167 [20, [18, 20, 83]],
1168 [83, [18, 20, 83]],
1169 ]);
1170 const readsAfterGrowth = (yield* Ref.get(fixture.stackCalls)).slice(readsBeforeGrowth);
1171 assert.deepStrictEqual(
1172 readsAfterGrowth.map((ref) => ref.number).toSorted(),
1173 [18, 20, 83],
1174 );
1175
1176 // Every member agrees now, so a further sweep reads no stack.
1177 yield* sweepAndApply(reactor);
1178 assert.strictEqual(
1179 (yield* Ref.get(fixture.stackCalls)).length,
1180 readsBeforeGrowth + readsAfterGrowth.length,
1181 );
1182 }).pipe(Effect.provide(fixture.layer));
1183 }),
1184 ),
1185 );
1186
1187 it.effect("reads past the cache when a sibling flags a member during its summary read", () =>
1188 Effect.scoped(
1189 Effect.gen(function* () {
1190 yield* TestClock.setTime(Date.parse(NOW));
1191 const stack = makeGrowingStack();
1192 const synced83 = yield* Deferred.make<void>();
1193 let holdSummary = false;
1194 const fixture = yield* makeHarness({
1195 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(18)] })]),
1196 invalidate: stack.invalidate,
1197 stack: stack.cachedRead,
1198 // #18's summary stays in flight until #83 has read its stack, flagged #18 and synced.
1199 summary: (input) =>
1200 (holdSummary && input.number === 18 ? Deferred.await(synced83) : Effect.void).pipe(
1201 Effect.as(makeSummary(input, { updatedAt: NOW })),
1202 ),
1203 onSync: (command) =>
1204 command.number === 83 ? Deferred.succeed(synced83, undefined) : Effect.void,
1205 });
1206
1207 yield* Effect.gen(function* () {
1208 const reactor = yield* startAndSweep(fixture);
1209 yield* applyRecordedSyncs(fixture);
1210
1211 // 30 s later a state change refreshes #18, which caches its two-layer read until 90 s.
1212 yield* TestClock.adjust("30 seconds");
1213 yield* requestAndApply(fixture, reactor, 18);
1214
1215 // #83 is pushed on top and linked as the scheduled sweep at 60 s starts, so that sweep
1216 // reads #83 for the first time while #18's summary is still in flight.
1217 stack.grow();
1218 yield* linkPullRequest83(fixture);
1219 holdSummary = true;
1220 const invalidatedBefore = stack.invalidated.length;
1221 yield* TestClock.adjust("30 seconds");
1222 yield* Queue.take(fixture.snapshotReads);
1223 yield* reactor.drain;
1224 yield* applyRecordedSyncs(fixture);
1225
1226 assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1227 [18, [18, 20, 83]],
1228 [83, [18, 20, 83]],
1229 ]);
1230 assert.deepStrictEqual(stack.invalidated.slice(invalidatedBefore), [18]);
1231 }).pipe(Effect.provide(fixture.layer));
1232 }),
1233 ),
1234 );
1235
1236 it.effect("leaves stacks in other repositories alone when their ids match", () =>
1237 Effect.scoped(
1238 Effect.gen(function* () {
1239 yield* TestClock.setTime(Date.parse(NOW));
1240 // Without a host id the GitHub decoder falls back to the stack number, so two
1241 // repositories can both report stack "3".
1242 const otherLink = makeLink(7, null, {
1243 repository: "owner/other",
1244 url: "https://github.com/owner/other/pull/7",
1245 });
1246 const fixture = yield* makeHarness({
1247 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(1), otherLink] })]),
1248 stack: (input) =>
1249 Effect.succeed({
1250 id: "3",
1251 number: 3,
1252 url: `https://github.com/${input.repository}/stack/3`,
1253 base: "main",
1254 layers: [
1255 { number: input.number, headBranch: "layer-1", state: "open" },
1256 { number: input.number + 1, headBranch: "layer-2", state: "open" },
1257 ],
1258 }),
1259 });
1260
1261 yield* Effect.gen(function* () {
1262 const reactor = yield* startAndSweep(fixture);
1263 yield* applyRecordedSyncs(fixture);
1264 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1265
1266 yield* sweepAgain(fixture, reactor);
1267 yield* sweepAgain(fixture, reactor);
1268 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1269 }).pipe(Effect.provide(fixture.layer));
1270 }),
1271 ),
1272 );
1273
1274 it.effect("keeps existing snapshots and continues when the host fails", () =>
1275 Effect.scoped(
1276 Effect.gen(function* () {
1277 yield* TestClock.setTime(Date.parse(NOW));
1278 const fixture = yield* makeHarness({
1279 snapshot: makeSnapshot([
1280 makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
1281 makeThread("fine", { pullRequests: [makeLink(8)] }),
1282 ]),
1283 summary: (input) =>
1284 input.number === 7
1285 ? Effect.fail(
1286 new PullRequestOperationError({ operation: "summary", detail: "host down" }),
1287 )
1288 : Effect.succeed(makeSummary(input)),
1289 });
1290
1291 yield* Effect.gen(function* () {
1292 yield* startAndSweep(fixture);
1293
1294 assert.deepStrictEqual(
1295 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1296 [8],
1297 );
1298 }).pipe(Effect.provide(fixture.layer));
1299 }),
1300 ),
1301 );
1302
1303 it.effect("reads open links fresh only when a run that ran a merge command ends", () =>
1304 Effect.scoped(
1305 Effect.gen(function* () {
1306 yield* TestClock.setTime(Date.parse(NOW));
1307 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1308 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1309 const fixture = yield* makeHarness({
1310 snapshot: makeSnapshot([
1311 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1312 makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }),
1313 ]),
1314 summary: (input) =>
1315 Ref.get(state).pipe(
1316 Effect.map((current) =>
1317 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1318 ),
1319 ),
1320 invalidate: ({ reference }) =>
1321 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1322 });
1323
1324 yield* Effect.gen(function* () {
1325 const reactor = yield* startAndSweep(fixture);
1326 yield* Ref.set(state, "merged");
1327 yield* Ref.set(fixture.summaryCalls, []);
1328
1329 yield* Queue.offerAll(fixture.domainEvents, [
1330 commandRan(ThreadId.make("other"), "gh pr view 9"),
1331 runUpdated(ThreadId.make("other"), "completed"),
1332 commandRan(ThreadId.make("agent"), "gh pr merge 7 --squash 2>&1 | tail -3"),
1333 runUpdated(ThreadId.make("agent"), "completed"),
1334 ]);
1335 yield* Queue.take(fixture.snapshotReads);
1336 yield* Queue.take(fixture.snapshotReads);
1337 yield* reactor.drain;
1338
1339 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1340 assert.deepStrictEqual(
1341 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
1342 [7],
1343 );
1344 assert.deepStrictEqual(
1345 (yield* Ref.get(fixture.syncCommands)).map((command) => [
1346 command.number,
1347 command.snapshot.state,
1348 ]),
1349 [[7, "merged"]],
1350 );
1351 }).pipe(Effect.provide(fixture.layer));
1352 }),
1353 ),
1354 );
1355});