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
Add GitHub notifications Autopilot and a monthly audit report (#12909)
[._.]/6684eb50a5de
diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsxindex 86a3ba45cc..daab6b947e 100644--- a/client/src/components/NotificationDropdown.jsx+++ b/client/src/components/NotificationDropdown.jsx@@ -1,7 +1,7 @@import { useState, useRef, useEffect } from 'react';import { createPortal } from 'react-dom';import { useNavigate } from 'react-router';-import { Bell, X, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code, HelpCircle, BellRing, Film, Sparkles, AlarmClock, Share2 } from 'lucide-react';+import { Bell, X, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code, HelpCircle, BellRing, Film, Sparkles, AlarmClock, Share2, GitPullRequest } from 'lucide-react';import { timeAgo, formatCount } from '../utils/formatters';import { useActionQueue } from '../hooks/useActionQueue';import ActionQueuePreview from './ActionQueuePreview';@@ -65,6 +65,11 @@ const NOTIFICATION_TYPE_CONFIG = {icon: Share2,color: 'text-orange-400',bgColor: 'bg-orange-500/20'+ },+ github_audit: {+ icon: GitPullRequest,+ color: 'text-gray-300',+ bgColor: 'bg-gray-500/20'}};diff --git a/client/src/components/github/GitHubAuditTab.jsx b/client/src/components/github/GitHubAuditTab.jsxindex b623e70729..88f897bc16 100644--- a/client/src/components/github/GitHubAuditTab.jsx+++ b/client/src/components/github/GitHubAuditTab.jsx@@ -12,6 +12,7 @@ import {getGitHubAuditChanges,runGitHubAudit,undoGitHubAuditChange,+ updateGitHubAccount,} from '../../services/api';const fetchAccounts = () => getGitHubAccounts({ silent: true });@@ -62,7 +63,7 @@ function SuggestionCard({ suggestion, onApply, onSkip, applying }) {export default function GitHubAuditTab() {const [searchParams, setSearchParams] = useSearchParams();- const { items: accounts, state: accountsState, error: accountsError, retry } = useListResource(fetchAccounts);+ const { items: accounts, state: accountsState, error: accountsError, retry, setItems: setAccounts } = useListResource(fetchAccounts);const accountId = searchParams.get('account') || accounts[0]?.id || null;const [audit, setAudit] = useState(null);const [running, setRunning] = useState(false);@@ -70,6 +71,7 @@ export default function GitHubAuditTab() {const [applyingId, setApplyingId] = useState(null);const [changes, setChanges] = useState([]);const [undoingId, setUndoingId] = useState(null);+ const [savingReport, setSavingReport] = useState(false);const loadChanges = useCallback(async () => {const result = await getGitHubAuditChanges({ silent: true }).catch(() => null);@@ -106,6 +108,13 @@ export default function GitHubAuditTab() {await loadChanges();};+ const setMonthlyReport = async (auditReport) => {+ setSavingReport(true);+ const saved = await updateGitHubAccount(accountId, { auditReport }).catch(() => null);+ setSavingReport(false);+ if (saved) setAccounts((prev) => prev.map((account) => (account.id === saved.id ? saved : account)));+ };+const undo = async (id) => {setUndoingId(id);const undone = await undoGitHubAuditChange(id).catch(() => null);@@ -124,6 +133,7 @@ export default function GitHubAuditTab() {}const visible = audit?.suggestions.filter((suggestion) => !skipped.has(suggestion.id)) || [];+ const selected = accounts.find((account) => account.id === accountId);return (<div className="min-w-0 space-y-4">@@ -157,6 +167,17 @@ export default function GitHubAuditTab() {)}{audit && !audit.watchedListed && <p className="text-xs text-port-warning">GitHub did not list your watched repos, so there are no unwatch suggestions this time.</p>}{!audit && !running && <p className="text-xs text-gray-500">Nothing changes until you tap Apply on a suggestion.</p>}+ <div className="flex items-center gap-2">+ <input+ id="github-audit-monthly"+ type="checkbox"+ checked={selected?.auditReport === true}+ disabled={savingReport || !selected}+ onChange={(event) => setMonthlyReport(event.target.checked)}+ className="h-4 w-4 accent-port-accent"+ />+ <label htmlFor="github-audit-monthly" className="text-xs text-gray-300">Send me this audit monthly as a notification (needs the scheduled check on)</label>+ </div></section>{audit && (visible.length ? (diff --git a/client/src/components/github/GitHubAutomationsTab.jsx b/client/src/components/github/GitHubAutomationsTab.jsxindex 242533e7eb..47aa581e44 100644--- a/client/src/components/github/GitHubAutomationsTab.jsx+++ b/client/src/components/github/GitHubAutomationsTab.jsx@@ -18,15 +18,20 @@ import {} from '../../services/api';import { ACTION_LABELS, LEARNED_DECISION_LABELS } from './githubTriageLabels';-const MODE_OPTIONS = ['observe', 'assist'];+const MODE_OPTIONS = ['observe', 'assist', 'autopilot'];const MODE_LABELS = { observe: 'Observe', assist: 'Assist', autopilot: 'Autopilot' };function modeHint(account) {- if (account.mode !== 'assist') return 'Records a decision for each notification; changes nothing on GitHub.';+ if (account.mode === 'observe') return 'Records a decision for each notification; changes nothing on GitHub.';const where = account.trust === 'private'? 'Text goes only to local AI providers unless you allow others in Accounts.': 'Text goes to the GitHub notifications provider in Models › LLMs › Abuse Guard.';- return `Screens and sorts notifications no rule decided, marks CI noise done and closed threads read. Never acts on outside or suspect threads. ${where}`;+ const assist = `Screens and sorts notifications no rule decided, marks CI noise done and closed threads read. Never acts on outside or suspect threads. ${where}`;+ if (account.mode !== 'autopilot') return assist;+ const handoff = account.trust === 'private'+ ? 'Private accounts never hand threads off.'+ : 'Also hands outside review requests and issues in your PortOS apps to Untrusted:Review and the issue watcher, when those are on for the app. Nothing outside your apps is ever started.';+ return `${assist} ${handoff}`;}const CADENCE_TEXT = {@@ -78,7 +83,7 @@ function AccountCard({ account, running, onRun, onMode, savingMode }) {}function ActivityList({ actions, onUndo, undoingId }) {- if (!actions.length) return <p className="text-xs text-gray-500">Assist has not acted on anything yet.</p>;+ if (!actions.length) return <p className="text-xs text-gray-500">Assist and Autopilot have not acted on anything yet.</p>;return (<ul className="divide-y divide-port-border">{actions.map((action) => (diff --git a/client/src/components/github/GitHubThreadDrawer.jsx b/client/src/components/github/GitHubThreadDrawer.jsxindex 5b37e7ed4b..6ceaeea16b 100644--- a/client/src/components/github/GitHubThreadDrawer.jsx+++ b/client/src/components/github/GitHubThreadDrawer.jsx@@ -1,12 +1,12 @@import { useEffect, useState } from 'react';-import { useNavigate } from 'react-router';+import { Link, useNavigate } from 'react-router';import { ExternalLink } from 'lucide-react';import Drawer from '../Drawer';import Pill from '../ui/Pill';import { formatDateTime } from '../../utils/formatters';import { getGitHubNotification } from '../../services/api';import socket from '../../services/socket';-import { AI_SKIP_LABELS, DECISION_VIEW, RULE_LABELS, SIGNAL_LABELS, TRUST_VIEW } from './githubTriageLabels';+import { AI_SKIP_LABELS, DECISION_VIEW, HANDOFF_SKIP_LABELS, LANE_VIEW, RULE_LABELS, SIGNAL_LABELS, TRUST_VIEW } from './githubTriageLabels';const EVENT_LABELS = {triaged: 'Triaged',@@ -16,10 +16,12 @@ const EVENT_LABELS = {mute: 'Muted',unsubscribe: 'Unsubscribed',resubscribe: 'Resubscribed',+ 'handed-off': 'Handed off',};function describeEvent(event) {const label = EVENT_LABELS[event.kind] || event.kind;+ if (event.kind === 'handed-off') return `${label} to ${LANE_VIEW[event.detail?.lane]?.label || event.detail?.lane}`;if (event.kind !== 'triaged') return label;const decision = DECISION_VIEW[event.detail?.decision]?.label || 'Needs you';return `${label}: ${decision}${event.detail?.mode ? ` (${event.detail.mode})` : ''}`;@@ -27,9 +29,29 @@ function describeEvent(event) {const eventActorSuffix = (event) => {if (event.actor !== 'automation') return ' by you';- return event.kind === 'triaged' ? '' : ' by Assist';+ if (event.kind === 'triaged') return '';+ return event.kind === 'handed-off' ? ' by Autopilot' : ' by Assist';};+function HandoffLine({ handoff }) {+ const lane = LANE_VIEW[handoff.lane];+ if (handoff.skipped) {+ return (+ <p className="text-xs text-gray-400">+ Autopilot left it with you: {HANDOFF_SKIP_LABELS[handoff.skipped] || handoff.skipped}{handoff.error ? ` (${handoff.error})` : ''}+ </p>+ );+ }+ return (+ <p className="text-xs text-gray-300">+ {handoff.duplicate ? 'Already with ' : 'Handed to '}{lane?.label || handoff.lane}+ {handoff.appId && lane && (+ <> for <Link to={`/apps/${encodeURIComponent(handoff.appId)}/${lane.tab}`} className="text-port-accent">{handoff.appName || handoff.appId}</Link></>+ )}+ </p>+ );+}+/** One thread's triage evidence and action log, opened from the Inbox at /devtools/github/inbox/:accountId/:threadId. */export default function GitHubThreadDrawer({ accountId, threadId }) {const navigate = useNavigate();@@ -85,6 +107,7 @@ export default function GitHubThreadDrawer({ accountId, threadId }) {{evidence.commenter && <p className="text-xs text-gray-400">Latest comment by <span className="font-mono">@{evidence.commenter}</span></p>}{evidence.subjectState && <p className="text-xs text-gray-400">Thread is {evidence.subjectState}</p>}{evidence.foldedInto && <p className="text-xs text-gray-400">Same failure as a newer notice</p>}+ {evidence.handoff && <HandoffLine handoff={evidence.handoff} />}{evidence.ai?.skipped && <p className="text-xs text-gray-400">Assist did not sort it: {AI_SKIP_LABELS[evidence.ai.skipped] || 'screening or the provider failed'}</p>}{evidence.metadataMissing && <p className="text-xs text-port-warning">GitHub did not return the thread's details; decided from the notification alone.</p>}{current.signals.length > 0 && (diff --git a/client/src/components/github/githubTriageLabels.js b/client/src/components/github/githubTriageLabels.jsindex 39cc6bf1f7..06788f89a4 100644--- a/client/src/components/github/githubTriageLabels.js+++ b/client/src/components/github/githubTriageLabels.js@@ -11,6 +11,7 @@ export const DECISION_VIEW = {duplicate: { tone: 'muted', label: 'Duplicate' },'suggest-done': { tone: 'muted', label: 'Suggest done' },'suggest-mute': { tone: 'muted', label: 'Suggest mute' },+ 'handed-off': { tone: 'success', label: 'Handed off' },};export const TRUST_VIEW = {@@ -50,6 +51,20 @@ export const ACTION_LABELS = {done: 'Marked done',read: 'Marked read',mute: 'Muted',+ 'handed-off': 'Handed off',+};++// The lanes Autopilot hands threads to, and the app tab each one reports on.+export const LANE_VIEW = {+ 'pr-reviewer': { label: 'Untrusted:Review', tab: 'pull-requests' },+ 'issue-watcher': { label: 'the issue watcher', tab: 'tasks' },+};++// Why Autopilot left a thread with you instead of handing it off.+export const HANDOFF_SKIP_LABELS = {+ 'private-account': 'Private accounts never hand off: the lanes use their own AI providers',+ 'no-managed-app': 'No PortOS app manages this repo',+ 'lane-unavailable': 'The lane would not take it',};export const LEARNED_DECISION_LABELS = {diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsxindex 8309e7c780..76c241290c 100644--- a/client/src/pages/GitHub.test.jsx+++ b/client/src/pages/GitHub.test.jsx@@ -457,6 +457,18 @@ describe('GitHub inbox triage', () => {expect(screen.getByText('Triaged: Suspect (observe)')).toBeTruthy();expect(mock.getGitHubNotification).toHaveBeenCalledWith('github-com', '101', { silent: true });});++ it('shows which lane Autopilot handed a thread to, linked to its app', async () => {+ mock.getGitHubNotifications.mockResolvedValue({ notifications: [], sync: {} });+ mock.getGitHubNotification.mockResolvedValue({+ ...NOTIFICATION, decision: 'handed-off', trust: 'outside', suspect: false, signals: [],+ evidence: { rule: 'review-outside-author', actor: 'mallory', handoff: { lane: 'pr-reviewer', appId: 'app-acme', appName: 'Acme App', pullNumber: 101, requestId: 'demand-1' } },+ events: [{ actor: 'automation', kind: 'handed-off', detail: { lane: 'pr-reviewer', appId: 'app-acme' }, at: '2026-10-01T10:05:00.000Z' }],+ });+ renderTab('inbox/github-com/101');+ expect((await screen.findByRole('link', { name: 'Acme App' })).getAttribute('href')).toBe('/apps/app-acme/pull-requests');+ expect(screen.getByText('Handed off to Untrusted:Review by Autopilot')).toBeTruthy();+ });});describe('GitHub automations tab', () => {@@ -557,4 +569,14 @@ describe('GitHub audit tab', () => {expect(await screen.findByText('Undone')).toBeTruthy();expect(mock.undoGitHubAuditChange).toHaveBeenCalledWith('5');});++ it('turns on the monthly audit report for the selected account', async () => {+ mock.updateGitHubAccount.mockResolvedValue({ ...ACCOUNT, auditReport: true });+ renderTab('audit');+ const toggle = await screen.findByLabelText(/Send me this audit monthly/);+ expect(toggle.checked).toBe(false);+ fireEvent.click(toggle);+ await waitFor(() => expect(screen.getByLabelText(/Send me this audit monthly/).checked).toBe(true));+ expect(mock.updateGitHubAccount).toHaveBeenCalledWith('github-com', { auditReport: true });+ });});diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex ddc13c5547..79ebe67067 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -611,7 +611,7 @@ Optional SDK environments under `data/venvs/` are machine-local, regenerable run`data/github-accounts.json` is `file-primary`: the GitHub logins the notifications manager works with (#12869), one record per login on one host (github.com or a GitHub Enterprise Server hostname) with its operator-chosen trust level (`public` | `private`), allowed AI providers, automation mode and enabled flag. It is small machine-local configuration, like Messages accounts: no foreign keys, no cross-record queries, no search. It holds no credentials (`gh` keeps those) and is never federated, because which logins a machine is signed into is a property of that machine. With no file, the API shows one implicit github.com account so existing installs need no migration or `data.reference/` seed; the file is written on the first edit, and a stored empty list stays authoritative. Version 1; a malformed or other-version file is refused with 503 and left untouched. Rsync backups include it. Code: `server/services/githubAccounts.js`.-The notifications inbox (#12870) is `db-primary`: `github_notifications` holds one row per thread per account (repo, reason, subject title/type, a link rebuilt on the account's own host, unread flag, GitHub's `updated_at`, and the local `state` `open` | `done` | `muted` | `unsubscribed`), keyed `(account_id, thread_id)`; `github_notification_sync` holds each account's `Last-Modified` cursor, `X-Poll-Interval` and last error. The rows are queried by account, state and recency and later phases join triage results to them, so they live in Postgres. Like the accounts they describe they are machine-local and never federated. Only notification metadata is stored; no thread body or linked page is fetched. Triage (#12871) adds per-thread `decision`, `trust`, `suspect`, `evidence` (rule, spam signals, actor login, repo ownership; never body text) and `triaged_for` columns, plus `github_notification_events`, the per-thread log of operator actions and automation decisions. Assist mode (#12872) reads an undecided thread's own body and latest comment only to pass them through untrusted-content screening; the text is not stored, only the model's enum verdict (or the skip code) in `evidence.ai`. `github_notification_rules` holds rules learned from the operator's corrections, keyed `(account_id, repo_full_name, reason, actor)`. Code: `server/services/githubNotifications.js`, schema `server/lib/db/schema/githubNotifications.js`.+The notifications inbox (#12870) is `db-primary`: `github_notifications` holds one row per thread per account (repo, reason, subject title/type, a link rebuilt on the account's own host, unread flag, GitHub's `updated_at`, and the local `state` `open` | `done` | `muted` | `unsubscribed`), keyed `(account_id, thread_id)`; `github_notification_sync` holds each account's `Last-Modified` cursor, `X-Poll-Interval` and last error. The rows are queried by account, state and recency and later phases join triage results to them, so they live in Postgres. Like the accounts they describe they are machine-local and never federated. Only notification metadata is stored; no thread body or linked page is fetched. Triage (#12871) adds per-thread `decision`, `trust`, `suspect`, `evidence` (rule, spam signals, actor login, repo ownership; never body text) and `triaged_for` columns, plus `github_notification_events`, the per-thread log of operator actions and automation decisions. Assist mode (#12872) reads an undecided thread's own body and latest comment only to pass them through untrusted-content screening; the text is not stored, only the model's enum verdict (or the skip code) in `evidence.ai`. `github_notification_rules` holds rules learned from the operator's corrections, keyed `(account_id, repo_full_name, reason, actor)`. The subscription audit (#12873) logs each applied change in `github_notification_audit_changes` so it can be undone. Autopilot (#12874) records a hand-off (lane, app id, request id, or why it was skipped) in `evidence.handoff`, and `github_notification_audit_reports` holds when each account's opt-in monthly audit report last went out. Code: `server/services/githubNotifications.js`, schema `server/lib/db/schema/githubNotifications.js`.### Music Video cover letteringdiff --git a/server/lib/db/schema/githubNotifications.js b/server/lib/db/schema/githubNotifications.jsindex 888f8c258e..fa0f23532b 100644--- a/server/lib/db/schema/githubNotifications.js+++ b/server/lib/db/schema/githubNotifications.js@@ -80,4 +80,9 @@ export const githubNotificationsDdl = [applied_at TIMESTAMPTZ DEFAULT NOW(),undone_at TIMESTAMPTZ)`,+ // Monthly audit report (#12874): when each account's report last went out.+ `CREATE TABLE IF NOT EXISTS github_notification_audit_reports (+ account_id TEXT PRIMARY KEY,+ last_sent_at TIMESTAMPTZ NOT NULL+ )`,];diff --git a/server/lib/githubNotificationTriage.js b/server/lib/githubNotificationTriage.jsindex 1b057984b7..94e27e007a 100644--- a/server/lib/githubNotificationTriage.js+++ b/server/lib/githubNotificationTriage.js@@ -11,6 +11,8 @@* Assist mode (#12872) adds three inputs, none of which can raise trust:* a learned rule (the operator's own past correction), a model verdict from a* fixed enum, and the one automatic action `assistAction` allows.+ * Autopilot (#12874) only picks a lane with `autopilotHandoff`; the lane+ * re-screens its own input.*/import { isUntrustedContentProvider } from './untrustedContent.js';import { isLocalInstanceEndpoint } from './localEndpoint.js';@@ -27,6 +29,7 @@ export const TRIAGE_DECISIONS = Object.freeze(['duplicate','suggest-done','suggest-mute',+ 'handed-off',]);export const TRUST_LEVELS = Object.freeze(['yours', 'trusted', 'outside', 'unknown']);@@ -165,3 +168,30 @@ 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.+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.+ */+export function autopilotHandoff({ account, row }) {+ if (account?.mode !== 'autopilot' || 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' };+ }+ if (!plan) return null;+ return account.trust === 'private' ? { ...plan, refused: 'private-account' } : plan;+}diff --git a/server/lib/githubNotificationTriage.test.js b/server/lib/githubNotificationTriage.test.jsindex e5c3debf11..0fa82a1a91 100644--- a/server/lib/githubNotificationTriage.test.js+++ b/server/lib/githubNotificationTriage.test.js@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest';import {- applyLearnedRule, assistAction, computeThreadTrust, decideThread, decisionFromVerdict, parseCiBranch, selectNotificationProvider, spamSignals,+ applyLearnedRule, assistAction, autopilotHandoff, computeThreadTrust, decideThread, decisionFromVerdict, parseCiBranch,+ selectNotificationProvider, spamSignals,MASS_MENTION_THRESHOLD,} from './githubNotificationTriage.js';@@ -127,3 +128,30 @@ describe('selectNotificationProvider', () => {expect(selectNotificationProvider({ account: { trust: 'private', allowedProviders: ['cloud'] }, providers })).toEqual({ provider: cloud, model: 'large' });});});++describe('autopilotHandoff', () => {+ const account = { mode: 'autopilot', trust: 'public' };+ const review = {+ state: 'open', suspect: false, trust: 'outside', decision: 'suggest-untrusted-review', subject_type: 'PullRequest',+ subject_api_url: 'https://api.github.com/repos/acme/app/pulls/42', evidence: { repoManaged: true },+ };+ const issue = { ...review, decision: 'needs-you', subject_type: 'Issue', subject_api_url: 'https://api.github.com/repos/acme/app/issues/7' };++ it('hands outside review requests and issue activity in a managed repo to their lanes', () => {+ expect(autopilotHandoff({ account, row: review })).toEqual({ lane: 'pr-reviewer', pullNumber: 42 });+ expect(autopilotHandoff({ account, row: issue })).toEqual({ lane: 'issue-watcher' });+ });++ 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, 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.+ expect(autopilotHandoff({ account, row: { ...issue, trust: 'trusted' } })).toBeNull();+ });++ it('refuses every hand-off on a Private account, whose provider allow-list the lanes cannot honor', () => {+ expect(autopilotHandoff({ account: { ...account, trust: 'private' }, row: review })).toEqual({ lane: 'pr-reviewer', pullNumber: 42, refused: 'private-account' });+ });+});diff --git a/server/lib/notificationTypes.js b/server/lib/notificationTypes.jsindex 34afd3fd02..732b797420 100644--- a/server/lib/notificationTypes.js+++ b/server/lib/notificationTypes.js@@ -13,7 +13,8 @@ export const NOTIFICATION_CATALOG = {CREATIVE_COMMISSION: { key: 'creative_commission', label: 'Creative Commissions' },MUSIC_VIDEO_ATTENTION: { key: 'music_video_attention', label: 'Music Video Attention' },ACTION_DUE: { key: 'action_due', label: 'Scheduled Actions Due' },- SHARE_BLOCKED: { key: 'share_blocked', label: 'Blocked Shares' }+ SHARE_BLOCKED: { key: 'share_blocked', label: 'Blocked Shares' },+ GITHUB_AUDIT: { key: 'github_audit', label: 'GitHub Audit Reports' }};export const NOTIFICATION_TYPES = Object.fromEntries(diff --git a/server/lib/validation.js b/server/lib/validation.jsindex c826bd38eb..2302f01deb 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -961,6 +961,8 @@ export const githubAccountCreateSchema = z.object({// null = the trust level's default (Private: local providers only).allowedProviders: z.array(z.string().trim().min(1).max(128)).max(50).nullable().optional(),mode: z.enum(GITHUB_ACCOUNT_MODES).optional(),+ // Monthly subscription audit delivered as a PortOS notification (#12874).+ auditReport: z.boolean().optional(),enabled: z.boolean().optional(),}).strict();diff --git a/server/routes/apps/pullRequests.js b/server/routes/apps/pullRequests.jsindex 4c5ec667f1..3a3b335ad1 100644--- a/server/routes/apps/pullRequests.js+++ b/server/routes/apps/pullRequests.js@@ -36,7 +36,6 @@ import { claimSafeReviewers, normalizeReviewers, validateRequest } from '../../limport { PR_COMPLETIONS, isSelfReviewMode } from '../../lib/prDisposition.js';import { isTruthyMeta } from '../../services/agentState.js';import { resolveReviewLoopOptions } from '../../services/codeReview.js';-import { getAllTasks } from '../../services/cos.js';import { spawnReviewLoopFollowUp } from '../../services/agentWorktreeCleanup.js';import { listAppPullRequests } from '../../services/appPullRequests.js';import {@@ -48,10 +47,15 @@ import {import { isDoReviewTask, spawnPrDoReviewTask } from '../../services/prDoReviewTask.js';import {isReviewablePullRequest,- listExternalOpenPullRequests,resolvePrReviewerTargetScope,} from '../../services/prReviewerSecurity.js';-import { getOnDemandRequests, triggerOnDemandTask } from '../../services/taskSchedule.js';+import {+ ACTIVE_TASK_STATUSES,+ queueTargetedPrReview,+ readActiveTasks,+ readPendingOnDemandRequests,+ reviewActionFor,+} from '../../services/prReviewerTargetedRun.js';import { loadApp } from './shared.js';const router = Router();@@ -68,14 +72,6 @@ const pullRequestMergeSchema = z.object({deleteBranch: z.boolean().optional(),});-const ACTIVE_TASK_STATUSES = new Set(['pending', 'in_progress', 'blocked']);-const PR_REVIEWER_TASK_TYPE = 'pr-reviewer';--const flattenTasks = (taskData) => [- ...(Array.isArray(taskData?.user?.tasks) ? taskData.user.tasks : []),- ...(Array.isArray(taskData?.cos?.tasks) ? taskData.cos.tasks : []),-];-const isResolveTaskFor = (task, appId, pullRequest) => {const metadata = task?.metadata;return ACTIVE_TASK_STATUSES.has(task?.status)@@ -84,18 +80,6 @@ const isResolveTaskFor = (task, appId, pullRequest) => {&& Number(metadata.reviewLoopPRNumber) === pullRequest.number;};-// A pr-reviewer run narrowed to this one request (`targetPullRequest` is stamped-// by the generator's security preflight). The unnarrowed sweep is deliberately-// NOT matched: it covers every external PR, so reporting it as this row's action-// would hide the per-row trigger behind an unrelated run.-const isReviewTaskFor = (task, appId, pullRequest) => {- const metadata = task?.metadata;- return ACTIVE_TASK_STATUSES.has(task?.status)- && metadata?.analysisType === PR_REVIEWER_TASK_TYPE- && metadata?.app === appId- && Number(metadata.targetPullRequest) === pullRequest.number;-};-// A `/do:review` run pinned to this request. It shares `targetPullRequest` with// the pr-reviewer match above — one vocabulary for "this task targets PR #N" —// and `isDoReviewTask` is what tells the two apart.@@ -107,41 +91,6 @@ const isDoReviewTaskFor = (task, appId, pullRequest) => {&& Number(metadata.targetPullRequest) === pullRequest.number;};-const isReviewRequestFor = (request, appId, pullRequest) => (- request?.taskType === PR_REVIEWER_TASK_TYPE- && request?.appId === appId- && Number(request?.targetPullRequest) === pullRequest.number-);--async function readActiveTasks() {- const taskData = await getAllTasks().catch(err => {- console.error(`❌ app-pull-requests: could not read CoS tasks: ${err.message}`);- return null;- });- if (!Array.isArray(taskData?.user?.tasks) || !Array.isArray(taskData?.cos?.tasks)) {- if (taskData) console.error('❌ app-pull-requests: CoS task response had an invalid shape');- return null;- }- return flattenTasks(taskData);-}--// Queued on-demand requests that have not yet become tasks. A pr-reviewer run-// is queued through the on-demand lane, so without these a row would show no-// action at all between the click and the generator's next cycle — and a page-// refresh in that window would offer the button again.-//-// `null` means UNREADABLE, which is not the same as "nothing queued": collapsing-// the two would let the review route miss an existing request and queue a-// duplicate scan of the same public PR. The POST fails closed on it; the GET,-// which only paints a button, degrades to showing no queued action.-async function readPendingOnDemandRequests() {- const requests = await getOnDemandRequests().catch(err => {- console.error(`❌ app-pull-requests: could not read on-demand requests: ${err.message}`);- return null;- });- return Array.isArray(requests) ? requests : null;-}-// Per-row pr-reviewer eligibility, resolved from the SAME facts the security// preflight filters on. Without it the tab would paint a Review button on every// GitHub row, including the ones the route answers with 409 — an action that is@@ -182,18 +131,6 @@ function actionFor(pullRequest, tasks, appId, matches) {return task ? { taskId: task.id, status: task.status } : null;}-function reviewActionFor(pullRequest, tasks, requests, appId) {- const task = tasks?.find(candidate => isReviewTaskFor(candidate, appId, pullRequest));- if (task) return { taskId: task.id, status: task.status };- const queued = requests?.find(request => isReviewRequestFor(request, appId, pullRequest));- if (queued) return { taskId: null, status: 'pending' };- const failure = tasks?.findLast(candidate => candidate.status === 'completed'- && candidate.metadata?.analysisType === PR_REVIEWER_TASK_TYPE- && candidate.metadata?.app === appId- && Number(candidate.metadata?.targetPullRequest) === pullRequest.number);- return failure?.metadata?.preflightFailure ? { taskId: failure.id, status: 'failed', error: failure.metadata.note } : null;-}-const taskResponse = task => task ? {id: task.id,status: task.status,@@ -447,10 +384,8 @@ router.post('/:id/pull-requests/:number/merge', loadApp, asyncHandler(async (req// for itself which of the app's external PRs to sweep; a targeted request pins// it to the row the user pressed.//-// Eligibility is answered by the same reader the generator's security preflight-// uses, so the answer here is the answer there: GitHub only, open against the-// default branch, and opened by someone other than the signed-in gh account.-// Checking now turns "the run silently produced nothing an hour later" into an+// Eligibility and the duplicate check live in `queueTargetedPrReview`, shared+// with the GitHub notifications Autopilot hand-off. Checking now turns "the run silently produced nothing an hour later" into an// immediate, explained refusal.router.post('/:id/pull-requests/:number/review', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;@@ -461,65 +396,16 @@ router.post('/:id/pull-requests/:number/review', loadApp, asyncHandler(async (re// warning rather than honored, same as any other pr-reviewer pin.const { provider, model, effort } = validateRequest(pullRequestProviderOverrideSchema, req.body || {});- const target = await listExternalOpenPullRequests(app);- if (!target.ok) {- throw new ServerError('Could not read the reviewable pull requests for this app', {- status: 503,- code: 'FORGE_UNAVAILABLE',- context: { reason: target.code || 'security-scan-target-unavailable' },- });- }- const pullRequest = target.prs.find(candidate => candidate.number === number);- if (!pullRequest) {- throw new ServerError(- `Pull request #${number} is not reviewable — PR review covers open GitHub pull requests against the default branch from an untrusted contributor`,- { status: 409, code: 'PULL_REQUEST_NOT_REVIEWABLE' },- );- }- // The security scan fingerprints the PR set by head commit, and the reader- // normalizes an unusable `headRefOid` to null. Accepting one anyway would- // return 202 for a run the preflight then drops on a null fingerprint — the UI- // would show a queued review that can never start.- if (!pullRequest.headRefOid) {- throw new ServerError(- `Pull request #${number} has no resolvable head commit, so its content cannot be safety-screened`,- { status: 502, code: 'PULL_REQUEST_CONTEXT_UNAVAILABLE' },- );- }-- const [tasks, requests] = await Promise.all([readActiveTasks(), readPendingOnDemandRequests()]);- // Fail CLOSED on unreadable task or on-demand state, matching /resolve:- // `reviewActionFor` reads either as "no run in flight", so queueing anyway would- // spend a second model-abuse scan and code review on a public PR already being- // reviewed.- if (tasks === null || requests === null) {- throw new ServerError('Could not inspect existing CoS actions before queueing this review', {- status: 503,- code: 'AGENT_ACTION_UNAVAILABLE',- });- }- const existing = reviewActionFor({ number }, tasks, requests, app.id);- if (existing && existing.status !== 'failed') {- res.json({ appId: app.id, appName: app.name, number, reviewAction: existing, duplicate: true });+ const queued = await queueTargetedPrReview(app, number, { provider, model, effort });+ if (queued.duplicate) {+ res.json({ appId: app.id, appName: app.name, number, reviewAction: queued.reviewAction, duplicate: true });return;}-- const request = await triggerOnDemandTask(PR_REVIEWER_TASK_TYPE, app.id, {- targetPullRequest: number,- provider,- model,- effort,- });- if (request?.error) {- throw new ServerError(request.error, { status: 409, code: 'PR_REVIEWER_UNAVAILABLE' });- }-- console.log(`🔍 Queued pr-reviewer request ${request.id} for app ${app.id} request #${number}`);res.status(202).json({appId: app.id,appName: app.name,number,- requestId: request.id,+ requestId: queued.request.id,reviewAction: { taskId: null, status: 'pending' },duplicate: false,});diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 22b106f1ab..4b907f239e 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1998,6 +1998,12 @@ CREATE TABLE IF NOT EXISTS github_notification_audit_changes (undone_at TIMESTAMPTZ);+-- Monthly audit report (#12874): when each account's report last went out.+CREATE TABLE IF NOT EXISTS github_notification_audit_reports (+ account_id TEXT PRIMARY KEY,+ last_sent_at TIMESTAMPTZ NOT NULL+);+-- Beeper conversation mirror (#27). Machine-local mirror of the Beeper Desktop-- API — accounts, conversations, messages, participants, attachment metadata,-- and per-chat sync cursors. NEVER FEDERATED: no sync_sequence column, nodiff --git a/server/services/githubAccounts.js b/server/services/githubAccounts.jsindex c3db512909..d02e6c3109 100644--- a/server/services/githubAccounts.js+++ b/server/services/githubAccounts.js@@ -46,6 +46,7 @@ const storedAccountSchema = z.object({trust: z.enum(GITHUB_ACCOUNT_TRUST_LEVELS),allowedProviders: z.array(z.string()).nullable(),mode: z.enum(GITHUB_ACCOUNT_MODES),+ auditReport: z.boolean().optional(),enabled: z.boolean(),createdAt: z.string(),updatedAt: z.string(),@@ -60,6 +61,7 @@ const implicitAccount = () => ({trust: 'public',allowedProviders: null,mode: 'observe',+ auditReport: false,enabled: true,createdAt: null,updatedAt: null,@@ -128,6 +130,7 @@ export function createAccount(input) {trust: data.trust || defaultTrustForHost(data.host),allowedProviders: data.allowedProviders ?? null,mode: data.mode || 'observe',+ auditReport: data.auditReport ?? false,enabled: data.enabled ?? true,createdAt: now,updatedAt: now,diff --git a/server/services/githubNotificationAssist.js b/server/services/githubNotificationAssist.jsindex abaff359a4..e26108f00c 100644--- a/server/services/githubNotificationAssist.js+++ b/server/services/githubNotificationAssist.js@@ -1,6 +1,6 @@/*** Assist mode for the GitHub notifications inbox (#12872). Runs after triage,- * only for an account the operator switched to Assist, so no model is called+ * only for an account the operator switched to Assist or Autopilot, so no model is called* before that choice.** Two steps:@@ -27,7 +27,8 @@ const GH_TIMEOUT_MS = 20_000;// Each sort is one screened model call; the rest wait for the next run.const MAX_SORTS_PER_RUN = 10;const MAX_ACTIONS_PER_RUN = 50;-const ASSIST_MODES = new Set(['assist']);+// Autopilot includes everything Assist does.+const ASSIST_MODES = new Set(['assist', 'autopilot']);const ACTIONABLE_DECISIONS = ['handled-by-pr-workflow', 'suggest-mark-read', 'suggest-done', 'suggest-mute'];// A skipped sort is retried an hour later (a provider added, a timeout), except// when the text itself was refused; new activity re-triages either way.diff --git a/server/services/githubNotificationAudit.js b/server/services/githubNotificationAudit.jsindex 8cad2f0a77..1fde03e0d4 100644--- a/server/services/githubNotificationAudit.js+++ b/server/services/githubNotificationAudit.js@@ -3,7 +3,8 @@* last 30 days of stored threads with what was done about them, and offer* one-tap changes (unwatch a repo, mute its handled threads) plus links for* settings the API cannot change. Nothing is applied without a tap, and every- * applied change is logged with Undo.+ * applied change is logged with Undo. Accounts can opt in to a monthly report+ * of the same suggestions as a PortOS notification.*/import { query } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';@@ -12,8 +13,10 @@ import { toPgJson } from '../lib/pgJson.js';import { execGh } from './github.js';import { getAccount, listAccounts, resolveGitHubAccountEnv } from './githubAccounts.js';import { applyNotificationAction } from './githubNotifications.js';+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';const GH_TIMEOUT_MS = 30_000;+const REPORT_EVERY_MS = AUDIT_WINDOW_DAYS * 24 * 60 * 60 * 1000;const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;// The last audit per account. Rebuilt by running the audit again; it holds@@ -172,3 +175,46 @@ export async function undoAuditChange(id) {await query('UPDATE github_notification_audit_changes SET undone_at = NOW() WHERE id = $1', [id]);return { id: String(id), undone: true };}++/**+ * The optional monthly report (#12874): for each enabled account that opted+ * in, run the audit at most once per audit window and send its open+ * suggestions as a PortOS notification. It only suggests; applying still+ * takes a tap on the Audit tab. A report with no suggestions sends nothing.+ */+export async function sendDueAuditReports({ now = Date.now() } = {}) {+ const accounts = (await listAccounts()).filter((account) => account.enabled && account.auditReport === true);+ if (!accounts.length) return [];+ const { rows } = await query(+ 'SELECT account_id, last_sent_at FROM github_notification_audit_reports WHERE account_id = ANY($1::text[])',+ [accounts.map((account) => account.id)],+ );+ const lastSent = new Map(rows.map((row) => [row.account_id, new Date(row.last_sent_at).getTime()]));+ const results = [];+ for (const account of accounts) {+ if (now - (lastSent.get(account.id) ?? 0) < REPORT_EVERY_MS) continue;+ const audit = await runAccountAudit(account.id).catch((error) => {+ console.log(`⏭️ Monthly GitHub audit for ${account.host} skipped: ${error.message}`);+ return null;+ });+ if (!audit) continue;+ const open = audit.suggestions.filter((suggestion) => !suggestion.applied);+ if (open.length) {+ await addNotification({+ type: NOTIFICATION_TYPES.GITHUB_AUDIT,+ title: `GitHub audit: ${open.length} suggestion${open.length === 1 ? '' : 's'} for ${account.label}`,+ description: `From the last ${audit.windowDays} days of notifications. Nothing changes until you tap Apply.`,+ priority: PRIORITY_LEVELS.LOW,+ link: `/devtools/github/audit?account=${encodeURIComponent(account.id)}`,+ metadata: { accountId: account.id },+ });+ }+ await query(+ `INSERT INTO github_notification_audit_reports (account_id, last_sent_at) VALUES ($1, $2)+ ON CONFLICT (account_id) DO UPDATE SET last_sent_at = EXCLUDED.last_sent_at`,+ [account.id, new Date(now).toISOString()],+ );+ results.push({ accountId: account.id, suggestions: open.length });+ }+ return results;+}diff --git a/server/services/githubNotificationAutopilot.js b/server/services/githubNotificationAutopilot.jsnew file mode 100644index 0000000000..d4cb80869a--- /dev/null+++ b/server/services/githubNotificationAutopilot.js@@ -0,0 +1,111 @@+/**+ * Autopilot mode for the GitHub notifications inbox (#12874). After triage and+ * 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`.+ *+ * 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+ * on-demand origin is automated, so the lane must be switched on for that app.+ * 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 { 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+// 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)))`;++/** Queue the app's issue-watcher run unless one is already queued or running. */+async function queueIssueWatcher(app) {+ 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.+ 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);+ 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 });+ 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 })+ .then((queued) => (queued.duplicate ? { duplicate: true, taskId: queued.reviewAction?.taskId || null } : { requestId: queued.request.id }));+}++async function recordHandoff(account, row, handoff) {+ await withTransaction(async (client) => {+ await client.query(+ `UPDATE github_notifications SET decision = CASE WHEN $3::boolean THEN 'handed-off' ELSE decision END,+ evidence = evidence || jsonb_build_object('handoff', $4::jsonb), updated_at = NOW()+ WHERE account_id = $1 AND thread_id = $2`,+ [account.id, row.thread_id, !handoff.skipped, toPgJson(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 })],+ );+ }+ });+}++/**+ * 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.+ */+export async function autopilotAccountNotifications(account) {+ if (account.mode !== 'autopilot') return { handedOff: 0 };+ const { rows } = await query(+ `SELECT * FROM github_notifications WHERE account_id = $1 AND state = 'open' AND NOT suspect+ AND ${CANDIDATE_SQL} AND (evidence->>'repoManaged')::boolean IS TRUE AND NOT (evidence ? 'handoff')+ ORDER BY gh_updated_at DESC LIMIT ${MAX_HANDOFFS_PER_RUN}`,+ [account.id],+ );+ const plans = rows.map((row) => ({ row, plan: autopilotHandoff({ account, row }) })).filter((entry) => entry.plan);+ if (!plans.length) return { handedOff: 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 handoff = {+ lane: plan.lane,+ appId: app?.id || null,+ appName: app?.name || null,+ ...(plan.pullNumber ? { pullNumber: plan.pullNumber } : {}),+ ...outcome,+ at: new Date().toISOString(),+ };+ await recordHandoff(account, row, handoff);+ if (handoff.skipped) {+ 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}`);+ }+ }+ return { handedOff };+}diff --git a/server/services/githubNotificationTriage.js b/server/services/githubNotificationTriage.jsindex b0b7504195..4060049769 100644--- a/server/services/githubNotificationTriage.js+++ b/server/services/githubNotificationTriage.js@@ -31,19 +31,21 @@ const COMMENT_JQ = '{author: .user.login, association: .author_association, mentconst loginOrNull = (value) => (typeof value === 'string' && LOGIN_RE.test(value) ? value : null);-/** Repos of PortOS managed apps, as lower-cased `host/owner/repo`. */-async function managedRepoKeys() {+/** PortOS managed apps keyed by their repo, as lower-cased `host/owner/repo`. */+export async function managedAppsByRepoKey() {const { getAllApps } = await import('./apps.js');const apps = await getAllApps({ includeArchived: false }).catch(() => []);- const keys = new Set();+ const byKey = new Map();for (const app of apps) {if (!app.repoPath) continue;const parsed = parseGitRemoteUrl(await readOriginRemoteUrl(app.repoPath).catch(() => null));- if (parsed) keys.add(`${parsed.host}/${parsed.owner}/${parsed.repo}`.toLowerCase());+ if (parsed) byKey.set(`${parsed.host}/${parsed.owner}/${parsed.repo}`.toLowerCase(), app);}- return keys;+ return byKey;}+const managedRepoKeys = async () => new Set((await managedAppsByRepoKey()).keys());+/** Per-run, per-account reader that caches each forge answer once. */function createReader(account, env) {const host = account.host;diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex a15f8f5391..ef8b38c1e6 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -21,8 +21,26 @@ vi.mock('./github.js', async (importOriginal) => ({ ...(await importOriginal()),vi.mock('./apps.js', () => ({ getAllApps: vi.fn(async () => []) }));// Assist's model boundary: the screened, tool-free analysis call.vi.mock('./untrustedContent.js', () => ({ runUntrustedContentAnalysis: vi.fn() }));+// Autopilot's boundaries: a managed app's origin remote, and the lanes' own+// on-demand entry points (the pr-reviewer target reader and the task queue).+vi.mock('../lib/gitRemote.js', async (importOriginal) => ({+ ...(await importOriginal()),+ readOriginRemoteUrl: vi.fn(async (repoPath) => (repoPath === '/example/acme-app' ? 'https://github.com/acme/app.git' : null)),+}));+vi.mock('./prReviewerSecurity.js', () => ({ listExternalOpenPullRequests: vi.fn() }));+vi.mock('./cos.js', () => ({ getAllTasks: vi.fn(async () => ({ user: { tasks: [] }, cos: { tasks: [] } })) }));+vi.mock('./taskSchedule.js', () => ({ triggerOnDemandTask: vi.fn(), getOnDemandRequests: vi.fn(async () => []) }));+vi.mock('./notifications.js', () => ({+ addNotification: vi.fn(async () => ({})),+ NOTIFICATION_TYPES: { GITHUB_AUDIT: 'github_audit' },+ PRIORITY_LEVELS: { LOW: 'low' },+}));const { execGh } = await import('./github.js');+const { getAllApps } = await import('./apps.js');+const { listExternalOpenPullRequests } = await import('./prReviewerSecurity.js');+const { triggerOnDemandTask } = await import('./taskSchedule.js');+const { addNotification } = await import('./notifications.js');const { runUntrustedContentAnalysis } = await import('./untrustedContent.js');const { createAccount, updateAccount } = await import('./githubAccounts.js');const {@@ -30,7 +48,7 @@ const {listAutomationActivity, undoAutomationAction, listLearnedRules,} = await import('./githubNotifications.js');const { buildTaskInput } = await import('./githubNotificationsHooks.js');-const { runAccountAudit, applyAuditSuggestion, listAuditChanges, undoAuditChange } = await import('./githubNotificationAudit.js');+const { runAccountAudit, applyAuditSuggestion, listAuditChanges, undoAuditChange, sendDueAuditReports } = await import('./githubNotificationAudit.js');let dbReady = false;let skipReason = '';@@ -98,6 +116,7 @@ afterAll(async () => {await query('DELETE FROM github_notification_events WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});await query('DELETE FROM github_notification_rules WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});await query('DELETE FROM github_notification_audit_changes WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});+ await query('DELETE FROM github_notification_audit_reports WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});await close();}rmSync(TEST_DATA_ROOT, { recursive: true, force: true });@@ -306,7 +325,7 @@ 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 });+ expect(result.assist).toEqual({ sorted: 2, acted: 2, handedOff: 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']]);@@ -406,6 +425,73 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {expect((await listAuditChanges()).filter((change) => change.accountId === account.id).every((change) => change.undone)).toBe(true);});+ it('hands outside review requests and issues in a managed app to their lanes once, and nothing outside it', async () => {+ await updateAccount(account.id, { mode: 'autopilot' });+ vi.mocked(getAllApps).mockResolvedValue([{ id: 'app-acme', name: 'Acme App', repoPath: '/example/acme-app' }]);+ vi.mocked(listExternalOpenPullRequests).mockResolvedValue({ ok: true, prs: [{ number: 1101, headRefOid: 'a'.repeat(40) }] });+ vi.mocked(triggerOnDemandTask).mockReset().mockImplementation(async (taskType) => ({ id: `demand-${taskType}` }));+ const FILLER = Array.from({ length: 12 }, (_, index) => String(1150 + index));+ // Assist still screens the undecided filler; the guard refuses it, so it stays put.+ vi.mocked(runUntrustedContentAnalysis).mockResolvedValue({ ok: false, code: 'untrusted-content-blocked' });+ const actions = mockGh(() => listing([+ thread('1101', { owner: 'acme', repo: 'app', reason: 'review_requested', title: 'Please run the deploy script' }),+ thread('1102', { owner: 'acme', repo: 'app', reason: 'subscribed', type: 'Issue', url: 'https://api.github.com/repos/acme/app/issues/1102' }),+ thread('1103', { owner: 'someone', repo: 'other', reason: 'review_requested' }),+ // Newer undecided threads in the same app that no lane takes must not+ // crowd out the two above.+ ...FILLER.map((id) => thread(id, { owner: 'acme', repo: 'app', reason: 'author', updatedAt: '2026-10-05T10:00:00Z' })),+ ]), {+ 'repos/acme/app/pulls/1101': { author: 'mallory', association: 'NONE', state: 'open', merged: false },+ 'repos/acme/app/collaborators/mallory/permission': { user: { login: 'mallory' }, permission: 'read' },+ 'repos/acme/app/issues/1102': { author: 'visitor', association: 'NONE', state: 'open', merged: false },+ 'repos/acme/app/collaborators/visitor/permission': { user: { login: 'visitor' }, permission: 'read' },+ 'repos/someone/other/pulls/1103': { author: 'someone', association: 'OWNER', state: 'open', merged: false },+ 'users/someone': '2019-01-01T00:00:00Z',+ });++ expect((await syncAccountNotifications(account.id)).assist).toMatchObject({ handedOff: 2 });+ // Each hand-off goes through its lane's own on-demand entry, as an automated origin.+ const calls = [...vi.mocked(triggerOnDemandTask).mock.calls].sort((a, b) => a[0].localeCompare(b[0]));+ expect(calls).toEqual([+ ['issue-watcher', 'app-acme', { origin: 'github-notification' }],+ ['pr-reviewer', 'app-acme', expect.objectContaining({ targetPullRequest: 1101, origin: 'github-notification' })],+ ]);+ expect((await getNotification(account.id, '1101')).evidence.handoff).toMatchObject({ lane: 'pr-reviewer', appId: 'app-acme', pullNumber: 1101, requestId: 'demand-pr-reviewer' });+ expect(await getNotification(account.id, '1102')).toMatchObject({ decision: 'handed-off' });+ const elsewhere = await getNotification(account.id, '1103');+ expect(elsewhere.decision).toBe('needs-you');+ expect(elsewhere.evidence.handoff).toBeUndefined();+ // The handed-off threads never reach a model, nothing is written to GitHub,+ // and nothing is handed off again on the next run.+ const screened = vi.mocked(runUntrustedContentAnalysis).mock.calls.map(([input]) => JSON.parse(input.content).title);+ expect(screened.filter((title) => !/^Thread 11[56]\d$/.test(title))).toEqual([]);+ expect(actions).toEqual([]);+ await syncAccountNotifications(account.id);+ expect(triggerOnDemandTask).toHaveBeenCalledTimes(2);+ const activity = (await listAutomationActivity()).filter((entry) => entry.accountId === account.id);+ expect(activity.map((entry) => [entry.threadId, entry.action, entry.undoable]).sort()).toEqual([['1101', 'handed-off', false], ['1102', 'handed-off', false]]);+ 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();+ const actions = mockGh(() => listing(['1201', '1202', '1203', '1204', '1205'].map((id) => thread(id, { owner: 'acme', repo: 'noisy', reason: 'subscribed', updatedAt: recent }))), {+ 'user/subscriptions?per_page=100': 'acme/noisy\n',+ });+ await syncAccountNotifications(account.id);+ actions.length = 0;+ vi.mocked(addNotification).mockClear();++ const sent = await sendDueAuditReports();+ expect(sent).toEqual([{ accountId: account.id, suggestions: 1 }]);+ expect(addNotification).toHaveBeenCalledWith(expect.objectContaining({ type: 'github_audit', link: `/devtools/github/audit?account=${account.id}` }));+ expect(actions).toEqual([]);+ expect(await sendDueAuditReports({ now: Date.now() + 86_400_000 })).toEqual([]);+ expect(addNotification).toHaveBeenCalledTimes(1);+ await updateAccount(account.id, { auditReport: false });+ });+it('runs the scheduled pass without any model call, respecting the poll interval', async () => {mockGh(() => listing([thread('801')]));const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('no network in this test'));diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.jsindex 60f8fab094..550fe605be 100644--- a/server/services/githubNotifications.js+++ b/server/services/githubNotifications.js@@ -117,9 +117,18 @@ async function recordSyncError(accountId, message) {);}-const runAssist = (account, env) => assistAccountNotifications(account, env, {- act: (threadId, action, detail) => applyNotificationAction(account.id, threadId, action, { actor: 'automation', detail }),-});+// Autopilot hands threads to their lanes first, so a thread a lane now owns+// is not also sorted by Assist. Loaded lazily: the hand-off reaches the CoS+// task schedule, which itself registers this module's scheduled check.+async function runAutomation(account, env) {+ const autopilot = account.mode === 'autopilot'+ ? await (await import('./githubNotificationAutopilot.js')).autopilotAccountNotifications(account)+ : { handedOff: 0 };+ const assist = await assistAccountNotifications(account, env, {+ act: (threadId, action, detail) => applyNotificationAction(account.id, threadId, action, { actor: 'automation', detail }),+ });+ return { ...assist, handedOff: autopilot.handedOff };+}async function syncAccountNow(account) {const env = await requireAccountEnv(account);@@ -129,8 +138,8 @@ async function syncAccountNow(account) {await query('UPDATE github_notification_sync SET last_sync_at = NOW(), last_error = \'\', updated_at = NOW() WHERE account_id = $1', [account.id]);// Threads past the last run's triage cap still need a decision.const triage = await triageAccountNotifications(account, env);- const assist = await runAssist(account, env);- if (triage.triaged || assist.sorted || assist.acted) githubNotificationEvents.emit('changed', { accountId: account.id });+ const assist = await runAutomation(account, env);+ if (triage.triaged || assist.sorted || assist.acted || assist.handedOff) githubNotificationEvents.emit('changed', { accountId: account.id });return { accountId: account.id, changed: false, fetched: 0, triage, assist };}const threads = [...first.threads];@@ -168,9 +177,9 @@ async function syncAccountNow(account) {);});const triage = await triageAccountNotifications(account, env);- const assist = await runAssist(account, env);+ const assist = await runAutomation(account, env);githubNotificationEvents.emit('changed', { accountId: account.id });- console.log(`📬 Synced ${records.length} GitHub notifications for ${account.host}${truncated ? ' (listing truncated)' : ''}, triaged ${triage.triaged}, sorted ${assist.sorted}, acted on ${assist.acted}`);+ console.log(`📬 Synced ${records.length} GitHub notifications for ${account.host}${truncated ? ' (listing truncated)' : ''}, triaged ${triage.triaged}, sorted ${assist.sorted}, acted on ${assist.acted}, handed off ${assist.handedOff}`);return { accountId: account.id, changed: true, fetched: records.length, truncated, triage, assist };}@@ -326,7 +335,7 @@ export async function listAutomationActivity({ limit = 50 } = {}) {FROM github_notification_events e JOIN github_notifications n ON n.account_id = e.account_id AND n.thread_id = e.thread_idWHERE e.actor = 'automation' AND e.kind = ANY($1::text[]) AND e.account_id = ANY($2::text[])ORDER BY e.created_at DESC, e.id DESC LIMIT $3`,- [NOTIFICATION_ACTIONS, accounts.map((account) => account.id), limit],+ [[...NOTIFICATION_ACTIONS, 'handed-off'], accounts.map((account) => account.id), limit],);return rows.map((row) => ({id: String(row.id),@@ -424,6 +433,9 @@ export async function runScheduledNotificationCheck({ now = Date.now() } = {}) {.catch((error) => ({ accountId: account.id, ok: false, error: error.message })));}lastScheduledSummary = describeScheduledCheck(results);+ // Only the scheduled check sends the opt-in monthly audit report.+ const { sendDueAuditReports } = await import('./githubNotificationAudit.js');+ await sendDueAuditReports({ now }).catch((error) => console.error(`❌ Monthly GitHub audit report failed: ${error.message}`));return results;}@@ -434,7 +446,9 @@ export function describeScheduledCheck(results) {const triaged = checked.reduce((sum, result) => sum + (result.triage?.triaged || 0), 0);const acted = checked.reduce((sum, result) => sum + (result.assist?.acted || 0), 0);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`);if (failed) parts.push(`${failed} failed`);return parts.join(', ');}diff --git a/server/services/prReviewerTargetedRun.js b/server/services/prReviewerTargetedRun.jsnew file mode 100644index 0000000000..8682c1abfe--- /dev/null+++ b/server/services/prReviewerTargetedRun.js@@ -0,0 +1,140 @@+/**+ * Queue the `pr-reviewer` scheduled task narrowed to ONE pull request. Shared by+ * the app Pull Requests tab's Untrusted:Review button and the GitHub+ * notifications Autopilot hand-off (#12874), so both reach the reviewer through+ * the same eligibility check, duplicate check and on-demand lane; neither starts+ * an agent from the request's content directly.+ */+import { ServerError } from '../lib/errorHandler.js';+import { getAllTasks } from './cos.js';+import { listExternalOpenPullRequests } from './prReviewerSecurity.js';+import { getOnDemandRequests, triggerOnDemandTask } from './taskSchedule.js';++export const ACTIVE_TASK_STATUSES = new Set(['pending', 'in_progress', 'blocked']);+const PR_REVIEWER_TASK_TYPE = 'pr-reviewer';++const flattenTasks = (taskData) => [+ ...(Array.isArray(taskData?.user?.tasks) ? taskData.user.tasks : []),+ ...(Array.isArray(taskData?.cos?.tasks) ? taskData.cos.tasks : []),+];++// A pr-reviewer run narrowed to this one request (`targetPullRequest` is stamped+// by the generator's security preflight). The unnarrowed sweep is deliberately+// NOT matched: it covers every external PR, so reporting it as this row's action+// would hide the per-row trigger behind an unrelated run.+const isReviewTaskFor = (task, appId, pullRequest) => {+ const metadata = task?.metadata;+ return ACTIVE_TASK_STATUSES.has(task?.status)+ && metadata?.analysisType === PR_REVIEWER_TASK_TYPE+ && metadata?.app === appId+ && Number(metadata.targetPullRequest) === pullRequest.number;+};++const isReviewRequestFor = (request, appId, pullRequest) => (+ request?.taskType === PR_REVIEWER_TASK_TYPE+ && request?.appId === appId+ && Number(request?.targetPullRequest) === pullRequest.number+);++/** Every CoS task, or null when the task store could not be read. */+export async function readActiveTasks() {+ const taskData = await getAllTasks().catch(err => {+ console.error(`❌ pr-reviewer targeting: could not read CoS tasks: ${err.message}`);+ return null;+ });+ if (!Array.isArray(taskData?.user?.tasks) || !Array.isArray(taskData?.cos?.tasks)) {+ if (taskData) console.error('❌ pr-reviewer targeting: CoS task response had an invalid shape');+ return null;+ }+ return flattenTasks(taskData);+}++// Queued on-demand requests that have not yet become tasks. A pr-reviewer run+// is queued through the on-demand lane, so without these a row would show no+// action at all between the click and the generator's next cycle — and a page+// refresh in that window would offer the button again.+//+// `null` means UNREADABLE, which is not the same as "nothing queued": collapsing+// the two would let a caller miss an existing request and queue a duplicate+// scan of the same public PR. Queueing fails closed on it; a listing, which only+// paints a button, degrades to showing no queued action.+export async function readPendingOnDemandRequests() {+ const requests = await getOnDemandRequests().catch(err => {+ console.error(`❌ pr-reviewer targeting: could not read on-demand requests: ${err.message}`);+ return null;+ });+ return Array.isArray(requests) ? requests : null;+}++export function reviewActionFor(pullRequest, tasks, requests, appId) {+ const task = tasks?.find(candidate => isReviewTaskFor(candidate, appId, pullRequest));+ if (task) return { taskId: task.id, status: task.status };+ const queued = requests?.find(request => isReviewRequestFor(request, appId, pullRequest));+ if (queued) return { taskId: null, status: 'pending' };+ const failure = tasks?.findLast(candidate => candidate.status === 'completed'+ && candidate.metadata?.analysisType === PR_REVIEWER_TASK_TYPE+ && candidate.metadata?.app === appId+ && Number(candidate.metadata?.targetPullRequest) === pullRequest.number);+ return failure?.metadata?.preflightFailure ? { taskId: failure.id, status: 'failed', error: failure.metadata.note } : null;+}++/**+ * Eligibility is answered by the same reader the generator's security preflight+ * uses: GitHub only, open against the default branch, and opened by someone+ * other than the signed-in gh account. `origin` defaults to a human Run+ * (see ON_DEMAND_ORIGINS); an automation passes its own. Returns `{ duplicate: true, reviewAction }`+ * when a run for this request is already in flight, else `{ duplicate: false,+ * request }`. Throws a ServerError with a status the route returns as is.+ */+export async function queueTargetedPrReview(app, number, { provider, model, effort, origin } = {}) {+ const target = await listExternalOpenPullRequests(app);+ if (!target.ok) {+ throw new ServerError('Could not read the reviewable pull requests for this app', {+ status: 503,+ code: 'FORGE_UNAVAILABLE',+ context: { reason: target.code || 'security-scan-target-unavailable' },+ });+ }+ const pullRequest = target.prs.find(candidate => candidate.number === number);+ if (!pullRequest) {+ throw new ServerError(+ `Pull request #${number} is not reviewable — PR review covers open GitHub pull requests against the default branch from an untrusted contributor`,+ { status: 409, code: 'PULL_REQUEST_NOT_REVIEWABLE' },+ );+ }+ // The security scan fingerprints the PR set by head commit, and the reader+ // normalizes an unusable `headRefOid` to null. Accepting one anyway would+ // queue a run the preflight then drops on a null fingerprint.+ if (!pullRequest.headRefOid) {+ throw new ServerError(+ `Pull request #${number} has no resolvable head commit, so its content cannot be safety-screened`,+ { status: 502, code: 'PULL_REQUEST_CONTEXT_UNAVAILABLE' },+ );+ }++ const [tasks, requests] = await Promise.all([readActiveTasks(), readPendingOnDemandRequests()]);+ // Fail CLOSED on unreadable task or on-demand state: `reviewActionFor` reads+ // either as "no run in flight", so queueing anyway would spend a second+ // model-abuse scan and code review on a public PR already being reviewed.+ if (tasks === null || requests === null) {+ throw new ServerError('Could not inspect existing CoS actions before queueing this review', {+ status: 503,+ code: 'AGENT_ACTION_UNAVAILABLE',+ });+ }+ const existing = reviewActionFor({ number }, tasks, requests, app.id);+ if (existing && existing.status !== 'failed') return { duplicate: true, reviewAction: existing };++ const request = await triggerOnDemandTask(PR_REVIEWER_TASK_TYPE, app.id, {+ targetPullRequest: number,+ provider,+ model,+ effort,+ origin,+ });+ if (request?.error) {+ throw new ServerError(request.error, { status: 409, code: 'PR_REVIEWER_UNAVAILABLE' });+ }+ console.log(`🔍 Queued pr-reviewer request ${request.id} for app ${app.id} request #${number}`);+ return { duplicate: false, request };+}diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 22b20e0729..e49b6f3705 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -1342,9 +1342,10 @@ export async function triggerOnDemandTask(taskType, appId = null, {// Per-app enablement is a rung for an UNATTENDED origin only. A human// pressing Run is deliberately overriding the app's cadence switch — the// drain's applyOnDemandRunResets exists for exactly that — while a burn- // picks its own step and must respect the switch the user set. Omitted,+ // or a notification hand-off picks its own target and must respect the+ // switch the user set. Omitted,// the ladder skips the rung.- appIds: origin === ON_DEMAND_ORIGINS.QUOTA_BURN && !manual+ appIds: (origin === ON_DEMAND_ORIGINS.QUOTA_BURN || origin === ON_DEMAND_ORIGINS.GITHUB_NOTIFICATION) && !manual? enabledAppIdsByTaskType(await getActiveApps().catch(() => [])).get(taskType) || []: undefined,} : null;diff --git a/server/services/taskScheduleConstants.js b/server/services/taskScheduleConstants.jsindex 947a1c8ffd..4bdb5d99ce 100644--- a/server/services/taskScheduleConstants.js+++ b/server/services/taskScheduleConstants.js@@ -56,7 +56,7 @@ export const FAILURE_PARK_THRESHOLD = 5;** A request written before `origin` existed carries none, which reads as USER.*/-export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill', QUOTA_BURN: QUOTA_BURN_REQUEST_ORIGIN };+export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill', QUOTA_BURN: QUOTA_BURN_REQUEST_ORIGIN, GITHUB_NOTIFICATION: 'github-notification' };export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;/*** Whether a human asked for this run. Absent origin reads as USER (see above),