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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: merge healthy PRs on watcher ticks (#3061)
[._.]/ Adam Eivy319fe5e0b34f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 78a99fd86c..9e50fabf73 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Layered Intelligence+- **[issue-3061] Healthy agent-created pull requests now merge on the watcher tick instead of spending another agent lane** — when PortOS opens a GitHub PR with no review loop, the scheduled PR watcher now reads its CI and merge state: a clean PR whose checks are all green merges directly, while an actual validation failure or merge conflict still starts the same merge-only follow-up agent as before. PRs waiting on CI remain quiet for a bounded number of checks; if they never settle, PortOS stops polling them and posts a high-priority notice with a link to the PR.- **[issue-3019] Layered Intelligence now notices when approved work is not being delivered** — its self-check now tracks approval-to-completion separately from reasoning-run success, so a loop that completes its own runs but repeatedly leaves approved proposals unfinished stops filing self-improvement work until delivery recovers. A five-approval floor keeps a fresh loop from being gated on cold-start noise, and the reasoner-facing notice identifies whether run health, delivery health, or both caused the guardrail.## 3Ddiff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 8be9fee343..95d3400e10 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -180,24 +180,65 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, p} else if (leaveOpen && !runsReviewLoop) {emitLog('info', `🤝 Leaving ${prResult.url} open for a human — JIRA-tracked task, no reviewers configured`, { agentId, prUrl: prResult.url });} else {- await spawnReviewLoopFollowUp({- originalAgentId: agentId,- originalTask,- prUrl: prResult.url,- prBranch: worktreeBranch,- sourceWorkspace,- prCompletion: resolvedPrCompletion,- reviewers: runsReviewLoop ? reviewerList : [],- usernames: runsReviewLoop ? usernames : [],- optionalReviewers: runsReviewLoop ? optionalReviewers : [],- reviewStopMode,- reviewerApplies,- reviewerModels,- leaveOpen- }).catch(err => {- emitLog('warn', `🤖 Failed to spawn PR follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });- warnings.push(`PR follow-up spawn failed for ${prResult.url}: ${err.message}`);- });+ // A merge-only GitHub PR needs no model while CI is healthy. Hand it to+ // pr-watcher's deterministic tick instead; that tick merges green PRs+ // directly and recreates this exact follow-up only for a failed check or+ // conflict. Non-GitHub forges and unscoped tasks retain the legacy agent+ // path because pr-watcher intentionally speaks gh against managed apps.+ const canQueueDeterministicMerge = resolvedPrCompletion === PR_COMPLETIONS.MERGE_ON_GREEN+ && prResult.cli === 'gh'+ && !!originalTask?.metadata?.app;+ let queuedDeterministicMerge = false;+ if (canQueueDeterministicMerge) {+ const parsedPr = git.parsePullRequestUrl(prResult.url);+ try {+ const { queuePendingMerge } = await import('./prWatcher.js');+ queuedDeterministicMerge = await queuePendingMerge(originalTask.metadata.app, {+ prUrl: prResult.url,+ prNumber: parsedPr?.number,+ prBranch: worktreeBranch,+ sourceAgentId: agentId,+ sourceTask: {+ id: originalTask?.id || null,+ priority: originalTask?.priority || 'MEDIUM',+ description: originalTask?.description || description || 'CoS automated task',+ metadata: {+ app: originalTask.metadata.app,+ provider: originalTask.metadata.provider,+ providerId: originalTask.metadata.providerId,+ model: originalTask.metadata.model,+ effort: originalTask.metadata.effort,+ }+ }+ });+ } catch (err) {+ emitLog('warn', `🤖 Failed to queue deterministic merge for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });+ }+ if (queuedDeterministicMerge) {+ emitLog('info', `🤖 Queued ${prResult.url} for deterministic merge on the next pr-watcher tick`, { agentId, prUrl: prResult.url });+ }+ }++ if (!queuedDeterministicMerge) {+ await spawnReviewLoopFollowUp({+ originalAgentId: agentId,+ originalTask,+ prUrl: prResult.url,+ prBranch: worktreeBranch,+ sourceWorkspace,+ prCompletion: resolvedPrCompletion,+ reviewers: runsReviewLoop ? reviewerList : [],+ usernames: runsReviewLoop ? usernames : [],+ optionalReviewers: runsReviewLoop ? optionalReviewers : [],+ reviewStopMode,+ reviewerApplies,+ reviewerModels,+ leaveOpen+ }).catch(err => {+ emitLog('warn', `🤖 Failed to spawn PR follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });+ warnings.push(`PR follow-up spawn failed for ${prResult.url}: ${err.message}`);+ });+ }}const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex cdb490f4e1..5bc0b39841 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -181,6 +181,11 @@ vi.mock('./git.js', () => ({})}));+const queuePendingMergeMock = vi.fn();+vi.mock('./prWatcher.js', () => ({+ queuePendingMerge: (...args) => queuePendingMergeMock(...args)+}));+vi.mock('./runner.js', () => ({executeApiRun: vi.fn(),executeCliRun: vi.fn(),@@ -211,6 +216,7 @@ function mockWorktreeAgent(overrides = {}) {describe('cleanupAgentWorktree - openPR path', () => {beforeEach(() => {vi.clearAllMocks();+ queuePendingMergeMock.mockResolvedValue(false);// Default: agent is a worktree agent with valid metadatagetAgent.mockResolvedValue(mockWorktreeAgent());git.getRepoBranches.mockResolvedValue({ baseBranch: 'main', devBranch: null });@@ -669,6 +675,33 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(removeWorktree).toHaveBeenCalled();});+ it('queues a managed GitHub merge-only PR for the watcher instead of consuming an agent lane', async () => {+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/61', cli: 'gh' });+ queuePendingMergeMock.mockResolvedValue(true);++ await cleanupAgentWorktree('agent-1', true, {+ openPR: true,+ requestCopilotReview: false,+ description: 'Build with deterministic merge',+ originalTask: {+ id: 'task-orig',+ priority: 'HIGH',+ metadata: { app: 'managed-app', provider: 'codex', providerId: 'codex', model: 'gpt-5.6', effort: 'high' },+ description: 'Build with deterministic merge'+ }+ });++ expect(queuePendingMergeMock).toHaveBeenCalledWith('managed-app', expect.objectContaining({+ prNumber: 61,+ prBranch: 'cos/task-abc123',+ sourceAgentId: 'agent-1',+ sourceTask: expect.objectContaining({ id: 'task-orig', priority: 'HIGH' })+ }));+ expect(addTask).not.toHaveBeenCalled();+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });+ });+// --- non-Copilot reviewer (--review-with claude/antigravity/codex) ---it('should NOT call the native GH Copilot reviewer API when the list has no copilot', async () => {diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 10fd250e91..4749f1a359 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2030,6 +2030,15 @@ async function resolveReferenceWatchBlock(app, taskType) {async function resolvePrWatcherBlock(app, taskType, metadata, taskSchedule) {if (taskType !== 'pr-watcher') return { skip: false, block: '', repoFullName: '', defaultBranch: '' };const prWatcher = await import('./prWatcher.js');+ // Merge-only PRs created by PortOS share this existing cadence. A green PR+ // lands deterministically here without claiming an agent lane; only a failed+ // check or conflict recreates the merge-only follow-up agent.+ const pendingMerges = await prWatcher.processPendingMergePrs(app);+ if (!pendingMerges.ok) {+ emitLog('warn', `pr-watcher pending merge sweep failed for ${app.name}: ${pendingMerges.reason}`, { appId: app.id });+ } else if (pendingMerges.merged || pendingMerges.escalated || pendingMerges.timedOut) {+ emitLog('info', `pr-watcher pending merges for ${app.name}: ${pendingMerges.merged} merged, ${pendingMerges.escalated} escalated, ${pendingMerges.timedOut} timed out`, { appId: app.id });+ }// prAuthorFilter was already merged + value-constrained into `metadata`.const authorFilter = metadata.prAuthorFilter || 'any';const check = await prWatcher.checkPullRequests(app, { authorFilter });diff --git a/server/services/git.js b/server/services/git.jsindex 77fee55503..85ad6ba0ac 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -451,6 +451,38 @@ export async function createPR(dir, { title, body, base, head }) {});}+/**+ * Merge an already-open GitHub pull request with the same owner-pinned `gh`+ * environment used to create it. Callers decide when CI is green; this helper+ * only performs the deterministic merge and reports its outcome.+ *+ * @param {string} dir - Working directory for the target repository+ * @param {number|string} prNumber - Pull request number+ * @returns {Promise<{success: boolean, error?: string, cli?: string, account?: string|null, owner?: string|null, host?: string|null}>}+ */+export async function mergePR(dir, prNumber) {+ const { cli, env, host, owner, account } = await resolveForgeForRepo(dir);+ const meta = { cli, account, owner, host };+ if (cli !== 'gh') {+ return { success: false, error: `Merge-only PR automation requires gh, not ${cli}`, ...meta };+ }++ return new Promise((resolve) => {+ const child = spawn('gh', ['pr', 'merge', String(prNumber), '--merge', '--delete-branch'], {+ cwd: dir, env, shell: false, windowsHide: true+ });+ let stderr = '';+ child.stderr.on('data', (data) => { stderr += data.toString(); });+ child.on('close', (code) => {+ if (code === 0) resolve({ success: true, ...meta });+ else resolve({ success: false, error: stderr.trim() || `gh exited with code ${code}`, ...meta });+ });+ child.on('error', (err) => {+ resolve({ success: false, error: `gh not available: ${err.message}`, ...meta });+ });+ });+}+/*** Request a Copilot code review on a GitHub PR. The reviewer login MUST include* the `[bot]` suffix or GitHub returns 422 "must be a collaborator". GitLab hasdiff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex f2254e0274..df003ea374 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -26,10 +26,14 @@import { execGh } from './github.js';import { getAppById, updateApp } from './apps.js';+import * as git from './git.js';+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';+import { classifyPrFailure } from './layeredIntelligenceRejections.js';import { getOriginInfo } from '../lib/gitRemote.js';import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';import { PR_AUTHOR_FILTERS } from '../lib/validation.js';import { safeJSONParse } from '../lib/fileUtils.js';+import { PR_COMPLETIONS } from '../lib/prDisposition.js';// Bound the gh query. The high-water mark (computePrCheck) advances to the max// open PR number it saw, so it can only correctly drain a backlog it received@@ -42,6 +46,17 @@ import { safeJSONParse } from '../lib/fileUtils.js';// the cap. 200 matches the limit github.js#syncRepos already uses.const PR_LIST_LIMIT = 200;+// A watcher tick normally runs every 30 minutes. Six hours is long enough for+// an ordinary CI queue, while still surfacing a wedged provider or branch+// protection rule before a merge-only PR silently leaks forever.+export const MAX_PENDING_MERGE_TICKS = 12;++const GREEN_CHECK_VERDICTS = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);+// Every app lives in the same apps.json store, so this must be one global tail+// rather than a per-app map: simultaneous writes for different app ids would+// otherwise still load stale whole-file snapshots and clobber one another.+let pendingMergeWriteTail = Promise.resolve();+// Cache the gh-authenticated login PER HOST, for the process lifetime. Host-keyed// for two reasons: (1) `gh api` does NOT infer the host from the working// directory's git remote the way `gh pr list` / `gh issue list` do — it hits the@@ -170,6 +185,192 @@ export function readPrWatcherState(app) {return state && typeof state === 'object' && !Array.isArray(state) ? state : {};}+/**+ * Read the merge-only PRs that a completed PortOS agent handed to this+ * watcher's deterministic CI gate. This lives beside, rather than inside,+ * `prWatcherState`: disabling the watcher clears its discovery high-water mark+ * so the next enable baselines cleanly, but it must never forget a PR it owns.+ */+export function readPendingMergePrs(app) {+ return Array.isArray(app?.pendingMergePrs) ? app.pendingMergePrs : [];+}++const pendingMergeKey = (pending) => `${pending?.prNumber ?? ''}:${pending?.prUrl ?? ''}`;++function normalizePendingMerge(pending) {+ if (!pending || typeof pending !== 'object') return null;+ if (!Number.isInteger(pending.prNumber) || pending.prNumber < 1) return null;+ if (typeof pending.prUrl !== 'string' || !pending.prUrl) return null;+ if (typeof pending.prBranch !== 'string' || !pending.prBranch) return null;+ if (!pending.sourceTask || typeof pending.sourceTask !== 'object') return null;+ return {+ ...pending,+ ticks: Number.isInteger(pending.ticks) && pending.ticks >= 0 ? pending.ticks : 0,+ };+}++function queuePendingMergeWrite(write) {+ const next = pendingMergeWriteTail.catch(() => undefined).then(write);+ pendingMergeWriteTail = next;+ return next;+}++async function mutatePendingMergePrs(appId, mutate) {+ return queuePendingMergeWrite(async () => {+ const app = await getAppById(appId);+ if (!app) return null;+ const next = mutate(readPendingMergePrs(app).map(normalizePendingMerge).filter(Boolean));+ return updateApp(appId, { pendingMergePrs: next });+ });+}++/**+ * Persist a merge-only PR for the next existing pr-watcher tick. The source+ * task carries only the fields the escalation path needs to recreate today's+ * merge follow-up, rather than retaining the whole completed task payload.+ */+export async function queuePendingMerge(appId, pending) {+ const normalized = normalizePendingMerge(pending);+ if (!appId || !normalized) return false;++ const result = await mutatePendingMergePrs(appId, (existing) => {+ const key = pendingMergeKey(normalized);+ const index = existing.findIndex((entry) => pendingMergeKey(entry) === key);+ if (index === -1) return [...existing, normalized];+ const next = [...existing];+ // Preserve the existing tick count so a duplicated completion callback+ // cannot reset an already-wedged PR's bounded-watch budget.+ next[index] = { ...normalized, ticks: existing[index].ticks };+ return next;+ });+ return Boolean(result);+}++/**+ * True only when an OPEN PR is cleanly mergeable and every reported check has+ * reached a non-blocking green verdict. An empty rollup remains pending: a+ * just-opened PR often reports no checks before CI attaches, and merging then+ * would race the gate this watcher is meant to enforce.+ */+export function isPendingMergeReady(prView) {+ if (String(prView?.state || '').toUpperCase() !== 'OPEN') return false;+ if (String(prView?.mergeStateStatus || '').toUpperCase() !== 'CLEAN') return false;+ const rollup = Array.isArray(prView?.statusCheckRollup) ? prView.statusCheckRollup : [];+ return rollup.length > 0 && rollup.every((check) => {+ const verdict = String(check?.conclusion || check?.state || '').toUpperCase();+ return GREEN_CHECK_VERDICTS.has(verdict);+ });+}++async function readPendingPullRequest(repoSpec, prNumber) {+ const raw = await execGh([+ 'pr', 'view', String(prNumber), '--repo', repoSpec,+ '--json', 'state,mergeStateStatus,statusCheckRollup'+ ]).catch(() => null);+ const parsed = raw === null ? null : safeJSONParse(raw, null);+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;+}++async function notifyPendingMergeTimeout(app, pending, reason) {+ return addNotification({+ type: NOTIFICATION_TYPES.AGENT_WARNING,+ priority: PRIORITY_LEVELS.HIGH,+ title: `Merge-only PR #${pending.prNumber} needs attention`,+ description: `PortOS stopped polling this PR after ${MAX_PENDING_MERGE_TICKS} checks because ${reason}.`,+ link: pending.prUrl,+ metadata: { appId: app.id, pendingMergePrNumber: pending.prNumber }+ }).catch((err) => {+ console.error(`❌ Failed to notify about pending PR #${pending.prNumber}: ${err.message}`);+ return null;+ });+}++/**+ * Drive merge-only PortOS PRs on the normal pr-watcher cadence. Green PRs are+ * merged without consuming an agent lane; only a classified CI failure or+ * merge conflict recreates the pre-existing merge-only follow-up agent.+ */+export async function processPendingMergePrs(app) {+ const pending = readPendingMergePrs(app).map(normalizePendingMerge).filter(Boolean);+ if (pending.length === 0) return { ok: true, checked: 0, merged: 0, escalated: 0, timedOut: 0 };++ const origin = await getOriginInfo(app?.repoPath).catch(() => null);+ const repoSpec = githubRepoSpec(origin);+ if (!repoSpec) return { ok: false, reason: 'not-a-github-repo' };++ const outcomes = new Map();+ const result = { ok: true, checked: 0, merged: 0, escalated: 0, timedOut: 0, errors: 0 };++ for (const entry of pending) {+ const key = pendingMergeKey(entry);+ const prView = await readPendingPullRequest(repoSpec, entry.prNumber);+ if (!prView) {+ outcomes.set(key, entry);+ result.errors += 1;+ continue;+ }+ result.checked += 1;++ if (String(prView.state || '').toUpperCase() === 'MERGED') {+ outcomes.set(key, null);+ continue;+ }++ const failure = classifyPrFailure(prView);+ if (failure) {+ try {+ const { spawnReviewLoopFollowUp } = await import('./agentWorktreeCleanup.js');+ await spawnReviewLoopFollowUp({+ originalAgentId: entry.sourceAgentId || null,+ originalTask: entry.sourceTask,+ prUrl: entry.prUrl,+ prBranch: entry.prBranch,+ sourceWorkspace: app.repoPath,+ prCompletion: PR_COMPLETIONS.MERGE_ON_GREEN,+ reviewers: [],+ usernames: [],+ optionalReviewers: []+ });+ outcomes.set(key, null);+ result.escalated += 1;+ } catch (err) {+ console.error(`❌ Failed to escalate PR #${entry.prNumber}: ${err.message}`);+ outcomes.set(key, entry);+ result.errors += 1;+ }+ continue;+ }++ if (isPendingMergeReady(prView)) {+ const merge = await git.mergePR(app.repoPath, entry.prNumber).catch((err) => ({ success: false, error: err.message }));+ if (merge.success) {+ outcomes.set(key, null);+ result.merged += 1;+ continue;+ }+ console.error(`❌ Deterministic merge failed for PR #${entry.prNumber}: ${merge.error || 'unknown error'}`);+ }++ const next = { ...entry, ticks: entry.ticks + 1 };+ if (next.ticks >= MAX_PENDING_MERGE_TICKS) {+ const reason = String(prView.state || '').toUpperCase() !== 'OPEN'+ ? `it is ${String(prView.state).toLowerCase()} rather than open`+ : 'CI or mergeability did not settle';+ await notifyPendingMergeTimeout(app, entry, reason);+ outcomes.set(key, null);+ result.timedOut += 1;+ } else {+ outcomes.set(key, next);+ }+ }++ await mutatePendingMergePrs(app.id, (current) => current.flatMap((entry) => {+ const outcome = outcomes.get(pendingMergeKey(entry));+ return outcome === undefined ? [entry] : outcome ? [outcome] : [];+ }));+ return result;+}+/*** Merge a patch into the app's persisted watcher state. Re-reads the app first* so the merge is against the freshest record.diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.jsindex 3bf68c24fa..1c7def8cfb 100644--- a/server/services/prWatcher.test.js+++ b/server/services/prWatcher.test.js@@ -7,6 +7,23 @@ vi.mock('./github.js', () => ({execGh: (...args) => execGhMock(...args),}));+const mergePrMock = vi.fn();+vi.mock('./git.js', () => ({+ mergePR: (...args) => mergePrMock(...args),+}));++const addNotificationMock = vi.fn();+vi.mock('./notifications.js', () => ({+ addNotification: (...args) => addNotificationMock(...args),+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },+ PRIORITY_LEVELS: { HIGH: 'high' },+}));++const spawnReviewLoopFollowUpMock = vi.fn();+vi.mock('./agentWorktreeCleanup.js', () => ({+ spawnReviewLoopFollowUp: (...args) => spawnReviewLoopFollowUpMock(...args),+}));+const mockApps = new Map();vi.mock('./apps.js', () => ({getAppById: vi.fn(async (id) => mockApps.get(id) || null),@@ -28,6 +45,11 @@ import {computePrCheck,formatPullRequestsForPrompt,readPrWatcherState,+ readPendingMergePrs,+ queuePendingMerge,+ isPendingMergeReady,+ processPendingMergePrs,+ MAX_PENDING_MERGE_TICKS,checkPullRequests,getSelfLogin,__resetSelfLoginCache,@@ -46,6 +68,11 @@ const pr = (number, login, extra = {}) => ({beforeEach(() => {execGhMock.mockReset();+ mergePrMock.mockReset();+ addNotificationMock.mockReset();+ spawnReviewLoopFollowUpMock.mockReset();+ addNotificationMock.mockResolvedValue({ id: 'notification-1' });+ spawnReviewLoopFollowUpMock.mockResolvedValue({ id: 'follow-up-1' });getOriginInfoMock.mockReset();mockApps.clear();__resetSelfLoginCache();@@ -118,6 +145,115 @@ describe('readPrWatcherState', () => {});});+const pendingMerge = (overrides = {}) => ({+ prUrl: 'https://github.com/o/r/pull/88',+ prNumber: 88,+ prBranch: 'cos/task-88',+ sourceAgentId: 'agent-88',+ sourceTask: {+ id: 'task-88',+ priority: 'MEDIUM',+ description: 'Automated task',+ metadata: { app: 'app1' }+ },+ ticks: 0,+ ...overrides,+});++const pendingApp = (entries = [pendingMerge()]) => ({+ id: 'app1',+ repoPath: '/repos/app1',+ pendingMergePrs: entries+});++describe('merge-only PR watcher', () => {+ beforeEach(() => {+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });+ });++ it('queues a valid pending merge once without resetting its elapsed tick budget', async () => {+ mockApps.set('app1', pendingApp([pendingMerge({ ticks: 4 })]));++ const queued = await queuePendingMerge('app1', pendingMerge());++ expect(queued).toBe(true);+ expect(readPendingMergePrs(mockApps.get('app1'))).toHaveLength(1);+ expect(readPendingMergePrs(mockApps.get('app1'))[0].ticks).toBe(4);+ });++ it('recognizes only a clean OPEN PR with completed green checks as merge-ready', () => {+ expect(isPendingMergeReady({+ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]+ })).toBe(true);+ expect(isPendingMergeReady({+ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: []+ })).toBe(false);+ expect(isPendingMergeReady({+ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ status: 'IN_PROGRESS' }]+ })).toBe(false);+ });++ it('merges a green pending PR without spawning a follow-up agent', async () => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ execGhMock.mockResolvedValueOnce(JSON.stringify({+ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]+ }));+ mergePrMock.mockResolvedValue({ success: true });++ const result = await processPendingMergePrs(app);++ expect(result).toMatchObject({ ok: true, checked: 1, merged: 1, escalated: 0 });+ expect(mergePrMock).toHaveBeenCalledWith('/repos/app1', 88);+ expect(spawnReviewLoopFollowUpMock).not.toHaveBeenCalled();+ expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);+ expect(execGhMock).toHaveBeenCalledWith([+ 'pr', 'view', '88', '--repo', 'github.com/o/r',+ '--json', 'state,mergeStateStatus,statusCheckRollup'+ ]);+ });++ it.each([+ ['validation-failed', { state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'FAILURE' }] }],+ ['merge-conflict', { state: 'OPEN', mergeStateStatus: 'DIRTY', statusCheckRollup: [{ conclusion: 'SUCCESS' }] }],+ ])('escalates %s to the existing merge-only follow-up', async (_reason, prView) => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ execGhMock.mockResolvedValueOnce(JSON.stringify(prView));++ const result = await processPendingMergePrs(app);++ expect(result).toMatchObject({ ok: true, escalated: 1, merged: 0 });+ expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledWith(expect.objectContaining({+ prUrl: 'https://github.com/o/r/pull/88',+ prBranch: 'cos/task-88',+ sourceWorkspace: '/repos/app1',+ prCompletion: 'merge-on-green',+ reviewers: []+ }));+ expect(mergePrMock).not.toHaveBeenCalled();+ expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);+ });++ it('stops polling and notifies after the bounded pending-merge budget', async () => {+ const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);+ mockApps.set(app.id, app);+ execGhMock.mockResolvedValueOnce(JSON.stringify({+ state: 'OPEN', mergeStateStatus: 'BLOCKED', statusCheckRollup: [{ status: 'IN_PROGRESS' }]+ }));++ const result = await processPendingMergePrs(app);++ expect(result).toMatchObject({ ok: true, timedOut: 1 });+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({+ type: 'agent_warning',+ priority: 'high',+ link: 'https://github.com/o/r/pull/88'+ }));+ expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);+ });+});+describe('formatPullRequestsForPrompt', () => {it('renders a markdown block with numbers, authors and urls', () => {const out = formatPullRequestsForPrompt(