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
simplify the screened-PR content boundary and make a dropped verdict visible
[._.]/ Adam Eivy37d7958fd41d
diff --git a/server/lib/README.md b/server/lib/README.mdindex 3dc77236a2..61a1e408d8 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -576,7 +576,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. || `prDisposition.js` | `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `prHandbackPolicy.js` | Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. `resolvePullRequestWriteAccess(pr)` reads `isCrossRepository`/`maintainerCanModify` into a `PR_WRITE_ACCESS` reason, failing closed on an unknown head-repository relationship; `resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted})` returns a `PR_HANDBACK` verdict — `remediate` (PortOS pushes the fixes and lands it), `assign-opener` (the PR goes to its author queue), or `none`. A deferred or unanchorable review never becomes an agent work order. Pure. |-| `prReviewContent.js` | The one definition of the external pull-request content PortOS screens — `pullRequestReviewContent({title, body, commits, diff})` builds the contributor-authored surface (commit log included, bounded by `MAX_COMMIT_LOG_CHARS`), `formatPullRequestCommitLog` renders that log, and `pullRequestReviewFingerprint` hashes the pair to a stable identity for one head commit. The pr-reviewer security preflight STAMPS this fingerprint and the deterministic coordinator RECOMPUTES it from a fresh forge read before it reviews, rebases, or merges, so the two must build the same bytes; when they drifted apart, every approved review was dropped with no log line at all. Never rebuild either shape at a call site. Pure. |+| `prReviewContent.js` | The one definition of the external pull-request content PortOS screens. `screenedPullRequestContent(pr, diff, commits?)` builds the contributor-authored surface — title, description, commit log, unified diff — and `screenedPullRequestFingerprint(pr, diff, commits?)` hashes it to a stable identity for one head commit, returning null when the commit log is missing rather than matching by omission. Both take the PR row, because the pr-reviewer preflight STAMPS that fingerprint and the coordinator RECOMPUTES it from a fresh forge read before it reviews, rebases, or merges: when the two hand-written field projections drifted apart, every approved review was dropped. Never rebuild either shape at a call site. Pure. || `prReviewReport.js` | Owns the structured PR-decision contract end to end: `PR_REVIEW_DECISION_CONTRACT` is the envelope both review producers (pr-reviewer stage 3, issue-watcher reasoning pass) interpolate into their prompts, `normalizeReviewReport` bounds what comes back, `reviewReportText` hands every model-authored string to the abuse scan, and `renderReviewBody`/`renderFinding` turn it into the markdown a human reads on the PR page — verdict banner, scope line, blocking/non-blocking index anchored to `path:line`, test-evidence bullets (`TEST_EVIDENCE_STATUSES` keeps `fail` for "the change is broken", with `expected-fail` and `blocked` for the non-zero exits that say nothing about it), notes, collapsed verified-claims list, and inline comments with an optional GitHub suggestion block. Bounded by `MAX_REVIEW_BODY_CHARS`, dropping whole low-priority sections instead of truncating mid-sentence. Pure. || `repoStateExpectations.js` | Post-completion repo-state audit, pure half. `resolveRepoStateExpectation({...})` answers whether one finished worktree agent should be audited — naming every not-audited path via `REPO_STATE_SKIPS` (a failed run is preserved for its retry; a review-loop follow-up or pr-watcher pending merge still owns the branch) — and returns just `staysOpen` + `prExpected`, from which `classifyRepoStateIssues(expectation, observed)` derives every check into `REPO_STATE_ISSUES` codes. Observations are tri-state: `null` ("could not ask") never produces an issue. `repoStateVerificationEnabled(app)` reads the per-app `verifyRepoStateOnCompletion` switch (unset = on). Probing + remediation live in `services/agentRepoStateVerification.js`. || `shellCd.js` | `buildCdCommand(path, shell)` + `formatShellCommandLine(command, args, shell)` + `detectShellFlavor(shell, platform?)` + `quoteForShell(value, flavor, position?)` — build `cd` and arbitrary command-token lines for the shell a PTY session is ACTUALLY running (`cmd.exe` → Windows-escaped double quotes, PowerShell → doubled single quotes with `&` for a quoted command token, everything else → POSIX `shellQuote`). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare `cd` does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. `formatShellCommandLine` joins a command + argv into one quoted line and is shared by `agentTuiSpawning.js#buildTuiSpawnConfig` and the AI Providers page's "Launch in Shell" deep link, so a hand-launched TUI provider is quoted exactly the way the CoS runner would quote it. Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in `tuiHandshake.js`. |diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex b8b9e4b3f7..f5c901671d 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -523,11 +523,10 @@ describe('deferred imports stay deferred (#6156)', () => {// closure adds nothing: it imports only `lib/modelAbuseGuard.js`, which every one// of those already had. There is no narrowing available, and deferring it would// defeat the point — the preflight STAMPS a content fingerprint that the-// coordinator RECOMPUTES before it acts, the check fails closed and silently, and-// two builders that drift apart disable review, CI approval, and merge for every-// external PR with no error anywhere. The contract test that pins the round trip-// reaches the coordinator through a call-site `await import()`, so it adds none of-// that service subtree.+// coordinator RECOMPUTES before it acts, the check fails closed, and two builders+// that drift apart disable review, CI approval, and merge for every external PR.+// Putting both halves in one pure leaf is what keeps the contract test out of the+// coordinator's service subtree entirely.const MAX_STATIC_INSTANTIATIONS = 104101;diff --git a/server/lib/prReviewContent.js b/server/lib/prReviewContent.jsindex d3b6d10b9b..da809f3477 100644--- a/server/lib/prReviewContent.js+++ b/server/lib/prReviewContent.js@@ -6,16 +6,20 @@* deterministic coordinator RECOMPUTES it from a fresh forge read immediately* before it reviews, rebases, or merges. A mismatch is the coordinator's only* defence against acting on content that changed after screening — and, because- * that check fails closed and silently, a divergence between the two builders- * does not look like a bug. It looks like the pipeline completing every stage- * and then doing nothing at all.+ * that check fails closed, a divergence between the two builders does not look+ * like a bug. It looks like the pipeline completing every stage and then doing+ * nothing at all.*- * That is exactly what happened when commit-message screening was added to the+ * That is what happened when commit-message screening was added to the* preflight's content (#7323): the coordinator kept hashing title+body+diff, so* every stamped fingerprint was unreachable and every approved review was- * dropped without a log line. Both sides now build the content here, and the- * "screened-content fingerprint contract" suite in- * `services/prReviewerSecurity.test.js` runs the real producer against the real+ * dropped. Note where the drift actually was — not in the hash, but in the two+ * hand-written PROJECTIONS of a PR row into the hashed fields. So these take+ * the row itself: adding the next screened field is one edit here, and no call+ * site can hold a different idea of what "the content" is.+ *+ * The "screened-content fingerprint contract" suite in+ * `services/prReviewerSecurity.test.js` runs the real preflight against this* consumer, rather than re-deriving the expected value from one of them.** Pure.@@ -23,7 +27,7 @@import { modelAbuseContentFingerprint } from './modelAbuseGuard.js';-export const MAX_COMMIT_LOG_CHARS = 100_000;+const MAX_COMMIT_LOG_CHARS = 100_000;const text = (value) => (typeof value === 'string' ? value : '');@@ -32,7 +36,7 @@ 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.*/-export function formatPullRequestCommitLog(commits) {+function formatCommitLog(commits) {if (!Array.isArray(commits) || commits.length === 0) return '';const log = commits.map((commit) => [text(commit?.messageHeadline), text(commit?.messageBody)].filter(Boolean).join('\n'))@@ -46,14 +50,19 @@ export function formatPullRequestCommitLog(commits) {* section a contributor controls belongs here: anything omitted is content a* reviewer would read but the guard never scored, and content the freshness* check would not notice changing.+ *+ * `commits` is separate only because the preflight reads it in its own call —+ * GitHub prices that field at a listing's LIMIT, so it cannot ride the bulk PR+ * listing. A row that already carries them (a single `gh pr view`) needs only+ * the row.*/-export function pullRequestReviewContent({ title, body, commits, diff } = {}) {- const commitLog = formatPullRequestCommitLog(commits);+export function screenedPullRequestContent(pr, diff, commits = pr?.commits) {+ const commitLog = formatCommitLog(commits);return ['Pull request title:',- text(title),+ text(pr?.title),'Pull request description:',- text(body),+ text(pr?.body),...(commitLog ? ['Commit messages:', commitLog] : []),'Complete unified diff:',text(diff),@@ -62,13 +71,16 @@ export function pullRequestReviewContent({ title, body, commits, diff } = {}) {/*** Stable identity for the exact PR content screened at a given head commit.- * Returns null when the identity is unusable, so a caller can never compare- * against a fingerprint that silently stands for "nothing".+ *+ * Null when the commit log is missing, rather than a fingerprint standing for a+ * smaller surface than the one that was stamped: a caller comparing against a+ * stamped value must fail closed, never match by omission.*/-export function pullRequestReviewFingerprint({ number, headSha, title, body, commits, diff } = {}) {+export function screenedPullRequestFingerprint(pr, diff, commits = pr?.commits) {+ if (!Array.isArray(commits)) return null;return modelAbuseContentFingerprint('pull-request',- { number, headSha },- pullRequestReviewContent({ title, body, commits, diff }),+ { number: pr?.number, headSha: pr?.headRefOid },+ screenedPullRequestContent(pr, diff, commits),);}diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.jsindex 515bf89a1e..4e593f5408 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 { pullRequestReviewContent, pullRequestReviewFingerprint } from '../lib/prReviewContent.js';+import { screenedPullRequestFingerprint } from '../lib/prReviewContent.js';import { trimTo } from '../lib/textUtils.js';const IN_PROGRESS_LABEL_SPEC = dispatchLabelSpec(IN_PROGRESS_LABEL);@@ -492,7 +492,7 @@ async function gatherIssueComments(ctx, { since, trust, state }) {commentAuthor: author, commentBody: '', commentUrl: issue.html_url || null,claimRequest: false, claimAssignable: false,};- const fingerprint = abuseFingerprint('issue-comment', item, issueAbuseInput(item));+ const fingerprint = abuseFingerprint(item, issueAbuseInput(item));if (state.issueSnapshots?.[issue.number] !== fingerprint) comments.push(item);}const issueComments = await listPaginated(ctx, `repos/${ctx.repoFullName}/issues/${issue.number}/comments`, [@@ -574,7 +574,7 @@ async function readPullRequest(ctx, number) {// a fork's head branch actually lives, which is what lets the remediation// agent's worktree attach to it at all (#6064). `assignees` keeps that// assignment idempotent across scheduled sweeps. `commits` is part of the- // screened content, so `pullRequestContentFingerprint` cannot verify a PR+ // screened content, so `screenedPullRequestFingerprint` cannot verify a PR// read without it — safe to ask for on a single PR, unlike the bulk listing// the preflight has to keep it out of (GraphQL node budget).'--json', 'id,number,title,body,url,state,isDraft,author,assignees,labels,commits,files,additions,deletions,baseRefName,baseRefOid,headRefName,headRefOid,isCrossRepository,maintainerCanModify,headRepository,headRepositoryOwner,mergeable,mergeStateStatus,statusCheckRollup',@@ -701,56 +701,30 @@ const issueAbuseInput = (item) => ['External comment:', item.commentBody,].join('\n\n');-const pullRequestAbuseInput = (item) => pullRequestReviewContent({- title: item.title, body: item.body, commits: item.commits, diff: item.diff,-});--function abuseFingerprint(kind, item, content) {- const identity = kind === 'issue-comment'- ? { kind, issueNumber: item.issueNumber, commentId: item.commentId }- : { kind, number: item.number, headSha: item.headSha };- return modelAbuseContentFingerprint(kind, identity, content);-}--/**- * Stable identity for the exact PR content screened by the model-abuse- * boundary. The output hook compares this with a fresh forge read before it can- * review, rebase, or merge anything.- *- * The commit log is part of that content, so `pr.commits` must carry the same- * commits the preflight screened — `readPullRequest` asks for them. A PR read- * without them yields null rather than a fingerprint that stands for a smaller- * surface than the one that was stamped.- */-export function pullRequestContentFingerprint(pr, diff) {- if (!Array.isArray(pr?.commits)) return null;- return pullRequestReviewFingerprint({- number: pr?.number,- headSha: pr?.headSha || pr?.headRefOid,- title: pr?.title,- body: pr?.body,- commits: pr.commits,- diff,- });+// Only issue comments reach the abuse screen here; external PR intake belongs+// exclusively to pr-reviewer, which stamps its own fingerprint.+function abuseFingerprint(item, content) {+ const kind = 'issue-comment';+ return modelAbuseContentFingerprint(kind, { kind, issueNumber: item.issueNumber, commentId: item.commentId }, content);}-function modelAbuseReport(kind, item, fingerprint, verdict) {+function modelAbuseReport(item, fingerprint, verdict) {const report = {- kind,+ kind: 'issue-comment',fingerprint,safe: verdict.safe === true,code: verdict.code || null,findingCount: Array.isArray(verdict.findings) ? verdict.findings.length : 0,findings: Array.isArray(verdict.findings) ? verdict.findings : [],guardId: verdict.guardId || MODEL_ABUSE_GUARD_ID,- ...(kind === 'issue-comment'- ? { issueNumber: item.issueNumber, commentId: item.commentId, commentUrl: item.commentUrl || null }- : { number: item.number, headSha: item.headSha, url: item.url || null }),+ issueNumber: item.issueNumber,+ commentId: item.commentId,+ commentUrl: item.commentUrl || null,};return report;}-async function screenModelAbuseInputs({ app, state, issueComments, pullRequests }) {+async function screenModelAbuseInputs({ app, state, issueComments }) {const previous = new Map((Array.isArray(state.modelAbuse?.blocked) ? state.modelAbuse.blocked : []).filter((report) => report?.fingerprint && report.safe !== true)@@ -759,29 +733,25 @@ async function screenModelAbuseInputs({ app, state, issueComments, pullRequestsconst blocked = [];const newBlocked = [];const safeComments = [];- const safePullRequests = [];const safeCommentFingerprints = new Map();- const safePullRequestFingerprints = new Map();- const screenOne = async (kind, item, content) => {+ const screenOne = async (item, content) => {if (typeof content !== 'string' || content.length > MODEL_ABUSE_GUARD_MAX_INPUT_CHARS) {return { ok: false, code: 'security-guard-input-too-large' };}- const fingerprint = kind === 'pull-request'- ? pullRequestContentFingerprint(item, item.diff)- : abuseFingerprint(kind, item, content);+ const fingerprint = abuseFingerprint(item, content);const known = previous.get(fingerprint);if (known) return { ok: true, safe: false, report: known, reused: true };const { screenUntrustedContent } = await import('./untrustedContent.js');- const screened = await screenUntrustedContent({ content, source: kind === 'issue-comment' ? 'github-issue' : 'github-pr' });+ const screened = await screenUntrustedContent({ content, source: 'github-issue' });const verdict = screened.screening || screened;if (!verdict.ok) return { ok: false, code: verdict.code || 'security-guard-unavailable' };- const report = modelAbuseReport(kind, item, fingerprint, verdict);+ const report = modelAbuseReport(item, fingerprint, verdict);return { ok: true, safe: verdict.safe === true, report, reused: false };};for (const item of issueComments) {- const result = await screenOne('issue-comment', item, issueAbuseInput(item));+ const result = await screenOne(item, issueAbuseInput(item));if (!result.ok) return { ok: false, code: result.code };if (result.safe) {safeComments.push(item);@@ -792,19 +762,6 @@ async function screenModelAbuseInputs({ app, state, issueComments, pullRequestsif (!result.reused) newBlocked.push(result.report);}}- for (const item of pullRequests) {- const result = await screenOne('pull-request', item, pullRequestAbuseInput(item));- if (!result.ok) return { ok: false, code: result.code };- if (result.safe) {- safePullRequests.push(item);- safePullRequestFingerprints.set(item.number, result.report.fingerprint);- }- else {- blocked.push(result.report);- if (!result.reused) newBlocked.push(result.report);- }- }-if (newBlocked.length > 0) {await addNotification({type: NOTIFICATION_TYPES.AGENT_WARNING,@@ -821,9 +778,7 @@ async function screenModelAbuseInputs({ app, state, issueComments, pullRequestsreturn {ok: true,safeComments,- safePullRequests,safeCommentFingerprints,- safePullRequestFingerprints,blocked,newBlocked,};@@ -837,7 +792,7 @@ async function assignSafeVolunteers(ctx, comments) {if (!item.claimAssignable || assignedIssues.has(item.issueNumber)) continue;const current = await readCurrentIssueComment(ctx, item);if (!current || current.issueAssignees.length > 0- || abuseFingerprint('issue-comment', current, issueAbuseInput(current)) !== abuseFingerprint('issue-comment', item, issueAbuseInput(item))) continue;+ || abuseFingerprint(current, issueAbuseInput(current)) !== abuseFingerprint(item, issueAbuseInput(item))) continue;const succeeded = await assignVolunteer(ctx, item.issueNumber, item.commentAuthor);if (succeeded) {assignedIssues.add(item.issueNumber);@@ -908,6 +863,7 @@ async function keepPendingApproval(app, approval, remaining, reason, { patch = {async function processPendingApprovals(app, ctx) {const approvals = Array.isArray(readState(app).approvedPullRequests) ? readState(app).approvedPullRequests : [];const remaining = [];+ const drops = createDropLog();const handbacks = createHandbackTracker(app);let changed = false;for (const approval of approvals) {@@ -922,7 +878,7 @@ async function processPendingApprovals(app, ctx) {continue;}if (pr.headRefOid !== approval.headSha) {- dropPullRequestDecision(pr.number, 'a new head commit replaced the approved one, so the pending merge was dropped');+ drops.record(pr.number, 'a new head commit replaced the approved one');changed = true;continue;}@@ -931,12 +887,12 @@ async function processPendingApprovals(app, ctx) {typeof approvedDiff !== 'string'|| approvedDiff.length > MAX_DIFF_CHARS|| !approval.contentFingerprint- || pullRequestContentFingerprint(pr, approvedDiff) !== approval.contentFingerprint+ || screenedPullRequestFingerprint(pr, approvedDiff) !== approval.contentFingerprint) {// A maintainer can edit the title/body or a contributor can replace the// head after the review. An old approval is never enough to merge the// new content, so discard the pending action and require a fresh run.- dropPullRequestDecision(pr.number, 'its content no longer matches the approved revision, so the pending merge was dropped');+ drops.record(pr.number, 'its content no longer matches the approved revision');changed = true;continue;}@@ -1045,8 +1001,7 @@ export async function gatherIssueWatcherInput({ app } = {}) {const since = firstRun ? new Date(0).toISOString() : state.cursor;const trust = await createGithubActorTrust({ runGh: (args) => runGh(args, ctx), host: ctx.host, repoFullName: ctx.repoFullName });const issueResult = await gatherIssueComments(ctx, { since, trust, state });- const pullRequests = []; // External PR intake belongs exclusively to pr-reviewer.- if (!issueResult.ok || pullRequests === null) {+ if (!issueResult.ok) {await persistState(app.id, { lastCheckedAt: startedAt, lastError: 'activity-read-failed' });return { skip: { reason: 'activity-read-failed' } };}@@ -1074,7 +1029,7 @@ export async function gatherIssueWatcherInput({ app } = {}) {lastCheckedAt: startedAt,lastError: null,});- if (pendingIssueComments.length === 0 && pullRequests.length === 0) {+ if (pendingIssueComments.length === 0) {return { skip: { reason: firstRun ? 'baselined' : 'no-cognitive-activity' } };}@@ -1088,7 +1043,6 @@ export async function gatherIssueWatcherInput({ app } = {}) {// Bound work per tick without truncating any record. Unselected entries// remain pending; every selected item is screened in full before an action.issueComments: takeIssueCommentsWithinBudget(pendingIssueComments),- pullRequests,});if (!screened.ok) {await persistState(app.id, {@@ -1127,8 +1081,7 @@ export async function gatherIssueWatcherInput({ app } = {}) {const safeIssueComments = takeIssueCommentsWithinBudget(screened.safeComments.filter((item) => (!assignmentResult.assignedCommentKeys.has(`${item.issueNumber}:${item.commentId}`))));- const safePullRequests = screened.safePullRequests;- if (safeIssueComments.length === 0 && safePullRequests.length === 0) {+ if (safeIssueComments.length === 0) {return {skip: {reason: screened.blocked.length > 0 ? 'model-abuse-content-withheld' : 'no-cognitive-activity',@@ -1149,12 +1102,9 @@ export async function gatherIssueWatcherInput({ app } = {}) {commentId,contentFingerprint: screened.safeCommentFingerprints.get(`${issueNumber}:${commentId}`),})),- pullRequests: safePullRequests.map(({ number, headSha, diffTruncated }) => ({- number,- headSha,- diffTruncated,- contentFingerprint: screened.safePullRequestFingerprints.get(number),- })),+ // External PR intake belongs exclusively to pr-reviewer, which builds its+ // own hook metadata; the analysis schema pins this to an empty array.+ pullRequests: [],},},};@@ -1271,17 +1221,60 @@ function mergeApproval(existing, approval) {}/**- * Say out loud that a completed review decision was thrown away.+ * Records a completed review decision that was thrown away, and why.** Every guard in the action loop fails closed by skipping the PR, which is the- * right posture and a terrible signal: the pipeline logs three green stages and- * the PR is left exactly as it was, with nothing anywhere naming the reason. A- * fingerprint builder that drifted out of sync with the preflight's looked- * identical to "the contributor pushed mid-review" — from the outside, both are- * silence (#7323). Name the PR and the reason at every exit.+ * right posture and a terrible signal: the pipeline reported three green stages+ * over a PR it had not touched, and nothing anywhere named the reason. A+ * fingerprint builder that had drifted out of sync with the preflight's looked+ * exactly like "the contributor pushed mid-review" — from the outside, both are+ * silence (#7323). So a drop is logged AND carried in the hook's result, which+ * is what the pipeline hands back as the stage's own outcome.+ */+function createDropLog() {+ const dropped = [];+ return {+ dropped,+ record(number, reason) {+ dropped.push({ number, reason });+ console.warn(`⚠️ issue-watcher: no action on PR #${number} — ${reason}`);+ },+ };+}++/**+ * Re-verify one reviewed PR against the content the security scan screened,+ * with a single exit carrying the reason.+ *+ * These checks are what stand between a model's verdict and a real merge, and+ * they are the reason the loop can silently do nothing. Keeping them in one+ * place means the NEXT guard added here cannot forget to name itself — which is+ * exactly how the last one got lost.*/-function dropPullRequestDecision(number, reason) {- console.warn(`⚠️ issue-watcher: no action on PR #${number} — ${reason}`);+async function verifyScreenedPullRequest(ctx, raw, expectedPullRequests) {+ const decision = normalizeReviewDecision(raw);+ if (!decision) {+ return { number: raw?.number ?? '?', reason: 'the reviewer returned a decision this hook could not validate' };+ }+ const { number } = decision;+ const target = expectedPullRequests.get(number);+ if (!target || decision.headSha !== target.headSha) {+ return { number, reason: 'it is not the screened PR/commit this run was handed' };+ }+ const pr = await readPullRequest(ctx, number);+ if (!pr) return { number, reason: 'it could not be read from GitHub' };+ if (pr.state !== 'OPEN' || pr.headRefOid !== target.headSha) {+ return { number, reason: 'it closed or moved to a new head commit during the review' };+ }+ const diff = await runGh(['pr', 'diff', String(number), '--repo', ctx.repoSpec], ctx).catch(() => null);+ if (diff === null) return { number, reason: 'its diff could not be re-read for verification' };+ // A PR description can change without changing its head SHA. Require the+ // exact content screened before cognition, not merely the same revision,+ // before any review, rebase, or merge action.+ if (!target.contentFingerprint || screenedPullRequestFingerprint(pr, diff) !== target.contentFingerprint) {+ return { number, reason: 'its content no longer matches what the security scan screened', notify: true };+ }+ return { ok: true, decision, target, pr, diff };}/** Validated reply/review/rebase/merge pass run after cognition. */@@ -1337,7 +1330,7 @@ export async function processTaskOutput({ appId, success, payload, task, requireconst decision = commentDecisions.get(key);if (!decision || !['reply', 'none'].includes(decision.action)) continue;const current = await readCurrentIssueComment(ctx, item);- if (!current || !item.contentFingerprint || abuseFingerprint('issue-comment', current, issueAbuseInput(current)) !== item.contentFingerprint) continue;+ if (!current || !item.contentFingerprint || abuseFingerprint(current, issueAbuseInput(current)) !== item.contentFingerprint) continue;if (decision.action === 'reply') {const posted = trimTo(decision.body, 5_000) && await postIssueReply(ctx, { ...current, body: decision.body });if (!posted) continue;@@ -1349,42 +1342,23 @@ export async function processTaskOutput({ appId, success, payload, task, require&& commentDecisions.size === expectedComments.size;let approvals = Array.isArray(readState(app).approvedPullRequests) ? readState(app).approvedPullRequests : [];+ const drops = createDropLog();const handbacks = createHandbackTracker(app);let reviewed = 0;let merged = 0;let rebased = 0;let handedBack = 0;for (const raw of payload.pullRequests) {- const decision = normalizeReviewDecision(raw);- const target = decision && expectedPullRequests.get(decision.number);- if (!decision) {- dropPullRequestDecision('?', 'the reviewer returned a decision this hook could not validate');- continue;- }- if (!target || decision.headSha !== target.headSha) {- dropPullRequestDecision(decision.number, 'it is not the screened PR/commit this run was handed');- continue;- }- const pr = await readPullRequest(ctx, decision.number);- if (!pr || pr.state !== 'OPEN' || pr.headRefOid !== target.headSha) {- dropPullRequestDecision(decision.number, !pr ? 'it could not be read from GitHub' : 'it closed or moved to a new head commit during the review');- continue;- }- const diff = await runGh(['pr', 'diff', String(pr.number), '--repo', ctx.repoSpec], ctx).catch(() => null);- if (diff === null) {- dropPullRequestDecision(decision.number, 'its diff could not be re-read for verification');- continue;- }- const currentContentFingerprint = pullRequestContentFingerprint(pr, diff);- // A PR description can change without changing its head SHA. Require the- // exact content screened before cognition, not merely the same revision,- // before any review, rebase, or merge action.- if (!target.contentFingerprint || currentContentFingerprint !== target.contentFingerprint) {- dropPullRequestDecision(decision.number, 'its content no longer matches what the security scan screened');- await notifyPendingApproval(app, { number: pr.number, url: pr.url },- 'The review finished, but the PR content no longer matches what the security scan screened, so PortOS took no action on it.');+ const verified = await verifyScreenedPullRequest(ctx, raw, expectedPullRequests);+ if (!verified.ok) {+ drops.record(verified.number, verified.reason);+ if (verified.notify) {+ await notifyPendingApproval(app, { number: verified.number, url: null },+ 'The review finished, but the PR content no longer matches what the security scan screened, so PortOS took no action on it.');+ }continue;}+ const { decision, target, pr, diff } = verified;const eligibilityRequired = requireEligibilityFacts|| Object.prototype.hasOwnProperty.call(target, 'eligibilityFacts');const eligibilityStillCurrent = async () => {@@ -1392,7 +1366,7 @@ export async function processTaskOutput({ appId, success, payload, task, requireconst current = await eligibilityFactsStillCurrent(ctx, pr, target);if (!current) {approvals = approvals.filter((entry) => entry.number !== pr.number);- dropPullRequestDecision(decision.number, 'the linked issue state or author assignment changed since the eligibility gate ran');+ drops.record(decision.number, 'the linked issue state or author assignment changed since the eligibility gate ran');}return current;};@@ -1430,7 +1404,7 @@ export async function processTaskOutput({ appId, success, payload, task, require: await submitReview(ctx, pr.number, { body: summary, event: 'COMMENT', comments: findings })|| await postReviewFallback(ctx, pr.number, summary);if (!posted) {- dropPullRequestDecision(decision.number, 'GitHub rejected the review comment');+ drops.record(decision.number, 'GitHub rejected the review comment');continue;}reviewed += 1;@@ -1462,7 +1436,7 @@ export async function processTaskOutput({ appId, success, payload, task, requireevent: 'APPROVE',}));if (!approved) {- dropPullRequestDecision(decision.number, 'GitHub rejected the approving review, so no CI approval or merge followed');+ drops.record(decision.number, 'GitHub rejected the approving review, so no CI approval or merge could follow');continue;}reviewed += 1;@@ -1577,5 +1551,5 @@ export async function processTaskOutput({ appId, success, payload, task, requirelastError: commentsHandled ? null : 'issue-response-incomplete',...(typeof handbackPatch === 'function' ? handbackPatch(state) : handbackPatch),}));- return { action: 'processed', replies, reviewed, rebased, merged, handedBack, commentsHandled };+ return { action: 'processed', replies, reviewed, rebased, merged, handedBack, commentsHandled, dropped: drops.dropped };}diff --git a/server/services/issueWatcher.test.js b/server/services/issueWatcher.test.jsindex 67a5a977e1..21d2d00ac3 100644--- a/server/services/issueWatcher.test.js+++ b/server/services/issueWatcher.test.js@@ -68,11 +68,11 @@ import {isTaskOutputPayload,parseAddedDiffLines,processTaskOutput,- pullRequestContentFingerprint,MAX_PENDING_APPROVAL_TICKS,MAX_PENDING_ISSUE_COMMENT_TICKS,} from './issueWatcher.js';import { linkedIssueIntentFingerprint } from '../lib/modelAbuseGuard.js';+import { screenedPullRequestFingerprint } from '../lib/prReviewContent.js';import { MAX_PR_REMEDIATION_ATTEMPTS } from '../lib/prHandbackPolicy.js';import { IN_PROGRESS_LABEL, dispatchLabelSpec } from '../lib/dispatchLabels.js';@@ -455,7 +455,7 @@ describe('processTaskOutput', () => {pullRequests: [{number: 7,headSha: 'a'.repeat(40),- contentFingerprint: pullRequestContentFingerprint(pullRequest(), DIFF),+ contentFingerprint: screenedPullRequestFingerprint(pullRequest(), DIFF),}],},};@@ -1050,7 +1050,7 @@ describe('processTaskOutput', () => {const approval = {number: 7,headSha: 'a'.repeat(40),- contentFingerprint: pullRequestContentFingerprint(pullRequest(), DIFF),+ contentFingerprint: screenedPullRequestFingerprint(pullRequest(), DIFF),url: 'https://github.com/o/r/pull/7',ciPolicy: 'required',rebaseRequired: false,@@ -1119,7 +1119,7 @@ describe('handing back a PR the coordinator could not merge', () => {pullRequests: [{number: 7,headSha: 'a'.repeat(40),- contentFingerprint: pullRequestContentFingerprint(pullRequest(), DIFF),+ contentFingerprint: screenedPullRequestFingerprint(pullRequest(), DIFF),}],},};@@ -1317,7 +1317,7 @@ describe('handing back a PR the coordinator could not merge', () => {approvedPullRequests: [{number: 7,headSha: 'a'.repeat(40),- contentFingerprint: pullRequestContentFingerprint(pullRequest(WRITABLE_FORK), DIFF),+ contentFingerprint: screenedPullRequestFingerprint(pullRequest(WRITABLE_FORK), DIFF),authorLogin: 'contributor',url: 'https://github.com/o/r/pull/7',ciPolicy: 'required',diff --git a/server/services/prReviewerSecurity.js b/server/services/prReviewerSecurity.jsindex 33d853a472..a7416644fb 100644--- a/server/services/prReviewerSecurity.js+++ b/server/services/prReviewerSecurity.js@@ -24,7 +24,10 @@ import {linkedIssueIntentFingerprint,normalizeLinkedIssues,} from '../lib/modelAbuseGuard.js';-import { pullRequestReviewContent, pullRequestReviewFingerprint } from '../lib/prReviewContent.js';+// The screened surface and its fingerprint have ONE definition, because the+// coordinator recomputes the same value from a fresh forge read before it acts.+// Never rebuild either shape here.+import { screenedPullRequestContent, screenedPullRequestFingerprint } from '../lib/prReviewContent.js';import { screenUntrustedContent } from './untrustedContent.js';import { safeJSONParse } from '../lib/fileUtils.js';@@ -256,13 +259,6 @@ const formatSecurityFindings = (findings) => findings.map((finding) => (`${finding.severity} — ${finding.location}: ${finding.reason}`)).join('\n');-// The screened surface and its fingerprint are defined in `lib/prReviewContent.js`-// because the coordinator recomputes the same value from a fresh forge read-// before it acts. Never build either shape locally.-const contentFor = (pr, diff, commits) => pullRequestReviewContent({- title: pr.title, body: pr.body, commits, diff,-});-const structuralVerdict = (findings) => ({ok: true,safe: false,@@ -276,15 +272,11 @@ const structuralVerdict = (findings) => ({layers: { deterministic: 'blocked', classifier: 'not-run', verdict: 'validated' },});-const contentFingerprintFor = (pr, diff, commits) => pullRequestReviewFingerprint({- number: pr?.number, headSha: pr?.headRefOid, title: pr?.title, body: pr?.body, commits, diff,-});-const reportFor = (pr, diff, commits, verdict) => ({number: pr.number,url: pr.url,headRefOid: pr.headRefOid,- contentFingerprint: contentFingerprintFor(pr, diff, commits),+ contentFingerprint: screenedPullRequestFingerprint(pr, diff, commits),updatedAt: pr.updatedAt,passed: verdict.safe === true,safe: verdict.safe === true,@@ -368,7 +360,7 @@ export async function runPrReviewerSecurityScan({ app, target = null, largeInput// halves separately — the diff by `contentFingerprint`, the issue text by// `eligibilityFacts.intentFingerprint`.const intentContent = linkedIssueIntentContent(pr.linkedIssues);- const prContent = contentFor(pr, diff, commits);+ const prContent = screenedPullRequestContent(pr, diff, commits);const content = intentContent ? `${prContent}\n\n${intentContent}` : prContent;if (content.length > SECURITY_SCAN_MAX_DIFF_CHARS) {return failure('security-scan-input-too-large', { reviewedPrs, scanKey });diff --git a/server/services/prReviewerSecurity.test.js b/server/services/prReviewerSecurity.test.jsindex 9f37ae2fc4..440bed715a 100644--- a/server/services/prReviewerSecurity.test.js+++ b/server/services/prReviewerSecurity.test.js@@ -23,17 +23,6 @@ vi.mock('../lib/gitRemote.js', () => ({getOriginInfo: (...args) => getOriginInfoMock(...args),}))-// The coordinator half of the fingerprint contract lives in issueWatcher.js.-// Its service-level dependencies are stubbed only so the module loads here;-// the contract test below calls one pure exported function.-vi.mock('./git.js', () => ({ mergePR: vi.fn(), resolveForgeForRepo: vi.fn() }))-vi.mock('./apps.js', () => ({ getAppById: vi.fn(), updateApp: vi.fn() }))-vi.mock('./notifications.js', () => ({- addNotification: vi.fn(), NOTIFICATION_TYPES: {}, PRIORITY_LEVELS: {},-}))-vi.mock('./prRemediationFollowUp.js', () => ({- PR_REMEDIATION_SPAWN: {}, spawnPrRemediationFollowUp: vi.fn(),-}))vi.mock('../lib/workTracker.js', async (importActual) => {const actual = await importActual()return {@@ -50,6 +39,7 @@ import {securityScanFingerprint,summarizeSecurityScanReport,} from './prReviewerSecurity.js'+import { screenedPullRequestFingerprint } from '../lib/prReviewContent.js'const app = { id: 'app-example', repoPath: '/tmp/example-repo' }const guardVerdict = (safe = true) => ({@@ -419,11 +409,11 @@ describe('pr-reviewer model-abuse preflight', () => {/*** The preflight STAMPS the fingerprint and the coordinator RECOMPUTES it from a- * fresh forge read; a PR whose two values disagree is silently skipped, so a- * one-sided change to the screened surface disables review, CI approval, and- * merge for every external PR at once, with no error anywhere. Deriving the- * expected value from either builder alone cannot catch that — only running the- * real producer against the real consumer can.+ * fresh forge read; a PR whose two values disagree is skipped, so a one-sided+ * change to the screened surface disables review, CI approval, and merge for+ * every external PR at once. Deriving the expected value from either builder+ * alone cannot catch that — this runs the REAL preflight scan and compares what+ * it stamped against what the coordinator recomputes from its own forge read.*/describe('screened-content fingerprint contract', () => {const HEAD = 'a'.repeat(40)@@ -442,16 +432,6 @@ describe('screened-content fingerprint contract', () => {...overrides,})- // Loaded at call time, not statically: the coordinator drags a large service- // subtree behind it and this suite needs one function from it (see the server- // import budget in lib/importScoping.test.js). Memoized so parallel awaits- // share one evaluation of the mocked module.- let coordinator- const pullRequestContentFingerprint = async (...args) => {- coordinator = coordinator || import('./issueWatcher.js')- return (await coordinator).pullRequestContentFingerprint(...args)- }-const scanOnce = async () => {routeGh({prs: [listedPr(12, 'contributor-a', HEAD)],@@ -465,7 +445,7 @@ describe('screened-content fingerprint contract', () => {}it('recomputes the exact fingerprint the preflight stamped', async () => {- expect(await pullRequestContentFingerprint(coordinatorRead(), DIFF)).toBe(await scanOnce())+ expect(screenedPullRequestFingerprint(coordinatorRead(), DIFF)).toBe(await scanOnce())})it('rejects a PR whose commit messages, title, body, or diff changed after screening', async () => {@@ -475,13 +455,13 @@ describe('screened-content fingerprint contract', () => {coordinatorRead({ title: 'Contributor update 12 (edited)' }),coordinatorRead({ body: 'Rewritten description' }),]- for (const pr of changed) expect(await pullRequestContentFingerprint(pr, DIFF)).not.toBe(stamped)- expect(await pullRequestContentFingerprint(coordinatorRead(), `${DIFF}\n+extra`)).not.toBe(stamped)+ for (const pr of changed) expect(screenedPullRequestFingerprint(pr, DIFF)).not.toBe(stamped)+ expect(screenedPullRequestFingerprint(coordinatorRead(), `${DIFF}\n+extra`)).not.toBe(stamped)})it('refuses to verify a PR read without its commit log instead of hashing a smaller surface', async () => {const stamped = await scanOnce()- expect(await pullRequestContentFingerprint(coordinatorRead({ commits: undefined }), DIFF)).toBeNull()+ expect(screenedPullRequestFingerprint(coordinatorRead({ commits: undefined }), DIFF)).toBeNull()expect(stamped).toEqual(expect.any(String))})})