Skip to content

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

Add a notification subscription audit to the GitHub page (#12900)

[._.]/72e63f97474a
diff --git a/client/src/components/github/GitHubAuditTab.jsx b/client/src/components/github/GitHubAuditTab.jsx
new file mode 100644
index 0000000000..b623e70729
--- /dev/null
+++ b/client/src/components/github/GitHubAuditTab.jsx
@@ -0,0 +1,209 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Link, useSearchParams } from 'react-router';
+import { ExternalLink, Search, Undo2 } from 'lucide-react';
+import Pill from '../ui/Pill';
+import ListLoadError from '../ui/ListLoadError';
+import useListResource from '../../hooks/useListResource';
+import { timeAgo } from '../../utils/formatters';
+import {
+ applyGitHubAuditSuggestion,
+ getGitHubAccounts,
+ getGitHubAudit,
+ getGitHubAuditChanges,
+ runGitHubAudit,
+ undoGitHubAuditChange,
+} from '../../services/api';
+
+const fetchAccounts = () => getGitHubAccounts({ silent: true });
+
+function suggestionTitle(suggestion) {
+ if (suggestion.kind === 'unwatch') return `Unwatch ${suggestion.repo}`;
+ if (suggestion.kind === 'mute-handled') return `Mute ${suggestion.threadIds.length} handled thread${suggestion.threadIds.length === 1 ? '' : 's'} in ${suggestion.repo}`;
+ if (suggestion.kind === 'custom-watch') return `Watch only releases and security in ${suggestion.repo}`;
+ return 'Only get notified about failed workflows';
+}
+
+const SUGGESTION_HINTS = {
+ unwatch: 'You never acted on these; they come from watching the repo.',
+ 'mute-handled': 'The PR workflow already handles these CI threads.',
+ 'custom-watch': 'GitHub only offers this on the repo page: Watch › Custom.',
+ 'actions-failed-only': 'Set Actions to "Only notify for failed workflows" in your GitHub notification settings.',
+};
+
+const CHANGE_LABELS = { unwatch: 'Unwatched', 'mute-handled': 'Muted handled threads in' };
+
+function SuggestionCard({ suggestion, onApply, onSkip, applying }) {
+ const { total, acted, handled } = suggestion.stats;
+ return (
+ <li className="min-w-0 space-y-2 rounded-lg border border-port-border bg-port-card p-4">
+ <div className="flex flex-wrap items-start gap-2">
+ <h3 className="min-w-0 flex-1 break-words font-semibold text-white">{suggestionTitle(suggestion)}</h3>
+ {suggestion.applied && <Pill tone="success">Applied</Pill>}
+ </div>
+ <p className="text-xs text-gray-300">{total} notifications · {acted} you acted on · {handled} handled by PortOS</p>
+ <p className="text-xs text-gray-400">{SUGGESTION_HINTS[suggestion.kind]}</p>
+ {!suggestion.applied && (
+ <div className="flex flex-wrap gap-2">
+ {suggestion.apply ? (
+ <button type="button" onClick={() => onApply(suggestion.id)} disabled={applying} className="rounded bg-port-accent px-3 py-1.5 text-xs text-white disabled:opacity-50">
+ {applying ? 'Applying…' : 'Apply'}
+ </button>
+ ) : (
+ <a href={suggestion.link} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 rounded bg-port-accent px-3 py-1.5 text-xs text-white">
+ <ExternalLink size={12} aria-hidden="true" /> Open on GitHub
+ </a>
+ )}
+ <button type="button" onClick={() => onSkip(suggestion.id)} className="rounded border border-port-border px-3 py-1.5 text-xs text-gray-300">Skip</button>
+ </div>
+ )}
+ </li>
+ );
+}
+
+export default function GitHubAuditTab() {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const { items: accounts, state: accountsState, error: accountsError, retry } = useListResource(fetchAccounts);
+ const accountId = searchParams.get('account') || accounts[0]?.id || null;
+ const [audit, setAudit] = useState(null);
+ const [running, setRunning] = useState(false);
+ const [skipped, setSkipped] = useState(() => new Set());
+ const [applyingId, setApplyingId] = useState(null);
+ const [changes, setChanges] = useState([]);
+ const [undoingId, setUndoingId] = useState(null);
+
+ const loadChanges = useCallback(async () => {
+ const result = await getGitHubAuditChanges({ silent: true }).catch(() => null);
+ if (result) setChanges(result.changes);
+ }, []);
+
+ useEffect(() => { loadChanges(); }, [loadChanges]);
+ useEffect(() => {
+ if (!accountId) return undefined;
+ let active = true;
+ setAudit(null);
+ getGitHubAudit(accountId, { silent: true })
+ .then((result) => { if (active) setAudit(result.audit); })
+ .catch(() => {});
+ return () => { active = false; };
+ }, [accountId]);
+
+ const run = async () => {
+ setRunning(true);
+ const result = await runGitHubAudit(accountId).catch(() => null);
+ setRunning(false);
+ if (result) {
+ setAudit(result.audit);
+ setSkipped(new Set());
+ }
+ };
+
+ const apply = async (suggestionId) => {
+ setApplyingId(suggestionId);
+ const applied = await applyGitHubAuditSuggestion(accountId, suggestionId).catch(() => null);
+ setApplyingId(null);
+ if (!applied) return;
+ setAudit((prev) => ({ ...prev, suggestions: prev.suggestions.map((entry) => (entry.id === suggestionId ? { ...entry, applied: true } : entry)) }));
+ await loadChanges();
+ };
+
+ const undo = async (id) => {
+ setUndoingId(id);
+ const undone = await undoGitHubAuditChange(id).catch(() => null);
+ setUndoingId(null);
+ if (undone) setChanges((prev) => prev.map((change) => (change.id === id ? { ...change, undone: true } : change)));
+ };
+
+ if (accountsState === 'error') return <ListLoadError what="GitHub accounts" error={accountsError} onRetry={retry} />;
+ if (accountsState === 'loading') return <p className="text-sm text-gray-400">Loading accounts…</p>;
+ if (!accounts.length) {
+ return (
+ <p className="rounded-lg border border-port-border bg-port-card p-4 text-sm text-gray-400">
+ No GitHub accounts yet. <Link to="/devtools/github/accounts" className="text-port-accent">Add one</Link>
+ </p>
+ );
+ }
+
+ const visible = audit?.suggestions.filter((suggestion) => !skipped.has(suggestion.id)) || [];
+
+ return (
+ <div className="min-w-0 space-y-4">
+ <section className="space-y-3 rounded-lg border border-port-border bg-port-card p-4" aria-label="Run notification audit">
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="min-w-0 flex-1 space-y-1">
+ <label htmlFor="github-audit-account" className="block text-xs text-gray-400">Account</label>
+ <select
+ id="github-audit-account"
+ value={accountId || ''}
+ onChange={(event) => setSearchParams({ account: event.target.value }, { replace: true })}
+ className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white"
+ >
+ {accounts.map((account) => <option key={account.id} value={account.id}>{account.label}</option>)}
+ </select>
+ </div>
+ <button type="button" onClick={run} disabled={running || !accountId} className="inline-flex items-center gap-1.5 rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">
+ <Search size={14} aria-hidden="true" /> {running ? 'Auditing…' : 'Run audit'}
+ </button>
+ </div>
+ {running && (
+ <div role="status" className="space-y-1">
+ <div className="h-1.5 overflow-hidden rounded bg-port-border"><div className="h-full w-1/3 animate-pulse rounded bg-port-accent" /></div>
+ <p className="text-xs text-gray-400">Reading watched repos and the last 30 days of notifications…</p>
+ </div>
+ )}
+ {audit && !running && (
+ <p className="text-xs text-gray-300">
+ Last {audit.windowDays} days: {audit.summary.total} notifications in {audit.summary.repos} repos · {audit.summary.acted} you acted on · {audit.summary.handled} handled by PortOS · audited {timeAgo(audit.ranAt)}
+ </p>
+ )}
+ {audit && !audit.watchedListed && <p className="text-xs text-port-warning">GitHub did not list your watched repos, so there are no unwatch suggestions this time.</p>}
+ {!audit && !running && <p className="text-xs text-gray-500">Nothing changes until you tap Apply on a suggestion.</p>}
+ </section>
+
+ {audit && (visible.length ? (
+ <ul className="grid grid-cols-1 gap-3 @3xl/page:grid-cols-2">
+ {visible.map((suggestion) => (
+ <SuggestionCard
+ key={suggestion.id}
+ suggestion={suggestion}
+ applying={applyingId === suggestion.id}
+ onApply={apply}
+ onSkip={(id) => setSkipped((prev) => new Set(prev).add(id))}
+ />
+ ))}
+ </ul>
+ ) : (
+ <p className="rounded-lg border border-port-border bg-port-card p-4 text-sm text-gray-400">No suggestions: your notifications look useful.</p>
+ ))}
+
+ <section className="space-y-2 rounded-lg border border-port-border bg-port-card p-4" aria-label="Applied audit changes">
+ <h2 className="font-semibold text-white">Applied changes</h2>
+ {changes.length === 0 ? (
+ <p className="text-xs text-gray-500">None yet.</p>
+ ) : (
+ <ul className="divide-y divide-port-border">
+ {changes.map((change) => (
+ <li key={change.id} className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 py-2">
+ <p className="min-w-0 flex-1 break-words text-xs text-gray-300">
+ {CHANGE_LABELS[change.kind] || change.kind} <span className="font-mono">{change.repo}</span>
+ {change.threadCount !== null ? ` (${change.threadCount})` : ''} · {change.accountLabel} · {timeAgo(change.appliedAt)}
+ </p>
+ {change.undone ? (
+ <Pill tone="muted">Undone</Pill>
+ ) : (
+ <button
+ type="button"
+ onClick={() => undo(change.id)}
+ disabled={undoingId === change.id}
+ className="inline-flex shrink-0 items-center gap-1 rounded border border-port-border px-2 py-1 text-xs text-gray-300 disabled:opacity-50"
+ >
+ <Undo2 size={12} aria-hidden="true" /> Undo
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ </div>
+ );
+}
diff --git a/client/src/pages/GitHub.jsx b/client/src/pages/GitHub.jsx
index d4a3302766..7c03ae4223 100644
--- a/client/src/pages/GitHub.jsx
+++ b/client/src/pages/GitHub.jsx
@@ -1,14 +1,15 @@
import { useParams } from 'react-router';
import RouteTabsHeader from '../components/ui/RouteTabsHeader';
import GitHubAccountsTab from '../components/github/GitHubAccountsTab';
+import GitHubAuditTab from '../components/github/GitHubAuditTab';
import GitHubAutomationsTab from '../components/github/GitHubAutomationsTab';
import GitHubInboxTab from '../components/github/GitHubInboxTab';
import GitHubReposTab from '../components/github/GitHubReposTab';
-// Audit joins when its phase ships (#12873).
export const GITHUB_PAGE_TABS = Object.freeze([
{ id: 'inbox', label: 'Inbox', to: '/devtools/github/inbox' },
{ id: 'automations', label: 'Automations', to: '/devtools/github/automations' },
+ { id: 'audit', label: 'Audit', to: '/devtools/github/audit' },
{ id: 'repos', label: 'Repos', to: '/devtools/github/repos' },
{ id: 'accounts', label: 'Accounts', to: '/devtools/github/accounts' },
]);
@@ -25,6 +26,7 @@ export default function GitHub() {
</div>
{activeTab === 'inbox' && <GitHubInboxTab />}
{activeTab === 'automations' && <GitHubAutomationsTab />}
+ {activeTab === 'audit' && <GitHubAuditTab />}
{activeTab === 'repos' && <GitHubReposTab />}
{activeTab === 'accounts' && <GitHubAccountsTab />}
</div>
diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsx
index dc99d656e9..8309e7c780 100644
--- a/client/src/pages/GitHub.test.jsx
+++ b/client/src/pages/GitHub.test.jsx
@@ -28,6 +28,11 @@ const mock = vi.hoisted(() => ({
getGitHubLearnedRules: vi.fn(),
deleteGitHubLearnedRule: vi.fn(),
getProviders: vi.fn(),
+ getGitHubAudit: vi.fn(),
+ runGitHubAudit: vi.fn(),
+ applyGitHubAuditSuggestion: vi.fn(),
+ getGitHubAuditChanges: vi.fn(),
+ undoGitHubAuditChange: vi.fn(),
}));
vi.mock('../services/api', () => mock);
@@ -509,3 +514,47 @@ describe('GitHub automations tab', () => {
await waitFor(() => expect(mock.getGitHubAutomations).toHaveBeenCalledTimes(2));
});
});
+
+describe('GitHub audit tab', () => {
+ const ACCOUNT = { id: 'github-com', label: 'github.com', host: 'github.com', trust: 'public', mode: 'observe', enabled: true };
+ const AUDIT = {
+ accountId: 'github-com', accountLabel: 'github.com', ranAt: '2026-10-22T00:00:00Z', windowDays: 30, watchedListed: true,
+ summary: { total: 20, acted: 0, handled: 12, repos: 2 },
+ suggestions: [
+ { id: 'unwatch:acme/noisy', kind: 'unwatch', repo: 'acme/noisy', stats: { total: 8, acted: 0, handled: 0 }, apply: true, applied: false },
+ { id: 'actions-failed-only', kind: 'actions-failed-only', repo: null, stats: { total: 12, acted: 0, handled: 12 }, link: 'https://github.com/settings/notifications', applied: false },
+ ],
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mock.getGitHubAccounts.mockResolvedValue([ACCOUNT]);
+ mock.getGitHubAudit.mockResolvedValue({ audit: null });
+ mock.getGitHubAuditChanges.mockResolvedValue({ changes: [] });
+ });
+
+ it('runs an audit on tap, applies one change, links the rest, and undoes from the log', async () => {
+ mock.runGitHubAudit.mockResolvedValue({ audit: AUDIT });
+ mock.applyGitHubAuditSuggestion.mockResolvedValue({ id: '5', kind: 'unwatch', repo: 'acme/noisy' });
+ renderTab('audit');
+ expect(await screen.findByText('Nothing changes until you tap Apply on a suggestion.')).toBeTruthy();
+ expect(mock.runGitHubAudit).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole('button', { name: /Run audit/ }));
+ expect(await screen.findByText('Unwatch acme/noisy')).toBeTruthy();
+ expect(screen.getByText(/20 notifications in 2 repos/)).toBeTruthy();
+ expect(screen.getByRole('link', { name: /Open on GitHub/ }).getAttribute('href')).toBe('https://github.com/settings/notifications');
+
+ mock.getGitHubAuditChanges.mockResolvedValue({ changes: [
+ { id: '5', accountId: 'github-com', accountLabel: 'github.com', kind: 'unwatch', repo: 'acme/noisy', threadCount: null, appliedAt: '2026-10-22T00:00:00Z', undone: false },
+ ] });
+ fireEvent.click(screen.getByRole('button', { name: 'Apply' }));
+ expect(await screen.findByText('Applied')).toBeTruthy();
+ expect(mock.applyGitHubAuditSuggestion).toHaveBeenCalledWith('github-com', 'unwatch:acme/noisy');
+
+ mock.undoGitHubAuditChange.mockResolvedValue({ id: '5', undone: true });
+ fireEvent.click(await screen.findByRole('button', { name: /Undo/ }));
+ expect(await screen.findByText('Undone')).toBeTruthy();
+ expect(mock.undoGitHubAuditChange).toHaveBeenCalledWith('5');
+ });
+});
diff --git a/client/src/services/apiGithub.js b/client/src/services/apiGithub.js
index 534a0d438a..cd7d46d04d 100644
--- a/client/src/services/apiGithub.js
+++ b/client/src/services/apiGithub.js
@@ -56,3 +56,13 @@ export const undoGitHubAutomationAction = (id, options = {}) =>
export const getGitHubLearnedRules = (options = {}) => request('/github/automations/rules', options);
export const deleteGitHubLearnedRule = (id, options = {}) =>
request(`/github/automations/rules/${encodeURIComponent(id)}`, { method: 'DELETE', ...options });
+
+// Audit tab: 30-day subscription audit per account and the changes applied from it.
+export const getGitHubAudit = (accountId, options = {}) => request(`/github/audit/${encodeURIComponent(accountId)}`, options);
+export const runGitHubAudit = (accountId, options = {}) =>
+ request(`/github/audit/${encodeURIComponent(accountId)}`, { method: 'POST', ...options });
+export const applyGitHubAuditSuggestion = (accountId, suggestionId, options = {}) =>
+ request(`/github/audit/${encodeURIComponent(accountId)}/apply`, { method: 'POST', body: JSON.stringify({ suggestionId }), ...options });
+export const getGitHubAuditChanges = (options = {}) => request('/github/audit-changes', options);
+export const undoGitHubAuditChange = (id, options = {}) =>
+ request(`/github/audit-changes/${encodeURIComponent(id)}/undo`, { method: 'POST', ...options });
diff --git a/server/lib/README.md b/server/lib/README.md
index 8a0c3aec8e..2134b37b56 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -472,6 +472,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. Pure except that `parseGitRemote` canonicalizes an ssh `Host` alias through `sshHostAlias.js`. |
| `sshHostAlias.js` | `resolveSshHostAlias`, `parseSshHostAliases` — resolves a personal SSH `Host` alias (`git@github-acme:…`, backed by `HostName github.com` in `~/.ssh/config`) to the host a remote actually connects to. Every remote-URL host parser (`gitForge.parseGitRemote`, `gitRemote.parseGitRemoteUrl`, `workTracker.hostFromOriginUrl`) canonicalizes through it, so multi-account checkouts classify as GitHub instead of an unreachable unknown host. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |
+| `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`, `toNotificationRecord` — pure parsing for the GitHub notifications inbox: `gh api --include` output and thread records, with links rebuilt only onto the account's own GitHub host. |
| `githubNotificationTriage.js` | `TRIAGE_DECISIONS`, `TRUST_LEVELS`, `MASS_MENTION_THRESHOLD`, `computeThreadTrust`, `spamSignals`, `parseCiBranch`, `decideThread`, `ASSIST_VERDICTS`, `decisionFromVerdict`, `learnedDecisionForAction`, `applyLearnedRule`, `assistAction`, `selectNotificationProvider` — the GitHub inbox's fixed trust, spam and routing rules plus Assist's verdict enum, learned rules, allowed actions and Private-account provider allow-list; trust comes only from accounts, repo ownership and forge permissions, never from content. |
| `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. |
diff --git a/server/lib/db/schema/githubNotifications.js b/server/lib/db/schema/githubNotifications.js
index 1ec71dbe6b..888f8c258e 100644
--- a/server/lib/db/schema/githubNotifications.js
+++ b/server/lib/db/schema/githubNotifications.js
@@ -69,4 +69,15 @@ export const githubNotificationsDdl = [
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE (account_id, repo_full_name, reason, actor)
)`,
+ // Subscription audit (#12873): each change the operator applied from an
+ // audit card, with what Undo needs to reverse it.
+ `CREATE TABLE IF NOT EXISTS github_notification_audit_changes (
+ id BIGSERIAL PRIMARY KEY,
+ account_id TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('unwatch','mute-handled')),
+ repo_full_name TEXT NOT NULL,
+ detail JSONB NOT NULL DEFAULT '{}'::jsonb,
+ applied_at TIMESTAMPTZ DEFAULT NOW(),
+ undone_at TIMESTAMPTZ
+ )`,
];
diff --git a/server/lib/githubNotificationAudit.js b/server/lib/githubNotificationAudit.js
new file mode 100644
index 0000000000..bfe920a4fc
--- /dev/null
+++ b/server/lib/githubNotificationAudit.js
@@ -0,0 +1,63 @@
+/**
+ * Suggestions for the GitHub notifications subscription audit (#12873). Pure:
+ * the service aggregates the last 30 days of stored threads per repo × reason
+ * and lists watched repos; this turns them into one-tap changes and links.
+ * Nothing here is applied automatically.
+ */
+
+export const AUDIT_WINDOW_DAYS = 30;
+const MIN_REPO_VOLUME = 5;
+const NOISY_SUBSCRIBED = 10;
+const CI_NOISE_FLOOR = 10;
+// Reasons that come from watching a repo rather than from being involved.
+const WATCH_REASONS = new Set(['subscribed', 'ci_activity', 'state_change']);
+
+const sum = (rows, field) => rows.reduce((total, row) => total + (row[field] || 0), 0);
+
+/**
+ * `groups`: `{ repo, reason, total, acted, handled, handledOpen: [threadId] }`
+ * rows; `watchedRepos`: full names the account watches (null when GitHub
+ * could not list them). Returns `{ summary, suggestions }`; a suggestion with
+ * `apply` is a change, one with `link` is advice for a setting the API cannot
+ * change.
+ */
+export function buildAuditSuggestions({ groups = [], watchedRepos = null, host = 'github.com' }) {
+ const watched = new Set((watchedRepos || []).map((repo) => repo.toLowerCase()));
+ const byRepo = new Map();
+ for (const group of groups) {
+ if (!byRepo.has(group.repo)) byRepo.set(group.repo, []);
+ byRepo.get(group.repo).push(group);
+ }
+ const suggestions = [];
+ for (const [repo, rows] of byRepo) {
+ const total = sum(rows, 'total');
+ const acted = sum(rows, 'acted');
+ const handled = sum(rows, 'handled');
+ const watchDriven = sum(rows.filter((row) => WATCH_REASONS.has(row.reason)), 'total');
+ const stats = { total, acted, handled };
+ const isWatched = watched.has(repo.toLowerCase());
+ if (isWatched && total >= MIN_REPO_VOLUME && acted === 0 && watchDriven / total >= 0.8) {
+ suggestions.push({ id: `unwatch:${repo}`, kind: 'unwatch', repo, stats, apply: true });
+ } else if (isWatched && sum(rows.filter((row) => row.reason === 'subscribed'), 'total') >= NOISY_SUBSCRIBED && acted / total < 0.2) {
+ suggestions.push({ id: `custom-watch:${repo}`, kind: 'custom-watch', repo, stats, link: `https://${host}/${repo}` });
+ }
+ const handledOpen = rows.flatMap((row) => row.handledOpen || []);
+ if (handledOpen.length) {
+ suggestions.push({ id: `mute-handled:${repo}`, kind: 'mute-handled', repo, stats, threadIds: handledOpen.slice(0, 50), apply: true });
+ }
+ }
+ const ci = groups.filter((group) => group.reason === 'ci_activity');
+ const ciTotal = sum(ci, 'total');
+ if (ciTotal >= CI_NOISE_FLOOR && sum(ci, 'acted') / ciTotal <= 0.1) {
+ suggestions.push({
+ id: 'actions-failed-only', kind: 'actions-failed-only', repo: null,
+ stats: { total: ciTotal, acted: sum(ci, 'acted'), handled: sum(ci, 'handled') },
+ link: `https://${host}/settings/notifications`,
+ });
+ }
+ suggestions.sort((a, b) => b.stats.total - a.stats.total);
+ return {
+ summary: { total: sum(groups, 'total'), acted: sum(groups, 'acted'), handled: sum(groups, 'handled'), repos: byRepo.size },
+ suggestions,
+ };
+}
diff --git a/server/lib/githubNotificationAudit.test.js b/server/lib/githubNotificationAudit.test.js
new file mode 100644
index 0000000000..2059facbc7
--- /dev/null
+++ b/server/lib/githubNotificationAudit.test.js
@@ -0,0 +1,34 @@
+import { describe, it, expect } from 'vitest';
+import { buildAuditSuggestions } from './githubNotificationAudit.js';
+
+const group = (repo, reason, total, { acted = 0, handled = 0, handledOpen = [] } = {}) => ({ repo, reason, total, acted, handled, handledOpen });
+
+describe('buildAuditSuggestions', () => {
+ it('suggests unwatching a watched repo you never act on, and links what the API cannot change', () => {
+ const { summary, suggestions } = buildAuditSuggestions({
+ host: 'ghe.example.com',
+ watchedRepos: ['acme/noisy', 'acme/busy', 'acme/core'],
+ groups: [
+ group('acme/noisy', 'subscribed', 8),
+ group('acme/busy', 'subscribed', 12, { acted: 1 }),
+ group('acme/core', 'mention', 6, { acted: 4 }),
+ group('acme/core', 'ci_activity', 14, { handled: 12, handledOpen: ['7', '8'] }),
+ ],
+ });
+ expect(summary).toEqual({ total: 40, acted: 5, handled: 12, repos: 3 });
+ expect(suggestions.map((entry) => [entry.id, entry.apply ? 'apply' : entry.link])).toEqual([
+ ['mute-handled:acme/core', 'apply'],
+ ['actions-failed-only', 'https://ghe.example.com/settings/notifications'],
+ ['custom-watch:acme/busy', 'https://ghe.example.com/acme/busy'],
+ ['unwatch:acme/noisy', 'apply'],
+ ]);
+ expect(suggestions[0].threadIds).toEqual(['7', '8']);
+ });
+
+ it('offers no unwatch when the repo is not watched, the list is unknown, or you act on it', () => {
+ const groups = [group('acme/noisy', 'subscribed', 8)];
+ expect(buildAuditSuggestions({ groups, watchedRepos: null }).suggestions).toEqual([]);
+ expect(buildAuditSuggestions({ groups, watchedRepos: ['acme/other'] }).suggestions).toEqual([]);
+ expect(buildAuditSuggestions({ groups: [group('acme/noisy', 'subscribed', 8, { acted: 1 })], watchedRepos: ['acme/noisy'] }).suggestions).toEqual([]);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index bb60d148d5..463b90b814 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -431,6 +431,7 @@ export * from './gitForge.js';
export * from './gitOutputParsers.js';
export * from './gitRemote.js';
export * from './gitStaleLock.js';
+export * from './githubNotificationAudit.js';
export * from './githubNotificationParse.js';
export * from './githubNotificationTriage.js';
export * from './repoUrl.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 95c42eea69..2af2be09aa 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -222,6 +222,7 @@ const RAW_NAV_COMMANDS = [
// ⌘K / voice only — no sidebar row: tabs of the GitHub page.
{ id: 'nav.devtools.github-accounts', path: '/devtools/github/accounts', label: 'GitHub Accounts', section: 'Dev Tools', aliases: ['github-accounts', 'github-enterprise'], keywords: ['github', 'enterprise', 'ghes', 'gh auth', 'login', 'trust', 'notifications'] },
{ id: 'nav.devtools.github-inbox', path: '/devtools/github/inbox', label: 'GitHub Inbox', section: 'Dev Tools', aliases: ['github-inbox', 'github-notifications'], keywords: ['github', 'notifications', 'inbox', 'mentions', 'review requests', 'mute', 'unsubscribe'] },
+ { id: 'nav.devtools.github-audit', path: '/devtools/github/audit', label: 'GitHub Notification Audit', section: 'Dev Tools', aliases: ['github-audit', 'notification-audit'], keywords: ['github', 'notifications', 'unwatch', 'unsubscribe', 'subscriptions', 'noise'] },
{ id: 'nav.devtools.github-automations', path: '/devtools/github/automations', label: 'GitHub Automations', section: 'Dev Tools', aliases: ['github-automations', 'github-triage'], keywords: ['github', 'notifications', 'schedule', 'triage', 'observe', 'run now'] },
{ id: 'nav.devtools.github-repos', path: '/devtools/github/repos', label: 'GitHub Repos', section: 'Dev Tools', aliases: ['github-repos', 'github-secrets'], keywords: ['github', 'repositories', 'secrets', 'archive', 'npm'] },
{ id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },
diff --git a/server/lib/validation.js b/server/lib/validation.js
index e44d5b8983..c826bd38eb 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -984,6 +984,10 @@ export const GITHUB_NOTIFICATION_THREAD_ID_RE = /^\d{1,20}$/;
// Automations tab (#12871): the one cadence it offers, or back to Run now only.
export const GITHUB_NOTIFICATION_CADENCES = Object.freeze({ 'weekdays-15m': '*/15 * * * 1-5', off: null });
+export const githubAuditApplySchema = z.object({
+ suggestionId: z.string().trim().min(1).max(300),
+}).strict();
+
export const githubNotificationCadenceSchema = z.object({
cadence: z.enum(Object.keys(GITHUB_NOTIFICATION_CADENCES)),
}).strict();
diff --git a/server/routes/github.js b/server/routes/github.js
index 2f48fcba0d..f4903ac266 100644
--- a/server/routes/github.js
+++ b/server/routes/github.js
@@ -2,10 +2,11 @@ import express from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, githubRepoUpdateSchema, githubSecretSchema, githubAccountCreateSchema, githubAccountUpdateSchema,
githubNotificationsQuerySchema, githubNotificationsSyncSchema, githubNotificationActionSchema, GITHUB_NOTIFICATION_THREAD_ID_RE,
- githubNotificationCadenceSchema } from '../lib/validation.js';
+ githubNotificationCadenceSchema, githubAuditApplySchema } from '../lib/validation.js';
import * as githubService from '../services/github.js';
import * as githubAccounts from '../services/githubAccounts.js';
import * as githubNotifications from '../services/githubNotifications.js';
+import * as githubAudit from '../services/githubNotificationAudit.js';
const router = express.Router();
@@ -216,4 +217,40 @@ router.delete('/automations/rules/:id', asyncHandler(async (req, res) => {
res.json(await githubNotifications.deleteLearnedRule(numericIdParam(req)));
}));
+/**
+ * GET /api/github/audit-changes — changes applied from audit cards, newest first
+ */
+router.get('/audit-changes', asyncHandler(async (req, res) => {
+ res.json({ changes: await githubAudit.listAuditChanges() });
+}));
+
+/**
+ * POST /api/github/audit-changes/:id/undo — re-watch the repo or re-subscribe the muted threads
+ */
+router.post('/audit-changes/:id/undo', asyncHandler(async (req, res) => {
+ res.json(await githubAudit.undoAuditChange(numericIdParam(req)));
+}));
+
+/**
+ * GET /api/github/audit/:accountId — the account's latest audit, or null
+ */
+router.get('/audit/:accountId', asyncHandler(async (req, res) => {
+ res.json({ audit: await githubAudit.getLastAudit(req.params.accountId) });
+}));
+
+/**
+ * POST /api/github/audit/:accountId — audit the last 30 days of notifications against what was done about them
+ */
+router.post('/audit/:accountId', asyncHandler(async (req, res) => {
+ res.json({ audit: await githubAudit.runAccountAudit(req.params.accountId) });
+}));
+
+/**
+ * POST /api/github/audit/:accountId/apply — apply one audit suggestion (unwatch, mute handled threads)
+ */
+router.post('/audit/:accountId/apply', asyncHandler(async (req, res) => {
+ const { suggestionId } = validateRequest(githubAuditApplySchema, req.body ?? {});
+ res.json(await githubAudit.applyAuditSuggestion(req.params.accountId, suggestionId));
+}));
+
export default router;
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 162ff2c2ae..2b214b6935 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -1972,6 +1972,16 @@ CREATE TABLE IF NOT EXISTS github_notification_rules (
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE (account_id, repo_full_name, reason, actor)
);
+-- Subscription audit (#12873): changes applied from audit cards, for Undo.
+CREATE TABLE IF NOT EXISTS github_notification_audit_changes (
+ id BIGSERIAL PRIMARY KEY,
+ account_id TEXT NOT NULL,
+ kind TEXT NOT NULL CHECK (kind IN ('unwatch','mute-handled')),
+ repo_full_name TEXT NOT NULL,
+ detail JSONB NOT NULL DEFAULT '{}'::jsonb,
+ applied_at TIMESTAMPTZ DEFAULT NOW(),
+ undone_at TIMESTAMPTZ
+);
-- Beeper conversation mirror (#27). Machine-local mirror of the Beeper Desktop
-- API — accounts, conversations, messages, participants, attachment metadata,
diff --git a/server/services/githubNotificationAudit.js b/server/services/githubNotificationAudit.js
new file mode 100644
index 0000000000..8cad2f0a77
--- /dev/null
+++ b/server/services/githubNotificationAudit.js
@@ -0,0 +1,174 @@
+/**
+ * Subscription audit for the GitHub notifications inbox (#12873): compare the
+ * last 30 days of stored threads with what was done about them, and offer
+ * one-tap changes (unwatch a repo, mute its handled threads) plus links for
+ * settings the API cannot change. Nothing is applied without a tap, and every
+ * applied change is logged with Undo.
+ */
+import { query } from '../lib/db.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { AUDIT_WINDOW_DAYS, buildAuditSuggestions } from '../lib/githubNotificationAudit.js';
+import { toPgJson } from '../lib/pgJson.js';
+import { execGh } from './github.js';
+import { getAccount, listAccounts, resolveGitHubAccountEnv } from './githubAccounts.js';
+import { applyNotificationAction } from './githubNotifications.js';
+
+const GH_TIMEOUT_MS = 30_000;
+const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
+
+// The last audit per account. Rebuilt by running the audit again; it holds
+// counts and repo names only.
+const lastAudits = new Map();
+
+async function accountEnv(account) {
+ const { env, status } = await resolveGitHubAccountEnv(account);
+ if (!env) {
+ throw new ServerError(`gh cannot act as ${account.label} (${status}). Check the Accounts tab.`, { status: 409, code: 'GITHUB_ACCOUNT_UNAVAILABLE' });
+ }
+ return env;
+}
+
+// Audit mutes and their undo are logged as operator events tagged `via`; they
+// are not the operator acting on a thread, so they never count as acted.
+const OUTCOMES_SQL = `
+ WITH recent AS (
+ SELECT n.thread_id, n.repo_full_name, n.reason, n.decision, n.state,
+ EXISTS (SELECT 1 FROM github_notification_events e
+ WHERE e.account_id = n.account_id AND e.thread_id = n.thread_id AND e.actor = 'operator'
+ AND COALESCE(e.detail->>'via', '') NOT IN ('audit', 'audit-undo')) AS operator_acted,
+ EXISTS (SELECT 1 FROM github_notification_events e
+ WHERE e.account_id = n.account_id AND e.thread_id = n.thread_id AND e.actor = 'automation' AND e.kind <> 'triaged') AS automation_acted
+ FROM github_notifications n
+ WHERE n.account_id = $1 AND n.gh_updated_at > NOW() - make_interval(days => $2)
+ )
+ SELECT repo_full_name, reason, COUNT(*)::int AS total,
+ COUNT(*) FILTER (WHERE operator_acted)::int AS acted,
+ COUNT(*) FILTER (WHERE decision = 'handled-by-pr-workflow' OR automation_acted)::int AS handled,
+ COALESCE(array_agg(thread_id ORDER BY thread_id) FILTER (WHERE decision = 'handled-by-pr-workflow' AND state = 'open'), '{}') AS handled_open
+ FROM recent GROUP BY repo_full_name, reason`;
+
+/** Full names of the repos the account watches, or null when GitHub would not list them. */
+async function listWatchedRepos(account, env) {
+ const out = await execGh(
+ ['api', '--hostname', account.host, '--method', 'GET', 'user/subscriptions?per_page=100', '--paginate', '--jq', '.[].full_name'],
+ GH_TIMEOUT_MS,
+ { env },
+ ).catch((error) => {
+ console.log(`⏭️ Could not list watched repos for ${account.host}: ${error.message}`);
+ return null;
+ });
+ return out === null ? null : out.split('\n').map((line) => line.trim()).filter((line) => REPO_RE.test(line));
+}
+
+// Only an unwatch stays applied across audits; a later audit's mute-handled
+// card lists threads that are still open, so it is always new work.
+async function openChanges(accountId) {
+ const { rows } = await query(
+ "SELECT kind, repo_full_name FROM github_notification_audit_changes WHERE account_id = $1 AND kind = 'unwatch' AND undone_at IS NULL",
+ [accountId],
+ );
+ return new Set(rows.map((row) => `${row.kind}:${row.repo_full_name}`));
+}
+
+const withApplied = (audit, applied) => ({
+ ...audit,
+ suggestions: audit.suggestions.map((suggestion) => ({ ...suggestion, applied: Boolean(suggestion.applied) || applied.has(suggestion.id) })),
+});
+
+export async function runAccountAudit(accountId) {
+ const account = await getAccount(accountId);
+ const env = await accountEnv(account);
+ const watchedRepos = await listWatchedRepos(account, env);
+ const { rows } = await query(OUTCOMES_SQL, [account.id, AUDIT_WINDOW_DAYS]);
+ const groups = rows.map((row) => ({
+ repo: row.repo_full_name, reason: row.reason, total: row.total, acted: row.acted, handled: row.handled, handledOpen: row.handled_open,
+ }));
+ const audit = {
+ accountId: account.id,
+ accountLabel: account.label,
+ ranAt: new Date().toISOString(),
+ windowDays: AUDIT_WINDOW_DAYS,
+ watchedListed: watchedRepos !== null,
+ ...buildAuditSuggestions({ groups, watchedRepos, host: account.host }),
+ };
+ lastAudits.set(account.id, audit);
+ console.log(`🔎 Audited GitHub notifications for ${account.host}: ${audit.summary.total} threads, ${audit.suggestions.length} suggestions`);
+ return withApplied(audit, await openChanges(account.id));
+}
+
+export async function getLastAudit(accountId) {
+ const account = await getAccount(accountId);
+ const audit = lastAudits.get(account.id);
+ return audit ? withApplied(audit, await openChanges(account.id)) : null;
+}
+
+/** Apply one audit card. Only a change the latest audit offered can be applied. */
+export async function applyAuditSuggestion(accountId, suggestionId) {
+ const account = await getAccount(accountId);
+ const suggestion = lastAudits.get(account.id)?.suggestions.find((entry) => entry.id === suggestionId && entry.apply);
+ if (!suggestion) throw new ServerError('Run the audit again; that suggestion is not in the latest one', { status: 409, code: 'GITHUB_AUDIT_STALE' });
+ if (suggestion.applied || (await openChanges(account.id)).has(suggestion.id)) throw new ServerError('Already applied', { status: 409, code: 'GITHUB_AUDIT_APPLIED' });
+ let detail = {};
+ if (suggestion.kind === 'unwatch') {
+ const env = await accountEnv(account);
+ await execGh(['api', '--hostname', account.host, '--method', 'DELETE', `repos/${suggestion.repo}/subscription`], GH_TIMEOUT_MS, { env });
+ } else {
+ const muted = [];
+ for (const threadId of suggestion.threadIds) {
+ // A thread that is already gone from the inbox is skipped, not fatal.
+ const ok = await applyNotificationAction(account.id, threadId, 'mute', { detail: { via: 'audit' }, learn: false })
+ .then(() => true)
+ .catch((error) => {
+ console.log(`⏭️ Audit mute skipped thread ${threadId}: ${error.message}`);
+ return false;
+ });
+ if (ok) muted.push(threadId);
+ }
+ detail = { threadIds: muted };
+ }
+ suggestion.applied = true;
+ const { rows } = await query(
+ 'INSERT INTO github_notification_audit_changes (account_id, kind, repo_full_name, detail) VALUES ($1, $2, $3, $4::jsonb) RETURNING id',
+ [account.id, suggestion.kind, suggestion.repo, toPgJson(detail)],
+ );
+ return { id: String(rows[0].id), kind: suggestion.kind, repo: suggestion.repo, ...detail };
+}
+
+export async function listAuditChanges() {
+ const accounts = await listAccounts();
+ const labels = new Map(accounts.map((account) => [account.id, account.label]));
+ const { rows } = await query(
+ 'SELECT * FROM github_notification_audit_changes WHERE account_id = ANY($1::text[]) ORDER BY applied_at DESC, id DESC LIMIT 100',
+ [accounts.map((account) => account.id)],
+ );
+ return rows.map((row) => ({
+ id: String(row.id),
+ accountId: row.account_id,
+ accountLabel: labels.get(row.account_id) || row.account_id,
+ kind: row.kind,
+ repo: row.repo_full_name,
+ threadCount: Array.isArray(row.detail?.threadIds) ? row.detail.threadIds.length : null,
+ appliedAt: row.applied_at instanceof Date ? row.applied_at.toISOString() : row.applied_at,
+ undone: Boolean(row.undone_at),
+ }));
+}
+
+/** Re-watch the repo, or re-subscribe the muted threads. */
+export async function undoAuditChange(id) {
+ const change = (await query('SELECT * FROM github_notification_audit_changes WHERE id = $1', [id])).rows[0];
+ if (!change) throw new ServerError('Audit change not found', { status: 404, code: 'GITHUB_AUDIT_CHANGE_NOT_FOUND' });
+ if (change.undone_at) throw new ServerError('Already undone', { status: 409, code: 'GITHUB_AUDIT_CHANGE_UNDONE' });
+ const account = await getAccount(change.account_id);
+ if (change.kind === 'unwatch') {
+ const env = await accountEnv(account);
+ await execGh(['api', '--hostname', account.host, '--method', 'PUT', `repos/${change.repo_full_name}/subscription`, '-F', 'subscribed=true'], GH_TIMEOUT_MS, { env });
+ } else {
+ for (const threadId of change.detail?.threadIds || []) {
+ await applyNotificationAction(account.id, threadId, 'resubscribe', { detail: { via: 'audit-undo' }, learn: false }).catch((error) => {
+ console.log(`⏭️ Audit undo skipped thread ${threadId}: ${error.message}`);
+ });
+ }
+ }
+ await query('UPDATE github_notification_audit_changes SET undone_at = NOW() WHERE id = $1', [id]);
+ return { id: String(id), undone: true };
+}
diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.js
index b17d987740..a15f8f5391 100644
--- a/server/services/githubNotifications.db.test.js
+++ b/server/services/githubNotifications.db.test.js
@@ -30,6 +30,7 @@ const {
listAutomationActivity, undoAutomationAction, listLearnedRules,
} = await import('./githubNotifications.js');
const { buildTaskInput } = await import('./githubNotificationsHooks.js');
+const { runAccountAudit, applyAuditSuggestion, listAuditChanges, undoAuditChange } = await import('./githubNotificationAudit.js');
let dbReady = false;
let skipReason = '';
@@ -76,7 +77,12 @@ function mockGh(respond, forge = {}) {
actions.push([args[args.indexOf('--method') + 1], path]);
return '';
}
+ const method = args[args.indexOf('--method') + 1];
const endpoint = args[args.indexOf('--method') + 2];
+ if (method !== 'GET') {
+ actions.push([method, endpoint]);
+ return '';
+ }
if (endpoint in forge) return typeof forge[endpoint] === 'string' ? forge[endpoint] : JSON.stringify(forge[endpoint]);
throw Object.assign(new Error('HTTP 404'), { ghExitCode: 1, ghStderr: 'HTTP 404' });
});
@@ -91,6 +97,7 @@ afterAll(async () => {
await query('DELETE FROM github_notification_sync WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});
await query('DELETE FROM github_notification_events WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});
await query('DELETE FROM github_notification_rules WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});
+ await query('DELETE FROM github_notification_audit_changes WHERE account_id = ANY($1::text[])', [accountIds]).catch(() => {});
await close();
}
rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
@@ -348,6 +355,57 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {
expect(await getNotification(account.id, '953')).toMatchObject({ decision: 'suggest-done', rule: 'learned', state: 'open' });
});
+ it('audits 30 days of notifications, applies an unwatch and a mute only on tap, and undoes both', async () => {
+ const recent = new Date(Date.now() - 86_400_000).toISOString();
+ const watched = (id) => thread(id, { owner: 'acme', repo: 'noisy', reason: 'subscribed', updatedAt: recent });
+ const ci = (id) => thread(id, { owner: 'acme', repo: 'core', reason: 'ci_activity', type: 'CheckSuite', url: null, updatedAt: recent, title: 'CI workflow run failed for feature branch' });
+ let actions = mockGh(() => listing(['1001', '1002', '1003', '1004', '1005'].map(watched).concat([ci('1011'), ci('1012')])), {
+ 'user/subscriptions?per_page=100': 'acme/noisy\nacme/core\n',
+ });
+ await syncAccountNotifications(account.id);
+ // Stand in for a managed app's PR workflow owning these CI threads.
+ await query("UPDATE github_notifications SET decision = 'handled-by-pr-workflow' WHERE account_id = $1 AND thread_id IN ('1011','1012')", [account.id]);
+ actions.length = 0;
+
+ const audit = await runAccountAudit(account.id);
+ expect(audit.summary).toMatchObject({ total: 7, acted: 0, repos: 2 });
+ expect(audit.suggestions.map((entry) => entry.id).sort()).toEqual(['mute-handled:acme/core', 'unwatch:acme/noisy']);
+ expect(actions).toEqual([]);
+
+ await applyAuditSuggestion(account.id, 'unwatch:acme/noisy');
+ const muted = await applyAuditSuggestion(account.id, 'mute-handled:acme/core');
+ expect(muted.threadIds).toEqual(['1011', '1012']);
+ expect(actions).toEqual([
+ ['DELETE', 'repos/acme/noisy/subscription'],
+ ['PUT', 'notifications/threads/1011/subscription'],
+ ['PUT', 'notifications/threads/1012/subscription'],
+ ]);
+ await expect(applyAuditSuggestion(account.id, 'unwatch:acme/noisy')).rejects.toMatchObject({ status: 409 });
+ await expect(applyAuditSuggestion(account.id, 'mute-handled:acme/core')).rejects.toMatchObject({ status: 409 });
+ // Audit mutes are not the operator acting, and a later handled thread in
+ // the same repo gets a fresh, unapplied mute card.
+ actions = mockGh(() => listing([ci('1013')]), { 'user/subscriptions?per_page=100': 'acme/core\n' });
+ await syncAccountNotifications(account.id);
+ await query("UPDATE github_notifications SET decision = 'handled-by-pr-workflow' WHERE account_id = $1 AND thread_id = '1013'", [account.id]);
+ const rerun = await runAccountAudit(account.id);
+ expect(rerun.summary.acted).toBe(0);
+ expect(rerun.suggestions.find((entry) => entry.id === 'mute-handled:acme/core')).toMatchObject({ threadIds: ['1013'], applied: false });
+ // A bulk audit mute teaches no learned rule.
+ expect((await listLearnedRules()).filter((rule) => rule.accountId === account.id)).toEqual([]);
+
+ const changes = (await listAuditChanges()).filter((change) => change.accountId === account.id);
+ expect(changes.map((change) => [change.kind, change.repo, change.undone])).toEqual([['mute-handled', 'acme/core', false], ['unwatch', 'acme/noisy', false]]);
+ actions.length = 0;
+ for (const change of changes) await undoAuditChange(change.id);
+ expect(actions).toEqual([
+ ['PUT', 'notifications/threads/1011/subscription'],
+ ['PUT', 'notifications/threads/1012/subscription'],
+ ['PUT', 'repos/acme/noisy/subscription'],
+ ]);
+ expect((await getNotification(account.id, '1011')).state).toBe('open');
+ expect((await listAuditChanges()).filter((change) => change.accountId === account.id).every((change) => change.undone)).toBe(true);
+ });
+
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.js
index 7b1f379a7b..60f8fab094 100644
--- a/server/services/githubNotifications.js
+++ b/server/services/githubNotifications.js
@@ -274,9 +274,10 @@ async function learnFromOperator(client, row, action) {
/**
* Apply one thread action on GitHub, then mirror it locally. The operator's
- * actions teach learned rules; an automation's carry the decision behind it.
+ * actions teach learned rules (unless `learn: false`, for a bulk audit change);
+ * an automation's carry the decision behind it.
*/
-export async function applyNotificationAction(accountId, threadId, action, { actor = 'operator', detail = {} } = {}) {
+export async function applyNotificationAction(accountId, threadId, action, { actor = 'operator', detail = {}, learn = actor === 'operator' } = {}) {
const spec = ACTION_SPECS[action];
const account = await getAccount(accountId);
const existing = (await query('SELECT * FROM github_notifications WHERE account_id = $1 AND thread_id = $2', [account.id, threadId])).rows[0];
@@ -292,7 +293,7 @@ export async function applyNotificationAction(accountId, threadId, action, { act
);
}
const row = await withTransaction(async (client) => {
- if (actor === 'operator') await learnFromOperator(client, existing, action);
+ if (learn) await learnFromOperator(client, existing, action);
const result = await client.query(
`UPDATE github_notifications SET
unread = CASE WHEN $3::text IN ('read','done') THEN FALSE ELSE unread END,