Public: anyone can read this; the crew can change it.

Revert-first lane: a red main's culprit is reverted by the crew, checked first, and lands on green #17236

opened this

Merged 36h 50m ago, live in production

checks/revert-lane → main 0 commits 1 thread · 1 unresolved

  • Merged. checks/revert-lane was merged into main as 0c2f468.

Review

Sign in to review this change.
23 files changed +702 −35
docs/features/revert-lane.md added +31
@@ -0,0 +1,31 @@
1 ---
2 topic: Ship and undo
3 row: A red main reverts its culprit first: the crew opens the revert, it checks first, and lands on green
4 ---
5 # The revert-first lane
6
7 When main goes red and the forge can name the landing that did it, the crew takes that landing
8 back before anything else moves (`src/checks/revert_lane.ts`).
9
10 - **When.** Main's verification bisects to one landed pull (`checks/culprit.ts`), or main fails the
11 same test twice in a row with one landing in between (`checks/revert_red.ts`). And when three
12 different pulls' checks fail the same test within half an hour while main's own check is not red,
13 main is asked for a verification at once (`checks/shared_verify.ts`); a red one is bisected to its
14 culprit like any other. A landing that
15 added a migration, a push no pull carried, or a red that ran out of time opens no revert, as
16 before.
17 - **Who.** The crew's agent (its first builder) opens the revert pull, labelled `revert-red`. The
18 body names the culprit and the failing test. The branch is the forge's own, written as the
19 repository's owner; an agent's own call to take a change back is still refused.
20 - **First.** Its check is never held by the red it answers, and it goes before every other check.
21 In the merge queue it gates alone, ahead of every batch, and joins none.
22 - **Lands.** Like any crew pull in an autonomous repository: once its own check is green on its
23 head (main may have moved) and it is approved, through the queue. Just before it is admitted,
24 the guard asks whether the red still stands:
25 - main went green again: the revert is closed, not landed, and says why;
26 - the culprit is no longer on main: closed;
27 - a pull by the culprit's author landed since main went red, or is open and green: the revert
28 waits, and main's next check says whether the fix answered it.
29 - **Stop.** The Bridge's red-main line, and the terminal home's, read "Main has been red for N min:
30 test. Reverting #culprit with #revert; Stop holds it." Stop opens the revert's hold: a held pull
31 never lands; lifting the hold resumes it.
src/actions/revert.ts +17 −6
@@ -9,9 +9,9 @@
99
1010 import type { App } from "../app.ts";
1111 import { revertOf, type Pull } from "../core/pulls.ts";
12 import type { Repo } from "../core/repos.ts";
1312 import { commitIdentity } from "../core/commit_identity.ts";
14 import type { User } from "../core/users.ts";
13 import { getUserById, type User } from "../core/users.ts";
14 import { onCrew, type Repo } from "../core/repos.ts";
1515 import { resolveOid } from "../git/merge.ts";
1616 import { repoDir } from "../git/repos.ts";
1717 import { revertCommit, type RevertError } from "../git/revert.ts";
@@ -35,13 +35,24 @@ export async function revertPull(
3535 repo: Repo,
3636 pull: Pull,
3737 body: string = `Reverts #${pull.number}.`,
38 /**
39 * `lane`: the forge's revert-first lane (`checks/revert_lane.ts`) opens it as the crew's agent.
40 * Never set by a door: an agent's tool call is refused below as before.
41 */
42 opts: { readonly lane?: boolean } = {},
3843 ): Promise<Result<Pull, RevertPullError>> {
39 const writer = requireWriter(app, actor, repo);
44 // The lane's revert: the branch is the forge's, written as the repository's owner; the pull is the
45 // crew's agent's (on this repository's crew), so its review and its landing are a crew pull's.
46 const lane = opts.lane === true && actor !== undefined && actor.kind === "agent" && onCrew(app.db, repo, actor);
47 const writer = requireWriter(app, lane ? getUserById(app.db, repo.ownerId) : actor, repo);
4048 if (!writer.ok) return writer;
4149 if (pull.repoId !== repo.id) return err("not_found");
4250 // Rule 1 in docs/APPS.md: the crew proposes, a person lands. Taking a
43 // change back is a landing verb, not a proposing one.
51 // change back is a landing verb, not a proposing one; only the forge's own revert lane opens one
52 // as the crew's agent, and it still lands only through its check, its review and the queue.
4453 if (writer.value.kind === "agent") return err("forbidden");
54 if (opts.lane === true && actor?.kind === "agent" && !lane) return err("forbidden");
55 const proposer = lane ? actor : writer.value;
4556 if (pull.mergedAt === null || pull.mergedOid === null)
4657 return err("not_shipped");
4758 // On a mirror the origin owns history; a local revert here would be
@@ -60,7 +71,7 @@ export async function revertPull(
6071 commitOid: pull.mergedOid,
6172 ontoOid: onto,
6273 message: `Revert "${pull.title}" (#${pull.number})`,
63 author: commitIdentity(app.config, writer.value),
74 author: commitIdentity(app.config, proposer),
6475 });
6576 if (!built.ok) return built;
6677
@@ -76,7 +87,7 @@ export async function revertPull(
7687 return err({ kind: "branch_failed", reason });
7788 }
7889
79 const opened = await openPull(app, writer.value, repo, {
90 const opened = await openPull(app, proposer, repo, {
8091 title: `Revert "${pull.title}"`,
8192 body,
8293 baseBranch: repo.defaultBranch,
src/checks/culprit.ts +4 −4
@@ -25,7 +25,7 @@
2525 */
2626
2727 import type { App } from "../app.ts";
28 import { revertPull } from "../actions/revert.ts";
28 import { LANE_LINE, openLaneRevert } from "./revert_lane.ts";
2929 import { deleteBranch } from "../actions/branches.ts";
3030 import { addComment as commentAs, setIssueState as closeAs } from "../actions/issues.ts";
3131 import { addComment, createIssue, getIssueById, setIssueState } from "../core/issues.ts";
@@ -219,13 +219,13 @@ async function name(app: App, repo: Repo, red: Run, culprit: string, green: stri
219219 const again = await confirmingRed(app, repo, red, culprit);
220220 if (again === undefined)
221221 return `culprit #${pull.number} (${short(culprit)}): its revert waits for the next verification to fail the same test`;
222 const owner = getUserById(app.db, repo.ownerId);
223222 const body =
224223 `Reverts #${pull.number}: verifying main after landing found it broke ${redSays(red)} — ${how}.\n\n` +
225224 `Main's verifications ${red.id} and ${again.id} are red at ${short(red.commitOid)} and ${short(again.commitOid)}, ` +
226225 `one after the other; each failed test fails alone too.\n\n` +
227 `Proposed by the forge; a person lands it.\n\nFiles: ${files.join(", ")}`;
228 const made = await revertPull(app, owner, repo, pull, body);
226 `${LANE_LINE}\n\nFiles: ${files.join(", ")}`;
227 // The crew's agent opens it, labelled, for the lane (`revert_lane.ts`).
228 const made = await openLaneRevert(app, repo, pull, body);
229229 return made.ok
230230 ? `culprit #${pull.number} (${short(culprit)}): proposed its revert, #${made.value.number}`
231231 : `culprit #${pull.number} (${short(culprit)}): the revert could not be proposed (${made.error})`;
src/checks/execute.ts +15 −1
@@ -12,7 +12,11 @@ import { afterVerify, closeOnGreen, closeRevertsOnGreen } from "./culprit.ts";
1212 import { noteLookPages } from "./look_pages.ts";
1313 import { reportGreen, reportRed, type AloneAnswer } from "./report.ts";
1414 import type { Database } from "bun:sqlite";
15 import { bisectOrigin, inVerifyLane, safeFile, VERIFY_ENV } from "./verify.ts";
15 import { bisectOrigin, inVerifyLane, safeFile, VERIFY_ENV, VERIFY_REASON } from "./verify.ts";
16 import { SHARED_VERIFY_MS, verifyForSharedRed } from "./shared_verify.ts";
17 import { SHARED_PULLS } from "./shared_red.ts";
18 import { resolveOid } from "../git/merge.ts";
19 import { repoDir } from "../git/repos.ts";
1620 import { getIssueById } from "../core/issues.ts";
1721 import { BUDGETS, budgetSummary, checkLimitMs } from "../kernel/budgets.ts";
1822 import { createLog } from "../kernel/log.ts";
@@ -247,6 +251,16 @@ export async function execute(
247251 proposeRevert(app, repo.id).catch((error) =>
248252 log.error("revert proposal failed", { error: String(error) }),
249253 );
254 // Three different pulls failing one test while main looks green: verify main now, so a red is

Add a test that drives this branch: three failing pull checks, then one verification request for main. Today only verifyForSharedRed is tested.

255 // bisected to its culprit and the revert lane can take it back (`shared_verify.ts`).
256 if (!outcome.ok && run.issueId !== null) {
257 const tip = await resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), `refs/heads/${repo.defaultBranch}`);
258 const shared = tip === undefined ? undefined : verifyForSharedRed(app.db, repo.id, tip);
259 if (shared !== undefined && tip !== undefined) {
260 write(`${SHARED_PULLS} pulls fail "${shared}" within ${SHARED_VERIFY_MS / 60_000} min: main is asked for a verification now`);
261 await lane.request(repo, VERIFY_ENV, tip, VERIFY_REASON);
262 }
263 }
250264 // Main's own check green with a reverted landing still in it closes that revert (#6377).
251265 if (done && outcome.ok && run.issueId === null && run.env === repo.defaultBranch)
252266 await closeRevertsOnGreen(app, repo, done, [])
src/checks/pick.ts +8 −1
@@ -40,7 +40,13 @@ export function pickNext(
4040 rank: (run: Run) => number | undefined = () => undefined,
4141 outside: (run: Run) => boolean = () => false,
4242 own: (run: Run) => boolean = () => false,
43 revert: (run: Run) => boolean = () => false,
4344 ): Run | undefined {
45 // A revert's check goes before every other (`revert_lane.ts`): it is the fix for a red main, and
46 // every other pull's check waits on that red. The newest first, as everywhere.
47 const reverts = queued.filter(revert);
48 if (reverts.length > 0)
49 return reverts.reduce((a, b) => (b.createdAt > a.createdAt || (b.createdAt === a.createdAt && b.id > a.id) ? b : a));
4450 // An unapproved outside contributor's check goes after everyone else's (`outside_lane.ts`).
4551 queued = ownersFirst(queued, outside);
4652 if (queued.length === 0) return undefined;
@@ -82,10 +88,11 @@ export function pickOrder(
8288 rank: (run: Run) => number | undefined = () => undefined,
8389 outside: (run: Run) => boolean = () => false,
8490 own: (run: Run) => boolean = () => false,
91 revert: (run: Run) => boolean = () => false,
8592 ): Run[] {
8693 const left = [...queued];
8794 const out: Run[] = [];
88 for (let next = pickNext(left, now, approved, rank, outside, own); next !== undefined; next = pickNext(left, now, approved, rank, outside, own)) {
95 for (let next = pickNext(left, now, approved, rank, outside, own, revert); next !== undefined; next = pickNext(left, now, approved, rank, outside, own, revert)) {
8996 out.push(next);
9097 left.splice(left.indexOf(next), 1);
9198 }
src/checks/queue.ts +6 −3
@@ -103,6 +103,8 @@ export interface Queued {
103103 * that its red tree held: none when it was red on its own merge.
104104 */
105105 handBack(red: Red, baseOid: string, together: readonly number[]): void;
106 /** A lane revert (`revert_lane.ts`): it gates alone, ahead of every batch, and joins none. */
107 readonly alone?: boolean;
106108 }
107109
108110 /** One pull's squash on top of the steps before it. */
@@ -1131,14 +1133,15 @@ async function launch(line: Line, gated: Gated, on: Flight | undefined): Promise
11311133 }
11321134 const cleared = (w: Waiting): boolean => suspectOf(line, w)?.cleared === true;
11331135 const open = line.waiting.filter((w) => suspectOf(line, w)?.alone !== true);
1134 const front = open.find((w) => !w.recheck && !cleared(w)) ?? open.find((w) => !w.recheck) ?? open[0]!;
1136 // A lane revert goes first, alone: it is the fix for a red main.
1137 const front = open.find((w) => w.entry.alone === true) ?? open.find((w) => !w.recheck && !cleared(w)) ?? open.find((w) => !w.recheck) ?? open[0]!;
11351138 const first = front.entry;
11361139 const branch = first.pull.baseBranch;
11371140 if (on !== undefined && (on.recheck || first.dir !== on.candidate.dir || branch !== on.branch)) return "apart";
1138 const same = open.filter((w) => !w.recheck && w.entry.dir === first.dir && w.entry.pull.baseBranch === branch);
1141 const same = open.filter((w) => !w.recheck && w.entry.alone !== true && w.entry.dir === first.dir && w.entry.pull.baseBranch === branch);
11391142 // A halved size holds fresh pulls back; what came back from a batch gates together.
11401143 const size = Math.min(line.ceiling, Math.max(batchSize(line), same.filter((w) => line.back.has(w)).length));
1141 const batch = front.recheck
1144 const batch = front.recheck || front.entry.alone === true
11421145 ? [front]
11431146 : [...same.filter((w) => !cleared(w)), ...same.filter(cleared)].slice(0, size);
11441147 for (const w of batch) line.back.delete(w);
src/checks/red_main.ts +3 −1
@@ -145,11 +145,13 @@ export function unheld(
145145 red: (repoId: string) => RedMain | undefined,
146146 holdMs: number,
147147 now: number = Date.now(),
148 /** A revert's check: the fix for the red, never held by it (`revert_lane.ts`). */
149 revert: (run: Run) => boolean = () => false,
148150 ): Run[] {
149151 if (holdMs <= 0) return [...queued];
150152 const seen = new Map<string, RedMain | undefined>();
151153 return queued.filter((run) => {
152 if (run.issueId === null || run.reason === ASKED) return true;
154 if (run.issueId === null || run.reason === ASKED || revert(run)) return true;
153155 if (!seen.has(run.repoId)) seen.set(run.repoId, red(run.repoId));
154156 return !heldByRed(run, seen.get(run.repoId), holdMs, now);
155157 });
src/checks/revert_lane.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * The revert-first lane (the owner's red main, 2026-12-01). When main's verification bisects to a
3 * landed pull (`culprit.ts`), or main fails the same test twice with one landing in between
4 * (`revert_red.ts`), the crew's own agent opens that pull's revert, labelled `revert-red`, naming
5 * the culprit and the failing test. Its check is never held by the red it answers and goes first
6 * (`pick.ts`, `red_main.ts`); in the merge queue it gates alone and first; and it lands like any
7 * crew pull, once its own check is green and it is approved, unless the red is already answered:
8 * main went green, the culprit is no longer on main, or a fix by the culprit's author landed or
9 * waits green (`laneGuard`, asked by `land_admit.ts`). A person stops it with a hold (the Bridge's
10 * red-main line says so). Plain rows in, plain answers out, but for `openLaneRevert`.
11 */
12
13 import type { Database } from "bun:sqlite";
14 import type { App } from "../app.ts";
15 import { revertPull, type RevertPullError } from "../actions/revert.ts";
16 import { listCrewRoles } from "../core/agents.ts";
17 import { createLabel, labelsFor, listLabels, setIssueLabels } from "../core/issues.ts";
18 import { getPull, type Pull } from "../core/pulls.ts";
19 import type { Repo } from "../core/repos.ts";
20 import type { Run } from "../core/runs.ts";
21 import { getUserById, type User } from "../core/users.ts";
22 import { runGit } from "../git/env.ts";
23 import { isSafeOid } from "../git/guard.ts";
24 import { repoDir } from "../git/repos.ts";
25 import type { Result } from "../kernel/result.ts";
26 import { redMain } from "./red_main.ts";
27
28 /** The label the lane's reverts carry. */
29 export const REVERT_LABEL = "revert-red";
30
31 /** What a lane revert says of how it lands, in place of "a person lands it". */
32 export const LANE_LINE =
33 "Opened by the crew's revert lane: it lands on its own once its own check is green and it is approved, unless a fix lands first. A hold on it (the Bridge's red-main line, Stop) stops it.";
34
35 /** Who opens the lane's revert: the crew's first builder, else its first seat, else the owner. */
36 export function laneAuthor(db: Database, repo: Repo): User | undefined {
37 const seats = listCrewRoles(db, repo.id);
38 const seat = seats.find((s) => s.role === "builder") ?? seats.find((s) => s.role === "maintainer") ?? seats[0];
39 return seat?.agent.user ?? getUserById(db, repo.ownerId);
40 }
41
42 /** Open `culprit`'s revert as the crew's agent, labelled; the label is made the first time. */
43 export async function openLaneRevert(app: App, repo: Repo, culprit: Pull, body: string): Promise<Result<Pull, RevertPullError>> {
44 const author = laneAuthor(app.db, repo);
45 const made = await revertPull(app, author, repo, culprit, body, { lane: true });
46 if (made.ok) {
47 const label = listLabels(app.db, repo.id).find((l) => l.name.toLowerCase() === REVERT_LABEL) ?? (() => {
48 const created = createLabel(app.db, repo.id, REVERT_LABEL, "b60205");
49 return created.ok ? created.value : undefined;
50 })();
51 if (label !== undefined) setIssueLabels(app.db, made.value.id, [...labelsFor(app.db, made.value.id).map((l) => l.id), label.id]);
52 }
53 return made;
54 }
55
56 /** The pull a pull takes back, when it is a revert. */
57 export const revertedBy = (db: Database, issueId: string): string | undefined =>
58 db.query<{ reverts: string | null }, [string]>("SELECT reverts_issue_id AS reverts FROM pull WHERE issue_id = ?1").get(issueId)?.reverts ?? undefined;
59
60 /** Whether the run is the check of a revert pull (any revert: it is a fix), asked once per run. */
61 export function revertOnce(db: Database): (run: Pick<Run, "id" | "issueId">) => boolean {
62 const known = new Map<string, boolean>();
63 return (run) => {
64 if (run.issueId === null) return false;
65 let yes = known.get(run.id);
66 if (yes === undefined) known.set(run.id, (yes = revertedBy(db, run.issueId) !== undefined));
67 return yes;
68 };
69 }
70
71 /** Whether a pull is one of the lane's: a revert carrying `revert-red`. */
72 export const isLaneRevert = (db: Database, pull: Pick<Pull, "id">): boolean =>
73 revertedBy(db, pull.id) !== undefined && labelsFor(db, pull.id).some((l) => l.name.toLowerCase() === REVERT_LABEL);
74
75 /** What stands between a lane revert and landing; `close` when the red is answered for good. */
76 export type LaneVerdict = { readonly go: true } | { readonly go: false; readonly close: boolean; readonly why: string };
77
78 /**
79 * Whether a lane revert may land now (its own green check and its approval are asked by
80 * `land_admit.ts` as for any pull). Main green again: close it, the red was answered. The culprit
81 * no longer on main: close it, nothing to take back. A pull by the culprit's author landed since
82 * the red, or open with a green head: wait, the fix may answer it; main's next green closes it.
83 */
84 export async function laneGuard(app: App, repo: Repo, revert: Pull): Promise<LaneVerdict> {
85 const target = revertedBy(app.db, revert.id);
86 const culprit = target === undefined ? undefined : app.db.query<{ number: number }, [string]>("SELECT number FROM issue WHERE id = ?1").get(target);
87 const pull = culprit === null || culprit === undefined ? undefined : getPull(app.db, repo.id, culprit.number);
88 if (pull === undefined) return { go: false, close: true, why: "the pull it takes back is gone" };
89 const red = redMain(app.db, repo.id);
90 if (red === undefined) return { go: false, close: true, why: `main is green again with #${pull.number} in it` };
91 const oid = pull.mergedOid;
92 if (oid === null || !isSafeOid(oid)) return { go: false, close: true, why: `#${pull.number} never landed` };
93 const onMain = await runGit(["merge-base", "--is-ancestor", oid, `refs/heads/${repo.defaultBranch}`], { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) });
94 if (!onMain.ok) return { go: false, close: true, why: `#${pull.number} is no longer on ${repo.defaultBranch}` };
95 const fix = app.db
96 .query<{ number: number; merged: string | null }, [string, string, string, string]>(
97 `SELECT i.number, p.merged_at AS merged FROM pull p JOIN issue i ON i.id = p.issue_id
98 WHERE i.repo_id = ?1 AND i.author_id = (SELECT author_id FROM issue WHERE id = ?2) AND i.id NOT IN (?2, ?3)
99 AND p.reverts_issue_id IS NULL
100 AND ((p.merged_at IS NOT NULL AND p.merged_at > ?4)
101 OR (i.state = 'open' AND p.merged_at IS NULL AND EXISTS (
102 SELECT 1 FROM run r WHERE r.issue_id = i.id AND r.kind = 'check' AND r.commit_oid = p.head_oid AND r.state = 'ok')))
103 ORDER BY p.merged_at IS NULL, i.number DESC LIMIT 1`,
104 )
105 .get(repo.id, pull.id, revert.id, red.since);
106 if (fix !== null)
107 return { go: false, close: false, why: fix.merged !== null ? `#${fix.number}, a fix by #${pull.number}'s author, landed since main went red: main's next check says whether it answered` : `#${fix.number}, a fix by #${pull.number}'s author, is open and green: it goes first` };
108 return { go: true };
109 }
110
111 /** The lane's open revert in a repository, for the Bridge's red-main line: the culprit and the revert. */
112 export function laneRevertOpen(db: Database, repoId: string): { readonly culprit: number; readonly revert: number } | undefined {
113 const row = db
114 .query<{ revert: number; culprit: number }, [string, string]>(
115 `SELECT i.number AS revert, t.number AS culprit FROM pull p JOIN issue i ON i.id = p.issue_id JOIN issue t ON t.id = p.reverts_issue_id
116 WHERE i.repo_id = ?1 AND i.state = 'open' AND p.merged_at IS NULL
117 AND EXISTS (SELECT 1 FROM issue_label il JOIN label l ON l.id = il.label_id WHERE il.issue_id = i.id AND l.name = ?2 COLLATE NOCASE)
118 ORDER BY i.number DESC LIMIT 1`,
119 )
120 .get(repoId, REVERT_LABEL);
121 return row ?? undefined;
122 }
123
124 /** `git patch-id --stable` of a diff: equal for two diffs that change the same lines the same way. */
125 async function patchId(dir: string, diff: string): Promise<string | undefined> {
126 if (diff.trim() === "") return undefined;
127 const id = await runGit(["patch-id", "--stable"], { cwd: dir, stdin: diff });
128 return id.ok ? id.value.split(" ")[0] || undefined : undefined;
129 }
130
131 /**
132 * The culprit's number when `pull` is a lane revert that git shows is a pure revert: its diff
133 * against its base is the culprit's landed change reversed, line for line (equal patch ids), so a
134 * reviewer has only that to confirm. Undefined for anything else, or when git cannot say.
135 */
136 export async function pureRevertOf(app: App, repo: Repo, pull: Pull): Promise<number | undefined> {
137 if (!isLaneRevert(app.db, pull) || !isSafeOid(pull.headOid)) return undefined;
138 const target = revertedBy(app.db, pull.id);
139 const culprit = target === undefined ? undefined : app.db.query<{ number: number }, [string]>("SELECT number FROM issue WHERE id = ?1").get(target);
140 const landed = culprit === null || culprit === undefined ? undefined : getPull(app.db, repo.id, culprit.number);
141 const oid = landed?.mergedOid;
142 if (landed === undefined || oid === null || oid === undefined || !isSafeOid(oid)) return undefined;
143 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
144 const base = await runGit(["merge-base", `refs/heads/${pull.baseBranch}`, pull.headOid], { cwd: dir });
145 if (!base.ok || !isSafeOid(base.value)) return undefined;
146 const [back, mine] = await Promise.all([
147 runGit(["diff", "--no-color", "--no-ext-diff", oid, `${oid}^1`], { cwd: dir }),
148 runGit(["diff", "--no-color", "--no-ext-diff", base.value, pull.headOid], { cwd: dir }),
149 ]);
150 if (!back.ok || !mine.ok) return undefined;
151 const [a, b] = await Promise.all([patchId(dir, `${back.value}\n`), patchId(dir, `${mine.value}\n`)]);
152 return a !== undefined && a === b ? landed.number : undefined;
153 }
src/checks/revert_red.ts +5 −7
@@ -11,12 +11,11 @@
1111 */
1212
1313 import type { App } from "../app.ts";
14 import { revertPull } from "../actions/revert.ts";
14 import { LANE_LINE, openLaneRevert } from "./revert_lane.ts";
1515 import { addComment, getIssueById } from "../core/issues.ts";
1616 import { getPull, type Pull } from "../core/pulls.ts";
1717 import { getRepoById } from "../core/repos.ts";
1818 import { getRun, type Run } from "../core/runs.ts";
19 import { getUserById } from "../core/users.ts";
2019 import { runGit } from "../git/env.ts";
2120 import { repoDir } from "../git/repos.ts";
2221 import { isSafeOid } from "../git/guard.ts";
@@ -113,7 +112,7 @@ export function revertBody(pull: Pick<Pull, "number">, red: RedMain): string {
113112 red.failing[0] !== undefined
114113 ? `the failing test is "${red.failing[0]}"${red.failing.length > 1 ? ` (and ${red.failing.length - 1} more)` : ""}`
115114 : red.summary.replace(/^check failed: /, "");
116 return `Reverts #${pull.number}, the one pull landed since main was last green.\n\nMain is red at ${red.commitOid.slice(0, 7)}: ${what}.\n\nProposed by the forge; a person lands it.`;
115 return `Reverts #${pull.number}, the one pull landed since main was last green.\n\nMain is red at ${red.commitOid.slice(0, 7)}: ${what}.\n\n${LANE_LINE}`;
117116 }
118117
119118 /**
@@ -169,10 +168,9 @@ export async function proposeRevert(app: App, repoId: string): Promise<Pull | un
169168 const repo = getRepoById(app.db, repoId);
170169 // A revert that deletes a migration pin is red before it runs: the alarm's, not a pull's.
171170 if (repo !== undefined && (await pinsLandedBy(app, repo, landed.mergedOid ?? "")).length > 0) return undefined;
172 const owner = repo === undefined ? undefined : getUserById(app.db, repo.ownerId);
173 if (repo === undefined || owner === undefined || getIssueById(app.db, landed.id) === undefined)
174 return undefined;
175 const made = await revertPull(app, owner, repo, landed, revertBody(landed, red));
171 if (repo === undefined || getIssueById(app.db, landed.id) === undefined) return undefined;
172 // The crew's agent opens it, labelled, for the lane (`revert_lane.ts`).
173 const made = await openLaneRevert(app, repo, landed, revertBody(landed, red));
176174 return made.ok ? made.value : undefined;
177175 } finally {
178176 working.delete(repoId);
src/checks/scheduler.ts +7 −2
@@ -6,6 +6,7 @@ import { approvedOnce } from "./approved_first.ts";
66 import { outsideOnce } from "./outside_lane.ts";
77 import { OWN_FIRST_WORDS, ownOnce } from "./own_first.ts";
88 import { redMain, unheld } from "./red_main.ts";
9 import { revertOnce } from "./revert_lane.ts";
910 import { rebasesFirst } from "./finishing_first.ts";
1011 import { inVerifyLane } from "./verify.ts";
1112 import { appendRunLog } from "../runs/log.ts";
@@ -124,11 +125,12 @@ function startable(lane: LaneState, queued: readonly Run[], grants = false): Run
124125 const rankOf = rankOnce(app.db);
125126 const isOutside = outsideOnce(app.db);
126127 const isOwn = ownOnce(app.db);
127 let next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside, isOwn);
128 const isRevert = revertOnce(app.db);
129 let next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside, isOwn, isRevert);
128130 while (next !== undefined && atLimit(lane, next)) {
129131 const held = next;
130132 rest = rest.filter((run) => run !== held);
131 next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside, isOwn);
133 next = pickNext(rest, Date.now(), isApproved, rankOf, isOutside, isOwn, isRevert);
132134 }
133135 // Its log says why it went ahead of the crew's checks.
134136 if (next !== undefined && isOwn(next) && !isApproved(next)) appendRunLog(app.config.dataDir, next.id, `started: ${OWN_FIRST_WORDS}`);
@@ -169,6 +171,9 @@ export function schedule(lane: LaneState): void {
169171 ),
170172 (repoId) => redMain(app.db, repoId),
171173 options.redHoldMs ?? 0,
174 Date.now(),
175 // A revert is the fix for the red: never held by it (`revert_lane.ts`).
176 revertOnce(app.db),
172177 );
173178 // The limit is asked at the point of starting, one pick at a time:
174179 // a started check is in flight before the next is asked about, so a
src/checks/shared_red.ts +12 −3
@@ -98,12 +98,12 @@ const PULLS_PER_TEST = `
9898 AND n.type = 'text' AND instr(n.value, ?4) = 0
9999 GROUP BY run.repo_id, n.value`;
100100
101 function pullsPerTest(db: Database, now: number, repoId: string | null): Row[] {
101 function pullsPerTest(db: Database, now: number, repoId: string | null, windowMs: number = SHARED_WINDOW_MS): Row[] {
102102 return db
103103 .query<Row, [string, string, string | null, string]>(PULLS_PER_TEST)
104104 .all(
105 idFloor(now - SHARED_WINDOW_MS - QUEUED_SLACK_MS),
106 new Date(now - SHARED_WINDOW_MS).toISOString(),
105 idFloor(now - windowMs - QUEUED_SLACK_MS),
106 new Date(now - windowMs).toISOString(),
107107 repoId,
108108 NO_TEST_NAME,
109109 )
@@ -129,6 +129,15 @@ export function sharedWithPulls(
129129 return names.every((n) => shared.has(n));
130130 }
131131
132 /**
133 * A test {@link SHARED_PULLS} or more pulls of one repository failed within `windowMs`, whoever's
134 * it turns out to be: the revert lane's third trigger (\`shared_verify.ts\`) asks main to settle it.
135 * Not filtered by main's newest check: a culprit that landed after it is what this looks for.
136 */
137 export function sharedRecently(db: Database, repoId: string, windowMs: number, now: number = Date.now()): string | undefined {
138 return pullsPerTest(db, now, repoId, windowMs).find((r) => r.pulls >= SHARED_PULLS)?.test;
139 }
140
132141 /** Every shared test across the forge's repositories, oldest first: one query. */
133142 export function sharedTests(db: Database, now: number = Date.now()): SharedTest[] {
134143 return lanes(db, pullsPerTest(db, now, null), now)
src/checks/shared_verify.ts added +33
@@ -0,0 +1,33 @@
1 /**
2 * The revert lane's third trigger (`revert_lane.ts`): three different pulls' checks failing the
3 * same test within half an hour, while main's own newest check is not red, say main is probably
4 * red with no landing yet named. Main is asked for a verification now rather than on its
5 * schedule; a red one is bisected to its culprit (`culprit.ts`), whose revert the lane opens.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { redMain } from "./red_main.ts";
10 import { sharedRecently } from "./shared_red.ts";
11 import { verifyDue, VERIFY_ENV } from "./verify.ts";
12
13 /** Within how long the pulls' reds must fall. */
14 export const SHARED_VERIFY_MS = 30 * 60_000;
15
16 /**
17 * The test to verify main for, if one: shared within {@link SHARED_VERIFY_MS}, main's newest check
18 * not already red (its own red has its own way back), and no verification of `tip` running or
19 * asked within the window.
20 */
21 export function verifyForSharedRed(db: Database, repoId: string, tip: string, now: number = Date.now()): string | undefined {
22 const test = sharedRecently(db, repoId, SHARED_VERIFY_MS, now);
23 if (test === undefined || redMain(db, repoId) !== undefined) return undefined;
24 const last = db
25 .query<{ commit_oid: string; created_at: string }, [string, string]>(
26 "SELECT commit_oid, created_at FROM run WHERE repo_id = ?1 AND kind = 'check' AND env = ?2 ORDER BY id DESC LIMIT 1",
27 )
28 .get(repoId, VERIFY_ENV);
29 const active =
30 db.query("SELECT 1 FROM run WHERE repo_id = ?1 AND kind = 'check' AND env = ?2 AND state IN ('queued', 'running') LIMIT 1").get(repoId, VERIFY_ENV) !== null;
31 const due = verifyDue({ tip, last: last === null ? undefined : { commitOid: last.commit_oid, createdAt: last.created_at }, active, now, everyMs: SHARED_VERIFY_MS });
32 return due ? test : undefined;
33 }
src/crew/brief.ts +8
@@ -353,6 +353,8 @@ export interface TaskInput extends BriefInput {
353353 * diff (#9034).
354354 */
355355 readonly sourceNote?: readonly string[] | undefined;
356 /** For `review` of a lane revert git verified as pure (`checks/revert_lane.ts`): the pull it reverts. */
357 readonly pureRevert?: number | undefined;
356358 /**
357359 * For `review` of a sealed pull: the ref its head was fetched to in the clone, from its sealed
358360 * fork (#14917).
@@ -693,6 +695,12 @@ function taskBody(input: TaskInput): string {
693695 `"comments" is optional. Each anchors to a line of the diff below: "path" is the file, "side" is "new" for an added or kept line (numbered as in the head) or "old" for a removed one (numbered as in the base), and "line" counts from the hunk header — in \`@@ -a,b +c,d @@\` the hunk's first line is c on the new side. If the API answers \`bad_anchor\`, nothing was posted: read its message, fix the anchors, and send the review once more; if it is refused again, send it without "comments" and put those points in the body.`,
694696 `Approve when it does what the direction asks, works in the preview, and looks right. Otherwise use "changes_requested" with a body a builder can act on: what does not work, and the one thing to fix first, concrete. You get ${REVIEW_ROUNDS} rounds of changes on a pull; after that it lands as it is, so if something is left, open an issue for it with the API instead. One review, then stop; your last message is not read by anyone.`,
695697 "",
698 ...(input.pureRevert === undefined
699 ? []
700 : [
701 `This pull is a pure revert of #${input.pureRevert}, verified by git: its diff is #${input.pureRevert}'s landed change reversed, line for line. The forge's revert lane opened it because main is red after #${input.pureRevert} landed. Keep the review short: confirm it takes back #${input.pureRevert} and nothing else, and approve. Ask for no other change here; anything else is a new issue.`,
702 "",
703 ]),
696704 input.landedAs === undefined
697705 ? "The change:"
698706 : `The change, as it landed: commit ${input.landedAs} on the base against its first parent. This pull is merged already, so judge what landed; your verdict carries the box pass.`,
src/crew/land_admit.ts +22 −1
@@ -1,6 +1,9 @@
11 /** Everything a green pull must be before it joins the merge queue. */
22
3 import { addComment } from "../actions/issues.ts";
3 import { addComment, setIssueState } from "../actions/issues.ts";
4 import { deleteBranch } from "../actions/branches.ts";
5 import { isLaneRevert, laneGuard } from "../checks/revert_lane.ts";
6 import { FORGE_CLOSED } from "../checks/revert_red.ts";
47 import { mergePull } from "../actions/pulls.ts";
58 import type { App } from "../app.ts";
69 import { noteRed, treatRed } from "../checks/doctor.ts";
@@ -201,6 +204,22 @@ export async function admit(
201204 // review lapsed.
202205 const review = await reviewed(app, repo, pull, now);
203206 if (review === "hold") return err("review");
207 // A lane revert lands only while the red it answers stands (`checks/revert_lane.ts`): main green
208 // again, or its culprit gone, closes it; a fix by the culprit's author goes first.
209 const lane = isLaneRevert(app.db, pull);
210 if (lane) {
211 const verdict = await laneGuard(app, repo, pull);
212 if (!verdict.go) {
213 if (verdict.close) {
214 const issue = getIssueById(app.db, pull.id);
215 if (issue !== undefined) {
216 addComment(app, by, repo, issue, `${FORGE_CLOSED}revert lane did not land this: ${verdict.why}. (The forge posts this; nobody wrote it by hand.)`);
217 if (setIssueState(app, by, repo, issue, "closed").ok) await deleteBranch(app, by, repo, pull.headBranch);
218 }
219 }
220 return err("answered");
221 }
222 }
204223 // The full tier, once, on the queue's candidate (#1198, #2036). Red is
205224 // told to the pull once per head and base, and the pull is out of the
206225 // queue until a push — a base that moved is no new try, or a pull red on
@@ -218,6 +237,8 @@ export async function admit(
218237 return ok({
219238 pull,
220239 dir,
240 // A lane revert gates alone and first in the line (`checks/queue.ts`).
241 ...(lane ? { alone: true } : {}),
221242 land: (expect) => landGated(app, repo, by, pull, review, expect),
222243 // On the forge's own code, the landed tree is checked out and
223244 // preflighted off to the side; the landing does not wait on it
src/crew/review.ts +10 −2
@@ -37,6 +37,7 @@ import { crewFilters, isStrangerPull } from "./stranger.ts";
3737 import { queueAgentRun } from "./dispatch.ts";
3838 import { type Handover, handoverOf, handoversOf } from "./guard.ts";
3939 import { crewDownNow, crewDownStretches, diedBeforeAgent, liveMs, type Stretch } from "./review_pause.ts";
40 import { isLaneRevert } from "../checks/revert_lane.ts";
4041
4142 const log = createLog("crew");
4243
@@ -713,9 +714,13 @@ async function queueReview(
713714 // A person's ask may name the reviewer (#4568).
714715 const ask = getReviewRequest(app.db, pull.id);
715716 const named = ask?.reviewerId == null ? undefined : pool.find((r) => r.user.id === ask.reviewerId);
717 // A lane revert (`checks/revert_lane.ts`) goes to the least busy reviewer whatever it touches:
718 // it takes a change back, so it needs no security or design eye, only a quick one.
716719 const reviewer =
717720 named ??
718 pickReviewer(pool, diff.files.map((f) => f.path), getTeam(app.db, "design")?.members, reviewLoad(app.db));
721 (isLaneRevert(app.db, pull)
722 ? pickReviewer(pool, [], [], reviewLoad(app.db))
723 : pickReviewer(pool, diff.files.map((f) => f.path), getTeam(app.db, "design")?.members, reviewLoad(app.db)));
719724 if (reviewer === undefined) return undefined;
720725 return queueAgentRun(app, repo, issue, reviewer, "review") === undefined ? undefined : reviewer;
721726 }
@@ -909,7 +914,10 @@ export async function sweepReviews(app: App, now = new Date()): Promise<number>
909914 for (const id of repoIds) {
910915 const repo = getRepoById(app.db, id);
911916 if (!repo) continue;
912 for (const pull of openPullsOldestFirst(app.db, repo.id)) {
917 // A lane revert is the fix for a red main: sent before every other pull (`checks/revert_lane.ts`).
918 const open = openPullsOldestFirst(app.db, repo.id);
919 const reverts = open.filter((p) => isLaneRevert(app.db, p));
920 for (const pull of reverts.length === 0 ? open : [...reverts, ...open.filter((p) => !reverts.includes(p))]) {
913921 if (queued >= SWEEP_SENDS) return forgetSettled(stalled, queued, resent);
914922 // An agent's green pull, or a stranger's the crew filters (#9575).
915923 const owed =
src/crew/run_prompt.ts +2
@@ -35,6 +35,7 @@ import { reviewRange } from "./review_range.ts";
3535 import { touchesDesign } from "./review.ts";
3636 import { SEALED_REMOTE } from "./sealed_head.ts";
3737 import { reviewSourceNote } from "./source_held.ts";
38 import { pureRevertOf } from "../checks/revert_lane.ts";
3839 import { isStrangerPull } from "./stranger.ts";
3940 import { owed } from "./team_share.ts";
4041 import { handedTooLarge } from "./too_large.ts";
@@ -139,6 +140,7 @@ export async function promptFor(s: PromptState): Promise<string> {
139140 // A sealed pull's head is in its builder's sealed fork, not the base (#14917).
140141 ...(await reviewInputs(app, repo, pull, record, await pullDir(app.db, app.reposRoot, repo, pull), signal)),
141142 sourceNote: await reviewSourceNote(app, repo, pull, bare),
143 pureRevert: await pureRevertOf(app, repo, pull),
142144 ...(sealedHead === undefined ? {} : { sealedRef: `${SEALED_REMOTE}/${pull.headBranch}` }),
143145 boxes: boxesOf(app, repo, pull),
144146 retry:
src/crew/waits.ts +3 −1
@@ -21,7 +21,9 @@ export type Wait =
2121 | "carried"
2222 | "wall"
2323 | "review"
24 | "red";
24 | "red"
25 /** A lane revert whose red is answered: main went green, its culprit is gone, or a fix goes first. */
26 | "answered";
2527
2628 /** How many approved pulls waited on each reason. */
2729 export type Waits = Partial<Record<Wait, number>>;
src/flow/alarm_red_main.ts +7 −1
@@ -6,6 +6,7 @@
66
77 import type { Database } from "bun:sqlite";
88 import { redMain } from "../checks/red_main.ts";
9 import { laneRevertOpen } from "../checks/revert_lane.ts";
910 import { getRepo } from "../core/repos.ts";
1011 import { ownRepoPath } from "../kernel/own_repo.ts";
1112
@@ -17,6 +18,8 @@ export interface RedMainAlarm {
1718 /** When the current red streak began, while main is red. */
1819 readonly since?: string;
1920 readonly says: string;
21 /** The revert lane's open revert (`checks/revert_lane.ts`): where Stop holds it. */
22 readonly stop?: string;
2023 }
2124
2225 /** The first failure after main's last green check: when the streak began. */
@@ -47,9 +50,12 @@ export function redMainAlarm(db: Database, now: Date): RedMainAlarm {
4750 return { fired: false, since, says: `Main went red ${Math.max(minutes, 0)} min ago.` };
4851 }
4952 const what = red.failing[0] ?? red.summary.replace(/\s+/g, " ").trim().slice(0, 120);
53 // The revert lane at work: which landing it takes back, with which pull, and where Stop holds it.
54 const lane = laneRevertOpen(db, repo.id);
5055 return {
5156 fired: true,
5257 since,
53 says: `Main has been red for ${minutes} min${what ? `: ${what}` : ""}.`,
58 says: `Main has been red for ${minutes} min${what ? `: ${what}` : ""}.${lane === undefined ? "" : ` Reverting #${lane.culprit} with #${lane.revert}; Stop holds it.`}`,
59 ...(lane === undefined ? {} : { stop: `/${repo.ownerName}/${repo.name}/pulls/${lane.revert}?more=1#hold` }),
5460 };
5561 }
src/flow/alarms.ts +1 −1
@@ -69,7 +69,7 @@ export function firedAlarms(
6969 const stopped = own && !opts.publicOnly ? landingStopped(db, own.id) : undefined;
7070 if (stopped) out.push({ key: "landing_stopped", says: stoppedSentence(stopped), since: stopped.since, href: "/boards" });
7171 const red = redMainAlarm(db, now);
72 if (red.fired) out.push({ key: "red_main", says: red.says, since: red.since!, href: redMainHref(db) });
72 if (red.fired) out.push(red.stop === undefined ? { key: "red_main", says: red.says, since: red.since!, href: redMainHref(db) } : { key: "red_main", says: red.says, since: red.since!, href: red.stop, action: "Stop" });
7373 const stuck = alarmStuck(db, now, opts.publicOnly ? { publicOnly: true } : {});
7474 if (stuck.fired) {
7575 out.push({ key: "stuck", says: stuck.says, since: stuck.since!, href: stuck.action!.path, action: stuck.action!.label });
src/flow/lanes_read.ts +2 −1
@@ -27,6 +27,7 @@ import { outsideOnce } from "../checks/outside_lane.ts";
2727 import { ownOnce } from "../checks/own_first.ts";
2828 import { pickOrder } from "../checks/pick.ts";
2929 import { rankOnce } from "../checks/ranked_first.ts";
30 import { revertOnce } from "../checks/revert_lane.ts";
3031 import { weekShare } from "../crew/week_read.ts";
3132 import { FORGE_BROKEN, firedAlarms } from "./alarms.ts";
3233 import { readBuilders, readKpis } from "./kpis.ts";
@@ -292,7 +293,7 @@ function runRows(
292293 */
293294 function checkOrder(db: Database, now: string): string[] {
294295 const queued = listActive(db, "check").filter((r) => r.state === "queued" && (r.notBefore === null || r.notBefore <= now));
295 return pickOrder(queued, Date.parse(now), approvedOnce(db), rankOnce(db), outsideOnce(db), ownOnce(db)).map((r) => r.id);
296 return pickOrder(queued, Date.parse(now), approvedOnce(db), rankOnce(db), outsideOnce(db), ownOnce(db), revertOnce(db)).map((r) => r.id);
296297 }
297298
298299 /** Approved pulls waiting for a person, oldest approval first. */
test/merge-queue-revert-alone.test.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * A lane revert (`checks/revert_lane.ts`, `Queued.alone`) gates alone and first in the merge
3 * queue's line: it joins no batch, and the line's other pulls batch as before behind it.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { type Candidate, enqueue, type Expect, type Queued } from "../src/checks/queue.ts";
10 import type { LandVerdict } from "../src/checks/tiers.ts";
11 import type { Pull } from "../src/core/pulls.ts";
12
13 let dir: string;
14 const git = (...args: string[]) => Bun.spawnSync(["git", "-C", dir, "-c", "user.name=t", "-c", "user.email=t@t", ...args]).stdout.toString().trim();
15
16 beforeAll(async () => {
17 dir = await mkdtemp(join(tmpdir(), "forge-merge-queue-alone-"));
18 Bun.spawnSync(["git", "init", "-q", "-b", "main", dir]);
19 git("commit", "-q", "--allow-empty", "-m", "start");
20 });
21
22 afterAll(async () => {
23 await rm(dir, { recursive: true, force: true });
24 });
25
26 async function headAdding(branch: string, file: string): Promise<string> {
27 git("checkout", "-q", "-B", branch, "main");
28 git("reset", "-q", "--hard", "main");
29 await Bun.write(join(dir, file), `${file}\n`);
30 git("add", file);
31 git("commit", "-q", "-m", file);
32 git("checkout", "-q", "--detach");
33 return git("rev-parse", branch);
34 }
35
36 function entry(number: number, headOid: string, alone = false): Queued {
37 return {
38 pull: { id: `p-${number}`, number, baseBranch: "main", headOid } as Pull,
39 dir,
40 land: async (expect: Expect) => {
41 if (git("rev-parse", "refs/heads/main") !== expect.baseOid) return undefined;
42 const tip = git("commit-tree", expect.treeOid, "-p", expect.baseOid, "-m", `#${number}`);
43 git("update-ref", "refs/heads/main", tip);
44 return tip;
45 },
46 release: () => {},
47 handBack: () => {},
48 ...(alone ? { alone: true } : {}),
49 };
50 }
51
52 test("the revert gates alone and first, though it joined the line last; the rest batch behind it", async () => {
53 const seen: number[][] = [];
54 const gate = async (candidate: Candidate): Promise<LandVerdict> => {
55 seen.push(candidate.steps.map((s) => s.entry.pull.number));
56 return { lands: true };
57 };
58 const line = [];
59 for (let n = 1; n <= 4; n++) line.push(entry(n, await headAdding(`p${n}`, `p${n}.txt`)));
60 line.push(entry(99, await headAdding("revert", "revert.txt"), true));
61 expect(await enqueue("revert-alone", line, gate, { depth: 1, batch: 8 })).toEqual([true, true, true, true, true]);
62 expect(seen[0]).toEqual([99]);
63 expect(seen.slice(1).flat().sort((a, b) => a - b)).toEqual([1, 2, 3, 4]);
64 expect(seen.slice(1).every((c) => !c.includes(99))).toBe(true);
65 });
test/revert-lane.test.ts added +212
@@ -0,0 +1,212 @@
1 /**
2 * The revert-first lane (`checks/revert_lane.ts`): a red main's revert is opened by the crew's
3 * agent, labelled `revert-red`, naming the culprit and the failing test; its check goes before
4 * every other and is never held by the red it answers; it lands like any crew pull once its own
5 * check is green and it is approved, unless the red is answered (main green, culprit gone, a fix
6 * by the culprit's author landed or waiting green). The Bridge's red-main line names it with Stop.
7 */
8 import { afterEach, beforeEach, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { addToCrew, createAgent } from "../src/actions/crew.ts";
14 import { mergePull, openPull } from "../src/actions/pulls.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { pickNext } from "../src/checks/pick.ts";
17 import { unheld, type RedMain } from "../src/checks/red_main.ts";
18 import { proposeRevert } from "../src/checks/revert_red.ts";
19 import { isLaneRevert, laneGuard, laneRevertOpen, REVERT_LABEL, revertOnce } from "../src/checks/revert_lane.ts";
20 import { labelsFor } from "../src/core/issues.ts";
21 import { getPull, type Pull } from "../src/core/pulls.ts";
22 import { getRepoById, type Repo } from "../src/core/repos.ts";
23 import { createRun, type Run } from "../src/core/runs.ts";
24 import { createUser, getUserById, type User } from "../src/core/users.ts";
25 import { resolveOid } from "../src/git/merge.ts";
26 import { repoDir } from "../src/git/repos.ts";
27
28 let dataDir: string, app: App, alice: User, bob: User, repo: Repo, builder: User;
29
30 /** A pull opened as Alice and said to be `who`'s (its author is what the guard reads). */
31 const open = async (who: User, branch: string, content: string) => {
32 await commitToBranch(app, alice, repo, { branch, base: "main", message: branch, files: [{ path: `${branch}.txt`, content }] });
33 const opened = await openPull(app, alice, repo, { title: `Change ${branch}`, baseBranch: "main", headBranch: branch });
34 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
35 app.db.query("UPDATE issue SET author_id = ?2 WHERE id = ?1").run(opened.value.id, who.id);
36 return getPull(app.db, repo.id, opened.value.number)!;
37 };
38
39 const land = async (who: User, branch: string, content: string): Promise<Pull> => {
40 const opened = { value: await open(who, branch, content) };
41 const merged = await mergePull(app, alice, repo, opened.value, "squash");
42 if (!merged.ok) throw new Error(JSON.stringify(merged.error));
43 return getPull(app.db, repo.id, opened.value.number)!;
44 };
45
46 const mainCheck = async (state: "ok" | "failed", names: string[] = []): Promise<void> => {
47 const oid = await resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), "refs/heads/main");
48 const run = createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: oid ?? "" });
49 app.db
50 .query("UPDATE run SET state = ?2, summary = ?3, check_detail = ?4, finished_at = ?5 WHERE id = ?1")
51 .run(run.id, state, state === "ok" ? "check passed in 1s" : "check failed: 1 test failed", state === "ok" ? "" : JSON.stringify({ names }), new Date().toISOString());
52 };
53
54 /** Main went green, then `landed` landed, then two reds on the same test: the lane's revert. */
55 async function laneRevert(): Promise<{ culprit: Pull; revert: Pull }> {
56 await mainCheck("ok");
57 const culprit = await land(bob, "one", "beta\n");
58 await mainCheck("failed", ["parses the thing"]);
59 await mainCheck("failed", ["parses the thing"]);
60 const revert = await proposeRevert(app, repo.id);
61 if (revert === undefined) throw new Error("no revert");
62 return { culprit, revert };
63 }
64
65 beforeEach(async () => {
66 dataDir = await mkdtemp(join(tmpdir(), "forge-revert-lane-"));
67 app = createApp({ dataDir, port: 0 });
68 const mk = async (username: string, first = false) => {
69 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
70 if (!u.ok) throw new Error(u.error);
71 return u.value;
72 };
73 alice = await mk("alice", true);
74 bob = await mk("bob");
75 const made = await createRepo(app, alice, { name: "app", visibility: "public" });
76 if (!made.ok) throw new Error(String(made.error));
77 repo = made.value;
78 await commitToBranch(app, alice, repo, { branch: "main", message: "base", files: [{ path: "code.txt", content: "alpha\n" }] });
79 const agent = await createAgent(app, alice, { username: "builderbot" });
80 if (!agent.ok) throw new Error(String(agent.error));
81 builder = agent.value.user;
82 expect(addToCrew(app, alice, repo, "builderbot").ok).toBe(true);
83 });
84
85 afterEach(async () => {
86 app.close();
87 await rm(dataDir, { recursive: true, force: true });
88 });
89
90 test("the crew's agent opens the revert, labelled, naming the culprit and the failing test", async () => {
91 const { culprit, revert } = await laneRevert();
92 expect(revert.authorId).toBe(builder.id);
93 expect(getUserById(app.db, revert.authorId)?.kind).toBe("agent");
94 expect(labelsFor(app.db, revert.id).map((l) => l.name)).toContain(REVERT_LABEL);
95 expect(revert.body).toContain(`Reverts #${culprit.number}`);
96 expect(revert.body).toContain("parses the thing");
97 expect(revert.body).toContain("lands on its own once its own check is green and it is approved, unless a fix lands first");
98 expect(isLaneRevert(app.db, revert)).toBe(true);
99 expect(laneRevertOpen(app.db, repo.id)).toEqual({ culprit: culprit.number, revert: revert.number });
100 });
101
102 test("its check goes before every other, and the red it answers never holds it", async () => {
103 const { revert } = await laneRevert();
104 const other = await land(alice, "two", "gamma\n");
105 const at = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString();
106 const check = (issueId: string, minutes: number): Run => ({ ...createRun(app.db, { repoId: repo.id, kind: "check", env: "pull", issueId }), createdAt: at(minutes) });
107 const crew = check(other.id, 30);
108 const fix = check(revert.id, 0);
109 const isRevert = revertOnce(app.db);
110 // Ahead of a check that has waited past every cap, and of an approved one.
111 expect(pickNext([crew, fix], Date.now(), () => true, undefined, undefined, undefined, isRevert)?.id).toBe(fix.id);
112 // A red main holds every pull check but the revert's.
113 const red = { repoId: repo.id, limit: false } as RedMain;
114 const left = unheld([crew, fix], () => red, 60 * 60_000, Date.now(), isRevert);
115 expect(left.map((r) => r.id)).toEqual([fix.id]);
116 });
117
118 test("the guard: it goes while the red stands; main green again closes it; a fix by the culprit's author goes first", async () => {
119 const { culprit, revert } = await laneRevert();
120 expect(await laneGuard(app, repo, revert)).toEqual({ go: true });
121 // Bob opens a fix whose check is green: the fix goes first.
122 const fix = { value: await open(bob, "fix", "fixed\n") };
123 const run = createRun(app.db, { repoId: repo.id, kind: "check", env: `pull-${fix.value.number}`, issueId: fix.value.id, commitOid: fix.value.headOid });
124 app.db.query("UPDATE run SET state = 'ok', finished_at = ?2 WHERE id = ?1").run(run.id, new Date().toISOString());
125 const waits = await laneGuard(app, repo, revert);
126 expect(waits.go).toBe(false);
127 if (!waits.go) {
128 expect(waits.close).toBe(false);
129 expect(waits.why).toContain(`#${fix.value.number}, a fix by #${culprit.number}'s author, is open and green`);
130 }
131 // Main goes green: the red is answered, and the revert closes.
132 await mainCheck("ok");
133 const answered = await laneGuard(app, repo, revert);
134 expect(answered).toEqual({ go: false, close: true, why: `main is green again with #${culprit.number} in it` });
135 });
136
137 test("a revert opened by hand is no lane revert: no label, no Bridge line", async () => {
138 await mainCheck("ok");
139 const landed = await land(bob, "solo", "delta\n");
140 const { revertPull } = await import("../src/actions/revert.ts");
141 const made = await revertPull(app, alice, repo, landed);
142 expect(made.ok).toBe(true);
143 if (made.ok) expect(isLaneRevert(app.db, made.value)).toBe(false);
144 expect(laneRevertOpen(app.db, repo.id)).toBeUndefined();
145 // An agent through a door is still refused: only the lane opens one as the crew.
146 const refused = await revertPull(app, builder, repo, landed);
147 expect(refused.ok).toBe(false);
148 });
149
150 test("the Bridge's red-main line names the culprit and the revert, with Stop on its hold", async () => {
151 const { culprit, revert } = await laneRevert();
152 const was = process.env.FORGE_SENTINEL_REPO;
153 process.env.FORGE_SENTINEL_REPO = "alice/app";
154 try {
155 // The red streak began twenty minutes ago: past the alarm's ten.
156 app.db.query("UPDATE run SET finished_at = ?2, created_at = ?2 WHERE repo_id = ?1 AND env = 'main' AND state = 'failed'").run(repo.id, new Date(Date.now() - 20 * 60_000).toISOString());
157 const { redMainAlarm } = await import("../src/flow/alarm_red_main.ts");
158 const alarm = redMainAlarm(app.db, new Date());
159 expect(alarm.fired).toBe(true);
160 expect(alarm.says).toContain(`Reverting #${culprit.number} with #${revert.number}; Stop holds it.`);
161 expect(alarm.stop).toBe(`/alice/app/pulls/${revert.number}?more=1#hold`);
162 } finally {
163 if (was === undefined) delete process.env.FORGE_SENTINEL_REPO;
164 else process.env.FORGE_SENTINEL_REPO = was;
165 }
166 });
167
168 test("landing asks the guard: with main green again, the approved green revert is closed, not landed", async () => {
169 const { culprit, revert } = await laneRevert();
170 app.db.query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1").run(repo.id, alice.id);
171 const fresh = getPull(app.db, repo.id, revert.number)!;
172 const check = createRun(app.db, { repoId: repo.id, kind: "check", env: `pull-${fresh.number}`, issueId: fresh.id, commitOid: fresh.headOid });
173 app.db.query("UPDATE run SET state = 'ok', finished_at = ?2 WHERE id = ?1").run(check.id, new Date().toISOString());
174 const { submitReview } = await import("../src/core/reviews.ts");
175 const approved = submitReview(app.db, { issueId: fresh.id, authorId: alice.id, state: "approved", commitOid: fresh.headOid });
176 expect(approved.ok).toBe(true);
177 await mainCheck("ok");
178 const { admit } = await import("../src/crew/land_admit.ts");
179 const said = await admit(app, getRepoById(app.db, repo.id)!, getPull(app.db, repo.id, revert.number)!);
180 expect(said.ok ? "admitted" : said.error).toBe("answered");
181 const after = getPull(app.db, repo.id, revert.number)!;
182 expect(after.state).toBe("closed");
183 expect(after.mergedAt).toBeNull();
184 const { listComments } = await import("../src/core/issues.ts");
185 expect(listComments(app.db, after.id).at(-1)?.body).toContain(`main is green again with #${culprit.number} in it`);
186 });
187
188 test("git verifies the lane's revert as pure, and the reviewer's brief says so; an extra change is not pure", async () => {
189 const { culprit, revert } = await laneRevert();
190 const { pureRevertOf } = await import("../src/checks/revert_lane.ts");
191 expect(await pureRevertOf(app, repo, getPull(app.db, repo.id, revert.number)!)).toBe(culprit.number);
192 const { taskPrompt } = await import("../src/crew/brief.ts");
193 type Input = Parameters<typeof taskPrompt>[0];
194 const brief = taskPrompt({
195 agent: { user: { username: "bot", displayName: "" }, brief: "" },
196 repo: { ownerName: "alice", name: "app", defaultBranch: "main", autonomyDirection: "" },
197 issue: { number: revert.number, title: "t", body: "b", authorName: "builderbot" },
198 comments: [],
199 reviews: [],
200 branch: "x",
201 forgeUrl: "http://forge.test",
202 reason: "review",
203 reviewDiff: "",
204 pureRevert: culprit.number,
205 } as unknown as Input);
206 expect(brief).toContain(`This pull is a pure revert of #${culprit.number}, verified by git`);
207 // One more change on the revert's branch: no longer pure.
208 await commitToBranch(app, alice, repo, { branch: revert.headBranch, message: "more", files: [{ path: "extra.txt", content: "x\n" }] });
209 expect(await pureRevertOf(app, repo, getPull(app.db, repo.id, revert.number)!)).toBeUndefined();
210 // A pull outside the lane never is.
211 expect(await pureRevertOf(app, repo, culprit)).toBeUndefined();
212 });
test/shared-verify.test.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * The revert lane's third trigger (`checks/shared_verify.ts`): three different pulls failing one
3 * test within half an hour ask main for a verification, unless main's own check is already red,
4 * a verification of the tip was asked within the window, or the reds are fewer or older.
5 */
6 import { afterEach, beforeEach, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { verifyForSharedRed } from "../src/checks/shared_verify.ts";
12 import { VERIFY_ENV } from "../src/checks/verify.ts";
13 import { createIssue } from "../src/core/issues.ts";
14 import { createRepo, type Repo } from "../src/core/repos.ts";
15 import { createRun } from "../src/core/runs.ts";
16 import { createUser } from "../src/core/users.ts";
17
18 let dataDir: string, app: App, repo: Repo, authorId: string;
19
20 beforeEach(async () => {
21 dataDir = await mkdtemp(join(tmpdir(), "forge-shared-verify-"));
22 app = createApp({ dataDir, port: 0 });
23 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
24 if (!u.ok) throw new Error(u.error);
25 authorId = u.value.id;
26 const made = await createRepo(app.db, app.reposRoot, { ownerId: authorId, name: "app", visibility: "public", description: "" });
27 if (!made.ok) throw new Error(String(made.error));
28 repo = made.value;
29 });
30
31 afterEach(async () => {
32 app.close();
33 await rm(dataDir, { recursive: true, force: true });
34 });
35
36 const finish = (runId: string, state: "ok" | "failed", names: string[], minutesAgo: number) =>
37 app.db
38 .query("UPDATE run SET state = ?2, check_detail = ?3, finished_at = ?4 WHERE id = ?1")
39 .run(runId, state, state === "ok" ? "" : JSON.stringify({ names }), new Date(Date.now() - minutesAgo * 60_000).toISOString());
40
41 /** A failed check of a new pull on `name`, `minutesAgo` minutes ago. */
42 function pullRed(name: string, minutesAgo: number): void {
43 const issue = createIssue(app.db, { repoId: repo.id, authorId, title: `pull ${name} ${minutesAgo}`, body: "" });
44 if (!issue.ok) throw new Error(String(issue.error));
45 finish(createRun(app.db, { repoId: repo.id, kind: "check", env: "pull", issueId: issue.value.id }).id, "failed", [name], minutesAgo);
46 }
47
48 const mainRun = (state: "ok" | "failed", names: string[] = []) =>
49 finish(createRun(app.db, { repoId: repo.id, kind: "check", env: "main", commitOid: "a1" }).id, state, names, 1);
50
51 test("three pulls on one test within half an hour ask main for a verification of its tip", () => {
52 mainRun("ok");
53 pullRed("parses the thing", 25);
54 pullRed("parses the thing", 10);
55 expect(verifyForSharedRed(app.db, repo.id, "tip1")).toBeUndefined();
56 pullRed("parses the thing", 1);
57 expect(verifyForSharedRed(app.db, repo.id, "tip1")).toBe("parses the thing");
58 });
59
60 test("not when the reds are older than the window, or spread over different tests", () => {
61 mainRun("ok");
62 pullRed("parses the thing", 45);
63 pullRed("parses the thing", 2);
64 pullRed("another test", 1);
65 expect(verifyForSharedRed(app.db, repo.id, "tip1")).toBeUndefined();
66 });
67
68 test("not when main's own check is already red, nor twice for one tip", () => {
69 for (const m of [3, 2, 1]) pullRed("parses the thing", m);
70 mainRun("failed", ["parses the thing"]);
71 expect(verifyForSharedRed(app.db, repo.id, "tip1")).toBeUndefined();
72 mainRun("ok");
73 expect(verifyForSharedRed(app.db, repo.id, "tip1")).toBe("parses the thing");
74 createRun(app.db, { repoId: repo.id, kind: "check", env: VERIFY_ENV, commitOid: "tip1" });
75 expect(verifyForSharedRed(app.db, repo.id, "tip1")).toBeUndefined();
76 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs