The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeV8 from "node:v8"; |
| 2 | |
| 3 | import { SourceControlProviderKind } from "@t3tools/contracts"; |
| 4 | import * as Stream from "effect/Stream"; |
| 5 | import { |
| 6 | EventId, |
| 7 | MessageId, |
| 8 | ProjectId, |
| 9 | ProviderInstanceId, |
| 10 | PullRequestOperationError, |
| 11 | PullRequestUnavailableError, |
| 12 | RunId, |
| 13 | ThreadId, |
| 14 | TurnItemId, |
| 15 | type OrchestrationV2Command as OrchestrationCommand, |
| 16 | type OrchestrationV2InternalCommand, |
| 17 | type OrchestrationV2DomainEvent, |
| 18 | type OrchestrationV2Run, |
| 19 | type OrchestrationProjectShell, |
| 20 | type PullRequestRef, |
| 21 | type PullRequestStack, |
| 22 | type PullRequestSummary, |
| 23 | type ThreadPullRequestKey, |
| 24 | type ThreadPullRequestLink, |
| 25 | type ThreadPullRequestSnapshot, |
| 26 | } from "@t3tools/contracts"; |
| 27 | import { assert, describe, it } from "@effect/vitest"; |
| 28 | import * as Cache from "effect/Cache"; |
| 29 | import * as Clock from "effect/Clock"; |
| 30 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 31 | import * as DateTime from "effect/DateTime"; |
| 32 | import * as Deferred from "effect/Deferred"; |
| 33 | import * as Duration from "effect/Duration"; |
| 34 | import * as Effect from "effect/Effect"; |
| 35 | import * as Fiber from "effect/Fiber"; |
| 36 | import * as Layer from "effect/Layer"; |
| 37 | import * as Queue from "effect/Queue"; |
| 38 | import * as Ref from "effect/Ref"; |
| 39 | import { ChildProcessSpawner } from "effect/process"; |
| 40 | import { TestClock } from "effect/testing"; |
| 41 | |
| 42 | import * as GitManager from "../git/GitManager.ts"; |
| 43 | import * as ProcessRunner from "../processRunner.ts"; |
| 44 | import * as PullRequestService from "../pullRequest/PullRequestService.ts"; |
| 45 | import * as ServerActivation from "../serverActivation.ts"; |
| 46 | import * as VcsProcess from "../vcs/VcsProcess.ts"; |
| 47 | import * as Orchestrator from "./Orchestrator.ts"; |
| 48 | import * as ProjectionStore from "./ProjectionStore.ts"; |
| 49 | import * as PullRequestSyncReactor from "./PullRequestSyncReactor.ts"; |
| 50 | import { type PullRequestTestThread, v2PullRequestThread } from "./testkit/pullRequestFixtures.ts"; |
| 51 | |
| 52 | const NOW = "2026-08-28T12:00:00.000Z"; |
| 53 | const PROJECT_ID = ProjectId.make("sync-project"); |
| 54 | |
| 55 | type SyncCommand = Extract< |
| 56 | OrchestrationCommand, |
| 57 | { readonly type: "thread.pull-request-link.sync" } |
| 58 | >; |
| 59 | type LinkCommand = Extract<OrchestrationCommand, { readonly type: "thread.pull-request.link" }>; |
| 60 | type ChecksReopenCommand = Extract< |
| 61 | OrchestrationV2InternalCommand, |
| 62 | { readonly type: "thread.pull-request-watch.checks-reopen" } |
| 63 | >; |
| 64 | |
| 65 | const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(1)); |
| 66 | |
| 67 | function makeProject(id: ProjectId = PROJECT_ID): OrchestrationProjectShell { |
| 68 | return { |
| 69 | id, |
| 70 | title: `Project ${id}`, |
| 71 | workspaceRoot: "/workspace/project", |
| 72 | defaultModelSelection: null, |
| 73 | scripts: [], |
| 74 | createdAt: "2026-08-01T00:00:00.000Z", |
| 75 | updatedAt: NOW, |
| 76 | }; |
| 77 | } |
| 78 | |
| 79 | function makeThread( |
| 80 | id: string, |
| 81 | overrides: Partial<PullRequestTestThread> = {}, |
| 82 | ): PullRequestTestThread { |
| 83 | return { |
| 84 | id: ThreadId.make(id), |
| 85 | projectId: PROJECT_ID, |
| 86 | title: id, |
| 87 | modelSelection: { |
| 88 | instanceId: ProviderInstanceId.make("codex"), |
| 89 | model: "gpt-5", |
| 90 | }, |
| 91 | runtimeMode: "full-access", |
| 92 | interactionMode: "default", |
| 93 | branch: null, |
| 94 | worktreePath: null, |
| 95 | pullRequests: [], |
| 96 | createdAt: "2026-08-01T00:00:00.000Z", |
| 97 | updatedAt: "2026-08-20T00:00:00.000Z", |
| 98 | archivedAt: null, |
| 99 | settledOverride: null, |
| 100 | settledAt: null, |
| 101 | latestUserMessageAt: "2026-08-20T00:00:00.000Z", |
| 102 | ...overrides, |
| 103 | }; |
| 104 | } |
| 105 | |
| 106 | function makeLink( |
| 107 | number: number, |
| 108 | snapshot: Partial<ThreadPullRequestSnapshot> | null = null, |
| 109 | overrides: Partial<ThreadPullRequestLink> = {}, |
| 110 | ): ThreadPullRequestLink { |
| 111 | return { |
| 112 | host: "github.com", |
| 113 | repository: "owner/repository", |
| 114 | number, |
| 115 | url: `https://github.com/owner/repository/pull/${number}`, |
| 116 | source: "manual", |
| 117 | linkedAt: "2026-08-10T00:00:00.000Z", |
| 118 | snapshot: |
| 119 | snapshot === null |
| 120 | ? null |
| 121 | : { |
| 122 | state: "open", |
| 123 | title: "Pull request", |
| 124 | headBranch: "feature", |
| 125 | baseBranch: "main", |
| 126 | isDraft: false, |
| 127 | updatedAt: "2026-08-27T00:00:00.000Z", |
| 128 | syncedAt: "2026-08-27T00:00:00.000Z", |
| 129 | ...snapshot, |
| 130 | }, |
| 131 | stack: null, |
| 132 | ...overrides, |
| 133 | }; |
| 134 | } |
| 135 | |
| 136 | interface TestShellSnapshot { |
| 137 | readonly snapshotSequence: number; |
| 138 | readonly projects: ReadonlyArray<OrchestrationProjectShell>; |
| 139 | readonly threads: ReadonlyArray<PullRequestTestThread>; |
| 140 | readonly updatedAt: string; |
| 141 | } |
| 142 | |
| 143 | function makeSnapshot( |
| 144 | threads: ReadonlyArray<PullRequestTestThread>, |
| 145 | snapshotSequence = 1, |
| 146 | ): TestShellSnapshot { |
| 147 | return { |
| 148 | snapshotSequence, |
| 149 | projects: [makeProject()], |
| 150 | threads, |
| 151 | updatedAt: NOW, |
| 152 | }; |
| 153 | } |
| 154 | |
| 155 | function makeSummary( |
| 156 | input: PullRequestRef, |
| 157 | overrides: Partial<PullRequestSummary> = {}, |
| 158 | ): PullRequestSummary { |
| 159 | return { |
| 160 | provider: SourceControlProviderKind.make("github"), |
| 161 | projectId: input.projectId, |
| 162 | repository: input.repository, |
| 163 | number: input.number, |
| 164 | title: "Pull request", |
| 165 | url: `https://github.com/${input.repository}/pull/${input.number}`, |
| 166 | state: "open", |
| 167 | headBranch: "feature", |
| 168 | baseBranch: "main", |
| 169 | updatedAt: "2026-08-27T00:00:00.000Z", |
| 170 | ...overrides, |
| 171 | }; |
| 172 | } |
| 173 | |
| 174 | const missingSummary = Effect.fail( |
| 175 | new PullRequestOperationError({ |
| 176 | operation: "summary", |
| 177 | detail: "Pull request not found", |
| 178 | reason: "not-found", |
| 179 | }), |
| 180 | ); |
| 181 | |
| 182 | interface HarnessOptions { |
| 183 | readonly invalidate?: PullRequestService.PullRequestService["Service"]["invalidate"]; |
| 184 | readonly batchesReads?: (input: PullRequestRef) => boolean; |
| 185 | readonly snapshot: TestShellSnapshot; |
| 186 | readonly summary?: ( |
| 187 | input: PullRequestRef, |
| 188 | ) => Effect.Effect<PullRequestSummary, PullRequestService.PullRequestError>; |
| 189 | readonly stack?: ( |
| 190 | input: PullRequestRef, |
| 191 | ) => Effect.Effect<PullRequestStack | null, PullRequestOperationError>; |
| 192 | readonly onSync?: (command: SyncCommand) => Effect.Effect<unknown>; |
| 193 | } |
| 194 | |
| 195 | const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: HarnessOptions) { |
| 196 | const activation = yield* Deferred.make<void>(); |
| 197 | const snapshots = yield* Ref.make(options.snapshot); |
| 198 | const snapshotReads = yield* Queue.unbounded<void>(); |
| 199 | const shellSnapshotReads = yield* Ref.make(0); |
| 200 | const syncCommands = yield* Ref.make<ReadonlyArray<SyncCommand>>([]); |
| 201 | const linkCommands = yield* Ref.make<ReadonlyArray<LinkCommand>>([]); |
| 202 | const reopenCommands = yield* Queue.unbounded<ChecksReopenCommand>(); |
| 203 | const summaryCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]); |
| 204 | const stackCalls = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]); |
| 205 | const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>(); |
| 206 | const stateChanges = yield* Queue.unbounded<ThreadPullRequestKey>(); |
| 207 | |
| 208 | const summary: PullRequestService.PullRequestService["Service"]["summary"] = ( |
| 209 | input, |
| 210 | readOptions, |
| 211 | ) => |
| 212 | Effect.gen(function* () { |
| 213 | assert.strictEqual(readOptions?.recoverTransientFailure, false); |
| 214 | yield* Ref.update(summaryCalls, (calls) => [...calls, input]); |
| 215 | return yield* options.summary?.(input) ?? Effect.succeed(makeSummary(input)); |
| 216 | }); |
| 217 | |
| 218 | const stack: PullRequestService.PullRequestService["Service"]["stack"] = (input, readOptions) => |
| 219 | Effect.gen(function* () { |
| 220 | assert.strictEqual(readOptions?.includeDetails, false); |
| 221 | yield* Ref.update(stackCalls, (calls) => [...calls, input]); |
| 222 | return yield* options.stack?.(input) ?? Effect.succeed(null); |
| 223 | }); |
| 224 | |
| 225 | const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) => { |
| 226 | if (command.type === "thread.pull-request-link.sync") { |
| 227 | return Ref.update(syncCommands, (recorded) => [...recorded, command]).pipe( |
| 228 | Effect.andThen(options.onSync?.(command) ?? Effect.void), |
| 229 | Effect.as({ sequence: 1, storedEvents: [] }), |
| 230 | ); |
| 231 | } |
| 232 | if (command.type === "thread.pull-request.link") { |
| 233 | return Ref.update(linkCommands, (recorded) => [...recorded, command]).pipe( |
| 234 | Effect.as({ sequence: 1, storedEvents: [] }), |
| 235 | ); |
| 236 | } |
| 237 | if (command.type === "thread.pull-request-watch.checks-reopen") { |
| 238 | return Queue.offer(reopenCommands, command).pipe( |
| 239 | Effect.as({ sequence: 1, storedEvents: [] }), |
| 240 | ); |
| 241 | } |
| 242 | return Effect.die(new Error(`Unexpected command: ${command.type}`)); |
| 243 | }; |
| 244 | |
| 245 | const layerDependencies = Layer.mergeAll( |
| 246 | Layer.mock(PullRequestService.PullRequestService)({ |
| 247 | withSharedProjectReads: (effect) => effect, |
| 248 | batchesReads: (input) => Effect.succeed(options.batchesReads?.(input) ?? true), |
| 249 | summary, |
| 250 | stack, |
| 251 | invalidate: options.invalidate ?? (() => Effect.void), |
| 252 | subscribeStateChanges: Effect.succeed(Stream.fromQueue(stateChanges)), |
| 253 | }), |
| 254 | Layer.mock(GitManager.GitManager)({ |
| 255 | subscribePullRequestStateChanges: Effect.succeed(Stream.empty), |
| 256 | }), |
| 257 | Layer.mock(ProjectionStore.ProjectionStoreV2)({ |
| 258 | getThreadsWithPullRequests: (threadId) => |
| 259 | Queue.offer(snapshotReads, undefined).pipe( |
| 260 | Effect.andThen(Ref.get(snapshots)), |
| 261 | Effect.map((snapshot) => |
| 262 | snapshot.threads |
| 263 | .filter( |
| 264 | (thread) => |
| 265 | (threadId === undefined || thread.id === threadId) && |
| 266 | thread.archivedAt === null && |
| 267 | thread.pullRequests.length > 0, |
| 268 | ) |
| 269 | .map((thread) => ({ |
| 270 | id: thread.id, |
| 271 | projectId: thread.projectId, |
| 272 | lineage: { |
| 273 | parentThreadId: null, |
| 274 | relationshipToParent: null, |
| 275 | rootThreadId: thread.id, |
| 276 | }, |
| 277 | settledOverride: thread.settledOverride, |
| 278 | settledAt: thread.settledAt === null ? null : DateTime.makeUnsafe(thread.settledAt), |
| 279 | pullRequests: thread.pullRequests, |
| 280 | })), |
| 281 | ), |
| 282 | ), |
| 283 | }), |
| 284 | Layer.mock(Orchestrator.OrchestratorV2)({ |
| 285 | getShellSnapshot: () => |
| 286 | Ref.update(shellSnapshotReads, (count) => count + 1).pipe( |
| 287 | Effect.andThen(Effect.die(new Error("pull request sync must not read the shell"))), |
| 288 | ), |
| 289 | dispatch, |
| 290 | streamDomainEvents: Stream.fromQueue(domainEvents), |
| 291 | }), |
| 292 | Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)), |
| 293 | Layer.succeed(SecureRandom.SecureRandom, testCrypto), |
| 294 | ); |
| 295 | |
| 296 | return { |
| 297 | activation, |
| 298 | snapshots, |
| 299 | snapshotReads, |
| 300 | shellSnapshotReads, |
| 301 | syncCommands, |
| 302 | linkCommands, |
| 303 | reopenCommands, |
| 304 | summaryCalls, |
| 305 | stackCalls, |
| 306 | domainEvents, |
| 307 | stateChanges, |
| 308 | layer: PullRequestSyncReactor.layer.pipe(Layer.provide(layerDependencies)), |
| 309 | }; |
| 310 | }); |
| 311 | |
| 312 | type Harness = Effect.Success<ReturnType<typeof makeHarness>>; |
| 313 | |
| 314 | const startAndSweep = Effect.fn("startPullRequestSyncHarness")(function* (fixture: Harness) { |
| 315 | const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor; |
| 316 | yield* reactor.start(); |
| 317 | yield* Deferred.succeed(fixture.activation, undefined); |
| 318 | yield* Queue.take(fixture.snapshotReads); |
| 319 | yield* reactor.drain; |
| 320 | return reactor; |
| 321 | }); |
| 322 | |
| 323 | const sweepAgain = Effect.fn("sweepPullRequestSyncHarness")(function* ( |
| 324 | fixture: Harness, |
| 325 | reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"], |
| 326 | ) { |
| 327 | yield* TestClock.adjust("1 minute"); |
| 328 | yield* Queue.take(fixture.snapshotReads); |
| 329 | yield* reactor.drain; |
| 330 | }); |
| 331 | |
| 332 | const sweepFor = Effect.fn("sweepPullRequestSyncHarnessFor")(function* ( |
| 333 | fixture: Harness, |
| 334 | reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"], |
| 335 | minutes: number, |
| 336 | ) { |
| 337 | for (let minute = 0; minute < minutes; minute++) yield* sweepAgain(fixture, reactor); |
| 338 | }); |
| 339 | |
| 340 | const failingGitLabLink = makeLink(13, null, { |
| 341 | host: "gitlab.com", |
| 342 | url: "https://gitlab.com/owner/repository/-/merge_requests/13", |
| 343 | }); |
| 344 | |
| 345 | const gitLabCliFailure = new PullRequestOperationError({ |
| 346 | operation: "summary", |
| 347 | detail: "GitLab CLI command failed", |
| 348 | }); |
| 349 | |
| 350 | function runUpdated( |
| 351 | threadId: ThreadId, |
| 352 | status: OrchestrationV2Run["status"], |
| 353 | ): OrchestrationV2DomainEvent { |
| 354 | const runId = RunId.make(`run:${threadId}:1`); |
| 355 | const at = DateTime.makeUnsafe(NOW); |
| 356 | return { |
| 357 | type: "run.updated", |
| 358 | id: EventId.make(`event:${threadId}:${status}`), |
| 359 | threadId, |
| 360 | runId, |
| 361 | occurredAt: at, |
| 362 | payload: { |
| 363 | id: runId, |
| 364 | threadId, |
| 365 | ordinal: 1, |
| 366 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 367 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, |
| 368 | providerThreadId: null, |
| 369 | userMessageId: MessageId.make(`message:${threadId}:1`), |
| 370 | rootNodeId: null, |
| 371 | activeAttemptId: null, |
| 372 | status, |
| 373 | requestedAt: at, |
| 374 | startedAt: at, |
| 375 | completedAt: at, |
| 376 | checkpointId: null, |
| 377 | contextHandoffId: null, |
| 378 | }, |
| 379 | }; |
| 380 | } |
| 381 | |
| 382 | function commandRan( |
| 383 | threadId: ThreadId, |
| 384 | input: string, |
| 385 | output?: string, |
| 386 | name = "command", |
| 387 | ): OrchestrationV2DomainEvent { |
| 388 | const runId = RunId.make(`run:${threadId}:1`); |
| 389 | const at = DateTime.makeUnsafe(NOW); |
| 390 | return { |
| 391 | type: "turn-item.updated", |
| 392 | id: EventId.make(`event:${threadId}:${name}`), |
| 393 | threadId, |
| 394 | runId, |
| 395 | occurredAt: at, |
| 396 | payload: { |
| 397 | id: TurnItemId.make(`item:${threadId}:${name}`), |
| 398 | threadId, |
| 399 | runId, |
| 400 | nodeId: null, |
| 401 | providerThreadId: null, |
| 402 | providerTurnId: null, |
| 403 | nativeItemRef: null, |
| 404 | parentItemId: null, |
| 405 | ordinal: 1, |
| 406 | status: "completed", |
| 407 | title: null, |
| 408 | startedAt: at, |
| 409 | completedAt: at, |
| 410 | updatedAt: at, |
| 411 | type: "command_execution", |
| 412 | input, |
| 413 | ...(output === undefined ? {} : { output }), |
| 414 | }, |
| 415 | }; |
| 416 | } |
| 417 | |
| 418 | function applySync( |
| 419 | snapshot: TestShellSnapshot, |
| 420 | commands: ReadonlyArray<SyncCommand>, |
| 421 | ): TestShellSnapshot { |
| 422 | return { |
| 423 | ...snapshot, |
| 424 | snapshotSequence: snapshot.snapshotSequence + 1, |
| 425 | threads: snapshot.threads.map((thread) => ({ |
| 426 | ...thread, |
| 427 | pullRequests: thread.pullRequests.map((link) => { |
| 428 | const command = commands.findLast( |
| 429 | (candidate) => candidate.threadId === thread.id && candidate.number === link.number, |
| 430 | ); |
| 431 | return command === undefined |
| 432 | ? link |
| 433 | : { ...link, snapshot: command.snapshot, stack: command.stack }; |
| 434 | }), |
| 435 | })), |
| 436 | }; |
| 437 | } |
| 438 | |
| 439 | const stackLayer = (number: number) => ({ |
| 440 | number, |
| 441 | headBranch: `layer-${number}`, |
| 442 | state: "open" as const, |
| 443 | }); |
| 444 | |
| 445 | /** |
| 446 | * Stack 80 starts as #18 and #20; `grow` pushes #83 on top. `cachedRead` behaves like |
| 447 | * `PullRequestReadCache`: a read is kept for 60 s and invalidating the reference drops it. |
| 448 | */ |
| 449 | function makeGrowingStack() { |
| 450 | let layers = [stackLayer(18), stackLayer(20)]; |
| 451 | const entries = new Map<number, { readonly layers: typeof layers; expiresAt: number }>(); |
| 452 | const invalidated: Array<number> = []; |
| 453 | const stackOf = (stackLayers: typeof layers): PullRequestStack => ({ |
| 454 | id: "stack-80", |
| 455 | number: 80, |
| 456 | url: "https://github.com/owner/repository/stack/80", |
| 457 | base: "main", |
| 458 | layers: stackLayers, |
| 459 | }); |
| 460 | return { |
| 461 | invalidated, |
| 462 | grow: () => { |
| 463 | layers = [...layers, stackLayer(83)]; |
| 464 | }, |
| 465 | read: () => Effect.sync(() => stackOf(layers)), |
| 466 | invalidate: (({ reference }) => |
| 467 | Effect.sync(() => { |
| 468 | invalidated.push(reference?.number ?? -1); |
| 469 | entries.delete(reference?.number ?? -1); |
| 470 | })) satisfies PullRequestService.PullRequestService["Service"]["invalidate"], |
| 471 | cachedRead: (input: PullRequestRef) => |
| 472 | Clock.currentTimeMillis.pipe( |
| 473 | Effect.map((now) => { |
| 474 | let entry = entries.get(input.number); |
| 475 | if (entry === undefined || entry.expiresAt <= now) { |
| 476 | entry = { layers, expiresAt: now + 60_000 }; |
| 477 | entries.set(input.number, entry); |
| 478 | } |
| 479 | return stackOf(entry.layers); |
| 480 | }), |
| 481 | ), |
| 482 | }; |
| 483 | } |
| 484 | |
| 485 | const applyRecordedSyncs = (fixture: Harness) => |
| 486 | Ref.get(fixture.syncCommands).pipe( |
| 487 | Effect.flatMap((commands) => |
| 488 | Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)), |
| 489 | ), |
| 490 | ); |
| 491 | |
| 492 | const linkPullRequest83 = (fixture: Harness) => |
| 493 | Ref.update(fixture.snapshots, (snapshot) => ({ |
| 494 | ...snapshot, |
| 495 | threads: snapshot.threads.map((thread) => ({ |
| 496 | ...thread, |
| 497 | pullRequests: [...thread.pullRequests, makeLink(83)], |
| 498 | })), |
| 499 | })); |
| 500 | |
| 501 | const storedStackLayers = (fixture: Harness) => |
| 502 | Ref.get(fixture.snapshots).pipe( |
| 503 | Effect.map((snapshot) => |
| 504 | snapshot.threads[0]!.pullRequests.map((link) => [ |
| 505 | link.number, |
| 506 | link.stack?.layers.map((layer) => layer.number), |
| 507 | ]), |
| 508 | ), |
| 509 | ); |
| 510 | |
| 511 | const requestAndApply = Effect.fn("requestPullRequestSyncHarness")(function* ( |
| 512 | fixture: Harness, |
| 513 | reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"], |
| 514 | number: number, |
| 515 | ) { |
| 516 | yield* reactor.requestSync({ host: "github.com", repository: "owner/repository", number }); |
| 517 | yield* Queue.take(fixture.snapshotReads); |
| 518 | yield* reactor.drain; |
| 519 | yield* applyRecordedSyncs(fixture); |
| 520 | }); |
| 521 | |
| 522 | /** A thread with an open pull request whose merge command marks the end of earlier events. */ |
| 523 | const MERGING_THREAD = ThreadId.make("merging"); |
| 524 | |
| 525 | /** The link commands `events` dispatch, read once the reactor has handled them all. */ |
| 526 | const linksFrom = Effect.fn("linksFrom")(function* ( |
| 527 | fixture: Harness, |
| 528 | reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"], |
| 529 | events: ReadonlyArray<OrchestrationV2DomainEvent>, |
| 530 | ) { |
| 531 | yield* Ref.set(fixture.linkCommands, []); |
| 532 | yield* Queue.offerAll(fixture.domainEvents, [ |
| 533 | ...events, |
| 534 | commandRan(MERGING_THREAD, "gh pr merge 7", undefined, "merge"), |
| 535 | ]); |
| 536 | yield* Queue.take(fixture.snapshotReads); |
| 537 | yield* Queue.take(fixture.snapshotReads); |
| 538 | yield* reactor.drain; |
| 539 | return yield* Ref.get(fixture.linkCommands); |
| 540 | }); |
| 541 | |
| 542 | const mergingSnapshot = () => |
| 543 | makeSnapshot([makeThread(MERGING_THREAD, { pullRequests: [makeLink(7, { state: "open" })] })]); |
| 544 | |
| 545 | describe("PullRequestSyncReactor", () => { |
| 546 | it.effect("lets a finished sweep's links go while a cache keeps the fiber that read them", () => |
| 547 | Effect.gen(function* () { |
| 548 | class SweptLink { |
| 549 | readonly swept = true; |
| 550 | } |
| 551 | // Like PullRequestReadCache's revisions: a lookup fiber, kept for good, forked from the reader. |
| 552 | const kept = yield* Cache.makeWith(() => Effect.void, { |
| 553 | capacity: 1, |
| 554 | timeToLive: () => Duration.infinity, |
| 555 | }); |
| 556 | const fixture = yield* makeHarness({ |
| 557 | snapshot: makeSnapshot([]), |
| 558 | summary: (input) => Cache.get(kept, undefined).pipe(Effect.as(makeSummary(input))), |
| 559 | }); |
| 560 | yield* Ref.set( |
| 561 | fixture.snapshots, |
| 562 | makeSnapshot( |
| 563 | Array.from({ length: 30 }, (_, index) => |
| 564 | makeThread(`thread-${index}`, { |
| 565 | pullRequests: [Object.assign(new SweptLink(), makeLink(7))], |
| 566 | }), |
| 567 | ), |
| 568 | ), |
| 569 | ); |
| 570 | yield* Effect.gen(function* () { |
| 571 | yield* startAndSweep(fixture); |
| 572 | assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 30); |
| 573 | yield* Ref.set(fixture.snapshots, makeSnapshot([])); |
| 574 | |
| 575 | assert.strictEqual(NodeV8.queryObjects(SweptLink, { format: "count" }), 0); |
| 576 | }).pipe(Effect.provide(fixture.layer)); |
| 577 | }), |
| 578 | ); |
| 579 | |
| 580 | it.effect("retries a failed stack read after the summary becomes terminal", () => |
| 581 | Effect.gen(function* () { |
| 582 | yield* TestClock.setTime(Date.parse(NOW)); |
| 583 | let attempts = 0; |
| 584 | const nativeStack: PullRequestStack = { |
| 585 | id: "stack", |
| 586 | number: 7, |
| 587 | url: "https://github.com/owner/repository/stacks/7", |
| 588 | base: "main", |
| 589 | layers: [{ number: 7, headBranch: "feature", state: "merged" }], |
| 590 | }; |
| 591 | const fixture = yield* makeHarness({ |
| 592 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]), |
| 593 | summary: (input) => Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })), |
| 594 | stack: () => |
| 595 | ++attempts === 1 |
| 596 | ? Effect.fail( |
| 597 | new PullRequestOperationError({ |
| 598 | operation: "stack", |
| 599 | detail: "temporary failure", |
| 600 | }), |
| 601 | ) |
| 602 | : Effect.succeed(nativeStack), |
| 603 | }); |
| 604 | yield* Effect.gen(function* () { |
| 605 | const reactor = yield* startAndSweep(fixture); |
| 606 | const commands = yield* Ref.get(fixture.syncCommands); |
| 607 | yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)); |
| 608 | yield* sweepAgain(fixture, reactor); |
| 609 | assert.strictEqual(attempts, 2); |
| 610 | assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, { |
| 611 | kind: "native", |
| 612 | ...nativeStack, |
| 613 | }); |
| 614 | }).pipe(Effect.provide(fixture.layer)); |
| 615 | }), |
| 616 | ); |
| 617 | |
| 618 | it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () => |
| 619 | Effect.gen(function* () { |
| 620 | yield* TestClock.setTime(Date.parse(NOW)); |
| 621 | const fixture = yield* makeHarness({ |
| 622 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]), |
| 623 | }); |
| 624 | yield* Effect.gen(function* () { |
| 625 | const reactor = yield* startAndSweep(fixture); |
| 626 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0); |
| 627 | yield* reactor.requestSync({ |
| 628 | host: "github.com", |
| 629 | repository: "owner/repository", |
| 630 | number: 7, |
| 631 | }); |
| 632 | yield* Queue.take(fixture.snapshotReads); |
| 633 | yield* reactor.drain; |
| 634 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1); |
| 635 | }).pipe(Effect.provide(fixture.layer)); |
| 636 | }), |
| 637 | ); |
| 638 | it.effect("syncs a rebase blocker even when the PR timestamp is unchanged", () => |
| 639 | Effect.scoped( |
| 640 | Effect.gen(function* () { |
| 641 | yield* TestClock.setTime(Date.parse(NOW)); |
| 642 | const required = yield* Ref.make(false); |
| 643 | const fixture = yield* makeHarness({ |
| 644 | snapshot: makeSnapshot([makeThread("rebase", { pullRequests: [makeLink(7)] })]), |
| 645 | summary: (input) => |
| 646 | Ref.get(required).pipe( |
| 647 | Effect.map((rebaseRequired) => makeSummary(input, { rebaseRequired })), |
| 648 | ), |
| 649 | }); |
| 650 | yield* Effect.gen(function* () { |
| 651 | const reactor = yield* startAndSweep(fixture); |
| 652 | yield* applyRecordedSyncs(fixture); |
| 653 | yield* Ref.set(required, true); |
| 654 | yield* reactor.requestSync({ |
| 655 | host: "github.com", |
| 656 | repository: "owner/repository", |
| 657 | number: 7, |
| 658 | }); |
| 659 | yield* Queue.take(fixture.snapshotReads); |
| 660 | yield* reactor.drain; |
| 661 | const commands = yield* Ref.get(fixture.syncCommands); |
| 662 | assert.equal(commands.length, 2); |
| 663 | assert.equal(commands[0]?.snapshot?.rebaseRequired, false); |
| 664 | assert.equal(commands[1]?.snapshot?.rebaseRequired, true); |
| 665 | assert.equal(commands[0]?.snapshot?.updatedAt, commands[1]?.snapshot?.updatedAt); |
| 666 | }).pipe(Effect.provide(fixture.layer)); |
| 667 | }), |
| 668 | ), |
| 669 | ); |
| 670 | |
| 671 | it.effect("snapshots an unsynced link once and writes it to the thread", () => |
| 672 | Effect.gen(function* () { |
| 673 | yield* TestClock.setTime(Date.parse(NOW)); |
| 674 | const fixture = yield* makeHarness({ |
| 675 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]), |
| 676 | summary: (input) => Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })), |
| 677 | }); |
| 678 | |
| 679 | yield* Effect.gen(function* () { |
| 680 | yield* startAndSweep(fixture); |
| 681 | |
| 682 | assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [ |
| 683 | { |
| 684 | projectId: PROJECT_ID, |
| 685 | host: "github.com", |
| 686 | repository: "owner/repository", |
| 687 | number: 42, |
| 688 | }, |
| 689 | ]); |
| 690 | assert.deepStrictEqual( |
| 691 | (yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest), |
| 692 | [ |
| 693 | { |
| 694 | type: "thread.pull-request-link.sync", |
| 695 | threadId: ThreadId.make("one"), |
| 696 | host: "github.com", |
| 697 | repository: "owner/repository", |
| 698 | number: 42, |
| 699 | snapshot: { |
| 700 | state: "open", |
| 701 | title: "Ship it", |
| 702 | headBranch: "feature", |
| 703 | baseBranch: "main", |
| 704 | isDraft: true, |
| 705 | updatedAt: "2026-08-27T00:00:00.000Z", |
| 706 | syncedAt: NOW, |
| 707 | closedAt: null, |
| 708 | mergedAt: null, |
| 709 | }, |
| 710 | stack: null, |
| 711 | }, |
| 712 | ], |
| 713 | ); |
| 714 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1); |
| 715 | assert.strictEqual(yield* Ref.get(fixture.shellSnapshotReads), 0); |
| 716 | }).pipe(Effect.provide(fixture.layer)); |
| 717 | }), |
| 718 | ); |
| 719 | |
| 720 | it.effect("asks the host once for a pull request shared by two threads in one project", () => |
| 721 | Effect.gen(function* () { |
| 722 | yield* TestClock.setTime(Date.parse(NOW)); |
| 723 | const fixture = yield* makeHarness({ |
| 724 | snapshot: makeSnapshot([ |
| 725 | makeThread("one", { pullRequests: [makeLink(42)] }), |
| 726 | makeThread("two", { |
| 727 | pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })], |
| 728 | }), |
| 729 | ]), |
| 730 | }); |
| 731 | |
| 732 | yield* Effect.gen(function* () { |
| 733 | yield* startAndSweep(fixture); |
| 734 | |
| 735 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1); |
| 736 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1); |
| 737 | const commands = yield* Ref.get(fixture.syncCommands); |
| 738 | assert.deepStrictEqual( |
| 739 | commands |
| 740 | .map((command) => [command.threadId, command.repository] as const) |
| 741 | .sort((left, right) => left[0].localeCompare(right[0])), |
| 742 | [ |
| 743 | [ThreadId.make("one"), "owner/repository"], |
| 744 | [ThreadId.make("two"), "Owner/Repository"], |
| 745 | ], |
| 746 | ); |
| 747 | }).pipe(Effect.provide(fixture.layer)); |
| 748 | }), |
| 749 | ); |
| 750 | |
| 751 | it.effect.each(["summary", "stack"] as const)( |
| 752 | "isolates a failed project %s refresh and retries it after the other project succeeds", |
| 753 | (operation) => |
| 754 | Effect.gen(function* () { |
| 755 | yield* TestClock.setTime(Date.parse(NOW)); |
| 756 | const otherProject = ProjectId.make("other-project"); |
| 757 | const link = makeLink(42, { state: "merged", mergedAt: NOW }); |
| 758 | let failing = true; |
| 759 | const failure = new PullRequestOperationError({ operation, detail: "checkout missing" }); |
| 760 | const fixture = yield* makeHarness({ |
| 761 | snapshot: makeSnapshot([ |
| 762 | makeThread("failing", { pullRequests: [link] }), |
| 763 | makeThread("healthy", { projectId: otherProject, pullRequests: [link] }), |
| 764 | makeThread("same-project", { projectId: otherProject, pullRequests: [link] }), |
| 765 | ]), |
| 766 | summary: (input) => |
| 767 | failing && input.projectId === PROJECT_ID && operation === "summary" |
| 768 | ? Effect.fail(failure) |
| 769 | : Effect.succeed( |
| 770 | makeSummary(input, { |
| 771 | state: "merged", |
| 772 | mergedAt: NOW, |
| 773 | title: input.projectId, |
| 774 | }), |
| 775 | ), |
| 776 | stack: (input) => |
| 777 | failing && input.projectId === PROJECT_ID && operation === "stack" |
| 778 | ? Effect.fail(failure) |
| 779 | : Effect.succeed({ |
| 780 | id: input.projectId, |
| 781 | number: 42, |
| 782 | url: "https://github.com/owner/repository/stacks/42", |
| 783 | base: "main", |
| 784 | layers: [{ number: 42, headBranch: "feature", state: "merged" }], |
| 785 | }), |
| 786 | }); |
| 787 | yield* Effect.gen(function* () { |
| 788 | const reactor = yield* startAndSweep(fixture); |
| 789 | assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []); |
| 790 | yield* reactor.requestSync(link); |
| 791 | yield* Queue.take(fixture.snapshotReads); |
| 792 | yield* reactor.drain; |
| 793 | const commands = yield* Ref.get(fixture.syncCommands); |
| 794 | assert.sameDeepMembers( |
| 795 | commands.map((command) => [ |
| 796 | command.threadId, |
| 797 | command.snapshot.title, |
| 798 | command.stack?.id, |
| 799 | ]), |
| 800 | [ |
| 801 | ["healthy", otherProject, otherProject], |
| 802 | ["same-project", otherProject, otherProject], |
| 803 | ], |
| 804 | ); |
| 805 | assert.sameMembers( |
| 806 | (yield* Ref.get(fixture.summaryCalls)).map((call) => call.projectId), |
| 807 | [PROJECT_ID, otherProject], |
| 808 | ); |
| 809 | assert.sameMembers( |
| 810 | (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId), |
| 811 | operation === "stack" ? [PROJECT_ID, otherProject] : [otherProject], |
| 812 | ); |
| 813 | yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)); |
| 814 | failing = false; |
| 815 | yield* sweepAgain(fixture, reactor); |
| 816 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3); |
| 817 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).at(-1)?.projectId, PROJECT_ID); |
| 818 | const retried = (yield* Ref.get(fixture.syncCommands)).at(-1); |
| 819 | assert.strictEqual(retried?.threadId, ThreadId.make("failing")); |
| 820 | assert.strictEqual(retried?.snapshot.title, PROJECT_ID); |
| 821 | assert.strictEqual(retried?.stack?.id, PROJECT_ID); |
| 822 | }).pipe(Effect.provide(fixture.layer)); |
| 823 | }), |
| 824 | ); |
| 825 | |
| 826 | it.effect("recovers the HTTP port when syncing an older Forgejo link", () => |
| 827 | Effect.gen(function* () { |
| 828 | const fixture = yield* makeHarness({ |
| 829 | snapshot: makeSnapshot([ |
| 830 | makeThread("one", { |
| 831 | pullRequests: [ |
| 832 | makeLink(42, null, { |
| 833 | host: "forge.example", |
| 834 | url: "http://forge.example:3000/owner/repository/pulls/42", |
| 835 | }), |
| 836 | ], |
| 837 | }), |
| 838 | ]), |
| 839 | summary: (input) => Effect.succeed(makeSummary(input)), |
| 840 | }); |
| 841 | yield* Effect.gen(function* () { |
| 842 | yield* startAndSweep(fixture); |
| 843 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000"); |
| 844 | assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000"); |
| 845 | }).pipe(Effect.provide(fixture.layer)); |
| 846 | }), |
| 847 | ); |
| 848 | |
| 849 | it.effect("dispatches nothing when the host snapshot is unchanged", () => |
| 850 | Effect.gen(function* () { |
| 851 | yield* TestClock.setTime(Date.parse(NOW)); |
| 852 | const fixture = yield* makeHarness({ |
| 853 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]), |
| 854 | summary: (input) => Effect.succeed(makeSummary(input, { updatedAt: NOW })), |
| 855 | }); |
| 856 | |
| 857 | yield* Effect.gen(function* () { |
| 858 | const reactor = yield* startAndSweep(fixture); |
| 859 | const firstSweep = yield* Ref.get(fixture.syncCommands); |
| 860 | assert.strictEqual(firstSweep.length, 1); |
| 861 | yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep)); |
| 862 | |
| 863 | yield* sweepAgain(fixture, reactor); |
| 864 | |
| 865 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 866 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1); |
| 867 | assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1); |
| 868 | }).pipe(Effect.provide(fixture.layer)); |
| 869 | }), |
| 870 | ); |
| 871 | |
| 872 | it.effect("keeps the known mergeability while the host recomputes it", () => |
| 873 | Effect.gen(function* () { |
| 874 | yield* TestClock.setTime(Date.parse(NOW)); |
| 875 | const answers = yield* Ref.make<ReadonlyArray<"unknown" | "mergeable">>([ |
| 876 | "unknown", |
| 877 | "mergeable", |
| 878 | ]); |
| 879 | const fixture = yield* makeHarness({ |
| 880 | snapshot: makeSnapshot([ |
| 881 | makeThread("one", { |
| 882 | pullRequests: [makeLink(42, { mergeability: "conflicting" })], |
| 883 | }), |
| 884 | ]), |
| 885 | summary: (input) => |
| 886 | Ref.modify(answers, ([next = "mergeable", ...rest]) => [ |
| 887 | makeSummary(input, { mergeability: next }), |
| 888 | rest, |
| 889 | ]), |
| 890 | }); |
| 891 | |
| 892 | yield* Effect.gen(function* () { |
| 893 | const reactor = yield* startAndSweep(fixture); |
| 894 | assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []); |
| 895 | |
| 896 | // An unchanged old PR uses main's five-minute quiet polling cadence. |
| 897 | yield* TestClock.adjust("5 minutes"); |
| 898 | yield* Queue.take(fixture.snapshotReads); |
| 899 | yield* reactor.drain; |
| 900 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 901 | |
| 902 | const commands = yield* Ref.get(fixture.syncCommands); |
| 903 | assert.deepStrictEqual( |
| 904 | commands.map((command) => command.snapshot.mergeability), |
| 905 | ["mergeable"], |
| 906 | ); |
| 907 | }).pipe(Effect.provide(fixture.layer)); |
| 908 | }), |
| 909 | ); |
| 910 | |
| 911 | it.effect.each([ |
| 912 | { provider: "github" as const, updatedAt: "2026-08-28T00:00:00.000Z" }, |
| 913 | { provider: "forgejo" as const, updatedAt: "2026-08-27T00:00:00.000Z" }, |
| 914 | ])("persists unknown mergeability for $provider at $updatedAt", ({ provider, updatedAt }) => |
| 915 | Effect.gen(function* () { |
| 916 | yield* TestClock.setTime(Date.parse(NOW)); |
| 917 | const fixture = yield* makeHarness({ |
| 918 | snapshot: makeSnapshot([ |
| 919 | makeThread("one", { |
| 920 | pullRequests: [makeLink(42, { mergeability: "mergeable" })], |
| 921 | }), |
| 922 | ]), |
| 923 | summary: (input) => |
| 924 | Effect.succeed( |
| 925 | makeSummary(input, { |
| 926 | provider: SourceControlProviderKind.make(provider), |
| 927 | updatedAt, |
| 928 | mergeability: "unknown", |
| 929 | }), |
| 930 | ), |
| 931 | }); |
| 932 | yield* Effect.gen(function* () { |
| 933 | yield* startAndSweep(fixture); |
| 934 | const commands = yield* Ref.get(fixture.syncCommands); |
| 935 | assert.deepStrictEqual( |
| 936 | commands.map((command) => command.snapshot.mergeability), |
| 937 | ["unknown"], |
| 938 | ); |
| 939 | }).pipe(Effect.provide(fixture.layer)); |
| 940 | }), |
| 941 | ); |
| 942 | |
| 943 | it.effect("refreshes closed links through each project after reopening elsewhere", () => |
| 944 | Effect.gen(function* () { |
| 945 | yield* TestClock.setTime(Date.parse(NOW)); |
| 946 | const invalidated = yield* Ref.make<ReadonlyArray<ProjectId>>([]); |
| 947 | const fixture = yield* makeHarness({ |
| 948 | snapshot: makeSnapshot([ |
| 949 | makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }), |
| 950 | makeThread("second", { |
| 951 | projectId: ProjectId.make("second-project"), |
| 952 | pullRequests: [makeLink(42, { state: "closed" })], |
| 953 | }), |
| 954 | ]), |
| 955 | invalidate: ({ reference }) => |
| 956 | reference !== undefined |
| 957 | ? Ref.update(invalidated, (projects) => [...projects, reference.projectId]) |
| 958 | : Effect.void, |
| 959 | summary: (input) => |
| 960 | Ref.get(invalidated).pipe( |
| 961 | Effect.map((projects) => |
| 962 | makeSummary(input, { |
| 963 | state: projects.includes(input.projectId) ? "open" : "closed", |
| 964 | }), |
| 965 | ), |
| 966 | ), |
| 967 | }); |
| 968 | yield* Effect.gen(function* () { |
| 969 | const reactor = yield* startAndSweep(fixture); |
| 970 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 971 | yield* reactor.requestSync({ |
| 972 | host: "github.com", |
| 973 | repository: "owner/repository", |
| 974 | number: 42, |
| 975 | }); |
| 976 | yield* Queue.take(fixture.snapshotReads); |
| 977 | yield* reactor.drain; |
| 978 | assert.sameMembers( |
| 979 | [...(yield* Ref.get(invalidated))], |
| 980 | [PROJECT_ID, ProjectId.make("second-project")], |
| 981 | ); |
| 982 | assert.sameMembers( |
| 983 | (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId), |
| 984 | [PROJECT_ID, ProjectId.make("second-project")], |
| 985 | ); |
| 986 | const commands = yield* Ref.get(fixture.syncCommands); |
| 987 | yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)); |
| 988 | const snapshot = yield* Ref.get(fixture.snapshots); |
| 989 | assert.deepStrictEqual( |
| 990 | snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state), |
| 991 | ["open", "open"], |
| 992 | ); |
| 993 | }).pipe(Effect.provide(fixture.layer)); |
| 994 | }), |
| 995 | ); |
| 996 | |
| 997 | it.effect("stops asking the host once a pull request is merged", () => |
| 998 | Effect.gen(function* () { |
| 999 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1000 | const fixture = yield* makeHarness({ |
| 1001 | snapshot: makeSnapshot([ |
| 1002 | makeThread("merged", { |
| 1003 | pullRequests: [makeLink(1, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" })], |
| 1004 | }), |
| 1005 | ]), |
| 1006 | }); |
| 1007 | |
| 1008 | yield* Effect.gen(function* () { |
| 1009 | const reactor = yield* startAndSweep(fixture); |
| 1010 | yield* sweepAgain(fixture, reactor); |
| 1011 | |
| 1012 | assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []); |
| 1013 | assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []); |
| 1014 | |
| 1015 | yield* reactor.requestSync({ |
| 1016 | host: "github.com", |
| 1017 | repository: "owner/repository", |
| 1018 | number: 1, |
| 1019 | }); |
| 1020 | yield* Queue.take(fixture.snapshotReads); |
| 1021 | yield* reactor.drain; |
| 1022 | |
| 1023 | assert.deepStrictEqual( |
| 1024 | (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number), |
| 1025 | [1], |
| 1026 | ); |
| 1027 | }).pipe(Effect.provide(fixture.layer)); |
| 1028 | }), |
| 1029 | ); |
| 1030 | |
| 1031 | it.effect("stops reading a pull request a day after it closed, until a refresh asks", () => |
| 1032 | Effect.gen(function* () { |
| 1033 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1034 | const closed = (closedAt: string | null) => ({ state: "closed" as const, closedAt }); |
| 1035 | const fixture = yield* makeHarness({ |
| 1036 | snapshot: makeSnapshot([ |
| 1037 | makeThread("closed", { |
| 1038 | pullRequests: [ |
| 1039 | makeLink(1, closed("2026-08-20T00:00:00.000Z")), |
| 1040 | makeLink(2, closed("2026-08-26T00:00:00.000Z")), |
| 1041 | makeLink(3, closed("2026-08-28T11:00:00.000Z")), |
| 1042 | makeLink(4, closed(null)), |
| 1043 | ], |
| 1044 | }), |
| 1045 | ]), |
| 1046 | summary: (input) => Effect.succeed(makeSummary(input, { state: "closed", closedAt: NOW })), |
| 1047 | }); |
| 1048 | const reads = Ref.get(fixture.summaryCalls).pipe( |
| 1049 | Effect.map((calls) => calls.map((call) => call.number).toSorted()), |
| 1050 | ); |
| 1051 | |
| 1052 | yield* Effect.gen(function* () { |
| 1053 | const reactor = yield* startAndSweep(fixture); |
| 1054 | // Closed within the day, or with no close time, keeps the fifteen-minute cadence. |
| 1055 | assert.deepStrictEqual(yield* reads, [3, 4]); |
| 1056 | for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor); |
| 1057 | assert.deepStrictEqual(yield* reads, [3, 3, 4, 4]); |
| 1058 | |
| 1059 | yield* reactor.requestSync({ |
| 1060 | host: "github.com", |
| 1061 | repository: "owner/repository", |
| 1062 | number: 1, |
| 1063 | }); |
| 1064 | yield* Queue.take(fixture.snapshotReads); |
| 1065 | yield* reactor.drain; |
| 1066 | assert.deepStrictEqual(yield* reads, [1, 3, 3, 4, 4]); |
| 1067 | }).pipe(Effect.provide(fixture.layer)); |
| 1068 | }), |
| 1069 | ); |
| 1070 | |
| 1071 | it.effect("re-reads a merged pull request until the host supplies its merge time", () => |
| 1072 | Effect.gen(function* () { |
| 1073 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1074 | const invalidated = yield* Ref.make<ReadonlyArray<number>>([]); |
| 1075 | const fixture = yield* makeHarness({ |
| 1076 | snapshot: makeSnapshot([ |
| 1077 | makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }), |
| 1078 | ]), |
| 1079 | invalidate: ({ reference }) => |
| 1080 | Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]), |
| 1081 | summary: (input) => |
| 1082 | Effect.succeed( |
| 1083 | makeSummary(input, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }), |
| 1084 | ), |
| 1085 | }); |
| 1086 | |
| 1087 | yield* Effect.gen(function* () { |
| 1088 | const reactor = yield* startAndSweep(fixture); |
| 1089 | const firstSweep = yield* Ref.get(fixture.syncCommands); |
| 1090 | assert.deepStrictEqual(yield* Ref.get(invalidated), [1]); |
| 1091 | assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z"); |
| 1092 | yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep)); |
| 1093 | |
| 1094 | for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor); |
| 1095 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1); |
| 1096 | }).pipe(Effect.provide(fixture.layer)); |
| 1097 | }), |
| 1098 | ); |
| 1099 | |
| 1100 | it.effect("syncs a pull request a reader saw merge without waiting for the sweep", () => |
| 1101 | Effect.gen(function* () { |
| 1102 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1103 | const state = yield* Ref.make<PullRequestSummary["state"]>("open"); |
| 1104 | const invalidated = yield* Ref.make<ReadonlyArray<number>>([]); |
| 1105 | const fixture = yield* makeHarness({ |
| 1106 | snapshot: makeSnapshot([ |
| 1107 | makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }), |
| 1108 | ]), |
| 1109 | summary: (input) => |
| 1110 | Ref.get(state).pipe( |
| 1111 | Effect.map((current) => |
| 1112 | makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}), |
| 1113 | ), |
| 1114 | ), |
| 1115 | invalidate: ({ reference }) => |
| 1116 | Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]), |
| 1117 | }); |
| 1118 | |
| 1119 | yield* Effect.gen(function* () { |
| 1120 | const reactor = yield* startAndSweep(fixture); |
| 1121 | yield* Ref.set(state, "merged"); |
| 1122 | |
| 1123 | yield* Queue.offer(fixture.stateChanges, { |
| 1124 | host: "github.com", |
| 1125 | repository: "owner/repository", |
| 1126 | number: 7, |
| 1127 | }); |
| 1128 | yield* Queue.take(fixture.snapshotReads); |
| 1129 | yield* reactor.drain; |
| 1130 | |
| 1131 | assert.deepStrictEqual(yield* Ref.get(invalidated), [7]); |
| 1132 | assert.deepStrictEqual( |
| 1133 | (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state), |
| 1134 | ["merged"], |
| 1135 | ); |
| 1136 | }).pipe(Effect.provide(fixture.layer)); |
| 1137 | }), |
| 1138 | ); |
| 1139 | |
| 1140 | it.effect.each([true, false])( |
| 1141 | "syncs linked draft status %s as soon as a reader reports a change", |
| 1142 | (isDraft) => |
| 1143 | Effect.gen(function* () { |
| 1144 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1145 | const draft = yield* Ref.make(!isDraft); |
| 1146 | const invalidated = yield* Ref.make<ReadonlyArray<number>>([]); |
| 1147 | const fixture = yield* makeHarness({ |
| 1148 | snapshot: makeSnapshot([ |
| 1149 | makeThread("agent", { pullRequests: [makeLink(7, { isDraft: !isDraft })] }), |
| 1150 | ]), |
| 1151 | summary: (input) => |
| 1152 | Ref.get(draft).pipe(Effect.map((isDraft) => makeSummary(input, { isDraft }))), |
| 1153 | invalidate: ({ reference }) => |
| 1154 | Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]), |
| 1155 | }); |
| 1156 | |
| 1157 | yield* Effect.gen(function* () { |
| 1158 | const reactor = yield* startAndSweep(fixture); |
| 1159 | yield* Ref.set(draft, isDraft); |
| 1160 | yield* Queue.offer(fixture.stateChanges, { |
| 1161 | host: "github.com", |
| 1162 | repository: "owner/repository", |
| 1163 | number: 7, |
| 1164 | }); |
| 1165 | yield* Queue.take(fixture.snapshotReads); |
| 1166 | yield* reactor.drain; |
| 1167 | |
| 1168 | assert.deepStrictEqual(yield* Ref.get(invalidated), [7]); |
| 1169 | assert.deepStrictEqual( |
| 1170 | (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.isDraft), |
| 1171 | [isDraft], |
| 1172 | ); |
| 1173 | }).pipe(Effect.provide(fixture.layer)); |
| 1174 | }), |
| 1175 | ); |
| 1176 | |
| 1177 | it.effect("preserves a refresh requested while an older host read is in flight", () => |
| 1178 | Effect.gen(function* () { |
| 1179 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1180 | const reading = yield* Deferred.make<void>(); |
| 1181 | const release = yield* Deferred.make<void>(); |
| 1182 | let calls = 0; |
| 1183 | const fixture = yield* makeHarness({ |
| 1184 | snapshot: makeSnapshot([]), |
| 1185 | summary: (input) => |
| 1186 | Effect.gen(function* () { |
| 1187 | calls += 1; |
| 1188 | if (calls === 1) { |
| 1189 | yield* Deferred.succeed(reading, undefined); |
| 1190 | yield* Deferred.await(release); |
| 1191 | } |
| 1192 | return makeSummary(input, { state: calls === 1 ? "closed" : "open" }); |
| 1193 | }), |
| 1194 | }); |
| 1195 | yield* Effect.gen(function* () { |
| 1196 | const reactor = yield* startAndSweep(fixture); |
| 1197 | yield* Ref.set( |
| 1198 | fixture.snapshots, |
| 1199 | makeSnapshot([ |
| 1200 | makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }), |
| 1201 | ]), |
| 1202 | ); |
| 1203 | const key = { host: "github.com", repository: "owner/repository", number: 2 }; |
| 1204 | yield* reactor.requestSync(key); |
| 1205 | yield* Deferred.await(reading); |
| 1206 | yield* reactor.requestSync(key); |
| 1207 | yield* Deferred.succeed(release, undefined); |
| 1208 | yield* reactor.drain; |
| 1209 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 1210 | assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open"); |
| 1211 | }).pipe(Effect.provide(fixture.layer)); |
| 1212 | }), |
| 1213 | ); |
| 1214 | |
| 1215 | it.effect("reads a burst of requested links in one sweep", () => |
| 1216 | Effect.gen(function* () { |
| 1217 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1218 | const reading = yield* Deferred.make<void>(); |
| 1219 | const release = yield* Deferred.make<void>(); |
| 1220 | const fixture = yield* makeHarness({ |
| 1221 | snapshot: makeSnapshot([]), |
| 1222 | summary: (input) => |
| 1223 | Effect.gen(function* () { |
| 1224 | if (input.number === 1) { |
| 1225 | yield* Deferred.succeed(reading, undefined); |
| 1226 | yield* Deferred.await(release); |
| 1227 | } |
| 1228 | return makeSummary(input); |
| 1229 | }), |
| 1230 | }); |
| 1231 | yield* Effect.gen(function* () { |
| 1232 | const reactor = yield* startAndSweep(fixture); |
| 1233 | yield* Ref.set( |
| 1234 | fixture.snapshots, |
| 1235 | makeSnapshot( |
| 1236 | [1, 2, 3, 4].map((number) => |
| 1237 | makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }), |
| 1238 | ), |
| 1239 | ), |
| 1240 | ); |
| 1241 | const request = (number: number) => |
| 1242 | reactor.requestSync({ host: "github.com", repository: "owner/repository", number }); |
| 1243 | yield* request(1); |
| 1244 | yield* Deferred.await(reading); |
| 1245 | yield* Effect.forEach([2, 3, 4], request, { discard: true }); |
| 1246 | yield* Deferred.succeed(release, undefined); |
| 1247 | yield* reactor.drain; |
| 1248 | assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2); |
| 1249 | assert.deepStrictEqual( |
| 1250 | (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(), |
| 1251 | [1, 2, 3, 4], |
| 1252 | ); |
| 1253 | }).pipe(Effect.provide(fixture.layer)); |
| 1254 | }), |
| 1255 | ); |
| 1256 | |
| 1257 | it.effect("reads hosts that batch all at once and other hosts at the old sweep width", () => |
| 1258 | Effect.gen(function* () { |
| 1259 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1260 | const numbers = Array.from({ length: 60 }, (_, index) => index + 1); |
| 1261 | const hostOf = (number: number) => (number <= 30 ? "github.com" : "gitlab.example.com"); |
| 1262 | const batches = (input: PullRequestRef) => input.host === "github.com"; |
| 1263 | const batched = yield* Ref.make(0); |
| 1264 | const unbatched = yield* Ref.make(0); |
| 1265 | const started = yield* Queue.unbounded<void>(); |
| 1266 | const release = yield* Deferred.make<void>(); |
| 1267 | const fixture = yield* makeHarness({ |
| 1268 | snapshot: makeSnapshot( |
| 1269 | numbers.map((number) => |
| 1270 | makeThread(`thread-${number}`, { |
| 1271 | pullRequests: [makeLink(number, null, { host: hostOf(number) })], |
| 1272 | }), |
| 1273 | ), |
| 1274 | ), |
| 1275 | batchesReads: batches, |
| 1276 | summary: (input) => { |
| 1277 | const inFlight = batches(input) ? batched : unbatched; |
| 1278 | return Ref.update(inFlight, (count) => count + 1).pipe( |
| 1279 | Effect.andThen(Queue.offer(started, undefined)), |
| 1280 | Effect.andThen(Deferred.await(release)), |
| 1281 | Effect.andThen(Ref.update(inFlight, (count) => count - 1)), |
| 1282 | Effect.as(makeSummary(input)), |
| 1283 | ); |
| 1284 | }, |
| 1285 | }); |
| 1286 | yield* Effect.gen(function* () { |
| 1287 | const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor; |
| 1288 | yield* reactor.start(); |
| 1289 | yield* Deferred.succeed(fixture.activation, undefined); |
| 1290 | yield* Queue.takeN(started, 55); |
| 1291 | assert.strictEqual(yield* Ref.get(batched), 30); |
| 1292 | assert.strictEqual(yield* Ref.get(unbatched), 25); |
| 1293 | yield* Deferred.succeed(release, undefined); |
| 1294 | yield* reactor.drain; |
| 1295 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, numbers.length); |
| 1296 | }).pipe(Effect.provide(fixture.layer)); |
| 1297 | }), |
| 1298 | ); |
| 1299 | |
| 1300 | it.effect("leaves a forge CLI slot for reads outside the sweep", () => |
| 1301 | Effect.gen(function* () { |
| 1302 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1303 | const asked = yield* Queue.unbounded<void>(); |
| 1304 | const started = yield* Queue.unbounded<string>(); |
| 1305 | const release = yield* Deferred.make<void>(); |
| 1306 | const vcs = yield* VcsProcess.make.pipe( |
| 1307 | Effect.provideService( |
| 1308 | ProcessRunner.ProcessRunner, |
| 1309 | ProcessRunner.ProcessRunner.of({ |
| 1310 | run: (input) => |
| 1311 | Queue.offer(started, input.args.at(-1)!).pipe( |
| 1312 | Effect.andThen(Deferred.await(release)), |
| 1313 | Effect.as({ |
| 1314 | stdout: "", |
| 1315 | stderr: "", |
| 1316 | code: ChildProcessSpawner.ExitCode(0), |
| 1317 | timedOut: false, |
| 1318 | stdoutTruncated: false, |
| 1319 | stderrTruncated: false, |
| 1320 | stdoutInvalidUtf8: false, |
| 1321 | stderrInvalidUtf8: false, |
| 1322 | }), |
| 1323 | ), |
| 1324 | }), |
| 1325 | ), |
| 1326 | ); |
| 1327 | const glab = (number: string) => |
| 1328 | vcs.run({ |
| 1329 | operation: "synthetic.glab.view", |
| 1330 | command: "glab", |
| 1331 | args: ["mr", "view", number], |
| 1332 | cwd: "/workspace", |
| 1333 | }); |
| 1334 | const numbers = Array.from({ length: 6 }, (_, index) => index + 1); |
| 1335 | const fixture = yield* makeHarness({ |
| 1336 | snapshot: makeSnapshot( |
| 1337 | numbers.map((number) => |
| 1338 | makeThread(`thread-${number}`, { |
| 1339 | pullRequests: [makeLink(number, null, { host: "gitlab.example.com" })], |
| 1340 | }), |
| 1341 | ), |
| 1342 | ), |
| 1343 | batchesReads: () => false, |
| 1344 | summary: (input) => |
| 1345 | Queue.offer(asked, undefined).pipe( |
| 1346 | Effect.andThen(glab(String(input.number))), |
| 1347 | Effect.orDie, |
| 1348 | Effect.as(makeSummary(input)), |
| 1349 | ), |
| 1350 | }); |
| 1351 | yield* Effect.gen(function* () { |
| 1352 | const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor; |
| 1353 | yield* reactor.start(); |
| 1354 | yield* Deferred.succeed(fixture.activation, undefined); |
| 1355 | yield* Queue.takeN(asked, numbers.length); |
| 1356 | yield* Queue.takeN(started, 3); |
| 1357 | const panel = yield* glab("panel").pipe(Effect.forkChild({ startImmediately: true })); |
| 1358 | assert.strictEqual(yield* Queue.take(started), "panel"); |
| 1359 | yield* Deferred.succeed(release, undefined); |
| 1360 | yield* Fiber.join(panel); |
| 1361 | yield* reactor.drain; |
| 1362 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, numbers.length); |
| 1363 | }).pipe(Effect.provide(fixture.layer)); |
| 1364 | }), |
| 1365 | ); |
| 1366 | |
| 1367 | it.effect("reads a member a sibling flags while the sweep is full", () => |
| 1368 | Effect.gen(function* () { |
| 1369 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1370 | const stackOf = (layers: ReadonlyArray<number>) => ({ |
| 1371 | id: "9", |
| 1372 | number: 9, |
| 1373 | url: "https://github.com/owner/repository/stack/9", |
| 1374 | base: "main", |
| 1375 | layers: layers.map(stackLayer), |
| 1376 | }); |
| 1377 | // #50 is merged and not due until #1's stack read shows it a different layer list. |
| 1378 | const merged = makeLink( |
| 1379 | 50, |
| 1380 | { state: "merged", mergedAt: NOW }, |
| 1381 | { stack: { kind: "native", ...stackOf([50]) } }, |
| 1382 | ); |
| 1383 | const started = yield* Ref.make(0); |
| 1384 | const full = yield* Deferred.make<void>(); |
| 1385 | const synced1 = yield* Deferred.make<void>(); |
| 1386 | const fixture = yield* makeHarness({ |
| 1387 | snapshot: makeSnapshot([ |
| 1388 | // Another host takes 24 of the 25 shared slots and #1 the last one. |
| 1389 | ...Array.from({ length: 24 }, (_, index) => |
| 1390 | makeThread(`thread-${index + 2}`, { |
| 1391 | pullRequests: [makeLink(index + 2, null, { host: "gitlab.example.com" })], |
| 1392 | }), |
| 1393 | ), |
| 1394 | makeThread("thread-1", { pullRequests: [makeLink(1)] }), |
| 1395 | makeThread("thread-50", { pullRequests: [merged] }), |
| 1396 | ]), |
| 1397 | batchesReads: () => false, |
| 1398 | // #1 reads once all 25 slots are taken; the other 24 hold theirs until #1 has synced. |
| 1399 | summary: (input) => |
| 1400 | Ref.updateAndGet(started, (count) => count + 1).pipe( |
| 1401 | // Forked, so #1 resumes only after the sweep has handed out its next slot. |
| 1402 | Effect.tap((count) => |
| 1403 | count === 25 ? Effect.forkChild(Deferred.succeed(full, undefined)) : Effect.void, |
| 1404 | ), |
| 1405 | Effect.andThen( |
| 1406 | input.number === 50 |
| 1407 | ? Effect.void |
| 1408 | : Deferred.await(input.number === 1 ? full : synced1), |
| 1409 | ), |
| 1410 | Effect.as(makeSummary(input)), |
| 1411 | ), |
| 1412 | stack: (input) => Effect.succeed(input.number === 1 ? stackOf([1, 50]) : null), |
| 1413 | onSync: (command) => |
| 1414 | command.number === 1 ? Deferred.succeed(synced1, undefined) : Effect.void, |
| 1415 | }); |
| 1416 | yield* Effect.gen(function* () { |
| 1417 | yield* startAndSweep(fixture); |
| 1418 | const read = (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number); |
| 1419 | assert.include(read, 50); |
| 1420 | }).pipe(Effect.provide(fixture.layer)); |
| 1421 | }), |
| 1422 | ); |
| 1423 | |
| 1424 | it.effect("skips the stack read for a pull request the summary places in no stack", () => |
| 1425 | Effect.gen(function* () { |
| 1426 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1427 | const fixture = yield* makeHarness({ |
| 1428 | snapshot: makeSnapshot([ |
| 1429 | makeThread("unstacked", { pullRequests: [makeLink(1)] }), |
| 1430 | makeThread("stacked", { pullRequests: [makeLink(2)] }), |
| 1431 | makeThread("unknown", { pullRequests: [makeLink(3)] }), |
| 1432 | ]), |
| 1433 | summary: (input) => |
| 1434 | Effect.succeed( |
| 1435 | makeSummary( |
| 1436 | input, |
| 1437 | input.number === 1 |
| 1438 | ? { stack: null } |
| 1439 | : input.number === 2 |
| 1440 | ? { stack: { number: 9, position: 1, size: 2, base: "main" } } |
| 1441 | : {}, |
| 1442 | ), |
| 1443 | ), |
| 1444 | }); |
| 1445 | yield* Effect.gen(function* () { |
| 1446 | yield* startAndSweep(fixture); |
| 1447 | assert.deepStrictEqual( |
| 1448 | (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(), |
| 1449 | [2, 3], |
| 1450 | ); |
| 1451 | assert.deepStrictEqual( |
| 1452 | (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(), |
| 1453 | [1, 2, 3], |
| 1454 | ); |
| 1455 | }).pipe(Effect.provide(fixture.layer)); |
| 1456 | }), |
| 1457 | ); |
| 1458 | |
| 1459 | it.effect("reads a settled thread's links once when it settles, then until unsettled", () => |
| 1460 | Effect.gen(function* () { |
| 1461 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1462 | const fixture = yield* makeHarness({ |
| 1463 | snapshot: makeSnapshot([ |
| 1464 | makeThread("settled", { |
| 1465 | settledOverride: "settled", |
| 1466 | settledAt: "2026-08-21T00:00:00.000Z", |
| 1467 | pullRequests: [ |
| 1468 | makeLink(5, { state: "open" }), |
| 1469 | makeLink(6, { state: "closed" }), |
| 1470 | makeLink(7), |
| 1471 | ], |
| 1472 | }), |
| 1473 | ]), |
| 1474 | }); |
| 1475 | |
| 1476 | yield* Effect.gen(function* () { |
| 1477 | const reactor = yield* startAndSweep(fixture); |
| 1478 | assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []); |
| 1479 | |
| 1480 | const threadId = ThreadId.make("settled"); |
| 1481 | const at = DateTime.makeUnsafe(NOW); |
| 1482 | yield* Queue.offer(fixture.domainEvents, { |
| 1483 | type: "thread.settled", |
| 1484 | id: EventId.make("event:settled"), |
| 1485 | threadId, |
| 1486 | occurredAt: at, |
| 1487 | payload: { |
| 1488 | createdBy: "user", |
| 1489 | creationSource: "web", |
| 1490 | id: threadId, |
| 1491 | projectId: PROJECT_ID, |
| 1492 | title: "settled", |
| 1493 | providerInstanceId: ProviderInstanceId.make("codex"), |
| 1494 | modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, |
| 1495 | runtimeMode: "full-access", |
| 1496 | interactionMode: "default", |
| 1497 | branch: null, |
| 1498 | worktreePath: null, |
| 1499 | activeProviderThreadId: null, |
| 1500 | lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, |
| 1501 | forkedFrom: null, |
| 1502 | createdAt: at, |
| 1503 | updatedAt: at, |
| 1504 | archivedAt: null, |
| 1505 | settledOverride: "settled", |
| 1506 | settledAt: at, |
| 1507 | lastVisitedAt: null, |
| 1508 | deletedAt: null, |
| 1509 | }, |
| 1510 | }); |
| 1511 | yield* Queue.take(fixture.snapshotReads); |
| 1512 | yield* Queue.take(fixture.snapshotReads); |
| 1513 | yield* reactor.drain; |
| 1514 | assert.deepStrictEqual( |
| 1515 | (yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(), |
| 1516 | [5, 6], |
| 1517 | ); |
| 1518 | for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor); |
| 1519 | assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []); |
| 1520 | |
| 1521 | yield* Ref.update(fixture.snapshots, (snapshot) => ({ |
| 1522 | ...snapshot, |
| 1523 | threads: snapshot.threads.map((thread) => ({ |
| 1524 | ...thread, |
| 1525 | settledOverride: null, |
| 1526 | settledAt: null, |
| 1527 | })), |
| 1528 | })); |
| 1529 | yield* sweepAgain(fixture, reactor); |
| 1530 | assert.deepStrictEqual( |
| 1531 | (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(), |
| 1532 | [5, 6, 7], |
| 1533 | ); |
| 1534 | }).pipe(Effect.provide(fixture.layer)); |
| 1535 | }), |
| 1536 | ); |
| 1537 | |
| 1538 | it.effect("auto-links missing native stack layers on active threads only", () => |
| 1539 | Effect.gen(function* () { |
| 1540 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1541 | const stack: PullRequestStack = { |
| 1542 | id: "stack-1", |
| 1543 | number: 42, |
| 1544 | url: "https://github.com/owner/repository/stack/1", |
| 1545 | base: "main", |
| 1546 | layers: [ |
| 1547 | { number: 41, headBranch: "layer-1", state: "merged" }, |
| 1548 | { number: 42, headBranch: "layer-2", state: "open" }, |
| 1549 | { number: 43, headBranch: "layer-3", state: "open" }, |
| 1550 | ], |
| 1551 | }; |
| 1552 | const fixture = yield* makeHarness({ |
| 1553 | snapshot: makeSnapshot([ |
| 1554 | makeThread("one", { |
| 1555 | pullRequests: [ |
| 1556 | makeLink(42), |
| 1557 | makeLink(41, { state: "merged" }, { source: "stack-dismissed" }), |
| 1558 | ], |
| 1559 | }), |
| 1560 | makeThread("settled", { |
| 1561 | settledOverride: "settled", |
| 1562 | settledAt: "2026-08-21T00:00:00.000Z", |
| 1563 | pullRequests: [makeLink(42)], |
| 1564 | }), |
| 1565 | ]), |
| 1566 | stack: () => Effect.succeed(stack), |
| 1567 | }); |
| 1568 | |
| 1569 | yield* Effect.gen(function* () { |
| 1570 | yield* startAndSweep(fixture); |
| 1571 | |
| 1572 | const syncCommands = yield* Ref.get(fixture.syncCommands); |
| 1573 | assert.deepStrictEqual( |
| 1574 | syncCommands.map((command) => [command.threadId, command.stack] as const), |
| 1575 | [ |
| 1576 | [ThreadId.make("one"), { kind: "native", ...stack }], |
| 1577 | [ThreadId.make("settled"), { kind: "native", ...stack }], |
| 1578 | ], |
| 1579 | ); |
| 1580 | assert.deepStrictEqual( |
| 1581 | (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest), |
| 1582 | [ |
| 1583 | { |
| 1584 | type: "thread.pull-request.link", |
| 1585 | threadId: ThreadId.make("one"), |
| 1586 | host: "github.com", |
| 1587 | repository: "owner/repository", |
| 1588 | number: 43, |
| 1589 | url: "https://github.com/owner/repository/pull/43", |
| 1590 | source: "stack", |
| 1591 | }, |
| 1592 | ], |
| 1593 | ); |
| 1594 | }).pipe(Effect.provide(fixture.layer)); |
| 1595 | }), |
| 1596 | ); |
| 1597 | |
| 1598 | it.effect("re-reads every member's layers once a new layer joins the stack", () => |
| 1599 | Effect.gen(function* () { |
| 1600 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1601 | const stack = makeGrowingStack(); |
| 1602 | const fixture = yield* makeHarness({ |
| 1603 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(18), makeLink(20)] })]), |
| 1604 | stack: stack.read, |
| 1605 | }); |
| 1606 | const sweepAndApply = (reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"]) => |
| 1607 | sweepAgain(fixture, reactor).pipe(Effect.andThen(applyRecordedSyncs(fixture))); |
| 1608 | |
| 1609 | yield* Effect.gen(function* () { |
| 1610 | const reactor = yield* startAndSweep(fixture); |
| 1611 | yield* applyRecordedSyncs(fixture); |
| 1612 | assert.deepStrictEqual(yield* storedStackLayers(fixture), [ |
| 1613 | [18, [18, 20]], |
| 1614 | [20, [18, 20]], |
| 1615 | ]); |
| 1616 | const readsBeforeGrowth = (yield* Ref.get(fixture.stackCalls)).length; |
| 1617 | |
| 1618 | // #83 is pushed on top and linked; only its own link starts without a snapshot. |
| 1619 | stack.grow(); |
| 1620 | yield* linkPullRequest83(fixture); |
| 1621 | yield* sweepAndApply(reactor); |
| 1622 | yield* sweepAndApply(reactor); |
| 1623 | |
| 1624 | assert.deepStrictEqual(yield* storedStackLayers(fixture), [ |
| 1625 | [18, [18, 20, 83]], |
| 1626 | [20, [18, 20, 83]], |
| 1627 | [83, [18, 20, 83]], |
| 1628 | ]); |
| 1629 | const readsAfterGrowth = (yield* Ref.get(fixture.stackCalls)).slice(readsBeforeGrowth); |
| 1630 | assert.deepStrictEqual(readsAfterGrowth.map((ref) => ref.number).toSorted(), [18, 20, 83]); |
| 1631 | |
| 1632 | // Every member agrees now, so a further sweep reads no stack. |
| 1633 | yield* sweepAndApply(reactor); |
| 1634 | assert.strictEqual( |
| 1635 | (yield* Ref.get(fixture.stackCalls)).length, |
| 1636 | readsBeforeGrowth + readsAfterGrowth.length, |
| 1637 | ); |
| 1638 | }).pipe(Effect.provide(fixture.layer)); |
| 1639 | }), |
| 1640 | ); |
| 1641 | |
| 1642 | it.effect("reads past the cache when a sibling flags a member during its summary read", () => |
| 1643 | Effect.gen(function* () { |
| 1644 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1645 | const stack = makeGrowingStack(); |
| 1646 | const synced83 = yield* Deferred.make<void>(); |
| 1647 | let holdSummary = false; |
| 1648 | const fixture = yield* makeHarness({ |
| 1649 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(18)] })]), |
| 1650 | invalidate: stack.invalidate, |
| 1651 | stack: stack.cachedRead, |
| 1652 | // #18's summary stays in flight until #83 has read its stack, flagged #18 and synced. |
| 1653 | summary: (input) => |
| 1654 | (holdSummary && input.number === 18 ? Deferred.await(synced83) : Effect.void).pipe( |
| 1655 | Effect.as(makeSummary(input, { updatedAt: NOW })), |
| 1656 | ), |
| 1657 | onSync: (command) => |
| 1658 | command.number === 83 ? Deferred.succeed(synced83, undefined) : Effect.void, |
| 1659 | }); |
| 1660 | |
| 1661 | yield* Effect.gen(function* () { |
| 1662 | const reactor = yield* startAndSweep(fixture); |
| 1663 | yield* applyRecordedSyncs(fixture); |
| 1664 | |
| 1665 | // 30 s later a state change refreshes #18, which caches its two-layer read until 90 s. |
| 1666 | yield* TestClock.adjust("30 seconds"); |
| 1667 | yield* requestAndApply(fixture, reactor, 18); |
| 1668 | |
| 1669 | // #83 is pushed on top and linked as the scheduled sweep at 60 s starts, so that sweep |
| 1670 | // reads #83 for the first time while #18's summary is still in flight. |
| 1671 | stack.grow(); |
| 1672 | yield* linkPullRequest83(fixture); |
| 1673 | holdSummary = true; |
| 1674 | const invalidatedBefore = stack.invalidated.length; |
| 1675 | yield* TestClock.adjust("30 seconds"); |
| 1676 | yield* Queue.take(fixture.snapshotReads); |
| 1677 | yield* reactor.drain; |
| 1678 | yield* applyRecordedSyncs(fixture); |
| 1679 | |
| 1680 | assert.deepStrictEqual(yield* storedStackLayers(fixture), [ |
| 1681 | [18, [18, 20, 83]], |
| 1682 | [83, [18, 20, 83]], |
| 1683 | ]); |
| 1684 | assert.deepStrictEqual(stack.invalidated.slice(invalidatedBefore), [18]); |
| 1685 | }).pipe(Effect.provide(fixture.layer)); |
| 1686 | }), |
| 1687 | ); |
| 1688 | |
| 1689 | it.effect("leaves stacks in other repositories alone when their ids match", () => |
| 1690 | Effect.gen(function* () { |
| 1691 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1692 | // Without a host id the GitHub decoder falls back to the stack number, so two |
| 1693 | // repositories can both report stack "3". |
| 1694 | const otherLink = makeLink(7, null, { |
| 1695 | repository: "owner/other", |
| 1696 | url: "https://github.com/owner/other/pull/7", |
| 1697 | }); |
| 1698 | const fixture = yield* makeHarness({ |
| 1699 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(1), otherLink] })]), |
| 1700 | stack: (input) => |
| 1701 | Effect.succeed({ |
| 1702 | id: "3", |
| 1703 | number: 3, |
| 1704 | url: `https://github.com/${input.repository}/stack/3`, |
| 1705 | base: "main", |
| 1706 | layers: [ |
| 1707 | { number: input.number, headBranch: "layer-1", state: "open" }, |
| 1708 | { number: input.number + 1, headBranch: "layer-2", state: "open" }, |
| 1709 | ], |
| 1710 | }), |
| 1711 | }); |
| 1712 | |
| 1713 | yield* Effect.gen(function* () { |
| 1714 | const reactor = yield* startAndSweep(fixture); |
| 1715 | yield* applyRecordedSyncs(fixture); |
| 1716 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2); |
| 1717 | |
| 1718 | yield* sweepAgain(fixture, reactor); |
| 1719 | yield* sweepAgain(fixture, reactor); |
| 1720 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2); |
| 1721 | }).pipe(Effect.provide(fixture.layer)); |
| 1722 | }), |
| 1723 | ); |
| 1724 | |
| 1725 | it.effect("keeps existing snapshots and continues when the host fails", () => |
| 1726 | Effect.gen(function* () { |
| 1727 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1728 | const fixture = yield* makeHarness({ |
| 1729 | snapshot: makeSnapshot([ |
| 1730 | makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }), |
| 1731 | makeThread("fine", { pullRequests: [makeLink(8)] }), |
| 1732 | ]), |
| 1733 | summary: (input) => |
| 1734 | input.number === 7 |
| 1735 | ? Effect.fail( |
| 1736 | new PullRequestOperationError({ operation: "summary", detail: "host down" }), |
| 1737 | ) |
| 1738 | : Effect.succeed(makeSummary(input)), |
| 1739 | }); |
| 1740 | |
| 1741 | yield* Effect.gen(function* () { |
| 1742 | yield* startAndSweep(fixture); |
| 1743 | |
| 1744 | assert.deepStrictEqual( |
| 1745 | (yield* Ref.get(fixture.syncCommands)).map((command) => command.number), |
| 1746 | [8], |
| 1747 | ); |
| 1748 | }).pipe(Effect.provide(fixture.layer)); |
| 1749 | }), |
| 1750 | ); |
| 1751 | |
| 1752 | it.effect( |
| 1753 | "retries missing links every fifteen minutes and resumes normal reads after recovery", |
| 1754 | () => |
| 1755 | Effect.gen(function* () { |
| 1756 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1757 | const found = yield* Ref.make(false); |
| 1758 | const fixture = yield* makeHarness({ |
| 1759 | snapshot: makeSnapshot([ |
| 1760 | makeThread("missing", { pullRequests: [makeLink(9), makeLink(10, {})] }), |
| 1761 | ]), |
| 1762 | summary: (input) => |
| 1763 | Ref.get(found).pipe( |
| 1764 | Effect.flatMap((available) => |
| 1765 | available ? Effect.succeed(makeSummary(input)) : missingSummary, |
| 1766 | ), |
| 1767 | ), |
| 1768 | }); |
| 1769 | yield* Effect.gen(function* () { |
| 1770 | const reactor = yield* startAndSweep(fixture); |
| 1771 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 1772 | for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor); |
| 1773 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 1774 | yield* sweepAgain(fixture, reactor); |
| 1775 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4); |
| 1776 | assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []); |
| 1777 | |
| 1778 | yield* Ref.set(found, true); |
| 1779 | for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor); |
| 1780 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4); |
| 1781 | yield* sweepAgain(fixture, reactor); |
| 1782 | const commands = yield* Ref.get(fixture.syncCommands); |
| 1783 | assert.deepStrictEqual( |
| 1784 | commands.map((command) => command.number), |
| 1785 | [9], |
| 1786 | ); |
| 1787 | yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands)); |
| 1788 | // Recovered quiet open pull requests return to the five-minute cadence. |
| 1789 | for (let index = 0; index < 5; index += 1) yield* sweepAgain(fixture, reactor); |
| 1790 | assert.deepStrictEqual( |
| 1791 | (yield* Ref.get(fixture.summaryCalls)) |
| 1792 | .map((call) => call.number) |
| 1793 | .toSorted((left, right) => left - right), |
| 1794 | [9, 9, 9, 9, 10, 10, 10, 10], |
| 1795 | ); |
| 1796 | }).pipe(Effect.provide(fixture.layer)); |
| 1797 | }), |
| 1798 | ); |
| 1799 | |
| 1800 | it.effect("stops reading a pull request on a host it cannot browse each sweep", () => |
| 1801 | Effect.gen(function* () { |
| 1802 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1803 | const fixture = yield* makeHarness({ |
| 1804 | snapshot: makeSnapshot([ |
| 1805 | makeThread("unsupported", { pullRequests: [makeLink(9, { state: "open" })] }), |
| 1806 | makeThread("fine", { pullRequests: [makeLink(8, { state: "open" })] }), |
| 1807 | ]), |
| 1808 | summary: (input) => |
| 1809 | input.number === 9 |
| 1810 | ? Effect.fail(new PullRequestUnavailableError({ reason: "provider-unsupported" })) |
| 1811 | : Effect.succeed(makeSummary(input)), |
| 1812 | }); |
| 1813 | const unsupportedReads = Ref.get(fixture.summaryCalls).pipe( |
| 1814 | Effect.map((calls) => calls.filter((call) => call.number === 9).length), |
| 1815 | ); |
| 1816 | yield* Effect.gen(function* () { |
| 1817 | const reactor = yield* startAndSweep(fixture); |
| 1818 | for (let index = 0; index < 5; index += 1) yield* sweepAgain(fixture, reactor); |
| 1819 | const afterSweeps = yield* unsupportedReads; |
| 1820 | |
| 1821 | // A refresh another link asks for must not re-read the unsupported one as well. |
| 1822 | yield* reactor.requestSync(makeLink(9)); |
| 1823 | yield* Queue.take(fixture.snapshotReads); |
| 1824 | yield* reactor.drain; |
| 1825 | const afterItsRefresh = yield* unsupportedReads; |
| 1826 | for (let index = 0; index < 3; index += 1) { |
| 1827 | yield* reactor.requestSync(makeLink(8)); |
| 1828 | yield* Queue.take(fixture.snapshotReads); |
| 1829 | yield* reactor.drain; |
| 1830 | } |
| 1831 | assert.deepStrictEqual( |
| 1832 | { afterSweeps, afterItsRefresh, afterOtherRefreshes: yield* unsupportedReads }, |
| 1833 | { afterSweeps: 1, afterItsRefresh: 2, afterOtherRefreshes: 2 }, |
| 1834 | ); |
| 1835 | }).pipe(Effect.provide(fixture.layer)); |
| 1836 | }), |
| 1837 | ); |
| 1838 | |
| 1839 | it.effect( |
| 1840 | "holds missing links through sibling and link updates but honors a reader refresh", |
| 1841 | () => |
| 1842 | Effect.gen(function* () { |
| 1843 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1844 | const fixture = yield* makeHarness({ |
| 1845 | snapshot: makeSnapshot([makeThread("missing", { pullRequests: [makeLink(9)] })]), |
| 1846 | summary: (input) => |
| 1847 | input.number === 9 ? missingSummary : Effect.succeed(makeSummary(input)), |
| 1848 | }); |
| 1849 | const missingReads = Ref.get(fixture.summaryCalls).pipe( |
| 1850 | Effect.map((calls) => calls.filter((call) => call.number === 9).length), |
| 1851 | ); |
| 1852 | yield* Effect.gen(function* () { |
| 1853 | const reactor = yield* startAndSweep(fixture); |
| 1854 | const linked = makeThread("missing", { pullRequests: [makeLink(9), makeLink(8)] }); |
| 1855 | yield* Ref.set(fixture.snapshots, makeSnapshot([linked])); |
| 1856 | yield* Queue.offer(fixture.domainEvents, { |
| 1857 | type: "thread.pull-request-synced", |
| 1858 | id: EventId.make("sibling-synced"), |
| 1859 | threadId: linked.id, |
| 1860 | occurredAt: DateTime.makeUnsafe(NOW), |
| 1861 | payload: { ...v2PullRequestThread(linked), lastVisitedAt: null }, |
| 1862 | }); |
| 1863 | yield* Queue.take(fixture.snapshotReads); |
| 1864 | yield* reactor.drain; |
| 1865 | const afterSiblingSync = yield* missingReads; |
| 1866 | assert.deepStrictEqual( |
| 1867 | (yield* Ref.get(fixture.syncCommands)).map((command) => command.number), |
| 1868 | [8], |
| 1869 | ); |
| 1870 | |
| 1871 | yield* Queue.offer(fixture.domainEvents, { |
| 1872 | type: "thread.pull-request-link-updated", |
| 1873 | id: EventId.make("missing-link-updated"), |
| 1874 | threadId: linked.id, |
| 1875 | occurredAt: DateTime.makeUnsafe(NOW), |
| 1876 | payload: makeLink(9), |
| 1877 | }); |
| 1878 | // Let the event consumer finish even when it correctly queues no sweep. |
| 1879 | yield* TestClock.adjust(0); |
| 1880 | yield* reactor.drain; |
| 1881 | const afterLinkUpdate = yield* missingReads; |
| 1882 | |
| 1883 | yield* Queue.offer(fixture.stateChanges, makeLink(9)); |
| 1884 | yield* TestClock.adjust(0); |
| 1885 | yield* reactor.drain; |
| 1886 | const afterReaderRefresh = yield* missingReads; |
| 1887 | yield* sweepAgain(fixture, reactor); |
| 1888 | assert.deepStrictEqual( |
| 1889 | { |
| 1890 | afterSiblingSync, |
| 1891 | afterLinkUpdate, |
| 1892 | afterReaderRefresh, |
| 1893 | afterSweep: yield* missingReads, |
| 1894 | }, |
| 1895 | { afterSiblingSync: 1, afterLinkUpdate: 1, afterReaderRefresh: 2, afterSweep: 2 }, |
| 1896 | ); |
| 1897 | }).pipe(Effect.provide(fixture.layer)); |
| 1898 | }), |
| 1899 | ); |
| 1900 | |
| 1901 | it.effect("a pending stack retry respects the missing summary backoff", () => |
| 1902 | Effect.gen(function* () { |
| 1903 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1904 | const found = yield* Ref.make(true); |
| 1905 | const fixture = yield* makeHarness({ |
| 1906 | snapshot: makeSnapshot([makeThread("missing", { pullRequests: [makeLink(4)] })]), |
| 1907 | summary: (input) => |
| 1908 | Ref.get(found).pipe( |
| 1909 | Effect.flatMap((available) => |
| 1910 | available ? Effect.succeed(makeSummary(input)) : missingSummary, |
| 1911 | ), |
| 1912 | ), |
| 1913 | stack: () => |
| 1914 | Effect.fail(new PullRequestOperationError({ operation: "stack", detail: "host down" })), |
| 1915 | }); |
| 1916 | yield* Effect.gen(function* () { |
| 1917 | const reactor = yield* startAndSweep(fixture); |
| 1918 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1); |
| 1919 | yield* Ref.set(found, false); |
| 1920 | yield* sweepAgain(fixture, reactor); |
| 1921 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 1922 | for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor); |
| 1923 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2); |
| 1924 | yield* sweepAgain(fixture, reactor); |
| 1925 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3); |
| 1926 | assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1); |
| 1927 | }).pipe(Effect.provide(fixture.layer)); |
| 1928 | }), |
| 1929 | ); |
| 1930 | |
| 1931 | it.effect( |
| 1932 | "caps the failed-read backoff at the slow cadence and restarts it after a success", |
| 1933 | () => |
| 1934 | Effect.scoped( |
| 1935 | Effect.gen(function* () { |
| 1936 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1937 | const failing = yield* Ref.make(true); |
| 1938 | const fixture = yield* makeHarness({ |
| 1939 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [failingGitLabLink] })]), |
| 1940 | summary: (input) => |
| 1941 | Ref.get(failing).pipe( |
| 1942 | Effect.flatMap((fails) => |
| 1943 | fails ? Effect.fail(gitLabCliFailure) : Effect.succeed(makeSummary(input)), |
| 1944 | ), |
| 1945 | ), |
| 1946 | }); |
| 1947 | yield* Effect.gen(function* () { |
| 1948 | const reactor = yield* startAndSweep(fixture); |
| 1949 | const readMinutes = [0]; |
| 1950 | const sweepMinutes = Effect.fnUntraced(function* (from: number, to: number) { |
| 1951 | for (let minute = from; minute <= to; minute++) { |
| 1952 | const before = (yield* Ref.get(fixture.summaryCalls)).length; |
| 1953 | yield* sweepAgain(fixture, reactor); |
| 1954 | if ((yield* Ref.get(fixture.summaryCalls)).length > before) |
| 1955 | readMinutes.push(minute); |
| 1956 | } |
| 1957 | }); |
| 1958 | |
| 1959 | yield* sweepMinutes(1, 60); |
| 1960 | assert.deepStrictEqual(readMinutes, [0, 1, 3, 7, 15, 30, 45, 60]); |
| 1961 | |
| 1962 | yield* Ref.set(failing, false); |
| 1963 | yield* sweepMinutes(61, 75); |
| 1964 | yield* Ref.set(failing, true); |
| 1965 | readMinutes.length = 0; |
| 1966 | yield* sweepMinutes(76, 80); |
| 1967 | assert.deepStrictEqual(readMinutes, [76, 77, 79]); |
| 1968 | }).pipe(Effect.provide(fixture.layer)); |
| 1969 | }), |
| 1970 | ), |
| 1971 | ); |
| 1972 | |
| 1973 | it.effect("reads a backed-off link at once when a refresh asks, then keeps backing off", () => |
| 1974 | Effect.scoped( |
| 1975 | Effect.gen(function* () { |
| 1976 | yield* TestClock.setTime(Date.parse(NOW)); |
| 1977 | const fixture = yield* makeHarness({ |
| 1978 | snapshot: makeSnapshot([makeThread("one", { pullRequests: [failingGitLabLink] })]), |
| 1979 | summary: () => Effect.fail(gitLabCliFailure), |
| 1980 | }); |
| 1981 | yield* Effect.gen(function* () { |
| 1982 | const reactor = yield* startAndSweep(fixture); |
| 1983 | yield* sweepFor(fixture, reactor, 4); |
| 1984 | const backedOffReads = (yield* Ref.get(fixture.summaryCalls)).length; |
| 1985 | |
| 1986 | yield* reactor.requestSync(failingGitLabLink); |
| 1987 | yield* Queue.take(fixture.snapshotReads); |
| 1988 | yield* reactor.drain; |
| 1989 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 1); |
| 1990 | |
| 1991 | // The refresh failed at minute 4 with the backoff doubled to 8 minutes. |
| 1992 | yield* sweepFor(fixture, reactor, 7); |
| 1993 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 1); |
| 1994 | yield* sweepAgain(fixture, reactor); |
| 1995 | assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, backedOffReads + 2); |
| 1996 | }).pipe(Effect.provide(fixture.layer)); |
| 1997 | }), |
| 1998 | ), |
| 1999 | ); |
| 2000 | |
| 2001 | it.effect.each([ |
| 2002 | "gh pr merge 7 --squash 2>&1 | tail -3", |
| 2003 | "cafe pr merge 7 --squash", |
| 2004 | "az repos pr update --id 7 --status completed", |
| 2005 | ])("reads open links fresh only for a thread that ran `%s`", (mergeCommand) => |
| 2006 | Effect.gen(function* () { |
| 2007 | yield* TestClock.setTime(Date.parse(NOW)); |
| 2008 | const state = yield* Ref.make<PullRequestSummary["state"]>("open"); |
| 2009 | const invalidated = yield* Ref.make<ReadonlyArray<number>>([]); |
| 2010 | const fixture = yield* makeHarness({ |
| 2011 | snapshot: makeSnapshot([ |
| 2012 | makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }), |
| 2013 | makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }), |
| 2014 | ]), |
| 2015 | summary: (input) => |
| 2016 | Ref.get(state).pipe( |
| 2017 | Effect.map((current) => |
| 2018 | makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}), |
| 2019 | ), |
| 2020 | ), |
| 2021 | invalidate: ({ reference }) => |
| 2022 | Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]), |
| 2023 | }); |
| 2024 | |
| 2025 | yield* Effect.gen(function* () { |
| 2026 | const reactor = yield* startAndSweep(fixture); |
| 2027 | yield* Ref.set(state, "merged"); |
| 2028 | yield* Ref.set(fixture.summaryCalls, []); |
| 2029 | |
| 2030 | yield* Queue.offerAll(fixture.domainEvents, [ |
| 2031 | commandRan(ThreadId.make("other"), "gh pr view 9"), |
| 2032 | runUpdated(ThreadId.make("other"), "completed"), |
| 2033 | commandRan(ThreadId.make("agent"), mergeCommand), |
| 2034 | runUpdated(ThreadId.make("agent"), "completed"), |
| 2035 | ]); |
| 2036 | yield* Queue.take(fixture.snapshotReads); |
| 2037 | yield* Queue.take(fixture.snapshotReads); |
| 2038 | yield* reactor.drain; |
| 2039 | |
| 2040 | assert.deepStrictEqual(yield* Ref.get(invalidated), [7]); |
| 2041 | assert.deepStrictEqual( |
| 2042 | (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number), |
| 2043 | [7], |
| 2044 | ); |
| 2045 | assert.deepStrictEqual( |
| 2046 | (yield* Ref.get(fixture.syncCommands)).map((command) => [ |
| 2047 | command.number, |
| 2048 | command.snapshot.state, |
| 2049 | ]), |
| 2050 | [[7, "merged"]], |
| 2051 | ); |
| 2052 | }).pipe(Effect.provide(fixture.layer)); |
| 2053 | }), |
| 2054 | ); |
| 2055 | |
| 2056 | it.effect("reopens a watch's checks when its thread's agent pushes", () => |
| 2057 | Effect.gen(function* () { |
| 2058 | yield* TestClock.setTime(Date.parse(NOW)); |
| 2059 | const watch = { |
| 2060 | startedAt: NOW, |
| 2061 | headSha: "aaaaaaaaaa", |
| 2062 | failedChecks: [], |
| 2063 | passed: true, |
| 2064 | passedChecks: ["test"], |
| 2065 | remarksThrough: NOW, |
| 2066 | remarkIds: [], |
| 2067 | conflicting: false, |
| 2068 | wakes: 0, |
| 2069 | }; |
| 2070 | const fixture = yield* makeHarness({ |
| 2071 | snapshot: makeSnapshot([ |
| 2072 | makeThread("agent", { |
| 2073 | pullRequests: [ |
| 2074 | makeLink(7, { state: "open" }, { watch: { ...watch, checksPending: false } }), |
| 2075 | ], |
| 2076 | }), |
| 2077 | makeThread("unread", { |
| 2078 | pullRequests: [makeLink(8, { state: "open" }, { watch })], |
| 2079 | }), |
| 2080 | ]), |
| 2081 | }); |
| 2082 | |
| 2083 | yield* Effect.gen(function* () { |
| 2084 | yield* startAndSweep(fixture); |
| 2085 | const agent = ThreadId.make("agent"); |
| 2086 | yield* Queue.offerAll(fixture.domainEvents, [ |
| 2087 | commandRan(agent, "git status && echo 'then git push'", undefined, "status"), |
| 2088 | // A watch that has not read its checks yet has no answer to forget. |
| 2089 | commandRan(ThreadId.make("unread"), "git push", undefined, "unread-push"), |
| 2090 | commandRan(agent, "cd app && git -C . push --force-with-lease", undefined, "push"), |
| 2091 | commandRan(agent, '/bin/zsh -lc "gh stack submit --auto"', undefined, "stack"), |
| 2092 | ]); |
| 2093 | for (const item of ["push", "stack"]) { |
| 2094 | const command = yield* Queue.take(fixture.reopenCommands); |
| 2095 | assert.deepStrictEqual( |
| 2096 | [command.threadId, command.commandId], |
| 2097 | [agent, `server:pr-push-checks:agent:item:agent:${item}`], |
| 2098 | ); |
| 2099 | } |
| 2100 | }).pipe(Effect.provide(fixture.layer)); |
| 2101 | }), |
| 2102 | ); |
| 2103 | |
| 2104 | it.effect("reads open links again when the run ends, after `merge --auto` left them open", () => |
| 2105 | Effect.gen(function* () { |
| 2106 | yield* TestClock.setTime(Date.parse(NOW)); |
| 2107 | const state = yield* Ref.make<PullRequestSummary["state"]>("open"); |
| 2108 | const fixture = yield* makeHarness({ |
| 2109 | snapshot: makeSnapshot([ |
| 2110 | makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }), |
| 2111 | ]), |
| 2112 | summary: (input) => |
| 2113 | Ref.get(state).pipe( |
| 2114 | Effect.map((current) => |
| 2115 | makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}), |
| 2116 | ), |
| 2117 | ), |
| 2118 | }); |
| 2119 | |
| 2120 | yield* Effect.gen(function* () { |
| 2121 | const reactor = yield* startAndSweep(fixture); |
| 2122 | yield* Queue.offer( |
| 2123 | fixture.domainEvents, |
| 2124 | commandRan(ThreadId.make("agent"), "gh pr merge 7 --auto"), |
| 2125 | ); |
| 2126 | yield* Queue.take(fixture.snapshotReads); |
| 2127 | yield* Queue.take(fixture.snapshotReads); |
| 2128 | yield* reactor.drain; |
| 2129 | yield* Ref.set(state, "merged"); |
| 2130 | yield* Ref.set(fixture.syncCommands, []); |
| 2131 | |
| 2132 | yield* Queue.offer(fixture.domainEvents, runUpdated(ThreadId.make("agent"), "completed")); |
| 2133 | yield* Queue.take(fixture.snapshotReads); |
| 2134 | yield* Queue.take(fixture.snapshotReads); |
| 2135 | yield* reactor.drain; |
| 2136 | |
| 2137 | assert.deepStrictEqual( |
| 2138 | (yield* Ref.get(fixture.syncCommands)).map((command) => [ |
| 2139 | command.number, |
| 2140 | command.snapshot.state, |
| 2141 | ]), |
| 2142 | [[7, "merged"]], |
| 2143 | ); |
| 2144 | }).pipe(Effect.provide(fixture.layer)); |
| 2145 | }), |
| 2146 | ); |
| 2147 | |
| 2148 | it.effect.each(["open", "closed"] as const)( |
| 2149 | "reads %s links fresh as soon as a merge command ends, before its run ends", |
| 2150 | (initialState) => |
| 2151 | Effect.gen(function* () { |
| 2152 | yield* TestClock.setTime(Date.parse(NOW)); |
| 2153 | const state = yield* Ref.make<PullRequestSummary["state"]>(initialState); |
| 2154 | const initialSnapshot = { |
| 2155 | state: initialState, |
| 2156 | closedAt: initialState === "closed" ? "2026-08-20T00:00:00.000Z" : null, |
| 2157 | }; |
| 2158 | const fixture = yield* makeHarness({ |
| 2159 | snapshot: makeSnapshot([ |
| 2160 | makeThread("agent", { pullRequests: [makeLink(7, initialSnapshot)] }), |
| 2161 | ]), |
| 2162 | summary: (input) => |
| 2163 | Ref.get(state).pipe( |
| 2164 | Effect.map((current) => |
| 2165 | makeSummary( |
| 2166 | input, |
| 2167 | current === "merged" ? { state: current, mergedAt: NOW } : initialSnapshot, |
| 2168 | ), |
| 2169 | ), |
| 2170 | ), |
| 2171 | }); |
| 2172 | |
| 2173 | yield* Effect.gen(function* () { |
| 2174 | const reactor = yield* startAndSweep(fixture); |
| 2175 | yield* Ref.set(state, "merged"); |
| 2176 | yield* Ref.set(fixture.summaryCalls, []); |
| 2177 | |
| 2178 | yield* Queue.offer( |
| 2179 | fixture.domainEvents, |
| 2180 | commandRan(ThreadId.make("agent"), "gh pr merge 7"), |
| 2181 | ); |
| 2182 | yield* Queue.take(fixture.snapshotReads); |
| 2183 | yield* Queue.take(fixture.snapshotReads); |
| 2184 | yield* reactor.drain; |
| 2185 | |
| 2186 | assert.deepStrictEqual( |
| 2187 | (yield* Ref.get(fixture.syncCommands)).map((command) => [ |
| 2188 | command.number, |
| 2189 | command.snapshot.state, |
| 2190 | ]), |
| 2191 | [[7, "merged"]], |
| 2192 | ); |
| 2193 | }).pipe(Effect.provide(fixture.layer)); |
| 2194 | }), |
| 2195 | ); |
| 2196 | |
| 2197 | it.effect.each([ |
| 2198 | { |
| 2199 | name: "a plain create", |
| 2200 | input: |
| 2201 | 'gh pr create --base main --head feature --title "fix: 7 things" --body-file /tmp/body.md', |
| 2202 | output: "https://github.com/owner/repository/pull/124\n", |
| 2203 | linked: [124], |
| 2204 | }, |
| 2205 | { |
| 2206 | name: "a Codex shell wrapper after a push", |
| 2207 | input: '/bin/zsh -lc "git push -u origin feature 2>&1 | tail -2 && gh pr create --fill"', |
| 2208 | output: [ |
| 2209 | "remote: Create a pull request for 'feature' on GitHub by visiting:", |
| 2210 | "remote: https://github.com/owner/repository/pull/new/feature", |
| 2211 | "https://github.com/owner/repository/pull/124", |
| 2212 | ].join("\n"), |
| 2213 | linked: [124], |
| 2214 | }, |
| 2215 | { |
| 2216 | name: "a Codex script quoted in pieces around a heredoc", |
| 2217 | input: |
| 2218 | "/bin/zsh -lc \"cat > /tmp/body.md <<'EOF'\nSet the \"'`hidden`'\" flag.\nEOF\ngh pr create --fill --body-file /tmp/body.md\"", |
| 2219 | output: "https://github.com/owner/repository/pull/62\n", |
| 2220 | linked: [62], |
| 2221 | }, |
| 2222 | { |
| 2223 | name: "an older pull request read in the same command", |
| 2224 | input: "gh pr view 120 --json url --jq .url && gh pr create --fill", |
| 2225 | output: |
| 2226 | "https://github.com/owner/repository/pull/120\nhttps://github.com/owner/repository/pull/124", |
| 2227 | linked: [124], |
| 2228 | }, |
| 2229 | { |
| 2230 | name: "both layers of a stack", |
| 2231 | input: "gh pr create --base main --head a --fill && gh pr create --base a --head b --fill", |
| 2232 | output: |
| 2233 | "https://github.com/owner/repository/pull/124\nhttps://github.com/owner/repository/pull/125", |
| 2234 | linked: [124, 125], |
| 2235 | }, |
| 2236 | { |
| 2237 | name: "the first pull request of a new repository", |
| 2238 | input: "cargo test 2>&1 | tail -1 && timeout 60 gh pr create -R owner/repository --fill", |
| 2239 | output: "test result: ok\nhttps://github.com/owner/repository/pull/1", |
| 2240 | linked: [1], |
| 2241 | }, |
| 2242 | { |
| 2243 | name: "a GitLab merge request", |
| 2244 | input: "glab mr create --fill --yes", |
| 2245 | output: |
| 2246 | "!3 Fix the thing (feature)\n https://gitlab.com/owner/repository/-/merge_requests/3\n", |
| 2247 | linked: [3], |
| 2248 | }, |
| 2249 | { |
| 2250 | name: "a new pull request whose number appears in the create command", |
| 2251 | input: "timeout 60 gh pr create --fill", |
| 2252 | output: "https://github.com/owner/repository/pull/60", |
| 2253 | linked: [60], |
| 2254 | }, |
| 2255 | { |
| 2256 | name: "a create subcommand that does not end its shell word", |
| 2257 | input: "gh pr create#typo; gh pr view --json url --jq .url", |
| 2258 | output: "https://github.com/owner/repository/pull/124", |
| 2259 | linked: [], |
| 2260 | }, |
| 2261 | { |
| 2262 | name: "a create after an empty heredoc", |
| 2263 | input: "cat > /tmp/notes.md <<'EOF'\nEOF\ngh pr create --fill", |
| 2264 | output: "https://github.com/owner/repository/pull/124", |
| 2265 | linked: [124], |
| 2266 | }, |
| 2267 | { |
| 2268 | name: "a read with no create", |
| 2269 | input: "gh pr view 124 --json url --jq .url", |
| 2270 | output: "https://github.com/owner/repository/pull/124", |
| 2271 | linked: [], |
| 2272 | }, |
| 2273 | { |
| 2274 | name: "a create command quoted in another program's query", |
| 2275 | input: `sqlite3 audit.db "select output from items where input like '%gh pr create%'"`, |
| 2276 | output: "https://github.com/owner/repository/pull/124", |
| 2277 | linked: [], |
| 2278 | }, |
| 2279 | { |
| 2280 | name: "a create command with a separator inside quotes", |
| 2281 | input: "echo 'example: gh pr create; gh pr create --fill' && gh pr view --json url --jq .url", |
| 2282 | output: "https://github.com/owner/repository/pull/124", |
| 2283 | linked: [], |
| 2284 | }, |
| 2285 | { |
| 2286 | name: "more URLs than create commands", |
| 2287 | input: "gh pr view --json url --jq .url && gh pr create --fill", |
| 2288 | output: |
| 2289 | "https://github.com/owner/repository/pull/120\nhttps://github.com/owner/repository/pull/124", |
| 2290 | linked: [], |
| 2291 | }, |
| 2292 | { |
| 2293 | name: "a create command only in heredoc text", |
| 2294 | input: |
| 2295 | "cat > notes.md <<'EOF'\nOpen it with gh pr create.\nEOF\ngh pr list --json url --jq '.[].url'", |
| 2296 | output: "https://github.com/owner/repository/pull/124", |
| 2297 | linked: [], |
| 2298 | }, |
| 2299 | { |
| 2300 | name: "a create command after a comment that starts at a separator", |
| 2301 | input: "gh pr view --json url --jq .url;# note; gh pr create --fill", |
| 2302 | output: "https://github.com/owner/repository/pull/124", |
| 2303 | linked: [], |
| 2304 | }, |
| 2305 | { |
| 2306 | name: "a create beside a command that lists other pull requests", |
| 2307 | input: "gh pr list --json url --jq '.[].url' && gh pr create --fill > /dev/null", |
| 2308 | output: "https://github.com/owner/repository/pull/120", |
| 2309 | linked: [], |
| 2310 | }, |
| 2311 | { |
| 2312 | name: "another host's URL beside a create command", |
| 2313 | input: "gh pr create --fill", |
| 2314 | output: "https://gitlab.com/owner/repository/-/merge_requests/3", |
| 2315 | linked: [], |
| 2316 | }, |
| 2317 | { |
| 2318 | name: "an existing pull request quoted in another command", |
| 2319 | input: |
| 2320 | "printf '%s\\n' 'https://github.com/owner/repository/pull/120'; gh pr create --fill > /dev/null", |
| 2321 | output: "https://github.com/owner/repository/pull/120", |
| 2322 | linked: [], |
| 2323 | }, |
| 2324 | ])("links what the command created: $name", ({ input, output, linked }) => |
| 2325 | Effect.gen(function* () { |
| 2326 | yield* TestClock.setTime(Date.parse(NOW)); |
| 2327 | const fixture = yield* makeHarness({ snapshot: mergingSnapshot() }); |
| 2328 | |
| 2329 | yield* Effect.gen(function* () { |
| 2330 | const reactor = yield* startAndSweep(fixture); |
| 2331 | const child = ThreadId.make("delegated-child"); |
| 2332 | const links = yield* linksFrom(fixture, reactor, [commandRan(child, input, output)]); |
| 2333 | |
| 2334 | assert.deepStrictEqual( |
| 2335 | links.map((command) => [command.threadId, command.number, command.source]), |
| 2336 | linked.map((number) => [child, number, "created"]), |
| 2337 | ); |
| 2338 | }).pipe(Effect.provide(fixture.layer)); |
| 2339 | }), |
| 2340 | ); |
| 2341 | |
| 2342 | it.effect("links a created pull request once its command settles, with one command id", () => |
| 2343 | Effect.gen(function* () { |
| 2344 | yield* TestClock.setTime(Date.parse(NOW)); |
| 2345 | const fixture = yield* makeHarness({ snapshot: mergingSnapshot() }); |
| 2346 | |
| 2347 | yield* Effect.gen(function* () { |
| 2348 | const reactor = yield* startAndSweep(fixture); |
| 2349 | const settled = commandRan( |
| 2350 | ThreadId.make("agent"), |
| 2351 | "gh pr create --fill", |
| 2352 | "https://github.com/owner/repository/pull/124", |
| 2353 | ); |
| 2354 | assert.strictEqual(settled.type, "turn-item.updated"); |
| 2355 | if (settled.type !== "turn-item.updated") return; |
| 2356 | |
| 2357 | const links = yield* linksFrom(fixture, reactor, [ |
| 2358 | { ...settled, payload: { ...settled.payload, status: "running" } }, |
| 2359 | settled, |
| 2360 | settled, |
| 2361 | ]); |
| 2362 | |
| 2363 | assert.deepStrictEqual( |
| 2364 | links.map((command) => command.number), |
| 2365 | [124, 124], |
| 2366 | ); |
| 2367 | assert.strictEqual(links[0]!.commandId, links[1]!.commandId); |
| 2368 | }).pipe(Effect.provide(fixture.layer)); |
| 2369 | }), |
| 2370 | ); |
| 2371 | }); |