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

Propose upstream names open pulls that change the same files (#16438) #16440

Merged opened this

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

Merged

fix/propose-names-overlaps → main 0 commits

  • Merged. fix/propose-names-overlaps was merged into main as bc5d5f6.

Review

Sign in to review this change.
8 files changed +330 −8
docs/features/propose-upstream.md +8
@@ -19,6 +19,14 @@ Talk first plans and tells you, in one sentence, what will happen:
1919 only read it, so the branch goes to your own fork there (made if you have
2020 none) and the pull request comes from it.
2121
22 **Someone else changing the same files.** The plan reads the origin's open pull
23 requests (at most 10, your own left out) and names each that changes a file your
24 branch changes, before the yes: _… ; octo/widgets #9 by maker also changes
25 src/valid.ts_. It costs one listing and up to 10 diffs at the origin per plan; an
26 origin that does not answer them leaves the list empty, never the plan refused.
27 The terminal's Propose upstream (`src/tui/screens/proposeupstream.ts`) shows the
28 same sentence.
29
2230 Your copy's default branch never goes up under the origin's default branch's
2331 name: it goes up as `you/main`, so a proposal never moves the origin's `main`.
2432
src/actions/bring.ts +49 −3
@@ -18,16 +18,18 @@ import { listAppEnvNames } from "../core/app_env.ts";
1818 import { getOriginFor, listOrigins, mirrorOf } from "../core/origins.ts";
1919 import { canRead, getRepo, getRepoById, listForks, type Repo } from "../core/repos.ts";
2020 import { existingFork } from "../origins/fork-route.ts";
21 import { upstreamWords } from "../origins/words.ts";
21 import { OVERLAP_PATHS_MAX, overlapWord, upstreamWords } from "../origins/words.ts";
2222 import { writeThroughFor } from "../origins/write-through.ts";
2323 import { isSafeRef } from "../git/guard.ts";
24 import { resolveOid } from "../git/merge.ts";
25 import { diffBetween } from "../core/pulls.ts";
2426 import { isActive, type User } from "../core/users.ts";
2527 import { readerFor } from "../git/read.ts";
2628 import { repoDir } from "../git/repos.ts";
2729 import { err, ok, type Result } from "../kernel/result.ts";
2830 import { startMirror } from "../origins/mirror.ts";
2931 import { settled, type MirrorJob } from "../origins/jobs.ts";
30 import type { Origin, OriginSaid } from "../origins/types.ts";
32 import type { Origin, OriginSaid, Provider } from "../origins/types.ts";
3133 import { NEW_ACCOUNT_GUARD_MESSAGE } from "../core/capacity.ts";
3234 import { needsOf, originOnHost, parseBringLink } from "../origins/bring.ts";
3335 import { requireVerified } from "./verify.ts";
@@ -347,6 +349,49 @@ export interface UpstreamPlan {
347349 readonly fork: string | null;
348350 /** The name the branch goes up under: never the origin's default branch. */
349351 readonly as: string;
352 /** Open pulls at the origin that change a file this branch changes, named before the yes. */
353 readonly overlaps: readonly UpstreamOverlap[];
354 }
355
356 /** An open pull at the origin touching the same files: its number, its author, the shared paths. */
357 export interface UpstreamOverlap {
358 readonly number: number;
359 readonly author: string;
360 readonly paths: readonly string[];
361 }
362
363 /** How many of the origin's open pulls a plan reads for overlaps: a bound, not a survey. */
364 const OVERLAP_PULLS_MAX = 10;
365
366 /**
367 * The origin's open pulls that change a file the copy's branch changes (against the mirror's
368 * default branch), so a person proposing onto a line someone else is changing hears it before the
369 * yes (#16438). The person's own pulls are left out. Anything the origin will not answer leaves the
370 * list short, never the plan refused. The cost: one listing and up to `OVERLAP_PULLS_MAX` diffs at
371 * the origin on every plan, in parallel.
372 */
373 async function overlapsAt(app: App, provider: Provider, origin: Origin, fullName: string, copy: Repo, mirror: Repo, branch: string): Promise<UpstreamOverlap[]> {
374 const copyDir = repoDir(app.reposRoot, copy.ownerName, copy.name);
375 const [head, base] = await Promise.all([
376 resolveOid(copyDir, `refs/heads/${branch}`),
377 resolveOid(repoDir(app.reposRoot, mirror.ownerName, mirror.name), `refs/heads/${mirror.defaultBranch}`),
378 ]);
379 if (head === undefined || base === undefined) return [];
380 const mine = new Set((await diffBetween(copyDir, base, head)).diff.files.map((f) => f.path));
381 if (mine.size === 0) return [];
382 const open = await provider.listIssues(fullName, { kind: "pull", state: "open" });
383 if (!open.ok) return [];
384 const login = origin.login.toLowerCase();
385 const theirs = open.value.items.filter((p) => p.author.toLowerCase() !== login).slice(0, OVERLAP_PULLS_MAX);
386 const diffs = await Promise.all(theirs.map((p) => provider.getPullDiff(fullName, p.number)));
387 return theirs.flatMap((p, i) => {
388 const d = diffs[i];
389 const paths = d?.ok === true ? d.value.files.map((f) => f.path).filter((path) => mine.has(path)) : [];
390 // The origin's words, cleaned and capped once here: every door that says the plan is safe.
391 const author = overlapWord(p.author);
392 const said = paths.map(overlapWord).filter((path) => path !== "").slice(0, OVERLAP_PATHS_MAX);
393 return said.length === 0 || author === "" ? [] : [{ number: p.number, author, paths: said }];
394 });
350395 }
351396
352397 export type UpstreamError = { readonly code: string; readonly words: string };
@@ -404,7 +449,8 @@ export async function planUpstream(
404449 if (live.ok && live.value.permissions.fork === false) return refuse("fork_held", forkHeldWords(fullName));
405450 }
406451 const fork = route === "fork" ? (found?.fullName ?? `${origin.login}/${fullName.split("/")[1] ?? copy.name}`) : null;
407 return ok({ copy, mirror, at: fullName, on: originWords(origin), branch, into: route === "direct" ? "branch" : "fork", fork, as });
452 const overlaps = await overlapsAt(app, provider, origin, fullName, copy, mirror, branch);
453 return ok({ copy, mirror, at: fullName, on: originWords(origin), branch, into: route === "direct" ? "branch" : "fork", fork, as, overlaps });
408454 }
409455
410456 /**
src/crew/conversation_ask.ts +17 −2
@@ -13,7 +13,7 @@
1313 * a secret (no form reads one).
1414 */
1515
16 import { upstreamWords } from "../origins/words.ts";
16 import { OVERLAP_PATHS_MAX, OVERLAP_WORD_MAX, upstreamWords } from "../origins/words.ts";
1717
1818 type Args = Record<string, unknown>;
1919
@@ -34,6 +34,21 @@ const UNSAID = /[\p{Cc}\p{Cf}\u2028\u2029`]+/gu;
3434 */
3535 export const unsaid = (v: string): string => v.replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ").replace(/\s+/g, " ").trim();
3636
37 /**
38 * A plan's overlaps, read back from the call's arguments: shape-checked and bounded (the plan
39 * cleaned them where it read them from the origin, `overlapsAt`), so a hand-made argument cannot
40 * stretch the sentence a yes is said to either.
41 */
42 function overlapsOf(raw: unknown): { number: number; author: string; paths: string[] }[] {
43 const line = (v: unknown): string => (typeof v === "string" ? unsaid(v).slice(0, OVERLAP_WORD_MAX) : "");
44 return (Array.isArray(raw) ? raw : []).slice(0, 5).flatMap((o) => {
45 const r = typeof o === "object" && o !== null ? (o as Record<string, unknown>) : {};
46 const n = r["number"];
47 const paths = (Array.isArray(r["paths"]) ? r["paths"] : []).map(line).filter((p) => p !== "").slice(0, OVERLAP_PATHS_MAX);
48 return typeof n === "number" && Number.isInteger(n) && n > 0 && line(r["author"]) !== "" && paths.length > 0 ? [{ number: n, author: line(r["author"]), paths }] : [];
49 });
50 }
51
3752 /** Most characters of a value the sentence says back; past it the value is cut. */
3853 export const SAID_MAX = 60;
3954
@@ -159,7 +174,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
159174 const plan = a["plan"];
160175 if (typeof plan !== "object" || plan === null) return "Open a pull request at the origin from your copy";
161176 const p: Args = Object.fromEntries(Object.entries(plan));
162 return upstreamWords({ at: val(p, "at"), on: val(p, "on"), branch: val(a, "branch"), into: p["into"] === "fork" ? "fork" : "branch", fork: val(p, "fork"), as: val(p, "as") });
177 return upstreamWords({ at: val(p, "at"), on: val(p, "on"), branch: val(a, "branch"), into: p["into"] === "fork" ? "fork" : "branch", fork: val(p, "fork"), as: val(p, "as"), overlaps: overlapsOf(p["overlaps"]) });
163178 },
164179 new_app: (a) => `Make a new app${clause(" called ", val(a, "name"))}${clause(": ", quote(a, "sentence"))}`,
165180 asks_act: (a) => `${capital(verb(a, "action", { dismiss: "dismiss", decline: "decline", mute: "mute", listen: "unmute", undo: "undo", ship: "ship", close: "close", replan: "replan" }, "decide"))} ${a["action"] === "listen" ? repo(a) : a["action"] === "undo" ? "the last decision on your asks" : count(a["items"], "ask", "asks")}`,
src/http/mcp/tools/propose_upstream.ts +1 −1
@@ -26,7 +26,7 @@ export const tool: Tool = {
2626 const planned = await planUpstream(ctx.app, user, named);
2727 if (!planned.ok) return bad(planned.error.code, planned.error.words);
2828 const p = planned.value;
29 const plan = { into: p.into, at: p.at, on: p.on, as: p.as, ...(p.fork === null ? {} : { fork: p.fork }) };
29 const plan = { into: p.into, at: p.at, on: p.on, as: p.as, ...(p.fork === null ? {} : { fork: p.fork }), ...(p.overlaps.length === 0 ? {} : { overlaps: p.overlaps }) };
3030 // The next call carries the plan, so the sentence the person says yes to is the plan.
3131 return good({ says: upstreamWords(p), plan, next: { repo, branch: p.branch, title: "", plan } });
3232 }
src/origins/providers/forge.ts +11
@@ -8,6 +8,7 @@
88 * (`forge-work.ts`).
99 */
1010
11 import type { Diff } from "../../git/diff.ts";
1112 import type {
1213 ListIssuesQuery,
1314 Page,
@@ -213,6 +214,16 @@ export class ForgeProvider extends ForgejoProvider {
213214 return succeed(branches);
214215 }
215216
217 /**
218 * A pull's diff, at a forge's own route (`…/pulls/:number/diff`): Forgejo's `.diff` suffix is not
219 * one a forge answers, so every pull read through it was "no such thing".
220 */
221 override async getPullDiff(fullName: string, number: number): Promise<ProviderResult<Diff>> {
222 const base = this.repoPath(fullName);
223 if (base === undefined || !Number.isInteger(number) || number < 1) return fail("not_found", "not a pull request");
224 return this.diff(`${base}/pulls/${number}/diff`);
225 }
226
216227 /** One repository, from a forge's own JSON. */
217228 override async getRepo(fullName: string): Promise<ProviderResult<RemoteRepo>> {
218229 const named = splitFullName(fullName);
src/origins/providers/forgejo.ts +1 −1
@@ -454,7 +454,7 @@ export class ForgejoProvider implements Provider {
454454 }
455455
456456 /** Here the diff is a `.diff` suffix on the path, not a media type. */
457 private async diff(path: string): Promise<ProviderResult<Diff>> {
457 protected async diff(path: string): Promise<ProviderResult<Diff>> {
458458 const result = await this.api.text({
459459 path,
460460 accept: "text/plain, */*",
src/origins/words.ts +17 −1
@@ -48,6 +48,19 @@ export const FORGE_SIGN_IN_ON_PAGE =
4848 export const FORGE_PULL_CHECK_NEEDS =
4949 "this forge is older than 0.7.355 and does not report a pull's check; it needs 0.7.355 or later";
5050
51 /** Most characters of an overlap's author or path said back; past it the word is cut. */
52 export const OVERLAP_WORD_MAX = 120;
53 /** Most paths one overlap names. */
54 export const OVERLAP_PATHS_MAX = 5;
55
56 /**
57 * An origin's login or path, as an overlap says it: one line, every control and line-breaking
58 * character a space, at most `OVERLAP_WORD_MAX` characters. The origin is a third party: its text
59 * reaches the model as a tool's answer and a person as a sentence, never as instructions.
60 */
61 export const overlapWord = (v: string): string =>
62 v.replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ").replace(/\s+/g, " ").trim().slice(0, OVERLAP_WORD_MAX);
63
5164 /**
5265 * The one sentence a proposal upstream is said in before the yes (`propose_upstream`, its
5366 * terminal door and Talk's confirm): which repository at the origin, and whether the branch is
@@ -60,7 +73,10 @@ export function upstreamWords(p: {
6073 readonly into: "branch" | "fork";
6174 readonly fork: string | null;
6275 readonly as: string;
76 readonly overlaps?: readonly { readonly number: number; readonly author: string; readonly paths: readonly string[] }[];
6377 }): string {
6478 const where = p.into === "fork" ? `the branch is pushed to your fork ${p.fork ?? ""} on ${p.on}` : `the branch is pushed to ${p.at} on ${p.on} as ${p.as}`;
65 return `Open a pull request on ${p.at} from your copy's ${p.branch}: ${where}`;
79 // Someone else's open pull changing the same files is said before the yes, by number and author.
80 const also = (p.overlaps ?? []).map((o) => `; ${p.at} #${o.number} by ${o.author} also changes ${o.paths.slice(0, 3).join(", ")}${o.paths.length > 3 ? ` and ${o.paths.length - 3} more` : ""}`).join("");
81 return `Open a pull request on ${p.at} from your copy's ${p.branch}: ${where}${also}`;
6682 }
test/upstream-overlaps.test.ts added +226
@@ -0,0 +1,226 @@
1 /**
2 * The propose plan names open pulls at the origin that change the same files, before the yes
3 * (#16438). In the rerun f2f-fixer proposed onto the line f2f-maker's pull #9 changed minutes
4 * earlier, and neither the plan nor Talk said so.
5 */
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 { planUpstream } from "../src/actions/bring.ts";
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 { confirmSentence } from "../src/crew/conversation_ask.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { syncsSettled } from "../src/origins/sync.ts";
22 import { originForRepo } from "../src/core/origins.ts";
23 import { providerForOrigin } from "../src/origins/credential.ts";
24 import { OVERLAP_WORD_MAX, overlapWord } from "../src/origins/words.ts";
25 import { seedAdmin } from "./helpers/admin.ts";
26 import { promote } from "./helpers/members.ts";
27 import { proveAll } from "./helpers/verified.ts";
28
29 let originDir: string;
30 let origin: App;
31 let originServers: Servers;
32 let homeDir: string;
33 let home: App;
34 let homeServers: Servers;
35 let gina: User;
36
37 const person = async (app: App, username: string): Promise<User> => {
38 const made = await createUser(app.db, {
39 origin: "seed",
40 trusted: true,
41 username,
42 email: `${username}@forge.test`,
43 password: `${username}-passphrase-long`,
44 });
45 if (!made.ok) throw new Error(made.error);
46 promote(app.db, made.value);
47 proveAll(app);
48 return made.value;
49 };
50
51 beforeAll(async () => {
52 originDir = await mkdtemp(join(tmpdir(), "forge-overlaps-origin-"));
53 origin = createApp({ dataDir: originDir, port: 0 });
54 originServers = await serve(origin);
55 const bob = await seedAdmin(origin, {
56 username: "bob",
57 email: "[email protected]",
58 password: "bob-passphrase-long",
59 });
60 if (!bob.ok) throw new Error(bob.error);
61 proveAll(origin);
62 const voxel = await createRepo(origin, bob.value, {
63 name: "voxel",
64 visibility: "public",
65 });
66 if (!voxel.ok) throw new Error("repo");
67 await commitToBranch(origin, bob.value, voxel.value, {
68 message: "first",
69 files: [
70 { path: "README.md", content: "# voxel\n" },
71 { path: "src/valid.ts", content: "export const NAME = /x/;\n" },
72 ],
73 });
74 // Maker's open pull changes src/valid.ts.
75 const maker = await person(origin, "maker");
76 const fork = await forkRepo(origin, maker, voxel.value);
77 if (!fork.ok) throw new Error(JSON.stringify(fork.error));
78 await commitToBranch(origin, maker, fork.value, {
79 branch: "pattern",
80 base: "main",
81 message: "pattern",
82 files: [{ path: "src/valid.ts", content: "export const NAME = /y/;\n" }],
83 });
84 const opened = await openPull(origin, maker, voxel.value, {
85 title: "pattern",
86 baseBranch: "main",
87 headBranch: "pattern",
88 headRepo: fork.value,
89 });
90 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
91 const fixer = await person(origin, "fixer");
92
93 homeDir = await mkdtemp(join(tmpdir(), "forge-overlaps-home-"));
94 home = createApp({ dataDir: homeDir, port: 0 });
95 homeServers = await serve(home);
96 const ada = await seedAdmin(home, {
97 username: "ada",
98 email: "[email protected]",
99 password: "ada-passphrase-long",
100 });
101 if (!ada.ok) throw new Error(ada.error);
102 gina = await person(home, "gina");
103 const connected = await connectOrigin(home, gina, {
104 host: originServers.url,
105 token: createToken(origin.db, fixer.id, "t", "rw").token,
106 });
107 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
108 const res = await fetch(`${homeServers.url}/mcp`, {
109 method: "POST",
110 headers: {
111 "content-type": "application/json",
112 accept: "application/json, text/event-stream",
113 authorization: `Bearer ${createToken(home.db, gina.id, "t", "rw").token}`,
114 },
115 body: JSON.stringify({
116 jsonrpc: "2.0",
117 id: 1,
118 method: "tools/call",
119 params: {
120 name: "bring",
121 arguments: { repo: `${originServers.url}/bob/voxel` },
122 },
123 }),
124 });
125 expect(res.status).toBe(200);
126 const copy = getRepo(home.db, "gina", "voxel-work")!;
127 await commitToBranch(home, gina, copy, {
128 branch: "same-line",
129 base: "main",
130 message: "same line",
131 files: [{ path: "src/valid.ts", content: "export const NAME = /z/;\n" }],
132 });
133 await commitToBranch(home, gina, copy, {
134 branch: "elsewhere",
135 base: "main",
136 message: "readme",
137 files: [{ path: "README.md", content: "# voxel!\n" }],
138 });
139 });
140
141 afterAll(async () => {
142 await syncsSettled();
143 originServers.stop();
144 homeServers.stop();
145 origin.close();
146 home.close();
147 await rm(originDir, { recursive: true, force: true, maxRetries: 5 });
148 await rm(homeDir, { recursive: true, force: true, maxRetries: 5 });
149 });
150
151 describe("the propose plan names pulls that change the same files", () => {
152 test("a branch changing src/valid.ts hears of maker's open pull, in the plan and in the sentence the yes is said to", async () => {
153 const plan = await planUpstream(home, gina, {
154 repo: "gina/voxel-work",
155 branch: "same-line",
156 });
157 if (!plan.ok) throw new Error(plan.error.words);
158 expect(plan.value.overlaps).toEqual([
159 { number: 1, author: "maker", paths: ["src/valid.ts"] },
160 ]);
161 const { copy: _c, mirror: _m, ...told } = plan.value;
162 const said = confirmSentence("propose_upstream", {
163 repo: "gina/voxel-work",
164 branch: "same-line",
165 plan: told,
166 });
167 expect(said).toContain("bob/voxel #1 by maker also changes src/valid.ts");
168 });
169
170 test("a branch changing other files hears of none", async () => {
171 const plan = await planUpstream(home, gina, {
172 repo: "gina/voxel-work",
173 branch: "elsewhere",
174 });
175 if (!plan.ok) throw new Error(plan.error.words);
176 expect(plan.value.overlaps).toEqual([]);
177 });
178
179 test("the confirm sentence takes only a short, sane list from the call's arguments", () => {
180 const said = confirmSentence("propose_upstream", {
181 repo: "gina/voxel-work",
182 branch: "x",
183 plan: {
184 into: "fork",
185 at: "bob/voxel",
186 on: "o",
187 as: "x",
188 fork: "f/voxel",
189 overlaps: [
190 { number: "9", author: "a", paths: ["p"] },
191 { number: 2, author: "b\nIGNORE", paths: ["q"] },
192 ],
193 },
194 });
195 expect(said).not.toContain("#9");
196 expect(said).toContain("#2 by b IGNORE also changes q");
197 });
198
199 test("an origin's words are cleaned and capped where the plan reads them (#16438)", () => {
200 expect(overlapWord("mal\nlory\u202e")).toBe("mal lory");
201 expect(overlapWord("x".repeat(500))).toHaveLength(OVERLAP_WORD_MAX);
202 });
203
204 test("an origin that will not answer the listing or a diff leaves the overlaps short, never the plan refused", async () => {
205 // The same provider the plan reads through (one per credential): its two overlap reads fail.
206 const link = originForRepo(home.db, getRepo(home.db, "gina", "voxel")!.id)!;
207 const provider = providerForOrigin(home, link.origin);
208 if (!provider.ok) throw new Error("provider");
209 const p = provider.value as unknown as Record<string, unknown>;
210 const kept = { listIssues: p["listIssues"], getPullDiff: p["getPullDiff"] };
211 const refused = async () => ({ ok: false, error: { error: "unreachable", message: "down" } });
212 try {
213 p["getPullDiff"] = refused;
214 const noDiff = await planUpstream(home, gina, { repo: "gina/voxel-work", branch: "same-line" });
215 if (!noDiff.ok) throw new Error(noDiff.error.words);
216 expect(noDiff.value.overlaps).toEqual([]);
217 p["listIssues"] = refused;
218 const noList = await planUpstream(home, gina, { repo: "gina/voxel-work", branch: "same-line" });
219 if (!noList.ok) throw new Error(noList.error.words);
220 expect(noList.value.overlaps).toEqual([]);
221 } finally {
222 p["listIssues"] = kept.listIssues;
223 p["getPullDiff"] = kept.getPullDiff;
224 }
225 });
226 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs