Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: stop recording a merge follow-up as failed after it lands its PR

[._.]/ Adam Eivy85c50ffd434c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dd2c5bf6b8..c8e451037e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -87,3 +87,4 @@
- A failed quota read on an already-loaded Quota Burn page now says so. Once a plan was on screen, a "Refresh quota" that never landed — or a background poll for a still-pending provider scrape — left the numbers exactly as they were, so a read that failed was indistinguishable from one that came back unchanged. Any failed read now raises a warning banner above the page header naming the cause, with its own Retry button, and clears itself on the next successful read (including the poll's). The banner is the page's single error surface: the manual refresh no longer toasts the same failure on top of it, and the stale plan stays rendered throughout rather than being blanked.
- Unsaved SongBook editor drafts survive a sidebar click, a ⌘K jump, voice nav and the browser Back button. The editor already deferred its own exits — the View toggle and the "All songs" link — behind an inline discard confirm, but anything that left through the router without touching those controls unmounted the editor and dropped the sheet text and practice notes silently, which is the same data loss through a different door. The client now mounts a react-router data router (the existing route tree hangs unchanged under one splat route, so no page needed rewriting), which makes `useBlocker` available, and the guard ships as a shared `useUnsavedChangesGuard(isDirty)` hook: it parks the navigation, hands the page `blocked` / `proceed()` / `reset()` so the page renders its own inline confirm rather than a `window.confirm`, and arms `beforeunload` for tab close and reload. A parked navigation that settles clean — the user hits Save with the confirm up — runs instead of being swallowed, a navigation that only changes search params on the same page is never blocked, and a ⌘-click that opens a second tab still leaves the editor standing untouched.
- Unsaved edits in the pipeline manuscript editor and the writers-room work editor now survive an in-app navigation. Both carried a `beforeunload`-only guard, so a tab close or reload asked before dropping the draft but a sidebar link, a ⌘K jump, a voice `ui_navigate` or the browser Back button unmounted the editor and discarded the work silently — manuscript sections only persist onBlur, so a section typed into and left without blurring was gone. Both now adopt the shared `useUnsavedChangesGuard` hook and render an inline Discard / Keep editing confirm (never a `window.confirm`), with the local `beforeunload` effects dropped in favour of the hook's. The manuscript editor is a splat route where switching issue tabs changes the pathname without leaving the editor, so the hook grew an `isSameView(from, to)` option that exempts an editor's own in-page moves: switching between issues with unsaved text raises nothing, while leaving the manuscript entirely still parks the navigation behind the confirm, and discarding restores each section to its last server-confirmed content before the navigation runs.
+- A merge follow-up that successfully lands its PR is no longer recorded as a failure. These runs exist to merge one pull request: they make no commit, are told to exit once the PR reads `MERGED`, and on Antigravity often skip the completion sentinel — so the idle reaper had only proxies to judge them by, and every proxy got it wrong. Their prompt quotes `gh pr checks`, `gh pr merge` and `--delete-branch`, which the TUI echoes back, which latches the swarm merge-queue tracker before any work happens; the finished agent then sat silent for the tracker's 15-minute grace and was reaped as "idled out in the merge queue — it likely died mid-merge", twice retried, and finally blocked on max retries with a high-priority "PR left open" notification naming a PR that had merged fifteen minutes into the first attempt. The reaper now asks the forge the actual question — once a follow-up run has been quiet for its normal idle window, it checks whether its PR merged, and finalises on that answer. A `gh` that cannot be reached still counts as "we could not ask" rather than "not merged", so every existing verdict is untouched when the forge is unavailable, and a follow-up whose PR genuinely did not land still surfaces as needs-manual-finish. The reaper's branch matrix also moved out of the interval body into a pure function the tests now call directly, replacing a hand-maintained copy of that logic inside the test file.
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index acac1f03b4..ea53bd6293 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -1063,6 +1063,84 @@ export function createBackgroundShellTracker() {
};
}
+/**
+ * The idle reaper's verdict, as a pure function of the signals the spawner has
+ * already latched. Lives here (not inline in the interval body) so the branch
+ * matrix is unit-testable against the REAL implementation — `agentTuiSpawning`
+ * calls this and executes what it returns.
+ *
+ * Priority order, highest first:
+ * 1. `prFollowUpMerged` — a PR follow-up run (`reviewLoopFollowUp`) exists to
+ * land ONE pull request. Once that PR reads MERGED and the session has been
+ * silent for the BASE window, the deliverable is provably in hand and there
+ * is nothing left to wait for. This outranks everything below because those
+ * branches all measure proxies (silence, worktree churn, a merge-queue
+ * latch) for a question this one answers directly. Without it a merge
+ * follow-up that did its whole job in 60s was recorded as a FAILURE: its
+ * prompt QUOTES `gh pr checks` / `gh pr merge` / `--delete-branch`, so the
+ * TUI's echo of that prompt latches `mergeQueueActive` before any work runs,
+ * and the agent — which is told to "Exit", makes no commit, and on
+ * Antigravity often skips the sentinel — then idles into (4)'s
+ * needs-manual-finish verdict 15 minutes later, gets retried twice more, and
+ * lands in Blocked with a HIGH "PR left open" card naming an already-merged
+ * PR (task sys-rl-msr1j1a5, PR #3909, 2026-08-13).
+ * 2. Not yet at the (possibly extended) deadline → keep waiting.
+ * 3–4. The extended-grace reaps: a latched merge queue / multi-reviewer loop
+ * that blew even its 15-minute window is a needs-manual-finish FAILURE
+ * (#2074, PR #2084) — the run really did go dark mid-merge.
+ * 5. `idle-no-activity` (#1229) — provider renders a work counter and it never
+ * advanced: the prompt never submitted.
+ * 6. Otherwise the pre-existing permissive `idle-complete`, which the caller
+ * still gates on worktree evidence (#2191) before recording success.
+ *
+ * Note `backgroundShellActive` extends the deadline but carries NO verdict of
+ * its own — a background-shell wait that blows its window falls through to the
+ * ordinary (5)/(6) reasoning, unchanged.
+ *
+ * @param {Object} signals
+ * @param {number} signals.idle - ms since the last PTY output
+ * @param {number} signals.baseIdleTimeoutMs - the run's configured idle window
+ * @param {boolean} [signals.mergeQueueActive]
+ * @param {boolean} [signals.reviewLoopActive]
+ * @param {boolean} [signals.backgroundShellActive]
+ * @param {boolean} [signals.prFollowUpMerged] - this is a PR follow-up AND its PR reads MERGED
+ * @param {boolean} [signals.workActive] - the work counter advanced post-submit
+ * @param {boolean} [signals.rendersCounter] - this provider renders a work counter at all
+ * @returns {{ action: 'wait'|'reap', effectiveIdleTimeoutMs: number, success?: boolean, reason?: string }}
+ */
+export function decideIdleReap({
+ idle,
+ baseIdleTimeoutMs,
+ mergeQueueActive = false,
+ reviewLoopActive = false,
+ backgroundShellActive = false,
+ prFollowUpMerged = false,
+ workActive = false,
+ rendersCounter = false,
+} = {}) {
+ const effectiveIdleTimeoutMs = mergeQueueActive
+ ? Math.max(baseIdleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)
+ : reviewLoopActive
+ ? Math.max(baseIdleTimeoutMs, REVIEW_LOOP_IDLE_TIMEOUT_MS)
+ : backgroundShellActive
+ ? Math.max(baseIdleTimeoutMs, BACKGROUND_SHELL_IDLE_TIMEOUT_MS)
+ : baseIdleTimeoutMs;
+ if (prFollowUpMerged && idle >= baseIdleTimeoutMs) {
+ return { action: 'reap', success: true, reason: 'pr-follow-up-merged', effectiveIdleTimeoutMs };
+ }
+ if (idle < effectiveIdleTimeoutMs) return { action: 'wait', effectiveIdleTimeoutMs };
+ if (mergeQueueActive) {
+ return { action: 'reap', success: false, reason: 'merge-queue-idle-timeout', effectiveIdleTimeoutMs };
+ }
+ if (reviewLoopActive) {
+ return { action: 'reap', success: false, reason: 'review-loop-idle-timeout', effectiveIdleTimeoutMs };
+ }
+ if (!workActive && rendersCounter) {
+ return { action: 'reap', success: false, reason: 'idle-no-activity', effectiveIdleTimeoutMs };
+ }
+ return { action: 'reap', success: true, reason: 'idle-complete', effectiveIdleTimeoutMs };
+}
+
// ─── Codex MCP-server boot detection ──────────────────────────────────────
//
// Codex (unlike Claude Code) boots any MCP servers configured in the user's
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 22d58db802..a407d04fea 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -33,6 +33,7 @@ import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { isMachineOnline } from '../lib/connectivity.js';
import { isAntigravityCommand } from '../lib/antigravity.js';
+import { detectForgeCli } from '../lib/gitForge.js';
import {
DEFAULT_TUI_PROMPT_DELAY_MS,
DEFAULT_TUI_IDLE_TIMEOUT_MS,
@@ -42,6 +43,7 @@ import {
MERGE_QUEUE_IDLE_TIMEOUT_MS,
REVIEW_LOOP_IDLE_TIMEOUT_MS,
BACKGROUND_SHELL_IDLE_TIMEOUT_MS,
+ decideIdleReap,
READY_POLL_INTERVAL_MS,
READY_IDLE_THRESHOLD_MS,
PASTE_MARKER_POLL_MS,
@@ -103,6 +105,13 @@ const PASTE_INPUT_GRACE_MS = 15000;
const CONNECTIVITY_RECHECK_MS = 10000;
const CONNECTIVITY_PROBE_LEAD_MS = 20000;
+// Throttle for the PR-follow-up deliverable check (see refreshFollowUpPrState).
+// Far slacker than the connectivity probe because it shells out to `gh` over the
+// network and the answer it is waiting for — "the PR flipped to MERGED" — only
+// ever changes once per run. Polling starts only after the session has already
+// been silent for its BASE idle window, so a busy follow-up never hits the forge.
+const PR_STATE_RECHECK_MS = 30000;
+
// Output buffering/spooling (createOutputSpooler) and failure-analysis /
// worktree-inspection helpers (readFileTail, worktreeHasChanges, commitsSince,
// worktreeHasWorkEvidence, captureWorktreeDiff, resolveErrorAnalysis,
@@ -837,6 +846,48 @@ export async function spawnTuiAgent({
.finally(() => { connectivity.checking = false; });
};
+ // PR-follow-up deliverable gate. A follow-up run spawned by
+ // `spawnReviewLoopFollowUp` exists to land ONE pull request — it makes no
+ // commit, is told to "Exit" when the PR reads MERGED, and (on Antigravity,
+ // which routinely skips the sentinel) then just sits at its prompt. Every
+ // signal the idle reaper otherwise has is a proxy that gets this run WRONG:
+ // its prompt quotes `gh pr checks` / `gh pr merge` / `--delete-branch`, so the
+ // TUI's echo latches the merge-queue tracker before any work happens, and the
+ // finished run is reaped 15 minutes later as `merge-queue-idle-timeout` — a
+ // needs-manual-finish FAILURE naming a PR that is already merged, retried to
+ // `Max retries exceeded` and a HIGH orphaned-PR notification (sys-rl-msr1j1a5
+ // / PR #3909, 2026-08-13). So ask the forge the actual question instead.
+ //
+ // `merged` starts false and only a `known` MERGED answer flips it: a gh we
+ // could not run (firewalled, offline) is NOT evidence of anything and must
+ // leave the pre-existing verdicts untouched. GitHub only — `gh pr view`
+ // against a GitLab MR answers nothing, so those follow-ups keep prior behavior.
+ const prFollowUpRef = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)
+ && detectForgeCli(task.metadata?.reviewLoopPRHost) === 'gh'
+ ? (task.metadata?.reviewLoopPRUrl || task.metadata?.reviewLoopPRNumber || null)
+ : null;
+ const followUpPr = { merged: false, checking: false, lastCheckAt: 0 };
+ const refreshFollowUpPrState = () => {
+ if (!prFollowUpRef || followUpPr.merged || followUpPr.checking) return;
+ if (Date.now() - followUpPr.lastCheckAt < PR_STATE_RECHECK_MS) return;
+ followUpPr.checking = true;
+ followUpPr.lastCheckAt = Date.now();
+ // Dynamic import, matching agentFinalization's forge-lookup call site: it
+ // keeps `github.js` (and its settings/data-file dependencies) out of the
+ // module graph of every suite that mocks this spawner.
+ import('./github.js')
+ .then(({ getPullRequestState }) => getPullRequestState(prFollowUpRef, { cwd }))
+ .then((res) => {
+ if (finalized) return;
+ if (res?.status === 'known' && res.state === 'MERGED') {
+ followUpPr.merged = true;
+ emitLog('info', `TUI agent ${agentId} follow-up PR reads MERGED — finalizing on the deliverable rather than the idle window`, { agentId });
+ }
+ })
+ .catch(() => {})
+ .finally(() => { followUpPr.checking = false; });
+ };
+
// The paste-attempt / max-runtime / wrap-up-grace machinery (postPasteBuffer,
// pasteEnterTimer, pasteVerifyTimer, submitEnterTimer, maxRuntimeTimer,
// wrapUpTimer) lives in createPasteRetryController rather than this closure
@@ -1608,13 +1659,26 @@ export async function spawnTuiAgent({
// re-runs go silent for minutes at a time; extend the idle grace so a
// still-working orchestrator isn't reaped mid-merge (issue #2074). The
// extended window still bounds a genuinely-dead orchestrator's reap.
- const effectiveIdleTimeoutMs = mergeQueue.active
- ? Math.max(tuiConfig.idleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)
- : reviewLoop.active
- ? Math.max(tuiConfig.idleTimeoutMs, REVIEW_LOOP_IDLE_TIMEOUT_MS)
- : backgroundShell.active
- ? Math.max(tuiConfig.idleTimeoutMs, BACKGROUND_SHELL_IDLE_TIMEOUT_MS)
- : tuiConfig.idleTimeoutMs;
+ // Which verdict this tick warrants — the whole branch matrix, as a pure
+ // function so it can be unit-tested against the real implementation instead
+ // of a drifting inline copy. This body just executes what it returns.
+ const decision = decideIdleReap({
+ idle,
+ baseIdleTimeoutMs: tuiConfig.idleTimeoutMs,
+ mergeQueueActive: mergeQueue.active,
+ reviewLoopActive: reviewLoop.active,
+ backgroundShellActive: backgroundShell.active,
+ prFollowUpMerged: followUpPr.merged,
+ workActive: workActivity.active,
+ rendersCounter: rendersWorkCounter(commandName),
+ });
+ const { effectiveIdleTimeoutMs } = decision;
+ // Past the BASE idle window a PR follow-up asks the forge whether its one
+ // deliverable already landed (throttled, non-blocking — the reading is read
+ // synchronously by the NEXT tick's decision). Keyed on the base window, not
+ // the extended one, precisely because the extended one is the bug: a merge
+ // follow-up latches the merge-queue grace off its own echoed prompt.
+ if (idle >= tuiConfig.idleTimeoutMs) refreshFollowUpPrState();
// Once within the LEAD window of the (possibly extended) reap deadline, keep
// a reachability reading fresh (throttled, non-blocking) so the gate below
// can read it synchronously and won't reap an agent that's only silent
@@ -1622,7 +1686,17 @@ export async function spawnTuiAgent({
// fixed lead off the base window) keeps a long merge-queue/review-loop idle
// from probing for its whole 15-min window.
if (idle >= effectiveIdleTimeoutMs - CONNECTIVITY_PROBE_LEAD_MS) refreshConnectivity();
- if (idle >= effectiveIdleTimeoutMs) {
+ if (decision.action === 'reap') {
+ // The follow-up's PR is MERGED and the session has gone quiet: the
+ // deliverable is provably in hand, so finalize on it. Deliberately ahead
+ // of the offline defer below — that gate exists because silence is
+ // ambiguous, and this verdict does not rest on silence.
+ if (decision.reason === 'pr-follow-up-merged') {
+ finish({ success: true, exitCode: 0, reason: 'pr-follow-up-merged' }).catch(err => {
+ emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });
+ });
+ return;
+ }
// An internet outage silences a live TUI exactly like a hung or finished
// agent looks to this timer. If a recent probe says we're offline, DEFER
// the reap — the agent is only blocked on the network and resumes when it
@@ -1639,7 +1713,7 @@ export async function spawnTuiAgent({
// almost certainly died mid-merge with PRs opened/merged-but-uncleaned.
// Surface it as a needs-manual-finish FAILURE rather than the silent
// `status: completed` that hid the half-done merge queue (issue #2074).
- if (mergeQueue.active) {
+ if (decision.reason === 'merge-queue-idle-timeout') {
finish({
success: false,
exitCode: 1,
@@ -1655,7 +1729,7 @@ export async function spawnTuiAgent({
// simply exceeded budget. Surface it as a needs-manual-finish FAILURE
// rather than the silent `status: completed` that let PR #2084 sit
// open+unmerged for hours while agent-61508f36 looked "done".
- if (reviewLoop.active) {
+ if (decision.reason === 'review-loop-idle-timeout') {
finish({
success: false,
exitCode: 1,
@@ -1687,8 +1761,7 @@ export async function spawnTuiAgent({
// orchestrator doesn't treat a no-op as done. Capture the diff into the
// agent archive dir before cleanup so post-mortems can see what (if
// anything) was left behind.
- const noWorkButCounterExpected = !workActivity.active && rendersWorkCounter(commandName);
- if (noWorkButCounterExpected) {
+ if (decision.reason === 'idle-no-activity') {
// Capture any uncommitted changes for post-mortem analysis
captureWorktreeDiff(cwd, agentDir).catch(() => {});
finish({
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 1f9f0cc56e..aa46baf043 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -211,7 +211,14 @@ import * as agentErrorAnalysis from './agentErrorAnalysis.js';
import * as cosAgentLifecycle from './cosAgentLifecycle.js';
import * as gitService from './git.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
-import { MAX_RUNTIME_WRAP_UP_GRACE_MS, SELF_CLEARING_RESUBMIT_INTERVAL_MS } from '../lib/tuiHandshake.js';
+import {
+ MAX_RUNTIME_WRAP_UP_GRACE_MS,
+ SELF_CLEARING_RESUBMIT_INTERVAL_MS,
+ MERGE_QUEUE_IDLE_TIMEOUT_MS,
+ REVIEW_LOOP_IDLE_TIMEOUT_MS,
+ BACKGROUND_SHELL_IDLE_TIMEOUT_MS,
+ decideIdleReap,
+} from '../lib/tuiHandshake.js';
// Real module, not a mock: the flag is a plain process-local boolean, so driving
// it directly exercises the same code path production does.
import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';
@@ -2449,39 +2456,15 @@ describe('spawnTuiAgent runtime', () => {
// Issue #2074 — the idle reaper must extend its grace while a swarm orchestrator
// is in its Phase C merge queue, and, if the EXTENDED window still blows, surface
-// a needs-manual-finish failure instead of a silent `status: completed`. This is
-// the exact decision the `idleTimer` interval makes; mirror it as a pure function
-// (the inline-copy pattern from subAgentSpawner.test.js) so the branch matrix is
-// tested without standing up the full fake-timer PTY harness. Generalized to
-// do:release/do:pr/do:rpr's multi-reviewer loop below (agent-61508f36, PR #2084).
+// a needs-manual-finish failure instead of a silent `status: completed`.
+//
+// Exercises the REAL `decideIdleReap` the idleTimer body calls (it was an inline
+// copy here until the merge-follow-up branch below made the drift risk concrete
+// — a copy would have "passed" while the shipped reaper still failed merged
+// PRs). The real code keeps an async worktree-changes check (#2191) that can
+// downgrade `idle-complete` to `idle-no-changes`; that's covered by the full
+// fake-timer harness above, not by this pure function.
describe('agentTuiSpawning — idle reap decision (#2074)', () => {
- const MERGE_QUEUE_IDLE_TIMEOUT_MS = 900000;
- const REVIEW_LOOP_IDLE_TIMEOUT_MS = 900000;
-
- // Faithful copy of the SYNCHRONOUS part of the idleTimer body's finalize-
- // selection logic. The real code has an async worktree-changes check (#2191)
- // that may downgrade `idle-complete` to `idle-no-changes` — that's tested via
- // the full fake-timer harness above, not this pure function.
- function decideIdleReap({ idle, baseIdleTimeoutMs, mergeQueueActive, reviewLoopActive, workActive, rendersCounter }) {
- const effectiveIdleTimeoutMs = mergeQueueActive
- ? Math.max(baseIdleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)
- : reviewLoopActive
- ? Math.max(baseIdleTimeoutMs, REVIEW_LOOP_IDLE_TIMEOUT_MS)
- : baseIdleTimeoutMs;
- if (idle < effectiveIdleTimeoutMs) return { action: 'wait', effectiveIdleTimeoutMs };
- if (mergeQueueActive) {
- return { action: 'reap', success: false, reason: 'merge-queue-idle-timeout', effectiveIdleTimeoutMs };
- }
- if (reviewLoopActive) {
- return { action: 'reap', success: false, reason: 'review-loop-idle-timeout', effectiveIdleTimeoutMs };
- }
- const noWorkButCounterExpected = !workActive && rendersCounter;
- if (noWorkButCounterExpected) {
- return { action: 'reap', success: false, reason: 'idle-no-activity', effectiveIdleTimeoutMs };
- }
- return { action: 'reap', success: true, reason: 'idle-complete', effectiveIdleTimeoutMs };
- }
-
const BASE = 180000;
it('does NOT reap at the 3-min default while in a merge queue — grace extends to 15min', () => {
@@ -2544,4 +2527,62 @@ describe('agentTuiSpawning — idle reap decision (#2074)', () => {
const r = decideIdleReap({ idle: 900001, baseIdleTimeoutMs: BASE, mergeQueueActive: true, reviewLoopActive: true, workActive: true, rendersCounter: true });
expect(r.reason).toBe('merge-queue-idle-timeout');
});
+
+ it('a background-shell wait extends the window but carries no verdict of its own', () => {
+ const waiting = decideIdleReap({ idle: BASE + 1, baseIdleTimeoutMs: BASE, backgroundShellActive: true, workActive: true, rendersCounter: true });
+ expect(waiting.action).toBe('wait');
+ expect(waiting.effectiveIdleTimeoutMs).toBe(BACKGROUND_SHELL_IDLE_TIMEOUT_MS);
+ const blown = decideIdleReap({ idle: BACKGROUND_SHELL_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, backgroundShellActive: true, workActive: true, rendersCounter: true });
+ expect(blown.reason).toBe('idle-complete');
+ expect(blown.success).toBe(true);
+ });
+
+ // The merge-follow-up false failure (task sys-rl-msr1j1a5 / PR #3909,
+ // 2026-08-13). The follow-up prompt QUOTES `gh pr checks` / `gh pr merge` /
+ // `--delete-branch`, so the TUI's echo of it latches `mergeQueueActive` before
+ // any work runs. The agent then merged the PR in ~60s, printed "PR Status:
+ // MERGED", made no commit (nothing to commit — it only merges), skipped the
+ // sentinel, and idled — and was recorded as `merge-queue-idle-timeout` 15
+ // minutes later, three times over, ending in Blocked with a HIGH "PR left
+ // open" card naming an already-merged PR.
+ describe('PR follow-up whose PR already merged', () => {
+ it('reaps as a SUCCESS at the BASE window even with the merge queue latched', () => {
+ const r = decideIdleReap({
+ idle: BASE + 1, baseIdleTimeoutMs: BASE,
+ mergeQueueActive: true, prFollowUpMerged: true, workActive: true, rendersCounter: true,
+ });
+ expect(r.action).toBe('reap');
+ expect(r.success).toBe(true);
+ expect(r.reason).toBe('pr-follow-up-merged');
+ });
+
+ it('does not fire before the BASE window — a merged PR is not a reason to cut a working agent short', () => {
+ const r = decideIdleReap({
+ idle: BASE - 1, baseIdleTimeoutMs: BASE,
+ mergeQueueActive: true, prFollowUpMerged: true, workActive: true, rendersCounter: true,
+ });
+ expect(r.action).toBe('wait');
+ });
+
+ it('outranks the no-activity downgrade too — the deliverable landed regardless of the work counter', () => {
+ const r = decideIdleReap({
+ idle: BASE + 1, baseIdleTimeoutMs: BASE,
+ prFollowUpMerged: true, workActive: false, rendersCounter: true,
+ });
+ expect(r.success).toBe(true);
+ expect(r.reason).toBe('pr-follow-up-merged');
+ });
+
+ // The bug this whole branch exists to kill: without `prFollowUpMerged` the
+ // SAME signals produce the needs-manual-finish failure. Guards against a
+ // future refactor that quietly stops threading the forge answer through.
+ it('still fails as needs-manual-finish when the PR did NOT merge', () => {
+ const r = decideIdleReap({
+ idle: MERGE_QUEUE_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE,
+ mergeQueueActive: true, prFollowUpMerged: false, workActive: true, rendersCounter: true,
+ });
+ expect(r.success).toBe(false);
+ expect(r.reason).toBe('merge-queue-idle-timeout');
+ });
+ });
});
diff --git a/server/services/github.js b/server/services/github.js
index 90624392ab..f5f1fd8837 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -562,3 +562,36 @@ export async function findPullRequestForBranch(branch, { cwd = null, env = null
if (!pr) return { status: 'none', number: null, url: null, detail: null };
return { status: 'found', number: pr.number ?? null, url: pr.url || null, detail: pr.state || null };
}
+
+/**
+ * Read ONE pull request's state. Same two-not-three-answers discipline as
+ * `findPullRequestForBranch`: `known` carries a real forge answer, `unavailable`
+ * means we could not ask (gh firewalled, PR deleted, unparseable output). A
+ * caller must never read `unavailable` as "not merged" — the whole point is to
+ * distinguish "the forge says OPEN" from "we never got to ask", because the
+ * merge-follow-up reaper turns the first into a needs-manual-finish failure and
+ * the second must leave prior behavior alone.
+ *
+ * GitHub only. PortOS opens GitLab MRs too, and `gh pr view` against a GitLab
+ * URL answers nothing useful — callers classify the host first and skip this.
+ *
+ * @param {string} prRef - PR url or number (anything `gh pr view` accepts)
+ * @param {{ cwd?: string, env?: object|null }} [opts] - repo dir gh resolves the
+ * remote from, and the env overlay to run under (see `resolveForgeForRepo`).
+ * @returns {Promise<{ status: 'known'|'unavailable', state: string|null, detail: string|null }>}
+ * `state` is upper-cased (`MERGED` / `OPEN` / `CLOSED`) when status is `known`.
+ */
+export async function getPullRequestState(prRef, { cwd = null, env = null } = {}) {
+ if (!prRef) return { status: 'unavailable', state: null, detail: 'no PR reference' };
+ const raw = await execGh(
+ ['pr', 'view', String(prRef), '--json', 'state'],
+ DEFAULT_EXEC_GH_TIMEOUT_MS,
+ { cwd, env }
+ ).catch(err => err);
+ if (raw instanceof Error) return { status: 'unavailable', state: null, detail: raw.message };
+ const parsed = safeJSONParse(raw, null);
+ const state = typeof parsed?.state === 'string' ? parsed.state.toUpperCase() : null;
+ // A zero-exit gh that emitted nothing parseable told us nothing.
+ if (!state) return { status: 'unavailable', state: null, detail: 'gh returned unparseable output' };
+ return { status: 'known', state, detail: null };
+}
diff --git a/server/services/github.test.js b/server/services/github.test.js
index 2035779d98..d7d0a47da9 100644
--- a/server/services/github.test.js
+++ b/server/services/github.test.js
@@ -7,7 +7,7 @@ vi.mock('child_process', async (importOriginal) => {
});
import { spawn } from 'child_process';
-import { execGh } from './github.js';
+import { execGh, getPullRequestState } from './github.js';
const makeChild = () => {
const child = new EventEmitter();
@@ -84,3 +84,72 @@ describe('execGh', () => {
await expect(promise).rejects.toThrow(/ENOENT/);
});
});
+
+// The merge-follow-up reaper turns "the forge says this PR is OPEN" into a
+// needs-manual-finish failure and "we could not ask" into leave-prior-behavior-
+// alone, so collapsing those two answers is the whole hazard this shape exists
+// to prevent (same discipline as findPullRequestForBranch, #3358).
+describe('getPullRequestState', () => {
+ beforeEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ const run = (prRef, drive) => {
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+ const promise = getPullRequestState(prRef);
+ drive(child);
+ return promise;
+ };
+
+ it('reports a known MERGED state, upper-cased', async () => {
+ await expect(run('https://example.test/o/r/pull/7', (c) => {
+ c.stdout.emit('data', Buffer.from('{"state":"merged"}'));
+ c.emit('close', 0);
+ })).resolves.toEqual({ status: 'known', state: 'MERGED', detail: null });
+ });
+
+ it('reports a known OPEN state rather than collapsing it into "not merged"', async () => {
+ const res = await run('7', (c) => {
+ c.stdout.emit('data', Buffer.from('{"state":"OPEN"}'));
+ c.emit('close', 0);
+ });
+ expect(res).toEqual({ status: 'known', state: 'OPEN', detail: null });
+ });
+
+ it('passes the PR reference straight to `gh pr view --json state`', async () => {
+ await run('https://example.test/o/r/pull/7', (c) => {
+ c.stdout.emit('data', Buffer.from('{"state":"MERGED"}'));
+ c.emit('close', 0);
+ });
+ expect(spawn).toHaveBeenCalledWith(
+ 'gh',
+ ['pr', 'view', 'https://example.test/o/r/pull/7', '--json', 'state'],
+ expect.anything()
+ );
+ });
+
+ it('reports unavailable — NOT a state — when gh fails (the firewalled-gh case)', async () => {
+ const res = await run('7', (c) => {
+ c.stderr.emit('data', Buffer.from('dial tcp: connect: bad file descriptor'));
+ c.emit('close', 1);
+ });
+ expect(res.status).toBe('unavailable');
+ expect(res.state).toBeNull();
+ expect(res.detail).toMatch(/bad file descriptor/);
+ });
+
+ it('reports unavailable when a zero-exit gh emits nothing parseable', async () => {
+ const res = await run('7', (c) => {
+ c.stdout.emit('data', Buffer.from('not json'));
+ c.emit('close', 0);
+ });
+ expect(res).toEqual({ status: 'unavailable', state: null, detail: 'gh returned unparseable output' });
+ });
+
+ it('reports unavailable without shelling out when given no reference', async () => {
+ await expect(getPullRequestState('')).resolves.toEqual({ status: 'unavailable', state: null, detail: 'no PR reference' });
+ expect(spawn).not.toHaveBeenCalled();
+ });
+});