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
Triage GitHub notifications with fixed rules and an Observe-mode check
Claude648b1b6a1168
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 91d11be91f..e893e68e9a 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -301,6 +301,7 @@ export default function App() {<Route path="devtools/flows" element={<FlowsDoc />} /><Route path="devtools/github" element={<GitHub />} /><Route path="devtools/github/:tab" element={<GitHub />} />+ <Route path="devtools/github/:tab/:accountId/:threadId" element={<GitHub />} /><Route path="devtools/history" element={<HistoryPage />} /><Route path="devtools/image-clean" element={<ImageClean />} /><Route path="devtools/quota-burn" element={<QuotaBurn />} />diff --git a/client/src/components/github/GitHubAutomationsTab.jsx b/client/src/components/github/GitHubAutomationsTab.jsxnew file mode 100644index 0000000000..2f5dfa2cbf--- /dev/null+++ b/client/src/components/github/GitHubAutomationsTab.jsx@@ -0,0 +1,139 @@+import { useCallback, useEffect, useState } from 'react';+import { Link } from 'react-router';+import { Play } from 'lucide-react';+import Pill from '../ui/Pill';+import LoadFailedState from '../ui/LoadFailedState';+import PageSkeleton from '../ui/PageSkeleton';+import { timeAgo } from '../../utils/formatters';+import socket from '../../services/socket';+import {+ getGitHubAutomations,+ setGitHubNotificationCadence,+ syncGitHubNotifications,+} from '../../services/api';++const MODE_VIEW = {+ observe: { label: 'Observe', hint: 'Records a decision for each notification; changes nothing on GitHub.' },+ assist: { label: 'Assist', hint: 'Coming next: runs only safe actions after screening.' },+ autopilot: { label: 'Autopilot', hint: 'Coming later: hands work to agents in your own repos.' },+};++const CADENCE_TEXT = {+ 'weekdays-15m': 'Every 15 minutes on weekdays',+ custom: 'On a custom schedule (CoS › Schedule)',+ off: 'Only when you tap Run now',+};++function AccountCard({ account, running, onRun }) {+ const mode = MODE_VIEW[account.mode] || MODE_VIEW.observe;+ return (+ <li className="min-w-0 space-y-2 rounded-lg border border-port-border bg-port-card p-4">+ <div className="flex flex-wrap items-start gap-2">+ <div className="min-w-0 flex-1">+ <h3 className="truncate font-semibold text-white">{account.label}</h3>+ <p className="truncate font-mono text-xs text-gray-400">{account.host}</p>+ </div>+ <Pill tone="muted">{mode.label}</Pill>+ {!account.enabled && <Pill tone="warning">Off</Pill>}+ </div>+ <p className="text-xs text-gray-400">{mode.hint}</p>+ <p className="text-xs text-gray-300">+ {account.lastSyncAt ? `Checked ${timeAgo(account.lastSyncAt)}` : 'Not checked yet'}+ {' · '}{account.needsYou} open{account.suspect ? ` · ${account.suspect} suspect` : ''}{account.pending ? ` · ${account.pending} waiting for triage` : ''}+ </p>+ {account.lastError && <p role="alert" className="break-words text-xs text-port-error">{account.lastError}</p>}+ <button+ type="button"+ onClick={() => onRun(account.id)}+ disabled={running || !account.enabled}+ className="inline-flex items-center gap-1.5 rounded border border-port-border px-3 py-1.5 text-xs text-gray-300 disabled:opacity-50"+ >+ <Play size={12} aria-hidden="true" /> {running ? 'Checking…' : 'Run now'}+ </button>+ </li>+ );+}++export default function GitHubAutomationsTab() {+ const [overview, setOverview] = useState(null);+ const [loadFailed, setLoadFailed] = useState(false);+ const [runningId, setRunningId] = useState(null);+ const [savingCadence, setSavingCadence] = useState(false);++ const load = useCallback(async () => {+ const result = await getGitHubAutomations({ silent: true }).catch(() => null);+ if (!result) {+ setLoadFailed(true);+ return;+ }+ setLoadFailed(false);+ setOverview(result);+ }, []);++ useEffect(() => { load(); }, [load]);+ useEffect(() => {+ socket.on('github:notifications:changed', load);+ socket.on('connect', load);+ return () => {+ socket.off('github:notifications:changed', load);+ socket.off('connect', load);+ };+ }, [load]);++ const runNow = async (accountId) => {+ setRunningId(accountId);+ // A failed check is recorded on the account and shown on its card.+ await syncGitHubNotifications(accountId, { silent: true }).catch(() => null);+ setRunningId(null);+ await load();+ };++ const toggleCadence = async () => {+ setSavingCadence(true);+ const next = overview.cadence === 'weekdays-15m' ? 'off' : 'weekdays-15m';+ const updated = await setGitHubNotificationCadence(next).catch(() => null);+ setSavingCadence(false);+ if (updated) setOverview(updated);+ };++ if (loadFailed && !overview) return <LoadFailedState title="Could not load GitHub automations." hint="Retry the local read." onRetry={load} />;+ if (!overview) return <PageSkeleton label="Loading GitHub automations" titleWidthClass="w-40" showAction={false} cards={2} />;++ return (+ <div className="min-w-0 space-y-4">+ <section className="space-y-2 rounded-lg border border-port-border bg-port-card p-4" aria-label="Notification check schedule">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="min-w-0">+ <h2 className="font-semibold text-white">Notification check</h2>+ <p className="text-xs text-gray-400">{CADENCE_TEXT[overview.cadence] || CADENCE_TEXT.off}</p>+ </div>+ <button+ type="button"+ onClick={toggleCadence}+ disabled={savingCadence || overview.cadence === 'custom'}+ aria-pressed={overview.cadence === 'weekdays-15m'}+ className="shrink-0 rounded bg-port-accent px-3 py-2 text-xs text-white disabled:opacity-50"+ >+ {overview.cadence === 'weekdays-15m' ? 'Turn off schedule' : 'Check every 15 min on weekdays'}+ </button>+ </div>+ <p className="text-xs text-gray-500">+ Each check reads notification details only and applies fixed rules; no AI is used.+ {overview.lastSummary ? ` Last run: ${overview.lastSummary}.` : ''}+ </p>+ </section>++ {overview.accounts.length === 0 ? (+ <p className="rounded-lg border border-port-border bg-port-card p-4 text-sm text-gray-400">+ No GitHub accounts yet. <Link to="/devtools/github/accounts" className="text-port-accent">Add one</Link>+ </p>+ ) : (+ <ul className="grid grid-cols-1 gap-3 @3xl/page:grid-cols-2">+ {overview.accounts.map((account) => (+ <AccountCard key={account.id} account={account} running={runningId === account.id} onRun={runNow} />+ ))}+ </ul>+ )}+ </div>+ );+}diff --git a/client/src/components/github/GitHubInboxTab.jsx b/client/src/components/github/GitHubInboxTab.jsxindex 012d6e1c61..79374be90e 100644--- a/client/src/components/github/GitHubInboxTab.jsx+++ b/client/src/components/github/GitHubInboxTab.jsx@@ -1,6 +1,10 @@import { useCallback, useEffect, useRef, useState } from 'react';+import { Link, useParams } from 'react-router';import { ExternalLink, RefreshCw } from 'lucide-react';import Pill from '../ui/Pill';+import GitHubThreadDrawer from './GitHubThreadDrawer';+import { DECISION_VIEW, TRUST_VIEW } from './githubTriageLabels';+import socket from '../../services/socket';import LoadFailedState from '../ui/LoadFailedState';import PageSkeleton from '../ui/PageSkeleton';import CollapsibleListItem from '../ui/CollapsibleListItem';@@ -14,6 +18,7 @@ import {const VIEWS = [{ id: 'needs-you', label: 'Needs you' },+ { id: 'suspect', label: 'Suspect' },{ id: 'handled', label: 'Handled' },{ id: 'all', label: 'All' },];@@ -54,10 +59,18 @@ const chipClass = (active) => `shrink-0 rounded-full border px-3 py-1.5 text-xs: 'border-port-border bg-port-bg text-gray-400'}`;// Whether a row still belongs in the view after an action moved it.-const belongsInView = (row, view) => view === 'all' || (view === 'needs-you') === (row.state === 'open');+const VIEW_MATCHERS = {+ 'needs-you': (row) => row.state === 'open' && !row.suspect,+ suspect: (row) => row.state === 'open' && row.suspect,+ handled: (row) => row.state !== 'open',+ all: () => true,+};+const belongsInView = (row, view) => VIEW_MATCHERS[view](row);function NotificationCard({ notification, accountLabel, busy, onAction }) {const handled = notification.state !== 'open';+ const trust = TRUST_VIEW[notification.trust];+ const decision = DECISION_VIEW[notification.decision];return (<article className="min-w-0 rounded-lg border border-port-border bg-port-card p-3"><div className="flex flex-wrap items-center gap-2 text-xs text-gray-400">@@ -66,10 +79,17 @@ function NotificationCard({ notification, accountLabel, busy, onAction }) {<span className="min-w-0 truncate font-mono">{notification.repoFullName}</span>{notification.yourRepo && <Pill tone="accent">Your repo</Pill>}{notification.repoPrivate && <Pill tone="muted">Private</Pill>}+ {trust && <Pill tone={trust.tone}>{trust.label}</Pill>}{handled && <Pill tone="muted">{STATE_LABELS[notification.state] || notification.state}</Pill>}<span className="ml-auto shrink-0">{timeAgo(notification.updatedAt)}</span></div>- <p className="mt-1.5 break-words text-sm text-white">{notification.title}</p>+ <Link+ to={`/devtools/github/inbox/${encodeURIComponent(notification.accountId)}/${notification.threadId}`}+ className="mt-1.5 block break-words text-sm text-white hover:underline"+ >+ {notification.title}+ </Link>+ {decision && <p className="mt-1"><Pill tone={decision.tone}>{decision.label}</Pill></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 && (@@ -99,6 +119,7 @@ function NotificationCard({ notification, accountLabel, busy, onAction }) {}export default function GitHubInboxTab() {+ const { accountId: routeAccountId, threadId } = useParams();const [accounts, setAccounts] = useState(null);const [accountId, setAccountId] = useState(null);const [view, setView] = useState('needs-you');@@ -139,8 +160,18 @@ export default function GitHubInboxTab() {getGitHubAccounts({ silent: true }).then(setAccounts).catch(() => {});}, []);- // Stored rows show at once; each finished sync re-reads them.+ // Stored rows show at once; each finished sync, and every server-side change+ // (a scheduled check, an action from another tab), re-reads them.useEffect(() => { loadList(); }, [loadList, syncTick]);+ useEffect(() => {+ const reload = () => setSyncTick((tick) => tick + 1);+ socket.on('github:notifications:changed', reload);+ socket.on('connect', reload);+ return () => {+ socket.off('github:notifications:changed', reload);+ socket.off('connect', reload);+ };+ }, []);useEffect(() => { refresh(); }, [refresh]);const handleAction = async (row, action) => {@@ -213,7 +244,7 @@ export default function GitHubInboxTab() {{data.notifications.length === 0 ? (<p className="rounded-lg border border-port-border bg-port-card p-4 text-sm text-gray-400">- {view === 'needs-you' ? 'Nothing needs you right now.' : 'No notifications here.'}+ {{ 'needs-you': 'Nothing needs you right now.', suspect: 'Nothing suspicious.' }[view] || 'No notifications here.'}</p>) : (<div className="min-w-0">@@ -234,6 +265,9 @@ export default function GitHubInboxTab() {)}{lastSyncAt && <p className="text-xs text-gray-500">Checked {timeAgo(lastSyncAt)}</p>}+ {threadId && routeAccountId && (+ <GitHubThreadDrawer accountId={routeAccountId} threadId={threadId} />+ )}</div>);}diff --git a/client/src/components/github/GitHubThreadDrawer.jsx b/client/src/components/github/GitHubThreadDrawer.jsxnew file mode 100644index 0000000000..7a054b16c3--- /dev/null+++ b/client/src/components/github/GitHubThreadDrawer.jsx@@ -0,0 +1,110 @@+import { useEffect, useState } from 'react';+import { 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 { DECISION_VIEW, RULE_LABELS, SIGNAL_LABELS, TRUST_VIEW } from './githubTriageLabels';++const EVENT_LABELS = {+ triaged: 'Triaged',+ read: 'Marked read',+ done: 'Done',+ reopen: 'Back to inbox',+ mute: 'Muted',+ unsubscribe: 'Unsubscribed',+ resubscribe: 'Resubscribed',+};++function describeEvent(event) {+ const label = EVENT_LABELS[event.kind] || event.kind;+ 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})` : ''}`;+}++/** 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();+ const [detail, setDetail] = useState(null);+ const [error, setError] = useState(null);+ const [version, setVersion] = useState(0);++ useEffect(() => {+ let active = true;+ getGitHubNotification(accountId, threadId, { silent: true })+ .then((result) => { if (active) { setDetail(result); setError(null); } })+ .catch((err) => { if (active) setError(err.message); });+ return () => { active = false; };+ }, [accountId, threadId, version]);++ useEffect(() => {+ const changed = (event) => { if (event?.accountId === accountId) setVersion((value) => value + 1); };+ socket.on('github:notifications:changed', changed);+ return () => socket.off('github:notifications:changed', changed);+ }, [accountId]);++ const close = () => navigate('/devtools/github/inbox');+ const current = detail && detail.accountId === accountId && detail.threadId === threadId ? detail : null;+ const decision = DECISION_VIEW[current?.decision];+ const trust = TRUST_VIEW[current?.trust];+ const evidence = current?.evidence || {};++ return (+ <Drawer open onClose={close} title="Notification" subtitle={current?.repoFullName}>+ {error && !current && <p role="alert" className="text-sm text-port-error">{error}</p>}+ {!error && !current && <p className="text-sm text-gray-400">Loading…</p>}+ {current && (+ <div className="space-y-4 text-sm">+ <section className="space-y-2">+ <p className="break-words text-white">{current.title}</p>+ <div className="flex flex-wrap gap-2">+ {decision ? <Pill tone={decision.tone}>{decision.label}</Pill> : <Pill tone="muted">{current.decision ? 'Needs you' : 'Not triaged yet'}</Pill>}+ {trust && <Pill tone={trust.tone}>{trust.label}</Pill>}+ {current.yourRepo && <Pill tone="accent">Your repo</Pill>}+ </div>+ {current.htmlUrl && (+ <a href={current.htmlUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent">+ <ExternalLink size={12} aria-hidden="true" /> Open on GitHub+ </a>+ )}+ </section>++ {current.decision && (+ <section className="space-y-1">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-gray-500">Why</h3>+ <p className="text-gray-300">{RULE_LABELS[evidence.rule] || evidence.rule}</p>+ {evidence.actor && <p className="text-xs text-gray-400">Actor <span className="font-mono">@{evidence.actor}</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.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 && (+ <ul className="list-disc space-y-0.5 pl-5 text-xs text-port-error">+ {current.signals.map((signal) => <li key={signal}>{SIGNAL_LABELS[signal] || signal}</li>)}+ </ul>+ )}+ </section>+ )}++ <section className="space-y-1">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-gray-500">History</h3>+ {current.events.length === 0 ? (+ <p className="text-xs text-gray-500">Nothing yet.</p>+ ) : (+ <ul className="space-y-1">+ {current.events.map((event, index) => (+ <li key={`${event.at}-${index}`} className="flex flex-wrap justify-between gap-x-3 text-xs">+ <span className="text-gray-300">{describeEvent(event)}{event.actor === 'automation' ? '' : ' by you'}</span>+ <span className="text-gray-500">{formatDateTime(event.at)}</span>+ </li>+ ))}+ </ul>+ )}+ </section>+ </div>+ )}+ </Drawer>+ );+}diff --git a/client/src/components/github/githubTriageLabels.js b/client/src/components/github/githubTriageLabels.jsnew file mode 100644index 0000000000..14a2dc6388--- /dev/null+++ b/client/src/components/github/githubTriageLabels.js@@ -0,0 +1,41 @@+// Display labels for the GitHub inbox's triage (server/lib/githubNotificationTriage.js).+// `needs-you` has no chip: it is the inbox's default state.+export const DECISION_VIEW = {+ suspect: { tone: 'error', label: 'Suspect' },+ 'surface-high': { tone: 'error', label: 'High priority' },+ 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' },+ 'handled-by-pr-workflow': { tone: 'success', label: 'PR workflow has it' },+ duplicate: { tone: 'muted', label: 'Duplicate' },+};++export const TRUST_VIEW = {+ yours: { tone: 'success', label: 'You' },+ trusted: { tone: 'success', label: 'Trusted' },+ outside: { tone: 'warning', label: 'Outside' },+};++// Why a thread got its decision, one line per rule.+export const RULE_LABELS = {+ 'spam-signal': 'A spam check matched, so nothing will act on it automatically',+ 'security-alert': 'Security alerts always surface first',+ 'invitation-never-accepted': 'Invitations surface and are never accepted automatically',+ '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',+ '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',+ 'review-elsewhere': 'Review requested on a repo you do not own',+ 'mention-elsewhere': 'Mentioned in a repo you do not own',+ default: 'No rule applied, so it waits for you',+};++export const SIGNAL_LABELS = {+ 'new-account': 'Actor account is less than 30 days old',+ 'first-time-actor': 'Actor has no history in this repo',+ 'mass-mention': 'The latest comment mentions many people',+ 'unrelated-repo': 'First notification from a repo you have no tie to',+};diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.jsindex 4f0e4ef1f5..9f15cb5b02 100644--- a/client/src/hooks/useOnDemandTaskToast.js+++ b/client/src/hooks/useOnDemandTaskToast.js@@ -148,9 +148,9 @@ export function useOnDemandTaskToast() {});return;}- // error-log-triage's deterministic pass IS the run; the reason is its- // result line (new entries, comments, investigations queued).- if (data?.taskType === 'error-log-triage' && data?.reason) {+ // error-log-triage's and github-notifications' deterministic pass IS+ // the run; the reason is its result line.+ if (['error-log-triage', 'github-notifications'].includes(data?.taskType) && data?.reason) {toast(`${task}: ${data.reason}.`, { duration: 7000, icon: '🩺' });return;}diff --git a/client/src/pages/GitHub.jsx b/client/src/pages/GitHub.jsxindex 44d10e6843..d4a3302766 100644--- a/client/src/pages/GitHub.jsx+++ b/client/src/pages/GitHub.jsx@@ -1,12 +1,14 @@import { useParams } from 'react-router';import RouteTabsHeader from '../components/ui/RouteTabsHeader';import GitHubAccountsTab from '../components/github/GitHubAccountsTab';+import GitHubAutomationsTab from '../components/github/GitHubAutomationsTab';import GitHubInboxTab from '../components/github/GitHubInboxTab';import GitHubReposTab from '../components/github/GitHubReposTab';-// Automations and Audit join as their phases ship (#12871–#12874).+// Audit joins when its phase ships (#12873).export const GITHUB_PAGE_TABS = Object.freeze([{ id: 'inbox', label: 'Inbox', to: '/devtools/github/inbox' },+ { id: 'automations', label: 'Automations', to: '/devtools/github/automations' },{ id: 'repos', label: 'Repos', to: '/devtools/github/repos' },{ id: 'accounts', label: 'Accounts', to: '/devtools/github/accounts' },]);@@ -22,6 +24,7 @@ export default function GitHub() {<RouteTabsHeader tabs={GITHUB_PAGE_TABS} activeTab={activeTab} ariaLabel="GitHub views" /></div>{activeTab === 'inbox' && <GitHubInboxTab />}+ {activeTab === 'automations' && <GitHubAutomationsTab />}{activeTab === 'repos' && <GitHubReposTab />}{activeTab === 'accounts' && <GitHubAccountsTab />}</div>diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsxindex d6d47c2251..03c9656dc2 100644--- a/client/src/pages/GitHub.test.jsx+++ b/client/src/pages/GitHub.test.jsx@@ -20,10 +20,26 @@ const mock = vi.hoisted(() => ({getGitHubNotifications: vi.fn(),syncGitHubNotifications: vi.fn(),applyGitHubNotificationAction: vi.fn(),+ getGitHubNotification: vi.fn(),+ getGitHubAutomations: vi.fn(),+ setGitHubNotificationCadence: vi.fn(),}));vi.mock('../services/api', () => mock);+vi.mock('../services/socket', () => {+ const listeners = new Map();+ return { default: {+ on: vi.fn((event, handler) => {+ if (!listeners.has(event)) listeners.set(event, new Set());+ listeners.get(event).add(handler);+ }),+ off: vi.fn((event, handler) => listeners.get(event)?.delete(handler)),+ emit: (event, payload) => listeners.get(event)?.forEach((handler) => handler(payload)),+ } };+});+import socket from '../services/socket';+import GitHub from './GitHub';const renderTab = (tab) => render(@@ -31,6 +47,7 @@ const renderTab = (tab) => render(<Routes><Route path="/devtools/github" element={<GitHub />} /><Route path="/devtools/github/:tab" element={<GitHub />} />+ <Route path="/devtools/github/:tab/:accountId/:threadId" element={<GitHub />} /></Routes></MemoryRouter>,);@@ -374,3 +391,70 @@ describe('GitHub inbox tab', () => {expect((await screen.findByRole('alert')).textContent).toContain('not-authenticated');});});++describe('GitHub inbox triage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.getGitHubAccounts.mockResolvedValue([IMPLICIT]);+ mock.syncGitHubNotifications.mockResolvedValue({ results: [] });+ });++ it('shows the recorded decision and trust, filters Suspect, and reloads when the server says the inbox changed', async () => {+ mock.getGitHubNotifications.mockResolvedValue({+ notifications: [{ ...NOTIFICATION, decision: 'suggest-untrusted-review', trust: 'outside', suspect: false, signals: [] }],+ sync: {},+ });+ renderTab('inbox');+ expect(await screen.findByText('Suggest Untrusted:Review')).toBeTruthy();+ expect(screen.getByText('Outside')).toBeTruthy();++ fireEvent.click(screen.getByRole('button', { name: 'Suspect' }));+ await waitFor(() => expect(mock.getGitHubNotifications).toHaveBeenLastCalledWith({ accountId: null, view: 'suspect' }, { silent: true }));++ const calls = mock.getGitHubNotifications.mock.calls.length;+ await act(async () => socket.emit('github:notifications:changed', { accountId: 'github-com' }));+ await waitFor(() => expect(mock.getGitHubNotifications.mock.calls.length).toBeGreaterThan(calls));+ });++ it('opens a thread drawer with the rule, spam signals and history', async () => {+ mock.getGitHubNotifications.mockResolvedValue({ notifications: [], sync: {} });+ mock.getGitHubNotification.mockResolvedValue({+ ...NOTIFICATION, decision: 'suspect', trust: 'outside', suspect: true, signals: ['new-account'],+ evidence: { rule: 'spam-signal', actor: 'newcomer', signals: ['new-account'] },+ events: [{ actor: 'automation', kind: 'triaged', detail: { decision: 'suspect', mode: 'observe' }, at: '2026-10-01T10:05:00.000Z' }],+ });+ renderTab('inbox/github-com/101');+ expect(await screen.findByText('Actor account is less than 30 days old')).toBeTruthy();+ expect(screen.getByText(/nothing will act on it automatically/)).toBeTruthy();+ expect(screen.getByText('Triaged: Suspect (observe)')).toBeTruthy();+ expect(mock.getGitHubNotification).toHaveBeenCalledWith('github-com', '101', { silent: true });+ });+});++describe('GitHub automations tab', () => {+ const OVERVIEW = {+ cadence: 'off', cronExpression: null, lastSummary: null,+ accounts: [{ id: 'github-com', label: 'github.com', host: 'github.com', trust: 'public', mode: 'observe', enabled: true, lastSyncAt: null, lastError: null, needsYou: 2, suspect: 1, pending: 0 }],+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mock.getGitHubAutomations.mockResolvedValue(OVERVIEW);+ mock.syncGitHubNotifications.mockResolvedValue({ results: [] });+ });++ it('turns on the weekday check in one tap and runs one account now', async () => {+ mock.setGitHubNotificationCadence.mockResolvedValue({ ...OVERVIEW, cadence: 'weekdays-15m' });+ renderTab('automations');+ expect(await screen.findByText('Only when you tap Run now')).toBeTruthy();+ expect(screen.getByText(/2 open · 1 suspect/)).toBeTruthy();++ fireEvent.click(screen.getByRole('button', { name: 'Check every 15 min on weekdays' }));+ expect(await screen.findByText('Every 15 minutes on weekdays')).toBeTruthy();+ expect(mock.setGitHubNotificationCadence).toHaveBeenCalledWith('weekdays-15m');++ fireEvent.click(screen.getByRole('button', { name: /Run now/ }));+ await waitFor(() => expect(mock.syncGitHubNotifications).toHaveBeenCalledWith('github-com', { silent: true }));+ await waitFor(() => expect(mock.getGitHubAutomations).toHaveBeenCalledTimes(2));+ });+});diff --git a/client/src/services/apiGithub.js b/client/src/services/apiGithub.jsindex 4f5ec8325a..27d56341e4 100644--- a/client/src/services/apiGithub.js+++ b/client/src/services/apiGithub.js@@ -43,3 +43,10 @@ export const applyGitHubNotificationAction = (accountId, threadId, action, optiorequest(`/github/notifications/${encodeURIComponent(accountId)}/${encodeURIComponent(threadId)}`, {method: 'POST', body: JSON.stringify({ action }), ...options,});+export const getGitHubNotification = (accountId, threadId, options = {}) =>+ request(`/github/notifications/${encodeURIComponent(accountId)}/${encodeURIComponent(threadId)}`, options);++// Automations tab: the notification check's cadence and each account's last run.+export const getGitHubAutomations = (options = {}) => request('/github/automations', options);+export const setGitHubNotificationCadence = (cadence, options = {}) =>+ request('/github/automations/schedule', { method: 'PUT', body: JSON.stringify({ cadence }), ...options });diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 4603f5fbc5..72c19f2a68 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -610,7 +610,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. 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. Code: `server/services/githubNotifications.js`, schema `server/lib/db/schema/githubNotifications.js`.### Music Video cover letteringdiff --git a/server/lib/README.md b/server/lib/README.mdindex c2c915fa79..b4884d5bc0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -472,7 +472,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. Pure except that `parseGitRemote` canonicalizes an ssh `Host` alias through `sshHostAlias.js`. || `sshHostAlias.js` | `resolveSshHostAlias`, `parseSshHostAliases` — resolves a personal SSH `Host` alias (`git@github-acme:…`, backed by `HostName github.com` in `~/.ssh/config`) to the host a remote actually connects to. Every remote-URL host parser (`gitForge.parseGitRemote`, `gitRemote.parseGitRemoteUrl`, `workTracker.hostFromOriginUrl`) canonicalizes through it, so multi-account checkouts classify as GitHub instead of an unreachable unknown host. || `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |-| `githubNotificationParse.js` | `parseGhIncludeOutput`, `linkHeaderHasNext`, `pollIntervalSeconds`, `toNotificationRecord` — pure parsing for the GitHub notifications inbox: `gh api --include` output and thread records, with links rebuilt only onto the account's own GitHub host. |+| `githubNotificationParse.js` | `parseGhIncludeOutput`, `linkHeaderHasNext`, `pollIntervalSeconds`, `repoApiPath`, `toNotificationRecord` — pure parsing for the GitHub notifications inbox: `gh api --include` output and thread records, with links rebuilt only onto the account's own GitHub host. |+| `githubNotificationTriage.js` | `TRIAGE_DECISIONS`, `TRUST_LEVELS`, `MASS_MENTION_THRESHOLD`, `computeThreadTrust`, `spamSignals`, `parseCiBranch`, `decideThread` — the GitHub inbox's fixed trust, spam and routing rules; trust comes only from accounts, repo ownership and forge permissions, never from content. || `gitRemote.js` | `getOriginInfo`, `classifyOriginRemote`, `parseGitRemoteUrl`, `readRemoteUrl`, `isUpstreamOwner`, `isUpstreamFullName`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — safely reads and classifies checkout remotes against PortOS or a caller-supplied canonical upstream. Used by self-update and managed integrations to detect forks. || `gitStaleLock.js` | `gitLockPathFromError`, `isStaleGitLock`, `clearStaleGitLock`, `clearStaleGitLocksIn`, `STALE_GIT_LOCK_MIN_AGE_MS` — recognizes the `*.lock` a KILLED git process left behind and removes it so the caller can retry. A lock under `.git/modules/<submodule>/` is shared by every worktree of the repo, so one dead process wedges submodule checkout install-wide with a bogus "another git process is running". Removal requires a `.lock` path under a `.git` directory (so a malformed message cannot aim the unlink at `yarn.lock`) that is older than 30 minutes — 3x the longest git command PortOS runs (`worktreeManager.WORKTREE_ADD_TIMEOUT_MS`, pinned by a test), which is what keeps it from deleting a LIVE competitor's lock. The threshold is deliberately not a parameter. `clearStaleGitLock(message)` is the reactive form, wired into `services/gitSubmodules.js#updateSubmodule` and `worktreeManager.addWorktreeWithRetry`; `clearStaleGitLocksIn(gitDir)` sweeps ahead of `update.sh`/`update.ps1`, the most likely producer. `scripts/doctor.js` reports one as the blocker. || `repoLinkFields.js` | `deriveRepoLinkFields(url)` / `normalizeRepoLinkFields(link)` / `linkIsRepo(link)` / `repoLinkLabel(link)` — the repository metadata a Brain link carries, plus the dual-write/tolerant-read shim that keeps the pre-multi-host `isGitHubRepo` field names readable across federated peers. |diff --git a/server/lib/db/schema/githubNotifications.js b/server/lib/db/schema/githubNotifications.jsindex 1ef595736b..50b3fb5a69 100644--- a/server/lib/db/schema/githubNotifications.js+++ b/server/lib/db/schema/githubNotifications.js@@ -28,6 +28,14 @@ export const githubNotificationsDdl = [PRIMARY KEY (account_id, thread_id))`,`CREATE INDEX IF NOT EXISTS idx_github_notifications_account_updated ON github_notifications (account_id, gh_updated_at DESC)`,+ // Triage (#12871): computed from metadata only. `triaged_for` is the+ // gh_updated_at a decision was made for, so new activity re-triages.+ `ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS latest_comment_api_url TEXT`,+ `ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS decision TEXT`,+ `ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS trust TEXT`,+ `ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS suspect BOOLEAN NOT NULL DEFAULT FALSE`,+ `ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS evidence JSONB NOT NULL DEFAULT '{}'::jsonb`,+ `ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS triaged_for TIMESTAMPTZ`,`CREATE TABLE IF NOT EXISTS github_notification_sync (account_id TEXT PRIMARY KEY,last_modified TEXT,@@ -36,4 +44,15 @@ export const githubNotificationsDdl = [last_error TEXT NOT NULL DEFAULT '',updated_at TIMESTAMPTZ DEFAULT NOW())`,+ // Who did what to a thread: the operator's actions and automation decisions.+ `CREATE TABLE IF NOT EXISTS github_notification_events (+ id BIGSERIAL PRIMARY KEY,+ account_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ actor TEXT NOT NULL CHECK (actor IN ('operator','automation')),+ kind TEXT NOT NULL,+ detail JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_github_notification_events_thread ON github_notification_events (account_id, thread_id, created_at DESC)`,];diff --git a/server/lib/githubNotificationParse.js b/server/lib/githubNotificationParse.jsindex f293e110de..75abeaf237 100644--- a/server/lib/githubNotificationParse.js+++ b/server/lib/githubNotificationParse.js@@ -39,7 +39,20 @@ export function pollIntervalSeconds(value) {}const webHostFor = (host) => (host === 'github.com' ? 'github.com' : host);-const apiPrefixFor = (host) => (host === 'github.com' ? 'https://api.github.com/repos/' : `https://${host}/api/v3/repos/`);+const apiRootFor = (host) => (host === 'github.com' ? 'https://api.github.com/' : `https://${host}/api/v3/`);+const apiPrefixFor = (host) => `${apiRootFor(host)}repos/`;++/**+ * The `gh api` path for a GitHub API url, only when it is a `repos/...` url on+ * the account's own API host with plain path segments; null otherwise, so a+ * url from notification data can never point `gh` at another host or endpoint.+ */+export function repoApiPath(url, host) {+ const prefix = apiPrefixFor(host);+ if (typeof url !== 'string' || !url.startsWith(prefix)) return null;+ const path = url.slice(apiRootFor(host).length);+ return /^repos(?:\/[A-Za-z0-9_.-]{1,100}){3,5}$/.test(path) && !path.split('/').includes('..') ? path : null;+}const SUBJECT_PATHS = { issues: 'issues', pulls: 'pull', commits: 'commit', discussions: 'discussions' };@@ -69,6 +82,7 @@ const rawThreadSchema = z.object({title: z.string(),type: z.string().max(64),url: z.string().max(2000).nullable().optional(),+ latest_comment_url: z.string().max(2000).nullable().optional(),}).passthrough(),repository: z.object({full_name: z.string().max(201),@@ -91,6 +105,7 @@ export function toNotificationRecord(raw, host) {subjectType: subject.type,subjectTitle: Array.from(subject.title).slice(0, MAX_TITLE_CHARS).join(''),subjectApiUrl: subject.url || null,+ latestCommentApiUrl: subject.latest_comment_url || null,unread,ghUpdatedAt: updatedAt,};diff --git a/server/lib/githubNotificationTriage.js b/server/lib/githubNotificationTriage.jsnew file mode 100644index 0000000000..da50d57b5b--- /dev/null+++ b/server/lib/githubNotificationTriage.js@@ -0,0 +1,95 @@+/**+ * Rule-based triage for the GitHub notifications inbox (#12871). Pure: the+ * service gathers metadata with `gh` and this module turns it into a trust+ * level, spam signals and one decision.+ *+ * Security boundary: trust comes only from configured accounts, repository+ * ownership and forge permissions, never from a title, comment body, label or+ * GitHub's self-reported `author_association`. Content may only ADD suspicion+ * (a mass-mention count); it can never raise trust or clear a signal.+ */++export const TRIAGE_DECISIONS = Object.freeze([+ 'suspect',+ 'surface-high',+ 'surface',+ 'needs-you',+ 'suggest-review',+ 'suggest-untrusted-review',+ 'suggest-mark-read',+ 'handled-by-pr-workflow',+ 'duplicate',+]);++export const TRUST_LEVELS = Object.freeze(['yours', 'trusted', 'outside', 'unknown']);++const NEW_ACCOUNT_DAYS = 30;+const DAY_MS = 24 * 60 * 60 * 1000;+export const MASS_MENTION_THRESHOLD = 10;+// GitHub's own label for an actor with no history in the repo. Used only to+// add suspicion on repos the operator does not own, never to grant trust.+const NO_HISTORY_ASSOCIATIONS = new Set(['NONE', 'FIRST_TIMER', 'FIRST_TIME_CONTRIBUTOR']);+const MENTION_REASONS = new Set(['mention', 'team_mention']);++const lower = (value) => (typeof value === 'string' ? value.toLowerCase() : null);++/**+ * `yours` for one of the operator's own logins on the host, `trusted` for an+ * actor the forge reports with write access to an owned repo (or, on a Private+ * account, a member of the repo's org), `outside` otherwise, `unknown` when+ * the thread has no human actor (CI, releases).+ */+export function computeThreadTrust({ actorLogin, ownLogins = [], repoOwned = false, actorHasWriteAccess = false, actorIsOrgMember = false, accountTrust = 'public' }) {+ const actor = lower(actorLogin);+ if (!actor) return 'unknown';+ if (ownLogins.some((login) => lower(login) === actor)) return 'yours';+ if (repoOwned && actorHasWriteAccess === true) return 'trusted';+ if (accountTrust === 'private' && actorIsOrgMember === true) return 'trusted';+ return 'outside';+}++/** Fixed spam checks; any hit makes the thread Suspect. */+export function spamSignals({ trust, actorCreatedAt, actorAssociation, mentionCount = 0, repoOwned = false, priorThreadsInRepo = 0, reason, now = Date.now() }) {+ if (trust === 'yours' || trust === 'trusted') return [];+ const signals = [];+ const created = Date.parse(actorCreatedAt || '');+ if (Number.isFinite(created) && now - created < NEW_ACCOUNT_DAYS * DAY_MS) signals.push('new-account');+ if (!repoOwned && NO_HISTORY_ASSOCIATIONS.has(String(actorAssociation || '').toUpperCase())) signals.push('first-time-actor');+ if (Number.isInteger(mentionCount) && mentionCount >= MASS_MENTION_THRESHOLD) signals.push('mass-mention');+ if (!repoOwned && priorThreadsInRepo === 0 && MENTION_REASONS.has(reason)) signals.push('unrelated-repo');+ return signals;+}++/**+ * The branch a GitHub Actions notification is about. Only used to fold+ * repeat CI notices together, never for trust.+ */+export function parseCiBranch(title) {+ const match = String(title || '').match(/ for ([\w./-]{1,255}) branch\b/);+ return match ? match[1] : null;+}++/**+ * 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.+ */+export function decideThread({ reason, subjectType, subjectState, subjectMerged = false, trust, 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' };+ 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') {+ if (ciBranch && defaultBranch && ciBranch === defaultBranch) return { decision: 'surface', rule: 'ci-default-branch' };+ if (repoManaged && ciBranch) return { decision: 'handled-by-pr-workflow', rule: 'ci-watched-by-pr-workflow' };+ return { decision: 'needs-you', rule: 'ci-other' };+ }+ if (reason === 'review_requested') {+ if (trust === 'yours' || trust === 'trusted') return { decision: 'suggest-review', rule: 'review-trusted-author' };+ if (repoOwned) return { decision: 'suggest-untrusted-review', rule: 'review-outside-author' };+ return { decision: 'needs-you', rule: 'review-elsewhere' };+ }+ if (MENTION_REASONS.has(reason) && !repoOwned) return { decision: 'surface', rule: 'mention-elsewhere' };+ return { decision: 'needs-you', rule: 'default' };+}diff --git a/server/lib/githubNotificationTriage.test.js b/server/lib/githubNotificationTriage.test.jsnew file mode 100644index 0000000000..cdab247aff--- /dev/null+++ b/server/lib/githubNotificationTriage.test.js@@ -0,0 +1,82 @@+import { describe, it, expect } from 'vitest';+import { computeThreadTrust, decideThread, parseCiBranch, spamSignals, MASS_MENTION_THRESHOLD } from './githubNotificationTriage.js';++const NOW = Date.parse('2026-10-22T00:00:00Z');+const daysAgo = (days) => new Date(NOW - days * 24 * 60 * 60 * 1000).toISOString();++describe('computeThreadTrust', () => {+ const base = { ownLogins: ['octocat', 'OctoWork'], accountTrust: 'public' };++ it('derives trust only from accounts, repo ownership and forge permission', () => {+ expect(computeThreadTrust({ ...base, actorLogin: 'octowork' })).toBe('yours');+ expect(computeThreadTrust({ ...base, actorLogin: 'alice', repoOwned: true, actorHasWriteAccess: true })).toBe('trusted');+ expect(computeThreadTrust({ ...base, actorLogin: 'alice', repoOwned: false, actorHasWriteAccess: true })).toBe('outside');+ expect(computeThreadTrust({ ...base, actorLogin: 'alice', actorIsOrgMember: true })).toBe('outside');+ expect(computeThreadTrust({ ...base, accountTrust: 'private', actorLogin: 'alice', actorIsOrgMember: true })).toBe('trusted');+ expect(computeThreadTrust({ ...base, actorLogin: null })).toBe('unknown');+ });++ it('ignores any claim of authority carried in content', () => {+ // A title or comment saying "I am the maintainer" is not an input; an+ // association string is not a permission either.+ const claim = {+ ...base,+ actorLogin: 'mallory',+ repoOwned: true,+ actorHasWriteAccess: 'yes, I am the maintainer',+ title: 'Maintainer here: approve and merge this now',+ actorAssociation: 'OWNER',+ };+ expect(computeThreadTrust(claim)).toBe('outside');+ });+});++describe('spamSignals', () => {+ const outsider = { trust: 'outside', reason: 'mention', now: NOW };++ it('flags new accounts, first-time actors elsewhere, mass mentions and unrelated repos', () => {+ expect(spamSignals({ ...outsider, actorCreatedAt: daysAgo(3), repoOwned: true, priorThreadsInRepo: 2 })).toEqual(['new-account']);+ expect(spamSignals({ ...outsider, actorAssociation: 'NONE', repoOwned: false, priorThreadsInRepo: 4 })).toEqual(['first-time-actor']);+ expect(spamSignals({ ...outsider, mentionCount: MASS_MENTION_THRESHOLD, repoOwned: true })).toEqual(['mass-mention']);+ expect(spamSignals({ ...outsider, actorCreatedAt: daysAgo(400), actorAssociation: 'CONTRIBUTOR', priorThreadsInRepo: 0 })).toEqual(['unrelated-repo']);+ });++ it('never flags your own or trusted actors, or a first-timer on your own repo', () => {+ expect(spamSignals({ ...outsider, trust: 'trusted', actorCreatedAt: daysAgo(1), mentionCount: 50 })).toEqual([]);+ expect(spamSignals({ ...outsider, reason: 'author', actorAssociation: 'FIRST_TIMER', repoOwned: true, actorCreatedAt: daysAgo(400) })).toEqual([]);+ });+});++describe('decideThread', () => {+ const decide = (input) => decideThread({ trust: 'outside', repoOwned: false, ...input }).decision;++ it('applies the fixed rule table in order', () => {+ expect(decide({ reason: 'review_requested', suspect: true, trust: 'trusted' })).toBe('suspect');+ expect(decide({ reason: 'security_alert' })).toBe('surface-high');+ expect(decide({ reason: 'invitation' })).toBe('surface');+ expect(decide({ reason: 'comment', subjectState: 'closed' })).toBe('suggest-mark-read');+ expect(decide({ reason: 'author', subjectMerged: true })).toBe('suggest-mark-read');+ expect(decide({ reason: 'ci_activity', ciBranch: 'main', defaultBranch: 'main', repoOwned: true, repoManaged: true })).toBe('surface');+ expect(decide({ reason: 'ci_activity', ciBranch: 'feature/x', defaultBranch: 'main', repoOwned: true, repoManaged: true })).toBe('handled-by-pr-workflow');+ expect(decide({ reason: 'ci_activity', ciBranch: 'feature/x', defaultBranch: 'main', repoOwned: true })).toBe('needs-you');+ expect(decide({ reason: 'review_requested', trust: 'trusted', repoOwned: true })).toBe('suggest-review');+ expect(decide({ reason: 'review_requested', repoOwned: true })).toBe('suggest-untrusted-review');+ expect(decide({ reason: 'review_requested' })).toBe('needs-you');+ expect(decide({ reason: 'mention' })).toBe('surface');+ expect(decide({ reason: 'mention', repoOwned: true })).toBe('needs-you');+ expect(decide({ reason: 'assign', repoOwned: true })).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' });+ });+});++describe('parseCiBranch', () => {+ it('reads the branch from GitHub Actions notice titles', () => {+ expect(parseCiBranch('CI workflow run failed for main branch')).toBe('main');+ expect(parseCiBranch('Deploy workflow run failed for release/1.2 branch')).toBe('release/1.2');+ expect(parseCiBranch('Something else')).toBeNull();+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 0099c5da19..bb60d148d5 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -432,6 +432,7 @@ export * from './gitOutputParsers.js';export * from './gitRemote.js';export * from './gitStaleLock.js';export * from './githubNotificationParse.js';+export * from './githubNotificationTriage.js';export * from './repoUrl.js';export * from './glabArgs.js';export * from './goalFeatureMap.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex b054cecff8..95c42eea69 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -222,6 +222,7 @@ const RAW_NAV_COMMANDS = [// ⌘K / voice only — no sidebar row: tabs of the GitHub page.{ id: 'nav.devtools.github-accounts', path: '/devtools/github/accounts', label: 'GitHub Accounts', section: 'Dev Tools', aliases: ['github-accounts', 'github-enterprise'], keywords: ['github', 'enterprise', 'ghes', 'gh auth', 'login', 'trust', 'notifications'] },{ id: 'nav.devtools.github-inbox', path: '/devtools/github/inbox', label: 'GitHub Inbox', section: 'Dev Tools', aliases: ['github-inbox', 'github-notifications'], keywords: ['github', 'notifications', 'inbox', 'mentions', 'review requests', 'mute', 'unsubscribe'] },+ { id: 'nav.devtools.github-automations', path: '/devtools/github/automations', label: 'GitHub Automations', section: 'Dev Tools', aliases: ['github-automations', 'github-triage'], keywords: ['github', 'notifications', 'schedule', 'triage', 'observe', 'run now'] },{ id: 'nav.devtools.github-repos', path: '/devtools/github/repos', label: 'GitHub Repos', section: 'Dev Tools', aliases: ['github-repos', 'github-secrets'], keywords: ['github', 'repositories', 'secrets', 'archive', 'npm'] },{ id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },{ id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['metadata', 'c2pa', 'content-credentials', 'sharp', 'denoise'] },diff --git a/server/lib/scheduledTaskTypes.js b/server/lib/scheduledTaskTypes.jsindex ebd45bba9e..d96e2a544a 100644--- a/server/lib/scheduledTaskTypes.js+++ b/server/lib/scheduledTaskTypes.js@@ -188,6 +188,11 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [// Install-wide only; its buildTaskInput hook (errorLogTriageHooks.js) does// the whole pass deterministically and never spawns a coordinator agent.'error-log-triage',+ // Syncs each configured GitHub account's notifications and records a+ // rule-based triage decision per thread (#12871). Install-wide only; its+ // buildTaskInput hook (githubNotificationsHooks.js) does the whole pass+ // without a model and never spawns a coordinator agent.+ 'github-notifications',// layered-intelligence is a PROGRAMMATIC-I/O task: it spawns a NORMAL reasoning// agent (visible in the CoS queue + Active Agents, TUI-attachable) with two// deterministic hooks around it — buildTaskInput gathers the app's goals +diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 957001dbfc..667a09b188 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -414,6 +414,11 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({payloadSchema: { type: 'object', properties: { operationId: { type: 'string' }, sourceId: { type: 'string' }, survivorId: { type: 'string' } },required: ['operationId', 'sourceId', 'survivorId'], additionalProperties: false },},+ 'github:notifications:changed': {+ direction: 'server-to-client',+ summary: 'Invalidate the GitHub notifications inbox, thread drawer and Automations tab after a sync, triage or action changed stored rows.',+ payloadSchema: { type: 'object', properties: { accountId: { type: 'string' } }, required: ['accountId'], additionalProperties: false },+ },'code-animation:changed': {direction: 'server-to-client',summary: 'Invalidate bounded Code Animation job/project galleries and matching details after a durable change; kind "poster" means only the gallery thumbnail changed.',diff --git a/server/lib/taskTargetScope.js b/server/lib/taskTargetScope.jsindex 7be0b9f54e..7522882d3e 100644--- a/server/lib/taskTargetScope.js+++ b/server/lib/taskTargetScope.js@@ -22,7 +22,7 @@* instead of forcing every run through the app picker (which would make the* install-wide lane unreachable on any install that has apps).*/-export const INSTALL_WIDE_TASK_TYPES = new Set(['repo-sync', 'user-action-review', 'model-comparison-refresh', 'error-log-triage']);+export const INSTALL_WIDE_TASK_TYPES = new Set(['repo-sync', 'user-action-review', 'model-comparison-refresh', 'error-log-triage', 'github-notifications']);// Task types that only make sense when pointed at a managed app. Keeping this// alongside the install-wide registry gives both the on-demand request gate@@ -66,6 +66,8 @@ const INSTALL_WIDE_ONLY_TASK_TYPES = new Set(['model-comparison-refresh',// Triage reads PortOS's own PM2 logs, which belong to no managed app.'error-log-triage',+ // The configured GitHub accounts belong to the machine, not to a managed app.+ 'github-notifications',...PROGRAMMATIC_SCHEDULED_TASK_TYPES,]);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex ae9abe18c0..e44d5b8983 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -969,7 +969,7 @@ export const githubAccountUpdateSchema = githubAccountCreateSchema.partial().str// GitHub notifications inbox (#12870).export const githubNotificationsQuerySchema = z.object({accountId: z.string().trim().min(1).max(100).optional(),- view: z.enum(['needs-you', 'handled', 'all']).optional(),+ view: z.enum(['needs-you', 'suspect', 'handled', 'all']).optional(),}).strict();export const githubNotificationsSyncSchema = z.object({@@ -982,6 +982,12 @@ export const githubNotificationActionSchema = z.object({export const GITHUB_NOTIFICATION_THREAD_ID_RE = /^\d{1,20}$/;+// Automations tab (#12871): the one cadence it offers, or back to Run now only.+export const GITHUB_NOTIFICATION_CADENCES = Object.freeze({ 'weekdays-15m': '*/15 * * * 1-5', off: null });+export const githubNotificationCadenceSchema = z.object({+ cadence: z.enum(Object.keys(GITHUB_NOTIFICATION_CADENCES)),+}).strict();+// =============================================================================// INSIGHTS SCHEMAS// =============================================================================diff --git a/server/routes/github.js b/server/routes/github.jsindex 86e32bafdf..6490c0d985 100644--- a/server/routes/github.js+++ b/server/routes/github.js@@ -1,7 +1,8 @@import express from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, githubRepoUpdateSchema, githubSecretSchema, githubAccountCreateSchema, githubAccountUpdateSchema,- githubNotificationsQuerySchema, githubNotificationsSyncSchema, githubNotificationActionSchema, GITHUB_NOTIFICATION_THREAD_ID_RE } from '../lib/validation.js';+ githubNotificationsQuerySchema, githubNotificationsSyncSchema, githubNotificationActionSchema, GITHUB_NOTIFICATION_THREAD_ID_RE,+ githubNotificationCadenceSchema } from '../lib/validation.js';import * as githubService from '../services/github.js';import * as githubAccounts from '../services/githubAccounts.js';import * as githubNotifications from '../services/githubNotifications.js';@@ -145,15 +146,41 @@ router.post('/notifications/sync', asyncHandler(async (req, res) => {res.json({ results });}));+const threadIdParam = (req) => {+ if (!GITHUB_NOTIFICATION_THREAD_ID_RE.test(req.params.threadId)) {+ throw new ServerError('Invalid notification thread id', { status: 400 });+ }+ return req.params.threadId;+};++/**+ * GET /api/github/notifications/:accountId/:threadId — one thread with its triage evidence and action log+ */+router.get('/notifications/:accountId/:threadId', asyncHandler(async (req, res) => {+ res.json(await githubNotifications.getNotification(req.params.accountId, threadIdParam(req)));+}));+/*** POST /api/github/notifications/:accountId/:threadId — read / done / reopen / mute / unsubscribe / resubscribe*/router.post('/notifications/:accountId/:threadId', asyncHandler(async (req, res) => {const { action } = validateRequest(githubNotificationActionSchema, req.body ?? {});- if (!GITHUB_NOTIFICATION_THREAD_ID_RE.test(req.params.threadId)) {- throw new ServerError('Invalid notification thread id', { status: 400 });- }- res.json(await githubNotifications.applyNotificationAction(req.params.accountId, req.params.threadId, action));+ res.json(await githubNotifications.applyNotificationAction(req.params.accountId, threadIdParam(req), action));+}));++/**+ * GET /api/github/automations — the notification check's cadence and each account's last run+ */+router.get('/automations', asyncHandler(async (req, res) => {+ res.json(await githubNotifications.getAutomationsOverview());+}));++/**+ * PUT /api/github/automations/schedule — weekday 15-minute checks, or Run now only+ */+router.put('/automations/schedule', asyncHandler(async (req, res) => {+ const { cadence } = validateRequest(githubNotificationCadenceSchema, req.body ?? {});+ res.json(await githubNotifications.setNotificationCadence(cadence));}));export default router;diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 379f932c19..725557ac9c 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1935,6 +1935,12 @@ CREATE TABLE IF NOT EXISTS github_notifications ();CREATE INDEX IF NOT EXISTS idx_github_notifications_account_updated ON github_notifications (account_id, gh_updated_at DESC);+ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS latest_comment_api_url TEXT;+ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS decision TEXT;+ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS trust TEXT;+ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS suspect BOOLEAN NOT NULL DEFAULT FALSE;+ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS evidence JSONB NOT NULL DEFAULT '{}'::jsonb;+ALTER TABLE github_notifications ADD COLUMN IF NOT EXISTS triaged_for TIMESTAMPTZ;CREATE TABLE IF NOT EXISTS github_notification_sync (account_id TEXT PRIMARY KEY,last_modified TEXT,@@ -1943,6 +1949,16 @@ CREATE TABLE IF NOT EXISTS github_notification_sync (last_error TEXT NOT NULL DEFAULT '',updated_at TIMESTAMPTZ DEFAULT NOW());+CREATE TABLE IF NOT EXISTS github_notification_events (+ id BIGSERIAL PRIMARY KEY,+ account_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ actor TEXT NOT NULL CHECK (actor IN ('operator','automation')),+ kind TEXT NOT NULL,+ detail JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_github_notification_events_thread ON github_notification_events (account_id, thread_id, created_at DESC);-- Beeper conversation mirror (#27). Machine-local mirror of the Beeper Desktop-- API — accounts, conversations, messages, participants, attachment metadata,diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex fdd56a112e..31e658c42a 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2037,6 +2037,10 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, tconst { readLastTriageSummary } = await import('./errorLogTriage.js');reason = await readLastTriageSummary().catch(() => null);}+ if (outcome === 'idle' && request.taskType === 'github-notifications') {+ const { readLastScheduledSummary } = await import('./githubNotifications.js');+ reason = readLastScheduledSummary();+ }// 'transient' says "the forge probe failed, try again shortly" — only true when// the forge is momentarily flaky. A gh that is missing, unauthenticated, ordiff --git a/server/services/githubNotificationEvents.js b/server/services/githubNotificationEvents.jsnew file mode 100644index 0000000000..2390095bc0--- /dev/null+++ b/server/services/githubNotificationEvents.js@@ -0,0 +1,8 @@+import { EventEmitter } from 'events';++/**+ * Leaf event bus for the GitHub notifications inbox (#12871), bridged to+ * Socket.IO as `github:notifications:changed`. Invalidation only: the payload+ * is `{ accountId }` and the browser refetches through the inbox routes.+ */+export const githubNotificationEvents = new EventEmitter();diff --git a/server/services/githubNotificationTriage.js b/server/services/githubNotificationTriage.jsnew file mode 100644index 0000000000..82ab3260ec--- /dev/null+++ b/server/services/githubNotificationTriage.js@@ -0,0 +1,212 @@+/**+ * Observe-mode triage for the GitHub notifications inbox (#12871): gather+ * metadata for each new or updated thread with `gh`, compute trust and spam+ * signals, and record one decision. Nothing here writes to GitHub, hands work+ * off, or calls a model; later modes act on these recorded decisions.+ *+ * What is read: the subject's author/state, the latest comment's author and+ * a count of @mentions in it (the body itself is never stored), the actor's+ * account age, the actor's permission on an owned repo, org membership for a+ * Private account, and a repo's default branch. Every url comes from+ * `repoApiPath`, so notification data can never aim `gh` at another host.+ */+import { query, withTransaction } from '../lib/db.js';+import { repoApiPath } from '../lib/githubNotificationParse.js';+import { computeThreadTrust, decideThread, parseCiBranch, spamSignals } from '../lib/githubNotificationTriage.js';+import { parseGitRemoteUrl, readOriginRemoteUrl } from '../lib/gitRemote.js';+import { safeJSONParse } from '../lib/fileUtils.js';+import { toPgJson } from '../lib/pgJson.js';+import { execGh } from './github.js';+import { createGithubActorTrust } from './forgeActorTrust.js';+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;+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}$/;++const SUBJECT_JQ = '{author: .user.login, association: .author_association, state: .state, merged: (.merged // false)}';+const COMMENT_JQ = '{author: .user.login, association: .author_association, mentions: ([(.body // "") | scan("@[A-Za-z0-9][A-Za-z0-9-]*")] | length)}';++const 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() {+ const { getAllApps } = await import('./apps.js');+ const apps = await getAllApps({ includeArchived: false }).catch(() => []);+ const keys = new Set();+ 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());+ }+ return keys;+}++/** Per-run, per-account reader that caches each forge answer once. */+function createReader(account, env) {+ const host = account.host;+ const run = (args) => execGh(['api', '--hostname', host, '--method', 'GET', ...args], GH_TIMEOUT_MS, { env });+ const json = async (path, jq) => safeJSONParse(await run([path, '--jq', jq]).catch(() => null), null, { logError: false });+ const memo = new Map();+ const once = (key, load) => {+ if (!memo.has(key)) memo.set(key, load());+ return memo.get(key);+ };+ return {+ subject: (path) => (path ? once(`s:${path}`, () => json(path, SUBJECT_JQ)) : null),+ comment: (path) => (path ? once(`c:${path}`, () => json(path, COMMENT_JQ)) : null),+ userCreatedAt: (login) => once(`u:${login}`, () => run([`users/${login}`, '--jq', '.created_at']).then((out) => out.trim() || null).catch(() => null)),+ defaultBranch: (repo) => once(`b:${repo}`, () => run([`repos/${repo}`, '--jq', '.default_branch']).then((out) => out.trim() || null).catch(() => null)),+ // 204 for a member; any failure (404, no visibility) is "not a member".+ orgMember: (org, login) => once(`o:${org}/${login}`, () => run([`orgs/${org}/members/${login}`]).then(() => true).catch(() => false)),+ repoTrust: (repo) => once(`t:${repo}`, () => createGithubActorTrust({+ runGh: (args) => execGh(args, GH_TIMEOUT_MS, { env }), host, repoFullName: repo, currentUser: null,+ })),+ viewer: () => once('viewer', () => run(['user', '--jq', '.login']).then((out) => loginOrNull(out.trim())).catch(() => null)),+ };+}++async function ownLoginsFor(account, reader) {+ const logins = (await listAccounts())+ .filter((entry) => entry.host === account.host && entry.login)+ .map((entry) => entry.login);+ if (!account.login) {+ const viewer = await reader.viewer();+ if (viewer) logins.push(viewer);+ }+ return logins;+}++async function triageThread(row, ctx) {+ const { account, reader, ownLogins, managedKeys, now } = ctx;+ const repo = REPO_RE.test(row.repo_full_name) ? row.repo_full_name : null;+ const owner = row.repo_owner.toLowerCase();+ const repoManaged = repo ? managedKeys.has(`${account.host}/${repo}`.toLowerCase()) : false;+ const repoOwned = repoManaged || ownLogins.some((login) => login.toLowerCase() === owner);++ const subjectPath = repoApiPath(row.subject_api_url, account.host);+ const commentPath = repoApiPath(row.latest_comment_api_url, account.host);+ const subject = await reader.subject(subjectPath);+ const comment = commentPath && commentPath !== subjectPath ? await reader.comment(commentPath) : null;+ const actorLogin = loginOrNull(comment?.author) || loginOrNull(subject?.author);+ const actorAssociation = comment?.author ? comment.association : subject?.association;++ const isOwn = actorLogin && ownLogins.some((login) => login.toLowerCase() === actorLogin.toLowerCase());+ const actorHasWriteAccess = Boolean(actorLogin && !isOwn && repoOwned && repo)+ && await (await reader.repoTrust(repo)).isTrusted(actorLogin);+ const actorIsOrgMember = Boolean(actorLogin && !isOwn && account.trust === 'private' && repo)+ && await reader.orgMember(row.repo_owner, actorLogin);+ const trust = computeThreadTrust({ actorLogin, ownLogins, repoOwned, actorHasWriteAccess, actorIsOrgMember, accountTrust: account.trust });++ const outsider = trust === 'outside';+ const priorThreadsInRepo = outsider+ ? Number((await query(+ 'SELECT COUNT(*)::int AS n FROM github_notifications WHERE account_id = $1 AND repo_full_name = $2 AND thread_id <> $3 AND created_at < $4',+ [account.id, row.repo_full_name, row.thread_id, row.created_at],+ )).rows[0].n)+ : 0;+ const signals = spamSignals({+ trust,+ actorCreatedAt: outsider && actorLogin ? await reader.userCreatedAt(actorLogin) : null,+ actorAssociation,+ mentionCount: comment?.mentions ?? 0,+ repoOwned,+ priorThreadsInRepo,+ reason: row.reason,+ now,+ });++ const isCi = row.reason === 'ci_activity' || row.subject_type === 'CheckSuite';+ const ciBranch = isCi ? parseCiBranch(row.subject_title) : null;+ const defaultBranch = isCi && ciBranch && repo ? await reader.defaultBranch(repo) : null;+ const { decision, rule } = decideThread({+ reason: row.reason,+ subjectType: row.subject_type,+ subjectState: subject?.state || null,+ subjectMerged: subject?.merged === true,+ trust,+ suspect: signals.length > 0,+ repoOwned,+ repoManaged,+ ciBranch,+ defaultBranch,+ });+ return {+ decision,+ trust,+ suspect: signals.length > 0,+ evidence: {+ rule,+ signals,+ actor: actorLogin,+ repoOwned,+ repoManaged,+ subjectState: subject ? (subject.merged === true ? 'merged' : subject.state || null) : null,+ ciBranch,+ metadataMissing: Boolean(subjectPath && !subject),+ },+ };+}++// Fold repeat default-branch CI notices for the same repo and branch into the+// newest one, so a red main shows once.+async function foldCiDuplicates(client, accountId) {+ const { rows } = await client.query(+ `SELECT thread_id, repo_full_name, evidence->>'ciBranch' AS branch FROM github_notifications+ WHERE account_id = $1 AND state = 'open' AND decision = 'surface' AND evidence->>'rule' = 'ci-default-branch'+ ORDER BY gh_updated_at DESC`,+ [accountId],+ );+ const newest = new Map();+ for (const row of rows) {+ const key = `${row.repo_full_name}#${row.branch}`;+ if (!newest.has(key)) {+ newest.set(key, row.thread_id);+ continue;+ }+ await client.query(+ `UPDATE github_notifications SET decision = 'duplicate', evidence = evidence || jsonb_build_object('foldedInto', $3::text), updated_at = NOW()+ WHERE account_id = $1 AND thread_id = $2`,+ [accountId, row.thread_id, newest.get(key)],+ );+ }+}++/**+ * Triage this account's threads that are new or have new activity since their+ * last decision. Returns `{ triaged, decisions: { [decision]: n } }`.+ */+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)+ ORDER BY gh_updated_at DESC LIMIT ${MAX_THREADS_PER_RUN}`,+ [account.id],+ );+ if (!rows.length) return { triaged: 0, decisions: {} };+ const reader = createReader(account, env);+ const ctx = { account, reader, ownLogins: await ownLoginsFor(account, reader), managedKeys: await managedRepoKeys(), now };+ const results = [];+ for (const row of rows) results.push({ row, result: await triageThread(row, ctx) });++ const decisions = {};+ await withTransaction(async (client) => {+ for (const { row, result } of results) {+ decisions[result.decision] = (decisions[result.decision] || 0) + 1;+ await client.query(+ `UPDATE github_notifications SET decision = $3, trust = $4, suspect = $5, evidence = $6::jsonb, triaged_for = $7, updated_at = NOW()+ WHERE account_id = $1 AND thread_id = $2`,+ [account.id, row.thread_id, result.decision, result.trust, result.suspect, toPgJson(result.evidence), row.gh_updated_at],+ );+ if (row.decision !== result.decision) {+ await client.query(+ `INSERT INTO github_notification_events (account_id, thread_id, actor, kind, detail) VALUES ($1, $2, 'automation', 'triaged', $3::jsonb)`,+ [account.id, row.thread_id, toPgJson({ decision: result.decision, rule: result.evidence.rule, mode: account.mode })],+ );+ }+ }+ await foldCiDuplicates(client, account.id);+ });+ return { triaged: results.length, decisions };+}diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex 6e59d68334..8affc869bb 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -1,8 +1,10 @@/**- * Postgres-backed tests for the GitHub notifications inbox (#12870): the- * upsert/reopen/read-reconcile SQL and the action mirror only run here against- * real constraints. `gh` is the only mocked boundary; the account store is the- * real one on a temp data root. Runs via `npm run test:db` (portos_test only).+ * Postgres-backed tests for the GitHub notifications inbox (#12870) and its+ * Observe-mode triage (#12871): the upsert/reopen/read-reconcile SQL, the+ * action mirror and the recorded decisions only run here against real+ * constraints. `gh` and the managed-app list are the mocked boundaries; the+ * account store is the real one on a temp data root. Runs via+ * `npm run test:db` (portos_test only).*/import { describe, it, expect, afterAll, beforeEach, vi } from 'vitest';import { mkdtempSync, rmSync } from 'fs';@@ -16,10 +18,14 @@ const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'github-notifications-test-'))vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));vi.mock('./github.js', async (importOriginal) => ({ ...(await importOriginal()), execGh: vi.fn() }));+vi.mock('./apps.js', () => ({ getAllApps: vi.fn(async () => []) }));const { execGh } = await import('./github.js');const { createAccount } = await import('./githubAccounts.js');-const { syncAccountNotifications, listNotifications, applyNotificationAction } = await import('./githubNotifications.js');+const {+ syncAccountNotifications, listNotifications, applyNotificationAction, getNotification, runScheduledNotificationCheck,+} = await import('./githubNotifications.js');+const { buildTaskInput } = await import('./githubNotificationsHooks.js');let dbReady = false;let skipReason = '';@@ -36,12 +42,12 @@ const runDb = requireDbOrSkip('services/githubNotifications.db.test', dbReady, sconst accountIds = [];-const thread = (id, { updatedAt = '2026-10-01T10:00:00Z', owner = 'octocat', repo = 'hello', title = `Thread ${id}` } = {}) => ({+const thread = (id, { updatedAt = '2026-10-01T10:00:00Z', owner = 'octocat', repo = 'hello', title = `Thread ${id}`, reason = 'author', type = 'PullRequest', url } = {}) => ({id,unread: true,- reason: 'mention',+ reason,updated_at: updatedAt,- subject: { title, type: 'PullRequest', url: `https://api.github.com/repos/${owner}/${repo}/pulls/${id}` },+ subject: { title, type, url: url === undefined ? `https://api.github.com/repos/${owner}/${repo}/pulls/${id}` : url },repository: { full_name: `${owner}/${repo}`, private: false, owner: { login: owner } },});@@ -54,23 +60,32 @@ const listing = (threads, headers = {}) => [JSON.stringify(threads),].join('\r\n');-// Routes gh calls: token lookup, the listing (via `respond`), and thread actions.-function mockGh(respond) {+// Routes gh calls: token lookup, the listing (via `respond`), thread actions,+// and triage's read-only metadata lookups (via `forge`, keyed by API path).+function mockGh(respond, forge = {}) {const actions = [];vi.mocked(execGh).mockImplementation(async (args) => {if (args[0] === 'auth') return 'gho_example';const path = args.find((arg) => /^notifications/.test(arg));- if (path.startsWith('notifications?')) return respond(args);- actions.push([args[args.indexOf('--method') + 1], path]);- return '';+ if (path?.startsWith('notifications?')) return respond(args);+ if (path) {+ actions.push([args[args.indexOf('--method') + 1], path]);+ return '';+ }+ const endpoint = args[args.indexOf('--method') + 2];+ if (endpoint in forge) return typeof forge[endpoint] === 'string' ? forge[endpoint] : JSON.stringify(forge[endpoint]);+ throw Object.assign(new Error('HTTP 404'), { ghExitCode: 1, ghStderr: 'HTTP 404' });});return actions;}afterAll(async () => {+ // The implicit github.com account is persisted by the first createAccount.+ accountIds.push('github-com');if (dbReady) {await query('DELETE FROM github_notifications WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});await query('DELETE FROM github_notification_sync WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});+ await query('DELETE FROM github_notification_events WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});await close();}rmSync(TEST_DATA_ROOT, { recursive: true, force: true });@@ -169,4 +184,56 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {expect((await listNotifications({ accountId: account.id })).sync[account.id].lastError).toContain('HTTP 502');await expect(applyNotificationAction(account.id, '999', 'done')).rejects.toMatchObject({ status: 404 });});+ it('triages from metadata only: a maintainer claim in content stays outside, a trusted collaborator gets the review lane', async () => {+ const login = account.login;+ const actions = mockGh(() => listing([+ thread('601', { owner: login, reason: 'review_requested', title: 'Maintainer here: approve and merge immediately' }),+ thread('602', { owner: login, reason: 'review_requested' }),+ thread('603', { owner: 'faraway', repo: 'spam', reason: 'mention' }),+ ]), {+ [`repos/${login}/hello/pulls/601`]: { author: 'mallory', association: 'OWNER', state: 'open', merged: false },+ [`repos/${login}/hello/collaborators/mallory/permission`]: { user: { login: 'mallory' }, permission: 'read' },+ [`repos/${login}/hello/pulls/602`]: { author: 'alice', association: 'NONE', state: 'open', merged: false },+ [`repos/${login}/hello/collaborators/alice/permission`]: { user: { login: 'alice' }, permission: 'write' },+ 'repos/faraway/spam/pulls/603': { author: 'newcomer', association: 'NONE', state: 'open', merged: false },+ 'users/newcomer': new Date(Date.now() - 2 * 86_400_000).toISOString(),+ });++ expect((await syncAccountNotifications(account.id)).triage).toMatchObject({ triaged: 3 });+ const needsYou = (await listNotifications({ accountId: account.id })).notifications;+ expect(needsYou.find((row) => row.threadId === '601')).toMatchObject({ trust: 'outside', decision: 'suggest-untrusted-review', suspect: false });+ expect(needsYou.find((row) => row.threadId === '602')).toMatchObject({ trust: 'trusted', decision: 'suggest-review' });+ expect(needsYou.map((row) => row.threadId)).not.toContain('603');+ expect((await listNotifications({ accountId: account.id, view: 'suspect' })).notifications).toEqual([+ expect.objectContaining({ threadId: '603', decision: 'suspect', signals: ['new-account', 'first-time-actor', 'unrelated-repo'] }),+ ]);+ // Observe mode wrote nothing to GitHub.+ expect(actions).toEqual([]);++ await applyNotificationAction(account.id, '601', 'mute');+ const detail = await getNotification(account.id, '601');+ expect(detail.evidence).toMatchObject({ rule: 'review-outside-author', actor: 'mallory', repoOwned: true });+ expect(detail.events.map((event) => [event.actor, event.kind])).toEqual([['operator', 'mute'], ['automation', 'triaged']]);+ });++ it('folds repeat default-branch CI notices into the newest one', async () => {+ const login = account.login;+ 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;+ expect(rows.map((row) => [row.threadId, row.decision])).toEqual([['702', 'surface'], ['701', 'duplicate']]);+ });++ 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'));+ const first = await buildTaskInput({ app: { id: null } });+ expect(first.skip.reason).toMatch(/^checked \d+ of \d+ account\(s\)/);+ const second = await runScheduledNotificationCheck();+ expect(second.find((result) => result.accountId === account.id)).toMatchObject({ skipped: 'poll-interval' });+ expect(fetchSpy).not.toHaveBeenCalled();+ expect(await buildTaskInput({ app: { id: 'app-1' } })).toEqual({ skip: { reason: 'install-wide-only' } });+ fetchSpy.mockRestore();+ });});diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.jsindex 2d636d8be9..d1bbf586a7 100644--- a/server/services/githubNotifications.js+++ b/server/services/githubNotifications.js@@ -10,6 +10,7 @@ import { query, withTransaction } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';import { safeJSONParse } from '../lib/fileUtils.js';import { createSingleFlight } from '../lib/singleFlight.js';+import { GITHUB_NOTIFICATION_CADENCES } from '../lib/validation.js';import {linkHeaderHasNext,parseGhIncludeOutput,@@ -18,6 +19,8 @@ import {} from '../lib/githubNotificationParse.js';import { execGh } from './github.js';import { getAccount, listAccounts, resolveGitHubAccountEnv } from './githubAccounts.js';+import { githubNotificationEvents } from './githubNotificationEvents.js';+import { triageAccountNotifications } from './githubNotificationTriage.js';const GH_TIMEOUT_MS = 30_000;const PER_PAGE = 50;@@ -26,7 +29,9 @@ const PER_PAGE = 50;const MAX_PAGES = 5;const LIST_LIMIT = 200;-export const NOTIFICATION_VIEWS = Object.freeze(['needs-you', 'handled', 'all']);+export const NOTIFICATION_VIEWS = Object.freeze(['needs-you', 'suspect', 'handled', 'all']);+// GitHub's floor between notification polls when it sends no X-Poll-Interval.+const MIN_POLL_SECONDS = 60;export const NOTIFICATION_ACTIONS = Object.freeze(['read', 'done', 'reopen', 'mute', 'unsubscribe', 'resubscribe']);// method + path suffix + fields for each operator action; the state it leaves@@ -80,8 +85,8 @@ async function fetchPage(account, env, page, ifModifiedSince) {const UPSERT_SQL = `INSERT INTO github_notifications (account_id, thread_id, repo_full_name, repo_owner, repo_private, reason, subject_type,- subject_title, subject_api_url, html_url, unread, gh_updated_at- ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)+ subject_title, subject_api_url, html_url, unread, gh_updated_at, latest_comment_api_url+ ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)ON CONFLICT (account_id, thread_id) DO UPDATE SETrepo_full_name = EXCLUDED.repo_full_name,repo_owner = EXCLUDED.repo_owner,@@ -91,6 +96,7 @@ const UPSERT_SQL = `INSERT INTO github_notifications (subject_title = EXCLUDED.subject_title,subject_api_url = EXCLUDED.subject_api_url,html_url = EXCLUDED.html_url,+ latest_comment_api_url = EXCLUDED.latest_comment_api_url,unread = EXCLUDED.unread,-- New activity brings back a thread marked done, and an unsubscribed one-- (GitHub re-subscribes on a fresh mention or review request). Muted stays.@@ -113,7 +119,10 @@ async function syncAccountNow(account) {const first = await fetchPage(account, env, 1, cursor?.last_modified || null);if (first.notModified) {await query('UPDATE github_notification_sync SET last_sync_at = NOW(), last_error = \'\', updated_at = NOW() WHERE account_id = $1', [account.id]);- return { accountId: account.id, changed: false, fetched: 0 };+ // Threads past the last run's triage cap still need a decision.+ const triage = await triageAccountNotifications(account, env);+ if (triage.triaged) githubNotificationEvents.emit('changed', { accountId: account.id });+ return { accountId: account.id, changed: false, fetched: 0, triage };}const threads = [...first.threads];let page = first;@@ -130,7 +139,7 @@ async function syncAccountNow(account) {for (const r of records) {await client.query(UPSERT_SQL, [account.id, r.threadId, r.repoFullName, r.repoOwner, r.repoPrivate, r.reason, r.subjectType,- r.subjectTitle, r.subjectApiUrl, r.htmlUrl, r.unread, r.ghUpdatedAt,+ r.subjectTitle, r.subjectApiUrl, r.htmlUrl, r.unread, r.ghUpdatedAt, r.latestCommentApiUrl,]);}// The listing holds only unread threads; one that dropped out was read@@ -149,8 +158,10 @@ async function syncAccountNow(account) {[account.id, first.headers['last-modified'] || null, pollIntervalSeconds(first.headers['x-poll-interval'])],);});- console.log(`📬 Synced ${records.length} GitHub notifications for ${account.host}${truncated ? ' (listing truncated)' : ''}`);- return { accountId: account.id, changed: true, fetched: records.length, truncated };+ const triage = await triageAccountNotifications(account, env);+ githubNotificationEvents.emit('changed', { accountId: account.id });+ console.log(`📬 Synced ${records.length} GitHub notifications for ${account.host}${truncated ? ' (listing truncated)' : ''}, triaged ${triage.triaged}`);+ return { accountId: account.id, changed: true, fetched: records.length, truncated, triage };}/** Fetch one account's unread notifications, coalescing concurrent requests. */@@ -175,11 +186,14 @@ export async function syncAllNotifications() {}const VIEW_FILTERS = {- 'needs-you': "state = 'open'",+ 'needs-you': "state = 'open' AND NOT suspect",+ suspect: "state = 'open' AND suspect",handled: "state <> 'open'",all: 'TRUE',};+const toIso = (value) => (value instanceof Date ? value.toISOString() : value);+const toApi = (row, accountsById) => {const account = accountsById.get(row.account_id);const login = account?.login?.toLowerCase();@@ -195,10 +209,16 @@ const toApi = (row, accountsById) => {htmlUrl: row.html_url,unread: row.unread,state: row.state,- updatedAt: row.gh_updated_at instanceof Date ? row.gh_updated_at.toISOString() : row.gh_updated_at,+ decision: row.decision || null,+ trust: row.trust || null,+ suspect: row.suspect === true,+ rule: row.evidence?.rule || null,+ signals: Array.isArray(row.evidence?.signals) ? row.evidence.signals : [],+ updatedAt: toIso(row.gh_updated_at),};};+export async function listNotifications({ accountId = null, view = 'needs-you' } = {}) {const accounts = await listAccounts();const accountsById = new Map(accounts.map((account) => [account.id, account]));@@ -214,7 +234,7 @@ export async function listNotifications({ accountId = null, view = 'needs-you' }return {notifications: rows.rows.map((row) => toApi(row, accountsById)),sync: Object.fromEntries(syncRows.rows.map((row) => [row.account_id, {- lastSyncAt: row.last_sync_at instanceof Date ? row.last_sync_at.toISOString() : row.last_sync_at,+ lastSyncAt: toIso(row.last_sync_at),lastError: row.last_error || null,pollIntervalSeconds: row.poll_interval_seconds,}])),@@ -246,5 +266,126 @@ export async function applyNotificationAction(accountId, threadId, action) {WHERE account_id = $1 AND thread_id = $2 RETURNING *`,[account.id, threadId, action, spec.state],);+ await query(+ `INSERT INTO github_notification_events (account_id, thread_id, actor, kind, detail) VALUES ($1, $2, 'operator', $3, '{}'::jsonb)`,+ [account.id, threadId, action],+ );+ githubNotificationEvents.emit('changed', { accountId: account.id });return toApi(result.rows[0], new Map([[account.id, account]]));}++/** One thread with its triage evidence and action log, newest event first. */+export async function getNotification(accountId, threadId) {+ const account = await getAccount(accountId);+ 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 events = await query(+ 'SELECT actor, kind, detail, created_at FROM github_notification_events WHERE account_id = $1 AND thread_id = $2 ORDER BY created_at DESC, id DESC LIMIT 50',+ [account.id, threadId],+ );+ return {+ ...toApi(row, new Map([[account.id, account]])),+ accountLabel: account.label,+ evidence: row.evidence || {},+ events: events.rows.map((event) => ({ actor: event.actor, kind: event.kind, detail: event.detail || {}, at: toIso(event.created_at) })),+ };+}++let lastScheduledSummary = null;+export const readLastScheduledSummary = () => lastScheduledSummary;++/**+ * The `github-notifications` scheduled pass: sync and triage every enabled+ * account whose poll interval has elapsed. Observe mode records decisions+ * only; nothing here writes to GitHub or calls a model.+ */+export async function runScheduledNotificationCheck({ now = Date.now() } = {}) {+ const accounts = (await listAccounts()).filter((account) => account.enabled);+ const cursors = new Map((await query(+ 'SELECT account_id, last_sync_at, poll_interval_seconds FROM github_notification_sync WHERE account_id = ANY($1::text[])',+ [accounts.map((account) => account.id)],+ )).rows.map((row) => [row.account_id, row]));+ const results = [];+ for (const account of accounts) {+ const cursor = cursors.get(account.id);+ const waitMs = Math.max(cursor?.poll_interval_seconds || 0, MIN_POLL_SECONDS) * 1000;+ if (cursor?.last_sync_at && now - new Date(cursor.last_sync_at).getTime() < waitMs) {+ results.push({ accountId: account.id, ok: true, skipped: 'poll-interval' });+ continue;+ }+ results.push(await syncAccountNotifications(account.id)+ .then((result) => ({ ...result, ok: true }))+ .catch((error) => ({ accountId: account.id, ok: false, error: error.message })));+ }+ lastScheduledSummary = describeScheduledCheck(results);+ return results;+}++export function describeScheduledCheck(results) {+ const checked = results.filter((result) => result.ok && !result.skipped);+ const failed = results.filter((result) => !result.ok).length;+ const fetched = checked.reduce((sum, result) => sum + (result.fetched || 0), 0);+ const triaged = checked.reduce((sum, result) => sum + (result.triage?.triaged || 0), 0);+ const parts = [`checked ${checked.length} of ${results.length} account(s)`, `${fetched} new or updated`, `${triaged} triaged`];+ if (failed) parts.push(`${failed} failed`);+ return parts.join(', ');+}++const CADENCE_TASK_TYPE = 'github-notifications';++function cadenceOf(interval) {+ if (interval?.enabled && interval.type === 'cron' && interval.cronExpression === GITHUB_NOTIFICATION_CADENCES['weekdays-15m']) return 'weekdays-15m';+ if (interval?.enabled && interval.type === 'cron') return 'custom';+ return 'off';+}++/** What the Automations tab shows: the check's cadence and each account's last run. */+export async function getAutomationsOverview() {+ const { getTaskInterval } = await import('./taskSchedule.js');+ const [accounts, interval] = await Promise.all([listAccounts(), getTaskInterval(CADENCE_TASK_TYPE)]);+ const ids = accounts.map((account) => account.id);+ const [syncRows, countRows] = await Promise.all([+ query('SELECT account_id, last_sync_at, last_error, poll_interval_seconds FROM github_notification_sync WHERE account_id = ANY($1::text[])', [ids]),+ query(+ `SELECT account_id, COUNT(*) FILTER (WHERE NOT suspect)::int AS needs_you, COUNT(*) FILTER (WHERE suspect)::int AS suspect,+ COUNT(*) FILTER (WHERE decision IS NULL)::int AS pending+ FROM github_notifications WHERE account_id = ANY($1::text[]) AND state = 'open' GROUP BY account_id`,+ [ids],+ ),+ ]);+ const syncById = new Map(syncRows.rows.map((row) => [row.account_id, row]));+ const countsById = new Map(countRows.rows.map((row) => [row.account_id, row]));+ return {+ cadence: cadenceOf(interval),+ cronExpression: interval?.type === 'cron' ? interval.cronExpression || null : null,+ lastSummary: lastScheduledSummary,+ accounts: accounts.map((account) => {+ const sync = syncById.get(account.id);+ const counts = countsById.get(account.id);+ return {+ id: account.id,+ label: account.label,+ host: account.host,+ trust: account.trust,+ mode: account.mode,+ enabled: account.enabled,+ lastSyncAt: toIso(sync?.last_sync_at) || null,+ lastError: sync?.last_error || null,+ pollIntervalSeconds: sync?.poll_interval_seconds ?? null,+ needsYou: counts?.needs_you || 0,+ suspect: counts?.suspect || 0,+ pending: counts?.pending || 0,+ };+ }),+ };+}++/** Turn the weekday 15-minute check on, or back to Run now only. */+export async function setNotificationCadence(cadence) {+ const { updateTaskInterval } = await import('./taskSchedule.js');+ const cron = GITHUB_NOTIFICATION_CADENCES[cadence];+ await updateTaskInterval(CADENCE_TASK_TYPE, cron+ ? { type: 'cron', cronExpression: cron, enabled: true }+ : { type: 'on-demand', cronExpression: null, enabled: true });+ return getAutomationsOverview();+}diff --git a/server/services/githubNotificationsHooks.js b/server/services/githubNotificationsHooks.jsnew file mode 100644index 0000000000..b73ab98a21--- /dev/null+++ b/server/services/githubNotificationsHooks.js@@ -0,0 +1,18 @@+/**+ * Pre-agent hook for the `github-notifications` scheduled task (#12871).+ *+ * The pass is deterministic (services/githubNotifications.js): sync each+ * enabled account, then record a rule-based triage decision per thread. It+ * starts no agent and calls no model, so the hook always answers `skip`;+ * `resolveTaskInputHook` records the execution, advancing the cadence.+ */+import { describeScheduledCheck, runScheduledNotificationCheck } from './githubNotifications.js';++export async function buildTaskInput({ app } = {}) {+ // The accounts belong to this machine; a per-app dispatch would sync them+ // once per app.+ if (app?.id) return { skip: { reason: 'install-wide-only' } };+ const line = describeScheduledCheck(await runScheduledNotificationCheck());+ console.log(`📬 github-notifications: ${line}`);+ return { skip: { reason: line } };+}diff --git a/server/services/socket.js b/server/services/socket.jsindex 90c6990f1c..a7fe7ed751 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -1,4 +1,5 @@import { catalogIdentityEvents } from './catalogIdentity/events.js';+import { githubNotificationEvents } from './githubNotificationEvents.js';import { registerModelObservationSocket } from './modelObservation.js';import { registerBrowserStatusSocket } from './browserStatus.js';import { registerFleetHostSocket } from './fleetHostNotify.js';@@ -318,6 +319,8 @@ const SIMPLE_BRIDGES = [{ emitter: importerEvents, event: 'progress', channel: 'importer:progress' },{ emitter: catalogEvents, event: 'progress', channel: 'catalog:extract:progress' },{ emitter: catalogIdentityEvents, event: 'changed', channel: 'catalog:identity-changed' },+ // A GitHub notification inbox sync, triage or action changed stored rows.+ { emitter: githubNotificationEvents, event: 'changed', channel: 'github:notifications:changed' },{ emitter: aiStatusEvents, event: 'status', channel: 'ai:status' },// The call-host tab already gets `voice:call:state` from its own socket// handler (server/sockets/voice.js); this fans it out to every OTHER tab.diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 94415077b4..b714d57124 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -302,7 +302,7 @@ describe('taskSchedule', () => {// repo-sync sweeps every managed checkout; user-action-review reads the// install-wide operator-action ledger; error-log-triage reads PortOS's own// PM2 logs — none is a per-app run.- expect([...INSTALL_WIDE_TASK_TYPES]).toEqual(['repo-sync', 'user-action-review', 'model-comparison-refresh', 'error-log-triage'])+ expect([...INSTALL_WIDE_TASK_TYPES]).toEqual(['repo-sync', 'user-action-review', 'model-comparison-refresh', 'error-log-triage', 'github-notifications'])})it('every install-wide type is a registered task type', () => {diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.jsindex b2f5748866..e6a10fa2b3 100644--- a/server/services/taskScheduleRegistry.js+++ b/server/services/taskScheduleRegistry.js@@ -439,6 +439,11 @@ const TASK_INTERVAL_DEFAULTS = {// buildTaskInput hook never spawns a coordinator agent — hence no prompt.// taskMetadata holds the run caps (lib/cosValidation.js clamps them).'error-log-triage': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: Object.fromEntries(Object.entries(ERROR_LOG_TRIAGE_LIMITS).map(([key, limit]) => [key, limit.default])) },+ // github-notifications (#12871) syncs and triages the GitHub accounts on+ // Dev Tools › GitHub. Off by default like every shipped task (other installs+ // must not start polling GitHub on upgrade); the Automations tab sets the+ // weekday cadence in one tap. No provider call and no coordinator agent.+ 'github-notifications': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null },// layered-intelligence is a programmatic-I/O task (agent-backed, hooked). On-demand// by default; per-app scheduling (enabled/interval/provider/model) is set in the// Intelligence tab and stored on the app's taskTypeOverrides['layered-intelligence'].@@ -657,6 +662,7 @@ export const TASK_TYPE_DESCRIPTIONS = {'media-render-research': 'Research local Apple Silicon image/video models, runtimes and settings; file ready-to-work issues for improvements (no code)','user-action-review': 'Review the operator-action log for repeated manual work and propose automations — file issues (default) or queue CoS tasks','error-log-triage': 'Triage new stderr lines from PortOS processes — fingerprint and dedupe against issues, then queue one investigation agent per new fault',+ 'github-notifications': 'Check each GitHub account\'s notifications and record a rule-based triage decision per thread — no model, no GitHub writes in Observe mode','layered-intelligence': "Use app goals + performance metrics to file at most one deduplicated improvement issue; inspect read-only context and file a visibility gap when evidence is insufficient — no code",'development-watchdog': 'Inspect maintainer repository ownership and queue eligible work without an inference call','music-video-autopilot': 'Turn the next unused Brain idea into a fully autonomous music video — lyrics, Suno song, mood board and video. No agent',@@ -692,6 +698,10 @@ export const TASK_TYPE_PROMPT_INFO = Object.freeze({mode: 'runtime-generated',description: 'PortOS reads its own stderr logs, fingerprints and redacts each new fault, and dedupes it against the issue tracker with no model call. Each new fault seen at least the configured number of times queues one investigation agent on the provider and model below, up to the per-run cap; that prompt is generated from the redacted excerpt.'}),+ 'github-notifications': Object.freeze({+ mode: 'runtime-generated',+ description: 'No prompt: PortOS fetches notification metadata for each account on Dev Tools › GitHub and applies fixed trust, spam and routing rules. Observe mode only records the decisions.'+ }),'layered-intelligence': Object.freeze({mode: 'runtime-generated',description: 'Generated for each run from the app\'s configured goals, metrics, and repository context.'diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex a048c8992c..478e9b6bec 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -86,6 +86,11 @@ const HOOK_MODULES = {'error-log-triage': {load: () => import('./errorLogTriageHooks.js')},+ // buildTaskInput only: syncs and triages the GitHub notification inboxes+ // and always skips — the pass is the run.+ 'github-notifications': {+ load: () => import('./githubNotificationsHooks.js')+ },};const PAYLOAD_OPTIONAL_OUTPUT_HOOKS = new Set();