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
drain merge-on-green PRs on the CoS tick instead of the disabled pr-watcher task
[._.]/ Adam Eivya7fb395921e5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 34df8ac2b2..cdc1bbdfd3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,3 +2,6 @@## Documentation- **Updated documentation index and feature references.** Added missing feature deep dive links for Quota-burn automation (`QUOTA-BURN.md`), Three.js procedural 3D models (`THREEJS_MODELS.md`), Stacker News stewardship (`stacker-news.md`), and the PortDeck native companion app API contract (`COMPANION_APP_API.md`) across `README.md` and `docs/README.md`. Improved inline JSDoc comments for client and server utility modules.++## Fixed+- **Pull requests opened by a CoS agent under a "merge when CI is green" policy now actually get merged.** The check that watches those PRs only ran when an app's optional "PR Watcher" scheduled task fired — and that task ships disabled, since its default prompt is a review-and-comment agent most setups don't want. So PortOS was queueing green PRs into a list nothing ever read: they sat open indefinitely, and because the retry counter never advanced, the safety net that gives up and notifies you after a few hours never fired either. The watch now runs on the normal CoS cadence, independent of that task.diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 0f2af45c11..00b873c29c 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1116,6 +1116,20 @@ export async function evaluateTasks(options) {return s;});+ // Drain merge-only PRs on the evaluation cadence rather than the `pr-watcher`+ // task's, which most installs leave disabled — that coupling stranded every+ // green PortOS-opened PR at `ticks: 0` forever. Runs BEFORE the agent-slot+ // gate below because a deterministic merge claims no lane, so a full agent+ // roster must not also wedge the merge queue. Gated on `!paused` to match the+ // autonomous tiers: merging is an autonomous action a global pause suppresses.+ if (!paused) {+ const prWatcher = await import('./prWatcher.js');+ const sweep = await prWatcher.sweepPendingMergePrs();+ if (sweep.merged || sweep.escalated || sweep.timedOut) {+ emitLog('info', `🤖 Pending merges: ${sweep.merged} merged, ${sweep.escalated} escalated, ${sweep.timedOut} timed out`);+ }+ }+// Resolve this instance's federation id once per cycle so the priority tiers// can skip tasks a peer holds a live lease on (#1650). Warm path is the cheap// cached read; only the cold boot creates the identity.@@ -2312,15 +2326,9 @@ 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 });- }+ // Merge-only PRs are NOT drained here — `evaluateTasks` sweeps them every+ // cycle instead, so a disabled `pr-watcher` task can't strand them (see+ // `sweepPendingMergePrs`). This function owns only PR *discovery*.// 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/prWatcher.js b/server/services/prWatcher.jsindex 4bb41ad25e..515e579914 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -25,7 +25,7 @@*/import { execGh, ensureForgeReachable } from './github.js';-import { getAppById, updateApp } from './apps.js';+import { getAppById, updateApp, getActiveApps } from './apps.js';import * as git from './git.js';import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';import { classifyPrFailure } from './layeredIntelligenceRejections.js';@@ -393,6 +393,49 @@ export async function processPendingMergePrs(app) {return result;}+/**+ * Drain every app's pending merge-only PRs, independent of whether that app has+ * the `pr-watcher` scheduled task enabled.+ *+ * `queuePendingMerge` is written from the agent-completion path whenever a+ * merge-on-green PR is opened — a path with no relationship to the watcher's+ * task-type config. Draining it only from `resolvePrWatcherBlock` (which runs+ * exclusively when a `pr-watcher` task fires) meant that on the common setup —+ * `pr-watcher` left disabled, since its default prompt is a review-and-comment+ * agent most operators don't want — PortOS queued PRs into a list nothing ever+ * read. Green PRs then sat open forever at `ticks: 0`, and even the bounded+ * `MAX_PENDING_MERGE_TICKS` escape hatch never fired.+ *+ * Called from the CoS evaluation tick, which is the same cadence-bearing loop+ * that spawned the agent that opened the PR. Never throws: each app is swept+ * independently and a failure is returned in `failures`, so one unreachable+ * forge can't stall the tick.+ *+ * @returns {Promise<{checked: number, merged: number, escalated: number,+ * timedOut: number, failures: number}>}+ */+export async function sweepPendingMergePrs() {+ const totals = { checked: 0, merged: 0, escalated: 0, timedOut: 0, failures: 0 };+ const apps = await getActiveApps().catch(() => []);+ // Only apps that actually own a queued PR — the common case is an empty list,+ // and `processPendingMergePrs` short-circuits on it anyway, but filtering here+ // keeps the tick from resolving git origins for every managed app.+ const withPending = apps.filter((app) => readPendingMergePrs(app).length > 0);+ for (const app of withPending) {+ const result = await processPendingMergePrs(app).catch((err) => ({ ok: false, reason: err.message }));+ if (!result?.ok) {+ totals.failures += 1;+ console.log(`⚠️ Pending-merge sweep failed for ${app.name}: ${result?.reason || 'unknown error'}`);+ continue;+ }+ totals.checked += result.checked || 0;+ totals.merged += result.merged || 0;+ totals.escalated += result.escalated || 0;+ totals.timedOut += result.timedOut || 0;+ }+ return totals;+}+/*** 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 b01382ad14..2bbadb172b 100644--- a/server/services/prWatcher.test.js+++ b/server/services/prWatcher.test.js@@ -28,6 +28,7 @@ vi.mock('./agentWorktreeCleanup.js', () => ({const mockApps = new Map();vi.mock('./apps.js', () => ({+ getActiveApps: vi.fn(async () => [...mockApps.values()]),getAppById: vi.fn(async (id) => mockApps.get(id) || null),updateApp: vi.fn(async (id, patch) => {const cur = mockApps.get(id) || { id };@@ -51,6 +52,7 @@ import {queuePendingMerge,isPendingMergeReady,processPendingMergePrs,+ sweepPendingMergePrs,MAX_PENDING_MERGE_TICKS,checkPullRequests,getSelfLogin,@@ -258,6 +260,62 @@ describe('merge-only PR watcher', () => {});});+describe('sweepPendingMergePrs', () => {+ beforeEach(() => {+ mockApps.clear();+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });+ });++ // The regression this whole sweep exists for: pending merges used to drain+ // only when the app's `pr-watcher` scheduled task fired, so an install that+ // left that task disabled queued green PRs into a list nothing ever read.+ // The sweep must not consult the task schedule at all.+ it('drains a pending merge for an app with no pr-watcher config', async () => {+ mockApps.set('app1', { ...pendingApp(), name: 'App One', prWatcherState: undefined });+ execGhMock.mockResolvedValueOnce(JSON.stringify({+ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]+ }));+ mergePrMock.mockResolvedValue({ success: true });++ const totals = await sweepPendingMergePrs();++ expect(totals).toMatchObject({ checked: 1, merged: 1, failures: 0 });+ expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);+ });++ it('skips apps with no queued PRs without resolving their git origin', async () => {+ mockApps.set('app1', { id: 'app1', name: 'App One', repoPath: '/repos/app1' });+ mockApps.set('app2', { id: 'app2', name: 'App Two', repoPath: '/repos/app2', pendingMergePrs: [] });++ const totals = await sweepPendingMergePrs();++ expect(totals).toMatchObject({ checked: 0, merged: 0, failures: 0 });+ expect(getOriginInfoMock).not.toHaveBeenCalled();+ expect(execGhMock).not.toHaveBeenCalled();+ });++ it('counts a failing app and still sweeps the rest', async () => {+ mockApps.set('app1', { ...pendingApp(), name: 'App One' });+ mockApps.set('app2', {+ id: 'app2', name: 'App Two', repoPath: '/repos/app2',+ pendingMergePrs: [pendingMerge({ prNumber: 99, prUrl: 'https://github.com/o/r/pull/99' })]+ });+ // app1 fails the forge check; app2 proceeds and merges.+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable' });+ execGhMock.mockResolvedValueOnce(JSON.stringify({+ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]+ }));+ mergePrMock.mockResolvedValue({ success: true });++ const totals = await sweepPendingMergePrs();++ expect(totals).toMatchObject({ failures: 1, checked: 1, merged: 1 });+ // The unreachable app keeps its entry for the next tick.+ expect(readPendingMergePrs(mockApps.get('app1'))).toHaveLength(1);+ expect(readPendingMergePrs(mockApps.get('app2'))).toEqual([]);+ });+});+describe('formatPullRequestsForPrompt', () => {it('renders a markdown block with numbers, authors and urls', () => {const out = formatPullRequestsForPrompt(