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

Three review rounds on one pull without an approval hand it to a person in one card #1300

Closed opened this
Closed without merging

scout/forge:scout/1176-three-review-rounds-on-one-pull-without → main 5 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +307 −25
README.md +12
@@ -325,6 +325,18 @@ changes, a line comment — and the agent picks it up in the background,
325325 resuming its session. A failed check re-engages it too, a bounded number of
326326 times before a person must speak.
327327
328 **Three rounds, then a person.** When the crew reviewer has asked for
329 changes three times on one pull with no approval and no word from a person
330 who may direct the crew between, no more feedback runs start on it. The
331 thread keeps a note ("Handed to a person by the crew:") with the three
332 asks, and the pull becomes a **hand-over** card in asks: *Tell them what to
333 try*, or *Close it*. Rounds are counted from the reviews, not the runs, so a
334 restart never adds one. A person resets the count by commenting as a
335 director (the crew then resumes) or by approving the pull from its page; the
336 card ends when the pull is approved, closed or merged. Hand-overs can be
337 closed in bulk like the other pull asks; the terminal screens do not list
338 asks cards, so they show the thread note only.
339
328340 **Already done.** A builder that finds its issue already built on the base
329341 branch declines with `DECLINED: already done on main in <commit>`, naming the
330342 full or abbreviated id of each commit that did it (at most five). The forge
src/crew/dispatch.ts +31 −18
@@ -35,9 +35,6 @@ import { getRepoById, type Repo } from "../core/repos.ts";
3535 import { listReviews } from "../core/reviews.ts";
3636 import {
3737 greenHead,
38 handedToPerson,
39 handoverNote,
40 reviewRounds,
4138 sendToReview,
4239 } from "./review.ts";
4340 import {
@@ -52,7 +49,7 @@ import {
5249 listQueued,
5350 type Run,
5451 } from "../core/runs.ts";
55 import { getUserById } from "../core/users.ts";
52 import { getUserById, type User } from "../core/users.ts";
5653 import { createLog } from "../kernel/log.ts";
5754 import { issueOfBranch, type RunReason } from "./brief.ts";
5855 import { detectClaude } from "./claude.ts";
@@ -61,6 +58,10 @@ import { breakerTripped } from "./breaker.ts";
6158 import {
6259 CAP_NOTE,
6360 capReached,
61 HANDOVER_NOTE,
62 handoverNote,
63 handoverOf,
64 type Handover,
6465 ISSUE_RUN_CAP,
6566 recordCap,
6667 skipsFeedback,
@@ -248,6 +249,25 @@ export async function startCrew(
248249 return handle;
249250 }
250251
252 /** Say the hand-over on the pull's thread, once per hand-over. */
253 function handOver(
254 app: App,
255 repo: Repo,
256 issue: Issue,
257 by: User,
258 over: Handover,
259 ): void {
260 const said = listComments(app.db, issue.id).some(
261 (c) => c.body.startsWith(HANDOVER_NOTE) && c.createdAt >= over.at,
262 );
263 if (said) return;
264 addComment(app, by, repo, issue, handoverNote(over));
265 log.info("handed to a person after three reviews", {
266 repo: `${repo.ownerName}/${repo.name}`,
267 pull: issue.number,
268 });
269 }
270
251271 /** Queue a run about an issue for an agent, unless one is already waiting. */
252272 export function queueAgentRun(
253273 app: App,
@@ -446,20 +466,13 @@ function route(app: App, event: ForgeEvent): void {
446466 }
447467 // The crew is off: a verdict is read by people, and wakes no one.
448468 if (reviewerVerdict && repo.autonomy === "off") return;
449 if (reviewerVerdict) {
450 // The loop is bounded: the third round hands the pull to a person.
451 const pull = getPull(app.db, repo.id, number);
452 if (pull && handedToPerson(app.db, repo.id, pull)) {
453 // One card: a re-sent verdict does not post a second.
454 const last = listComments(app.db, issue.id, { kind: "comment" }).at(-1);
455 if (!last?.body.startsWith("Handed to a person"))
456 addComment(
457 app,
458 actor,
459 repo,
460 issue,
461 handoverNote(reviewRounds(app.db, repo.id, pull)),
462 );
469 // The third changes-requested with no approval or person's word
470 // between is a person's to answer: one card on the pull, and no
471 // feedback run, now or for the verdicts after (`guard.ts`).
472 if (reviewerVerdict && event.payload["state"] === "changes_requested") {
473 const over = handoverOf(app.db, repo, issue.id);
474 if (over !== undefined) {
475 handOver(app, repo, issue, actor, over);
463476 return;
464477 }
465478 }
src/crew/guard.ts +95
@@ -176,3 +176,98 @@ export function guardCounts(
176176 rows.find((r) => r.answer === answer)?.n ?? 0;
177177 return { skipped: of("skipped"), capped: of("capped") };
178178 }
179
180 /** Crew `changes_requested` verdicts on one pull, with no approval or person's word between, before it is a person's. */
181 export const HANDOVER_ROUNDS = 3;
182
outdated

Four queries per call, and it is called for every open pull on every asks build. Return early on a cheap count of crew changes_requested rows (<3) before the comment and director lookups.

183 /** What the hand-over card starts with: the thread's own record of it, and what `handover` ignores as a person's word. */
184 export const HANDOVER_NOTE = "Handed to a person by the crew:";
185
186 export interface Handover {
187 /** The crew reviewer's verdicts that asked for changes, oldest first. */
188 readonly reviews: readonly { id: string; author: string; body: string; at: string }[];
189 /** When the third one landed: the card's age. */
190 readonly at: string;
191 }
192
193 /**
194 * Whether `pullId` has had `HANDOVER_ROUNDS` crew `changes_requested` verdicts
195 * since the last approval or the last word of a person who may direct the
196 * crew. Counted from the verdict rows, never the runs: a run a restart
197 * repeats is one verdict.
198 */
199 export function handoverOf(
200 db: Database,
201 repo: Repo,
202 pullId: string,
203 ): Handover | undefined {
204 // The common pull has fewer than three crew verdicts: one cheap count
205 // answers it before the approval, comment and director lookups.
206 const crewAsked = db
207 .query<{ n: number }, [string, string]>(
208 `SELECT COUNT(*) AS n FROM review r
209 JOIN repo_crew c ON c.user_id = r.author_id AND c.repo_id = ?2
210 WHERE r.issue_id = ?1 AND r.state = 'changes_requested' AND c.role = 'reviewer'`,
211 )
212 .get(pullId, repo.id)!.n;
213 if (crewAsked < HANDOVER_ROUNDS) return undefined;
214 const approved =
215 db
216 .query<{ at: string | null }, [string]>(
217 "SELECT MAX(created_at) AS at FROM review WHERE issue_id = ?1 AND state = 'approved'",
218 )
219 .get(pullId)?.at ?? "";
220 const spoke = db
221 .query<{ id: string; at: string }, [string]>(
222 `SELECT author_id AS id, MAX(created_at) AS at FROM comment
223 WHERE issue_id = ?1 AND origin_author IS NULL AND kind != 'review'
224 AND body NOT LIKE '${HANDOVER_NOTE}%'
225 GROUP BY author_id`,
226 )
227 .all(pullId);
228 const directors = new Set(
229 directorsAmong(
230 db,
231 repo,
232 spoke.map((s) => s.id),
233 ),
234 );
235 const since = spoke
236 .filter((s) => directors.has(s.id))
237 .map((s) => s.at)
238 .reduce((a, b) => (a > b ? a : b), approved);
239 const rounds = db
240 .query<
241 { id: string; author: string; body: string; at: string },
242 [string, string, string]
243 >(
244 `SELECT r.id AS id, u.username AS author, r.body AS body, r.created_at AS at
245 FROM review r JOIN user u ON u.id = r.author_id
246 JOIN repo_crew c ON c.user_id = r.author_id AND c.repo_id = ?3
247 WHERE r.issue_id = ?1 AND r.state = 'changes_requested'
248 AND r.created_at > ?2 AND c.role = 'reviewer'
249 ORDER BY r.created_at, r.id`,
250 )
251 .all(pullId, since, repo.id);
252 if (rounds.length < HANDOVER_ROUNDS) return undefined;
253 return { reviews: rounds, at: rounds[HANDOVER_ROUNDS - 1]!.at };
254 }
255
256 /** One line per review, for the card and the thread: who asked, and the first line of what. */
257 export function handoverLines(h: Handover): string[] {
258 return h.reviews.slice(0, HANDOVER_ROUNDS).map((r, n) => {
259 const first = (r.body.split("\n").find((l) => l.trim() !== "") ?? "no words")
260 .trim()
261 .slice(0, 140);
262 return `${n + 1}. ${r.author}: ${first}`;
263 });
264 }
265
266 /** The note the pull's thread keeps of the hand-over. */
267 export function handoverNote(h: Handover): string {
268 return [
269 `${HANDOVER_NOTE} the reviewer asked for changes three times with no approval between, so no more feedback runs start here until you say what to try.`,
270 "",
271 ...handoverLines(h),
272 ].join("\n");
273 }
src/web/studio/asks.ts +49 −6
@@ -47,6 +47,7 @@ import {
4747 } from "../../crew/autonomy.ts";
4848 import { breakerParked, WAITING_NOTES } from "../../crew/breaker.ts";
4949 import { CHECK_FAILED_LIMIT } from "../../crew/dispatch.ts";
50 import { handoverLines, handoverOf, type Handover } from "../../crew/guard.ts";
5051 import { isStalePull, mergesAgainSince } from "../../crew/stale_asks.ts";
5152 import { waitsForPerson, type ReviewWait } from "../../crew/review.ts";
5253 import type { Ctx } from "../../http/context.ts";
@@ -94,7 +95,7 @@ export function writableAppsOf(ctx: Ctx, user: User | undefined) {
9495 );
9596 }
9697
97 export type DecisionKind = "stopped" | "look" | "review" | "paused" | "parked" | "declined";
98 export type DecisionKind = "stopped" | "look" | "review" | "paused" | "parked" | "declined" | "handover";
9899
99100 /** Dollars as a person reads them: cents when small, whole when not. */
100101 const dollars = (n: number): string => (n < 10 ? n.toFixed(2) : n.toFixed(0));
@@ -150,6 +151,11 @@ export const ASK_WORDS: Readonly<Record<DecisionKind, AskWords>> = {
150151 options: ["Tell them"],
151152 ifNothing: "nothing more starts on it",
152153 },
154 handover: {
155 decision: "The reviewer asked for changes three times: what should the builder try?",
156 options: ["Tell them what to try", "Close it"],
157 ifNothing: "no more feedback runs start; the pull waits for you",
158 },
153159 declined: {
154160 decision: "The planner declined the direction: answer it?",
155161 options: ["Answer the planner"],
@@ -179,6 +185,7 @@ export const KIND_TIER: Readonly<Record<DecisionKind, Consequence>> = {
179185 declined: { score: 70, why: "the planner has stopped for this app" },
180186 stopped: { score: 50, why: "red, and the crew stopped" },
181187 review: { score: 45, why: "an agent's change waits for a review" },
188 handover: { score: 55, why: "three reviews without an approval: handed to a person" },
182189 parked: { score: 40, why: "parked by the crew" },
183190 look: { score: 30, why: "green, waiting" },
184191 };
@@ -221,6 +228,8 @@ interface AskCandidate {
221228 readonly stoppedByDecider?: boolean;
222229 /** For "declined": the declining run and what the planner said. */
223230 readonly decline?: { readonly runId: string; readonly words: string };
231 /** For "handover": the reviews that asked for changes. */
232 readonly handover?: Handover;
224233 }
225234
226235 /**
@@ -270,6 +279,22 @@ function askCandidatesFor(
270279 const who = issue.authorName;
271280 // The crew is on it: that is working, not a question for a person.
272281 if (activeRunFor(db, "agent", issue.id) !== undefined) continue;
282 // Three reviews without an approval: the crew stopped, and says so
283 // before anything about the check (`guard.ts`).
284 const over = handoverOf(db, repo, issue.id);
285 if (over !== undefined) {
286 out.push({
287 kind: "handover",
288 id: `handover:${pull.id}`,
289 since: over.at,
290 repo,
291 pull,
292 who,
293 authorIsAgent: issue.authorIsAgent,
294 handover: over,
295 });
296 continue;
297 }
273298 if (check?.state === "failed") {
274299 // Automatic retries, and the limit that stops them, are the crew's
275300 // own machinery — a person's own failing pull never accrues tries,
@@ -553,14 +578,14 @@ function waitingOn(
553578 }
554579
555580 /** How an ask that is no longer asked ended, when nobody dismissed it. */
556 function endOf(
581 export function endOf(
557582 db: Database,
558583 viewerId: string,
559584 askId: string,
560585 raisedAt: string,
561586 ): Exclude<AskEnd, "dismissed"> {
562587 const [kind, what] = askId.split(":") as [DecisionKind, string];
563 if (kind === "look" || kind === "review" || kind === "stopped") {
588 if (kind === "look" || kind === "review" || kind === "stopped" || kind === "handover") {
564589 const pull = getIssueById(db, what);
565590 // Shipped or closed: someone decided. Held by the one it asked: they
566591 // answered "not yet". Still open otherwise: the cause went away.
@@ -638,6 +663,8 @@ function lineOf(c: AskCandidate): string {
638663 return `the crew parked #${c.issue!.number} after three failed runs`;
639664 if (c.kind === "declined")
640665 return "the planner declined the direction and waits for you";
666 if (c.kind === "handover")
667 return `"${c.pull?.title ?? ""}" had three reviews asking for changes and waits for you`;
641668 const title = c.pull?.title ?? "";
642669 if (c.kind === "review")
643670 return `"${title}" waits for your review: ${reviewWhy(c.reviewWait)}`;
@@ -662,6 +689,7 @@ export const ROW_PLURAL: Readonly<Record<DecisionKind, (n: number) => string>> =
662689 review: (n) => `${n} agent changes wait for your review`,
663690 stopped: (n) => `the crew stopped on ${n} changes`,
664691 parked: (n) => `the crew parked ${n} issues after three failed runs`,
692 handover: (n) => `${n} changes had three reviews asking for changes and wait for you`,
665693 declined: (n) => `the planner declined ${n} times and waits for you`,
666694 paused: (n) => `${n} pauses at the ceiling`,
667695 };
@@ -790,6 +818,16 @@ export function decisionsFor(
790818 says: `The planner declined the direction: \u201c${c.decline.words}\u201d. It plans nothing more until you answer on #${c.issue.number}.`,
791819 short: `the planner declined the direction: \u201c${c.decline.words}\u201d`,
792820 };
821 if (c.kind === "handover" && c.pull && c.handover)
822 return {
823 kind: "handover",
824 id: `handover:${c.pull.id}`,
825 repo: c.repo,
826 pull: c.pull,
827 who: c.who,
828 says: `The reviewer asked for changes three times with no approval between, so the crew stopped. ${handoverLines(c.handover).join(" ")} Say what to try (or approve it on its page), or close it.`,
829 short: `"${c.pull.title}" had three reviews asking for changes`,
830 };
793831 if (c.kind === "stopped" && c.pull) {
794832 const tries = c.tries ?? 0;
795833 const stopped = c.stoppedByDecider ?? false;
@@ -861,7 +899,7 @@ export function decisionForm(d: Decision): Html | null {
861899 if (pull === undefined) return null;
862900 const base = repoBase(d.repo);
863901 const own = html`id="${askFormId(d)}" method="post" hidden`;
864 if (d.kind === "stopped")
902 if (d.kind === "stopped" || d.kind === "handover")
865903 return html`<form ${own} action="${base}/pulls/${pull.number}/state">
866904 <input type="hidden" name="state" value="closed" />
867905 </form>`;
@@ -893,7 +931,7 @@ export function decisionButtons(ctx: Ctx, d: Decision): { primary: Html; others:
893931 : getAppByRepo(ctx.app.db, d.repo.id) === undefined
894932 ? undefined
895933 : `${base}/app/pull-${pull.number}/open`;
896 if (d.kind === "stopped" && pull)
934 if ((d.kind === "stopped" || d.kind === "handover") && pull)
897935 return {
898936 primary: btn("Tell them", {
899937 href: `${changeHref(base, pull.number)}#comment-body`,
@@ -1002,7 +1040,12 @@ export function asksAnswer(ctx: Ctx, user: User) {
10021040 */
10031041 export function askItemsOf(issue: Issue): string[] {
10041042 return issue.kind === "pull"
1005 ? [`ask:look:${issue.id}`, `ask:review:${issue.id}`, `ask:stopped:${issue.id}`]
1043 ? [
1044 `ask:look:${issue.id}`,
1045 `ask:review:${issue.id}`,
1046 `ask:stopped:${issue.id}`,
1047 `ask:handover:${issue.id}`,
1048 ]
10061049 : [`ask:parked:${issue.id}`];
10071050 }
10081051
src/web/studio/asks_page.ts +2 −1
@@ -51,7 +51,7 @@ const ASK_KIND_WORDS: Readonly<Record<string, string>> = {
5151 };
5252
5353 /** The kinds a bulk action takes: a ceiling and a planner's decline are decided where they live. */
54 const BULK_KINDS: ReadonlySet<Decision["kind"]> = new Set(["look", "review", "stopped", "parked"]);
54 const BULK_KINDS: ReadonlySet<Decision["kind"]> = new Set(["look", "review", "stopped", "handover", "parked"]);
5555
5656 /** A row's box for the bulk form, which sits apart (`form="asks-bulk"`): forms do not nest. */
5757 const pick = (d: Decision, picked: ReadonlySet<string>): Html | null =>
@@ -153,6 +153,7 @@ const KIND_LABEL: Readonly<Record<Decision["kind"], string>> = {
153153 look: "Ready to ship",
154154 review: "Needs review",
155155 stopped: "Stopped",
156 handover: "Handed over",
156157 parked: "Parked",
157158 declined: "Declined",
158159 paused: "Paused",
test/crew-loop.test.ts +118
@@ -25,6 +25,9 @@ import { serve, type Servers } from "../src/http/server.ts";
2525 import { driveRepo, settleAgentRun } from "../src/crew/autonomy.ts";
2626 import { startCrew, queueAgentRun, type CrewHandle } from "../src/crew/dispatch.ts";
2727 import { getAgent } from "../src/core/agents.ts";
28 import type { Ctx } from "../src/http/context.ts";
29 import { setIssueState } from "../src/actions/issues.ts";
30 import { ASK_WORDS, KIND_TIER, askLinesFor, decisionActions, decisionForm, decisionsFor, endOf } from "../src/web/studio/asks.ts";
2831 import { breakerParked, breakerTripped } from "../src/crew/breaker.ts";
2932
3033 describe("an agent's own comment never starts its next run", () => {
@@ -384,4 +387,119 @@ describe("a crew reviewer's changes-requested wakes the builder", () => {
384387 await settle();
385388 expect(feedback(pull).length).toBe(0);
386389 });
390
391 /** The builder's queued follow-ups end, so each round is counted on its own. */
392 const settleFeedback = (pull: Pull) => {
393 for (const r of feedback(pull)) {
394 claimRun(app.db, r.id);
395 finishRun(app.db, r.id, { state: "ok", summary: "Pushed a fix." });
396 }
397 };
398 const verdict = async (pull: Pull, body: string, state = "changes_requested") => {
399 await submitReview(app, sentinel, fresh(), pull, {
400 state: state as "changes_requested",
401 body,
402 });
403 await settle();
404 };
405 const handoverNotes = (pull: Pull) =>
406 listComments(app.db, pull.id).filter((c) =>
407 c.body.startsWith("Handed to a person by the crew:"),
408 );
409
410 test("the third changes-requested hands the pull to a person; a fourth queues nothing", async () => {
411 const set = await updateRepoSettings(app, alice, fresh(), {
412 autonomy: "autonomous",
413 autonomyCeilingUsd: 100,
414 autonomyBy: alice.id,
415 });
416 if (!set.ok) throw new Error(JSON.stringify(set.error));
417 const pull = await masonPull("rounds");
418 await verdict(pull, "Round one: the token is logged.");
419 expect(feedback(pull).length).toBe(1);
420 settleFeedback(pull);
421 await verdict(pull, "Round two: still logged.");
422 expect(feedback(pull).length).toBe(2);
423 settleFeedback(pull);
424 expect(handoverNotes(pull).length).toBe(0);
425 await verdict(pull, "Round three: and the retry loops.");
426 expect(feedback(pull).length).toBe(2);
427 const notes = handoverNotes(pull);
428 expect(notes.length).toBe(1);
429 expect(notes[0]!.body).toContain("1. sentinel: Round one");
430 expect(notes[0]!.body).toContain("3. sentinel: Round three");
431 // Not parked, not closed: it is still open and asks a person.
432 expect(getIssueById(app.db, pull.id)!.state).toBe("open");
433 const asked = askLinesFor(app.db, alice).filter((a) => a.kind === "handover");
434 expect(asked.length).toBe(1);
435 expect(asked[0]!.number).toBe(pull.number);
436 await verdict(pull, "Round four.");
437 expect(feedback(pull).length).toBe(2);
438 expect(handoverNotes(pull).length).toBe(1);
439 });
440
441 test("a person's comment resets the count", async () => {
442 const pull = await masonPull("reset-comment");
443 await verdict(pull, "One.");
444 settleFeedback(pull);
445 await verdict(pull, "Two.");
446 settleFeedback(pull);
447 await verdict(pull, "Three.");
448 expect(handoverNotes(pull).length).toBe(1);
449 addComment(app, alice, fresh(), getIssueById(app.db, pull.id)!, "Try the other way.");
450 await settle();
451 settleFeedback(pull);
452 expect(askLinesFor(app.db, alice).some((a) => a.number === pull.number && a.kind === "handover")).toBe(false);
453 const before = feedback(pull).length;
454 await verdict(pull, "Four, a new first round.");
455 expect(feedback(pull).length).toBe(before + 1);
456 });
457
458 test("an approval resets the count", async () => {
459 const pull = await masonPull("reset-approval");
460 await verdict(pull, "One.");
461 settleFeedback(pull);
462 await verdict(pull, "Two.");
463 settleFeedback(pull);
464 await verdict(pull, "Fine now.", "approved");
465 await verdict(pull, "Three.");
466 expect(handoverNotes(pull).length).toBe(0);
467 });
468 test("the hand-over card offers three words, a close and a way to speak; closing or approving ends it", async () => {
469 const pull = await masonPull("card");
470 await verdict(pull, "One.");
471 settleFeedback(pull);
472 await verdict(pull, "Two.");
473 settleFeedback(pull);
474 await verdict(pull, "Three.");
475 expect(ASK_WORDS.handover.options).toEqual(["Tell them what to try", "Close it"]);
476 expect(KIND_TIER.handover).toBeDefined();
477 const ctx = {
478 app,
479 request: new Request("http://forge.test/"),
480 url: new URL("http://forge.test/"),
481 params: {},
482 auth: { user: alice, scope: undefined, via: "session" },
483 theme: undefined,
484 } as Ctx;
485 const card = decisionsFor(ctx, [fresh()]).find((d) => d.kind === "handover");
486 expect(card?.pull?.number).toBe(pull.number);
487 expect(card!.consequence.why).toBe(KIND_TIER.handover.why);
488 expect(card!.says).toContain("Say what to try");
489 expect(askLinesFor(app.db, alice).find((a) => a.kind === "handover")!.words).toEqual(ASK_WORDS.handover);
490 const form = String(decisionForm(card!));
491 expect(form).toContain(`/pulls/${pull.number}/state`);
492 expect(form).toContain('value="closed"');
493 const actions = String(decisionActions(ctx, card!));
494 expect(actions).toContain("Tell them");
495 expect(actions).toContain("Close");
496 expect(actions).not.toContain("Approve");
497 const ask = `handover:${pull.id}`;
498 const raised = new Date(0).toISOString();
499 expect(endOf(app.db, alice.id, ask, raised)).toBe("expired");
500 await verdict(pull, "Fine now.", "approved");
501 expect(askLinesFor(app.db, alice).some((a) => a.number === pull.number && a.kind === "handover")).toBe(false);
502 await setIssueState(app, alice, fresh(), getIssueById(app.db, pull.id)!, "closed");
503 expect(endOf(app.db, alice.id, ask, raised)).toBe("acted");
504 });
387505 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs