Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
GitHub inbox: read the whole inbox, clear what's done, fix security alerts outside your apps (#13086)
[._.]/48a044f943d7
diff --git a/client/src/components/github/GitHubAutomationsTab.jsx b/client/src/components/github/GitHubAutomationsTab.jsxindex 09ef99d1a8..22cc54e8eb 100644--- a/client/src/components/github/GitHubAutomationsTab.jsx+++ b/client/src/components/github/GitHubAutomationsTab.jsx@@ -30,7 +30,7 @@ function modeHint(account) {if (account.mode !== 'autopilot') return assist;const handoff = account.trust === 'private'? 'Private accounts never hand threads off.'- : 'Also hands outside review requests, outside issues and security alerts in your PortOS apps to Untrusted:Review, the issue watcher and dependency updates when those are on for the app, one run per app for each. Nothing outside your apps is ever started.';+ : '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.';return `${assist} ${handoff}`;}diff --git a/client/src/components/github/GitHubThreadDrawer.jsx b/client/src/components/github/GitHubThreadDrawer.jsxindex 0bdfd5675b..6748668cb8 100644--- a/client/src/components/github/GitHubThreadDrawer.jsx+++ b/client/src/components/github/GitHubThreadDrawer.jsx@@ -45,9 +45,12 @@ function HandoffLine({ handoff }) {return (<p className="text-xs text-gray-300">{handoff.duplicate ? 'Already with ' : 'Handed to '}{lane?.label || handoff.lane}- {handoff.appId && lane && (+ {handoff.appId && lane?.tab && (<> for <Link to={`/apps/${encodeURIComponent(handoff.appId)}/${lane.tab}`} className="text-port-accent">{handoff.appName || handoff.appId}</Link></>)}+ {!handoff.appId && handoff.taskId && (+ <> (<Link to="/cos/tasks" className="text-port-accent">CoS task</Link>)</>+ )}{handoff.batchSize > 1 && `, in one run with ${handoff.batchSize - 1} other notification${handoff.batchSize === 2 ? '' : 's'}`}</p>);diff --git a/client/src/components/github/githubTriageLabels.js b/client/src/components/github/githubTriageLabels.jsindex e3ad89089e..3915019254 100644--- a/client/src/components/github/githubTriageLabels.js+++ b/client/src/components/github/githubTriageLabels.js@@ -60,6 +60,8 @@ export const LANE_VIEW = {'pr-reviewer': { label: 'Untrusted:Review', tab: 'pull-requests' },'issue-watcher': { label: 'the issue watcher', tab: 'tasks' },'dependency-updates': { label: 'dependency updates', tab: 'tasks' },+ // A one-off CoS task in a scratch clone, for a repo no app manages.+ 'security-fix': { label: 'a security fix agent', tab: null },};// Why Resolve with agent is unavailable for a thread.diff --git a/server/lib/README.md b/server/lib/README.mdindex 26fd9d310f..f3fa707383 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -486,7 +486,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. |+| `githubNotificationParse.js` | `parseGhIncludeOutput`, `linkHeaderHasNext`, `pollIntervalSeconds`, `repoApiPath`, `advisoryIdFromUrl`, `GHSA_RE`, `toNotificationRecord` — pure parsing for the GitHub notifications inbox: `gh api --include` output and thread records, with links rebuilt only onto the account's own GitHub host. || `githubNotificationTriage.js` | `TRIAGE_DECISIONS`, `TRUST_LEVELS`, `MASS_MENTION_THRESHOLD`, `computeThreadTrust`, `spamSignals`, `parseCiBranch`, `decideThread`, `ASSIST_VERDICTS`, `decisionFromVerdict`, `learnedDecisionForAction`, `applyLearnedRule`, `assistAction`, `selectNotificationProvider` — the GitHub inbox's fixed trust, spam and routing rules plus Assist's verdict enum, learned rules, allowed actions and Private-account provider allow-list; trust comes only from accounts, repo ownership and forge permissions, never from content. || `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. |diff --git a/server/lib/githubNotificationParse.js b/server/lib/githubNotificationParse.jsindex 75abeaf237..539806a75f 100644--- a/server/lib/githubNotificationParse.js+++ b/server/lib/githubNotificationParse.js@@ -54,6 +54,19 @@ export function repoApiPath(url, host) {return /^repos(?:\/[A-Za-z0-9_.-]{1,100}){3,5}$/.test(path) && !path.split('/').includes('..') ? path : null;}+export const GHSA_RE = /^GHSA(?:-[23456789cfghjmpqrvwx]{4}){3}$/;++/**+ * The GHSA id of a global security advisory thread (one that names no single+ * repository), from its API url on the account's own host; null otherwise.+ */+export function advisoryIdFromUrl(url, host) {+ const prefix = `${apiRootFor(host)}advisories/`;+ if (typeof url !== 'string' || !url.startsWith(prefix)) return null;+ const id = url.slice(prefix.length);+ return GHSA_RE.test(id) ? id : null;+}+const SUBJECT_PATHS = { issues: 'issues', pulls: 'pull', commits: 'commit', discussions: 'discussions' };/**@@ -62,6 +75,8 @@ const SUBJECT_PATHS = { issues: 'issues', pulls: 'pull', commits: 'commit', disc* that would leave `host` is dropped rather than shown.*/function notificationHtmlUrl({ subjectApiUrl, repoFullName }, host) {+ const advisory = advisoryIdFromUrl(subjectApiUrl, host);+ if (advisory) return `https://${webHostFor(host)}/advisories/${advisory}`;const [owner, repo] = String(repoFullName || '').split('/');if (!REPO_PART_RE.test(owner || '') || !REPO_PART_RE.test(repo || '')) return '';const repoUrl = `https://${webHostFor(host)}/${owner}/${repo}`;@@ -84,11 +99,13 @@ const rawThreadSchema = z.object({url: z.string().max(2000).nullable().optional(),latest_comment_url: z.string().max(2000).nullable().optional(),}).passthrough(),+ // A global security advisory ("affects at least one of your repositories")+ // may come without a single repository.repository: z.object({full_name: z.string().max(201),private: z.boolean().optional(),owner: z.object({ login: z.string().max(100) }).passthrough(),- }).passthrough(),+ }).passthrough().nullable().optional(),}).passthrough();/** A stored-shape record from one raw API thread, or null when malformed. */@@ -98,9 +115,9 @@ export function toNotificationRecord(raw, host) {const { id, unread, reason, updated_at: updatedAt, subject, repository } = parsed.data;const record = {threadId: id,- repoFullName: repository.full_name,- repoOwner: repository.owner.login,- repoPrivate: repository.private === true,+ repoFullName: repository?.full_name || '',+ repoOwner: repository?.owner.login || '',+ repoPrivate: repository?.private === true,reason,subjectType: subject.type,subjectTitle: Array.from(subject.title).slice(0, MAX_TITLE_CHARS).join(''),diff --git a/server/lib/githubNotificationTriage.js b/server/lib/githubNotificationTriage.jsindex 85869e725e..5b4e147ee6 100644--- a/server/lib/githubNotificationTriage.js+++ b/server/lib/githubNotificationTriage.js@@ -36,7 +36,7 @@ export const TRUST_LEVELS = Object.freeze(['yours', 'trusted', 'outside', 'unkno// Bump when a rule change should re-decide threads that have no new activity;// open threads triaged under an older version are triaged again.-export const TRIAGE_RULES_VERSION = 2;+export const TRIAGE_RULES_VERSION = 3;// Decisions that leave nothing for you: something else has the thread, or it// is already closed or merged. They sit under Handled instead of Needs you,@@ -196,7 +196,8 @@ const PULL_PATH_RE = /\/pulls\/(\d{1,9})$/;/*** Which lane an agent may resolve a thread in, or null when no lane fits. A* plan with `refused` names why it cannot go: only a PortOS managed app's- * repo has lanes (they run per app), and a Private account's threads never+ * repo has lanes (they run per app), except a security alert in a repo of+ * yours or a global advisory (`security-fix`), and a Private account's threads never* go, because the lanes use their own providers, which its provider* allow-list cannot bind. Suspect and closed threads never qualify. The pull* number comes from the subject's API url, never from a title or body. Used@@ -212,12 +213,16 @@ export function agentHandoff({ account, row }) {} else if (row.subject_type === 'Issue' && HANDOFF_ISSUE_DECISIONS.has(row.decision) && (row.trust === 'outside' || evidence.commenter)) {plan = { lane: 'issue-watcher' };} else if (row.reason === 'security_alert' && row.decision === 'surface-high') {- // The lane reads the repo's own Dependabot alerts and PRs, not the thread.- plan = { lane: 'dependency-updates' };+ // A managed app's own dependency lane reads the repo's Dependabot alerts and+ // PRs, not the thread. A repo of yours with no app, or an advisory that+ // names no repo, gets a one-off security fix run that works in a scratch clone.+ plan = evidence.repoManaged !== true && (evidence.repoOwned === true || !row.repo_full_name)+ ? { lane: 'security-fix', repo: row.repo_full_name || null }+ : { lane: 'dependency-updates' };}if (!plan) return null;if (account?.trust === 'private') return { ...plan, refused: 'private-account' };- if (evidence.repoManaged !== true) return { ...plan, refused: 'no-managed-app' };+ if (plan.lane !== 'security-fix' && evidence.repoManaged !== true) return { ...plan, refused: 'no-managed-app' };return plan;}diff --git a/server/services/githubNotificationAudit.js b/server/services/githubNotificationAudit.jsindex 1fde03e0d4..5ad17cfd59 100644--- a/server/services/githubNotificationAudit.js+++ b/server/services/githubNotificationAudit.js@@ -42,7 +42,8 @@ const OUTCOMES_SQL = `EXISTS (SELECT 1 FROM github_notification_events eWHERE e.account_id = n.account_id AND e.thread_id = n.thread_id AND e.actor = 'automation' AND e.kind <> 'triaged') AS automation_actedFROM github_notifications n- WHERE n.account_id = $1 AND n.gh_updated_at > NOW() - make_interval(days => $2)+ -- A global advisory names no repo, so there is no repo to watch or mute.+ WHERE n.account_id = $1 AND n.repo_full_name <> '' 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,diff --git a/server/services/githubNotificationAutopilot.js b/server/services/githubNotificationAutopilot.jsindex e0270810ab..7773dab7ee 100644--- a/server/services/githubNotificationAutopilot.js+++ b/server/services/githubNotificationAutopilot.js@@ -4,7 +4,9 @@* that already owns that work: a review request from an outside author to* `pr-reviewer` (the same targeted run as the Pull Requests tab's* Untrusted:Review button), outside issue activity to `issue-watcher`, and a- * security alert to `dependency-updates`. The inbox's Resolve with agent button+ * security alert to `dependency-updates`. A security alert in a repo of yours+ * that no app manages, or a global advisory, goes to a one-off `security-fix`+ * task (githubSecurityFixTask.js). The inbox's Resolve with agent button* hands one thread off the same way on a tap, in any mode.** Nothing here reads thread text or starts an agent: each hand-off queues the@@ -14,9 +16,11 @@*/import { query, withTransaction } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';+import { advisoryIdFromUrl } from '../lib/githubNotificationParse.js';import { agentHandoff, autopilotHandoff } from '../lib/githubNotificationTriage.js';import { toPgJson } from '../lib/pgJson.js';import { managedAppsByRepoKey } from './githubNotificationTriage.js';+import { queueSecurityFixTask } from './githubSecurityFixTask.js';import { queueTargetedPrReview, readActiveTasks, readPendingOnDemandRequests, ACTIVE_TASK_STATUSES } from './prReviewerTargetedRun.js';import { triggerOnDemandTask } from './taskSchedule.js';import { ON_DEMAND_ORIGINS } from './taskScheduleConstants.js';@@ -49,7 +53,11 @@ async function queueAppLane(taskType, app, origin) {return request?.error ? { error: request.error } : { requestId: request.id };}-async function queueLane(plan, app, origin) {+async function queueLane(plan, app, origin, { account, rows }) {+ if (plan.lane === 'security-fix') {+ const advisories = plan.repo ? [] : rows.map((row) => advisoryIdFromUrl(row.subject_api_url, account.host)).filter(Boolean);+ return queueSecurityFixTask({ account, repo: plan.repo || null, advisories, origin });+ }if (plan.lane !== 'pr-reviewer' || !plan.pullNumber) return queueAppLane(plan.lane, app, origin);return queueTargetedPrReview(app, plan.pullNumber, { origin }).then((queued) => (queued.duplicate ? { duplicate: true, taskId: queued.reviewAction?.taskId || null } : { requestId: queued.request.id }));@@ -84,7 +92,7 @@ export async function autopilotAccountNotifications(account) {if (account.mode !== 'autopilot') return { handedOff: 0, agentRuns: 0 };const { rows } = await query(`SELECT * FROM github_notifications WHERE account_id = $1 AND state = 'open' AND NOT suspect- AND ${CANDIDATE_SQL} AND (evidence->>'repoManaged')::boolean IS TRUE AND NOT (evidence ? 'handoff')+ AND ${CANDIDATE_SQL} AND ((evidence->>'repoManaged')::boolean IS TRUE OR reason = 'security_alert') AND NOT (evidence ? 'handoff')ORDER BY gh_updated_at DESC LIMIT ${MAX_HANDOFFS_PER_RUN}`,[account.id],);@@ -94,6 +102,13 @@ export async function autopilotAccountNotifications(account) {const batches = new Map();const skipped = [];for (const entry of plans) {+ if (!entry.plan.refused && entry.plan.lane === 'security-fix') {+ // One run per repo, and one for every global advisory together.+ const key = `security-fix#${entry.plan.repo || '*'}`;+ if (!batches.has(key)) batches.set(key, { app: null, lane: 'security-fix', repo: entry.plan.repo, entries: [] });+ batches.get(key).entries.push({ ...entry, app: null });+ continue;+ }const app = apps.get(`${account.host}/${entry.row.repo_full_name}`.toLowerCase());if (entry.plan.refused || !app) {skipped.push({ ...entry, app, outcome: { skipped: entry.plan.refused || 'no-managed-app' } });@@ -123,18 +138,19 @@ export async function autopilotAccountNotifications(account) {}};for (const entry of skipped) await record(entry);- for (const { app, lane, entries } of batches.values()) {+ for (const { app, lane, repo, entries } of batches.values()) {const pullNumbers = new Set(entries.map((entry) => entry.plan.pullNumber).filter(Boolean));- const batchPlan = lane === 'pr-reviewer' && pullNumbers.size === 1 ? entries[0].plan : { lane };+ const batchPlan = lane === 'pr-reviewer' && pullNumbers.size === 1 ? entries[0].plan : { lane, repo };// 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).catch((error) => ({ error: error.message }));+ const queued = await queueLane(batchPlan, app, ON_DEMAND_ORIGINS.GITHUB_NOTIFICATION, { account, rows: entries.map((entry) => entry.row) })+ .catch((error) => ({ error: error.message }));const outcome = queued.error? { skipped: 'lane-unavailable', error: String(queued.error).slice(0, 300) }: { ...queued, ...(entries.length > 1 ? { batchSize: entries.length } : {}) };- if (queued.requestId) agentRuns += 1;+ if (!queued.error && !queued.duplicate) agentRuns += 1;for (const entry of entries) await record({ ...entry, outcome });- if (!queued.error) console.log(`🤝 Autopilot handed ${entries.length} GitHub notification(s) to one ${lane} run for ${app.name}`);+ if (!queued.error) console.log(`🤝 Autopilot handed ${entries.length} GitHub notification(s) to one ${lane} run for ${app?.name || repo || 'your repositories'}`);}return { handedOff, agentRuns };}@@ -155,17 +171,17 @@ export async function handOffThread(account, threadId) {const plan = agentHandoff({ account, row });if (!plan) throw new ServerError('No agent handles this kind of notification', { status: 409, code: 'GITHUB_NOTIFICATION_NO_LANE' });if (plan.refused) throw new ServerError(REFUSED_MESSAGES[plan.refused], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });- const app = (await managedAppsByRepoKey()).get(`${account.host}/${row.repo_full_name}`.toLowerCase());- if (!app) throw new ServerError(REFUSED_MESSAGES['no-managed-app'], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });- const queued = await queueLane(plan, app, ON_DEMAND_ORIGINS.USER);+ const app = plan.lane === 'security-fix' ? null : (await managedAppsByRepoKey()).get(`${account.host}/${row.repo_full_name}`.toLowerCase());+ if (plan.lane !== 'security-fix' && !app) throw new ServerError(REFUSED_MESSAGES['no-managed-app'], { status: 409, code: 'GITHUB_NOTIFICATION_HANDOFF_REFUSED' });+ const queued = await queueLane(plan, app, ON_DEMAND_ORIGINS.USER, { account, rows: [row] });if (queued.error) throw new ServerError(String(queued.error), { status: 409, code: 'GITHUB_NOTIFICATION_LANE_UNAVAILABLE' });await recordHandoff(account, row, {lane: plan.lane,- appId: app.id,- appName: app.name || null,+ appId: app?.id || null,+ appName: app?.name || null,...(plan.pullNumber ? { pullNumber: plan.pullNumber } : {}),...queued,at: new Date().toISOString(),}, 'operator');- console.log(`🤝 Handed GitHub notification ${row.thread_id} to ${plan.lane} for ${app.name}`);+ console.log(`🤝 Handed GitHub notification ${row.thread_id} to ${plan.lane} for ${app?.name || row.repo_full_name || 'your repositories'}`);}diff --git a/server/services/githubNotificationTriage.js b/server/services/githubNotificationTriage.jsindex 3589d1d838..5eff0021af 100644--- a/server/services/githubNotificationTriage.js+++ b/server/services/githubNotificationTriage.js@@ -21,20 +21,25 @@ import { createGithubActorTrust } from './forgeActorTrust.js';import { listAccounts } from './githubAccounts.js';const GH_TIMEOUT_MS = 20_000;-// Each thread costs a few API calls; the rest wait for the next run.-const MAX_THREADS_PER_RUN = 25;+// Each thread costs a few API calls; the rest wait for the next run. The first+// sync reads the whole inbox, read threads included.+const MAX_THREADS_PER_RUN = 60;// Open threads a rules-version bump re-decides without new activity: version 2-// changed your own PRs and finished threads (now marked done, not just read).-// A thread already handed off keeps its hand-off, and one an Assist model-// sorted is not read again.-const REDECIDE_SQL = `(state = 'open' AND NOT (evidence ? 'handoff') AND COALESCE(evidence->>'rule', '') NOT LIKE 'ai-%'- AND ((reason = 'author' AND subject_type = 'PullRequest') OR decision = 'suggest-mark-read'))`;+// changed your own PRs and finished threads (now marked done, not just read);+// version 3 leaves a bot's comment on your own PR to the PR workflow. A thread+// already handed off keeps its hand-off. One an Assist model sorted is not+// read again, except your own PR: the rule table decides those, so a verdict+// from before the rule existed must not keep one in front of you.+const REDECIDE_SQL = `(state = 'open' AND NOT (evidence ? 'handoff')+ AND ((reason = 'author' AND subject_type = 'PullRequest' AND trust = 'yours')+ OR (decision = 'suggest-mark-read' AND COALESCE(evidence->>'rule', '') NOT LIKE 'ai-%')))`;const LOGIN_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}(?:\[bot\])?$/;const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;const SUBJECT_JQ = '{author: .user.login, association: .author_association, state: .state, merged: (.merged // false)}';const COMMENT_JQ = '{author: .user.login, association: .author_association, mentions: ([(.body // "") | scan("@[A-Za-z0-9][A-Za-z0-9-]*")] | length)}';+const isBotLogin = (login) => /\[bot\]$/i.test(login);const loginOrNull = (value) => (typeof value === 'string' && LOGIN_RE.test(value) ? value : null);/** PortOS managed apps keyed by their repo, as lower-cased `host/owner/repo`. */@@ -148,7 +153,10 @@ async function triageThread(row, ctx) {// never leaves Needs you on a comment nobody checked.let commenterTrust = commentPath && commentPath !== subjectPath && !commenter ? 'outside' : null;if (commenter && subjectAuthor && commenter.toLowerCase() !== subjectAuthor.toLowerCase()) {- commenterTrust = await trustOf(commenter);+ // A bot (a CI or review app) commenting on your own PR in your repo was+ // installed there by you, so it is the PR workflow's business, not an+ // outside reply waiting on you. The repo's collaborator list never names it.+ commenterTrust = isBotLogin(commenter) && repoOwned && trust === 'yours' ? 'unknown' : await trustOf(commenter);for (const signal of await signalsFor(commenter, commenterTrust, comment.association, comment.mentions ?? 0)) signalSet.add(signal);}const signals = [...signalSet];diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex abb2908e0d..f3ca74be2a 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -28,7 +28,7 @@ vi.mock('../lib/gitRemote.js', async (importOriginal) => ({readOriginRemoteUrl: vi.fn(async (repoPath) => (repoPath === '/example/acme-app' ? 'https://github.com/acme/app.git' : null)),}));vi.mock('./prReviewerSecurity.js', () => ({ listExternalOpenPullRequests: vi.fn() }));-vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ user: { tasks: [] }, cos: { tasks: [] } })) }));+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ user: { tasks: [] }, cos: { tasks: [] } })), addTask: vi.fn() }));vi.mock('./taskSchedule.js', () => ({ triggerOnDemandTask: vi.fn(), getOnDemandRequests: vi.fn(async () => []) }));vi.mock('./notifications.js', () => ({addNotification: vi.fn(async () => ({})),@@ -41,6 +41,7 @@ const { getAllApps } = await import('./apps.js');const { listExternalOpenPullRequests } = await import('./prReviewerSecurity.js');const { triggerOnDemandTask } = await import('./taskSchedule.js');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 {@@ -130,14 +131,14 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {accountIds.push(account.id);});- it('stores threads with a host-bound link, sends If-Modified-Since next time, and reconciles reads', async () => {+ it('reads the whole inbox, sends If-Modified-Since next time, and marks a thread gone from GitHub done', async () => {const login = account.login;const seen = [];mockGh((args) => {seen.push(args);return seen.length === 1? listing([thread('101', { owner: login }), thread('102', { owner: 'someone-else' })])- : listing([thread('102', { owner: 'someone-else' })]);+ : listing([{ ...thread('102', { owner: 'someone-else' }), unread: false }]);});expect(await syncAccountNotifications(account.id)).toMatchObject({ changed: true, fetched: 2 });@@ -149,10 +150,16 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {expect(first.sync[account.id]).toMatchObject({ lastError: null, pollIntervalSeconds: 60 });await syncAccountNotifications(account.id);+ expect(seen[0]).toContain('notifications?all=true&per_page=50&page=1');expect(seen[1]).toContain('If-Modified-Since: Thu, 01 Oct 2026 10:00:00 GMT');- const rows = (await listNotifications({ accountId: account.id })).notifications;- expect(rows.find((row) => row.threadId === '101').unread).toBe(false);- expect(rows.find((row) => row.threadId === '102').unread).toBe(true);+ // A cursor saved by the older unread-only listing is not sent.+ await query("UPDATE github_notification_sync SET last_modified = 'Thu, 01 Oct 2026 09:00:00 GMT' WHERE account_id = $1", [account.id]);+ await syncAccountNotifications(account.id);+ expect(seen[2].some((arg) => String(arg).startsWith('If-Modified-Since'))).toBe(false);+ const rows = (await listNotifications({ accountId: account.id, view: 'all' })).notifications;+ // Read on GitHub but still in its inbox: open here too. Gone from the inbox: done.+ expect(rows.find((row) => row.threadId === '102')).toMatchObject({ unread: false, state: 'open' });+ expect(rows.find((row) => row.threadId === '101')).toMatchObject({ unread: false, state: 'done' });});it('treats a 304 as unchanged and keeps rows', async () => {@@ -488,6 +495,8 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {thread('1202', { owner: 'acme', repo: 'app', commentUrl: 'https://api.github.com/repos/acme/app/issues/comments/9' }),// Its latest comment cannot be read, so it is not assumed to be yours.thread('1208', { owner: 'acme', repo: 'app', commentUrl: 'https://api.github.com/repos/acme/app/issues/comments/404' }),+ // A review app's comment is the PR workflow's, not an outside reply.+ thread('1209', { owner: 'acme', repo: 'app', commentUrl: 'https://api.github.com/repos/acme/app/issues/comments/10' }),alert('1203'), alert('1204'), alert('1205'),thread('1206', { owner: 'acme', repo: 'app', reason: 'review_requested' }),thread('1207', { owner: 'acme', repo: 'app', reason: 'review_requested' }),@@ -495,6 +504,8 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {'repos/acme/app/pulls/1201': { author: account.login, association: 'OWNER', state: 'open', merged: false },'repos/acme/app/pulls/1202': { author: account.login, association: 'OWNER', state: 'open', merged: false },'repos/acme/app/pulls/1208': { author: account.login, association: 'OWNER', state: 'open', merged: false },+ 'repos/acme/app/pulls/1209': { author: account.login, association: 'OWNER', state: 'open', merged: false },+ 'repos/acme/app/issues/comments/10': { author: 'cursor[bot]', association: 'NONE', mentions: 0 },'repos/acme/app/issues/comments/9': { author: 'visitor', association: 'NONE', mentions: 0 },'repos/acme/app/collaborators/visitor/permission': { user: { login: 'visitor' }, permission: 'read' },'repos/acme/app/pulls/1206': { author: 'mallory', association: 'NONE', state: 'open', merged: false },@@ -517,10 +528,12 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {const handled = (await listNotifications({ accountId: account.id, view: 'handled' })).notifications;// Autopilot includes Assist, which marks it done on GitHub.expect(handled.find((row) => row.threadId === '1201')).toMatchObject({ state: 'done', decision: 'handled-by-pr-workflow', rule: 'own-pr-in-managed-repo' });+ expect(handled.find((row) => row.threadId === '1209')).toMatchObject({ state: 'done', decision: 'handled-by-pr-workflow' });- // A thread decided under older rules is decided again without new activity.+ // Your own PR decided under older rules is decided again without new+ // activity, even when an Assist model sorted it then.await query(- `UPDATE github_notifications SET state = 'open', decision = 'needs-you', evidence = evidence - 'rulesVersion' || '{"rule":"default"}'::jsonb+ `UPDATE github_notifications SET state = 'open', decision = 'surface', evidence = evidence - 'rulesVersion' || '{"rule":"ai-surface"}'::jsonbWHERE account_id = $1 AND thread_id = '1201'`,[account.id],);@@ -555,6 +568,40 @@ describe.skipIf(!runDb)('GitHub notifications inbox against Postgres', () => {vi.mocked(getAllApps).mockResolvedValue([]);});+ it('gives a security alert outside your apps one security fix task per repo, and one for global advisories', async () => {+ await updateAccount(account.id, { mode: 'autopilot' });+ 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 alert = (id, owner, repo) => thread(id, { owner, repo, reason: 'security_alert', type: 'RepositoryVulnerabilityAlert', url: null });+ const advisory = (id, ghsa) => ({+ ...thread(id, { reason: 'security_alert', type: 'SecurityAdvisory', url: `https://api.github.com/advisories/${ghsa}` }),+ repository: null,+ });+ mockGh(() => listing([+ alert('1401', account.login, 'tool'), alert('1402', account.login, 'tool'),+ alert('1403', 'someone', 'other'),+ advisory('1404', 'GHSA-q3jh-wrc6-jgq8'), advisory('1405', 'GHSA-8r9p-f939-6h3c'),+ ]));++ expect((await syncAccountNotifications(account.id)).assist).toMatchObject({ handedOff: 4, agentRuns: 2 });+ const tasks = vi.mocked(addTask).mock.calls.map(([task]) => task);+ expect(tasks).toHaveLength(2);+ const repoTask = tasks.find((task) => task.metadata.githubSecurityFix.repo);+ expect(repoTask).toMatchObject({ useWorktree: false, openPR: false, noCodeOutput: true, metadata: { githubSecurityFix: { repo: `${account.login}/tool` } } });+ expect(repoTask.description.split('\n')[0]).toBe(`Fix the open security alerts in github.com/${account.login}/tool`);+ expect(repoTask.description).toContain(`gh repo clone ${account.login}/tool`);+ const advisoryTask = tasks.find((task) => !task.metadata.githubSecurityFix.repo);+ expect(advisoryTask.metadata.githubSecurityFix.advisories).toEqual(['GHSA-8r9p-f939-6h3c', 'GHSA-q3jh-wrc6-jgq8']);+ expect(await getNotification(account.id, '1404')).toMatchObject({ decision: 'handed-off', htmlUrl: 'https://github.com/advisories/GHSA-q3jh-wrc6-jgq8' });+ // The two batches share a timestamp, so either may be queued first.+ expect((await getNotification(account.id, '1402')).evidence.handoff).toMatchObject({ lane: 'security-fix', taskId: `task-${tasks.indexOf(repoTask) + 1}`, batchSize: 2 });+ // A repo you neither own nor manage is not yours to fix.+ expect(await getNotification(account.id, '1403')).toMatchObject({ decision: 'surface-high' });+ await syncAccountNotifications(account.id);+ expect(addTask).toHaveBeenCalledTimes(2);+ });+it('sends the opt-in monthly audit report once per window, as suggestions only', async () => {await updateAccount(account.id, { auditReport: true });const recent = new Date(Date.now() - 86_400_000).toISOString();diff --git a/server/services/githubNotifications.js b/server/services/githubNotifications.jsindex 40aadbafa1..443cdcf4ee 100644--- a/server/services/githubNotifications.js+++ b/server/services/githubNotifications.js@@ -28,9 +28,9 @@ import { toPgJson } from '../lib/pgJson.js';const GH_TIMEOUT_MS = 30_000;const PER_PAGE = 50;-// GitHub lists at most 50 threads a page; past 250 unread the listing is-// truncated and read-state is not reconciled for threads it did not return.-const MAX_PAGES = 5;+// GitHub lists at most 50 threads a page; past 1,000 inbox threads the+// listing is truncated and threads it did not return are not reconciled.+const MAX_PAGES = 20;const LIST_LIMIT = 200;export const NOTIFICATION_VIEWS = Object.freeze(['needs-you', 'suspect', 'handled', 'all']);@@ -59,6 +59,14 @@ const syncFlightFor = (accountId) => {return syncFlights.get(accountId);};+// The stored Last-Modified cursor names the listing it came from. A cursor+// saved by the older unread-only listing is not reused: a 304 against it would+// skip the first read of the whole inbox until something new arrived.+const LISTING_CURSOR_PREFIX = 'all:';+const listingCursor = (stored) => (typeof stored === 'string' && stored.startsWith(LISTING_CURSOR_PREFIX)+ ? stored.slice(LISTING_CURSOR_PREFIX.length) || null+ : null);+const isNotModified = (error) => /\bHTTP 304\b/.test(String(error?.ghStderr || error?.message || ''));async function requireAccountEnv(account) {@@ -76,7 +84,7 @@ async function requireAccountEnv(account) {async function fetchPage(account, env, page, ifModifiedSince) {const args = ['api', '--hostname', account.host, '--include', '--method', 'GET',- `notifications?per_page=${PER_PAGE}&page=${page}`];+ `notifications?all=true&per_page=${PER_PAGE}&page=${page}`];if (ifModifiedSince) args.push('-H', `If-Modified-Since: ${ifModifiedSince}`);const output = await execGh(args, GH_TIMEOUT_MS, { env }).catch((error) => {if (ifModifiedSince && isNotModified(error)) return null;@@ -143,7 +151,7 @@ async function runAutomation(account, env, automate) {async function syncAccountNow(account, automate) {const env = await requireAccountEnv(account);const cursor = (await query('SELECT last_modified FROM github_notification_sync WHERE account_id = $1', [account.id])).rows[0];- const first = await fetchPage(account, env, 1, cursor?.last_modified || null);+ const first = await fetchPage(account, env, 1, listingCursor(cursor?.last_modified));if (first.notModified) {await query('UPDATE github_notification_sync SET last_sync_at = NOW(), last_error = \'\', updated_at = NOW() WHERE account_id = $1', [account.id]);// Threads past the last run's triage cap still need a decision.@@ -170,11 +178,15 @@ async function syncAccountNow(account, automate) {r.subjectTitle, r.subjectApiUrl, r.htmlUrl, r.unread, r.ghUpdatedAt, r.latestCommentApiUrl,]);}- // The listing holds only unread threads; one that dropped out was read- // elsewhere. A truncated listing proves nothing about the rest.+ // The listing is the whole GitHub inbox, read and unread (`all=true`); a+ // thread that dropped out was marked done on GitHub. A truncated listing+ // proves nothing about the rest.if (!truncated) {await client.query(- 'UPDATE github_notifications SET unread = FALSE, updated_at = NOW() WHERE account_id = $1 AND unread AND NOT (thread_id = ANY($2::text[]))',+ `UPDATE github_notifications SET unread = FALSE,+ state = CASE WHEN state = 'open' THEN 'done' ELSE state END,+ state_changed_at = CASE WHEN state = 'open' THEN NOW() ELSE state_changed_at END, updated_at = NOW()+ WHERE account_id = $1 AND (unread OR state = 'open') AND NOT (thread_id = ANY($2::text[]))`,[account.id, records.map((r) => r.threadId)],);}@@ -183,7 +195,7 @@ async function syncAccountNow(account, automate) {VALUES ($1, $2, $3, NOW(), '', NOW())ON CONFLICT (account_id) DO UPDATE SET last_modified = EXCLUDED.last_modified,poll_interval_seconds = EXCLUDED.poll_interval_seconds, last_sync_at = NOW(), last_error = '', updated_at = NOW()`,- [account.id, first.headers['last-modified'] || null, pollIntervalSeconds(first.headers['x-poll-interval'])],+ [account.id, first.headers['last-modified'] ? `${LISTING_CURSOR_PREFIX}${first.headers['last-modified']}` : null, pollIntervalSeconds(first.headers['x-poll-interval'])],);});const triage = await triageAccountNotifications(account, env);@@ -194,7 +206,7 @@ async function syncAccountNow(account, automate) {}/**- * Fetch one account's unread notifications, coalescing concurrent requests.+ * Fetch one account's GitHub inbox (read and unread), coalescing concurrent requests.* `automate: false` (a caller without host control) skips Assist/Autopilot.*/export async function syncAccountNotifications(accountId, { automate = true } = {}) {diff --git a/server/services/githubSecurityFixTask.js b/server/services/githubSecurityFixTask.jsnew file mode 100644index 0000000000..79e846590a--- /dev/null+++ b/server/services/githubSecurityFixTask.js@@ -0,0 +1,87 @@+/**+ * The `security-fix` lane for the GitHub notifications inbox: a security alert+ * in a repo of yours that no PortOS app manages, or a global advisory that+ * names no single repo, queues one CoS task that clones the repo into a scratch+ * directory, fixes the alerts, opens a pull request and merges it when checks+ * pass. A managed app's alerts go to its own `dependency-updates` lane instead.+ *+ * The prompt carries only values the forge and the account config vouch for:+ * the account's host and login, a repo name matching REPO_RE and GHSA ids+ * matching their fixed format. No notification title or body reaches it.+ */+import { GHSA_RE } from '../lib/githubNotificationParse.js';+import { addTask } from './cosTaskStore.js';++const REPO_RE = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;+const HOST_RE = /^[A-Za-z0-9.-]{1,253}$/;+const LOGIN_RE = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/;++const SCRATCH_STEPS = (cloneTarget) => [+ `Clone it into a new scratch directory outside the PortOS checkout you start in: \`dir=$(mktemp -d) && gh repo clone ${cloneTarget} "$dir/repo"\`. Make every change in that clone; never edit, commit or push anything in the PortOS checkout.`,+ 'If Dependabot already opened a pull request that fixes an alert (author login exactly `dependabot[bot]`, head branch in this same repo, not a fork) and its checks pass, merge that pull request instead of writing your own. Never merge any other pull request you did not open.',+ 'Otherwise update each vulnerable dependency to a patched version (lockfiles included), run the repo\'s tests, and open one pull request from a new branch with all the fixes.',+ 'Wait for the checks. When they pass, squash-merge the pull request. If a fix needs a breaking upgrade you cannot make safely, or a check fails for a reason you cannot fix, leave the pull request open and say why in it.',+ 'Delete the scratch directory when you are done.',+];++function buildPrompt({ host, login, repo, advisories }) {+ const gh = `gh api --hostname ${host}`;+ const as = login ? ` gh is signed in as ${login} on ${host}.` : '';+ if (repo) {+ const steps = [+ `List the open Dependabot alerts: \`${gh} "repos/${repo}/dependabot/alerts?state=open&per_page=100"\`. If there are none, stop and report that.`,+ ...SCRATCH_STEPS(host === 'github.com' ? repo : `${host}/${repo}`),+ ];+ return [+ `Fix the open security alerts in ${host}/${repo}`,+ '',+ `GitHub reported security vulnerabilities in the dependencies of ${repo}, a repository of yours that no PortOS app manages.${as}`,+ '',+ ...steps.map((step, index) => `${index + 1}. ${step}`),+ '',+ 'Finish by reporting each pull request link and any alert you could not fix.',+ ].join('\n');+ }+ const ids = advisories.join(', ');+ const select = advisories.map((id) => `.security_advisory.ghsa_id == "${id}"`).join(' or ');+ const steps = [+ `Find the repositories these advisories affect: list your repositories with \`${gh} "user/repos?affiliation=owner&per_page=100" --paginate --jq '.[] | select(.archived | not) | .full_name'\`, then for each one \`${gh} "repos/<repo>/dependabot/alerts?state=open&per_page=100" --jq '[.[] | select(${select})] | length'\`. Skip a repo whose alerts are not readable. If none is affected, stop and report that.`,+ 'For each affected repository, in turn:',+ ...SCRATCH_STEPS('<repo>').map((step) => ` - ${step}`),+ ];+ return [+ `Fix security advisories ${ids} across your ${host} repositories`,+ '',+ `GitHub reported that ${advisories.length === 1 ? 'a security advisory affects' : 'security advisories affect'} at least one of your repositories: ${ids}.${as}`,+ '',+ ...steps.map((step, index) => (step.startsWith(' ') ? step : `${index + 1}. ${step}`)),+ '',+ 'Finish by reporting each pull request link and any affected repository you could not fix.',+ ].join('\n');+}++/**+ * Queue one security-fix run for a repo (`repo`) or for a set of global+ * advisories (`advisories`). Returns `{ taskId }`, `{ duplicate: true, taskId }`+ * when the same run is already queued or running, or `{ error }`.+ */+export async function queueSecurityFixTask({ account, repo = null, advisories = [], origin = 'automation' }) {+ if (!HOST_RE.test(account?.host || '')) return { error: 'Invalid account host' };+ const login = LOGIN_RE.test(account.login || '') ? account.login : null;+ if (repo !== null && !REPO_RE.test(repo)) return { error: 'Invalid repository name' };+ const ids = [...new Set(advisories.filter((id) => GHSA_RE.test(id)))].sort();+ if (!repo && !ids.length) return { error: 'No repository or advisory to fix' };+ const task = await addTask({+ description: buildPrompt({ host: account.host, login, repo, advisories: ids }),+ priority: 'HIGH',+ // The deliverable is a pull request on another repo, made from a scratch+ // clone during the run: no PortOS worktree, and a clean PortOS tree is success.+ useWorktree: false,+ openPR: false,+ noCodeOutput: true,+ worktreeChangesExpected: false,+ metadata: { githubSecurityFix: { host: account.host, repo, advisories: ids, origin } },+ }, 'user');+ if (!task?.id) return { error: 'The task could not be queued' };+ return task.duplicate ? { duplicate: true, taskId: task.id } : { taskId: task.id };+}