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

The pull page shows a reviewer the Approve and Request changes buttons and no Merge, and the pull tool says the same #12706

Merged opened this

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

Merged

scout/forge:scout/12631-the-pull-page-shows-a-reviewer-the-appro → main 8 commits fork 2 threads · 2 unresolved

  • Merged. scout/12631-the-pull-page-shows-a-reviewer-the-appro was merged into main as 287c6b5.

Review

Sign in to review this change.
8 files changed +261 −14
docs/features/team-roles.md +14
@@ -26,3 +26,17 @@ crew, as before.
2626
2727 Every change of role is told on the outbox as `team.member_role_set`, with
2828 who made it, the member, and the role before and after.
29
30 ## A reviewer judges; a writer lands
31
32 A person who is a `reviewer` on a team of the organization, even a read
33 team, passes verdicts on its pulls but does not merge them (#12631):
34
35 - **Page:** the pull's review card offers Approve and Request changes; the
36 merge box shows no Merge button and says "You can review; a writer lands it."
37 - **MCP:** `review { repo, number, verdict: "approve" | "changes" }` is taken;
38 `merge` is refused as `forbidden` with "You can review; a writer lands it."
39 - **Terminal:** on the pull's screen `R` opens the review card; the hints show
40 `m` disabled, with "You can review; a writer lands it."
41
42 A plain reader still only comments, and a writer still merges as before.
src/actions/review_words.ts +2
@@ -10,6 +10,8 @@ export const reviewWords = {
1010 tooLong: "That review is too long (64 KB at most).",
1111 /** `forbidden`: a reader cannot pass a verdict that gates a merge. */
1212 forbidden: "A verdict that gates a merge needs write access.",
13 /** A team reviewer (`canVerdict`, not a writer): may judge, may not land (#12631). */
14 reviewerLands: "You can review; a writer lands it.",
1315 /** `looks_required`: a stylesheet change is approved beside the home page's looks. */
1416 looksRequired:
1517 "This pull changes a stylesheet: wait for its preview's phone and desktop looks of the home page (beside main's on the pull page), then approve.",
src/core/following.ts +7 −5
@@ -476,16 +476,18 @@ export async function refreshPullHead(
476476 : await fetchInto(baseDir, headDir, `refs/heads/${pull.headBranch}`);
477477 if (tip === undefined) return undefined;
478478 await writeRef(snapshotDir, `refs/pull/${pull.number}/head`, tip);
479 // The row says where the head is too, so a reader of the pull — the API,
480 // a page — sees the same tip the ref holds. Written with the ref, before
481 // any await: a refresh that reads the ref as current between the two
482 // would otherwise answer from a row still naming the old head.
483 forge.db
484 .query("UPDATE pull SET head_oid = ?2 WHERE issue_id = ?1")
485 .run(pull.id, tip);
479486 // A rebase onto a moved base changes no line: its approval stands.
480487 if (!apart) {
481488 const baseNow = await resolveOid(baseDir, `refs/heads/${pull.baseBranch}`);
482489 if (baseNow !== undefined) await carryApproval(forge.db, baseDir, pull, baseNow, tip);
483490 }
484 // The row says where the head is too, so a reader of the pull — the API,
485 // a page — sees the same tip the ref holds.
486 forge.db
487 .query("UPDATE pull SET head_oid = ?2 WHERE issue_id = ?1")
488 .run(pull.id, tip);
489491 // A kept fork's pull is combined with main on our side (#9012).
490492 if (!apart && fromKeptFork(forge.db, pull)) {
491493 const baseTip = await resolveOid(baseDir, `refs/heads/${pull.baseBranch}`);
src/http/mcp/tools/merge.ts +6 −1
@@ -2,6 +2,8 @@ import { mayView } from "../../../core/sealed.ts";
22 import { mergePull } from "../../../actions/pulls.ts";
33 import { getPull, pullDir, pullMergeState } from "../../../core/pulls.ts";
44 import { checkSummary } from "../../../core/runs.ts";
5 import { canVerdict } from "../../../core/verdict.ts";
6 import { reviewWords } from "../../../actions/review_words.ts";
57 import { mergeFailure } from "../../../web/pages/pull.ts";
68 import { LAND_AS_IS, stalledWords } from "../../../web/studio/land_as_is.ts";
79 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
@@ -80,7 +82,10 @@ export const tool: Tool = {
8082 : error === "unauthorized"
8183 ? "forbidden"
8284 : error;
83 return bad(code, mergeFailure(error));
85 // A team reviewer judges and does not land: the page's words (#12631).
86 const words =
87 code === "forbidden" && canVerdict(ctx.app.db, repo, user) ? reviewWords.reviewerLands : mergeFailure(error);
88 return bad(code, words);
8489 }
8590 return good({
8691 dryRun: false,
src/http/mcp/tools/review.ts +1 −1
@@ -7,7 +7,7 @@ import { good, bad, type Tool, str, REPO_ARG, repoArg, isAnswer } from "../share
77
88 export const tool: Tool = {
99 name: "review",
10 doc: "`{ repo, number, verdict, reason? }`: approve a pull (`approve`) or request changes (`changes`, with a `reason`), as the page does; a writer's or the crew's, and never your own pull",
10 doc: "`{ repo, number, verdict, reason? }`: approve a pull (`approve`) or request changes (`changes`, with a `reason`), as the page does; a writer's, the crew's or a team reviewer's, and never your own pull",
1111 description:
1212 "Approve a pull, or request changes (`reason` required); your own pull is refused.",
1313 inputSchema: {
src/tui/screens/pull.ts +15 −2
@@ -80,6 +80,8 @@ import { getPull, pullDir, variantSiblings, type MergePullError, type Pull } fro
8080 import { voteVariant } from "../../actions/variants.ts";
8181 import { costLineFor } from "../../core/ledger_rollup.ts";
8282 import { getRepoById, type Repo } from "../../core/repos.ts";
83 import { canVerdict } from "../../core/verdict.ts";
84 import { reviewWords } from "../../actions/review_words.ts";
8385 import { verdictOf, type Verdict } from "../../web/pages/pull-verdict.ts";
8486 import { wallOf, wallPlain, type Wall } from "../../contract/policy.ts";
8587 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
@@ -320,6 +322,12 @@ export function pullScreen(
320322 /** Agent runs about this pull, newest first. */
321323 const crew = new RunList(f);
322324 const mayWrite = (): boolean => src.capabilities.write && repo !== undefined;
325 /**
326 * A team reviewer (#12631): may pass a verdict (`R`), may not land. The
327 * page's rule, `canVerdict`; `submitReview` and `mergePull` hold the gates.
328 */
329 const mayJudge = (): boolean =>
330 !mayWrite() && repo !== undefined && f.user !== undefined && canVerdict(f.db, repo, f.user);
323331 /** The hold that stands on this pull; undefined when none does. */
324332 let hold: Hold | undefined;
325333 /** What this pull cost (#12114), or "" when none or not for this viewer. */
@@ -1185,7 +1193,12 @@ export function pullScreen(
11851193 ]
11861194 : [binding(["x"], "close")]),
11871195 ]
1188 : liveBindings(src)),
1196 : [
1197 ...liveBindings(src),
1198 ...(mayJudge()
1199 ? [binding(["R"], "review"), binding(["m"], reviewWords.reviewerLands, { disabled: true })]
1200 : []),
1201 ]),
11891202 binding(["r"], "refresh"),
11901203 ];
11911204 },
@@ -1396,7 +1409,7 @@ export function pullScreen(
13961409 landPast();
13971410 return true;
13981411 }
1399 if (e.key === "R" && mayWrite()) {
1412 if (e.key === "R" && (mayWrite() || mayJudge())) {
14001413 review();
14011414 return true;
14021415 }
src/web/pages/pull.ts +10 −5
@@ -63,6 +63,7 @@ import {
6363 } from "../../core/reviews.ts";
6464 import { getUsersByIds } from "../../core/users.ts";
6565 import { canAdmin, canWrite, getRepoById, type Repo } from "../../core/repos.ts";
66 import { canVerdict } from "../../core/verdict.ts";
6667 import { bypassOffered, landPastGate, type BypassError } from "../../checks/bypass.ts";
6768 import { commitLog, readerFor } from "../../git/read.ts";
6869 import { wallOf } from "../../contract/policy.ts";
@@ -772,7 +773,9 @@ function mergeBox(
772773 icon: "merge",
773774 })}
774775 </form>`
775 : html`<span class="muted small">You need write access to merge.</span>`,
776 : ctx.auth.user !== undefined && canVerdict(ctx.app.db, repo, ctx.auth.user)
outdated

Principle 1: the card (data-reviewer-lands) and this merge box both say the same sentence on one page, so it explains itself twice. Keep it in one place.

777 ? html`<span class="muted small" data-reviewer-lands>${reviewWords.reviewerLands}</span>`
778 : html`<span class="muted small">You need write access to merge.</span>`,
776779 );
777780 }
778781
@@ -864,14 +867,16 @@ function reviewCard(ctx: Ctx, repo: Repo, pull: Pull, action: string): Html {
864867 <h2>Review</h2>`,
865868 });
866869 if (pull.mergedAt !== null || pull.state === "closed") return html``;
867 const writer = canWrite(ctx.app.db, repo, user);
870 // A team reviewer passes a verdict without write access (`canVerdict`);
871 // the merge box says they do not land it.
872 const judge = canVerdict(ctx.app.db, repo, user);
868873 const isAuthor = pull.authorId === user.id;
869874 const options: { value: string; label: string; hint: string; key: string }[] =
870875 [];
871876 // A reader's change runs nothing here until a writer approves it: the
872877 // approval is also what lets its code run, and the reviewer should know.
873878 const runsOnApproval = !pullMayRun(ctx.app.db, repo, pull, "");
874 if (writer && !isAuthor)
879 if (judge && !isAuthor)
875880 options.push({
876881 value: "approved",
877882 label: "Approve",
@@ -880,7 +885,7 @@ function reviewCard(ctx: Ctx, repo: Repo, pull: Pull, action: string): Html {
880885 : "This is good to merge.",
881886 key: "v a",
882887 });
883 if (writer)
888 if (judge)
884889 options.push({
885890 value: "changes_requested",
886891 label: "Request changes",
@@ -933,7 +938,7 @@ function reviewCard(ctx: Ctx, repo: Repo, pull: Pull, action: string): Html {
933938 >`,
934939 )}
935940 ${when(
936 !writer,
941 !judge,
937942 () =>
938943 html`<span class="muted small"
939944 >${icon("alert")} ${reviewWords.forbidden}</span
test/reviewer-lands.test.ts added +206
@@ -0,0 +1,206 @@
1 /**
2 * A team reviewer judges and does not land (#12631): the pull page shows
3 * them Approve and Request changes and no Merge, with the one line that
4 * says why; MCP's `review` takes their verdict and `merge` refuses them in
5 * the same words. A plain reader still sees neither verdict nor that line.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { getUserByName } from "../src/core/users.ts";
15 import { reviewWords } from "../src/actions/review_words.ts";
16 import { seedAdmin } from "./helpers/admin.ts";
17 import { tokenFor } from "./helpers/tokens.ts";
18 import { mcpTool } from "./helpers/mcp.ts";
19 import { getRepo } from "../src/core/repos.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { pullScreen } from "../src/tui/screens/pull.ts";
22 import { local } from "../src/tui/screens/where.ts";
23 import { headlessTerminal } from "../src/tui/term/terminal.ts";
24 import { settleApp, settleUntil } from "./helpers/tui.ts";
25
26 const PASSWORD = "reviewer-lands-pass";
27
28 describe("a team reviewer reviews and a writer lands", () => {
29 let dataDir: string;
30 let app: App;
31 let servers: Servers;
32 let number = 0;
33 const tokens: Record<string, string> = {};
34
35 const as = (who: string, method: string, path: string, payload?: unknown) =>
36 fetch(`${servers.url}${path}`, {
37 method,
38 headers: {
39 authorization: `Bearer ${tokens[who]}`,
40 ...(payload === undefined ? {} : { "content-type": "application/json" }),
41 },
42 ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
43 });
44
45 const page = async (who: string): Promise<string> => {
46 const user = getUserByName(app.db, who)!;
47 const res = await fetch(`${servers.url}/acme/lib/pulls/${number}/files`, {
48 headers: { cookie: `forge_session=${createSession(app.db, user.id).token}` },
49 });
50 expect(res.status).toBe(200);
51 return res.text();
52 };
53
54 beforeAll(async () => {
55 dataDir = await mkdtemp(join(tmpdir(), "forge-rl-"));
56 app = createApp({ dataDir, port: 0 });
57 servers = await serve(app);
58 await seedAdmin(app, { username: "ada", email: "[email protected]", password: PASSWORD });
59 tokens["ada"] = tokenFor(app, "ada", "admin");
60 for (const who of ["bob", "cas", "dee"]) {
61 await fetch(`${servers.url}/api/v1/users`, {
62 method: "POST",
63 headers: { "content-type": "application/json" },
64 body: JSON.stringify({ username: who, email: `${who}@f.dev`, password: PASSWORD }),
65 });
66 tokens[who] = tokenFor(app, who, "admin");
67 }
68 const ok = async (r: Promise<Response>) => expect((await r).status).toBe(201);
69 await ok(as("ada", "POST", "/api/v1/orgs", { name: "acme" }));
70 await ok(as("ada", "POST", "/api/v1/orgs/acme/teams", { name: "devs", permission: "write" }));
71 await ok(as("ada", "POST", "/api/v1/orgs/acme/teams/devs/members", { user: "bob" }));
72 await ok(as("ada", "POST", "/api/v1/orgs/acme/teams", { name: "judges", permission: "read" }));
73 await ok(as("ada", "POST", "/api/v1/orgs/acme/teams/judges/members", { user: "dee", role: "reviewer" }));
74 await ok(as("ada", "POST", "/api/v1/repos", { owner: "acme", name: "lib", visibility: "public" }));
75 await ok(
76 as("ada", "POST", "/api/v1/repos/acme/lib/edits", {
77 branch: "main",
78 message: "init",
79 files: [{ path: "a.txt", content: "one\n" }],
80 }),
81 );
82 const edit = await as("bob", "POST", "/api/v1/repos/acme/lib/edits", {
83 newBranch: "judged",
84 base: "main",
85 message: "judged work",
86 files: [{ path: "a.txt", content: "two\n" }],
87 openPull: { title: "judged work" },
88 });
89 expect(edit.status).toBe(201);
90 number = ((await edit.json()) as { pull: { number: number } }).pull.number;
91 });
92
93 afterAll(async () => {
94 servers.stop();
95 app.close();
96 await rm(dataDir, { recursive: true, force: true });
97 });
98
99 test("the page shows a team reviewer Approve and Request changes, no Merge, and says why", async () => {
100 const body = await page("dee");
101 expect(body).toContain('value="approved"');
102 expect(body).toContain('value="changes_requested"');
103 expect(body).not.toContain("Merge pull request");
104 // Said once, in the merge box where Merge would stand.
outdated

This assertion is satisfied by the review-card line alone, so it would still pass if the merge box change were reverted. Assert the merge box separately (e.g. occurrence count or the muted span in the merge box).

105 const said = reviewWords.reviewerLands.replace("'", "&#39;");
106 expect(body.split(said).length - 1).toBe(1);
107 expect(body).toContain(`<span class="muted small" data-reviewer-lands>${said}</span>`);
108 expect(body).not.toContain("You need write access to merge.");
109 expect(body).not.toContain(reviewWords.forbidden);
110 });
111
112 test("a plain reader sees only Comment, and not the reviewer's line", async () => {
113 const body = await page("cas");
114 expect(body).not.toContain('value="approved"');
115 expect(body).not.toContain('value="changes_requested"');
116 expect(body).toContain(reviewWords.forbidden);
117 expect(body).not.toContain("data-reviewer-lands");
118 });
119
120 test("a writer sees the verdicts and not the reviewer's line", async () => {
121 const body = await page("ada");
122 expect(body).toContain('value="changes_requested"');
123 expect(body).not.toContain("data-reviewer-lands");
124 });
125
126 test("the terminal offers a team reviewer R and says why m is not theirs; a plain reader gets neither", async () => {
127 const lib = getRepo(app.db, "acme", "lib")!;
128 const screenOf = async (who: string): Promise<string> => {
129 const user = getUserByName(app.db, who)!;
130 const { app: tui, session } = createForgeApp(
131 app,
132 { sshUsername: who, remoteAddress: "127.0.0.1", fingerprint: `SHA256:${who}`, user },
133 { terminal: headlessTerminal(200, 50), exitHooks: false },
134 );
135 tui.start();
136 try {
137 tui.ctx.push(pullScreen(session, tui.ctx, local(session, lib), number));
138 await settleUntil(tui, "refresh", { timeoutMs: 10_000 });
139 if (who === "dee") {
140 tui.dispatch({ type: "key", key: "R", ctrl: false, alt: false, shift: true });
141 await settleApp(tui);
142 }
143 return tui.screen.toText();
144 } finally {
145 tui.stop();
146 }
147 };
148 expect(await screenOf("dee")).toContain(`Review #${number}`);
149 const reader = await screenOf("cas");
150 expect(reader).not.toContain(reviewWords.reviewerLands);
151 }, 30_000);
152
153 test("the terminal's hints name the reviewer's line", async () => {
154 const lib = getRepo(app.db, "acme", "lib")!;
155 const user = getUserByName(app.db, "dee")!;
156 const { app: tui, session } = createForgeApp(
157 app,
158 { sshUsername: "dee", remoteAddress: "127.0.0.1", fingerprint: "SHA256:dee", user },
159 { terminal: headlessTerminal(240, 50), exitHooks: false },
160 );
161 tui.start();
162 try {
163 tui.ctx.push(pullScreen(session, tui.ctx, local(session, lib), number));
164 await settleUntil(tui, reviewWords.reviewerLands, { timeoutMs: 10_000 });
165 } finally {
166 tui.stop();
167 }
168 }, 30_000);
169
170 test("MCP takes the team reviewer's verdict and refuses their merge in the page's words", async () => {
171 const asked = await mcpTool(servers.url, tokens["dee"]!, "review", {
172 repo: "acme/lib",
173 number,
174 verdict: "changes",
175 reason: "one more pass",
176 });
177 expect(asked.value?.says).toBe("Changes requested.");
178 const approved = await mcpTool(servers.url, tokens["dee"]!, "review", {
179 repo: "acme/lib",
180 number,
181 verdict: "approve",
182 });
183 expect(approved.value?.says).toBe("Approved.");
184
185 const merge = await mcpTool(servers.url, tokens["dee"]!, "merge", {
186 repo: "acme/lib",
187 number,
188 dryRun: false,
189 });
190 expect(merge.error).toContain(reviewWords.reviewerLands);
191
192 // A plain reader's verdict is still refused, and their merge keeps its words.
193 const reader = await mcpTool(servers.url, tokens["cas"]!, "review", {
194 repo: "acme/lib",
195 number,
196 verdict: "approve",
197 });
198 expect(reader.error).toContain(reviewWords.forbidden);
199 const readerMerge = await mcpTool(servers.url, tokens["cas"]!, "merge", {
200 repo: "acme/lib",
201 number,
202 dryRun: false,
203 });
204 expect(readerMerge.error).not.toContain(reviewWords.reviewerLands);
205 });
206 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs