Open History to see the last commit
1import {
2 ProjectId,
3 ProviderInstanceId,
4 SourceControlProviderKind,
5 ThreadId,
6 type OrchestrationProjectShell,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ThreadShell,
9 type OrchestrationV2ServerCommand,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "@effect/vitest";
12import * as SecureRandom from "effect/crypto/SecureRandom";
13import * as DateTime from "effect/DateTime";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as PlatformError from "effect/PlatformError";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24
25import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
26import * as GitManager from "../git/GitManager.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
29import * as PullRequestService from "../pullRequest/PullRequestService.ts";
30import * as ServerActivation from "../serverActivation.ts";
31import * as ProjectionStore from "./ProjectionStore.ts";
32import * as SqlClient from "effect/sql/SqlClient";
33import * as SqlitePersistence from "../persistence/Sqlite.ts";
34import { EventId } from "@t3tools/contracts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ThreadPullRequestService from "./ThreadPullRequestService.ts";
37
38describe("ThreadPullRequestServiceV2 project guard", () => {
39 it("rejects a pull-request result when the project root changes before dispatch", () => {
40 const currentProject = Option.some({
41 workspaceRoot: "/workspace/replaced",
42 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
43
44 expect(
45 ThreadPullRequestService.projectWorkspaceMatchesSnapshot(
46 currentProject,
47 "/workspace/original",
48 ),
49 ).toBe(false);
50 });
51});
52
53describe("ThreadPullRequestServiceV2 reads", () => {
54 const NOW = DateTime.makeUnsafe("2026-09-20T00:00:00.000Z");
55 const threadShell = (id: string): OrchestrationV2ThreadShell => {
56 const threadId = ThreadId.make(id);
57 return {
58 id: threadId,
59 projectId: ProjectId.make("project-1"),
60 title: id,
61 providerInstanceId: ProviderInstanceId.make("codex"),
62 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
63 runtimeMode: "full-access",
64 interactionMode: "default",
65 branch: null,
66 worktreePath: null,
67 activeProviderThreadId: null,
68 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
69 forkedFrom: null,
70 createdBy: "user",
71 creationSource: "web",
72 activeRunId: null,
73 latestRunId: null,
74 status: "idle",
75 pendingRuntimeRequest: null,
76 latestVisibleMessage: null,
77 latestUserMessageAt: null,
78 hasActionableProposedPlan: false,
79 itemCount: 0,
80 visibleItemCount: 0,
81 createdAt: NOW,
82 updatedAt: NOW,
83 archivedAt: null,
84 settledOverride: null,
85 settledAt: null,
86 lastVisitedAt: null,
87 deletedAt: null,
88 };
89 };
90
91 it.effect("does not sweep branch pull requests while no client is connected", () =>
92 Effect.scoped(
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 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
135 resolve: () =>
136 Effect.succeed({
137 canonicalKey: "github.com/acme/project",
138 locator: {
139 source: "git-remote" as const,
140 remoteName: "origin",
141 remoteUrl: "git@github.com:acme/project.git",
142 },
143 provider: SourceControlProviderKind.make("github"),
144 owner: "acme",
145 name: "project",
146 }),
147 }),
148 // No client holds an activity lease.
149 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
150 shouldRunScopeWork: () => Effect.succeed(false),
151 shouldRunOpportunisticWork: Effect.succeed(false),
152 }),
153 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
154 Layer.succeed(
155 SecureRandom.SecureRandom,
156 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
157 ),
158 FileSystem.layerNoop({}),
159 Path.layer,
160 );
161 yield* Effect.gen(function* () {
162 const service = yield* ThreadPullRequestService.make;
163 yield* service.start();
164 yield* Deferred.succeed(activation, undefined);
165
166 // A finished turn still discovers the pull request for its branch.
167 yield* Queue.offer(domainEvents, {
168 type: "checkpoint.captured",
169 threadId: thread.id,
170 } as OrchestrationV2DomainEvent);
171 yield* Deferred.await(turnLookup);
172 yield* service.drain;
173 const lookupsBeforeIdle = lookups.length;
174
175 yield* TestClock.adjust("10 minutes");
176 yield* service.drain;
177
178 expect(lookups.slice(lookupsBeforeIdle)).toEqual([]);
179 }).pipe(Effect.provide(dependencies));
180 }),
181 ),
182 );
183
184 it.effect.each([
185 {
186 worktree: "a linked worktree",
187 existingPaths: ["/workspace/worktree", "/workspace/worktree/.git"],
188 unreadablePaths: [],
189 cwd: "/workspace/worktree",
190 },
191 // A folder that outlived its .git makes git fail with not_a_repository.
192 {
193 worktree: "a folder without .git",
194 existingPaths: ["/workspace/worktree"],
195 unreadablePaths: [],
196 cwd: "/workspace/project",
197 },
198 {
199 worktree: "a folder whose .git cannot be checked",
200 existingPaths: ["/workspace/worktree"],
201 unreadablePaths: ["/workspace/worktree/.git"],
202 cwd: "/workspace/worktree",
203 },
204 {
205 worktree: "a missing folder",
206 existingPaths: [],
207 unreadablePaths: [],
208 cwd: "/workspace/project",
209 },
210 ] as const)(
211 "looks up a branch whose worktree is $worktree in $cwd",
212 ({ existingPaths, unreadablePaths, cwd }) =>
213 Effect.scoped(
214 Effect.gen(function* () {
215 const thread = {
216 ...threadShell("worktree-thread"),
217 settledOverride: "settled" as const,
218 settledAt: NOW,
219 branch: "feature/worktree",
220 worktreePath: "/workspace/worktree",
221 };
222 const project: OrchestrationProjectShell = {
223 id: thread.projectId,
224 title: "Project",
225 workspaceRoot: "/workspace/project",
226 defaultModelSelection: null,
227 scripts: [],
228 createdAt: "2026-08-01T00:00:00.000Z",
229 updatedAt: "2026-08-01T00:00:00.000Z",
230 };
231 const activation = yield* Deferred.make<void>();
232 const sweepStarted = yield* Deferred.make<void>();
233 const lookupCwds: Array<string> = [];
234 const dependencies = Layer.mergeAll(
235 Layer.mock(Orchestrator.OrchestratorV2)({
236 streamDomainEvents: Stream.never,
237 getPullRequestSnapshot: () =>
238 Deferred.succeed(sweepStarted, undefined).pipe(
239 Effect.as({
240 schemaVersion: 2,
241 snapshotSequence: 1,
242 threads: [thread],
243 archivedThreads: [],
244 }),
245 ),
246 }),
247 Layer.mock(ProjectStore.ProjectStoreV2)({
248 listShells: () => Effect.succeed([project]),
249 getShell: () => Effect.succeedSome(project),
250 }),
251 Layer.mock(GitManager.GitManager)({
252 branchPullRequest: (input) =>
253 Effect.sync(() => {
254 lookupCwds.push(input.cwd);
255 return null;
256 }),
257 }),
258 Layer.mock(PullRequestService.PullRequestService)({}),
259 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
260 resolve: () =>
261 Effect.succeed({
262 canonicalKey: "github.com/acme/project",
263 locator: {
264 source: "git-remote" as const,
265 remoteName: "origin",
266 remoteUrl: "git@github.com:acme/project.git",
267 },
268 provider: SourceControlProviderKind.make("github"),
269 owner: "acme",
270 name: "project",
271 }),
272 }),
273 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
274 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
275 Layer.succeed(
276 SecureRandom.SecureRandom,
277 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
278 ),
279 FileSystem.layerNoop({
280 exists: (path) =>
281 unreadablePaths.some((entry) => entry === path)
282 ? Effect.fail(
283 PlatformError.systemError({
284 _tag: "PermissionDenied",
285 module: "FileSystem",
286 method: "exists",
287 pathOrDescriptor: path,
288 }),
289 )
290 : Effect.succeed(existingPaths.some((entry) => entry === path)),
291 }),
292 Path.layer,
293 );
294 yield* Effect.gen(function* () {
295 const service = yield* ThreadPullRequestService.make;
296 yield* service.start();
297 yield* Deferred.succeed(activation, undefined);
298 yield* Deferred.await(sweepStarted);
299 yield* service.drain;
300 }).pipe(Effect.provide(dependencies));
301
302 expect(lookupCwds).toEqual([cwd]);
303 }),
304 ),
305 );
306
307 it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
308 Effect.scoped(
309 Effect.gen(function* () {
310 const parent = {
311 ...threadShell("parent-thread"),
312 branch: "feature/parent",
313 worktreePath: "/workspace/parent",
314 };
315 const child: OrchestrationV2ThreadShell = {
316 ...threadShell("child-thread"),
317 branch: "t3/reply-ok",
318 worktreePath: "/workspace/child",
319 lineage: {
320 rootThreadId: parent.id,
321 parentThreadId: parent.id,
322 relationshipToParent: "subagent",
323 },
324 };
325 const project: OrchestrationProjectShell = {
326 id: parent.projectId,
327 title: "Project",
328 workspaceRoot: "/workspace/project",
329 defaultModelSelection: null,
330 scripts: [],
331 createdAt: "2026-08-01T00:00:00.000Z",
332 updatedAt: "2026-08-01T00:00:00.000Z",
333 };
334 const activation = yield* Deferred.make<void>();
335 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
336 const sweeps = yield* Queue.unbounded<void>();
337 const childLookup = yield* Deferred.make<void>();
338 const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
339 const dependencies = Layer.mergeAll(
340 Layer.mock(Orchestrator.OrchestratorV2)({
341 streamDomainEvents: Stream.fromQueue(domainEvents),
342 getPullRequestSnapshot: ({ threadId }) =>
343 threadId !== undefined
344 ? Effect.succeed({ snapshotSequence: 1, threads: [child] })
345 : Queue.offer(sweeps, undefined).pipe(
346 Effect.as({
347 schemaVersion: 2,
348 snapshotSequence: 1,
349 threads: [parent, child],
350 archivedThreads: [],
351 }),
352 ),
353 }),
354 Layer.mock(ProjectStore.ProjectStoreV2)({
355 listShells: () => Effect.succeed([project]),
356 getShell: () => Effect.succeedSome(project),
357 }),
358 Layer.mock(GitManager.GitManager)({
359 branchPullRequest: (input, options) =>
360 Effect.gen(function* () {
361 const refresh = options?.refresh ?? false;
362 lookups.push({ branch: input.branch, refresh });
363 if (input.branch === child.branch && refresh) {
364 yield* Deferred.succeed(childLookup, undefined);
365 }
366 return null;
367 }),
368 }),
369 Layer.mock(PullRequestService.PullRequestService)({}),
370 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
371 resolve: () =>
372 Effect.succeed({
373 canonicalKey: "github.com/acme/project",
374 locator: {
375 source: "git-remote" as const,
376 remoteName: "origin",
377 remoteUrl: "git@github.com:acme/project.git",
378 },
379 provider: SourceControlProviderKind.make("github"),
380 owner: "acme",
381 name: "project",
382 }),
383 }),
384 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
385 shouldRunScopeWork: () => Effect.succeed(true),
386 shouldRunOpportunisticWork: Effect.succeed(true),
387 }),
388 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
389 Layer.succeed(
390 SecureRandom.SecureRandom,
391 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
392 ),
393 FileSystem.layerNoop({}),
394 Path.layer,
395 );
396 yield* Effect.gen(function* () {
397 const service = yield* ThreadPullRequestService.make;
398 yield* service.start();
399 yield* Deferred.succeed(activation, undefined);
400
401 // Startup backfill sweep, then one periodic sweep.
402 yield* Queue.take(sweeps);
403 yield* service.drain;
404 yield* TestClock.adjust("1 minute");
405 yield* Queue.take(sweeps);
406 yield* service.drain;
407 const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
408
409 // The child's own turn still discovers its pull request.
410 yield* Queue.offer(domainEvents, {
411 type: "checkpoint.captured",
412 threadId: child.id,
413 } as OrchestrationV2DomainEvent);
414 yield* Deferred.await(childLookup);
415 yield* service.drain;
416
417 expect(sweepLookups).toEqual([parent.branch, parent.branch]);
418 expect(lookups.slice(sweepLookups.length)).toEqual([
419 { branch: child.branch, refresh: true },
420 ]);
421 }).pipe(Effect.provide(dependencies));
422 }),
423 ),
424 );
425
426 it.effect.each([
427 { state: "closed", sameBranch: false },
428 { state: "merged", sameBranch: false },
429 { state: "closed", sameBranch: true },
430 { state: "merged", sameBranch: true },
431 ] as const)(
432 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
433 ({ state, sameBranch }) =>
434 Effect.scoped(
435 Effect.gen(function* () {
436 const savedReference = {
437 projectId: ProjectId.make("project-1"),
438 repository: "acme/project",
439 number: 42,
440 url: "https://github.com/acme/project/pull/42",
441 };
442 const thread = {
443 ...threadShell("branch-pr-thread"),
444 branch: "main",
445 branchPullRequest: savedReference,
446 linkedPullRequest: savedReference,
447 };
448 const project: OrchestrationProjectShell = {
449 id: thread.projectId,
450 title: "Project",
451 workspaceRoot: "/workspace/project",
452 defaultModelSelection: null,
453 scripts: [],
454 createdAt: "2026-08-01T00:00:00.000Z",
455 updatedAt: "2026-08-01T00:00:00.000Z",
456 };
457 const activation = yield* Deferred.make<void>();
458 const sweepStarted = yield* Deferred.make<void>();
459 const commands: Array<OrchestrationV2ServerCommand> = [];
460 const dependencies = Layer.mergeAll(
461 Layer.mock(Orchestrator.OrchestratorV2)({
462 streamDomainEvents: Stream.never,
463 getPullRequestSnapshot: (options) =>
464 Effect.gen(function* () {
465 const store = yield* ProjectionStore.ProjectionStoreV2;
466 yield* store.apply({
467 id: EventId.make(`event:${thread.id}:created`),
468 type: "thread.created",
469 threadId: thread.id,
470 occurredAt: NOW,
471 payload: { ...thread, lastVisitedAt: thread.lastVisitedAt ?? null },
472 });
473 const sql = yield* SqlClient.SqlClient;
474 yield* sql`INSERT INTO orchestration_events (
475 sequence, event_id, aggregate_kind, stream_id, stream_version, event_type,
476 occurred_at, actor_kind, payload_json, metadata_json, application_event_version
477 ) VALUES (7, 'pr-discovery', 'thread', ${thread.id}, 1, 'thread.created',
478 '2026-09-20T00:00:00.000Z', 'system', '{}', '{}', 2)`;
479 for (const table of [
480 "orchestration_v2_projection_turn_items",
481 "orchestration_v2_projection_messages",
482 "orchestration_v2_projection_provider_threads",
483 "orchestration_v2_projection_runs",
484 ])
485 yield* sql.unsafe(`DROP TABLE ${table}`);
486 const snapshot = yield* store.getPullRequestSnapshot(options);
487 yield* Deferred.succeed(sweepStarted, undefined);
488 return snapshot;
489 }).pipe(
490 Effect.provide(
491 ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
492 ),
493 Effect.orDie,
494 ),
495 dispatch: (command) =>
496 Effect.sync(() => {
497 commands.push(command);
498 return { sequence: 2, storedEvents: [] };
499 }),
500 }),
501 Layer.mock(ProjectStore.ProjectStoreV2)({
502 listShells: () => Effect.succeed([project]),
503 getShell: () => Effect.succeedSome(project),
504 }),
505 Layer.mock(GitManager.GitManager)({
506 branchPullRequest: () => Effect.succeed(null),
507 }),
508 Layer.mock(PullRequestService.PullRequestService)({
509 summary: () =>
510 Effect.succeed({
511 ...savedReference,
512 provider: SourceControlProviderKind.make("github"),
513 title: "Previous branch work",
514 state,
515 headBranch: sameBranch ? thread.branch : "feature/previous-work",
516 baseBranch: "release",
517 updatedAt: "2026-09-19T00:00:00.000Z",
518 }),
519 }),
520 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
521 resolve: () =>
522 Effect.succeed({
523 canonicalKey: "github.com/acme/project",
524 locator: {
525 source: "git-remote" as const,
526 remoteName: "origin",
527 remoteUrl: "git@github.com:acme/project.git",
528 },
529 provider: SourceControlProviderKind.make("github"),
530 owner: "acme",
531 name: "project",
532 }),
533 }),
534 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
535 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
536 Layer.succeed(
537 SecureRandom.SecureRandom,
538 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
539 ),
540 FileSystem.layerNoop({}),
541 Path.layer,
542 );
543 yield* Effect.gen(function* () {
544 const service = yield* ThreadPullRequestService.make;
545 yield* service.start();
546 yield* Deferred.succeed(activation, undefined);
547 yield* Deferred.await(sweepStarted);
548 yield* service.drain;
549 }).pipe(Effect.provide(dependencies));
550
551 if (sameBranch) {
552 expect(commands).toEqual([]);
553 } else {
554 expect(commands).toHaveLength(1);
555 expect(commands[0]).toMatchObject({
556 type: "thread.pull-request.sync",
557 threadId: thread.id,
558 snapshotSequence: 7,
559 expected: {
560 workspaceRoot: project.workspaceRoot,
561 branch: thread.branch,
562 worktreePath: thread.worktreePath,
563 linkedPullRequest: savedReference,
564 branchPullRequest: savedReference,
565 },
566 branchPullRequest: null,
567 });
568 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
569 }
570 }),
571 ),
572 );
573});