From 2ff63fb2b713102e1191a8651b050864cbe9bb9f Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 23 Jul 2026 23:24:57 -0700 Subject: [PATCH] Address round-2 review feedback - Ignore review-thread activity whose latest comment is the viewer's own reply, breaking the self-triggered wake cycle - Retry boot reconciliation on the first successful poll instead of swallowing a failed shell snapshot at startup - Remove the registration when archive teardown dispatch fails so archived threads are never polled or woken again - Stamp wake claims with the turn command's createdAt so provider turn-start failures (which echo that timestamp) match the release condition; a fresh post-dispatch timestamp could never match Co-Authored-By: Claude Fable 5 --- .../src/monitor/PullRequestMonitor.test.ts | 110 +++++++++++++++- apps/server/src/monitor/PullRequestMonitor.ts | 119 ++++++++++-------- apps/server/src/monitor/monitorDiff.test.ts | 24 ++++ apps/server/src/monitor/monitorDiff.ts | 1 + .../sourceControl/gitHubPullRequestMonitor.ts | 7 +- 5 files changed, 207 insertions(+), 54 deletions(-) diff --git a/apps/server/src/monitor/PullRequestMonitor.test.ts b/apps/server/src/monitor/PullRequestMonitor.test.ts index 77fceb2127..359733b384 100644 --- a/apps/server/src/monitor/PullRequestMonitor.test.ts +++ b/apps/server/src/monitor/PullRequestMonitor.test.ts @@ -18,6 +18,7 @@ import * as Stream from "effect/Stream"; import { OrchestrationCommandInvariantError } from "../orchestration/Errors.ts"; import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; +import { PersistenceSqlError } from "../persistence/Errors.ts"; import { GitHubPullRequestMonitorDecodeError, type PullRequestMonitorSnapshot, @@ -58,6 +59,7 @@ const snapshot = ( const comment = (id: string) => ({ id, author: { login: "bugbot", type: "app" as const }, + latestCommentByViewer: false, body: `Finding ${id}`, path: "src/file.ts", line: 12, @@ -104,7 +106,10 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { readonly current: { value: PullRequestMonitorSnapshot }; readonly wakeCount?: number; readonly failWake?: boolean; + readonly failEnd?: boolean; readonly failFreshFetch?: boolean; + readonly reconcileFailures?: number; + readonly reconcileThreadId?: ThreadId; readonly busy?: { value: boolean }; readonly afterUpdate?: () => void; readonly changeGenerationAfterUpdate?: boolean; @@ -131,7 +136,10 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { Effect.sync(() => { if (registration?.generation === generation) registration = undefined; }), - get: () => Effect.sync(() => (registration ? Option.some(registration) : Option.none())), + get: (requestedThreadId) => + Effect.sync(() => + registration?.threadId === requestedThreadId ? Option.some(registration) : Option.none(), + ), updateCursor: (_, cursor, expectedGeneration) => Effect.sync(() => { ordering.push("ack"); @@ -203,10 +211,19 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { ); } } + if (command.type === "thread.monitor.end" && input.failEnd) { + return Effect.fail( + new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "rejected", + }), + ); + } return Effect.succeed({ sequence: commands.length }); }, }); let fetchCount = 0; + let reconcileCount = 0; const monitor = yield* make.pipe( Effect.provideService(MonitorRegistry.MonitorRegistry, registry), Effect.provideService(PullRequestSnapshotFetcher, { @@ -228,6 +245,45 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { Effect.provide( Layer.mergeAll( Layer.mock(ProjectionSnapshotQuery)({ + getShellSnapshot: () => { + reconcileCount += 1; + if (reconcileCount <= (input.reconcileFailures ?? 0)) { + return Effect.fail( + new PersistenceSqlError({ + operation: "PullRequestMonitor.test:getShellSnapshot", + detail: "reconcile failed", + }), + ); + } + return Effect.succeed({ + snapshotSequence: 0, + projects: [], + threads: input.reconcileThreadId + ? [ + { + ...thread(), + id: input.reconcileThreadId, + monitor: { + status: "monitoring" as const, + prNumber: 42, + startedAt: now, + blockersSummary: "", + headSha: "head-1", + wakeCount: 0, + updatedAt: now, + endedAt: null, + endedReason: null, + }, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + }, + ] + : [], + updatedAt: now, + }); + }, getThreadDetailById: () => Effect.succeed(Option.some(thread(input.busy?.value ?? false))), }), @@ -486,4 +542,56 @@ describe("PullRequestMonitor dispatch protocol", () => { assert.strictEqual(h.getRegistration(), undefined); }), ); + + it.effect("removes an archived registration when projecting monitor end fails", () => + Effect.gen(function* () { + const h = yield* harness({ + initial: snapshot(), + current: { value: snapshot() }, + failEnd: true, + }); + yield* h.monitor.handleDomainEvent({ + sequence: 1, + eventId: EventId.make("archived"), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: now, + commandId: CommandId.make("archived"), + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.archived", + payload: { threadId, archivedAt: now, updatedAt: now }, + }); + assert.strictEqual(h.getRegistration(), undefined); + }), + ); + + it.effect("retries boot reconciliation on the first poll after a failed attempt", () => + Effect.gen(function* () { + const orphanThreadId = ThreadId.make("orphan-monitor-thread"); + const h = yield* harness({ + initial: snapshot(), + current: { value: snapshot() }, + reconcileFailures: 1, + reconcileThreadId: orphanThreadId, + }); + + yield* h.monitor.pollOnce; + assert.strictEqual( + h.commands.some( + (command) => command.type === "thread.monitor.end" && command.threadId === orphanThreadId, + ), + false, + ); + + yield* h.monitor.pollOnce; + assert.strictEqual( + h.commands.some( + (command) => command.type === "thread.monitor.end" && command.threadId === orphanThreadId, + ), + true, + ); + }), + ); }); diff --git a/apps/server/src/monitor/PullRequestMonitor.ts b/apps/server/src/monitor/PullRequestMonitor.ts index 614a1dfd30..291673c2cb 100644 --- a/apps/server/src/monitor/PullRequestMonitor.ts +++ b/apps/server/src/monitor/PullRequestMonitor.ts @@ -85,6 +85,7 @@ export const make = Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const claims = yield* Ref.make>(new Map()); const lastPollFailed = yield* Ref.make(false); + const reconciled = yield* Ref.make(false); const mutateClaim = ( threadId: ThreadId, @@ -238,15 +239,17 @@ export const make = Effect.gen(function* () { }) .pipe( Effect.tap(() => - DateTime.now.pipe( - Effect.map(DateTime.formatIso), - Effect.flatMap((dispatchedAt) => - mutateClaim(registration.threadId, (claim) => - claim?.commandId === commandId - ? { ...claim, phase: "in-flight", dispatchedAt } - : claim, - ), - ), + // Stamp the claim with the command's own createdAt: a provider + // turn-start failure activity echoes exactly this timestamp + // (ProviderCommandReactor appends it with the event payload's + // createdAt), so equality means "our wake failed" while an older + // turn's delayed failure compares strictly older. A post-dispatch + // DateTime.now here would always exceed the echoed timestamp and + // make the release condition unsatisfiable. + mutateClaim(registration.threadId, (claim) => + claim?.commandId === commandId + ? { ...claim, phase: "in-flight", dispatchedAt: createdAt } + : claim, ), ), Effect.tap(() => @@ -317,7 +320,43 @@ export const make = Effect.gen(function* () { ); }); + const reconcile = Effect.fn("PullRequestMonitor.reconcile")(function* () { + if (yield* Ref.get(reconciled)) return; + const shell = yield* snapshots.getShellSnapshot(); + yield* Effect.forEach( + shell.threads.filter((thread) => thread.monitor?.status === "monitoring"), + (thread) => + registry.get(thread.id).pipe( + Effect.flatMap((registration) => { + if (Option.isSome(registration)) return Effect.void; + return Effect.gen(function* () { + const endedAt = DateTime.formatIso(yield* DateTime.now); + yield* engine.dispatch({ + type: "thread.monitor.end", + commandId: CommandId.make(`monitor-boot-reconcile:${thread.id}:${endedAt}`), + threadId: thread.id, + reason: "session-ended", + blockersSummary: "", + endedAt, + }); + }); + }), + ), + { discard: true }, + ); + yield* Ref.set(reconciled, true); + }); + const pollOnce = Ref.set(lastPollFailed, false).pipe( + Effect.andThen( + reconcile().pipe( + Effect.catch((error) => + Effect.logWarning("pull request monitor boot reconcile failed", { error }).pipe( + Effect.andThen(Ref.set(lastPollFailed, true)), + ), + ), + ), + ), Effect.andThen(registry.listActive), Effect.flatMap((registrations) => Effect.forEach( @@ -344,13 +383,25 @@ export const make = Effect.gen(function* () { Effect.flatMap((registration) => Option.isNone(registration) ? Effect.void - : end(threadId, "stopped", "", registration.value.generation), - ), - Effect.catch((error) => - Effect.logWarning("pull request monitor archive teardown failed", { - threadId, - error, - }), + : end(threadId, "stopped", "", registration.value.generation).pipe( + Effect.catch((error) => + Effect.logWarning( + "pull request monitor archive projection stuck; removing registration", + { + threadId, + error, + }, + ).pipe( + Effect.andThen(registry.remove(threadId, registration.value.generation)), + Effect.andThen( + mutateClaim(threadId, (claim) => + claim?.generation === registration.value.generation ? undefined : claim, + ), + ), + Effect.asVoid, + ), + ), + ), ), ); } @@ -393,42 +444,6 @@ export const make = Effect.gen(function* () { }; const start = Effect.fn("PullRequestMonitor.start")(function* () { - const shell = yield* snapshots - .getShellSnapshot() - .pipe( - Effect.catch((error) => - Effect.logWarning("pull request monitor boot reconcile query failed", { error }).pipe( - Effect.as({ threads: [] as const }), - ), - ), - ); - yield* Effect.forEach( - shell.threads.filter((thread) => thread.monitor?.status === "monitoring"), - (thread) => - registry.get(thread.id).pipe( - Effect.flatMap((registration) => { - if (Option.isSome(registration)) return Effect.void; - return Effect.gen(function* () { - const endedAt = DateTime.formatIso(yield* DateTime.now); - yield* engine.dispatch({ - type: "thread.monitor.end", - commandId: CommandId.make(`monitor-boot-reconcile:${thread.id}:${endedAt}`), - threadId: thread.id, - reason: "session-ended", - blockersSummary: "", - endedAt, - }); - }); - }), - Effect.catch((error) => - Effect.logWarning("pull request monitor boot reconcile failed", { - threadId: thread.id, - error, - }), - ), - ), - { discard: true }, - ); yield* Effect.forkDetach(Stream.runForEach(engine.streamDomainEvents, onEvent)); yield* Effect.forkDetach( Effect.forever( diff --git a/apps/server/src/monitor/monitorDiff.test.ts b/apps/server/src/monitor/monitorDiff.test.ts index 79f7587690..a31d13770a 100644 --- a/apps/server/src/monitor/monitorDiff.test.ts +++ b/apps/server/src/monitor/monitorDiff.test.ts @@ -23,6 +23,7 @@ const snapshot = ( const thread = (updatedAt = "2026-01-01T00:00:00Z", resolved = false) => ({ id: "thread-1", author: { login: "review-bot", type: "app" as const }, + latestCommentByViewer: false, body: "Fix this", path: "src/a.ts", line: 3, @@ -69,6 +70,29 @@ describe("pull request monitor diff", () => { ]); }); + it("does not wake for the viewer's reply, then wakes for a subsequent reviewer comment", () => { + const initial = snapshot({ reviewThreads: [thread()] }); + const selfReply = snapshot({ + reviewThreads: [ + { + ...thread("2026-01-02T00:00:00Z"), + author: { login: "claude", type: "user" as const }, + latestCommentByViewer: true, + }, + ], + }); + const ignored = diffPullRequestMonitorSnapshot(cursorFromSnapshot(initial), selfReply); + assert.deepStrictEqual(ignored.actionableEvents, []); + + const reviewerReply = snapshot({ + reviewThreads: [thread("2026-01-03T00:00:00Z")], + }); + assert.deepStrictEqual( + diffPullRequestMonitorSnapshot(ignored.nextCursor, reviewerReply).actionableEvents, + [{ kind: "new-review-comment", threadId: "thread-1", edited: true }], + ); + }); + it("detects new and edited bot issue comments", () => { const issueComment = { id: "comment-1", diff --git a/apps/server/src/monitor/monitorDiff.ts b/apps/server/src/monitor/monitorDiff.ts index 8134bef48d..7aaeda8186 100644 --- a/apps/server/src/monitor/monitorDiff.ts +++ b/apps/server/src/monitor/monitorDiff.ts @@ -70,6 +70,7 @@ export function diffPullRequestMonitorSnapshot( for (const thread of snapshot.reviewThreads) { const previous = previousCursor.threadVersions[thread.id]; if ( + !thread.latestCommentByViewer && !thread.resolved && (!previous || previous.resolved || previous.updatedAt !== thread.updatedAt) ) { diff --git a/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts b/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts index bd55333a5f..ef17444f62 100644 --- a/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts +++ b/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts @@ -22,6 +22,7 @@ export interface PullRequestMonitorReview { export interface PullRequestMonitorReviewThread { readonly id: string; readonly author: PullRequestMonitorActor; + readonly latestCommentByViewer: boolean; readonly body: string; readonly path: string | null; readonly line: number | null; @@ -100,6 +101,7 @@ const ThreadSchema = Schema.Struct({ }); const PullRequestPageSchema = Schema.Struct({ data: Schema.Struct({ + viewer: Schema.Struct({ login: Schema.String }), repository: Schema.Struct({ pullRequest: Schema.NullOr( Schema.Struct({ @@ -260,6 +262,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna let threadCursor: string | null = null; let reviewsComplete = false; let threadsComplete = false; + let viewerLogin: string | undefined; let metadata: | Pick< PullRequestMonitorSnapshot, @@ -267,7 +270,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna > | undefined; do { - const query = `query($owner:String!,$name:String!,$number:Int!,$reviews:String,$threads:String){repository(owner:$owner,name:$name){pullRequest(number:$number){state isDraft merged mergeable headRefOid baseRefName reviews(first:100,after:$reviews){nodes{id author{login __typename} state submittedAt commit{oid}} pageInfo{hasNextPage endCursor}} reviewThreads(first:100,after:$threads){nodes{id isResolved comments(last:1){nodes{author{login __typename} body path line createdAt updatedAt}}} pageInfo{hasNextPage endCursor}}}}}`; + const query = `query($owner:String!,$name:String!,$number:Int!,$reviews:String,$threads:String){viewer{login} repository(owner:$owner,name:$name){pullRequest(number:$number){state isDraft merged mergeable headRefOid baseRefName reviews(first:100,after:$reviews){nodes{id author{login __typename} state submittedAt commit{oid}} pageInfo{hasNextPage endCursor}} reviewThreads(first:100,after:$threads){nodes{id isResolved comments(last:1){nodes{author{login __typename} body path line createdAt updatedAt}}} pageInfo{hasNextPage endCursor}}}}}`; const result: VcsProcess.VcsProcessOutput = yield* github.execute({ cwd: input.cwd, args: [ @@ -294,6 +297,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna const pr: NonNullable< Schema.Schema.Type["data"]["repository"]["pullRequest"] > | null = page.data.repository.pullRequest; + viewerLogin ??= page.data.viewer.login; if (!pr) { return yield* new GitHubPullRequestMonitorDecodeError({ command: "gh", @@ -334,6 +338,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna reviewThreads.set(thread.id, { id: thread.id, author: actor(comment.author), + latestCommentByViewer: comment.author?.login === viewerLogin, body: comment.body, path: comment.path, line: comment.line,