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

A person can ask the crew to review their pull (route, button and @mention); today person-authored pulls are never reviewed #4574

Parked opened this in answer to
Closed without merging

scout/forge:scout/4568-a-person-can-ask-the-crew-to-review-thei → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +771 −14
README.md +4
@@ -2145,3 +2145,7 @@ The here-manifest (`GET /api/v1/here?path=…`) reads the same for guests and
21452145 members. On `/explore` and `/search` it names the page's own read, `?q=` carried
21462146 over and encoded: `GET /api/v1/explore?q=…` (MCP tool `explore`) or
21472147 `GET /api/v1/search?q=…` (MCP tool `search`), listed once.
2148
2149 ### Asking the crew to review a person's pull
2150
2151 The crew reviews its own agents' pulls on its own; a person's pull is reviewed once asked. `POST /api/v1/repos/:owner/:name/pulls/:number/review-requests` with `{"reviewer": "<agent>"}` (optional; without it, the reviewer with the fewest queued or running runs), the "Ask the crew to review" button on the pull page, or an `@mention` of a crew reviewer in a pull comment by a person who writes the repository. The ask is one row (`review_request`); from it the review runs like an agent pull's (same rounds, verdicts and lapse, the clock starting at the ask), and an approval on the head lets `landIfGreen` land it. From the terminal, press `K` on a pull's screen (a reviewer's username, or empty for the least busy). Over MCP, `request_review {app, pull, reviewer?}` plans by default and asks with `dryRun: false`. Without a name the least busy reviewer is chosen and kept, so every door answers with who was asked. A later mention of the reviewer already asked does not ask again or restart the clock. An agent cannot ask, and a held pull is not reviewed.
src/actions/review_requests.ts added +100
@@ -0,0 +1,100 @@
1 /**
2 * Asking the crew to review a person's pull (`core/review_requests.ts`).
3 *
4 * A person who writes the repository asks, by the button, the API or an
5 * @mention of a reviewer in a comment (`mentionedReviewer`). An agent is
6 * refused: the ask is a person's word, not the crew's to give itself. The
7 * pull is then the crew's to review like an agent's — and when its head is
8 * already green the review is sent now, not at the next sweep.
9 */
10
11 import type { App } from "../app.ts";
12 import type { Agent } from "../core/agents.ts";
13 import { getHold } from "../core/holds.ts";
14 import { setReviewRequest, type ReviewRequest } from "../core/review_requests.ts";
15 import type { Pull } from "../core/pulls.ts";
16 import { canRead, canWrite, type Repo } from "../core/repos.ts";
17 import type { User } from "../core/users.ts";
18 import { createLog } from "../kernel/log.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20 import { greenHead, leastBusy, reviewersOf, sendToReview } from "../crew/review.ts";
21 import type { AccessError } from "./access.ts";
22
23 const log = createLog("crew");
24
25 export type ReviewRequestError =
26 | AccessError
27 | "not_open"
28 | "agent_pull"
29 | "held"
30 | "no_reviewer"
31 | "not_reviewer";
32
33 /** A kept ask, and the reviewer's name it resolved to. */
34 export interface Asked {
35 readonly request: ReviewRequest;
36 readonly reviewer: string;
37 }
38
39 /**
40 * Ask the crew to review this pull, of the named reviewer or, with none,
41 * the least busy now (kept, so the answer names who). Asking again names
42 * again and restarts the review clock. `dry` checks everything, names who
43 * would be asked, and writes nothing.
44 */
45 export function requestReview(
46 app: App,
47 actor: User | undefined,
48 repo: Repo,
49 pull: Pull,
50 reviewer?: string,
51 dry = false,
52 ): Result<Asked, ReviewRequestError> {
53 if (pull.repoId !== repo.id || !canRead(app.db, repo, actor)) return err("not_found");
54 if (!actor) return err("unauthorized");
55 if (actor.kind !== "user" || !canWrite(app.db, repo, actor)) return err("forbidden");
56 if (pull.state !== "open" || pull.mergedAt !== null) return err("not_open");
57 if (pull.authorIsAgent) return err("agent_pull");
58 if (getHold(app.db, pull.id) !== undefined) return err("held");
59 const crew = reviewersOf(app.db, repo.id);
60 if (crew.length === 0) return err("no_reviewer");
61 let named: Agent | undefined;
62 if (reviewer !== undefined && reviewer !== "") {
63 const name = reviewer.replace(/^@/, "").toLowerCase();
64 named = crew.find((r) => r.user.username.toLowerCase() === name);
65 if (named === undefined) return err("not_reviewer");
66 }
67 const chosen = named ?? leastBusy(app.db, crew)!;
68 if (dry)
69 return ok({
70 request: {
71 pullId: pull.id,
72 requestedBy: actor.id,
73 reviewerId: chosen.user.id,
74 requestedAt: new Date().toISOString(),
75 },
76 reviewer: chosen.user.username,
77 });
78 const request = setReviewRequest(app.db, pull.id, actor.id, chosen.user.id);
79 if (greenHead(app.db, pull))
80 sendToReview(app, repo, pull).catch((error) =>
81 log.error("sending to review failed", { pull: pull.number, error: String(error) }),
82 );
83 return ok({ request, reviewer: chosen.user.username });
84 }
85
86 /** The crew reviewer an @mention in this text names, if one is. */
87 export function mentionedReviewer(
88 app: App,
89 repo: Repo,
90 text: string,
91 ): string | undefined {
92 const crew = reviewersOf(app.db, repo.id);
93 if (crew.length === 0) return undefined;
94 for (const m of text.matchAll(/(?<![\w@])@([a-z0-9][a-z0-9_-]{0,38})(?![\w-])/gi)) {
95 const name = m[1]!.toLowerCase();
96 const found = crew.find((r) => r.user.username.toLowerCase() === name);
97 if (found) return found.user.username;
98 }
99 return undefined;
100 }
src/core/migrations/20261022130000-review-requests.ts added +10
@@ -0,0 +1,10 @@
1 // A person's ask that the crew review their pull (#4568, `core/review_requests.ts`).
2 // One row per pull; asking again moves the time and the named reviewer.
3 export default `
4 CREATE TABLE IF NOT EXISTS review_request (
5 issue_id TEXT PRIMARY KEY REFERENCES issue(id) ON DELETE CASCADE,
6 requested_by TEXT NOT NULL REFERENCES user(id),
7 reviewer_id TEXT REFERENCES user(id),
8 requested_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
9 );
10 `;
src/core/review_requests.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * A person's ask that the crew review their pull (#4568). The crew reviews
3 * the pulls its agents wrote on its own; a person's pull is reviewed only
4 * once asked, by the button, the API, or an @mention of a reviewer. The
5 * ask is kept, one row per pull, and from then on the review runs as an
6 * agent pull's does: the same rounds, verdicts and lapse, the clock
7 * starting at the ask when the head was already green.
8 *
9 * Pure data, no authz, no events (`actions/review_requests.ts`).
10 */
11
12 import type { Database } from "bun:sqlite";
13
14 export interface ReviewRequest {
15 readonly pullId: string;
16 readonly requestedBy: string;
17 /** The reviewer asked by name, or null for the least busy. */
18 readonly reviewerId: string | null;
19 readonly requestedAt: string;
20 }
21
22 interface Row {
23 issue_id: string;
24 requested_by: string;
25 reviewer_id: string | null;
26 requested_at: string;
27 }
28
29 const fromRow = (r: Row): ReviewRequest => ({
30 pullId: r.issue_id,
31 requestedBy: r.requested_by,
32 reviewerId: r.reviewer_id,
33 requestedAt: r.requested_at,
34 });
35
36 /** Record the ask; asking again replaces the reviewer and restarts the clock. */
37 export function setReviewRequest(
38 db: Database,
39 pullId: string,
40 by: string,
41 reviewerId: string | null,
42 ): ReviewRequest {
43 return fromRow(
44 db
45 .query<Row, [string, string, string | null]>(
46 `INSERT INTO review_request (issue_id, requested_by, reviewer_id) VALUES (?1, ?2, ?3)
47 ON CONFLICT(issue_id) DO UPDATE SET requested_by = ?2, reviewer_id = ?3,
48 requested_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
49 RETURNING issue_id, requested_by, reviewer_id, requested_at`,
50 )
51 .get(pullId, by, reviewerId)!,
52 );
53 }
54
55 /** The asks on these pulls, by pull: one read for a list. */
56 export function reviewRequestsFor(
57 db: Database,
58 pullIds: readonly string[],
59 ): Map<string, ReviewRequest> {
60 const out = new Map<string, ReviewRequest>();
61 const CHUNK = 400;
62 for (let i = 0; i < pullIds.length; i += CHUNK) {
63 const batch = pullIds.slice(i, i + CHUNK);
64 for (const row of db
65 .query<Row, string[]>(
66 `SELECT issue_id, requested_by, reviewer_id, requested_at FROM review_request
67 WHERE issue_id IN (${batch.map((_, n) => `?${n + 1}`).join(",")})`,
68 )
69 .all(...batch))
70 out.set(row.issue_id, fromRow(row));
71 }
72 return out;
73 }
74
75 export const getReviewRequest = (db: Database, pullId: string): ReviewRequest | undefined =>
76 reviewRequestsFor(db, [pullId]).get(pullId);
src/crew/autonomy.ts +3 −2
@@ -123,7 +123,7 @@ import {
123123 import { crewOffInPreview } from "./preview.ts";
124124 import { approvedOnHead, finishApproved, finishFields } from "./finishing.ts";
125125 import { moveRequested, tallyRequested, tallyWords } from "./requested.ts";
126 import { reviewersOf, sendToReview, sweepReviews } from "./review.ts";
126 import { crewReviews, reviewersOf, sendToReview, sweepReviews } from "./review.ts";
127127 import { lastWaits, noteWaits, tallyWaits, type Wait, waitWords } from "./waits.ts";
128128 import { bootCounts } from "../kernel/boots.ts";
129129
@@ -1725,7 +1725,8 @@ async function reviewed(
17251725 // An agent's pull ships only on an approving review — the crew's reviewer
17261726 // or a person's. With no reviewer, or a review that lapsed, it waits for
17271727 // a person (`waitsForPerson` puts it where a person looks); never by lapse.
1728 if (pull.authorIsAgent) {
1728 // A person's pull the crew was asked to review is held the same way (#4568).
1729 if (crewReviews(app.db, pull)) {
17291730 if (reviewersOf(app.db, repo.id).length > 0) await sendToReview(app, repo, pull);
17301731 return "hold";
17311732 }
src/crew/dispatch.ts +17 −2
@@ -36,7 +36,9 @@ import { decideAndRecord } from "./ledger.ts";
3636 import { byDials } from "./team_share.ts";
3737 import { ARCHIVED_WHY, getRepoById, type Repo } from "../core/repos.ts";
3838 import { listReviews } from "../core/reviews.ts";
39 import { mentionedReviewer, requestReview } from "../actions/review_requests.ts";
3940 import {
41 crewReviews,
4042 greenHead,
4143 sendToReview,
4244 } from "./review.ts";
@@ -53,7 +55,8 @@ import {
5355 listQueued,
5456 type Run,
5557 } from "../core/runs.ts";
56 import { getUserById, type User } from "../core/users.ts";
58 import { getUserById, getUserByName, type User } from "../core/users.ts";
59 import { getReviewRequest } from "../core/review_requests.ts";
5760 import { guestSql, lacks } from "../core/roles.ts";
5861 import { createLog } from "../kernel/log.ts";
5962 import { issueOfBranch, type RunReason } from "./brief.ts";
@@ -507,6 +510,18 @@ function route(app: App, event: ForgeEvent): void {
507510 if (!mayDirectCrew(app.db, repo, actor)) return;
508511 const issue = getIssue(app.db, repo.id, number);
509512 if (!issue || issue.state !== "open") return;
513 // A person's @mention of a crew reviewer in a pull's comment asks it
514 // to review that pull (#4568); the words go on to the builder as usual.
515 const spoken = event.payload["body"];
516 if (event.kind === "pull.commented" && actor.kind === "user" && typeof spoken === "string") {
517 const reviewer = mentionedReviewer(app, repo, spoken);
518 const pull = reviewer === undefined ? undefined : getPull(app.db, repo.id, number);
519 // Asked once: a later mention of the same reviewer ("thanks @quill")
520 // is only words, and does not restart the review clock.
521 const kept = pull === undefined ? undefined : getReviewRequest(app.db, pull.id);
522 if (pull && (kept === undefined || kept.reviewerId !== getUserByName(app.db, reviewer!)?.id))
523 requestReview(app, actor, repo, pull, reviewer);
524 }
510525 if (
511526 event.kind === "pull.reviewed" &&
512527 event.payload["state"] === "approved"
@@ -605,7 +620,7 @@ function route(app: App, event: ForgeEvent): void {
605620 const pull = getPull(app.db, repo.id, issue.number);
606621 if (!pull) return;
607622 if (repo.autonomy !== "autonomous") {
608 if (pull.authorIsAgent && greenHead(app.db, pull))
623 if (crewReviews(app.db, pull) && greenHead(app.db, pull))
609624 sendToReview(app, repo, pull).catch((error) =>
610625 log.error("sending to review failed", {
611626 pull: issue.number,
src/crew/review.ts +37 −10
@@ -26,6 +26,7 @@ import { listPulls, pullDiff, type Pull, pullDir} from "../core/pulls.ts";
2626 import { getRepoById, type Repo } from "../core/repos.ts";
2727 import { teamsOfPull, teamVerdicts } from "../core/issue_teams.ts";
2828 import { reviewSummariesFor, reviewSummary } from "../core/reviews.ts";
29 import { getReviewRequest, reviewRequestsFor } from "../core/review_requests.ts";
2930 import { checksForHead } from "../core/runs.ts";
3031 import { getTeam } from "../core/teams.ts";
3132 import { repoDir } from "../git/repos.ts";
@@ -76,6 +77,19 @@ export function pickReviewer(
7677 return preferred[0] ?? reviewers[0];
7778 }
7879
80 /** The reviewer with the fewest review runs queued or running; the first on a tie. */
81 export function leastBusy(db: Database, reviewers: readonly Agent[]): Agent | undefined {
82 const load = (a: Agent): number =>
83 db
84 .query<{ n: number }, [string]>(
85 `SELECT COUNT(*) AS n FROM run WHERE kind = 'agent' AND actor_id = ?1 AND state IN ('queued','running')`,
86 )
87 .get(a.user.id)!.n;
88 return reviewers
89 .map((a) => ({ a, n: load(a) }))
90 .reduce<{ a: Agent; n: number } | undefined>((best, c) => (best === undefined || c.n < best.n ? c : best), undefined)?.a;
91 }
92
7993 /** The crew's reviewers on a repository. */
8094 export const reviewersOf = (db: Database, repoId: string): Agent[] =>
8195 reviewersForRepos(db, [repoId]).get(repoId) ?? [];
@@ -174,6 +188,7 @@ export function reviewAttemptsFor(
174188 )
175189 .all(...batch.flatMap((p) => [p.id, p.headOid]));
176190 const released = lastReleasesFor(db, ids);
191 const asked = reviewRequestsFor(db, ids);
177192 const reviews = new Map<string, { createdAt: string; active: boolean; reviewerId: string | null }[]>();
178193 for (const r of db
179194 .query<{ issue_id: string; created_at: string; state: string; actor_id: string | null }, string[]>(
@@ -208,7 +223,9 @@ export function reviewAttemptsFor(
208223 const green = greenRun.finished_at!;
209224 const checkMs = hasCheck ? Date.parse(green) - Date.parse(greenRun.created_at) : 0;
210225 const release = released.get(pull.id);
211 const since = release !== undefined && release > green ? release : green;
226 // Review is owed from the latest of the green, a release and a person's ask.
227 const ask = asked.get(pull.id)?.requestedAt;
228 const since = [release, ask].reduce<string>((at, t) => (t !== undefined && t > at ? t : at), green);
212229 const attempts = (reviews.get(pull.id) ?? []).filter((a) => a.createdAt >= since);
213230 const first = attempts[0];
214231 const lateAt =
@@ -299,8 +316,12 @@ export function waitsForReviewer(
299316 return waitsOne(db, repoId, pull, now)?.reviewer;
300317 }
301318
319 /** Whether the crew reviews this pull: an agent's, or a person's once asked (#4568). */
320 export const crewReviews = (db: Database, pull: Pull): boolean =>
321 pull.authorIsAgent || getReviewRequest(db, pull.id) !== undefined;
322
302323 function waitsOne(db: Database, repoId: string, pull: Pull, now: Date): ReviewWaits | undefined {
303 if (!pull.authorIsAgent) return undefined;
324 if (!crewReviews(db, pull)) return undefined;
304325 const repo = getRepoById(db, repoId);
305326 return repo ? reviewWaitsFor(db, [{ repo, pull }], now).get(pull.id) : undefined;
306327 }
@@ -321,7 +342,8 @@ export function reviewWaitsFor(
321342 handovers?: ReadonlyMap<string, Handover>,
322343 ): Map<string, ReviewWaits> {
323344 const out = new Map<string, ReviewWaits>();
324 const agents = pulls.filter((p) => p.pull.authorIsAgent);
345 const asked = reviewRequestsFor(db, pulls.filter((p) => !p.pull.authorIsAgent).map((p) => p.pull.id));
346 const agents = pulls.filter((p) => p.pull.authorIsAgent || asked.has(p.pull.id));
325347 const held = holdsFor(db, agents.map((p) => p.pull.id));
326348 const unheld = agents.filter((p) => !held.has(p.pull.id));
327349 const seen = reviewSummariesFor(db, unheld.map((p) => p.pull));
@@ -373,7 +395,7 @@ export function reviewWaitsFor(
373395 * state cannot answer differently.
374396 */
375397 function handedOver(db: Database, repoId: string, pull: Pull): Handover | undefined {
376 if (!pull.authorIsAgent) return undefined;
398 if (!crewReviews(db, pull)) return undefined;
377399 const repo = getRepoById(db, repoId);
378400 return repo ? handoverOf(db, repo, pull.id) : undefined;
379401 }
@@ -427,11 +449,16 @@ export async function sendToReview(
427449 // when the crew has one; with only one, the same reviewer tries again.
428450 const failed = history.attempts.at(-1)?.reviewerId;
429451 const others = reviewers.filter((r) => r.user.id !== failed);
430 const reviewer = pickReviewer(
431 others.length > 0 ? others : reviewers,
432 diff.files.map((f) => f.path),
433 getTeam(app.db, "design")?.members,
434 );
452 const pool = others.length > 0 ? others : reviewers;
453 // A person's ask may name the reviewer; otherwise a person's pull goes to
454 // the least busy of those the change calls for (#4568).
455 const ask = getReviewRequest(app.db, pull.id);
456 const named = ask?.reviewerId == null ? undefined : pool.find((r) => r.user.id === ask.reviewerId);
457 const reviewer =
458 named ??
459 (ask === undefined
460 ? pickReviewer(pool, diff.files.map((f) => f.path), getTeam(app.db, "design")?.members)
461 : leastBusy(app.db, pool));
435462 if (reviewer === undefined) return "wait";
436463 if (queueAgentRun(app, repo, issue, reviewer, "review") === undefined)
437464 return "wait";
@@ -549,7 +576,7 @@ export async function sweepReviews(app: App): Promise<number> {
549576 if (!repo) continue;
550577 for (const pull of openPullsOldestFirst(app.db, repo.id)) {
551578 if (queued >= SWEEP_SENDS) return forgetSettled(stalled, queued);
552 if (!pull.authorIsAgent || !greenHead(app.db, pull)) continue;
579 if (!greenHead(app.db, pull) || !crewReviews(app.db, pull)) continue;
553580 const result = await sendToReview(app, repo, pull);
554581 if (result === "sent") queued++;
555582 else if (result === "lapsed" || result === "wait") {
src/http/api.ts +35
@@ -147,6 +147,7 @@ import {
147147 import { attachLook } from "../actions/attach_look.ts";
148148 import { lookUrl } from "../core/looks.ts";
149149 import { holdPull, releasePull } from "../actions/holds.ts";
150 import { requestReview } from "../actions/review_requests.ts";
150151 import { getHold, type Hold } from "../core/holds.ts";
151152 import { watchMilestone } from "../actions/watches.ts";
152153 import { THOUGHT_MAX, keepThought } from "../actions/thought.ts";
@@ -4060,6 +4061,40 @@ export function apiRoutes(router: Router<Handler>): void {
40604061 },
40614062 );
40624063
4064 // Ask the crew to review a person's pull (`actions/review_requests.ts`):
4065 // `{reviewer?: "<agent>"}`; without one, the least busy reviewer.
4066 router.add(
4067 "POST",
4068 "/api/v1/repos/:owner/:name/pulls/:number/review-requests",
4069 async (ctx) => {
4070 const denied = requireScope(ctx, "rw");
4071 if (denied) return denied;
4072 const found = loadPull(ctx);
4073 if ("error" in found) return found.error;
4074 const input = await body(ctx.request);
4075 const asked = requestReview(
4076 ctx.app,
4077 ctx.auth.user,
4078 found.repo,
4079 found.pull,
4080 str(input.reviewer),
4081 );
4082 if (!asked.ok)
4083 return respondAccess(
4084 asked.error,
4085 asked.error === "not_open" || asked.error === "held" ? 409 : 422,
4086 );
4087 return json(
4088 {
4089 requested: true,
4090 reviewer: asked.value.reviewer,
4091 at: asked.value.request.requestedAt,
4092 },
4093 201,
4094 );
4095 },
4096 );
4097
40634098 router.add(
40644099 "POST",
40654100 "/api/v1/repos/:owner/:name/pulls/:number/merge",
src/http/mcp.ts +60
@@ -60,6 +60,7 @@ import {
6060 import { submitReview } from "../actions/pulls.ts";
6161 import { originError } from "../web/pages/thread.ts";
6262 import { holdPull, releasePull } from "../actions/holds.ts";
63 import { requestReview } from "../actions/review_requests.ts";
6364 import { openPlan, parsePlan, PLAN_MAX, proposePlan } from "../actions/plan.ts";
6465 import { cancelRepoRun, listRepoRuns } from "../actions/runs.ts";
6566 import { familyView } from "../spawn/family.ts";
@@ -3121,6 +3122,65 @@ const TOOLS: readonly Tool[] = [
31213122 });
31223123 },
31233124 },
3125 {
3126 name: "request_review",
3127 description:
3128 "Ask the crew to review a person's pull: of the reviewer named (`reviewer`) or, with none, the least busy. The review then runs like an agent pull's, and an approval lets it land. Writers only; an agent's pull is the crew's already.",
3129 inputSchema: {
3130 type: "object",
3131 properties: {
3132 app: APP_ARG,
3133 pull: { type: "integer" },
3134 reviewer: {
3135 type: "string",
3136 description: "A reviewer on the crew, by username; omit for the least busy.",
3137 },
3138 dryRun: {
3139 type: "boolean",
3140 description: "false to apply",
3141 },
3142 },
3143 required: ["app", "pull"],
3144 },
3145 writes: true,
3146 dryByDefault: true,
3147 run(ctx, user, args) {
3148 const repo = planRepo(ctx, user, args);
3149 if (isAnswer(repo)) return repo;
3150 const n = args["pull"];
3151 const pull =
3152 typeof n === "number" && Number.isInteger(n) && n > 0
3153 ? getPull(ctx.app.db, repo.id, n)
3154 : undefined;
3155 if (pull === undefined)
3156 return bad("no_such_pull", `no pull #${String(n)}`);
3157 const dry = args["dryRun"] !== false;
3158 const name = `${repo.ownerName}/${repo.name}#${pull.number}`;
3159 const asked = requestReview(ctx.app, user, repo, pull, str(args["reviewer"]), dry);
3160 if (!asked.ok)
3161 return bad(
3162 asked.error,
3163 asked.error === "not_open"
3164 ? "only an open pull can be reviewed"
3165 : asked.error === "held"
3166 ? "release the hold first; no rule reviews a held pull"
3167 : asked.error === "agent_pull"
3168 ? "the crew already reviews its own pulls"
3169 : asked.error === "no_reviewer"
3170 ? "this crew has no reviewer"
3171 : asked.error === "not_reviewer"
3172 ? "that is not a reviewer on this crew (reviewer)"
3173 : "asking for a review is for a person who can write this app",
3174 );
3175 return good({
3176 says: dry
3177 ? `Would ask ${asked.value.reviewer} to review ${name}. Nothing changed; send dryRun: false to do it.`
3178 : `Asked ${asked.value.reviewer} to review ${name}.`,
3179 reviewer: asked.value.reviewer,
3180 dryRun: dry,
3181 });
3182 },
3183 },
31243184 {
31253185 name: "hold",
31263186 description:
src/http/server.ts +2
@@ -246,6 +246,7 @@ import {
246246 takeBackSubmit,
247247 holdSubmit,
248248 releaseSubmit,
249 reviewRequestSubmit,
249250 composerSubmit,
250251 tellSubmit,
251252 } from "../web/studio/actions.ts";
@@ -1134,6 +1135,7 @@ export function buildRouter(): Router<Handler> {
11341135 router.add("POST", "/:owner/:name/pulls/:number/take-back", takeBackSubmit);
11351136 router.add("POST", "/:owner/:name/pulls/:number/hold", holdSubmit);
11361137 router.add("POST", "/:owner/:name/pulls/:number/release", releaseSubmit);
1138 router.add("POST", "/:owner/:name/pulls/:number/ask-review", reviewRequestSubmit);
11371139 // What an issue waits for: link and unlink, from the issue page.
11381140 router.add(
11391141 "POST",
src/tui/screens/common.ts +4
@@ -867,6 +867,10 @@ const MESSAGES: Record<string, string> = {
867867 // refusal a reviewer can act on, so it names the act rather than the rule.
868868 review_required: "this needs an approval of its current head first",
869869 self_review: "you cannot approve your own change",
870 agent_pull: "the crew already reviews its own changes",
871 no_reviewer: "this crew has no reviewer",
872 not_reviewer: "that is not a reviewer on this crew",
873 held: "release the hold first; no rule reviews a held change",
870874 invalid_state: "that is not a review verdict",
871875 // The fork flow. Each of these leaves the world in a different place, so
872876 // each keeps its own sentence.
src/tui/screens/pull.ts +22
@@ -116,6 +116,7 @@ import { FINISH_REFUSALS, finishConflicts } from "../../actions/finish-conflicts
116116 import { PROPOSE_WHY, proposalOf, proposeResolution } from "../../crew/proposal.ts";
117117 import { conflictScreen } from "./conflicts.ts";
118118 import { reviewScreen } from "./review.ts";
119 import { requestReview } from "../../actions/review_requests.ts";
119120 import { RunList, openRunLog, runTone } from "./runlist.ts";
120121 import { Composer, threadLines, type ThreadEntry } from "./thread.ts";
121122 import { local, localRepo, whereRows, whereStrip } from "./where.ts";
@@ -774,6 +775,7 @@ export function pullScreen(
774775 binding(["c"], tab === 1 ? "review line" : "comment"),
775776 binding(["R"], "review"),
776777 binding(["C"], "check again"),
778 binding(["K"], "ask the crew to review"),
777779 ...(mayVote() ? [binding(["+", "-"], "like/dislike a variant")] : []),
778780 ...(mayApproveHere()
779781 ? [
@@ -992,6 +994,26 @@ export function pullScreen(
992994 review();
993995 return true;
994996 }
997 if (e.key === "K" && mayWrite() && repo !== undefined) {
998 const target = repo;
999 const row = getPull(f.db, target.id, number);
1000 if (row === undefined) return true;
1001 ctx.push(
1002 promptScreen(ctx, screen, {
1003 title: `Ask the crew to review #${number}`,
1004 label: "Reviewer (empty: the least busy)",
1005 hint: "A reviewer's username. Enter asks; Esc cancels.",
1006 onSubmit: (value) => {
1007 const asked = requestReview(f.app, f.user, target, row, value.trim());
1008 if (!asked.ok) return errorText(asked.error);
1009 ctx.toast(`asked ${asked.value.reviewer} to review`, "success");
1010 runAsync(ctx, reload);
1011 return undefined;
1012 },
1013 }),
1014 );
1015 return true;
1016 }
9951017 if (e.key === "A" && mayApproveHere()) {
9961018 approveToRun();
9971019 return true;
src/web/pages/pull.ts +2
@@ -103,6 +103,7 @@ import { specFindings } from "./pull-spec.ts";
103103 import { pullPreviewFindings } from "../../core/preview_findings.ts";
104104 import { crewActivityCard } from "./runs.ts";
105105 import { holdCard } from "../studio/hold.ts";
106 import { askReviewCard } from "../studio/ask_review.ts";
106107 import {
107108 changeHead,
108109 changeTabs,
@@ -936,6 +937,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
936937 </p>
937938 ${when(wall, (w) => wallCard(w))}
938939 ${holdCard(ctx, repo, pull, { act: false })}
940 ${askReviewCard(ctx, repo, pull)}
939941 ${teamsCard(teamVerdicts(ctx.app.db, { ...pull, headOid: status.headOid }))}
940942 ${mergeBox(ctx, repo, pull, status, mayMerge, by, check, isApp, tier, stale)}
941943 <div class="split">
src/web/studio/actions.ts +32
@@ -10,6 +10,7 @@
1010
1111 import { mayView } from "../../core/sealed.ts";
1212 import { holdPull, releasePull } from "../../actions/holds.ts";
13 import { requestReview } from "../../actions/review_requests.ts";
1314 import { addComment } from "../../actions/issues.ts";
1415 import { parseFrom, SENT_WORDS, tell, toldWords, TOO_LONG_WORDS } from "../../actions/tell.ts";
1516 import { contextNote, parseContext } from "../../actions/tell_context.ts";
@@ -383,3 +384,34 @@ export async function releaseSubmit(ctx: Ctx): Promise<Response> {
383384 });
384385 }
385386
387
388 /** POST /:owner/:name/pulls/:number/ask-review { reviewer? } — ask the crew to review this change. */
389 export async function reviewRequestSubmit(ctx: Ctx): Promise<Response> {
390 const repo = loadRepo(ctx);
391 if (!repo) return notFoundPage(ctx);
392 if (!ctx.auth.user) return signInFirst(ctx);
393 const form = await readForm(ctx, "rw");
394 if (form instanceof Response) return form;
395 const found = heldPull(ctx, repo);
396 if (!found) return notFoundPage(ctx);
397 const asked = requestReview(ctx.app, ctx.auth.user, repo, found.pull, field(form, "reviewer"));
398 if (!asked.ok && (asked.error === "not_found" || asked.error === "forbidden"))
399 return notFoundPage(ctx);
400 return flashTo(ctx, `${changeHref(repoBase(repo), found.pull.number)}#review`, {
401 ...(asked.ok
402 ? { message: "Asked. The crew reads it and says what it finds." }
403 : {
404 tone: "danger" as const,
405 message:
406 asked.error === "no_reviewer"
407 ? "This repository's crew has no reviewer."
408 : asked.error === "not_reviewer"
409 ? "That is not a reviewer on this crew."
410 : asked.error === "held"
411 ? "Release the hold first; no rule reviews a held change."
412 : asked.error === "agent_pull"
413 ? "The crew already reviews its own changes."
414 : "Only an open change can be reviewed.",
415 }),
416 });
417 }
src/web/studio/ask_review.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * "Ask the crew to review", on a person's pull (`core/review_requests.ts`).
3 * A person who writes the repository names a reviewer or leaves it to the
4 * least busy; once asked, the card says so. Posts to
5 * `/pulls/:number/ask-review` (`reviewRequestSubmit`).
6 */
7
8 import { getReviewRequest } from "../../core/review_requests.ts";
9 import type { Pull } from "../../core/pulls.ts";
10 import { canWrite, type Repo } from "../../core/repos.ts";
11 import { reviewersOf } from "../../crew/review.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { repoBase } from "../chrome.ts";
14 import { html, when, type Html } from "../html.ts";
15 import { btn, card, icon, selectField, time } from "../ui.ts";
16
17 export function askReviewCard(ctx: Ctx, repo: Repo, pull: Pull): Html | null {
18 const user = ctx.auth.user;
19 if (pull.authorIsAgent || pull.state !== "open" || pull.mergedAt !== null) return null;
20 if (user === undefined || user.kind !== "user" || !canWrite(ctx.app.db, repo, user)) return null;
21 const crew = reviewersOf(ctx.app.db, repo.id);
22 if (crew.length === 0) return null;
23 const asked = getReviewRequest(ctx.app.db, pull.id);
24 const named = crew.find((r) => r.user.id === asked?.reviewerId)?.user.username;
25 return card(
26 html`${when(
27 asked !== undefined,
28 () =>
29 html`<p class="muted small">
30 Asked ${named ?? "the crew"} to review, ${time(asked!.requestedAt)}.
31 </p>`,
32 )}
33 <form
34 method="post"
35 action="${repoBase(repo)}/pulls/${pull.number}/ask-review"
36 class="edit-row mt"
37 >
38 ${selectField({
39 label: "Reviewer",
40 name: "reviewer",
41 options: [
42 { value: "", label: "Least busy reviewer", selected: named === undefined },
43 ...crew.map((r) => ({
44 value: r.user.username,
45 label: r.user.username,
46 selected: r.user.username === named,
47 })),
48 ],
49 })}
50 ${btn(asked === undefined ? "Ask the crew to review" : "Ask again", { size: "sm" })}
51 </form>`,
52 { id: "review", head: html`${icon("user")}<h2>Crew review</h2>` },
53 );
54 }
test/mcp.test.ts +1
@@ -243,6 +243,7 @@ describe("the forge over MCP", () => {
243243 "labels",
244244 "wait_for",
245245 "attach_look",
246 "request_review",
246247 "hold",
247248 "plan",
248249 "access",
test/review-request.test.ts added +312
@@ -0,0 +1,312 @@
1 /**
2 * A person asks the crew to review their pull (#4568): the ask records, the
3 * review runs as an agent pull's does, the reviewer's approval lets
4 * landIfGreen land it. An @mention of a reviewer asks the same.
5 */
6 import { afterAll, beforeAll, describe, 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 { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { mentionedReviewer, requestReview } from "../src/actions/review_requests.ts";
15 import { setCrewRole } from "../src/core/agents.ts";
16 import { getPull, type Pull } from "../src/core/pulls.ts";
17 import { getRepoById, type Repo } from "../src/core/repos.ts";
18 import { submitReview } from "../src/core/reviews.ts";
19 import { claimRun, createRun, finishRun, listRuns } from "../src/core/runs.ts";
20 import { createUser, getUserByName, type User } from "../src/core/users.ts";
21 import { landIfGreen } from "../src/crew/autonomy.ts";
22 import { addComment } from "../src/actions/issues.ts";
23 import { startCrew } from "../src/crew/dispatch.ts";
24 import { createToken } from "../src/core/tokens.ts";
25 import { getReviewRequest } from "../src/core/review_requests.ts";
26 import { serve, type Servers } from "../src/http/server.ts";
27 import { createForgeApp } from "../src/tui/forge.ts";
28 import { pullScreen } from "../src/tui/screens/pull.ts";
29 import { local } from "../src/tui/screens/where.ts";
30 import { headlessTerminal } from "../src/tui/term/terminal.ts";
31 import { settleApp } from "./helpers/tui.ts";
32 import { sweepReviews, waitsForReviewer } from "../src/crew/review.ts";
33
34 describe("asking the crew to review", () => {
35 let dataDir: string;
36 let app: App;
37 let alice: User;
38 let mason: User;
39 let quill: User;
40 let repo: Repo;
41 const fresh = () => getRepoById(app.db, repo.id)!;
42 const reviewRuns = (pull: Pull) =>
43 listRuns(app.db, repo.id, { issueId: pull.id }).filter((r) => r.reason === "review");
44
45 beforeAll(async () => {
46 dataDir = await mkdtemp(join(tmpdir(), "forge-review-request-"));
47 app = createApp({ dataDir, port: 0 });
48 const a = await createUser(app.db, {
49 origin: "seed",
50 trusted: true,
51 username: "alice",
52 email: "[email protected]",
53 password: "a-good-passphrase",
54 adminIfFirst: true,
55 });
56 if (!a.ok) throw new Error(a.error);
57 alice = a.value;
58 const made = await createRepo(app, alice, { name: "engine", visibility: "private" });
59 if (!made.ok) throw new Error(String(made.error));
60 repo = made.value;
61 const seeded = await commitToBranch(app, alice, repo, {
62 message: "Start",
63 files: [{ path: "README.md", content: "# engine\n" }],
64 });
65 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
66 for (const name of ["mason", "quill"]) {
67 const agent = await createAgent(app, alice, { username: name });
68 if (!agent.ok) throw new Error(String(agent.error));
69 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
70 }
71 mason = getUserByName(app.db, "mason")!;
72 quill = getUserByName(app.db, "quill")!;
73 });
74
75 afterAll(async () => {
76 await app.close?.();
77 await rm(dataDir, { recursive: true, force: true });
78 });
79
80 async function greenPull(name: string): Promise<Pull> {
81 const branch = await commitToBranch(app, alice, repo, {
82 branch: `feature/${name}`,
83 base: "main",
84 message: name,
85 files: [{ path: `${name}.ts`, content: `export const n = "${name}";\n` }],
86 });
87 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
88 const opened = await openPull(app, alice, repo, {
89 title: name,
90 baseBranch: "main",
91 headBranch: `feature/${name}`,
92 });
93 if (!opened.ok) throw new Error(String(opened.error));
94 const pull = getPull(app.db, repo.id, opened.value.number)!;
95 const check = createRun(app.db, {
96 repoId: repo.id,
97 kind: "check",
98 issueId: pull.id,
99 env: `pull-${pull.number}`,
100 commitOid: pull.headOid,
101 reason: "pull",
102 });
103 claimRun(app.db, check.id);
104 finishRun(app.db, check.id, { state: "ok", summary: "check passed" });
105 return pull;
106 }
107
108 test("a pull nobody asked about is not swept to review; a reader or an agent cannot ask", async () => {
109 setCrewRole(app.db, repo.id, quill.id, "reviewer");
110 const pull = await greenPull("quiet");
111 await sweepReviews(app);
112 expect(reviewRuns(pull)).toHaveLength(0);
113 expect(requestReview(app, undefined, fresh(), pull).ok).toBe(false);
114 const byAgent = requestReview(app, mason, fresh(), pull);
115 expect(byAgent.ok ? "" : byAgent.error).toBe("forbidden");
116 const stranger = await createUser(app.db, {
117 origin: "seed",
118 trusted: true,
119 username: "eve",
120 email: "[email protected]",
121 password: "a-good-passphrase",
122 });
123 if (!stranger.ok) throw new Error(stranger.error);
124 const refused = requestReview(app, stranger.value, fresh(), pull);
125 expect(refused.ok).toBe(false);
126 });
127
128 test("a named reviewer must be on the crew's reviewers", async () => {
129 const pull = await greenPull("named");
130 const bad = requestReview(app, alice, fresh(), pull, "mason");
131 expect(bad.ok ? "" : bad.error).toBe("not_reviewer");
132 expect(reviewRuns(pull)).toHaveLength(0);
133 });
134
135 test("a requested review runs, the approval lands the pull", async () => {
136 const pull = await greenPull("landed");
137 // Assisted repository: a green person's pull is not sent on its own.
138 expect(await landIfGreen(app, fresh(), pull)).toBe(false);
139 const asked = requestReview(app, alice, fresh(), pull, "quill");
140 expect(asked.ok).toBe(true);
141 await Bun.sleep(50);
142 expect(reviewRuns(pull)).toHaveLength(1);
143 expect(reviewRuns(pull)[0]!.actorId).toBe(quill.id);
144 expect(waitsForReviewer(app.db, repo.id, pull)).toBe("quill");
145
146 submitReview(app.db, {
147 issueId: pull.id,
148 authorId: quill.id,
149 state: "approved",
150 commitOid: pull.headOid,
151 });
152 app.db
153 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
154 .run(repo.id, alice.id);
155 expect(await landIfGreen(app, fresh(), pull)).toBe(true);
156 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).not.toBeNull();
157 });
158
159 test("without a name the least busy reviewer is asked", async () => {
160 app.db
161 .query("UPDATE repo SET autonomy = 'assisted', autonomy_by = NULL WHERE id = ?1")
162 .run(repo.id);
163 setCrewRole(app.db, repo.id, mason.id, "reviewer");
164 // Quill is busy with one queued run; mason has none.
165 const busy = await greenPull("busy");
166 expect(requestReview(app, alice, fresh(), busy, "quill").ok).toBe(true);
167 await Bun.sleep(50);
168 const pull = await greenPull("free");
169 expect(requestReview(app, alice, fresh(), pull).ok).toBe(true);
170 await Bun.sleep(50);
171 expect(reviewRuns(pull)[0]!.actorId).toBe(mason.id);
172 });
173
174 test("an @mention of a reviewer names it; others and non-reviewers are not", () => {
175 expect(mentionedReviewer(app, fresh(), "could you look, @quill?")).toBe("quill");
176 expect(mentionedReviewer(app, fresh(), "mail [email protected]")).toBeUndefined();
177 expect(mentionedReviewer(app, fresh(), "@nobody please")).toBeUndefined();
178 });
179
180 test("a person's @mention in a pull comment asks that reviewer", async () => {
181 const crew = await startCrew(app, {
182 forgeUrl: "http://127.0.0.1:1",
183 localUrl: "http://127.0.0.1:1",
184 binary: "/nonexistent/claude",
185 concurrency: 0,
186 budgetUsd: 1,
187 runTimeoutMs: 60_000,
188 });
189 try {
190 const pull = await greenPull("mentioned");
191 const said = addComment(app, alice, fresh(), pull, "@quill please review this");
192 expect(said.ok).toBe(true);
193 await Bun.sleep(200);
194 expect(reviewRuns(pull)).toHaveLength(1);
195 expect(reviewRuns(pull)[0]!.actorId).toBe(quill.id);
196 } finally {
197 await crew.stop();
198 }
199 });
200
201 test("a second mention of the same reviewer does not ask again or move the clock", async () => {
202 const crew = await startCrew(app, {
203 forgeUrl: "http://127.0.0.1:1",
204 localUrl: "http://127.0.0.1:1",
205 binary: "/nonexistent/claude",
206 concurrency: 0,
207 budgetUsd: 1,
208 runTimeoutMs: 60_000,
209 });
210 try {
211 const pull = await greenPull("thanked");
212 addComment(app, alice, fresh(), pull, "@quill please review this");
213 await Bun.sleep(100);
214 const first = getReviewRequest(app.db, pull.id)!;
215 expect(first.reviewerId).toBe(quill.id);
216 await Bun.sleep(20);
217 addComment(app, alice, fresh(), pull, "thanks @quill");
218 await Bun.sleep(100);
219 expect(getReviewRequest(app.db, pull.id)!.requestedAt).toBe(first.requestedAt);
220 expect(reviewRuns(pull)).toHaveLength(1);
221 // Naming the other reviewer is a new ask.
222 addComment(app, alice, fresh(), pull, "@mason you too");
223 await Bun.sleep(100);
224 expect(getReviewRequest(app.db, pull.id)!.reviewerId).toBe(mason.id);
225 } finally {
226 await crew.stop();
227 }
228 });
229
230 test("the API, the MCP tool and the terminal ask the same way, and say who was asked", async () => {
231 const servers: Servers = await serve(app);
232 try {
233 const rw = createToken(app.db, alice.id, "t", "rw").token;
234 const ro = createToken(app.db, alice.id, "r", "ro").token;
235 const mcp = async (args: Record<string, unknown>, token = rw) => {
236 const res = await fetch(`${servers.url}/mcp`, {
237 method: "POST",
238 headers: {
239 "content-type": "application/json",
240 accept: "application/json, text/event-stream",
241 authorization: `Bearer ${token}`,
242 },
243 body: JSON.stringify({
244 jsonrpc: "2.0",
245 id: 1,
246 method: "tools/call",
247 params: { name: "request_review", arguments: args },
248 }),
249 });
250 const body = (await res.json()) as any;
251 const text: string = body.result.content[0].text;
252 return body.result.isError === true ? { error: text, value: undefined } : { error: undefined, value: JSON.parse(text) };
253 };
254
255 // API: the resolved username, not the raw input.
256 const viaApi = await greenPull("by-api");
257 const res = await fetch(
258 `${servers.url}/api/v1/repos/alice/engine/pulls/${viaApi.number}/review-requests`,
259 {
260 method: "POST",
261 headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" },
262 body: JSON.stringify({ reviewer: "@Quill" }),
263 },
264 );
265 expect(res.status).toBe(201);
266 expect(((await res.json()) as any).reviewer).toBe("quill");
267 const unnamed = await greenPull("by-api-unnamed");
268 const res2 = await fetch(
269 `${servers.url}/api/v1/repos/alice/engine/pulls/${unnamed.number}/review-requests`,
270 { method: "POST", headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" }, body: "{}" },
271 );
272 expect(typeof ((await res2.json()) as any).reviewer).toBe("string");
273
274 // MCP: a plan by default, a read-only token may plan, the ask on dryRun: false.
275 const viaMcp = await greenPull("by-mcp");
276 const args = { app: "alice/engine", pull: viaMcp.number, reviewer: "mason" };
277 const planned = await mcp(args, ro);
278 expect(planned.value.says).toContain("Would ask mason");
279 expect(getReviewRequest(app.db, viaMcp.id)).toBeUndefined();
280 expect((await mcp({ ...args, reviewer: "nobody" })).error).toContain("not_reviewer");
281 expect((await mcp({ ...args, pull: 999 })).error).toContain("no_such_pull");
282 const done = await mcp({ ...args, dryRun: false });
283 expect(done.value.says).toBe(`Asked mason to review alice/engine#${viaMcp.number}.`);
284 expect(getReviewRequest(app.db, viaMcp.id)!.reviewerId).toBe(mason.id);
285
286 // Terminal: K, a reviewer's name, Enter.
287 const viaTui = await greenPull("by-tui");
288 const { app: tui, session } = createForgeApp(
289 app,
290 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:alice", user: alice },
291 { terminal: headlessTerminal(160, 44), exitHooks: false },
292 );
293 tui.start();
294 try {
295 tui.ctx.push(pullScreen(session, tui.ctx, local(session, repo), viaTui.number));
296 await settleApp(tui);
297 const press = (key: string) =>
298 tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
299 press("K");
300 await settleApp(tui);
301 for (const ch of "quill") press(ch);
302 press("enter");
303 await settleApp(tui);
304 expect(getReviewRequest(app.db, viaTui.id)!.reviewerId).toBe(quill.id);
305 } finally {
306 tui.stop?.();
307 }
308 } finally {
309 servers.stop();
310 }
311 });
312 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs