diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts index 6a05213ffa906..bae8b91b468be 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.test.ts @@ -327,6 +327,30 @@ it("deduplicates a stranded queue until the queue advances or drains", () => { assert.isTrue(step("queued:3", true, 11)); }); +it("an open-PR lane-ended report dropped undelivered can report again on the next run end", () => { + const judged = { + threadId: "thread:fleet", + evaluated: ["lane-ended"] as const, + findings: [finding("lane-ended", "open-prs:github.com/o/r#7")], + }; + const first = recordThreadEvents(EMPTY_MODEL_ALERT_STATE, judged, eventAlert, ["watcher"], 0); + assert.isTrue(first.enqueued); + // A later run with the same open pull requests shares the report while it is queued. + assert.isFalse(recordThreadEvents(first.state, judged, eventAlert, ["watcher"], 1).enqueued); + const [queued] = first.state.outbox; + assert.isDefined(queued); + const dropped = afterDrop(first.state, queued, 2); + assert.deepEqual(dropped.outbox, []); + assert.isTrue(recordThreadEvents(dropped, judged, eventAlert, ["watcher"], 3).enqueued); + // A run-keyed report keeps its dedupe after a drop: that run will not end again. + const failedRun = { ...judged, findings: [finding("lane-ended", "run:1")] }; + const failed = recordThreadEvents(EMPTY_MODEL_ALERT_STATE, failedRun, eventAlert, ["watcher"], 0); + const afterFailedDrop = afterDrop(failed.state, failed.state.outbox[0]!, 1); + assert.isFalse( + recordThreadEvents(afterFailedDrop, failedRun, eventAlert, ["watcher"], 2).enqueued, + ); +}); + it("a thread holding a question and an inbox flip reports each once, not on every trigger", () => { const both = [finding("needs-person", "request:1"), finding("needs-person", "inbox:kameron")]; let state = EMPTY_MODEL_ALERT_STATE; diff --git a/apps/server/src/orchestration-v2/ModelAlertReactor.ts b/apps/server/src/orchestration-v2/ModelAlertReactor.ts index b2b4e3d66ad54..1c8185549e6b7 100644 --- a/apps/server/src/orchestration-v2/ModelAlertReactor.ts +++ b/apps/server/src/orchestration-v2/ModelAlertReactor.ts @@ -18,6 +18,7 @@ import { runModelSignals, workerAlert } from "@t3tools/provider-core/server/suba import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Option from "effect/Option"; @@ -42,6 +43,11 @@ import * as EventSubscriptionStore from "../persistence/EventSubscriptions.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { + normalizeThreadPullRequestKey, + threadPullRequestKeyOf, +} from "../sourceControl/threadPullRequests.ts"; import { forkParked } from "../serverActivation.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as Orchestrator from "./Orchestrator.ts"; @@ -55,18 +61,21 @@ import { withCursor, } from "./eventSubscription.ts"; import { + isOpenPrLaneEndedSignature, isStrandedQueueSignature, judgeThread, keepStrandedQueueReport, type StrandedQueue, threadEventAlert, launchingThreadId, + openPullRequestLinks, ThreadEventAlert, type ThreadEventKind, threadEventMessage, REJUDGE_TRIGGER, threadEventStillHolds, type ThreadEventTrigger, + withPullRequestStates, type ThreadFinding, } from "./ThreadEventAlerts.ts"; import { @@ -369,6 +378,32 @@ function setReported( }; } +function openPrLaneEndedSignature(alert: WatcherAlert): string | undefined { + if (alert.type !== "thread-event" || alert.kind !== "lane-ended") return undefined; + const prefix = `${alert.environmentId}:${alert.threadId}:${alert.kind}:`; + const suffix = `:${alert.occurredAt}`; + if (!alert.id.startsWith(prefix) || !alert.id.endsWith(suffix)) return undefined; + const signature = alert.id.slice(prefix.length, -suffix.length); + return isOpenPrLaneEndedSignature(signature) ? signature : undefined; +} + +/** + * An open-PR lane-ended report is shared by every run with the same open pull requests, so one + * dropped undelivered must be forgotten, or the next run that ends that way stays silent too. + */ +function forgetDroppedOpenPrReport(reported: ModelAlertState["reported"], entry: Delivery) { + const signature = openPrLaneEndedSignature(entry.alert); + if (signature === undefined || entry.alert.type !== "thread-event") return reported; + const key = reportedKey(entry.alert.threadId, "lane-ended"); + const known = (reported[key] ?? "").split("\n").filter(Boolean); + if (!known.includes(signature)) return reported; + return setReported( + reported, + key, + known.filter((candidate) => candidate !== signature), + ); +} + function recordStrandedDelivery( reported: ModelAlertState["reported"], entry: Delivery, @@ -632,7 +667,7 @@ export const afterDrop = ( (candidate) => candidate.alert.id === entry.alert.id && !sameDelivery(candidate, entry), ) ? state.reported - : recordStrandedDelivery(state.reported, entry, false), + : forgetDroppedOpenPrReport(recordStrandedDelivery(state.reported, entry, false), entry), outbox: state.outbox.flatMap((candidate) => { if (!sameDelivery(candidate, entry)) return [candidate]; if ( @@ -1016,6 +1051,7 @@ export const make = Effect.gen(function* () { const subscriptionStore = yield* Effect.serviceOption( EventSubscriptionStore.EventSubscriptionStore, ); + const pullRequestService = yield* Effect.serviceOption(PullRequestService.PullRequestService); let eventWakeSeq = 0; const projections = yield* ProjectionStore.ProjectionStoreV2; const settings = yield* ServerSettings.ServerSettingsService; @@ -1144,10 +1180,15 @@ export const make = Effect.gen(function* () { alert.type === "model-degraded" ? { providerInstanceId: alert.providerInstanceId, newerRunSupersedes: false } : undefined; - if (!(yield* stillCurrent(alert.threadId, alert.runId, about))) return null; + // An open-PR report covers later runs too, so a newer run does not supersede it; the + // re-judge below still drops it once the run is live, failed, or the open set changed. + const runId = openPrLaneEndedSignature(alert) === undefined ? alert.runId : null; + if (!(yield* stillCurrent(alert.threadId, runId, about))) return null; if (alert.type === "thread-event") { - const shell = yield* projections.getThreadShell(ThreadId.make(alert.threadId)); - if (shell === null) return null; + const stored = yield* projections.getThreadShell(ThreadId.make(alert.threadId)); + if (stored === null) return null; + const shell = + openPrLaneEndedSignature(alert) === undefined ? stored : yield* withHostPrStates(stored); const holds = threadEventStillHolds({ hasStalenessWait: yield* hasActiveStalenessWait(shell, REJUDGE_TRIGGER[alert.kind]), alert, @@ -1160,6 +1201,38 @@ export const make = Effect.gen(function* () { return alert; }); + /** + * The stored snapshot can predate a merge or close by a sync interval, so an open-PR alert + * rereads its open links from the host. A failed read keeps the stored state. + */ + const withHostPrStates = Effect.fnUntraced(function* (shell: OrchestrationV2ThreadShell) { + if (Option.isNone(pullRequestService)) return shell; + const service = pullRequestService.value; + const read = yield* Effect.forEach( + openPullRequestLinks(shell), + (link) => + service + .summary( + { + projectId: shell.projectId, + host: normalizeThreadPullRequestKey(link).host, + repository: link.repository, + number: link.number, + }, + { bypassCache: true, recoverTransientFailure: false }, + ) + .pipe( + Effect.map((summary) => [[threadPullRequestKeyOf(link), summary.state] as const]), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => Effect.succeed([]), + ), + ), + { concurrency: 4 }, + ); + return withPullRequestStates(shell, new Map(read.flat())); + }); + /** What the shell does not carry: open delegated tasks elsewhere, and children's last activity. */ const hasActiveStalenessWait = Effect.fnUntraced(function* ( shell: OrchestrationV2ThreadShell, diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts index 5b3e03bcf7edf..dcfa2175f5f12 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts @@ -1456,7 +1456,7 @@ describe("PullRequestSyncReactor", () => { }), ); - it.effect("reads a settled thread's links once when it settles, then until unsettled", () => + it.effect("refreshes open links on settled threads on the slow cadence until terminal", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); const fixture = yield* makeHarness({ @@ -1468,6 +1468,7 @@ describe("PullRequestSyncReactor", () => { makeLink(5, { state: "open" }), makeLink(6, { state: "closed" }), makeLink(7), + makeLink(8, { state: "merged", mergedAt: "2026-08-20T00:00:00.000Z" }), ], }), ]), @@ -1475,7 +1476,11 @@ describe("PullRequestSyncReactor", () => { yield* Effect.gen(function* () { const reactor = yield* startAndSweep(fixture); - assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []); + // Open (#5) and unsynced (#7) links on settled thread are swept; closed (#6) and merged (#8) are not. + assert.deepStrictEqual( + (yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(), + [5, 7], + ); const threadId = ThreadId.make("settled"); const at = DateTime.makeUnsafe(NOW); @@ -1515,9 +1520,17 @@ describe("PullRequestSyncReactor", () => { (yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(), [5, 6], ); - for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor); + // Before SLOW_SYNC_INTERVAL_MS (15m), open link #5 is not re-swept. + for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor); assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []); + // At 15m, open (#5) and unsynced (#7) links are refreshed on the slow cadence; closed (#6) and merged (#8) stay quiet. + yield* sweepAgain(fixture, reactor); + assert.deepStrictEqual( + (yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(), + [5, 7], + ); + yield* Ref.update(fixture.snapshots, (snapshot) => ({ ...snapshot, threads: snapshot.threads.map((thread) => ({ @@ -1527,9 +1540,10 @@ describe("PullRequestSyncReactor", () => { })), })); yield* sweepAgain(fixture, reactor); + // After unsettling, #6 (closed, 15m since last read) and #7 (unsynced) are due; #5 was just refreshed 1m ago and is in quiet cooldown. assert.deepStrictEqual( (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(), - [5, 6, 7], + [6, 7], ); }).pipe(Effect.provide(fixture.layer)); }), diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts index 8f57f900d0c2d..4f0fd29deb6dc 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts @@ -380,10 +380,18 @@ export const make = Effect.gen(function* () { const isDue = (key: string, entries: ReadonlyArray, nowMs: number): boolean => { if ((failedReads.get(key)?.retryAtMs ?? 0) > nowMs) return false; if (requested.has(key)) return true; - const active = entries.filter((entry) => isUnsettled(entry.thread)); - if (active.length === 0) return false; const last = lastSyncedAt.get(key); const sinceLastMs = last === undefined ? Number.POSITIVE_INFINITY : nowMs - last; + const active = entries.filter((entry) => isUnsettled(entry.thread)); + if (active.length === 0) { + // Settled threads still refresh open/unsynced pull requests on the slow cadence so PRs + // merged or closed after settlement reach a terminal snapshot instead of staying "open". + const hasOpenSettled = entries.some( + (entry) => entry.link.snapshot === null || entry.link.snapshot.state === "open", + ); + if (!hasOpenSettled) return false; + return sinceLastMs >= SLOW_SYNC_INTERVAL_MS; + } if (missing.has(key)) return sinceLastMs >= SLOW_SYNC_INTERVAL_MS; if (retryStacks.has(key) || active.some((entry) => entry.link.snapshot === null)) return true; // Merged snapshots without mergedAt cannot settle threads; reread slowly until supplied. @@ -873,7 +881,7 @@ export const make = Effect.gen(function* () { // Every reaction skips a running command, so only an ended one forks. return active ? Effect.void : inThreadOrder(event.threadId, reaction); } - // Settled threads are not swept, so read their links once to settle with fresh status. + // Settling reads the links at once rather than waiting for the slow settled cadence. case "thread.settled": return inThreadOrder(event.threadId, refreshUnmergedLinks(event.threadId)); case "run.updated": diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts index 92860800a53af..c1bd4dc4dd421 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.test.ts @@ -10,7 +10,9 @@ import { threadEventStillHolds, type ThreadEventTrigger, type WatchedShell, + withPullRequestStates, } from "./ThreadEventAlerts.ts"; +import { threadPullRequestKeyOf } from "../sourceControl/threadPullRequests.ts"; const NOW = Date.parse("2026-11-19T05:00:00.000Z"); const at = (minutesAgo: number) => DateTime.makeUnsafe(NOW - minutesAgo * 60_000); @@ -130,6 +132,45 @@ it("lane-ended stays quiet for a failure the model alert already reported as a u assert.deepEqual(findings, []); }); +it("lane-ended with open pull requests dedupes by open-PR set across runs, and clears on settle", () => { + const run1 = judge( + shellWith({ + status: "completed", + latestRunId: "run:1", + pullRequests: [openPullRequest], + } as never), + "run-ended", + ); + const run2 = judge( + shellWith({ + status: "completed", + latestRunId: "run:2", + pullRequests: [openPullRequest], + } as never), + "run-ended", + ); + const finding1 = run1.findings.find((finding) => finding.kind === "lane-ended"); + const finding2 = run2.findings.find((finding) => finding.kind === "lane-ended"); + assert.ok(finding1 && finding2); + assert.strictEqual(finding1.signature, finding2.signature); + assert.ok(finding1.signature.startsWith("open-prs:")); + + const settled = judge( + shellWith({ + status: "completed", + latestRunId: "run:2", + settledOverride: "settled", + pullRequests: [openPullRequest], + } as never), + "settled", + ); + assert.ok(settled.evaluated.includes("lane-ended")); + assert.deepEqual( + settled.findings.filter((finding) => finding.kind === "lane-ended"), + [], + ); +}); + it.each([ { settledOverride: "settled" }, { archivedAt: at(1) }, @@ -395,6 +436,18 @@ const asking = { } as never; const promised = { status: "idle", latestVisibleMessage: assistantSays(FLEET_PROMISE) } as never; +it("an open-PR lane-ended alert stops holding once a host reread finds its pull request merged", () => { + const alert = fired(openWithPr, "run-ended"); + const stored = shellWith(openWithPr); + const key = threadPullRequestKeyOf(openPullRequest); + const reread = (state: "open" | "merged") => + withPullRequestStates(stored, new Map([[key, state]])); + assert.isTrue(threadEventStillHolds({ alert, shell: reread("open"), stuckMinutes: 20 })); + assert.isFalse(threadEventStillHolds({ alert, shell: reread("merged"), stuckMinutes: 20 })); + // A newer run that ended the same way keeps the open-PR report, so it is not superseded. + assert.isTrue(stillHolds(alert, { latestRunId: "run:8" } as never, openWithPr)); +}); + it.each([ ["lane-ended, nothing changed", failed, "run-ended", {}, true], ["lane-ended, the lane restarted itself", failed, "run-ended", quietRun, false], diff --git a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts index ed160d2dacfb5..d1c53eb0b1462 100644 --- a/apps/server/src/orchestration-v2/ThreadEventAlerts.ts +++ b/apps/server/src/orchestration-v2/ThreadEventAlerts.ts @@ -1,11 +1,14 @@ import { type EnvironmentId, + type PullRequestState, + type ThreadPullRequestLink, isListedThreadLineage, isDelegatedAppThread, ModelAlertWatcher, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; +import { threadPullRequestKeyOf } from "../sourceControl/threadPullRequests.ts"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; @@ -49,7 +52,7 @@ export type ThreadEventTrigger = "run-ended" | "settled" | "inbox" | "request" | const KINDS_BY_TRIGGER: Record> = { "run-ended": ["lane-ended", "thread-failed", "promise-without-wake"], - settled: ["promise-without-wake"], + settled: ["lane-ended", "promise-without-wake"], inbox: ["needs-person"], request: ["needs-person"], sweep: ["stuck"], @@ -98,11 +101,38 @@ const timeMs = (value: DateTime.Utc | null | undefined) => const isLive = (shell: WatchedShell) => shell.activeRunId !== null || (shell.activityRunStatus ?? null) !== null; +const OPEN_PR_SIGNATURE_PREFIX = "open-prs:"; +/** A lane-ended report keyed by its open pull requests, not its run, so later runs share it. */ +export const isOpenPrLaneEndedSignature = (signature: string) => + signature.startsWith(OPEN_PR_SIGNATURE_PREFIX); + const openPullRequests = (shell: WatchedShell) => visibleThreadPullRequests(shell.pullRequests ?? []).filter( (link) => link.snapshot === null || link.snapshot.state === "open", ); +/** The links a lane-ended re-judge should reread from the host: the ones it counts as open. */ +export const openPullRequestLinks = (shell: Pick) => + openPullRequests(shell as WatchedShell); + +/** + * The shell as fresh host reads (keyed by `threadPullRequestKeyOf`) say it is. A link no longer + * open leaves the open set; one with no snapshot yet has none to amend, so it is left out unless + * a watch on it still counts as a wake handle. + */ +export function withPullRequestStates>( + shell: S, + states: ReadonlyMap, +): S { + const links = (shell.pullRequests ?? []).flatMap((link): ThreadPullRequestLink[] => { + const state = states.get(threadPullRequestKeyOf(link)); + if (state === undefined || state === "open") return [link]; + if (link.snapshot !== null) return [{ ...link, snapshot: { ...link.snapshot, state } }]; + return link.watch === undefined ? [] : [link]; + }); + return { ...shell, pullRequests: links }; +} + /** A pending task, a watching PR, a delegated task or a snooze that will bring the thread back. */ function hasWakeHandle(shell: WatchedShell, remoteTaskCount: number, nowMs: number) { if ((shell.pendingBackgroundTasks ?? []).length > 0) return true; @@ -215,10 +245,11 @@ export function judgeThread(input: { prs.length > 0 && !hasWakeHandle(shell, remoteTaskCount, nowMs) ) { + const openPrSignature = prs.map(threadPullRequestKeyOf).toSorted().join(","); findings.push({ kind: "lane-ended", detail: `its last run completed with ${prs.length} open pull request${prs.length === 1 ? "" : "s"} and nothing tracked that will wake it`, - signature: shell.latestRunId, + signature: `${OPEN_PR_SIGNATURE_PREFIX}${openPrSignature}`, }); } }