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 assert.deepStrictEqual(yield* Ref.get(invalidated), [1]);
863 assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z");
864 yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
865
866 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
867 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
868 }).pipe(Effect.provide(fixture.layer));
869 }),
870 ),
871 );
872
873 it.effect("syncs a pull request a reader saw merge without waiting for the sweep", () =>
874 Effect.scoped(
875 Effect.gen(function* () {
876 yield* TestClock.setTime(Date.parse(NOW));
877 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
878 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
879 const fixture = yield* makeHarness({
880 snapshot: makeSnapshot([
881 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
882 ]),
883 summary: (input) =>
884 Ref.get(state).pipe(
885 Effect.map((current) =>
886 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
887 ),
888 ),
889 invalidate: ({ reference }) =>
890 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
891 });
892
893 yield* Effect.gen(function* () {
894 const reactor = yield* startAndSweep(fixture);
895 yield* Ref.set(state, "merged");
896
897 yield* Queue.offer(fixture.stateChanges, {
898 host: "github.com",
899 repository: "owner/repository",
900 number: 7,
901 });
902 yield* Queue.take(fixture.snapshotReads);
903 yield* reactor.drain;
904
905 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
906 assert.deepStrictEqual(
907 (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state),
908 ["merged"],
909 );
910 }).pipe(Effect.provide(fixture.layer));
911 }),
912 ),
913 );
914
915 it.effect.each([true, false])(
916 "syncs linked draft status %s as soon as a reader reports a change",
917 (isDraft) =>
918 Effect.gen(function* () {
919 yield* TestClock.setTime(Date.parse(NOW));
920 const draft = yield* Ref.make(!isDraft);
921 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
922 const fixture = yield* makeHarness({
923 snapshot: makeSnapshot([
924 makeThread("agent", { pullRequests: [makeLink(7, { isDraft: !isDraft })] }),
925 ]),
926 summary: (input) =>
927 Ref.get(draft).pipe(Effect.map((isDraft) => makeSummary(input, { isDraft }))),
928 invalidate: ({ reference }) =>
929 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
930 });
931
932 yield* Effect.gen(function* () {
933 const reactor = yield* startAndSweep(fixture);
934 yield* Ref.set(draft, isDraft);
935 yield* Queue.offer(fixture.stateChanges, {
936 host: "github.com",
937 repository: "owner/repository",
938 number: 7,
939 });
940 yield* Queue.take(fixture.snapshotReads);
941 yield* reactor.drain;
942
943 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
944 assert.deepStrictEqual(
945 (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.isDraft),
946 [isDraft],
947 );
948 }).pipe(Effect.provide(fixture.layer));
949 }),
950 );
951
952 it.effect("preserves a refresh requested while an older host read is in flight", () =>
953 Effect.scoped(
954 Effect.gen(function* () {
955 yield* TestClock.setTime(Date.parse(NOW));
956 const reading = yield* Deferred.make<void>();
957 const release = yield* Deferred.make<void>();
958 let calls = 0;
959 const fixture = yield* makeHarness({
960 snapshot: makeSnapshot([]),
961 summary: (input) =>
962 Effect.gen(function* () {
963 calls += 1;
964 if (calls === 1) {
965 yield* Deferred.succeed(reading, undefined);
966 yield* Deferred.await(release);
967 }
968 return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
969 }),
970 });
971 yield* Effect.gen(function* () {
972 const reactor = yield* startAndSweep(fixture);
973 yield* Ref.set(
974 fixture.snapshots,
975 makeSnapshot([
976 makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
977 ]),
978 );
979 const key = { host: "github.com", repository: "owner/repository", number: 2 };
980 yield* reactor.requestSync(key);
981 yield* Deferred.await(reading);
982 yield* reactor.requestSync(key);
983 yield* Deferred.succeed(release, undefined);
984 yield* reactor.drain;
985 assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
986 assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
987 }).pipe(Effect.provide(fixture.layer));
988 }),
989 ),
990 );
991
992 it.effect("reads a burst of requested links in one sweep", () =>
993 Effect.scoped(
994 Effect.gen(function* () {
995 yield* TestClock.setTime(Date.parse(NOW));
996 const reading = yield* Deferred.make<void>();
997 const release = yield* Deferred.make<void>();
998 const fixture = yield* makeHarness({
999 snapshot: makeSnapshot([]),
1000 summary: (input) =>
1001 Effect.gen(function* () {
1002 if (input.number === 1) {
1003 yield* Deferred.succeed(reading, undefined);
1004 yield* Deferred.await(release);
1005 }
1006 return makeSummary(input);
1007 }),
1008 });
1009 yield* Effect.gen(function* () {
1010 const reactor = yield* startAndSweep(fixture);
1011 yield* Ref.set(
1012 fixture.snapshots,
1013 makeSnapshot(
1014 [1, 2, 3, 4].map((number) =>
1015 makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
1016 ),
1017 ),
1018 );
1019 const request = (number: number) =>
1020 reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
1021 yield* request(1);
1022 yield* Deferred.await(reading);
1023 yield* Effect.forEach([2, 3, 4], request, { discard: true });
1024 yield* Deferred.succeed(release, undefined);
1025 yield* reactor.drain;
1026 assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
1027 assert.deepStrictEqual(
1028 (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
1029 [1, 2, 3, 4],
1030 );
1031 }).pipe(Effect.provide(fixture.layer));
1032 }),
1033 ),
1034 );
1035
1036 it.effect("skips the stack read for a pull request the summary places in no stack", () =>
1037 Effect.scoped(
1038 Effect.gen(function* () {
1039 yield* TestClock.setTime(Date.parse(NOW));
1040 const fixture = yield* makeHarness({
1041 snapshot: makeSnapshot([
1042 makeThread("unstacked", { pullRequests: [makeLink(1)] }),
1043 makeThread("stacked", { pullRequests: [makeLink(2)] }),
1044 makeThread("unknown", { pullRequests: [makeLink(3)] }),
1045 ]),
1046 summary: (input) =>
1047 Effect.succeed(
1048 makeSummary(
1049 input,
1050 input.number === 1
1051 ? { stack: null }
1052 : input.number === 2
1053 ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
1054 : {},
1055 ),
1056 ),
1057 });
1058 yield* Effect.gen(function* () {
1059 yield* startAndSweep(fixture);
1060 assert.deepStrictEqual(
1061 (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
1062 [2, 3],
1063 );
1064 assert.deepStrictEqual(
1065 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
1066 [1, 2, 3],
1067 );
1068 }).pipe(Effect.provide(fixture.layer));
1069 }),
1070 ),
1071 );
1072
1073 it.effect("leaves a settled thread's links unread until the thread is unsettled", () =>
1074 Effect.scoped(
1075 Effect.gen(function* () {
1076 yield* TestClock.setTime(Date.parse(NOW));
1077 const fixture = yield* makeHarness({
1078 snapshot: makeSnapshot([
1079 makeThread("settled", {
1080 settledOverride: "settled",
1081 settledAt: "2026-08-21T00:00:00.000Z",
1082 pullRequests: [makeLink(5, { state: "open" }), makeLink(6, { state: "closed" })],
1083 }),
1084 ]),
1085 });
1086
1087 yield* Effect.gen(function* () {
1088 const reactor = yield* startAndSweep(fixture);
1089 for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1090 assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1091
1092 yield* Ref.update(fixture.snapshots, (snapshot) => ({
1093 ...snapshot,
1094 threads: snapshot.threads.map((thread) => ({
1095 ...thread,
1096 settledOverride: null,
1097 settledAt: null,
1098 })),
1099 }));
1100 yield* sweepAgain(fixture, reactor);
1101 assert.deepStrictEqual(
1102 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
1103 [5, 6],
1104 );
1105 }).pipe(Effect.provide(fixture.layer));
1106 }),
1107 ),
1108 );
1109
1110 it.effect("auto-links missing native stack layers on active threads only", () =>
1111 Effect.scoped(
1112 Effect.gen(function* () {
1113 yield* TestClock.setTime(Date.parse(NOW));
1114 const stack: PullRequestStack = {
1115 id: "stack-1",
1116 number: 42,
1117 url: "https://github.com/owner/repository/stack/1",
1118 base: "main",
1119 layers: [
1120 { number: 41, headBranch: "layer-1", state: "merged" },
1121 { number: 42, headBranch: "layer-2", state: "open" },
1122 { number: 43, headBranch: "layer-3", state: "open" },
1123 ],
1124 };
1125 const fixture = yield* makeHarness({
1126 snapshot: makeSnapshot([
1127 makeThread("one", {
1128 pullRequests: [
1129 makeLink(42),
1130 makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
1131 ],
1132 }),
1133 makeThread("settled", {
1134 settledOverride: "settled",
1135 settledAt: "2026-08-21T00:00:00.000Z",
1136 pullRequests: [makeLink(42)],
1137 }),
1138 ]),
1139 stack: () => Effect.succeed(stack),
1140 });
1141
1142 yield* Effect.gen(function* () {
1143 yield* startAndSweep(fixture);
1144
1145 const syncCommands = yield* Ref.get(fixture.syncCommands);
1146 assert.deepStrictEqual(
1147 syncCommands.map((command) => [command.threadId, command.stack] as const),
1148 [
1149 [ThreadId.make("one"), { kind: "native", ...stack }],
1150 [ThreadId.make("settled"), { kind: "native", ...stack }],
1151 ],
1152 );
1153 assert.deepStrictEqual(
1154 (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
1155 [
1156 {
1157 type: "thread.pull-request.link",
1158 threadId: ThreadId.make("one"),
1159 host: "github.com",
1160 repository: "owner/repository",
1161 number: 43,
1162 url: "https://github.com/owner/repository/pull/43",
1163 source: "stack",
1164 },
1165 ],
1166 );
1167 }).pipe(Effect.provide(fixture.layer));
1168 }),
1169 ),
1170 );
1171
1172 it.effect("re-reads every member's layers once a new layer joins the stack", () =>
1173 Effect.scoped(
1174 Effect.gen(function* () {
1175 yield* TestClock.setTime(Date.parse(NOW));
1176 const stack = makeGrowingStack();
1177 const fixture = yield* makeHarness({
1178 snapshot: makeSnapshot([
1179 makeThread("one", { pullRequests: [makeLink(18), makeLink(20)] }),
1180 ]),
1181 stack: stack.read,
1182 });
1183 const sweepAndApply = (reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"]) =>
1184 sweepAgain(fixture, reactor).pipe(Effect.andThen(applyRecordedSyncs(fixture)));
1185
1186 yield* Effect.gen(function* () {
1187 const reactor = yield* startAndSweep(fixture);
1188 yield* applyRecordedSyncs(fixture);
1189 assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1190 [18, [18, 20]],
1191 [20, [18, 20]],
1192 ]);
1193 const readsBeforeGrowth = (yield* Ref.get(fixture.stackCalls)).length;
1194
1195 // #83 is pushed on top and linked; only its own link starts without a snapshot.
1196 stack.grow();
1197 yield* linkPullRequest83(fixture);
1198 yield* sweepAndApply(reactor);
1199 yield* sweepAndApply(reactor);
1200
1201 assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1202 [18, [18, 20, 83]],
1203 [20, [18, 20, 83]],
1204 [83, [18, 20, 83]],
1205 ]);
1206 const readsAfterGrowth = (yield* Ref.get(fixture.stackCalls)).slice(readsBeforeGrowth);
1207 assert.deepStrictEqual(
1208 readsAfterGrowth.map((ref) => ref.number).toSorted(),
1209 [18, 20, 83],
1210 );
1211
1212 // Every member agrees now, so a further sweep reads no stack.
1213 yield* sweepAndApply(reactor);
1214 assert.strictEqual(
1215 (yield* Ref.get(fixture.stackCalls)).length,
1216 readsBeforeGrowth + readsAfterGrowth.length,
1217 );
1218 }).pipe(Effect.provide(fixture.layer));
1219 }),
1220 ),
1221 );
1222
1223 it.effect("reads past the cache when a sibling flags a member during its summary read", () =>
1224 Effect.scoped(
1225 Effect.gen(function* () {
1226 yield* TestClock.setTime(Date.parse(NOW));
1227 const stack = makeGrowingStack();
1228 const synced83 = yield* Deferred.make<void>();
1229 let holdSummary = false;
1230 const fixture = yield* makeHarness({
1231 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(18)] })]),
1232 invalidate: stack.invalidate,
1233 stack: stack.cachedRead,
1234 // #18's summary stays in flight until #83 has read its stack, flagged #18 and synced.
1235 summary: (input) =>
1236 (holdSummary && input.number === 18 ? Deferred.await(synced83) : Effect.void).pipe(
1237 Effect.as(makeSummary(input, { updatedAt: NOW })),
1238 ),
1239 onSync: (command) =>
1240 command.number === 83 ? Deferred.succeed(synced83, undefined) : Effect.void,
1241 });
1242
1243 yield* Effect.gen(function* () {
1244 const reactor = yield* startAndSweep(fixture);
1245 yield* applyRecordedSyncs(fixture);
1246
1247 // 30 s later a state change refreshes #18, which caches its two-layer read until 90 s.
1248 yield* TestClock.adjust("30 seconds");
1249 yield* requestAndApply(fixture, reactor, 18);
1250
1251 // #83 is pushed on top and linked as the scheduled sweep at 60 s starts, so that sweep
1252 // reads #83 for the first time while #18's summary is still in flight.
1253 stack.grow();
1254 yield* linkPullRequest83(fixture);
1255 holdSummary = true;
1256 const invalidatedBefore = stack.invalidated.length;
1257 yield* TestClock.adjust("30 seconds");
1258 yield* Queue.take(fixture.snapshotReads);
1259 yield* reactor.drain;
1260 yield* applyRecordedSyncs(fixture);
1261
1262 assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1263 [18, [18, 20, 83]],
1264 [83, [18, 20, 83]],
1265 ]);
1266 assert.deepStrictEqual(stack.invalidated.slice(invalidatedBefore), [18]);
1267 }).pipe(Effect.provide(fixture.layer));
1268 }),
1269 ),
1270 );
1271
1272 it.effect("leaves stacks in other repositories alone when their ids match", () =>
1273 Effect.scoped(
1274 Effect.gen(function* () {
1275 yield* TestClock.setTime(Date.parse(NOW));
1276 // Without a host id the GitHub decoder falls back to the stack number, so two
1277 // repositories can both report stack "3".
1278 const otherLink = makeLink(7, null, {
1279 repository: "owner/other",
1280 url: "https://github.com/owner/other/pull/7",
1281 });
1282 const fixture = yield* makeHarness({
1283 snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(1), otherLink] })]),
1284 stack: (input) =>
1285 Effect.succeed({
1286 id: "3",
1287 number: 3,
1288 url: `https://github.com/${input.repository}/stack/3`,
1289 base: "main",
1290 layers: [
1291 { number: input.number, headBranch: "layer-1", state: "open" },
1292 { number: input.number + 1, headBranch: "layer-2", state: "open" },
1293 ],
1294 }),
1295 });
1296
1297 yield* Effect.gen(function* () {
1298 const reactor = yield* startAndSweep(fixture);
1299 yield* applyRecordedSyncs(fixture);
1300 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1301
1302 yield* sweepAgain(fixture, reactor);
1303 yield* sweepAgain(fixture, reactor);
1304 assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1305 }).pipe(Effect.provide(fixture.layer));
1306 }),
1307 ),
1308 );
1309
1310 it.effect("keeps existing snapshots and continues when the host fails", () =>
1311 Effect.scoped(
1312 Effect.gen(function* () {
1313 yield* TestClock.setTime(Date.parse(NOW));
1314 const fixture = yield* makeHarness({
1315 snapshot: makeSnapshot([
1316 makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
1317 makeThread("fine", { pullRequests: [makeLink(8)] }),
1318 ]),
1319 summary: (input) =>
1320 input.number === 7
1321 ? Effect.fail(
1322 new PullRequestOperationError({ operation: "summary", detail: "host down" }),
1323 )
1324 : Effect.succeed(makeSummary(input)),
1325 });
1326
1327 yield* Effect.gen(function* () {
1328 yield* startAndSweep(fixture);
1329
1330 assert.deepStrictEqual(
1331 (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1332 [8],
1333 );
1334 }).pipe(Effect.provide(fixture.layer));
1335 }),
1336 ),
1337 );
1338
1339 it.effect.each([
1340 "gh pr merge 7 --squash 2>&1 | tail -3",
1341 "cafe pr merge 7 --squash",
1342 "az repos pr update --id 7 --status completed",
1343 ])("reads open links fresh only when a run that ran `%s` ends", (mergeCommand) =>
1344 Effect.scoped(
1345 Effect.gen(function* () {
1346 yield* TestClock.setTime(Date.parse(NOW));
1347 const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1348 const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1349 const fixture = yield* makeHarness({
1350 snapshot: makeSnapshot([
1351 makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1352 makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }),
1353 ]),
1354 summary: (input) =>
1355 Ref.get(state).pipe(
1356 Effect.map((current) =>
1357 makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1358 ),
1359 ),
1360 invalidate: ({ reference }) =>
1361 Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1362 });
1363
1364 yield* Effect.gen(function* () {
1365 const reactor = yield* startAndSweep(fixture);
1366 yield* Ref.set(state, "merged");
1367 yield* Ref.set(fixture.summaryCalls, []);
1368
1369 yield* Queue.offerAll(fixture.domainEvents, [
1370 commandRan(ThreadId.make("other"), "gh pr view 9"),
1371 runUpdated(ThreadId.make("other"), "completed"),
1372 commandRan(ThreadId.make("agent"), mergeCommand),
1373 runUpdated(ThreadId.make("agent"), "completed"),
1374 ]);
1375 yield* Queue.take(fixture.snapshotReads);
1376 yield* Queue.take(fixture.snapshotReads);
1377 yield* reactor.drain;
1378
1379 assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1380 assert.deepStrictEqual(
1381 (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
1382 [7],
1383 );
1384 assert.deepStrictEqual(
1385 (yield* Ref.get(fixture.syncCommands)).map((command) => [
1386 command.number,
1387 command.snapshot.state,
1388 ]),
1389 [[7, "merged"]],
1390 );
1391 }).pipe(Effect.provide(fixture.layer));
1392 }),
1393 ),
1394 );
1395});