Open History to see the last commit
1import {
2 CheckpointRef,
3 EventId,
4 GitManagerError,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 TurnId,
9 type OrchestrationCommand,
10 type OrchestrationEvent,
11 type OrchestrationProjectShell,
12 type OrchestrationShellSnapshot,
13 type OrchestrationThreadShell,
14 type PullRequestRef,
15 type PullRequestSummary,
16 type ThreadLinkedPullRequest,
17} from "@t3tools/contracts";
18import { describe, expect, it } from "@effect/vitest";
19import * as Crypto from "effect/Crypto";
20import * as Deferred from "effect/Deferred";
21import * as Effect from "effect/Effect";
22import * as FileSystem from "effect/FileSystem";
23import * as Layer from "effect/Layer";
24import * as Option from "effect/Option";
25import * as PubSub from "effect/PubSub";
26import * as Queue from "effect/Queue";
27import * as Ref from "effect/Ref";
28import * as Stream from "effect/Stream";
29import { TestClock } from "effect/testing";
30import * as SqlClient from "effect/unstable/sql/SqlClient";
31
32import { GitManager, type GitBranchPullRequest } from "../git/GitManager.ts";
33import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
34import { PullRequestService } from "../pullRequest/PullRequestService.ts";
35import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";
36import { ServerActivation } from "../serverActivation.ts";
37import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
38import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
39import {
40 ProjectionSnapshotQuery,
41 type ProjectionSnapshotQueryShape,
42} from "./Services/ProjectionSnapshotQuery.ts";
43import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
44import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";
45import * as ThreadPullRequestReactor from "./ThreadPullRequestReactor.ts";
46
47const NOW = "2026-09-01T12:00:00.000Z";
48const PROJECT_ID = ProjectId.make("project");
49const REPOSITORY = "owner/repository";
50const REPOSITORY_KEY = `github.com/${REPOSITORY}`;
51type SyncCommand = Extract<OrchestrationCommand, { type: "thread.pull-request.sync" }>;
52
53function reference(number: number): ThreadLinkedPullRequest {
54 return {
55 projectId: PROJECT_ID,
56 repository: REPOSITORY,
57 number,
58 url: `https://github.com/${REPOSITORY}/pull/${number}`,
59 };
60}
61
62function branchPullRequest(
63 number = 42,
64 state: GitBranchPullRequest["state"] = "open",
65): GitBranchPullRequest {
66 return {
67 ...reference(number),
68 title: "Branch pull request",
69 baseRef: "main",
70 headRef: "feature",
71 state,
72 updatedAt: NOW,
73 repositoryKey: REPOSITORY_KEY,
74 };
75}
76
77function summary(input: PullRequestRef, state: PullRequestSummary["state"]): PullRequestSummary {
78 return {
79 ...input,
80 provider: "github",
81 title: "Pull request",
82 url: reference(input.number).url,
83 state,
84 headBranch: "feature",
85 baseBranch: "main",
86 updatedAt: NOW,
87 };
88}
89
90function thread(
91 id: string,
92 overrides: Partial<OrchestrationThreadShell> = {},
93): OrchestrationThreadShell {
94 return {
95 id: ThreadId.make(id),
96 projectId: PROJECT_ID,
97 title: id,
98 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
99 runtimeMode: "full-access",
100 interactionMode: "default",
101 pullRequests: [],
102 branch: "feature",
103 worktreePath: null,
104 latestTurn: null,
105 createdAt: NOW,
106 updatedAt: NOW,
107 archivedAt: null,
108 settledOverride: null,
109 settledAt: null,
110 session: null,
111 latestUserMessageAt: NOW,
112 hasPendingApprovals: false,
113 hasPendingUserInput: false,
114 hasActionableProposedPlan: false,
115 ...overrides,
116 };
117}
118
119const project = {
120 id: PROJECT_ID,
121 title: "Project",
122 workspaceRoot: "/workspace/project",
123 repositoryIdentity: {
124 canonicalKey: REPOSITORY_KEY,
125 displayName: REPOSITORY,
126 rootPath: "/workspace/project",
127 locator: {
128 source: "git-remote",
129 remoteName: "origin",
130 remoteUrl: `git@github.com:${REPOSITORY}.git`,
131 },
132 },
133 defaultModelSelection: null,
134 scripts: [],
135 createdAt: NOW,
136 updatedAt: NOW,
137} satisfies OrchestrationProjectShell;
138
139const makeHarness = Effect.fn("makeThreadPullRequestHarness")(function* (options: {
140 readonly threads: ReadonlyArray<OrchestrationThreadShell>;
141 readonly branchPullRequest?: GitManager["Service"]["branchPullRequest"];
142 readonly summary?: PullRequestService["Service"]["summary"];
143 readonly existingWorktrees?: ReadonlyArray<string>;
144 readonly project?: OrchestrationProjectShell;
145 readonly resolveRepositoryIdentity?: RepositoryIdentityResolver["Service"]["resolve"];
146 /** Serve full sweep reads from this instead of `threads`. */
147 readonly getShellSnapshot?: ProjectionSnapshotQueryShape["getShellSnapshot"];
148}) {
149 const activation = yield* Deferred.make<void>();
150 const snapshots = yield* Ref.make<OrchestrationShellSnapshot>({
151 snapshotSequence: 1,
152 projects: [options.project ?? project],
153 threads: options.threads,
154 updatedAt: NOW,
155 });
156 // Each shell read: a thread id for a one-thread read, null for a full read.
157 const reads = yield* Queue.unbounded<ThreadId | null>();
158 const events = yield* PubSub.unbounded<OrchestrationEvent>();
159 const commands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]);
160 const branchCalls = yield* Ref.make<
161 ReadonlyArray<{ readonly cwd: string; readonly branch: string; readonly refresh: boolean }>
162 >([]);
163 const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
164 let uuid = 0;
165 const dependencies = Layer.mergeAll(
166 Layer.mock(ProjectionSnapshotQuery)({
167 getShellSnapshot: (readOptions) =>
168 (options.getShellSnapshot?.(readOptions) ?? Ref.get(snapshots)).pipe(
169 Effect.tap(() => Queue.offer(reads, null)),
170 ),
171 getSnapshotSequence: () =>
172 Ref.get(snapshots).pipe(Effect.map(({ snapshotSequence }) => ({ snapshotSequence }))),
173 getThreadShellById: (threadId) =>
174 Ref.get(snapshots).pipe(
175 Effect.map(({ threads }) =>
176 Option.fromUndefinedOr(
177 threads.find((thread) => thread.id === threadId && thread.archivedAt === null),
178 ),
179 ),
180 Effect.tap(() => Queue.offer(reads, threadId)),
181 ),
182 getProjectShells: (projectIds) =>
183 Ref.get(snapshots).pipe(
184 Effect.map(({ projects }) =>
185 projects.filter((project) => projectIds?.includes(project.id) ?? true),
186 ),
187 ),
188 }),
189 Layer.mock(GitManager)({
190 branchPullRequest: (input, readOptions) =>
191 Ref.update(branchCalls, (calls) => [
192 ...calls,
193 { ...input, refresh: readOptions?.refresh === true },
194 ]).pipe(
195 Effect.andThen(options.branchPullRequest?.(input, readOptions) ?? Effect.succeed(null)),
196 ),
197 }),
198 Layer.mock(PullRequestService)({
199 summary: (input, readOptions) =>
200 Ref.update(summaryCalls, (calls) => [...calls, input]).pipe(
201 Effect.andThen(
202 options.summary?.(input, readOptions) ?? Effect.succeed(summary(input, "open")),
203 ),
204 ),
205 }),
206 Layer.mock(RepositoryIdentityResolver)({
207 resolve:
208 options.resolveRepositoryIdentity ??
209 (() => Effect.succeed(options.project?.repositoryIdentity ?? project.repositoryIdentity)),
210 }),
211 Layer.mock(OrchestrationEngineService)({
212 subscribeDomainEvents: PubSub.subscribe(events).pipe(
213 Effect.map((subscription) => Stream.fromSubscription(subscription)),
214 ),
215 dispatch: (command) => {
216 if (command.type !== "thread.pull-request.sync") {
217 return Effect.die(`Unexpected command: ${command.type}`);
218 }
219 return Ref.update(commands, (current) => [...current, command]).pipe(
220 Effect.andThen(
221 Ref.updateAndGet(snapshots, (snapshot) => ({
222 ...snapshot,
223 snapshotSequence: snapshot.snapshotSequence + 1,
224 threads: snapshot.threads.map((current) =>
225 current.id === command.threadId
226 ? {
227 ...current,
228 branchPullRequest: command.branchPullRequest,
229 ...(command.linkedPullRequest !== undefined
230 ? { linkedPullRequest: command.linkedPullRequest }
231 : {}),
232 }
233 : current,
234 ),
235 })),
236 ),
237 Effect.map((snapshot) => ({ sequence: snapshot.snapshotSequence })),
238 );
239 },
240 }),
241 Layer.succeed(ServerActivation, Deferred.await(activation)),
242 Layer.succeed(
243 Crypto.Crypto,
244 Crypto.make({
245 randomBytes: (size) => new Uint8Array(size).fill(++uuid),
246 digest: (_algorithm, data) => Effect.succeed(data),
247 }),
248 ),
249 FileSystem.layerNoop({
250 exists: (path) => Effect.succeed(options.existingWorktrees?.includes(path) ?? false),
251 }),
252 );
253
254 const start = Effect.fn("startThreadPullRequestHarness")(function* () {
255 const reactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
256 yield* reactor.start();
257 yield* Deferred.succeed(activation, undefined);
258 yield* Queue.take(reads);
259 yield* reactor.drain;
260 return reactor;
261 });
262
263 return {
264 start,
265 reads,
266 snapshots,
267 commands,
268 branchCalls,
269 summaryCalls,
270 publish: (event: OrchestrationEvent) => PubSub.publish(events, event),
271 layer: ThreadPullRequestReactor.layer.pipe(Layer.provide(dependencies)),
272 };
273});
274
275describe("ThreadPullRequestReactor", () => {
276 it.effect("discovers saved branch PRs without a client and shares branch lookups", () =>
277 Effect.scoped(
278 Effect.gen(function* () {
279 const fixture = yield* makeHarness({
280 threads: [
281 thread("first"),
282 thread("second"),
283 thread("archived", { archivedAt: NOW }),
284 thread("no-branch", { branch: null }),
285 ],
286 branchPullRequest: () => Effect.succeed(branchPullRequest()),
287 });
288 yield* Effect.gen(function* () {
289 const reactor = yield* fixture.start();
290 expect(yield* Ref.get(fixture.branchCalls)).toEqual([
291 { cwd: project.workspaceRoot, branch: "feature", refresh: false },
292 { cwd: project.workspaceRoot, branch: "feature", refresh: false },
293 ]);
294 expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
295 "first",
296 "second",
297 ]);
298 expect((yield* Ref.get(fixture.snapshots)).threads[0]?.branchPullRequest).toEqual(
299 reference(42),
300 );
301
302 yield* TestClock.adjust("1 minute");
303 yield* Queue.take(fixture.reads);
304 yield* reactor.drain;
305 expect(yield* Ref.get(fixture.commands)).toHaveLength(2);
306 }).pipe(Effect.provide(fixture.layer));
307 }),
308 ),
309 );
310
311 it.effect("replaces terminal manual links but preserves open links and explicit unlink", () =>
312 Effect.scoped(
313 Effect.gen(function* () {
314 const fixture = yield* makeHarness({
315 threads: [
316 thread("merged", { linkedPullRequest: reference(1) }),
317 thread("closed", { linkedPullRequest: reference(2) }),
318 thread("open", { linkedPullRequest: reference(3) }),
319 thread("unlinked", { linkedPullRequest: null }),
320 ],
321 branchPullRequest: () => Effect.succeed(branchPullRequest()),
322 summary: (input) =>
323 Effect.succeed(
324 summary(
325 input,
326 input.number === 1 ? "merged" : input.number === 2 ? "closed" : "open",
327 ),
328 ),
329 });
330 yield* Effect.gen(function* () {
331 yield* fixture.start();
332 const snapshot = yield* Ref.get(fixture.snapshots);
333 expect(snapshot.threads.map((current) => current.linkedPullRequest)).toEqual([
334 reference(42),
335 reference(42),
336 reference(3),
337 null,
338 ]);
339 expect(
340 snapshot.threads.every((current) => current.branchPullRequest?.number === 42),
341 ).toBe(true);
342 }).pipe(Effect.provide(fixture.layer));
343 }),
344 ),
345 );
346
347 it.effect.each(["session-first", "checkpoint-first"] as const)(
348 "refreshes discovery once after a turn ends with %s event ordering",
349 (order) =>
350 Effect.scoped(
351 Effect.gen(function* () {
352 const current = thread("turn-thread");
353 const detected = yield* Ref.make<GitBranchPullRequest | null>(null);
354 const fixture = yield* makeHarness({
355 threads: [current],
356 branchPullRequest: (_input, options) =>
357 options?.refresh
358 ? Ref.set(detected, branchPullRequest()).pipe(Effect.andThen(Ref.get(detected)))
359 : Ref.get(detected),
360 });
361 yield* Effect.gen(function* () {
362 const reactor = yield* fixture.start();
363 expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
364 const sessionEvent: OrchestrationEvent = {
365 type: "thread.session-set",
366 sequence: 2,
367 eventId: EventId.make("turn-finished"),
368 aggregateKind: "thread",
369 aggregateId: current.id,
370 occurredAt: NOW,
371 commandId: null,
372 causationEventId: null,
373 correlationId: null,
374 metadata: {},
375 payload: {
376 threadId: current.id,
377 session: {
378 threadId: current.id,
379 status: "ready",
380 providerName: "Codex",
381 runtimeMode: "full-access",
382 activeTurnId: null,
383 lastError: null,
384 updatedAt: NOW,
385 },
386 },
387 };
388 const checkpointEvent: OrchestrationEvent = {
389 ...sessionEvent,
390 type: "thread.turn-diff-completed",
391 sequence: 3,
392 eventId: EventId.make("checkpoint-finished"),
393 payload: {
394 threadId: current.id,
395 turnId: TurnId.make("turn"),
396 checkpointTurnCount: 1,
397 checkpointRef: CheckpointRef.make("checkpoint"),
398 status: "ready",
399 files: [],
400 assistantMessageId: null,
401 completedAt: NOW,
402 },
403 };
404 const events =
405 order === "session-first"
406 ? [sessionEvent, checkpointEvent]
407 : [checkpointEvent, sessionEvent];
408 for (const event of events) {
409 yield* fixture.publish(event);
410 expect(yield* Queue.take(fixture.reads)).toBe(current.id);
411 yield* reactor.drain;
412 }
413 expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual(reference(42));
414 expect(
415 (yield* Ref.get(fixture.branchCalls)).filter((call) => call.refresh),
416 ).toHaveLength(1);
417 }).pipe(Effect.provide(fixture.layer));
418 }),
419 ),
420 );
421
422 it.effect("refreshes the project identity when a turn adds the remote", () =>
423 Effect.scoped(
424 Effect.gen(function* () {
425 const current = thread("new-remote");
426 const fixture = yield* makeHarness({
427 threads: [current],
428 project: { ...project, repositoryIdentity: null },
429 branchPullRequest: () => Effect.succeed(branchPullRequest()),
430 resolveRepositoryIdentity: (_cwd, options) =>
431 Effect.succeed(options?.refresh ? project.repositoryIdentity : null),
432 });
433 yield* Effect.gen(function* () {
434 const reactor = yield* fixture.start();
435 expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
436
437 yield* fixture.publish({
438 type: "thread.turn-diff-completed",
439 sequence: 2,
440 eventId: EventId.make("checkpoint-finished"),
441 aggregateKind: "thread",
442 aggregateId: current.id,
443 occurredAt: NOW,
444 commandId: null,
445 causationEventId: null,
446 correlationId: null,
447 metadata: {},
448 payload: {
449 threadId: current.id,
450 turnId: TurnId.make("turn"),
451 checkpointTurnCount: 1,
452 checkpointRef: CheckpointRef.make("checkpoint"),
453 status: "ready",
454 files: [],
455 assistantMessageId: null,
456 completedAt: NOW,
457 },
458 });
459 yield* Queue.take(fixture.reads);
460 yield* reactor.drain;
461 expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual(reference(42));
462 }).pipe(Effect.provide(fixture.layer));
463 }),
464 ),
465 );
466
467 it.effect("uses live worktrees and falls back to the project for removed worktrees", () =>
468 Effect.scoped(
469 Effect.gen(function* () {
470 const fixture = yield* makeHarness({
471 threads: [
472 thread("live", { worktreePath: "/workspace/worktree" }),
473 thread("removed", { worktreePath: "/workspace/removed" }),
474 ],
475 existingWorktrees: ["/workspace/worktree"],
476 branchPullRequest: () => Effect.succeed(branchPullRequest()),
477 });
478 yield* Effect.gen(function* () {
479 yield* fixture.start();
480 expect(new Set((yield* Ref.get(fixture.branchCalls)).map((call) => call.cwd))).toEqual(
481 new Set(["/workspace/project", "/workspace/worktree"]),
482 );
483 }).pipe(Effect.provide(fixture.layer));
484 }),
485 ),
486 );
487
488 it.effect("retains only terminal PRs on shared checkouts and clears a removed branch", () =>
489 Effect.scoped(
490 Effect.gen(function* () {
491 const fixture = yield* makeHarness({
492 threads: [
493 thread("terminal", { branch: "main", branchPullRequest: reference(1) }),
494 thread("open", { branchPullRequest: reference(2) }),
495 thread("worktree", {
496 worktreePath: "/workspace/worktree",
497 branchPullRequest: reference(1),
498 }),
499 thread("cleared", {
500 branch: null,
501 branchPullRequest: reference(1),
502 linkedPullRequest: reference(3),
503 }),
504 ],
505 summary: (input) =>
506 Effect.succeed(summary(input, input.number === 1 ? "merged" : "open")),
507 });
508 yield* Effect.gen(function* () {
509 yield* fixture.start();
510 const snapshot = yield* Ref.get(fixture.snapshots);
511 expect(snapshot.threads.map((current) => current.branchPullRequest)).toEqual([
512 reference(1),
513 null,
514 null,
515 null,
516 ]);
517 expect(snapshot.threads[3]?.linkedPullRequest).toEqual(reference(3));
518 }).pipe(Effect.provide(fixture.layer));
519 }),
520 ),
521 );
522
523 it.effect("keeps saved links on lookup failures and rejects a different repository", () =>
524 Effect.scoped(
525 Effect.gen(function* () {
526 const fixture = yield* makeHarness({
527 threads: [
528 thread("failed", { branch: "failed", branchPullRequest: reference(1) }),
529 thread("wrong-repository", {
530 branch: "wrong-repository",
531 branchPullRequest: reference(2),
532 }),
533 thread("healthy"),
534 ],
535 branchPullRequest: ({ cwd, branch }) =>
536 branch === "failed"
537 ? Effect.fail(
538 new GitManagerError({
539 operation: "branchPullRequest",
540 cwd,
541 detail: "Lookup failed",
542 }),
543 )
544 : Effect.succeed({
545 ...branchPullRequest(),
546 repositoryKey:
547 branch === "wrong-repository" ? "github.com/other/repository" : REPOSITORY_KEY,
548 }),
549 });
550 yield* Effect.gen(function* () {
551 yield* fixture.start();
552 expect(
553 (yield* Ref.get(fixture.snapshots)).threads.map((current) => current.branchPullRequest),
554 ).toEqual([reference(1), reference(2), reference(42)]);
555 expect(yield* Ref.get(fixture.commands)).toHaveLength(1);
556 }).pipe(Effect.provide(fixture.layer));
557 }),
558 ),
559 );
560
561 it.effect.each(["settled", null] as const)(
562 "retries settled backfills and stops after success with settledOverride %s",
563 (settledOverride) =>
564 Effect.scoped(
565 Effect.gen(function* () {
566 const online = yield* Ref.make(false);
567 const fixture = yield* makeHarness({
568 threads: [
569 thread("backfill", { settledOverride, settledAt: NOW }),
570 thread("known", {
571 branch: "known",
572 settledOverride,
573 settledAt: NOW,
574 branchPullRequest: reference(1),
575 }),
576 ],
577 branchPullRequest: ({ cwd }) =>
578 Ref.get(online).pipe(
579 Effect.flatMap((connected) =>
580 connected
581 ? Effect.succeed(branchPullRequest(42, "merged"))
582 : Effect.fail(
583 new GitManagerError({
584 operation: "branchPullRequest",
585 cwd,
586 detail: "Offline",
587 }),
588 ),
589 ),
590 ),
591 });
592 yield* Effect.gen(function* () {
593 const reactor = yield* fixture.start();
594 expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
595 // A one-thread read cannot show that other pending threads are gone.
596 const gone = ThreadId.make("gone");
597 yield* fixture.publish({
598 type: "thread.unarchived",
599 sequence: 2,
600 eventId: EventId.make("gone-unarchived"),
601 aggregateKind: "thread",
602 aggregateId: gone,
603 occurredAt: NOW,
604 commandId: null,
605 causationEventId: null,
606 correlationId: null,
607 metadata: {},
608 payload: { threadId: gone, updatedAt: NOW },
609 });
610 expect(yield* Queue.take(fixture.reads)).toBe(gone);
611 yield* reactor.drain;
612 yield* Ref.set(online, true);
613 yield* TestClock.adjust("1 minute");
614 yield* Queue.take(fixture.reads);
615 yield* reactor.drain;
616 expect((yield* Ref.get(fixture.commands))[0]?.threadId).toBe("backfill");
617 yield* TestClock.adjust("1 minute");
618 yield* Queue.take(fixture.reads);
619 yield* reactor.drain;
620 expect((yield* Ref.get(fixture.branchCalls)).map((call) => call.branch)).toEqual([
621 "feature",
622 "feature",
623 "feature",
624 ]);
625 }).pipe(Effect.provide(fixture.layer));
626 }),
627 ),
628 );
629
630 it.effect("stops retrying a settled backfill after repeated lookup failures", () =>
631 Effect.scoped(
632 Effect.gen(function* () {
633 const fixture = yield* makeHarness({
634 threads: [thread("backfill", { settledOverride: "settled", settledAt: NOW })],
635 branchPullRequest: ({ cwd }) =>
636 Effect.fail(
637 new GitManagerError({ operation: "branchPullRequest", cwd, detail: "No gh" }),
638 ),
639 });
640 yield* Effect.gen(function* () {
641 const reactor = yield* fixture.start();
642 for (
643 let attempt = 1;
644 attempt < ThreadPullRequestReactor.BACKFILL_ATTEMPTS + 2;
645 attempt++
646 ) {
647 yield* TestClock.adjust("1 minute");
648 yield* Queue.take(fixture.reads);
649 yield* reactor.drain;
650 }
651 expect(yield* Ref.get(fixture.branchCalls)).toHaveLength(
652 ThreadPullRequestReactor.BACKFILL_ATTEMPTS,
653 );
654 expect(yield* Ref.get(fixture.commands)).toHaveLength(0);
655 }).pipe(Effect.provide(fixture.layer));
656 }),
657 ),
658 );
659
660 it.effect("discovers the same PRs from the unsettled read as from the full read", () =>
661 Effect.gen(function* () {
662 const sql = yield* SqlClient.SqlClient;
663 const query = yield* ProjectionSnapshotQuery;
664 yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at)
665 VALUES ('project', 'Project', '/workspace/project', '[]', ${NOW}, ${NOW}),
666 ('dormant', 'Dormant', '/workspace/dormant', '[]', ${NOW}, ${NOW})`;
667 yield* sql`INSERT INTO projection_threads (thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, branch, branch_pull_request_json, created_at, updated_at, archived_at, settled_override, settled_at)
668 VALUES
669 ('open', 'project', 'Open', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'open', NULL, ${NOW}, ${NOW}, NULL, NULL, NULL),
670 ('resumed', 'project', 'Resumed', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'resumed', NULL, ${NOW}, ${NOW}, NULL, 'active', NULL),
671 ('linked', 'project', 'Linked', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'linked', '{"projectId":"project","repository":"owner/repository","number":3,"url":"https://github.com/owner/repository/pull/3"}', ${NOW}, ${NOW}, NULL, NULL, NULL),
672 ('settled', 'project', 'Settled', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'settled', '{"projectId":"project","repository":"owner/repository","number":4,"url":"https://github.com/owner/repository/pull/4"}', ${NOW}, ${NOW}, NULL, 'settled', ${NOW}),
673 ('backfill', 'project', 'Backfill', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'backfill', NULL, ${NOW}, ${NOW}, NULL, 'settled', ${NOW}),
674 ('imported', 'dormant', 'Imported', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', NULL, NULL, ${NOW}, ${NOW}, NULL, 'settled', ${NOW}),
675 ('archived', 'project', 'Archived', '{"provider":"codex","model":"gpt-5"}', 'full-access', 'default', 'archived', NULL, ${NOW}, ${NOW}, ${NOW}, NULL, NULL)`;
676 const numbers = new Map([
677 ["open", 1],
678 ["resumed", 2],
679 ["linked", 3],
680 ["settled", 4],
681 ["backfill", 5],
682 ["archived", 6],
683 ]);
684
685 // Startup, then two periodic passes. The startup backfill lookup fails,
686 // so the first periodic pass retries it from the full read.
687 const discover = (read: ProjectionSnapshotQueryShape["getShellSnapshot"]) =>
688 Effect.gen(function* () {
689 const online = yield* Ref.make(false);
690 const reads: Array<ReadonlyArray<string>> = [];
691 const fixture = yield* makeHarness({
692 threads: [],
693 getShellSnapshot: (options) =>
694 read(options).pipe(
695 Effect.tap((snapshot) =>
696 Effect.sync(() => reads.push(snapshot.threads.map(({ id }) => id).toSorted())),
697 ),
698 ),
699 branchPullRequest: ({ cwd, branch }) =>
700 Effect.gen(function* () {
701 if (branch === "backfill" && !(yield* Ref.get(online))) {
702 return yield* new GitManagerError({
703 operation: "branchPullRequest",
704 cwd,
705 detail: "Offline",
706 });
707 }
708 const number = numbers.get(branch);
709 return number === undefined ? null : branchPullRequest(number);
710 }),
711 });
712 return yield* Effect.gen(function* () {
713 const reactor = yield* fixture.start();
714 const startupCalls = (yield* Ref.get(fixture.branchCalls)).length;
715 const startupCommands = (yield* Ref.get(fixture.commands)).length;
716 yield* Ref.set(online, true);
717 for (let pass = 0; pass < 2; pass++) {
718 yield* TestClock.adjust("1 minute");
719 yield* Queue.take(fixture.reads);
720 yield* reactor.drain;
721 }
722 return {
723 reads,
724 branchCalls: (yield* Ref.get(fixture.branchCalls))
725 .slice(startupCalls)
726 .map(({ branch }) => branch)
727 .toSorted(),
728 commands: (yield* Ref.get(fixture.commands))
729 .slice(startupCommands)
730 .map(
731 ({ threadId, branchPullRequest }) => `${threadId} ${branchPullRequest?.number}`,
732 )
733 .toSorted(),
734 };
735 }).pipe(Effect.provide(fixture.layer));
736 }).pipe(Effect.scoped);
737
738 const { reads: unsettledReads, ...unsettled } = yield* discover(query.getShellSnapshot);
739 const { reads: fullReads, ...full } = yield* discover(() => query.getShellSnapshot());
740 expect(unsettled).toEqual(full);
741 expect(unsettled.commands).toEqual([
742 "backfill 5",
743 "open 1",
744 "open 1",
745 "resumed 2",
746 "resumed 2",
747 ]);
748 // The last pass has no backfill left, so it reads no settled thread.
749 expect(fullReads.at(-1)).toContain("imported");
750 expect(unsettledReads.at(-1)).toEqual(["linked", "open", "resumed"]);
751 }).pipe(
752 Effect.provide(
753 OrchestrationProjectionSnapshotQueryLive.pipe(
754 Layer.provide(ThreadBackgroundLiveness.layer),
755 Layer.provide(ThreadPlanProgress.layer),
756 Layer.provide(
757 Layer.succeed(RepositoryIdentityResolver, {
758 resolve: () => Effect.succeed(project.repositoryIdentity),
759 }),
760 ),
761 Layer.provideMerge(SqlitePersistenceMemory),
762 ),
763 ),
764 ),
765 );
766
767 it.effect("matches Azure SSH projects to HTTPS PRs with the provider repository selector", () =>
768 Effect.scoped(
769 Effect.gen(function* () {
770 const fixture = yield* makeHarness({
771 threads: [thread("azure")],
772 project: {
773 ...project,
774 repositoryIdentity: {
775 canonicalKey: "ssh.dev.azure.com/v3/org/project/repository",
776 displayName: "v3/org/project/repository",
777 name: "repository",
778 provider: "azure-devops",
779 rootPath: project.workspaceRoot,
780 locator: {
781 source: "git-remote",
782 remoteName: "origin",
783 remoteUrl: "git@ssh.dev.azure.com:v3/org/project/repository",
784 },
785 },
786 },
787 branchPullRequest: () =>
788 Effect.succeed({
789 ...branchPullRequest(),
790 repositoryKey: "dev.azure.com/org/project/_git/repository",
791 url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
792 }),
793 });
794 yield* Effect.gen(function* () {
795 yield* fixture.start();
796 expect((yield* Ref.get(fixture.commands))[0]?.branchPullRequest).toEqual({
797 projectId: PROJECT_ID,
798 repository: "repository",
799 number: 42,
800 url: "https://dev.azure.com/org/project/_git/repository/pullrequest/42",
801 });
802 }).pipe(Effect.provide(fixture.layer));
803 }),
804 ),
805 );
806
807 it.effect.each(["primary", "branch"] as const)(
808 "rejects the group's links if the %s remote changes during a summary read",
809 (changedRemote) =>
810 Effect.scoped(
811 Effect.gen(function* () {
812 const identity = yield* Ref.make(project.repositoryIdentity);
813 const detected = yield* Ref.make(branchPullRequest());
814 const fixture = yield* makeHarness({
815 threads: [thread("manual", { linkedPullRequest: reference(1) }), thread("automatic")],
816 branchPullRequest: () => Ref.get(detected),
817 resolveRepositoryIdentity: (_cwd, options) =>
818 options?.refresh ? Ref.get(identity) : Effect.succeed(project.repositoryIdentity),
819 summary: (input) =>
820 (changedRemote === "primary"
821 ? Ref.set(identity, {
822 ...project.repositoryIdentity,
823 canonicalKey: "github.com/other/repository",
824 displayName: "other/repository",
825 })
826 : Ref.set(detected, {
827 ...branchPullRequest(99),
828 repositoryKey: "github.com/other/repository",
829 url: "https://github.com/other/repository/pull/99",
830 })
831 ).pipe(Effect.as(summary(input, "merged"))),
832 });
833 yield* Effect.gen(function* () {
834 yield* fixture.start();
835 expect(yield* Ref.get(fixture.commands)).toEqual([]);
836 expect((yield* Ref.get(fixture.snapshots)).threads[0]?.linkedPullRequest).toEqual(
837 reference(1),
838 );
839 }).pipe(Effect.provide(fixture.layer));
840 }),
841 ),
842 );
843});