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 prompting users to merge automated PRs

[._.]/ Adam Eivy34d8066b1611
diff --git a/scripts/migrations/441-retire-merge-followup-alerts.js b/scripts/migrations/441-retire-merge-followup-alerts.js
new file mode 100644
index 0000000000..f8fb4bc8e6
--- /dev/null
+++ b/scripts/migrations/441-retire-merge-followup-alerts.js
@@ -0,0 +1,52 @@
+/** Retire the human reminders formerly emitted for automated PR merge work. */
+import { readdir } from 'node:fs/promises';
+import { join } from 'node:path';
+import { readJSONFile } from '../../server/lib/jsonIo.js';
+import { supersedingTimestamp } from '../../server/lib/tombstones.js';
+import { writeJsonAtomic } from './_lib.js';
+
+// Frozen producer signatures: do not retire unrelated or edited commitments.
+const TITLE = 'PR left open: its merge follow-up was blocked';
+const NEXT_ACTION = 'Check the linked PR. If it is still open, fix the blocker and re-run the task or merge it manually.';
+
+export default {
+ async up({ rootDir }) {
+ const notificationPath = join(rootDir, 'data', 'notifications.json');
+ const history = await readJSONFile(notificationPath, null, { strict: true });
+ let notifications = 0;
+ if (history !== null) {
+ if (!Array.isArray(history.notifications)) throw new Error('Invalid notification history');
+ for (const record of history.notifications) {
+ if (record?.type !== 'agent_warning' || record.title !== TITLE
+ || !record.metadata?.taskId || !record.metadata?.prUrl
+ || (record.historyHidden === true && record.read === true)) continue;
+ record.historyHidden = true;
+ record.read = true;
+ notifications++;
+ }
+ if (notifications) await writeJsonAtomic(notificationPath, history);
+ }
+
+ const threadsDir = join(rootDir, 'data', 'brain', 'threads');
+ const entries = await readdir(threadsDir, { withFileTypes: true }).catch(error => {
+ if (error.code === 'ENOENT') return [];
+ throw error;
+ });
+ let threads = 0;
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ const path = join(threadsDir, entry.name, 'index.json');
+ const record = await readJSONFile(path, null, { strict: true });
+ if (!record || record._deleted || record.source !== 'cos' || record.title !== TITLE
+ || record.nextAction !== NEXT_ACTION || ['done', 'archived'].includes(record.status)
+ || !Array.isArray(record.refs) || record.refs.length !== 1
+ || record.refs[0]?.kind !== 'cos.task' || !record.refs[0]?.id) continue;
+ const timestamp = supersedingTimestamp(record.updatedAt);
+ await writeJsonAtomic(path, {
+ ...record, status: 'archived', closedAt: timestamp, updatedAt: timestamp,
+ });
+ threads++;
+ }
+ return { notifications, threads };
+ },
+};
diff --git a/scripts/migrations/441-retire-merge-followup-alerts.test.js b/scripts/migrations/441-retire-merge-followup-alerts.test.js
new file mode 100644
index 0000000000..18e8a095b1
--- /dev/null
+++ b/scripts/migrations/441-retire-merge-followup-alerts.test.js
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import migration from './441-retire-merge-followup-alerts.js';
+
+const TITLE = 'PR left open: its merge follow-up was blocked';
+const NEXT_ACTION = 'Check the linked PR. If it is still open, fix the blocker and re-run the task or merge it manually.';
+const notification = {
+ id: 'alert', type: 'agent_warning', title: TITLE, read: false,
+ metadata: { taskId: 'task', prUrl: 'https://github.com/example/repo/pull/1' },
+};
+const thread = {
+ title: TITLE, nextAction: NEXT_ACTION, source: 'cos', status: 'open',
+ refs: [{ kind: 'cos.task', id: 'task', label: TITLE }], notes: 'PR and blocker',
+ updatedAt: '2099-01-01T00:00:00.000Z', originInstanceId: 'instance',
+};
+
+let rootDir;
+const notificationPath = () => join(rootDir, 'data', 'notifications.json');
+const threadPath = id => join(rootDir, 'data', 'brain', 'threads', id, 'index.json');
+const readDocument = async path => JSON.parse(await readFile(path, 'utf8'));
+async function writeThread(id, record) {
+ await mkdir(join(rootDir, 'data', 'brain', 'threads', id), { recursive: true });
+ await writeFile(threadPath(id), JSON.stringify(record));
+}
+
+beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-retire-pr-alerts-'));
+ await mkdir(join(rootDir, 'data'));
+});
+afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
+
+describe('retired merge follow-up reminders', () => {
+ it('archives generated commitments and hides alerts without losing their context, idempotently', async () => {
+ await writeFile(notificationPath(), JSON.stringify({ version: 1, notifications: [notification] }));
+ await writeThread('generated', thread);
+ expect(await migration.up({ rootDir })).toEqual({ notifications: 1, threads: 1 });
+ expect((await readDocument(notificationPath())).notifications).toEqual([
+ { ...notification, read: true, historyHidden: true },
+ ]);
+ const archived = await readDocument(threadPath('generated'));
+ expect(archived).toEqual({
+ ...thread, status: 'archived', closedAt: '2099-01-01T00:00:00.001Z', updatedAt: '2099-01-01T00:00:00.001Z',
+ });
+ expect(await migration.up({ rootDir })).toEqual({ notifications: 0, threads: 0 });
+ expect(await readDocument(threadPath('generated'))).toEqual(archived);
+ });
+
+ it('preserves unrelated alerts, edited commitments, completed history, and tombstones', async () => {
+ const other = { ...notification, title: 'A different warning' };
+ await writeFile(notificationPath(), JSON.stringify({ notifications: [other] }));
+ const preserved = {
+ manual: { ...thread, source: 'manual' },
+ edited: { ...thread, nextAction: 'Follow up with the contributor' },
+ linked: { ...thread, refs: [...thread.refs, { kind: 'github.issue', id: 'another' }] },
+ done: { ...thread, status: 'done', closedAt: '2026-10-01T00:00:00.000Z' },
+ deleted: { ...thread, _deleted: true },
+ };
+ for (const [id, record] of Object.entries(preserved)) await writeThread(id, record);
+ expect(await migration.up({ rootDir })).toEqual({ notifications: 0, threads: 0 });
+ expect((await readDocument(notificationPath())).notifications).toEqual([other]);
+ for (const [id, record] of Object.entries(preserved)) expect(await readDocument(threadPath(id))).toEqual(record);
+ });
+
+ it('accepts a fresh install but refuses corrupt stores without overwriting them', async () => {
+ expect(await migration.up({ rootDir })).toEqual({ notifications: 0, threads: 0 });
+ await writeFile(notificationPath(), '{broken');
+ await expect(migration.up({ rootDir })).rejects.toThrow();
+ expect(await readFile(notificationPath(), 'utf8')).toBe('{broken');
+ await rm(notificationPath());
+ await writeThread('broken', thread);
+ await writeFile(threadPath('broken'), '{broken');
+ await expect(migration.up({ rootDir })).rejects.toThrow();
+ expect(await readFile(threadPath('broken'), 'utf8')).toBe('{broken');
+ });
+});
diff --git a/server/services/blockedPrRemediation.js b/server/services/blockedPrRemediation.js
new file mode 100644
index 0000000000..c221a9b236
--- /dev/null
+++ b/server/services/blockedPrRemediation.js
@@ -0,0 +1,37 @@
+/**
+ * Hand blocked contributor-remediation tasks back to their PR author.
+ * Merge follow-ups remain owned by CoS recovery and the development watchdog;
+ * their blocked state must not create human notifications or Brain commitments.
+ */
+
+import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.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('./cosTaskStore.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;
+ });
+}
+
+/** Handle a genuine block transition; timed cooldowns recover automatically. */
+export async function handBackBlockedPrRemediation({ task, previousStatus } = {}) {
+ if (task?.status !== 'blocked' || previousStatus === 'blocked') return false;
+ if (TIMED_COOLDOWN_BLOCKED_CATEGORIES.has(task.metadata?.blockedCategory)) return false;
+ if (!task.metadata?.prRemediationFollowUp) return false;
+ return handBackBlockedRemediation(task);
+}
diff --git a/server/services/blockedPrRemediation.test.js b/server/services/blockedPrRemediation.test.js
new file mode 100644
index 0000000000..27921ac103
--- /dev/null
+++ b/server/services/blockedPrRemediation.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('./notifications.js', () => ({
+ addNotification: vi.fn().mockResolvedValue({}),
+ exists: vi.fn().mockResolvedValue(false),
+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
+ PRIORITY_LEVELS: { HIGH: 'high' },
+}));
+vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));
+
+vi.mock('./cosTaskStore.js', () => ({ addTask: vi.fn(), getTaskById: vi.fn(), updateTask: vi.fn() }));
+vi.mock('./github.js', () => ({ execGh: vi.fn().mockImplementation(async (args) => args[0] === 'api' ? 'maintainer' : 'false') }));
+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 './cosTaskStore.js';
+import { execGh } from './github.js';
+import { handBackBlockedPrRemediation } from './blockedPrRemediation.js';
+import { addNotification } from './notifications.js';
+import { ensureTaskThread } from './brainTaskThreads.js';
+
+const PR_URL = 'https://github.com/example-org/example-repo/pull/9';
+
+const followUp = (metadata = {}) => ({
+ id: 'sys-rl-1',
+ status: 'blocked',
+ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: PR_URL,
+ reviewLoopPRBranch: 'cos/task-1/agent-1',
+ blockedReason: "App 'null' didn't resolve to a repository directory.",
+ blockedCategory: 'app-unresolved',
+ ...metadata,
+ },
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('automated merge follow-ups', () => {
+ it.each(['app-unresolved', 'max-retries', 'worktree-failed', 'worktree-busy'])(
+ 'keeps a %s block out of human notifications and Brain commitments', async blockedCategory => {
+ expect(await handBackBlockedPrRemediation({ task: followUp({ blockedCategory }), previousStatus: 'pending' })).toBe(false);
+ expect(addNotification).not.toHaveBeenCalled();
+ expect(ensureTaskThread).not.toHaveBeenCalled();
+ expect(execGh).not.toHaveBeenCalled();
+ },
+ );
+});
+
+// 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([handBackBlockedPrRemediation(change), handBackBlockedPrRemediation(change)])).toEqual([true, false]);
+ const writes = execGh.mock.calls.filter(([args]) => ['comment', 'edit'].includes(args[1]));
+ expect(writes.map(([args]) => args.slice(0, 3))).toEqual([
+ ['pr', 'comment', PR_URL], ['pr', 'edit', PR_URL],
+ ]);
+ expect(writes[0][0].at(-1)).toContain('remediation task is now blocked');
+ expect(writes[0][0].at(-1)).not.toContain('it did not run');
+ expect(writes[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 handBackBlockedPrRemediation(change)).toBe(false);
+ expect(execGh).toHaveBeenCalledTimes(4);
+ expect(addNotification).not.toHaveBeenCalled();
+ });
+
+ it.each(['worktree-busy', 'pr-head-moved'])('does not hand back a %s block', async (category) => {
+ expect(await handBackBlockedPrRemediation({ task: remediation(category), previousStatus: 'pending' })).toBe(false);
+ expect(execGh).not.toHaveBeenCalled();
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
+ it('ignores empty payloads and events without a block transition', async () => {
+ expect(await handBackBlockedPrRemediation()).toBe(false);
+ expect(await handBackBlockedPrRemediation({})).toBe(false);
+ const task = remediation('max-retries');
+ expect(await handBackBlockedPrRemediation({ task, previousStatus: 'blocked' })).toBe(false);
+ expect(await handBackBlockedPrRemediation({ task: { ...task, status: 'pending' }, previousStatus: 'blocked' })).toBe(false);
+ expect(execGh).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 handBackBlockedPrRemediation({ task, previousStatus: 'in_progress' })).toBe(false);
+ expect(execGh).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/cos.js b/server/services/cos.js
index 8686b7d3fb..6f572b5a4d 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -65,7 +65,7 @@ import { getPendingTaskIds as readPendingTaskIds, getUserTasks, getCosTasks, get
import { ensureInstanceId } from './instanceIdentity.js';
import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';
import { retryTasksResolvedByInvestigation } from './investigationRetry.js';
-import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';
+import { handBackBlockedPrRemediation } from './blockedPrRemediation.js';
import { notifyCriticalHealth, clearCriticalHealthIfRecovered } from './healthCriticalNotifier.js';
const RESUME_DEQUEUE_DELAY_MS = 500;
@@ -1608,15 +1608,11 @@ export async function init() {
}
});
- // A task that was going to MERGE a pull request just got blocked — surface the
- // current blocker and PR link. Registered separately from the dequeue listener
- // above because it must fire on a transition that listener has no branch for
- // (→ blocked), and it is not gated on `isDaemonRunning()`: even while stopped,
- // the notification and Brain commitment preserve the next action. The
- // development watchdog later retires the task if the PR is already terminal.
+ // Contributor remediation retains its forge hand-back when blocked. Ordinary
+ // merge follow-ups stay in automated recovery rather than the human inbox.
cosEvents.on('tasks:changed', (data) => {
- notifyIfPrLeftOrphaned(data)
- .catch(err => console.error(`❌ Orphaned-PR check failed for task ${data?.task?.id}: ${err.message}`));
+ handBackBlockedPrRemediation(data)
+ .catch(err => console.error(`❌ Blocked PR remediation hand-back failed for task ${data?.task?.id}: ${err.message}`));
});
// A critical health transition reaches the bell even when no CoS view is open.
diff --git a/server/services/orphanedPrNotifier.js b/server/services/orphanedPrNotifier.js
deleted file mode 100644
index 148285fb8c..0000000000
--- a/server/services/orphanedPrNotifier.js
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Orphaned-PR notifier.
- *
- * A review-loop / merge follow-up task (`spawnReviewLoopFollowUp`) exists for
- * exactly one reason: to land the pull request named in its `reviewLoopPRUrl`.
- * Blocking one can leave the PR, its branch, and its worktree with no active
- * merge follow-up. The development watchdog rechecks the forge and retires the
- * task if the PR has already become terminal; while it remains open and the
- * follow-up remains blocked, the user needs the blocker and PR link to decide
- * what to do.
- *
- * Some block categories are deliberate user decisions, so the investigation
- * retry and failure reaper leave them alone. A blocked follow-up can therefore
- * outlive a PR that was merged or closed externally; developmentWatchdog owns
- * that forge-state reconciliation.
- *
- * Keyed on the `pending|in_progress|… → blocked` TRANSITION off the shared
- * `tasks:changed` event rather than hung off one blocking call site: ~12 sites
- * across agentErrorAnalysis / agentManagement / agentLifecycle / agentFinalization
- * / cosTaskGenerator / agentWorkspacePrep set `status: 'blocked'`, and a follow-up
- * blocked by `max-retries` or `worktree-failed` strands its PR exactly as hard as
- * one blocked by `app-unresolved`. One listener covers all of them, and stays
- * correct as new blocking paths are added.
- */
-
-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('./cosTaskStore.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;
- });
-}
-
-/**
- * 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 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 or hand-back was raised
- */
-export async function notifyIfPrLeftOrphaned({ task, previousStatus } = {}) {
- if (task?.status !== 'blocked' || previousStatus === 'blocked') 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
- // below would then swallow the card for a REAL block that followed (the
- // `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.
- if (await notificationExists(NOTIFICATION_TYPES.AGENT_WARNING, 'prUrl', prUrl)) return false;
- const why = task.metadata?.blockedReason || `it was blocked (${task.metadata?.blockedCategory || 'no category'}).`;
- await addNotification({
- type: NOTIFICATION_TYPES.AGENT_WARNING,
- title: 'PR left open: its merge follow-up was blocked',
- description: `The merge follow-up task ${task.id} is blocked: ${why} PR: ${prUrl}. `
- + `If the PR is still open, fix the blocker and re-run the task or merge it manually.`,
- priority: PRIORITY_LEVELS.HIGH,
- link: prUrl,
- metadata: { taskId: task.id, prUrl, prBranch: task.metadata?.reviewLoopPRBranch },
- });
- await ensureTaskThread({
- taskId: task.id,
- title: 'PR left open: its merge follow-up was blocked',
- nextAction: 'Check the linked PR. If it is still open, fix the blocker and re-run the task or merge it manually.',
- notes: `${prUrl}\n${why}`,
- priority: 'high',
- });
- return true;
-}
diff --git a/server/services/orphanedPrNotifier.test.js b/server/services/orphanedPrNotifier.test.js
deleted file mode 100644
index 2da44a7e58..0000000000
--- a/server/services/orphanedPrNotifier.test.js
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * Tests for orphanedPrNotifier — the `tasks:changed → blocked` listener that
- * surfaces a pull request whose merge follow-up got parked.
- *
- * The contract these pin: it fires on the TRANSITION into blocked (not the
- * level), only for a task carrying `reviewLoopPRUrl`, and only once per PR.
- */
-
-import { describe, it, expect, beforeEach, vi } from 'vitest';
-
-vi.mock('./notifications.js', () => ({
- addNotification: vi.fn().mockResolvedValue({}),
- exists: vi.fn().mockResolvedValue(false),
- NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
- PRIORITY_LEVELS: { HIGH: 'high' },
-}));
-vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));
-
-vi.mock('./cosTaskStore.js', () => ({ addTask: vi.fn(), getTaskById: vi.fn(), updateTask: vi.fn() }));
-vi.mock('./github.js', () => ({ execGh: vi.fn().mockImplementation(async (args) => args[0] === 'api' ? 'maintainer' : 'false') }));
-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 './cosTaskStore.js';
-import { execGh } from './github.js';
-import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';
-import { addNotification, exists } from './notifications.js';
-import { ensureTaskThread } from './brainTaskThreads.js';
-
-const PR_URL = 'https://github.com/example-org/example-repo/pull/9';
-
-const followUp = (metadata = {}) => ({
- id: 'sys-rl-1',
- status: 'blocked',
- metadata: {
- reviewLoopFollowUp: true,
- reviewLoopPRUrl: PR_URL,
- reviewLoopPRBranch: 'cos/task-1/agent-1',
- blockedReason: "App 'null' didn't resolve to a repository directory.",
- blockedCategory: 'app-unresolved',
- ...metadata,
- },
-});
-
-beforeEach(() => {
- vi.clearAllMocks();
- exists.mockResolvedValue(false);
-});
-
-describe('notifyIfPrLeftOrphaned', () => {
- it('notifies with the PR url when a merge follow-up transitions into blocked', async () => {
- const raised = await notifyIfPrLeftOrphaned({ task: followUp(), previousStatus: 'pending' });
- expect(raised).toBe(true);
- expect(addNotification).toHaveBeenCalledWith(expect.objectContaining({
- type: 'agent_warning',
- priority: 'high',
- link: PR_URL,
- description: expect.stringContaining(PR_URL),
- metadata: expect.objectContaining({
- taskId: 'sys-rl-1', prUrl: PR_URL, prBranch: 'cos/task-1/agent-1',
- }),
- }));
- // The block's own explanation is what tells the user how to unstick it.
- expect(addNotification.mock.calls[0][0].description).toContain("didn't resolve");
- expect(ensureTaskThread).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'sys-rl-1', priority: 'high' }));
- });
-
- // ~12 sites set `status: 'blocked'`; a follow-up blocked by max-retries or a
- // failed worktree strands its PR exactly as hard as an unresolved app does.
- it('fires for any blocking category, not just app-unresolved', async () => {
- const task = followUp({ blockedCategory: 'max-retries', blockedReason: 'Task failed 3 times.' });
- expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'in_progress' })).toBe(true);
- });
-
- it('falls back to the category when the block carries no reason', async () => {
- const task = followUp({ blockedReason: undefined, blockedCategory: 'worktree-failed' });
- await notifyIfPrLeftOrphaned({ task, previousStatus: 'pending' });
- expect(addNotification.mock.calls[0][0].description).toContain('worktree-failed');
- });
-
- // ...but a TIMED pause is not an orphaning: the cooldown sweeper revives it.
- // The one-per-PR guard makes this load-bearing — a card raised for the pause
- // would swallow the card for the real block the task lands on if it gives up.
- it('stays quiet for a self-reviving cooldown block', async () => {
- const task = followUp({
- blockedCategory: 'worktree-busy',
- blockedReason: 'Branch cos/task-1/agent-1 is still checked out in another worktree',
- cooldownUntil: new Date(Date.now() + 60_000).toISOString(),
- });
- expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'pending' })).toBe(false);
- expect(addNotification).not.toHaveBeenCalled();
- // The cooldown check must come before the dedupe probe, or the pause would
- // still consume the one card this PR gets.
- expect(exists).not.toHaveBeenCalled();
- });
-
- it('ignores an ordinary blocked task that is not landing a PR', async () => {
- const task = { id: 't-plain', status: 'blocked', metadata: { blockedCategory: 'app-unresolved' } };
- expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'pending' })).toBe(false);
- expect(addNotification).not.toHaveBeenCalled();
- });
-
- it('ignores a task that is not blocked', async () => {
- const task = { ...followUp(), status: 'pending' };
- expect(await notifyIfPrLeftOrphaned({ task, previousStatus: 'blocked' })).toBe(false);
- expect(addNotification).not.toHaveBeenCalled();
- });
-
- // `updateTask` re-emits `tasks:changed` on every later write to an already
- // blocked task (an edit to its description is enough) — keying on the level
- // rather than the edge would re-notify on each one.
- it('ignores a re-emit for a task that was already blocked', async () => {
- expect(await notifyIfPrLeftOrphaned({ task: followUp(), previousStatus: 'blocked' })).toBe(false);
- expect(addNotification).not.toHaveBeenCalled();
- });
-
- it('does not stack a second card for a PR already notified about', async () => {
- exists.mockResolvedValue(true);
- expect(await notifyIfPrLeftOrphaned({ task: followUp(), previousStatus: 'pending' })).toBe(false);
- expect(exists).toHaveBeenCalledWith('agent_warning', 'prUrl', PR_URL);
- expect(addNotification).not.toHaveBeenCalled();
- });
-
- it('tolerates an empty payload', async () => {
- expect(await notifyIfPrLeftOrphaned()).toBe(false);
- 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]);
- const writes = execGh.mock.calls.filter(([args]) => ['comment', 'edit'].includes(args[1]));
- expect(writes.map(([args]) => args.slice(0, 3))).toEqual([
- ['pr', 'comment', PR_URL], ['pr', 'edit', PR_URL],
- ]);
- expect(writes[0][0].at(-1)).toContain('remediation task is now blocked');
- expect(writes[0][0].at(-1)).not.toContain('it did not run');
- expect(writes[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(4);
- 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();
- });
-});