Skip to content

Commit 547a1f9

Browse files
authored
ci: Harden Codex gate reconciliation
1 parent 69d3366 commit 547a1f9

1 file changed

Lines changed: 135 additions & 40 deletions

File tree

‎.github/workflows/codex-review-gate.yml‎

Lines changed: 135 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,14 @@ jobs:
4040
with:
4141
script: |
4242
const gateName = 'codex-review-gate';
43-
const gateVersion = 'v6';
43+
const gateVersion = 'v7';
4444
const stateName = 'codex-review-quota-state';
4545
const codexLogins = new Set([
4646
'chatgpt-codex-connector',
4747
'chatgpt-codex-connector[bot]',
4848
]);
49+
const trustedReviewPermissions = new Set(['admin', 'maintain', 'write']);
50+
const reviewCommandPermissions = new Map();
4951
const quotaText = 'reached your Codex usage limits for code reviews';
5052
const fiveHours = 5 * 60 * 60 * 1000;
5153
const retryDelay = 5.25 * 60 * 60 * 1000;
@@ -79,6 +81,43 @@ jobs:
7981
};
8082
8183
const isCodex = (login) => codexLogins.has(login || '');
84+
async function isTrustedReviewCommand(comment) {
85+
const login = comment?.user?.login || '';
86+
if (
87+
!login ||
88+
isCodex(login) ||
89+
String(comment?.body || '').trim() !== '@codex review'
90+
) {
91+
return false;
92+
}
93+
94+
// Requests emitted by this workflow use the repository's Actions
95+
// identity. A pull request cannot impersonate that identity in
96+
// the base repository, so it is safe to treat it as trusted.
97+
if (login === 'github-actions[bot]') return true;
98+
99+
if (reviewCommandPermissions.has(login)) {
100+
return reviewCommandPermissions.get(login);
101+
}
102+
103+
let allowed = false;
104+
try {
105+
const response = await github.rest.repos.getCollaboratorPermissionLevel({
106+
owner,
107+
repo,
108+
username: login,
109+
});
110+
allowed = trustedReviewPermissions.has(response.data.permission);
111+
} catch (error) {
112+
if (error.status !== 404) {
113+
core.warning(
114+
`Could not verify review-command permission for ${login}: ${error}`,
115+
);
116+
}
117+
}
118+
reviewCommandPermissions.set(login, allowed);
119+
return allowed;
120+
}
82121
const isCodexTaskSummary = (body) => {
83122
const text = String(body || '');
84123
return text.startsWith('### Summary\n') && text.includes('[View task →](');
@@ -91,12 +130,17 @@ jobs:
91130
isCodex(context.payload.comment?.user?.login)
92131
? Number(context.payload.comment.id)
93132
: null;
94-
const triggeringReviewCommandId =
133+
let triggeringReviewCommandId = null;
134+
if (
95135
context.eventName === 'issue_comment' &&
96-
!isCodex(context.payload.comment?.user?.login) &&
97136
String(context.payload.comment?.body || '').trim() === '@codex review'
98-
? Number(context.payload.comment.id)
99-
: null;
137+
) {
138+
if (await isTrustedReviewCommand(context.payload.comment)) {
139+
triggeringReviewCommandId = Number(context.payload.comment.id);
140+
} else {
141+
core.notice('Ignoring untrusted @codex review command.');
142+
}
143+
}
100144
101145
function normalizeState(value) {
102146
if (!value || typeof value !== 'object') return { ...emptyState };
@@ -288,36 +332,55 @@ jobs:
288332
}),
289333
]);
290334
291-
const reviewRequests = issueComments
292-
.filter((comment) => {
293-
if (isCodex(comment.user?.login)) return false;
294-
if (String(comment.body || '').trim() !== '@codex review') {
295-
return false;
296-
}
297-
const createdAt = asDate(comment.created_at);
298-
const isTriggeringCommand =
299-
eventPullNumber === pull.number &&
300-
triggeringReviewCommandId === Number(comment.id);
301-
return createdAt && (createdAt >= startedAt || isTriggeringCommand);
302-
})
303-
.map((comment) => ({
304-
at: asDate(comment.created_at),
305-
id: Number(comment.id),
306-
}))
307-
.sort((a, b) => b.at - a.at);
308-
const requestCommentId =
309-
reviewRequests[0]?.id || requestCommentIdForRun(run);
310-
const requestReactions = requestCommentId
311-
? await github.paginate(github.rest.reactions.listForIssueComment, {
312-
owner,
313-
repo,
314-
comment_id: requestCommentId,
315-
per_page: 100,
316-
})
335+
const storedRequestCommentId = requestCommentIdForRun(run);
336+
const reviewRequests = [];
337+
for (const comment of issueComments) {
338+
if (String(comment.body || '').trim() !== '@codex review') continue;
339+
const createdAt = asDate(comment.created_at);
340+
const commentId = Number(comment.id);
341+
const isTriggeringCommand =
342+
eventPullNumber === pull.number &&
343+
triggeringReviewCommandId === commentId;
344+
const isStoredRequest = storedRequestCommentId === commentId;
345+
if (
346+
!createdAt ||
347+
(createdAt < startedAt && !isTriggeringCommand && !isStoredRequest)
348+
) {
349+
continue;
350+
}
351+
if (
352+
!isStoredRequest &&
353+
!(await isTrustedReviewCommand(comment))
354+
) {
355+
continue;
356+
}
357+
reviewRequests.push({ at: createdAt, id: commentId });
358+
}
359+
reviewRequests.sort((a, b) => b.at - a.at);
360+
361+
const reactionsByRequest = new Map();
362+
await Promise.all(
363+
reviewRequests.map(async (request) => {
364+
const reactions = await github.paginate(
365+
github.rest.reactions.listForIssueComment,
366+
{
367+
owner,
368+
repo,
369+
comment_id: request.id,
370+
per_page: 100,
371+
},
372+
);
373+
reactionsByRequest.set(request.id, reactions);
374+
}),
375+
);
376+
const latestRequestReactions = reviewRequests[0]
377+
? reactionsByRequest.get(reviewRequests[0].id) || []
317378
: [];
318-
const requestInFlight = requestReactions.some(
319-
(reaction) =>
320-
isCodex(reaction.user?.login) && reaction.content === 'eyes',
379+
const requestInFlight = reviewRequests.some((request) =>
380+
(reactionsByRequest.get(request.id) || []).some(
381+
(reaction) =>
382+
isCodex(reaction.user?.login) && reaction.content === 'eyes',
383+
),
321384
);
322385
323386
const commentsByReview = new Map();
@@ -352,7 +415,10 @@ jobs:
352415
}
353416
354417
const approvals = [];
355-
for (const reaction of requestReactions) {
418+
// A clean approval belongs to the newest request in this review
419+
// cycle. Older requests are still inspected above for in-flight
420+
// acknowledgements, but cannot satisfy a newer review request.
421+
for (const reaction of latestRequestReactions) {
356422
if (!isCodex(reaction.user?.login)) continue;
357423
if (reaction.content !== '+1') continue;
358424
const createdAt = asDate(reaction.created_at);
@@ -443,8 +509,15 @@ jobs:
443509
// still acknowledged: another overlapping review may yet report
444510
// findings, and review-submission events are intentionally not
445511
// trusted to execute this write-capable workflow.
512+
// A newer quota response also supersedes an older clean result:
513+
// that review request did not complete and must be retried.
514+
const cleanApproval = !requestInFlight ? approvals[0] || null : null;
446515
const terminal =
447-
findings[0] || (!requestInFlight ? approvals[0] : null) || null;
516+
findings[0] ||
517+
(cleanApproval &&
518+
(!quotas[0] || cleanApproval.at >= quotas[0].at)
519+
? cleanApproval
520+
: null);
448521
449522
return {
450523
terminal,
@@ -528,6 +601,7 @@ jobs:
528601
if (run.status === 'completed' && !completedSuccess) continue;
529602
530603
const outcome = await inspectCodexOutcome(pull, run, availableSince);
604+
if (outcome.quota) quotaEvents.push(outcome.quota);
531605
if (outcome.terminal) {
532606
if (completedSuccess && outcome.terminal.kind !== 'findings') {
533607
continue;
@@ -542,7 +616,6 @@ jobs:
542616
continue;
543617
}
544618
if (completedSuccess) continue;
545-
if (outcome.quota) quotaEvents.push(outcome.quota);
546619
547620
pending.push({
548621
base_sha: pull.base.sha,
@@ -580,6 +653,7 @@ jobs:
580653
verdictEvents.sort((a, b) => a.at - b.at);
581654
for (const event of verdictEvents) {
582655
let stillRelevant = false;
656+
let baseChangedWithSameHead = null;
583657
for (const pullNumber of event.prs) {
584658
const current = await github.rest.pulls.get({
585659
owner,
@@ -596,19 +670,40 @@ jobs:
596670
stillRelevant = true;
597671
break;
598672
}
673+
if (
674+
current.data.state === 'open' &&
675+
!current.data.draft &&
676+
current.data.base.ref === defaultBranch &&
677+
current.data.head.sha === event.head_sha &&
678+
current.data.base.sha !== event.base_sha
679+
) {
680+
baseChangedWithSameHead = current.data;
681+
}
599682
}
600683
601684
if (!stillRelevant) {
685+
// If only the base moved, neutral would satisfy a required
686+
// check for the unchanged PR head. Publish a replacement
687+
// pending check first and make the stale verdict blocking, so
688+
// there is no mergeable window before reconciliation catches
689+
// the new default-branch base.
690+
if (baseChangedWithSameHead) {
691+
await createPendingGate(baseChangedWithSameHead, true);
692+
}
602693
await github.rest.checks.update({
603694
owner,
604695
repo,
605696
check_run_id: event.check_run_id,
606697
status: 'completed',
607-
conclusion: 'neutral',
698+
conclusion: baseChangedWithSameHead ? 'failure' : 'neutral',
608699
completed_at: now.toISOString(),
609700
output: {
610-
title: 'Codex review superseded',
611-
summary: 'The pull request head or base changed while its Codex result was being reconciled.',
701+
title: baseChangedWithSameHead
702+
? 'Codex review stale after base update'
703+
: 'Codex review superseded',
704+
summary: baseChangedWithSameHead
705+
? 'The default branch changed while the Codex result was being reconciled. Update or rebase the pull request so its new base can be reviewed.'
706+
: 'The pull request head or base changed while its Codex result was being reconciled.',
612707
},
613708
});
614709
continue;

0 commit comments

Comments
 (0)