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