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

The pull API and the MCP say whether a pull merges: `mergeable` and `conflicts` on every reading of a pull #1415

Closed opened this
Closed without merging

scout/forge:scout/1413-the-pull-api-and-the-mcp-say-whether-a-p → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +265 −29
scripts/gate.ts +1
@@ -89,6 +89,7 @@ export const GATE: readonly string[] = [
8989 "test/fork-flow.test.ts",
9090 "test/fork-pull-approval.test.ts",
9191 "test/cross-repo-pull.test.ts",
92 "test/pull-mergeable.test.ts",
9293 "test/pulls.test.ts",
9394 "test/api-reader-marks.test.ts",
9495 "test/app-members.test.ts",
src/core/pulls.ts +57 −21
@@ -627,29 +627,65 @@ export async function pullStatus(
627627 : `refs/heads/${pull.headBranch}`;
628628 const headOid = (await resolveOid(dir, headRef)) ?? pull.headOid;
629629 const reviews = gate === undefined ? null : reviewGate(gate, pull, headOid);
630 const { ahead, mergeable: clean, conflicts } = await mergeReading(
631 dir,
632 baseOid,
633 headOid,
634 );
635 return { baseOid, headOid, ahead, mergeable: clean, conflicts, reviews };
636 }
637
638 interface MergeReading {
639 readonly ahead: number;
640 readonly mergeable: boolean;
641 readonly conflicts: string[];
642 }
643
644 /** Readings by `head:base` oid: a merge-tree over two commits never changes. */
645 const readings = new Map<string, MergeReading>();
646 const READINGS_MAX = 500;
647
648 async function mergeReading(
649 dir: string,
650 baseOid: string,
651 headOid: string,
652 ): Promise<MergeReading> {
653 const key = `${headOid}:${baseOid}`;
654 const known = readings.get(key);
655 if (known !== undefined) return { ...known, conflicts: [...known.conflicts] };
630656 const ahead = await aheadCount(dir, baseOid, headOid);
631 if (ahead === 0) {
632 return {
633 baseOid,
634 headOid,
635 ahead,
636 mergeable: false,
637 conflicts: [],
638 reviews,
639 };
657 let reading: MergeReading;
658 if (ahead === 0) reading = { ahead, mergeable: false, conflicts: [] };
659 else {
660 const check = await mergeable(dir, baseOid, headOid);
661 reading = check.ok
662 ? { ahead, mergeable: true, conflicts: [] }
663 : {
664 ahead,
665 mergeable: false,
666 conflicts: check.error.kind === "conflict" ? check.error.files : [],
667 };
668 // A git failure is not a verdict about the commits: do not remember it.
669 if (!check.ok && check.error.kind !== "conflict") return reading;
640670 }
641 const check = await mergeable(dir, baseOid, headOid);
642 if (check.ok)
643 return {
644 baseOid,
645 headOid,
646 ahead,
647 mergeable: true,
648 conflicts: [],
649 reviews,
650 };
651 const conflicts = check.error.kind === "conflict" ? check.error.files : [];
652 return { baseOid, headOid, ahead, mergeable: false, conflicts, reviews };
671 if (readings.size >= READINGS_MAX)
672 readings.delete(readings.keys().next().value!);
673 readings.set(key, reading);
674 return { ...reading, conflicts: [...reading.conflicts] };
675 }
676
677 /**
678 * Whether an open pull merges into its base's current head, and the paths
679 * that stop it — what the API and the MCP say on every reading of a pull.
680 * Null for a pull that is no longer open: there is nothing left to merge.
681 */
682 export async function pullMergeState(
683 dir: string,
684 pull: Pull,
685 ): Promise<{ mergeable: boolean; conflicts: string[] } | null> {
686 if (pull.state !== "open" || pull.mergedAt !== null) return null;
687 const { mergeable: clean, conflicts } = await pullStatus(dir, pull);
688 return { mergeable: clean, conflicts };
653689 }
654690
655691 /**
src/http/api.ts +18 −7
@@ -157,6 +157,7 @@ import {
157157 listPulls,
158158 pullDiff,
159159 pullDir,
160 pullMergeState,
160161 type Pull,
161162 } from "../core/pulls.ts";
162163 import {
@@ -2679,17 +2680,23 @@ export function apiRoutes(router: Router<Handler>): void {
26792680
26802681 // ── pull requests — so automation drives the review/merge loop ───────
26812682
2682 router.add("GET", "/api/v1/repos/:owner/:name/pulls", (ctx) => {
2683 router.add("GET", "/api/v1/repos/:owner/:name/pulls", async (ctx) => {
26832684 const repo = loadRepo(ctx);
26842685 if (!repo) return notFound();
26852686 const query = listQuery(ctx);
2686 const items = withLabelsMany(
2687 ctx,
2688 listPulls(ctx.app.db, repo.id, {
2689 ...query,
2690 ...sealedScope(ctx.app.db, repo, ctx.auth.user),
2691 }),
2687 const pulls = listPulls(ctx.app.db, repo.id, {
2688 ...query,
2689 ...sealedScope(ctx.app.db, repo, ctx.auth.user),
2690 });
2691 const states = await Promise.all(
2692 pulls.map(async (p) =>
2693 pullMergeState(await pullDirOf(ctx, repo, p), p),
2694 ),
26922695 );
2696 const items = withLabelsMany(ctx, pulls).map((item, i) => ({
2697 ...item,
2698 ...(states[i] ?? {}),
2699 }));
26932700 return json(paged(items, query.limit, (p) => p.number));
26942701 });
26952702
@@ -2751,6 +2758,10 @@ export function apiRoutes(router: Router<Handler>): void {
27512758 const hold = getHold(ctx.app.db, found.pull.id);
27522759 return json({
27532760 ...withLabels(ctx, found.pull),
2761 ...(await pullMergeState(
2762 await pullDirOf(ctx, found.repo, found.pull),
2763 found.pull,
2764 )),
27542765 status,
27552766 diff,
27562767 hold: hold === undefined ? null : holdJson(hold),
src/http/mcp.ts +38 −1
@@ -57,7 +57,7 @@ import { parseTargets } from "./feed.ts";
5757 import { appsRuntime, envsFor } from "../apps/runtime.ts";
5858 import { getIssue, getIssueById, listOpenAgentPullsVisibleTo } from "../core/issues.ts";
5959 import { waitsForPerson } from "../crew/review.ts";
60 import { getPull } from "../core/pulls.ts";
60 import { getPull, pullDir, pullMergeState } from "../core/pulls.ts";
6161 import { repoGraph } from "../core/dependencies.ts";
6262 import { pillarView } from "../core/pillars.ts";
6363 import { getAppByRepo } from "../core/apps.ts";
@@ -358,6 +358,43 @@ const TOOLS: readonly Tool[] = [
358358 : bad("refused", "that could not be said here");
359359 },
360360 },
361 {
362 name: "pull",
363 description:
364 "Read a pull: its title, state and head and base, and for an open pull whether it merges into the base's current head (`mergeable`) and the paths that stop it (`conflicts`). The same two fields as GET /api/v1/repos/:owner/:name/pulls/:number.",
365 inputSchema: {
366 type: "object",
367 properties: {
368 repo: REPO_ARG,
369 number: { type: "integer", minimum: 1 },
370 },
371 required: ["repo", "number"],
372 },
373 writes: false,
374 async run(ctx, user, args) {
375 const repo = repoArg(ctx, user, args);
376 if (isAnswer(repo)) return repo;
377 const n = args["number"];
378 const pull =
379 typeof n === "number" && Number.isInteger(n) && n > 0
380 ? getPull(ctx.app.db, repo.id, n)
381 : undefined;
382 if (pull === undefined || !mayView(ctx.app.db, repo, pull, user))
383 return bad("no_such_pull", `no pull #${String(n)}`);
384 const state = await pullMergeState(
385 await pullDir(ctx.app.db, ctx.app.reposRoot, repo, pull),
386 pull,
387 );
388 return good({
389 number: pull.number,
390 title: pull.title,
391 state: pull.mergedAt !== null ? "merged" : pull.state,
392 base: pull.baseBranch,
393 head: pull.headBranch,
394 ...(state ?? {}),
395 });
396 },
397 },
361398 {
362399 name: "edit",
363400 description:
test/mcp.test.ts +1
@@ -159,6 +159,7 @@ describe("the forge over MCP", () => {
159159 "tell",
160160 "share",
161161 "say",
162 "pull",
162163 "edit",
163164 "asks",
164165 "asks_act",
test/pull-mergeable.test.ts added +150
@@ -0,0 +1,150 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { serve, type Servers } from "../src/http/server.ts";
7 import { gitClientEnv } from "./helpers/git-client.ts";
8
9 const gitEnv = gitClientEnv();
10
11 describe("a pull says whether it merges", () => {
12 let dataDir: string;
13 let work: string;
14 let app: App;
15 let servers: Servers;
16 let base: string;
17 let token = "";
18 let dir: string;
19
20 async function gitOk(args: string[]): Promise<void> {
21 const p = Bun.spawn(["git", ...args], {
22 cwd: dir,
23 env: gitEnv,
24 stdout: "ignore",
25 stderr: "pipe",
26 });
27 const [err, code] = await Promise.all([
28 new Response(p.stderr).text(),
29 p.exited,
30 ]);
31 if (code !== 0) throw new Error(`git ${args.join(" ")}: ${err}`);
32 }
33 const auth = { authorization: "" };
34 const api = async (path: string, init: RequestInit = {}) =>
35 (await fetch(`${base}/api/v1/repos/dev/app${path}`, {
36 ...init,
37 headers: { ...auth, "content-type": "application/json" },
38 })).json() as Promise<any>;
39 const mcp = async (name: string, args: unknown) => {
40 const res = await fetch(`${base}/mcp`, {
41 method: "POST",
42 headers: {
43 "content-type": "application/json",
44 accept: "application/json, text/event-stream",
45 ...auth,
46 },
47 body: JSON.stringify({
48 jsonrpc: "2.0",
49 id: 1,
50 method: "tools/call",
51 params: { name, arguments: args },
52 }),
53 });
54 const body = (await res.json()) as any;
55 return JSON.parse(body.result.content[0].text);
56 };
57 const write = async (text: string, message: string) => {
58 await Bun.write(join(dir, "code.txt"), text);
59 await gitOk(["commit", "-am", message]);
60 };
61
62 beforeAll(async () => {
63 dataDir = await mkdtemp(join(tmpdir(), "forge-pm-"));
64 work = await mkdtemp(join(tmpdir(), "forge-pm-work-"));
65 app = createApp({ dataDir, port: 0 });
66 servers = await serve(app);
67 base = servers.url;
68 await fetch(`${base}/signup`, {
69 method: "POST",
70 body: new URLSearchParams({
71 username: "dev",
72 email: "[email protected]",
73 password: "pull-mergeable-pass",
74 }),
75 redirect: "manual",
76 });
77 token = await fetch(`${base}/api/v1/tokens`, {
78 method: "POST",
79 headers: { "content-type": "application/json" },
80 body: JSON.stringify({
81 adminConfirm: true,
82 username: "dev",
83 password: "pull-mergeable-pass",
84 name: "cli",
85 scope: "rw",
86 }),
87 })
88 .then((r) => r.json())
89 .then((j) => (j as { token: string }).token);
90 auth.authorization = `Bearer ${token}`;
91 await fetch(`${base}/api/v1/repos`, {
92 method: "POST",
93 headers: { ...auth, "content-type": "application/json" },
94 body: JSON.stringify({ name: "app", visibility: "public" }),
95 });
96 const remote = `${base.replace("http://", `http://dev:${token}@`)}/dev/app.git`;
97 dir = work;
98 await gitOk(["clone", remote, "app"]);
99 dir = join(work, "app");
100 await Bun.write(join(dir, "code.txt"), "alpha\nbeta\ngamma\n");
101 await gitOk(["add", "."]);
102 await gitOk(["commit", "-m", "base"]);
103 await gitOk(["push", "origin", "main"]);
104 });
105
106 afterAll(async () => {
107 servers.stop();
108 app.close();
109 await rm(dataDir, { recursive: true, force: true });
110 await rm(work, { recursive: true, force: true });
111 });
112
113 test("a conflicting pull reads false with the path; once the base resolves it, true", async () => {
114 await gitOk(["checkout", "-b", "loud"]);
115 await write("alpha\nBETA\ngamma\n", "loud beta");
116 await gitOk(["push", "origin", "loud"]);
117 const made = await api("/pulls", {
118 method: "POST",
119 body: JSON.stringify({ base: "main", head: "loud", title: "Loud" }),
120 });
121 expect(made.number).toBe(1);
122
123 // The base takes a different edit of the same line.
124 await gitOk(["checkout", "main"]);
125 await write("alpha\nbeta!\ngamma\n", "quiet beta");
126 await gitOk(["push", "origin", "main"]);
127
128 const one = await api("/pulls/1");
129 expect(one.mergeable).toBe(false);
130 expect(one.conflicts).toEqual(["code.txt"]);
131 const listed = await api("/pulls");
132 expect(listed.items[0].mergeable).toBe(false);
133 expect(listed.items[0].conflicts).toEqual(["code.txt"]);
134 const seen = await mcp("pull", { repo: "dev/app", number: 1 });
135 expect(seen.mergeable).toBe(false);
136 expect(seen.conflicts).toEqual(["code.txt"]);
137
138 // The base moves to hold the same line the pull wants.
139 await write("alpha\nBETA\ngamma\n", "the same edit");
140 await gitOk(["push", "origin", "main"]);
141
142 const after = await api("/pulls/1");
143 expect(after.mergeable).toBe(true);
144 expect(after.conflicts).toEqual([]);
145 expect((await api("/pulls")).items[0].mergeable).toBe(true);
146 const mcpAfter = await mcp("pull", { repo: "dev/app", number: 1 });
147 expect(mcpAfter.mergeable).toBe(true);
148 expect(mcpAfter.conflicts).toEqual([]);
149 });
150 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs