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

ThreadPullRequestService.test.ts

1,152 lines44.6 KB

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("leaves delegated child threads to their own refresh instead of the sweep", () =>
516 Effect.gen(function* () {
517 const parent = {
518 ...threadShell("parent-thread"),
519 branch: "feature/parent",
520 worktreePath: "/workspace/parent",
521 };
522 const child: OrchestrationV2ThreadShell = {
523 ...threadShell("child-thread"),
524 branch: "t3/reply-ok",
525 worktreePath: "/workspace/child",
526 lineage: {
527 rootThreadId: parent.id,
528 parentThreadId: parent.id,
529 relationshipToParent: "subagent",
530 },
531 };
532 const project: OrchestrationProjectShell = {
533 id: parent.projectId,
534 title: "Project",
535 workspaceRoot: "/workspace/project",
536 defaultModelSelection: null,
537 scripts: [],
538 createdAt: "2026-08-01T00:00:00.000Z",
539 updatedAt: "2026-08-01T00:00:00.000Z",
540 };
541 const activation = yield* Deferred.make<void>();
542 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
543 const sweeps = yield* Queue.unbounded<void>();
544 const childLookup = yield* Deferred.make<void>();
545 const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
546 const dependencies = Layer.mergeAll(
547 Layer.mock(Orchestrator.OrchestratorV2)({
548 streamDomainEvents: Stream.fromQueue(domainEvents),
549 getPullRequestSnapshot: ({ threadId }) =>
550 threadId !== undefined
551 ? Effect.succeed({ snapshotSequence: 1, threads: [child] })
552 : Queue.offer(sweeps, undefined).pipe(
553 Effect.as({
554 schemaVersion: 2,
555 snapshotSequence: 1,
556 threads: [parent, child],
557 archivedThreads: [],
558 }),
559 ),
560 }),
561 Layer.mock(ProjectStore.ProjectStoreV2)({
562 listShells: () => Effect.succeed([project]),
563 getShell: () => Effect.succeedSome(project),
564 }),
565 Layer.mock(GitManager.GitManager)({
566 branchPullRequest: (input, options) =>
567 Effect.gen(function* () {
568 const refresh = options?.refresh ?? false;
569 lookups.push({ branch: input.branch, refresh });
570 if (input.branch === child.branch && refresh) {
571 yield* Deferred.succeed(childLookup, undefined);
572 }
573 return null;
574 }),
575 }),
576 Layer.mock(PullRequestService.PullRequestService)({
577 notifyLinkedThreadsChanged: Effect.void,
578 }),
579 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
580 resolve: () =>
581 Effect.succeed({
582 canonicalKey: "github.com/acme/project",
583 locator: {
584 source: "git-remote" as const,
585 remoteName: "origin",
586 remoteUrl: "git@github.com:acme/project.git",
587 },
588 provider: SourceControlProviderKind.make("github"),
589 owner: "acme",
590 name: "project",
591 }),
592 }),
593 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
594 shouldRunScopeWork: () => Effect.succeed(true),
595 shouldRunOpportunisticWork: Effect.succeed(true),
596 }),
597 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
598 Layer.succeed(
599 SecureRandom.SecureRandom,
600 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
601 ),
602 FileSystem.layerNoop({}),
603 Path.layer,
604 );
605 yield* Effect.gen(function* () {
606 const service = yield* ThreadPullRequestService.make;
607 yield* service.start();
608 yield* Deferred.succeed(activation, undefined);
609​
610 // Startup backfill sweep, then one periodic sweep.
611 yield* Queue.take(sweeps);
612 yield* service.drain;
613 yield* TestClock.adjust("1 minute");
614 yield* Queue.take(sweeps);
615 yield* service.drain;
616 const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
617​
618 // The child's own turn still discovers its pull request.
619 yield* Queue.offer(domainEvents, {
620 type: "checkpoint.captured",
621 threadId: child.id,
622 } as OrchestrationV2DomainEvent);
623 yield* Deferred.await(childLookup);
624 yield* service.drain;
625​
626 expect(sweepLookups).toEqual([parent.branch, parent.branch]);
627 expect(lookups.slice(sweepLookups.length)).toEqual([
628 { branch: child.branch, refresh: true },
629 ]);
630 }).pipe(Effect.provide(dependencies));
631 }),
632 );
633​
634 it.effect.each([
635 { state: "open", checkedOut: false },
636 { state: "merged", checkedOut: false },
637 { state: "closed", checkedOut: false },
638 { state: "merged", checkedOut: true },
639 ] as const)(
640 "associates a $state branch PR (checkedOut=$checkedOut) only with threads that predate its completion or saved it",
641 ({ state, checkedOut }) =>
642 Effect.gen(function* () {
643 const reference = {
644 projectId: ProjectId.make("project-1"),
645 repository: "acme/project",
646 number: 42,
647 url: "https://github.com/acme/project/pull/42",
648 };
649 const terminalAt = "2026-09-19T00:00:00.000Z";
650 const detected = {
651 number: 42,
652 url: reference.url,
653 title: "Previous staging work",
654 baseRef: "main",
655 headRef: "staging",
656 state,
657 updatedAt: terminalAt,
658 closedAt: state === "closed" ? terminalAt : null,
659 mergedAt: state === "merged" ? terminalAt : null,
660 repositoryKey: "github.com/acme/project",
661 };
662 const threads = [
663 { ...threadShell("older"), createdAt: DateTime.makeUnsafe("2026-09-18T00:00:00Z") },
664 { ...threadShell("same-time"), createdAt: DateTime.makeUnsafe(terminalAt) },
665 threadShell("new"),
666 { ...threadShell("saved"), branchPullRequest: reference },
667 { ...threadShell("explicit"), linkedPullRequest: reference },
668 ].map((thread) => ({ ...thread, branch: "staging" }));
669 const project: OrchestrationProjectShell = {
670 id: reference.projectId,
671 title: "Project",
672 workspaceRoot: "/workspace/project",
673 defaultModelSelection: null,
674 scripts: [],
675 createdAt: "2026-08-01T00:00:00.000Z",
676 updatedAt: "2026-08-01T00:00:00.000Z",
677 };
678 const activation = yield* Deferred.make<void>();
679 const sweepStarted = yield* Deferred.make<void>();
680 const commands: Array<OrchestrationV2ServerCommand> = [];
681 const dependencies = Layer.mergeAll(
682 Layer.mock(Orchestrator.OrchestratorV2)({
683 streamDomainEvents: Stream.never,
684 getPullRequestSnapshot: () =>
685 Deferred.succeed(sweepStarted, undefined).pipe(
686 Effect.as({ snapshotSequence: 1, threads }),
687 ),
688 dispatch: (command) =>
689 Effect.sync(() => {
690 commands.push(command);
691 return { sequence: 2, storedEvents: [] };
692 }),
693 }),
694 Layer.mock(ProjectStore.ProjectStoreV2)({
695 listShells: () => Effect.succeed([project]),
696 getShell: () => Effect.succeedSome(project),
697 }),
698 Layer.mock(GitManager.GitManager)({
699 branchPullRequest: () => Effect.succeed(detected),
700 checkedOutPullRequest: () => Effect.succeed(checkedOut),
701 }),
702 Layer.mock(PullRequestService.PullRequestService)({
703 summary: () =>
704 Effect.succeed({
705 ...detected,
706 ...reference,
707 provider: SourceControlProviderKind.make("github"),
708 baseBranch: detected.baseRef,
709 headBranch: detected.headRef,
710 }),
711 }),
712 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
713 resolve: () =>
714 Effect.succeed({
715 canonicalKey: "github.com/acme/project",
716 locator: {
717 source: "git-remote" as const,
718 remoteName: "origin",
719 remoteUrl: "git@github.com:acme/project.git",
720 },
721 provider: SourceControlProviderKind.make("github"),
722 owner: "acme",
723 name: "project",
724 }),
725 }),
726 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
727 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
728 Layer.succeed(
729 SecureRandom.SecureRandom,
730 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
731 ),
732 FileSystem.layerNoop({}),
733 Path.layer,
734 );
735 yield* Effect.gen(function* () {
736 const service = yield* ThreadPullRequestService.make;
737 yield* service.start();
738 yield* Deferred.succeed(activation, undefined);
739 yield* Deferred.await(sweepStarted);
740 yield* service.drain;
741 }).pipe(Effect.provide(dependencies));
742​
743 expect(
744 commands.map((command) => {
745 if (command.type !== "thread.pull-request.sync") throw new Error(command.type);
746 expect(command).not.toHaveProperty("linkedPullRequest");
747 return [command.threadId, command.branchPullRequest];
748 }),
749 ).toEqual(
750 (state === "open" || checkedOut
751 ? ["older", "same-time", "new", "explicit"]
752 : ["older", "same-time"]
753 ).map((id) => [id, reference]),
754 );
755 }),
756 );
757​
758 it.effect.each([
759 { state: "closed", sameBranch: false },
760 { state: "merged", sameBranch: false },
761 { state: "closed", sameBranch: true },
762 { state: "merged", sameBranch: true },
763 ] as const)(
764 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
765 ({ state, sameBranch }) =>
766 Effect.gen(function* () {
767 const savedReference = {
768 projectId: ProjectId.make("project-1"),
769 repository: "acme/project",
770 number: 42,
771 url: "https://github.com/acme/project/pull/42",
772 };
773 const thread = {
774 ...threadShell("branch-pr-thread"),
775 branch: "main",
776 branchPullRequest: savedReference,
777 linkedPullRequest: savedReference,
778 };
779 const project: OrchestrationProjectShell = {
780 id: thread.projectId,
781 title: "Project",
782 workspaceRoot: "/workspace/project",
783 defaultModelSelection: null,
784 scripts: [],
785 createdAt: "2026-08-01T00:00:00.000Z",
786 updatedAt: "2026-08-01T00:00:00.000Z",
787 };
788 const activation = yield* Deferred.make<void>();
789 const sweepStarted = yield* Deferred.make<void>();
790 const commands: Array<OrchestrationV2ServerCommand> = [];
791 let snapshotThread: unknown;
792 const dependencies = Layer.mergeAll(
793 Layer.mock(Orchestrator.OrchestratorV2)({
794 streamDomainEvents: Stream.never,
795 getPullRequestSnapshot: (options) =>
796 Effect.gen(function* () {
797 const store = yield* ProjectionStore.ProjectionStoreV2;
798 yield* store.apply({
799 id: EventId.make(`event:${thread.id}:created`),
800 type: "thread.created",
801 threadId: thread.id,
802 occurredAt: NOW,
803 payload: { ...thread, lastVisitedAt: thread.lastVisitedAt ?? null },
804 });
805 const sql = yield* SqlClient.SqlClient;
806 yield* sql`INSERT INTO orchestration_events (
807 sequence, event_id, aggregate_kind, stream_id, stream_version, event_type,
808 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
809 ) VALUES (7, 'pr-discovery', 'thread', ${thread.id}, 1, 'thread.created',
810 '2026-09-20T00:00:00.000Z', 'system', '{}', '{}', 2)`;
811 for (const table of [
812 "orchestration_v2_projection_turn_items",
813 "orchestration_v2_projection_messages",
814 "orchestration_v2_projection_provider_threads",
815 "orchestration_v2_projection_runs",
816 ])
817 yield* sql.unsafe(`DROP TABLE ${table}`);
818 const snapshot = yield* store.getPullRequestSnapshot(options);
819 snapshotThread = snapshot.threads[0];
820 yield* Deferred.succeed(sweepStarted, undefined);
821 return snapshot;
822 }).pipe(
823 Effect.provide(
824 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
825 ),
826 Effect.orDie,
827 ),
828 dispatch: (command) =>
829 Effect.sync(() => {
830 commands.push(command);
831 return { sequence: 2, storedEvents: [] };
832 }),
833 }),
834 Layer.mock(ProjectStore.ProjectStoreV2)({
835 listShells: () => Effect.succeed([project]),
836 getShell: () => Effect.succeedSome(project),
837 }),
838 Layer.mock(GitManager.GitManager)({
839 branchPullRequest: () => Effect.succeed(null),
840 }),
841 Layer.mock(PullRequestService.PullRequestService)({
842 summary: () =>
843 Effect.succeed({
844 ...savedReference,
845 provider: SourceControlProviderKind.make("github"),
846 title: "Previous branch work",
847 state,
848 headBranch: sameBranch ? thread.branch : "feature/previous-work",
849 baseBranch: "release",
850 updatedAt: "2026-09-19T00:00:00.000Z",
851 }),
852 }),
853 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
854 resolve: () =>
855 Effect.succeed({
856 canonicalKey: "github.com/acme/project",
857 locator: {
858 source: "git-remote" as const,
859 remoteName: "origin",
860 remoteUrl: "git@github.com:acme/project.git",
861 },
862 provider: SourceControlProviderKind.make("github"),
863 owner: "acme",
864 name: "project",
865 }),
866 }),
867 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
868 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
869 Layer.succeed(
870 SecureRandom.SecureRandom,
871 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
872 ),
873 FileSystem.layerNoop({}),
874 Path.layer,
875 );
876 yield* Effect.gen(function* () {
877 const service = yield* ThreadPullRequestService.make;
878 yield* service.start();
879 yield* Deferred.succeed(activation, undefined);
880 yield* Deferred.await(sweepStarted);
881 yield* service.drain;
882 }).pipe(Effect.provide(dependencies));
883​
884 expect(snapshotThread).toHaveProperty("createdAt", NOW);
885 if (sameBranch) {
886 expect(commands).toEqual([]);
887 } else {
888 expect(commands).toHaveLength(1);
889 expect(commands[0]).toMatchObject({
890 type: "thread.pull-request.sync",
891 threadId: thread.id,
892 snapshotSequence: 7,
893 expected: {
894 workspaceRoot: project.workspaceRoot,
895 branch: thread.branch,
896 worktreePath: thread.worktreePath,
897 linkedPullRequest: savedReference,
898 branchPullRequest: savedReference,
899 },
900 branchPullRequest: null,
901 });
902 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
903 }
904 }),
905 );
906​
907 it.effect("a saved merged branch PR rereads no git state on each sweep", () =>
908 Effect.gen(function* () {
909 const savedReference = {
910 projectId: ProjectId.make("project-1"),
911 repository: "acme/project",
912 number: 42,
913 url: "https://github.com/acme/project/pull/42",
914 };
915 const thread = {
916 ...threadShell("merged-branch-thread"),
917 branch: "feature/merged",
918 branchPullRequest: savedReference,
919 };
920 const project: OrchestrationProjectShell = {
921 id: thread.projectId,
922 title: "Project",
923 workspaceRoot: "/workspace/project",
924 defaultModelSelection: null,
925 scripts: [],
926 createdAt: "2026-08-01T00:00:00.000Z",
927 updatedAt: "2026-08-01T00:00:00.000Z",
928 };
929 const activation = yield* Deferred.make<void>();
930 const sweeps = yield* Queue.unbounded<void>();
931 const commands: Array<OrchestrationV2ServerCommand> = [];
932 const lookups: Array<Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1]> =
933 [];
934 const dependencies = Layer.mergeAll(
935 Layer.mock(Orchestrator.OrchestratorV2)({
936 streamDomainEvents: Stream.never,
937 getPullRequestSnapshot: () =>
938 Queue.offer(sweeps, undefined).pipe(
939 Effect.as({
940 schemaVersion: 2,
941 snapshotSequence: 1,
942 threads: [thread],
943 archivedThreads: [],
944 }),
945 ),
946 dispatch: (command) =>
947 Effect.sync(() => {
948 commands.push(command);
949 return { sequence: 2, storedEvents: [] };
950 }),
951 }),
952 Layer.mock(ProjectStore.ProjectStoreV2)({
953 listShells: () => Effect.succeed([project]),
954 getShell: () => Effect.succeedSome(project),
955 }),
956 Layer.mock(GitManager.GitManager)({
957 branchPullRequest: (_input, options) =>
958 Effect.sync(() => {
959 lookups.push(options);
960 return {
961 number: 42,
962 title: "Merged work",
963 url: savedReference.url,
964 baseRef: "main",
965 headRef: thread.branch,
966 state: "merged" as const,
967 repositoryKey: "github.com/acme/project",
968 updatedAt: "2026-09-19T00:00:00.000Z",
969 closedAt: null,
970 mergedAt: "2026-09-19T00:00:00.000Z",
971 };
972 }),
973 }),
974 Layer.mock(PullRequestService.PullRequestService)({
975 notifyLinkedThreadsChanged: Effect.void,
976 }),
977 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
978 resolve: () =>
979 Effect.succeed({
980 canonicalKey: "github.com/acme/project",
981 locator: {
982 source: "git-remote" as const,
983 remoteName: "origin",
984 remoteUrl: "git@github.com:acme/project.git",
985 },
986 provider: SourceControlProviderKind.make("github"),
987 owner: "acme",
988 name: "project",
989 }),
990 }),
991 // A connected client keeps the periodic sweep running.
992 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
993 shouldRunOpportunisticWork: Effect.succeed(true),
994 }),
995 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
996 Layer.succeed(
997 SecureRandom.SecureRandom,
998 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
999 ),
1000 FileSystem.layerNoop({}),
1001 Path.layer,
1002 );
1003 yield* Effect.gen(function* () {
1004 const service = yield* ThreadPullRequestService.make;
1005 yield* service.start();
1006 yield* Deferred.succeed(activation, undefined);
1007 yield* Queue.take(sweeps);
1008 yield* service.drain;
1009 yield* TestClock.adjust("1 minute");
1010 yield* Queue.take(sweeps);
1011 yield* service.drain;
1012 }).pipe(Effect.provide(dependencies));
1013​
1014 expect(commands).toEqual([]);
1015 expect(lookups).toHaveLength(2);
1016 // GitManager rereads git state on request, and by default whenever its
1017 // remembered answer is merged or closed.
1018 expect(
1019 lookups.filter(
1020 (options) =>
1021 options?.refresh === true ||
1022 options?.freshGitState === true ||
1023 options?.confirmTerminal !== false,
1024 ),
1025 ).toEqual([]);
1026 }),
1027 );
1028​
1029 const mergedPullRequest43 = {
1030 number: 43,
1031 title: "Replacement work",
1032 url: "https://github.com/acme/project/pull/43",
1033 baseRef: "main",
1034 headRef: "feature/replaced",
1035 state: "merged" as const,
1036 repositoryKey: "github.com/acme/project",
1037 updatedAt: "2026-09-19T00:00:00.000Z",
1038 closedAt: null,
1039 mergedAt: "2026-09-19T00:00:00.000Z",
1040 };
1041​
1042 it.effect.each([
1043 { name: "reopened", fresh: { ...mergedPullRequest43, state: "open" as const }, writes: false },
1044 { name: "the same merged PR", fresh: mergedPullRequest43, writes: true },
1045 ])("saves a remembered merged PR only when fresh git state finds $name", ({ fresh, writes }) =>
1046 Effect.gen(function* () {
1047 const savedReference = {
1048 projectId: ProjectId.make("project-1"),
1049 repository: "acme/project",
1050 number: 42,
1051 url: "https://github.com/acme/project/pull/42",
1052 };
1053 const thread = {
1054 ...threadShell("replaced-branch-thread"),
1055 createdAt: DateTime.makeUnsafe("2026-09-01T00:00:00.000Z"),
1056 branch: mergedPullRequest43.headRef,
1057 branchPullRequest: savedReference,
1058 };
1059 const project: OrchestrationProjectShell = {
1060 id: thread.projectId,
1061 title: "Project",
1062 workspaceRoot: "/workspace/project",
1063 defaultModelSelection: null,
1064 scripts: [],
1065 createdAt: "2026-08-01T00:00:00.000Z",
1066 updatedAt: "2026-08-01T00:00:00.000Z",
1067 };
1068 const activation = yield* Deferred.make<void>();
1069 const sweeps = yield* Queue.unbounded<void>();
1070 const commands: Array<OrchestrationV2ServerCommand> = [];
1071 const dependencies = Layer.mergeAll(
1072 Layer.mock(Orchestrator.OrchestratorV2)({
1073 streamDomainEvents: Stream.never,
1074 getPullRequestSnapshot: () =>
1075 Queue.offer(sweeps, undefined).pipe(
1076 Effect.as({
1077 schemaVersion: 2,
1078 snapshotSequence: 1,
1079 threads: [thread],
1080 archivedThreads: [],
1081 }),
1082 ),
1083 dispatch: (command) =>
1084 Effect.sync(() => {
1085 commands.push(command);
1086 return { sequence: 2, storedEvents: [] };
1087 }),
1088 }),
1089 Layer.mock(ProjectStore.ProjectStoreV2)({
1090 listShells: () => Effect.succeed([project]),
1091 getShell: () => Effect.succeedSome(project),
1092 }),
1093 // Only the fresh read disagrees with the remembered detection.
1094 Layer.mock(GitManager.GitManager)({
1095 branchPullRequest: (_input, options) =>
1096 Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
1097 }),
1098 Layer.mock(PullRequestService.PullRequestService)({
1099 notifyLinkedThreadsChanged: Effect.void,
1100 }),
1101 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1102 resolve: () =>
1103 Effect.succeed({
1104 canonicalKey: "github.com/acme/project",
1105 locator: {
1106 source: "git-remote" as const,
1107 remoteName: "origin",
1108 remoteUrl: "git@github.com:acme/project.git",
1109 },
1110 provider: SourceControlProviderKind.make("github"),
1111 owner: "acme",
1112 name: "project",
1113 }),
1114 }),
1115 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1116 shouldRunOpportunisticWork: Effect.succeed(true),
1117 }),
1118 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1119 Layer.succeed(
1120 SecureRandom.SecureRandom,
1121 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1122 ),
1123 FileSystem.layerNoop({}),
1124 Path.layer,
1125 );
1126 yield* Effect.gen(function* () {
1127 const service = yield* ThreadPullRequestService.make;
1128 yield* service.start();
1129 yield* Deferred.succeed(activation, undefined);
1130 yield* Queue.take(sweeps);
1131 yield* service.drain;
1132 }).pipe(Effect.provide(dependencies));
1133​
1134 expect(
1135 commands.map((command) =>
1136 command.type === "thread.pull-request.sync" ? command.branchPullRequest : command.type,
1137 ),
1138 ).toEqual(
1139 writes
1140 ? [
1142 projectId: project.id,
1143 repository: "acme/project",
1144 number: 43,
1145 url: mergedPullRequest43.url,
1146 },
1148 : [],
1149 );
1150 }),
1151 );
1152});