diff --git a/apps/server/src/mcp/toolkits/monitor/handlers.ts b/apps/server/src/mcp/toolkits/monitor/handlers.ts index 19f77e74f1..6d48bd0f2d 100644 --- a/apps/server/src/mcp/toolkits/monitor/handlers.ts +++ b/apps/server/src/mcp/toolkits/monitor/handlers.ts @@ -1,6 +1,5 @@ import { CommandId } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; -import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -64,11 +63,12 @@ const monitorStart = Effect.fn("MonitorToolkit.monitorStart")(function* ({ const warning = snapshot.draft ? `PR #${prNumber} is a draft. Monitoring started, but review bots may not run until it is marked ready for review.` : null; - const generation = yield* Clock.currentTimeMillis; + const generation = yield* registry.nextGeneration; const won = yield* registry.registerIfAbsent({ threadId: invocation.threadId, prNumber, generation, + startedAt: createdAt, cursor: cursorFromSnapshot(snapshot), wakeCount: 0, repoCwd, diff --git a/apps/server/src/monitor/MonitorRegistry.ts b/apps/server/src/monitor/MonitorRegistry.ts index f185d08e3a..cb52c095cf 100644 --- a/apps/server/src/monitor/MonitorRegistry.ts +++ b/apps/server/src/monitor/MonitorRegistry.ts @@ -12,6 +12,7 @@ export interface MonitorRegistration { readonly threadId: ThreadId; readonly prNumber: number; readonly generation: number; + readonly startedAt: string; readonly cursor: PullRequestMonitorCursor; readonly wakeCount: number; readonly repoCwd: string; @@ -29,10 +30,23 @@ export interface MonitorRegistryShape { readonly updateCursor: ( threadId: ThreadId, cursor: PullRequestMonitorCursor, + expectedGeneration?: number, ) => Effect.Effect; - readonly incrementWake: (threadId: ThreadId) => Effect.Effect; - readonly remove: (threadId: ThreadId) => Effect.Effect>; + readonly incrementWake: ( + threadId: ThreadId, + expectedGeneration?: number, + ) => Effect.Effect; + readonly setWakeCount: ( + threadId: ThreadId, + wakeCount: number, + expectedGeneration?: number, + ) => Effect.Effect; + readonly remove: ( + threadId: ThreadId, + expectedGeneration?: number, + ) => Effect.Effect>; readonly listActive: Effect.Effect>; + readonly nextGeneration: Effect.Effect; } export class MonitorRegistry extends Context.Service()( @@ -45,6 +59,7 @@ export class MonitorRegistry extends Context.Service(); +let generation = 0; const make: MonitorRegistryShape = { registerIfAbsent: (registration) => @@ -61,30 +76,59 @@ const make: MonitorRegistryShape = { } }), get: (threadId) => Effect.sync(() => Option.fromNullishOr(registrations.get(threadId))), - updateCursor: (threadId, cursor) => + updateCursor: (threadId, cursor, expectedGeneration) => Effect.sync(() => { const current = registrations.get(threadId); - if (current !== undefined) registrations.set(threadId, { ...current, cursor }); + if ( + current !== undefined && + (expectedGeneration === undefined || current.generation === expectedGeneration) + ) { + registrations.set(threadId, { ...current, cursor }); + } }), - incrementWake: (threadId) => + incrementWake: (threadId, expectedGeneration) => Effect.sync(() => { const current = registrations.get(threadId); + if ( + current === undefined || + (expectedGeneration !== undefined && current.generation !== expectedGeneration) + ) { + return current?.wakeCount ?? 0; + } const wakeCount = (current?.wakeCount ?? 0) + 1; - if (current !== undefined) registrations.set(threadId, { ...current, wakeCount }); + registrations.set(threadId, { ...current, wakeCount }); return wakeCount; }), - remove: (threadId) => + setWakeCount: (threadId, wakeCount, expectedGeneration) => Effect.sync(() => { const current = registrations.get(threadId); + if ( + current !== undefined && + (expectedGeneration === undefined || current.generation === expectedGeneration) + ) { + registrations.set(threadId, { ...current, wakeCount }); + } + }), + remove: (threadId, expectedGeneration) => + Effect.sync(() => { + const current = registrations.get(threadId); + if ( + current === undefined || + (expectedGeneration !== undefined && current.generation !== expectedGeneration) + ) { + return Option.none(); + } registrations.delete(threadId); return Option.fromNullishOr(current); }), listActive: Effect.sync(() => [...registrations.values()]), + nextGeneration: Effect.sync(() => ++generation), }; // The engine used for teardown dispatch is bound by PullRequestMonitor when // it starts (it is the only construction site that has the engine and runs in -// the runtime core). Until then teardown just clears the store. +// the runtime core). Until then teardown leaves registrations intact because +// it cannot durably project the corresponding monitor end. let activeEngine: OrchestrationEngineService["Service"] | undefined; export const bindEngine = (engine: OrchestrationEngineService["Service"]): void => { @@ -104,7 +148,7 @@ export const layer = Layer.effect( export const endActiveMonitorForSession = (threadId: ThreadId): Effect.Effect => Effect.gen(function* () { - const registration = yield* make.remove(threadId); + const registration = yield* make.get(threadId); if (Option.isNone(registration) || activeEngine === undefined) return; const endedAt = DateTime.formatIso(yield* DateTime.now); const commandId = CommandId.make(`monitor-session-ended:${threadId}:${endedAt}`); @@ -116,6 +160,7 @@ export const endActiveMonitorForSession = (threadId: ThreadId): Effect.Effect Effect.logWarning("monitor teardown failed", { threadId, error })), ); @@ -124,6 +169,7 @@ export const __testing = { make, reset: (): void => { registrations.clear(); + generation = 0; activeEngine = undefined; }, }; diff --git a/apps/server/src/monitor/PullRequestMonitor.test.ts b/apps/server/src/monitor/PullRequestMonitor.test.ts index baa717b8e9..77fceb2127 100644 --- a/apps/server/src/monitor/PullRequestMonitor.test.ts +++ b/apps/server/src/monitor/PullRequestMonitor.test.ts @@ -18,7 +18,10 @@ 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 type { PullRequestMonitorSnapshot } from "../sourceControl/gitHubPullRequestMonitor.ts"; +import { + GitHubPullRequestMonitorDecodeError, + type PullRequestMonitorSnapshot, +} from "../sourceControl/gitHubPullRequestMonitor.ts"; import * as MonitorRegistry from "./MonitorRegistry.ts"; import { cursorFromSnapshot } from "./monitorDiff.ts"; import { make, PullRequestSnapshotFetcher } from "./PullRequestMonitor.ts"; @@ -32,6 +35,7 @@ const snapshot = ( state: "open", draft: false, headSha: "head-1", + baseRefName: "main", mergeability: "mergeable", behindBaseBy: null, requiredChecksKnown: true, @@ -100,6 +104,7 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { readonly current: { value: PullRequestMonitorSnapshot }; readonly wakeCount?: number; readonly failWake?: boolean; + readonly failFreshFetch?: boolean; readonly busy?: { value: boolean }; readonly afterUpdate?: () => void; readonly changeGenerationAfterUpdate?: boolean; @@ -108,6 +113,7 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { threadId, prNumber: 42, generation: 1, + startedAt: now, cursor: cursorFromSnapshot(input.initial), wakeCount: input.wakeCount ?? 0, repoCwd: "/repo", @@ -126,24 +132,53 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { if (registration?.generation === generation) registration = undefined; }), get: () => Effect.sync(() => (registration ? Option.some(registration) : Option.none())), - updateCursor: (_, cursor) => + updateCursor: (_, cursor, expectedGeneration) => Effect.sync(() => { ordering.push("ack"); - if (registration) registration = { ...registration, cursor }; + if ( + registration && + (expectedGeneration === undefined || registration.generation === expectedGeneration) + ) { + registration = { ...registration, cursor }; + } }), - incrementWake: () => + incrementWake: (_, expectedGeneration) => Effect.sync(() => { + if ( + registration && + expectedGeneration !== undefined && + registration.generation !== expectedGeneration + ) { + return registration.wakeCount; + } const count = (registration?.wakeCount ?? 0) + 1; if (registration) registration = { ...registration, wakeCount: count }; return count; }), - remove: () => + setWakeCount: (_, wakeCount, expectedGeneration) => Effect.sync(() => { + if ( + registration && + (expectedGeneration === undefined || registration.generation === expectedGeneration) + ) { + registration = { ...registration, wakeCount }; + } + }), + remove: (_, expectedGeneration) => + Effect.sync(() => { + if ( + registration && + expectedGeneration !== undefined && + registration.generation !== expectedGeneration + ) { + return Option.none(); + } const removed = registration ? Option.some(registration) : Option.none(); registration = undefined; return removed; }), listActive: Effect.sync(() => (registration ? [registration] : [])), + nextGeneration: Effect.succeed(2), }); const engine = OrchestrationEngineService.of({ readEvents: () => Stream.empty, @@ -171,10 +206,23 @@ const harness = Effect.fn("PullRequestMonitor.testHarness")(function* (input: { return Effect.succeed({ sequence: commands.length }); }, }); + let fetchCount = 0; const monitor = yield* make.pipe( Effect.provideService(MonitorRegistry.MonitorRegistry, registry), Effect.provideService(PullRequestSnapshotFetcher, { - fetch: () => Effect.succeed(input.current.value), + fetch: () => { + fetchCount += 1; + return input.failFreshFetch && fetchCount === 2 + ? Effect.fail( + new GitHubPullRequestMonitorDecodeError({ + command: "gh", + cwd: "/repo", + detail: "fresh fetch failed", + cause: null, + }), + ) + : Effect.succeed(input.current.value); + }, }), Effect.provideService(OrchestrationEngineService, engine), Effect.provide( @@ -224,6 +272,22 @@ describe("PullRequestMonitor dispatch protocol", () => { }), ); + it.effect("ignores unresolved review threads that predate monitoring", () => + Effect.gen(function* () { + const oldComment = { + ...comment("old"), + createdAt: "2026-07-22T00:00:00.000Z", + }; + const ready = snapshot({ + reviewThreads: [oldComment], + checkRuns: [{ ...snapshot().checkRuns[0]!, status: "completed", conclusion: "success" }], + }); + const h = yield* harness({ initial: snapshot(), current: { value: ready } }); + yield* h.monitor.pollOnce; + assert.strictEqual(endReason(h.commands)?.type, "thread.monitor.end"); + }), + ); + it.effect("wake-then-ack ordering", () => Effect.gen(function* () { const h = yield* harness({ @@ -250,6 +314,67 @@ describe("PullRequestMonitor dispatch protocol", () => { }), ); + it.effect("failed-send-boundary-fetch-discards-wake-without-acking", () => + Effect.gen(function* () { + const initial = snapshot(); + const h = yield* harness({ + initial, + current: { value: snapshot({ reviewThreads: [comment("one")] }) }, + failFreshFetch: true, + }); + yield* h.monitor.pollOnce; + assert.strictEqual( + h.commands.some((command) => command.type === "thread.turn.start"), + false, + ); + assert.deepStrictEqual(h.getRegistration()?.cursor, cursorFromSnapshot(initial)); + assert.strictEqual(h.getRegistration()?.wakeCount, 0); + }), + ); + + it.effect("provider failure correlates by dispatch time and rewinds cursor plus wake count", () => + Effect.gen(function* () { + const initial = snapshot(); + const h = yield* harness({ + initial, + current: { value: snapshot({ reviewThreads: [comment("one")] }) }, + }); + yield* h.monitor.pollOnce; + const wake = h.commands.find((command) => command.type === "thread.turn.start"); + assert.ok(wake?.type === "thread.turn.start"); + const failureEvent = (createdAt: string) => + ({ + sequence: 1, + eventId: EventId.make(`failure-${createdAt}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: createdAt, + commandId: CommandId.make(`failure-${createdAt}`), + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.activity-appended", + payload: { + threadId, + activity: { + id: EventId.make(`activity-${createdAt}`), + tone: "error", + kind: "provider.turn.start.failed", + summary: "Provider turn start failed", + payload: {}, + turnId: null, + createdAt, + }, + }, + }) as const; + yield* h.monitor.handleDomainEvent(failureEvent("0001-01-01T00:00:00.000Z")); + assert.strictEqual(h.getRegistration()?.wakeCount, 1); + yield* h.monitor.handleDomainEvent(failureEvent(wake.createdAt)); + assert.strictEqual(h.getRegistration()?.wakeCount, 0); + assert.deepStrictEqual(h.getRegistration()?.cursor, cursorFromSnapshot(initial)); + }), + ); + it.effect("user-turn-discards-pending-wake", () => Effect.gen(function* () { const busy = { value: true }; @@ -339,4 +464,26 @@ describe("PullRequestMonitor dispatch protocol", () => { assert.strictEqual(ended?.type === "thread.monitor.end" && ended.reason, "needs-attention"); }), ); + + it.effect("archives by projecting stopped before removing the registration", () => + Effect.gen(function* () { + const h = yield* harness({ initial: snapshot(), current: { value: snapshot() } }); + 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 }, + }); + const ended = endReason(h.commands); + assert.strictEqual(ended?.type === "thread.monitor.end" && ended.reason, "stopped"); + assert.strictEqual(h.getRegistration(), undefined); + }), + ); }); diff --git a/apps/server/src/monitor/PullRequestMonitor.ts b/apps/server/src/monitor/PullRequestMonitor.ts index b915da4f38..614a1dfd30 100644 --- a/apps/server/src/monitor/PullRequestMonitor.ts +++ b/apps/server/src/monitor/PullRequestMonitor.ts @@ -29,6 +29,8 @@ interface WakeClaim { readonly generation: number; readonly commandId: CommandId; readonly phase: "pending" | "in-flight"; + readonly dispatchedAt?: string; + readonly previousWakeCount: number; // Cursor as it was before this wake acked, so a wake that dies after the // ack — provider start failure, superseded by a user turn — can rewind and // let the next poll re-diff the same events instead of losing them (I5). @@ -82,9 +84,6 @@ export const make = Effect.gen(function* () { const snapshots = yield* ProjectionSnapshotQuery; const crypto = yield* Crypto.Crypto; const claims = yield* Ref.make>(new Map()); - const latestStates = yield* Ref.make>( - new Map(), - ); const lastPollFailed = yield* Ref.make(false); const mutateClaim = ( @@ -114,7 +113,10 @@ export const make = Effect.gen(function* () { Effect.flatMap((released) => released === undefined || released.phase !== "in-flight" ? Effect.void - : registry.updateCursor(threadId, released.previousCursor), + : Effect.all([ + registry.updateCursor(threadId, released.previousCursor, released.generation), + registry.setWakeCount(threadId, released.previousWakeCount, released.generation), + ]).pipe(Effect.asVoid), ), ); @@ -138,9 +140,12 @@ export const make = Effect.gen(function* () { const end = Effect.fn("PullRequestMonitor.end")(function* ( threadId: ThreadId, - reason: "ready" | "terminal" | "needs-attention", + reason: "ready" | "terminal" | "needs-attention" | "stopped", blockersSummary: string, + expectedGeneration: number, ) { + const current = yield* registry.get(threadId); + if (Option.isNone(current) || current.value.generation !== expectedGeneration) return; // Dispatch before removing: if the end event fails to persist, the // registration survives and the next poll retries the same terminal / // ready / breaker verdict, instead of leaving the projection stuck on @@ -154,7 +159,7 @@ export const make = Effect.gen(function* () { blockersSummary, endedAt, }); - yield* registry.remove(threadId); + yield* registry.remove(threadId, expectedGeneration); yield* mutateClaim(threadId, () => undefined); }); @@ -174,6 +179,7 @@ export const make = Effect.gen(function* () { commandId, phase: "pending", previousCursor: registration.cursor, + previousWakeCount: registration.wakeCount, }); }); if (!claimed) return; @@ -182,16 +188,19 @@ export const make = Effect.gen(function* () { // Fresh terminal read at the send boundary (I1): the poll's snapshot is // seconds stale by now, and a merge in that window must veto the wake — // the cached `latestStates` alone cannot see it. - const freshState: PullRequestMonitorSnapshot["state"] | "unknown" = yield* fetcher + const freshState = yield* fetcher .fetch({ cwd: registration.repoCwd, pullRequestNumber: registration.prNumber }) .pipe( - Effect.map((fresh) => fresh.state), - Effect.orElseSucceed(() => "unknown" as const), + Effect.map((fresh) => Option.some(fresh.state)), + Effect.orElseSucceed(() => Option.none()), ); - const state = - freshState === "unknown" - ? (yield* Ref.get(latestStates)).get(registration.threadId) - : freshState; + if (Option.isNone(freshState)) { + yield* mutateClaim(registration.threadId, (claim) => + claim?.commandId === commandId ? undefined : claim, + ); + return; + } + const state = freshState.value; const thread = yield* snapshots.getThreadDetailById(registration.threadId); const validRegistration = Option.isSome(current) && current.value.generation === registration.generation; @@ -229,18 +238,27 @@ export const make = Effect.gen(function* () { }) .pipe( Effect.tap(() => - mutateClaim(registration.threadId, (claim) => - claim?.commandId === commandId ? { ...claim, phase: "in-flight" } : claim, + DateTime.now.pipe( + Effect.map(DateTime.formatIso), + Effect.flatMap((dispatchedAt) => + mutateClaim(registration.threadId, (claim) => + claim?.commandId === commandId + ? { ...claim, phase: "in-flight", dispatchedAt } + : claim, + ), + ), ), ), - Effect.tap(() => registry.updateCursor(registration.threadId, nextCursor)), + Effect.tap(() => + registry.updateCursor(registration.threadId, nextCursor, registration.generation), + ), Effect.tapError(() => mutateClaim(registration.threadId, (claim) => claim?.commandId === commandId ? undefined : claim, ), ), ); - const wakeCount = yield* registry.incrementWake(registration.threadId); + const wakeCount = yield* registry.incrementWake(registration.threadId, registration.generation); yield* dispatchUpdate( registration.threadId, formatBlockersSummary(computeReadiness(snapshot)), @@ -252,18 +270,19 @@ export const make = Effect.gen(function* () { const pollRegistration = Effect.fn("PullRequestMonitor.pollRegistration")(function* ( registration: MonitorRegistry.MonitorRegistration, ) { - const snapshot = yield* fetcher.fetch({ + const fetchedSnapshot = yield* fetcher.fetch({ cwd: registration.repoCwd, pullRequestNumber: registration.prNumber, }); - yield* Ref.update(latestStates, (states) => - new Map(states).set(registration.threadId, snapshot.state), - ); + const snapshot = { + ...fetchedSnapshot, + monitoringStartedAt: registration.startedAt, + }; const readiness = computeReadiness(snapshot); const summary = formatBlockersSummary(readiness); if (snapshot.state !== "open") { - yield* end(registration.threadId, "terminal", summary); + yield* end(registration.threadId, "terminal", summary, registration.generation); return; } if (readiness.ready) { @@ -273,7 +292,7 @@ export const make = Effect.gen(function* () { snapshot.headSha, registration.wakeCount, ); - yield* end(registration.threadId, "ready", summary); + yield* end(registration.threadId, "ready", summary, registration.generation); return; } @@ -281,7 +300,7 @@ export const make = Effect.gen(function* () { yield* dispatchUpdate(registration.threadId, summary, snapshot.headSha, registration.wakeCount); if (diff.actionableEvents.length === 0) return; if (registration.wakeCount >= 10) { - yield* end(registration.threadId, "needs-attention", summary); + yield* end(registration.threadId, "needs-attention", summary, registration.generation); return; } yield* dispatchWake( @@ -320,9 +339,23 @@ export const make = Effect.gen(function* () { const onEvent = (event: OrchestrationEvent) => { const threadId = threadIdOf(event); if (threadId === undefined) return Effect.void; + if (event.type === "thread.archived") { + return registry.get(threadId).pipe( + 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, + }), + ), + ); + } if ( event.type === "thread.deleted" || - event.type === "thread.archived" || event.type === "thread.settled" || event.type === "thread.monitor-ended" ) { @@ -342,7 +375,13 @@ export const make = Effect.gen(function* () { ) { // engine.dispatch succeeded but the provider reactor failed the turn // asynchronously — the acked events never reached an agent (I5). - return releaseClaim(threadId, () => true); + return releaseClaim( + threadId, + (claim) => + claim.phase === "in-flight" && + claim.dispatchedAt !== undefined && + claim.dispatchedAt <= event.payload.activity.createdAt, + ); } if (event.type === "thread.session-set") { const status = event.payload.session.status; @@ -354,6 +393,42 @@ 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 af4484b70f..79f7587690 100644 --- a/apps/server/src/monitor/monitorDiff.test.ts +++ b/apps/server/src/monitor/monitorDiff.test.ts @@ -9,6 +9,7 @@ const snapshot = ( state: "open", draft: false, headSha: "head-1", + baseRefName: "main", mergeability: "mergeable", behindBaseBy: null, requiredChecksKnown: true, @@ -104,13 +105,26 @@ describe("pull request monitor diff", () => { assert.strictEqual(result.nextCursor.threadVersions["thread-1"]?.resolved, true); }); - it("does not wake for a rerun of an already-seen failure", () => { + it("wakes when a resolved thread is reopened without an updatedAt change", () => { + const initial = snapshot({ reviewThreads: [thread(undefined, true)] }); + const result = diffPullRequestMonitorSnapshot( + cursorFromSnapshot(initial), + snapshot({ reviewThreads: [thread()] }), + ); + assert.deepStrictEqual(result.actionableEvents, [ + { kind: "new-review-comment", threadId: "thread-1", edited: true }, + ]); + }); + + it("wakes for a failed rerun with a new run id", () => { const initial = snapshot({ checkRuns: [check("run-1", "failure")] }); const result = diffPullRequestMonitorSnapshot( cursorFromSnapshot(initial), snapshot({ checkRuns: [check("run-2", "failure")] }), ); - assert.deepStrictEqual(result.actionableEvents, []); + assert.deepStrictEqual(result.actionableEvents, [ + { kind: "check-failed", checkRunId: "run-2", checkName: "CI" }, + ]); }); it("wakes for a new failure after a seen success", () => { @@ -123,4 +137,27 @@ describe("pull request monitor diff", () => { { kind: "check-failed", checkRunId: "run-2", checkName: "CI" }, ]); }); + + it("wakes for a same-name failure on a new head", () => { + const initial = snapshot({ checkRuns: [check("run-1", "failure")] }); + const nextCheck = { ...check("run-2", "failure"), headSha: "head-2" }; + const result = diffPullRequestMonitorSnapshot( + cursorFromSnapshot(initial), + snapshot({ headSha: "head-2", checkRuns: [nextCheck] }), + ); + assert.deepStrictEqual(result.actionableEvents, [ + { kind: "check-failed", checkRunId: "run-2", checkName: "CI" }, + ]); + }); + + it("tracks concurrent same-name runs independently", () => { + const initial = snapshot({ checkRuns: [check("run-1", "success")] }); + const result = diffPullRequestMonitorSnapshot( + cursorFromSnapshot(initial), + snapshot({ checkRuns: [check("run-1", "success"), check("run-2", "failure")] }), + ); + assert.deepStrictEqual(result.actionableEvents, [ + { kind: "check-failed", checkRunId: "run-2", checkName: "CI" }, + ]); + }); }); diff --git a/apps/server/src/monitor/monitorDiff.ts b/apps/server/src/monitor/monitorDiff.ts index cd62e1fc3a..8134bef48d 100644 --- a/apps/server/src/monitor/monitorDiff.ts +++ b/apps/server/src/monitor/monitorDiff.ts @@ -50,7 +50,10 @@ export function cursorFromSnapshot(snapshot: PullRequestMonitorSnapshot): PullRe checkRuns: Object.fromEntries( snapshot.checkRuns .filter((check) => check.headSha === snapshot.headSha) - .map((check) => [check.name, { runId: check.id, outcome: checkOutcome(check) }]), + .map((check) => [ + `${check.headSha}::${check.name}::${check.id}`, + { runId: check.id, outcome: checkOutcome(check) }, + ]), ), behindBase: (snapshot.behindBaseBy ?? 0) > 0, }; @@ -66,7 +69,10 @@ export function diffPullRequestMonitorSnapshot( const actionableEvents: PullRequestMonitorActionableEvent[] = []; for (const thread of snapshot.reviewThreads) { const previous = previousCursor.threadVersions[thread.id]; - if (!thread.resolved && (!previous || previous.updatedAt !== thread.updatedAt)) { + if ( + !thread.resolved && + (!previous || previous.resolved || previous.updatedAt !== thread.updatedAt) + ) { actionableEvents.push({ kind: "new-review-comment", threadId: thread.id, @@ -95,8 +101,9 @@ export function diffPullRequestMonitorSnapshot( } for (const check of snapshot.checkRuns.filter((item) => item.headSha === snapshot.headSha)) { const outcome = checkOutcome(check); - const previous = previousCursor.checkRuns[check.name]; - // A rerun preserves the check-name outcome history; only success -> failure wakes again. + const previous = previousCursor.checkRuns[`${check.headSha}::${check.name}::${check.id}`]; + // Each concrete run is acknowledged independently, including concurrent + // same-name runs on one head and reruns/new heads with new run ids. if (outcome === "failure" && previous?.outcome !== "failure") { actionableEvents.push({ kind: "check-failed", diff --git a/apps/server/src/monitor/readiness.test.ts b/apps/server/src/monitor/readiness.test.ts index 6972b86831..0c25491a5b 100644 --- a/apps/server/src/monitor/readiness.test.ts +++ b/apps/server/src/monitor/readiness.test.ts @@ -9,6 +9,7 @@ const snapshot = ( state: "open", draft: false, headSha: "head-2", + baseRefName: "main", mergeability: "mergeable", behindBaseBy: null, requiredChecksKnown: true, @@ -51,6 +52,25 @@ describe("pull request monitor readiness", () => { ]); }); + it("blocks on a human changes-requested review", () => { + const result = computeReadiness( + snapshot({ + reviews: [ + { + id: "review-human", + author: { login: "human-reviewer", type: "user" }, + state: "changes-requested", + submittedAt: "2026-01-01T00:00:00Z", + commitSha: "head-2", + }, + ], + }), + ); + assert.deepStrictEqual(result.blockers, [ + { kind: "changes-requested", reviewer: "human-reviewer" }, + ]); + }); + it("ignores stale approvals after a push", () => { const result = computeReadiness( snapshot({ diff --git a/apps/server/src/monitor/readiness.ts b/apps/server/src/monitor/readiness.ts index 3d18b0924b..3daafe89e2 100644 --- a/apps/server/src/monitor/readiness.ts +++ b/apps/server/src/monitor/readiness.ts @@ -42,7 +42,7 @@ export function computeReadiness( // Stale approvals must not count toward green, but a changes-requested // review blocks regardless of which commit it reviewed — GitHub keeps it // active until dismissed or superseded by a re-review. - if (review.author.type === "app" && review.state === "changes-requested") { + if (review.state === "changes-requested") { blockers.push({ kind: "changes-requested", reviewer: review.author.login }); } } diff --git a/apps/server/src/monitor/wakePrompt.ts b/apps/server/src/monitor/wakePrompt.ts index 4d4578f0c1..5d72fca76e 100644 --- a/apps/server/src/monitor/wakePrompt.ts +++ b/apps/server/src/monitor/wakePrompt.ts @@ -59,7 +59,7 @@ function formatEvent( return `- Check ${event.checkName}: ${check?.conclusion ?? "failure"}`; } case "behind-base": - return `- PR is behind main${snapshot.behindBaseBy === null ? "" : ` by ${snapshot.behindBaseBy} commit(s)`}`; + return `- PR is behind ${snapshot.baseRefName}${snapshot.behindBaseBy === null ? "" : ` by ${snapshot.behindBaseBy} commit(s)`}`; } } @@ -81,7 +81,7 @@ Policy: - Verify bot claims against the source before acting. - Fix legitimate findings and push. - Dismiss false positives with a brief reply — never silently ignore or comply. -- For CI failures: compare against main; re-run suspected flakes; if the same real failure repeats, ask the user via a question rather than guessing. -- Rebase if the PR is behind main. +- For CI failures: compare against ${input.snapshot.baseRefName}; re-run suspected flakes; if the same real failure repeats, ask the user via a question rather than guessing. +- Rebase if the PR is behind ${input.snapshot.baseRefName}. - If the goal has become impossible, say so and ask the user.`; } diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 7bf387d40e..c6eccc6590 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -726,7 +726,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti status: "monitoring", blockersSummary: event.payload.blockersSummary, headSha: event.payload.headSha, - wakeCount: 0, + wakeCount: event.payload.wakeCount, startedAt: event.payload.startedAt, endedAt: null, endedReason: null, diff --git a/apps/server/src/orchestration/decider.monitor.test.ts b/apps/server/src/orchestration/decider.monitor.test.ts index 13f8e2e34a..a95a9d3ca3 100644 --- a/apps/server/src/orchestration/decider.monitor.test.ts +++ b/apps/server/src/orchestration/decider.monitor.test.ts @@ -50,7 +50,7 @@ const activeMonitor: NonNullable = { status: "monitoring", blockersSummary: "waiting", headSha: "abc", - wakeCount: 0, + wakeCount: 4, startedAt: NOW, endedAt: null, endedReason: null, @@ -83,9 +83,11 @@ it.layer(NodeServices.layer)("monitor decider", (it) => { if ("type" in repeated && repeated.type === "thread.monitor-started") { const payload = repeated.payload as { readonly headSha: string; + readonly wakeCount: number; readonly startedAt: string; }; expect(payload.headSha).toBe("abc"); + expect(payload.wakeCount).toBe(4); expect(payload.startedAt).toBe(NOW); } }), diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 587652da77..41eb852cc5 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -554,6 +554,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" : command.blockersSummary, headSha: thread.monitor?.status === "monitoring" ? thread.monitor.headSha : command.headSha, + wakeCount: thread.monitor?.status === "monitoring" ? thread.monitor.wakeCount : 0, startedAt: thread.monitor?.status === "monitoring" ? thread.monitor.startedAt : command.createdAt, }, diff --git a/apps/server/src/orchestration/projector.monitor.test.ts b/apps/server/src/orchestration/projector.monitor.test.ts index cb4c550ed7..038a74bfc3 100644 --- a/apps/server/src/orchestration/projector.monitor.test.ts +++ b/apps/server/src/orchestration/projector.monitor.test.ts @@ -50,6 +50,7 @@ it.effect("projects the monitor lifecycle without changing settledOverride", () prNumber: 42, blockersSummary: "draft", headSha: "abc", + wakeCount: 0, startedAt: NOW, }), ); diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index aa883ba062..9e2f8148c3 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -407,7 +407,7 @@ export function projectEvent( status: "monitoring", blockersSummary: payload.blockersSummary, headSha: payload.headSha, - wakeCount: 0, + wakeCount: payload.wakeCount, startedAt: payload.startedAt, endedAt: null, endedReason: null, diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index b1c29b5659..e369832229 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -216,8 +216,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const runtimeEventPubSub = yield* PubSub.unbounded(); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => - MonitorRegistry.endActiveMonitorForSession(threadId).pipe( - Effect.andThen(McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId })), + McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe( Effect.tap((credential) => credential ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)) diff --git a/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts b/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts index 1ec0427d0c..bd55333a5f 100644 --- a/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts +++ b/apps/server/src/sourceControl/gitHubPullRequestMonitor.ts @@ -60,6 +60,7 @@ export interface PullRequestMonitorSnapshot { readonly state: "open" | "closed" | "merged"; readonly draft: boolean; readonly headSha: string; + readonly baseRefName: string; readonly mergeability: "mergeable" | "conflicting" | "unknown"; readonly behindBaseBy: number | null; readonly requiredChecksKnown: boolean; @@ -107,6 +108,7 @@ const PullRequestPageSchema = Schema.Struct({ merged: Schema.Boolean, mergeable: Schema.String, headRefOid: Schema.String, + baseRefName: Schema.String, reviews: Schema.Struct({ nodes: Schema.Array(ReviewSchema), pageInfo: Schema.Struct({ @@ -259,10 +261,13 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna let reviewsComplete = false; let threadsComplete = false; let metadata: - | Pick + | Pick< + PullRequestMonitorSnapshot, + "state" | "draft" | "headSha" | "baseRefName" | "mergeability" + > | 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 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){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: [ @@ -301,6 +306,7 @@ export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSna state: pr.merged ? "merged" : pr.state === "CLOSED" ? "closed" : "open", draft: pr.isDraft, headSha: pr.headRefOid, + baseRefName: pr.baseRefName, mergeability: pr.mergeable === "MERGEABLE" ? "mergeable" diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 848753a5da..bd8e0f7383 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -1068,6 +1068,7 @@ export const ThreadMonitorStartedPayload = Schema.Struct({ prNumber: NonNegativeInt, blockersSummary: Schema.String, headSha: Schema.String, + wakeCount: NonNegativeInt, startedAt: IsoDateTime, });