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

A review run that fails at start records why, in one line on the run #16391

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/16177-a-review-run-that-fails-at-start-records → main 0 commits fork

  • Merged. torque/16177-a-review-run-that-fails-at-start-records was merged into main as 297e485.

Review

Sign in to review this change.
7 files changed +356 −24
docs/features/review-failed-start.md +15 −3
@@ -15,9 +15,10 @@ could not be fetched. Such a run ends with no turn and $0.00.
1515 aborts the run and, if a step of the brief ignores the abort, leaves it behind
1616 after a 5 s grace and ends the run, so a stalled brief no longer holds the run
1717 for 15 min or more past the budget.
18 - A head gets two review runs (`REVIEW_TRIES`, as before). When both ended
19 without the reviewer reading the pull, the pull no longer says "the reviewer
20 did not answer"; it says **review failed to start**. A reviewer that read and
18 - A head gets two review runs (`REVIEW_TRIES`), after up to two the forge
19 itself failed (`FORGE_FAULTS_FORGIVEN`, #16177). When the counted ones also
20 ended without the reviewer reading the pull, the pull no longer says "the
21 reviewer did not answer"; it says **review failed to start**. A reviewer that read and
2122 posted nothing still says "did not answer".
2223
2324 ## Where it appears
@@ -38,3 +39,14 @@ holds the runner to them.
3839 ## A review the shell refused (#16214)
3940
4041 Some reviews ran, read the pull, and were never posted: the reviewer's post command carried the review's words (a heredoc, or a quoted body that mentioned `rm`), and the shell's permission check refused it, so the run ended "reviewed: no verdict was posted" (#15694). The review brief now has the reviewer write its JSON with the Write tool to `review.json` and post it with a fixed `curl … --data-binary @review.json`, so no prose reaches the shell (`test/review-post-file.test.ts`).
42
43 ## The run says why (#16177)
44
45 A review run that failed for the forge's reason says which, on its one line:
46
47 - `budget: a review run, waiting on the head's check before its reviewer started, took 30 min, limit 10`: it overran before its agent began, behind the head's check (#16009's runs, fixed by #16115).
48 - `budget: a review run, before its reviewer started, took …`: it overran in the clone or brief.
49 - `the run failed: <error>`: its launch threw (`RUN_THREW_PREFIX`).
50 - `reviewed: no verdict was posted; the harness refused its Bash call`: the reviewer read the pull and the harness's permission check refused it a tool (#15694's runs, fixed by #16227), read from the result's `permission_denials`.
51
52 Such a run (`forgeFault`) spends none of the head's tries, up to two a head: the reviewer was never heard, so it is asked again, however long ago the head went green. Pinned by `test/review-start-failure.test.ts`.
src/crew/agent_runner.ts +4
@@ -160,6 +160,10 @@ export interface AgentOutcome {
160160 readonly contextTokens: number;
161161 /** The model's context window in tokens, from the result's `modelUsage`; 0 when it named none. */
162162 readonly contextWindow: number;
163 /**
164 * The tools the harness's permission check refused this run, by name; absent or empty for none.
165 */
166 readonly denied?: readonly string[] | undefined;
163167 /** `completed`, `max_budget_reached`, `timeout`, `cancelled`, `error`, `exit <n>`. */
164168 readonly reason: string;
165169 /**
src/crew/claude.ts +21
@@ -183,6 +183,21 @@ export function partialOf(event: unknown, calling: Map<string, string>, onDelta:
183183 }
184184 }
185185
186 /**
187 * The tool names a result's `permission_denials` lists (Claude Code's `{ tool_name, … }` per
188 * refused call), each once; anything else in the field is ignored. A review that ends with no
189 * verdict says which tool the harness refused, so the run carries why (#16177).
190 */
191 export function deniedOf(field: unknown): string[] {
192 if (!Array.isArray(field)) return [];
193 const names = new Set<string>();
194 for (const d of field) {
195 const name = typeof d === "object" && d !== null ? (d as Record<string, unknown>)["tool_name"] : undefined;
196 if (typeof name === "string" && /^[\w.:-]{1,64}$/.test(name)) names.add(name);
197 }
198 return [...names];
199 }
200
186201 /** The tool calls a `user` record answers, each ended once, `ok` unless its result is an error. */
187202 export function answeredOf(message: unknown, calling: Map<string, string>): Delta[] {
188203 const content = recordOf(message)["content"];
@@ -297,6 +312,8 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
297312 let result = "";
298313 let costUsd = 0;
299314 let turns = 0;
315 // The tools the harness's permission check refused, by name, from the result (#16177).
316 let denied: string[] = [];
300317 let tokensIn = 0;
301318 let tokensOut = 0;
302319 let contextTokens = 0;
@@ -442,6 +459,7 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
442459 typeof e["total_cost_usd"] === "number" ? e["total_cost_usd"] : 0;
443460 contextWindow = windowOf(e["modelUsage"]);
444461 turns = typeof e["num_turns"] === "number" ? e["num_turns"] : 0;
462 denied = deniedOf(e["permission_denials"]);
445463 ({ tokensIn, tokensOut } = tokensOf(e["usage"]));
446464 input.onUsage?.({ tokensIn, tokensOut, costUsd });
447465 const terminal = e["terminal_reason"];
@@ -559,6 +577,7 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
559577 tokensOut,
560578 contextTokens,
561579 contextWindow,
580 denied,
562581 reason: why,
563582 };
564583 }
@@ -574,6 +593,7 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
574593 tokensOut,
575594 contextTokens,
576595 contextWindow,
596 denied,
577597 reason: `exit ${code}`,
578598 };
579599 }
@@ -588,6 +608,7 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> {
588608 tokensOut,
589609 contextTokens,
590610 contextWindow,
611 denied,
591612 reason,
592613 };
593614 }
src/crew/review.ts +67 −7
@@ -195,6 +195,8 @@ export interface ReviewAttempt {
195195 * The run ended before its agent took a turn and spent nothing: the reviewer never read the pull.
196196 */
197197 readonly failedToStart?: boolean;
198 /** The run failed for the forge's reason, not the reviewer's (`forgeFault`). */
199 readonly forgeFault?: boolean;
198200 }
199201
200202 /**
@@ -207,10 +209,40 @@ export const NOT_REVIEWED_PREFIX = "not reviewed:";
207209 * it).
208210 */
209211 export const SEALED_FETCH_PREFIX = "fetch of the sealed head failed:";
212 /**
213 * What a run's summary starts with when its launch threw (`runner.ts` writes it, the error after
214 * it).
215 */
216 export const RUN_THREW_PREFIX = "the run failed:";
210217 /**
211218 * The summaries of a run that ended before its agent read anything: written from these constants.
212219 */
213 const START_FAILURES = [BUDGET_PREFIX, NOT_REVIEWED_PREFIX, SEALED_FETCH_PREFIX];
220 const START_FAILURES = [BUDGET_PREFIX, NOT_REVIEWED_PREFIX, SEALED_FETCH_PREFIX, RUN_THREW_PREFIX];
221
222 /** What a review run with no verdict says when the harness refused its reviewer a tool (#16177). */
223 export const HARNESS_REFUSED = "the harness refused";
224
225 /**
226 * The cause line of a review run that ended with no verdict: the tools the harness's permission
227 * check refused, when it refused any, so the run says why (#16177). Names are the runner's
228 * (`deniedOf` keeps them to a word each).
229 */
230 export const noVerdictSummary = (denied: readonly string[] = []): string =>
231 denied.length === 0
232 ? "reviewed: no verdict was posted"
233 : `reviewed: no verdict was posted; ${HARNESS_REFUSED} its ${denied.slice(0, 3).join(", ")} call`;
234
235 /**
236 * What a review run past its time limit was, for its `budget:` line (`budgetSummary`'s `what`):
237 * one that never reached its reviewer says so, and one waiting behind the head's check names
238 * that (#16177). The words go before "took", so `limitInSummary` still reads the limit.
239 */
240 export const overranWhere = (reached: boolean, waitingCheck: boolean): string =>
241 reached
242 ? "a review run"
243 : waitingCheck
244 ? "a review run, waiting on the head's check before its reviewer started,"
245 : "a review run, before its reviewer started,";
214246
215247 /**
216248 * Whether an ended review run never reached the reviewer's reading (#16096): it failed or was
@@ -223,6 +255,18 @@ export const failedAtStart = (state: string, summary: string | null, turns: numb
223255 (state === "failed" || state === "cancelled") &&
224256 START_FAILURES.some((prefix) => (summary ?? "").trim().toLowerCase().startsWith(prefix.toLowerCase()));
225257
258 /**
259 * Whether an ended review run failed for the forge's own reason, not the reviewer's (#16177):
260 * it never reached its reading (`failedAtStart`), or the harness refused the reviewer the call
261 * that posts the verdict. The reviewer was never heard, so the head's tries are not spent on it,
262 * up to `FORGE_FAULTS_FORGIVEN` such runs a head.
263 */
264 export const forgeFault = (state: string, summary: string | null, turns: number): boolean =>
265 failedAtStart(state, summary, turns) || (state === "failed" && (summary ?? "").includes(HARNESS_REFUSED));
266
267 /** The forge's own failures (`forgeFault`) a head is forgiven before they count as tries. */
268 export const FORGE_FAULTS_FORGIVEN = 2;
269
226270 /**
227271 * A head that went green this long after the lapse, with no review yet,
228272 * is still sent once, late; past it, nothing was ever going to send.
@@ -283,7 +327,7 @@ export function reviewAttemptsFor(
283327 pulls: readonly Pull[],
284328 now = new Date(),
285329 ): Map<string, ReviewHistory> {
286 const found: { pull: Pull; since: string; attempts: ReviewAttempt[]; checkMinutes: number }[] = [];
330 const found: { pull: Pull; since: string; attempts: ReviewAttempt[]; forgiven: number; checkMinutes: number }[] = [];
287331 const out = new Map<string, ReviewHistory>();
288332 const CHUNK = 400;
289333 for (let i = 0; i < pulls.length; i += CHUNK) {
@@ -323,6 +367,7 @@ export function reviewAttemptsFor(
323367 active: r.state === "queued" || r.state === "running",
324368 reviewerId: r.actor_id,
325369 failedToStart: failedAtStart(r.state, r.summary, r.turns),
370 forgeFault: forgeFault(r.state, r.summary, r.turns),
326371 };
327372 const list = reviews.get(r.issue_id);
328373 if (list) list.push(attempt);
@@ -358,15 +403,24 @@ export function reviewAttemptsFor(
358403 const restart = starved.reduce((m, f) => (f > m ? f : m));
359404 if (restart > since) since = restart;
360405 }
361 const attempts = (reviews.get(pull.id) ?? []).filter((a) => a.createdAt >= since);
362 found.push({ pull, since, attempts, checkMinutes: Math.round(checkMs / 60_000) });
406 // The forge's own failures are not the reviewer's tries, up to the forgiven few (#16177).
407 let forgiven = 0;
408 const attempts = (reviews.get(pull.id) ?? []).filter((a) => {
409 if (a.createdAt < since) return false;
410 if (a.forgeFault === true && forgiven < FORGE_FAULTS_FORGIVEN) {
411 forgiven++;
412 return false;
413 }
414 return true;
415 });
416 found.push({ pull, since, attempts, forgiven, checkMinutes: Math.round(checkMs / 60_000) });
363417 }
364418 }
365419 if (found.length === 0) return out;
366420 // One read of the crew's outages for the set, from the oldest head's green on.
367421 const at = now.getTime();
368422 const all = crewDownStretches(db, Math.min(...found.map((f) => Date.parse(f.since))), at);
369 for (const { pull, since, attempts, checkMinutes } of found) {
423 for (const { pull, since, attempts, forgiven, checkMinutes } of found) {
370424 const from = Date.parse(since);
371425 const paused = all.filter(([, b]) => b > from);
372426 const first = attempts[0];
@@ -374,7 +428,7 @@ export function reviewAttemptsFor(
374428 first !== undefined && liveMs(from, Date.parse(first.createdAt), paused) >= REVIEW_LAPSE_MS
375429 ? first.createdAt
376430 : undefined;
377 out.set(pull.id, { greenAt: since, attempts, lateAt, checkMinutes, paused });
431 out.set(pull.id, { greenAt: since, attempts, forgiven, lateAt, checkMinutes, paused });
378432 }
379433 return out;
380434 }
@@ -383,6 +437,8 @@ export function reviewAttemptsFor(
383437 export interface ReviewHistory {
384438 readonly greenAt: string;
385439 readonly attempts: ReviewAttempt[];
440 /** The forge's own failures on this head left out of `attempts` (`FORGE_FAULTS_FORGIVEN`). */
441 readonly forgiven?: number;
386442 /** When the first review was sent, if it was sent past the lapse: the lapse clock restarts there. */
387443 readonly lateAt: string | undefined;
388444 /** How long the check took, from queued to green. */
@@ -401,6 +457,9 @@ export function stageOf(
401457 now: Date,
402458 ): "send" | "wait" | "lapsed" | "late" {
403459 const age = liveMs(Date.parse(history.greenAt), now.getTime(), history.paused);
460 // Every run so far was the forge's own failure: the reviewer was never heard, so it is asked
461 // however long the head has been green (#16177). `FORGE_FAULTS_FORGIVEN` bounds how often.
462 if (history.attempts.length === 0 && (history.forgiven ?? 0) > 0) return "send";
404463 if (history.attempts.length === 0 && age >= REVIEW_LAPSE_MS)
405464 return age < REVIEW_LAPSE_MS + LATE_SEND_MS ? "late" : "lapsed";
406465 return reviewStage(history.lateAt ?? history.greenAt, history.attempts, now, history.paused);
@@ -518,7 +577,8 @@ export function reviewWaitsFor(
518577 ? {
519578 // Asked twice and neither run reached its agent: say so, not "did not answer".
520579 why:
521 history.attempts.length >= REVIEW_TRIES && history.attempts.every((a) => a.failedToStart === true)
580 history.attempts.length + (history.forgiven ?? 0) >= REVIEW_TRIES &&
581 history.attempts.every((a) => a.failedToStart === true)
522582 ? "failed to start"
523583 : "lapsed",
524584 since: history.greenAt,
src/crew/runner.ts +19 −5
@@ -125,6 +125,9 @@ import {
125125 import {
126126 CHECK_PENDING_SUMMARY,
127127 NOT_REVIEWED_PREFIX,
128 noVerdictSummary,
129 overranWhere,
130 RUN_THREW_PREFIX,
128131 SEALED_FETCH_PREFIX,
129132 touchesDesign,
130133 waitingOnCheck,
@@ -413,13 +416,18 @@ export function wrapUpReserve(budgetUsd: number): number {
413416 * reviewer passed one since the run began, or stands by one on the head it
414417 * was given (the same verdict sent again is the one already there);
415418 * `failed` when it did neither. A reviewer pushes nothing by design, so
416 * what it pushed never decides it.
419 * what it pushed never decides it. A run the harness refused a tool says
420 * which (#16177): that is the forge's failure, not the reviewer's.
417421 */
418422 export function settleReview(
419423 reviews: readonly Review[],
420424 reviewerId: string,
421425 since: string,
422426 headOid: string,
427 /**
428 * The tools the harness refused the reviewer (`AgentOutcome.denied`): named when no verdict came.
429 */
430 denied: readonly string[] = [],
423431 ): { state: "ok" | "failed"; summary: string } {
424432 const verdict = reviews.findLast(
425433 (r) =>
@@ -427,7 +435,7 @@ export function settleReview(
427435 (r.createdAt >= since || r.commitOid === headOid),
428436 );
429437 return verdict === undefined
430 ? { state: "failed", summary: "reviewed: no verdict was posted" }
438 ? { state: "failed", summary: noVerdictSummary(denied) }
431439 : { state: "ok", summary: `reviewed: ${verdict.state.replace("_", " ")}` };
432440 }
433441
@@ -435,6 +443,8 @@ export function settleReview(
435443 interface Ran {
436444 claimed: boolean;
437445 inHarness: boolean;
446 /** The agent's session was started: a review that ends before this never reached its reviewer. */
447 reached: boolean;
438448 inWrapUp: boolean;
439449 /** Every network hop the run made, for its `hops:` line (#14650). */
440450 hops: Hops;
@@ -451,7 +461,7 @@ export async function executeAgentRun(
451461 options: CrewOptions,
452462 ): Promise<Pause | undefined> {
453463 const watch = new Stopwatch(options.now ?? Date.now);
454 const began = { claimed: false, inHarness: false, inWrapUp: false, hops: new Hops() };
464 const began = { claimed: false, inHarness: false, reached: false, inWrapUp: false, hops: new Hops() };
455465 try {
456466 return await runClaimed(app, run, options, watch, began);
457467 } finally {
@@ -582,7 +592,7 @@ async function runClaimed(
582592 log.error("agent run threw", { run: run.id, error: String(error) });
583593 outcome = {
584594 state: "failed",
585 summary: `the run failed: ${String(error).slice(0, 200)}`,
595 summary: `${RUN_THREW_PREFIX} ${String(error).slice(0, 200)}`,
586596 };
587597 } finally {
588598 clearTimeout(clock);
@@ -599,7 +609,7 @@ async function runClaimed(
599609 meterUsage(app, claimed, outcome, meter, started);
600610 if (overran) {
601611 const summary = budgetSummary(
602 "a review run",
612 overranWhere(began.reached, reviewWaitsOnCheck(app, claimed)),
603613 Date.now() - started,
604614 options.reviewBudgetMs ?? BUDGETS.review,
605615 );
@@ -1794,6 +1804,7 @@ async function work(
17941804 );
17951805 watch.lap("brief");
17961806 ran.inHarness = true;
1807 ran.reached = true;
17971808 const working = budget - reserve;
17981809 if (!reviewing)
17991810 early = watchForPull({
@@ -2005,6 +2016,8 @@ async function work(
20052016 );
20062017 result = {
20072018 ...wrapped,
2019 // A refusal in either turn is one the run met (#16177).
2020 denied: [...new Set([...(result.denied ?? []), ...(wrapped.denied ?? [])])],
20082021 sessionId: wrapped.sessionId || result.sessionId,
20092022 costUsd: result.costUsd + wrapped.costUsd,
20102023 turns: result.turns + wrapped.turns,
@@ -2089,6 +2102,7 @@ async function work(
20892102 agent.user.id,
20902103 began,
20912104 pull.headOid,
2105 result.denied,
20922106 );
20932107 write(settled.summary);
20942108 return {
test/review-failed-start.test.ts +12 −9
@@ -2,7 +2,8 @@
22 * A review run that fails at its start is retried once, then said on the pull (#16096). On
33 * 2026-11-23 review runs spent their whole 10 min budget in the brief, before the agent took a
44 * turn, ending at $0.00; the pulls then read "the reviewer did not answer", as if it had been
5 * asked and read them. A start that failed twice says "review failed to start".
5 * asked and read them. A start that failed is the forge's failure: it is forgiven twice
6 * (#16177), then spends the head's two tries, and says "review failed to start".
67 */
78 import { seatAs } from "./helpers/seat.ts";
89 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
@@ -19,7 +20,7 @@ import { createApp as createAppRecord } from "../src/core/apps.ts";
1920 import { createRun, listRuns } from "../src/core/runs.ts";
2021 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2122 import { markVerified } from "../src/core/verify.ts";
22 import { failedAtStart, sendToReview, waitsForPerson } from "../src/crew/review.ts";
23 import { FORGE_FAULTS_FORGIVEN, failedAtStart, sendToReview, waitsForPerson } from "../src/crew/review.ts";
2324 import { crewNow } from "../src/actions/crew_now.ts";
2425 import { reviewWhy } from "../src/web/studio/asks.ts";
2526 import { NOT_REVIEWED_PREFIX, SEALED_FETCH_PREFIX } from "../src/crew/review.ts";
@@ -141,17 +142,19 @@ describe("a review that fails to start", () => {
141142 .run(run.id, state, summary, turns, new Date().toISOString());
142143 }
143144
144 test("is sent once more, then said on the pull as a start that failed, not as silence", async () => {
145 test("is sent again, then said on the pull as a start that failed, not as silence", async () => {
145146 const pull = await greenPull("fails-at-start");
147 // The forge's own failures are forgiven first (#16177), then the head's two tries are spent.
148 for (let i = 0; i < FORGE_FAULTS_FORGIVEN + 1; i++) {
149 expect(await sendToReview(app, repo, pull)).toBe("sent");
150 expect(waitsForPerson(app.db, repo.id, pull)).toBeUndefined();
151 end(pull, i % 2 === 0 ? "cancelled" : "failed", OVERRAN, 0);
152 }
146153 expect(await sendToReview(app, repo, pull)).toBe("sent");
147 end(pull, "cancelled", OVERRAN, 0);
148 // The first try failed at its start: the retry goes out, to the one reviewer there is.
149 expect(await sendToReview(app, repo, pull)).toBe("sent");
150 expect(waitsForPerson(app.db, repo.id, pull)).toBeUndefined();
151154 end(pull, "failed", OVERRAN, 0);
152 // Two tries are all a head gets: no third run, and the pull says why it waits.
155 // No run past those, and the pull says why it waits.
153156 expect(await sendToReview(app, repo, pull)).toBe("lapsed");
154 expect(reviews(pull)).toHaveLength(2);
157 expect(reviews(pull)).toHaveLength(FORGE_FAULTS_FORGIVEN + 2);
155158 const wait = waitsForPerson(app.db, repo.id, pull);
156159 expect(wait?.why).toBe("failed to start");
157160 expect(reviewSays(wait, false)).toBe("review failed to start");
test/review-start-failure.test.ts added +218
@@ -0,0 +1,218 @@
1 /**
2 * A review run that fails at its start records why, in one line on the run (#16177). On
3 * 2026-11-23 the reviews of #16009 overran their 10 min in the brief, waiting on the head's
4 * check, and #15694's reviewers wrote a verdict the harness then refused to post; each run said
5 * only "budget: … took 30 min" or "no verdict was posted", each spent one of the head's two
6 * tries, and both heads lapsed to a person while the causes were fixed under them (#16115,
7 * #16227). Now the line names the cause, and a run the forge failed spends no try, up to
8 * `FORGE_FAULTS_FORGIVEN` a head.
9 */
10 import { seatAs } from "./helpers/seat.ts";
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createApp, type App } from "../src/app.ts";
16 import { addToCrew, createAgent } from "../src/actions/crew.ts";
17 import { openPull } from "../src/actions/pulls.ts";
18 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
19 import { createApp as createAppRecord } from "../src/core/apps.ts";
20 import { type Pull } from "../src/core/pulls.ts";
21 import { type Repo } from "../src/core/repos.ts";
22 import { createRun, getRun, listRuns } from "../src/core/runs.ts";
23 import { createUser, getUserByName, type User } from "../src/core/users.ts";
24 import { markVerified } from "../src/core/verify.ts";
25 import { deniedOf } from "../src/crew/claude.ts";
26 import {
27 FORGE_FAULTS_FORGIVEN,
28 HARNESS_REFUSED,
29 RUN_THREW_PREFIX,
30 failedAtStart,
31 forgeFault,
32 noVerdictSummary,
33 overranWhere,
34 sendToReview,
35 waitsForPerson,
36 } from "../src/crew/review.ts";
37 import { executeAgentRun, settleReview } from "../src/crew/runner.ts";
38 import { budgetSummary, limitInSummary } from "../src/kernel/budgets.ts";
39
40 const MIN = 60_000;
41
42 describe("the cause line", () => {
43 test("a review past its limit before its reviewer started says so, and where it waited", () => {
44 const waiting = budgetSummary(overranWhere(false, true), 30 * MIN, 10 * MIN);
45 expect(waiting).toBe(
46 "budget: a review run, waiting on the head's check before its reviewer started, took 30 min, limit 10",
47 );
48 expect(budgetSummary(overranWhere(false, false), 30 * MIN, 10 * MIN)).toBe(
49 "budget: a review run, before its reviewer started, took 30 min, limit 10",
50 );
51 // A reviewer that was reading when the clock ran out reads as before.
52 expect(budgetSummary(overranWhere(true, true), 30 * MIN, 10 * MIN)).toBe(
53 "budget: a review run took 30 min, limit 10",
54 );
55 // The limit is still read off the line, and the line is still a start that failed.
56 expect(limitInSummary(waiting)).toBe(10);
57 expect(failedAtStart("cancelled", waiting, 0)).toBe(true);
58 });
59
60 test("a review the harness refused a tool names the tool, and is the forge's failure", () => {
61 const at = "2026-11-24T00:19:00.000Z";
62 const settled = settleReview([], "u1", at, "abc", ["Bash"]);
63 expect(settled).toEqual({ state: "failed", summary: "reviewed: no verdict was posted; the harness refused its Bash call" });
64 expect(settled.summary).toContain(HARNESS_REFUSED);
65 expect(forgeFault(settled.state, settled.summary, 3)).toBe(true);
66 // No refusal: the reviewer read and said nothing, which is its own.
67 const silent = settleReview([], "u1", at, "abc");
68 expect(silent.summary).toBe(noVerdictSummary());
69 expect(forgeFault(silent.state, silent.summary, 3)).toBe(false);
70 });
71
72 test("the result's refusals are read by tool name, once each, and nothing else is", () => {
73 expect(
74 deniedOf([
75 { tool_name: "Bash", tool_use_id: "t1", tool_input: { command: "curl …" } },
76 { tool_name: "Bash", tool_use_id: "t2" },
77 { tool_name: "Write" },
78 { tool_name: "<script>" },
79 "Bash",
80 null,
81 ]),
82 ).toEqual(["Bash", "Write"]);
83 expect(deniedOf(undefined)).toEqual([]);
84 expect(deniedOf({ tool_name: "Bash" })).toEqual([]);
85 });
86 });
87
88 describe("a review launch that throws", () => {
89 let dataDir: string;
90 let app: App;
91 let alice: User;
92 let repo: Repo;
93
94 beforeAll(async () => {
95 dataDir = await mkdtemp(join(tmpdir(), "forge-review-start-failure-"));
96 app = createApp({ dataDir, port: 0 });
97 const a = await createUser(app.db, {
98 origin: "seed",
99 trusted: true,
100 username: "alice",
101 email: "[email protected]",
102 password: "a-good-passphrase",
103 adminIfFirst: true,
104 });
105 if (!a.ok) throw new Error(a.error);
106 alice = a.value;
107 markVerified(app.db, alice.id, new Date().toISOString());
108 const made = await createRepo(app, alice, { name: "engine", visibility: "private" });
109 if (!made.ok) throw new Error(String(made.error));
110 repo = made.value;
111 await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# engine\n" }] });
112 for (const name of ["scout", "juniper"]) {
113 const agent = await createAgent(app, alice, { username: name, brief: `I am ${name}.` });
114 if (!agent.ok) throw new Error(String(agent.error));
115 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
116 }
117 seatAs(app.db, repo.id, getUserByName(app.db, "juniper")!.id, "reviewer");
118 }, 60_000);
119
120 afterAll(async () => {
121 await app.close?.();
122 await rm(dataDir, { recursive: true, force: true });
123 });
124
125 async function greenPull(name: string, greenAgoMs: number): Promise<Pull> {
126 await commitToBranch(app, alice, repo, {
127 branch: `feature/${name}`,
128 base: "main",
129 message: name,
130 files: [{ path: `docs/${name}.md`, content: `${name}\n` }],
131 });
132 const opened = await openPull(app, alice, repo, {
133 title: name,
134 body: "",
135 baseBranch: "main",
136 headBranch: `feature/${name}`,
137 });
138 if (!opened.ok) throw new Error(String(opened.error));
139 const pull = opened.value;
140 createAppRecord(app.db, { repoId: repo.id, slug: "engine", access: "private" });
141 app.db.query("UPDATE issue SET author_id = ?2 WHERE id = ?1").run(pull.id, getUserByName(app.db, "scout")!.id);
142 const check = createRun(app.db, {
143 repoId: repo.id,
144 kind: "check",
145 issueId: pull.id,
146 env: `pull-${pull.number}`,
147 commitOid: pull.headOid,
148 reason: "pull",
149 });
150 const green = new Date(Date.now() - greenAgoMs).toISOString();
151 app.db
152 .query("UPDATE run SET state = 'ok', summary = 'check passed', created_at = ?2, finished_at = ?2 WHERE id = ?1")
153 .run(check.id, green);
154 return { ...pull, authorIsAgent: true };
155 }
156
157 const reviews = (pull: Pull) =>
158 listRuns(app.db, pull.repoId, { issueId: pull.id }).filter((r) => r.reason === "review");
159
160 test("leaves a failed run whose summary names the error, read as a start that failed", async () => {
161 const pull = await greenPull("throws-at-launch", 5 * MIN);
162 expect(await sendToReview(app, repo, pull)).toBe("sent");
163 const queued = reviews(pull).at(0)!;
164 // The forge's disk is gone under the launch: the first read of where repositories live throws.
165 const broken = new Proxy(app, {
166 get(target, key, receiver) {
167 if (key === "reposRoot") throw new Error("ENOSPC: no space left on device");
168 return Reflect.get(target, key, receiver);
169 },
170 });
171 await executeAgentRun(broken, queued, {
172 forgeUrl: "http://127.0.0.1:9",
173 localUrl: "http://127.0.0.1:9",
174 binary: "/bin/false",
175 concurrency: 1,
176 budgetUsd: 1,
177 runTimeoutMs: 60_000,
178 });
179 const ended = getRun(app.db, queued.id)!;
180 expect(ended.state).toBe("failed");
181 expect(ended.summary).toBe(`${RUN_THREW_PREFIX} Error: ENOSPC: no space left on device`);
182 expect(failedAtStart(ended.state, ended.summary, ended.turns)).toBe(true);
183 // The reviewer never read it: the try is not spent, and the next pass asks again.
184 expect(await sendToReview(app, repo, pull)).toBe("sent");
185 expect(waitsForPerson(app.db, repo.id, pull)).toBeUndefined();
186 }, 60_000);
187
188 test("a head lapsed on the forge's own failures is sent again, however long ago it went green", async () => {
189 // #16009's shape: green a day ago, two reviews overran before their reviewer started.
190 const pull = await greenPull("lapsed-on-faults", 24 * 60 * MIN);
191 const waited = budgetSummary(overranWhere(false, true), 30 * MIN, 10 * MIN);
192 for (let i = 0; i < FORGE_FAULTS_FORGIVEN; i++) {
193 const run = createRun(app.db, {
194 repoId: repo.id,
195 kind: "agent",
196 issueId: pull.id,
197 reason: "review",
198 actorId: getUserByName(app.db, "juniper")!.id,
199 });
200 const at = new Date(Date.now() - (23 - i) * 60 * MIN).toISOString();
201 app.db
202 .query("UPDATE run SET state = 'cancelled', summary = ?2, turns = 0, created_at = ?3, finished_at = ?3 WHERE id = ?1")
203 .run(run.id, waited, at);
204 }
205 // What the reviewer then says is its own: it has the head's two tries, and two silences lapse
206 // it.
207 for (let i = 0; i < 2; i++) {
208 expect(await sendToReview(app, repo, pull)).toBe("sent");
209 const sent = reviews(pull).find((r) => r.state === "queued")!;
210 app.db
211 .query("UPDATE run SET state = 'failed', summary = ?2, turns = 4, finished_at = ?3 WHERE id = ?1")
212 .run(sent.id, noVerdictSummary(), new Date().toISOString());
213 }
214 expect(await sendToReview(app, repo, pull)).toBe("lapsed");
215 expect(waitsForPerson(app.db, repo.id, pull)?.why).toBe("lapsed");
216 expect(reviews(pull)).toHaveLength(FORGE_FAULTS_FORGIVEN + 2);
217 }, 60_000);
218 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs