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.each([
804 { state: "open", checkedOut: false },
805 { state: "merged", checkedOut: false },
806 { state: "closed", checkedOut: false },
807 { state: "merged", checkedOut: true },
808 ] as const)(
809 "associates a $state branch PR (checkedOut=$checkedOut) only with threads that predate its completion or saved it",
810 ({ state, checkedOut }) =>
811 Effect.gen(function* () {
812 const reference = {
813 projectId: ProjectId.make("project-1"),
814 repository: "acme/project",
815 number: 42,
816 url: "https://github.com/acme/project/pull/42",
817 };
818 const terminalAt = "2026-09-19T00:00:00.000Z";
819 const detected = {
820 number: 42,
821 url: reference.url,
822 title: "Previous staging work",
823 baseRef: "main",
824 headRef: "staging",
825 state,
826 updatedAt: terminalAt,
827 closedAt: state === "closed" ? terminalAt : null,
828 mergedAt: state === "merged" ? terminalAt : null,
829 repositoryKey: "github.com/acme/project",
830 };
831 const threads = [
832 { ...threadShell("older"), createdAt: DateTime.makeUnsafe("2026-09-18T00:00:00Z") },
833 { ...threadShell("same-time"), createdAt: DateTime.makeUnsafe(terminalAt) },
834 threadShell("new"),
835 { ...threadShell("saved"), branchPullRequest: reference },
836 { ...threadShell("explicit"), linkedPullRequest: reference },
837 ].map((thread) => ({ ...thread, branch: "staging" }));
838 const project: OrchestrationProjectShell = {
839 id: reference.projectId,
840 title: "Project",
841 workspaceRoot: "/workspace/project",
842 defaultModelSelection: null,
843 scripts: [],
844 createdAt: "2026-08-01T00:00:00.000Z",
845 updatedAt: "2026-08-01T00:00:00.000Z",
846 };
847 const activation = yield* Deferred.make<void>();
848 const sweepStarted = yield* Deferred.make<void>();
849 const commands: Array<OrchestrationV2ServerCommand> = [];
850 const dependencies = Layer.mergeAll(
851 Layer.mock(Orchestrator.OrchestratorV2)({
852 streamDomainEvents: Stream.never,
853 getPullRequestSnapshot: () =>
854 Deferred.succeed(sweepStarted, undefined).pipe(
855 Effect.as({ snapshotSequence: 1, threads }),
856 ),
857 dispatch: (command) =>
858 Effect.sync(() => {
859 commands.push(command);
860 return { sequence: 2, storedEvents: [] };
861 }),
862 }),
863 Layer.mock(ProjectStore.ProjectStoreV2)({
864 listShells: () => Effect.succeed([project]),
865 getShell: () => Effect.succeedSome(project),
866 }),
867 Layer.mock(GitManager.GitManager)({
868 branchPullRequest: () => Effect.succeed(detected),
869 checkedOutPullRequest: () => Effect.succeed(checkedOut),
870 }),
871 Layer.mock(PullRequestService.PullRequestService)({
872 summary: () =>
873 Effect.succeed({
874 ...detected,
875 ...reference,
876 provider: SourceControlProviderKind.make("github"),
877 baseBranch: detected.baseRef,
878 headBranch: detected.headRef,
879 }),
880 }),
881 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
882 resolve: () =>
883 Effect.succeed({
884 canonicalKey: "github.com/acme/project",
885 locator: {
886 source: "git-remote" as const,
887 remoteName: "origin",
888 remoteUrl: "git@github.com:acme/project.git",
889 },
890 provider: SourceControlProviderKind.make("github"),
891 owner: "acme",
892 name: "project",
893 }),
894 }),
895 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
896 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
897 Layer.succeed(
898 SecureRandom.SecureRandom,
899 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
900 ),
901 FileSystem.layerNoop({}),
902 Path.layer,
903 );
904 yield* Effect.gen(function* () {
905 const service = yield* ThreadPullRequestService.make;
906 yield* service.start();
907 yield* Deferred.succeed(activation, undefined);
908 yield* Deferred.await(sweepStarted);
909 yield* service.drain;
910 }).pipe(Effect.provide(dependencies));
911
912 expect(
913 commands.map((command) => {
914 if (command.type !== "thread.pull-request.sync") throw new Error(command.type);
915 expect(command).not.toHaveProperty("linkedPullRequest");
916 return [command.threadId, command.branchPullRequest];
917 }),
918 ).toEqual(
919 (state === "open" || checkedOut
920 ? ["older", "same-time", "new", "explicit"]
921 : ["older", "same-time"]
922 ).map((id) => [id, reference]),
923 );
924 }),
925 );
926
927 it.effect.each([
928 { state: "closed", sameBranch: false },
929 { state: "merged", sameBranch: false },
930 { state: "closed", sameBranch: true },
931 { state: "merged", sameBranch: true },
932 ] as const)(
933 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
934 ({ state, sameBranch }) =>
935 Effect.gen(function* () {
936 const savedReference = {
937 projectId: ProjectId.make("project-1"),
938 repository: "acme/project",
939 number: 42,
940 url: "https://github.com/acme/project/pull/42",
941 };
942 const thread = {
943 ...threadShell("branch-pr-thread"),
944 branch: "main",
945 branchPullRequest: savedReference,
946 linkedPullRequest: savedReference,
947 };
948 const project: OrchestrationProjectShell = {
949 id: thread.projectId,
950 title: "Project",
951 workspaceRoot: "/workspace/project",
952 defaultModelSelection: null,
953 scripts: [],
954 createdAt: "2026-08-01T00:00:00.000Z",
955 updatedAt: "2026-08-01T00:00:00.000Z",
956 };
957 const activation = yield* Deferred.make<void>();
958 const sweepStarted = yield* Deferred.make<void>();
959 const commands: Array<OrchestrationV2ServerCommand> = [];
960 let snapshotThread: unknown;
961 const dependencies = Layer.mergeAll(
962 Layer.mock(Orchestrator.OrchestratorV2)({
963 streamDomainEvents: Stream.never,
964 getPullRequestSnapshot: (options) =>
965 Effect.gen(function* () {
966 const store = yield* ProjectionStore.ProjectionStoreV2;
967 yield* store.apply({
968 id: EventId.make(`event:${thread.id}:created`),
969 type: "thread.created",
970 threadId: thread.id,
971 occurredAt: NOW,
972 payload: { ...thread, lastVisitedAt: thread.lastVisitedAt ?? null },
973 });
974 const sql = yield* SqlClient.SqlClient;
975 yield* sql`INSERT INTO orchestration_events (
976 sequence, event_id, aggregate_kind, stream_id, stream_version, event_type,
977 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
978 ) VALUES (7, 'pr-discovery', 'thread', ${thread.id}, 1, 'thread.created',
979 '2026-09-20T00:00:00.000Z', 'system', '{}', '{}', 2)`;
980 for (const table of [
981 "orchestration_v2_projection_turn_items",
982 "orchestration_v2_projection_messages",
983 "orchestration_v2_projection_provider_threads",
984 "orchestration_v2_projection_runs",
985 ])
986 yield* sql.unsafe(`DROP TABLE ${table}`);
987 const snapshot = yield* store.getPullRequestSnapshot(options);
988 snapshotThread = snapshot.threads[0];
989 yield* Deferred.succeed(sweepStarted, undefined);
990 return snapshot;
991 }).pipe(
992 Effect.provide(
993 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
994 ),
995 Effect.orDie,
996 ),
997 dispatch: (command) =>
998 Effect.sync(() => {
999 commands.push(command);
1000 return { sequence: 2, storedEvents: [] };
1001 }),
1002 }),
1003 Layer.mock(ProjectStore.ProjectStoreV2)({
1004 listShells: () => Effect.succeed([project]),
1005 getShell: () => Effect.succeedSome(project),
1006 }),
1007 Layer.mock(GitManager.GitManager)({
1008 branchPullRequest: () => Effect.succeed(null),
1009 }),
1010 Layer.mock(PullRequestService.PullRequestService)({
1011 summary: () =>
1012 Effect.succeed({
1013 ...savedReference,
1014 provider: SourceControlProviderKind.make("github"),
1015 title: "Previous branch work",
1016 state,
1017 headBranch: sameBranch ? thread.branch : "feature/previous-work",
1018 baseBranch: "release",
1019 updatedAt: "2026-09-19T00:00:00.000Z",
1020 }),
1021 }),
1022 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1023 resolve: () =>
1024 Effect.succeed({
1025 canonicalKey: "github.com/acme/project",
1026 locator: {
1027 source: "git-remote" as const,
1028 remoteName: "origin",
1029 remoteUrl: "git@github.com:acme/project.git",
1030 },
1031 provider: SourceControlProviderKind.make("github"),
1032 owner: "acme",
1033 name: "project",
1034 }),
1035 }),
1036 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
1037 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1038 Layer.succeed(
1039 SecureRandom.SecureRandom,
1040 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1041 ),
1042 FileSystem.layerNoop({}),
1043 Path.layer,
1044 );
1045 yield* Effect.gen(function* () {
1046 const service = yield* ThreadPullRequestService.make;
1047 yield* service.start();
1048 yield* Deferred.succeed(activation, undefined);
1049 yield* Deferred.await(sweepStarted);
1050 yield* service.drain;
1051 }).pipe(Effect.provide(dependencies));
1052
1053 expect(snapshotThread).toHaveProperty("createdAt", NOW);
1054 if (sameBranch) {
1055 expect(commands).toEqual([]);
1056 } else {
1057 expect(commands).toHaveLength(1);
1058 expect(commands[0]).toMatchObject({
1059 type: "thread.pull-request.sync",
1060 threadId: thread.id,
1061 snapshotSequence: 7,
1062 expected: {
1063 workspaceRoot: project.workspaceRoot,
1064 branch: thread.branch,
1065 worktreePath: thread.worktreePath,
1066 linkedPullRequest: savedReference,
1067 branchPullRequest: savedReference,
1068 },
1069 branchPullRequest: null,
1070 });
1071 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
1072 }
1073 }),
1074 );
1075
1076 it.effect("a saved merged branch PR rereads no git state on each sweep", () =>
1077 Effect.gen(function* () {
1078 const savedReference = {
1079 projectId: ProjectId.make("project-1"),
1080 repository: "acme/project",
1081 number: 42,
1082 url: "https://github.com/acme/project/pull/42",
1083 };
1084 const thread = {
1085 ...threadShell("merged-branch-thread"),
1086 branch: "feature/merged",
1087 branchPullRequest: savedReference,
1088 };
1089 const project: OrchestrationProjectShell = {
1090 id: thread.projectId,
1091 title: "Project",
1092 workspaceRoot: "/workspace/project",
1093 defaultModelSelection: null,
1094 scripts: [],
1095 createdAt: "2026-08-01T00:00:00.000Z",
1096 updatedAt: "2026-08-01T00:00:00.000Z",
1097 };
1098 const activation = yield* Deferred.make<void>();
1099 const sweeps = yield* Queue.unbounded<void>();
1100 const commands: Array<OrchestrationV2ServerCommand> = [];
1101 const lookups: Array<Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1]> =
1102 [];
1103 const dependencies = Layer.mergeAll(
1104 Layer.mock(Orchestrator.OrchestratorV2)({
1105 streamDomainEvents: Stream.never,
1106 getPullRequestSnapshot: () =>
1107 Queue.offer(sweeps, undefined).pipe(
1108 Effect.as({
1109 schemaVersion: 2,
1110 snapshotSequence: 1,
1111 threads: [thread],
1112 archivedThreads: [],
1113 }),
1114 ),
1115 dispatch: (command) =>
1116 Effect.sync(() => {
1117 commands.push(command);
1118 return { sequence: 2, storedEvents: [] };
1119 }),
1120 }),
1121 Layer.mock(ProjectStore.ProjectStoreV2)({
1122 listShells: () => Effect.succeed([project]),
1123 getShell: () => Effect.succeedSome(project),
1124 }),
1125 Layer.mock(GitManager.GitManager)({
1126 branchPullRequest: (_input, options) =>
1127 Effect.sync(() => {
1128 lookups.push(options);
1129 return {
1130 number: 42,
1131 title: "Merged work",
1132 url: savedReference.url,
1133 baseRef: "main",
1134 headRef: thread.branch,
1135 state: "merged" as const,
1136 repositoryKey: "github.com/acme/project",
1137 updatedAt: "2026-09-19T00:00:00.000Z",
1138 closedAt: null,
1139 mergedAt: "2026-09-19T00:00:00.000Z",
1140 };
1141 }),
1142 }),
1143 Layer.mock(PullRequestService.PullRequestService)({
1144 notifyLinkedThreadsChanged: Effect.void,
1145 }),
1146 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1147 resolve: () =>
1148 Effect.succeed({
1149 canonicalKey: "github.com/acme/project",
1150 locator: {
1151 source: "git-remote" as const,
1152 remoteName: "origin",
1153 remoteUrl: "git@github.com:acme/project.git",
1154 },
1155 provider: SourceControlProviderKind.make("github"),
1156 owner: "acme",
1157 name: "project",
1158 }),
1159 }),
1160 // A connected client keeps the periodic sweep running.
1161 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1162 shouldRunOpportunisticWork: Effect.succeed(true),
1163 }),
1164 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1165 Layer.succeed(
1166 SecureRandom.SecureRandom,
1167 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1168 ),
1169 FileSystem.layerNoop({}),
1170 Path.layer,
1171 );
1172 yield* Effect.gen(function* () {
1173 const service = yield* ThreadPullRequestService.make;
1174 yield* service.start();
1175 yield* Deferred.succeed(activation, undefined);
1176 yield* Queue.take(sweeps);
1177 yield* service.drain;
1178 yield* TestClock.adjust("1 minute");
1179 yield* Queue.take(sweeps);
1180 yield* service.drain;
1181 }).pipe(Effect.provide(dependencies));
1182
1183 expect(commands).toEqual([]);
1184 expect(lookups).toHaveLength(2);
1185 // GitManager rereads git state on request, and by default whenever its
1186 // remembered answer is merged or closed.
1187 expect(
1188 lookups.filter(
1189 (options) =>
1190 options?.refresh === true ||
1191 options?.freshGitState === true ||
1192 options?.confirmTerminal !== false,
1193 ),
1194 ).toEqual([]);
1195 }),
1196 );
1197
1198 const mergedPullRequest43 = {
1199 number: 43,
1200 title: "Replacement work",
1201 url: "https://github.com/acme/project/pull/43",
1202 baseRef: "main",
1203 headRef: "feature/replaced",
1204 state: "merged" as const,
1205 repositoryKey: "github.com/acme/project",
1206 updatedAt: "2026-09-19T00:00:00.000Z",
1207 closedAt: null,
1208 mergedAt: "2026-09-19T00:00:00.000Z",
1209 };
1210
1211 it.effect.each([
1212 { name: "reopened", fresh: { ...mergedPullRequest43, state: "open" as const }, writes: false },
1213 { name: "the same merged PR", fresh: mergedPullRequest43, writes: true },
1214 ])("saves a remembered merged PR only when fresh git state finds $name", ({ fresh, writes }) =>
1215 Effect.gen(function* () {
1216 const savedReference = {
1217 projectId: ProjectId.make("project-1"),
1218 repository: "acme/project",
1219 number: 42,
1220 url: "https://github.com/acme/project/pull/42",
1221 };
1222 const thread = {
1223 ...threadShell("replaced-branch-thread"),
1224 createdAt: DateTime.makeUnsafe("2026-09-01T00:00:00.000Z"),
1225 branch: mergedPullRequest43.headRef,
1226 branchPullRequest: savedReference,
1227 };
1228 const project: OrchestrationProjectShell = {
1229 id: thread.projectId,
1230 title: "Project",
1231 workspaceRoot: "/workspace/project",
1232 defaultModelSelection: null,
1233 scripts: [],
1234 createdAt: "2026-08-01T00:00:00.000Z",
1235 updatedAt: "2026-08-01T00:00:00.000Z",
1236 };
1237 const activation = yield* Deferred.make<void>();
1238 const sweeps = yield* Queue.unbounded<void>();
1239 const commands: Array<OrchestrationV2ServerCommand> = [];
1240 const dependencies = Layer.mergeAll(
1241 Layer.mock(Orchestrator.OrchestratorV2)({
1242 streamDomainEvents: Stream.never,
1243 getPullRequestSnapshot: () =>
1244 Queue.offer(sweeps, undefined).pipe(
1245 Effect.as({
1246 schemaVersion: 2,
1247 snapshotSequence: 1,
1248 threads: [thread],
1249 archivedThreads: [],
1250 }),
1251 ),
1252 dispatch: (command) =>
1253 Effect.sync(() => {
1254 commands.push(command);
1255 return { sequence: 2, storedEvents: [] };
1256 }),
1257 }),
1258 Layer.mock(ProjectStore.ProjectStoreV2)({
1259 listShells: () => Effect.succeed([project]),
1260 getShell: () => Effect.succeedSome(project),
1261 }),
1262 // Only the fresh read disagrees with the remembered detection.
1263 Layer.mock(GitManager.GitManager)({
1264 branchPullRequest: (_input, options) =>
1265 Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
1266 }),
1267 Layer.mock(PullRequestService.PullRequestService)({
1268 notifyLinkedThreadsChanged: Effect.void,
1269 }),
1270 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1271 resolve: () =>
1272 Effect.succeed({
1273 canonicalKey: "github.com/acme/project",
1274 locator: {
1275 source: "git-remote" as const,
1276 remoteName: "origin",
1277 remoteUrl: "git@github.com:acme/project.git",
1278 },
1279 provider: SourceControlProviderKind.make("github"),
1280 owner: "acme",
1281 name: "project",
1282 }),
1283 }),
1284 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1285 shouldRunOpportunisticWork: Effect.succeed(true),
1286 }),
1287 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1288 Layer.succeed(
1289 SecureRandom.SecureRandom,
1290 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1291 ),
1292 FileSystem.layerNoop({}),
1293 Path.layer,
1294 );
1295 yield* Effect.gen(function* () {
1296 const service = yield* ThreadPullRequestService.make;
1297 yield* service.start();
1298 yield* Deferred.succeed(activation, undefined);
1299 yield* Queue.take(sweeps);
1300 yield* service.drain;
1301 }).pipe(Effect.provide(dependencies));
1302
1303 expect(
1304 commands.map((command) =>
1305 command.type === "thread.pull-request.sync" ? command.branchPullRequest : command.type,
1306 ),
1307 ).toEqual(
1308 writes
1309 ? [
1310 {
1311 projectId: project.id,
1312 repository: "acme/project",
1313 number: 43,
1314 url: mergedPullRequest43.url,
1315 },
1316 ]
1317 : [],
1318 );
1319 }),
1320 );
1321});