mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-24 04:47:03 +00:00
feat(ci): label PRs with the Codex review verdict (#2360)
The review outcome was only visible by opening the PR and reading the body. Each published review now sets exactly one verdict label: codex-review:pass (all stages pass, no Blocker/Major findings; Minor/Nit are advisory), codex-review:changes, or codex-review:clarify. A review of new inputs clears the previous verdict first, so a stale pass never outlives the commit it described, and a failed run on current inputs is marked codex-review:error. Other labels are left alone. The review body now opens with the verdict and finding counts. Label API failures only warn; they never fail or block the published review.
This commit is contained in:
@@ -7,6 +7,16 @@ const SIGNATURE = '*HAPI Bot*';
|
||||
const VERSION = 2;
|
||||
const SEVERITIES = ['Blocker', 'Major', 'Minor', 'Nit'];
|
||||
const DECISIONS = ['pass', 'needs_changes', 'needs_clarification'];
|
||||
// Minor and Nit findings are advisory; only these keep a PR from passing.
|
||||
const BLOCKING_SEVERITIES = ['Blocker', 'Major'];
|
||||
// Exactly one of these labels marks the latest review outcome of a PR.
|
||||
const VERDICT_LABELS = {
|
||||
pass: { name: 'codex-review:pass', color: '0e8a16', description: 'HAPI Bot: all review stages passed, no Blocker/Major findings' },
|
||||
needs_changes: { name: 'codex-review:changes', color: 'd93f0b', description: 'HAPI Bot: review requests changes' },
|
||||
needs_clarification: { name: 'codex-review:clarify', color: 'fbca04', description: 'HAPI Bot: review needs clarification' },
|
||||
error: { name: 'codex-review:error', color: 'b60205', description: 'HAPI Bot: review run failed; re-run the workflow' },
|
||||
};
|
||||
const VERDICT_LABEL_NAMES = Object.values(VERDICT_LABELS).map(label => label.name);
|
||||
|
||||
function hash(value) {
|
||||
return createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
@@ -84,6 +94,34 @@ function skip(core, reason) {
|
||||
return { skipped: true, reason };
|
||||
}
|
||||
|
||||
// Labels carry no commit, so they are reconciled on every review: cleared when
|
||||
// new inputs start a review, then set once the outcome for them is known.
|
||||
async function syncVerdictLabel(github, request, core, labels, verdictKey) {
|
||||
const target = verdictKey ? VERDICT_LABELS[verdictKey] : null;
|
||||
const current = new Set((labels || []).map(label => typeof label === 'string' ? label : label.name));
|
||||
const issue = { owner: request.owner, repo: request.repo, issue_number: request.pull_number };
|
||||
try {
|
||||
for (const name of VERDICT_LABEL_NAMES) {
|
||||
if (name === target?.name || !current.has(name)) continue;
|
||||
try {
|
||||
await github.rest.issues.removeLabel({ ...issue, name });
|
||||
} catch (error) {
|
||||
if (error.status !== 404) throw error;
|
||||
}
|
||||
}
|
||||
if (!target || current.has(target.name)) return;
|
||||
try {
|
||||
await github.rest.issues.createLabel({ owner: request.owner, repo: request.repo, ...target });
|
||||
} catch (error) {
|
||||
if (error.status !== 422) throw error;
|
||||
}
|
||||
await github.rest.issues.addLabels({ ...issue, labels: [target.name] });
|
||||
} catch (error) {
|
||||
// A label is a convenience view of the review; never fail or mislabel it over this.
|
||||
core.warning(`Could not update review verdict label: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function listBotReviews(github, request, env) {
|
||||
return botReviews(await github.paginate(github.rest.pulls.listReviews, {
|
||||
...request,
|
||||
@@ -121,6 +159,9 @@ async function prepareReview({ github, context, core, env = process.env }) {
|
||||
commit_id: latest.commit_id,
|
||||
body: latest.body,
|
||||
} : null;
|
||||
// The previous verdict described other inputs; do not leave it standing
|
||||
// while this review runs (or if it is cancelled or fails).
|
||||
await syncVerdictLabel(github, request, core, pull.labels, null);
|
||||
const contextPath = path.join(env.RUNNER_TEMP, 'hapi-pr-review-context.json');
|
||||
fs.writeFileSync(contextPath, JSON.stringify(snapshot, null, 2));
|
||||
core.setOutput('context_path', contextPath);
|
||||
@@ -205,6 +246,14 @@ function validateResult(raw) {
|
||||
return result;
|
||||
}
|
||||
|
||||
function verdict(result) {
|
||||
const stages = [result.requirement.status, result.approach.status];
|
||||
if (stages.includes('needs_changes')) return 'needs_changes';
|
||||
if (stages.includes('needs_clarification')) return 'needs_clarification';
|
||||
if (result.code.findings.some(finding => BLOCKING_SEVERITIES.includes(finding.severity))) return 'needs_changes';
|
||||
return 'pass';
|
||||
}
|
||||
|
||||
// With zero context, every line in each hunk range is changed. Keep the new
|
||||
// filename for renamed files on both sides, matching GitHub review comments.
|
||||
function changedLines(diff) {
|
||||
@@ -264,6 +313,8 @@ const LABELS = {
|
||||
not_reviewed: 'Not reviewed', reviewed: 'Reviewed', evidence: 'Evidence', suggestions: 'Suggestions',
|
||||
fix: 'Suggested fix', noFindings: 'No reportable code issues found.',
|
||||
notRun: 'Not run (automation; PR code execution is prohibited).',
|
||||
headline: { pass: '✅ All stages passed', needs_changes: '⚠️ Needs changes', needs_clarification: '❓ Needs clarification' },
|
||||
counts: items => ` (${items.join(', ')})`,
|
||||
},
|
||||
zh: {
|
||||
mode: '评审模式', initial: '首次评审', follow_up_context: '说明更新后的复评',
|
||||
@@ -273,12 +324,19 @@ const LABELS = {
|
||||
not_reviewed: '未评审', reviewed: '已评审', evidence: '依据', suggestions: '建议',
|
||||
fix: '修复建议', noFindings: '未发现可报告的代码缺陷。',
|
||||
notRun: '未运行测试(自动评审禁止执行 PR 代码)。',
|
||||
headline: { pass: '✅ 全部通过', needs_changes: '⚠️ 需要调整', needs_clarification: '❓ 需要澄清' },
|
||||
counts: items => `(${items.join(',')})`,
|
||||
},
|
||||
};
|
||||
|
||||
function renderReview(result, snapshot) {
|
||||
const labels = LABELS[result.language];
|
||||
const parts = [`${labels.mode}: ${labels[snapshot.mode]}`];
|
||||
const counts = SEVERITIES
|
||||
.map(severity => [severity, result.code.findings.filter(finding => finding.severity === severity).length])
|
||||
.filter(([, count]) => count)
|
||||
.map(([severity, count]) => `${count} ${severity}`);
|
||||
const headline = `**${labels.headline[verdict(result)]}**${counts.length ? labels.counts(counts) : ''}`;
|
||||
const parts = [headline, `${labels.mode}: ${labels[snapshot.mode]}`];
|
||||
for (const key of ['requirement', 'approach']) {
|
||||
const stage = result[key];
|
||||
parts.push(`**${labels[key]} — ${labels[stage.status]}**`, stage.summary);
|
||||
@@ -342,8 +400,27 @@ async function publishReview({ github, context, core, env = process.env, getDiff
|
||||
const { data: review } = await github.rest.pulls.createReview({ ...request, ...payload });
|
||||
core.setOutput('published', 'true');
|
||||
core.setOutput('review_url', review.html_url);
|
||||
const verdictKey = verdict(result);
|
||||
core.setOutput('verdict', verdictKey);
|
||||
await syncVerdictLabel(github, request, core, latest.labels, verdictKey);
|
||||
await core.summary.addRaw(payload.body).write();
|
||||
return review;
|
||||
}
|
||||
|
||||
module.exports = { inputId, marker, botReviews, hasReview, prepareReview, validateResult, changedLines, readDiff, renderReview, publishReview };
|
||||
// Runs only when a review of these inputs failed. A newer run (new commits or
|
||||
// description) owns the label instead, so stale failures leave it alone.
|
||||
async function markReviewError({ github, context, core, env = process.env }) {
|
||||
const request = requestContext(context);
|
||||
const snapshot = JSON.parse(fs.readFileSync(env.REVIEW_CONTEXT_PATH, 'utf8'));
|
||||
const { data: live } = await github.rest.pulls.get(request);
|
||||
if (skipReason(live) || inputId(snapshotPull(live), snapshot.policy_digest) !== snapshot.input_id) {
|
||||
return skip(core, 'PR inputs changed since the failed review');
|
||||
}
|
||||
await syncVerdictLabel(github, request, core, live.labels, 'error');
|
||||
return { labeled: VERDICT_LABELS.error.name };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
VERDICT_LABELS, inputId, marker, botReviews, hasReview, prepareReview, validateResult, verdict,
|
||||
changedLines, readDiff, renderReview, publishReview, markReviewError,
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@ const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { test } = require('node:test');
|
||||
const {
|
||||
inputId, marker, botReviews, hasReview, prepareReview, validateResult,
|
||||
changedLines, readDiff, renderReview, publishReview,
|
||||
VERDICT_LABELS, inputId, marker, botReviews, hasReview, prepareReview, validateResult, verdict,
|
||||
changedLines, readDiff, renderReview, publishReview, markReviewError,
|
||||
} = require('./pr-review.cjs');
|
||||
|
||||
const HEAD = 'a'.repeat(40);
|
||||
@@ -76,16 +76,41 @@ function review(overrides = {}) {
|
||||
function harness(t) {
|
||||
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'hapi-pr-review-test-'));
|
||||
t.after(() => fs.rmSync(temporary, { recursive: true, force: true }));
|
||||
const state = { pull: pull(), reviews: [], posts: [], outputs: {}, diffReads: 0, getCalls: 0 };
|
||||
const state = {
|
||||
pull: pull(), reviews: [], posts: [], outputs: {}, diffReads: 0, getCalls: 0,
|
||||
createdLabels: [], warnings: [], existingLabels: new Set(),
|
||||
};
|
||||
const labelNames = () => state.pull.labels.map(label => label.name);
|
||||
const env = { GITHUB_WORKSPACE: path.resolve(__dirname, '../..'), RUNNER_TEMP: temporary };
|
||||
const context = { repo: { owner: 'tiann', repo: 'hapi' }, payload: { pull_request: { number: 1842 } } };
|
||||
const core = {
|
||||
info: () => {},
|
||||
warning: message => { state.warnings.push(message); },
|
||||
setOutput: (key, value) => { state.outputs[key] = value; },
|
||||
summary: { addRaw: () => ({ write: async () => {} }) },
|
||||
};
|
||||
const github = {
|
||||
rest: { pulls: {
|
||||
rest: { issues: {
|
||||
removeLabel: async ({ issue_number, name }) => {
|
||||
assert.equal(issue_number, 1842);
|
||||
if (state.labelError) throw state.labelError;
|
||||
if (!labelNames().includes(name)) throw Object.assign(new Error('Label does not exist'), { status: 404 });
|
||||
state.pull.labels = state.pull.labels.filter(label => label.name !== name);
|
||||
},
|
||||
createLabel: async label => {
|
||||
if (state.labelError) throw state.labelError;
|
||||
if (state.existingLabels.has(label.name)) throw Object.assign(new Error('already_exists'), { status: 422 });
|
||||
state.existingLabels.add(label.name);
|
||||
state.createdLabels.push(label);
|
||||
},
|
||||
addLabels: async ({ issue_number, labels }) => {
|
||||
assert.equal(issue_number, 1842);
|
||||
if (state.labelError) throw state.labelError;
|
||||
for (const name of labels) {
|
||||
if (!labelNames().includes(name)) state.pull.labels.push({ name });
|
||||
}
|
||||
},
|
||||
}, pulls: {
|
||||
get: async () => {
|
||||
state.getCalls++;
|
||||
state.onGet?.();
|
||||
@@ -118,6 +143,8 @@ function harness(t) {
|
||||
return DIFF;
|
||||
} });
|
||||
},
|
||||
markError: () => markReviewError({ github, context, core, env }),
|
||||
labels: labelNames,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -405,3 +432,108 @@ test('reads the fixed head against its merge base, including spaces, Unicode, re
|
||||
assert.deepEqual(files.get('deleted.ts'), { LEFT: [[1, 5]], RIGHT: [] });
|
||||
assert.equal(files.has('base-only.ts'), false);
|
||||
});
|
||||
|
||||
const label = key => VERDICT_LABELS[key].name;
|
||||
|
||||
test('verdict passes with Minor/Nit findings and blocks on Blocker/Major or a non-passing stage', () => {
|
||||
const withFindings = (...severities) => {
|
||||
const value = result();
|
||||
value.code.findings = severities.map(severity => finding({ severity }));
|
||||
return value;
|
||||
};
|
||||
assert.equal(verdict(result()), 'pass');
|
||||
assert.equal(verdict(withFindings('Minor', 'Nit')), 'pass');
|
||||
assert.equal(verdict(withFindings('Nit', 'Major')), 'needs_changes');
|
||||
assert.equal(verdict(withFindings('Blocker')), 'needs_changes');
|
||||
assert.equal(verdict(result('needs_changes')), 'needs_changes');
|
||||
assert.equal(verdict(result('needs_clarification')), 'needs_clarification');
|
||||
assert.equal(verdict(result('pass', 'needs_changes')), 'needs_changes');
|
||||
assert.equal(verdict(result('pass', 'needs_clarification')), 'needs_clarification');
|
||||
});
|
||||
|
||||
test('leads the review with the verdict and finding counts', async t => {
|
||||
const h = harness(t);
|
||||
const snapshot = await h.prepare();
|
||||
const value = result();
|
||||
value.code.findings = [finding(), finding({ severity: 'Nit' }), finding()];
|
||||
assert.ok(renderReview(value, snapshot).body.startsWith('**✅ All stages passed** (2 Minor, 1 Nit)\n\nReview mode: initial'));
|
||||
assert.ok(renderReview(result(), snapshot).body.startsWith('**✅ All stages passed**\n\n'));
|
||||
value.code.findings.push(finding({ severity: 'Major' }));
|
||||
value.language = 'zh';
|
||||
assert.ok(renderReview(value, snapshot).body.startsWith('**⚠️ 需要调整**(1 Major,2 Minor,1 Nit)\n\n评审模式'));
|
||||
assert.ok(renderReview(result('needs_clarification'), snapshot).body.startsWith('**❓ Needs clarification**\n\n'));
|
||||
});
|
||||
|
||||
for (const [requirement, approach, severity, key] of [
|
||||
['pass', 'pass', 'Minor', 'pass'],
|
||||
['pass', 'pass', 'Major', 'needs_changes'],
|
||||
['needs_changes', 'not_reviewed', null, 'needs_changes'],
|
||||
['pass', 'needs_clarification', null, 'needs_clarification'],
|
||||
]) {
|
||||
test(`labels a published ${key} review (${requirement}/${approach}${severity ? `/${severity}` : ''})`, async t => {
|
||||
const h = harness(t);
|
||||
await h.prepare();
|
||||
const value = result(requirement, approach);
|
||||
if (severity) value.code.findings = [finding({ severity })];
|
||||
await h.publish(value);
|
||||
assert.equal(h.state.outputs.verdict, key);
|
||||
assert.deepEqual(h.labels(), [label(key)]);
|
||||
assert.deepEqual(h.state.createdLabels.map(created => created.name), [label(key)]);
|
||||
assert.deepEqual(h.state.warnings, []);
|
||||
});
|
||||
}
|
||||
|
||||
test('a new review clears only the previous verdict label, then sets the new one', async t => {
|
||||
const h = harness(t);
|
||||
h.state.pull.labels = [{ name: label('pass') }, { name: 'cold-review-clean' }, { name: label('error') }];
|
||||
h.state.existingLabels = new Set(Object.values(VERDICT_LABELS).map(item => item.name));
|
||||
await h.prepare();
|
||||
assert.deepEqual(h.labels(), ['cold-review-clean']);
|
||||
const value = result();
|
||||
value.code.findings = [finding({ severity: 'Blocker' })];
|
||||
await h.publish(value);
|
||||
assert.deepEqual(h.labels(), ['cold-review-clean', label('needs_changes')]);
|
||||
assert.deepEqual(h.state.createdLabels, []);
|
||||
});
|
||||
|
||||
test('already reviewed inputs keep their verdict label', async t => {
|
||||
const h = harness(t);
|
||||
const snapshot = await h.prepare();
|
||||
h.state.reviews = [review({ body: renderReview(result(), snapshot).body })];
|
||||
h.state.pull.labels = [{ name: label('pass') }];
|
||||
assert.equal((await h.prepare()).skipped, true);
|
||||
assert.deepEqual(h.labels(), [label('pass')]);
|
||||
});
|
||||
|
||||
test('invalid output and stale inputs leave no verdict label', async t => {
|
||||
const h = harness(t);
|
||||
h.state.pull.labels = [{ name: label('pass') }];
|
||||
await h.prepare();
|
||||
await assert.rejects(h.publish('{}'));
|
||||
h.state.pull.body += ' changed';
|
||||
assert.equal((await h.publish(result())).skipped, true);
|
||||
assert.deepEqual(h.labels(), []);
|
||||
});
|
||||
|
||||
test('a label API failure warns without failing the published review', async t => {
|
||||
const h = harness(t);
|
||||
await h.prepare();
|
||||
h.state.labelError = Object.assign(new Error('Resource not accessible by integration'), { status: 403 });
|
||||
await h.publish(result());
|
||||
assert.equal(h.state.outputs.published, 'true');
|
||||
assert.equal(h.state.posts.length, 1);
|
||||
assert.match(h.state.warnings[0], /Resource not accessible/);
|
||||
});
|
||||
|
||||
test('a failed review is labeled only while its inputs are still current', async t => {
|
||||
const h = harness(t);
|
||||
h.state.pull.labels = [{ name: label('pass') }];
|
||||
await h.prepare();
|
||||
assert.deepEqual(await h.markError(), { labeled: label('error') });
|
||||
assert.deepEqual(h.labels(), [label('error')]);
|
||||
|
||||
h.state.pull.labels = [];
|
||||
h.state.pull.head.sha = 'c'.repeat(40);
|
||||
assert.equal((await h.markError()).skipped, true);
|
||||
assert.deepEqual(h.labels(), []);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user