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
fix: hand blocked PR remediation back to its author (#12523)
[._.]/ Adam Eivyde8b535c03dc
diff --git a/server/services/orphanedPrNotifier.js b/server/services/orphanedPrNotifier.jsindex 381cc7fdd4..9d9a61cd70 100644--- a/server/services/orphanedPrNotifier.js+++ b/server/services/orphanedPrNotifier.js@@ -26,23 +26,43 @@import { addNotification, exists as notificationExists, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js';import { ensureTaskThread } from './brainTaskThreads.js';+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';++const queueHandback = createKeyCachedQueue();++async function handBackBlockedRemediation(task) {+ if (task.metadata.blockedCategory === 'pr-head-moved') return false;+ return queueHandback(task.id, async () => {+ const [{ getTaskById, updateTask }, { getAppById }, { handBackPrRemediation }] = await Promise.all([+ import('./cos.js'), import('./apps.js'), import('./prRemediationFollowUp.js'),+ ]);+ // Re-read inside the queue: overlapping block events may hold older snapshots.+ const current = await getTaskById(task.id);+ if (current?.status !== 'blocked' || current.metadata?.prRemediationHandedBackAt+ || current.metadata?.blockedCategory === 'pr-head-moved'+ || TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(current.metadata?.blockedCategory)) return false;+ const app = await getAppById(current.app || current.metadata?.app);+ if (!app?.repoPath) return false;+ if (!await handBackPrRemediation({ task: current, workspacePath: app.repoPath })) return false;+ await updateTask(task.id, { metadata: { prRemediationHandedBackAt: new Date().toISOString() } }, 'internal');+ return true;+ });+}/**- * Raise a notification when a task that was going to merge a PR gets blocked.+ * Preserve PR ownership when a merge or remediation follow-up gets blocked.** Self-guarding: returns `false` without side effects unless the task is a- * genuine block transition carrying a PR url. A notification-store failure+ * genuine block transition carrying PR follow-up metadata. A notification-store failure* rejects rather than being swallowed here, so the caller decides — the* `tasks:changed` listener in cos.js logs it, because a throw from an event* listener has no request lifecycle to bubble to.** @param {{ task?: object, previousStatus?: string }} change - a `tasks:changed` payload- * @returns {Promise<boolean>} whether a notification was raised+ * @returns {Promise<boolean>} whether a notification or hand-back was raised*/export async function notifyIfPrLeftOrphaned({ task, previousStatus } = {}) {if (task?.status !== 'blocked' || previousStatus === 'blocked') return false;- const prUrl = task.metadata?.reviewLoopPRUrl;- if (!prUrl) return false;// A TIMED pause is not an orphaning: the cooldown sweeper flips the task back// to `pending` on its own, so the PR still has something coming for it. Staying// quiet matters twice over — the card would be wrong, and the one-per-PR guard@@ -50,6 +70,9 @@ export async function notifyIfPrLeftOrphaned({ task, previousStatus } = {}) {// `worktree-busy` wait gives up after a bounded number of attempts and re-blocks// as `worktree-failed`, which is the block a human actually needs to see).if (TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(task.metadata?.blockedCategory)) return false;+ if (task.metadata?.prRemediationFollowUp) return handBackBlockedRemediation(task);+ const prUrl = task.metadata?.reviewLoopPRUrl;+ if (!prUrl) return false;// One notification per PR, not per block. Fixing the cause and re-running is// the intended recovery, and a re-run that blocks again would otherwise stack// another HIGH card for a PR the user is already looking at.diff --git a/server/services/orphanedPrNotifier.test.js b/server/services/orphanedPrNotifier.test.jsindex f0d9fa1dc0..74c66479d1 100644--- a/server/services/orphanedPrNotifier.test.js+++ b/server/services/orphanedPrNotifier.test.js@@ -16,6 +16,14 @@ vi.mock('./notifications.js', () => ({}));vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));+vi.mock('./cos.js', () => ({ addTask: vi.fn(), getTaskById: vi.fn(), updateTask: vi.fn() }));+vi.mock('./github.js', () => ({ execGh: vi.fn().mockResolvedValue('') }));+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));+vi.mock('./forgeAuth.js', () => ({ resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: {} }) }));+vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue({ repoPath: '/repos/example' }) }));++import { getTaskById, updateTask } from './cos.js';+import { execGh } from './github.js';import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';import { addNotification, exists } from './notifications.js';import { ensureTaskThread } from './brainTaskThreads.js';@@ -119,3 +127,52 @@ describe('notifyIfPrLeftOrphaned', () => {expect(await notifyIfPrLeftOrphaned({})).toBe(false);});});++// Exercises the same entrypoint the tasks:changed listener invokes, through the+// real hand-back service to the forge adapter.+describe('blocked PR remediation hand-back', () => {+ const remediation = (blockedCategory) => ({+ id: 'sys-remediation-1', app: 'app-1', status: 'blocked',+ metadata: {+ prRemediationFollowUp: true, blockedCategory,+ prRemediationNumber: 9, prRemediationRepoFullName: 'example-org/example-repo',+ prRemediationUrl: PR_URL, prRemediationAuthorLogin: 'contributor',+ prRemediationHeadSha: 'a'.repeat(40),+ },+ });++ it.each(['worktree-failed', 'max-retries'])('hands back %s once across concurrent events and later re-blocks', async (category) => {+ const task = remediation(category);+ getTaskById.mockImplementation(async () => structuredClone(task));+ updateTask.mockImplementation(async (_id, { metadata }) => {+ Object.assign(task.metadata, metadata);+ return structuredClone(task);+ });+ const change = { task: structuredClone(task), previousStatus: 'pending' };+ expect(await Promise.all([notifyIfPrLeftOrphaned(change), notifyIfPrLeftOrphaned(change)])).toEqual([true, false]);+ expect(execGh.mock.calls.map(([args]) => args.slice(0, 3))).toEqual([+ ['pr', 'comment', PR_URL], ['pr', 'edit', PR_URL],+ ]);+ expect(execGh.mock.calls[0][0].at(-1)).toContain('remediation task is now blocked');+ expect(execGh.mock.calls[0][0].at(-1)).not.toContain('it did not run');+ expect(execGh.mock.calls[1][0]).toContain('contributor');+ expect(task.metadata.prRemediationHandedBackAt).toEqual(expect.any(String));+ expect(updateTask).toHaveBeenCalledWith(task.id, { metadata: { prRemediationHandedBackAt: expect.any(String) } }, 'internal');+ expect(await notifyIfPrLeftOrphaned(change)).toBe(false);+ expect(execGh).toHaveBeenCalledTimes(2);+ expect(addNotification).not.toHaveBeenCalled();+ });++ it.each(['worktree-busy', 'pr-head-moved'])('does not hand back a %s block', async (category) => {+ expect(await notifyIfPrLeftOrphaned({ task: remediation(category), previousStatus: 'pending' })).toBe(false);+ expect(execGh).not.toHaveBeenCalled();+ expect(updateTask).not.toHaveBeenCalled();+ });++ it('does not hand back a task revived before its event was processed', async () => {+ const task = remediation('max-retries');+ getTaskById.mockResolvedValue({ ...task, status: 'pending' });+ expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'in_progress' })).toBe(false);+ expect(execGh).not.toHaveBeenCalled();+ });+});diff --git a/server/services/prRemediationFollowUp.js b/server/services/prRemediationFollowUp.jsindex 093e210ab9..3802a0119f 100644--- a/server/services/prRemediationFollowUp.js+++ b/server/services/prRemediationFollowUp.js@@ -211,9 +211,8 @@ export async function spawnPrRemediationFollowUp({ app, repoFullName, pullReques}/**- * Give a PR back to its opener when workspace prep refuses the pinned attach —- * the head moved after review, or the task carries no reviewed head. The text- * is fixed: it names the reviewed commit and nothing a contributor wrote.+ * Give a PR back to its opener when remediation is blocked. The text is fixed:+ * it names the reviewed commit and nothing a contributor wrote.** @returns {Promise<boolean>} whether the comment was posted*/@@ -230,7 +229,8 @@ export async function handBackPrRemediation({ task, workspacePath } = {}) {const [{ execGh }, { resolveForgeForRepo }, { getAppById }] = await Promise.all([import('./github.js'), import('./forgeAuth.js'), import('./apps.js'),]);- const app = meta.app ? await getAppById(meta.app).catch(() => null) : null;+ const appId = task.app || meta.app;+ const app = appId ? await getAppById(appId).catch(() => null) : null;const forge = await resolveForgeForRepo(workspacePath, { forgeAccount: app?.forgeAccount || null });if (forge?.cli !== 'gh') return false;const options = { cwd: workspacePath, env: forge.env };@@ -238,13 +238,19 @@ export async function handBackPrRemediation({ task, workspacePath } = {}) {? `commit ${meta.prRemediationHeadSha.slice(0, 12)}`: 'an earlier revision';const login = typeof meta.prRemediationAuthorLogin === 'string' ? meta.prRemediationAuthorLogin.trim() : '';+ const terminalBlock = meta.blockedCategory && meta.blockedCategory !== 'pr-head-moved';const body = [- `PortOS reviewed this pull request at ${reviewed} and queued an agent to finish it, but could not confirm the head branch was still at that revision when the agent started.`,- 'The agent only works on the revision PortOS reviewed, so it did not run.',+ ...(terminalBlock ? [+ `PortOS reviewed this pull request at ${reviewed} and queued an agent to finish it, but the remediation task is now blocked.`,+ 'PortOS is no longer working on this pull request.',+ ] : [+ `PortOS reviewed this pull request at ${reviewed} and queued an agent to finish it, but could not confirm the head branch was still at that revision when the agent started.`,+ 'The agent only works on the revision PortOS reviewed, so it did not run.',+ ]),`${login ? `@${login}, this` : 'This'} pull request is back with its author; the next push gets a fresh review.`,].join(' ');await execGh(['pr', 'comment', ...prRef, '--body', body], undefined, options);if (login) await execGh(['pr', 'edit', ...prRef, '--add-assignee', login], undefined, options);- emitLog('info', `↩️ Handed PR #${number} in ${repoFullName} back after its remediation attach was refused`, { taskId: task.id, prNumber: number });+ emitLog('info', `↩️ Handed PR #${number} in ${repoFullName} back after its remediation was blocked`, { taskId: task.id, prNumber: number });return true;}