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

PullRequestSyncReactor.test.ts

1,392 lines50.2 KB

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