Review waits: count agent runs and failed tries, checks re-read while CI runs, CI fix from the earlier review, own pushes skip cap and interval, maintainer-only merge-time stale check

This commit is contained in:
aiongg committed 2026-11-07 03:57:17 +00:00
1 parent 09f5b16ef4
commit c773848a93
16 files changed
+224 -60

No files matched your search

+1 -1
View File
@@ -39,7 +39,7 @@ The image sets every path (`/data/...`, `/config/...`). A deployment sets only t
| `AUTOCRAFT_STOP_TIMEOUT` | no | `25` | Seconds the runner may take to stop. Keep the pod's `terminationGracePeriodSeconds` above it (30). |
| `AUTOCRAFT_HEALTH_LISTEN` | no | off | `host:port` of a runner listener that serves only `/healthz` and `/readyz`. |
| `AUTOCRAFT_NO_SANDBOX` | no | off | `1` runs without bubblewrap, so without tool mode. Use it only if the cluster cannot allow the runner settings below. |
| `AUTOCRAFT_REVIEW_BOTS` | no | `coderabbitai` | Logins of review bots whose comments never make a review stale. Set it alike for dashboard, runner and periodic. |
| `AUTOCRAFT_REVIEW_BOTS` | no | `coderabbitai,dependabot,renovate` | Logins of review bots whose comments never make a review stale. Set it alike for dashboard, runner and periodic. |
| `AUTOCRAFT_GITHUB_APP_NAME` | no | `AutoCraft` | Name suggested on the GitHub App registration form. |
| `AUTOCRAFT_IMAGE_TOKEN_FILE` | no | `gh auth token` | File holding the token the dashboard's image proxy uses for GitHub images. |
| `AUTOCRAFT_DISCORD_TOKEN_FILE` | no | off | File holding a Discord bot token (mode 600). Setting it on the runner turns on Discord mention counting; it needs the key file too. |
+1 -1
View File
@@ -39,7 +39,7 @@ The frontend is the React app in `web/`. Build it before serving: `pnpm -C web i
| `AUTOCRAFT_BASE_URL` | Public origin of the dashboard, such as `https://dashboard.example.org` (no path). The OAuth App's callback URL must be exactly `<AUTOCRAFT_BASE_URL>/auth/callback`. Required unless dev auth is on. |
| `AUTOCRAFT_LISTEN` | `host:port` to listen on. Default `127.0.0.1:8993`; with dev auth, `127.0.0.1:8994`. |
| `AUTOCRAFT_DB` | SQLite database path (the mirror database). |
| `AUTOCRAFT_REVIEW_BOTS` | Comma-separated logins of review bots whose comments never make a review stale, besides accounts of type Bot or ending in `[bot]`. Default `coderabbitai`. Read by `sync` (when it stores a comment), the database backfill and the runner, so set it for all three alike. |
| `AUTOCRAFT_REVIEW_BOTS` | Comma-separated logins of review bots whose comments never make a review stale, besides accounts of type Bot or ending in `[bot]`. Default `coderabbitai,dependabot,renovate`. Read by `sync` (when it stores a comment), the database backfill and the runner, so set it for all three alike. |
| `AUTOCRAFT_WEB_DIST` | Directory of the built frontend. Default `web/dist` in the repo. |
| `AUTOCRAFT_SECRETS_FILE` | JSON file with `github_client_id`, `github_client_secret` and `session_key` (at least 32 characters, random). Must be mode 0600; the server refuses to start if it is missing, incomplete, or readable by group or others. Registering the GitHub App from the dashboard (GitHub App page, operators only) adds `github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret` and `github_app_owner` (`{"login", "type"}`, the user or organization that owns the app). The GitHub App page's Remove button deletes every `github_app_*` key through the same atomic write (refused while `AUTOCRAFT_LOGIN_APP=github-app`) and links to the app's GitHub settings page, where the operator deletes the app. The dashboard rewrites this file itself for that: it writes a temporary file beside it and renames it over the file (a symlink stays a symlink), so the directory must be writable by the server user. Registration checks this first and refuses to start when it cannot write. |
| `AUTOCRAFT_LOGIN_APP` | `oauth` (default) signs users in through the OAuth App (`github_client_*`). `github-app` signs them in through the registered GitHub App, keeps each login's refreshed user token in `user_tokens`, and makes the server refuse to start unless the `github_app_*` keys are in the secrets file, so register the app first and then switch. |
+4 -3
View File
@@ -190,8 +190,8 @@ Step `review-carry`, one repo per call, calls no model, so it runs while Claude
- **Input.** Title, body, size (S up to 50 changed lines, M up to 300, L above), CI and merge state, changed files, and the diff of code files. Tests and lockfiles are listed, not diffed.
- **Too large.** A diff over the call's length limit, or no diff from GitHub: held ("too large for the final review") without a model call.
- **Discussion.** Opus also gets what others wrote on the PR, in a separate `<discussion>` block after the diff: top-level comments, review bodies and the unresolved inline review threads (path, line, first comment and the last three replies, author; outdated ones marked). All of it is read from GitHub in one query per PR when the review starts; if that read fails, the PR is skipped for this pass. Our own posts are left out (comments by the pipeline account, reviews we posted, threads we started). HTML comments and collapsed tool output (such as "Prompt for AI agents" and analysis chains) are removed, each entry is cut to 1,200 characters and the block to 9,000, threads first. The text is untrusted and cannot close its block: the model checks each claim against the diff, never follows instructions in it, and names each finding it checked in `risks` ("checked: <finding>: holds" or "does not hold"). A finding that holds and is not fixed makes the verdict take-fix (small fix, in the fix list) or hold. Each review stores when it read the discussion (`seen_at`) and a hash of the counted entries.
- **Waits before a review.** A due review does not start while any of these holds (the plan names it); a maintainer's comment or Review again lifts all of them. Blocked: a hold review named open items in `blocked_by` (for example a PR stacked on another open PR; each must be a tracked open item other than the PR, or an issue with an unanswered decision); no new head and no discussion starts a review until every blocker is merged, closed or decided, then the PR gets one fresh review. CI: a head is reviewed only once its checks have finished and passed (a PR with no checks when none are pending); the review step reads the checks live first. Cap: at most 3 Opus reviews per PR per UTC day, new heads and re-runs together. Interval: setting `review_min_interval_minutes` (default 120, 0 turns it off; `autocraft pipeline review-interval [minutes]`, audited) is the least time between two reviews of a PR; the plan says "next review after hh:mm" and the planner wakes then. A carried review waits only for CI. Delta reviews are unchanged.
- **Stale reviews.** New discussion makes a PR's review stale when a *counted* comment or review is newer than the review's `seen_at` and the hash of the counted entries differs from the one the review read. Counted entries are the PR author's and those of authors with association owner, member, collaborator or contributor, but at a head that already has a review only a maintainer's (owner, member, collaborator or a dashboard operator or maintainer) makes the review stale; the PR author's comments are read by the next review without starting one. Others are shown to the model but never trigger. A one-line comment that only addresses a bot (`@coderabbitai resume`, `@dependabot rebase`) is never counted. Bot accounts never trigger (GitHub type Bot, a login ending in `[bot]`, or a login on the review-bot list, default `coderabbitai`, set with `AUTOCRAFT_REVIEW_BOTS`), even when the bot is the PR author; empty bodies and bare approvals never trigger. A stale PR is a candidate again at the same head, at most 3 times per PR per UTC day (head changes do not count; the log says when the cap holds one back). Until a PR has an Opus review at its head, it has no final verdict and no queue state, and it cannot merge; an integration batch that contains it is rebuilt without it. Just before a single or batch merge the discussion is read live again; a counted entry the review did not read stops the merge and marks the PR stale. A re-review at the same head sets aside the head's Merge? decision (kept, renamed), so the question is asked again and an earlier answer does not count; the exception is a head where Opus was ever unsure (see Unsure): its question stays while unanswered. The posted review is edited when a newer Opus review exists at the same head. Reviews made before snapshots existed count as having read everything up to the migration. `autocraft review again <repo>#<n>` (operator, audited as `review-again`) marks a PR's review stale by hand, ignoring the cap.
- **Waits before a review.** A due review does not start while any of these holds (the plan names it); a maintainer's or operator's request after the latest review (a comment, Review again) lifts all of them. Blocked: a hold review named open items in `blocked_by` (`repo#n`, `#n` or `owner/repo#n`; each must be a tracked open item other than the PR, or an issue with an unanswered decision); no new head and no discussion starts a review until every blocker is merged, closed or decided, then the PR gets one fresh review. A blocker that itself waits on this PR is ignored, and the list expires after 14 days. CI: a head is reviewed only once its checks have finished and passed (a PR with no checks when none are pending); the first review of a PR also runs on finished red CI, and so does the one after blockers settled. While a head's CI runs or is red, the repo's checks are read again every minute, and a red head with an earlier take or take-fix review goes to CI fix. Cap: at most 3 Opus calls per PR per UTC day, counting new heads, re-runs, failed calls and reply-fix turns (agent runs of `opus-review`); carried reviews do not count. Interval: setting `review_min_interval_minutes` (default 120, 0 turns it off; `autocraft pipeline review-interval [minutes]`, audited) is the least time since the PR's last call; the plan says "next review after hh:mm" and the planner wakes then. A head made only by our own pushes since the last review skips the cap and the interval. Failures: a call that gives no valid review waits 10 minutes, then 30 minutes, then 2 hours at that head; a fourth failure holds the head until a new commit or Review again. A carry waits only for CI. Delta reviews, once a review runs, are as before.
- **Stale reviews.** New discussion makes a PR's review stale when a *counted* comment or review is newer than the review's `seen_at` and the hash of the counted entries differs from the one the review read. Counted entries are the PR author's and those of authors with association owner, member, collaborator or contributor, but at a head that already has a review only a maintainer's (owner, member, collaborator or a dashboard operator or maintainer) makes the review stale; the PR author's comments are read by the next review without starting one. Others are shown to the model but never trigger. A one-line comment that only addresses a bot (`@coderabbitai resume`, `@dependabot rebase`) is never counted. Bot accounts never trigger (GitHub type Bot, a login ending in `[bot]`, or a login on the review-bot list, default `coderabbitai`, `dependabot` and `renovate`, set with `AUTOCRAFT_REVIEW_BOTS`), even when the bot is the PR author; empty bodies and bare approvals never trigger. A stale PR is a candidate again at the same head, subject to the waits below. Until a PR has an Opus review at its head, it has no final verdict and no queue state, and it cannot merge; an integration batch that contains it is rebuilt without it. Just before a single or batch merge the discussion is read live again; a maintainer's or operator's entry the review did not read stops the merge and marks the PR stale (the PR author's comments do not). A re-review at the same head sets aside the head's Merge? decision (kept, renamed), so the question is asked again and an earlier answer does not count; the exception is a head where Opus was ever unsure (see Unsure): its question stays while unanswered. The posted review is edited when a newer Opus review exists at the same head. Reviews made before snapshots existed count as having read everything up to the migration. `autocraft review again <repo>#<n>` (operator, audited as `review-again`) marks a PR's review stale by hand, ignoring the waits.
| Verdict | Meaning |
|---|---|
@@ -698,7 +698,8 @@ Automated work waits only for the reasons below. A stage that is not running sho
| Checks before Review and Verify | CI data younger than 5 minutes is reused | 5 minutes | Job list |
| Blocked by another item | A hold review named an open item as its reason (for example the PR is stacked on another open PR); the PR is not reviewed again, on new commits or discussion, until that item is merged, closed or decided | Until the blocker is merged, closed or decided; a maintainer's comment or Review again lifts it | Plan wait: the blocker's reference |
| CI on the latest commit | A new head is reviewed only after its CI has finished and passed; a head whose CI runs or is red is skipped | Until CI at the head finishes green, or a later push | Plan wait: CI on the latest commit |
| Review cap for today | At most 3 Opus reviews per PR per UTC day, new commits and re-runs together | Until the next UTC day; a maintainer's comment or Review again lifts it | Plan wait: review cap for today reached |
| Failed review | A review call that gave no valid review is not repeated at once: the failure is counted per head | 10 minutes after the first failure, 30 after the second, 2 hours after the third; a fourth holds the head until a new commit or Review again | Plan wait: the review after n failed tries |
| Review cap for today | At most 3 Opus review calls per PR per UTC day, new commits, re-runs, failed calls and reply-fix turns together | Until the next UTC day; a maintainer's comment or Review again lifts it | Plan wait: review cap for today reached |
| Minimum time between reviews | Setting review_min_interval_minutes (default 120, 0 turns it off; `autocraft pipeline review-interval`): a PR reviewed less than that long ago waits, then the latest green head is reviewed | The setting's minutes since the PR's last review; a maintainer's comment or Review again lifts it | Plan wait: next review after hh:mm |
| Fix landing poll | A deep-scan fix that went out as a pull request waits for its merge, which the mirror reports; a fix that went the advisory way waits for a repository admin to merge it, which shows as the patch reaching the default branch | 2 minutes, read by the sync run, with the pipeline on or off | The finding's state: landing, awaiting admin, then landed or advisory |
| Lint task | A model patch is stored while a build worker formats it and runs clippy on the patched tree; the result is collected when the task ends | Until the build task ends (minutes); a lost task is queued once more, then the patch is given up | Builds page; the PR's fix-up or CI fix row is linting |
+2 -1
View File
@@ -234,7 +234,8 @@ function unassignOf(f: PrFacts, state: PlanState, actions: Action[]): Action[] {
const fx = fixupOf(f), cf = cifixBucket(f);
const inBatch = state === "in-batch" || state === "batch-checking" || f.inActiveBatch;
const flying = inFlightNow(f, state);
const working = actions.some(worksOn) || inBatch || flying;
const waitingToReview = f.reviewHold?.kind === "ci" || f.reviewHold?.kind === "interval";
const working = actions.some(worksOn) || inBatch || flying || waitingToReview;
// A conflicting PR whose conflict step has nothing to do (asked, held, not approved, done) waits on its author, whatever the queue state says.
const conflictStuck = f.mergeable === "CONFLICTING" && !!f.conflict && f.conflict.bucket !== "merge" && f.conflict.bucket !== "linting";
const gaveUp = state === "opus-close" || state === "verify-failed" || state === "verify-error" || state === "batch-failed" || conflictStuck
+6 -3
View File
@@ -40,7 +40,7 @@ import { sensitiveReasons } from "./sensitive.ts";
import { CARRIED, carriedReview } from "../review/carry.ts";
import { postSource } from "../review/post-source.ts";
import { staleReviews } from "../review/discussion.ts";
import { reviewHold } from "../review/gate.ts";
import { reviewHolds } from "../review/gate.ts";
import { scopeAnswers, unsettledScope } from "../review/candidates.ts";
import { NOT_RUST_REASON, PRIVATE_REASON, cachedRust } from "../verify/candidates.ts";
import { CIFIX_PUSH_STATES, CIFIX_TRY_STATES, MAX_FAILURES, labelWithScopeAnswer, sizeOf } from "./rules.ts";
@@ -222,6 +222,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
return { waiting, reread: !!w.reread, crossRepo: !!w.cross_repo, approvable: runs.filter((x) => x.event === "pull_request" && (failed[x.id] ?? 0) < MAX_FAILURES).length, blocked };
};
const holdOf = reviewHolds(db, now);
const out: PrFacts[] = [];
for (const r of rows) {
// The queue leaves merged PRs outside the pilot and our own integration PRs out.
@@ -290,7 +291,7 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
if (hasPoints) base.carry.push({ attempts: k.attempts });
}
}
if (r.state === "OPEN" && head && !base.draft) { const hold = reviewHold(db, r.repo, r.number, head, now); if (hold) base.reviewHold = hold; }
if (r.state === "OPEN" && head && !base.draft) { const hold = holdOf(r.repo, r.number, head); if (hold) base.reviewHold = hold; }
if (!r.r_head || !r.r_verdict || !r.r_at) { out.push(base); continue; }
const take = r.r_verdict === "take" || r.r_verdict === "take-fix";
@@ -324,7 +325,9 @@ export function loadPrFacts(db: DatabaseSync, opts: LoadOptions = {}): PrFacts[]
base.ci = checksHere ? (approvedPending ? "pending" : effectiveCi(db, r.repo, r.overall ?? "none", r.c_checks)) : "unknown";
base.runs = runsOf(wait, rf.f.ciApproved);
// Our push to this head turned its required checks red: the CI fix works on it now, without waiting for a review of the new head.
base.brokeByUs = brokeAt.get(ref) === head && r.c_head === head && effectiveCi(db, r.repo, r.overall ?? "none", r.c_checks) === "failure";
// A head that our own push or the review's CI gate (red CI at a new head, reviewed earlier) left red is repaired against that head.
const gateRed = !!base.reviewHold?.red && !!head && head !== r.r_head;
base.brokeByUs = (brokeAt.get(ref) === head || gateRed) && r.c_head === head && effectiveCi(db, r.repo, r.overall ?? "none", r.c_checks) === "failure";
base.tier = (r.author ? tiers.get(r.author) : undefined) ?? "not";
// The pipeline's own Fix PRs count as whitelisted; an operator's deny still wins.
if (base.tier === "not" && r.author && own.isOwn(r.repo, r.author) && own.prs.has(ref)) base.tier = "whitelisted";
+1 -1
View File
@@ -99,7 +99,7 @@ export type PrFacts = {
/** The head has no review, but the review of the earlier head carries to it (src/review/carry.ts): the Carry step stores it and no model reviews the head. */
carriable?: boolean;
/** Why a due review waits (src/review/gate.ts): an open blocker, CI at the head not finished or not passed, the PR's daily review cap, or the minimum time since its last review. */
reviewHold?: { kind: "blocked" | "ci" | "cap" | "interval"; wait: string; /** When an interval wait ends (ms). */ until?: number };
reviewHold?: { kind: "blocked" | "ci" | "cap" | "interval" | "failed"; wait: string; /** When a timed wait ends (ms). */ until?: number; /** A ci hold whose head's CI has failed. */ red?: boolean };
/** AutoCraft has its own work on this PR: one of its pushes (fix-up, CI fix, base merge) at or since the reviewed head, a stored lint patch, or the PR is our own fix PR. It ends when the PR is closed; selection also drops it while the plan waits on a person (see inFlightNow). */
inFlight?: boolean;
/** Our push moved this open PR off its mirrored head and no sync has run since (the mirror's updatedAt is not after the push). */
+1 -1
View File
@@ -244,7 +244,7 @@ public: the review as it will be posted on the pull request for its author and t
- It never mentions /reference or any documentation outside the repository.
- At most 8 points. In mode "delta" it covers the whole pull request at its new head, not only the new changes.
blocked_by: fill it only when the verdict is hold because of something outside this pull request: it is stacked on, or depends on, another open pull request or item (for example its changes include the commits of another open pull request), or a person must first decide another item. List each as "repo#number". The pull request is then not reviewed again until those items are merged, closed or decided, so name only items that really are the reason. Otherwise "blocked_by" is [].
blocked_by: fill it only when the verdict is hold because of something outside this pull request: it is stacked on, or depends on, another open pull request or item (for example its changes include the commits of another open pull request), or a person must first decide another item. List each as "repo#number" (or "#number" for a pull request of this repository). The pull request is then not reviewed again until those items are merged, closed or decided, so name only items that really are the reason. Otherwise "blocked_by" is [].
summary: 2 or 3 plain sentences: what the pull request does, your verdict, and the main risk. ${SUMMARY_RULES}
+18
View File
@@ -26,3 +26,21 @@ export function openBlockers(db: DatabaseSync, refs: readonly string[]): string[
return i.kind === "pr" || !!pending.get(m[1]!, Number(m[2]));
});
}
/** A hold's blocker list is ignored after this long: the PR then gets one fresh review. */
export const BLOCKED_EXPIRES_MS = 14 * 24 * 3600_000;
/**
* The blockers of the review of `self` made at `at` that still hold: open (openBlockers), not past BLOCKED_EXPIRES_MS, and not
* themselves waiting on `self` (two PRs blocking each other would never be reviewed).
*/
export function activeBlockers(db: DatabaseSync, self: string, stored: string | null | undefined, at: string, nowMs: number = Date.now()): string[] {
const refs = storedBlockedBy(stored);
if (!refs.length || nowMs - Date.parse(at) > BLOCKED_EXPIRES_MS) return [];
const latest = db.prepare("SELECT verdict, blocked_by FROM main.opus_reviews WHERE repo = ? AND number = ? AND verdict IS NOT NULL ORDER BY at DESC, rowid DESC LIMIT 1");
return openBlockers(db, refs).filter((ref) => {
const [repo, n] = ref.split("#");
const l = latest.get(repo!, Number(n)) as { verdict: string; blocked_by: string | null } | undefined;
return !(l?.verdict === "hold" && storedBlockedBy(l.blocked_by).includes(self));
});
}
+2 -2
View File
@@ -2,7 +2,7 @@
import { envVar } from "../env.ts";
/** Review bots whose accounts do not carry GitHub's Bot type or a `[bot]` suffix; `AUTOCRAFT_REVIEW_BOTS` (comma-separated logins) replaces the list. */
const DEFAULT_REVIEW_BOTS = ["coderabbitai"];
const DEFAULT_REVIEW_BOTS = ["coderabbitai", "dependabot", "renovate"];
/** The configured review bot logins, lower case. */
export const reviewBots = (): string[] => (envVar("REVIEW_BOTS")?.split(",") ?? DEFAULT_REVIEW_BOTS).map((x) => x.trim().toLowerCase()).filter(Boolean);
@@ -16,5 +16,5 @@ export function isBotLogin(login: string): boolean {
/** A one-line comment that only addresses a bot ("@coderabbitai resume", "@dependabot rebase"): a command, not discussion. */
export function isBotCommand(body: string): boolean {
const m = /^@([\w-]+(?:\[bot\])?)(?:\s.*)?$/.exec(body.trim());
return !!m && !body.trim().includes("\n") && (isBotLogin(m[1]!) || /(?:ai|bot|\[bot\])$/i.test(m[1]!));
return !!m && !body.trim().includes("\n") && isBotLogin(m[1]!);
}
+16 -11
View File
@@ -6,7 +6,7 @@ import { createHash } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
import { audit } from "../dash/audit.ts";
import { isBotCommand, isBotLogin } from "./bots.ts";
import { openBlockers, storedBlockedBy } from "./blockers.ts";
import { activeBlockers, storedBlockedBy } from "./blockers.ts";
import type { Querier } from "../mirror.ts";
import { FORMAL_REVIEWS, recordGate, recordGateFailure, type ReviewFact } from "../merge/changes-requested.ts";
import { ENTRY_LIMIT, TOTAL_LIMIT, type DiscussionEntry } from "./parse.ts";
@@ -63,7 +63,7 @@ export function isCounted(w: Written): boolean {
if (w.state === "APPROVED" && !inline && body.length < 40) return false;
const login = w.author ?? "";
if (!login || w.bot || isBotLogin(login)) return false;
if (isBotCommand(body)) return false;
if (!inline && isBotCommand(body)) return false;
return login === w.prAuthor || COUNTED_ASSOCIATIONS.includes(w.association ?? "");
}
@@ -137,7 +137,8 @@ type ThreadNode = {
head?: { nodes?: Node[] }; tail?: { nodes?: Node[] };
};
export type LiveDiscussion = { entries: DiscussionEntry[]; snap: Snapshot; newest: string | null; /** Latest formal review of each reviewer with write access, for the changes-requested rule. */ formal: ReviewFact[]; reviewDecision: string | null };
export type LiveDiscussion = { entries: DiscussionEntry[]; snap: Snapshot; newest: string | null; /** Latest formal review of each reviewer with write access, for the changes-requested rule. */ formal: ReviewFact[]; reviewDecision: string | null;
/** Newest counted entry written by a maintainer or dashboard user; the merge-time check goes by this, as stale reviews do. */ newestMaint: string | null };
/**
* Everything others wrote on the PR, read from GitHub (a read, never a write) in one query: comments, review
@@ -154,7 +155,9 @@ export async function liveDiscussion(q: Querier, db: DatabaseSync, repo: string,
const prAuthor: string | null = pr.author?.login ?? null;
const entries: DiscussionEntry[] = [];
const counted: { id: string; body: string | null }[] = [];
let newest: string | null = null;
let newest: string | null = null, newestMaint: string | null = null;
const dash = new Set((db.prepare("SELECT login FROM main.access WHERE role IN ('operator', 'maintainer')").all() as { login: string }[]).map((r) => r.login.toLowerCase()));
const isMaint = (login: string | null | undefined, assoc: string | undefined) => MAINTAINER_ASSOCIATIONS.includes(assoc ?? "") || (!!login && dash.has(login.toLowerCase()));
const take = (kind: "comment" | "review", n: Node) => {
if (mine(n.author, n.id)) return;
const body = cleanBody(n.body);
@@ -162,6 +165,7 @@ export async function liveDiscussion(q: Querier, db: DatabaseSync, repo: string,
if (isCounted({ author: n.author?.login ?? null, association: n.authorAssociation, bot: n.author?.__typename === "Bot", prAuthor, state: n.state, body: n.body ?? null, inline: n.comments?.totalCount })) {
counted.push({ id: n.id ?? "", body: n.body ?? null });
if (n.createdAt && (!newest || n.createdAt > newest)) newest = n.createdAt;
if (n.createdAt && isMaint(n.author?.login, n.authorAssociation) && (!newestMaint || n.createdAt > newestMaint)) newestMaint = n.createdAt;
}
};
for (const n of (pr.comments?.nodes ?? []) as Node[]) take("comment", n);
@@ -174,6 +178,7 @@ export async function liveDiscussion(q: Querier, db: DatabaseSync, repo: string,
if (isCounted({ author: c.author?.login ?? null, association: c.authorAssociation, bot: c.author?.__typename === "Bot", prAuthor, body: c.body ?? null })) {
counted.push({ id: c.id ?? "", body: c.body ?? null });
if (c.createdAt && (!newest || c.createdAt > newest)) newest = c.createdAt;
if (c.createdAt && isMaint(c.author?.login, c.authorAssociation) && (!newestMaint || c.createdAt > newestMaint)) newestMaint = c.createdAt;
}
const replies = (t.tail?.nodes ?? []).filter((r) => r.id !== c.id && !mine(r.author, r.id))
.map((r) => ({ author: r.author?.login ?? null, body: clip(cleanBody(r.body), ENTRY_LIMIT / 2) })).filter((r) => r.body);
@@ -181,7 +186,7 @@ export async function liveDiscussion(q: Querier, db: DatabaseSync, repo: string,
}
const formal = ((pr.formal?.nodes ?? []) as Node[])
.map((n) => ({ id: n.id ?? null, author: n.author?.login ?? null, association: n.authorAssociation ?? null, state: n.state ?? null, at: n.submittedAt ?? n.createdAt ?? null }));
return { entries, snap: { seen, hash: discussionHash(counted) }, newest, formal, reviewDecision: pr.reviewDecision ?? null };
return { entries, snap: { seen, hash: discussionHash(counted) }, newest, newestMaint, formal, reviewDecision: pr.reviewDecision ?? null };
}
/** Retries a read a few times: a failed read must not silently drop what reviewers wrote. */
@@ -222,7 +227,7 @@ export function discussionOf(db: DatabaseSync, repo: string, number: number, liv
const staleKey = (repo: string, number: number) => `${STALE_KEY}${repo}#${number}`;
type DiscussionState = Map<string, { newest: string; hash: string; /** Newest counted entry by a maintainer (OWNER, MEMBER, COLLABORATOR or a dashboard user); "" when none. */ maint: string }>;
export type DiscussionState = Map<string, { newest: string; hash: string; /** Newest counted entry by a maintainer (OWNER, MEMBER, COLLABORATOR or a dashboard user); "" when none. */ maint: string }>;
const MAINTAINER_ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR"];
@@ -267,8 +272,8 @@ function maintainerSince(state: { newest: string; hash: string; maint: string }
* Whether a maintainer or an operator asked for a new review of the PR after `since` (the latest review's time): "Review again",
* a merge-time check that found new discussion, or a maintainer's comment. Such a request skips the blocker, CI and daily-cap waits.
*/
export function reviewRequestedSince(db: DatabaseSync, repo: string, number: number, since: string, seen: string | null, hash: string | null): boolean {
return markedStaleSince(db, repo, number, since) || maintainerSince(discussionState(db, repo).get(`${repo}#${number}`), seen ?? since, hash);
export function reviewRequestedSince(db: DatabaseSync, repo: string, number: number, since: string, seen: string | null, hash: string | null, state: DiscussionState = discussionState(db, repo)): boolean {
return markedStaleSince(db, repo, number, since) || maintainerSince(state.get(`${repo}#${number}`), seen ?? since, hash);
}
/** True when the discussion has a counted entry newer than a review's snapshot and differs from what that review read (no hash: any newer entry). */
@@ -316,7 +321,7 @@ export function staleReviews(db: DatabaseSync, repo?: string, respectCap = false
// On a head that has a review, only a maintainer's words (or an operator's request) make it stale: the PR author's comments feed the next review but do not start one.
const talked = maintainerSince(state.get(ref), r.seen_at ?? r.at, r.disc_hash);
// A hold that waited for other items is reviewed once when none is open any more.
const unblocked = !!r.blocked_by && storedBlockedBy(r.blocked_by).length > 0 && openBlockers(db, storedBlockedBy(r.blocked_by)).length === 0;
const unblocked = !!r.blocked_by && storedBlockedBy(r.blocked_by).length > 0 && activeBlockers(db, ref, r.blocked_by, r.at).length === 0;
if (!marked && !unblocked && !(talked && !(respectCap && capped(r)))) continue;
out.add(`${ref}@${r.head_oid}`);
}
@@ -332,7 +337,7 @@ export async function ensurePipelineLogin(db: DatabaseSync, q: Querier): Promise
/**
* Just before a merge: reads the PR's discussion and reviews live in one query. `moved`: a counted entry newer than
* the final review's snapshot (and different from what it read) exists; the PR's reviews are then marked stale so the
* the final review's snapshot (and different from what it read) was written by a maintainer or operator (the PR author's comments are read by the next review without stopping the merge); the PR's reviews are then marked stale so the
* pipeline reviews it again. `blocked`: a maintainer's changes-requested review stands. Either way the caller must
* not merge. What the read saw of the formal reviews is stored in review_gates.
*/
@@ -340,7 +345,7 @@ export async function liveGate(db: DatabaseSync, q: Querier, repo: string, numbe
const live = await liveDiscussion(q, db, repo, number);
const blocked = recordGate(db, repo, number, live.formal, live.reviewDecision);
const snap = db.prepare("SELECT COALESCE(seen_at, at) AS seen, disc_hash AS hash FROM opus_reviews WHERE repo = ? AND number = ? AND head_oid = ? AND verdict IS NOT NULL").get(repo, number, head) as { seen: string; hash: string | null } | undefined;
if (!snap || !live.newest || !changedSince({ newest: live.newest, hash: live.snap.hash! }, snap.seen, snap.hash)) return { moved: false, blocked };
if (!snap || !live.newestMaint || !changedSince({ newest: live.newestMaint, hash: live.snap.hash! }, snap.seen, snap.hash)) return { moved: false, blocked };
db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(staleKey(repo, number), new Date().toISOString());
return { moved: true, blocked };
}
+76 -27
View File
@@ -1,11 +1,13 @@
// Reasons a due review waits: another item blocks the PR, CI at its head has not passed, or the PR used its reviews for the day.
// Reasons a due review waits: another item blocks the PR, CI at its head has not passed, the PR used its reviews for the day,
// the last review is too recent, or the last attempts at this head failed.
import type { DatabaseSync } from "node:sqlite";
import { audit } from "../dash/audit.ts";
import { effectiveCi } from "../optional-checks.ts";
import { openBlockers, storedBlockedBy } from "./blockers.ts";
import { MAX_RERUNS_PER_DAY, reviewRequestedSince } from "./discussion.ts";
import { activeBlockers, storedBlockedBy } from "./blockers.ts";
import { MAX_RERUNS_PER_DAY, discussionState, reviewRequestedSince, type DiscussionState } from "./discussion.ts";
import { ourCommitsSince } from "./ours.ts";
/** Opus reviews of one PR per UTC day, new heads and re-runs together. */
/** Opus review calls of one PR per UTC day, new heads, re-runs, failed calls and reply-fix turns together. */
export const MAX_REVIEWS_PER_DAY = MAX_RERUNS_PER_DAY;
/** Setting: least minutes between two Opus reviews of one PR; 0 turns the wait off. */
@@ -13,6 +15,10 @@ export const MIN_INTERVAL_KEY = "review_min_interval_minutes";
export const MIN_INTERVAL_DEFAULT = 120;
const MIN_INTERVAL_MAX = 7 * 24 * 60;
/** Waits after the 1st, 2nd and 3rd failed review at one head; a 4th failure holds the head until a new commit or Review again. */
export const FAILURE_BACKOFF_MS = [10 * 60_000, 30 * 60_000, 2 * 3600_000];
const FAIL_KEY = "review_fail:";
export function reviewMinInterval(db: DatabaseSync): number {
const v = (db.prepare("SELECT value FROM main.settings WHERE key = ?").get(MIN_INTERVAL_KEY) as { value: string } | undefined)?.value;
const n = Number(v);
@@ -28,8 +34,19 @@ export function setReviewMinInterval(db: DatabaseSync, input: unknown, by: strin
return n;
}
/** `until`: when an interval wait ends (ms), so the planner wakes then. */
export type ReviewHold = { kind: "blocked" | "ci" | "cap" | "interval"; wait: string; until?: number };
const failKey = (repo: string, number: number, head: string) => `${FAIL_KEY}${repo}#${number}@${head}`;
/** Counts a review call at this head that gave no valid review; the earlier heads' counts are forgotten. */
export function recordReviewFailure(db: DatabaseSync, repo: string, number: number, head: string, nowMs: number = Date.now()): void {
const key = failKey(repo, number, head);
const cur = (db.prepare("SELECT value FROM main.settings WHERE key = ?").get(key) as { value: string } | undefined)?.value;
const n = (Number(cur?.split("|")[0]) || 0) + 1;
db.prepare("DELETE FROM main.settings WHERE key LIKE ? AND key <> ?").run(`${FAIL_KEY}${repo}#${number}@%`, key);
db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(key, `${n}|${new Date(nowMs).toISOString()}`);
}
/** `until`: when a timed wait ends (ms), so the planner wakes then. `red`: a ci hold whose head's CI has failed (not still running). */
export type ReviewHold = { kind: "blocked" | "ci" | "cap" | "interval" | "failed"; wait: string; until?: number; red?: boolean };
/** CI at the PR's head as the review gate reads it: "ok" (passed, or no checks and none pending), "pending", "failure", or "unknown" when the stored checks describe another head. */
export function headCi(db: DatabaseSync, repo: string, number: number, head: string): "ok" | "pending" | "failure" | "unknown" {
@@ -39,29 +56,61 @@ export function headCi(db: DatabaseSync, repo: string, number: number, head: str
return o === "pending" ? "pending" : o === "failure" ? "failure" : "ok";
}
const nextMidnight = (ms: number): number => { const d = new Date(ms); return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1); };
/**
* What holds back the next review of a PR at `head`, or null. A maintainer's or operator's request after the latest review lifts every hold.
* The hold check of every PR of one planning pass: statements are prepared once. A hold is what keeps the next review of a PR at `head`
* from starting, or null. A maintainer's or operator's request after the latest review lifts every hold.
* An unknown CI state does not hold (the review step reads the checks live before asking the model and applies this again).
* Not held by CI: the first review of a PR when CI is red (running CI still waits), and the one review after the blockers settled.
* Not held by the cap or the interval: a head that only our own pushes made since the last review.
*/
export function reviewHold(db: DatabaseSync, repo: string, number: number, head: string, nowMs: number = Date.now()): ReviewHold | null {
const last = db.prepare(`SELECT head_oid, at, verdict, seen_at, disc_hash, blocked_by FROM main.opus_reviews WHERE repo = ? AND number = ? AND verdict IS NOT NULL ORDER BY at DESC, rowid DESC LIMIT 1`)
.get(repo, number) as { head_oid: string; at: string; verdict: string; seen_at: string | null; disc_hash: string | null; blocked_by: string | null } | undefined;
if (last && reviewRequestedSince(db, repo, number, last.at, last.seen_at, last.disc_hash)) return null;
if (last?.verdict === "hold") {
const open = openBlockers(db, storedBlockedBy(last.blocked_by));
if (open.length) return { kind: "blocked", wait: `${open.join(", ")}, which blocks its review` };
}
const ci = headCi(db, repo, number, head);
if (ci === "pending") return { kind: "ci", wait: "CI on the latest commit to finish" };
if (ci === "failure") return { kind: "ci", wait: "CI on the latest commit to pass" };
export function reviewHolds(db: DatabaseSync, nowMs: number = Date.now()): (repo: string, number: number, head: string) => ReviewHold | null {
const lastReview = db.prepare(`SELECT head_oid, at, verdict, seen_at, disc_hash, blocked_by FROM main.opus_reviews WHERE repo = ? AND number = ? AND verdict IS NOT NULL ORDER BY at DESC, rowid DESC LIMIT 1`);
const history = db.prepare(`SELECT COUNT(CASE WHEN at >= :today THEN 1 END) AS n, MAX(at) AS last FROM main.opus_review_history
WHERE repo = :repo AND number = :number AND model IS NOT NULL AND model <> 'carried' AND COALESCE(mode, '') <> 'carried'`);
const runs = db.prepare(`SELECT COUNT(CASE WHEN r.started_at >= :today THEN 1 END) AS n, MAX(r.started_at) AS last FROM main.agent_run_items i
JOIN main.agent_runs r ON r.id = i.run_id WHERE i.repo = :repo AND i.number = :number AND r.step = 'opus-review'`);
const failure = db.prepare("SELECT value FROM main.settings WHERE key = ?");
const interval = reviewMinInterval(db) * 60_000;
const today = new Date(nowMs).toISOString().slice(0, 10);
const n = (db.prepare("SELECT COUNT(*) AS n FROM main.opus_review_history WHERE repo = ? AND number = ? AND model IS NOT NULL AND at >= ?").get(repo, number, today) as { n: number }).n;
if (n >= MAX_REVIEWS_PER_DAY) return { kind: "cap", wait: "review cap for today reached; next on a maintainer's request or tomorrow" };
const gap = reviewMinInterval(db) * 60_000;
if (gap) {
const at = (db.prepare("SELECT MAX(at) AS at FROM main.opus_review_history WHERE repo = ? AND number = ? AND model IS NOT NULL").get(repo, number) as { at: string | null }).at;
const until = at ? Date.parse(at) + gap : 0;
if (until > nowMs) return { kind: "interval", wait: `next review after ${new Date(until).toISOString().slice(11, 16)}`, until };
}
return null;
const states = new Map<string, DiscussionState>();
type Last = { head_oid: string; at: string; verdict: string; seen_at: string | null; disc_hash: string | null; blocked_by: string | null };
return (repo, number, head) => {
const last = lastReview.get(repo, number) as Last | undefined;
if (last) {
let state = states.get(repo);
if (!state) states.set(repo, (state = discussionState(db, repo)));
if (reviewRequestedSince(db, repo, number, last.at, last.seen_at, last.disc_hash, state)) return null;
}
let settled = false;
if (last?.verdict === "hold" && storedBlockedBy(last.blocked_by).length) {
const open = activeBlockers(db, `${repo}#${number}`, last.blocked_by, last.at, nowMs);
if (open.length) return { kind: "blocked", wait: `${open.join(", ")}, which blocks its review` };
settled = true;
}
const ci = headCi(db, repo, number, head);
if (ci === "pending") return { kind: "ci", wait: "CI on the latest commit to finish" };
if (ci === "failure" && last && !settled) return { kind: "ci", wait: "CI on the latest commit to pass", red: true };
const failed = (failure.get(failKey(repo, number, head)) as { value: string } | undefined)?.value;
if (failed) {
const [n, at] = [Number(failed.split("|")[0]), Date.parse(failed.split("|")[1] ?? "")];
const delay = FAILURE_BACKOFF_MS[n - 1];
if (delay === undefined) return { kind: "failed", wait: `its review failed ${n} times at this commit; a new commit or a maintainer's request` };
if (at + delay > nowMs) return { kind: "failed", wait: `the review after ${n} failed ${n === 1 ? "try" : "tries"} at this commit, from ${new Date(at + delay).toISOString().slice(11, 16)}`, until: at + delay };
}
const ours = last && last.head_oid !== head ? ourCommitsSince(db, repo, number, last.head_oid, head) : null;
if (ours?.complete && ours.commits.length) return null;
const h = history.get({ today, repo, number }) as { n: number; last: string | null };
const r = runs.get({ today, repo, number }) as { n: number; last: string | null };
if (Math.max(h.n, r.n) >= MAX_REVIEWS_PER_DAY) return { kind: "cap", wait: "review cap for today reached; next on a maintainer's request or tomorrow", until: nextMidnight(nowMs) };
if (interval) {
const at = [h.last, r.last].filter((x): x is string => !!x).sort().pop();
const until = at ? Date.parse(at) + interval : 0;
if (until > nowMs) return { kind: "interval", wait: `next review after ${new Date(until).toISOString().slice(11, 16)}`, until };
}
return null;
};
}
export const reviewHold = (db: DatabaseSync, repo: string, number: number, head: string, nowMs: number = Date.now()): ReviewHold | null => reviewHolds(db, nowMs)(repo, number, head);
+7 -4
View File
@@ -75,15 +75,18 @@ export type OpusPr = {
statements?: OwnerStatement[];
};
const BLOCKER_REF = /^[\w.-]+#\d+$/;
/** "repo#n", "#n" (a PR of the same repo) or "owner/repo#n" (the owner is dropped). */
const BLOCKER_REF = /^(?:[\w.-]+\/)?([\w.-]*)#(\d+)$/;
/** The `blocked_by` of a reply: well-formed "repo#n" refs other than the PR itself, one each, at most 5. Whether they are tracked is checked against the database (openBlockers). */
/** The `blocked_by` of a reply: refs normalised to "repo#n", other than the PR itself, one each, at most 5. Whether they are tracked is checked against the database (openBlockers). */
export function parseBlockedBy(v: unknown, self: string): string[] {
if (!Array.isArray(v)) return [];
const out: string[] = [];
for (const x of v) {
const ref = typeof x === "string" ? x.trim() : "";
if (BLOCKER_REF.test(ref) && ref !== self && !out.includes(ref)) out.push(ref);
const m = BLOCKER_REF.exec(typeof x === "string" ? x.trim() : "");
if (!m) continue;
const ref = `${m[1] || self.split("#")[0]}#${m[2]}`;
if (ref !== self && !out.includes(ref)) out.push(ref);
}
return out.slice(0, 5);
}
+4 -2
View File
@@ -10,7 +10,7 @@ import { REVIEW_OPUS } from "../agents/steps.ts";
import { Client, type Querier } from "../mirror.ts";
import { checksOf, refreshChecks } from "./checks.ts";
import { openBlockers } from "./blockers.ts";
import { reviewHold } from "./gate.ts";
import { recordReviewFailure, reviewHolds } from "./gate.ts";
import { MAX_RERUNS_PER_DAY, countRerun, discussionOf, ensurePipelineLogin, liveDiscussion, markedStaleSince, staleReviews, withRetry, type Snapshot } from "./discussion.ts";
import { withdrawMergeQuestion } from "../merge/withdraw.ts";
import { headWasUnsure, mergeDecisionId } from "../merge/queue.ts";
@@ -205,12 +205,13 @@ export async function runOpusReview(db: DatabaseSync, params: OpusParams, log: (
return summary;
}
const asked = cands.length;
const holds = reviewHolds(db);
const byNumber = new Map(live.map((l) => [l.number, l]));
cands = cands.filter((c) => {
const l = byNumber.get(c.number);
const ok = !!l && l.state === "OPEN" && !l.is_draft && l.head_oid === c.head_oid;
// The checks were just read: a head whose CI is running or red waits for the next push or the finished run.
const hold = ok ? reviewHold(db, repo, c.number, c.head_oid) : null;
const hold = ok ? holds(c.repo, c.number, c.head_oid) : null;
if (hold) { log(` ${refOf(c)}: not reviewed, waits for ${hold.wait}`); return false; }
if (!ok) log(` ${refOf(c)}: dropped, ${l ? `now ${l.state}${l.is_draft ? " draft" : ""} at ${l.head_oid.slice(0, 7)}` : "not found on GitHub"}`);
return ok;
@@ -267,6 +268,7 @@ export async function runOpusReview(db: DatabaseSync, params: OpusParams, log: (
saveOpus(db, runId, c, { mode, base, model: deps.model, review: got, snap, unapplied: outcomes });
tally(c, got);
} else {
recordReviewFailure(db, c.repo, c.number, c.head_oid);
jobItem(db, c.repo, c.number, "no valid Opus review", log);
summary.missing.push(refOf(c));
}
+11
View File
@@ -297,6 +297,8 @@ const LANE_CODE: Omit<Lane, "steps">[] = [
const top = firstByRepo(planned(db, "review", { plans: plansOf(db, ctx) }));
// A PR waiting out the minimum time between reviews is planned again when it ends.
for (const p of plansOf(db, ctx).prs) if (p.facts.reviewHold?.until) ctx.wake?.push(p.facts.reviewHold.until);
// No other stage re-reads the checks of a head that was stored as running or red: a PR whose review waits for CI has its repo's checks read again, at most once per WAITING_CI_RECHECK_MS.
const ciWait = new Set(plansOf(db, ctx).prs.filter((p) => p.facts.reviewHold?.kind === "ci" && p.plan.wait === p.facts.reviewHold.wait).map((p) => p.facts.repo));
for (const repo of flightFirst(plansOf(db, ctx), fastFirst(db, roundRobin(ctx.tracked, getSetting(db, KEY_CURSOR)), (r) => top.get(r)?.facts.number))) {
if (!top.has(repo)) continue;
const checks = lastJobEnd(db, "checks", repo);
@@ -304,6 +306,15 @@ const LANE_CODE: Omit<Lane, "steps">[] = [
const review = { step: "opus-review", params: { repo } };
out.push(fresh ? review : { step: "checks", params: { repo }, poll: true, gate: review });
}
for (const repo of [...ciWait].sort()) {
if (out.some((c) => c.params.repo === repo)) continue;
const last = lastJobEnd(db, "checks", repo);
if (last && Date.now() - Date.parse(last.endedAt) < WAITING_CI_RECHECK_MS) {
ctx.wake?.push(Date.parse(last.endedAt) + WAITING_CI_RECHECK_MS);
continue;
}
out.push({ step: "checks", params: { repo }, poll: true });
}
return out;
},
topScore: (db, ctx) => {
+2 -1
View File
@@ -235,7 +235,8 @@ export const STAGES: StageDef[] = [
{ name: "Checks before Review and Verify", why: "CI data younger than 5 minutes is reused", howLong: "5 minutes", showsAs: "Job list", kind: "backoff" },
{ name: "Blocked by another item", why: "A hold review named an open item as its reason (for example the PR is stacked on another open PR); the PR is not reviewed again, on new commits or discussion, until that item is merged, closed or decided", howLong: "Until the blocker is merged, closed or decided; a maintainer's comment or Review again lifts it", showsAs: "Plan wait: the blocker's reference", kind: "external" },
{ name: "CI on the latest commit", why: "A new head is reviewed only after its CI has finished and passed; a head whose CI runs or is red is skipped", howLong: "Until CI at the head finishes green, or a later push", showsAs: "Plan wait: CI on the latest commit", kind: "external" },
{ name: "Review cap for today", why: "At most 3 Opus reviews per PR per UTC day, new commits and re-runs together", howLong: "Until the next UTC day; a maintainer's comment or Review again lifts it", showsAs: "Plan wait: review cap for today reached", kind: "external" },
{ name: "Failed review", why: "A review call that gave no valid review is not repeated at once: the failure is counted per head", howLong: "10 minutes after the first failure, 30 after the second, 2 hours after the third; a fourth holds the head until a new commit or Review again", showsAs: "Plan wait: the review after n failed tries", kind: "backoff" },
{ name: "Review cap for today", why: "At most 3 Opus review calls per PR per UTC day, new commits, re-runs, failed calls and reply-fix turns together", howLong: "Until the next UTC day; a maintainer's comment or Review again lifts it", showsAs: "Plan wait: review cap for today reached", kind: "external" },
{ name: "Minimum time between reviews", why: "Setting review_min_interval_minutes (default 120, 0 turns it off; `autocraft pipeline review-interval`): a PR reviewed less than that long ago waits, then the latest green head is reviewed", howLong: "The setting's minutes since the PR's last review; a maintainer's comment or Review again lifts it", showsAs: "Plan wait: next review after hh:mm", kind: "external" },
],
writes: [{ what: "Final review comment", approval: "comment" }],
+72 -2
View File
@@ -1,8 +1,10 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { loadPlanSet } from "../src/core/plan-set.ts";
import { isCounted, markReviewsStale, staleReviews } from "../src/review/discussion.ts";
import { setReviewMinInterval } from "../src/review/gate.ts";
import { cifixBucket } from "../src/core/decide.ts";
import { detectAutopilot } from "../src/runner/autopilot.ts";
import { isCounted, liveGate, markReviewsStale, staleReviews } from "../src/review/discussion.ts";
import { recordReviewFailure, setReviewMinInterval } from "../src/review/gate.ts";
import { saveOpus } from "../src/review/opus.ts";
import { parseOpusReply } from "../src/review/opus-parse.ts";
import { world } from "./world-db.ts";
@@ -61,6 +63,10 @@ test("a head is reviewed once CI at it has finished green", () => {
assert.equal(reviews(w, 1), 0);
assert.match(planOf(w, 1).wait ?? "", /CI on the latest commit/);
w.db.prepare("UPDATE pr_checks SET overall = 'failure', checks = '[{\"name\":\"gate / test\",\"state\":\"failure\"}]' WHERE number = 1").run();
assert.equal(reviews(w, 1), 1); // the first review of a PR runs on finished red CI
review(w, 1, "h1", "take");
w.synced(1, "h2");
w.db.prepare("UPDATE pr_checks SET overall = 'failure', checks = '[{\"name\":\"gate / test\",\"state\":\"failure\"}]' WHERE number = 1").run();
assert.equal(reviews(w, 1), 0);
w.db.prepare("UPDATE pr_checks SET overall = 'success', checks = '[]' WHERE number = 1").run();
assert.equal(reviews(w, 1), 1);
@@ -89,3 +95,67 @@ test("a second review inside the minimum interval waits until it passes; Review
markReviewsStale(w.db, "op", "app", 1);
assert.equal(reviews(w, 1), 1);
});
test("a PR whose review waits for CI gets its repo's checks read again", async () => {
const w = noGaps(world().repo().pr(1, { head: "h1" }).pipeline(true));
review(w, 1, "h1", "take");
w.synced(1, "h2");
w.db.prepare("UPDATE pr_checks SET overall = 'pending' WHERE number = 1").run();
const found = await detectAutopilot(w.db);
assert.ok(found.proposals.some((p) => p.step === "checks" && p.params.repo === "app"), JSON.stringify(found.proposals));
});
test("red CI at a new head leaves the CI fix to work from the earlier review; the first review still runs on red CI", () => {
const w = noGaps(world().repo().pr(1, { head: "h1" }).pr(2, { head: "g1" }));
review(w, 1, "h1", "take");
w.synced(1, "h2");
const red = "UPDATE pr_checks SET overall = 'failure', checks = '[{\"name\":\"gate / test\",\"state\":\"failure\"}]' WHERE number = ";
w.db.prepare(red + "1").run();
assert.equal(reviews(w, 1), 0);
const facts = loadPlanSet(w.db).prs.find((p) => p.facts.number === 1)!.facts;
assert.notEqual(cifixBucket(facts), null);
w.db.prepare(red + "2").run();
assert.equal(reviews(w, 2), 1);
});
test("a head made only by our own push skips the interval", () => {
const w = world().repo().pr(1, { head: "h1" });
setReviewMinInterval(w.db, 120, "test");
review(w, 1, "h1", "take");
w.synced(1, "h2");
assert.equal(reviews(w, 1), 0);
w.db.prepare("INSERT INTO fixups (repo, number, from_head, to_head, state, attempt, created_at) VALUES ('app', 1, 'h1', 'h2', 'pushed', 1, ?)").run(new Date().toISOString());
assert.equal(reviews(w, 1), 1);
});
test("review calls and failed tries count: runs fill the day's cap, failures back off then hold", () => {
const w = noGaps(world().repo().pr(1, { head: "h1" }));
review(w, 1, "h1", "take");
w.synced(1, "h2");
for (let i = 0; i < 3; i++) {
const id = Number(w.db.prepare("INSERT INTO agent_runs (step, stage, prompt_id, prompt_version, provider, model, state, started_at) VALUES ('opus-review', 5, 'review.opus', '1', 'claude', 'opus', 'failed', ?)").run(new Date().toISOString()).lastInsertRowid);
w.db.prepare("INSERT INTO agent_run_items (run_id, repo, number) VALUES (?, 'app', 1)").run(id);
}
w.db.prepare("DELETE FROM opus_review_history").run();
assert.match(planOf(w, 1).wait ?? "", /review cap for today/);
w.db.prepare("DELETE FROM agent_runs").run(); w.db.prepare("DELETE FROM agent_run_items").run();
assert.equal(reviews(w, 1), 1);
recordReviewFailure(w.db, "app", 1, "h2");
assert.equal(reviews(w, 1), 0);
assert.equal(planOf(w, 1, Date.now() + 11 * 60_000).actions.filter((a) => a.kind === "review").length, 1);
for (let i = 0; i < 3; i++) recordReviewFailure(w.db, "app", 1, "h2");
assert.equal(planOf(w, 1, Date.now() + 24 * 3600_000 * 0.5).actions.filter((a) => a.kind === "review").length, 0);
assert.match(planOf(w, 1).wait ?? "", /failed 4 times/);
});
test("the merge-time check ignores the PR author's new comment", async () => {
const w = noGaps(world().repo().pr(1, { head: "h1", author: "regular" }));
review(w, 1, "h1", "take");
const at = new Date(Date.now() + 5000).toISOString();
const node = (assoc: string, login: string) => ({ id: `c-${login}`, author: { login, __typename: "User" }, authorAssociation: assoc, createdAt: at, body: "Please look again" });
const q = (login: string, assoc: string) => ({ spent: 0, remaining: 1, async query() {
return { repository: { pullRequest: { author: { login: "regular" }, reviewDecision: null, comments: { nodes: [node(assoc, login)] }, reviews: { nodes: [] }, formal: { nodes: [] }, reviewThreads: { nodes: [] } } } };
} }) as never;
assert.equal((await liveGate(w.db, q("regular", "CONTRIBUTOR"), "app", 1, "h1")).moved, false);
assert.equal((await liveGate(w.db, q("maint", "MEMBER"), "app", 1, "h1")).moved, true);
});