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