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
fix: require complete current assessments before queued PR actions (#7896)
Adam Eivy4d031b52792c
diff --git a/server/lib/prReviewContent.js b/server/lib/prReviewContent.jsindex c9d6ec8f08..ba8fd39d85 100644--- a/server/lib/prReviewContent.js+++ b/server/lib/prReviewContent.js@@ -27,7 +27,7 @@import { modelAbuseContentFingerprint } from './modelAbuseGuard.js';-const MAX_COMMIT_LOG_CHARS = 100_000;+const LEGACY_MAX_COMMIT_LOG_CHARS = 100_000;const text = (value) => (typeof value === 'string' ? value : '');@@ -36,13 +36,13 @@ const text = (value) => (typeof value === 'string' ? value : '');* commit exactly as a reader of `git log` would see them, so an instruction* hidden in a commit body is scored as the text it is.*/-function formatCommitLog(commits) {+function formatCommitLog(commits, maxChars = Infinity) {if (!Array.isArray(commits) || commits.length === 0) return '';const log = commits.map((commit) => [text(commit?.messageHeadline), text(commit?.messageBody)].filter(Boolean).join('\n')).filter(Boolean).join('\n\n');- return log.length > MAX_COMMIT_LOG_CHARS ? log.slice(0, MAX_COMMIT_LOG_CHARS) : log;+ return log.slice(0, maxChars);}/**@@ -57,7 +57,10 @@ function formatCommitLog(commits) {* the row.*/export function screenedPullRequestContent(pr, diff, commits = pr?.commits) {- const commitLog = formatCommitLog(commits);+ return pullRequestContent(pr, diff, formatCommitLog(commits));+}++function pullRequestContent(pr, diff, commitLog) {return ['Pull request title:',text(pr?.title),@@ -90,7 +93,7 @@ export function screenedPullRequestContent(pr, diff, commits = pr?.commits) {* Changing `screenedPullRequestContent` means bumping this AND adding the* outgoing recipe to `FINGERPRINT_RECIPES`, in the same commit.*/-export const SCREENED_PR_FINGERPRINT_VERSION = 2;+export const SCREENED_PR_FINGERPRINT_VERSION = 3;/*** Every recipe PortOS has ever stamped with, by version. A stamp names its own@@ -111,7 +114,10 @@ const FINGERPRINT_RECIPES = Object.freeze({1: (pr, diff) => screenedPullRequestContent(pr, diff, []),// v2 (#7323): + the commit log, so an instruction hidden in a commit body is// both screened and watched for change.- 2: (pr, diff, commits) => (Array.isArray(commits) ? screenedPullRequestContent(pr, diff, commits) : null),+ 2: (pr, diff, commits) => (Array.isArray(commits)+ ? pullRequestContent(pr, diff, formatCommitLog(commits, LEGACY_MAX_COMMIT_LOG_CHARS)) : null),+ // v3: complete commit messages; oversized evidence is refused by the screen.+ 3: (pr, diff, commits) => (Array.isArray(commits) ? screenedPullRequestContent(pr, diff, commits) : null),});// A version with no recipe could only stamp fingerprints nothing can everdiff --git a/server/lib/prReviewContent.test.js b/server/lib/prReviewContent.test.jsindex c2dec3616e..0181468de0 100644--- a/server/lib/prReviewContent.test.js+++ b/server/lib/prReviewContent.test.js@@ -1,4 +1,5 @@import { describe, it, expect } from 'vitest';+import { modelAbuseContentFingerprint } from './modelAbuseGuard.js';import {SCREENED_PR_FINGERPRINT_VERSION,isScreenedPullRequestFingerprint,@@ -97,3 +98,17 @@ describe('screenedPullRequestContent', () => {expect(screenedPullRequestContent(PR, DIFF, COMMITS)).toContain('Commit messages:');});});++it('covers a commit tail past the old limit while retaining the v2 recipe', () => {+ const commits = [{ messageHeadline: 'x'.repeat(100_001) + 'TAIL' }];+ const content = screenedPullRequestContent(PR, DIFF, commits);+ expect(content).toContain('TAIL');+ const stamp = screenedPullRequestFingerprint(PR, DIFF, commits);+ const edited = [{ messageHeadline: 'x'.repeat(100_001) + 'EDIT' }];+ expect(screenedPullRequestFingerprintMatches(stamp, PR, DIFF, edited)).toBe(false);+ const legacyContent = content.replace(commits[0].messageHeadline, 'x'.repeat(100_000));+ const v2 = '2:' + modelAbuseContentFingerprint('pull-request',+ { number: PR.number, headSha: PR.headRefOid }, legacyContent);+ expect(screenedPullRequestFingerprintMatches(v2, PR, DIFF, commits)).toBe(true);+ expect(screenedPullRequestFingerprintMatches(v2, { ...PR, body: 'edited' }, DIFF, commits)).toBe(false);+});diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.jsindex 6fa53b78d8..21cbea01e4 100644--- a/server/services/issueWatcher.js+++ b/server/services/issueWatcher.js@@ -31,7 +31,7 @@ import { mergePR, resolveForgeForRepo } from './git.js';import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';import { normalizeEligibilityFacts } from './modelAbuseGuard.js';import { issuePrerequisiteWaived, linkedIssueIntentFingerprint } from '../lib/modelAbuseGuard.js';-import { screenedPullRequestContent, screenedPullRequestFingerprintMatches } from '../lib/prReviewContent.js';+import { screenedPullRequestFingerprintMatches } from '../lib/prReviewContent.js';import { trimTo } from '../lib/textUtils.js';const IN_PROGRESS_LABEL_SPEC = dispatchLabelSpec(IN_PROGRESS_LABEL);@@ -128,10 +128,10 @@ async function resolveContext(app) {const repoSpec = githubRepoSpec(origin);const host = githubApiHost(origin?.host);if (!repoSpec || !host || !origin?.fullName) return null;- const reachable = await ensureForgeReachable('issue-watcher', { hostname: host });- if (!reachable.ok) return null;- const forge = await resolveForgeForRepo(app.repoPath).catch(() => null);+ const forge = await resolveForgeForRepo(app.repoPath, { forgeAccount: app.forgeAccount || null }).catch(() => null);if (!forge || forge.cli !== 'gh') return null;+ const reachable = await ensureForgeReachable('issue-watcher', { hostname: host, env: forge.env });+ if (!reachable.ok) return null;return {cwd: app.repoPath,env: forge.env,@@ -625,10 +625,9 @@ async function eligibilityFactsStillCurrent(ctx, pr, target) {const expected = normalizeEligibilityFacts(target?.eligibilityFacts);const authorLogin = typeof target?.authorLogin === 'string' ? target.authorLogin.trim() : '';if (!authorLogin || !sameLogin(pr?.author?.login, authorLogin)) return false;- // A waived prerequisite (the maintainer's explicit request) cannot go stale,- // so only the author identity is rechecked for it; re-requiring an open- // linked issue here would silently skip every action on a PR with none.- if (issuePrerequisiteWaived(expected)) return true;+ // A targeted request waives the prerequisite, never intent already assessed.+ const waived = issuePrerequisiteWaived(expected);+ if (waived && !expected.intentFingerprint) return true;if (!expected.issueLookupComplete) return false;if (expected.linkedIssueNumbers.length === 0) return false;@@ -652,10 +651,10 @@ async function eligibilityFactsStillCurrent(ctx, pr, target) {openerAssignedIssueNumbers,issueLookupComplete: true,});- if (!sameNumberList(expected.linkedIssueNumbers, actual.linkedIssueNumbers)+ if (!waived && (!sameNumberList(expected.linkedIssueNumbers, actual.linkedIssueNumbers)|| !sameNumberList(expected.openLinkedIssueNumbers, actual.openLinkedIssueNumbers)|| !sameNumberList(expected.openerAssignedIssueNumbers, actual.openerAssignedIssueNumbers)- || expected.issueLookupComplete !== actual.issueLookupComplete) return false;+ || expected.issueLookupComplete !== actual.issueLookupComplete)) return false;// The gate judged the diff against the issue text as it read at scan time. A// requirement that was rewritten since is a different requirement, so the old@@ -893,7 +892,8 @@ async function processPendingApprovals(app, ctx) {changed = true;continue;}- if (!await currentPullRequestSecurityPasses(pr, approvedDiff)) {+ const assessment = await assessCurrentPullRequest(ctx, pr, approvedDiff);+ if (!assessment.ok) {await keepPendingApproval(app, approval, remaining, 'the current security-model assessment did not pass');changed = true;continue;@@ -912,7 +912,7 @@ async function processPendingApprovals(app, ctx) {continue;}if (behindBy > 0) {- if (await updatePullRequestBranch(ctx, pr.number, pr.headRefOid)) changed = true;+ if (await assessment.stillCurrent() && await updatePullRequestBranch(ctx, pr.number, pr.headRefOid)) changed = true;else {await keepPendingApproval(app, approval, remaining, 'its required rebase could not be applied', { ctx, pr, tracker: handbacks });changed = true;@@ -944,8 +944,8 @@ async function processPendingApprovals(app, ctx) {&& checkRollup.length === 0&& approval.noChecksObserved === true;const mayMerge = checks === 'green' || maySkipEmptyChecks;- if (mayMerge && pr.mergeable === 'MERGEABLE') {- const merged = await mergePR(app.repoPath, approval.number, { expectedHeadSha: approval.headSha }).catch(() => ({ success: false }));+ if (mayMerge && pr.mergeable === 'MERGEABLE' && await assessment.stillCurrent()) {+ const merged = await mergePR(app.repoPath, approval.number, { expectedHeadSha: approval.headSha, forgeAccount: app.forgeAccount || null }).catch(() => ({ success: false }));if (merged.success) {changed = true;continue;@@ -1279,8 +1279,8 @@ async function readCurrentIssueComment(ctx, item) {};}-async function submitReview(ctx, number, { body, event, comments = [] }) {- const input = JSON.stringify({ body: trimTo(body, MAX_REVIEW_BODY_CHARS), event, comments });+async function submitReview(ctx, number, headSha, { body, event, comments = [] }) {+ const input = JSON.stringify({ commit_id: headSha, body: trimTo(body, MAX_REVIEW_BODY_CHARS), event, comments });return runGh([...apiArgs(ctx, `repos/${ctx.repoFullName}/pulls/${number}/reviews`, { method: 'POST' }), '--input', '-'], ctx, input).then(() => true).catch((err) => {@@ -1334,10 +1334,14 @@ function createDropLog() {};}-async function currentPullRequestSecurityPasses(pr, diff) {- const { screenUntrustedContent } = await import('./untrustedContent.js');- const result = await screenUntrustedContent({ content: screenedPullRequestContent(pr, diff), source: 'github-pr' });- return result.ok === true && result.screening?.safe === true;+async function assessCurrentPullRequest(ctx, pr, diff) {+ const { assessPullRequestForAction } = await import('./prReviewerSecurity.js');+ return assessPullRequestForAction({+ pr, diff, repoFullName: ctx.repoFullName,+ readPr: () => readPullRequest(ctx, pr.number),+ readDiff: () => runGh(['pr', 'diff', String(pr.number), '--repo', ctx.repoSpec], ctx).catch(() => null),+ readIssue: (number) => runJson(apiArgs(ctx, `repos/${ctx.repoFullName}/issues/${number}`), ctx),+ }).catch(() => ({ ok: false }));}/**@@ -1373,10 +1377,11 @@ async function verifyScreenedPullRequest(ctx, raw, expectedPullRequests) {// `pr` rides along so the notification can still link to it.return { number, pr, reason: 'its content no longer matches what the security scan screened', notify: true };}- if (!await currentPullRequestSecurityPasses(pr, diff)) {+ const assessment = await assessCurrentPullRequest(ctx, pr, diff);+ if (!assessment.ok) {return { number, pr, reason: 'the current security-model assessment did not pass', notify: true };}- return { ok: true, decision, target, pr, diff };+ return { ok: true, decision, target, pr, diff, assessment };}/** Validated reply/review/rebase/merge pass run after cognition. */@@ -1460,10 +1465,14 @@ export async function processTaskOutput({ appId, success, payload, task, require}continue;}- const { decision, target, pr, diff } = verified;+ const { decision, target, pr, diff, assessment } = verified;const eligibilityRequired = requireEligibilityFacts|| Object.prototype.hasOwnProperty.call(target, 'eligibilityFacts');const eligibilityStillCurrent = async () => {+ if (!await assessment.stillCurrent()) {+ drops.record(decision.number, 'the assessed contribution or CI changed before action');+ return false;+ }if (!eligibilityRequired) return true;const current = await eligibilityFactsStillCurrent(ctx, pr, target);if (!current) {@@ -1501,9 +1510,9 @@ export async function processTaskOutput({ appId, success, payload, task, requiredowngraded,});const posted = shouldRequestChanges- ? await submitReview(ctx, pr.number, { body: summary, event: 'REQUEST_CHANGES', comments: findings })- || await submitReview(ctx, pr.number, { body: summary, event: 'COMMENT', comments: findings })- : await submitReview(ctx, pr.number, { body: summary, event: 'COMMENT', comments: findings })+ ? await submitReview(ctx, pr.number, pr.headRefOid, { body: summary, event: 'REQUEST_CHANGES', comments: findings })+ || await submitReview(ctx, pr.number, pr.headRefOid, { body: summary, event: 'COMMENT', comments: findings })+ : await submitReview(ctx, pr.number, pr.headRefOid, { body: summary, event: 'COMMENT', comments: findings })|| await postReviewFallback(ctx, pr.number, summary);if (!posted) {drops.record(decision.number, 'GitHub rejected the review comment');@@ -1529,11 +1538,11 @@ export async function processTaskOutput({ appId, success, payload, task, requirenonBlockingFindings: normalizedFindings,});if (!await eligibilityStillCurrent()) continue;- const approved = await submitReview(ctx, pr.number, {+ const approved = await submitReview(ctx, pr.number, pr.headRefOid, {body: approveBody,event: 'APPROVE',comments: findings,- }) || (findings.length > 0 && await submitReview(ctx, pr.number, {+ }) || (findings.length > 0 && await submitReview(ctx, pr.number, pr.headRefOid, {body: approveBody,event: 'APPROVE',}));@@ -1569,7 +1578,7 @@ export async function processTaskOutput({ appId, success, payload, task, requireconst mayMerge = pr.mergeable === 'MERGEABLE' && checks === 'green';if (mayMerge) {if (!await eligibilityStillCurrent()) continue;- const result = await mergePR(app.repoPath, pr.number, { expectedHeadSha: pr.headRefOid }).catch(() => ({ success: false }));+ const result = await mergePR(app.repoPath, pr.number, { expectedHeadSha: pr.headRefOid, forgeAccount: app.forgeAccount || null }).catch(() => ({ success: false }));if (result.success) {approvals = approvals.filter((entry) => entry.number !== pr.number);merged += 1;diff --git a/server/services/issueWatcher.test.js b/server/services/issueWatcher.test.jsindex 947ed5ccf3..b41b3a6b2d 100644--- a/server/services/issueWatcher.test.js+++ b/server/services/issueWatcher.test.js@@ -598,8 +598,8 @@ describe('processTaskOutput', () => {expect(result).toMatchObject({ reviewed: 1, merged: 1 });const reviewCall = execGhMock.mock.calls.find(([args]) => args.includes('repos/o/r/pulls/7/reviews') && args.includes('--input'));- expect(JSON.parse(reviewCall[2].input)).toMatchObject({ event: 'APPROVE', comments: [] });- expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40) });+ expect(JSON.parse(reviewCall[2].input)).toMatchObject({ event: 'APPROVE', comments: [], commit_id: 'a'.repeat(40) });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40), forgeAccount: null });});it.each([@@ -704,7 +704,7 @@ describe('processTaskOutput', () => {});expect(result).toMatchObject({ reviewed: 1, merged: 1 });- expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40) });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40), forgeAccount: null });expect(execGhMock.mock.calls.some(([args]) => (args[0] === 'api' && args.some((arg) => String(arg).endsWith('/issues/101'))))).toBe(true);@@ -713,7 +713,7 @@ describe('processTaskOutput', () => {// The gate approved this diff against the issue as it read at scan time. If// that requirement was rewritten since, the review answered a question nobody// is asking any more — so the approval is discarded rather than merged.- it('discards an approval whose linked issue was rewritten after the gate judged it', async () => {+ it.each([false, true])('discards rewritten linked intent (maintainerTargeted=%s)', async (maintainerTargeted) => {const issue = {number: 101,state: 'open',@@ -730,6 +730,7 @@ describe('processTaskOutput', () => {...eligibilityMetadata.issueWatcher.pullRequests[0],eligibilityFacts: {...eligibilityFacts,+ maintainerTargeted,intentFingerprint: linkedIssueIntentFingerprint([{number: 101, title: 'Crash on empty import', body: 'Importing an empty file throws.',}]),@@ -802,7 +803,7 @@ describe('processTaskOutput', () => {body: '💡 **Non-blocking**\n\nConsider making this helper name more specific in a follow-up.',}],});- expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40) });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40), forgeAccount: null });});it('approves without inline comments when GitHub rejects the comment anchors', async () => {@@ -838,8 +839,8 @@ describe('processTaskOutput', () => {expect(result).toMatchObject({ reviewed: 1, merged: 1 });const reviewCalls = execGhMock.mock.calls.filter(([args]) => args.includes('repos/o/r/pulls/7/reviews') && args.includes('--input'));expect(reviewCalls).toHaveLength(2);- expect(JSON.parse(reviewCalls[1][2].input)).toMatchObject({ event: 'APPROVE', comments: [] });- expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40) });+ expect(JSON.parse(reviewCalls[1][2].input)).toMatchObject({ event: 'APPROVE', comments: [], commit_id: 'a'.repeat(40) });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40), forgeAccount: null });});it('treats a finding with no explicit blocking flag as blocking and does not merge', async () => {@@ -919,6 +920,59 @@ describe('processTaskOutput', () => {expect(execGhMock.mock.calls.some(([args]) => args.includes('--disable-auto'))).toBe(true);});+ it.each(['review', 'queued merge'])('withholds %s when linked intent changes during assessment', async (action) => {+ const pr = pullRequest({ body: 'Closes #101' });+ const issue = { number: 101, state: 'open', title: 'Example request', body: 'Preserve private access.', assignees: [] };+ installDefaultGhMock({ pr, issueDetails: { 101: issue } });+ const contentFingerprint = screenedPullRequestFingerprint(pr, DIFF);+ const target = { number: 7, headSha: pr.headRefOid, contentFingerprint };+ runModelAbuseScanMock.mockImplementation(async ({ content }) => {+ if (content.includes('Linked issue #101')) issue.body = 'Rewritten during inference';+ return { ok: true, safe: true, findings: [] };+ });+ if (action === 'review') {+ const result = await processTaskOutput({ appId: APP.id, success: true,+ task: { metadata: { issueWatcher: { ...metadata.issueWatcher, pullRequests: [target] } } },+ payload: { issueComments: [], pullRequests: [{+ number: 7, headSha: pr.headRefOid, verdict: 'approve', summary: 'Reviewed.',+ findings: [], rebaseRequired: false, ciPolicy: 'required',+ }] },+ });+ expect(result).toMatchObject({ reviewed: 0, merged: 0 });+ } else {+ apps.set(APP.id, { ...APP, issueWatcherState: { approvedPullRequests: [{+ ...target, ciPolicy: 'required', ticks: 0,+ }] } });+ await buildTaskInput({ app: apps.get(APP.id) });+ expect(apps.get(APP.id).issueWatcherState.approvedPullRequests).toHaveLength(1);+ }+ expect(runModelAbuseScanMock).toHaveBeenCalledWith(expect.objectContaining({+ content: expect.stringContaining('Preserve private access.'),+ }));+ expect(execGhMock.mock.calls.some(([args]) => args.includes('repos/o/r/pulls/7/reviews') && args.includes('--input'))).toBe(false);+ expect(mergePrMock).not.toHaveBeenCalled();+ });++ it('does not merge if the PR body changes while its pinned review is posted', async () => {+ const pr = pullRequest();+ installDefaultGhMock({ pr });+ const forgeRead = execGhMock.getMockImplementation();+ execGhMock.mockImplementation((args, ...rest) => {+ if (args.includes('repos/o/r/pulls/7/reviews') && args.includes('--input')) pr.body = 'Changed after assessment';+ return forgeRead(args, ...rest);+ });+ const result = await processTaskOutput({ appId: APP.id, success: true, task: { metadata }, payload: {+ issueComments: [], pullRequests: [{+ number: 7, headSha: pr.headRefOid, verdict: 'approve', summary: 'Reviewed.',+ findings: [], rebaseRequired: false, ciPolicy: 'required',+ }],+ } });+ expect(result).toMatchObject({ reviewed: 1, merged: 0 });+ const reviewCall = execGhMock.mock.calls.find(([args]) => args.includes('repos/o/r/pulls/7/reviews') && args.includes('--input'));+ expect(JSON.parse(reviewCall[2].input).commit_id).toBe('a'.repeat(40));+ expect(mergePrMock).not.toHaveBeenCalled();+ });+it('retains an armed legacy auto-merge when revocation fails beyond the normal polling budget', async () => {installDefaultGhMock();const forgeRead = execGhMock.getMockImplementation();@@ -952,6 +1006,22 @@ describe('processTaskOutput', () => {]);});+ it('uses the owning account for pending approval reads and the pinned merge', async () => {+ installDefaultGhMock();+ apps.set(APP.id, { ...APP, forgeAccount: 'example-maintainer', issueWatcherState: {+ approvedPullRequests: [{+ number: 7, headSha: 'a'.repeat(40),+ contentFingerprint: screenedPullRequestFingerprint(pullRequest(), DIFF), ciPolicy: 'required',+ }],+ } });+ mergePrMock.mockResolvedValue({ success: true });+ await buildTaskInput({ app: apps.get(APP.id) });+ expect(resolveForgeForRepoMock).toHaveBeenCalledWith(APP.repoPath, { forgeAccount: 'example-maintainer' });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, {+ expectedHeadSha: 'a'.repeat(40), forgeAccount: 'example-maintainer',+ });+ });+it('waits one scheduled observation before treating absent CI as skippable', async () => {installDefaultGhMock({ pr: pullRequest({ statusCheckRollup: [] }) });mergePrMock.mockResolvedValue({ success: true });@@ -978,7 +1048,7 @@ describe('processTaskOutput', () => {const followUp = await buildTaskInput({ app: apps.get(APP.id) });expect(followUp).toEqual({ skip: { reason: 'baselined' } });- expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40) });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40), forgeAccount: null });expect(apps.get(APP.id).issueWatcherState.approvedPullRequests).toEqual([]);});@@ -1011,7 +1081,7 @@ describe('processTaskOutput', () => {reviews: [[{ user: { login: 'owner' }, commit_id: 'a'.repeat(40), state: 'APPROVED' }]],});await buildTaskInput({ app: apps.get(APP.id) });- expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40) });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40), forgeAccount: null });});it('does not release CI for a PR it did not approve', async () => {@@ -1120,7 +1190,7 @@ describe('processTaskOutput', () => {await buildTaskInput({ app: apps.get(APP.id) });- expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40) });+ expect(mergePrMock).toHaveBeenCalledWith(APP.repoPath, 7, { expectedHeadSha: 'a'.repeat(40), forgeAccount: null });expect(apps.get(APP.id).issueWatcherState.approvedPullRequests).toEqual([]);});diff --git a/server/services/prReviewerSecurity.js b/server/services/prReviewerSecurity.jsindex a7416644fb..6918594768 100644--- a/server/services/prReviewerSecurity.js+++ b/server/services/prReviewerSecurity.js@@ -50,7 +50,7 @@ function issueNumbersFromText(value, repoFullName) {// unrelated cross-repo issue cannot become an eligibility fact.const referencePattern = /(?:\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|relate[sd]?\s+to|ref(?:s)?|part\s+of)\s+)?(?:(?:[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\s*)?#(\d+)/gi;let match;- while ((match = referencePattern.exec(value)) && numbers.size < MAX_LINKED_ISSUES) {+ while ((match = referencePattern.exec(value)) && numbers.size <= MAX_LINKED_ISSUES) {const qualified = match[0].match(/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\s*#\d+$/i)?.[1];if (qualified && qualified.toLowerCase() !== repo) continue;const number = Number(match[1]);@@ -63,7 +63,7 @@ export function extractLinkedIssueNumbers(pr, repoFullName) {return [...new Set([...issueNumbersFromText(pr?.title, repoFullName),...issueNumbersFromText(pr?.body, repoFullName),- ])].sort((a, b) => a - b).slice(0, MAX_LINKED_ISSUES);+ ])].sort((a, b) => a - b).slice(0, MAX_LINKED_ISSUES + 1);}/**@@ -72,7 +72,12 @@ export function extractLinkedIssueNumbers(pr, repoFullName) {* issues contribute intent — a closed issue is not a live requirement, and the* pre-action recheck recomputes the fingerprint from the same open set.*/-async function resolveEligibilityFacts(pr, repoFullName, hostname) {+async function resolveEligibilityFacts(pr, repoFullName, hostname, readIssue = async (number) => {+ const raw = await execGh([+ 'api', '--hostname', hostname, `repos/${repoFullName}/issues/${number}`,+ ]).catch(() => null);+ return safeJSONParse(raw, null);+}) {const linkedIssueNumbers = extractLinkedIssueNumbers(pr, repoFullName);if (linkedIssueNumbers.length === 0) {return {@@ -87,15 +92,15 @@ async function resolveEligibilityFacts(pr, repoFullName, hostname) {inputComplete: true,};}+ if (linkedIssueNumbers.length > MAX_LINKED_ISSUES) {+ return { facts: { issueLookupComplete: false }, linkedIssues: [], inputComplete: false };+ }const openLinkedIssueNumbers = [];const openerAssignedIssueNumbers = [];const openIssues = [];let issueLookupComplete = true;for (const issueNumber of linkedIssueNumbers) {- const raw = await execGh([- 'api', '--hostname', hostname, `repos/${repoFullName}/issues/${issueNumber}`,- ]).catch(() => null);- const issue = safeJSONParse(raw, null);+ const issue = await readIssue(issueNumber);if (!issue || issue.number !== issueNumber) {issueLookupComplete = false;continue;@@ -126,6 +131,50 @@ async function resolveEligibilityFacts(pr, repoFullName, hostname) {};}+/**+ * Assess the complete current contribution, then re-read after inference. Both+ * automated merge queues use this boundary; the caller supplies forge readers+ * so every read retains the owning app's account and host.+ *+ * stillCurrent performs no inference and can be called again after a review or+ * another network action. A verdict never authorizes a changed head, mutable+ * description, linked intent, or CI observation.+ */+export async function assessPullRequestForAction({ pr, diff, repoFullName, readPr, readDiff, readIssue }) {+ const fingerprint = screenedPullRequestFingerprint(pr, diff);+ if (!fingerprint || !isHeadRefOid(pr?.headRefOid) || typeof diff !== 'string' || !diff.trim()) {+ return failure('security-action-evidence-unavailable');+ }+ const readIntent = (row) => resolveEligibilityFacts(+ { ...row, authorLogin: row.author?.login }, repoFullName, null, readIssue,+ );+ const intent = await readIntent(pr);+ if (!intent.inputComplete || !intent.facts.issueLookupComplete) return failure('security-action-intent-unavailable');+ const content = [screenedPullRequestContent(pr, diff), linkedIssueIntentContent(intent.linkedIssues)]+ .filter(Boolean).join('\n\n');+ if (content.length > SECURITY_SCAN_MAX_DIFF_CHARS) return failure('security-action-input-too-large');+ const screened = await screenUntrustedContent({ content, source: 'github-pr' });+ if (screened?.ok !== true || screened.screening?.safe !== true) return failure('security-action-assessment-withheld');++ const actionState = (row) => JSON.stringify({+ state: row.state, isDraft: row.isDraft, author: row.author?.login,+ baseRefName: row.baseRefName, baseRefOid: row.baseRefOid,+ mergeable: row.mergeable, mergeStateStatus: row.mergeStateStatus,+ checks: row.statusCheckRollup,+ });+ const stillCurrent = async () => {+ const [current, currentDiff] = await Promise.all([readPr(), readDiff()]);+ if (!current || typeof currentDiff !== 'string'+ || screenedPullRequestFingerprint(current, currentDiff) !== fingerprint+ || actionState(current) !== actionState(pr)) return false;+ const currentIntent = await readIntent(current);+ return currentIntent.inputComplete && currentIntent.facts.issueLookupComplete+ && JSON.stringify(currentIntent.facts) === JSON.stringify(intent.facts);+ };+ if (!await stillCurrent()) return failure('security-action-evidence-changed');+ return { ok: true, stillCurrent };+}+/*** The three facts that decide which of a repo's open PRs pr-reviewer may target:* the `gh` repo selector, the default branch it reviews against, and the logindiff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex d718b3612f..807d2485e2 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -301,7 +301,7 @@ export function isPendingMergeReady(prView) {async function readPendingPullRequest(repoSpec, prNumber, { cwd, env } = {}) {const raw = await execGh(['pr', 'view', String(prNumber), '--repo', repoSpec,- '--json', 'state,mergeStateStatus,statusCheckRollup'+ '--json', 'number,title,body,commits,headRefOid,author,state,isDraft,baseRefName,baseRefOid,mergeable,mergeStateStatus,statusCheckRollup'], undefined, { cwd, env, backoffKey: repoSpec }).catch(() => null);const parsed = raw === null ? null : safeJSONParse(raw, null);return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;@@ -403,9 +403,25 @@ export async function processPendingMergePrs(app) {continue;}+ let withheldReason = null;if (isPendingMergeReady(prView)) {- const merge = await git.mergePR(app.repoPath, entry.prNumber, { forgeAccount: app?.forgeAccount || null })- .catch((err) => ({ success: false, error: err.message }));+ const { assessPullRequestForAction } = await import('./prReviewerSecurity.js');+ const readDiff = () => execGh(['pr', 'diff', String(entry.prNumber), '--repo', repoSpec],+ undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null);+ const assessment = await assessPullRequestForAction({+ pr: prView, diff: await readDiff(), repoFullName: origin.fullName,+ readPr: () => readPendingPullRequest(repoSpec, entry.prNumber, forgeExec),+ readDiff,+ readIssue: async (number) => safeJSONParse(await execGh([+ 'api', '--hostname', githubApiHost(origin.host), `repos/${origin.fullName}/issues/${number}`,+ ], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null), null),+ }).catch(() => ({ ok: false }));+ withheldReason = assessment.ok ? null : 'the complete current contribution assessment was unavailable or withheld';+ const merge = assessment.ok+ ? await git.mergePR(app.repoPath, entry.prNumber, {+ forgeAccount: app?.forgeAccount || null, expectedHeadSha: prView.headRefOid,+ }).catch((err) => ({ success: false, error: err.message }))+ : { success: false, error: withheldReason };if (merge.success) {outcomes.set(key, null);result.merged += 1;@@ -418,7 +434,7 @@ export async function processPendingMergePrs(app) {if (next.ticks >= MAX_PENDING_MERGE_TICKS) {const reason = String(prView.state || '').toUpperCase() !== 'OPEN'? `it is ${String(prView.state).toLowerCase()} rather than open`- : 'CI or mergeability did not settle';+ : withheldReason || 'CI or mergeability did not settle';await notifyPendingMergeTimeout(app, entry, reason);outcomes.set(key, null);result.timedOut += 1;diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.jsindex abbbfb650c..aa6923865b 100644--- a/server/services/prWatcher.test.js+++ b/server/services/prWatcher.test.js@@ -21,6 +21,10 @@ vi.mock('./forgeExecOptions.js', () => ({resolveForgeExecOptions: (...args) => resolveForgeExecOptionsMock(...args),}));+const screenMock = vi.fn();+vi.mock('./untrustedContent.js', () => ({+ screenUntrustedContent: (...args) => screenMock(...args),+}));const mergePrMock = vi.fn();vi.mock('./git.js', () => ({mergePR: (...args) => mergePrMock(...args),@@ -85,6 +89,7 @@ const pr = (number, login, extra = {}) => ({beforeEach(() => {execGhMock.mockReset();+ screenMock.mockReset().mockResolvedValue({ ok: true, screening: { safe: true } });ensureForgeReachableMock.mockReset();ensureForgeReachableMock.mockResolvedValue({ ok: true, status: 'ok', detail: null, remedy: null });mergePrMock.mockReset();@@ -188,6 +193,26 @@ const pendingApp = (entries = [pendingMerge()]) => ({pendingMergePrs: entries});++function installPendingEvidence() {+ const evidence = {+ pr: {+ number: 88, title: 'Fix example', body: 'Closes #101', headRefOid: 'a'.repeat(40),+ author: { login: 'contributor' }, commits: [{ messageHeadline: 'Complete commit', messageBody: '' }],+ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }],+ },+ issue: { number: 101, state: 'open', title: 'Example requirement', body: 'Preserve private access.', assignees: [] },+ diff: 'diff --git a/example.js b/example.js\n+const safe = true;',+ };+ execGhMock.mockImplementation(async (args) => {+ if (args[0] === 'pr' && args[1] === 'view') return JSON.stringify({ ...evidence.pr, number: Number(args[2]) });+ if (args[0] === 'pr' && args[1] === 'diff') return evidence.diff;+ if (args[0] === 'api' && args.includes('repos/o/r/issues/101')) return JSON.stringify(evidence.issue);+ throw new Error('Unexpected forge read');+ });+ return evidence;+}+describe('merge-only PR watcher', () => {beforeEach(() => {getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });@@ -218,23 +243,94 @@ describe('merge-only PR watcher', () => {it('merges a green pending PR without spawning a follow-up agent', async () => {const app = pendingApp();mockApps.set(app.id, app);- execGhMock.mockResolvedValueOnce(JSON.stringify({- state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]- }));+ installPendingEvidence();mergePrMock.mockResolvedValue({ success: true });const result = await processPendingMergePrs(app);expect(result).toMatchObject({ ok: true, checked: 1, merged: 1, escalated: 0 });- expect(mergePrMock).toHaveBeenCalledWith('/repos/app1', 88, { forgeAccount: 'other-account' });+ expect(mergePrMock).toHaveBeenCalledWith('/repos/app1', 88, { forgeAccount: 'other-account', expectedHeadSha: 'a'.repeat(40) });expect(spawnReviewLoopFollowUpMock).not.toHaveBeenCalled();expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);expect(execGhMock).toHaveBeenCalledWith(['pr', 'view', '88', '--repo', 'github.com/o/r',- '--json', 'state,mergeStateStatus,statusCheckRollup'+ '--json', 'number,title,body,commits,headRefOid,author,state,isDraft,baseRefName,baseRefOid,mergeable,mergeStateStatus,statusCheckRollup'], undefined, { cwd: '/repos/app1', env: PINNED_ENV, backoffKey: 'github.com/o/r' });});+ it.each([+ ['unavailable', { ok: false }],+ ['malformed', {}],+ ['uncertain', { ok: false, screening: { safe: false, layers: { securityModel: 'uncertain' } } }],+ ['incompatible', { ok: false, screening: { safe: false, layers: { securityModel: 'incompatible' } } }],+ ])('retains a ready PR when the contribution assessment is %s', async (_name, response) => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ installPendingEvidence();+ screenMock.mockResolvedValue(response);+ expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0 });+ expect(mergePrMock).not.toHaveBeenCalled();+ expect(readPendingMergePrs(mockApps.get(app.id))[0].ticks).toBe(1);+ });++ it.each([+ ['head', (e) => { e.pr.headRefOid = 'b'.repeat(40); }],+ ['title', (e) => { e.pr.title = 'Rewritten title'; }],+ ['body', (e) => { e.pr.body = 'Rewritten description'; }],+ ['intent', (e) => { e.issue.body = 'Changed requirement'; }],+ ['CI', (e) => { e.pr.statusCheckRollup = [{ status: 'IN_PROGRESS' }]; }],+ ])('withholds a queued merge when %s changes during inference', async (_name, mutate) => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ const evidence = installPendingEvidence();+ screenMock.mockImplementation(async () => {+ mutate(evidence);+ return { ok: true, screening: { safe: true } };+ });+ expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0 });+ expect(mergePrMock).not.toHaveBeenCalled();+ expect(readPendingMergePrs(mockApps.get(app.id))).toHaveLength(1);+ });++ it('screens complete commit tails and linked intent using the owning forge account', async () => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ const evidence = installPendingEvidence();+ evidence.pr.commits[0].messageBody = 'x'.repeat(100_001) + 'TAIL';+ mergePrMock.mockResolvedValue({ success: true });+ expect(await processPendingMergePrs(app)).toMatchObject({ merged: 1 });+ expect(screenMock).toHaveBeenCalledWith(expect.objectContaining({+ content: expect.stringContaining('TAIL'),+ }));+ expect(screenMock.mock.calls[0][0].content).toContain('Preserve private access.');+ for (const [, , options] of execGhMock.mock.calls) {+ expect(options).toMatchObject({ cwd: app.repoPath, env: PINNED_ENV });+ }+ });++ it.each(['commits', 'linked issues'])('refuses oversized complete %s before inference', async (surface) => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ const evidence = installPendingEvidence();+ if (surface === 'commits') evidence.pr.commits[0].messageBody = 'x'.repeat(2_000_001);+ else evidence.issue.body = 'x'.repeat(65_537);+ expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0 });+ expect(screenMock).not.toHaveBeenCalled();+ expect(mergePrMock).not.toHaveBeenCalled();+ });++ it('notifies and retires an unavailable assessment at the queue deadline', async () => {+ const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);+ mockApps.set(app.id, app);+ installPendingEvidence();+ screenMock.mockRejectedValue(new Error('Provider unavailable'));+ expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0, timedOut: 1 });+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({+ description: expect.stringContaining('assessment was unavailable or withheld'),+ }));+ expect(readPendingMergePrs(mockApps.get(app.id))).toEqual([]);+ });+it.each([['validation-failed', { state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'FAILURE' }] }],['merge-conflict', { state: 'OPEN', mergeStateStatus: 'DIRTY', statusCheckRollup: [{ conclusion: 'SUCCESS' }] }],@@ -318,9 +414,7 @@ describe('sweepPendingMergePrs', () => {// The sweep must not consult the task schedule at all.it('drains a pending merge for an app with no pr-watcher config', async () => {mockApps.set('app1', { ...pendingApp(), name: 'App One', prWatcherState: undefined });- execGhMock.mockResolvedValueOnce(JSON.stringify({- state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]- }));+ installPendingEvidence();mergePrMock.mockResolvedValue({ success: true });const totals = await sweepPendingMergePrs();@@ -348,9 +442,7 @@ describe('sweepPendingMergePrs', () => {});// app1 fails the forge check; app2 proceeds and merges.ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable' });- execGhMock.mockResolvedValueOnce(JSON.stringify({- state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]- }));+ installPendingEvidence();mergePrMock.mockResolvedValue({ success: true });const totals = await sweepPendingMergePrs();