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: scope GitHub automation rules to accounts and organizations
[._.]/ Adam Eivyf1b5a49b5ac9
diff --git a/client/src/components/github/GitHubAgentRules.jsx b/client/src/components/github/GitHubAgentRules.jsxindex 8e2772d7aa..b6dfad99c6 100644--- a/client/src/components/github/GitHubAgentRules.jsx+++ b/client/src/components/github/GitHubAgentRules.jsx@@ -8,11 +8,13 @@ import { describeAgentPin } from './GitHubAgentPinForm';const ALL_REPOS = '*';const OTHER_REPO = '__other__';-const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;+const OTHER_OWNER = '__owner__';+const OWNER_RE = /^[A-Za-z0-9_.-]{1,100}$/;+const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/(?:\*|[A-Za-z0-9_.-]{1,100})$/;const newRuleId = () => `rule-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;-const repoLabel = (repo) => (repo === ALL_REPOS ? 'All repos' : repo);+const repoLabel = (repo) => (repo === ALL_REPOS ? 'All repos' : repo.endsWith('/*') ? `${repo.slice(0, -2)} (all repos)` : repo);const actionLabel = (action) => RULE_ACTIONS.find((option) => option.value === action)?.label || action;@@ -22,16 +24,21 @@ function pinLabel(rule, providers) {}// 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+// server's per-kind counts: repo > owner > all. 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);+ const scope = repo.toLowerCase();+ const other = rules.filter((rule) => rule.kind === kind && rule.id !== editingId).map((rule) => rule.repo.toLowerCase());+ return ofKind.filter((entry) => {+ const name = entry.repo.toLowerCase();+ const owner = `${name.split('/')[0]}/*`;+ if (scope === ALL_REPOS) return !other.includes(name) && !other.includes(owner);+ if (scope.endsWith('/*')) return owner === scope && !other.includes(name);+ return name === scope;+ }).reduce((sum, entry) => sum + entry[metric], 0);}// Whether a run of this account now would carry out the rule's action.@@ -41,17 +48,19 @@ function RuleForm({ rule, repos, rules, account, takenKeys, onCancel, onSubmit,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 owners = [...new Set(repos.map((name) => name.split('/')[0].toLowerCase()))].sort();+ const ownerRule = rule?.repo?.endsWith('/*');+ const knownRepo = !rule || rule.repo === ALL_REPOS || repos.includes(rule.repo) || (ownerRule && owners.includes(rule.repo.slice(0, -2).toLowerCase()));+ const [repoChoice, setRepoChoice] = useState(rule ? (knownRepo ? (ownerRule ? rule.repo.toLowerCase() : rule.repo) : ownerRule ? OTHER_OWNER : OTHER_REPO) : ALL_REPOS);+ const [otherRepo, setOtherRepo] = useState(knownRepo ? '' : ownerRule ? rule.repo.slice(0, -2) : rule?.repo || '');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 repo = repoChoice === OTHER_REPO ? otherRepo.trim() : repoChoice === OTHER_OWNER ? `${otherRepo.trim()}/*` : repoChoice;+ const repoValid = repoChoice === OTHER_OWNER ? OWNER_RE.test(otherRepo.trim()) : 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);@@ -81,6 +90,10 @@ function RuleForm({ rule, repos, rules, account, takenKeys, onCancel, onSubmit,<span className="block">In</span><select id={`${formId}-repo`} value={repoChoice} onChange={(event) => setRepoChoice(event.target.value)} className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-white"><option value={ALL_REPOS}>All repos</option>+ <optgroup label="Accounts and organizations">+ {owners.map((owner) => <option key={owner} value={`${owner}/*`}>{owner} (all repos)</option>)}+ <option value={OTHER_OWNER}>Another account or organization…</option>+ </optgroup>{repos.map((name) => <option key={name} value={name}>{name}</option>)}<option value={OTHER_REPO}>Another repo…</option></select>@@ -92,10 +105,10 @@ function RuleForm({ rule, repos, rules, account, takenKeys, onCancel, onSubmit,</select></label></div>- {repoChoice === OTHER_REPO && (+ {(repoChoice === OTHER_REPO || repoChoice === OTHER_OWNER) && (<label htmlFor={`${formId}-other`} className="block space-y-1 text-xs text-gray-400">- <span className="block">Repo (owner/name)</span>- <input id={`${formId}-other`} value={otherRepo} onChange={(event) => setOtherRepo(event.target.value)} placeholder="owner/repo" autoComplete="off" className="w-full rounded border border-port-border bg-port-card px-2 py-1.5 font-mono text-sm text-white" />+ <span className="block">{repoChoice === OTHER_OWNER ? 'Account or organization name' : 'Repo (owner/name)'}</span>+ <input id={`${formId}-other`} value={otherRepo} onChange={(event) => setOtherRepo(event.target.value)} placeholder={repoChoice === OTHER_OWNER ? 'owner' : '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>)}{action === 'agent' && (@@ -129,9 +142,9 @@ function RuleForm({ rule, repos, rules, account, takenKeys, onCancel, onSubmit,/*** 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,+ * an account/organization or all repos, 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+ * repo's own rule wins over its owner rule, then All repos. `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, prefill = null, onPrefillDone, onApplyNow }) {@@ -170,6 +183,7 @@ export default function GitHubAgentRules({ account, onSave, saving, prefill = nu</button>)}</div>+ <p className="text-xs text-gray-500">Scope rules to an account or organization to cover its repos, including future ones. Specific repo rules override account or organization rules, which override All repos.</p>{account.mode !== 'autopilot' && rules.length > 0 && (<p className="text-xs text-port-warning">{account.mode === 'assist'diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsxindex 03238c6e6b..981549060c 100644--- a/client/src/pages/GitHub.test.jsx+++ b/client/src/pages/GitHub.test.jsx@@ -794,6 +794,46 @@ describe('GitHub automations tab', () => {expect(screen.queryByRole('form', { name: 'New automation rule' })).toBeNull();});+ it('saves and edits owner rules while counting only threads without a repo override', async () => {+ mock.getGitHubAutomations.mockResolvedValue({+ ...OVERVIEW,+ accounts: [{ ...OVERVIEW.accounts[0], mode: 'autopilot',+ agentRules: [{ id: 'quiet', kind: 'review-request', repo: 'octocat/quiet', action: 'leave' }],+ repos: ['octocat/hello', 'octocat/quiet', 'watched/app'],+ openByKind: [+ { kind: 'review-request', repo: 'octocat/hello', total: 2, actionable: 2 },+ { kind: 'review-request', repo: 'octocat/future', total: 3, actionable: 3 },+ { kind: 'review-request', repo: 'octocat/quiet', total: 4, actionable: 4 },+ { kind: 'review-request', repo: 'watched/app', total: 8, actionable: 8 },+ ],+ }],+ });+ mock.updateGitHubAccount.mockImplementation(async (id, data) => ({ id, ...data }));+ renderTab('automations');+ const addOwnerRule = await screen.findByRole('button', { name: /Add rule/ });+ await act(async () => fireEvent.click(addOwnerRule));+ fireEvent.change(screen.getByLabelText('In'), { target: { value: 'octocat/*' } });+ expect(screen.getByText('Matches 5 open threads now.')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Save rule' }));+ await waitFor(() => expect(mock.updateGitHubAccount).toHaveBeenCalledWith('github-com', {+ agentRules: [expect.objectContaining({ id: 'quiet' }), expect.objectContaining({ kind: 'review-request', repo: 'octocat/*', action: 'agent' })],+ }));+ const editOwnerRule = await screen.findByRole('button', { name: 'Edit Review requests rule for octocat (all repos)' });+ await act(async () => fireEvent.click(editOwnerRule));+ expect(screen.getByLabelText('In').value).toBe('octocat/*');+ fireEvent.change(screen.getByLabelText('In'), { target: { value: '__owner__' } });+ fireEvent.change(screen.getByLabelText('Account or organization name'), { target: { value: 'new-org' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save rule' }));+ await waitFor(() => expect(mock.updateGitHubAccount).toHaveBeenLastCalledWith('github-com', {+ agentRules: [expect.objectContaining({ id: 'quiet' }), expect.objectContaining({ repo: 'new-org/*', action: 'agent' })],+ }));+ const editCustomOwnerRule = await screen.findByRole('button', { name: 'Edit Review requests rule for new-org (all repos)' });+ await act(async () => fireEvent.click(editCustomOwnerRule));+ expect(screen.getByLabelText('Account or organization name').value).toBe('new-org');+ fireEvent.change(screen.getByLabelText('Account or organization name'), { target: { value: 'bad/name' } });+ expect(screen.getByRole('button', { name: 'Save rule' }).disabled).toBe(true);+ });+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({diff --git a/server/lib/githubNotificationTriage.js b/server/lib/githubNotificationTriage.jsindex dd4782688f..498aede53e 100644--- a/server/lib/githubNotificationTriage.js+++ b/server/lib/githubNotificationTriage.js@@ -251,7 +251,7 @@ const AGENT_ONLY_RULE_KINDS = new Set(['security-alert']);// before #13192 (their own lanes), so they never start a generic run.export const GENERIC_RULE_KINDS = Object.freeze(['ci-activity', 'own-pr', 'mention', 'release', 'other']);const GENERIC_KIND_SET = new Set(GENERIC_RULE_KINDS);-const RULE_REPO_RE = /^(?:\*|[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100})$/;+const RULE_REPO_RE = /^(?:\*|[A-Za-z0-9_.-]{1,100}\/(?:\*|[A-Za-z0-9_.-]{1,100}))$/;// A review request still waiting on you; one you sorted as done or noise is not.const REVIEW_DECISIONS = new Set(['suggest-review', 'suggest-untrusted-review', 'needs-you', 'surface']);const REVIEW_TRUST = new Set(['yours', 'trusted']);@@ -336,13 +336,17 @@ function matchAgentRule(rules, kind, repo) {if (!kind) return null;const valid = validRules(rules, kind);const name = String(repo || '').toLowerCase();- return (name && valid.find((rule) => rule.repo.toLowerCase() === name)) || valid.find((rule) => rule.repo === '*') || null;+ const owner = name.includes('/') ? `${name.split('/')[0]}/*` : null;+ return (name && valid.find((rule) => rule.repo.toLowerCase() === name))+ || (owner && valid.find((rule) => rule.repo.toLowerCase() === owner))+ || valid.find((rule) => rule.repo === '*') || null;}/*** 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+ * query: `only` allows and `except` denies lowercase repo or owner/* scopes.+ * Exact repos win over owners, then `all` is the fallback. 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.*/@@ -351,9 +355,17 @@ export function agentRuleScope(rules, kind, { optIn = false, actions = ['agent']const star = valid.find((rule) => rule.repo === '*');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) };+ return { all, except: repos(false), only: repos(true) };}+/** SQL mirror of rule precedence; parameters are `all`, `except`, `only`. */+export const agentRuleScopeSql = (n) => `(CASE+ WHEN lower(repo_full_name) = ANY($${n + 2}::text[]) THEN TRUE+ WHEN lower(repo_full_name) = ANY($${n + 1}::text[]) THEN FALSE+ WHEN (split_part(lower(repo_full_name), '/', 1) || '/*') = ANY($${n + 2}::text[]) THEN TRUE+ WHEN (split_part(lower(repo_full_name), '/', 1) || '/*') = ANY($${n + 1}::text[]) THEN FALSE+ ELSE $${n}::boolean END)`;+/** `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: [] }diff --git a/server/lib/githubNotificationTriage.test.js b/server/lib/githubNotificationTriage.test.jsindex 0414405cbb..2e4f252fb4 100644--- a/server/lib/githubNotificationTriage.test.js+++ b/server/lib/githubNotificationTriage.test.js@@ -252,6 +252,24 @@ describe('autopilotHandoff', () => {expect(agentRuleScope([], 'review-request', { optIn: true })).toEqual({ all: false, except: [], only: [] });});+ it('limits reviews to an owner group, preserves pins and lets repo exceptions win regardless of order', () => {+ const rules = [+ { id: 'all', kind: 'review-request', repo: '*', action: 'leave' },+ { id: 'owner', kind: 'review-request', repo: 'Acme/*', action: 'agent', model: 'owner-model' },+ { id: 'quiet', kind: 'review-request', repo: 'acme/quiet', action: 'leave' },+ { id: 'exception', kind: 'review-request', repo: 'other/special', action: 'agent' },+ ];+ const row = { ...review, trust: 'trusted', decision: 'suggest-review', evidence: { repoManaged: false } };+ for (const ordered of [rules, [...rules].reverse()]) {+ const scoped = { ...account, agentRules: ordered };+ expect(autopilotHandoff({ account: scoped, row: { ...row, repo_full_name: 'ACME/new-repo' } })).toMatchObject({ lane: 'do-review', pin: { model: 'owner-model' }, rule: { id: 'owner' } });+ for (const repo of ['acme/quiet', 'acme-other/app', 'watched/app', null]) {+ expect(autopilotHandoff({ account: scoped, row: { ...row, repo_full_name: repo } }), String(repo)).toBeNull();+ }+ expect(autopilotHandoff({ account: scoped, row: { ...row, repo_full_name: 'other/special' } })).toMatchObject({ lane: 'do-review', rule: { id: 'exception' } });+ }+ });+it('refuses every hand-off on a Private account until the operator allows agents on it', () => {const enterprise = { ...account, trust: 'private' };expect(autopilotHandoff({ account: enterprise, row: review })).toEqual({ lane: 'pr-reviewer', pullNumber: 42, refused: 'private-account' });@@ -268,6 +286,15 @@ describe('autopilotHandoff', () => {describe('ruleAction', () => {const ci = { state: 'open', reason: 'ci_activity', subject_type: 'CheckSuite', repo_full_name: 'acme/app', rule: 'ci-other' };+ it('lets owner rules override defaults and repo rules override owner rules for Assist', () => {+ const account = { agentRules: [+ { kind: 'ci-activity', repo: 'ACME/*', action: 'leave' },+ { kind: 'ci-activity', repo: 'acme/noisy', action: 'mute' },+ ] };+ expect(ruleAction({ account, row: ci })).toBeNull();+ expect(ruleAction({ account, row: { ...ci, repo_full_name: 'acme/noisy' } })).toBe('mute');+ expect(ruleAction({ account, row: { ...ci, repo_full_name: 'another/app' } })).toBe('done');+ });it('marks CI notices done by default and lets a repo or * rule override it', () => {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' }];diff --git a/server/lib/validation.js b/server/lib/validation.jsindex dcd7c42b97..70a6093486 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -953,20 +953,20 @@ export const GITHUB_ACCOUNT_TRUST_LEVELS = Object.freeze(['public', 'private']);export const GITHUB_ACCOUNT_MODES = Object.freeze(['disabled', 'observe', 'assist', 'autopilot']);// 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+// Autopilot do with a kind of notification, in one repo (`owner/repo`), an+// account/org (`owner/*`) or every repo (`*`), and on which provider/model/effort+// when it starts an agent. Repo > owner > all. 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})$/;+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'),+ repo: z.string().trim().regex(GITHUB_AGENT_RULE_REPO_RE, 'Use owner/repo, owner/* for an account or organization, or * for every repo'),agent: z.boolean().optional(),action: z.enum(GITHUB_AGENT_RULE_ACTIONS).optional(),provider: z.preprocess(emptyToNullString, z.string().trim().min(1).max(128).nullable()).optional(),diff --git a/server/services/githubAccounts.test.js b/server/services/githubAccounts.test.jsindex 47febbc51d..73492fc97c 100644--- a/server/services/githubAccounts.test.js+++ b/server/services/githubAccounts.test.js@@ -61,6 +61,23 @@ describe('GitHub accounts API', () => {expect(after.body[0].implicit).toBeUndefined();});+ it('persists owner automation scopes through the account API and refuses malformed or duplicate scopes', async () => {+ const agentRules = [+ { id: 'all', kind: 'review-request', repo: '*', action: 'leave' },+ { id: 'org', kind: 'review-request', repo: 'Acme/*', action: 'agent', model: 'example-model' },+ { id: 'repo', kind: 'review-request', repo: 'acme/quiet', action: 'leave' },+ ];+ const updated = await request(app).put('/api/github/accounts/github-com').send({ agentRules });+ expect(updated.status).toBe(200);+ expect(updated.body.agentRules).toEqual(agentRules);+ expect((await request(app).get('/api/github/accounts')).body[0].agentRules).toEqual(agentRules);+ for (const repo of ['*/app', 'acme/pre*', 'acme/*/extra', 'acme/']) {+ expect((await request(app).put('/api/github/accounts/github-com').send({ agentRules: [{ ...agentRules[1], repo }] })).status, repo).toBe(400);+ }+ expect((await request(app).put('/api/github/accounts/github-com').send({ agentRules: [...agentRules, { ...agentRules[1], id: 'duplicate', repo: 'acme/*' }] })).status).toBe(400);+ expect((await request(app).get('/api/github/accounts')).body[0].agentRules).toEqual(agentRules);+ });+it('defaults Enterprise hosts to private trust, normalizes the host, and refuses duplicates', async () => {const created = await request(app).post('/api/github/accounts').send({ host: 'HTTPS://GitHub.Example.com/', login: 'alice' });expect(created.status).toBe(201);diff --git a/server/services/githubNotificationAssist.js b/server/services/githubNotificationAssist.jsindex 4cafc35842..fe6e765a51 100644--- a/server/services/githubNotificationAssist.js+++ b/server/services/githubNotificationAssist.js@@ -16,7 +16,7 @@ import { query, withTransaction } from '../lib/db.js';import { safeJSONParse } from '../lib/fileUtils.js';import { repoApiPath } from '../lib/githubNotificationParse.js';import {- AGENT_RULE_KINDS, ASSIST_VERDICTS, KIND_SQL, PINNED_TRIAGE_RULES, assistAction, decisionFromVerdict, ruleAction, ruleActionScope, selectNotificationProvider,+ AGENT_RULE_KINDS, ASSIST_VERDICTS, KIND_SQL, PINNED_TRIAGE_RULES, agentRuleScopeSql, assistAction, decisionFromVerdict, ruleAction, ruleActionScope, selectNotificationProvider,} from '../lib/githubNotificationTriage.js';import { resolveUntrustedContentPolicy } from '../lib/untrustedContent.js';import { toPgJson } from '../lib/pgJson.js';@@ -135,7 +135,7 @@ export async function assistAccountNotifications(account, env, { act }) {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[])))`;+ return `(${KIND_SQL} = '${kind}' AND ${agentRuleScopeSql(n)})`;}).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_notificationsdiff --git a/server/services/githubNotificationAutopilot.js b/server/services/githubNotificationAutopilot.jsindex dec55cc449..8ee02c0616 100644--- a/server/services/githubNotificationAutopilot.js+++ b/server/services/githubNotificationAutopilot.js@@ -26,7 +26,7 @@ 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, FINISHED_DECISIONS, GENERIC_AGENT_LANE, GENERIC_RULE_KINDS, KIND_SQL,+ agentHandoff, agentRuleScope, agentRuleScopeSql as inScope, 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';@@ -41,8 +41,6 @@ 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;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[]))`;const NOT_FINISHED_SQL = `COALESCE(evidence->>'subjectState', '') NOT IN ('merged', 'closed')`;const PULL_URL_SQL = `COALESCE(subject_api_url, '') ~ '/pulls/[0-9]{1,9}$'`;diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex 56e637357a..6903eb7c6b 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -1156,7 +1156,7 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {const rows = [];let n = 0;for (const [kind, shapes] of Object.entries(fixtures)) {- for (const shape of shapes) {+ for (const shape of shapes.flatMap((shape) => ['acme/app', 'acme/quiet', 'watched/app'].map((repo) => ({ ...shape, repo_full_name: repo, repo_owner: repo.split('/')[0] })))) {n += 1;const row = {account_id: account.id, thread_id: `parity-${n}`, repo_full_name: 'acme/app', repo_owner: 'acme', state: 'open', suspect: false,@@ -1181,8 +1181,15 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {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 }] : [];+ for (const repo of ['*', 'acme/app', 'ACME/*', 'other/*']) {+ const agentRules = action ? [+ { id: 'parity', kind: ruleKind, repo, action },+ // Contradictory defaults and repo exceptions exercise precedence in SQL.+ ...(repo.endsWith('/*') ? [+ { id: 'fallback', kind: ruleKind, repo: '*', action: action === 'agent' ? 'leave' : 'agent' },+ { id: 'exception', kind: ruleKind, repo: 'acme/quiet', action: action === 'agent' ? 'leave' : 'agent' },+ ] : []),+ ] : [];const autopilot = { ...account, mode: 'autopilot', agentRules };const filter = candidateFilter(agentRules, 3);const { rows: selected } = await query(