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
address review (claude): harden watcher queue and forge failures
[._.]/ Adam Eivy580bc524a768
diff --git a/server/services/github.js b/server/services/github.jsindex 2f0438a6ea..cdb3aefc76 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -82,7 +82,7 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nul});if (input !== null && input !== undefined) {child.stdin.on('error', (err) => {- if (timedOut) return;+ if (timedOut || err.code === 'EPIPE') return;clearTimeout(timer);reject(err);});diff --git a/server/services/github.test.js b/server/services/github.test.jsindex f241a09add..45397b36d3 100644--- a/server/services/github.test.js+++ b/server/services/github.test.js@@ -60,6 +60,20 @@ describe('execGh', () => {await expect(promise).resolves.toBe('');});+ it('preserves gh stderr when an input write ends with EPIPE', async () => {+ const child = makeChild();+ spawn.mockReturnValue(child);+ const promise = execGh(['api', '--input', '-', 'repos/o/r/pulls/1/reviews'], 5000, {+ input: '{"event":"APPROVE"}'+ });+ child.stderr.emit('data', Buffer.from('HTTP 422: validation failed'));+ const error = new Error('write EPIPE');+ error.code = 'EPIPE';+ child.stdin.emit('error', error);+ child.emit('close', 1);+ await expect(promise).rejects.toThrow('HTTP 422: validation failed');+ });+it('rejects with stderr on a non-zero close', async () => {const child = makeChild();spawn.mockReturnValue(child);diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.jsindex 1ea9153217..54e75bc953 100644--- a/server/services/issueWatcher.js+++ b/server/services/issueWatcher.js@@ -23,10 +23,14 @@ const GH_TIMEOUT_MS = 60_000;const LIST_LIMIT = 100;const MAX_PULL_REQUESTS_PER_RUN = 3;const MAX_DIFF_CHARS = 120_000;+const MAX_TOTAL_DIFF_CHARS = 180_000;const MAX_ISSUE_COMMENTS_PER_RUN = 25;+const MAX_ISSUE_CONTEXT_CHARS = 40_000;+const MAX_PENDING_ISSUE_COMMENTS = 250;export const MAX_PENDING_APPROVAL_TICKS = 12;+export const MAX_PENDING_ISSUE_COMMENT_TICKS = 12;const GREEN_CHECKS = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED']);-const FAILED_CHECKS = new Set(['ACTION_REQUIRED', 'CANCELLED', 'FAILURE', 'STALE', 'TIMED_OUT']);+const FAILED_CHECKS = new Set(['ACTION_REQUIRED', 'CANCELLED', 'ERROR', 'FAILURE', 'STALE', 'STARTUP_FAILURE', 'TIMED_OUT']);let stateWriteTail = Promise.resolve();@@ -206,7 +210,6 @@ async function gatherIssueComments(ctx, { since, ownerLogin }) {if (rows === null) return { ok: false, comments: [], assignments: 0 };const comments = [];let assignments = 0;- let assignmentFailed = false;for (const issue of rows.filter((row) => !row.pull_request)) {const issueComments = await listPaginated(ctx, `repos/${ctx.repoFullName}/issues/${issue.number}/comments`, [['since', since], ['per_page', LIST_LIMIT],@@ -230,7 +233,6 @@ async function gatherIssueComments(ctx, { since, ownerLogin }) {assignments += 1;continue;}- assignmentFailed = true;}}comments.push({@@ -244,7 +246,7 @@ async function gatherIssueComments(ctx, { since, ownerLogin }) {});}}- return { ok: !assignmentFailed, comments, assignments };+ return { ok: true, comments, assignments };}async function readPullRequest(ctx, number) {@@ -279,6 +281,7 @@ async function gatherPullRequests(ctx, ownerLogin) {return null;}const candidates = [];+ let diffChars = 0;const ordered = listed.filter((pr) => !pr.isDraft && pr.author?.login && pr.author?.is_bot !== true && !sameLogin(pr.author.login, ownerLogin)).sort((a, b) => String(a.updatedAt || '').localeCompare(String(b.updatedAt || '')));@@ -291,7 +294,11 @@ async function gatherPullRequests(ctx, ownerLogin) {if (!pr || pr.state !== 'OPEN' || pr.headRefOid !== summary.headRefOid) continue;const rawDiff = await runGh(['pr', 'diff', String(pr.number), '--repo', ctx.repoSpec], ctx).catch(() => null);if (rawDiff === null) return null;- const truncated = rawDiff.length > MAX_DIFF_CHARS;+ const remainingDiffChars = MAX_TOTAL_DIFF_CHARS - diffChars;+ if (remainingDiffChars <= 0) break;+ const diffLimit = Math.min(MAX_DIFF_CHARS, remainingDiffChars);+ const truncated = rawDiff.length > diffLimit;+ diffChars += Math.min(rawDiff.length, diffLimit);candidates.push({number: pr.number,title: text(pr.title, 500),@@ -309,13 +316,29 @@ async function gatherPullRequests(ctx, ownerLogin) {mergeable: pr.mergeable,mergeStateStatus: pr.mergeStateStatus,checks: classifyChecks(pr.statusCheckRollup),- diff: truncated ? `${rawDiff.slice(0, MAX_DIFF_CHARS)}\n\n[DIFF TRUNCATED — verdict must be defer]` : rawDiff,+ diff: truncated ? `${rawDiff.slice(0, diffLimit)}\n\n[DIFF TRUNCATED — verdict must be defer]` : rawDiff,diffTruncated: truncated,});}return candidates;}+function takeIssueCommentsWithinBudget(comments) {+ const selected = [];+ let used = 0;+ for (const item of comments) {+ if (selected.length >= MAX_ISSUE_COMMENTS_PER_RUN) break;+ const size = String(item?.issueTitle || '').length+ + String(item?.issueBody || '').length+ + String(item?.commentBody || '').length+ + 200;+ if (selected.length > 0 && used + size > MAX_ISSUE_CONTEXT_CHARS) break;+ selected.push(item);+ used += size;+ }+ return selected;+}+function renderPrompt({ app, ctx, ownerLogin, issueComments, pullRequests }) {const issues = issueComments.length === 0 ? '_No issue comments need judgment._' : issueComments.map((item) => [`### Issue #${item.issueNumber}: ${item.issueTitle}`,@@ -379,7 +402,7 @@ Include one decision for every supplied issue comment and PR, and no others.`;async function keepPendingApproval(app, approval, remaining, reason, patch = {}) {const next = { ...approval, ...patch, ticks: (approval.ticks || 0) + 1 };if (next.ticks >= MAX_PENDING_APPROVAL_TICKS) {- await notifyPendingApprovalTimeout(app, approval, reason);+ await notifyPendingApproval(app, approval, `PortOS stopped polling after ${MAX_PENDING_APPROVAL_TICKS} checks because ${reason}.`);} else {remaining.push(next);}@@ -422,6 +445,11 @@ async function processPendingApprovals(app, ctx) {}const checkRollup = Array.isArray(pr.statusCheckRollup) ? pr.statusCheckRollup : [];const checks = classifyChecks(checkRollup);+ if (checks === 'failed') {+ await notifyPendingApproval(app, approval, 'CI reported a failing status, so PortOS stopped automatic merge polling.');+ changed = true;+ continue;+ }// An empty rollup is ambiguous immediately after review: CI may simply not// have attached yet. A low-risk PR may skip CI only after two consecutive// scheduled observations see no checks. Active checks are never waived.@@ -445,12 +473,12 @@ async function processPendingApprovals(app, ctx) {return remaining;}-async function notifyPendingApprovalTimeout(app, approval, reason) {+async function notifyPendingApproval(app, approval, description) {return addNotification({type: NOTIFICATION_TYPES.AGENT_WARNING,priority: PRIORITY_LEVELS.HIGH,title: `Issue Watcher PR #${approval.number} needs attention`,- description: `PortOS stopped polling this reviewed PR after ${MAX_PENDING_APPROVAL_TICKS} checks because ${reason}.`,+ description,link: approval.url,metadata: { appId: app.id, issueWatcherPrNumber: approval.number },}).catch((err) => {@@ -493,17 +521,23 @@ export async function buildTaskInput({ app } = {}) {const pendingById = new Map();for (const item of [...(Array.isArray(state.pendingIssueComments) ? state.pendingIssueComments : []), ...issueResult.comments]) {if (item && Number.isInteger(item.issueNumber) && Number.isInteger(item.commentId)) {- pendingById.set(`${item.issueNumber}:${item.commentId}`, item);+ const key = `${item.issueNumber}:${item.commentId}`;+ const existing = pendingById.get(key);+ pendingById.set(key, { ...item, ticks: existing?.ticks || item.ticks || 0 });}}- const pendingIssueComments = [...pendingById.values()];+ const allPendingIssueComments = [...pendingById.values()];+ const pendingIssueComments = allPendingIssueComments.slice(-MAX_PENDING_ISSUE_COMMENTS);+ if (allPendingIssueComments.length > pendingIssueComments.length) {+ console.warn(`⚠️ issue-watcher: dropped ${allPendingIssueComments.length - pendingIssueComments.length} oldest pending issue comment(s) for ${app.name} to preserve queue progress.`);+ }await persistState(app.id, {cursor: startedAt,pendingIssueComments,lastCheckedAt: startedAt,lastError: null,});- const issueComments = pendingIssueComments.slice(0, MAX_ISSUE_COMMENTS_PER_RUN);+ const issueComments = takeIssueCommentsWithinBudget(pendingIssueComments);if (issueComments.length === 0 && pullRequests.length === 0) {return { skip: { reason: firstRun ? 'baselined' : 'no-cognitive-activity' } };@@ -525,27 +559,39 @@ export async function buildTaskInput({ app } = {}) {async function postIssueReply(ctx, decision) {return runGh(['issue', 'comment', String(decision.issueNumber), '--repo', ctx.repoSpec, '--body', text(decision.body, 5_000),- ], ctx).then(() => true).catch(() => false);+ ], ctx).then(() => true).catch((err) => {+ console.error(`❌ issue-watcher: issue reply failed for #${decision.issueNumber}: ${err.message}`);+ return false;+ });}async function submitReview(ctx, number, { body, event, comments = [] }) {const input = JSON.stringify({ body: text(body, 4_000), event, comments });return runGh([...apiArgs(ctx, `repos/${ctx.repoFullName}/pulls/${number}/reviews`, { method: 'POST' }), '--input', '-'], ctx, input).then(() => true)- .catch(() => false);+ .catch((err) => {+ console.error(`❌ issue-watcher: review submit failed for PR #${number} (${event}): ${err.message}`);+ return false;+ });}async function postReviewFallback(ctx, number, body) {return runGh(['pr', 'comment', String(number), '--repo', ctx.repoSpec, '--body', text(body, 5_000)], ctx).then(() => true)- .catch(() => false);+ .catch((err) => {+ console.error(`❌ issue-watcher: review comment failed for PR #${number}: ${err.message}`);+ return false;+ });}async function updatePullRequestBranch(ctx, number, headSha) {const input = JSON.stringify({ expected_head_sha: headSha, update_method: 'rebase' });return runGh([...apiArgs(ctx, `repos/${ctx.repoFullName}/pulls/${number}/update-branch`, { method: 'PUT' }), '--input', '-'], ctx, input).then(() => true)- .catch(() => false);+ .catch((err) => {+ console.error(`❌ issue-watcher: update-branch failed for PR #${number}: ${err.message}`);+ return false;+ });}function mergeApproval(existing, approval) {@@ -639,6 +685,14 @@ export async function processTaskOutput({ appId, success, payload, task } = {})continue;}}+ if (checks === 'failed') {+ await notifyPendingApproval(app, {+ number: pr.number,+ url: pr.url,+ }, 'CI reported a failing status, so PortOS did not merge this approved PR.');+ approvals = approvals.filter((entry) => entry.number !== pr.number);+ continue;+ }approvals = mergeApproval(approvals, {number: pr.number,headSha: pr.headRefOid,@@ -652,8 +706,30 @@ export async function processTaskOutput({ appId, success, payload, task } = {})}const latestState = readState(await getAppById(appId) || app);+ const timedOutComments = [];const pendingIssueComments = (Array.isArray(latestState.pendingIssueComments) ? latestState.pendingIssueComments : [])- .filter((item) => !handledCommentKeys.has(`${item?.issueNumber}:${item?.commentId}`));+ .flatMap((item) => {+ const key = `${item?.issueNumber}:${item?.commentId}`;+ if (handledCommentKeys.has(key)) return [];+ if (!expectedComments.has(key)) return [item];+ const next = { ...item, ticks: (item.ticks || 0) + 1 };+ if (next.ticks < MAX_PENDING_ISSUE_COMMENT_TICKS) return [next];+ timedOutComments.push(next);+ return [];+ });+ if (timedOutComments.length > 0) {+ await addNotification({+ type: NOTIFICATION_TYPES.AGENT_WARNING,+ priority: PRIORITY_LEVELS.HIGH,+ title: `${timedOutComments.length} Issue Watcher comment${timedOutComments.length === 1 ? '' : 's'} need attention`,+ description: `PortOS stopped retrying after ${MAX_PENDING_ISSUE_COMMENT_TICKS} incomplete reasoning or reply attempts.`,+ link: timedOutComments[0].commentUrl,+ metadata: { appId, issueWatcherCommentCount: timedOutComments.length },+ }).catch((err) => {+ console.error(`❌ issue-watcher: failed to notify about timed-out issue comments: ${err.message}`);+ return null;+ });+ }await persistState(appId, {approvedPullRequests: approvals,pendingIssueComments,diff --git a/server/services/issueWatcher.test.js b/server/services/issueWatcher.test.jsindex e635f637b5..44e624980c 100644--- a/server/services/issueWatcher.test.js+++ b/server/services/issueWatcher.test.js@@ -44,6 +44,7 @@ import {parseAddedDiffLines,processTaskOutput,MAX_PENDING_APPROVAL_TICKS,+ MAX_PENDING_ISSUE_COMMENT_TICKS,} from './issueWatcher.js';const APP = { id: 'app-1', name: 'Example App', repoPath: '/repos/example' };@@ -140,6 +141,8 @@ describe('issue-watcher pure contracts', () => {it('keeps failed, pending, and green check states distinct', () => {expect(classifyChecks([{ conclusion: 'FAILURE' }])).toBe('failed');+ expect(classifyChecks([{ state: 'ERROR' }])).toBe('failed');+ expect(classifyChecks([{ conclusion: 'STARTUP_FAILURE' }])).toBe('failed');expect(classifyChecks([])).toBe('pending');expect(classifyChecks([{ status: 'IN_PROGRESS' }])).toBe('pending');expect(classifyChecks([{ conclusion: 'SUCCESS' }, { conclusion: 'SKIPPED' }])).toBe('green');@@ -207,6 +210,31 @@ describe('buildTaskInput', () => {);expect(apps.get(APP.id).issueWatcherState.cursor).toMatch(/^2026-/);});++ it('continues to cognition when an explicit volunteer cannot be assigned', async () => {+ apps.set(APP.id, { ...APP, issueWatcherState: { cursor: '2026-08-29T00:00:00.000Z' } });+ installDefaultGhMock({ pr: null });+ execGhMock.mockImplementation(async (args) => {+ if (args[0] === 'api' && args.includes('repos/o/r') && !args.some((arg) => String(arg).includes('/issues'))) {+ return JSON.stringify({ owner: { login: 'owner', type: 'User' } });+ }+ if (args[0] === 'api' && args.some((arg) => String(arg).endsWith('/issues'))) {+ return JSON.stringify([[{ number: 12, title: 'Small task', body: 'Please help', assignees: [] }]]);+ }+ if (args[0] === 'api' && args.some((arg) => String(arg).includes('/comments'))) {+ return JSON.stringify([[{ id: 99, body: 'I can take this issue', created_at: '2026-08-30T00:00:00.000Z', user: { login: 'alice' } }]]);+ }+ if (args[0] === 'issue' && args[1] === 'edit') throw new Error('HTTP 422');+ if (args[0] === 'pr' && args[1] === 'list') return '[]';+ return '{}';+ });++ const result = await buildTaskInput({ app: apps.get(APP.id) });++ expect(result.prompt).toContain('Issue #12: Small task');+ expect(result.hookMetadata.issueWatcher.issueComments).toEqual([{ issueNumber: 12, commentId: 99 }]);+ expect(apps.get(APP.id).issueWatcherState.cursor).toMatch(/^2026-/);+ });});describe('processTaskOutput', () => {@@ -286,6 +314,42 @@ describe('processTaskOutput', () => {expect(mergePrMock).not.toHaveBeenCalled();});+ it('approves and merges a fresh clean PR after green checks', async () => {+ installDefaultGhMock();+ mergePrMock.mockResolvedValue({ success: true });+ const payload = {+ issueComments: [],+ pullRequests: [{+ number: 7, headSha: 'a'.repeat(40), verdict: 'approve', summary: 'No material issues found.', findings: [],+ rebaseRequired: false, ciPolicy: 'required',+ }],+ };++ const result = await processTaskOutput({ appId: APP.id, success: true, payload, task: { metadata } });++ expect(result).toMatchObject({ reviewed: 1, merged: 1 });+ const reviewCall = execGhMock.mock.calls.find(([args]) => args.includes('repos/o/r/pulls/7/reviews') && args.includes('--input'));+ expect(JSON.parse(reviewCall[2].input)).toMatchObject({ event: 'APPROVE', comments: [] });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7);+ });++ it('does not review or merge when the PR head changed after cognition', async () => {+ installDefaultGhMock({ pr: pullRequest({ headRefOid: 'c'.repeat(40) }) });+ const payload = {+ issueComments: [],+ pullRequests: [{+ number: 7, headSha: 'a'.repeat(40), verdict: 'approve', summary: 'No material issues found.', findings: [],+ rebaseRequired: false, ciPolicy: 'required',+ }],+ };++ const result = await processTaskOutput({ appId: APP.id, success: true, payload, task: { metadata } });++ expect(result).toMatchObject({ reviewed: 0, merged: 0 });+ expect(execGhMock.mock.calls.some(([args]) => args.includes('repos/o/r/pulls/7/reviews') && args.includes('--input'))).toBe(false);+ expect(mergePrMock).not.toHaveBeenCalled();+ });+it('waits one scheduled observation before treating absent CI as skippable', async () => {installDefaultGhMock({ pr: pullRequest({ statusCheckRollup: [] }) });mergePrMock.mockResolvedValue({ success: true });@@ -349,9 +413,11 @@ describe('processTaskOutput', () => {expect(result).toMatchObject({ reviewed: 1, merged: 0 });expect(mergePrMock).not.toHaveBeenCalled();- expect(apps.get(APP.id).issueWatcherState.approvedPullRequests).toEqual([- expect.objectContaining({ number: 7, headSha: 'a'.repeat(40), ciPolicy: 'skippable' }),- ]);+ expect(apps.get(APP.id).issueWatcherState.approvedPullRequests).toEqual([]);+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({+ title: 'Issue Watcher PR #7 needs attention',+ link: 'https://github.com/o/r/pull/7',+ }));});it('bounds polling for an approved PR whose CI never settles', async () => {@@ -379,4 +445,37 @@ describe('processTaskOutput', () => {metadata: { appId: APP.id, issueWatcherPrNumber: 7 },}));});++ it('ages out a repeatedly incomplete issue-comment decision and notifies', async () => {+ const pending = {+ issueNumber: 12,+ commentId: 99,+ commentUrl: 'https://github.com/o/r/issues/12#issuecomment-99',+ ticks: MAX_PENDING_ISSUE_COMMENT_TICKS - 1,+ };+ apps.set(APP.id, { ...APP, issueWatcherState: { pendingIssueComments: [pending] } });+ installDefaultGhMock();+ const commentMetadata = {+ issueWatcher: {+ ...metadata.issueWatcher,+ issueComments: [{ issueNumber: 12, commentId: 99 }],+ pullRequests: [],+ },+ };++ const result = await processTaskOutput({+ appId: APP.id,+ success: true,+ payload: { issueComments: [], pullRequests: [] },+ task: { metadata: commentMetadata },+ });++ expect(result).toMatchObject({ commentsHandled: false });+ expect(apps.get(APP.id).issueWatcherState.pendingIssueComments).toEqual([]);+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({+ type: 'agent_warning',+ link: pending.commentUrl,+ metadata: { appId: APP.id, issueWatcherCommentCount: 1 },+ }));+ });});