Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
GitHub inbox: per-repo agent rules and a dashboard layout (#13100)
[._.]/51628b960b89
diff --git a/client/src/components/github/GitHubAgentRules.jsx b/client/src/components/github/GitHubAgentRules.jsxnew file mode 100644index 0000000000..c104158a4c--- /dev/null+++ b/client/src/components/github/GitHubAgentRules.jsx@@ -0,0 +1,169 @@+import { useEffect, useId, useRef, useState } from 'react';+import { Bot, Pencil, Plus, X } from 'lucide-react';+import ProviderModelSelector from '../ProviderModelSelector';+import useRunWithPicker from '../../hooks/useRunWithPicker';+import { AGENT_RULE_KINDS } from './githubTriageLabels';++const ALL_REPOS = '*';+const OTHER_REPO = '__other__';+const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;++const newRuleId = () => `rule-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;++const repoLabel = (repo) => (repo === ALL_REPOS ? 'All repos' : repo);++function pinLabel(rule, providers) {+ if (!rule.agent) return "Don't start an agent";+ const provider = rule.provider ? providers.find((entry) => entry.id === rule.provider)?.name || rule.provider : 'Auto provider';+ return ['Start an agent', provider, rule.model, rule.effort ? `${rule.effort} effort` : null].filter(Boolean).join(' · ');+}++function RuleForm({ rule, repos, takenKeys, onCancel, onSubmit, saving }) {+ const formId = useId();+ const picker = useRunWithPicker({ preselectDefaults: false });+ const [kind, setKind] = useState(rule?.kind || AGENT_RULE_KINDS[0].value);+ const knownRepo = !rule || rule.repo === ALL_REPOS || repos.includes(rule.repo);+ const [repoChoice, setRepoChoice] = useState(rule ? (knownRepo ? rule.repo : OTHER_REPO) : ALL_REPOS);+ const [otherRepo, setOtherRepo] = useState(knownRepo ? '' : rule?.repo || '');+ const [agent, setAgent] = useState(rule ? rule.agent : true);+ const seeded = useRef(false);+ const { loading, setSelectedProviderId, setSelectedModel, setEffort } = picker;+ useEffect(() => {+ // Seed the picker once its catalog has loaded, so a saved pin is not lost.+ if (!rule || seeded.current || loading) return;+ seeded.current = true;+ if (rule.provider) setSelectedProviderId(rule.provider);+ if (rule.model) setSelectedModel(rule.model);+ if (rule.effort) setEffort(rule.effort);+ }, [rule, loading, setSelectedProviderId, setSelectedModel, setEffort]);++ const repo = repoChoice === OTHER_REPO ? otherRepo.trim() : repoChoice;+ const repoValid = repo === ALL_REPOS || REPO_RE.test(repo);+ const clash = takenKeys.has(`${kind}#${repo.toLowerCase()}`);+ const submit = (event) => {+ event.preventDefault();+ if (!repoValid || clash) return;+ onSubmit({+ id: rule?.id || newRuleId(),+ kind,+ repo,+ agent,+ provider: agent ? picker.pin.provider || null : null,+ model: agent ? picker.pin.model || null : null,+ effort: agent ? picker.pin.effort || null : null,+ });+ };++ return (+ <form onSubmit={submit} className="space-y-3 rounded-lg border border-port-border bg-port-bg p-3" aria-label={rule ? 'Edit agent rule' : 'New agent rule'}>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">+ <label htmlFor={`${formId}-kind`} className="space-y-1 text-xs text-gray-400">+ <span className="block">When I get</span>+ <select id={`${formId}-kind`} value={kind} onChange={(event) => setKind(event.target.value)} className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-white">+ {AGENT_RULE_KINDS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}+ </select>+ </label>+ <label htmlFor={`${formId}-repo`} className="space-y-1 text-xs text-gray-400">+ <span className="block">In</span>+ <select id={`${formId}-repo`} value={repoChoice} onChange={(event) => setRepoChoice(event.target.value)} className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-white">+ <option value={ALL_REPOS}>All repos</option>+ {repos.map((name) => <option key={name} value={name}>{name}</option>)}+ <option value={OTHER_REPO}>Another repo…</option>+ </select>+ </label>+ <label htmlFor={`${formId}-agent`} className="space-y-1 text-xs text-gray-400">+ <span className="block">Then</span>+ <select id={`${formId}-agent`} value={agent ? 'agent' : 'none'} onChange={(event) => setAgent(event.target.value === 'agent')} className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-white">+ <option value="agent">Start a CoS agent</option>+ <option value="none">Don't start an agent</option>+ </select>+ </label>+ </div>+ {repoChoice === OTHER_REPO && (+ <label htmlFor={`${formId}-other`} className="block space-y-1 text-xs text-gray-400">+ <span className="block">Repo (owner/name)</span>+ <input id={`${formId}-other`} value={otherRepo} onChange={(event) => setOtherRepo(event.target.value)} placeholder="owner/repo" autoComplete="off" className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 font-mono text-sm text-white" />+ </label>+ )}+ {agent && (+ <div className="space-y-1">+ <span className="flex items-center gap-1.5 text-xs text-gray-400"><Bot size={12} aria-hidden="true" /> Run with</span>+ <ProviderModelSelector {...picker.selectorProps} compact />+ </div>+ )}+ <p className="text-xs text-gray-500">{AGENT_RULE_KINDS.find((option) => option.value === kind)?.hint}</p>+ {clash && <p role="alert" className="text-xs text-port-error">There is already a rule for this kind of notification in {repoLabel(repo)}.</p>}+ <div className="flex flex-wrap gap-2">+ <button type="submit" disabled={saving || !repoValid || clash} className="rounded bg-port-accent px-3 py-1.5 text-xs text-white disabled:opacity-50">+ {saving ? 'Saving…' : 'Save rule'}+ </button>+ <button type="button" onClick={onCancel} className="rounded border border-port-border px-3 py-1.5 text-xs text-gray-300">Cancel</button>+ </div>+ </form>+ );+}++/**+ * One account's agent rules: for each kind of notification, in one repo or all+ * of them, whether Autopilot starts a CoS agent and on which provider, model+ * and effort. A repo's own rule wins over its All repos rule.+ */+export default function GitHubAgentRules({ account, onSave, saving }) {+ const [editing, setEditing] = useState(null);+ const rules = account.agentRules || [];+ const { providers } = useRunWithPicker({ preselectDefaults: false });+ const repos = account.repos || [];+ const kindLabel = (kind) => AGENT_RULE_KINDS.find((option) => option.value === kind)?.label || kind;++ const save = async (next) => {+ const saved = await onSave(account.id, next);+ if (saved) setEditing(null);+ };+ const upsert = (rule) => save(rules.some((entry) => entry.id === rule.id) ? rules.map((entry) => (entry.id === rule.id ? rule : entry)) : [...rules, rule]);+ const remove = (id) => save(rules.filter((rule) => rule.id !== id));+ const takenKeys = new Set(rules.filter((rule) => rule.id !== editing?.id).map((rule) => `${rule.kind}#${rule.repo.toLowerCase()}`));++ return (+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <h4 className="text-xs font-semibold uppercase tracking-wide text-gray-400">Agent rules</h4>+ {!editing && (+ <button type="button" onClick={() => setEditing({ id: null })} className="inline-flex items-center gap-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300">+ <Plus size={12} aria-hidden="true" /> Add rule+ </button>+ )}+ </div>+ {account.mode !== 'autopilot' && rules.length > 0 && (+ <p className="text-xs text-port-warning">Autopilot follows these rules. This account is in {account.mode === 'assist' ? 'Assist' : 'Observe'}, so nothing starts on its own yet.</p>+ )}+ {rules.length === 0 && !editing && (+ <p className="text-xs text-gray-500">No rules: security alerts and outside issues and pull requests in your apps go to their usual agents, and other review requests wait for you.</p>+ )}+ {rules.length > 0 && (+ <ul className="divide-y divide-port-border">+ {rules.map((rule) => (editing?.id === rule.id ? (+ <li key={rule.id} className="py-2">+ <RuleForm rule={rule} repos={repos} takenKeys={takenKeys} onCancel={() => setEditing(null)} onSubmit={upsert} saving={saving} />+ </li>+ ) : (+ <li key={rule.id} className="flex min-w-0 items-center gap-2 py-2">+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm text-white">{kindLabel(rule.kind)} · <span className={rule.repo === ALL_REPOS ? '' : 'font-mono'}>{repoLabel(rule.repo)}</span></p>+ <p className={`truncate text-xs ${rule.agent ? 'text-port-success' : 'text-gray-400'}`}>{pinLabel(rule, providers)}</p>+ </div>+ <button type="button" onClick={() => setEditing(rule)} disabled={Boolean(editing)} className="inline-flex min-h-[44px] min-w-[44px] shrink-0 items-center justify-center rounded text-gray-400 hover:text-white disabled:opacity-40" aria-label={`Edit ${kindLabel(rule.kind)} rule for ${repoLabel(rule.repo)}`}>+ <Pencil size={14} aria-hidden="true" />+ </button>+ <button type="button" onClick={() => remove(rule.id)} disabled={saving} className="inline-flex min-h-[44px] min-w-[44px] shrink-0 items-center justify-center rounded text-gray-400 hover:text-white disabled:opacity-40" aria-label={`Remove ${kindLabel(rule.kind)} rule for ${repoLabel(rule.repo)}`}>+ <X size={14} aria-hidden="true" />+ </button>+ </li>+ )))}+ </ul>+ )}+ {editing && !editing.id && (+ <RuleForm rule={null} repos={repos} takenKeys={takenKeys} onCancel={() => setEditing(null)} onSubmit={upsert} saving={saving} />+ )}+ </div>+ );+}diff --git a/client/src/components/github/GitHubAutomationsTab.jsx b/client/src/components/github/GitHubAutomationsTab.jsxindex 22cc54e8eb..8626a05b5e 100644--- a/client/src/components/github/GitHubAutomationsTab.jsx+++ b/client/src/components/github/GitHubAutomationsTab.jsx@@ -17,6 +17,7 @@ import {updateGitHubAccount,} from '../../services/api';import { ACTION_LABELS, LEARNED_DECISION_LABELS } from './githubTriageLabels';+import GitHubAgentRules from './GitHubAgentRules';const MODE_OPTIONS = ['observe', 'assist', 'autopilot'];const MODE_LABELS = { observe: 'Observe', assist: 'Assist', autopilot: 'Autopilot' };@@ -30,7 +31,7 @@ function modeHint(account) {if (account.mode !== 'autopilot') return assist;const handoff = account.trust === 'private'? 'Private accounts never hand threads off.'- : 'Also hands outside review requests, outside issues and security alerts in your PortOS apps to Untrusted:Review, the issue watcher and dependency updates when those are on for the app, one run per app for each. A security alert in another repo of yours starts one CoS task per repo that fixes it in a pull request and merges it.';+ : 'Also hands outside review requests, outside issues and security alerts in your PortOS apps to Untrusted:Review, the issue watcher and dependency updates when those are on for the app, one run per app for each. A security alert in another repo of yours starts one CoS task per repo that fixes it in a pull request and merges it. Agent rules below turn kinds on or off per repo and pick the provider.';return `${assist} ${handoff}`;}@@ -40,7 +41,7 @@ const CADENCE_TEXT = {off: 'Only when you tap Run now',};-function AccountCard({ account, running, onRun, onMode, savingMode }) {+function AccountCard({ account, running, onRun, onMode, savingMode, onSaveRules, savingRules }) {const selectId = `github-mode-${account.id}`;return (<li className="min-w-0 space-y-2 rounded-lg border border-port-border bg-port-card p-4">@@ -78,6 +79,7 @@ function AccountCard({ account, running, onRun, onMode, savingMode }) {><Play size={12} aria-hidden="true" /> {running ? 'Checking…' : 'Run now'}</button>+ {account.trust !== 'private' && <GitHubAgentRules account={account} onSave={onSaveRules} saving={savingRules} />}</li>);}@@ -141,6 +143,7 @@ export default function GitHubAutomationsTab() {const [actions, setActions] = useState([]);const [rules, setRules] = useState([]);const [savingModeId, setSavingModeId] = useState(null);+ const [savingRulesId, setSavingRulesId] = useState(null);const [undoingId, setUndoingId] = useState(null);const load = useCallback(async () => {@@ -185,6 +188,15 @@ export default function GitHubAutomationsTab() {setOverview((prev) => ({ ...prev, accounts: prev.accounts.map((account) => (account.id === accountId ? { ...account, mode: updated.mode } : account)) }));};+ const saveRules = async (accountId, agentRules) => {+ setSavingRulesId(accountId);+ const updated = await updateGitHubAccount(accountId, { agentRules }).catch(() => null);+ setSavingRulesId(null);+ if (!updated) return false;+ setOverview((prev) => ({ ...prev, accounts: prev.accounts.map((account) => (account.id === accountId ? { ...account, agentRules: updated.agentRules || [] } : account)) }));+ return true;+ };+const undo = async (id) => {setUndoingId(id);const undone = await undoGitHubAutomationAction(id).catch(() => null);@@ -239,7 +251,7 @@ export default function GitHubAutomationsTab() {) : (<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} onMode={changeMode} savingMode={savingModeId === account.id} />+ <AccountCard key={account.id} account={account} running={runningId === account.id} onRun={runNow} onMode={changeMode} savingMode={savingModeId === account.id} onSaveRules={saveRules} savingRules={savingRulesId === account.id} />))}</ul>)}diff --git a/client/src/components/github/GitHubInboxTab.jsx b/client/src/components/github/GitHubInboxTab.jsxindex 2904b04939..9745aec07c 100644--- a/client/src/components/github/GitHubInboxTab.jsx+++ b/client/src/components/github/GitHubInboxTab.jsx@@ -1,14 +1,18 @@import { useCallback, useEffect, useRef, useState } from 'react';import { Link, useParams } from 'react-router';-import { Bot, ExternalLink, RefreshCw } from 'lucide-react';+import {+ Bell, BellOff, Bot, Check, CheckCircle2, CircleDot, CircleX, ExternalLink, GitCommitHorizontal, GitPullRequest,+ Inbox, Layers, Mail, MailX, MessagesSquare, RefreshCw, ShieldAlert, Tag,+} from 'lucide-react';import Pill from '../ui/Pill';+import OverflowMenu from '../ui/OverflowMenu';import GitHubThreadDrawer from './GitHubThreadDrawer';import { AGENT_REFUSED_LABELS, DECISION_VIEW, TRUST_VIEW } from './githubTriageLabels';import socket from '../../services/socket';import LoadFailedState from '../ui/LoadFailedState';import PageSkeleton from '../ui/PageSkeleton';import CollapsibleListItem from '../ui/CollapsibleListItem';-import { timeAgo } from '../../utils/formatters';+import { formatCount, timeAgo } from '../../utils/formatters';import {getGitHubAccounts,getGitHubNotifications,@@ -17,13 +21,6 @@ import {resolveGitHubNotificationWithAgent,} from '../../services/api';-const VIEWS = [- { id: 'needs-you', label: 'Needs you' },- { id: 'suspect', label: 'Suspect' },- { id: 'handled', label: 'Handled' },- { id: 'all', label: 'All' },-];-// GitHub's `reason` vocabulary, phrased for a glance.const REASON_LABELS = {assign: 'Assigned',@@ -49,16 +46,13 @@ const UNDO_ACTIONS = {unsubscribed: { action: 'resubscribe', label: 'Resubscribe' },};-const OPEN_ACTIONS = [- { action: 'done', label: 'Done' },- { action: 'mute', label: 'Mute' },- { action: 'unsubscribe', label: 'Unsubscribe' },+const DONE_ACTION = { action: 'done', label: 'Done' };+// Rarer and harder to undo than Done, so they sit in the row's overflow menu.+const MORE_ACTIONS = [+ { action: 'mute', label: 'Mute', icon: BellOff },+ { action: 'unsubscribe', label: 'Unsubscribe', icon: MailX },];-const chipClass = (active) => `shrink-0 rounded-full border px-3 py-1.5 text-xs ${active- ? 'border-port-accent/40 bg-port-accent/20 text-port-accent'- : 'border-port-border bg-port-bg text-gray-400'}`;-// Mirrors HANDLED_DECISIONS in server/lib/githubNotificationTriage.js:// nothing is left for you on these threads, so they sit under Handled.const HANDLED_DECISIONS = new Set(['handled-by-pr-workflow', 'duplicate', 'handed-off', 'suggest-mark-read']);@@ -73,65 +67,161 @@ const VIEW_MATCHERS = {};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];+// The kind of thing a thread is about, as an icon and a word for screen readers.+const KIND_VIEW = {+ PullRequest: { icon: GitPullRequest, label: 'Pull request', className: 'text-port-accent' },+ Issue: { icon: CircleDot, label: 'Issue', className: 'text-port-success' },+ CheckSuite: { icon: CircleX, label: 'CI', className: 'text-port-error' },+ Release: { icon: Tag, label: 'Release', className: 'text-gray-300' },+ Discussion: { icon: MessagesSquare, label: 'Discussion', className: 'text-gray-300' },+ Commit: { icon: GitCommitHorizontal, label: 'Commit', className: 'text-gray-300' },+ RepositoryInvitation: { icon: Mail, label: 'Invitation', className: 'text-gray-300' },+};+const SECURITY_KIND = { icon: ShieldAlert, label: 'Security alert', className: 'text-port-error' };+const kindOf = (notification) => (notification.reason === 'security_alert'+ ? SECURITY_KIND+ : KIND_VIEW[notification.subjectType] || { icon: Bell, label: notification.subjectType || 'Notification', className: 'text-gray-400' });++// Summary tiles double as the view picker. Counts come from the server for+// every view at once; tone follows meaning, and every tile also has a label.+const TILES = [+ { id: 'needs-you', label: 'Needs you', icon: Inbox, iconClass: 'text-port-accent' },+ { id: 'suspect', label: 'Suspect', icon: ShieldAlert, iconClass: 'text-port-warning' },+ { id: 'handled', label: 'Handled', icon: CheckCircle2, iconClass: 'text-port-success' },+ { id: 'all', label: 'All', icon: Layers, iconClass: 'text-gray-400' },+];++function SummaryTiles({ view, counts, onSelect }) {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">- {notification.unread && <span className="h-2 w-2 shrink-0 rounded-full bg-port-accent" aria-label="Unread" />}- <span className="font-medium text-gray-300">{REASON_LABELS[notification.reason] || notification.reason}</span>- <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>- <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>}- {!handled && notification.agent?.refused && (- <p className="mt-1 text-xs text-gray-500">{AGENT_REFUSED_LABELS[notification.agent.refused] || notification.agent.refused}</p>- )}- {accountLabel && <p className="mt-0.5 text-xs text-gray-500">{accountLabel}</p>}- <div className="mt-2 flex flex-wrap gap-2">- {notification.htmlUrl && (- <a- href={notification.htmlUrl}- target="_blank"- rel="noopener noreferrer"- className="inline-flex items-center gap-1 rounded border border-port-border px-3 py-1.5 text-xs text-gray-300"- >- <ExternalLink size={12} aria-hidden="true" /> Open- </a>- )}- {!handled && notification.agent && !notification.agent.refused && (+ <div className="grid grid-cols-2 gap-2 @3xl/page:grid-cols-4" role="group" aria-label="Inbox view">+ {TILES.map((tile) => {+ const active = view === tile.id;+ const count = counts?.[tile.id];+ return (<button+ key={tile.id}type="button"- disabled={busy}- onClick={() => onAction(notification, 'agent')}- className="inline-flex items-center gap-1 rounded border border-port-accent/40 bg-port-accent/10 px-3 py-1.5 text-xs text-port-accent disabled:opacity-50"+ aria-pressed={active}+ onClick={() => onSelect(tile.id)}+ className={`min-w-0 rounded-xl border p-3 text-left transition-colors ${active+ ? 'border-port-accent/60 bg-port-accent/10'+ : 'border-port-border bg-port-card hover:border-port-accent/30'}`}>- <Bot size={12} aria-hidden="true" /> Resolve with agent+ <span className="flex items-center gap-1.5 text-xs text-gray-400">+ <tile.icon size={14} className={tile.iconClass} aria-hidden="true" />+ {tile.label}+ </span>+ <span className="mt-1 block text-2xl font-semibold tabular-nums text-white">{formatCount(count)}</span></button>- )}- {(handled ? [UNDO_ACTIONS[notification.state]].filter(Boolean) : OPEN_ACTIONS).map(({ action, label }) => (- <button- key={action}- type="button"- disabled={busy}- onClick={() => onAction(notification, action)}- className="rounded border border-port-border px-3 py-1.5 text-xs text-gray-300 disabled:opacity-50"+ );+ })}+ </div>+ );+}++function RepoFilter({ repos, repo, onSelect, total }) {+ const item = (value, label, count) => {+ const active = repo === value;+ return (+ <li key={value ?? '*'}>+ <button+ type="button"+ aria-pressed={active}+ onClick={() => onSelect(value)}+ className={`flex w-full min-w-0 items-center gap-2 rounded-lg px-2.5 py-2 text-left text-xs ${active ? 'bg-port-accent/15 text-white' : 'text-gray-400 hover:bg-port-card hover:text-gray-200'}`}+ >+ <span className={`min-w-0 flex-1 truncate ${value ? 'font-mono' : ''}`}>{label}</span>+ <span className="shrink-0 tabular-nums text-gray-500">{formatCount(count)}</span>+ </button>+ </li>+ );+ };+ return (+ <nav aria-label="Repositories" className="min-w-0">+ <h2 className="mb-1 px-2.5 text-xs font-semibold uppercase tracking-wide text-gray-500">Repositories</h2>+ <ul className="space-y-0.5">+ {item(null, 'All repositories', total)}+ {repos.map(([name, count]) => item(name, name || 'Advisories', count))}+ </ul>+ </nav>+ );+}++function NotificationRow({ notification, accountLabel, busy, onAction }) {+ const handled = notification.state !== 'open';+ const trust = TRUST_VIEW[notification.trust];+ const decision = DECISION_VIEW[notification.decision];+ const kind = kindOf(notification);+ const canResolve = !handled && notification.agent && !notification.agent.refused;+ const overflow = handled ? [] : MORE_ACTIONS.map(({ action, label, icon }) => ({+ id: action, label, icon, disabled: busy, onSelect: () => onAction(notification, action),+ }));+ return (+ <article className="flex min-w-0 gap-3 px-3 py-3 @3xl/page:px-4">+ <span className="relative mt-0.5 shrink-0">+ <kind.icon size={18} className={kind.className} aria-label={kind.label} role="img" />+ {notification.unread && <span className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-port-accent ring-2 ring-port-card" aria-label="Unread" />}+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-2 @3xl/page:flex-row @3xl/page:items-start">+ <div className="min-w-0 flex-1">+ <Link+ to={`/devtools/github/inbox/${encodeURIComponent(notification.accountId)}/${notification.threadId}`}+ className={`block break-words text-sm hover:underline ${notification.unread ? 'font-semibold text-white' : 'text-gray-200'}`}>- {label}- </button>- ))}+ {notification.title}+ </Link>+ <div className="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-gray-400">+ <span className="text-gray-300">{REASON_LABELS[notification.reason] || notification.reason}</span>+ {notification.repoFullName && <span className="min-w-0 truncate font-mono">{notification.repoFullName}</span>}+ <span className="shrink-0">· {timeAgo(notification.updatedAt)}</span>+ {accountLabel && <span className="shrink-0">· {accountLabel}</span>}+ </div>+ <div className="mt-1.5 flex flex-wrap items-center gap-1.5">+ {decision && <Pill tone={decision.tone}>{decision.label}</Pill>}+ {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>}+ </div>+ {!handled && notification.agent?.refused && (+ <p className="mt-1 text-xs text-gray-500">{AGENT_REFUSED_LABELS[notification.agent.refused] || notification.agent.refused}</p>+ )}+ </div>+ <div className="flex shrink-0 flex-wrap items-center gap-1.5">+ {canResolve && (+ <button+ type="button"+ disabled={busy}+ onClick={() => onAction(notification, 'agent')}+ className="inline-flex min-h-[36px] items-center gap-1 rounded-lg bg-port-accent px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50"+ >+ <Bot size={13} aria-hidden="true" /> Resolve with agent+ </button>+ )}+ {(handled ? [UNDO_ACTIONS[notification.state]].filter(Boolean) : [DONE_ACTION]).map(({ action, label }) => (+ <button+ key={action}+ type="button"+ disabled={busy}+ onClick={() => onAction(notification, action)}+ className="inline-flex min-h-[36px] items-center gap-1 rounded-lg border border-port-border px-3 py-1.5 text-xs text-gray-200 hover:border-gray-500 disabled:opacity-50"+ >+ {action === 'done' && <Check size={13} aria-hidden="true" />}+ {label}+ </button>+ ))}+ {notification.htmlUrl && (+ <a+ href={notification.htmlUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex min-h-[36px] items-center gap-1 rounded-lg border border-port-border px-3 py-1.5 text-xs text-gray-300 hover:border-gray-500"+ >+ <ExternalLink size={12} aria-hidden="true" /> Open+ </a>+ )}+ {overflow.length > 0 && <OverflowMenu label={`More actions for ${notification.title}`} items={overflow} />}+ </div></div></article>);@@ -142,6 +232,7 @@ export default function GitHubInboxTab() {const [accounts, setAccounts] = useState(null);const [accountId, setAccountId] = useState(null);const [view, setView] = useState('needs-you');+ const [repo, setRepo] = useState(null);const [data, setData] = useState(null);const [loadFailed, setLoadFailed] = useState(false);const [syncing, setSyncing] = useState(false);@@ -225,67 +316,105 @@ export default function GitHubInboxTab() {if (loadFailed && !data) return <LoadFailedState title="Could not load GitHub notifications." hint="Retry the local inbox read." onRetry={loadList} />;if (!data) return <PageSkeleton label="Loading GitHub notifications" titleWidthClass="w-40" showAction={false} cards={3} />;+ const rows = data.notifications;+ // The repo list is built from the loaded view, so it always matches the rows.+ const repoCounts = [...rows.reduce((map, row) => map.set(row.repoFullName, (map.get(row.repoFullName) || 0) + 1), new Map())]+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));+ const activeRepo = repo !== null && repoCounts.some(([name]) => name === repo) ? repo : null;+ const shown = activeRepo === null ? rows : rows.filter((row) => row.repoFullName === activeRepo);+ const repoSelectId = 'github-inbox-repo';+return (- <div className="min-w-0 space-y-3">- <div className="flex items-center gap-2">- <div className="flex min-w-0 flex-1 gap-2 overflow-x-auto" role="group" aria-label="Inbox view">- {VIEWS.map((entry) => (- <button key={entry.id} type="button" aria-pressed={view === entry.id} onClick={() => setView(entry.id)} className={chipClass(view === entry.id)}>- {entry.label}- </button>- ))}- </div>+ <div className="min-w-0 space-y-4">+ <div className="flex flex-wrap items-center gap-2">+ {enabledAccounts.length > 1 && (+ <>+ <label htmlFor="github-inbox-account" className="sr-only">Account</label>+ <select+ id="github-inbox-account"+ value={accountId || ''}+ onChange={(event) => setAccountId(event.target.value || null)}+ className="rounded-lg border border-port-border bg-port-card px-2.5 py-1.5 text-xs text-white"+ >+ <option value="">All accounts</option>+ {enabledAccounts.map((account) => <option key={account.id} value={account.id}>{account.label}</option>)}+ </select>+ </>+ )}+ <span className="text-xs text-gray-500">{lastSyncAt ? `Checked ${timeAgo(lastSyncAt)}` : 'Not checked yet'}</span><buttontype="button"onClick={refresh}disabled={syncing}- className="inline-flex shrink-0 items-center gap-1.5 rounded border border-port-border px-3 py-1.5 text-xs text-gray-300 disabled:opacity-60"+ className="ml-auto inline-flex min-h-[36px] shrink-0 items-center gap-1.5 rounded-lg border border-port-border bg-port-card px-3 py-1.5 text-xs text-gray-200 disabled:opacity-60"><RefreshCw size={12} className={syncing ? 'animate-spin' : ''} aria-hidden="true" />{syncing ? 'Checking…' : 'Refresh'}</button></div>- {enabledAccounts.length > 1 && (- <div className="flex gap-2 overflow-x-auto" role="group" aria-label="Account">- <button type="button" aria-pressed={!accountId} onClick={() => setAccountId(null)} className={chipClass(!accountId)}>All accounts</button>- {enabledAccounts.map((account) => (- <button key={account.id} type="button" aria-pressed={accountId === account.id} onClick={() => setAccountId(account.id)} className={chipClass(accountId === account.id)}>- {account.label}- </button>- ))}- </div>+ <SummaryTiles view={view} counts={data.counts} onSelect={setView} />+ {data.counts?.['with-agents'] > 0 && (+ <p className="flex items-center gap-1.5 text-xs text-gray-400">+ <Bot size={13} className="text-port-accent" aria-hidden="true" />+ {formatCount(data.counts['with-agents'])} with an agent now+ </p>)}{syncErrors.map(([id, state]) => (- <p key={id} role="alert" className="rounded border border-port-error/40 bg-port-error/10 p-2 text-xs text-port-error break-words">+ <p key={id} role="alert" className="rounded-lg border border-port-error/40 bg-port-error/10 p-2 text-xs text-port-error break-words">{accounts?.find((account) => account.id === id)?.label || id}: {state.lastError}</p>))}- {data.notifications.length === 0 ? (- <p className="rounded-lg border border-port-border bg-port-card p-4 text-sm text-gray-400">- {{ 'needs-you': 'Nothing needs you right now.', suspect: 'Nothing suspicious.' }[view] || 'No notifications here.'}- </p>- ) : (- <div className="min-w-0">- {data.notifications.map((notification) => {- const key = keyOf(notification);- return (- <CollapsibleListItem key={key} removing={removing.has(key)} onExited={() => dropRow(key)}>- <NotificationCard- notification={notification}- accountLabel={labelFor(notification.accountId)}- busy={busyKey === key || removing.has(key)}- onAction={handleAction}- />- </CollapsibleListItem>- );- })}- </div>- )}+ <div className="grid min-w-0 grid-cols-1 gap-4 @5xl/page:grid-cols-[15rem_minmax(0,1fr)]">+ {repoCounts.length > 1 && (+ <>+ <div className="hidden @5xl/page:block">+ <RepoFilter repos={repoCounts} repo={activeRepo} onSelect={setRepo} total={rows.length} />+ </div>+ <div className="@5xl/page:hidden">+ <label htmlFor={repoSelectId} className="sr-only">Repository</label>+ <select+ id={repoSelectId}+ value={activeRepo ?? '*'}+ onChange={(event) => setRepo(event.target.value === '*' ? null : event.target.value)}+ className="w-full rounded-lg border border-port-border bg-port-card px-2.5 py-2 text-sm text-white"+ >+ <option value="*">All repositories ({formatCount(rows.length)})</option>+ {repoCounts.map(([name, count]) => <option key={name} value={name}>{name || 'Advisories'} ({formatCount(count)})</option>)}+ </select>+ </div>+ </>+ )}+ <section+ aria-label="Notifications"+ className={`min-w-0 overflow-hidden rounded-xl border border-port-border bg-port-card ${repoCounts.length > 1 ? '' : '@5xl/page:col-span-2'}`}+ >+ {shown.length === 0 ? (+ <p className="p-6 text-center text-sm text-gray-400">+ {{ 'needs-you': 'Nothing needs you right now.', suspect: 'Nothing suspicious.' }[view] || 'No notifications here.'}+ </p>+ ) : (+ <div className="min-w-0 divide-y divide-port-border">+ {shown.map((notification) => {+ const key = keyOf(notification);+ return (+ <CollapsibleListItem key={key} removing={removing.has(key)} onExited={() => dropRow(key)}>+ <NotificationRow+ notification={notification}+ accountLabel={labelFor(notification.accountId)}+ busy={busyKey === key || removing.has(key)}+ onAction={handleAction}+ />+ </CollapsibleListItem>+ );+ })}+ </div>+ )}+ </section>+ </div>- {lastSyncAt && <p className="text-xs text-gray-500">Checked {timeAgo(lastSyncAt)}</p>}{threadId && routeAccountId && (<GitHubThreadDrawer accountId={routeAccountId} threadId={threadId} />)}diff --git a/client/src/components/github/githubTriageLabels.js b/client/src/components/github/githubTriageLabels.jsindex 3915019254..0e2545936e 100644--- a/client/src/components/github/githubTriageLabels.js+++ b/client/src/components/github/githubTriageLabels.js@@ -62,8 +62,16 @@ export const LANE_VIEW = {'dependency-updates': { label: 'dependency updates', tab: 'tasks' },// A one-off CoS task in a scratch clone, for a repo no app manages.'security-fix': { label: 'a security fix agent', tab: null },+ 'do-review': { label: 'a Do:Review agent', tab: 'pull-requests' },};+// The notification kinds an agent rule can name (GITHUB_AGENT_RULE_KINDS on the server).+export const AGENT_RULE_KINDS = [+ { value: 'review-request', label: 'Review requests', hint: 'A review request starts a review-only Do:Review run that publishes an inline review. An outside pull request in one of your apps goes to Untrusted:Review instead.' },+ { value: 'security-alert', label: 'Security alerts', hint: 'A security alert starts a run that updates the vulnerable dependencies, opens a pull request and merges it when checks pass.' },+ { value: 'issue-activity', label: 'Issue activity', hint: 'Outside activity on an issue in one of your apps goes to its issue watcher.' },+];+// Why Resolve with agent is unavailable for a thread.export const AGENT_REFUSED_LABELS = {'private-account': 'Private accounts never hand off to an agent',diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsxindex 1d05a917e7..c8c9a87546 100644--- a/client/src/pages/GitHub.test.jsx+++ b/client/src/pages/GitHub.test.jsx@@ -37,6 +37,10 @@ const mock = vi.hoisted(() => ({}));vi.mock('../services/api', () => mock);+vi.mock('../services/apiLocalLlm', () => ({+ getToolUseModels: vi.fn().mockResolvedValue({ models: [] }),+ getVisionModels: vi.fn().mockResolvedValue({ models: [] }),+}));vi.mock('../services/socket', () => {const listeners = new Map();@@ -424,7 +428,7 @@ describe('GitHub inbox tab', () => {});mock.applyGitHubNotificationAction.mockImplementation(async (_account, threadId) => ({ ...NOTIFICATION, threadId, state: 'open' }));renderTab('inbox');- fireEvent.click(await screen.findByRole('button', { name: 'Handled' }));+ fireEvent.click(await screen.findByRole('button', { name: /^Handled/ }));fireEvent.click(await screen.findByRole('button', { name: 'Back to inbox' }));fireEvent.click(screen.getByRole('button', { name: 'Unmute' }));await waitFor(() => expect(mock.applyGitHubNotificationAction).toHaveBeenCalledTimes(2));@@ -433,6 +437,20 @@ describe('GitHub inbox tab', () => {await act(async () => {});});+ it('shows each view count in its tile and narrows the list to one repository', async () => {+ mock.getGitHubNotifications.mockResolvedValue({+ notifications: [NOTIFICATION, { ...NOTIFICATION, threadId: '102', title: 'Other repo change', repoFullName: 'octocat/other' }],+ counts: { 'needs-you': 2, suspect: 0, handled: 14, all: 16, 'with-agents': 3 },+ sync: {},+ });+ renderTab('inbox');+ expect(await screen.findByRole('button', { name: 'Handled 14' })).toBeTruthy();+ expect(screen.getByText('3 with an agent now')).toBeTruthy();+ fireEvent.change(screen.getByLabelText('Repository'), { target: { value: 'octocat/other' } });+ expect(screen.queryByText('Example change')).toBeNull();+ expect(screen.getByText('Other repo change')).toBeTruthy();+ });+it('shows a failed sync for the account instead of an empty inbox', async () => {mock.getGitHubNotifications.mockResolvedValue({notifications: [], sync: { 'github-com': { lastSyncAt: null, lastError: 'gh cannot act as github.com (not-authenticated).' } },@@ -458,7 +476,7 @@ describe('GitHub inbox triage', () => {expect(await screen.findByText('Suggest Untrusted:Review')).toBeTruthy();expect(screen.getByText('Outside')).toBeTruthy();- fireEvent.click(screen.getByRole('button', { name: 'Suspect' }));+ 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;@@ -547,6 +565,30 @@ describe('GitHub automations tab', () => {await waitFor(() => expect(mock.syncGitHubNotifications).toHaveBeenCalledWith('github-com', { silent: true }));await waitFor(() => expect(mock.getGitHubAutomations).toHaveBeenCalledTimes(2));});++ it('adds an agent rule for review requests in one repo and refuses a duplicate', async () => {+ mock.getProviders.mockResolvedValue({ providers: [{ id: 'example-provider', name: 'Example Provider', type: 'cli', enabled: true, models: ['example-model'], defaultModel: 'example-model' }] });+ mock.getGitHubAutomations.mockResolvedValue({+ ...OVERVIEW,+ accounts: [{ ...OVERVIEW.accounts[0], mode: 'autopilot', agentRules: [{ id: 'rule-1', kind: 'review-request', repo: '*', agent: false }], repos: ['octocat/hello'] }],+ });+ mock.updateGitHubAccount.mockImplementation(async (id, data) => ({ id, ...data }));+ renderTab('automations');++ expect(await screen.findByText("Don't start an agent")).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /Add rule/ }));+ // Same kind and repo as the existing rule: refused until changed.+ expect(await screen.findByText(/There is already a rule/)).toBeTruthy();+ fireEvent.change(screen.getByLabelText('In'), { target: { value: 'octocat/hello' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save rule' }));+ await waitFor(() => expect(mock.updateGitHubAccount).toHaveBeenCalledWith('github-com', {+ agentRules: [+ { id: 'rule-1', kind: 'review-request', repo: '*', agent: false },+ expect.objectContaining({ kind: 'review-request', repo: 'octocat/hello', agent: true }),+ ],+ }));+ expect(await screen.findByText('octocat/hello', { selector: 'span' })).toBeTruthy();+ });});describe('GitHub audit tab', () => {diff --git a/server/lib/README.md b/server/lib/README.mdindex f3fa707383..5ea5682669 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -487,7 +487,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. || `githubNotificationAudit.js` | `AUDIT_WINDOW_DAYS`, `buildAuditSuggestions` — the GitHub notifications subscription audit's suggestions from 30 days of stored threads per repo × reason: unwatch, mute handled threads, and links for settings the API cannot change. || `githubNotificationParse.js` | `parseGhIncludeOutput`, `linkHeaderHasNext`, `pollIntervalSeconds`, `repoApiPath`, `advisoryIdFromUrl`, `GHSA_RE`, `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`, `ASSIST_VERDICTS`, `decisionFromVerdict`, `learnedDecisionForAction`, `applyLearnedRule`, `assistAction`, `selectNotificationProvider` — the GitHub inbox's fixed trust, spam and routing rules plus Assist's verdict enum, learned rules, allowed actions and Private-account provider allow-list; trust comes only from accounts, repo ownership and forge permissions, never from content. |+| `githubNotificationTriage.js` | `TRIAGE_DECISIONS`, `TRUST_LEVELS`, `MASS_MENTION_THRESHOLD`, `computeThreadTrust`, `spamSignals`, `parseCiBranch`, `decideThread`, `ASSIST_VERDICTS`, `decisionFromVerdict`, `learnedDecisionForAction`, `applyLearnedRule`, `assistAction`, `selectNotificationProvider`, `agentHandoff`, `autopilotHandoff`, `agentRuleScope` — the GitHub inbox's fixed trust, spam and routing rules plus Assist's verdict enum, learned rules, allowed actions and Private-account provider allow-list, plus agent lanes and per-repo agent 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/githubNotificationTriage.js b/server/lib/githubNotificationTriage.jsindex 5b4e147ee6..e55dbdea5e 100644--- a/server/lib/githubNotificationTriage.js+++ b/server/lib/githubNotificationTriage.js@@ -193,26 +193,91 @@ export function selectNotificationProvider({ account, providers = [], policy = {const HANDOFF_ISSUE_DECISIONS = new Set(['needs-you', 'surface']);const PULL_PATH_RE = /\/pulls\/(\d{1,9})$/;+// The notification kinds an agent rule can name (GITHUB_AGENT_RULE_KINDS in+// lib/validation.js), and the kind of a thread, or null when no rule applies.+const RULE_KINDS = new Set(['review-request', 'security-alert', 'issue-activity']);+const RULE_REPO_RE = /^(?:\*|[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100})$/;+// A review request still waiting on you; one you sorted as done or noise is not.+const REVIEW_DECISIONS = new Set(['suggest-review', 'suggest-untrusted-review', 'needs-you', 'surface']);+const REVIEW_TRUST = new Set(['yours', 'trusted']);++function threadAgentKind(row) {+ if (row?.reason === 'security_alert') return 'security-alert';+ if (row?.reason === 'review_requested' && row.subject_type === 'PullRequest') return 'review-request';+ if (row?.subject_type === 'Issue') return 'issue-activity';+ return null;+}++/**+ * The account's agent rule for a kind of thread in a repo: the repo's own rule,+ * else the `*` rule, else null. A malformed stored rule is ignored.+ */+const validRules = (rules, kind) => (Array.isArray(rules) ? rules : []).filter((rule) => rule+ && RULE_KINDS.has(rule.kind) && rule.kind === kind+ && typeof rule.repo === 'string' && RULE_REPO_RE.test(rule.repo) && typeof rule.agent === 'boolean');++function matchAgentRule(rules, kind, repo) {+ if (!kind) return null;+ const valid = validRules(rules, kind);+ const name = String(repo || '').toLowerCase();+ return (name && valid.find((rule) => rule.repo.toLowerCase() === name)) || valid.find((rule) => rule.repo === '*') || null;+}++/**+ * Which repos Autopilot hands a kind of thread off in, for its candidate query:+ * every repo except `except` when `all`, else only the `only` repos (lowercase).+ * The `*` rule sets the default; a kind with no `*` rule is on unless `optIn`.+ * Mirrors `matchAgentRule` + `autopilotHandoff`, so a row a rule keeps from an+ * agent never takes a slot in the run.+ */+export function agentRuleScope(rules, kind, { optIn = false } = {}) {+ const valid = validRules(rules, kind);+ const star = valid.find((rule) => rule.repo === '*');+ const all = star ? star.agent : !optIn;+ const repos = (agent) => valid.filter((rule) => rule.repo !== '*' && rule.agent === agent).map((rule) => rule.repo.toLowerCase());+ return all ? { all, except: repos(false), only: [] } : { all, except: [], only: repos(true) };+}++const rulePin = (rule) => {+ const pin = {};+ for (const key of ['provider', 'model', 'effort']) if (typeof rule?.[key] === 'string' && rule[key]) pin[key] = rule[key];+ return Object.keys(pin).length ? pin : null;+};+/*** Which lane an agent may resolve a thread in, or null when no lane fits. A- * plan with `refused` names why it cannot go: only a PortOS managed app's- * repo has lanes (they run per app), except a security alert in a repo of- * yours or a global advisory (`security-fix`), and a Private account's threads never- * go, because the lanes use their own providers, which its provider- * allow-list cannot bind. Suspect and closed threads never qualify. The pull- * number comes from the subject's API url, never from a title or body. Used- * by Autopilot (#12874) and the inbox's Resolve with agent button.+ * plan with `refused` names why it cannot go: a Private account's threads never+ * go (the lanes use their own providers, which its allow-list cannot bind), and+ * the per-app lanes need the repo to be a PortOS managed app. Suspect and closed+ * threads never qualify. The pull number comes from the subject's API url and+ * the link from the stored html url, never from a title or body.+ *+ * Lanes: an outside PR's review request in a managed app goes to+ * `pr-reviewer`; a review request for a PR by you or a trusted author goes to+ * a review-only `/do:review` run+ * (`do-review`, opt-in for Autopilot through an agent rule); outside issue+ * activity to `issue-watcher`; a security alert to the app's+ * `dependency-updates`, or, in a repo of yours with no app or a global+ * advisory, a one-off `security-fix` run in a scratch clone. The account's+ * matching agent rule (`matchAgentRule`) adds its provider/model/effort pin.+ * Used by Autopilot and the inbox's Resolve with agent button.*/export function agentHandoff({ account, row }) {if (row?.state !== 'open' || row.suspect) return null;const evidence = row.evidence || {};+ const kind = threadAgentKind(row);+ const rule = matchAgentRule(account?.agentRules, kind, row.repo_full_name);let plan = null;- if (row.decision === 'suggest-untrusted-review' && row.subject_type === 'PullRequest') {+ if (kind === 'review-request' && REVIEW_DECISIONS.has(row.decision)) {const pullNumber = Number(PULL_PATH_RE.exec(String(row.subject_api_url || ''))?.[1]);- if (pullNumber > 0) plan = { lane: 'pr-reviewer', pullNumber };- } else if (row.subject_type === 'Issue' && HANDOFF_ISSUE_DECISIONS.has(row.decision) && (row.trust === 'outside' || evidence.commenter)) {+ // Only a PR by you or a trusted author goes to a plain /do:review run; an+ // outside PR goes to pr-reviewer, which screens untrusted content first and+ // needs a managed app (`needsApp` below refuses it otherwise).+ if (pullNumber > 0 && REVIEW_TRUST.has(row.trust)) plan = { lane: 'do-review', pullNumber, repo: row.repo_full_name, optIn: true };+ else if (pullNumber > 0 && row.decision === 'suggest-untrusted-review') plan = { lane: 'pr-reviewer', pullNumber };+ } else if (kind === 'issue-activity' && HANDOFF_ISSUE_DECISIONS.has(row.decision) && (row.trust === 'outside' || evidence.commenter)) {plan = { lane: 'issue-watcher' };- } else if (row.reason === 'security_alert' && row.decision === 'surface-high') {+ } else if (kind === 'security-alert' && row.decision === 'surface-high') {// A managed app's own dependency lane reads the repo's Dependabot alerts and// PRs, not the thread. A repo of yours with no app, or an advisory that// names no repo, gets a one-off security fix run that works in a scratch clone.@@ -221,12 +286,24 @@ export function agentHandoff({ account, row }) {: { lane: 'dependency-updates' };}if (!plan) return null;+ const pin = rulePin(rule);+ if (pin) plan.pin = pin;+ if (rule) plan.rule = { id: rule.id || null, agent: rule.agent };if (account?.trust === 'private') return { ...plan, refused: 'private-account' };- if (plan.lane !== 'security-fix' && evidence.repoManaged !== true) return { ...plan, refused: 'no-managed-app' };+ const needsApp = plan.lane !== 'security-fix' && plan.lane !== 'do-review';+ if (needsApp && evidence.repoManaged !== true) return { ...plan, refused: 'no-managed-app' };return plan;}-/** Autopilot's plan for a thread: `agentHandoff`, only in Autopilot mode. */+/**+ * Autopilot's plan for a thread: `agentHandoff` in Autopilot mode, minus+ * anything an agent rule switched off, and minus an opt-in lane no rule+ * switched on.+ */export function autopilotHandoff({ account, row }) {- return account?.mode === 'autopilot' ? agentHandoff({ account, row }) : null;+ if (account?.mode !== 'autopilot') return null;+ const plan = agentHandoff({ account, row });+ if (!plan || plan.rule?.agent === false) return null;+ if (plan.optIn && plan.rule?.agent !== true) return null;+ return plan;}diff --git a/server/lib/githubNotificationTriage.test.js b/server/lib/githubNotificationTriage.test.jsindex f506d98736..1d1dc39ee0 100644--- a/server/lib/githubNotificationTriage.test.js+++ b/server/lib/githubNotificationTriage.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import {- agentHandoff, applyLearnedRule, assistAction, autopilotHandoff, computeThreadTrust, decideThread, decisionFromVerdict, parseCiBranch,+ agentHandoff, agentRuleScope, applyLearnedRule, assistAction, autopilotHandoff, computeThreadTrust, decideThread, decisionFromVerdict, parseCiBranch,selectNotificationProvider, spamSignals,MASS_MENTION_THRESHOLD,} from './githubNotificationTriage.js';@@ -143,7 +143,7 @@ describe('selectNotificationProvider', () => {describe('autopilotHandoff', () => {const account = { mode: 'autopilot', trust: 'public' };const review = {- state: 'open', suspect: false, trust: 'outside', decision: 'suggest-untrusted-review', subject_type: 'PullRequest',+ state: 'open', suspect: false, trust: 'outside', reason: 'review_requested', decision: 'suggest-untrusted-review', subject_type: 'PullRequest',subject_api_url: 'https://api.github.com/repos/acme/app/pulls/42', evidence: { repoManaged: true },};const issue = { ...review, decision: 'needs-you', subject_type: 'Issue', subject_api_url: 'https://api.github.com/repos/acme/app/issues/7' };@@ -168,6 +168,43 @@ describe('autopilotHandoff', () => {expect(autopilotHandoff({ account, row: { ...issue, trust: 'trusted' } })).toBeNull();});+ it('sends a trusted PR to Do:Review only when a rule switches it on, and keeps outside PRs off it', () => {+ const trusted = { ...review, trust: 'trusted', decision: 'suggest-review', evidence: { repoManaged: false } };+ expect(autopilotHandoff({ account, row: trusted })).toBeNull();+ const rules = [{ id: 'r', kind: 'review-request', repo: '*', agent: true, effort: 'high' }];+ expect(autopilotHandoff({ account: { ...account, agentRules: rules }, row: trusted }))+ .toMatchObject({ lane: 'do-review', pullNumber: 42, pin: { effort: 'high' } });+ expect(autopilotHandoff({ account: { ...account, agentRules: rules }, row: { ...review, evidence: { repoManaged: false } } }))+ .toMatchObject({ lane: 'pr-reviewer', refused: 'no-managed-app' });+ });++ it('applies the repo rule over the * rule, case-insensitively, and ignores a malformed rule', () => {+ const rules = [+ { id: 'all', kind: 'security-alert', repo: '*', agent: true, model: 'wide' },+ { id: 'one', kind: 'security-alert', repo: 'ACME/App', agent: false },+ { id: 'bad', kind: 'security-alert', repo: 'not a repo', agent: true },+ ];+ const alert = { ...review, reason: 'security_alert', decision: 'surface-high', subject_type: 'RepositoryVulnerabilityAlert', trust: 'unknown' };+ expect(autopilotHandoff({ account: { ...account, agentRules: rules }, row: { ...alert, repo_full_name: 'acme/app' } })).toBeNull();+ expect(agentHandoff({ account: { ...account, agentRules: rules }, row: { ...alert, repo_full_name: 'acme/app' } }))+ .toMatchObject({ lane: 'dependency-updates', rule: { id: 'one', agent: false } });+ expect(autopilotHandoff({ account: { ...account, agentRules: rules }, row: { ...alert, repo_full_name: 'acme/other' } }))+ .toMatchObject({ lane: 'dependency-updates', pin: { model: 'wide' }, rule: { id: 'all' } });+ });++ it('scopes Autopilot candidates the way the rules decide them', () => {+ const rules = [+ { kind: 'review-request', repo: '*', agent: true },+ { kind: 'review-request', repo: 'Acme/Quiet', agent: false },+ { kind: 'security-alert', repo: '*', agent: false },+ { kind: 'security-alert', repo: 'acme/app', agent: true },+ ];+ expect(agentRuleScope(rules, 'review-request', { optIn: true })).toEqual({ all: true, except: ['acme/quiet'], only: [] });+ expect(agentRuleScope(rules, 'security-alert')).toEqual({ all: false, except: [], only: ['acme/app'] });+ expect(agentRuleScope([], 'issue-activity')).toEqual({ all: true, except: [], only: [] });+ expect(agentRuleScope([], 'review-request', { optIn: true })).toEqual({ all: false, except: [], only: [] });+ });+it('refuses every hand-off on a Private account, whose provider allow-list the lanes cannot honor', () => {expect(autopilotHandoff({ account: { ...account, trust: 'private' }, row: review })).toEqual({ lane: 'pr-reviewer', pullNumber: 42, refused: 'private-account' });});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 094f33bfe3..32768d4219 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -951,6 +951,30 @@ export const GITHUB_ACCOUNT_LOGIN_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/;export const GITHUB_ACCOUNT_TRUST_LEVELS = Object.freeze(['public', 'private']);export const GITHUB_ACCOUNT_MODES = Object.freeze(['observe', 'assist', 'autopilot']);+// Per-repo agent rules for the GitHub inbox: which kind of notification starts+// a CoS agent, in one repo (`owner/repo`) or every repo (`*`), and on which+// provider/model/effort. A repo rule wins over the `*` rule of the same kind.+export const GITHUB_AGENT_RULE_KINDS = Object.freeze(['review-request', 'security-alert', 'issue-activity']);+export const GITHUB_AGENT_RULE_REPO_RE = /^(?:\*|[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100})$/;+const emptyToNullString = (value) => (value === '' ? null : value);+export const githubAgentRuleSchema = z.object({+ id: z.string().regex(/^[A-Za-z0-9-]{1,64}$/),+ kind: z.enum(GITHUB_AGENT_RULE_KINDS),+ repo: z.string().trim().regex(GITHUB_AGENT_RULE_REPO_RE, 'Use owner/repo, or * for every repo'),+ agent: z.boolean(),+ provider: z.preprocess(emptyToNullString, z.string().trim().min(1).max(128).nullable()).optional(),+ model: z.preprocess(emptyToNullString, z.string().trim().min(1).max(200).nullable()).optional(),+ effort: z.preprocess(emptyToNullString, z.enum(EFFORT_LEVELS).nullable()).optional(),+}).strict();+export const githubAgentRulesSchema = z.array(githubAgentRuleSchema).max(200).superRefine((rules, ctx) => {+ const seen = new Set();+ rules.forEach((rule, index) => {+ const key = `${rule.kind}#${rule.repo.toLowerCase()}`;+ if (seen.has(key)) ctx.addIssue({ code: 'custom', path: [index, 'repo'], message: `There is already a ${rule.kind} rule for ${rule.repo}` });+ seen.add(key);+ });+});+export const githubAccountCreateSchema = z.object({label: z.string().trim().max(80).optional(),host: z.string().trim().toLowerCase()@@ -963,6 +987,7 @@ export const githubAccountCreateSchema = z.object({mode: z.enum(GITHUB_ACCOUNT_MODES).optional(),// Monthly subscription audit delivered as a PortOS notification (#12874).auditReport: z.boolean().optional(),+ agentRules: githubAgentRulesSchema.optional(),enabled: z.boolean().optional(),}).strict();diff --git a/server/services/githubAccounts.js b/server/services/githubAccounts.jsindex d02e6c3109..54c8952a4c 100644--- a/server/services/githubAccounts.js+++ b/server/services/githubAccounts.js@@ -47,6 +47,7 @@ const storedAccountSchema = z.object({allowedProviders: z.array(z.string()).nullable(),mode: z.enum(GITHUB_ACCOUNT_MODES),auditReport: z.boolean().optional(),+ agentRules: z.array(z.object({}).passthrough()).optional(),enabled: z.boolean(),createdAt: z.string(),updatedAt: z.string(),@@ -62,6 +63,7 @@ const implicitAccount = () => ({allowedProviders: null,mode: 'observe',auditReport: false,+ agentRules: [],enabled: true,createdAt: null,updatedAt: null,@@ -131,6 +133,7 @@ export function createAccount(input) {allowedProviders: data.allowedProviders ?? null,mode: data.mode || 'observe',auditReport: data.auditReport ?? false,+ agentRules: data.agentRules ?? [],enabled: data.enabled ?? true,createdAt: now,updatedAt: now,diff --git a/server/services/githubNotificationAutopilot.js b/server/services/githubNotificationAutopilot.jsindex 7773dab7ee..269b865ac9 100644--- a/server/services/githubNotificationAutopilot.js+++ b/server/services/githubNotificationAutopilot.js@@ -6,40 +6,53 @@* Untrusted:Review button), outside issue activity to `issue-watcher`, and a* security alert to `dependency-updates`. A security alert in a repo of yours* that no app manages, or a global advisory, goes to a one-off `security-fix`- * task (githubSecurityFixTask.js). The inbox's Resolve with agent button- * hands one thread off the same way on a tap, in any mode.+ * task (githubSecurityFixTask.js). Any other review request goes to a+ * review-only `/do:review` run (prDoReviewTask.js) once an agent rule switches+ * review requests on for its repo. The account's agent rules also switch a kind+ * off for a repo, and pin each run's provider/model/effort. The inbox's Resolve+ * with agent button hands one thread off the same way on a tap, in any mode.*- * Nothing here reads thread text or starts an agent: each hand-off queues the- * lane's own on-demand run, which re-screens its input with its own guards. The- * on-demand origin is automated, so the lane must be switched on for that app.- * Mentions or requests in repos the operator does not own are never handed off.+ * Nothing here reads thread text: each hand-off queues the lane's own run,+ * which re-screens its input with its own guards. The on-demand origin is+ * automated, so a per-app lane must be switched on for that app. Mentions in+ * repos the operator does not own are never handed off.*/import { query, withTransaction } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';import { advisoryIdFromUrl } from '../lib/githubNotificationParse.js';-import { agentHandoff, autopilotHandoff } from '../lib/githubNotificationTriage.js';+import { agentHandoff, agentRuleScope, autopilotHandoff } from '../lib/githubNotificationTriage.js';import { toPgJson } from '../lib/pgJson.js';import { managedAppsByRepoKey } from './githubNotificationTriage.js';import { queueSecurityFixTask } from './githubSecurityFixTask.js';+import { spawnPrDoReviewTask } from './prDoReviewTask.js';import { queueTargetedPrReview, readActiveTasks, readPendingOnDemandRequests, ACTIVE_TASK_STATUSES } from './prReviewerTargetedRun.js';import { triggerOnDemandTask } from './taskSchedule.js';import { ON_DEMAND_ORIGINS } from './taskScheduleConstants.js';// Threads per run, not agent runs: a run queues at most one agent per repo and lane.const MAX_HANDOFFS_PER_RUN = 50;-// The SQL mirror of `agentHandoff`'s lane rules, so a run's limit is spent-// only on threads that can be handed off and an older eligible thread is never-// starved by newer ones the rule would reject.-const CANDIDATE_SQL = `((decision = 'suggest-untrusted-review' AND subject_type = 'PullRequest')- OR (subject_type = 'Issue' AND decision IN ('needs-you', 'surface') AND (trust = 'outside' OR evidence->>'commenter' IS NOT NULL))- OR (reason = 'security_alert' AND decision = 'surface-high'))`;+// The SQL mirror of `agentHandoff`'s lane rules and the account's agent+// rules, so a run's limit is spent only on threads that can be handed off and+// an older eligible thread is never starved by newer ones the rules would+// reject. `inScope(n)` reads one `agentRuleScope` as parameters $n..$n+2.+const inScope = (n) => `(($${n}::boolean AND NOT (lower(repo_full_name) = ANY($${n + 1}::text[]))) OR lower(repo_full_name) = ANY($${n + 2}::text[]))`;+const CANDIDATE_SQL = `((reason = 'review_requested' AND subject_type = 'PullRequest' AND (+ (decision = 'suggest-untrusted-review' AND COALESCE(trust, '') NOT IN ('yours', 'trusted') AND (evidence->>'repoManaged')::boolean IS TRUE AND ${inScope(2)})+ OR (decision IN ('suggest-review', 'suggest-untrusted-review', 'needs-you', 'surface') AND trust IN ('yours', 'trusted') AND ${inScope(5)})))+ OR (subject_type = 'Issue' AND decision IN ('needs-you', 'surface') AND (trust = 'outside' OR evidence->>'commenter' IS NOT NULL)+ AND (evidence->>'repoManaged')::boolean IS TRUE AND ${inScope(8)})+ OR (reason = 'security_alert' AND decision = 'surface-high' AND ${inScope(11)}))`;+const scopeParams = ({ all, except, only }) => [all, except, only];++// Lanes that run without a managed app: a scratch clone, or `gh` in PR mode.+const APP_FREE_LANES = new Set(['security-fix', 'do-review']);/*** Queue the app's run of a whole-app lane unless one is already queued or* running. For pr-reviewer this is the sweep over every outside PR, so a run* narrowed to one PR does not count as one.*/-async function queueAppLane(taskType, app, origin) {+async function queueAppLane(taskType, app, origin, pin) {const covers = (target) => target === undefined || target === null;const [tasks, requests] = await Promise.all([readActiveTasks(), readPendingOnDemandRequests()]);// Unreadable state is not "nothing queued": fail closed rather than queue a@@ -49,17 +62,26 @@ async function queueAppLane(taskType, app, origin) {&& task.metadata?.analysisType === taskType && task.metadata?.app === app.id && covers(task.metadata?.targetPullRequest));if (running) return { duplicate: true, taskId: running.id };if (requests.some((request) => request?.taskType === taskType && request?.appId === app.id && covers(request?.targetPullRequest))) return { duplicate: true };- const request = await triggerOnDemandTask(taskType, app.id, { origin });+ const request = await triggerOnDemandTask(taskType, app.id, { origin, ...pin });return request?.error ? { error: request.error } : { requestId: request.id };}-async function queueLane(plan, app, origin, { account, rows }) {+async function queueLane(plan, app, origin, { account, rows, immediate = false }) {+ const pin = plan.pin || {};if (plan.lane === 'security-fix') {const advisories = plan.repo ? [] : rows.map((row) => advisoryIdFromUrl(row.subject_api_url, account.host)).filter(Boolean);- return queueSecurityFixTask({ account, repo: plan.repo || null, advisories, origin });+ return queueSecurityFixTask({ account, repo: plan.repo || null, advisories, origin, ...pin });+ }+ if (plan.lane === 'do-review') {+ // The stored html url is rebuilt from GitHub's own API url on the account's host.+ const url = rows[0]?.html_url || '';+ if (!url.endsWith(`/pull/${plan.pullNumber}`)) return { error: 'No pull request link for this notification' };+ const queued = await spawnPrDoReviewTask({ app, pullRequest: { number: plan.pullNumber, url }, repoFullName: plan.repo, ...pin, immediate });+ if (!queued.task) return { error: 'The review could not be queued' };+ return queued.duplicate ? { duplicate: true, taskId: queued.task.id } : { taskId: queued.task.id };}- if (plan.lane !== 'pr-reviewer' || !plan.pullNumber) return queueAppLane(plan.lane, app, origin);- return queueTargetedPrReview(app, plan.pullNumber, { origin })+ if (plan.lane !== 'pr-reviewer' || !plan.pullNumber) return queueAppLane(plan.lane, app, origin, pin);+ return queueTargetedPrReview(app, plan.pullNumber, { origin, ...pin }).then((queued) => (queued.duplicate ? { duplicate: true, taskId: queued.reviewAction?.taskId || null } : { requestId: queued.request.id }));}@@ -90,11 +112,18 @@ async function recordHandoff(account, row, handoff, actor = 'automation') {*/export async function autopilotAccountNotifications(account) {if (account.mode !== 'autopilot') return { handedOff: 0, agentRuns: 0 };+ const rules = account.agentRules;const { rows } = await query(`SELECT * FROM github_notifications WHERE account_id = $1 AND state = 'open' AND NOT suspect- AND ${CANDIDATE_SQL} AND ((evidence->>'repoManaged')::boolean IS TRUE OR reason = 'security_alert') AND NOT (evidence ? 'handoff')+ AND ${CANDIDATE_SQL} AND NOT (evidence ? 'handoff')ORDER BY gh_updated_at DESC LIMIT ${MAX_HANDOFFS_PER_RUN}`,- [account.id],+ [+ account.id,+ ...scopeParams(agentRuleScope(rules, 'review-request')),+ ...scopeParams(agentRuleScope(rules, 'review-request', { optIn: true })),+ ...scopeParams(agentRuleScope(rules, 'issue-activity')),+ ...scopeParams(agentRuleScope(rules, 'security-alert')),+ ],);const plans = rows.map((row) => ({ row, plan: autopilotHandoff({ account, row }) })).filter((entry) => entry.plan);if (!plans.length) return { handedOff: 0, agentRuns: 0 };@@ -102,20 +131,22 @@ export async function autopilotAccountNotifications(account) {const batches = new Map();const skipped = [];for (const entry of plans) {- if (!entry.plan.refused && entry.plan.lane === 'security-fix') {- // One run per repo, and one for every global advisory together.- const key = `security-fix#${entry.plan.repo || '*'}`;- if (!batches.has(key)) batches.set(key, { app: null, lane: 'security-fix', repo: entry.plan.repo, entries: [] });- batches.get(key).entries.push({ ...entry, app: null });+ const app = apps.get(`${account.host}/${entry.row.repo_full_name}`.toLowerCase()) || null;+ if (!entry.plan.refused && APP_FREE_LANES.has(entry.plan.lane)) {+ // A security fix runs once per repo, and once for every global advisory+ // together; a review runs once per pull request.+ const target = entry.plan.lane === 'do-review' ? `${entry.row.repo_full_name}#${entry.plan.pullNumber}` : entry.plan.repo || '*';+ const key = `${entry.plan.lane}#${target}`;+ if (!batches.has(key)) batches.set(key, { app, lane: entry.plan.lane, repo: entry.plan.repo, plan: entry.plan, entries: [] });+ batches.get(key).entries.push({ ...entry, app });continue;}- const app = apps.get(`${account.host}/${entry.row.repo_full_name}`.toLowerCase());if (entry.plan.refused || !app) {skipped.push({ ...entry, app, outcome: { skipped: entry.plan.refused || 'no-managed-app' } });continue;}const key = `${app.id}#${entry.plan.lane}`;- if (!batches.has(key)) batches.set(key, { app, lane: entry.plan.lane, entries: [] });+ if (!batches.has(key)) batches.set(key, { app, lane: entry.plan.lane, plan: entry.plan, entries: [] });batches.get(key).entries.push({ ...entry, app });}@@ -127,6 +158,7 @@ export async function autopilotAccountNotifications(account) {appId: app?.id || null,appName: app?.name || null,...(plan.pullNumber ? { pullNumber: plan.pullNumber } : {}),+ ...(plan.pin ? { pin: plan.pin } : {}),...outcome,at: new Date().toISOString(),};@@ -138,9 +170,12 @@ export async function autopilotAccountNotifications(account) {}};for (const entry of skipped) await record(entry);- for (const { app, lane, repo, entries } of batches.values()) {+ for (const { app, lane, repo, plan, entries } of batches.values()) {const pullNumbers = new Set(entries.map((entry) => entry.plan.pullNumber).filter(Boolean));- const batchPlan = lane === 'pr-reviewer' && pullNumbers.size === 1 ? entries[0].plan : { lane, repo };+ // One rule covers a batch (same repo and kind), so its pin is shared.+ const batchPlan = lane === 'do-review' || (lane === 'pr-reviewer' && pullNumbers.size === 1)+ ? plan+ : { lane, repo, ...(plan.pin ? { pin: plan.pin } : {}) };// A lane that throws (a schedule write failing) is a recorded skip, so// it never stops Assist or the rest of the sync for this account.const queued = await queueLane(batchPlan, app, ON_DEMAND_ORIGINS.GITHUB_NOTIFICATION, { account, rows: entries.map((entry) => entry.row) })@@ -171,15 +206,16 @@ export async function handOffThread(account, threadId) {const plan = agentHandoff({ account, row });if (!plan) throw new ServerError('No agent handles this kind of notification', { status: 409, code: 'GITHUB_NOTIFICATION_NO_LANE' });if (plan.refused) throw new ServerError(REFUSED_MESSAGES[plan.refused], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });- const app = plan.lane === 'security-fix' ? null : (await managedAppsByRepoKey()).get(`${account.host}/${row.repo_full_name}`.toLowerCase());- if (plan.lane !== 'security-fix' && !app) throw new ServerError(REFUSED_MESSAGES['no-managed-app'], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });- const queued = await queueLane(plan, app, ON_DEMAND_ORIGINS.USER, { account, rows: [row] });+ const app = (await managedAppsByRepoKey()).get(`${account.host}/${row.repo_full_name}`.toLowerCase()) || null;+ if (!APP_FREE_LANES.has(plan.lane) && !app) throw new ServerError(REFUSED_MESSAGES['no-managed-app'], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });+ const queued = await queueLane(plan, app, ON_DEMAND_ORIGINS.USER, { account, rows: [row], immediate: true });if (queued.error) throw new ServerError(String(queued.error), { status: 409, code: 'GITHUB_NOTIFICATION_LANE_UNAVAILABLE' });await recordHandoff(account, row, {lane: plan.lane,appId: app?.id || null,appName: app?.name || null,...(plan.pullNumber ? { pullNumber: plan.pullNumber } : {}),+ ...(plan.pin ? { pin: plan.pin } : {}),...queued,at: new Date().toISOString(),}, 'operator');diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex f3ca74be2a..61ff15a9ac 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -160,6 +160,7 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {// Read on GitHub but still in its inbox: open here too. Gone from the inbox: done.expect(rows.find((row) => row.threadId === '102')).toMatchObject({ unread: false, state: 'open' });expect(rows.find((row) => row.threadId === '101')).toMatchObject({ unread: false, state: 'done' });+ expect((await listNotifications({ accountId: account.id })).counts).toEqual({ 'needs-you': 1, suspect: 0, handled: 1, all: 2, 'with-agents': 0 });});it('treats a 304 as unchanged and keeps rows', async () => {@@ -555,8 +556,8 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {await syncAccountNotifications(account.id);const listed = (await listNotifications({ accountId: account.id, view: 'needs-you' })).notifications;expect(Object.fromEntries(listed.map((row) => [row.threadId, row.agent]))).toEqual({- 1301: { lane: 'issue-watcher', refused: null },- 1302: { lane: 'dependency-updates', refused: 'no-managed-app' },+ 1301: { lane: 'issue-watcher', refused: null, pin: null },+ 1302: { lane: 'dependency-updates', refused: 'no-managed-app', pin: null },});expect(triggerOnDemandTask).not.toHaveBeenCalled();@@ -602,6 +603,59 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {expect(addTask).toHaveBeenCalledTimes(2);});+ it('follows agent rules: a review request starts a pinned Do:Review run, and a rule can switch a kind off', async () => {+ vi.mocked(getAllApps).mockResolvedValue([{ id: 'app-acme', name: 'Acme App', repoPath: '/example/acme-app' }]);+ vi.mocked(triggerOnDemandTask).mockReset().mockImplementation(async (taskType) => ({ id: `demand-${taskType}` }));+ vi.mocked(runUntrustedContentAnalysis).mockResolvedValue({ ok: false, code: 'untrusted-content-blocked' });+ let taskCount = 0;+ vi.mocked(addTask).mockReset().mockImplementation(async (task) => ({ id: `task-${++taskCount}`, description: task.description }));+ await updateAccount(account.id, {+ mode: 'autopilot',+ agentRules: [+ { id: 'rule-review', kind: 'review-request', repo: '*', agent: true, provider: 'example-provider', model: 'example-model', effort: 'high' },+ { id: 'rule-quiet', kind: 'security-alert', repo: 'acme/app', agent: false },+ ],+ });+ const login = account.login;+ mockGh(() => listing([+ thread('1501', { owner: login, repo: 'tool', reason: 'review_requested' }),+ thread('1502', { owner: 'acme', repo: 'app', reason: 'security_alert', type: 'RepositoryVulnerabilityAlert', url: null }),+ thread('1503', { owner: login, repo: 'side', reason: 'review_requested' }),+ ]), {+ [`repos/${login}/side/pulls/1503`]: { author: 'stranger', association: 'NONE', state: 'open', merged: false },+ [`repos/${login}/side/collaborators/stranger/permission`]: { user: { login: 'stranger' }, permission: 'read' },+ [`repos/${login}/tool/pulls/1501`]: { author: 'teammate', association: 'COLLABORATOR', state: 'open', merged: false },+ [`repos/${login}/tool/collaborators/teammate/permission`]: { user: { login: 'teammate' }, permission: 'write' },+ });++ expect((await syncAccountNotifications(account.id)).assist).toMatchObject({ handedOff: 1, agentRuns: 1 });+ const [review] = vi.mocked(addTask).mock.calls.map(([task]) => task);+ expect(review).toMatchObject({+ description: `Review PR #1501 for ${login}/tool`,+ slashdoCommand: 'review',+ slashdoArgs: `https://github.com/${login}/tool/pull/1501 --no-apply`,+ provider: 'example-provider', model: 'example-model', effort: 'high',+ noCodeOutput: true,+ });+ expect(review.app).toBeUndefined();+ expect((await getNotification(account.id, '1501')).evidence.handoff).toMatchObject({ lane: 'do-review', taskId: 'task-1', pin: { provider: 'example-provider', effort: 'high' } });+ // Switched off for this repo: the alert stays with you, untouched.+ const alert = await getNotification(account.id, '1502');+ expect(alert).toMatchObject({ decision: 'surface-high' });+ expect(alert.evidence.handoff).toBeUndefined();+ expect(triggerOnDemandTask).not.toHaveBeenCalled();+ // An outside PR never reaches the unscreened /do:review run, whatever the+ // rule says; with no managed app it has no lane and is never a candidate.+ const outside = await getNotification(account.id, '1503');+ expect(outside).toMatchObject({ decision: 'suggest-untrusted-review' });+ expect(outside.evidence.handoff).toBeUndefined();+ expect(addTask).toHaveBeenCalledTimes(1);+ // A malformed rule is refused at the boundary.+ expect(() => updateAccount(account.id, { agentRules: [{ id: 'x', kind: 'review-request', repo: 'not a repo', agent: true }] })).toThrow('Validation failed');+ await updateAccount(account.id, { agentRules: [] });+ vi.mocked(getAllApps).mockResolvedValue([]);+ });+it('sends the opt-in monthly audit report once per window, as suggestions only', async () => {await updateAccount(account.id, { auditReport: true });const recent = new Date(Date.now() - 86_400_000).toISOString();diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.jsindex 443cdcf4ee..104547f154 100644--- a/server/services/githubNotifications.js+++ b/server/services/githubNotifications.js@@ -244,7 +244,7 @@ const toIso = (value) => (value instanceof Date ? value.toISOString() : value);// The lane Resolve with agent would use, and why it cannot when refused.const agentView = (account, row) => {const plan = account ? agentHandoff({ account, row }) : null;- return plan ? { lane: plan.lane, refused: plan.refused || null } : null;+ return plan ? { lane: plan.lane, refused: plan.refused || null, pin: plan.pin || null } : null;};const toApi = (row, accountsById) => {@@ -277,16 +277,24 @@ export async function listNotifications({ accountId = null, view = 'needs-you' }const accounts = await listAccounts();const accountsById = new Map(accounts.map((account) => [account.id, account]));const ids = accountId ? [accountId] : accounts.map((account) => account.id);- const [rows, syncRows] = await Promise.all([+ const [rows, syncRows, countRows] = await Promise.all([query(`SELECT * FROM github_notifications WHERE account_id = ANY($1::text[]) AND ${VIEW_FILTERS[view]}ORDER BY gh_updated_at DESC LIMIT ${LIST_LIMIT}`,[ids],),query('SELECT account_id, last_sync_at, last_error, poll_interval_seconds FROM github_notification_sync WHERE account_id = ANY($1::text[])', [ids]),+ // Every view's size for the inbox's summary, plus the open threads an agent has.+ query(+ `SELECT ${NOTIFICATION_VIEWS.map((name) => `COUNT(*) FILTER (WHERE ${VIEW_FILTERS[name]})::int AS "${name}"`).join(', ')},+ COUNT(*) FILTER (WHERE state = 'open' AND decision = 'handed-off')::int AS "with-agents"+ FROM github_notifications WHERE account_id = ANY($1::text[])`,+ [ids],+ ),]);return {notifications: rows.rows.map((row) => toApi(row, accountsById)),+ counts: countRows.rows[0],sync: Object.fromEntries(syncRows.rows.map((row) => [row.account_id, {lastSyncAt: toIso(row.last_sync_at),lastError: row.last_error || null,@@ -502,7 +510,7 @@ export async function getAutomationsOverview() {const { getJob } = await import('./autonomousJobs.js');const [accounts, job] = await Promise.all([listAccounts(), getJob(NOTIFICATION_CHECK_JOB_ID)]);const ids = accounts.map((account) => account.id);- const [syncRows, countRows] = await Promise.all([+ const [syncRows, countRows, repoRows] = 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,@@ -510,7 +518,14 @@ export async function getAutomationsOverview() {FROM github_notifications WHERE account_id = ANY($1::text[]) AND state = 'open' GROUP BY account_id`,[ids],),+ // The repos an agent rule can name without typing: those the inbox has seen.+ query(+ `SELECT account_id, array_agg(DISTINCT repo_full_name ORDER BY repo_full_name) AS repos+ FROM github_notifications WHERE account_id = ANY($1::text[]) AND repo_full_name <> '' GROUP BY account_id`,+ [ids],+ ),]);+ const reposById = new Map(repoRows.rows.map((row) => [row.account_id, row.repos.slice(0, 200)]));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 {@@ -533,6 +548,8 @@ export async function getAutomationsOverview() {needsYou: counts?.needs_you || 0,suspect: counts?.suspect || 0,pending: counts?.pending || 0,+ agentRules: Array.isArray(account.agentRules) ? account.agentRules : [],+ repos: reposById.get(account.id) || [],};}),};diff --git a/server/services/githubSecurityFixTask.js b/server/services/githubSecurityFixTask.jsindex 79e846590a..fe2fc9c926 100644--- a/server/services/githubSecurityFixTask.js+++ b/server/services/githubSecurityFixTask.js@@ -62,10 +62,10 @@ function buildPrompt({ host, login, repo, advisories }) {/*** Queue one security-fix run for a repo (`repo`) or for a set of global- * advisories (`advisories`). Returns `{ taskId }`, `{ duplicate: true, taskId }`+ * advisories (`advisories`), optionally pinned to a provider/model/effort. Returns `{ taskId }`, `{ duplicate: true, taskId }`* when the same run is already queued or running, or `{ error }`.*/-export async function queueSecurityFixTask({ account, repo = null, advisories = [], origin = 'automation' }) {+export async function queueSecurityFixTask({ account, repo = null, advisories = [], origin = 'automation', provider, model, effort }) {if (!HOST_RE.test(account?.host || '')) return { error: 'Invalid account host' };const login = LOGIN_RE.test(account.login || '') ? account.login : null;if (repo !== null && !REPO_RE.test(repo)) return { error: 'Invalid repository name' };@@ -74,6 +74,7 @@ export async function queueSecurityFixTask({ account, repo = null, advisories =const task = await addTask({description: buildPrompt({ host: account.host, login, repo, advisories: ids }),priority: 'HIGH',+ provider, model, effort,// The deliverable is a pull request on another repo, made from a scratch// clone during the run: no PortOS worktree, and a clean PortOS tree is success.useWorktree: false,diff --git a/server/services/prDoReviewTask.js b/server/services/prDoReviewTask.jsindex 5abc702dd3..739fdaf482 100644--- a/server/services/prDoReviewTask.js+++ b/server/services/prDoReviewTask.js@@ -98,7 +98,9 @@ function renderContext({ number, url, repoLabel, selfReview }) {* that reaches this module (server/AGENTS.md, "Import scoping").** @param {Object} params- * @param {Object} params.app - the managed app record (`id`, `name`)+ * @param {Object|null} params.app - the managed app record (`id`, `name`), or+ * null for a PR in a repo no app manages: PR mode reads it through `gh`, so+ * the run needs no checkout of that repo* @param {Object} params.pullRequest - the freshly-read open PR (`number`, `url`)* @param {string} [params.repoFullName] - `owner/repo`, for the prompt's label* @param {string} [params.provider] - "Run with" provider pin@@ -106,6 +108,8 @@ function renderContext({ number, url, repoLabel, selfReview }) {* @param {string} [params.effort] - "Run with" reasoning-effort pin* @param {boolean} [params.selfReview] - run with no delegated reviewers, so the* provider above is the only thing that reads the diff (`--review-with none`)+ * @param {boolean} [params.immediate] - start the agent now (a button press is+ * the approval); false leaves it to the normal queue, for automation* @param {Object} [params.reviewerConfig] - already-sanitized reviewer override* (`reviewerConfigMetadata`) persisted for the prompt layer to resolve over* the install's Code Review Defaults. Ignored under `selfReview`, which has no@@ -114,17 +118,17 @@ function renderContext({ number, url, repoLabel, selfReview }) {*/export async function spawnPrDoReviewTask({app, pullRequest, repoFullName = '', provider, model, effort,- selfReview = false, reviewerConfig = null,+ selfReview = false, reviewerConfig = null, immediate = true,} = {}) {const { addTask } = await import('./cosTaskStore.js');const { forceSpawnTask } = await import('./cos.js');const { number, url } = pullRequest;- const appLabel = String(app.name || app.id).replace(/\s+/g, ' ').trim();+ const appLabel = app ? String(app.name || app.id).replace(/\s+/g, ' ').trim() : repoFullName;const repoLabel = repoFullName || appLabel;const created = await addTask({description: `Review PR #${number} for ${appLabel}`,- app: app.id,+ ...(app ? { app: app.id } : {}),priority: 'HIGH',context: renderContext({ number, url, repoLabel, selfReview }),slashdoCommand: DO_REVIEW_COMMAND,@@ -153,27 +157,28 @@ export async function spawnPrDoReviewTask({// review the review.reviewLoop: false,metadata: { targetPullRequest: number },- }, 'user', { suppressDequeue: true });+ }, 'user', { suppressDequeue: immediate });if (!created) return { task: null, duplicate: false, dispatch: { started: false, reason: null } };if (created.duplicate) {emitLog('info', `🔍 /do:review for ${repoLabel} #${number} is already queued as ${created.id}`, {- taskId: created.id, appId: app.id, prNumber: number,+ taskId: created.id, appId: app?.id || null, prNumber: number,});return { task: created, duplicate: true, dispatch: { started: false, reason: null } };}+ if (!immediate) return { task: created, duplicate: false, dispatch: { started: false, reason: null } };const spawn = await forceSpawnTask(created.id).catch(err => ({ error: err.message }));if (spawn?.error) {// The task is persisted and holds its place in the queue — report why it has// not started rather than claiming an agent is on it.emitLog('warn', `⏳ Queued /do:review task ${created.id} for ${repoLabel} #${number} — ${spawn.error}`, {- taskId: created.id, appId: app.id, prNumber: number,+ taskId: created.id, appId: app?.id || null, prNumber: number,});return { task: created, duplicate: false, dispatch: { started: false, reason: spawn.error } };}- emitLog('info', `🔍 Started /do:review agent for task ${created.id} (app ${app.id} request #${number})`, {- taskId: created.id, appId: app.id, prNumber: number,+ emitLog('info', `🔍 Started /do:review agent for task ${created.id} (${repoLabel} request #${number})`, {+ taskId: created.id, appId: app?.id || null, prNumber: number,});return { task: created, duplicate: false, dispatch: { started: true, reason: null } };}diff --git a/server/services/prDoReviewTask.test.js b/server/services/prDoReviewTask.test.jsindex c436da32be..ad76aac9d7 100644--- a/server/services/prDoReviewTask.test.js+++ b/server/services/prDoReviewTask.test.js@@ -84,6 +84,16 @@ describe('spawnPrDoReviewTask', () => {expect(result).toMatchObject({ duplicate: false, dispatch: { started: true, reason: null } });});+ it('leaves an automated run to the normal queue, and needs no app for a PR read through gh', async () => {+ const result = await queue({ app: null, immediate: false });++ expect(addTask).toHaveBeenCalledWith(expect.anything(), 'user', { suppressDequeue: false });+ expect(queuedTask().app).toBeUndefined();+ expect(queuedTask().description).toBe('Review PR #17 for acme/widget');+ expect(forceSpawnTask).not.toHaveBeenCalled();+ expect(result).toMatchObject({ duplicate: false, dispatch: { started: false, reason: null } });+ });+it('reports a refused dispatch as queued-not-started rather than as a running agent', async () => {forceSpawnTask.mockResolvedValue({ error: 'No available agent slots (3/3)' });