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

Pulls say who wrote them and whether you may review (#16436) #16437

Merged opened this

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

Merged

fix/pulls-say-who → main 0 commits

  • Merged. fix/pulls-say-who was merged into main as 0b45754.

Review

Sign in to review this change.
4 files changed +329 −2
src/http/mcp/pull_people.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * Who a pull is by, and what the asker may do about it (#16436), so an agent reading a list cannot
3 * call someone else's pull "yours" or offer a review the asker cannot give. A mirrored pull's
4 * author is the origin's login (`originAuthor`), never the account that connected the mirror;
5 * whether the asker may review it is the origin's question, answered here from what it last said of
6 * this account (`canPush`) and the connection being theirs.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { getOriginRepo, originForRepo } from "../../core/origins.ts";
11 import type { Pull } from "../../core/pulls.ts";
12 import { canWrite, type Repo } from "../../core/repos.ts";
13 import type { User } from "../../core/users.ts";
14
15 export interface PullPeople {
16 /** Who wrote it: the local account, or `login` at the origin's host for a mirrored pull. */
17 readonly author: string;
18 /** Whether the asker wrote it. */
19 readonly yours: boolean;
20 /**
21 * Whether the asker's review would count where the pull lands: a writer there, not its author.
22 */
23 readonly youMayReview: boolean;
24 }
25
26 /** One repository's answer for each of its pulls: the mirror link is read once. */
27 export function pullPeopleIn(
28 db: Database,
29 repo: Repo,
30 user: User,
31 ): (pull: Pull) => PullPeople {
32 const link = originForRepo(db, repo.id);
33 if (link === undefined) {
34 const writes = canWrite(db, repo, user);
35 return (pull) => {
36 const yours = pull.authorId === user.id;
37 return { author: pull.authorName, yours, youMayReview: writes && !yours };
38 };
39 }
40 const host = hostOf(link.origin.webUrl);
41 const mine = link.origin.userId === user.id;
42 const login = mine ? link.origin.login.toLowerCase() : undefined;
43 const pushes =
44 mine && getOriginRepo(db, link.origin.id, link.fullName)?.canPush === true;
45 return (pull) => {
46 const by = pull.originAuthor ?? pull.authorName;
47 const yours = login !== undefined && by.toLowerCase() === login;
48 return {
49 author: host === "" ? by : `${by} on ${host}`,
50 yours,
51 youMayReview: pushes && !yours,
52 };
53 };
54 }
55
56 const hostOf = (url: string): string => {
57 try {
58 return new URL(url).host;
59 } catch {
60 return "";
61 }
62 };
src/http/mcp/tools/pulls.ts +7 −2
@@ -10,11 +10,12 @@ import type { User } from "../../../core/users.ts";
1010 import { pullWaitsFor } from "../../../flow/waits_for.ts";
1111 import { whyPulls } from "../../../flow/why.ts";
1212 import { pageRows } from "../page.ts";
13 import { pullPeopleIn } from "../pull_people.ts";
1314 import { good, bad, limitArg, type Args, type Answer, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1415
1516 export const tool: Tool = {
1617 name: "pulls",
17 doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null); with `repo`, its pulls, newest first, one line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `movedSinceApproval` (approved, then the head or base moved), `changesRequested`, `mergeable` (null once closed), `waitsFor` (`pull`'s `line`, or null); `state` open (default) or closed, `limit` 1-50 (default 20). `{ repo, brief: true, days? }` (1-90, default 14): pulls merged each UTC day, `{ repo, days: [YYYY-MM-DD], merged: [n] }`, oldest first, to chart shipping; without `repo`: what shipped where you may read, `{ since, days, merged, repos: [{ repo, merged }] (top 10), others }`",
18 doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `author`, `yours`, `youMayReview`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null); with `repo`, its pulls, newest first, one line each: `number`, `title`, `author` (a mirrored pull's: its login `on` the origin's host), `yours` (the asker wrote it), `youMayReview` (a writer where it lands, not its author), `head`, `check` (state), `approvals`, `movedSinceApproval` (approved, then the head or base moved), `changesRequested`, `mergeable` (null once closed), `waitsFor` (`pull`'s `line`, or null); `state` open (default) or closed, `limit` 1-50 (default 20). `{ repo, brief: true, days? }` (1-90, default 14): pulls merged each UTC day, `{ repo, days: [YYYY-MM-DD], merged: [n] }`, oldest first, to chart shipping; without `repo`: what shipped where you may read, `{ since, days, merged, repos: [{ repo, merged }] (top 10), others }`",
1819 description:
1920 "A repo's pulls, newest first; no `repo`: all open ones you may read, oldest first; `brief`, no `repo`: merged per repo.",
2021 inputSchema: {
@@ -61,11 +62,12 @@ export const tool: Tool = {
6162 pulls.map((p, i) => (p.state === "open" ? refTip(dirs[i]!, `refs/heads/${p.baseBranch}`) : undefined)),
6263 );
6364 const checks = pulls.map((p) => checkSummary(db, p.id, p.headOid));
65 const people = pullPeopleIn(db, repo, user);
6466 const answer = good({
6567 pulls: pulls.map((p, i) => ({
6668 number: p.number,
6769 title: p.title,
68 author: p.authorName,
70 ...people(p),
6971 head: p.headBranch,
7072 check: checks[i]!.state,
7173 approvals: reviews.get(p.id)?.approvals ?? 0,
@@ -132,6 +134,8 @@ function pile(ctx: Ctx, user: User, args: Args): Answer {
132134 const pulls = pullsByIssueIds(db, items.map((r) => r.id));
133135 const reviews = reviewSummariesFor(db, pulls);
134136 const whys = whyPulls(ctx.app, pulls.map((pull) => ({ repo: repos.get(pull.repoId)!, pull })));
137 // Who each is by and whether the asker may review it, read once per repository.
138 const peopleOf = new Map<string, ReturnType<typeof pullPeopleIn>>();
135139 return good({
136140 pulls: pulls.map((p, i) => {
137141 const repo = repos.get(p.repoId)!;
@@ -141,6 +145,7 @@ function pile(ctx: Ctx, user: User, args: Args): Answer {
141145 repo: `${repo.ownerName}/${repo.name}`,
142146 number: p.number,
143147 title: p.title,
148 ...(peopleOf.get(p.repoId) ?? peopleOf.set(p.repoId, pullPeopleIn(db, repo, user)).get(p.repoId)!)(p),
144149 check: check.state,
145150 verdict: (r?.changesRequested ?? 0) > 0 ? "changes_requested" : (r?.approvals ?? 0) > 0 ? "approved" : "none",
146151 gate: whys[i]?.cause?.name ?? null,
test/mcp-pulls.test.ts +3
@@ -114,6 +114,9 @@ test("lists open pulls in the brief shape, newest first, limited", async () => {
114114 number: 2,
115115 title: "Pull two",
116116 author: "ada",
117 // Rita reads ada/svc and writes nothing there: not hers, not hers to review.
118 yours: false,
119 youMayReview: false,
117120 head: "two",
118121 check: "none",
119122 approvals: 0,
test/pulls-say-who.test.ts added +257
@@ -0,0 +1,257 @@
1 /**
2 * The pulls tool says who each pull is by and whether the asker may review it (#16436). In the
3 * rerun the reader's Talk listed #9 and #10 on the mirror of trevato/voxel and said "Both changes
4 * are yours": the answer named the account that connected the mirror as their author, and nothing
5 * said the reader could not review there.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { connectOrigin } from "../src/actions/origins.ts";
13 import { openPull } from "../src/actions/pulls.ts";
14 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import { getRepo } from "../src/core/repos.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { syncsSettled } from "../src/origins/sync.ts";
21 import { seedAdmin } from "./helpers/admin.ts";
22 import { promote } from "./helpers/members.ts";
23 import { proveAll } from "./helpers/verified.ts";
24
25 let originDir: string;
26 let origin: App;
27 let originServers: Servers;
28 let homeDir: string;
29 let home: App;
30 let homeServers: Servers;
31 let gina: User;
32 let kim: User;
33 let rpc = 1;
34
35 const person = async (app: App, username: string): Promise<User> => {
36 const made = await createUser(app.db, {
37 origin: "seed",
38 trusted: true,
39 username,
40 email: `${username}@forge.test`,
41 password: `${username}-passphrase-long`,
42 });
43 if (!made.ok) throw new Error(made.error);
44 promote(app.db, made.value);
45 proveAll(app);
46 return made.value;
47 };
48
49 type Row = {
50 number: number;
51 title: string;
52 author: string;
53 yours: boolean;
54 youMayReview: boolean;
55 };
56 const pulls = async (
57 who: User,
58 args: Record<string, unknown>,
59 ): Promise<Row[]> => {
60 const res = await fetch(`${homeServers.url}/mcp`, {
61 method: "POST",
62 headers: {
63 "content-type": "application/json",
64 accept: "application/json, text/event-stream",
65 authorization: `Bearer ${createToken(home.db, who.id, "t", "rw").token}`,
66 },
67 body: JSON.stringify({
68 jsonrpc: "2.0",
69 id: rpc++,
70 method: "tools/call",
71 params: { name: "pulls", arguments: args },
72 }),
73 });
74 const text = (
75 (await res.json()) as { result: { content: { text: string }[] } }
76 ).result.content[0]!.text;
77 return (
78 JSON.parse(text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1)) as {
79 pulls: Row[];
80 }
81 ).pulls;
82 };
83
84 beforeAll(async () => {
85 originDir = await mkdtemp(join(tmpdir(), "forge-pulls-who-origin-"));
86 origin = createApp({ dataDir: originDir, port: 0 });
87 originServers = await serve(origin);
88 const bob = await seedAdmin(origin, {
89 username: "bob",
90 email: "[email protected]",
91 password: "bob-passphrase-long",
92 });
93 if (!bob.ok) throw new Error(bob.error);
94 proveAll(origin);
95 const voxel = await createRepo(origin, bob.value, {
96 name: "voxel",
97 visibility: "public",
98 });
99 if (!voxel.ok) throw new Error("repo");
100 await commitToBranch(origin, bob.value, voxel.value, {
101 message: "first",
102 files: [{ path: "README.md", content: "# voxel\n" }],
103 });
104 // Two people propose to bob/voxel from their forks, as f2f-maker and f2f-fixer did.
105 for (const name of ["maker", "fixer"]) {
106 const who = await person(origin, name);
107 const fork = await forkRepo(origin, who, voxel.value);
108 if (!fork.ok) throw new Error(JSON.stringify(fork.error));
109 await commitToBranch(origin, who, fork.value, {
110 branch: "change",
111 base: "main",
112 message: `${name}'s change`,
113 files: [{ path: "src/valid.ts", content: `// ${name}\n` }],
114 });
115 const opened = await openPull(origin, who, voxel.value, {
116 title: `${name}'s change`,
117 baseBranch: "main",
118 headBranch: "change",
119 headRepo: fork.value,
120 });
121 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
122 }
123 const reader = await person(origin, "reader");
124
125 homeDir = await mkdtemp(join(tmpdir(), "forge-pulls-who-home-"));
126 home = createApp({ dataDir: homeDir, port: 0 });
127 homeServers = await serve(home);
128 const ada = await seedAdmin(home, {
129 username: "ada",
130 email: "[email protected]",
131 password: "ada-passphrase-long",
132 });
133 if (!ada.ok) throw new Error(ada.error);
134 gina = await person(home, "gina");
135 kim = await person(home, "kim");
136 const connected = await connectOrigin(home, gina, {
137 host: originServers.url,
138 token: createToken(origin.db, reader.id, "t", "rw").token,
139 });
140 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
141 const res = await fetch(`${homeServers.url}/mcp`, {
142 method: "POST",
143 headers: {
144 "content-type": "application/json",
145 accept: "application/json, text/event-stream",
146 authorization: `Bearer ${createToken(home.db, gina.id, "t", "rw").token}`,
147 },
148 body: JSON.stringify({
149 jsonrpc: "2.0",
150 id: rpc++,
151 method: "tools/call",
152 params: {
153 name: "bring",
154 arguments: { repo: `${originServers.url}/bob/voxel` },
155 },
156 }),
157 });
158 expect(res.status).toBe(200);
159 await syncsSettled();
160 });
161
162 afterAll(async () => {
163 await syncsSettled();
164 originServers.stop();
165 homeServers.stop();
166 origin.close();
167 home.close();
168 await rm(originDir, { recursive: true, force: true, maxRetries: 5 });
169 await rm(homeDir, { recursive: true, force: true, maxRetries: 5 });
170 });
171
172 describe("who a pull is by, and whether the asker may review it", () => {
173 test("a mirror's pulls name their authors at the origin; none is the reader's, and the reader may review none", async () => {
174 expect(getRepo(home.db, "gina", "voxel")).toBeDefined();
175 const rows = await pulls(gina, { repo: "gina/voxel" });
176 const host = new URL(originServers.url).host;
177 expect(rows.map((r) => r.author).sort()).toEqual([
178 `fixer on ${host}`,
179 `maker on ${host}`,
180 ]);
181 expect(rows.every((r) => !r.yours && !r.youMayReview)).toBe(true);
182 });
183
184 test("on a forge's own repository: the author's pull is theirs and not theirs to review; a writer may review another's", async () => {
185 const repo = await createRepo(home, gina, {
186 name: "garden",
187 visibility: "public",
188 });
189 if (!repo.ok) throw new Error("repo");
190 await commitToBranch(home, gina, repo.value, {
191 message: "first",
192 files: [{ path: "a.txt", content: "a\n" }],
193 });
194 await commitToBranch(home, gina, repo.value, {
195 branch: "mine",
196 base: "main",
197 message: "mine",
198 files: [{ path: "a.txt", content: "b\n" }],
199 });
200 expect(
201 (
202 await openPull(home, gina, repo.value, {
203 title: "gina's",
204 baseBranch: "main",
205 headBranch: "mine",
206 })
207 ).ok,
208 ).toBe(true);
209 const fork = await forkRepo(home, kim, repo.value);
210 if (!fork.ok) throw new Error(JSON.stringify(fork.error));
211 await commitToBranch(home, kim, fork.value, {
212 branch: "theirs",
213 base: "main",
214 message: "kim",
215 files: [{ path: "a.txt", content: "k\n" }],
216 });
217 expect(
218 (
219 await openPull(home, kim, repo.value, {
220 title: "kim's",
221 baseBranch: "main",
222 headBranch: "theirs",
223 headRepo: fork.value,
224 })
225 ).ok,
226 ).toBe(true);
227
228 const asGina = await pulls(gina, { repo: "gina/garden" });
229 expect(asGina.find((r) => r.title === "gina's")).toMatchObject({
230 author: "gina",
231 yours: true,
232 youMayReview: false,
233 });
234 expect(asGina.find((r) => r.title === "kim's")).toMatchObject({
235 author: "kim",
236 yours: false,
237 youMayReview: true,
238 });
239 // Kim reads the same list: theirs is theirs, and Kim writes nothing here.
240 const asKim = await pulls(kim, { repo: "gina/garden" });
241 expect(asKim.find((r) => r.title === "kim's")).toMatchObject({
242 yours: true,
243 youMayReview: false,
244 });
245 expect(asKim.find((r) => r.title === "gina's")).toMatchObject({
246 yours: false,
247 youMayReview: false,
248 });
249 // Without `repo`, the open pile says the same.
250 const pile = await pulls(kim, {});
251 expect(pile.find((r) => r.title === "gina's")).toMatchObject({
252 author: "gina",
253 yours: false,
254 youMayReview: false,
255 });
256 });
257 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs