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

Merge queue: show which open pulls touch the same files #17176

opened this

Merged 44h 36m ago, live in production

scout/forge:scout/17037-merge-queue-show-which-open-pulls-touch → main 0 commits fork 6 threads · 6 unresolved

  • Merged. scout/17037-merge-queue-show-which-open-pulls-touch was merged into main as c113a29.

Review

Sign in to review this change.
12 files changed +554 −9
docs/features/queue-collisions.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Tell the crew
3 row: Pulls that collide
4 ---
5 # Pulls that collide (#17037)
6
7 The queue page (`/<owner>/<name>/queue`), the terminal's "Pulls that collide" (palette, while the repository is open) and the `flow` tool with `{ kind: collisions, repo }` all read `viewerCollisions` in `src/core/pull_collisions.ts`. For every pair of open pulls that change a common file it runs `git merge-tree --write-tree` over the two heads (no checkout) and says "#12 collides with #14 in a.ts", or that the pair shares files but git merges them. `order` is the order to land in: fewest conflicts first, then the oldest. Readings are kept by head pair; a reading past 400 ms answers what it has and the rest is there on the next one. A fork's pull, and all but the first 30 open pulls, are `skipped`. A sealed pull a viewer may not read is left out.
8
9 ## When a reading is partial
10
11 The queue page never waits on git: it shows what earlier readings kept and fills the rest in the
12 background, so a first load may show a line such as "Some pairs are not read yet. The order may
13 change." (or "Left out of this reading: #9." for a fork's pull, or any pull past the 30 read).
14 Reload in a moment. The terminal screen and the `flow` tool (`kind: collisions`, in `says`) say the
15 same line.
src/core/bounded.ts added +5
@@ -0,0 +1,5 @@
1 /** A map that keeps at most `max` entries: adding past it drops the oldest (#17037). */
2 export function keepNewest<K, V>(into: Map<K, V>, key: K, value: V, max: number): void {
3 if (into.size >= max) into.delete(into.keys().next().value!);
4 into.set(key, value);
5 }
src/core/pull_collisions.ts added +180
@@ -0,0 +1,180 @@
1 /**
2 * Which open pulls collide before they land (#17037, from #16331): for every pair of open pulls
3 * that change a common file, `git merge-tree --write-tree` of the two heads (no checkout) says
4 * whether the pair conflicts and in which files, and one order to land them in puts the pulls with
5 * the fewest collisions first. The page, the terminal and the API read this one function.
6 * Readings are kept by head pair (a merge-tree over two commits never changes) and a pass past its
7 * time budget answers what it has; the rest finishes on the next reading.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { keepNewest } from "./bounded.ts";
12 import { runGitCapture } from "../git/env.ts";
13 import { isSafeOid, isSafeTreePath } from "../git/guard.ts";
14 import { repoDir } from "../git/repos.ts";
15 import { listOpenPulls } from "./pulls.ts";
16 import type { Repo } from "./repos.ts";
17 import { mayView } from "./sealed.ts";
18 import type { User } from "./users.ts";
19
20 /** What a reading needs of a pull; a `Pull` is one. */
21 export interface CollisionInput {
22 readonly number: number;
23 readonly baseOid: string;
outdated

title is never read. Remove it, and the title: p.title assignment in viewerCollisions.

24 readonly headOid: string;
25 readonly crossRepo: boolean;
26 }
27
28 /** Two pulls that change a common file; `conflicts` is the part git cannot merge. */
29 export interface Collision {
30 readonly a: number;
31 readonly b: number;
32 readonly shared: readonly string[];
33 readonly conflicts: readonly string[];
34 }
35
36 export interface Collisions {
37 readonly pairs: readonly Collision[];
38 /** Pull numbers, the order to land in: fewest conflicts first, then the oldest. */
39 readonly order: readonly number[];
40 /** Pulls left out: a fork's pull (its head is not in this repository) or one not read in time. */
41 readonly skipped: readonly number[];
42 /** True when a reading was cut short or not cached yet: pairs or the order may be incomplete. */
43 readonly partial: boolean;
44 }
45
46 const MAX_PULLS = 30;
47 const BUDGET_MS = 400;
48 const AT_ONCE = 4;
49 const KEPT_MAX = 2000;
50 const touched = new Map<string, readonly string[]>();
outdated

Duplicates keep in review_evidence.ts. Reuse that one.

51 const merged = new Map<string, readonly string[]>();
52
53
54 const lines = (out: string): string[] => out.split("\n").filter(isSafeTreePath);
55
56 async function filesOf(dir: string, p: CollisionInput, cachedOnly: boolean): Promise<readonly string[] | undefined> {
57 const key = `${p.baseOid}:${p.headOid}`;
58 const known = touched.get(key);
59 if (known !== undefined || cachedOnly) return known;
60 const out = await runGitCapture(["diff", "--name-only", `${p.baseOid}...${p.headOid}`], { cwd: dir, timeoutMs: 20_000 });
61 if (out.code !== 0) return undefined;
62 const files = lines(out.stdout);
63 keepNewest(touched, key, files, KEPT_MAX);
64 return files;
65 }
66
67 async function conflictsOf(dir: string, x: CollisionInput, y: CollisionInput, cachedOnly: boolean): Promise<readonly string[] | undefined> {
68 const [first, second] = x.headOid < y.headOid ? [x.headOid, y.headOid] : [y.headOid, x.headOid];
69 const key = `${first}:${second}`;
70 const known = merged.get(key);
71 if (known !== undefined || cachedOnly) return known;
72 const out = await runGitCapture(["merge-tree", "--write-tree", "--name-only", "--no-messages", first, second], { cwd: dir, timeoutMs: 20_000 });
73 if (out.code !== 0 && out.code !== 1) return undefined;
74 const files = out.code === 0 ? [] : lines(out.stdout.split("\n").slice(1).join("\n").split("\n\n")[0] ?? "");
75 keepNewest(merged, key, files, KEPT_MAX);
76 return files;
77 }
78
79 /** Run `work` over `items`, `AT_ONCE` at a time, starting none after `until`. */
80 async function eachBefore<T>(items: readonly T[], until: number, work: (item: T) => Promise<void>): Promise<void> {
81 let next = 0;
82 const lane = async (): Promise<void> => {
83 while (next < items.length && Date.now() < until) await work(items[next++]!);
84 };
85 await Promise.all(Array.from({ length: Math.min(AT_ONCE, items.length) }, lane));
86 }
87
88 /**
89 * The collisions among `pulls` (open, oldest first) in the bare repository at `dir`. With
90 * `cachedOnly` no git process starts: only what an earlier reading kept is answered.
91 */
92 export async function pullCollisions(dir: string, pulls: readonly CollisionInput[], cachedOnly = false, now = Date.now()): Promise<Collisions> {
93 const until = now + BUDGET_MS;
94 const skipped: number[] = [];
95 const readable = pulls.filter((p) => {
96 const ok = !p.crossRepo && isSafeOid(p.baseOid) && isSafeOid(p.headOid);
97 if (!ok) skipped.push(p.number);
98 return ok;
99 });
100 for (const p of readable.slice(MAX_PULLS)) skipped.push(p.number);
101 const among = readable.slice(0, MAX_PULLS);
102 const files = new Map<number, readonly string[]>();
103 await eachBefore(among, until, async (p) => {
104 const f = await filesOf(dir, p, cachedOnly);
105 if (f !== undefined) files.set(p.number, f);
106 });
107 for (const p of among) if (!files.has(p.number)) skipped.push(p.number);
108 const read = among.filter((p) => files.has(p.number));
109 const todo: { x: CollisionInput; y: CollisionInput; shared: string[] }[] = [];
110 for (let i = 0; i < read.length; i++)
111 for (let j = i + 1; j < read.length; j++) {
112 const other = new Set(files.get(read[j]!.number));
113 const shared = files.get(read[i]!.number)!.filter((f) => other.has(f));
114 if (shared.length > 0) todo.push({ x: read[i]!, y: read[j]!, shared });
115 }
116 const pairs: Collision[] = [];
117 await eachBefore(todo, until, async ({ x, y, shared }) => {
118 const conflicts = await conflictsOf(dir, x, y, cachedOnly);
119 if (conflicts !== undefined) pairs.push({ a: x.number, b: y.number, shared, conflicts });
120 });
121 pairs.sort((p, q) => p.a - q.a || p.b - q.b);
122 const hits = (n: number): number => pairs.filter((p) => p.conflicts.length > 0 && (p.a === n || p.b === n)).length;
123 const order = read.map((p) => p.number).sort((m, n) => hits(m) - hits(n) || m - n);
124 const partial = skipped.length > 0 || pairs.length < todo.length;
125 return { pairs, order, skipped: skipped.sort((m, n) => m - n), partial };
126 }
127
128 /**
outdated

Two refTip spawns per open pull on every call. Use the stored oids, or read this off the request.

129 * What a viewer sees of the repository's open pulls: sealed ones they may not read are left out of
130 * the pairs, the order and the sentences, as everywhere else. The stored head and base are read, no
131 * live tip; `cachedOnly` answers from what earlier readings kept and starts no git process.
132 */
133 export async function viewerCollisions(db: Database, reposRoot: string, repo: Repo, user: User | undefined, cachedOnly = false): Promise<Collisions> {
134 const open = listOpenPulls(db, repo.id).filter((p) => mayView(db, repo, p, user));
135 const dir = repoDir(reposRoot, repo.ownerName, repo.name);
136 return pullCollisions(dir, open, cachedOnly);
137 }
138
139 /** Per repository: when the last pass started and whether one is running. */
140 const passes = new Map<string, { at: number; running: boolean }>();
141 const REFILL_MS = 5_000;
142
143 /**
144 * Fill the cache for `viewerCollisions(…, true)` off the request: one pass at a time a repository,
145 * at most one in `REFILL_MS`.
146 */
147 export function warmCollisions(db: Database, reposRoot: string, repo: Repo, user: User | undefined, now = Date.now()): Promise<void> {
148 const key = repo.id;
149 const last = passes.get(key);
150 if (last !== undefined && (last.running || now - last.at < REFILL_MS)) return Promise.resolve();
151 keepNewest(passes, key, { at: now, running: true }, KEPT_MAX);
152 return viewerCollisions(db, reposRoot, repo, user)
153 .then(() => undefined, () => undefined)
154 .finally(() => keepNewest(passes, key, { at: now, running: false }, KEPT_MAX));
155 }
156
157 /**
158 * One plain line when a reading is not the whole story: the pulls left out, or pairs not read yet.
159 */
160 export function partialLine(c: Collisions): string | null {
161 if (!c.partial) return null;
162 const left = c.skipped.length > 0 ? `Left out of this reading: ${c.skipped.map((n) => `#${n}`).join(", ")}. ` : "Some pairs are not read yet. ";
163 return `${left}The order may change.`;
164 }
165
166 /**
167 * One sentence per pull that collides: "#12 collides with #14 in a.ts, b.ts", else what it shares.
168 */
169 export function collisionLines(c: Collisions): string[] {
170 const out: string[] = [];
171 for (const p of c.pairs) {
172 const where = (fs: readonly string[]): string => (fs.length > 3 ? `${fs.slice(0, 3).join(", ")} and ${fs.length - 3} more` : fs.join(", "));
173 out.push(
174 p.conflicts.length > 0
175 ? `#${p.a} collides with #${p.b} in ${where(p.conflicts)}`
176 : `#${p.a} and #${p.b} both change ${where(p.shared)}; git merges them`,
177 );
178 }
179 return out;
180 }
src/http/mcp/tools/flow.ts +12 −3
@@ -7,6 +7,7 @@ import { canWrite } from "../../../core/repos.ts";
77 import { bringUpToDate } from "../../../crew/conflict_release.ts";
88 import { mayView, sealedScope } from "../../../core/sealed.ts";
99 import { growth } from "../../../core/growth.ts";
10 import { collisionLines, partialLine, viewerCollisions } from "../../../core/pull_collisions.ts";
1011 import { DAYS } from "../../../web/pages/queue.ts";
1112 import { whyIssue, whyPull, liveHead, whyRepo, type Why } from "../../../flow/why.ts";
1213 import { countRead } from "../../../system/telemetry_reads.ts";
@@ -39,13 +40,13 @@ const said = (subject: string, why: Why) =>
3940
4041 export const tool: Tool = {
4142 name: "flow",
42 doc: "with no arguments, the forge's pipeline (a forge admin's, or an agent the owner granted `telemetry:read`; private repositories cut out): per stage counts, `oldestWaiting`, `capacity`, the bottleneck, the merge `queue` and what each reviewer has `reviewing`, and `declines` (crew runs declined in 24 h, by reason) (the `ui://forge/flow` card); with `{ q, sort? }`, the rows a fleet query line selects: `{ kind, columns, items }`, only rows you may read, `sort` a column key led by `-` to reverse, a bad line answers its reason; with `{ q, action: { verb, value }, apply? }`, a fleet operation over those rows as `POST /api/v1/fleet/ops` answers it: the dry-run plan `{ dryRun: true, query, kind, verb, value, reversible, rows, counts }` and nothing changed, or with `apply: true` (an admin token, a person) the receipt `{ dryRun: false, id, rows, … }` whose id `limb` undoes; with `{ kind: report }` (as the no-argument read: an admin, or an agent granted `telemetry:read`, public repositories only), `{ readings, lines }` the ten flow reads and the line that words each, as `bun scripts/flow-report.ts`; with `{ kind: drift }`, `{ drifting: [{ repo, number, landings, hours }] }` the open pulls over 25 landings or 6 h behind main, furthest first; each is brought up to date by `POST /{repo}/pulls/{number}/update`, or with `{ kind: drift, repo, pull, action: update }` (a repository writer) the same: `{ updating, by }` names the agent, or a refusal in the route's words; with `{ kind: bugs }`, `{ open, overdue, bugs: [{ repo, number, priority, dueAt }] }` soonest due first, at most 100 (an admin sees all, anyone else public repositories); with `{ kind: cpu }`, `{ stopped, closed: [{ repo, number, closedAt }] }` the hour's checks stopped for CPU (an admin's) and the pulls closed unmerged after one, newest first, at most 20, to queue again; with `{ repo, issue? or pull? }` (a repository writer), why it is not moving: `{ subject, moving, state?, cause, says, clears, next? }`, the first of wall (a person decides access), ceiling, hot_file, blocked_by, later_gate, no_builder, no_headroom, red_check, waiting_review that holds it (`flow/why.ts`); with `{ kind: growth, repo }` (anyone who can read it), is the work growing: `{ open: { issues, pulls }, perDay, daysQueued, growingRun, sentences, suggest }` as `/queue` shows, over its 14 days; `suggest` is words only, null when no pause is worth considering; `repo` alone asks about the repository's builders",
43 doc: "with no arguments, the forge's pipeline (a forge admin's, or an agent the owner granted `telemetry:read`; private repositories cut out): per stage counts, `oldestWaiting`, `capacity`, the bottleneck, the merge `queue` and what each reviewer has `reviewing`, and `declines` (crew runs declined in 24 h, by reason) (the `ui://forge/flow` card); with `{ q, sort? }`, the rows a fleet query line selects: `{ kind, columns, items }`, only rows you may read, `sort` a column key led by `-` to reverse, a bad line answers its reason; with `{ q, action: { verb, value }, apply? }`, a fleet operation over those rows as `POST /api/v1/fleet/ops` answers it: the dry-run plan `{ dryRun: true, query, kind, verb, value, reversible, rows, counts }` and nothing changed, or with `apply: true` (an admin token, a person) the receipt `{ dryRun: false, id, rows, … }` whose id `limb` undoes; with `{ kind: report }` (as the no-argument read: an admin, or an agent granted `telemetry:read`, public repositories only), `{ readings, lines }` the ten flow reads and the line that words each, as `bun scripts/flow-report.ts`; with `{ kind: drift }`, `{ drifting: [{ repo, number, landings, hours }] }` the open pulls over 25 landings or 6 h behind main, furthest first; each is brought up to date by `POST /{repo}/pulls/{number}/update`, or with `{ kind: drift, repo, pull, action: update }` (a repository writer) the same: `{ updating, by }` names the agent, or a refusal in the route's words; with `{ kind: bugs }`, `{ open, overdue, bugs: [{ repo, number, priority, dueAt }] }` soonest due first, at most 100 (an admin sees all, anyone else public repositories); with `{ kind: cpu }`, `{ stopped, closed: [{ repo, number, closedAt }] }` the hour's checks stopped for CPU (an admin's) and the pulls closed unmerged after one, newest first, at most 20, to queue again; with `{ repo, issue? or pull? }` (a repository writer), why it is not moving: `{ subject, moving, state?, cause, says, clears, next? }`, the first of wall (a person decides access), ceiling, hot_file, blocked_by, later_gate, no_builder, no_headroom, red_check, waiting_review that holds it (`flow/why.ts`); with `{ kind: collisions, repo }` (anyone who can read it), the open pulls that change a common file: `{ pairs: [{ a, b, shared, conflicts }], order, skipped, says }`, `conflicts` the files git cannot merge between the two heads (merge-tree, no checkout), `order` the pulls to land in, fewest conflicts first, `says` one sentence per pair (#12 collides with #14 in a.ts); with `{ kind: growth, repo }` (anyone who can read it), is the work growing: `{ open: { issues, pulls }, perDay, daysQueued, growingRun, sentences, suggest }` as `/queue` shows, over its 14 days; `suggest` is words only, null when no pause is worth considering; `repo` alone asks about the repository's builders",
4344 description:
4445 "Pipeline (admin); `q`: `/fleet` rows, `action` plans an op, `apply` does it; `kind:bugs`; `repo`: why stuck.",
4546 inputSchema: {
4647 type: "object",
4748 properties: {
48 kind: { type: "string", enum: ["bugs", "cpu", "drift", "growth", "lanes", "report"] },
49 kind: { type: "string", enum: ["bugs", "collisions", "cpu", "drift", "growth", "lanes", "report"] },
4950 q: { type: "string", maxLength: 500 },
5051 sort: { type: "string" },
5152 action: {},
@@ -121,6 +122,14 @@ export const tool: Tool = {
121122 );
122123 return good({ open, perDay, daysQueued, growingRun, sentences, suggest });
123124 }
125 if (args["kind"] === "collisions") {

The new kind: collisions branch has no test: sealed pulls left out, guest on a private repository refused, and the says field.

126 const repo = repoArg(ctx, user, args);
127 if (isAnswer(repo)) return repo;
128 const c = await viewerCollisions(ctx.app.db, ctx.app.reposRoot, repo, user);
129 const says = collisionLines(c);
130 const note = partialLine(c);
131 return good({ pairs: c.pairs, order: c.order, skipped: c.skipped, says: note === null ? says : [...says, note] });
132 }
124133 if (args["kind"] === "drift") {
125134 const all = user.isAdmin && user.kind !== "agent" ? {} : { publicOnly: true };
126135 return good({ drifting: driftingPulls(await readDrifts(ctx.app, all), Date.now()).slice(0, 100) });
@@ -152,7 +161,7 @@ export const tool: Tool = {
152161 const now = new Date();
153162 return good({ stopped: admin ? cpuStops(ctx.app.db, now).stopped : 0, closed: cpuClosedPulls(ctx.app.db, now, { publicOnly: !admin }) });
154163 }
155 if (args["kind"] !== "bugs") return bad("invalid", "kind is bugs, cpu, drift, growth, lanes or report");
164 if (args["kind"] !== "bugs") return bad("invalid", "kind is bugs, collisions, cpu, drift, growth, lanes or report");
156165 // As the terminal's bugs screen: an admin sees every repository, anyone else public ones.
157166 const all = openBugs(ctx.app.db, user.isAdmin && user.kind !== "agent" ? {} : { publicOnly: true });
158167 const now = Date.now();
src/tui/screens/collisions.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * The open pulls that collide, in the terminal (#17037): `viewerCollisions`, the queue page's own
3 * read, one sentence a pair and the order to land in. Reached from the palette's "Pulls that
4 * collide" while a repository is open (`queueCommands`, `queuegrowth.ts`).
5 */
6
7 import { collisionLines, partialLine, viewerCollisions } from "../../core/pull_collisions.ts";
8 import type { Repo } from "../../core/repos.ts";
9 import type { Ctx, Screen } from "../app/app.ts";
10 import { binding } from "../app/keys.ts";
11 import type { Session } from "../session.ts";
12 import { style } from "../term/style.ts";
13 import { truncate } from "../term/width.ts";
14 import { runAsync } from "./common.ts";
15
16 /**
17 * The open pulls that collide and the order to land them in (#17037): the page's section, from its
18 * read.
19 */

No test covers this screen or its gating, and a partial result (skipped) is not shown. Add both.

20 export function collisionScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
21 let lines: string[] = ["Reading the open pulls…"];
22 runAsync(ctx, async () => {
23 const c = await viewerCollisions(f.db, f.app.reposRoot, repo, f.user);
24 const said = collisionLines(c);
25 const note = partialLine(c);
26 lines = said.length === 0 ? ["No open pulls change a common file."] : [...said, "", `Order to land in: ${c.order.map((n) => `#${n}`).join(", ")}`];
27 if (note !== null) lines.push("", note);
28 ctx.invalidate();
29 });
30 return {
31 title: `${repo.ownerName}/${repo.name} — Pulls that collide`,
32 keys: [binding(["esc", "q"], "back")],
33 key(e) {
34 if (e.key !== "esc" && e.key !== "q") return false;
35 ctx.pop();
36 return true;
37 },
38 render(area, s) {
39 const c = ctx.theme.c;
40 lines.forEach((line, i) => {
41 if (i < area.h) s.text(area.x, area.y + i, truncate(line, area.w), style(c.fg, c.bg), area.x + area.w);
42 });
43 },
44 };
45 }
src/tui/screens/queuegrowth.ts +7
@@ -25,6 +25,7 @@ import { style } from "../term/style.ts";
2525 import { truncate } from "../term/width.ts";
2626 import type { Session } from "../session.ts";
2727 import { promptScreen } from "./common.ts";
28 import { collisionScreen } from "./collisions.ts";
2829
2930 const DAYS = 14;
3031
@@ -216,5 +217,11 @@ export function queueCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Com
216217 hint: "is the work growing or shrinking, and the planner's switch",
217218 run: () => ctx.push(queueScreen(f, ctx, repo)),
218219 },
220 {
221 id: "queue-collisions",
222 title: `${repo.ownerName}/${repo.name} — Pulls that collide`,
223 hint: "which open pulls change the same files, and the order to land in",
224 run: () => ctx.push(collisionScreen(f, ctx, repo)),
225 },
219226 ];
220227 }
src/web/pages/queue.ts +20 −1
@@ -13,6 +13,7 @@ import { takeOrder } from "../../crew/take_order.ts";
1313 import { growth, oldest, WHO, type Growth } from "../../core/growth.ts";
1414 import { openPullsCeiling, pullsCeilingHold, PULLS_CEILING_REASON, PULLS_HELD_NOTE } from "../../core/pulls_ceiling.ts";
1515 import { ceilingHold, CEILING_HELD_NOTE, CEILING_REASON, openCeiling, PAUSE_STOPS, pauseSentence, pausedUntil } from "../../core/planner_pause.ts";
16 import { collisionLines, partialLine, viewerCollisions, warmCollisions, type Collisions } from "../../core/pull_collisions.ts";
1617 import { canAdmin, type Repo } from "../../core/repos.ts";
1718 import { sealedScope } from "../../core/sealed.ts";
1819 import type { Ctx } from "../../http/context.ts";
@@ -114,13 +115,30 @@ export function takeRows(base: string, rows: readonly NextRow[], chapters: Reado
114115 );
115116 }
116117
118 /**
119 * The pulls that collide, one row each, and the order to land them in (#17037). Nothing when none
120 * do.
121 */
122 export function collisionRows(c: Collisions, base: string): Html | null {
123 const said = collisionLines(c);
124 const note = partialLine(c);
125 if (said.length === 0 && note === null) return null;
126 return html`<h2>Pulls that collide</h2>
127 <p class="muted">Order to land in, fewest conflicts first: ${c.order.map((n, i) => html`${i === 0 ? "" : ", "}<a href="${base}/pulls/${n}">#${n}</a>`)}.</p>
128 ${note === null ? null : html`<p class="muted" data-collisions-partial>${note}</p>`}
129 ${listCard(c.pairs.map((p, i) => row({ title: said[i]!, meta: html`<a href="${base}/pulls/${p.a}">#${p.a}</a> · <a href="${base}/pulls/${p.b}">#${p.b}</a>`, trail: badge(p.conflicts.length > 0 ? "conflict" : "same files") })), { attrs: html`data-collisions` })}`;
130 }
131
117132 const ago = (iso: string, now: Date) => `${Math.max(0, Math.floor((now.getTime() - Date.parse(iso)) / 86_400_000))} days old`;
118133
119134 // GET /:owner/:name/queue
120 export function queuePage(ctx: Ctx): Response {
135 export async function queuePage(ctx: Ctx): Promise<Response> {
121136 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
122137 const repo = loadRepo(ctx);
outdated

Security/perf: await viewerCollisions(...) blocks the first paint on git subprocesses for any viewer, guests included. Serve the cached reading and refresh it off the request.

123138 if (!repo) return notFoundPage(ctx);
139 // The first paint never waits on git: the kept reading now, the cache filled off the request.
140 const collisions = await viewerCollisions(ctx.app.db, ctx.app.reposRoot, repo, ctx.auth.user, true);
141 if (collisions.partial) void warmCollisions(ctx.app.db, ctx.app.reposRoot, repo, ctx.auth.user);
124142 const rendering = performance.now();
125143 const now = new Date();
126144 const user = ctx.auth.user;
@@ -148,6 +166,7 @@ export function queuePage(ctx: Ctx): Response {
148166 ${pullsForm(repo, pullsCeiling, owner)}
149167 <p><a href="${base}/chapters">Chapters</a></p>
150168 ${taking.length === 0 ? null : html`<h2>Next to be taken</h2><p class="muted">The next rows the crew takes, in order.</p>${takeRows(base, taking, chapterNames(ctx.app.db, repo.id))}`}
169 ${collisionRows(collisions, base)}
151170 ${aged.length === 0 ? null : html`<ul class="list setting-list" data-aged>${aged}</ul>`}
152171 ${growthRows(g, openFlowWords(ctx.app.db, repo.id, scope, now))}`;
153172 const response = page({ ctx, title: `Queue · ${repo.name}`, crumbs: crumbsFor(repo), palette: repoPalette(ctx, repo), body });
src/web/studio/review_evidence.ts +2 −2
@@ -8,6 +8,7 @@
88 * fails cannot turn each visit into a git process.
99 */
1010
11 import { keepNewest } from "../../core/bounded.ts";
1112 import { pullDir, type Pull } from "../../core/pulls.ts";
1213 import type { App } from "../../app.ts";
1314 import { runGit } from "../../git/env.ts";
@@ -137,8 +138,7 @@ async function compute(
137138 }
138139
139140 function keep(w: Work, key: string, stat: DiffStat): void {
140 if (w.kept.size >= KEPT_MAX) w.kept.delete(w.kept.keys().next().value!);
141 w.kept.set(key, stat);
141 keepNewest(w.kept, key, stat, KEPT_MAX);
142142 }
143143
144144 /** Seed the cache for a (base, head) pair: for tests that need a known size without a repository. */
test/budgets/pages/owner-name-queue.json +2 −2
@@ -1,5 +1,5 @@
11 {
22 "pattern": "/:owner/:name/queue",
3 "statements": 64,
4 "why": "+4: the header's crew line for an admin (#6008)"
3 "statements": 66,
4 "why": "+4: the header's crew line for an admin (#6008); +2: the open pulls the collisions section reads (listOpenPulls, #17037)"
55 }
test/planner-ceiling.test.ts +1 −1
@@ -177,7 +177,7 @@ describe("the open-issue ceiling", () => {
177177 auth: { user: undefined, scope: undefined, via: "none" },
178178 theme: undefined,
179179 };
180 const text = await queuePage(sessionless).text();
180 const text = await (await queuePage(sessionless)).text();
181181 expect(text).toContain("Open-issue ceiling");
182182 expect(text).toContain("held by the open-issue ceiling");
183183 expect(text).toContain('data-ceiling-held="yes"');
test/pull-collisions.test.ts added +116
@@ -0,0 +1,116 @@
1 /** Which open pulls collide (#17037): real commits, real merge-tree, no checkout. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { collisionLines, partialLine, pullCollisions, type CollisionInput } from "../src/core/pull_collisions.ts";
7 import { collisionRows } from "../src/web/pages/queue.ts";
8 import { gitClientEnv } from "./helpers/git-client.ts";
9
10 const env = gitClientEnv({ GIT_AUTHOR_NAME: "A", GIT_AUTHOR_EMAIL: "[email protected]", GIT_COMMITTER_NAME: "A", GIT_COMMITTER_EMAIL: "[email protected]" });
11 let dir = "";
12 function git(...args: string[]): string {
13 const p = Bun.spawnSync(["git", ...args], { cwd: dir, env, stdout: "pipe", stderr: "pipe" });
14 if (p.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${p.stderr.toString()}`);
15 return p.stdout.toString().trim();
16 }
17 /** A branch off main with one commit writing `files`; its tip. */
18 function branch(name: string, files: Record<string, string>): string {
19 git("checkout", "-q", "-B", name, "main");
20 for (const [path, text] of Object.entries(files)) {
21 Bun.spawnSync(["sh", "-c", 'printf "%s" "$1" > "$2"', "_", text, path], { cwd: dir });
22 git("add", path);
23 }
24 git("commit", "-q", "-m", name);
25 return git("rev-parse", "HEAD");
26 }
27 let base = "";
28 const pull = (number: number, headOid: string): CollisionInput => ({ number, baseOid: base, headOid, crossRepo: false });
29
30 beforeAll(async () => {
31 dir = await mkdtemp(join(tmpdir(), "forge-collisions-"));
32 git("init", "-q", "-b", "main");
33 Bun.spawnSync(["sh", "-c", 'printf "one\\ntwo\\nthree\\n" > a.txt; printf "x\\n" > b.txt; printf "y\\n" > c.txt'], { cwd: dir });
34 git("add", ".");
35 git("commit", "-q", "-m", "seed");
36 base = git("rev-parse", "HEAD");
37 });
38 afterAll(async () => {
39 await rm(dir, { recursive: true, force: true });
40 });
41
42 test("two pulls editing the same line collide, and the sentence names the file", async () => {
43 const p1 = branch("p1", { "a.txt": "ONE\ntwo\nthree\n" });
44 const p2 = branch("p2", { "a.txt": "uno\ntwo\nthree\n" });
45 const found = await pullCollisions(dir, [pull(1, p1), pull(2, p2)]);
46 expect(found.pairs).toEqual([{ a: 1, b: 2, shared: ["a.txt"], conflicts: ["a.txt"] }]);
47 expect(collisionLines(found)).toEqual(["#1 collides with #2 in a.txt"]);
48 });
49
50 test("two pulls in different parts of one file share it but merge; unrelated pulls are not a pair", async () => {
51 const p1 = branch("p1", { "a.txt": "ONE\ntwo\nthree\n" });
52 const p2 = branch("p2", { "a.txt": "one\ntwo\nTHREE\n" });
53 const p3 = branch("p3", { "c.txt": "z\n" });
54 const found = await pullCollisions(dir, [pull(1, p1), pull(2, p2), pull(3, p3)]);
55 expect(found.pairs).toEqual([{ a: 1, b: 2, shared: ["a.txt"], conflicts: [] }]);
56 expect(collisionLines(found)[0]).toContain("both change a.txt");
57 });
58
59 test("the order lands the pull that collides with nobody before those that do", async () => {
60 const p1 = branch("p1", { "a.txt": "ONE\ntwo\nthree\n" });
61 const p2 = branch("p2", { "a.txt": "uno\ntwo\nthree\n" });
62 const p3 = branch("p3", { "c.txt": "z\n" });
63 const found = await pullCollisions(dir, [pull(1, p1), pull(2, p2), pull(3, p3)]);
64 expect(found.order).toEqual([3, 1, 2]);
65 });
66
67 test("a fork's pull is skipped, and the page shows the rows with links and the order", async () => {
68 const p1 = branch("p1", { "a.txt": "ONE\ntwo\nthree\n" });
69 const p2 = branch("p2", { "a.txt": "uno\ntwo\nthree\n" });
70 const fork: CollisionInput = { ...pull(9, p2), crossRepo: true };
71 const found = await pullCollisions(dir, [pull(1, p1), pull(2, p2), fork]);
72 expect(found.skipped).toEqual([9]);
73 const text = String(collisionRows(found, "/o/r"));
74 expect(text).toContain("#1 collides with #2 in a.txt");
75 expect(text).toContain("/o/r/pulls/2");
76 expect(collisionRows(await pullCollisions(dir, [pull(1, p1)]), "/o/r")).toBeNull();
77 });
78
79 test("at most 30 pulls are read: the 31st is left out and the reading says so", async () => {
80 const p1 = branch("p1", { "a.txt": "ONE\ntwo\nthree\n" });
81 const found = await pullCollisions(dir, Array.from({ length: 31 }, (_, i) => pull(i + 1, p1)));
82 expect(found.skipped).toEqual([31]);
83 expect(found.order).toHaveLength(30);
84 expect(partialLine(found)).toBe("Left out of this reading: #31. The order may change.");
85 });
86
87 test("a pass past its 400 ms budget starts no git and says it is partial", async () => {
88 const p1 = branch("p1", { "a.txt": "ONE\ntwo\nthree\n" });
89 const p2 = branch("p2", { "a.txt": "uno\ntwo\nthree\n" });
90 const late = await pullCollisions(dir, [pull(1, p1), pull(2, p2)], false, Date.now() - 1000);
91 expect(late.order).toEqual([]);
92 expect(late.skipped).toEqual([1, 2]);
93 expect(late.partial).toBe(true);
94 expect(partialLine(late)).toContain("#1, #2");
95 });
96
97 test("cachedOnly starts no git: an unseen head is left out, a kept reading is answered", async () => {
98 const p1 = branch("p1", { "b.txt": "fresh one\n" });
99 const p2 = branch("p2", { "b.txt": "fresh two\n" });
100 const cold = await pullCollisions(dir, [pull(1, p1), pull(2, p2)], true);
101 expect(cold.pairs).toEqual([]);
102 expect(cold.skipped).toEqual([1, 2]);
103 await pullCollisions(dir, [pull(1, p1), pull(2, p2)]);
104 const warm = await pullCollisions(dir, [pull(1, p1), pull(2, p2)], true);
105 expect(warm.pairs).toHaveLength(1);
106 expect(warm.partial).toBe(false);
107 expect(partialLine(warm)).toBeNull();
108 });
109
110 test("the page says in one line when the reading is partial", async () => {
111 const p1 = branch("p1", { "a.txt": "ONE\ntwo\nthree\n" });
112 const p2 = branch("p2", { "a.txt": "uno\ntwo\nthree\n" });
113 const fork: CollisionInput = { ...pull(9, p2), crossRepo: true };
114 const text = String(collisionRows(await pullCollisions(dir, [pull(1, p1), pull(2, p2), fork]), "/o/r"));
115 expect(text).toContain("Left out of this reading: #9. The order may change.");
116 });
test/queue-collisions-surfaces.test.ts added +149
@@ -0,0 +1,149 @@
1 /**
2 * The collisions read on its surfaces (#17037): sealed pulls, the flow tool, the terminal, the
3 * page.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { openPull } from "../src/actions/pulls.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { viewerCollisions } from "../src/core/pull_collisions.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { collisionScreen } from "../src/tui/screens/collisions.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { pollUntil } from "./helpers/poll.ts";
22 import { settleApp } from "./helpers/tui.ts";
23
24 quietLogs();
25
26 let dir: string;
27 let app: App;
28 let servers: Servers;
29 let alice: User;
30 let carol: User;
31 let pub: Repo;
32 let priv: Repo;
33 let carolTok = "";
34 let aliceTok = "";
35 let id = 1;
36
37 async function seed(repo: Repo, tag: string): Promise<void> {
38 const put = async (branch: string, content: string, from?: string) => {
39 const done = await commitToBranch(app, alice, repo, { branch, ...(from ? { from } : {}), message: `${tag} ${branch}`, files: [{ path: "code.txt", content }] });
40 if (!done.ok) throw new Error(JSON.stringify(done.error));
41 };
42 await put("main", "top\nbase\nend\n");
43 for (const [branch, line] of [["one", "first"], ["two", "second"], ["three", "third"]] as const) {
44 await put(branch, `top\n${line}\nend\n`, "main");
45 const opened = await openPull(app, alice, repo, { title: branch, baseBranch: "main", headBranch: branch });
46 if (!opened.ok) throw new Error(String(opened.error));
47 }
48 }
49
50 const call = async (token: string, args: unknown) => {
51 const res = await fetch(`${servers.url}/mcp`, {
52 method: "POST",
53 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
54 body: JSON.stringify({ jsonrpc: "2.0", id: id++, method: "tools/call", params: { name: "flow", arguments: args } }),
55 });
56 const body: any = await res.json();
57 const text: string = body.result.content[0].text;
58 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
59 };
60
61 beforeAll(async () => {
62 dir = await mkdtemp(join(tmpdir(), "forge-collide-surfaces-"));
63 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
64 servers = await serve(app);
65 const people: User[] = [];
66 for (const [username, first] of [["alice", true], ["carol", false]] as const) {
67 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
68 if (!made.ok) throw new Error(made.error);
69 people.push(made.value);
70 }
71 [alice, carol] = people as [User, User];
72 aliceTok = createToken(app.db, alice.id, "rw", "rw").token;
73 carolTok = createToken(app.db, carol.id, "rw", "rw").token;
74 const a = await createRepo(app, alice, { name: "lib", visibility: "public" });
75 const b = await createRepo(app, alice, { name: "vault", visibility: "private" });
76 if (!a.ok || !b.ok) throw new Error("repos");
77 pub = a.value;
78 priv = b.value;
79 await seed(pub, "pub");
80 await seed(priv, "priv");
81 // Pull 2 of the public repository is sealed: carol may not read it.
82 app.db.run("UPDATE issue SET sealed = 1 WHERE repo_id = ?1 AND number = 2", [pub.id]);
83 }, 120_000);
84
85 afterAll(async () => {
86 servers.stop();
87 app.close();
88 await rm(dir, { recursive: true, force: true });
89 });
90
91 test("the page answers from the cache without waiting on git, and shows the pairs once the cache is filled", async () => {
92 const load = async () => await (await fetch(`${servers.url}/alice/lib/queue`)).text();
93 const first = await load();
94 expect(first).toContain("data-collisions-partial");
95 expect(first).not.toContain("collides with");
96 let later = first;
97 await pollUntil(async () => (later = await load()).includes("collides with"), "the filled reading", 15_000);
98 expect(later).toContain("#1 collides with #3 in code.txt");
99 expect(later).not.toContain("#2 collides");
100 });
101
102 test("a sealed pull the viewer may not read is left out of the pairs and the order", async () => {
103 const mine = await viewerCollisions(app.db, app.reposRoot, pub, alice);
104 const theirs = await viewerCollisions(app.db, app.reposRoot, pub, carol);
105 expect(mine.order).toContain(2);
106 expect(theirs.order).not.toContain(2);
107 expect(theirs.pairs.every((p) => p.a !== 2 && p.b !== 2)).toBe(true);
108 expect(theirs.pairs).toHaveLength(1);
109 });
110
111 test("flow kind collisions: pairs, order and sentences; a sealed pull is not named to a guest", async () => {
112 const guest = await call(carolTok, { kind: "collisions", repo: "alice/lib" });
113 expect(guest.value.order).not.toContain(2);
114 expect(guest.value.pairs).toHaveLength(1);
115 expect(guest.value.says[0]).toBe("#1 collides with #3 in code.txt");
116 expect(JSON.stringify(guest.value)).not.toContain("#2");
117 const writer = await call(aliceTok, { kind: "collisions", repo: "alice/lib" });
118 expect(writer.value.pairs).toHaveLength(3);
119 });
120
121 test("flow kind collisions: a private repository is refused to a guest and read by its owner", async () => {
122 expect((await call(carolTok, { kind: "collisions", repo: "alice/vault" })).error).toContain("no such");
123 expect((await call(aliceTok, { kind: "collisions", repo: "alice/vault" })).value.pairs).toHaveLength(3);
124 });
125
126 test("the terminal screen shows the sentences and order, and not a sealed pull to a guest", async () => {
127 const screenFor = async (user: User): Promise<string> => {
128 const { app: tui, session } = createForgeApp(
129 app,
130 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: `SHA256:${user.username}`, user },
131 { terminal: headlessTerminal(140, 30), exitHooks: false },
132 );
133 tui.start();
134 try {
135 tui.ctx.push(collisionScreen(session, tui.ctx, pub));
136 await pollUntil(async () => {
137 await settleApp(tui);
138 return tui.screen.toText().includes("Order to land in");
139 }, "the order", 20_000);
140 return tui.screen.toText();
141 } finally {
142 tui.stop();
143 }
144 };
145 const guest = await screenFor(carol);
146 expect(guest).toContain("#1 collides with #3 in code.txt");
147 expect(guest).not.toContain("#2");
148 expect(await screenFor(alice)).toContain("#2");
149 }, 60_000);

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs