mirror of
https://github.com/Devolutions/IronRDP.git
synced 2026-11-27 10:42:37 +00:00
ci(pr-automation): harden review pipeline (#1931)
Harden PR-automation classification, review dispatch, and publication without relaxing SHA-bound safeguards. - Require a trusted, GitHub Actions-owned `AI classification` check with valid machine state at the current head before any reviewer starts. Forced reviews bypass policy and CI eligibility only; valid `Automation stopped` classifications remain force-reviewable, while missing, stale, or invalid classifications fail forced or manual `workflow_dispatch` invocations before provider work begins. Automatic CI and classification-complete races remain normal skips. - Retry exactly one malformed, read-only GitHub pull GET (`500 Unexpected end of JSON input`) at the post-check, pre-dispatch boundary observed in production. Do not retry writes or dispatch POSTs: stale, terminal, and exhausted paths neither dispatch nor replay the persisted check. Classification dispatch remains edge-triggered. - Use four classifier lanes and seven whole-pipeline lanes, with at most three specialists running per pipeline. The peak provider capacity is 25 concurrent requests: four classifiers plus three specialists across seven pipelines. Lanes are calculated in trusted JavaScript, not GitHub Actions expressions. - Preserve every validated finding, including clean reviews. Required reviewer failure is unavailable; optional failure produces deterministic reduced-coverage notices naming unavailable reviewers without provider diagnostic details. - Publish stage outcomes and LLM-only metrics with cumulative elapsed seconds plus explicit input, output, and total token columns. Totals include repeated context across requests and repairs; missing or partial usage remains explicit. Detailed failure diagnostics stay in the workflow summary, not pull-request reviews or checks. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -2,6 +2,8 @@
|
||||
|
||||
`.github/workflows/labeler.yml` classifies ready, open pull requests and calls `.github/workflows/review-pipeline.yml` for at most two automated reviews.
|
||||
Automatic routes stop at `ai-reviewed/2` unless a maintainer uses force mode.
|
||||
Manual `workflow_dispatch` requests and forced reviews require a successful GitHub Actions-owned `AI classification` check for the current head with valid machine state.
|
||||
They fail visibly before any reviewer starts when that prerequisite is missing, stale, or invalid; automatic CI and classification-complete races instead skip normally.
|
||||
Model analysis fails closed when the reviewable pull request diff exceeds the applicable evidence limit.
|
||||
The trusted `evidence-diff-attributes` policy represents reproducibly verified generated artifacts with binary-change markers.
|
||||
The automation posts guidance on the pull request instead of invoking a model with partial evidence.
|
||||
@@ -24,7 +26,7 @@ The pipeline performs these stages:
|
||||
9. Resolve validated state and publish through the serialized writer.
|
||||
|
||||
`.github/workflows/review-pipeline.yml` is reusable and `workflow_call` is its only trigger.
|
||||
The caller owns the global concurrency lock, the reviewer selection, and publication.
|
||||
The caller owns the concurrency lane, reviewer selection, and publication.
|
||||
The pipeline owns evidence, specialists, aggregation, the general review, validation, and stage recovery.
|
||||
|
||||
`required-reviewers` names the specialists that must succeed, and the caller is authoritative.
|
||||
@@ -198,8 +200,8 @@ Duplicates at confidence 0.85 or greater, legitimacy triage, and `ai-reviewed/2`
|
||||
Unavailable or invalid classification fails closed to maintainer review.
|
||||
|
||||
Bot-authored pull requests do not run automatic routes or label reconciliation.
|
||||
Force mode can override policy gates for an open pull request at its current head.
|
||||
Force mode never bypasses evidence retrieval, output validation, filesystem restrictions, protocol citation validation, or stale-head checks.
|
||||
Force mode can override policy gates for an open pull request at its current head after a trusted, valid classification for that exact head selects its reviewers.
|
||||
Force mode never bypasses classification validity, evidence retrieval, output validation, filesystem restrictions, protocol citation validation, or stale-head checks.
|
||||
|
||||
## Size and fork limits
|
||||
|
||||
@@ -230,15 +232,18 @@ Attempt-scoped workflow artifacts carry evidence and validated results between r
|
||||
Only the final writer mutates pull request state, and it serializes those mutations per pull request.
|
||||
Model-execution jobs have read-only or empty permissions.
|
||||
|
||||
Two static classifier concurrency lanes allow at most two classifier jobs to invoke Helmcode at once.
|
||||
The reusable `.github/workflows/review-pipeline.yml` runs under one global caller-job lock and allows at most three specialist requests at once.
|
||||
The general reviewer starts only after all specialists finish, so these limits keep Helmcode usage within the five-request API-key limit.
|
||||
Four static classifier lanes allow at most four classifier jobs to invoke Helmcode at once.
|
||||
Seven static caller-job lanes lock each reusable review pipeline from evidence through its result.
|
||||
Each pipeline allows at most three specialist requests at once, for at most 25 model requests across the classifier and reviewer lanes.
|
||||
The general reviewer starts only after all specialists finish.
|
||||
|
||||
Inline comments target only validated added lines.
|
||||
Other findings appear in the review body.
|
||||
All model prose is escaped to neutralize Markdown, HTML, mentions, issue references, and links.
|
||||
|
||||
Specialist failures are recorded explicitly.
|
||||
An optional specialist failure completes the review with reduced coverage and names the unavailable reviewer in the review and check.
|
||||
Detailed failure reasons appear only in the workflow summary.
|
||||
Every failed stage is reported, not only the first one.
|
||||
A mandatory specialist failure, invalid aggregate, invalid final review, exhausted limit, provider failure, or unavailable evidence fails closed to `maintainer-required`.
|
||||
Stale heads stop publication without mutation.
|
||||
|
||||
@@ -13,7 +13,7 @@ const { validateCandidateReview } = require("./validate-candidate-review");
|
||||
const {
|
||||
provenancePrefix, validateFinalReview, validateNormalizedFinalReview,
|
||||
} = require("./validate-final-review");
|
||||
const { buildSpecialistAggregate, validateSpecialistRun } = require("./review-pipeline");
|
||||
const { buildSpecialistAggregate, validateReviewGate, validateSpecialistRun } = require("./review-pipeline");
|
||||
const { resolveReviewerRoute, validateReviewerRoute } = require("./routing");
|
||||
const {
|
||||
resolveClassificationState, resolveReviewState, reviewOutcome, reviewPolicyEligible, DUPLICATE_MARKER,
|
||||
@@ -23,7 +23,7 @@ const {
|
||||
const { resolvePr } = require("./resolve-pr");
|
||||
const { resolveClassificationGate } = require("./classification-gate");
|
||||
const {
|
||||
StaleHeadError, StalePolicyError, applyLabels, escapeMarkdown, markerBody, writeState,
|
||||
StalePolicyError, applyLabels, escapeMarkdown, markerBody, writeState,
|
||||
} = require("./write-state");
|
||||
const { forkRateLimit } = require("./fork-rate-limit");
|
||||
const { reviewSkipReasons } = require("./review-skip-summary");
|
||||
@@ -43,7 +43,7 @@ const {
|
||||
REPORT_VERSION, buildReport, parseReport, stageIds, stageOutcome,
|
||||
} = require("./review-report");
|
||||
const {
|
||||
MAXIMUM_DELAY_SECONDS, delayedRetryGate, retryGateStep,
|
||||
MAXIMUM_DELAY_SECONDS, StaleHeadError, delayedRetryGate, retryGateStep,
|
||||
} = require("./review-retry");
|
||||
const {
|
||||
TERMINAL_CODE, validateGeneral, validateSpecialist,
|
||||
@@ -105,6 +105,52 @@ function resolveReviewScript(workflow = readWorkflow()) {
|
||||
return match[1].replace(/^ {13}/gm, "");
|
||||
}
|
||||
|
||||
function reviewGateScript(workflow = readWorkflow()) {
|
||||
const job = workflowJob(workflow, "review-gate");
|
||||
const match = job.match(/script: \|\n((?: {12}.*\n?)+)/);
|
||||
assert.ok(match, "review-gate script is missing");
|
||||
return match[1].replace(/^ {12}/gm, "");
|
||||
}
|
||||
|
||||
async function runReviewGateScript({
|
||||
force = false, route = "classification-complete", classificationRuns = [], labels = [],
|
||||
author = { type: "User", login: "member", nodeId: "U_1", association: "MEMBER" },
|
||||
} = {}) {
|
||||
const outputs = new Map();
|
||||
const failures = [];
|
||||
const core = {
|
||||
setOutput: (name, value) => outputs.set(name, value),
|
||||
setFailed: (message) => failures.push(message),
|
||||
info: () => {},
|
||||
warning: () => {},
|
||||
};
|
||||
const github = {
|
||||
rest: {
|
||||
checks: {
|
||||
listForRef: async () => ({ data: { check_runs: classificationRuns } }),
|
||||
},
|
||||
issues: {
|
||||
get: async () => ({ data: { labels: labels.map((name) => ({ name })) } }),
|
||||
},
|
||||
actions: {
|
||||
listWorkflowRunsForRepo: async () => ({ data: {
|
||||
workflow_runs: [{ name: "CI", conclusion: "success" }],
|
||||
} }),
|
||||
},
|
||||
},
|
||||
};
|
||||
const context = { repo: { owner: "Devolutions", repo: "IronRDP" } };
|
||||
const process = { env: {
|
||||
PULL_REQUEST_NUMBER: "1", HEAD_SHA: SHA, FORCE: String(force),
|
||||
LABELS: JSON.stringify(labels), AUTHOR: JSON.stringify(author), ROUTE: route,
|
||||
} };
|
||||
const rootRequire = createRequire(path.join(__dirname, "..", "..", "labeler.js"));
|
||||
await new AsyncFunction("core", "github", "context", "require", "process", reviewGateScript())(
|
||||
core, github, context, rootRequire, process,
|
||||
);
|
||||
return { gate: JSON.parse(outputs.get("gate")), eligible: outputs.get("eligible"), failures };
|
||||
}
|
||||
|
||||
async function runResolveReviewScript({ report, pipelineResult = "success" }) {
|
||||
const outputs = new Map();
|
||||
const summary = [];
|
||||
@@ -127,6 +173,7 @@ async function runResolveReviewScript({ report, pipelineResult = "success" }) {
|
||||
HEAD_SHA: SHA, BASE_SHA: "c".repeat(40),
|
||||
GATE: JSON.stringify({
|
||||
ok: true, head_sha: SHA, labels: ["risk/low"], classificationCheck: true, ciGreen: true,
|
||||
classificationValid: true,
|
||||
protocolRelated: false, risk: "low",
|
||||
specialistReviewers: [], contributor: { status: "eligible" },
|
||||
}),
|
||||
@@ -188,6 +235,14 @@ test("automatic review requires exact-head CI and only reruns after a later push
|
||||
/ok: classificationCheck && ciGreen && secondReviewEligible && policyEligible/);
|
||||
assert.match(workflowJob(workflow, "classification-gate"), /'ai-reviewed\/2'/);
|
||||
assert.match(reviewPipeline, /review-gate\.outputs\.eligible == 'true'/);
|
||||
assert.match(reviewPipeline, /needs\.resolve-pr\.outputs\.force == 'true'/);
|
||||
const resolvePrJob = workflowJob(workflow, "resolve-pr");
|
||||
assert.match(resolvePrJob, /"classifier-lane", result\.prNumber \? \(Number\(result\.prNumber\) % 4\) \+ 1 : ""/);
|
||||
assert.match(resolvePrJob, /"reviewer-pipeline-lane", result\.prNumber \? \(Number\(result\.prNumber\) % 7\) \+ 1 : ""/);
|
||||
assert.match(resolvePrJob, /reviewer-pipeline-lane: \$\{\{ steps\.resolve\.outputs\.reviewer-pipeline-lane \}\}/);
|
||||
assert.match(reviewPipeline, /group: llm-reviewer-pipeline-\$\{\{ needs\.resolve-pr\.outputs\.reviewer-pipeline-lane \}\}/);
|
||||
assert.doesNotMatch(reviewPipeline, /fromJSON\(needs\.resolve-pr\.outputs\.pr-number\) %/);
|
||||
assert.doesNotMatch(reviewPipeline, /group: llm-reviewer-pipeline\n/);
|
||||
assert.match(reviewGate, /required-reviewers: \$\{\{ steps\.gate\.outputs\.required-reviewers \}\}/);
|
||||
assert.match(reviewPipeline, /required-reviewers: \$\{\{ needs\.review-gate\.outputs\.required-reviewers \}\}/);
|
||||
assert.match(reviewPipeline, /actions: read/);
|
||||
@@ -201,6 +256,7 @@ test("automatic review requires exact-head CI and only reruns after a later push
|
||||
assert.match(reviewState, /parseReport\(process\.env\.REVIEW_REPORT\)/);
|
||||
assert.match(reviewState, /report\.status === "success" \? parse\(process\.env\.RAW_OUTPUT, null\) : null/);
|
||||
assert.match(reviewState, /renderReviewReport/);
|
||||
assert.doesNotMatch(reviewState, /specialistReviewers: \["skeptical", "code-compressor"\]/);
|
||||
assert.match(reviewState, /REVIEW_GATE_RESULT: \$\{\{ needs\.review-gate\.result \}\}/);
|
||||
assert.match(reviewState, /FORK_RATE_LIMIT_RESULT: \$\{\{ needs\.fork-rate-limit\.result \}\}/);
|
||||
assert.match(reviewState, /REVIEW_PIPELINE_RESULT: \$\{\{ needs\.review-pipeline\.result \}\}/);
|
||||
@@ -235,6 +291,49 @@ test("review skip summary lists every failed gate condition", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("manual reviews with no valid classification fail as invocation errors", async () => {
|
||||
for (const force of [false, true]) {
|
||||
const result = await runReviewGateScript({ force, route: "dispatch" });
|
||||
assert.deepEqual(result.gate, {
|
||||
ok: false, force, head_sha: SHA, classificationValid: false,
|
||||
classificationCheck: false, legitimacyStopped: false, ciGreen: false,
|
||||
secondReviewEligible: false, policyEligible: false, labels: [],
|
||||
protocolRelated: false, risk: "unknown", specialistReviewers: [],
|
||||
contributor: { status: force ? "forced" : "unavailable" },
|
||||
reason: "valid classification unavailable",
|
||||
});
|
||||
assert.equal(result.eligible, false);
|
||||
assert.deepEqual(result.failures,
|
||||
["manual or forced review requires a valid classification for the current head"]);
|
||||
}
|
||||
|
||||
const automatic = await runReviewGateScript();
|
||||
assert.equal(automatic.eligible, false);
|
||||
assert.deepEqual(automatic.failures, []);
|
||||
});
|
||||
|
||||
test("automatic policy ineligibility remains a non-error gate skip", async () => {
|
||||
const machineState = {
|
||||
protocolRelated: false, risk: "low", specialistReviewers: [],
|
||||
automaticReviewEligible: true,
|
||||
};
|
||||
const result = await runReviewGateScript({
|
||||
labels: ["duplicate"],
|
||||
classificationRuns: [{
|
||||
id: 1, external_id: `${CLASSIFIER_SCHEMA_VERSION}:${SHA}`, conclusion: "success",
|
||||
app: { slug: "github-actions" },
|
||||
output: {
|
||||
title: "Classification complete",
|
||||
summary: `Validated classification.\n\n${encodeCheckState(machineState)}`,
|
||||
},
|
||||
}],
|
||||
});
|
||||
assert.equal(result.gate.ok, false);
|
||||
assert.equal(result.gate.policyEligible, false);
|
||||
assert.equal(result.eligible, false);
|
||||
assert.deepEqual(result.failures, []);
|
||||
});
|
||||
|
||||
test("review outcome requires validated final output", () => {
|
||||
assert.equal(reviewOutcome({
|
||||
reportStatus: "success",
|
||||
@@ -243,6 +342,12 @@ test("review outcome requires validated final output", () => {
|
||||
}), "unavailable");
|
||||
assert.equal(reviewOutcome({ reportStatus: "success", state: {}, recovered: true }), "recovered");
|
||||
assert.equal(reviewOutcome({ reportStatus: "success", state: {}, recovered: false }), "complete");
|
||||
assert.equal(reviewOutcome({
|
||||
reportStatus: "success", state: {}, reducedCoverage: ["code-compressor"],
|
||||
}), "reduced-coverage");
|
||||
assert.equal(reviewOutcome({
|
||||
reportStatus: "success", state: {}, recovered: true, reducedCoverage: ["code-compressor"],
|
||||
}), "recovered-reduced-coverage");
|
||||
assert.equal(reviewOutcome({ reportStatus: "failed", state: {}, recovered: true }), "unavailable");
|
||||
});
|
||||
|
||||
@@ -253,7 +358,7 @@ test("resolve review state renders bounded recovery diagnostics in the check and
|
||||
metrics: { tokens: null, elapsed_ms: 0, request_retries: null, output_repairs: null },
|
||||
},
|
||||
{
|
||||
id: "general", status: "success", attempts: 2,
|
||||
id: "general", status: "success", attempts: 2, provider: true,
|
||||
previous_reason: "retry declined | malformed <payload>",
|
||||
metrics: {
|
||||
tokens: { input: 0, output: 4, complete: false },
|
||||
@@ -282,14 +387,15 @@ test("resolve review state renders bounded recovery diagnostics in the check and
|
||||
},
|
||||
});
|
||||
assert.match(recovered.state.check.summary, /Validated automated review was produced after stage recovery/);
|
||||
assert.match(recovered.state.check.summary, /retry declined \\| malformed <payload>/);
|
||||
assert.match(recovered.state.check.summary, /0\/4\/(?:unknown|unavailable) \\\(partial\\\)/);
|
||||
assert.doesNotMatch(recovered.state.check.summary, /retry declined \\| malformed <payload>/);
|
||||
assert.match(recovered.state.check.summary, /Input tokens/);
|
||||
assert.match(recovered.state.check.summary, /Cumulative elapsed/);
|
||||
assert.match(recovered.state.check.summary, /\| 0 \|/);
|
||||
assert.match(recovered.state.check.summary, /unavailable/);
|
||||
assert.match(recovered.state.check.summary, /View the workflow summary/);
|
||||
assert.equal(recovered.state.check.conclusion, "success");
|
||||
assert.match(recovered.summary, /retry declined \\| malformed <payload>/);
|
||||
assert.match(recovered.summary, /Per-stage metrics/);
|
||||
assert.match(recovered.summary, /LLM stage metrics/);
|
||||
|
||||
const terminal = await runResolveReviewScript({
|
||||
report: {
|
||||
@@ -324,8 +430,8 @@ test("resolve review state renders bounded recovery diagnostics in the check and
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.match(terminal.state.check.summary, /protocol: provider unavailable/);
|
||||
assert.match(terminal.state.check.summary, /retry-declined/);
|
||||
assert.doesNotMatch(terminal.state.check.summary, /provider unavailable/);
|
||||
assert.doesNotMatch(terminal.state.check.summary, /retry-declined/);
|
||||
assert.match(terminal.state.check.summary, /unavailable/);
|
||||
assert.equal(terminal.state.check.conclusion, "neutral");
|
||||
|
||||
@@ -342,7 +448,7 @@ test("resolve review state renders bounded recovery diagnostics in the check and
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.match(missing.state.check.summary, /no usable report/);
|
||||
assert.doesNotMatch(missing.state.check.summary, /no usable report/);
|
||||
assert.match(missing.state.check.summary, /unavailable/);
|
||||
|
||||
const bounded = renderReviewReport({
|
||||
@@ -370,6 +476,25 @@ test("resolve review state renders bounded recovery diagnostics in the check and
|
||||
assert.match(bounded.workflowSummary, /stage-15-/);
|
||||
});
|
||||
|
||||
test("review gates require classification before forced work starts", () => {
|
||||
const valid = {
|
||||
ok: true, force: true, head_sha: SHA, classificationValid: true,
|
||||
protocolRelated: true, risk: "medium",
|
||||
specialistReviewers: ["protocol", "skeptical"],
|
||||
};
|
||||
assert.equal(validateReviewGate(valid, SHA, valid.specialistReviewers).ok, true);
|
||||
assert.equal(validateReviewGate({ ...valid, classificationValid: false }, SHA).ok, false);
|
||||
assert.equal(validateReviewGate({ ...valid, specialistReviewers: ["skeptical"] }, SHA).ok, false);
|
||||
|
||||
const rejected = resolveReviewState({
|
||||
expectedSha: SHA, labels: [], reviewer: review(), gate: {
|
||||
...valid, classificationValid: false,
|
||||
}, force: true, reviewMarkerId: "1",
|
||||
});
|
||||
assert.equal(rejected.failed, true);
|
||||
assert.match(rejected.reason, /classification gate unavailable/);
|
||||
});
|
||||
|
||||
test("review skip summary explains gate and quota failures", () => {
|
||||
assert.deepEqual(reviewSkipReasons({
|
||||
gateResult: "success",
|
||||
@@ -643,7 +768,10 @@ test("evidence caps are trusted, bounded, and fail closed with guidance", () =>
|
||||
assert.match(markerBody(classification.comments[0]), /ai-review\/allow-oversized/);
|
||||
|
||||
const reviewFailure = resolveReviewState({
|
||||
expectedSha: SHA, labels: [], gate: { force: true, head_sha: SHA },
|
||||
expectedSha: SHA, labels: [], gate: {
|
||||
ok: true, force: true, head_sha: SHA, classificationValid: true,
|
||||
protocolRelated: false, risk: "unknown", specialistReviewers: ["skeptical"],
|
||||
},
|
||||
reviewerReason: "pull request diff exceeds the 4 MiB evidence limit",
|
||||
force: true, reviewMarkerId: "1",
|
||||
});
|
||||
@@ -1530,7 +1658,7 @@ test("forced review bypasses eligibility while retaining publication gates", ()
|
||||
labels: ["ai-reviewed/2", "duplicate", "size/XXL", "risk/low"],
|
||||
reviewer,
|
||||
gate: {
|
||||
ok: true, force: true, head_sha: SHA, protocolRelated: false,
|
||||
ok: true, force: true, head_sha: SHA, classificationValid: true, protocolRelated: false,
|
||||
risk: "unknown", specialistReviewers: ["skeptical"],
|
||||
},
|
||||
contributor: { status: "ineligible" },
|
||||
@@ -1963,6 +2091,7 @@ test("classification dispatch remains edge-triggered except for explicit retries
|
||||
},
|
||||
reviewRequested,
|
||||
});
|
||||
|
||||
return { creates, updates, dispatches };
|
||||
};
|
||||
|
||||
@@ -1981,6 +2110,100 @@ test("classification dispatch remains edge-triggered except for explicit retries
|
||||
});
|
||||
});
|
||||
|
||||
test("writer retries a truncated current-head read before dispatching once", async () => {
|
||||
let reads = 0;
|
||||
let checkWrites = 0;
|
||||
let dispatches = 0;
|
||||
const machineState = {
|
||||
protocolRelated: false, risk: "low", specialistReviewers: [],
|
||||
automaticReviewEligible: true,
|
||||
};
|
||||
const state = {
|
||||
ok: true, mode: "classification", expectedSha: SHA, labelSets: [], addLabels: [],
|
||||
comments: [], removeCommentMarkers: [], dispatchReview: true,
|
||||
check: {
|
||||
name: "AI classification", externalId: `${CLASSIFIER_SCHEMA_VERSION}:${SHA}`,
|
||||
title: "Classification complete", summary: "Validated classification.", machineState,
|
||||
},
|
||||
};
|
||||
const github = {
|
||||
paginate: { iterator: async function* () { yield { data: [] }; } },
|
||||
rest: {
|
||||
checks: { listForRef: () => {}, create: async () => { checkWrites += 1; } },
|
||||
pulls: { get: async () => {
|
||||
reads += 1;
|
||||
if (reads === 3) {
|
||||
const error = new Error("Unexpected end of JSON input");
|
||||
error.status = 500;
|
||||
throw error;
|
||||
}
|
||||
return { data: { state: "open", head: { sha: SHA } } };
|
||||
} },
|
||||
issues: { get: async () => ({ data: { labels: [] } }) },
|
||||
repos: { createDispatchEvent: async () => { dispatches += 1; } },
|
||||
},
|
||||
};
|
||||
await writeState({
|
||||
github, owner: "Devolutions", repo: "IronRDP", prNumber: 1, botLogin: "github-actions[bot]",
|
||||
state,
|
||||
});
|
||||
assert.equal(reads, 4);
|
||||
assert.equal(checkWrites, 1);
|
||||
assert.equal(dispatches, 1);
|
||||
|
||||
const failedDispatch = async (errorAtRead) => {
|
||||
let failedReads = 0;
|
||||
let failedCheckWrites = 0;
|
||||
let failedDispatches = 0;
|
||||
const github = {
|
||||
paginate: { iterator: async function* () { yield { data: [] }; } },
|
||||
rest: {
|
||||
checks: { listForRef: () => {}, create: async () => { failedCheckWrites += 1; } },
|
||||
pulls: { get: async () => {
|
||||
failedReads += 1;
|
||||
if (failedReads > 2) {
|
||||
const result = errorAtRead(failedReads);
|
||||
if (result instanceof Error) throw result;
|
||||
return { data: { state: "open", head: { sha: result } } };
|
||||
}
|
||||
return { data: { state: "open", head: { sha: SHA } } };
|
||||
} },
|
||||
issues: { get: async () => ({ data: { labels: [] } }) },
|
||||
repos: { createDispatchEvent: async () => { failedDispatches += 1; } },
|
||||
},
|
||||
};
|
||||
await assert.rejects(writeState({
|
||||
github, owner: "Devolutions", repo: "IronRDP", prNumber: 1, botLogin: "github-actions[bot]",
|
||||
state,
|
||||
}));
|
||||
return { failedReads, failedCheckWrites, failedDispatches };
|
||||
};
|
||||
|
||||
const terminal = await failedDispatch(() => {
|
||||
const error = new Error("internal server error");
|
||||
error.status = 500;
|
||||
return error;
|
||||
});
|
||||
assert.deepEqual(terminal, { failedReads: 3, failedCheckWrites: 1, failedDispatches: 0 });
|
||||
|
||||
const staleRetry = await failedDispatch((read) => {
|
||||
if (read === 3) {
|
||||
const error = new Error("Unexpected end of JSON input");
|
||||
error.status = 500;
|
||||
return error;
|
||||
}
|
||||
return OTHER_SHA;
|
||||
});
|
||||
assert.deepEqual(staleRetry, { failedReads: 4, failedCheckWrites: 1, failedDispatches: 0 });
|
||||
|
||||
const exhausted = await failedDispatch(() => {
|
||||
const error = new Error("Unexpected end of JSON input");
|
||||
error.status = 500;
|
||||
return error;
|
||||
});
|
||||
assert.deepEqual(exhausted, { failedReads: 4, failedCheckWrites: 1, failedDispatches: 0 });
|
||||
});
|
||||
|
||||
test("writer does not dispatch a completed classification after the head changes", async () => {
|
||||
let headReads = 0;
|
||||
let dispatches = 0;
|
||||
@@ -2226,6 +2449,63 @@ test("writer publishes a green main comment when no findings remain", async () =
|
||||
assert.match(published.body, /:green_circle: No findings identified\./);
|
||||
});
|
||||
|
||||
test("writer adds deterministic reduced-coverage notices without filtering findings", async () => {
|
||||
let published;
|
||||
const github = {
|
||||
paginate: { iterator: async function* () { yield { data: [] }; } },
|
||||
rest: {
|
||||
pulls: {
|
||||
listReviews: () => {},
|
||||
get: async () => ({ data: { state: "open", head: { sha: SHA } } }),
|
||||
createReview: async (payload) => { published = payload; },
|
||||
},
|
||||
issues: { get: async () => ({ data: { labels: [] } }) },
|
||||
},
|
||||
};
|
||||
await writeState({
|
||||
github, owner: "Devolutions", repo: "IronRDP", prNumber: 1, botLogin: "github-actions[bot]",
|
||||
state: {
|
||||
ok: true, mode: "review", expectedSha: SHA, labelSets: [], addLabels: [],
|
||||
expectedReviewCount: null, forced: false, protocolRelated: false,
|
||||
comments: [{
|
||||
kind: "review", marker: `<!-- ironrdp-pr-automation:review:${SHA} -->`,
|
||||
reducedCoverage: ["protocol"],
|
||||
review: review({ findings: [finding({ confidence: 0.01 })] }),
|
||||
}],
|
||||
},
|
||||
});
|
||||
assert.match(published.body, /Reduced coverage: optional reviewer protocol was unavailable/);
|
||||
assert.equal(published.comments.length, 1);
|
||||
});
|
||||
|
||||
test("review checks name reduced coverage without publishing failure reasons", () => {
|
||||
const report = buildReport([
|
||||
{ id: "evidence", status: "success", required: true },
|
||||
{ id: "specialist:code-compressor", status: "failed", provider: true,
|
||||
reason: "provider timeout with internal details", category: "provider-timeout" },
|
||||
{ id: "aggregate", status: "success", required: true },
|
||||
{ id: "general", status: "success", required: true, provider: true },
|
||||
{ id: "validate", status: "success", required: true },
|
||||
]);
|
||||
const rendered = renderReviewReport({
|
||||
report, outcome: "recovered-reduced-coverage", reducedCoverage: ["code-compressor"],
|
||||
summaryUrl: "https://github.example/actions/runs/123",
|
||||
});
|
||||
assert.equal(rendered.checkSummary.split("\n\n")[0],
|
||||
"Validated automated review was produced after stage recovery with reduced coverage: " +
|
||||
"optional reviewer code-compressor was unavailable.");
|
||||
assert.match(rendered.checkSummary, /code-compressor/);
|
||||
assert.doesNotMatch(rendered.checkSummary, /provider timeout with internal details/);
|
||||
assert.match(rendered.workflowSummary, /provider timeout with internal details/);
|
||||
const multiple = renderReviewReport({
|
||||
report, outcome: "reduced-coverage", reducedCoverage: ["skeptical", "code-compressor"],
|
||||
summaryUrl: "https://github.example/actions/runs/123",
|
||||
});
|
||||
assert.equal(multiple.checkSummary.split("\n\n")[0],
|
||||
"Validated automated review is bound to this commit with reduced coverage: " +
|
||||
"optional reviewers skeptical, code-compressor were unavailable.");
|
||||
});
|
||||
|
||||
function paginated(pages) {
|
||||
return {
|
||||
paginate: { iterator: async function* (_method, options) {
|
||||
@@ -2888,6 +3168,11 @@ test("a retry re-decides review eligibility against the pull request as it is af
|
||||
// stage sleeps must not buy a second provider request.
|
||||
assert.deepEqual(await gate({ classificationTitle: "Automation stopped" }),
|
||||
{ retry: false, reason: "classification no longer authorizes an automatic review" });
|
||||
assert.deepEqual(await gate({ classificationTitle: "Automation stopped" }, { force: true }),
|
||||
{ retry: true, reason: "" });
|
||||
const reviewGate = workflowJob(readWorkflow(path.join(__dirname, "..")), "review-gate");
|
||||
assert.match(reviewGate, /const classificationValid = classificationOwned && protocolState !== null;/);
|
||||
assert.match(reviewGate, /const classificationCheck = classificationValid &&\s+classification\.output\?\.title === "Classification complete"/);
|
||||
|
||||
// A stale classification bound to an older head cannot authorize this one.
|
||||
assert.equal((await gate({ classificationHeadSha: OTHER_SHA })).retry, false);
|
||||
@@ -2924,7 +3209,7 @@ test("the caller's force bypasses review policy, and nothing that makes a review
|
||||
|
||||
for (const state of [
|
||||
{ draft: true }, { labels: ["triage/legitimacy"] }, { ciConclusion: "failure" },
|
||||
{ classificationConclusion: "failure" }, { alreadyReviewed: true }, { authorType: "Bot" },
|
||||
{ alreadyReviewed: true }, { authorType: "Bot" },
|
||||
]) {
|
||||
assert.equal((await gate(state)).retry, true, JSON.stringify(state));
|
||||
}
|
||||
@@ -3053,6 +3338,25 @@ test("a provider stage that never reported usage keeps the totals honest", () =>
|
||||
{ id: "general", status: "failed", required: true, reason: "provider unavailable",
|
||||
provider: providerWasCalled(parseDiagnostics("")), metrics: parseDiagnostics("") },
|
||||
]).metrics.tokens_complete, false);
|
||||
|
||||
const metrics = buildReport([
|
||||
{ id: "evidence", status: "success", required: true, attempts: 2, metrics: {
|
||||
tokens: { input: 100, output: 20, total: 120, complete: true },
|
||||
elapsed_ms: 1000, request_retries: 3, output_repairs: 2,
|
||||
} },
|
||||
{ id: "general", status: "success", required: true, provider: true, metrics: {
|
||||
tokens: { input: 10, output: 2, total: 12, complete: true },
|
||||
elapsed_ms: 100, request_retries: 1, output_repairs: 0,
|
||||
} },
|
||||
]).metrics;
|
||||
assert.deepEqual(metrics, {
|
||||
tokens: { input: 10, output: 2, total: 12 },
|
||||
tokens_complete: true,
|
||||
elapsed_ms: 100,
|
||||
request_retries: 1,
|
||||
output_repairs: 0,
|
||||
stage_retries: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test("the caller reads exactly what the pipeline wrote, and never reads garbage as success", () => {
|
||||
@@ -3317,6 +3621,9 @@ test("the mandatory reviewer set is resolved once and read everywhere else", ()
|
||||
|
||||
// One interpretation, taken before any provider work, so an unusable plan fails closed early.
|
||||
assert.match(evidence, /resolveRequiredReviewers/, "evidence must resolve the required set");
|
||||
const plan = evidence.slice(evidence.indexOf("- id: plan"), evidence.indexOf("Fetch bounded review"));
|
||||
assert.match(plan, /HEAD_SHA: \$\{\{ inputs\.head-sha \}\}/,
|
||||
"the plan must validate the gate against the reusable workflow's reviewed head");
|
||||
assert.match(evidence, /if \(!resolved\.ok\) \{/);
|
||||
assert.match(evidence, /throw new Error\(resolved\.reason\)/);
|
||||
assert.ok(evidence.indexOf("id: plan") < evidence.indexOf("Fetch bounded review"),
|
||||
@@ -3372,8 +3679,12 @@ async function runFirstStepScript(jobName, env) {
|
||||
|
||||
test("the review plan keeps the gate fallback for a caller that sends no required list", async () => {
|
||||
const base = {
|
||||
HEAD_SHA: SHA,
|
||||
SELECTED_REVIEWERS: JSON.stringify(REVIEWABLE_REVIEWERS),
|
||||
GATE: JSON.stringify({ protocolRelated: true, risk: "medium" }),
|
||||
GATE: JSON.stringify({
|
||||
ok: true, head_sha: SHA, classificationValid: true, classificationCheck: true,
|
||||
protocolRelated: true, risk: "medium", specialistReviewers: REVIEWABLE_REVIEWERS,
|
||||
}),
|
||||
};
|
||||
const planned = async (env) => JSON.parse(
|
||||
(await runFirstStepScript("evidence", env)).outputs["required-reviewers"],
|
||||
@@ -3413,7 +3724,7 @@ test("the review plan keeps the gate fallback for a caller that sends no require
|
||||
}).then(() => null, (error) => error);
|
||||
assert.ok(noncanonical !== null, "a noncanonical plan must fail the job");
|
||||
assert.match(String(noncanonical.stepOutputs["failure-reason"]),
|
||||
/invalid specialist execution plan/);
|
||||
/reviewers differ from the classification route/);
|
||||
|
||||
const evidence = workflowJob(readReviewWorkflow().slice(readReviewWorkflow().indexOf("\njobs:")),
|
||||
"evidence");
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
const { SCHEMA_VERSION: CLASSIFIER_SCHEMA_VERSION, validateClassifier } = require("./validate-classifier");
|
||||
const { validateNormalizedFinalReview } = require("./validate-final-review");
|
||||
const { resolveReviewerRoute, reviewPolicyEligible, validateReviewerRoute } = require("./routing");
|
||||
const { resolveReviewerRoute, reviewPolicyEligible } = require("./routing");
|
||||
const { validateReviewGate } = require("./review-pipeline");
|
||||
|
||||
const RISK = ["risk/low", "risk/medium", "risk/high", "risk/unknown"];
|
||||
const AI_COUNTS = ["ai-reviewed/1", "ai-reviewed/2"];
|
||||
@@ -253,7 +254,7 @@ async function contributorEligibility({ github, owner, repo, author, currentPrNu
|
||||
|
||||
function resolveReviewState({
|
||||
expectedSha, labels, reviewer, gate, contributor,
|
||||
rateLimit, reviewerReason, force, reviewMarkerId,
|
||||
rateLimit, reviewerReason, force, reviewMarkerId, reducedCoverage,
|
||||
} = {}) {
|
||||
const existing = labelsOf(labels);
|
||||
const forced = force === true;
|
||||
@@ -283,6 +284,8 @@ function resolveReviewState({
|
||||
if (typeof expectedSha !== "string") return { ok: false, reason: "missing expected SHA" };
|
||||
if (forced) {
|
||||
if (gate?.force !== true || gate.head_sha !== expectedSha) return fail("forced review gate unavailable");
|
||||
const classification = validateReviewGate(gate, expectedSha);
|
||||
if (!classification.ok) return fail(classification.reason);
|
||||
if (typeof reviewMarkerId !== "string" || !/^[1-9]\d{0,19}$/.test(reviewMarkerId)) {
|
||||
return fail("forced review marker unavailable");
|
||||
}
|
||||
@@ -293,13 +296,9 @@ function resolveReviewState({
|
||||
const reason = gate?.reason ? `review gate unavailable: ${gate.reason}` : "review gate unavailable";
|
||||
return fail(reason);
|
||||
}
|
||||
const classification = validateReviewGate({ ...gate, ok: true }, expectedSha);
|
||||
if (!classification.ok) return fail(classification.reason);
|
||||
if (gate.classificationCheck !== true || gate.ciGreen !== true) return fail("review gate unavailable");
|
||||
const route = validateReviewerRoute({
|
||||
reviewers: gate.specialistReviewers,
|
||||
protocolRelated: gate.protocolRelated,
|
||||
risk: gate.risk,
|
||||
});
|
||||
if (!route.ok) return fail("reviewer route unavailable");
|
||||
if (contributor?.status === "ineligible") {
|
||||
const reason = Number.isSafeInteger(contributor.merged)
|
||||
? `contributor history ineligible (merged: ${contributor.merged}, required: ${ELIGIBLE_MERGED_PRS})`
|
||||
@@ -340,7 +339,10 @@ function resolveReviewState({
|
||||
ok: true, mode: "review", expectedSha, labelSets: [{ owned: AI_COUNTS, desired: [nextCount] }],
|
||||
addLabels: nextCount === "ai-reviewed/2" || !hasFindings ? ["maintainer-required"] : [],
|
||||
removeLabels: nextCount === "ai-reviewed/1" && hasFindings ? ["maintainer-required"] : [],
|
||||
comments: [{ kind: "review", marker: reviewMarker, review: reviewerResult.value }],
|
||||
comments: [{
|
||||
kind: "review", marker: reviewMarker, review: reviewerResult.value,
|
||||
reducedCoverage: Array.isArray(reducedCoverage) ? reducedCoverage : [],
|
||||
}],
|
||||
removeCommentMarkers: [
|
||||
EVIDENCE_LIMIT_MARKER, FORK_QUOTA_MARKER, GLOBAL_QUOTA_MARKER,
|
||||
CONTRIBUTOR_INELIGIBLE_MARKER,
|
||||
@@ -352,8 +354,11 @@ function resolveReviewState({
|
||||
};
|
||||
}
|
||||
|
||||
function reviewOutcome({ reportStatus, state, recovered = false } = {}) {
|
||||
function reviewOutcome({ reportStatus, state, recovered = false, reducedCoverage = [] } = {}) {
|
||||
if (reportStatus !== "success" || state?.failed === true) return "unavailable";
|
||||
if (Array.isArray(reducedCoverage) && reducedCoverage.length > 0) {
|
||||
return recovered ? "recovered-reduced-coverage" : "reduced-coverage";
|
||||
}
|
||||
return recovered ? "recovered" : "complete";
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
const { normalizeCandidateReview } = require("./validate-candidate-review");
|
||||
const { validateProtocolReferences } = require("./validate-protocol-review");
|
||||
const {
|
||||
REVIEWER_ORDER: SPECIALIST_ORDER, normalizeReviewerIds, resolveReviewerRoute,
|
||||
REVIEWER_ORDER: SPECIALIST_ORDER, normalizeReviewerIds, resolveReviewerRoute, validateReviewerRoute,
|
||||
} = require("./routing");
|
||||
const { SHA, exactKeys, invalid, normalizeText } = require("./validation");
|
||||
const { normalizeStageMetrics } = require("./review-report");
|
||||
@@ -85,6 +85,30 @@ function resolveRequiredReviewers({
|
||||
return { ok: true, reviewers: route.reviewers, source: "gate" };
|
||||
}
|
||||
|
||||
function validateReviewGate(gate, expectedSha, selectedReviewers) {
|
||||
const classificationValid = gate?.classificationValid ??
|
||||
(gate?.force !== true && gate?.classificationCheck === true);
|
||||
if (!gate || typeof gate !== "object" || gate.head_sha !== expectedSha ||
|
||||
gate.ok !== true || classificationValid !== true) {
|
||||
return invalid("valid classification gate unavailable");
|
||||
}
|
||||
if (gate.force !== true && gate.classificationCheck !== true) {
|
||||
return invalid("classification no longer authorizes an automatic review");
|
||||
}
|
||||
const route = validateReviewerRoute({
|
||||
reviewers: gate.specialistReviewers,
|
||||
protocolRelated: gate.protocolRelated,
|
||||
risk: gate.risk,
|
||||
});
|
||||
if (!route.ok) return invalid("invalid classification reviewer route");
|
||||
if (selectedReviewers !== undefined &&
|
||||
(route.reviewers.length !== selectedReviewers.length ||
|
||||
route.reviewers.some((reviewer, index) => reviewer !== selectedReviewers[index]))) {
|
||||
return invalid("reviewers differ from the classification route");
|
||||
}
|
||||
return { ok: true, reviewers: route.reviewers };
|
||||
}
|
||||
|
||||
function buildSpecialistAggregate({
|
||||
expectedSha, selectedReviewers, runs, requiredReviewers, protocolRelated, risk,
|
||||
} = {}) {
|
||||
@@ -219,4 +243,5 @@ module.exports = {
|
||||
SPECIALIST_ORDER,
|
||||
buildSpecialistAggregate, failedRun, isRetryableFailure, mergeDiagnostics, parseDiagnostics,
|
||||
plannedRequiredReviewers, providerWasCalled, resolveRequiredReviewers, validateSpecialistRun,
|
||||
validateReviewGate,
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
const { REVIEWER_ORDER } = require("./routing");
|
||||
const { escapeMarkdown } = require("./write-state");
|
||||
const { escapeMarkdown, reducedCoverageText } = require("./write-state");
|
||||
|
||||
const MAX_CHECK_STAGES = REVIEWER_ORDER.length + 4;
|
||||
const MAX_WORKFLOW_STAGES = 64;
|
||||
@@ -16,11 +16,17 @@ function metric(value) {
|
||||
return value === null ? "unavailable" : value === undefined ? "unknown" : String(value);
|
||||
}
|
||||
|
||||
function tokens(tokens, complete = tokens?.complete) {
|
||||
if (tokens === null) return "unavailable";
|
||||
if (tokens === undefined) return "unknown";
|
||||
function tokenColumns(tokens, complete = tokens?.complete) {
|
||||
if (tokens === null) return ["unavailable", "unavailable", "unavailable"];
|
||||
if (tokens === undefined) return ["unknown", "unknown", "unknown"];
|
||||
const values = ["input", "output", "total"].map((name) => metric(tokens[name]));
|
||||
return `${values.join("/")} ${complete ? "" : "(partial)"}`.trim();
|
||||
values[2] = `${values[2]}${complete ? "" : " (partial)"}`;
|
||||
return values;
|
||||
}
|
||||
|
||||
function seconds(milliseconds) {
|
||||
return milliseconds === null ? "unavailable" :
|
||||
milliseconds === undefined ? "unknown" : String(milliseconds / 1000);
|
||||
}
|
||||
|
||||
function table(headers, rows, maxTextLength) {
|
||||
@@ -40,65 +46,77 @@ function failureAttempts(stages) {
|
||||
});
|
||||
}
|
||||
|
||||
function diagnostics(report, outcome, maxStages, maxTextLength) {
|
||||
function diagnostics(report, outcome, maxStages, maxTextLength, includeReasons) {
|
||||
const stages = report.stages.slice(0, maxStages);
|
||||
const omittedStages = report.stages.length - stages.length;
|
||||
const attempts = failureAttempts(stages);
|
||||
if (omittedStages > 0) attempts.push(["additional stages", "unknown", `${omittedStages} omitted to bound output`]);
|
||||
const metrics = report.metrics;
|
||||
const failedAttempts = attempts.length === 0
|
||||
? "No stage failure was reported."
|
||||
: table(["Stage", "Attempt", "Reason"], attempts, maxTextLength);
|
||||
const totalMetrics = table(["Metric", "Total"], [
|
||||
["Tokens", tokens(metrics.tokens, metrics.tokens_complete)],
|
||||
["Elapsed (ms)", metric(metrics.elapsed_ms)],
|
||||
["Request retries", metric(metrics.request_retries)],
|
||||
["Output repairs", metric(metrics.output_repairs)],
|
||||
["Stage retries", metric(metrics.stage_retries)],
|
||||
], maxTextLength);
|
||||
const stageRows = stages.map((stage) => [
|
||||
stage.id, stage.status, stage.attempts, tokens(stage.metrics.tokens),
|
||||
metric(stage.metrics.elapsed_ms), metric(stage.metrics.request_retries),
|
||||
const stageOutcomes = stages.map((stage) => [stage.id, stage.status, stage.attempts]);
|
||||
if (omittedStages > 0) {
|
||||
stageOutcomes.push(["additional stages", "unknown", `${omittedStages} omitted to bound output`]);
|
||||
}
|
||||
const totalMetrics = table(["Input tokens", "Output tokens", "Total tokens", "Cumulative elapsed (seconds)", "Request retries", "Output repairs", "Stage recoveries"], [[
|
||||
...tokenColumns(metrics.tokens, metrics.tokens_complete),
|
||||
seconds(metrics.elapsed_ms), metric(metrics.request_retries), metric(metrics.output_repairs),
|
||||
metric(metrics.stage_retries),
|
||||
]], maxTextLength);
|
||||
const stageRows = stages.filter((stage) => stage.provider).map((stage) => [
|
||||
stage.id, stage.status, stage.attempts, ...tokenColumns(stage.metrics.tokens),
|
||||
seconds(stage.metrics.elapsed_ms), metric(stage.metrics.request_retries),
|
||||
metric(stage.metrics.output_repairs),
|
||||
]);
|
||||
if (omittedStages > 0) {
|
||||
stageRows.push(["additional stages", "unknown", "unknown", "unknown", "unknown", "unknown",
|
||||
`${omittedStages} omitted to bound output`]);
|
||||
}
|
||||
const stageMetrics = table(
|
||||
["Stage", "Status", "Attempts", "Tokens", "Elapsed (ms)", "Request retries", "Output repairs"],
|
||||
["Stage", "Status", "Attempts", "Input tokens", "Output tokens", "Total tokens",
|
||||
"Cumulative elapsed (seconds)", "Request retries", "Output repairs"],
|
||||
stageRows, maxTextLength,
|
||||
);
|
||||
const reasons = (() => {
|
||||
if (!includeReasons) return "";
|
||||
const attempts = failureAttempts(stages);
|
||||
if (omittedStages > 0) attempts.push(["additional stages", "unknown", `${omittedStages} omitted to bound output`]);
|
||||
return attempts.length === 0
|
||||
? "No stage failure was reported."
|
||||
: table(["Stage", "Attempt", "Reason"], attempts, maxTextLength);
|
||||
})();
|
||||
return [
|
||||
`Review outcome: **${outcome}**.`,
|
||||
"",
|
||||
"### Failed stage attempts",
|
||||
failedAttempts,
|
||||
"### Stage outcomes",
|
||||
table(["Stage", "Status", "Attempts"], stageOutcomes, maxTextLength),
|
||||
"",
|
||||
"### Metrics",
|
||||
totalMetrics,
|
||||
"",
|
||||
"### Per-stage metrics",
|
||||
"Token totals count repeated context across requests and repairs.",
|
||||
"",
|
||||
"### LLM stage metrics",
|
||||
stageMetrics,
|
||||
...(includeReasons ? ["", "### Failed stage attempts", reasons] : []),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function renderReviewReport({ report, outcome, detail, summaryUrl }) {
|
||||
const checkDiagnostics = diagnostics(report, outcome, MAX_CHECK_STAGES, MAX_CHECK_TEXT_LENGTH);
|
||||
const workflowDiagnostics = diagnostics(report, outcome, MAX_WORKFLOW_STAGES, MAX_WORKFLOW_TEXT_LENGTH);
|
||||
function renderReviewReport({ report, outcome, summaryUrl, reducedCoverage = [] }) {
|
||||
const checkDiagnostics = diagnostics(report, outcome, MAX_CHECK_STAGES, MAX_CHECK_TEXT_LENGTH, false);
|
||||
const workflowDiagnostics = diagnostics(report, outcome, MAX_WORKFLOW_STAGES, MAX_WORKFLOW_TEXT_LENGTH, true);
|
||||
const heading = {
|
||||
complete: "Automated review complete",
|
||||
recovered: "Automated review recovered",
|
||||
"reduced-coverage": "Automated review completed with reduced coverage",
|
||||
"recovered-reduced-coverage": "Automated review recovered with reduced coverage",
|
||||
unavailable: "Automated review unavailable",
|
||||
}[outcome];
|
||||
const outcomeText = outcome === "complete"
|
||||
? "Validated automated review is bound to this commit."
|
||||
: outcome === "recovered"
|
||||
? "Validated automated review was produced after stage recovery."
|
||||
: `Automated review is unavailable: ${text(detail || "review unavailable", MAX_CHECK_TEXT_LENGTH)}. Maintainer review is required.`;
|
||||
const outcomeText = outcome === "complete" || outcome === "reduced-coverage"
|
||||
? "Validated automated review is bound to this commit"
|
||||
: outcome === "recovered" || outcome === "recovered-reduced-coverage"
|
||||
? "Validated automated review was produced after stage recovery"
|
||||
: "Automated review is unavailable. Maintainer review is required";
|
||||
const coverage = outcome.endsWith("reduced-coverage")
|
||||
? ` with reduced coverage:${reducedCoverageText(
|
||||
reducedCoverage.map((reviewer) => text(reviewer, MAX_CHECK_TEXT_LENGTH)),
|
||||
)}`
|
||||
: "";
|
||||
return {
|
||||
title: heading,
|
||||
checkSummary: `${outcomeText}\n\n${checkDiagnostics}\n\n[View the workflow summary](${summaryUrl})`,
|
||||
checkSummary: `${outcomeText}${coverage}.\n\n${checkDiagnostics}\n\n[View the workflow summary](${summaryUrl})`,
|
||||
workflowSummary: `# Automated review\n\n${workflowDiagnostics}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -84,6 +84,7 @@ function aggregateMetrics(outcomes) {
|
||||
};
|
||||
let anyTokens = false;
|
||||
for (const stage of outcomes) {
|
||||
if (!stage.provider) continue;
|
||||
if (stage.attempts === 2) metrics.stage_retries += 1;
|
||||
const ran = stage.status !== "skipped";
|
||||
if (stage.metrics.tokens) {
|
||||
@@ -93,16 +94,14 @@ function aggregateMetrics(outcomes) {
|
||||
else if (metrics.tokens[key] !== null) metrics.tokens[key] += stage.metrics.tokens[key];
|
||||
}
|
||||
if (!stage.metrics.tokens.complete) metrics.tokens_complete = false;
|
||||
} else if (stage.provider && ran) {
|
||||
} else if (ran) {
|
||||
metrics.tokens_complete = false;
|
||||
}
|
||||
// A stage that ran without reporting a measurement makes the total unknown, never a smaller
|
||||
// number that reads as measured. Retries and repairs are provider counters, so only a provider
|
||||
// stage can leave them unknown.
|
||||
// Timing and retry metrics describe model work only. A stage that reached a provider without
|
||||
// reporting a measurement makes the total unknown, never a smaller measured number.
|
||||
for (const key of ["elapsed_ms", "request_retries", "output_repairs"]) {
|
||||
const measurable = ran && (key === "elapsed_ms" || stage.provider);
|
||||
if (stage.metrics[key] === null) {
|
||||
if (measurable) metrics[key] = null;
|
||||
if (ran) metrics[key] = null;
|
||||
} else if (metrics[key] !== null) {
|
||||
metrics[key] += stage.metrics[key];
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ const { SCHEMA_VERSION, parseCheckState } = require("./validate-classifier");
|
||||
const { contributorEligibility, reviewPolicyEligible } = require("./resolve-state");
|
||||
const { forkRateLimit } = require("./fork-rate-limit");
|
||||
const { normalizeReviewerIds } = require("./routing");
|
||||
const { isRetryableFailure, plannedRequiredReviewers } = require("./review-pipeline");
|
||||
const { isRetryableFailure, plannedRequiredReviewers, validateReviewGate } = require("./review-pipeline");
|
||||
|
||||
const MAXIMUM_DELAY_SECONDS = 15 * 60;
|
||||
const OVERSIZED_REVIEW_LABEL = "ai-review/allow-oversized";
|
||||
@@ -15,10 +15,28 @@ const CLASSIFICATION_COMPLETE = "Classification complete";
|
||||
|
||||
const decline = (reason) => ({ retry: false, reason });
|
||||
|
||||
class StaleHeadError extends Error {
|
||||
constructor() { super("pull request head is no longer current"); this.name = "StaleHeadError"; }
|
||||
}
|
||||
|
||||
function isTruncatedGithubResponse(error) {
|
||||
return error?.status === 500 && /unexpected end of JSON input/i.test(String(error.message));
|
||||
}
|
||||
|
||||
async function readPullRequest({ github, owner, repo, pullNumber }) {
|
||||
const read = () => github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
|
||||
try {
|
||||
return (await read()).data;
|
||||
} catch (error) {
|
||||
if (!isTruncatedGithubResponse(error)) throw error;
|
||||
return (await read()).data;
|
||||
}
|
||||
}
|
||||
|
||||
async function assertCurrentHead({ github, owner, repo, pullNumber, expectedHeadSha }) {
|
||||
const { data } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
|
||||
const data = await readPullRequest({ github, owner, repo, pullNumber });
|
||||
if (data.state !== "open" || data.head?.sha !== expectedHeadSha) {
|
||||
throw new Error("pull request head is no longer current");
|
||||
throw new StaleHeadError();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +57,7 @@ async function retryStillPermitted({
|
||||
github, owner, repo, pullNumber, expectedHeadSha, expectedBaseSha, force = false,
|
||||
selectedReviewers = [], requiredReviewers, diffBytes = null,
|
||||
} = {}) {
|
||||
const pull = (await github.rest.pulls.get({ owner, repo, pull_number: pullNumber })).data;
|
||||
const pull = await readPullRequest({ github, owner, repo, pullNumber });
|
||||
if (pull.state !== "open") return decline("pull request is no longer open");
|
||||
if (pull.head?.sha !== expectedHeadSha) return decline("pull request head is no longer current");
|
||||
if (expectedBaseSha && pull.base?.sha !== expectedBaseSha) {
|
||||
@@ -54,13 +72,6 @@ async function retryStillPermitted({
|
||||
const cap = labels.includes(OVERSIZED_REVIEW_LABEL) ? 4 * MIB : MIB;
|
||||
if (diffBytes > cap) return decline("pull request evidence exceeds the current evidence limit");
|
||||
|
||||
// A trusted caller's force bypasses policy and CI, and nothing else.
|
||||
if (force) return { retry: true, reason: "" };
|
||||
|
||||
if (pull.user?.type === "Bot") return decline("pull request author is a bot");
|
||||
if (pull.draft === true) return decline("pull request is a draft");
|
||||
if (!reviewPolicyEligible({ labels })) return decline("review is no longer policy eligible");
|
||||
|
||||
const runsFor = async (checkName) => (await github.rest.checks.listForRef({
|
||||
owner, repo, ref: expectedHeadSha, check_name: checkName, per_page: 100,
|
||||
})).data.check_runs.filter((run) => run?.app?.slug === "github-actions");
|
||||
@@ -73,10 +84,21 @@ async function retryStillPermitted({
|
||||
return decline("classification is no longer valid for this head");
|
||||
}
|
||||
const state = parseCheckState(classification.output?.summary);
|
||||
if (state === null || state.automaticReviewEligible !== true ||
|
||||
classification.output?.title !== CLASSIFICATION_COMPLETE) {
|
||||
if (state === null) {
|
||||
return decline("classification is no longer valid for this head");
|
||||
}
|
||||
if (!force && classification.output?.title !== CLASSIFICATION_COMPLETE) {
|
||||
return decline("classification no longer authorizes an automatic review");
|
||||
}
|
||||
const classificationGate = validateReviewGate({
|
||||
ok: true, force, head_sha: expectedHeadSha, classificationValid: true,
|
||||
classificationCheck: state.automaticReviewEligible === true,
|
||||
protocolRelated: state.protocolRelated, risk: state.risk,
|
||||
specialistReviewers: state.specialistReviewers,
|
||||
}, expectedHeadSha);
|
||||
if (!classificationGate.ok) {
|
||||
return decline(classificationGate.reason);
|
||||
}
|
||||
if (!sameReviewers(state.specialistReviewers, selectedReviewers)) {
|
||||
return decline("classification now selects a different reviewer set");
|
||||
}
|
||||
@@ -86,6 +108,13 @@ async function retryStillPermitted({
|
||||
return decline("a required reviewer is no longer selected");
|
||||
}
|
||||
|
||||
// A trusted caller's force bypasses policy and CI, and nothing else.
|
||||
if (force) return { retry: true, reason: "" };
|
||||
|
||||
if (pull.user?.type === "Bot") return decline("pull request author is a bot");
|
||||
if (pull.draft === true) return decline("pull request is a draft");
|
||||
if (!reviewPolicyEligible({ labels })) return decline("review is no longer policy eligible");
|
||||
|
||||
if ((await runsFor("AI automated review")).some((run) => run.conclusion === "success")) {
|
||||
return decline("this head was already reviewed");
|
||||
}
|
||||
@@ -177,5 +206,5 @@ async function retryGateStep({ github, context, core, env, stage }) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
MAXIMUM_DELAY_SECONDS, assertCurrentHead, delayedRetryGate, retryGateStep, retryStillPermitted,
|
||||
MAXIMUM_DELAY_SECONDS, StaleHeadError, assertCurrentHead, delayedRetryGate, retryGateStep, retryStillPermitted,
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
const { encodeCheckState } = require("./validate-classifier");
|
||||
const { provenancePrefix } = require("./validate-final-review");
|
||||
const { reviewPolicyEligible } = require("./routing");
|
||||
const { assertCurrentHead } = require("./review-retry");
|
||||
|
||||
const SEVERITY_EMOJI = {
|
||||
critical: ":purple_circle:",
|
||||
@@ -11,10 +12,6 @@ const SEVERITY_EMOJI = {
|
||||
low: ":yellow_circle:",
|
||||
};
|
||||
|
||||
class StaleHeadError extends Error {
|
||||
constructor() { super("pull request head is no longer current"); this.name = "StaleHeadError"; }
|
||||
}
|
||||
|
||||
class StalePolicyError extends Error {
|
||||
constructor() { super("pull request review policy changed"); this.name = "StalePolicyError"; }
|
||||
}
|
||||
@@ -36,11 +33,6 @@ function findingIndicator(finding) {
|
||||
`${finding.question ? " :question:" : ""}`;
|
||||
}
|
||||
|
||||
async function assertCurrentHead(github, owner, repo, prNumber, expectedSha) {
|
||||
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber });
|
||||
if (pr.state !== "open" || pr.head?.sha !== expectedSha) throw new StaleHeadError();
|
||||
}
|
||||
|
||||
async function issueLabels(github, owner, repo, prNumber) {
|
||||
const { data } = await github.rest.issues.get({ owner, repo, issue_number: prNumber });
|
||||
return new Set(data.labels.map((label) => typeof label === "string" ? label : label.name).filter(Boolean));
|
||||
@@ -83,7 +75,7 @@ async function upsertMarkedComment(github, owner, repo, prNumber, expectedSha, b
|
||||
item.user?.login === botLogin && typeof item.body === "string" && item.body.includes(comment.marker));
|
||||
if (existing?.body === body) return false;
|
||||
await issueLabels(github, owner, repo, prNumber);
|
||||
await assertCurrentHead(github, owner, repo, prNumber, expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: expectedSha });
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
|
||||
} else {
|
||||
@@ -97,19 +89,27 @@ async function deleteMarkedComment(github, owner, repo, prNumber, expectedSha, b
|
||||
const existing = (await comments(github, owner, repo, prNumber)).find((item) =>
|
||||
item.user?.login === botLogin && typeof item.body === "string" && item.body.includes(marker));
|
||||
if (!existing) return false;
|
||||
await assertCurrentHead(github, owner, repo, prNumber, expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: expectedSha });
|
||||
await github.rest.issues.deleteComment({ owner, repo, comment_id: existing.id });
|
||||
return true;
|
||||
}
|
||||
|
||||
function reviewBody(marker, review) {
|
||||
function reviewBody(marker, review, reducedCoverage = []) {
|
||||
const findings = review.findings.filter((finding) => finding.start_line === null).map((finding, index) => {
|
||||
return `${index + 1}. **${provenancePrefix(finding.sources)} ${escapeMarkdown(finding.title)}** — ` +
|
||||
`${findingIndicator(finding)} — ${escapeMarkdown(finding.path)}\n` +
|
||||
` ${escapeMarkdown(finding.rationale)}`;
|
||||
}).join("\n");
|
||||
const clean = review.findings.length === 0 ? ":green_circle: " : "";
|
||||
return `${marker}\n\n${clean}${escapeMarkdown(review.summary)}${findings ? `\n\n${findings}` : ""}`;
|
||||
const coverage = reducedCoverage.length === 0
|
||||
? ""
|
||||
: `\n\nReduced coverage:${reducedCoverageText(reducedCoverage.map(escapeMarkdown))}.`;
|
||||
return `${marker}\n\n${clean}${escapeMarkdown(review.summary)}${coverage}${findings ? `\n\n${findings}` : ""}`;
|
||||
}
|
||||
|
||||
function reducedCoverageText(reducedCoverage) {
|
||||
return ` optional reviewer${reducedCoverage.length === 1 ? "" : "s"} ` +
|
||||
`${reducedCoverage.join(", ")} ${reducedCoverage.length === 1 ? "was" : "were"} unavailable`;
|
||||
}
|
||||
|
||||
async function reviews(github, owner, repo, prNumber) {
|
||||
@@ -149,11 +149,11 @@ async function publishReview(github, owner, repo, prNumber, state, botLogin, com
|
||||
}
|
||||
return comment;
|
||||
});
|
||||
await assertCurrentHead(github, owner, repo, prNumber, state.expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: state.expectedSha });
|
||||
assertReviewPolicy(await issueLabels(github, owner, repo, prNumber), state);
|
||||
await github.rest.pulls.createReview({
|
||||
owner, repo, pull_number: prNumber, commit_id: state.expectedSha, event: "COMMENT",
|
||||
body: reviewBody(comment.marker, review), comments: inline,
|
||||
body: reviewBody(comment.marker, review, comment.reducedCoverage), comments: inline,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -176,7 +176,7 @@ async function ensureClassificationCheck(github, owner, repo, prNumber, expected
|
||||
const existing = await findCheck(github, owner, repo, expectedSha, check);
|
||||
if (existing?.conclusion === conclusion && existing.output?.title === check.title &&
|
||||
existing.output?.summary === summary) return false;
|
||||
await assertCurrentHead(github, owner, repo, prNumber, expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: expectedSha });
|
||||
const payload = {
|
||||
owner, repo, name: check.name, head_sha: expectedSha, external_id: check.externalId,
|
||||
status: "completed", conclusion,
|
||||
@@ -200,7 +200,7 @@ async function ensureReviewCheck(github, owner, repo, prNumber, expectedSha, che
|
||||
if (state.failed !== true) {
|
||||
assertReviewPolicy(await issueLabels(github, owner, repo, prNumber), state);
|
||||
}
|
||||
await assertCurrentHead(github, owner, repo, prNumber, expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: expectedSha });
|
||||
const payload = {
|
||||
owner, repo, name: check.name, head_sha: expectedSha, external_id: check.externalId,
|
||||
status: "completed", conclusion, output: { title, summary },
|
||||
@@ -214,7 +214,7 @@ async function ensureReviewCheck(github, owner, repo, prNumber, expectedSha, che
|
||||
}
|
||||
|
||||
async function dispatchClassificationComplete(github, owner, repo, prNumber, expectedSha) {
|
||||
await assertCurrentHead(github, owner, repo, prNumber, expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: expectedSha });
|
||||
await github.rest.repos.createDispatchEvent({
|
||||
owner, repo, event_type: "pr-automation-classified",
|
||||
client_payload: { pr_number: prNumber, head_sha: expectedSha },
|
||||
@@ -236,7 +236,7 @@ async function applyLabels(github, owner, repo, prNumber, state, currentLabels)
|
||||
const additions = [...add].filter((label) => !current.has(label));
|
||||
const removals = [...remove].filter((label) => current.has(label));
|
||||
if (additions.length === 0 && removals.length === 0) return false;
|
||||
await assertCurrentHead(github, owner, repo, prNumber, state.expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: state.expectedSha });
|
||||
if (additions.length > 0) {
|
||||
await github.rest.issues.addLabels({ owner, repo, issue_number: prNumber, labels: additions });
|
||||
}
|
||||
@@ -255,7 +255,7 @@ async function writeState({ github, owner, repo, prNumber, state, botLogin, revi
|
||||
typeof state.expectedSha !== "string" || !Number.isSafeInteger(prNumber) || prNumber <= 0) {
|
||||
throw new Error("invalid normalized state");
|
||||
}
|
||||
await assertCurrentHead(github, owner, repo, prNumber, state.expectedSha);
|
||||
await assertCurrentHead({ github, owner, repo, pullNumber: prNumber, expectedHeadSha: state.expectedSha });
|
||||
if (state.mode === "review") {
|
||||
const comments = state.comments || [];
|
||||
for (const comment of comments.filter((comment) => comment.kind === "review")) {
|
||||
@@ -297,6 +297,7 @@ async function writeState({ github, owner, repo, prNumber, state, botLogin, revi
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
StaleHeadError, StalePolicyError, applyLabels, assertCurrentHead, deleteMarkedComment, dispatchClassificationComplete,
|
||||
StalePolicyError, applyLabels, deleteMarkedComment, dispatchClassificationComplete,
|
||||
escapeMarkdown, markerBody, upsertMarkedComment, writeState,
|
||||
reducedCoverageText,
|
||||
};
|
||||
|
||||
@@ -59,6 +59,7 @@ jobs:
|
||||
classification-requested: ${{ steps.resolve.outputs.classification-requested }}
|
||||
review-route: ${{ steps.resolve.outputs.review-route }}
|
||||
classifier-lane: ${{ steps.resolve.outputs.classifier-lane }}
|
||||
reviewer-pipeline-lane: ${{ steps.resolve.outputs.reviewer-pipeline-lane }}
|
||||
evidence-max-bytes: ${{ steps.resolve.outputs.evidence-max-bytes }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
@@ -91,7 +92,8 @@ jobs:
|
||||
core.setOutput("review-requested", result.reviewRequested === true);
|
||||
core.setOutput("classification-requested", result.classificationRequested === true);
|
||||
core.setOutput("review-route", result.reviewRoute === true);
|
||||
core.setOutput("classifier-lane", result.prNumber ? (Number(result.prNumber) % 2) + 1 : "");
|
||||
core.setOutput("classifier-lane", result.prNumber ? (Number(result.prNumber) % 4) + 1 : "");
|
||||
core.setOutput("reviewer-pipeline-lane", result.prNumber ? (Number(result.prNumber) % 7) + 1 : "");
|
||||
core.setOutput("evidence-max-bytes", result.evidenceMaxBytes ?? "");
|
||||
core.info(JSON.stringify({ event: "pr-automation.resolve-pr", decision: result }));
|
||||
if (!result.ok) core.warning(`PR automation did not start: ${result.reason}`);
|
||||
@@ -543,6 +545,7 @@ jobs:
|
||||
const prNumber = Number(process.env.PULL_REQUEST_NUMBER);
|
||||
const headSha = process.env.HEAD_SHA;
|
||||
const force = process.env.FORCE === "true";
|
||||
const manual = process.env.ROUTE === "dispatch";
|
||||
let resolvedLabels = [];
|
||||
let author = null;
|
||||
try { resolvedLabels = JSON.parse(process.env.LABELS || "[]"); } catch {}
|
||||
@@ -574,25 +577,37 @@ jobs:
|
||||
// A check without the current machine-readable state predates this contract: fail closed
|
||||
// and wait for a later classification event to rewrite it.
|
||||
const protocolState = classificationOwned ? parseCheckState(classification.output?.summary) : null;
|
||||
const classificationCheck = classificationOwned && protocolState !== null &&
|
||||
protocolState.automaticReviewEligible === true &&
|
||||
classification.output?.title === "Classification complete";
|
||||
const classificationValid = classificationOwned && protocolState !== null;
|
||||
const classificationCheck = classificationValid &&
|
||||
classification.output?.title === "Classification complete" &&
|
||||
protocolState.automaticReviewEligible === true;
|
||||
const legitimacyStopped = classificationOwned &&
|
||||
classification.output?.title === "Automation stopped";
|
||||
const protocolRelated = protocolState?.protocolRelated === true;
|
||||
if (!classificationValid && (force || manual)) {
|
||||
publish({
|
||||
ok: false, force, head_sha: headSha, classificationValid: false,
|
||||
classificationCheck: false, legitimacyStopped, ciGreen: false,
|
||||
secondReviewEligible: false, policyEligible: false, labels: resolvedLabels,
|
||||
protocolRelated: false, risk: "unknown", specialistReviewers: [],
|
||||
contributor: { status: force ? "forced" : "unavailable" },
|
||||
reason: "valid classification unavailable",
|
||||
}, false);
|
||||
core.setFailed("manual or forced review requires a valid classification for the current head");
|
||||
return;
|
||||
}
|
||||
if (force) {
|
||||
const route = resolveReviewerRoute({
|
||||
suggestedReviewers: protocolState?.specialistReviewers || [],
|
||||
deterministicReviewers: ["skeptical", "code-compressor"],
|
||||
suggestedReviewers: protocolState.specialistReviewers,
|
||||
protocolRelated,
|
||||
risk: protocolState?.risk || "unknown",
|
||||
risk: protocolState.risk,
|
||||
});
|
||||
publish({
|
||||
ok: true, force: true, head_sha: headSha, classificationCheck,
|
||||
ok: route.ok, force: true, head_sha: headSha, classificationValid, classificationCheck,
|
||||
legitimacyStopped, ciGreen: false, secondReviewEligible: true,
|
||||
policyEligible: true, labels: resolvedLabels, protocolRelated,
|
||||
risk: protocolState?.risk || "unknown",
|
||||
specialistReviewers: route.ok ? route.reviewers : ["skeptical", "code-compressor"],
|
||||
risk: protocolState.risk,
|
||||
specialistReviewers: route.ok ? route.reviewers : [],
|
||||
contributor: { status: "forced" },
|
||||
});
|
||||
return;
|
||||
@@ -621,7 +636,7 @@ jobs:
|
||||
publish({
|
||||
ok: classificationCheck && ciGreen && secondReviewEligible && policyEligible &&
|
||||
contributor.status === "eligible",
|
||||
force: false, head_sha: headSha, classificationCheck, legitimacyStopped,
|
||||
force: false, head_sha: headSha, classificationValid, classificationCheck, legitimacyStopped,
|
||||
ciGreen, secondReviewEligible, policyEligible, labels, contributor,
|
||||
protocolRelated, risk: protocolState?.risk || "unknown",
|
||||
specialistReviewers: protocolState?.specialistReviewers || [],
|
||||
@@ -629,13 +644,13 @@ jobs:
|
||||
} catch (error) {
|
||||
core.warning(`Review gate unavailable: ${error.message}`);
|
||||
publish({
|
||||
ok: force, force, head_sha: headSha, classificationCheck: false,
|
||||
ok: false, force, head_sha: headSha, classificationValid: false, classificationCheck: false,
|
||||
legitimacyStopped: false, ciGreen: false, secondReviewEligible: force,
|
||||
policyEligible: force, labels: force ? resolvedLabels : [], protocolRelated: false,
|
||||
risk: "unknown", specialistReviewers: force ? ["skeptical", "code-compressor"] : [],
|
||||
policyEligible: false, labels: force ? resolvedLabels : [], protocolRelated: false,
|
||||
risk: "unknown", specialistReviewers: [],
|
||||
contributor: force ? { status: "forced" } : { status: "unavailable" },
|
||||
reason: error.message,
|
||||
}, force);
|
||||
}, false);
|
||||
}
|
||||
|
||||
review-pipeline:
|
||||
@@ -645,12 +660,12 @@ jobs:
|
||||
always() && !cancelled() &&
|
||||
needs.resolve-pr.outputs.ok == 'true' &&
|
||||
needs.resolve-pr.outputs.review-route == 'true' &&
|
||||
needs.review-gate.outputs.eligible == 'true' &&
|
||||
(needs.resolve-pr.outputs.force == 'true' ||
|
||||
(needs.fork-rate-limit.result == 'success' &&
|
||||
needs.fork-rate-limit.outputs.allowed == 'true' &&
|
||||
needs.review-gate.outputs.eligible == 'true'))
|
||||
needs.fork-rate-limit.outputs.allowed == 'true'))
|
||||
concurrency:
|
||||
group: llm-reviewer-pipeline
|
||||
group: llm-reviewer-pipeline-${{ needs.resolve-pr.outputs.reviewer-pipeline-lane }}
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
permissions:
|
||||
@@ -713,13 +728,13 @@ jobs:
|
||||
const { renderReviewReport } = require("./.github/pr-automation/review-report-summary");
|
||||
const parse = (value, fallback) => { try { return JSON.parse(value || ""); } catch { return fallback; } };
|
||||
const force = process.env.FORCE === "true";
|
||||
const gate = parse(process.env.GATE, force ? {
|
||||
ok: true, force: true, head_sha: process.env.HEAD_SHA,
|
||||
labels: parse(process.env.LABELS, []), protocolRelated: false, risk: "unknown",
|
||||
specialistReviewers: ["skeptical", "code-compressor"], contributor: { status: "forced" },
|
||||
} : {});
|
||||
const gate = parse(process.env.GATE, {});
|
||||
const report = parseReport(process.env.REVIEW_REPORT);
|
||||
const recovered = report.stages.filter((stage) => stage.attempts === 2);
|
||||
const reducedCoverage = report.stages
|
||||
.filter((stage) => stage.id.startsWith("specialist:") &&
|
||||
stage.status === "failed" && stage.required !== true)
|
||||
.map((stage) => stage.id.slice("specialist:".length));
|
||||
const failureReasons = report.stages.filter((stage) => stage.status === "failed")
|
||||
.map((stage) => `${stage.id}: ${stage.reason || stage.category}`);
|
||||
const reviewerReason = report.status === "failed"
|
||||
@@ -735,6 +750,7 @@ jobs:
|
||||
reviewerReason,
|
||||
force,
|
||||
reviewMarkerId: process.env.REVIEW_MARKER_ID,
|
||||
reducedCoverage,
|
||||
});
|
||||
core.setOutput("state", JSON.stringify(state));
|
||||
core.info(JSON.stringify({
|
||||
@@ -760,10 +776,10 @@ jobs:
|
||||
} else {
|
||||
const outcome = reviewOutcome({
|
||||
reportStatus: report.status, state, recovered: recovered.length > 0,
|
||||
reducedCoverage,
|
||||
});
|
||||
const detail = state.failed === true ? state.reason || reviewerReason : reviewerReason;
|
||||
const rendered = renderReviewReport({
|
||||
report, outcome, detail, summaryUrl: process.env.SUMMARY_URL,
|
||||
report, outcome, summaryUrl: process.env.SUMMARY_URL, reducedCoverage,
|
||||
});
|
||||
if (state.check) {
|
||||
state.check.title = rendered.title;
|
||||
|
||||
@@ -29,7 +29,7 @@ on:
|
||||
type: string
|
||||
default: ""
|
||||
gate:
|
||||
description: Validated review gate state, required for a forced review and whenever required-reviewers is absent
|
||||
description: Validated exact-head classification and review gate state
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
@@ -74,7 +74,6 @@ jobs:
|
||||
WORKFLOW_SHA: ${{ github.workflow_sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "EVIDENCE_STARTED_MS=$(date +%s%3N)" >> "$GITHUB_ENV"
|
||||
export GIT_CONFIG_NOSYSTEM=1
|
||||
export GIT_CONFIG_GLOBAL=/dev/null
|
||||
git init .
|
||||
@@ -96,19 +95,23 @@ jobs:
|
||||
name: Resolve the mandatory reviewer set
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
HEAD_SHA: ${{ inputs.head-sha }}
|
||||
SELECTED_REVIEWERS: ${{ inputs.specialist-reviewers }}
|
||||
REQUIRED_REVIEWERS: ${{ inputs.required-reviewers }}
|
||||
GATE: ${{ inputs.gate }}
|
||||
with:
|
||||
script: |
|
||||
const {
|
||||
resolveRequiredReviewers,
|
||||
resolveRequiredReviewers, validateReviewGate,
|
||||
} = require("./.github/pr-automation/review-pipeline");
|
||||
const resolved = (() => {
|
||||
try {
|
||||
const gate = process.env.GATE ? JSON.parse(process.env.GATE) : {};
|
||||
const selectedReviewers = JSON.parse(process.env.SELECTED_REVIEWERS);
|
||||
const validatedGate = validateReviewGate(gate, process.env.HEAD_SHA, selectedReviewers);
|
||||
if (!validatedGate.ok) return validatedGate;
|
||||
return resolveRequiredReviewers({
|
||||
selectedReviewers: JSON.parse(process.env.SELECTED_REVIEWERS),
|
||||
selectedReviewers,
|
||||
requiredReviewers: process.env.REQUIRED_REVIEWERS
|
||||
? JSON.parse(process.env.REQUIRED_REVIEWERS)
|
||||
: undefined,
|
||||
@@ -243,7 +246,6 @@ jobs:
|
||||
script: |
|
||||
const { stageOutcome } = require("./.github/pr-automation/review-report");
|
||||
const ok = process.env.EVIDENCE_STATUS === "success";
|
||||
const started = Number(process.env.EVIDENCE_STARTED_MS);
|
||||
const reason = ok
|
||||
? ""
|
||||
: process.env.PLAN_REASON || process.env.EVIDENCE_REASON ||
|
||||
@@ -255,9 +257,6 @@ jobs:
|
||||
required: true,
|
||||
reason,
|
||||
category: ok ? "" : "evidence-unavailable",
|
||||
metrics: {
|
||||
elapsed_ms: Number.isFinite(started) ? Date.now() - started : null,
|
||||
},
|
||||
})));
|
||||
|
||||
specialists:
|
||||
|
||||
Reference in New Issue
Block a user