Add PR monitoring: server-driven babysit mode for agent threads #4428
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 7 commits into
main fromt3code/add-pr-monitoring-flowopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- apps/web/src/components/SidebarV2.tsx line 443Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -413,4 +415,19 @@413415416+ // The PR monitor ("babysit") mode wraps the normal statuses: a monitoring417+ // row recedes like any in-flight row, a ready row demands attention like an418+ // unread completion, and a dead-session monitor gets a subtle floor marker.419+ const monitorState = resolveMonitorSidebarState(thread.monitor);420+ const isMonitoring = monitorState === "monitoring";421+ const isMonitorReady = monitorState === "ready";422+ const isMonitorStopped = monitorState === "stopped";423+ // What the PR is waiting on, in place of the branch on the sub-line — the424+ // legibility that answers "Are you still going?" (mock 4a). No counter.425+ const monitorBlockers = thread.monitor?.blockersSummary?.trim() ?? "";426+ const monitorSubLine =427+ (isMonitoring || isMonitorReady) && monitorBlockers !== "" ? monitorBlockers : null;414428 // Same semantics as v1 (never-visited counts as read): flipping the beta415- // flag must not light up every historical thread as unread.416- const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt });429+ // flag must not light up every historical thread as unread. A ready PR is430+ // the payoff moment — treat it as unread-prominent — while an actively431+ // monitoring thread suppresses the success-shaped unread from its quiet432+ // wake-turn completions (never a blocked state — that surfaces via status).433+ const isUnread =
- apps/server/src/monitor/PullRequestMonitor.ts lines 191 to 194OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +174,21 @@174+ commandId,175+ phase: "pending",176+ previousCursor: registration.cursor,177+ });178+ });179+ if (!claimed) return;180+181+ const current = yield* registry.get(registration.threadId);182+ // Fresh terminal read at the send boundary (I1): the poll's snapshot is183+ // seconds stale by now, and a merge in that window must veto the wake —184+ // the cached `latestStates` alone cannot see it.185+ const freshState: PullRequestMonitorSnapshot["state"] | "unknown" = yield* fetcher186+ .fetch({ cwd: registration.repoCwd, pullRequestNumber: registration.prNumber })187+ .pipe(188+ Effect.map((fresh) => fresh.state),189+ Effect.orElseSucceed(() => "unknown" as const),190+ );191+ const state =192+ freshState === "unknown"193+ ? (yield* Ref.get(latestStates)).get(registration.threadId)194+ : freshState;apps/server/src/sourceControl/gitHubPullRequestMonitor.ts line 503Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +402,21 @@402+ );403+ checkRuns.push(404+ ...response.check_runs.map((check) => ({405+ id: String(check.id),406+ name: check.name,407+ status: normalizeCheckStatus(check.status),408+ conclusion:409+ check.conclusion && conclusions.has(check.conclusion as never)410+ ? (check.conclusion as PullRequestMonitorCheckRun["conclusion"])411+ : null,412+ startedAt: check.started_at,413+ headSha: check.head_sha,414+ })),415+ );416+ if (response.check_runs.length < 100) break;417+ }418+419+ return {420+ ...metadata,421+ behindBaseBy: null,422+ requiredChecksKnown: false,apps/server/src/monitor/PullRequestMonitor.ts line 539Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +324,21 @@324+ event.type === "thread.deleted" ||325+ event.type === "thread.archived" ||326+ event.type === "thread.settled" ||327+ event.type === "thread.monitor-ended"328+ ) {329+ return registry330+ .remove(threadId)331+ .pipe(Effect.andThen(mutateClaim(threadId, () => undefined)), Effect.asVoid);332+ }333+ if (event.type === "thread.turn-start-requested") {334+ // A turn we didn't start won the thread. Drop our claim — and if our335+ // wake had already acked the cursor (in-flight), rewind it so the336+ // superseded events re-diff next poll instead of being lost (I5).337+ return releaseClaim(threadId, (claim) => claim.commandId !== event.commandId);338+ }339+ if (340+ event.type === "thread.activity-appended" &&341+ event.payload.activity.kind === "provider.turn.start.failed"342+ ) {343+ // engine.dispatch succeeded but the provider reactor failed the turn344+ // asynchronously — the acked events never reached an agent (I5).apps/server/src/monitor/wakePrompt.ts line 84OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+}65+66+export function buildWakePrompt(input: {67+ readonly prNumber: number;68+ readonly wakeCount: number;69+ readonly events: ReadonlyArray<PullRequestMonitorActionableEvent>;70+ readonly snapshot: PullRequestMonitorSnapshot;71+ readonly readiness: PullRequestMonitorReadiness;72+}): string {73+ return `New activity on PR #${input.prNumber} (monitoring, wake ${input.wakeCount}/10).74+75+${input.events.map((event) => formatEvent(event, input.snapshot)).join("\n")}76+77+Status: ${formatBlockersSummary(input.readiness)}78+Head: ${input.snapshot.headSha} (approvals/checks are evaluated against this commit)79+80+Policy:81+- Verify bot claims against the source before acting.82+- Fix legitimate findings and push.83+- Dismiss false positives with a brief reply — never silently ignore or comply.84+- 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.apps/server/src/mcp/toolkits/monitor/handlers.ts lines 67 to 67OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +47,21 @@47+ if (!thread || !project) {48+ return yield* new MonitorStartError({ message: "The invoking thread no longer exists." });49+ }50+ const repoCwd = thread.worktreePath ?? project.workspaceRoot;51+ const snapshot = yield* getPullRequestMonitorSnapshot({52+ cwd: repoCwd,53+ pullRequestNumber: prNumber,54+ }).pipe(Effect.mapError((error) => new MonitorStartError({ message: error.message })));55+ if (snapshot.state !== "open") {56+ return yield* new MonitorStartError({57+ message: `PR #${prNumber} is ${snapshot.state}; only open pull requests can be monitored.`,58+ });59+ }60+61+ const createdAt = DateTime.formatIso(yield* DateTime.now);62+ const crypto = yield* Crypto.Crypto;63+ const commandId = CommandId.make(yield* crypto.randomUUIDv4);64+ const warning = snapshot.draft65+ ? `PR #${prNumber} is a draft. Monitoring started, but review bots may not run until it is marked ready for review.`66+ : null;67+ const generation = yield* Clock.currentTimeMillis;apps/server/src/monitor/MonitorRegistry.ts line 78Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +43,21 @@43+// constructed both in the runtime core (for the poller) and inside the MCP44+// routes layer (for monitor_start), and those two layer instances must see45+// the same registrations. All operations are synchronous, so plain-Map46+// mutation inside Effect.sync is atomic per call.47+const registrations = new Map<ThreadId, MonitorRegistration>();48+49+const make: MonitorRegistryShape = {50+ registerIfAbsent: (registration) =>51+ Effect.sync(() => {52+ if (registrations.has(registration.threadId)) return false;53+ registrations.set(registration.threadId, registration);54+ return true;55+ }),56+ removeGeneration: (threadId, generation) =>57+ Effect.sync(() => {58+ const current = registrations.get(threadId);59+ if (current !== undefined && current.generation === generation) {60+ registrations.delete(threadId);61+ }62+ }),63+ get: (threadId) => Effect.sync(() => Option.fromNullishOr(registrations.get(threadId))),apps/server/src/orchestration/decider.ts line 561Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -506,0 +520,21 @@520+ blockersSummary: thread.monitor.blockersSummary,521+ endedAt: occurredAt,522+ },523+ },524+ settledEvent,525+ ];526+ }527+528+ case "thread.monitor.start": {529+ const thread = yield* requireThreadNotArchived({530+ readModel,531+ command,532+ threadId: command.threadId,533+ });534+ if (thread.monitor?.status === "monitoring" && thread.monitor.prNumber !== command.prNumber) {535+ return yield* new OrchestrationCommandInvariantError({536+ commandType: command.type,537+ detail: `thread ${command.threadId} is already monitoring PR #${thread.monitor.prNumber}`,538+ });539+ }540+ const monitorStartedEvent: Omit<OrchestrationEvent, "sequence"> = {apps/server/src/monitor/monitorDiff.ts line 54Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +30,21 @@30+ check.conclusion === "skipped"31+ ) {32+ return "success";33+ }34+ return "failure";35+};36+37+export function cursorFromSnapshot(snapshot: PullRequestMonitorSnapshot): PullRequestMonitorCursor {38+ return {39+ headSha: snapshot.headSha,40+ reviewStates: Object.fromEntries(snapshot.reviews.map((review) => [review.id, review.state])),41+ threadVersions: Object.fromEntries(42+ snapshot.reviewThreads.map((thread) => [43+ thread.id,44+ { updatedAt: thread.updatedAt, resolved: thread.resolved },45+ ]),46+ ),47+ issueCommentVersions: Object.fromEntries(48+ snapshot.issueComments.map((comment) => [comment.id, comment.updatedAt]),49+ ),50+ checkRuns: Object.fromEntries(apps/server/src/monitor/monitorDiff.ts lines 69 to 72OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +52,21 @@52+ .filter((check) => check.headSha === snapshot.headSha)53+ .map((check) => [check.name, { runId: check.id, outcome: checkOutcome(check) }]),54+ ),55+ behindBase: (snapshot.behindBaseBy ?? 0) > 0,56+ };57+}58+59+export function diffPullRequestMonitorSnapshot(60+ previousCursor: PullRequestMonitorCursor,61+ snapshot: PullRequestMonitorSnapshot,62+): {63+ readonly actionableEvents: ReadonlyArray<PullRequestMonitorActionableEvent>;64+ readonly nextCursor: PullRequestMonitorCursor;65+} {66+ const actionableEvents: PullRequestMonitorActionableEvent[] = [];67+ for (const thread of snapshot.reviewThreads) {68+ const previous = previousCursor.threadVersions[thread.id];69+ if (!thread.resolved && (!previous || previous.updatedAt !== thread.updatedAt)) {70+ actionableEvents.push({71+ kind: "new-review-comment",72+ threadId: thread.id,apps/server/src/monitor/readiness.ts lines 45 to 47OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+ }28+ const currentChecks = snapshot.checkRuns.filter((check) => check.headSha === snapshot.headSha);29+ if (currentChecks.length === 0) blockers.push({ kind: "checks-missing" });30+ for (const check of currentChecks) {31+ if (check.status !== "completed") {32+ blockers.push({ kind: "check-pending", checkName: check.name });33+ } else if (34+ check.conclusion !== "success" &&35+ check.conclusion !== "neutral" &&36+ check.conclusion !== "skipped"37+ ) {38+ blockers.push({ kind: "check-failed", checkName: check.name });39+ }40+ }41+ for (const review of snapshot.reviews) {42+ // Stale approvals must not count toward green, but a changes-requested43+ // review blocks regardless of which commit it reviewed — GitHub keeps it44+ // active until dismissed or superseded by a re-review.45+ if (review.author.type === "app" && review.state === "changes-requested") {46+ blockers.push({ kind: "changes-requested", reviewer: review.author.login });47+ }apps/server/src/sourceControl/gitHubPullRequestMonitor.ts line 502Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +401,21 @@401+ "GitHub API returned invalid check run JSON.",402+ );403+ checkRuns.push(404+ ...response.check_runs.map((check) => ({405+ id: String(check.id),406+ name: check.name,407+ status: normalizeCheckStatus(check.status),408+ conclusion:409+ check.conclusion && conclusions.has(check.conclusion as never)410+ ? (check.conclusion as PullRequestMonitorCheckRun["conclusion"])411+ : null,412+ startedAt: check.started_at,413+ headSha: check.head_sha,414+ })),415+ );416+ if (response.check_runs.length < 100) break;417+ }418+419+ return {420+ ...metadata,421+ behindBaseBy: null,apps/server/src/monitor/MonitorRegistry.ts line 149Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +85,21 @@85+// The engine used for teardown dispatch is bound by PullRequestMonitor when86+// it starts (it is the only construction site that has the engine and runs in87+// the runtime core). Until then teardown just clears the store.88+let activeEngine: OrchestrationEngineService["Service"] | undefined;89+90+export const bindEngine = (engine: OrchestrationEngineService["Service"]): void => {91+ activeEngine = engine;92+};93+94+export const layer = Layer.effect(95+ MonitorRegistry,96+ Effect.acquireRelease(Effect.succeed(MonitorRegistry.of(make)), () =>97+ Effect.gen(function* () {98+ for (const registration of [...registrations.values()]) {99+ yield* endActiveMonitorForSession(registration.threadId);100+ }101+ }),102+ ),103+);104+105+export const endActiveMonitorForSession = (threadId: ThreadId): Effect.Effect<void> =>apps/server/src/monitor/monitorDiff.ts line 13Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,13 @@1+import type {2+ PullRequestMonitorCheckRun,3+ PullRequestMonitorSnapshot,4+} from "../sourceControl/gitHubPullRequestMonitor.ts";5+6+export interface PullRequestMonitorCursor {7+ readonly headSha: string;8+ readonly reviewStates: Readonly<Record<string, string>>;9+ readonly threadVersions: Readonly<10+ Record<string, { readonly updatedAt: string; readonly resolved: boolean }>11+ >;12+ readonly issueCommentVersions: Readonly<Record<string, string>>;13+ readonly checkRuns: Readonly<
- apps/server/src/provider/Layers/ProviderService.ts line 226Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -215,12 +216,12 @@215216 const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();216217 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);217218 const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>218- McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(219+ MonitorRegistry.endActiveMonitorForSession(threadId).pipe(220+ Effect.andThen(McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId })),219221 Effect.tap((credential) =>220222 credential221223 ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))222224 : Effect.void,223225 ),224226 );225227 const clearMcpSession = (threadId: ThreadId) =>226- McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(apps/server/src/monitor/readiness.ts line 68Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +35,21 @@35+ check.conclusion !== "neutral" &&36+ check.conclusion !== "skipped"37+ ) {38+ blockers.push({ kind: "check-failed", checkName: check.name });39+ }40+ }41+ for (const review of snapshot.reviews) {42+ // Stale approvals must not count toward green, but a changes-requested43+ // review blocks regardless of which commit it reviewed — GitHub keeps it44+ // active until dismissed or superseded by a re-review.45+ if (review.author.type === "app" && review.state === "changes-requested") {46+ blockers.push({ kind: "changes-requested", reviewer: review.author.login });47+ }48+ }49+ for (const thread of snapshot.reviewThreads) {50+ if (51+ !thread.resolved &&52+ (!snapshot.monitoringStartedAt || thread.createdAt >= snapshot.monitoringStartedAt)53+ ) {54+ blockers.push({ kind: "unresolved-thread", threadId: thread.id });55+ }apps/server/src/monitor/PullRequestMonitor.ts line 331OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +311,21 @@311+ cause,312+ }).pipe(Effect.andThen(Ref.set(lastPollFailed, true))),313+ ),314+ ),315+ { concurrency: "unbounded", discard: true },316+ ),317+ ),318+ );319+320+ const onEvent = (event: OrchestrationEvent) => {321+ const threadId = threadIdOf(event);322+ if (threadId === undefined) return Effect.void;323+ if (324+ event.type === "thread.deleted" ||325+ event.type === "thread.archived" ||326+ event.type === "thread.settled" ||327+ event.type === "thread.monitor-ended"328+ ) {329+ return registry330+ .remove(threadId)331+ .pipe(Effect.andThen(mutateClaim(threadId, () => undefined)), Effect.asVoid);apps/server/src/monitor/PullRequestMonitor.ts line 340Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +229,21 @@229+ })230+ .pipe(231+ Effect.tap(() =>232+ mutateClaim(registration.threadId, (claim) =>233+ claim?.commandId === commandId ? { ...claim, phase: "in-flight" } : claim,234+ ),235+ ),236+ Effect.tap(() => registry.updateCursor(registration.threadId, nextCursor)),237+ Effect.tapError(() =>238+ mutateClaim(registration.threadId, (claim) =>239+ claim?.commandId === commandId ? undefined : claim,240+ ),241+ ),242+ );243+ const wakeCount = yield* registry.incrementWake(registration.threadId);244+ yield* dispatchUpdate(245+ registration.threadId,246+ formatBlockersSummary(computeReadiness(snapshot)),247+ snapshot.headSha,248+ wakeCount,249+ );apps/server/src/monitor/MonitorRegistry.ts line 172Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +98,21 @@98+ for (const registration of [...registrations.values()]) {99+ yield* endActiveMonitorForSession(registration.threadId);100+ }101+ }),102+ ),103+);104+105+export const endActiveMonitorForSession = (threadId: ThreadId): Effect.Effect<void> =>106+ Effect.gen(function* () {107+ const registration = yield* make.remove(threadId);108+ if (Option.isNone(registration) || activeEngine === undefined) return;109+ const endedAt = DateTime.formatIso(yield* DateTime.now);110+ const commandId = CommandId.make(`monitor-session-ended:${threadId}:${endedAt}`);111+ yield* activeEngine.dispatch({112+ type: "thread.monitor.end",113+ commandId,114+ threadId,115+ reason: "session-ended",116+ blockersSummary: "",117+ endedAt,118+ });apps/server/src/monitor/readiness.ts line 58Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +27,21 @@27+ }28+ const currentChecks = snapshot.checkRuns.filter((check) => check.headSha === snapshot.headSha);29+ if (currentChecks.length === 0) blockers.push({ kind: "checks-missing" });30+ for (const check of currentChecks) {31+ if (check.status !== "completed") {32+ blockers.push({ kind: "check-pending", checkName: check.name });33+ } else if (34+ check.conclusion !== "success" &&35+ check.conclusion !== "neutral" &&36+ check.conclusion !== "skipped"37+ ) {38+ blockers.push({ kind: "check-failed", checkName: check.name });39+ }40+ }41+ for (const review of snapshot.reviews) {42+ // Stale approvals must not count toward green, but a changes-requested43+ // review blocks regardless of which commit it reviewed — GitHub keeps it44+ // active until dismissed or superseded by a re-review.45+ if (review.author.type === "app" && review.state === "changes-requested") {46+ blockers.push({ kind: "changes-requested", reviewer: review.author.login });47+ }apps/server/src/monitor/PullRequestMonitor.ts line 580Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +345,21 @@345+ return releaseClaim(threadId, () => true);346+ }347+ if (event.type === "thread.session-set") {348+ const status = event.payload.session.status;349+ if (status !== "starting" && status !== "running") {350+ return mutateClaim(threadId, (claim) => (claim?.phase === "in-flight" ? undefined : claim));351+ }352+ }353+ return Effect.void;354+ };355+356+ const start = Effect.fn("PullRequestMonitor.start")(function* () {357+ yield* Effect.forkDetach(Stream.runForEach(engine.streamDomainEvents, onEvent));358+ yield* Effect.forkDetach(359+ Effect.forever(360+ pollOnce.pipe(361+ Effect.andThen(Ref.get(lastPollFailed)),362+ Effect.flatMap((failed) => Effect.sleep(failed ? MAX_BACKOFF : POLL_INTERVAL)),363+ ),364+ ),365+ );
- apps/server/src/sourceControl/gitHubPullRequestMonitor.ts line 244Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +207,21 @@207+ }208+};209+210+const normalizeCheckStatus = (status: string): PullRequestMonitorCheckRun["status"] => {211+ if (status === "queued" || status === "completed") return status;212+ if (status === "in_progress") return "in-progress";213+ return "unknown";214+};215+216+const conclusions = new Set<NonNullable<PullRequestMonitorCheckRun["conclusion"]>>([217+ "success",218+ "failure",219+ "neutral",220+ "cancelled",221+ "skipped",222+ "timed-out",223+ "action-required",224+ "stale",225+]);226+227+export const getPullRequestMonitorSnapshot = Effect.fn("getPullRequestMonitorSnapshot")(apps/server/src/monitor/PullRequestMonitor.ts line 396OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +376,21 @@376+ // engine.dispatch succeeded but the provider reactor failed the turn377+ // asynchronously — the acked events never reached an agent (I5).378+ return releaseClaim(379+ threadId,380+ (claim) =>381+ claim.phase === "in-flight" &&382+ claim.dispatchedAt !== undefined &&383+ claim.dispatchedAt <= event.payload.activity.createdAt,384+ );385+ }386+ if (event.type === "thread.session-set") {387+ const status = event.payload.session.status;388+ if (status !== "starting" && status !== "running") {389+ return mutateClaim(threadId, (claim) => (claim?.phase === "in-flight" ? undefined : claim));390+ }391+ }392+ return Effect.void;393+ };394+395+ const start = Effect.fn("PullRequestMonitor.start")(function* () {396+ const shell = yield* snapshotsapps/server/src/monitor/PullRequestMonitor.ts line 349OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +329,21 @@329+ threadId: registration.threadId,330+ cause,331+ }).pipe(Effect.andThen(Ref.set(lastPollFailed, true))),332+ ),333+ ),334+ { concurrency: "unbounded", discard: true },335+ ),336+ ),337+ );338+339+ const onEvent = (event: OrchestrationEvent) => {340+ const threadId = threadIdOf(event);341+ if (threadId === undefined) return Effect.void;342+ if (event.type === "thread.archived") {343+ return registry.get(threadId).pipe(344+ Effect.flatMap((registration) =>345+ Option.isNone(registration)346+ ? Effect.void347+ : end(threadId, "stopped", "", registration.value.generation),348+ ),349+ Effect.catch((error) =>
- apps/server/src/monitor/PullRequestMonitor.ts line 546Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +364,21 @@364+ .pipe(Effect.andThen(mutateClaim(threadId, () => undefined)), Effect.asVoid);365+ }366+ if (event.type === "thread.turn-start-requested") {367+ // A turn we didn't start won the thread. Drop our claim — and if our368+ // wake had already acked the cursor (in-flight), rewind it so the369+ // superseded events re-diff next poll instead of being lost (I5).370+ return releaseClaim(threadId, (claim) => claim.commandId !== event.commandId);371+ }372+ if (373+ event.type === "thread.activity-appended" &&374+ event.payload.activity.kind === "provider.turn.start.failed"375+ ) {376+ // engine.dispatch succeeded but the provider reactor failed the turn377+ // asynchronously — the acked events never reached an agent (I5).378+ return releaseClaim(379+ threadId,380+ (claim) =>381+ claim.phase === "in-flight" &&382+ claim.dispatchedAt !== undefined &&383+ claim.dispatchedAt <= event.payload.activity.createdAt,384+ );
- apps/server/src/monitor/PullRequestMonitor.ts line 347OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +327,21 @@327+ shell.threads.filter((thread) => thread.monitor?.status === "monitoring"),328+ (thread) =>329+ registry.get(thread.id).pipe(330+ Effect.flatMap((registration) => {331+ if (Option.isSome(registration)) return Effect.void;332+ return Effect.gen(function* () {333+ const endedAt = DateTime.formatIso(yield* DateTime.now);334+ yield* engine.dispatch({335+ type: "thread.monitor.end",336+ commandId: CommandId.make(`monitor-boot-reconcile:${thread.id}:${endedAt}`),337+ threadId: thread.id,338+ reason: "session-ended",339+ blockersSummary: "",340+ endedAt,341+ });342+ });343+ }),344+ ),345+ { discard: true },346+ );347+ yield* Ref.set(reconciled, true);
- apps/server/src/monitor/PullRequestMonitor.ts line 288OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +268,21 @@268+ },269+ runtimeMode: thread.value.runtimeMode,270+ interactionMode: thread.value.interactionMode,271+ createdAt,272+ })273+ .pipe(274+ Effect.tap(() =>275+ // Stamp the claim with the command's own createdAt: a provider276+ // turn-start failure activity echoes exactly this timestamp277+ // (ProviderCommandReactor appends it with the event payload's278+ // createdAt), so equality means "our wake failed" while an older279+ // turn's delayed failure compares strictly older. A post-dispatch280+ // DateTime.now here would always exceed the echoed timestamp and281+ // make the release condition unsatisfiable.282+ mutateClaim(registration.threadId, (claim) =>283+ claim?.commandId === commandId284+ ? { ...claim, phase: "in-flight", dispatchedAt: createdAt }285+ : claim,286+ ),287+ ),288+ Effect.tap(() =>
- apps/server/src/monitor/PullRequestMonitor.ts line 404OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +384,21 @@384+ yield* engine.dispatch({385+ type: "thread.monitor.end",386+ commandId: CommandId.make(`monitor-boot-reconcile:${thread.id}:${endedAt}`),387+ threadId: thread.id,388+ generation: thread.monitor!.generation,389+ reason: "session-ended",390+ blockersSummary: "",391+ endedAt,392+ });393+ });394+ }),395+ Effect.catchCause((cause) =>396+ Effect.logWarning("pull request monitor orphan reconcile failed", {397+ threadId: thread.id,398+ cause,399+ }),400+ ),401+ ),402+ { discard: true },403+ );404+ yield* Ref.set(reconciled, true);apps/server/src/monitor/PullRequestMonitor.ts line 566Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +498,21 @@498+ return releaseClaim(threadId, (claim) => claim.commandId !== event.commandId);499+ }500+ if (501+ event.type === "thread.activity-appended" &&502+ event.payload.activity.kind === "provider.turn.start.failed"503+ ) {504+ // engine.dispatch succeeded but the provider reactor failed the turn505+ // asynchronously — the acked events never reached an agent (I5).506+ return releaseClaim(507+ threadId,508+ (claim) =>509+ claim.phase === "in-flight" &&510+ claim.dispatchedAt !== undefined &&511+ claim.dispatchedAt <= event.payload.activity.createdAt,512+ );513+ }514+ if (event.type === "thread.session-set") {515+ const status = event.payload.session.status;516+ if (status !== "starting" && status !== "running") {517+ return mutateClaim(threadId, (claim) => (claim?.phase === "in-flight" ? undefined : claim));518+ }apps/server/src/monitor/MonitorRegistry.ts line 152OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +132,21 @@132+let activeEngine: OrchestrationEngineService["Service"] | undefined;133+134+export const bindEngine = (engine: OrchestrationEngineService["Service"]): void => {135+ activeEngine = engine;136+};137+138+export const layer = Layer.effect(139+ MonitorRegistry,140+ Effect.acquireRelease(Effect.succeed(MonitorRegistry.of(make)), () =>141+ Effect.gen(function* () {142+ for (const registration of [...registrations.values()]) {143+ yield* endActiveMonitorForSession(registration.threadId);144+ }145+ }),146+ ),147+);148+149+export const endActiveMonitorForSession = (threadId: ThreadId): Effect.Effect<void> =>150+ Effect.gen(function* () {151+ const registration = yield* make.get(threadId);152+ if (Option.isNone(registration) || activeEngine === undefined) return;
- apps/server/src/monitor/MonitorRegistry.ts line 21Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,21 @@1+import { CommandId, type ThreadId } from "@t3tools/contracts";2+import * as Context from "effect/Context";3+import * as DateTime from "effect/DateTime";4+import * as Effect from "effect/Effect";5+import * as Layer from "effect/Layer";6+import * as Option from "effect/Option";7+8+import type { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";9+import type { PullRequestMonitorCursor } from "./monitorDiff.ts";10+11+export interface MonitorRegistration {12+ readonly threadId: ThreadId;13+ readonly prNumber: number;14+ readonly generation: number;15+ readonly startedAt: string;16+ readonly cursor: PullRequestMonitorCursor;17+ readonly wakeCount: number;18+ readonly repoCwd: string;19+}20+21+export interface MonitorRegistryShape {@@ -0,0 +22,21 @@22+import { diffPullRequestMonitorSnapshot, type PullRequestMonitorCursor } from "./monitorDiff.ts";23+import { computeReadiness } from "./readiness.ts";24+import { buildWakePrompt, formatBlockersSummary } from "./wakePrompt.ts";25+26+const POLL_INTERVAL = Duration.seconds(30);27+const MAX_BACKOFF = Duration.minutes(5);28+const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;29+30+interface WakeClaim {31+ readonly generation: number;32+ readonly commandId: CommandId;33+ readonly phase: "pending" | "in-flight";34+ readonly dispatchedAt?: string;35+ readonly previousWakeCount: number;36+ // Cursor as it was before this wake acked, so a wake that dies after the37+ // ack — provider start failure, superseded by a user turn — can rewind and38+ // let the next poll re-diff the same events instead of losing them (I5).39+ readonly previousCursor: PullRequestMonitorCursor;40+}41+42+export interface PullRequestSnapshotFetcherShape {
- apps/server/src/monitor/PullRequestMonitor.ts line 563Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +537,21 @@537+ ) {538+ // engine.dispatch succeeded but the provider reactor failed the turn539+ // asynchronously — the acked events never reached an agent (I5).540+ return releaseClaim(541+ threadId,542+ (claim) =>543+ claim.phase === "in-flight" &&544+ claim.dispatchedAt !== undefined &&545+ claim.dispatchedAt <= event.payload.activity.createdAt,546+ );547+ }548+ if (event.type === "thread.session-set") {549+ const status = event.payload.session.status;550+ // A provider failure surfaces as session-set(error) BEFORE551+ // provider.turn.start.failed, so dropping the claim here would leave552+ // that later handler nothing to rewind and the acked events would never553+ // re-diff (I5). Rewind on error; a clean finish (ready/idle/stopped)554+ // just frees the claim — its events were genuinely delivered.555+ if (status === "error") {556+ return releaseClaim(threadId, (claim) => claim.phase === "in-flight");557+ }
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
c625b82c-8650-4902-9e98-6215d8881819You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share