Open History to see the last commit
1import {
2 ProjectId,
3 ProviderInstanceId,
4 SourceControlProviderKind,
5 ThreadId,
6 type OrchestrationProjectShell,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ThreadShell,
9 type OrchestrationV2ServerCommand,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "@effect/vitest";
12import * as SecureRandom from "effect/crypto/SecureRandom";
13import * as DateTime from "effect/DateTime";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as PlatformError from "effect/PlatformError";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24
25import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
26import * as GitManager from "../git/GitManager.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
29import * as PullRequestService from "../pullRequest/PullRequestService.ts";
30import * as ServerActivation from "../serverActivation.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32import * as SqlClient from "effect/sql/SqlClient";
33import * as SqlitePersistence from "../persistence/Sqlite.ts";
34import { EventId } from "@t3tools/contracts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ThreadPullRequestService from "./ThreadPullRequestService.ts";
37
38describe("ThreadPullRequestServiceV2 project guard", () => {
39 it("rejects a pull-request result when the project root changes before dispatch", () => {
40 const currentProject = Option.some({
41 workspaceRoot: "/workspace/replaced",
42 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
43
44 expect(
45 ThreadPullRequestService.projectWorkspaceMatchesSnapshot(
46 currentProject,
47 "/workspace/original",
48 ),
49 ).toBe(false);
50 });
51});
52
53describe("ThreadPullRequestServiceV2 reads", () => {
54 const NOW = DateTime.makeUnsafe("2026-09-20T00:00:00.000Z");
55 const threadShell = (id: string): OrchestrationV2ThreadShell => {
56 const threadId = ThreadId.make(id);
57 return {
58 id: threadId,
59 projectId: ProjectId.make("project-1"),
60 title: id,
61 providerInstanceId: ProviderInstanceId.make("codex"),
62 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
63 runtimeMode: "full-access",
64 interactionMode: "default",
65 branch: null,
66 worktreePath: null,
67 activeProviderThreadId: null,
68 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
69 forkedFrom: null,
70 createdBy: "user",
71 creationSource: "web",
72 activeRunId: null,
73 latestRunId: null,
74 status: "idle",
75 pendingRuntimeRequest: null,
76 latestVisibleMessage: null,
77 latestUserMessageAt: null,
78 hasActionableProposedPlan: false,
79 itemCount: 0,
80 visibleItemCount: 0,
81 createdAt: NOW,
82 updatedAt: NOW,
83 archivedAt: null,
84 settledOverride: null,
85 settledAt: null,
86 lastVisitedAt: null,
87 deletedAt: null,
88 };
89 };
90
91 it.effect("does not sweep branch pull requests while no client is connected", () =>
92 Effect.gen(function* () {
93 // Polling active branches without a connected client wastes GitHub requests.
94 const thread = { ...threadShell("idle-branch-thread"), branch: "feature/idle" };
95 const project: OrchestrationProjectShell = {
96 id: thread.projectId,
97 title: "Project",
98 workspaceRoot: "/workspace/project",
99 defaultModelSelection: null,
100 scripts: [],
101 createdAt: "2026-08-01T00:00:00.000Z",
102 updatedAt: "2026-08-01T00:00:00.000Z",
103 };
104 const activation = yield* Deferred.make<void>();
105 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
106 const turnLookup = yield* Deferred.make<void>();
107 const lookups: Array<{ readonly refresh: boolean }> = [];
108 const dependencies = Layer.mergeAll(
109 Layer.mock(Orchestrator.OrchestratorV2)({
110 streamDomainEvents: Stream.fromQueue(domainEvents),
111 getPullRequestSnapshot: () =>
112 Effect.succeed({
113 schemaVersion: 2,
114 snapshotSequence: 1,
115 threads: [thread],
116 archivedThreads: [],
117 }),
118 }),
119 Layer.mock(ProjectStore.ProjectStoreV2)({
120 listShells: () => Effect.succeed([project]),
121 getShell: () => Effect.succeedSome(project),
122 }),
123 Layer.mock(GitManager.GitManager)({
124 branchPullRequest: (_input, options) =>
125 Effect.gen(function* () {
126 const refresh = options?.refresh ?? false;
127 lookups.push({ refresh });
128 if (refresh) yield* Deferred.succeed(turnLookup, undefined);
129 return null;
130 }),
131 }),
132 Layer.mock(PullRequestService.PullRequestService)({
133 notifyLinkedThreadsChanged: Effect.void,
134 }),
135 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
136 resolve: () =>
137 Effect.succeed({
138 canonicalKey: "github.com/acme/project",
139 locator: {
140 source: "git-remote" as const,
141 remoteName: "origin",
142 remoteUrl: "git@github.com:acme/project.git",
143 },
144 provider: SourceControlProviderKind.make("github"),
145 owner: "acme",
146 name: "project",
147 }),
148 }),
149 // No client holds an activity lease.
150 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
151 shouldRunScopeWork: () => Effect.succeed(false),
152 shouldRunOpportunisticWork: Effect.succeed(false),
153 }),
154 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
155 Layer.succeed(
156 SecureRandom.SecureRandom,
157 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
158 ),
159 FileSystem.layerNoop({}),
160 Path.layer,
161 );
162 yield* Effect.gen(function* () {
163 const service = yield* ThreadPullRequestService.make;
164 yield* service.start();
165 yield* Deferred.succeed(activation, undefined);
166
167 // A finished turn still discovers the pull request for its branch.
168 yield* Queue.offer(domainEvents, {
169 type: "checkpoint.captured",
170 threadId: thread.id,
171 } as OrchestrationV2DomainEvent);
172 yield* Deferred.await(turnLookup);
173 yield* service.drain;
174 const lookupsBeforeIdle = lookups.length;
175
176 yield* TestClock.adjust("10 minutes");
177 yield* service.drain;
178
179 expect(lookups.slice(lookupsBeforeIdle)).toEqual([]);
180 }).pipe(Effect.provide(dependencies));
181 }),
182 );
183
184 it.effect("refreshes linked-thread readers at most every 10s while activity reorders them", () =>
185 Effect.gen(function* () {
186 const link = {
187 host: "github.com",
188 repository: "acme/web",
189 number: 7,
190 url: "https://github.com/acme/web/pull/7",
191 source: "agent",
192 };
193 const linked = (id: string) =>
194 ({
195 type: "thread.pull-request-synced",
196 threadId: ThreadId.make(id),
197 payload: { ...threadShell(id), pullRequests: [link] },
198 }) as unknown as OrchestrationV2DomainEvent;
199 const activity = (id: string, second: number) =>
200 ({
201 type: "message.updated",
202 threadId: ThreadId.make(id),
203 occurredAt: DateTime.makeUnsafe(`2026-09-20T00:00:${String(second).padStart(2, "0")}Z`),
204 }) as unknown as OrchestrationV2DomainEvent;
205 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
206 const notified = yield* Queue.unbounded<void>();
207 const dependencies = Layer.mergeAll(
208 Layer.mock(Orchestrator.OrchestratorV2)({
209 streamDomainEvents: Stream.fromQueue(domainEvents),
210 getPullRequestSnapshot: () =>
211 Effect.succeed({
212 schemaVersion: 2,
213 snapshotSequence: 1,
214 threads: [],
215 archivedThreads: [],
216 }),
217 }),
218 Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Effect.succeed([]) }),
219 Layer.mock(GitManager.GitManager)({}),
220 Layer.mock(PullRequestService.PullRequestService)({
221 notifyLinkedThreadsChanged: Queue.offer(notified, undefined).pipe(Effect.asVoid),
222 }),
223 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
224 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
225 shouldRunOpportunisticWork: Effect.succeed(false),
226 }),
227 Layer.succeed(ServerActivation.ServerActivation, undefined),
228 Layer.succeed(
229 SecureRandom.SecureRandom,
230 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
231 ),
232 FileSystem.layerNoop({}),
233 Path.layer,
234 );
235 yield* Effect.gen(function* () {
236 const service = yield* ThreadPullRequestService.make;
237 yield* service.start();
238
239 yield* Queue.offerAll(domainEvents, [linked("a"), linked("b"), activity("a", 1)]);
240 yield* Queue.takeN(notified, 3);
241 // Two turns on threads linked to one pull request swap its top thread on every event.
242 yield* Queue.offerAll(
243 domainEvents,
244 Array.from({ length: 20 }, (_, index) => activity(index % 2 ? "a" : "b", index + 2)),
245 );
246 // A link change still refreshes at once, and marks the burst as processed.
247 yield* Queue.offer(domainEvents, linked("c"));
248 yield* Queue.take(notified);
249 expect(yield* Queue.size(notified)).toBe(0);
250
251 yield* TestClock.adjust("10 seconds");
252 yield* Queue.take(notified);
253 yield* TestClock.adjust("10 seconds");
254 expect(yield* Queue.size(notified)).toBe(0);
255 }).pipe(Effect.provide(dependencies));
256 }),
257 );
258
259 it.effect("looks up a finished turn's branch once for all its turn-end events", () =>
260 Effect.gen(function* () {
261 const thread = { ...threadShell("turn-end-thread"), branch: "t3/turn-end" };
262 const otherThread = {
263 ...threadShell("other-turn-end-thread"),
264 branch: "t3/other-turn-end",
265 };
266 const project: OrchestrationProjectShell = {
267 id: thread.projectId,
268 title: "Project",
269 workspaceRoot: "/workspace/project",
270 defaultModelSelection: null,
271 scripts: [],
272 createdAt: "2026-08-01T00:00:00.000Z",
273 updatedAt: "2026-08-01T00:00:00.000Z",
274 };
275 // A turn end commits its checkpoints and the run's end together. The queued
276 // non-refresh request ahead of them must still become a refresh when they join it.
277 const turnEnd = [
278 { type: "thread.metadata-updated", threadId: thread.id, payload: thread },
279 { type: "checkpoint.captured", threadId: thread.id },
280 { type: "checkpoint.captured", threadId: thread.id },
281 { type: "run.updated", threadId: thread.id, payload: { status: "completed" } },
282 { type: "checkpoint.captured", threadId: otherThread.id },
283 { type: "run.updated", threadId: otherThread.id, payload: { status: "completed" } },
284 ] as Array<OrchestrationV2DomainEvent>;
285 // Arrives during the thread's own lookup, which may already have read the old host state.
286 const duringLookup = [
287 { type: "checkpoint.captured", threadId: thread.id },
288 { type: "thread.metadata-updated", threadId: thread.id, payload: thread },
289 ] as unknown as Array<OrchestrationV2DomainEvent>;
290 const activation = yield* Deferred.make<void>();
291 const sweepStarted = yield* Deferred.make<void>();
292 const turnEndQueued = yield* Deferred.make<void>();
293 const lookupStarted = yield* Deferred.make<void>();
294 const followUpQueued = yield* Deferred.make<void>();
295 const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
296 const dependencies = Layer.mergeAll(
297 Layer.mock(Orchestrator.OrchestratorV2)({
298 // The batch arrives while the worker is busy with the startup sweep.
299 streamDomainEvents: Stream.fromEffect(Deferred.await(sweepStarted)).pipe(
300 Stream.drain,
301 Stream.concat(Stream.fromIterable(turnEnd)),
302 Stream.concat(
303 Stream.fromEffect(Deferred.succeed(turnEndQueued, undefined)).pipe(Stream.drain),
304 ),
305 Stream.concat(Stream.fromEffect(Deferred.await(lookupStarted)).pipe(Stream.drain)),
306 Stream.concat(Stream.fromIterable(duringLookup)),
307 Stream.concat(
308 Stream.fromEffect(Deferred.succeed(followUpQueued, undefined)).pipe(Stream.drain),
309 ),
310 Stream.concat(Stream.never),
311 ),
312 getPullRequestSnapshot: ({ threadId }) =>
313 Effect.succeed({
314 schemaVersion: 2,
315 snapshotSequence: 1,
316 threads: [thread, otherThread].filter(
317 (candidate) => threadId === undefined || candidate.id === threadId,
318 ),
319 archivedThreads: [],
320 }),
321 }),
322 Layer.mock(ProjectStore.ProjectStoreV2)({
323 listShells: () => Effect.succeed([project]),
324 getShell: () => Effect.succeedSome(project),
325 }),
326 Layer.mock(GitManager.GitManager)({
327 branchPullRequest: (input, options) =>
328 Effect.gen(function* () {
329 lookups.push({ branch: input.branch, refresh: options?.refresh ?? false });
330 if (!(yield* Deferred.isDone(turnEndQueued))) {
331 yield* Deferred.succeed(sweepStarted, undefined);
332 yield* Deferred.await(turnEndQueued);
333 } else if (
334 input.branch === thread.branch &&
335 !(yield* Deferred.isDone(followUpQueued))
336 ) {
337 yield* Deferred.succeed(lookupStarted, undefined);
338 yield* Deferred.await(followUpQueued);
339 }
340 return null;
341 }),
342 }),
343 Layer.mock(PullRequestService.PullRequestService)({
344 notifyLinkedThreadsChanged: Effect.void,
345 }),
346 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
347 resolve: () =>
348 Effect.succeed({
349 canonicalKey: "github.com/acme/project",
350 locator: {
351 source: "git-remote" as const,
352 remoteName: "origin",
353 remoteUrl: "git@github.com:acme/project.git",
354 },
355 provider: SourceControlProviderKind.make("github"),
356 owner: "acme",
357 name: "project",
358 }),
359 }),
360 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
361 shouldRunScopeWork: () => Effect.succeed(false),
362 shouldRunOpportunisticWork: Effect.succeed(false),
363 }),
364 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
365 Layer.succeed(
366 SecureRandom.SecureRandom,
367 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
368 ),
369 FileSystem.layerNoop({}),
370 Path.layer,
371 );
372 yield* Effect.gen(function* () {
373 const service = yield* ThreadPullRequestService.make;
374 yield* service.start();
375 yield* Deferred.succeed(activation, undefined);
376 yield* Deferred.await(followUpQueued);
377 yield* service.drain;
378 }).pipe(Effect.provide(dependencies));
379
380 // The startup sweep, one refresh lookup per thread for its turn-end batch, then one
381 // follow-up refresh for the events that arrived during the thread's lookup.
382 expect(lookups).toEqual([
383 { branch: thread.branch, refresh: false },
384 { branch: otherThread.branch, refresh: false },
385 { branch: thread.branch, refresh: true },
386 { branch: otherThread.branch, refresh: true },
387 { branch: thread.branch, refresh: true },
388 ]);
389 }),
390 );
391
392 it.effect.each([
393 {
394 worktree: "a linked worktree",
395 existingPaths: ["/workspace/worktree", "/workspace/worktree/.git"],
396 unreadablePaths: [],
397 cwd: "/workspace/worktree",
398 },
399 // A folder that outlived its .git makes git fail with not_a_repository.
400 {
401 worktree: "a folder without .git",
402 existingPaths: ["/workspace/worktree"],
403 unreadablePaths: [],
404 cwd: "/workspace/project",
405 },
406 {
407 worktree: "a folder whose .git cannot be checked",
408 existingPaths: ["/workspace/worktree"],
409 unreadablePaths: ["/workspace/worktree/.git"],
410 cwd: "/workspace/worktree",
411 },
412 {
413 worktree: "a missing folder",
414 existingPaths: [],
415 unreadablePaths: [],
416 cwd: "/workspace/project",
417 },
418 ] as const)(
419 "looks up a branch whose worktree is $worktree in $cwd",
420 ({ existingPaths, unreadablePaths, cwd }) =>
421 Effect.gen(function* () {
422 const thread = {
423 ...threadShell("worktree-thread"),
424 settledOverride: "settled" as const,
425 settledAt: NOW,
426 branch: "feature/worktree",
427 worktreePath: "/workspace/worktree",
428 };
429 const project: OrchestrationProjectShell = {
430 id: thread.projectId,
431 title: "Project",
432 workspaceRoot: "/workspace/project",
433 defaultModelSelection: null,
434 scripts: [],
435 createdAt: "2026-08-01T00:00:00.000Z",
436 updatedAt: "2026-08-01T00:00:00.000Z",
437 };
438 const activation = yield* Deferred.make<void>();
439 const sweepStarted = yield* Deferred.make<void>();
440 const lookupCwds: Array<string> = [];
441 const dependencies = Layer.mergeAll(
442 Layer.mock(Orchestrator.OrchestratorV2)({
443 streamDomainEvents: Stream.never,
444 getPullRequestSnapshot: () =>
445 Deferred.succeed(sweepStarted, undefined).pipe(
446 Effect.as({
447 schemaVersion: 2,
448 snapshotSequence: 1,
449 threads: [thread],
450 archivedThreads: [],
451 }),
452 ),
453 }),
454 Layer.mock(ProjectStore.ProjectStoreV2)({
455 listShells: () => Effect.succeed([project]),
456 getShell: () => Effect.succeedSome(project),
457 }),
458 Layer.mock(GitManager.GitManager)({
459 branchPullRequest: (input) =>
460 Effect.sync(() => {
461 lookupCwds.push(input.cwd);
462 return null;
463 }),
464 }),
465 Layer.mock(PullRequestService.PullRequestService)({
466 notifyLinkedThreadsChanged: Effect.void,
467 }),
468 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
469 resolve: () =>
470 Effect.succeed({
471 canonicalKey: "github.com/acme/project",
472 locator: {
473 source: "git-remote" as const,
474 remoteName: "origin",
475 remoteUrl: "git@github.com:acme/project.git",
476 },
477 provider: SourceControlProviderKind.make("github"),
478 owner: "acme",
479 name: "project",
480 }),
481 }),
482 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
483 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
484 Layer.succeed(
485 SecureRandom.SecureRandom,
486 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
487 ),
488 FileSystem.layerNoop({
489 exists: (path) =>
490 unreadablePaths.some((entry) => entry === path)
491 ? Effect.fail(
492 PlatformError.systemError({
493 _tag: "PermissionDenied",
494 module: "FileSystem",
495 method: "exists",
496 pathOrDescriptor: path,
497 }),
498 )
499 : Effect.succeed(existingPaths.some((entry) => entry === path)),
500 }),
501 Path.layer,
502 );
503 yield* Effect.gen(function* () {
504 const service = yield* ThreadPullRequestService.make;
505 yield* service.start();
506 yield* Deferred.succeed(activation, undefined);
507 yield* Deferred.await(sweepStarted);
508 yield* service.drain;
509 }).pipe(Effect.provide(dependencies));
510
511 expect(lookupCwds).toEqual([cwd]);
512 }),
513 );
514
515 it.effect.each([
516 // The repositories are the project's own checkouts, each on whatever branch it is on.
517 { name: "in the project folder", checkouts: "/workspace/wrapper", branch: null },
518 // The repositories are the thread's worktrees; `web` stands for a checkout off its branch.
519 { name: "in a task folder", checkouts: "/worktrees/wrapper/task", branch: "feature/api" },
520 ])(
521 "links the open pull request of each tracked repository a thread $name changed",
522 ({ checkouts, branch }) =>
523 Effect.scoped(
524 Effect.gen(function* () {
525 let thread: OrchestrationV2ThreadShell = {
526 ...threadShell("repositories-thread"),
527 branch,
528 worktreePath: branch === null ? null : checkouts,
529 };
530 const project: OrchestrationProjectShell = {
531 id: thread.projectId,
532 title: "Wrapper",
533 workspaceRoot: "/workspace/wrapper",
534 trackedFolders: ["api", "web", "docs"].map((name) => ({
535 name,
536 path: `/workspace/wrapper/${name}`,
537 })),
538 defaultModelSelection: null,
539 scripts: [],
540 createdAt: "2026-08-01T00:00:00.000Z",
541 updatedAt: "2026-08-01T00:00:00.000Z",
542 };
543 const activation = yield* Deferred.make<void>();
544 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
545 const lookedUp = yield* Queue.unbounded<void>();
546 const lookups: Array<{ readonly cwd: string; readonly branch: string }> = [];
547 const dispatched: Array<OrchestrationV2ServerCommand> = [];
548 const dependencies = Layer.mergeAll(
549 Layer.mock(Orchestrator.OrchestratorV2)({
550 streamDomainEvents: Stream.fromQueue(domainEvents),
551 getPullRequestSnapshot: () =>
552 Effect.sync(() => ({
553 schemaVersion: 2,
554 snapshotSequence: 1,
555 threads: [thread],
556 archivedThreads: [],
557 })),
558 // The thread changed api and web, and a folder the project no longer tracks.
559 getCheckpointContext: () =>
560 Effect.succeed({
561 runs: [],
562 checkpoints: [],
563 checkpointScopes: ["api", "web", "removed"].map((name) => ({
564 id: `scope-${name}`,
565 runId: null,
566 kind: "manual",
567 cwd: `${checkouts}/${name}`,
568 repositoryPath: `/workspace/wrapper/${name}`,
569 })),
570 } as never),
571 dispatch: (command) =>
572 Effect.sync(() => {
573 dispatched.push(command as OrchestrationV2ServerCommand);
574 return {} as never;
575 }),
576 }),
577 Layer.mock(ProjectStore.ProjectStoreV2)({
578 listShells: () => Effect.succeed([project]),
579 getShell: () => Effect.succeedSome(project),
580 }),
581 Layer.mock(GitManager.GitManager)({
582 localStatus: ({ cwd }) =>
583 Effect.succeed({
584 isRepo: true,
585 refName: cwd.endsWith("/api")
586 ? "feature/api"
587 : branch === null
588 ? "main"
589 : "other",
590 isDefaultRef: !cwd.endsWith("/api") && branch === null,
591 } as never),
592 branchPullRequest: (input) =>
593 Queue.offer(lookedUp, undefined).pipe(
594 Effect.map(() => {
595 lookups.push(input);
596 return {
597 number: 7,
598 title: "API change",
599 url: "https://github.com/Acme/API/pull/7",
600 baseRef: "main",
601 headRef: input.branch,
602 state: "open" as const,
603 repositoryKey: "github.com/acme/api",
604 updatedAt: null,
605 };
606 }),
607 ),
608 }),
609 Layer.mock(PullRequestService.PullRequestService)({}),
610 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
611 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
612 shouldRunScopeWork: () => Effect.succeed(false),
613 shouldRunOpportunisticWork: Effect.succeed(false),
614 }),
615 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
616 Layer.succeed(
617 SecureRandom.SecureRandom,
618 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
619 ),
620 FileSystem.layerNoop({}),
621 Path.layer,
622 );
623 yield* Effect.gen(function* () {
624 const service = yield* ThreadPullRequestService.make;
625 yield* service.start();
626 yield* Deferred.succeed(activation, undefined);
627 // The startup sweep asks no repository.
628 yield* service.drain;
629 expect(lookups).toEqual([]);
630
631 const turnEnd = {
632 type: "checkpoint.captured",
633 threadId: thread.id,
634 } as OrchestrationV2DomainEvent;
635 yield* Queue.offer(domainEvents, turnEnd);
636 yield* Queue.take(lookedUp);
637 yield* service.drain;
638
639 // Only the repository on a branch of its own is asked, and nothing touches the
640 // thread's own branch.
641 expect(lookups).toEqual([{ cwd: `${checkouts}/api`, branch: "feature/api" }]);
642 expect(dispatched).toMatchObject([
643 {
644 type: "thread.pull-request.link",
645 threadId: thread.id,
646 host: "github.com",
647 repository: "acme/api",
648 number: 7,
649 source: "created",
650 },
651 ]);
652
653 thread = {
654 ...thread,
655 pullRequests: [
656 {
657 host: "github.com",
658 repository: "acme/api",
659 number: 7,
660 url: "https://github.com/acme/api/pull/7",
661 source: "created",
662 linkedAt: "2026-09-20T00:00:00.000Z",
663 snapshot: null,
664 stack: null,
665 },
666 ],
667 };
668 yield* Queue.offer(domainEvents, turnEnd);
669 yield* Queue.take(lookedUp);
670 yield* service.drain;
671 expect(dispatched).toHaveLength(1);
672 }).pipe(Effect.provide(dependencies));
673 }),
674 ),
675 );
676
677 it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
678 Effect.gen(function* () {
679 const parent = {
680 ...threadShell("parent-thread"),
681 branch: "feature/parent",
682 worktreePath: "/workspace/parent",
683 };
684 const child: OrchestrationV2ThreadShell = {
685 ...threadShell("child-thread"),
686 branch: "t3/reply-ok",
687 worktreePath: "/workspace/child",
688 lineage: {
689 rootThreadId: parent.id,
690 parentThreadId: parent.id,
691 relationshipToParent: "subagent",
692 },
693 };
694 const project: OrchestrationProjectShell = {
695 id: parent.projectId,
696 title: "Project",
697 workspaceRoot: "/workspace/project",
698 defaultModelSelection: null,
699 scripts: [],
700 createdAt: "2026-08-01T00:00:00.000Z",
701 updatedAt: "2026-08-01T00:00:00.000Z",
702 };
703 const activation = yield* Deferred.make<void>();
704 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
705 const sweeps = yield* Queue.unbounded<void>();
706 const childLookup = yield* Deferred.make<void>();
707 const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
708 const dependencies = Layer.mergeAll(
709 Layer.mock(Orchestrator.OrchestratorV2)({
710 streamDomainEvents: Stream.fromQueue(domainEvents),
711 getPullRequestSnapshot: ({ threadId }) =>
712 threadId !== undefined
713 ? Effect.succeed({ snapshotSequence: 1, threads: [child] })
714 : Queue.offer(sweeps, undefined).pipe(
715 Effect.as({
716 schemaVersion: 2,
717 snapshotSequence: 1,
718 threads: [parent, child],
719 archivedThreads: [],
720 }),
721 ),
722 }),
723 Layer.mock(ProjectStore.ProjectStoreV2)({
724 listShells: () => Effect.succeed([project]),
725 getShell: () => Effect.succeedSome(project),
726 }),
727 Layer.mock(GitManager.GitManager)({
728 branchPullRequest: (input, options) =>
729 Effect.gen(function* () {
730 const refresh = options?.refresh ?? false;
731 lookups.push({ branch: input.branch, refresh });
732 if (input.branch === child.branch && refresh) {
733 yield* Deferred.succeed(childLookup, undefined);
734 }
735 return null;
736 }),
737 }),
738 Layer.mock(PullRequestService.PullRequestService)({
739 notifyLinkedThreadsChanged: Effect.void,
740 }),
741 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
742 resolve: () =>
743 Effect.succeed({
744 canonicalKey: "github.com/acme/project",
745 locator: {
746 source: "git-remote" as const,
747 remoteName: "origin",
748 remoteUrl: "git@github.com:acme/project.git",
749 },
750 provider: SourceControlProviderKind.make("github"),
751 owner: "acme",
752 name: "project",
753 }),
754 }),
755 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
756 shouldRunScopeWork: () => Effect.succeed(true),
757 shouldRunOpportunisticWork: Effect.succeed(true),
758 }),
759 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
760 Layer.succeed(
761 SecureRandom.SecureRandom,
762 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
763 ),
764 FileSystem.layerNoop({}),
765 Path.layer,
766 );
767 yield* Effect.gen(function* () {
768 const service = yield* ThreadPullRequestService.make;
769 yield* service.start();
770 yield* Deferred.succeed(activation, undefined);
771
772 // Startup backfill sweep, then periodic sweeps: a branch without a pull request
773 // is reread after half an hour, not on every sweep.
774 yield* Queue.take(sweeps);
775 yield* service.drain;
776 for (let minute = 1; minute <= 29; minute += 1) {
777 yield* TestClock.adjust("1 minute");
778 yield* Queue.take(sweeps);
779 yield* service.drain;
780 }
781 expect(lookups.map((lookup) => lookup.branch)).toEqual([parent.branch]);
782 yield* TestClock.adjust("1 minute");
783 yield* Queue.take(sweeps);
784 yield* service.drain;
785 const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
786
787 // The child's own turn still discovers its pull request.
788 yield* Queue.offer(domainEvents, {
789 type: "checkpoint.captured",
790 threadId: child.id,
791 } as OrchestrationV2DomainEvent);
792 yield* Deferred.await(childLookup);
793 yield* service.drain;
794
795 expect(sweepLookups).toEqual([parent.branch, parent.branch]);
796 expect(lookups.slice(sweepLookups.length)).toEqual([
797 { branch: child.branch, refresh: true },
798 ]);
799 }).pipe(Effect.provide(dependencies));
800 }),
801 );
802
803 it.effect("startup backfill looks up a branch once for threads whose worktrees are gone", () =>
804 Effect.gen(function* () {
805 // Removed worktree folders all fall back to the project root, so they share one lookup.
806 const shared = ["a", "b", "c", "d"].map((suffix) => ({
807 ...threadShell(`gone-worktree-${suffix}`),
808 branch: "feature/shared",
809 worktreePath: `/workspace/worktrees/gone-${suffix}`,
810 settledAt: NOW,
811 }));
812 // Every start repeats the backfill, so it reads only the most recently updated threads.
813 const older = Array.from({ length: 100 }, (_, index) => ({
814 ...threadShell(`old-${index}`),
815 branch: `t3/old-${index}`,
816 worktreePath: `/workspace/worktrees/old-${index}`,
817 settledAt: NOW,
818 updatedAt: DateTime.subtract(NOW, { minutes: index + 1 }),
819 }));
820 const threads = [...older.toReversed(), ...shared];
821 const project: OrchestrationProjectShell = {
822 id: threads[0]!.projectId,
823 title: "Project",
824 workspaceRoot: "/workspace/project",
825 defaultModelSelection: null,
826 scripts: [],
827 createdAt: "2026-08-01T00:00:00.000Z",
828 updatedAt: "2026-08-01T00:00:00.000Z",
829 };
830 const activation = yield* Deferred.make<void>();
831 const sweeps = yield* Queue.unbounded<void>();
832 const lookups: Array<{ readonly cwd: string; readonly branch: string }> = [];
833 const dependencies = Layer.mergeAll(
834 Layer.mock(Orchestrator.OrchestratorV2)({
835 streamDomainEvents: Stream.never,
836 getPullRequestSnapshot: () =>
837 Queue.offer(sweeps, undefined).pipe(
838 Effect.as({
839 schemaVersion: 2,
840 snapshotSequence: 1,
841 threads,
842 archivedThreads: [],
843 }),
844 ),
845 }),
846 Layer.mock(ProjectStore.ProjectStoreV2)({
847 listShells: () => Effect.succeed([project]),
848 getShell: () => Effect.succeedSome(project),
849 }),
850 Layer.mock(GitManager.GitManager)({
851 branchPullRequest: (input) =>
852 Effect.sync(() => {
853 lookups.push({ cwd: input.cwd, branch: input.branch });
854 return null;
855 }),
856 }),
857 Layer.mock(PullRequestService.PullRequestService)({
858 notifyLinkedThreadsChanged: Effect.void,
859 }),
860 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
861 resolve: () =>
862 Effect.succeed({
863 canonicalKey: "github.com/acme/project",
864 locator: {
865 source: "git-remote" as const,
866 remoteName: "origin",
867 remoteUrl: "git@github.com:acme/project.git",
868 },
869 provider: SourceControlProviderKind.make("github"),
870 owner: "acme",
871 name: "project",
872 }),
873 }),
874 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
875 shouldRunScopeWork: () => Effect.succeed(true),
876 shouldRunOpportunisticWork: Effect.succeed(true),
877 }),
878 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
879 Layer.succeed(
880 SecureRandom.SecureRandom,
881 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
882 ),
883 FileSystem.layerNoop({}),
884 Path.layer,
885 );
886 yield* Effect.gen(function* () {
887 const service = yield* ThreadPullRequestService.make;
888 yield* service.start();
889 yield* Deferred.succeed(activation, undefined);
890
891 yield* Queue.take(sweeps);
892 yield* service.drain;
893
894 expect(lookups.map((lookup) => lookup.branch).toSorted()).toEqual(
895 ["feature/shared", ...older.slice(0, 60).map((thread) => thread.branch)].toSorted(),
896 );
897 expect(lookups.every((lookup) => lookup.cwd === project.workspaceRoot)).toBe(true);
898 }).pipe(Effect.provide(dependencies));
899 }),
900 );
901
902 it.effect.each([
903 { state: "open", checkedOut: false },
904 { state: "merged", checkedOut: false },
905 { state: "closed", checkedOut: false },
906 { state: "merged", checkedOut: true },
907 ] as const)(
908 "associates a $state branch PR (checkedOut=$checkedOut) only with threads that predate its completion or saved it",
909 ({ state, checkedOut }) =>
910 Effect.gen(function* () {
911 const reference = {
912 projectId: ProjectId.make("project-1"),
913 repository: "acme/project",
914 number: 42,
915 url: "https://github.com/acme/project/pull/42",
916 };
917 const terminalAt = "2026-09-19T00:00:00.000Z";
918 const detected = {
919 number: 42,
920 url: reference.url,
921 title: "Previous staging work",
922 baseRef: "main",
923 headRef: "staging",
924 state,
925 updatedAt: terminalAt,
926 closedAt: state === "closed" ? terminalAt : null,
927 mergedAt: state === "merged" ? terminalAt : null,
928 repositoryKey: "github.com/acme/project",
929 };
930 const threads = [
931 { ...threadShell("older"), createdAt: DateTime.makeUnsafe("2026-09-18T00:00:00Z") },
932 { ...threadShell("same-time"), createdAt: DateTime.makeUnsafe(terminalAt) },
933 threadShell("new"),
934 { ...threadShell("saved"), branchPullRequest: reference },
935 { ...threadShell("explicit"), linkedPullRequest: reference },
936 ].map((thread) => ({ ...thread, branch: "staging" }));
937 const project: OrchestrationProjectShell = {
938 id: reference.projectId,
939 title: "Project",
940 workspaceRoot: "/workspace/project",
941 defaultModelSelection: null,
942 scripts: [],
943 createdAt: "2026-08-01T00:00:00.000Z",
944 updatedAt: "2026-08-01T00:00:00.000Z",
945 };
946 const activation = yield* Deferred.make<void>();
947 const sweepStarted = yield* Deferred.make<void>();
948 const commands: Array<OrchestrationV2ServerCommand> = [];
949 const dependencies = Layer.mergeAll(
950 Layer.mock(Orchestrator.OrchestratorV2)({
951 streamDomainEvents: Stream.never,
952 getPullRequestSnapshot: () =>
953 Deferred.succeed(sweepStarted, undefined).pipe(
954 Effect.as({ snapshotSequence: 1, threads }),
955 ),
956 dispatch: (command) =>
957 Effect.sync(() => {
958 commands.push(command);
959 return { sequence: 2, storedEvents: [] };
960 }),
961 }),
962 Layer.mock(ProjectStore.ProjectStoreV2)({
963 listShells: () => Effect.succeed([project]),
964 getShell: () => Effect.succeedSome(project),
965 }),
966 Layer.mock(GitManager.GitManager)({
967 branchPullRequest: () => Effect.succeed(detected),
968 checkedOutPullRequest: () => Effect.succeed(checkedOut),
969 }),
970 Layer.mock(PullRequestService.PullRequestService)({
971 summary: () =>
972 Effect.succeed({
973 ...detected,
974 ...reference,
975 provider: SourceControlProviderKind.make("github"),
976 baseBranch: detected.baseRef,
977 headBranch: detected.headRef,
978 }),
979 }),
980 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
981 resolve: () =>
982 Effect.succeed({
983 canonicalKey: "github.com/acme/project",
984 locator: {
985 source: "git-remote" as const,
986 remoteName: "origin",
987 remoteUrl: "git@github.com:acme/project.git",
988 },
989 provider: SourceControlProviderKind.make("github"),
990 owner: "acme",
991 name: "project",
992 }),
993 }),
994 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
995 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
996 Layer.succeed(
997 SecureRandom.SecureRandom,
998 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
999 ),
1000 FileSystem.layerNoop({}),
1001 Path.layer,
1002 );
1003 yield* Effect.gen(function* () {
1004 const service = yield* ThreadPullRequestService.make;
1005 yield* service.start();
1006 yield* Deferred.succeed(activation, undefined);
1007 yield* Deferred.await(sweepStarted);
1008 yield* service.drain;
1009 }).pipe(Effect.provide(dependencies));
1010
1011 expect(
1012 commands.map((command) => {
1013 if (command.type !== "thread.pull-request.sync") throw new Error(command.type);
1014 expect(command).not.toHaveProperty("linkedPullRequest");
1015 return [command.threadId, command.branchPullRequest];
1016 }),
1017 ).toEqual(
1018 (state === "open" || checkedOut
1019 ? ["older", "same-time", "new", "explicit"]
1020 : ["older", "same-time"]
1021 ).map((id) => [id, reference]),
1022 );
1023 }),
1024 );
1025
1026 it.effect.each([
1027 { state: "closed", sameBranch: false },
1028 { state: "merged", sameBranch: false },
1029 { state: "closed", sameBranch: true },
1030 { state: "merged", sameBranch: true },
1031 ] as const)(
1032 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
1033 ({ state, sameBranch }) =>
1034 Effect.gen(function* () {
1035 const savedReference = {
1036 projectId: ProjectId.make("project-1"),
1037 repository: "acme/project",
1038 number: 42,
1039 url: "https://github.com/acme/project/pull/42",
1040 };
1041 const thread = {
1042 ...threadShell("branch-pr-thread"),
1043 branch: "main",
1044 branchPullRequest: savedReference,
1045 linkedPullRequest: savedReference,
1046 };
1047 const project: OrchestrationProjectShell = {
1048 id: thread.projectId,
1049 title: "Project",
1050 workspaceRoot: "/workspace/project",
1051 defaultModelSelection: null,
1052 scripts: [],
1053 createdAt: "2026-08-01T00:00:00.000Z",
1054 updatedAt: "2026-08-01T00:00:00.000Z",
1055 };
1056 const activation = yield* Deferred.make<void>();
1057 const sweepStarted = yield* Deferred.make<void>();
1058 const commands: Array<OrchestrationV2ServerCommand> = [];
1059 let snapshotThread: unknown;
1060 const dependencies = Layer.mergeAll(
1061 Layer.mock(Orchestrator.OrchestratorV2)({
1062 streamDomainEvents: Stream.never,
1063 getPullRequestSnapshot: (options) =>
1064 Effect.gen(function* () {
1065 const store = yield* ProjectionStore.ProjectionStoreV2;
1066 yield* store.apply({
1067 id: EventId.make(`event:${thread.id}:created`),
1068 type: "thread.created",
1069 threadId: thread.id,
1070 occurredAt: NOW,
1071 payload: { ...thread, lastVisitedAt: thread.lastVisitedAt ?? null },
1072 });
1073 const sql = yield* SqlClient.SqlClient;
1074 yield* sql`INSERT INTO orchestration_events (
1075 sequence, event_id, aggregate_kind, stream_id, stream_version, event_type,
1076 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
1077 ) VALUES (7, 'pr-discovery', 'thread', ${thread.id}, 1, 'thread.created',
1078 '2026-09-20T00:00:00.000Z', 'system', '{}', '{}', 2)`;
1079 for (const table of [
1080 "orchestration_v2_projection_turn_items",
1081 "orchestration_v2_projection_messages",
1082 "orchestration_v2_projection_provider_threads",
1083 "orchestration_v2_projection_runs",
1084 ])
1085 yield* sql.unsafe(`DROP TABLE ${table}`);
1086 const snapshot = yield* store.getPullRequestSnapshot(options);
1087 snapshotThread = snapshot.threads[0];
1088 yield* Deferred.succeed(sweepStarted, undefined);
1089 return snapshot;
1090 }).pipe(
1091 Effect.provide(
1092 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
1093 ),
1094 Effect.orDie,
1095 ),
1096 dispatch: (command) =>
1097 Effect.sync(() => {
1098 commands.push(command);
1099 return { sequence: 2, storedEvents: [] };
1100 }),
1101 }),
1102 Layer.mock(ProjectStore.ProjectStoreV2)({
1103 listShells: () => Effect.succeed([project]),
1104 getShell: () => Effect.succeedSome(project),
1105 }),
1106 Layer.mock(GitManager.GitManager)({
1107 branchPullRequest: () => Effect.succeed(null),
1108 }),
1109 Layer.mock(PullRequestService.PullRequestService)({
1110 summary: () =>
1111 Effect.succeed({
1112 ...savedReference,
1113 provider: SourceControlProviderKind.make("github"),
1114 title: "Previous branch work",
1115 state,
1116 headBranch: sameBranch ? thread.branch : "feature/previous-work",
1117 baseBranch: "release",
1118 updatedAt: "2026-09-19T00:00:00.000Z",
1119 }),
1120 }),
1121 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1122 resolve: () =>
1123 Effect.succeed({
1124 canonicalKey: "github.com/acme/project",
1125 locator: {
1126 source: "git-remote" as const,
1127 remoteName: "origin",
1128 remoteUrl: "git@github.com:acme/project.git",
1129 },
1130 provider: SourceControlProviderKind.make("github"),
1131 owner: "acme",
1132 name: "project",
1133 }),
1134 }),
1135 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
1136 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1137 Layer.succeed(
1138 SecureRandom.SecureRandom,
1139 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1140 ),
1141 FileSystem.layerNoop({}),
1142 Path.layer,
1143 );
1144 yield* Effect.gen(function* () {
1145 const service = yield* ThreadPullRequestService.make;
1146 yield* service.start();
1147 yield* Deferred.succeed(activation, undefined);
1148 yield* Deferred.await(sweepStarted);
1149 yield* service.drain;
1150 }).pipe(Effect.provide(dependencies));
1151
1152 expect(snapshotThread).toHaveProperty("createdAt", NOW);
1153 if (sameBranch) {
1154 expect(commands).toEqual([]);
1155 } else {
1156 expect(commands).toHaveLength(1);
1157 expect(commands[0]).toMatchObject({
1158 type: "thread.pull-request.sync",
1159 threadId: thread.id,
1160 snapshotSequence: 7,
1161 expected: {
1162 workspaceRoot: project.workspaceRoot,
1163 branch: thread.branch,
1164 worktreePath: thread.worktreePath,
1165 linkedPullRequest: savedReference,
1166 branchPullRequest: savedReference,
1167 },
1168 branchPullRequest: null,
1169 });
1170 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
1171 }
1172 }),
1173 );
1174
1175 it.effect("a saved merged branch PR rereads no git state on each sweep", () =>
1176 Effect.gen(function* () {
1177 const savedReference = {
1178 projectId: ProjectId.make("project-1"),
1179 repository: "acme/project",
1180 number: 42,
1181 url: "https://github.com/acme/project/pull/42",
1182 };
1183 const thread = {
1184 ...threadShell("merged-branch-thread"),
1185 branch: "feature/merged",
1186 branchPullRequest: savedReference,
1187 };
1188 const project: OrchestrationProjectShell = {
1189 id: thread.projectId,
1190 title: "Project",
1191 workspaceRoot: "/workspace/project",
1192 defaultModelSelection: null,
1193 scripts: [],
1194 createdAt: "2026-08-01T00:00:00.000Z",
1195 updatedAt: "2026-08-01T00:00:00.000Z",
1196 };
1197 const activation = yield* Deferred.make<void>();
1198 const sweeps = yield* Queue.unbounded<void>();
1199 const commands: Array<OrchestrationV2ServerCommand> = [];
1200 const lookups: Array<Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1]> =
1201 [];
1202 const dependencies = Layer.mergeAll(
1203 Layer.mock(Orchestrator.OrchestratorV2)({
1204 streamDomainEvents: Stream.never,
1205 getPullRequestSnapshot: () =>
1206 Queue.offer(sweeps, undefined).pipe(
1207 Effect.as({
1208 schemaVersion: 2,
1209 snapshotSequence: 1,
1210 threads: [thread],
1211 archivedThreads: [],
1212 }),
1213 ),
1214 dispatch: (command) =>
1215 Effect.sync(() => {
1216 commands.push(command);
1217 return { sequence: 2, storedEvents: [] };
1218 }),
1219 }),
1220 Layer.mock(ProjectStore.ProjectStoreV2)({
1221 listShells: () => Effect.succeed([project]),
1222 getShell: () => Effect.succeedSome(project),
1223 }),
1224 Layer.mock(GitManager.GitManager)({
1225 branchPullRequest: (_input, options) =>
1226 Effect.sync(() => {
1227 lookups.push(options);
1228 return {
1229 number: 42,
1230 title: "Merged work",
1231 url: savedReference.url,
1232 baseRef: "main",
1233 headRef: thread.branch,
1234 state: "merged" as const,
1235 repositoryKey: "github.com/acme/project",
1236 updatedAt: "2026-09-19T00:00:00.000Z",
1237 closedAt: null,
1238 mergedAt: "2026-09-19T00:00:00.000Z",
1239 };
1240 }),
1241 }),
1242 Layer.mock(PullRequestService.PullRequestService)({
1243 notifyLinkedThreadsChanged: Effect.void,
1244 }),
1245 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1246 resolve: () =>
1247 Effect.succeed({
1248 canonicalKey: "github.com/acme/project",
1249 locator: {
1250 source: "git-remote" as const,
1251 remoteName: "origin",
1252 remoteUrl: "git@github.com:acme/project.git",
1253 },
1254 provider: SourceControlProviderKind.make("github"),
1255 owner: "acme",
1256 name: "project",
1257 }),
1258 }),
1259 // A connected client keeps the periodic sweep running.
1260 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1261 shouldRunOpportunisticWork: Effect.succeed(true),
1262 }),
1263 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1264 Layer.succeed(
1265 SecureRandom.SecureRandom,
1266 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1267 ),
1268 FileSystem.layerNoop({}),
1269 Path.layer,
1270 );
1271 yield* Effect.gen(function* () {
1272 const service = yield* ThreadPullRequestService.make;
1273 yield* service.start();
1274 yield* Deferred.succeed(activation, undefined);
1275 yield* Queue.take(sweeps);
1276 yield* service.drain;
1277 yield* TestClock.adjust("1 minute");
1278 yield* Queue.take(sweeps);
1279 yield* service.drain;
1280 }).pipe(Effect.provide(dependencies));
1281
1282 expect(commands).toEqual([]);
1283 expect(lookups).toHaveLength(2);
1284 // GitManager rereads git state on request, and by default whenever its
1285 // remembered answer is merged or closed.
1286 expect(
1287 lookups.filter(
1288 (options) =>
1289 options?.refresh === true ||
1290 options?.freshGitState === true ||
1291 options?.confirmTerminal !== false,
1292 ),
1293 ).toEqual([]);
1294 }),
1295 );
1296
1297 const mergedPullRequest43 = {
1298 number: 43,
1299 title: "Replacement work",
1300 url: "https://github.com/acme/project/pull/43",
1301 baseRef: "main",
1302 headRef: "feature/replaced",
1303 state: "merged" as const,
1304 repositoryKey: "github.com/acme/project",
1305 updatedAt: "2026-09-19T00:00:00.000Z",
1306 closedAt: null,
1307 mergedAt: "2026-09-19T00:00:00.000Z",
1308 };
1309
1310 it.effect.each([
1311 { name: "reopened", fresh: { ...mergedPullRequest43, state: "open" as const }, writes: false },
1312 { name: "the same merged PR", fresh: mergedPullRequest43, writes: true },
1313 ])("saves a remembered merged PR only when fresh git state finds $name", ({ fresh, writes }) =>
1314 Effect.gen(function* () {
1315 const savedReference = {
1316 projectId: ProjectId.make("project-1"),
1317 repository: "acme/project",
1318 number: 42,
1319 url: "https://github.com/acme/project/pull/42",
1320 };
1321 const thread = {
1322 ...threadShell("replaced-branch-thread"),
1323 createdAt: DateTime.makeUnsafe("2026-09-01T00:00:00.000Z"),
1324 branch: mergedPullRequest43.headRef,
1325 branchPullRequest: savedReference,
1326 };
1327 const project: OrchestrationProjectShell = {
1328 id: thread.projectId,
1329 title: "Project",
1330 workspaceRoot: "/workspace/project",
1331 defaultModelSelection: null,
1332 scripts: [],
1333 createdAt: "2026-08-01T00:00:00.000Z",
1334 updatedAt: "2026-08-01T00:00:00.000Z",
1335 };
1336 const activation = yield* Deferred.make<void>();
1337 const sweeps = yield* Queue.unbounded<void>();
1338 const commands: Array<OrchestrationV2ServerCommand> = [];
1339 const dependencies = Layer.mergeAll(
1340 Layer.mock(Orchestrator.OrchestratorV2)({
1341 streamDomainEvents: Stream.never,
1342 getPullRequestSnapshot: () =>
1343 Queue.offer(sweeps, undefined).pipe(
1344 Effect.as({
1345 schemaVersion: 2,
1346 snapshotSequence: 1,
1347 threads: [thread],
1348 archivedThreads: [],
1349 }),
1350 ),
1351 dispatch: (command) =>
1352 Effect.sync(() => {
1353 commands.push(command);
1354 return { sequence: 2, storedEvents: [] };
1355 }),
1356 }),
1357 Layer.mock(ProjectStore.ProjectStoreV2)({
1358 listShells: () => Effect.succeed([project]),
1359 getShell: () => Effect.succeedSome(project),
1360 }),
1361 // Only the fresh read disagrees with the remembered detection.
1362 Layer.mock(GitManager.GitManager)({
1363 branchPullRequest: (_input, options) =>
1364 Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
1365 }),
1366 Layer.mock(PullRequestService.PullRequestService)({
1367 notifyLinkedThreadsChanged: Effect.void,
1368 }),
1369 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1370 resolve: () =>
1371 Effect.succeed({
1372 canonicalKey: "github.com/acme/project",
1373 locator: {
1374 source: "git-remote" as const,
1375 remoteName: "origin",
1376 remoteUrl: "git@github.com:acme/project.git",
1377 },
1378 provider: SourceControlProviderKind.make("github"),
1379 owner: "acme",
1380 name: "project",
1381 }),
1382 }),
1383 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1384 shouldRunOpportunisticWork: Effect.succeed(true),
1385 }),
1386 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1387 Layer.succeed(
1388 SecureRandom.SecureRandom,
1389 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1390 ),
1391 FileSystem.layerNoop({}),
1392 Path.layer,
1393 );
1394 yield* Effect.gen(function* () {
1395 const service = yield* ThreadPullRequestService.make;
1396 yield* service.start();
1397 yield* Deferred.succeed(activation, undefined);
1398 yield* Queue.take(sweeps);
1399 yield* service.drain;
1400 }).pipe(Effect.provide(dependencies));
1401
1402 expect(
1403 commands.map((command) =>
1404 command.type === "thread.pull-request.sync" ? command.branchPullRequest : command.type,
1405 ),
1406 ).toEqual(
1407 writes
1408 ? [
1409 {
1410 projectId: project.id,
1411 repository: "acme/project",
1412 number: 43,
1413 url: mergedPullRequest43.url,
1414 },
1415 ]
1416 : [],
1417 );
1418 }),
1419 );
1420});