feat(server): agents can watch a PR and get woken when checks, reviews, or conflicts need them #15057
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 13 commits into
main fromrefs/pull/15057/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/Orchestrator.ts line 9279Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -9130,3 +9241,4 @@91309241 case "thread.pull-request.link":91319242 case "thread.pull-request.unlink":91329243 case "thread.pull-request-link.sync":9244+ case "thread.pull-request.watch":apps/server/src/orchestration-v2/PullRequestWatchReactor.ts line 125OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +105,21 @@105+ if (thread.settledOverride === "settled" || thread.settledAt !== null) return;106+107+ const reference = { projectId: thread.projectId, ...pullRequest };108+ const [detail, activity] = yield* Effect.all(109+ [pullRequests.detail({ ...reference, allowStale: false }), pullRequests.activity(reference)],110+ { concurrency: 2 },111+ );112+ if (detail.state !== "open") return yield* record(null);113+114+ // GitHub sends the first comments of each review thread; the rest are read here so a late115+ // reply in a long thread still counts.116+ const longThreads = activity.reviewThreads.filter(117+ (reviewThread) => reviewThread.nextCommentsCursor !== undefined,118+ );119+ const rest = yield* Effect.forEach(120+ longThreads,121+ (reviewThread) =>122+ Effect.gen(function* () {123+ const comments: Array<PullRequestComment> = [];124+ let cursor: string | null | undefined = reviewThread.nextCommentsCursor;125+ for (let page = 0; cursor != null && page < THREAD_PAGES; page += 1) {apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx line 131OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -118,2 +130,2 @@118130 signals={119131 snapshot?.state === "open" ? (apps/server/src/mcp/toolkits/pullRequests/handlers.ts line 259OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -196,0 +239,21 @@239+ .dispatch({240+ type: "thread.pull-request.link",241+ commandId: yield* commandId("mcp-pr-link", thread.id),242+ threadId: thread.id,243+ ...identity,244+ source: "agent",245+ })246+ .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError)));247+ }248+ yield* engine249+ .dispatch({250+ type: "thread.pull-request.watch",251+ commandId: yield* commandId("mcp-pr-watch", thread.id),252+ threadId: thread.id,253+ host: target.host,254+ repository: target.repository,255+ number: target.number,256+ watching,257+ })258+ .pipe(Effect.catchCause(dispatchFailure(PullRequestWatchFailedError)));259+ return { ...identity, watching, wasWatching };
juliusmarminge added labelsmacroscope-review
- apps/server/src/mcp/toolkits/pullRequests/handlers.ts line 237OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -196,0 +217,21 @@217+ const thread = yield* requireThread(PullRequestWatchFailedError);218+ const project = yield* projectOf(thread, PullRequestWatchFailedError);219+ const target = yield* resolveTarget(input, project);220+ const identity = {221+ host: target.host,222+ repository: target.repository,223+ number: target.number,224+ url: target.url,225+ };226+ const existing = threadPullRequestsOf(thread).find(227+ (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target),228+ );229+ const wasWatching = existing?.watch !== undefined;230+ if (wasWatching === watching || (!watching && existing === undefined)) {231+ return { ...identity, watching: wasWatching, wasWatching };232+ }233+ const state = existing?.snapshot?.state;234+ if (watching && state !== undefined && state !== "open") {235+ return yield* new PullRequestNotOpenError({ state });236+ }237+ if (existing === undefined) {
- apps/server/src/orchestration-v2/PullRequestWatchReactor.ts line 37OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +17,21 @@17+import * as Crypto from "effect/Crypto";18+import * as Effect from "effect/Effect";19+import * as Layer from "effect/Layer";20+import * as Schedule from "effect/Schedule";21+import type * as Scope from "effect/Scope";22+23+import * as PullRequestService from "../pullRequest/PullRequestService.ts";24+import { forkParked } from "../serverActivation.ts";25+import * as Orchestrator from "./Orchestrator.ts";26+import * as ProjectionStore from "./ProjectionStore.ts";27+import { evaluatePullRequestWatch, pullRequestWatchMessage } from "./pullRequestWatch.ts";28+29+/** Extra comment pages read per review thread; a longer thread leaves the read incomplete. */30+const THREAD_PAGES = 5;31+32+const logFailure =33+ (message: string, fields: Record<string, unknown>) =>34+ <E>(cause: Cause.Cause<E>): Effect.Effect<void> =>35+ Cause.hasInterruptsOnly(cause)36+ ? Effect.interrupt37+ : Effect.logWarning(message, { ...fields, cause: Cause.pretty(cause) });
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/orchestration-v2/PullRequestWatchReactor.ts lines 104 to 104OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +84,21 @@84+ // The orchestrator applies this only while the same watch is on, so a stop or restart that85+ // lands during the host read wins.86+ const record = (87+ next: ThreadPullRequestWatch | null,88+ wake?: { readonly text: string; readonly notification: OrchestrationV2Notification },89+ ) =>90+ Effect.gen(function* () {91+ const uuid = yield* crypto.randomUUIDv4;92+ yield* engine.dispatch({93+ type: "thread.pull-request-watch.sync",94+ commandId: CommandId.make(`server:pr-watch:${thread.id}:${uuid}`),95+ threadId: thread.id,96+ ...pullRequest,97+ startedAt: watch.startedAt,98+ watch: next,99+ ...(wake === undefined100+ ? {}101+ : { wake: { ...wake, messageId: MessageId.make(`message:pr-watch:${uuid}`) } }),102+ });103+ });104+ if (link.snapshot !== null && link.snapshot.state !== "open") return yield* record(null);
- apps/server/src/orchestration-v2/pullRequestWatch.ts lines 70 to 70OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +50,21 @@50+51+/**52+ * Compares a watched pull request with what its agent was last told. A check result is53+ * reported as soon as any check fails or once every check passed, and again only after the54+ * head commit moves or the checks start over. Remarks count when someone other than the55+ * viewer or the pull request's author wrote them: the agent posts as the viewer, so its own56+ * replies never wake it. `remarks` is null when the conversation could not be read whole;57+ * remarks are then left for a later pass rather than skipped.58+ */59+export function evaluatePullRequestWatch(60+ watch: ThreadPullRequestWatch,61+ detail: Pick<PullRequestDetail, "headSha" | "checks" | "mergeability" | "viewer" | "author">,62+ remarks: ReadonlyArray<PullRequestComment> | null,63+): PullRequestWatchReport {64+ const changes: Array<PullRequestWatchChange> = [];65+ const headSha = detail.headSha ?? null;66+ const outcome = checksOutcome(detail.checks);67+ // Hosts that report no head commit still show a push or a rerun as checks starting over.68+ const restarted =69+ headSha !== watch.headSha ||70+ (watch.checks !== null && (outcome === "pending" || outcome === null));apps/server/src/orchestration-v2/pullRequestWatch.ts lines 34 to 34Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +14,21 @@14+const LISTED_ITEMS = 10;15+const SNIPPET_LENGTH = 200;16+17+export type PullRequestWatchChange =18+ | {19+ readonly kind: "checks-failed";20+ readonly failed: ReadonlyArray<PullRequestCheck>;21+ /** Checks still running; a later report follows once they finish. */22+ readonly running: number;23+ }24+ | { readonly kind: "checks-passed"; readonly count: number }25+ | { readonly kind: "remarks"; readonly remarks: ReadonlyArray<PullRequestComment> }26+ | { readonly kind: "conflicting" };27+28+export interface PullRequestWatchReport {29+ /** What the agent has not been told yet. Empty means no wake. */30+ readonly changes: ReadonlyArray<PullRequestWatchChange>;31+ /** The watch to record, whether or not anything is reported. */32+ readonly next: ThreadPullRequestWatch;33+ /** This report spends the last wake before the limit, so watching stops after it. */34+ readonly exhausted: boolean;
- apps/server/src/orchestration-v2/pullRequestWatch.ts line 70OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +50,21 @@50+51+/**52+ * Compares a watched pull request with what its agent was last told. A check result is53+ * reported as soon as any check fails or once every check passed, and again only after the54+ * head commit moves or the checks start over. Remarks count when someone other than the55+ * viewer or the pull request's author wrote them: the agent posts as the viewer, so its own56+ * replies never wake it. `remarks` is null when the conversation could not be read whole;57+ * remarks are then left for a later pass rather than skipped.58+ */59+export function evaluatePullRequestWatch(60+ watch: ThreadPullRequestWatch,61+ detail: Pick<PullRequestDetail, "headSha" | "checks" | "mergeability" | "viewer" | "author">,62+ remarks: ReadonlyArray<PullRequestComment> | null,63+): PullRequestWatchReport {64+ const changes: Array<PullRequestWatchChange> = [];65+ const headSha = detail.headSha ?? null;66+ const outcome = checksOutcome(detail.checks);67+ // Hosts that report no head commit still show a push or a rerun as checks starting over.68+ const restarted =69+ headSha !== watch.headSha ||70+ (watch.checks !== null && (outcome === "pending" || outcome === null));
- apps/server/src/orchestration-v2/pullRequestWatch.ts lines 47 to 144OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +124,21 @@124+ const conflicting =125+ detail.mergeability === "unknown" ? watch.conflicting : detail.mergeability === "conflicting";126+127+ // A new check run, a push, or any check or conflict news is progress, so the count restarts.128+ const commentsOnly = changes.length > 0 && changes.every((change) => change.kind === "remarks");129+ const progress = restarted || rerun || (changes.length > 0 && !commentsOnly);130+ const wakes = (progress ? 0 : watch.wakes) + (commentsOnly ? 1 : 0);131+ return {132+ changes,133+ next: {134+ startedAt: watch.startedAt,135+ headSha,136+ checks,137+ remarksThrough,138+ remarkIds,139+ conflicting,140+ wakes,141+ },142+ exhausted: commentsOnly && wakes >= PULL_REQUEST_WATCH_WAKE_LIMIT,143+ };144+}apps/server/src/orchestration-v2/pullRequestWatch.ts lines 73 to 75OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +55,21 @@55+56+/**57+ * Compares a watched pull request with what its agent was last told. A check result is58+ * reported as soon as any check fails or once every check passed, and again only after the59+ * head commit moves or the checks start over. Remarks count when someone other than the60+ * viewer or the pull request's author wrote them: the agent posts as the viewer, so its own61+ * replies never wake it. `remarks` is null when the conversation could not be read whole;62+ * remarks are then left for a later pass rather than skipped.63+ */64+export function evaluatePullRequestWatch(65+ watch: ThreadPullRequestWatch,66+ detail: Pick<PullRequestDetail, "headSha" | "checks" | "mergeability" | "viewer" | "author">,67+ remarks: ReadonlyArray<PullRequestComment> | null,68+): PullRequestWatchReport {69+ const changes: Array<PullRequestWatchChange> = [];70+ const headSha = detail.headSha ?? null;71+ const outcome = checksOutcome(detail.checks);72+ // Hosts that report no head commit still show a push or a rerun as checks starting over.73+ const restarted =74+ headSha !== watch.headSha ||75+ (watch.checks !== null && (outcome === "pending" || outcome === null));
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/orchestration-v2/pullRequestWatch.ts lines 75 to 76Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +56,21 @@56+ const result = checksResult(detail.checks);57+ // Hosts that report no head commit still show a push or a rerun as checks running again.58+ const restarted = headSha !== watch.headSha || (watch.checks !== null && result === null);59+60+ let checks = restarted ? null : watch.checks;61+ if (result !== null && result !== checks) {62+ changes.push(63+ result === "passing"64+ ? { kind: "checks-passed", count: detail.checks.length }65+ : { kind: "checks-failed", failed: detail.checks.filter(isFailedCheck) },66+ );67+ checks = result;68+ }69+70+ const own = new Set(71+ [detail.viewer, detail.author?.login].flatMap((login) => (login ? [login.toLowerCase()] : [])),72+ );73+ const through = Date.parse(watch.remarksThrough);74+ // GitHub times are per second, so remarks at the boundary time are told apart by ID.75+ const fresh = (remarks ?? []).filter((remark) => {76+ const at = Date.parse(remark.createdAt);
- apps/server/src/orchestration-v2/Orchestrator.ts line 2940Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2830,3 +2926,13 @@28302926 updatedAt: command.type === "thread.pull-request-link.sync" ? thread.updatedAt : now,28312927 };28322928 }2929+ case "thread.pull-request.watch":2930+ case "thread.pull-request-watch.sync": {2931+ const key = normalizeThreadPullRequestKey(command);2932+ const startedAt = DateTime.formatIso(now);2933+ const linked = threadPullRequestsOf(thread);2934+ const visible = (link: ThreadPullRequestLink) =>2935+ link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, key);2936+ // A watch started on an unlinked (or dismissed) pull request links it in the same step.2937+ const links =2938+ command.type === "thread.pull-request.watch" &&apps/server/src/orchestration-v2/Orchestrator.ts lines 2977 to 2984Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2832,0 +2960,21 @@2960+ ? (command.watch ?? undefined)2961+ : existing.watch2962+ : !command.watching2963+ ? undefined2964+ : (existing.watch ?? {2965+ startedAt,2966+ headSha: null,2967+ failedChecks: [],2968+ passed: false,2969+ remarksThrough: startedAt,2970+ remarkIds: [],2971+ conflicting: false,2972+ wakes: 0,2973+ });2974+ if (watch === existing.watch && links === linked) return thread;2975+ return {2976+ ...thread,2977+ pullRequests: links.map((link) =>2978+ link === existing ? withPullRequestWatch(link, watch) : link,2979+ ),2980+ };apps/server/src/orchestration-v2/PullRequestWatchReactor.ts line 179OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +159,21 @@159+ source: { kind: "monitor" },160+ outcome: "failed",161+ summary: `#${target.link.number}: stopped watching, could not read it`,162+ },163+ }).pipe(Effect.catch(() => record(target, null)));164+165+ const sweep = Effect.gen(function* () {166+ const threads = yield* projections.getThreadsWithPullRequests();167+ const targets = threads.flatMap((thread) =>168+ visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) =>169+ link.watch === undefined ? [] : [{ thread, link, watch: link.watch }],170+ ),171+ );172+ const keys = new Set(targets.map(failureKey));173+ for (const key of readFailures.keys()) if (!keys.has(key)) readFailures.delete(key);174+ yield* Effect.forEach(175+ targets,176+ (target) =>177+ check(target).pipe(178+ Effect.tap(() => Effect.sync(() => readFailures.delete(failureKey(target)))),179+ Effect.catchCause((cause) => {
- apps/server/src/orchestration-v2/PullRequestWatchReactor.ts lines 148 to 158Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +137,21 @@137+ const read = yield* Effect.exit(138+ Effect.all(139+ [140+ pullRequests.detail({ ...reference, allowStale: false }),141+ pullRequests.activity(reference),142+ ],143+ { concurrency: 2 },144+ ),145+ );146+ // Only host reads count towards giving up; a refused wake is not the host's fault.147+ const key = failureKey(target);148+ if (Exit.isFailure(read)) {149+ if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause);150+ const failures = (readFailures.get(key) ?? 0) + 1;151+ readFailures.set(key, failures);152+ if (failures >= READ_FAILURE_LIMIT) {153+ readFailures.delete(key);154+ yield* giveUp(target);155+ }156+ return yield* Effect.failCause(read.cause);157+ }
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed