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
feat: GitHub inbox automation rules with done/mute/agent actions, added from any row (#13192)
Adam Eivy41f4fa016737
diff --git a/client/src/components/github/GitHubAgentRules.jsx b/client/src/components/github/GitHubAgentRules.jsxindex d81cc01c42..8e2772d7aa 100644--- a/client/src/components/github/GitHubAgentRules.jsx+++ b/client/src/components/github/GitHubAgentRules.jsx@@ -2,7 +2,8 @@ import { useId, useState } from 'react';import { Bot, Pencil, Plus, X } from 'lucide-react';import ProviderModelSelector from '../ProviderModelSelector';import useRunWithPicker from '../../hooks/useRunWithPicker';-import { AGENT_RULE_KINDS, CI_RULE_ACTIONS } from './githubTriageLabels';+import { formatCount } from '../../utils/formatters';+import { AGENT_RULE_KINDS, RULE_ACTIONS, actionsForKind, ruleActionOf } from './githubTriageLabels';import { describeAgentPin } from './GitHubAgentPinForm';const ALL_REPOS = '*';@@ -13,47 +14,62 @@ const newRuleId = () => `rule-${Date.now().toString(36)}-${Math.random().toStrinconst repoLabel = (repo) => (repo === ALL_REPOS ? 'All repos' : repo);-const ciActionLabel = (action) => CI_RULE_ACTIONS.find((option) => option.value === action)?.label || action;+const actionLabel = (action) => RULE_ACTIONS.find((option) => option.value === action)?.label || action;function pinLabel(rule, providers) {- if (rule.kind === 'ci-activity') return ciActionLabel(rule.action);- return rule.agent ? `Start an agent · ${describeAgentPin(rule, providers)}` : "Don't start an agent";+ const action = ruleActionOf(rule);+ return action === 'agent' ? `Start an agent · ${describeAgentPin(rule, providers)}` : actionLabel(action);}-function RuleForm({ rule, repos, takenKeys, onCancel, onSubmit, saving }) {+// Open threads a rule for this kind and repo would match now, from the+// server's per-kind counts: a repo rule covers its repo, the All repos rule+// every repo without its own rule. Done and mute never touch threads a pinned+// triage rule decided, so they count only `actionable`.+function ruleMatchCount({ openByKind, rules, editingId, kind, repo, action }) {+ if (!Array.isArray(openByKind)) return null;+ const metric = action === 'done' || action === 'mute' ? 'actionable' : 'total';+ const ofKind = openByKind.filter((entry) => entry.kind === kind);+ if (repo !== ALL_REPOS) return ofKind.filter((entry) => entry.repo === repo.toLowerCase()).reduce((sum, entry) => sum + entry[metric], 0);+ const own = new Set(rules.filter((rule) => rule.kind === kind && rule.id !== editingId && rule.repo !== ALL_REPOS).map((rule) => rule.repo.toLowerCase()));+ return ofKind.filter((entry) => !own.has(entry.repo)).reduce((sum, entry) => sum + entry[metric], 0);+}++// Whether a run of this account now would carry out the rule's action.+const actsNow = (mode, action) => (action === 'agent' ? mode === 'autopilot' : (action === 'done' || action === 'mute') && (mode === 'assist' || mode === 'autopilot'));++function RuleForm({ rule, repos, rules, account, takenKeys, onCancel, onSubmit, saving }) {const formId = useId();const picker = useRunWithPicker({ preselectDefaults: false, seed: rule });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 !== false : true);- const [ciAction, setCiAction] = useState(rule?.action || 'done');- const isCi = kind === 'ci-activity';+ const [chosenAction, setAction] = useState(rule ? ruleActionOf(rule) : 'agent');+ const [applyNow, setApplyNow] = useState(false);+ const options = actionsForKind(kind);+ // A kind that cannot take the chosen action falls back to its first one.+ const action = options.some((option) => option.value === chosenAction) ? chosenAction : options[0].value;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 matches = repoValid ? ruleMatchCount({ openByKind: account.openByKind, rules, editingId: rule?.id, kind, repo, action }) : null;+ const canApplyNow = matches > 0 && actsNow(account.mode, action);const submit = (event) => {event.preventDefault();if (!repoValid || clash) return;- if (isCi) {- onSubmit({ id: rule?.id || newRuleId(), kind, repo, action: ciAction });- return;- }+ const agent = action === 'agent';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,- });+ action,+ ...(agent ? { provider: picker.pin.provider || null, model: picker.pin.model || null, effort: picker.pin.effort || null } : {}),+ }, { applyNow: canApplyNow && applyNow });};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'}>+ <form onSubmit={submit} className="space-y-3 rounded-lg border border-port-border bg-port-bg p-3" aria-label={rule?.id ? 'Edit automation rule' : 'New automation 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>@@ -69,18 +85,11 @@ function RuleForm({ rule, repos, takenKeys, onCancel, onSubmit, saving }) {<option value={OTHER_REPO}>Another repo…</option></select></label>- <label htmlFor={`${formId}-agent`} className="space-y-1 text-xs text-gray-400">+ <label htmlFor={`${formId}-action`} className="space-y-1 text-xs text-gray-400"><span className="block">Then</span>- {isCi ? (- <select id={`${formId}-agent`} value={ciAction} onChange={(event) => setCiAction(event.target.value)} className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-white">- {CI_RULE_ACTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}- </select>- ) : (- <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>- )}+ <select id={`${formId}-action`} value={action} onChange={(event) => setAction(event.target.value)} className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-white">+ {options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}+ </select></label></div>{repoChoice === OTHER_REPO && (@@ -89,13 +98,24 @@ function RuleForm({ rule, repos, takenKeys, onCancel, onSubmit, saving }) {<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 && !isCi && (+ {action === '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>+ {matches !== null && (+ <p className="text-xs text-gray-300">+ {matches === 1 ? 'Matches 1 open thread now.' : `Matches ${formatCount(matches)} open threads now.`}+ </p>+ )}+ {canApplyNow && (+ <label htmlFor={`${formId}-apply`} className="flex items-center gap-2 text-xs text-gray-300">+ <input id={`${formId}-apply`} type="checkbox" checked={applyNow} onChange={(event) => setApplyNow(event.target.checked)} />+ Apply to {matches === 1 ? 'this 1' : `these ${formatCount(matches)}`} now+ </label>+ )}{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">@@ -108,12 +128,21 @@ function RuleForm({ rule, repos, takenKeys, onCancel, onSubmit, saving }) {}/**- * 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.+ * One account's automation rules: for each kind of notification, in one repo+ * or all of them, whether Assist and Autopilot mark it done, mute it, leave it,+ * or (Autopilot) start a CoS agent and on which provider, model and effort. A+ * repo's own rule wins over its All repos rule. `prefill` ({ kind, repo }) opens+ * a new rule from an inbox row; `onApplyNow` runs the account's check at once.*/-export default function GitHubAgentRules({ account, onSave, saving }) {- const [editing, setEditing] = useState(null);+export default function GitHubAgentRules({ account, onSave, saving, prefill = null, onPrefillDone, onApplyNow }) {+ const [editingState, setEditing] = useState(null);+ // A row's Add automation rule opens a new rule for its kind and repo.+ // It starts on Mark done, the usual reason to add one from a row.+ const editing = editingState || (prefill ? { id: null, kind: prefill.kind, repo: prefill.repo, action: prefill.kind === 'security-alert' ? 'agent' : 'done' } : null);+ const close = () => {+ setEditing(null);+ onPrefillDone?.();+ };const rules = account.agentRules || [];// Built-in rules apply until the operator saves a rule for the same kind and repo.const defaults = (account.defaultAgentRules || []).filter((rule) => !rules.some((entry) => entry.kind === rule.kind && entry.repo.toLowerCase() === rule.repo.toLowerCase()));@@ -121,18 +150,20 @@ export default function GitHubAgentRules({ account, onSave, saving }) {const repos = account.repos || [];const kindLabel = (kind) => AGENT_RULE_KINDS.find((option) => option.value === kind)?.label || kind;- const save = async (next) => {+ const save = async (next, { applyNow = false } = {}) => {const saved = await onSave(account.id, next);- if (saved) setEditing(null);+ if (!saved) return;+ close();+ if (applyNow) onApplyNow?.(account.id);};- const upsert = (rule) => save(rules.some((entry) => entry.id === rule.id) ? rules.map((entry) => (entry.id === rule.id ? rule : entry)) : [...rules, rule]);+ const upsert = (rule, options) => save(rules.some((entry) => entry.id === rule.id) ? rules.map((entry) => (entry.id === rule.id ? rule : entry)) : [...rules, rule], options);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>+ <h4 className="text-xs font-semibold uppercase tracking-wide text-gray-400">Automation 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@@ -140,7 +171,11 @@ export default function GitHubAgentRules({ account, onSave, saving }) {)}</div>{account.mode !== 'autopilot' && rules.length > 0 && (- <p className="text-xs text-port-warning">Autopilot follows these rules. This account is in {{ assist: 'Assist', disabled: 'Disabled' }[account.mode] || 'Observe'}, so nothing starts on its own yet.</p>+ <p className="text-xs text-port-warning">+ {account.mode === 'assist'+ ? 'Assist follows the done and mute rules; only Autopilot starts agents.'+ : `Assist and Autopilot follow these rules. This account is in ${account.mode === 'disabled' ? 'Disabled' : 'Observe'}, so nothing happens on its own yet.`}+ </p>)}{defaults.length > 0 && (<ul className="divide-y divide-port-border" aria-label="Default rules">@@ -148,7 +183,7 @@ export default function GitHubAgentRules({ account, onSave, saving }) {<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)} · {repoLabel(rule.repo)}</p>- <p className="truncate text-xs text-port-success">{ciActionLabel(rule.action)} · default</p>+ <p className="truncate text-xs text-port-success">{actionLabel(rule.action)} · default</p></div><button type="button" onClick={() => setEditing({ id: null, kind: rule.kind, repo: rule.repo, action: rule.action })} disabled={Boolean(editing)} className="inline-flex min-h-[44px] shrink-0 items-center justify-center rounded px-2 text-xs text-gray-400 hover:text-white disabled:opacity-40" aria-label={`Override default ${kindLabel(rule.kind)} rule`}>Override@@ -158,19 +193,19 @@ export default function GitHubAgentRules({ account, onSave, saving }) {</ul>)}{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>+ <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. Add a rule here or from any inbox row.</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} />+ <RuleForm rule={rule} repos={repos} rules={rules} account={account} takenKeys={takenKeys} onCancel={close} 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>+ <p className={`truncate text-xs ${ruleActionOf(rule) === 'leave' ? 'text-gray-400' : 'text-port-success'}`}>{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" />@@ -183,7 +218,7 @@ export default function GitHubAgentRules({ account, onSave, saving }) {</ul>)}{editing && !editing.id && (- <RuleForm rule={editing.kind ? editing : null} repos={repos} takenKeys={takenKeys} onCancel={() => setEditing(null)} onSubmit={upsert} saving={saving} />+ <RuleForm key={`${editing.kind || ''}#${editing.repo || ''}`} rule={editing.kind ? editing : null} repos={repos} rules={rules} account={account} takenKeys={takenKeys} onCancel={close} onSubmit={upsert} saving={saving} />)}</div>);diff --git a/client/src/components/github/GitHubAutomationsTab.jsx b/client/src/components/github/GitHubAutomationsTab.jsxindex b9a4cfcb03..42a7a49810 100644--- a/client/src/components/github/GitHubAutomationsTab.jsx+++ b/client/src/components/github/GitHubAutomationsTab.jsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useState } from 'react';-import { Link } from 'react-router';+import { Link, useSearchParams } from 'react-router';import { Bot, Pencil, Play, Undo2, X } from 'lucide-react';import Pill from '../ui/Pill';import LoadFailedState from '../ui/LoadFailedState';@@ -16,7 +16,7 @@ import {undoGitHubAutomationAction,updateGitHubAccount,} from '../../services/api';-import { ACTION_LABELS, LEARNED_DECISION_LABELS } from './githubTriageLabels';+import { ACTION_LABELS, AGENT_RULE_KINDS, LEARNED_DECISION_LABELS } from './githubTriageLabels';import GitHubAgentRules from './GitHubAgentRules';import GitHubAgentPinForm, { describeAgentPin } from './GitHubAgentPinForm';import useRunWithPicker from '../../hooks/useRunWithPicker';@@ -34,7 +34,7 @@ function modeHint(account) {if (account.mode !== 'autopilot') return assist;const handoff = account.trust === 'private' && !account.allowAgents? 'Private accounts hand threads off only after you allow agents on them below.'- : '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.';+ : '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. Automation rules below turn kinds on or off per repo, mark them done or muted, and pick the provider.';return `${assist} ${handoff}`;}@@ -109,7 +109,18 @@ function AgentDefaults({ account, onSave, saving }) {);}-function AccountCard({ account, running, onRun, onMode, savingMode, onAllowAgents, onSaveRules, savingRules, onSaveAccount }) {+// An inbox row's Add automation rule links here with the thread's kind and+// repo, so the form opens prefilled and the link stays shareable.+const RULE_PARAMS = ['ruleAccount', 'ruleKind', 'ruleRepo'];+const RULE_REPO_RE = /^(?:\*|[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100})$/;+function rulePrefillFrom(params) {+ const kind = params.get('ruleKind');+ const repo = params.get('ruleRepo') || '*';+ if (!params.get('ruleAccount') || !AGENT_RULE_KINDS.some((option) => option.value === kind) || !RULE_REPO_RE.test(repo)) return null;+ return { accountId: params.get('ruleAccount'), kind, repo };+}++function AccountCard({ account, running, onRun, onMode, savingMode, onAllowAgents, onSaveRules, savingRules, onSaveAccount, prefill, onPrefillDone }) {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">@@ -149,7 +160,7 @@ function AccountCard({ account, running, onRun, onMode, savingMode, onAllowAgent</button><AgentAccess account={account} onAllow={onAllowAgents} saving={savingMode} /><AgentDefaults account={account} onSave={onSaveAccount} saving={savingMode} />- <GitHubAgentRules account={account} onSave={onSaveRules} saving={savingRules} />+ <GitHubAgentRules account={account} onSave={onSaveRules} saving={savingRules} prefill={prefill} onPrefillDone={onPrefillDone} onApplyNow={onRun} /></li>);}@@ -205,6 +216,13 @@ function RuleList({ rules, onDelete }) {}export default function GitHubAutomationsTab() {+ const [searchParams, setSearchParams] = useSearchParams();+ const rulePrefill = rulePrefillFrom(searchParams);+ const clearRulePrefill = () => setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ RULE_PARAMS.forEach((key) => next.delete(key));+ return next;+ }, { replace: true });const [overview, setOverview] = useState(null);const [loadFailed, setLoadFailed] = useState(false);const [runningId, setRunningId] = useState(null);@@ -329,7 +347,20 @@ 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} onAllowAgents={allowAgents} onSaveRules={saveRules} savingRules={savingRulesId === account.id} onSaveAccount={changeAccount} />+ <AccountCard+ key={account.id}+ account={account}+ running={runningId === account.id}+ onRun={runNow}+ onMode={changeMode}+ savingMode={savingModeId === account.id}+ onAllowAgents={allowAgents}+ onSaveRules={saveRules}+ savingRules={savingRulesId === account.id}+ onSaveAccount={changeAccount}+ prefill={rulePrefill?.accountId === account.id ? rulePrefill : null}+ onPrefillDone={clearRulePrefill}+ />))}</ul>)}diff --git a/client/src/components/github/GitHubInboxTab.jsx b/client/src/components/github/GitHubInboxTab.jsxindex 6c32875366..217da0abcf 100644--- a/client/src/components/github/GitHubInboxTab.jsx+++ b/client/src/components/github/GitHubInboxTab.jsx@@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { Link, useParams } from 'react-router';import {Bell, BellOff, Bot, Check, CheckCheck, CheckCircle2, CircleDot, CircleX, ExternalLink, GitCommitHorizontal, GitPullRequest,- Inbox, Layers, Mail, MailX, MessagesSquare, RefreshCw, Rocket, ShieldAlert, Tag,+ Inbox, Layers, ListPlus, Mail, MailX, MessagesSquare, RefreshCw, Rocket, ShieldAlert, Tag,} from 'lucide-react';import Pill from '../ui/Pill';import OverflowMenu from '../ui/OverflowMenu';@@ -163,6 +163,13 @@ const SUGGESTION_TONES = {muted: 'border-port-border bg-port-bg text-gray-200',};+// The Automations tab's rule form, prefilled with this thread's kind and repo.+const automationRuleLink = (notification) => {+ const params = new URLSearchParams({ ruleAccount: notification.accountId, ruleKind: notification.ruleKind });+ if (notification.repoFullName) params.set('ruleRepo', notification.repoFullName);+ return `/devtools/github/automations?${params}`;+};+function NotificationRow({ notification, accountLabel, busy, onAction, onUpdated }) {const [reviewing, setReviewing] = useState(false);const [picking, setPicking] = useState(false);@@ -179,9 +186,13 @@ function NotificationRow({ notification, accountLabel, busy, onAction, onUpdatedconst startAgent = async (pin) => {if (await onAction(notification, 'agent', pin)) setPicking(false);};- const overflow = handled ? [] : MORE_ACTIONS.map(({ action, label, icon }) => ({- id: action, label, icon, disabled: busy, onSelect: () => onAction(notification, action),- }));+ const overflow = [+ ...(handled ? [] : MORE_ACTIONS.map(({ action, label, icon }) => ({+ id: action, label, icon, disabled: busy, onSelect: () => onAction(notification, action),+ }))),+ // Handle every similar thread the same way from now on (#13192).+ ...(notification.ruleKind ? [{ id: 'add-rule', label: 'Add automation rule…', icon: ListPlus, to: automationRuleLink(notification) }] : []),+ ];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">diff --git a/client/src/components/github/githubTriageLabels.js b/client/src/components/github/githubTriageLabels.jsindex 54c14c6bb4..3a6b881c1e 100644--- a/client/src/components/github/githubTriageLabels.js+++ b/client/src/components/github/githubTriageLabels.js@@ -80,21 +80,32 @@ export const LANE_VIEW = {'notification-resolve': { label: 'a CoS agent', tab: null },};-// The notification kinds an agent rule can name (GITHUB_AGENT_RULE_KINDS on the server).+// The notification kinds an automation 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: '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. A rule never marks one done or mutes it.' },{ value: 'issue-activity', label: 'Issue activity', hint: 'Outside activity on an issue in one of your apps goes to its issue watcher.' },- { value: 'ci-activity', label: 'CI activity', hint: 'A workflow run or check suite notice. By default Autopilot and Assist mark these done; pick another action per repo.' },+ { value: 'ci-activity', label: 'CI activity', hint: 'A workflow run or check suite notice. By default Autopilot and Assist mark these done. An agent looks into a failure only in a repo of yours.' },+ { value: 'own-pr', label: 'Your pull requests', hint: 'Activity on a pull request you opened. An agent takes it only when everyone in the thread is you or trusted.' },+ { value: 'mention', label: 'Mentions', hint: 'You or your team were mentioned. An agent takes it only when everyone in the thread is you or trusted.' },+ { value: 'release', label: 'Releases', hint: 'A new release in a repo you watch.' },+ { value: 'other', label: 'Everything else', hint: 'Any other notification: comments, discussions, commits and subscriptions. An agent takes it only when everyone in the thread is you or trusted.' },];-// What a ci-activity rule does with the notice (GITHUB_CI_RULE_ACTIONS on the server).-export const CI_RULE_ACTIONS = [+// What an automation rule does (GITHUB_AGENT_RULE_ACTIONS on the server).+export const RULE_ACTIONS = [+ { value: 'agent', label: 'Start a CoS agent' },{ value: 'done', label: 'Mark done' },{ value: 'mute', label: 'Mute the thread' },{ value: 'leave', label: 'Leave in the inbox' },];+// Security alerts are never marked done or muted by a rule.+export const actionsForKind = (kind) => (kind === 'security-alert' ? RULE_ACTIONS.filter((option) => option.value === 'agent' || option.value === 'leave') : RULE_ACTIONS);++// A rule's action; a legacy `agent` boolean reads as agent / leave.+export const ruleActionOf = (rule) => rule?.action || (rule?.agent === true ? 'agent' : 'leave');+// Why Resolve with agent is unavailable for a thread (agentHandoff on the server).export const AGENT_REFUSED_LABELS = {'private-account': 'Allow agents on this Private account in Accounts to resolve it with an agent',diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsxindex dc7a793d27..02d3702c0d 100644--- a/client/src/pages/GitHub.test.jsx+++ b/client/src/pages/GitHub.test.jsx@@ -413,6 +413,14 @@ describe('GitHub inbox tab', () => {expect(mock.getGitHubRepos).not.toHaveBeenCalled();});+ it('offers Add automation rule from a row, linked to a form prefilled with its kind and repo (#13192)', async () => {+ mock.getGitHubNotifications.mockResolvedValue({ notifications: [{ ...NOTIFICATION, ruleKind: 'review-request' }], sync: {} });+ renderTab('inbox');+ fireEvent.click(await screen.findByRole('button', { name: 'More actions for Example change' }));+ const link = await screen.findByRole('menuitem', { name: /Add automation rule/ });+ expect(link.getAttribute('href')).toBe('/devtools/github/automations?ruleAccount=github-com&ruleKind=review-request&ruleRepo=octocat%2Fhello');+ });+it('links a deployment approval to the run waiting on you', async () => {const runUrl = 'https://github.com/octocat/hello/actions/runs/4242';mock.getGitHubNotifications.mockResolvedValue({@@ -722,6 +730,42 @@ describe('GitHub automations tab', () => {expect(await screen.findByText(/^CoS defaults/)).toBeTruthy();});+ it('adds a rule from an inbox row link, shows how many threads it matches and applies it now (#13192)', async () => {+ mock.getGitHubAutomations.mockResolvedValue({+ ...OVERVIEW,+ accounts: [{+ ...OVERVIEW.accounts[0], mode: 'assist', agentRules: [], repos: ['octocat/hello'],+ openByKind: [+ { kind: 'ci-activity', repo: 'octocat/hello', total: 2, actionable: 2 },+ { kind: 'ci-activity', repo: 'octocat/other', total: 3, actionable: 3 },+ { kind: 'mention', repo: 'octocat/hello', total: 4, actionable: 4 },+ ],+ }],+ });+ mock.updateGitHubAccount.mockImplementation(async (id, data) => ({ id, ...data }));+ render(+ <MemoryRouter initialEntries={['/devtools/github/automations?ruleAccount=github-com&ruleKind=ci-activity&ruleRepo=octocat%2Fhello']}>+ <Routes><Route path="/devtools/github/:tab" element={<GitHub />} /></Routes>+ </MemoryRouter>,+ );+ const form = await screen.findByRole('form', { name: 'New automation rule' });+ expect(screen.getByLabelText('When I get').value).toBe('ci-activity');+ expect(screen.getByLabelText('In').value).toBe('octocat/hello');+ expect(screen.getByLabelText('Then').value).toBe('done');+ expect(screen.getByText('Matches 2 open threads now.')).toBeTruthy();+ // All repos is one change away, and counts every repo.+ fireEvent.change(screen.getByLabelText('In'), { target: { value: '*' } });+ expect(screen.getByText('Matches 5 open threads now.')).toBeTruthy();+ fireEvent.change(screen.getByLabelText('In'), { target: { value: 'octocat/hello' } });+ fireEvent.click(screen.getByLabelText('Apply to these 2 now'));+ fireEvent.submit(form);+ await waitFor(() => expect(mock.updateGitHubAccount).toHaveBeenCalledWith('github-com', {+ agentRules: [expect.objectContaining({ kind: 'ci-activity', repo: 'octocat/hello', action: 'done' })],+ }));+ await waitFor(() => expect(mock.syncGitHubNotifications).toHaveBeenCalledWith('github-com', { silent: true }));+ expect(screen.queryByRole('form', { name: 'New automation rule' })).toBeNull();+ });+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({@@ -731,7 +775,8 @@ describe('GitHub automations tab', () => {mock.updateGitHubAccount.mockImplementation(async (id, data) => ({ id, ...data }));renderTab('automations');- expect(await screen.findByText("Don't start an agent")).toBeTruthy();+ // A stored legacy `agent: false` rule reads as Leave in the inbox.+ expect(await screen.findByText('Leave in the inbox')).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();@@ -740,7 +785,7 @@ describe('GitHub automations tab', () => {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.objectContaining({ kind: 'review-request', repo: 'octocat/hello', action: 'agent' }),],}));expect(await screen.findByText('octocat/hello', { selector: 'span' })).toBeTruthy();diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 86c4cd7132..25e18ba2f0 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -610,7 +610,7 @@ Optional SDK environments under `data/venvs/` are machine-local, regenerable run### GitHub accounts-`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, agent rules, agent defaults (the provider/model/effort a Resolve with agent run starts from, #13191) 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`.+`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, automation rules (each `action` is `agent`, `done`, `mute` or `leave`; a rule saved before #13192 holds an `agent` boolean, read as `agent` / `leave` with no migration), agent defaults (the provider/model/effort a Resolve with agent run starts from, #13191) and enabled flag. It is small machine-local configuration, like Messages accounts: no foreign keys, no cross-record queries, no search. It holds no credentials (`gh` keeps those) and is never federated, because which logins a machine is signed into is a property of that machine. With no file, the API shows one implicit github.com account so existing installs need no migration or `data.reference/` seed; the file is written on the first edit, and a stored empty list stays authoritative. Version 1; a malformed or other-version file is refused with 503 and left untouched. Rsync backups include it. Code: `server/services/githubAccounts.js`.The notifications inbox (#12870) is `db-primary`: `github_notifications` holds one row per thread per account (repo, reason, subject title/type, a link rebuilt on the account's own host, unread flag, GitHub's `updated_at`, and the local `state` `open` | `done` | `muted` | `unsubscribed`), keyed `(account_id, thread_id)`; `github_notification_sync` holds each account's `Last-Modified` cursor, `X-Poll-Interval` and last error. The rows are queried by account, state and recency and later phases join triage results to them, so they live in Postgres. Like the accounts they describe they are machine-local and never federated. Only notification metadata is stored; no thread body or linked page is fetched. Triage (#12871) adds per-thread `decision`, `trust`, `suspect`, `evidence` (rule, spam signals, actor login, repo ownership; never body text) and `triaged_for` columns, plus `github_notification_events`, the per-thread log of operator actions and automation decisions. Assist mode (#12872) reads an undecided thread's own body and latest comment only to pass them through untrusted-content screening; the text is not stored, only the model's enum verdict (or the skip code) in `evidence.ai`. `github_notification_rules` holds rules learned from the operator's corrections, keyed `(account_id, repo_full_name, reason, actor)`. The subscription audit (#12873) logs each applied change in `github_notification_audit_changes` so it can be undone. Autopilot (#12874) records a hand-off (lane, app id, request id, or why it was skipped) in `evidence.handoff`; a generic `notification-resolve` run (#13191) adds its task id and, when it fails, `evidence.handoff.failed`, while triage records the latest commenter's trust in `evidence.commenterTrust`; and `github_notification_audit_reports` holds when each account's opt-in monthly audit report last went out. Code: `server/services/githubNotifications.js`, schema `server/lib/db/schema/githubNotifications.js`.diff --git a/server/lib/README.md b/server/lib/README.mdindex 5ac22532c2..ad6549d8a9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -489,7 +489,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`, `notificationHtmlUrl`, `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`, `agentHandoff`, `autopilotHandoff`, `agentRuleScope`, `agentRunPin`, `GENERIC_AGENT_LANE`, `APP_FREE_AGENT_LANES` — 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 (with the generic `notification-resolve` lane's trust gate), per-repo agent rules and run-pin precedence; 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`, `agentRunPin`, `GENERIC_AGENT_LANE`, `APP_FREE_AGENT_LANES`, `AGENT_RULE_KINDS`, `AGENT_RULE_ACTIONS`, `threadAgentKind`, `KIND_SQL`, `agentRuleAction`, `normalizeAgentRules`, `ruleAction`, `ruleActionScope`, `PINNED_TRIAGE_RULES` — 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 (with the generic `notification-resolve` lane's trust gate), per-repo automation rules (kind × agent/done/mute/leave, legacy `agent` booleans read as actions) and run-pin precedence; 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 913e8355ca..b9cf81f1da 100644--- a/server/lib/githubNotificationTriage.js+++ b/server/lib/githubNotificationTriage.js@@ -176,6 +176,8 @@ export function decisionFromVerdict(verdict) {// actor; it never overrides a spam signal, a security alert or an invitation.const LEARNED_DECISIONS = Object.freeze(['surface', 'suggest-done', 'suggest-mute']);const PINNED_RULES = new Set(['spam-signal', 'security-alert', 'invitation-never-accepted', 'deployment-approval']);+/** Triage rules no learned or automation rule may override. */+export const PINNED_TRIAGE_RULES = Object.freeze(PINNED_RULES);const ACTION_LESSONS = Object.freeze({ done: 'suggest-done', unsubscribe: 'suggest-done', mute: 'suggest-mute', reopen: 'surface', resubscribe: 'surface' });/** The decision an operator action teaches, or null when it teaches nothing (a plain read). */@@ -235,11 +237,19 @@ 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', 'ci-activity']);-// `ci-activity` rules name a GitHub action instead of starting an agent.-export const CI_RULE_ACTIONS = Object.freeze(['done', 'mute', 'leave']);+// The notification kinds an automation rule can name (GITHUB_AGENT_RULE_KINDS+// in lib/validation.js).+export const AGENT_RULE_KINDS = Object.freeze(['review-request', 'security-alert', 'issue-activity', 'ci-activity', 'own-pr', 'mention', 'release', 'other']);+const RULE_KINDS = new Set(AGENT_RULE_KINDS);+// What a rule does with a matching thread (#13192). A stored legacy rule's+// `agent: true/false` reads as `agent` / `leave`.+export const AGENT_RULE_ACTIONS = Object.freeze(['agent', 'done', 'mute', 'leave']);+// A security alert is never marked done or muted by a rule.+export const AGENT_ONLY_RULE_KINDS = Object.freeze(new Set(['security-alert']));+// Kinds no specific lane owns: an `agent` rule on one sends it to the generic+// lane on Autopilot. Review, issue and alert rules keep their meaning from+// before #13192 (their own lanes), so they never start a generic run.+export const GENERIC_RULE_KINDS = Object.freeze(new Set(['ci-activity', 'own-pr', 'mention', 'release', 'other']));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']);@@ -247,21 +257,56 @@ const REVIEW_TRUST = new Set(['yours', 'trusted']);// Mirrored in CANDIDATE_SQL (githubNotificationAutopilot.js).const FINISHED_SUBJECT_STATES = new Set(['merged', 'closed']);-function threadAgentKind(row) {+/** The rule kind of a thread, from its reason and subject type only. */+export 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?.reason === 'ci_activity' || row?.subject_type === 'CheckSuite') return 'ci-activity';if (row?.subject_type === 'Issue') return 'issue-activity';+ if (row?.reason === 'author' && row.subject_type === 'PullRequest') return 'own-pr';+ if (MENTION_REASONS.has(row?.reason)) return 'mention';+ if (row?.subject_type === 'Release') return 'release';+ return 'other';+}++// The SQL mirror of `threadAgentKind`, for candidate queries over+// github_notifications rows; the parity DB test fails when they drift.+export const KIND_SQL = `(CASE+ WHEN reason = 'security_alert' THEN 'security-alert'+ WHEN reason = 'review_requested' AND subject_type = 'PullRequest' THEN 'review-request'+ WHEN reason = 'ci_activity' OR subject_type = 'CheckSuite' THEN 'ci-activity'+ WHEN subject_type = 'Issue' THEN 'issue-activity'+ WHEN reason = 'author' AND subject_type = 'PullRequest' THEN 'own-pr'+ WHEN reason IN ('mention', 'team_mention') THEN 'mention'+ WHEN subject_type = 'Release' THEN 'release'+ ELSE 'other' END)`;++/** A stored rule's action: its `action`, else the legacy `agent` boolean, else null. */+export function agentRuleAction(rule) {+ if (AGENT_RULE_ACTIONS.includes(rule?.action)) return rule.action;+ if (typeof rule?.agent === 'boolean') return rule.agent ? 'agent' : 'leave';return null;}+/** Stored rules as the client edits them: legacy `agent` booleans read as `action`. */+export const normalizeAgentRules = (rules) => (Array.isArray(rules) ? rules : []).map((rule) => {+ const action = agentRuleAction(rule);+ if (!action || !rule || typeof rule !== 'object') return rule;+ const { agent: _legacy, ...rest } = rule;+ return { ...rest, action };+});+/**- * 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.+ * The account's rules for one kind, coerced to `{ ...rule, action }`. A+ * malformed rule, or one naming an action its kind cannot take, 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)- && (kind === 'ci-activity' ? CI_RULE_ACTIONS.includes(rule.action) : typeof rule.agent === 'boolean'));+const validRules = (rules, kind) => (Array.isArray(rules) ? rules : []).flatMap((rule) => {+ if (!rule || !RULE_KINDS.has(rule.kind) || rule.kind !== kind) return [];+ if (typeof rule.repo !== 'string' || !RULE_REPO_RE.test(rule.repo)) return [];+ const action = agentRuleAction(rule);+ if (!action || (AGENT_ONLY_RULE_KINDS.has(kind) && action !== 'agent' && action !== 'leave')) return [];+ return [{ ...rule, action }];+});// Built-in rules shown under every account. A rule the operator saves for the// same kind and repo wins; with none, a CI notice is simply marked done.@@ -269,18 +314,21 @@ export const DEFAULT_AGENT_RULES = Object.freeze([Object.freeze({ id: 'default-ci-activity', kind: 'ci-activity', repo: '*', action: 'done', builtin: true }),]);-const isCiThread = (row) => row?.reason === 'ci_activity' || row?.subject_type === 'CheckSuite';+const withDefaults = (account) => [...(Array.isArray(account?.agentRules) ? account.agentRules : []), ...DEFAULT_AGENT_RULES];/**- * What the account's rules do with a CI notification: `done`, `mute` or- * `leave`. The repo's own rule, else the `*` rule, else the built-in default.- * Suspect and closed-out threads are handled elsewhere, so this only reads- * the thread's kind and repo.+ * The GitHub write the account's rules make for a thread on Assist or+ * Autopilot: `done` or `mute`, or null (no rule, or a rule that starts an agent+ * or leaves it). A rule is the operator's own choice, so it needs no trusted+ * actor, but it never acts on a suspect or closed thread, or one a pinned rule+ * decided (a security alert, an invitation, a deployment approval).+ * `row.rule` is the triage rule (`evidence->>'rule'`).*/-export function ciActivityAction({ account, row }) {- if (!isCiThread(row)) return null;- const rules = [...(Array.isArray(account?.agentRules) ? account.agentRules : []), ...DEFAULT_AGENT_RULES];- return matchAgentRule(rules, 'ci-activity', row.repo_full_name)?.action || null;+export function ruleAction({ account, row }) {+ if (!row || row.suspect || row.state !== 'open') return null;+ if (PINNED_RULES.has(row.rule ?? row.evidence?.rule) || row.reason === 'security_alert') return null;+ const action = matchAgentRule(withDefaults(account), threadAgentKind(row), row.repo_full_name)?.action;+ return action === 'done' || action === 'mute' ? action : null;}function matchAgentRule(rules, kind, repo) {@@ -291,20 +339,25 @@ function matchAgentRule(rules, kind, repo) {}/**- * 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.+ * Which repos a kind of thread gets one of `actions` in, for a 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 in+ * unless `optIn`. Mirrors `matchAgentRule`, so a row a rule keeps out never+ * takes a slot in the run.*/-export function agentRuleScope(rules, kind, { optIn = false } = {}) {+export function agentRuleScope(rules, kind, { optIn = false, actions = ['agent'] } = {}) {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());+ const all = star ? actions.includes(star.action) : !optIn;+ const repos = (inScope) => valid.filter((rule) => rule.repo !== '*' && actions.includes(rule.action) === inScope).map((rule) => rule.repo.toLowerCase());return all ? { all, except: repos(false), only: [] } : { all, except: [], only: repos(true) };}+/** `agentRuleScope` over the account's rules plus the built-in defaults, for Assist's done/mute rules. */+export const ruleActionScope = (account, kind) => (AGENT_ONLY_RULE_KINDS.has(kind)+ ? { all: false, except: [], only: [] }+ : agentRuleScope(withDefaults(account), kind, { optIn: true, actions: ['done', 'mute'] }));+const rulePin = (rule) => {const pin = {};for (const key of ['provider', 'model', 'effort']) if (typeof rule?.[key] === 'string' && rule[key]) pin[key] = rule[key];@@ -363,7 +416,7 @@ export function agentHandoff({ account, row }) {if (!plan) plan = genericHandoff(row, evidence);const pin = rulePin(rule);if (pin) plan.pin = pin;- if (rule) plan.rule = { id: rule.id || null, agent: rule.agent };+ if (rule) plan.rule = { id: rule.id || null, action: rule.action };if (plan.refused) return plan;if (account?.trust === 'private' && account.allowAgents !== true) return { ...plan, refused: 'private-account' };const needsApp = !APP_FREE_AGENT_LANES.has(plan.lane);@@ -436,16 +489,19 @@ export function agentRunPin({ perRun, rulePin: rule, defaults } = {}) {/*** 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.+ * anything a rule gave another action, and minus an opt-in lane no rule+ * switched on. The generic lane runs only for a kind no specific lane owns,+ * on an explicit `agent` rule, and never for a thread already finished or+ * with an agent (CANDIDATE_SQL mirrors all of this).*/export function autopilotHandoff({ account, row }) {if (account?.mode !== 'autopilot') return null;const plan = agentHandoff({ account, row });- if (!plan || plan.rule?.agent === false) return null;- // The generic lane is on-tap only: an agent rule for it (#13192) is the only- // way Autopilot may start one, and the review/issue/alert rules do not count.- if (plan.lane === GENERIC_AGENT_LANE) return null;- if (plan.optIn && plan.rule?.agent !== true) return null;+ if (!plan || (plan.rule && plan.rule.action !== 'agent')) return null;+ if (plan.lane === GENERIC_AGENT_LANE) {+ if (plan.rule?.action !== 'agent' || !GENERIC_RULE_KINDS.has(threadAgentKind(row))) return null;+ return plan.refused === 'finished' || plan.refused === 'handed-off' ? null : plan;+ }+ if (plan.optIn && plan.rule?.action !== 'agent') return null;return plan;}diff --git a/server/lib/githubNotificationTriage.test.js b/server/lib/githubNotificationTriage.test.jsindex 5e58ed106e..0414405cbb 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, agentRuleScope, agentRunPin, ciActivityAction, applyLearnedRule, assistAction, autopilotHandoff, computeThreadTrust, decideThread, decisionFromVerdict, matchWaitingRun, parseCiBranch,+ agentHandoff, agentRuleScope, agentRunPin, ruleAction, applyLearnedRule, assistAction, autopilotHandoff, computeThreadTrust, decideThread, decisionFromVerdict, matchWaitingRun, parseCiBranch,selectNotificationProvider, spamSignals,MASS_MENTION_THRESHOLD,} from './githubNotificationTriage.js';@@ -234,7 +234,7 @@ describe('autopilotHandoff', () => {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 } });+ .toMatchObject({ lane: 'dependency-updates', rule: { id: 'one', action: 'leave' } });expect(autopilotHandoff({ account: { ...account, agentRules: rules }, row: { ...alert, repo_full_name: 'acme/other' } })).toMatchObject({ lane: 'dependency-updates', pin: { model: 'wide' }, rule: { id: 'all' } });});@@ -262,21 +262,44 @@ describe('autopilotHandoff', () => {it('applies agent rules and their pin on a Private account that allows agents', () => {const rules = [{ id: 'r', kind: 'review-request', repo: 'acme/app', agent: true, provider: 'p1' }];const enterprise = { ...account, trust: 'private', allowAgents: true, agentRules: rules };- expect(agentHandoff({ account: enterprise, row: { ...review, repo_full_name: 'acme/app' } })).toEqual({ lane: 'pr-reviewer', pullNumber: 42, pin: { provider: 'p1' }, rule: { id: 'r', agent: true } });+ expect(agentHandoff({ account: enterprise, row: { ...review, repo_full_name: 'acme/app' } })).toEqual({ lane: 'pr-reviewer', pullNumber: 42, pin: { provider: 'p1' }, rule: { id: 'r', action: 'agent' } });});});-describe('ciActivityAction', () => {- const ci = { reason: 'ci_activity', subject_type: 'CheckSuite', repo_full_name: 'acme/app' };+describe('ruleAction', () => {+ const ci = { state: 'open', reason: 'ci_activity', subject_type: 'CheckSuite', repo_full_name: 'acme/app', rule: 'ci-other' };it('marks CI notices done by default and lets a repo or * rule override it', () => {- expect(ciActivityAction({ account: { agentRules: [] }, row: ci })).toBe('done');+ expect(ruleAction({ account: { agentRules: [] }, row: ci })).toBe('done');const rules = [{ id: 'a', kind: 'ci-activity', repo: '*', action: 'leave' }, { id: 'b', kind: 'ci-activity', repo: 'acme/app', action: 'mute' }];- expect(ciActivityAction({ account: { agentRules: rules }, row: ci })).toBe('mute');- expect(ciActivityAction({ account: { agentRules: rules }, row: { ...ci, repo_full_name: 'acme/other' } })).toBe('leave');+ expect(ruleAction({ account: { agentRules: rules }, row: ci })).toBe('mute');+ expect(ruleAction({ account: { agentRules: rules }, row: { ...ci, repo_full_name: 'acme/other' } })).toBeNull();+ // A rule that starts an agent leaves the GitHub write to the fixed table.+ expect(ruleAction({ account: { agentRules: [{ kind: 'ci-activity', repo: '*', action: 'agent' }] }, row: ci })).toBeNull();+ expect(ruleAction({ account: { agentRules: [{ kind: 'ci-activity', repo: '*', action: 'nuke' }] }, row: ci })).toBe('done');});- it('ignores non-CI threads and malformed rules', () => {- expect(ciActivityAction({ account: {}, row: { reason: 'mention', subject_type: 'Issue' } })).toBeNull();- expect(ciActivityAction({ account: { agentRules: [{ kind: 'ci-activity', repo: '*', action: 'nuke' }] }, row: ci })).toBe('done');++ it('applies a done or mute rule to any kind, but never to a suspect thread, a security alert or a pinned decision', () => {+ const mention = { state: 'open', reason: 'mention', subject_type: 'PullRequest', repo_full_name: 'acme/app', rule: 'mention-elsewhere' };+ const rules = [+ { kind: 'mention', repo: 'acme/app', action: 'done' },+ { kind: 'other', repo: '*', action: 'mute' },+ // Refused at the schema; a stored one is ignored.+ { kind: 'security-alert', repo: '*', action: 'done' },+ ];+ const account = { agentRules: rules };+ expect(ruleAction({ account, row: mention })).toBe('done');+ expect(ruleAction({ account, row: { ...mention, suspect: true } })).toBeNull();+ expect(ruleAction({ account, row: { ...mention, state: 'done' } })).toBeNull();+ expect(ruleAction({ account, row: { ...mention, reason: 'security_alert', rule: 'security-alert' } })).toBeNull();+ const invitation = { state: 'open', reason: 'invitation', subject_type: 'RepositoryInvitation', repo_full_name: 'acme/app', rule: 'invitation-never-accepted' };+ expect(ruleAction({ account, row: invitation })).toBeNull();+ expect(ruleAction({ account, row: { ...invitation, reason: 'subscribed', subject_type: 'Discussion', rule: 'default' } })).toBe('mute');+ });++ it('reads a stored legacy agent boolean as agent or leave', () => {+ const issue = { state: 'open', reason: 'subscribed', subject_type: 'Issue', repo_full_name: 'acme/app', rule: 'default' };+ expect(ruleAction({ account: { agentRules: [{ kind: 'issue-activity', repo: '*', agent: false }] }, row: issue })).toBeNull();+ expect(agentRuleScope([{ kind: 'issue-activity', repo: '*', agent: false }], 'issue-activity')).toEqual({ all: false, except: [], only: [] });});});@@ -382,13 +405,21 @@ describe('generic notification-resolve lane (#13191)', () => {expect(agentHandoff({ account, row: { ...ci, evidence: legacyCi } })).toEqual({ lane: 'notification-resolve', repo: 'acme/app' });});- it('is on-tap only: Autopilot never starts it, whatever rules match the thread', () => {+ it('starts on Autopilot only for a kind no specific lane owns, on an explicit agent rule', () => {const issue = { ...ownPr, subject_type: 'Issue', evidence: { ...ownPr.evidence, commenter: null, commenterTrust: null } };const rules = [{ id: 'r', kind: 'issue-activity', repo: '*', agent: true, model: 'wide' }];const autopilot = { ...account, mode: 'autopilot', agentRules: rules };expect(agentHandoff({ account: autopilot, row: issue })).toMatchObject({ lane: 'notification-resolve', pin: { model: 'wide' } });+ // A legacy issue-activity rule meant the issue watcher, never a generic run.expect(autopilotHandoff({ account: autopilot, row: issue })).toBeNull();expect(autopilotHandoff({ account: { ...autopilot, agentRules: [] }, row: ci })).toBeNull();+ const ciAgent = { ...autopilot, agentRules: [{ id: 'c', kind: 'ci-activity', repo: 'acme/app', action: 'agent', effort: 'high' }] };+ expect(autopilotHandoff({ account: ciAgent, row: ci })).toEqual({ lane: 'notification-resolve', repo: 'acme/app', pin: { effort: 'high' }, rule: { id: 'c', action: 'agent' } });+ expect(autopilotHandoff({ account: { ...ciAgent, agentRules: [{ kind: 'ci-activity', repo: 'acme/app', action: 'done' }] }, row: ci })).toBeNull();+ // Outside content is still refused (recorded as a skip), and a finished thread is not a candidate.+ expect(autopilotHandoff({ account: { ...autopilot, agentRules: [{ kind: 'other', repo: '*', action: 'agent' }] }, row: { ...ownPr, trust: 'outside' } }))+ .toMatchObject({ refused: 'outside-content' });+ expect(autopilotHandoff({ account: ciAgent, row: { ...ci, decision: 'duplicate' } })).toBeNull();});it('picks the run pin whole: per-run, else the rule pin, else the account defaults', () => {diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 8cbfb36168..dcd7c42b97 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -952,28 +952,33 @@ 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(['disabled', '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', 'ci-activity']);-export const GITHUB_CI_RULE_ACTIONS = Object.freeze(['done', 'mute', 'leave']);+// Per-repo automation rules for the GitHub inbox (#13192): what Assist and+// Autopilot do with a kind of notification, in one repo (`owner/repo`) or every+// repo (`*`), and on which provider/model/effort when it starts an agent. A repo+// rule wins over the `*` rule of the same kind. Mirrors AGENT_RULE_KINDS and+// AGENT_RULE_ACTIONS in lib/githubNotificationTriage.js.+export const GITHUB_AGENT_RULE_KINDS = Object.freeze(['review-request', 'security-alert', 'issue-activity', 'ci-activity', 'own-pr', 'mention', 'release', 'other']);+export const GITHUB_AGENT_RULE_ACTIONS = Object.freeze(['agent', 'done', 'mute', 'leave']);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);+// A legacy `agent: true/false` (rules saved before #13192) is accepted and+// stored as `action: 'agent' / 'leave'`; `action` wins when both are sent.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'),- // `ci-activity` rules carry an `action` instead of `agent`.agent: z.boolean().optional(),- action: z.enum(GITHUB_CI_RULE_ACTIONS).optional(),+ action: z.enum(GITHUB_AGENT_RULE_ACTIONS).optional(),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().superRefine((rule, ctx) => {- const ci = rule.kind === 'ci-activity';- if (ci && !rule.action) ctx.addIssue({ code: 'custom', path: ['action'], message: 'Choose what to do with CI notifications' });- if (!ci && typeof rule.agent !== 'boolean') ctx.addIssue({ code: 'custom', path: ['agent'], message: 'Choose whether to start an agent' });-});+ const action = rule.action ?? (typeof rule.agent === 'boolean' ? (rule.agent ? 'agent' : 'leave') : null);+ if (!action) ctx.addIssue({ code: 'custom', path: ['action'], message: 'Choose what to do with these notifications' });+ else if (rule.kind === 'security-alert' && action !== 'agent' && action !== 'leave') {+ ctx.addIssue({ code: 'custom', path: ['action'], message: 'Security alerts are never marked done or muted by a rule' });+ }+}).transform(({ agent, ...rule }) => ({ ...rule, action: rule.action ?? (agent ? 'agent' : 'leave') }));export const githubAgentRulesSchema = z.array(githubAgentRuleSchema).max(200).superRefine((rules, ctx) => {const seen = new Set();rules.forEach((rule, index) => {diff --git a/server/services/githubNotificationAssist.js b/server/services/githubNotificationAssist.jsindex 968855024c..34db27deff 100644--- a/server/services/githubNotificationAssist.js+++ b/server/services/githubNotificationAssist.js@@ -15,7 +15,9 @@ import { z } from 'zod';import { query, withTransaction } from '../lib/db.js';import { safeJSONParse } from '../lib/fileUtils.js';import { repoApiPath } from '../lib/githubNotificationParse.js';-import { ASSIST_VERDICTS, assistAction, ciActivityAction, decisionFromVerdict, selectNotificationProvider } from '../lib/githubNotificationTriage.js';+import {+ AGENT_RULE_KINDS, ASSIST_VERDICTS, KIND_SQL, PINNED_TRIAGE_RULES, assistAction, decisionFromVerdict, ruleAction, ruleActionScope, selectNotificationProvider,+} from '../lib/githubNotificationTriage.js';import { resolveUntrustedContentPolicy } from '../lib/untrustedContent.js';import { toPgJson } from '../lib/pgJson.js';import { execGh } from './github.js';@@ -127,20 +129,29 @@ async function sortUndecided(account, env) {export async function assistAccountNotifications(account, env, { act }) {if (!ASSIST_MODES.has(account.mode)) return { sorted: 0, acted: 0 };const sorted = await sortUndecided(account, env);+ // Rows a done/mute automation rule (or the built-in CI rule) covers, scoped+ // exactly as `ruleAction` matches them, so a repo whose rule leaves its+ // threads never takes a slot. Pinned decisions are never a rule's to change.+ const scopes = AGENT_RULE_KINDS.map((kind) => ruleActionScope(account, kind));+ const ruleSql = AGENT_RULE_KINDS.map((kind, index) => {+ const n = 4 + index * 3;+ return `(${KIND_SQL} = '${kind}' AND (($${n}::boolean AND NOT (lower(repo_full_name) = ANY($${n + 1}::text[]))) OR lower(repo_full_name) = ANY($${n + 2}::text[])))`;+ }).join(' OR ');const { rows } = await query(`SELECT thread_id, decision, trust, suspect, state, reason, subject_type, repo_full_name, evidence->>'rule' AS rule FROM github_notificationsWHERE account_id = $1 AND state = 'open' AND NOT suspect AND NOT (evidence ? 'assisted')AND decision IS DISTINCT FROM 'handed-off'- AND (decision = ANY($2::text[]) OR reason = 'ci_activity' OR subject_type = 'CheckSuite')+ AND (decision = ANY($2::text[])+ OR (reason <> 'security_alert' AND NOT (COALESCE(evidence->>'rule', '') = ANY($3::text[])) AND (${ruleSql})))ORDER BY gh_updated_at DESC LIMIT ${MAX_ACTIONS_PER_RUN}`,- [account.id, ACTIONABLE_DECISIONS],+ [account.id, ACTIONABLE_DECISIONS, [...PINNED_TRIAGE_RULES], ...scopes.flatMap(({ all, except, only }) => [all, except, only])],);let acted = 0;for (const row of rows) {- // A CI rule is the operator's own choice, so it needs no trusted actor;- // `leave` falls back to the fixed table (a closed run is still done).- const ciAction = ciActivityAction({ account, row });- const action = (ciAction && ciAction !== 'leave' ? ciAction : null) || (ACTIONABLE_DECISIONS.includes(row.decision) ? assistAction(row) : null);+ // An automation rule is the operator's own choice, so it needs no trusted+ // actor; `leave` and `agent` fall back to the fixed table (a closed thread+ // is still done).+ const action = ruleAction({ account, row }) || (ACTIONABLE_DECISIONS.includes(row.decision) ? assistAction(row) : null);if (!action) continue;const ok = await act(row.thread_id, action, { decision: row.decision, rule: row.rule }).then(() => true)diff --git a/server/services/githubNotificationAutopilot.js b/server/services/githubNotificationAutopilot.jsindex 22541f01fc..537d8e9dce 100644--- a/server/services/githubNotificationAutopilot.js+++ b/server/services/githubNotificationAutopilot.js@@ -13,7 +13,9 @@* agent defaults). The inbox's Resolve with agent button hands one thread off* the same way on a tap, in any mode; a thread no specific lane fits goes on a* tap to a generic `notification-resolve` run (githubNotificationResolveTask.js),- * which Autopilot never starts on its own.+ * which Autopilot starts only for a kind no specific lane owns (CI, your own+ * PRs, mentions, releases, other) on an explicit `agent` automation rule+ * (#13192), after the same whole-thread commenter check as the tap.** 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@@ -23,7 +25,9 @@import { query, withTransaction } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';import { advisoryIdFromUrl } from '../lib/githubNotificationParse.js';-import { agentHandoff, agentRuleScope, agentRunPin, APP_FREE_AGENT_LANES as APP_FREE_LANES, autopilotHandoff, GENERIC_AGENT_LANE } from '../lib/githubNotificationTriage.js';+import {+ agentHandoff, agentRuleScope, agentRunPin, APP_FREE_AGENT_LANES as APP_FREE_LANES, autopilotHandoff, FINISHED_DECISIONS, GENERIC_AGENT_LANE, GENERIC_RULE_KINDS, KIND_SQL,+} from '../lib/githubNotificationTriage.js';import { toPgJson } from '../lib/pgJson.js';import { managedAppsByRepoKey, threadDiscussionVouched } from './githubNotificationTriage.js';import { requireAccountEnv } from './githubNotifications.js';@@ -36,19 +40,39 @@ 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 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 sqlList = (values) => [...values].map((value) => `'${value}'`).join(', ');+// `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[]))`;-export const CANDIDATE_SQL = `((reason = 'review_requested' AND subject_type = 'PullRequest' AND COALESCE(evidence->>'subjectState', '') NOT IN ('merged', 'closed') 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')+const NOT_FINISHED_SQL = `COALESCE(evidence->>'subjectState', '') NOT IN ('merged', 'closed')`;+const PULL_URL_SQL = `COALESCE(subject_api_url, '') ~ '/pulls/[0-9]{1,9}$'`;++/**+ * The SQL mirror of `autopilotHandoff` over the account's 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. Parameters+ * start at `$first`. The parity DB test runs every kind × action through both.+ */+function candidateFilter(rules, first = 2) {+ const scopes = [+ agentRuleScope(rules, 'review-request'),+ agentRuleScope(rules, 'review-request', { optIn: true }),+ agentRuleScope(rules, 'issue-activity'),+ agentRuleScope(rules, 'security-alert'),+ ];+ const generic = [...GENERIC_RULE_KINDS].map((kind) => agentRuleScope(rules, kind, { optIn: true }));+ const at = (index) => first + index * 3;+ const genericSql = [...GENERIC_RULE_KINDS].map((kind, index) => `(${KIND_SQL} = '${kind}' AND ${inScope(at(scopes.length + index))})`).join(' OR ');+ const sql = `((${KIND_SQL} = 'review-request' AND ${NOT_FINISHED_SQL} AND ${PULL_URL_SQL} AND (+ (decision = 'suggest-untrusted-review' AND COALESCE(trust, '') NOT IN ('yours', 'trusted') AND (evidence->>'repoManaged')::boolean IS TRUE AND ${inScope(at(0))})+ OR (decision IN ('suggest-review', 'suggest-untrusted-review', 'needs-you', 'surface') AND trust IN ('yours', 'trusted') AND ${inScope(at(1))})))+ OR (${KIND_SQL} = 'issue-activity' AND decision IN ('needs-you', 'surface')AND (trust = 'outside' OR (evidence->>'commenter' IS NOT NULL AND COALESCE(evidence->>'commenterTrust', '') NOT IN ('yours', 'trusted')))- 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];+ AND (evidence->>'repoManaged')::boolean IS TRUE AND ${inScope(at(2))})+ OR (${KIND_SQL} = 'security-alert' AND decision = 'surface-high' AND ${inScope(at(3))})+ OR (COALESCE(decision, '') NOT IN (${sqlList([...FINISHED_DECISIONS, 'handed-off'])}) AND ${NOT_FINISHED_SQL} AND (${genericSql})))`;+ const params = [...scopes, ...generic].flatMap(({ all, except, only }) => [all, except, only]);+ return { sql, params };+}/*** Queue the app's run of a whole-app lane unless one is already queued or@@ -127,26 +151,20 @@ async function recordHandoff(account, row, handoff, actor = 'automation') {* `autopilotHandoff`, so each must agree with it on every row.*/async function listAutopilotCandidates(account) {- const rules = account.agentRules;+ const candidates = candidateFilter(account.agentRules, 2);const { rows } = await query(`SELECT * FROM github_notifications WHERE account_id = $1 AND state = 'open' AND NOT suspect- AND ${CANDIDATE_SQL} AND NOT (evidence ? 'handoff')+ AND ${candidates.sql} AND NOT (evidence ? 'handoff')ORDER BY gh_updated_at DESC LIMIT ${MAX_HANDOFFS_PER_RUN}`,- [- account.id,- ...scopeParams(agentRuleScope(rules, 'review-request')),- ...scopeParams(agentRuleScope(rules, 'review-request', { optIn: true })),- ...scopeParams(agentRuleScope(rules, 'issue-activity')),- ...scopeParams(agentRuleScope(rules, 'security-alert')),- ],+ [account.id, ...candidates.params],);return rows;}// The DB suite checks the SQL prefilter against `autopilotHandoff` row by row.-export const __testing = { listAutopilotCandidates };+export const __testing = { listAutopilotCandidates, candidateFilter };-export async function autopilotAccountNotifications(account) {+export async function autopilotAccountNotifications(account, env = null) {if (account.mode !== 'autopilot') return { handedOff: 0, agentRuns: 0 };const rows = await listAutopilotCandidates(account);const plans = rows.map((row) => ({ row, plan: withRunPin(account, autopilotHandoff({ account, row })) })).filter((entry) => entry.plan);@@ -159,7 +177,9 @@ export async function autopilotAccountNotifications(account) {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 || '*';+ // A generic run resolves one thread.+ const target = entry.plan.lane === 'do-review' ? `${entry.row.repo_full_name}#${entry.plan.pullNumber}`+ : entry.plan.lane === GENERIC_AGENT_LANE ? `thread#${entry.row.thread_id}` : 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 });@@ -183,6 +203,8 @@ export async function autopilotAccountNotifications(account) {appName: app?.name || null,...(plan.pullNumber ? { pullNumber: plan.pullNumber } : {}),...(plan.pin ? { pin: plan.pin } : {}),+ // A failed generic run restores it (githubNotificationResolveTask.js).+ ...(plan.lane === GENERIC_AGENT_LANE ? { previousDecision: row.decision || null } : {}),...outcome,at: new Date().toISOString(),};@@ -200,6 +222,15 @@ export async function autopilotAccountNotifications(account) {const batchPlan = lane === 'do-review' || (lane === 'pr-reviewer' && pullNumbers.size === 1)? plan: { lane, repo, ...(plan.pin ? { pin: plan.pin } : {}) };+ // The generic run reads the whole thread, not just the latest comment+ // triage rated, so every commenter is checked first, as on a tap.+ if (lane === GENERIC_AGENT_LANE) {+ const vouched = await threadDiscussionVouched(account, env || await requireAccountEnv(account), entries[0].row).catch(() => false);+ if (!vouched) {+ for (const entry of entries) await record({ ...entry, outcome: { skipped: 'outside-content' } });+ continue;+ }+ }// 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) })diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex 0ef1614621..778c46c19c 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -44,8 +44,7 @@ const { addNotification } = await import('./notifications.js');const { addTask } = await import('./cosTaskStore.js');const { runUntrustedContentAnalysis } = await import('./untrustedContent.js');const { createAccount, updateAccount } = await import('./githubAccounts.js');-const { __testing: { listAutopilotCandidates } } = await import('./githubNotificationAutopilot.js');-const { autopilotHandoff } = await import('../lib/githubNotificationTriage.js');+const { __testing: { listAutopilotCandidates, candidateFilter } } = await import('./githubNotificationAutopilot.js');const {syncAccountNotifications, syncAllNotifications, listNotifications, applyNotificationAction, clearFinishedNotifications, getNotification, runScheduledNotificationCheck, describeScheduledCheck,listAutomationActivity, undoAutomationAction, listLearnedRules, resolveWithAgent, getAutomationsOverview, setNotificationCadence,@@ -54,7 +53,7 @@ const { getDeploymentReview, reviewDeployment } = await import('./githubNotificaconst { startNotificationResolveListener } = await import('./githubNotificationResolveTask.js');const { cosEvents } = await import('./cosEvents.js');const { runAccountAudit, applyAuditSuggestion, listAuditChanges, undoAuditChange, sendDueAuditReports } = await import('./githubNotificationAudit.js');-const { CANDIDATE_SQL } = await import('./githubNotificationAutopilot.js');+const { AGENT_RULE_ACTIONS, AGENT_RULE_KINDS, KIND_SQL, autopilotHandoff, threadAgentKind } = await import('../lib/githubNotificationTriage.js');let dbReady = false;let skipReason = '';@@ -959,7 +958,7 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {// A review request on a merged PR is finished: marked done, never reviewed.expect(await getNotification(account.id, '1504')).toMatchObject({ decision: 'suggest-mark-read', state: 'done' });// A row still decided as a review suggestion is not an Autopilot candidate- // once its PR is merged (CANDIDATE_SQL mirrors agentHandoff).+ // once its PR is merged (candidateFilter mirrors agentHandoff).await query(`UPDATE github_notifications SET state = 'open', decision = 'suggest-review', evidence = evidence - 'assisted'WHERE account_id = $1 AND thread_id = '1504'`,@@ -1068,17 +1067,13 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {expect(triggerOnDemandTask).toHaveBeenCalledWith('issue-watcher', 'app-acme', { origin: 'github-notification' });expect(await getNotification(account.id, '1602')).toMatchObject({ decision: 'handed-off' });- // CANDIDATE_SQL prefilter agrees with autopilotHandoff: selects 1602 (outside commenter), excludes 1601 (vouched)+ // The candidate prefilter agrees with autopilotHandoff: selects 1602 (outside commenter), excludes 1601 (vouched)await query(`UPDATE github_notifications SET decision = 'needs-you' WHERE thread_id = '1602' AND account_id = $1`, [account.id]);- const candidateQuery = `SELECT thread_id FROM github_notifications WHERE account_id = $1 AND thread_id = ANY($14::text[]) AND ${CANDIDATE_SQL}`;- const { rows: candidateRows } = await query(candidateQuery, [- account.id,- true, [], [],- true, [], [],- true, [], [],- true, [], [],- ['1601', '1602'],- ]);+ const filter = candidateFilter([], 3);+ const { rows: candidateRows } = await query(+ `SELECT thread_id FROM github_notifications WHERE account_id = $1 AND thread_id = ANY($2::text[]) AND ${filter.sql}`,+ [account.id, ['1601', '1602'], ...filter.params],+ );expect(candidateRows.map((r) => r.thread_id)).toEqual(['1602']);await query(`UPDATE github_notifications SET decision = 'handed-off' WHERE thread_id = '1602' AND account_id = $1`, [account.id]);@@ -1116,6 +1111,142 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {vi.mocked(getAllApps).mockResolvedValue([]);});+ it('keeps the Autopilot candidate SQL and the rule-kind SQL in step with the JS planner for every kind × action (#13192)', async () => {+ // One open row per kind, shaped so the kind's lane (or the generic lane)+ // would take it: managed, owned and vouched, so only the rules decide.+ const evidence = (extra = {}) => ({ repoManaged: true, repoOwned: true, metadataMissing: false, commenter: null, commenterTrust: null, ...extra });+ const fixtures = {+ 'review-request': [+ { reason: 'review_requested', subject_type: 'PullRequest', trust: 'outside', decision: 'suggest-untrusted-review', evidence: evidence({ rule: 'review-outside-author' }) },+ { reason: 'review_requested', subject_type: 'PullRequest', trust: 'trusted', decision: 'suggest-review', evidence: evidence({ rule: 'review-trusted-author' }) },+ ],+ 'security-alert': [{ reason: 'security_alert', subject_type: 'RepositoryVulnerabilityAlert', trust: 'unknown', decision: 'surface-high', evidence: evidence({ rule: 'security-alert' }) }],+ 'issue-activity': [{ reason: 'subscribed', subject_type: 'Issue', trust: 'outside', decision: 'needs-you', evidence: evidence({ rule: 'default' }) }],+ 'ci-activity': [+ { reason: 'ci_activity', subject_type: 'CheckSuite', trust: 'unknown', decision: 'surface', evidence: evidence({ rule: 'ci-default-branch' }) },+ { reason: 'ci_activity', subject_type: 'CheckSuite', trust: 'unknown', decision: 'duplicate', evidence: evidence({ rule: 'ci-default-branch' }) },+ ],+ 'own-pr': [{ reason: 'author', subject_type: 'PullRequest', trust: 'yours', decision: 'needs-you', evidence: evidence({ rule: 'default', repoManaged: false }) }],+ mention: [{ reason: 'mention', subject_type: 'PullRequest', trust: 'trusted', decision: 'needs-you', evidence: evidence({ rule: 'default' }) }],+ release: [{ reason: 'subscribed', subject_type: 'Release', trust: 'unknown', decision: 'needs-you', evidence: evidence({ rule: 'default' }) }],+ other: [+ { reason: 'comment', subject_type: 'Discussion', trust: 'yours', decision: 'needs-you', evidence: evidence({ rule: 'default' }) },+ { reason: '', subject_type: '', trust: 'yours', decision: 'needs-you', evidence: evidence({ rule: 'default' }) },+ ],+ };+ // Every kind the planner knows has a fixture, so a new kind cannot skip the check.+ expect(Object.keys(fixtures).sort()).toEqual([...AGENT_RULE_KINDS].sort());+ const rows = [];+ let n = 0;+ for (const [kind, shapes] of Object.entries(fixtures)) {+ for (const shape of shapes) {+ n += 1;+ const row = {+ account_id: account.id, thread_id: `parity-${n}`, repo_full_name: 'acme/app', repo_owner: 'acme', state: 'open', suspect: false,+ subject_api_url: `https://api.github.com/repos/acme/app/${shape.subject_type === 'Issue' ? 'issues' : 'pulls'}/${n}`, latest_comment_api_url: null, ...shape,+ };+ await query(+ `INSERT INTO github_notifications (account_id, thread_id, repo_full_name, repo_owner, reason, subject_type, subject_api_url, gh_updated_at, state, decision, trust, suspect, evidence)+ VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), 'open', $8, $9, FALSE, $10::jsonb)`,+ [row.account_id, row.thread_id, row.repo_full_name, row.repo_owner, row.reason, row.subject_type, row.subject_api_url, row.decision, row.trust, JSON.stringify(row.evidence)],+ );+ rows.push({ kind, row });+ }+ }+ const ids = rows.map(({ row }) => row.thread_id);+ // The SQL classifier names the same kind as threadAgentKind.+ const { rows: kinds } = await query(`SELECT thread_id, ${KIND_SQL} AS kind FROM github_notifications WHERE account_id = $1 AND thread_id = ANY($2::text[])`, [account.id, ids]);+ const sqlKind = new Map(kinds.map((entry) => [entry.thread_id, entry.kind]));+ for (const { kind, row } of rows) {+ expect(threadAgentKind(row), row.thread_id).toBe(kind);+ expect(sqlKind.get(row.thread_id), row.thread_id).toBe(kind);+ }+ const disagreements = [];+ for (const ruleKind of AGENT_RULE_KINDS) {+ for (const action of [...AGENT_RULE_ACTIONS, null]) {+ for (const repo of ['*', 'acme/app']) {+ const agentRules = action ? [{ id: 'parity', kind: ruleKind, repo, action }] : [];+ const autopilot = { ...account, mode: 'autopilot', agentRules };+ const filter = candidateFilter(agentRules, 3);+ const { rows: selected } = await query(+ `SELECT thread_id FROM github_notifications WHERE account_id = $1 AND thread_id = ANY($2::text[]) AND ${filter.sql}`,+ [account.id, ids, ...filter.params],+ );+ const sqlIds = new Set(selected.map((entry) => entry.thread_id));+ for (const { row } of rows) {+ const js = Boolean(autopilotHandoff({ account: autopilot, row }));+ if (js !== sqlIds.has(row.thread_id)) disagreements.push(`${ruleKind}/${action}/${repo} on ${row.thread_id} (${threadAgentKind(row)}): js=${js} sql=${!js}`);+ }+ }+ }+ }+ expect(disagreements).toEqual([]);+ await query('DELETE FROM github_notifications WHERE account_id = $1 AND thread_id = ANY($2::text[])', [account.id, ids]);+ });++ it('applies done rules saved from a row on the next Assist run, never to security alerts, and keeps legacy agent rules (#13192)', async () => {+ await updateAccount(account.id, {+ mode: 'assist',+ agentRules: [+ { id: 'rule-mentions', kind: 'mention', repo: 'acme/app', action: 'done' },+ // A legacy rule from before #13192 is accepted and stored as an action.+ { id: 'rule-legacy', kind: 'issue-activity', repo: '*', agent: true },+ ],+ });+ expect(() => updateAccount(account.id, { agentRules: [{ id: 'x', kind: 'security-alert', repo: '*', action: 'done' }] })).toThrow('Validation failed');+ vi.mocked(runUntrustedContentAnalysis).mockResolvedValue({ ok: false, code: 'untrusted-content-blocked' });+ const actions = mockGh(() => listing([+ thread('1701', { owner: 'acme', repo: 'app', reason: 'mention', type: 'Issue', url: 'https://api.github.com/repos/acme/app/issues/1701' }),+ thread('1702', { owner: 'acme', repo: 'app', reason: 'mention', type: 'PullRequest' }),+ thread('1703', { owner: 'acme', repo: 'other', reason: 'mention', type: 'PullRequest' }),+ thread('1704', { owner: 'acme', repo: 'app', reason: 'security_alert', type: 'RepositoryVulnerabilityAlert', url: null }),+ ]), {+ 'repos/acme/app/issues/1701': { author: 'teammate', association: 'COLLABORATOR', state: 'open', merged: false },+ 'repos/acme/app/pulls/1702': { author: 'teammate', association: 'COLLABORATOR', state: 'open', merged: false },+ 'repos/acme/other/pulls/1703': { author: 'teammate', association: 'COLLABORATOR', state: 'open', merged: false },+ 'repos/acme/app/collaborators/teammate/permission': { user: { login: 'teammate' }, permission: 'write' },+ 'repos/acme/other/collaborators/teammate/permission': { user: { login: 'teammate' }, permission: 'write' },+ });+ await syncAccountNotifications(account.id);+ // A mention on a PR in acme/app matches the rule; one on an issue is issue activity.+ expect(await getNotification(account.id, '1702')).toMatchObject({ state: 'done' });+ expect(actions).toContainEqual(['DELETE', 'notifications/threads/1702']);+ for (const id of ['1701', '1703', '1704']) expect(await getNotification(account.id, id), id).toMatchObject({ state: 'open' });+ // The automation event can be undone like any other.+ const done = (await listAutomationActivity()).find((entry) => entry.accountId === account.id && entry.threadId === '1702');+ expect(done).toMatchObject({ action: 'done', undoable: true });+ await undoAutomationAction(done.id);+ expect(await getNotification(account.id, '1702')).toMatchObject({ state: 'open' });+ // The legacy rule reads back as an agent action.+ const overview = await getAutomationsOverview();+ const card = overview.accounts.find((entry) => entry.id === account.id);+ expect(card.agentRules.find((rule) => rule.id === 'rule-legacy')).toEqual({ id: 'rule-legacy', kind: 'issue-activity', repo: '*', action: 'agent' });+ expect(card.openByKind).toEqual(expect.arrayContaining([expect.objectContaining({ kind: 'mention', repo: 'acme/app', total: 1, actionable: 1 }), expect.objectContaining({ kind: 'security-alert', actionable: 0 })]));+ await updateAccount(account.id, { mode: 'observe', agentRules: [] });+ });++ it('starts a generic agent run on Autopilot for CI in a repo of yours only under an explicit agent rule (#13192)', async () => {+ const login = account.login;+ let taskCount = 0;+ vi.mocked(addTask).mockReset().mockImplementation(async (task) => ({ id: `task-${++taskCount}`, description: task.description }));+ vi.mocked(runUntrustedContentAnalysis).mockResolvedValue({ ok: false, code: 'untrusted-content-blocked' });+ const ciThread = (id, repo) => thread(id, {+ owner: login, repo, reason: 'ci_activity', type: 'CheckSuite', url: null, title: 'CI failed for main branch',+ });+ await updateAccount(account.id, { mode: 'autopilot', agentRules: [{ id: 'rule-ci', kind: 'ci-activity', repo: `${login}/tool`, action: 'agent', effort: 'high' }] });+ mockGh(() => listing([ciThread('1801', 'tool'), ciThread('1802', 'side')]), {+ [`repos/${login}/tool`]: { default_branch: 'main' },+ [`repos/${login}/side`]: { default_branch: 'main' },+ });+ expect((await syncAccountNotifications(account.id)).assist).toMatchObject({ handedOff: 1, agentRuns: 1 });+ expect(vi.mocked(addTask).mock.calls[0][0]).toMatchObject({ effort: 'high', metadata: { githubNotificationResolve: { threadId: '1801', repo: `${login}/tool` } } });+ expect(await getNotification(account.id, '1801')).toMatchObject({ decision: 'handed-off' });+ // No agent rule for the other repo: the built-in CI rule marks it done instead.+ expect(await getNotification(account.id, '1802')).toMatchObject({ state: 'done' });+ expect(addTask).toHaveBeenCalledTimes(1);+ await updateAccount(account.id, { mode: 'observe', agentRules: [] });+ });+it('runs the scheduled pass without any model call, respecting the poll interval', async () => {mockGh(() => listing([thread('801')]));const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('no network in this test'));diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.jsindex 1b509156e7..0cc96ad583 100644--- a/server/services/githubNotifications.js+++ b/server/services/githubNotifications.js@@ -24,7 +24,9 @@ import { getAccount, listAccounts, resolveGitHubAccountEnv } from './githubAccouimport { githubNotificationEvents } from './githubNotificationEvents.js';import { triageAccountNotifications } from './githubNotificationTriage.js';import { assistAccountNotifications } from './githubNotificationAssist.js';-import { agentHandoff, agentRunPin, DEFAULT_AGENT_RULES, FINISHED_DECISIONS, learnedDecisionForAction } from '../lib/githubNotificationTriage.js';+import {+ agentHandoff, agentRunPin, DEFAULT_AGENT_RULES, FINISHED_DECISIONS, KIND_SQL, learnedDecisionForAction, normalizeAgentRules, PINNED_TRIAGE_RULES, threadAgentKind,+} from '../lib/githubNotificationTriage.js';import { toPgJson } from '../lib/pgJson.js';const GH_TIMEOUT_MS = 30_000;@@ -174,7 +176,7 @@ const SKIPPED_AUTOMATION = Object.freeze({ sorted: 0, acted: 0, handedOff: 0, agasync function runAutomation(account, env, automate) {if (!automate) return SKIPPED_AUTOMATION;const autopilot = account.mode === 'autopilot'- ? await (await import('./githubNotificationAutopilot.js')).autopilotAccountNotifications(account)+ ? await (await import('./githubNotificationAutopilot.js')).autopilotAccountNotifications(account, env): { handedOff: 0, agentRuns: 0 };const assist = await assistAccountNotifications(account, env, {act: (threadId, action, detail) => applyNotificationAction(account.id, threadId, action, { actor: 'automation', detail }),@@ -358,6 +360,8 @@ const toApi = (row, accountsById) => {suspect: row.suspect === true,rule: row.evidence?.rule || null,signals: Array.isArray(row.evidence?.signals) ? row.evidence.signals : [],+ // The automation-rule kind, so a row can prefill Add automation rule (#13192).+ ruleKind: threadAgentKind(row),agent: agentView(account, row),agentFailed: agentFailedView(row),updatedAt: toIso(row.gh_updated_at),@@ -643,7 +647,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, repoRows] = await Promise.all([+ const [syncRows, countRows, repoRows, openRows] = 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,@@ -657,7 +661,23 @@ export async function getAutomationsOverview() {FROM github_notifications WHERE account_id = ANY($1::text[]) AND repo_full_name <> '' GROUP BY account_id`,[ids],),+ // Open threads per rule kind and repo, so the rule form can say how many a+ // rule matches now. `actionable` leaves out the threads a pinned triage rule+ // decided, which a done or mute rule never touches.+ query(+ `SELECT account_id, ${KIND_SQL} AS kind, lower(repo_full_name) AS repo, COUNT(*)::int AS total,+ COUNT(*) FILTER (WHERE NOT (COALESCE(evidence->>'rule', '') = ANY($2::text[])))::int AS actionable+ FROM github_notifications WHERE account_id = ANY($1::text[]) AND state = 'open' AND NOT suspect+ AND decision IS DISTINCT FROM 'handed-off'+ GROUP BY 1, 2, 3`,+ [ids, [...PINNED_TRIAGE_RULES]],+ ),]);+ const openById = new Map();+ for (const row of openRows.rows) {+ if (!openById.has(row.account_id)) openById.set(row.account_id, []);+ openById.get(row.account_id).push({ kind: row.kind, repo: row.repo, total: row.total, actionable: row.actionable });+ }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]));@@ -683,9 +703,10 @@ export async function getAutomationsOverview() {pending: counts?.pending || 0,allowAgents: account.allowAgents === true,agentDefaults: account.agentDefaults || null,- agentRules: Array.isArray(account.agentRules) ? account.agentRules : [],+ agentRules: normalizeAgentRules(account.agentRules),defaultAgentRules: DEFAULT_AGENT_RULES,repos: reposById.get(account.id) || [],+ openByKind: openById.get(account.id) || [],};}),};