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
GitHub inbox: only actionable items in Needs you, Resolve with agent, batched Autopilot (#12923)
[._.]/ad1b68e017c8
diff --git a/client/src/components/github/GitHubInboxTab.jsx b/client/src/components/github/GitHubInboxTab.jsxindex 79374be90e..2904b04939 100644--- a/client/src/components/github/GitHubInboxTab.jsx+++ b/client/src/components/github/GitHubInboxTab.jsx@@ -1,9 +1,9 @@import { useCallback, useEffect, useRef, useState } from 'react';import { Link, useParams } from 'react-router';-import { ExternalLink, RefreshCw } from 'lucide-react';+import { Bot, ExternalLink, RefreshCw } from 'lucide-react';import Pill from '../ui/Pill';import GitHubThreadDrawer from './GitHubThreadDrawer';-import { DECISION_VIEW, TRUST_VIEW } from './githubTriageLabels';+import { AGENT_REFUSED_LABELS, DECISION_VIEW, TRUST_VIEW } from './githubTriageLabels';import socket from '../../services/socket';import LoadFailedState from '../ui/LoadFailedState';import PageSkeleton from '../ui/PageSkeleton';@@ -14,6 +14,7 @@ import {getGitHubNotifications,syncGitHubNotifications,applyGitHubNotificationAction,+ resolveGitHubNotificationWithAgent,} from '../../services/api';const VIEWS = [@@ -58,11 +59,16 @@ const chipClass = (active) => `shrink-0 rounded-full border px-3 py-1.5 text-xs? 'border-port-accent/40 bg-port-accent/20 text-port-accent': 'border-port-border bg-port-bg text-gray-400'}`;+// Mirrors HANDLED_DECISIONS in server/lib/githubNotificationTriage.js:+// nothing is left for you on these threads, so they sit under Handled.+const HANDLED_DECISIONS = new Set(['handled-by-pr-workflow', 'duplicate', 'handed-off', 'suggest-mark-read']);+const nothingLeft = (row) => !row.suspect && HANDLED_DECISIONS.has(row.decision);+// Whether a row still belongs in the view after an action moved it.const VIEW_MATCHERS = {- 'needs-you': (row) => row.state === 'open' && !row.suspect,+ 'needs-you': (row) => row.state === 'open' && !row.suspect && !nothingLeft(row),suspect: (row) => row.state === 'open' && row.suspect,- handled: (row) => row.state !== 'open',+ handled: (row) => row.state !== 'open' || nothingLeft(row),all: () => true,};const belongsInView = (row, view) => VIEW_MATCHERS[view](row);@@ -90,6 +96,9 @@ function NotificationCard({ notification, accountLabel, busy, onAction }) {{notification.title}</Link>{decision && <p className="mt-1"><Pill tone={decision.tone}>{decision.label}</Pill></p>}+ {!handled && notification.agent?.refused && (+ <p className="mt-1 text-xs text-gray-500">{AGENT_REFUSED_LABELS[notification.agent.refused] || notification.agent.refused}</p>+ )}{accountLabel && <p className="mt-0.5 text-xs text-gray-500">{accountLabel}</p>}<div className="mt-2 flex flex-wrap gap-2">{notification.htmlUrl && (@@ -102,6 +111,16 @@ function NotificationCard({ notification, accountLabel, busy, onAction }) {<ExternalLink size={12} aria-hidden="true" /> Open</a>)}+ {!handled && notification.agent && !notification.agent.refused && (+ <button+ type="button"+ disabled={busy}+ onClick={() => onAction(notification, 'agent')}+ className="inline-flex items-center gap-1 rounded border border-port-accent/40 bg-port-accent/10 px-3 py-1.5 text-xs text-port-accent disabled:opacity-50"+ >+ <Bot size={12} aria-hidden="true" /> Resolve with agent+ </button>+ )}{(handled ? [UNDO_ACTIONS[notification.state]].filter(Boolean) : OPEN_ACTIONS).map(({ action, label }) => (<buttonkey={action}@@ -177,7 +196,9 @@ export default function GitHubInboxTab() {const handleAction = async (row, action) => {const key = keyOf(row);setBusyKey(key);- const updated = await applyGitHubNotificationAction(row.accountId, row.threadId, action).catch(() => null);+ const updated = await (action === 'agent'+ ? resolveGitHubNotificationWithAgent(row.accountId, row.threadId)+ : applyGitHubNotificationAction(row.accountId, row.threadId, action)).catch(() => null);setBusyKey(null);if (!updated) return;if (belongsInView(updated, view)) {diff --git a/client/src/components/github/GitHubThreadDrawer.jsx b/client/src/components/github/GitHubThreadDrawer.jsxindex 6ceaeea16b..0bdfd5675b 100644--- a/client/src/components/github/GitHubThreadDrawer.jsx+++ b/client/src/components/github/GitHubThreadDrawer.jsx@@ -48,6 +48,7 @@ function HandoffLine({ handoff }) {{handoff.appId && lane && (<> for <Link to={`/apps/${encodeURIComponent(handoff.appId)}/${lane.tab}`} className="text-port-accent">{handoff.appName || handoff.appId}</Link></>)}+ {handoff.batchSize > 1 && `, in one run with ${handoff.batchSize - 1} other notification${handoff.batchSize === 2 ? '' : 's'}`}</p>);}diff --git a/client/src/components/github/githubTriageLabels.js b/client/src/components/github/githubTriageLabels.jsindex 06788f89a4..e3ad89089e 100644--- a/client/src/components/github/githubTriageLabels.js+++ b/client/src/components/github/githubTriageLabels.js@@ -6,7 +6,7 @@ export const DECISION_VIEW = {surface: { tone: 'accent', label: 'Worth a look' },'suggest-review': { tone: 'accent', label: 'Suggest Do:Review' },'suggest-untrusted-review': { tone: 'warning', label: 'Suggest Untrusted:Review' },- 'suggest-mark-read': { tone: 'muted', label: 'Suggest mark read' },+ 'suggest-mark-read': { tone: 'muted', label: 'Closed or merged' },'handled-by-pr-workflow': { tone: 'success', label: 'PR workflow has it' },duplicate: { tone: 'muted', label: 'Duplicate' },'suggest-done': { tone: 'muted', label: 'Suggest done' },@@ -28,6 +28,7 @@ export const RULE_LABELS = {'finished-thread': 'The issue or pull request is already closed or merged','ci-default-branch': 'CI failed on the default branch','ci-watched-by-pr-workflow': 'CI on a branch of a PortOS managed app, which its PR workflow handles',+ 'own-pr-in-managed-repo': 'Activity on your own PR in a PortOS managed app, which its PR workflow handles','ci-other': 'CI result outside the default branch of a repo PortOS does not manage','review-trusted-author': 'Review requested by you or a collaborator with write access','review-outside-author': 'Review requested on your repo by someone without write access',@@ -58,6 +59,13 @@ export const ACTION_LABELS = {export const LANE_VIEW = {'pr-reviewer': { label: 'Untrusted:Review', tab: 'pull-requests' },'issue-watcher': { label: 'the issue watcher', tab: 'tasks' },+ 'dependency-updates': { label: 'dependency updates', tab: 'tasks' },+};++// Why Resolve with agent is unavailable for a thread.+export const AGENT_REFUSED_LABELS = {+ 'private-account': 'Private accounts never hand off to an agent',+ 'no-managed-app': 'Add this repo as a PortOS app to resolve it with an agent',};// Why Autopilot left a thread with you instead of handing it off.diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsxindex 76c241290c..eb0c0f73b2 100644--- a/client/src/pages/GitHub.test.jsx+++ b/client/src/pages/GitHub.test.jsx@@ -20,6 +20,7 @@ const mock = vi.hoisted(() => ({getGitHubNotifications: vi.fn(),syncGitHubNotifications: vi.fn(),applyGitHubNotificationAction: vi.fn(),+ resolveGitHubNotificationWithAgent: vi.fn(),getGitHubNotification: vi.fn(),getGitHubAutomations: vi.fn(),setGitHubNotificationCadence: vi.fn(),@@ -395,6 +396,25 @@ describe('GitHub inbox tab', () => {expect(await screen.findByText('Nothing needs you right now.')).toBeTruthy();});+ it('resolves an actionable thread with an agent in one tap, and says why when it cannot', async () => {+ mock.getGitHubNotifications.mockResolvedValue({+ notifications: [+ { ...NOTIFICATION, agent: { lane: 'pr-reviewer', refused: null } },+ { ...NOTIFICATION, threadId: '102', title: 'Alert elsewhere', reason: 'security_alert', agent: { lane: 'dependency-updates', refused: 'no-managed-app' } },+ ],+ sync: {},+ });+ mock.resolveGitHubNotificationWithAgent.mockResolvedValue({ ...NOTIFICATION, decision: 'handed-off', agent: null });+ renderTab('inbox');+ expect(await screen.findByText('Add this repo as a PortOS app to resolve it with an agent')).toBeTruthy();+ const buttons = screen.getAllByRole('button', { name: 'Resolve with agent' });+ expect(buttons).toHaveLength(1);+ fireEvent.click(buttons[0]);+ expect(mock.resolveGitHubNotificationWithAgent).toHaveBeenCalledWith('github-com', '101');+ // A handed-off thread is something else's now, so it leaves Needs you.+ await waitFor(() => expect(screen.queryByText('Example change')).toBeNull());+ });+it('undoes Done locally and a mute by re-subscribing', async () => {mock.getGitHubNotifications.mockResolvedValue({notifications: [{ ...NOTIFICATION, state: 'done' }, { ...NOTIFICATION, threadId: '102', title: 'Muted change', state: 'muted' }],diff --git a/client/src/services/apiGithub.js b/client/src/services/apiGithub.jsindex cd7d46d04d..80be6a9faa 100644--- a/client/src/services/apiGithub.js+++ b/client/src/services/apiGithub.js@@ -43,6 +43,8 @@ export const applyGitHubNotificationAction = (accountId, threadId, action, optiorequest(`/github/notifications/${encodeURIComponent(accountId)}/${encodeURIComponent(threadId)}`, {method: 'POST', body: JSON.stringify({ action }), ...options,});+export const resolveGitHubNotificationWithAgent = (accountId, threadId, options = {}) =>+ request(`/github/notifications/${encodeURIComponent(accountId)}/${encodeURIComponent(threadId)}/agent`, { method: 'POST', ...options });export const getGitHubNotification = (accountId, threadId, options = {}) =>request(`/github/notifications/${encodeURIComponent(accountId)}/${encodeURIComponent(threadId)}`, options);diff --git a/server/lib/githubNotificationTriage.js b/server/lib/githubNotificationTriage.jsindex 94e27e007a..85869e725e 100644--- a/server/lib/githubNotificationTriage.js+++ b/server/lib/githubNotificationTriage.js@@ -34,6 +34,15 @@ export const TRIAGE_DECISIONS = Object.freeze([export const TRUST_LEVELS = Object.freeze(['yours', 'trusted', 'outside', 'unknown']);+// Bump when a rule change should re-decide threads that have no new activity;+// open threads triaged under an older version are triaged again.+export const TRIAGE_RULES_VERSION = 2;++// Decisions that leave nothing for you: something else has the thread, or it+// is already closed or merged. They sit under Handled instead of Needs you,+// even in Observe before anything acts on GitHub.+export const HANDLED_DECISIONS = Object.freeze(['handled-by-pr-workflow', 'duplicate', 'handed-off', 'suggest-mark-read']);+const NEW_ACCOUNT_DAYS = 30;const DAY_MS = 24 * 60 * 60 * 1000;export const MASS_MENTION_THRESHOLD = 10;@@ -82,13 +91,20 @@ export function parseCiBranch(title) {/*** One decision from the fixed rule table (reason × source). First match wins:- * suspect, security alert, invitation, finished thread, CI, review request,- * mention elsewhere, then Needs you.+ * suspect, security alert, invitation, your own PR in a managed repo,+ * finished thread, CI, review request, mention elsewhere, then Needs you.+ *+ * `commenterTrust` is the latest commenter's trust when it differs from the+ * subject author. Activity on your own PR goes to the PR workflow that opened+ * and drives it, unless someone outside commented: that waits for you.*/-export function decideThread({ reason, subjectType, subjectState, subjectMerged = false, trust, suspect = false, repoOwned = false, repoManaged = false, ciBranch = null, defaultBranch = null }) {+export function decideThread({ reason, subjectType, subjectState, subjectMerged = false, trust, commenterTrust = null, suspect = false, repoOwned = false, repoManaged = false, ciBranch = null, defaultBranch = null }) {if (suspect) return { decision: 'suspect', rule: 'spam-signal' };if (reason === 'security_alert') return { decision: 'surface-high', rule: 'security-alert' };if (reason === 'invitation') return { decision: 'surface', rule: 'invitation-never-accepted' };+ if (reason === 'author' && subjectType === 'PullRequest' && trust === 'yours' && repoManaged && commenterTrust !== 'outside') {+ return { decision: 'handled-by-pr-workflow', rule: 'own-pr-in-managed-repo' };+ }const finished = subjectMerged === true || subjectState === 'closed';if (finished && reason !== 'review_requested') return { decision: 'suggest-mark-read', rule: 'finished-thread' };if (reason === 'ci_activity' || subjectType === 'CheckSuite') {@@ -137,14 +153,17 @@ export function applyLearnedRule(result, learned) {/*** The one GitHub write Assist may make for a thread, or null to leave it for- * the operator. Outside and Suspect threads are never acted on; a mute needs a- * trusted source or the operator's own learned rule.+ * the operator. Suspect threads are never acted on. Outside threads are acted+ * on only when the forge reports them closed or merged, which no content can+ * fake; a mute needs a trusted source or the operator's own learned rule.*/-export function assistAction({ decision, rule, trust, suspect = false, unread = true, state = 'open' }) {- if (suspect || state !== 'open' || trust === 'outside') return null;+export function assistAction({ decision, rule, trust, suspect = false, state = 'open' }) {+ if (suspect || state !== 'open') return null;+ // A closed or merged thread has nothing left to do, so it is done, not just read.+ if (decision === 'suggest-mark-read') return 'done';+ if (trust === 'outside') return null;const vouched = trust === 'yours' || trust === 'trusted' || rule === 'learned';if (decision === 'handled-by-pr-workflow') return 'done';- if (decision === 'suggest-mark-read') return unread ? 'read' : null;if (decision === 'suggest-done' && vouched) return 'done';if (decision === 'suggest-mute' && vouched) return 'mute';return null;@@ -169,29 +188,40 @@ export function selectNotificationProvider({ account, providers = [], policy = {return { code: 'github-notification-provider-not-allowed' };}-// Autopilot (#12874) hands a thread to the lane that already owns that kind of-// work. Issue activity qualifies while it would otherwise wait for you.+// A thread goes to the lane that already owns its kind of work. Issue+// activity qualifies while it would otherwise wait for you.const HANDOFF_ISSUE_DECISIONS = new Set(['needs-you', 'surface']);const PULL_PATH_RE = /\/pulls\/(\d{1,9})$/;/**- * Which lane Autopilot may hand a thread to, or null to leave it with you.- * Only threads in a PortOS managed app's repo qualify (the lanes run per app),- * never a Suspect or closed one. A Private account's hand-off is refused: the- * lanes use their own providers, which its provider allow-list cannot bind.- * The pull number comes from the subject's API url, never from a title or body.+ * Which lane an agent may resolve a thread in, or null when no lane fits. A+ * plan with `refused` names why it cannot go: only a PortOS managed app's+ * repo has lanes (they run per app), and a Private account's threads never+ * go, because the lanes use their own providers, which its provider+ * allow-list cannot bind. Suspect and closed threads never qualify. The pull+ * number comes from the subject's API url, never from a title or body. Used+ * by Autopilot (#12874) and the inbox's Resolve with agent button.*/-export function autopilotHandoff({ account, row }) {- if (account?.mode !== 'autopilot' || row?.state !== 'open' || row.suspect) return null;+export function agentHandoff({ account, row }) {+ if (row?.state !== 'open' || row.suspect) return null;const evidence = row.evidence || {};- if (evidence.repoManaged !== true) return null;let plan = null;if (row.decision === 'suggest-untrusted-review' && row.subject_type === 'PullRequest') {const pullNumber = Number(PULL_PATH_RE.exec(String(row.subject_api_url || ''))?.[1]);if (pullNumber > 0) plan = { lane: 'pr-reviewer', pullNumber };} else if (row.subject_type === 'Issue' && HANDOFF_ISSUE_DECISIONS.has(row.decision) && (row.trust === 'outside' || evidence.commenter)) {plan = { lane: 'issue-watcher' };+ } else if (row.reason === 'security_alert' && row.decision === 'surface-high') {+ // The lane reads the repo's own Dependabot alerts and PRs, not the thread.+ plan = { lane: 'dependency-updates' };}if (!plan) return null;- return account.trust === 'private' ? { ...plan, refused: 'private-account' } : plan;+ if (account?.trust === 'private') return { ...plan, refused: 'private-account' };+ if (evidence.repoManaged !== true) return { ...plan, refused: 'no-managed-app' };+ return plan;+}++/** Autopilot's plan for a thread: `agentHandoff`, only in Autopilot mode. */+export function autopilotHandoff({ account, row }) {+ return account?.mode === 'autopilot' ? agentHandoff({ account, row }) : null;}diff --git a/server/lib/githubNotificationTriage.test.js b/server/lib/githubNotificationTriage.test.jsindex 0fa82a1a91..f506d98736 100644--- a/server/lib/githubNotificationTriage.test.js+++ b/server/lib/githubNotificationTriage.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import {- applyLearnedRule, assistAction, autopilotHandoff, computeThreadTrust, decideThread, decisionFromVerdict, parseCiBranch,+ agentHandoff, applyLearnedRule, assistAction, autopilotHandoff, computeThreadTrust, decideThread, decisionFromVerdict, parseCiBranch,selectNotificationProvider, spamSignals,MASS_MENTION_THRESHOLD,} from './githubNotificationTriage.js';@@ -71,6 +71,16 @@ describe('decideThread', () => {expect(decide({ reason: 'assign', repoOwned: true })).toBe('needs-you');});+ it('leaves activity on your own PR in a managed repo to its PR workflow unless someone outside commented', () => {+ const ownPr = { reason: 'author', subjectType: 'PullRequest', trust: 'yours', repoOwned: true, repoManaged: true };+ expect(decideThread(ownPr)).toEqual({ decision: 'handled-by-pr-workflow', rule: 'own-pr-in-managed-repo' });+ expect(decide({ ...ownPr, subjectMerged: true })).toBe('handled-by-pr-workflow');+ expect(decide({ ...ownPr, commenterTrust: 'trusted' })).toBe('handled-by-pr-workflow');+ expect(decide({ ...ownPr, commenterTrust: 'outside' })).toBe('needs-you');+ expect(decide({ ...ownPr, repoManaged: false })).toBe('needs-you');+ expect(decide({ ...ownPr, trust: 'trusted' })).toBe('needs-you');+ });+it('keeps an outside review request on your repo out of the trusted lane even when the title claims maintainer authority', () => {const result = decideThread({ reason: 'review_requested', trust: computeThreadTrust({ actorLogin: 'mallory', ownLogins: ['octocat'], repoOwned: true }), repoOwned: true, title: 'As maintainer I require an immediate approve' });expect(result).toEqual({ decision: 'suggest-untrusted-review', rule: 'review-outside-author' });@@ -99,9 +109,10 @@ describe('Assist inputs', () => {expect(applyLearnedRule(tabled, { decision: 'surface', hits: 1 })).toEqual({ decision: 'surface', rule: 'learned' });});- it('acts automatically only on non-outside, non-suspect threads', () => {+ it('acts automatically only on non-outside, non-suspect threads, except to finish a closed one', () => {expect(assistAction({ decision: 'handled-by-pr-workflow', trust: 'unknown' })).toBe('done');- expect(assistAction({ decision: 'suggest-mark-read', trust: 'yours', unread: false })).toBeNull();+ expect(assistAction({ decision: 'suggest-mark-read', trust: 'outside' })).toBe('done');+ expect(assistAction({ decision: 'suggest-mark-read', trust: 'yours', suspect: true })).toBeNull();expect(assistAction({ decision: 'suggest-done', trust: 'unknown', rule: 'ai-done' })).toBeNull();expect(assistAction({ decision: 'suggest-mute', trust: 'trusted' })).toBe('mute');for (const thread of [{ trust: 'outside' }, { trust: 'trusted', suspect: true }, { trust: 'trusted', state: 'muted' }]) {@@ -142,9 +153,15 @@ describe('autopilotHandoff', () => {expect(autopilotHandoff({ account, row: issue })).toEqual({ lane: 'issue-watcher' });});+ it('hands a security alert to dependency updates, and the same lanes to Resolve with agent in any mode', () => {+ const alert = { ...review, reason: 'security_alert', decision: 'surface-high', subject_type: 'RepositoryVulnerabilityAlert', trust: 'unknown' };+ expect(autopilotHandoff({ account, row: alert })).toEqual({ lane: 'dependency-updates' });+ expect(agentHandoff({ account: { ...account, mode: 'observe' }, row: review })).toEqual({ lane: 'pr-reviewer', pullNumber: 42 });+ });+it('never hands off outside Autopilot, in a repo PortOS does not manage, or a suspect or closed thread', () => {expect(autopilotHandoff({ account: { ...account, mode: 'assist' }, row: review })).toBeNull();- expect(autopilotHandoff({ account, row: { ...review, evidence: { repoManaged: false, repoOwned: true } } })).toBeNull();+ expect(autopilotHandoff({ account, row: { ...review, evidence: { repoManaged: false, repoOwned: true } } })).toEqual({ lane: 'pr-reviewer', pullNumber: 42, refused: 'no-managed-app' });expect(autopilotHandoff({ account, row: { ...review, suspect: true } })).toBeNull();expect(autopilotHandoff({ account, row: { ...issue, state: 'done' } })).toBeNull();// An issue from you or a collaborator with no outside comment stays with you.diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex decef9b24d..76e208653e 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -982,6 +982,8 @@ export const HOST_CONTROL_ROUTES = Object.freeze(['POST /api/github/repos/:fullName/unarchive','PUT /api/github/secrets/:name','POST /api/github/secrets/:name/sync',+ // Resolve with agent queues CoS agent work against the thread's app.+ 'POST /api/github/notifications/:accountId/:threadId/agent',// Beeper outbox creation records approved send intent; send spends the// operator's saved connection, and breaker reset re-arms that capability.diff --git a/server/routes/github.js b/server/routes/github.jsindex f4903ac266..aac6512cd6 100644--- a/server/routes/github.js+++ b/server/routes/github.js@@ -169,6 +169,13 @@ router.post('/notifications/:accountId/:threadId', asyncHandler(async (req, res)res.json(await githubNotifications.applyNotificationAction(req.params.accountId, threadIdParam(req), action));}));+/**+ * POST /api/github/notifications/:accountId/:threadId/agent — Resolve with agent: queue the thread's lane now+ */+router.post('/notifications/:accountId/:threadId/agent', asyncHandler(async (req, res) => {+ res.json(await githubNotifications.resolveWithAgent(req.params.accountId, threadIdParam(req)));+}));+/*** GET /api/github/automations — the notification check's cadence and each account's last run*/diff --git a/server/services/githubNotificationAssist.js b/server/services/githubNotificationAssist.jsindex e26108f00c..fac96dd03d 100644--- a/server/services/githubNotificationAssist.js+++ b/server/services/githubNotificationAssist.js@@ -128,7 +128,7 @@ export async function assistAccountNotifications(account, env, { act }) {if (!ASSIST_MODES.has(account.mode)) return { sorted: 0, acted: 0 };const sorted = await sortUndecided(account, env);const { rows } = await query(- `SELECT thread_id, decision, trust, suspect, unread, state, evidence->>'rule' AS rule FROM github_notifications+ `SELECT thread_id, decision, trust, suspect, state, evidence->>'rule' AS rule FROM github_notificationsWHERE account_id = $1 AND state = 'open' AND NOT suspect AND decision = ANY($2::text[]) AND NOT (evidence ? 'assisted')ORDER BY gh_updated_at DESC LIMIT ${MAX_ACTIONS_PER_RUN}`,[account.id, ACTIONABLE_DECISIONS],diff --git a/server/services/githubNotificationAutopilot.js b/server/services/githubNotificationAutopilot.jsindex d4cb80869a..e0270810ab 100644--- a/server/services/githubNotificationAutopilot.js+++ b/server/services/githubNotificationAutopilot.js@@ -3,7 +3,9 @@* Assist, a thread in one of the operator's managed apps is handed to the lane* that already owns that work: a review request from an outside author to* `pr-reviewer` (the same targeted run as the Pull Requests tab's- * Untrusted:Review button), and outside issue activity to `issue-watcher`.+ * Untrusted:Review button), outside issue activity to `issue-watcher`, and a+ * security alert to `dependency-updates`. The inbox's Resolve with agent button+ * hands one thread off the same way on a tap, in any mode.** Nothing here reads thread text or starts an agent: each hand-off queues the* lane's own on-demand run, which re-screens its input with its own guards. The@@ -11,42 +13,49 @@* Mentions or requests in repos the operator does not own are never handed off.*/import { query, withTransaction } from '../lib/db.js';-import { autopilotHandoff } from '../lib/githubNotificationTriage.js';+import { ServerError } from '../lib/errorHandler.js';+import { agentHandoff, autopilotHandoff } from '../lib/githubNotificationTriage.js';import { toPgJson } from '../lib/pgJson.js';import { managedAppsByRepoKey } from './githubNotificationTriage.js';import { queueTargetedPrReview, readActiveTasks, readPendingOnDemandRequests, ACTIVE_TASK_STATUSES } from './prReviewerTargetedRun.js';import { triggerOnDemandTask } from './taskSchedule.js';import { ON_DEMAND_ORIGINS } from './taskScheduleConstants.js';-const MAX_HANDOFFS_PER_RUN = 10;-const ISSUE_WATCHER_TASK_TYPE = 'issue-watcher';-// The SQL mirror of `autopilotHandoff`'s lane rules, so a run's limit is spent+// Threads per run, not agent runs: a run queues at most one agent per repo and lane.+const MAX_HANDOFFS_PER_RUN = 50;+// The SQL mirror of `agentHandoff`'s lane rules, so a run's limit is spent// only on threads that can be handed off and an older eligible thread is never// starved by newer ones the rule would reject.const CANDIDATE_SQL = `((decision = 'suggest-untrusted-review' AND subject_type = 'PullRequest')- OR (subject_type = 'Issue' AND decision IN ('needs-you', 'surface') AND (trust = 'outside' OR evidence->>'commenter' IS NOT NULL)))`;+ OR (subject_type = 'Issue' AND decision IN ('needs-you', 'surface') AND (trust = 'outside' OR evidence->>'commenter' IS NOT NULL))+ OR (reason = 'security_alert' AND decision = 'surface-high'))`;-/** Queue the app's issue-watcher run unless one is already queued or running. */-async function queueIssueWatcher(app) {+/**+ * Queue the app's run of a whole-app lane unless one is already queued or+ * running. For pr-reviewer this is the sweep over every outside PR, so a run+ * narrowed to one PR does not count as one.+ */+async function queueAppLane(taskType, app, origin) {+ const covers = (target) => target === undefined || target === null;const [tasks, requests] = await Promise.all([readActiveTasks(), readPendingOnDemandRequests()]);// Unreadable state is not "nothing queued": fail closed rather than queue a- // second screening pass over the same issues.+ // second pass over the same work.if (tasks === null || requests === null) return { error: 'Could not inspect existing CoS actions' };const running = tasks.find((task) => ACTIVE_TASK_STATUSES.has(task?.status)- && task.metadata?.analysisType === ISSUE_WATCHER_TASK_TYPE && task.metadata?.app === app.id);+ && task.metadata?.analysisType === taskType && task.metadata?.app === app.id && covers(task.metadata?.targetPullRequest));if (running) return { duplicate: true, taskId: running.id };- if (requests.some((request) => request?.taskType === ISSUE_WATCHER_TASK_TYPE && request?.appId === app.id)) return { duplicate: true };- const request = await triggerOnDemandTask(ISSUE_WATCHER_TASK_TYPE, app.id, { origin: ON_DEMAND_ORIGINS.GITHUB_NOTIFICATION });+ if (requests.some((request) => request?.taskType === taskType && request?.appId === app.id && covers(request?.targetPullRequest))) return { duplicate: true };+ const request = await triggerOnDemandTask(taskType, app.id, { origin });return request?.error ? { error: request.error } : { requestId: request.id };}-async function queueLane(plan, app) {- if (plan.lane === 'issue-watcher') return queueIssueWatcher(app);- return queueTargetedPrReview(app, plan.pullNumber, { origin: ON_DEMAND_ORIGINS.GITHUB_NOTIFICATION })+async function queueLane(plan, app, origin) {+ if (plan.lane !== 'pr-reviewer' || !plan.pullNumber) return queueAppLane(plan.lane, app, origin);+ return queueTargetedPrReview(app, plan.pullNumber, { origin }).then((queued) => (queued.duplicate ? { duplicate: true, taskId: queued.reviewAction?.taskId || null } : { requestId: queued.request.id }));}-async function recordHandoff(account, row, handoff) {+async function recordHandoff(account, row, handoff, actor = 'automation') {await withTransaction(async (client) => {await client.query(`UPDATE github_notifications SET decision = CASE WHEN $3::boolean THEN 'handed-off' ELSE decision END,@@ -56,20 +65,23 @@ async function recordHandoff(account, row, handoff) {);if (!handoff.skipped) {await client.query(- `INSERT INTO github_notification_events (account_id, thread_id, actor, kind, detail) VALUES ($1, $2, 'automation', 'handed-off', $3::jsonb)`,- [account.id, row.thread_id, toPgJson({ lane: handoff.lane, appId: handoff.appId, previousDecision: row.decision })],+ `INSERT INTO github_notification_events (account_id, thread_id, actor, kind, detail) VALUES ($1, $2, $3, 'handed-off', $4::jsonb)`,+ [account.id, row.thread_id, actor, toPgJson({ lane: handoff.lane, appId: handoff.appId, previousDecision: row.decision })],);}});}/**- * Hand off this account's eligible threads. Each thread is tried once per- * activity: a refusal is recorded with its reason and the thread stays with- * you until new activity re-triages it.+ * Hand off this account's eligible threads, batched so one agent run covers+ * every thread of a lane in a repo: a dozen alerts for one repo queue one+ * dependency-updates run, and review requests on several outside PRs in one+ * repo queue one pr-reviewer sweep instead of one targeted run each. Each+ * thread is tried once per activity: a refusal is recorded with its reason and+ * the thread stays with you until new activity re-triages it.*/export async function autopilotAccountNotifications(account) {- if (account.mode !== 'autopilot') return { handedOff: 0 };+ if (account.mode !== 'autopilot') return { handedOff: 0, agentRuns: 0 };const { rows } = await query(`SELECT * FROM github_notifications WHERE account_id = $1 AND state = 'open' AND NOT suspectAND ${CANDIDATE_SQL} AND (evidence->>'repoManaged')::boolean IS TRUE AND NOT (evidence ? 'handoff')@@ -77,20 +89,24 @@ export async function autopilotAccountNotifications(account) {[account.id],);const plans = rows.map((row) => ({ row, plan: autopilotHandoff({ account, row }) })).filter((entry) => entry.plan);- if (!plans.length) return { handedOff: 0 };+ if (!plans.length) return { handedOff: 0, agentRuns: 0 };const apps = await managedAppsByRepoKey();- let handedOff = 0;- for (const { row, plan } of plans) {- const app = apps.get(`${account.host}/${row.repo_full_name}`.toLowerCase());- let outcome;- if (plan.refused) outcome = { skipped: plan.refused };- else if (!app) outcome = { skipped: 'no-managed-app' };- else {- // A lane that throws (a schedule write failing) is a recorded skip, so- // it never stops Assist or the rest of the sync for this account.- const queued = await queueLane(plan, app).catch((error) => ({ error: error.message }));- outcome = queued.error ? { skipped: 'lane-unavailable', error: String(queued.error).slice(0, 300) } : queued;+ const batches = new Map();+ const skipped = [];+ for (const entry of plans) {+ const app = apps.get(`${account.host}/${entry.row.repo_full_name}`.toLowerCase());+ if (entry.plan.refused || !app) {+ skipped.push({ ...entry, app, outcome: { skipped: entry.plan.refused || 'no-managed-app' } });+ continue;}+ const key = `${app.id}#${entry.plan.lane}`;+ if (!batches.has(key)) batches.set(key, { app, lane: entry.plan.lane, entries: [] });+ batches.get(key).entries.push({ ...entry, app });+ }++ let handedOff = 0;+ let agentRuns = 0;+ const record = async ({ row, plan, app, outcome }) => {const handoff = {lane: plan.lane,appId: app?.id || null,@@ -104,8 +120,52 @@ export async function autopilotAccountNotifications(account) {console.log(`⏭️ Autopilot left GitHub notification ${row.thread_id} with you: ${handoff.skipped}${handoff.error ? ` (${handoff.error})` : ''}`);} else {handedOff += 1;- console.log(`🤝 Autopilot handed GitHub notification ${row.thread_id} to ${plan.lane} for ${app.name}`);}+ };+ for (const entry of skipped) await record(entry);+ for (const { app, lane, entries } of batches.values()) {+ const pullNumbers = new Set(entries.map((entry) => entry.plan.pullNumber).filter(Boolean));+ const batchPlan = lane === 'pr-reviewer' && pullNumbers.size === 1 ? entries[0].plan : { lane };+ // A lane that throws (a schedule write failing) is a recorded skip, so+ // it never stops Assist or the rest of the sync for this account.+ const queued = await queueLane(batchPlan, app, ON_DEMAND_ORIGINS.GITHUB_NOTIFICATION).catch((error) => ({ error: error.message }));+ const outcome = queued.error+ ? { skipped: 'lane-unavailable', error: String(queued.error).slice(0, 300) }+ : { ...queued, ...(entries.length > 1 ? { batchSize: entries.length } : {}) };+ if (queued.requestId) agentRuns += 1;+ for (const entry of entries) await record({ ...entry, outcome });+ if (!queued.error) console.log(`🤝 Autopilot handed ${entries.length} GitHub notification(s) to one ${lane} run for ${app.name}`);}- return { handedOff };+ return { handedOff, agentRuns };+}++const REFUSED_MESSAGES = {+ 'private-account': 'Private accounts never hand threads to an agent: the agents use their own AI providers',+ 'no-managed-app': 'No PortOS app manages this repo, so no agent can work on it',+};++/**+ * The inbox's Resolve with agent tap: hand one thread to its lane now, in any+ * mode, under the same rules as Autopilot. A refusal or a lane that will not+ * take it is an error for the tap and leaves the thread as it was.+ */+export async function handOffThread(account, threadId) {+ const row = (await query('SELECT * FROM github_notifications WHERE account_id = $1 AND thread_id = $2', [account.id, threadId])).rows[0];+ if (!row) throw new ServerError('Notification not found', { status: 404, code: 'GITHUB_NOTIFICATION_NOT_FOUND' });+ const plan = agentHandoff({ account, row });+ if (!plan) throw new ServerError('No agent handles this kind of notification', { status: 409, code: 'GITHUB_NOTIFICATION_NO_LANE' });+ if (plan.refused) throw new ServerError(REFUSED_MESSAGES[plan.refused], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });+ const app = (await managedAppsByRepoKey()).get(`${account.host}/${row.repo_full_name}`.toLowerCase());+ if (!app) throw new ServerError(REFUSED_MESSAGES['no-managed-app'], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });+ const queued = await queueLane(plan, app, ON_DEMAND_ORIGINS.USER);+ if (queued.error) throw new ServerError(String(queued.error), { status: 409, code: 'GITHUB_NOTIFICATION_LANE_UNAVAILABLE' });+ await recordHandoff(account, row, {+ lane: plan.lane,+ appId: app.id,+ appName: app.name || null,+ ...(plan.pullNumber ? { pullNumber: plan.pullNumber } : {}),+ ...queued,+ at: new Date().toISOString(),+ }, 'operator');+ console.log(`🤝 Handed GitHub notification ${row.thread_id} to ${plan.lane} for ${app.name}`);}diff --git a/server/services/githubNotificationTriage.js b/server/services/githubNotificationTriage.jsindex 4060049769..3589d1d838 100644--- a/server/services/githubNotificationTriage.js+++ b/server/services/githubNotificationTriage.js@@ -12,7 +12,7 @@*/import { query, withTransaction } from '../lib/db.js';import { repoApiPath } from '../lib/githubNotificationParse.js';-import { applyLearnedRule, computeThreadTrust, decideThread, parseCiBranch, spamSignals } from '../lib/githubNotificationTriage.js';+import { applyLearnedRule, computeThreadTrust, decideThread, parseCiBranch, spamSignals, TRIAGE_RULES_VERSION } from '../lib/githubNotificationTriage.js';import { parseGitRemoteUrl, readOriginRemoteUrl } from '../lib/gitRemote.js';import { safeJSONParse } from '../lib/fileUtils.js';import { toPgJson } from '../lib/pgJson.js';@@ -23,6 +23,12 @@ import { listAccounts } from './githubAccounts.js';const GH_TIMEOUT_MS = 20_000;// Each thread costs a few API calls; the rest wait for the next run.const MAX_THREADS_PER_RUN = 25;+// Open threads a rules-version bump re-decides without new activity: version 2+// changed your own PRs and finished threads (now marked done, not just read).+// A thread already handed off keeps its hand-off, and one an Assist model+// sorted is not read again.+const REDECIDE_SQL = `(state = 'open' AND NOT (evidence ? 'handoff') AND COALESCE(evidence->>'rule', '') NOT LIKE 'ai-%'+ AND ((reason = 'author' AND subject_type = 'PullRequest') OR decision = 'suggest-mark-read'))`;const LOGIN_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}(?:\[bot\])?$/;const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;@@ -138,8 +144,12 @@ async function triageThread(row, ctx) {const signalSet = new Set(actorLogin? await signalsFor(actorLogin, trust, subjectAuthor ? subject.association : comment?.association, subjectAuthor ? 0 : comment?.mentions ?? 0): []);+ // A latest comment that could not be read counts as outside, so your own PR+ // never leaves Needs you on a comment nobody checked.+ let commenterTrust = commentPath && commentPath !== subjectPath && !commenter ? 'outside' : null;if (commenter && subjectAuthor && commenter.toLowerCase() !== subjectAuthor.toLowerCase()) {- for (const signal of await signalsFor(commenter, await trustOf(commenter), comment.association, comment.mentions ?? 0)) signalSet.add(signal);+ commenterTrust = await trustOf(commenter);+ for (const signal of await signalsFor(commenter, commenterTrust, comment.association, comment.mentions ?? 0)) signalSet.add(signal);}const signals = [...signalSet];@@ -152,6 +162,7 @@ async function triageThread(row, ctx) {subjectState: subject?.state || null,subjectMerged: subject?.merged === true,trust,+ commenterTrust,suspect: signals.length > 0,repoOwned,repoManaged,@@ -173,6 +184,7 @@ async function triageThread(row, ctx) {subjectState: subject ? (subject.merged === true ? 'merged' : subject.state || null) : null,ciBranch,metadataMissing: Boolean(subjectPath && !subject),+ rulesVersion: TRIAGE_RULES_VERSION,},};}@@ -207,9 +219,10 @@ async function foldCiDuplicates(client, accountId) {*/export async function triageAccountNotifications(account, env, { now = Date.now() } = {}) {const { rows } = await query(- `SELECT * FROM github_notifications WHERE account_id = $1 AND (triaged_for IS NULL OR triaged_for < gh_updated_at)+ `SELECT * FROM github_notifications WHERE account_id = $1 AND (triaged_for IS NULL OR triaged_for < gh_updated_at+ OR (${REDECIDE_SQL} AND COALESCE((evidence->>'rulesVersion')::int, 0) < $2))ORDER BY gh_updated_at DESC LIMIT ${MAX_THREADS_PER_RUN}`,- [account.id],+ [account.id, TRIAGE_RULES_VERSION],);if (!rows.length) return { triaged: 0, decisions: {} };const reader = createReader(account, env);diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex ef8b38c1e6..e70d878a43 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -45,7 +45,7 @@ const { runUntrustedContentAnalysis } = await import('./untrustedContent.js');const { createAccount, updateAccount } = await import('./githubAccounts.js');const {syncAccountNotifications, listNotifications, applyNotificationAction, getNotification, runScheduledNotificationCheck,- listAutomationActivity, undoAutomationAction, listLearnedRules,+ listAutomationActivity, undoAutomationAction, listLearnedRules, resolveWithAgent,} = await import('./githubNotifications.js');const { buildTaskInput } = await import('./githubNotificationsHooks.js');const { runAccountAudit, applyAuditSuggestion, listAuditChanges, undoAuditChange, sendDueAuditReports } = await import('./githubNotificationAudit.js');@@ -283,8 +283,10 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {const ci = (id, updatedAt) => thread(id, { owner: login, reason: 'ci_activity', type: 'CheckSuite', url: null, updatedAt, title: 'CI workflow run failed for main branch' });mockGh(() => listing([ci('701', '2026-10-01T10:00:00Z'), ci('702', '2026-10-01T11:00:00Z')]), { [`repos/${login}/hello`]: 'main' });await syncAccountNotifications(account.id);- const rows = (await listNotifications({ accountId: account.id })).notifications;+ const rows = (await listNotifications({ accountId: account.id, view: 'all' })).notifications;expect(rows.map((row) => [row.threadId, row.decision])).toEqual([['702', 'surface'], ['701', 'duplicate']]);+ // The folded notice is Handled while still open, so red main shows once in Needs you.+ expect((await listNotifications({ accountId: account.id })).notifications.map((row) => row.threadId)).toEqual(['702']);});it('sorts undecided threads only in Assist, acts only on trusted ones, and undoes into a learned rule', async () => {@@ -325,13 +327,17 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {await updateAccount(account.id, { mode: 'assist' });const result = await syncAccountNotifications(account.id);- expect(result.assist).toEqual({ sorted: 2, acted: 2, handedOff: 0 });+ expect(result.assist).toEqual({ sorted: 2, acted: 3, handedOff: 0, agentRuns: 0 });expect(runUntrustedContentAnalysis).toHaveBeenCalledTimes(3);// Same activity time on every thread, so compare without order.- expect([...actions].sort()).toEqual([['DELETE', 'notifications/threads/903'], ['PATCH', 'notifications/threads/901']]);+ // Closed or merged threads are done, even an outside one: the forge reports+ // that state, so no content can fake it.+ expect([...actions].sort()).toEqual([+ ['DELETE', 'notifications/threads/901'], ['DELETE', 'notifications/threads/902'], ['DELETE', 'notifications/threads/903'],+ ]);const byId = Object.fromEntries((await listNotifications({ accountId: account.id, view: 'all' })).notifications.map((row) => [row.threadId, row]));- expect(byId['902']).toMatchObject({ decision: 'suggest-mark-read', trust: 'outside', unread: true });+ expect(byId['902']).toMatchObject({ decision: 'suggest-mark-read', trust: 'outside', state: 'done' });expect(byId['903']).toMatchObject({ decision: 'suggest-done', rule: 'ai-done', state: 'done' });// The injected comment got a verdict but no action and no change of trust.expect(byId['904']).toMatchObject({ decision: 'suggest-done', trust: 'outside', state: 'open', suspect: false });@@ -340,9 +346,8 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {const activity = await listAutomationActivity();const mine = activity.filter((entry) => entry.accountId === account.id);- expect(mine.map((entry) => [entry.threadId, entry.action, entry.undoable]).sort()).toEqual([['901', 'read', false], ['903', 'done', true]]);+ expect(mine.map((entry) => [entry.threadId, entry.action, entry.undoable]).sort()).toEqual([['901', 'done', true], ['902', 'done', true], ['903', 'done', true]]);const byThread = Object.fromEntries(mine.map((entry) => [entry.threadId, entry]));- await expect(undoAutomationAction(byThread['901'].id)).rejects.toMatchObject({ status: 409 });await undoAutomationAction(byThread['903'].id);expect(await getNotification(account.id, '903')).toMatchObject({ state: 'open', decision: 'surface', rule: 'learned' });expect((await listLearnedRules()).filter((rule) => rule.accountId === account.id)).toEqual([@@ -473,6 +478,84 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {vi.mocked(getAllApps).mockResolvedValue([]);});+ it('files your own PRs under Handled, and batches Autopilot to one agent run per repo and lane', async () => {+ await updateAccount(account.id, { mode: 'autopilot' });+ vi.mocked(getAllApps).mockResolvedValue([{ id: 'app-acme', name: 'Acme App', repoPath: '/example/acme-app' }]);+ vi.mocked(triggerOnDemandTask).mockReset().mockImplementation(async (taskType) => ({ id: `demand-${taskType}` }));+ vi.mocked(runUntrustedContentAnalysis).mockResolvedValue({ ok: false, code: 'untrusted-content-blocked' });+ const alert = (id) => thread(id, { owner: 'acme', repo: 'app', reason: 'security_alert', type: 'RepositoryVulnerabilityAlert', url: null, title: 'Your repository has dependencies with security vulnerabilities' });+ mockGh(() => listing([+ thread('1201', { owner: 'acme', repo: 'app' }),+ thread('1202', { owner: 'acme', repo: 'app', commentUrl: 'https://api.github.com/repos/acme/app/issues/comments/9' }),+ // Its latest comment cannot be read, so it is not assumed to be yours.+ thread('1208', { owner: 'acme', repo: 'app', commentUrl: 'https://api.github.com/repos/acme/app/issues/comments/404' }),+ alert('1203'), alert('1204'), alert('1205'),+ thread('1206', { owner: 'acme', repo: 'app', reason: 'review_requested' }),+ thread('1207', { owner: 'acme', repo: 'app', reason: 'review_requested' }),+ ]), {+ 'repos/acme/app/pulls/1201': { author: account.login, association: 'OWNER', state: 'open', merged: false },+ 'repos/acme/app/pulls/1202': { author: account.login, association: 'OWNER', state: 'open', merged: false },+ 'repos/acme/app/pulls/1208': { author: account.login, association: 'OWNER', state: 'open', merged: false },+ 'repos/acme/app/issues/comments/9': { author: 'visitor', association: 'NONE', mentions: 0 },+ 'repos/acme/app/collaborators/visitor/permission': { user: { login: 'visitor' }, permission: 'read' },+ 'repos/acme/app/pulls/1206': { author: 'mallory', association: 'NONE', state: 'open', merged: false },+ 'repos/acme/app/pulls/1207': { author: 'mallory', association: 'NONE', state: 'open', merged: false },+ 'repos/acme/app/collaborators/mallory/permission': { user: { login: 'mallory' }, permission: 'read' },+ });++ expect((await syncAccountNotifications(account.id)).assist).toMatchObject({ handedOff: 5, agentRuns: 2 });+ // Three alerts make one dependency-updates run; two outside PRs make one+ // pr-reviewer sweep rather than a targeted run each.+ const calls = [...vi.mocked(triggerOnDemandTask).mock.calls].sort((a, b) => a[0].localeCompare(b[0]));+ expect(calls).toEqual([+ ['dependency-updates', 'app-acme', { origin: 'github-notification' }],+ ['pr-reviewer', 'app-acme', { origin: 'github-notification' }],+ ]);+ expect((await getNotification(account.id, '1204')).evidence.handoff).toMatchObject({ lane: 'dependency-updates', requestId: 'demand-dependency-updates', batchSize: 3 });+ // Your own PR waits for you only when someone outside commented on it.+ const needsYou = (await listNotifications({ accountId: account.id, view: 'needs-you' })).notifications.map((row) => row.threadId);+ expect(needsYou.sort()).toEqual(['1202', '1208']);+ const handled = (await listNotifications({ accountId: account.id, view: 'handled' })).notifications;+ // Autopilot includes Assist, which marks it done on GitHub.+ expect(handled.find((row) => row.threadId === '1201')).toMatchObject({ state: 'done', decision: 'handled-by-pr-workflow', rule: 'own-pr-in-managed-repo' });++ // A thread decided under older rules is decided again without new activity.+ await query(+ `UPDATE github_notifications SET state = 'open', decision = 'needs-you', evidence = evidence - 'rulesVersion' || '{"rule":"default"}'::jsonb+ WHERE account_id = $1 AND thread_id = '1201'`,+ [account.id],+ );+ await syncAccountNotifications(account.id);+ expect(await getNotification(account.id, '1201')).toMatchObject({ decision: 'handled-by-pr-workflow' });+ vi.mocked(getAllApps).mockResolvedValue([]);+ });++ it('resolves one thread with an agent on a tap in any mode, and refuses a repo PortOS does not manage', async () => {+ vi.mocked(getAllApps).mockResolvedValue([{ id: 'app-acme', name: 'Acme App', repoPath: '/example/acme-app' }]);+ vi.mocked(triggerOnDemandTask).mockReset().mockImplementation(async (taskType) => ({ id: `demand-${taskType}` }));+ mockGh(() => listing([+ thread('1301', { owner: 'acme', repo: 'app', reason: 'subscribed', type: 'Issue', url: 'https://api.github.com/repos/acme/app/issues/1301' }),+ thread('1302', { owner: 'someone', repo: 'other', reason: 'security_alert', type: 'RepositoryVulnerabilityAlert', url: null }),+ ]), {+ 'repos/acme/app/issues/1301': { author: 'visitor', association: 'NONE', state: 'open', merged: false },+ 'repos/acme/app/collaborators/visitor/permission': { user: { login: 'visitor' }, permission: 'read' },+ });+ await syncAccountNotifications(account.id);+ const listed = (await listNotifications({ accountId: account.id, view: 'needs-you' })).notifications;+ expect(Object.fromEntries(listed.map((row) => [row.threadId, row.agent]))).toEqual({+ 1301: { lane: 'issue-watcher', refused: null },+ 1302: { lane: 'dependency-updates', refused: 'no-managed-app' },+ });+ expect(triggerOnDemandTask).not.toHaveBeenCalled();++ expect(await resolveWithAgent(account.id, '1301')).toMatchObject({ decision: 'handed-off', agent: null });+ expect(triggerOnDemandTask).toHaveBeenCalledWith('issue-watcher', 'app-acme', { origin: 'user' });+ expect((await getNotification(account.id, '1301')).events.find((event) => event.kind === 'handed-off')).toMatchObject({ actor: 'operator' });+ await expect(resolveWithAgent(account.id, '1302')).rejects.toMatchObject({ status: 409 });+ expect(triggerOnDemandTask).toHaveBeenCalledTimes(1);+ vi.mocked(getAllApps).mockResolvedValue([]);+ });+it('sends the opt-in monthly audit report once per window, as suggestions only', async () => {await updateAccount(account.id, { auditReport: true });const recent = new Date(Date.now() - 86_400_000).toISOString();diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.jsindex 550fe605be..3243529af1 100644--- a/server/services/githubNotifications.js+++ b/server/services/githubNotifications.js@@ -23,7 +23,7 @@ import { getAccount, listAccounts, resolveGitHubAccountEnv } from './githubAccouimport { githubNotificationEvents } from './githubNotificationEvents.js';import { triageAccountNotifications } from './githubNotificationTriage.js';import { assistAccountNotifications } from './githubNotificationAssist.js';-import { learnedDecisionForAction } from '../lib/githubNotificationTriage.js';+import { agentHandoff, HANDLED_DECISIONS, learnedDecisionForAction } from '../lib/githubNotificationTriage.js';import { toPgJson } from '../lib/pgJson.js';const GH_TIMEOUT_MS = 30_000;@@ -123,11 +123,11 @@ async function recordSyncError(accountId, message) {async function runAutomation(account, env) {const autopilot = account.mode === 'autopilot'? await (await import('./githubNotificationAutopilot.js')).autopilotAccountNotifications(account)- : { handedOff: 0 };+ : { handedOff: 0, agentRuns: 0 };const assist = await assistAccountNotifications(account, env, {act: (threadId, action, detail) => applyNotificationAction(account.id, threadId, action, { actor: 'automation', detail }),});- return { ...assist, handedOff: autopilot.handedOff };+ return { ...assist, handedOff: autopilot.handedOff, agentRuns: autopilot.agentRuns };}async function syncAccountNow(account) {@@ -204,15 +204,24 @@ export async function syncAllNotifications() {return results;}+// A thread with nothing left for you (something else has it, or it is closed+// or merged) is Handled while it is still open on GitHub.+const HANDLED_SQL = `decision IN (${HANDLED_DECISIONS.map((decision) => `'${decision}'`).join(', ')})`;const VIEW_FILTERS = {- 'needs-you': "state = 'open' AND NOT suspect",+ 'needs-you': `state = 'open' AND NOT suspect AND (decision IS NULL OR NOT ${HANDLED_SQL})`,suspect: "state = 'open' AND suspect",- handled: "state <> 'open'",+ handled: `(state <> 'open' OR (NOT suspect AND ${HANDLED_SQL}))`,all: 'TRUE',};const toIso = (value) => (value instanceof Date ? value.toISOString() : value);+// The lane Resolve with agent would use, and why it cannot when refused.+const agentView = (account, row) => {+ const plan = account ? agentHandoff({ account, row }) : null;+ return plan ? { lane: plan.lane, refused: plan.refused || null } : null;+};+const toApi = (row, accountsById) => {const account = accountsById.get(row.account_id);const login = account?.login?.toLowerCase();@@ -233,6 +242,7 @@ const toApi = (row, accountsById) => {suspect: row.suspect === true,rule: row.evidence?.rule || null,signals: Array.isArray(row.evidence?.signals) ? row.evidence.signals : [],+ agent: agentView(account, row),updatedAt: toIso(row.gh_updated_at),};};@@ -448,7 +458,8 @@ export function describeScheduledCheck(results) {const parts = [`checked ${checked.length} of ${results.length} account(s)`, `${fetched} new or updated`, `${triaged} triaged`];const handedOff = checked.reduce((sum, result) => sum + (result.assist?.handedOff || 0), 0);if (acted) parts.push(`${acted} handled`);- if (handedOff) parts.push(`${handedOff} handed off`);+ const agentRuns = checked.reduce((sum, result) => sum + (result.assist?.agentRuns || 0), 0);+ if (handedOff) parts.push(`${handedOff} handed off in ${agentRuns} agent run(s)`);if (failed) parts.push(`${failed} failed`);return parts.join(', ');}@@ -511,3 +522,13 @@ export async function setNotificationCadence(cadence) {: { type: 'on-demand', cronExpression: null, enabled: true });return getAutomationsOverview();}++/** Resolve with agent: hand one thread to its lane now, then return it. */+export async function resolveWithAgent(accountId, threadId) {+ const account = await getAccount(accountId);+ const { handOffThread } = await import('./githubNotificationAutopilot.js');+ await handOffThread(account, threadId);+ const row = (await query('SELECT * FROM github_notifications WHERE account_id = $1 AND thread_id = $2', [account.id, threadId])).rows[0];+ githubNotificationEvents.emit('changed', { accountId: account.id });+ return toApi(row, new Map([[account.id, account]]));+}