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

A pull whose issue names a team cannot merge until that team's reviewer approves, when the team has one #9945

Parked opened this
Closed without merging

scout/forge:scout/9930-a-pull-whose-issue-names-a-team-cannot-m → main 11 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +442 −12
docs/OPERATING.md +1 −1

Diff not shown — a line 2,708 characters wide (limit 2,000). +1 −1

View file
src/actions/pulls.ts +5 −1
@@ -9,6 +9,7 @@ import { takeGuestPull } from "./guests.ts";
99 import { requireAbility } from "./roles.ts";
1010 import { addComment as addIssueComment } from "../core/issues.ts";
1111 import { landedNote, leftNote, unticked } from "../core/done_on_main.ts";
12 import { teamsHolding } from "../core/issue_teams.ts";
1213 import { resolveOpen } from "../core/decisions.ts";
1314 import type { App } from "../app.ts";
1415 import { applyBoxPass, holdPass, landHeldPass, type BoxPass } from "./box_pass.ts";
@@ -476,7 +477,7 @@ export async function mergePull(
476477 requested: MergeStrategy,
477478 /** The merge queue's guard: land only onto this base, as this tree (#2036). */
478479 expect?: LandingExpect,
479 /** `pastGate`: the owner's break-glass (`checks/bypass.ts`) skips the checks requirement. */
480 /** `pastGate`: the owner's break-glass (`checks/bypass.ts`) skips the checks requirement and the teams' (#9930). */
480481 opts: { readonly pastGate?: boolean } = {},
481482 ): Promise<
482483 Result<{ mergeOid: string; carried: boolean }, AccessError | MergePullError>
@@ -550,6 +551,9 @@ export async function mergePull(
550551 db: app.db,
551552 requireReview: repo.requireReview,
552553 requireChecks: repo.requireChecks && opts.pastGate !== true,
554 ...(opts.pastGate === true
555 ? {}
556 : { teams: (pull: Pull, headOid: string) => teamsHolding(app.db, { ...pull, headOid }).map((v) => v.name) }),
553557 },
554558 strategy,
555559 ...(expect === undefined ? {} : { expect }),
src/core/issue_teams.ts +27
@@ -10,6 +10,7 @@ import { getIssue } from "./issues.ts";
1010 import { closesFromBody } from "./pulls.ts";
1111 import { listReviews, type Review, type ReviewState } from "./reviews.ts";
1212 import { getTeam } from "./teams.ts";
13 import { crewWithRole } from "./agents.ts";
1314
1415 export const TEAMS_MAX = 2;
1516
@@ -96,3 +97,29 @@ export function teamVerdicts(
9697 /** Whether every named team has a current verdict on the head (vacuously true with no teams). */
9798 export const teamsAnswered = (verdicts: readonly TeamVerdict[]): boolean =>
9899 verdicts.every((v) => v.state !== undefined && !v.stale);
100
101 /**
102 * The named teams that hold a pull's merge (#9930): each one that has a crew
103 * reviewer on this repository and no current approval of the head. A team
104 * with nobody here to ask does not hold it — its review lapses to a person
105 * like any review — so a forge whose teams are empty merges as before.
106 */
107 export function teamsHolding(
108 db: Database,
109 pull: { id: string; repoId: string; body: string; headOid: string },
110 ): TeamVerdict[] {
111 const verdicts = teamVerdicts(db, pull);
112 if (verdicts.length === 0) return [];
113 const reviewers = new Set(
114 (crewWithRole(db, [pull.repoId], "reviewer").get(pull.repoId) ?? []).map((a) => a.user.id),
115 );
116 return verdicts.filter(
117 (v) =>
118 !(v.state === "approved" && !v.stale) &&
119 (getTeam(db, v.team)?.members ?? []).some((m) => reviewers.has(m)),
120 );
121 }
122
123 /** The one sentence every door says while teams hold a merge: "Waiting on Design's review". */
124 export const teamWait = (names: readonly string[]): string =>
125 `Waiting on ${names.map((n) => `${n}'s`).join(" and ")} review`;
src/core/pulls.ts +22
@@ -796,6 +796,12 @@ export interface ReviewGate {
796796 * Read live inside the merge like the review verdict. @default false
797797 */
798798 readonly requireChecks?: boolean;
799 /**
800 * The names of the teams that hold this pull at `headOid` (#9930), read
801 * live inside the merge; handed in by the caller (`teamsHolding` in
802 * `core/issue_teams.ts`), which imports this module. Absent, no team holds.
803 */
804 readonly teams?: (pull: Pull, headOid: string) => readonly string[];
799805 }
800806
801807 export interface PullStatus {
@@ -1078,6 +1084,8 @@ export type MergePullError =
10781084 | "mirrored"
10791085 /** The repo requires an approval of this head, or a change was requested. */
10801086 | "review_required"
1087 /** A team the closed issue names, with a reviewer here, has not approved this head (#9930); `teams` are their names. */
1088 | { readonly kind: "team_review_required"; readonly teams: readonly string[] }
10811089 /** The repo requires a passing deploy of this head, and there is none yet. */
10821090 | "checks_required";
10831091
@@ -1087,6 +1095,16 @@ export interface LandingExpect {
10871095 readonly treeOid: string;
10881096 }
10891097
1098 /** The team gate's refusal at this head, when the gate asks for teams and one holds. */
1099 function teamHold(
1100 gate: ReviewGate | undefined,
1101 pull: Pull,
1102 headOid: string,
1103 ): { kind: "team_review_required"; teams: string[] } | undefined {
1104 const held = gate?.teams?.(pull, headOid) ?? [];
1105 return held.length === 0 ? undefined : { kind: "team_review_required", teams: [...held] };
1106 }
1107
10901108 export async function mergePull(
10911109 db: Database,
10921110 dir: string,
@@ -1130,6 +1148,8 @@ export async function mergePull(
11301148 const there = await pullStatus(input.sealedFrom, pull, input.gate);
11311149 if (there.reviews !== null && !there.reviews.mergeable)
11321150 return err("review_required");
1151 const held = teamHold(input.gate, live, there.headOid);
1152 if (held !== undefined) return err(held);
11331153 if (
11341154 input.gate?.requireChecks === true &&
11351155 checkSummary(input.gate.db, pull.id, there.headOid).state !== "ok"
@@ -1175,6 +1195,8 @@ export async function mergePull(
11751195 }
11761196 if (status.reviews !== null && !status.reviews.mergeable)
11771197 return err("review_required");
1198 const held = teamHold(input.gate, live, status.headOid);
1199 if (held !== undefined) return err(held);
11781200 // The check is the latest deploy run of *this* head. Read here, not
11791201 // handed in, for the same reason as the review verdict above. A landing
11801202 // the merge queue gated (`expect`) is not held for a green on an older
src/http/api.ts +4 −1
@@ -8,6 +8,7 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import { teamWait } from "../core/issue_teams.ts";
1112 import { guardedRefusal } from "../crew/stranger.ts";
1213 import { MAX_PASS, passOf } from "../actions/box_pass.ts";
1314 import { homeTruth } from "../system/home_truth.ts";
@@ -2757,7 +2758,9 @@ export function apiRoutes(router: Router<Handler>): void {
27572758 if (typeof merged.error !== "string")
27582759 return merged.error.kind === "guarded"
27592760 ? json({ error: "guarded", message: guardedRefusal(merged.error.paths), paths: merged.error.paths }, 409)
2760 : json({ error: merged.error.kind }, 409);
2761 : merged.error.kind === "team_review_required"
2762 ? json({ error: "team_review_required", message: teamWait(merged.error.teams), teams: merged.error.teams }, 409)
2763 : json({ error: merged.error.kind }, 409);
27612764 return originAware(merged.error, 409);
27622765 }
27632766 return json({ merged: true, ...merged.value });
src/tui/screens/pull.ts +27 −5
@@ -59,7 +59,7 @@ import {
5959 type EnvStatus, envsFor } from "../../apps/runtime.ts";
6060 import { proposedByText } from "../../core/proposal_token.ts";
6161 import { getAppByRepo } from "../../core/apps.ts";
62 import { teamVerdicts, type TeamVerdict } from "../../core/issue_teams.ts";
62 import { teamsHolding, teamVerdicts, teamWait, type TeamVerdict } from "../../core/issue_teams.ts";
6363 import { getIssue, type Issue } from "../../core/issues.ts";
6464 import { isProposed, pullMayRun } from "../../core/pull_trust.ts";
6565 import { guestWaits, mayApproveGuest } from "../../origins/guest.ts";
@@ -246,6 +246,8 @@ export function pullScreen(
246246 let step: PathStep | null = null;
247247 /** Where each team the issue names stands; empty when it names none. */
248248 let teams: TeamVerdict[] = [];
249 /** The names of the teams holding the merge (`teamsHolding`, #9930). */
250 let held: string[] = [];
249251 /** Settled threads the reader has opened back up, for this visit only. */
250252 const expanded = new Set<string>();
251253 let lines: Span[][] = [];
@@ -420,6 +422,10 @@ export function pullScreen(
420422 ...row,
421423 headOid: row.headOid || (facts?.headOid ?? ""),
422424 });
425 held =
426 row === undefined
427 ? []
428 : teamsHolding(f.db, { ...row, headOid: row.headOid || (facts?.headOid ?? "") }).map((v) => v.name);
423429 checkOld =
424430 repo !== undefined &&
425431 row !== undefined &&
@@ -603,7 +609,7 @@ export function pullScreen(
603609 const gated = (): boolean => {
604610 if (repo === undefined) return false;
605611 const now = standing();
606 return now.blocking.length > 0 || (requireReview && now.approvals === 0);
612 return now.blocking.length > 0 || (requireReview && now.approvals === 0) || held.length > 0;
607613 };
608614
609615 /**
@@ -772,7 +778,16 @@ export function pullScreen(
772778 const landed = await mergePull(f.app, f.user, target, row, strategy);
773779 if (!landed.ok) {
774780 const why = landed.error;
775 ctx.toast(typeof why !== "string" && why.kind === "guarded" ? guardedRefusal(why.paths) : errorText(String(why)), "danger");
781 ctx.toast(
782 typeof why === "string"
783 ? errorText(why)
784 : why.kind === "guarded"
785 ? guardedRefusal(why.paths)
786 : why.kind === "team_review_required"
787 ? teamWait(why.teams)
788 : errorText(why.kind),
789 "danger",
790 );
776791 return;
777792 }
778793 await reload();
@@ -1207,6 +1222,7 @@ export function pullScreen(
12071222 standing: standing(),
12081223 required: requireReview,
12091224 teams,
1225 held,
12101226 });
12111227 tabs(s, tabRow!, c, {
12121228 items: [
@@ -1461,7 +1477,9 @@ export function pullScreen(
14611477 ctx.toast(
14621478 now.blocking.length > 0
14631479 ? `changes requested by ${now.blocking.join(", ")}`
1464 : errorText("review_required"),
1480 : held.length > 0
1481 ? teamWait(held)
1482 : errorText("review_required"),
14651483 "attn",
14661484 );
14671485 return true;
@@ -1844,6 +1862,8 @@ function drawMergeBox(
18441862 standing: Standing;
18451863 required: boolean;
18461864 teams: readonly TeamVerdict[];
1865 /** The teams holding the merge, by name (#9930). */
1866 held?: readonly string[];
18471867 },
18481868 ): void {
18491869 const state = mergeState(issue, pull, mirrored, o.gated, o.checksGated);
@@ -1886,7 +1906,9 @@ function drawMergeBox(
18861906 : state === "review_required"
18871907 ? o.standing.blocking.length > 0
18881908 ? `Changes requested by ${o.standing.blocking.join(", ")}`
1889 : "Needs an approval of this head before it can merge"
1909 : (o.held ?? []).length > 0
1910 ? teamWait(o.held ?? [])
1911 : "Needs an approval of this head before it can merge"
18901912 : state === "checks_required"
18911913 ? o.check.state === "ok"
18921914 ? "Waiting on checks: checked against an older base; press C to check again"
src/web/pages/pull.ts +27 −2
@@ -85,7 +85,7 @@ import {
8585 type ThreadView,
8686 } from "../diff-view.ts";
8787 import { field, readForm } from "../form.ts";
88 import { teamVerdicts, type TeamVerdict } from "../../core/issue_teams.ts";
88 import { teamsHolding, teamVerdicts, teamWait, type TeamVerdict } from "../../core/issue_teams.ts";
8989 import { html, raw, when, type Html } from "../html.ts";
9090 import { flashTo, fragment, page } from "../layout.ts";
9191 import { liveRegionsJs } from "../client.ts";
@@ -475,6 +475,8 @@ function mergeBox(
475475 isApp: boolean,
476476 tier = "",
477477 stale = false,
478 /** The names of the teams holding the merge (`teamsHolding`), #9930. */
479 held: readonly string[] = [],
478480 ): Html {
479481 const thread = `${repoBase(repo)}/pulls/${pull.number}`;
480482 // A reader's head runs nothing until a writer approves it; say so rather
@@ -592,6 +594,25 @@ function mergeBox(
592594 );
593595 }
594596
597 // The team gate, `mergePull`'s `team_review_required`: each team the
598 // closed issue names, with a reviewer here, approves this head first.
599 if (held.length > 0) {
outdated

Principle 1 and 8: the box title says who it waits on, then the body explains the rule again in a long sentence. Say it once; keep the chips. Add a page test for this box.

600 return box(
601 "attn",
602 icon("eye"),
603 `${teamWait(held)}.`,
604 html`${reviewsChip(status.reviews, by)} ${checks}`,
605 when(mayMerge, () =>
606 btn("Merge pull request", {
607 variant: "primary",
608 icon: "merge",
609 disabled: true,
610 title: teamWait(held),
611 }),
612 ),
613 );
614 }
615
595616 // The check gate, `mergePull`'s `checks_required`: the deploy of the
596617 // commit that is head right now must have passed. Read live here so the
597618 // button is honest — the refusal itself happens in the merge.
@@ -921,6 +942,8 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
921942 const applied = labelsFor(ctx.app.db, pull.id);
922943 const allLabels = listLabels(ctx.app.db, repo.id);
923944 const by = tick("reviews", () => standings(ctx.app.db, pull, status.headOid));
945 // The teams holding the merge, by the gate `mergePull` asks (#9930).
946 const held = teamsHolding(ctx.app.db, { ...pull, headOid: status.headOid }).map((v) => v.name);
924947 // The checks are the deploy runs of the live head, read here for the same
925948 // reason the review gate is: the box and the merge answer one question.
926949 const check = tick("checks", () => checkSummary(ctx.app.db, pull.id, status.headOid));
@@ -1053,7 +1076,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
10531076 ${when(wall, (w) => wallCard(w, mayMerge ? thread : undefined))}
10541077 ${holdCard(ctx, repo, pull, { act: false })}
10551078 ${teamsCard(teamVerdicts(ctx.app.db, { ...pull, headOid: status.headOid }))}
1056 ${mergeBox(ctx, repo, pull, status, mayMerge, by, check, isApp, tier, stale)}
1079 ${mergeBox(ctx, repo, pull, status, mayMerge, by, check, isApp, tier, stale, held)}
10571080 ${slicesCard(base, thread, slices, status.ahead, ends, pull.state === "open" && pull.mergedAt === null, mayLand)}
10581081 ${await combinedCard(dir, pull, status.headOid, status.baseOid)}
10591082 <div class="split">
@@ -1098,6 +1121,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
10981121 pull.originHeadRepo === null &&
10991122 status.mergeable &&
11001123 !(status.reviews !== null && !status.reviews.mergeable) &&
1124 held.length === 0 &&
11011125 !checksHold(repo.requireChecks, check.state, stale),
11021126 }),
11031127 ],
@@ -1230,6 +1254,7 @@ export function mergeFailure(error: AccessError | MergePullError): string {
12301254 return "The base branch moved while merging. Try again.";
12311255 if (error.kind === "unsafe") return "That merge was refused as unsafe.";
12321256 if (error.kind === "guarded") return guardedRefusal(error.paths);
1257 if (error.kind === "team_review_required") return `${teamWait(error.teams)}. Nothing was merged.`;
12331258 return "Git refused the merge.";
12341259 }
12351260 const fromOrigin = originError(error);
src/web/studio/change.ts +4 −2
@@ -67,7 +67,7 @@ import { lookCard } from "../pages/looks.ts";
6767 import { approveHereCard, pullChecksLineFor, teamsCard } from "../pages/pull.ts";
6868 import { guestWalls, strangerCard } from "../pages/pull-guest.ts";
6969 import { combinedCard } from "../pages/pull-combined.ts";
70 import { teamVerdicts } from "../../core/issue_teams.ts";
70 import { teamsHolding, teamVerdicts } from "../../core/issue_teams.ts";
7171 import { liveRegionsJs } from "../client.ts";
7272 import { pullState } from "../pages/pulls.ts";
7373 import { workSpent } from "../pages/runs.ts";
@@ -519,7 +519,9 @@ async function changeConversation(
519519 // the same flag `shipSubmit` reads).
520520 const writer = ctx.auth.user !== undefined && canWrite(db, repo, ctx.auth.user);
521521 const openForOwner = writer && status !== undefined;
522 const reviewed = status?.reviews == null || status.reviews.mergeable;
522 const reviewed =
523 (status?.reviews == null || status.reviews.mergeable) &&
524 (status === undefined || teamsHolding(db, { ...pull, headOid: status.headOid }).length === 0);
523525 // A mirror's change lands on the origin, never here (`mergePull` refuses
524526 // it as "mirrored"): no decision is offered, and Files says where to merge.
525527 const mirrored = repo.origin !== null || pull.originHeadRepo !== null;
test/team-merge-gate-doors.test.ts added +186
@@ -0,0 +1,186 @@
1 /**
2 * The team gate's doors (#9930): the API, the terminal, the pull page and
3 * the studio all say the one sentence while a named team holds the merge,
4 * and none of them offers a merge it would refuse.
5 */
6
7 import { seatAs } from "./helpers/seat.ts";
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 { enableApp } from "../src/actions/apps.ts";
13 import { addToCrew, createAgent } from "../src/actions/crew.ts";
14 import { nameTeams } from "../src/actions/issue_teams.ts";
15 import { openIssue } from "../src/actions/issues.ts";
16 import { openPull } from "../src/actions/pulls.ts";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { createApp, type App } from "../src/app.ts";
19 import { getPull, type Pull } from "../src/core/pulls.ts";
20 import type { Repo } from "../src/core/repos.ts";
21 import { submitReview } from "../src/core/reviews.ts";
22 import { saveTeam } from "../src/core/teams.ts";
23 import { createUser, getUserByName, type User } from "../src/core/users.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { createForgeApp } from "../src/tui/forge.ts";
26 import { pullScreen } from "../src/tui/screens/pull.ts";
27 import { local } from "../src/tui/screens/where.ts";
28 import { headlessTerminal } from "../src/tui/term/terminal.ts";
29 import { quietLogs } from "./helpers/globals.ts";
30 import { tokenFor } from "./helpers/tokens.ts";
31 import { settleApp } from "./helpers/tui.ts";
32
33 quietLogs();
34
35 const WAIT = "Waiting on Design's review";
36 /** The page escapes the apostrophe; read it back the way a browser would. */
37 const unescape = (s: string): string => s.replace(/&#39;|&#x27;|&apos;/g, "'");
38
39 describe("the team gate at every door", () => {
40 let dataDir = "";
41 let app: App;
42 let servers: Servers;
43 let alice: User;
44 let repo: Repo;
45 let cookie = "";
46 let n = 0;
47 const id = (name: string) => getUserByName(app.db, name)!.id;
48
49 const pullNaming = async (): Promise<Pull> => {
50 const issue = openIssue(app, alice, repo, { title: "A chart" });
51 if (!issue.ok) throw new Error(issue.error);
52 const named = nameTeams(app, alice, repo, issue.value, ["design"]);
53 if (!named.ok) throw new Error(named.error);
54 const branch = `b${++n}`;
55 const c = await commitToBranch(app, alice, repo, {
56 branch,
57 base: "main",
58 message: branch,
59 files: [{ path: `${branch}.md`, content: "x\n" }],
60 });
61 if (!c.ok) throw new Error(JSON.stringify(c.error));
62 const o = await openPull(app, alice, repo, {
63 title: branch,
64 body: `Closes #${issue.value.number}`,
65 baseBranch: "main",
66 headBranch: branch,
67 });
68 if (!o.ok) throw new Error(String(o.error));
69 return o.value;
70 };
71 const get = (path: string, mode: "studio" | "forge" = "forge") =>
72 fetch(`${servers.url}${path}`, { headers: { cookie: `${cookie}; forge_mode=${mode}` }, redirect: "manual" });
73
74 beforeAll(async () => {
75 dataDir = await mkdtemp(join(tmpdir(), "forge-team-doors-"));
76 app = createApp({ dataDir, port: 0 });
77 servers = await serve(app);
78 const made = await createUser(app.db, {
79 origin: "seed",
80 trusted: true,
81 username: "alice",
82 email: "[email protected]",
83 password: "a-good-passphrase",
84 adminIfFirst: true,
85 });
86 if (!made.ok) throw new Error(made.error);
87 alice = made.value;
88 const r = await createRepo(app, alice, { name: "garden", visibility: "public" });
89 if (!r.ok) throw new Error(String(r.error));
90 repo = r.value;
91 const seeded = await commitToBranch(app, alice, repo, {
92 message: "seed",
93 files: [
94 { path: "package.json", content: '{"name":"garden","scripts":{"start":"bun run server.ts"}}\n' },
95 { path: "server.ts", content: "Bun.serve({ port: Number(process.env.PORT), fetch: () => new Response('ok') });\n" },
96 ],
97 });
98 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
99 const enabled = await enableApp(app, alice, repo, { slug: "garden" });
100 if (!enabled.ok) throw new Error(String(enabled.error));
101 const agent = await createAgent(app, alice, { username: "quill" });
102 if (!agent.ok) throw new Error(String(agent.error));
103 addToCrew(app, alice, repo, "quill");
104 seatAs(app.db, repo.id, id("quill"), "reviewer");
105 saveTeam(app.db, "design", { charter: "", dial: 0, members: [id("quill")] });
106 cookie = (
107 (
108 await fetch(`${servers.url}/signin`, {
109 method: "POST",
110 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
111 redirect: "manual",
112 })
113 ).headers.get("set-cookie") ?? ""
114 ).split(";")[0]!;
115 }, 120_000);
116
117 afterAll(async () => {
118 servers?.stop();
119 for (let i = 0; i < 20; i++) await new Promise((done) => setImmediate(done));
120 await Bun.sleep(100);
121 app?.close();
122 if (dataDir !== "") await rm(dataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
123 }, 30_000);
124
125 test("the API answers 409 with the code, the sentence and the teams", async () => {
126 const pull = await pullNaming();
127 const res = await fetch(`${servers.url}/api/v1/repos/alice/garden/pulls/${pull.number}/merge`, {
128 method: "POST",
129 headers: { authorization: `Bearer ${tokenFor(app, "alice", "rw")}`, "content-type": "application/json" },
130 body: JSON.stringify({ strategy: "merge" }),
131 });
132 expect(res.status).toBe(409);
133 expect(await res.json()).toEqual({ error: "team_review_required", message: WAIT, teams: ["Design"] });
134 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).toBeNull();
135 });
136
137 test("the pull page's merge box says the sentence once, with a disabled merge", async () => {
138 const pull = await pullNaming();
139 const page = unescape(await (await get(`/alice/garden/pulls/${pull.number}/files`)).text());
140 expect(page).toContain(`${WAIT}.`);
141 expect(page).toMatch(new RegExp(`<button[^>]*disabled[^>]*title="${WAIT}"|<button[^>]*title="${WAIT}"[^>]*disabled`));
142 expect(page).not.toContain("Ready to merge");
143 expect(page).not.toContain("names this team");
144 });
145
146 test("the studio does not offer Ship while the team holds it, and does once it approves", async () => {
147 const pull = await pullNaming();
148 const held = await (await get(`/alice/garden/pulls/${pull.number}`, "studio")).text();
149 expect(held).toContain(`id="decide"`);
150 expect(held).toContain("Not ready to ship");
151 expect(held).not.toContain(`/pulls/${pull.number}/ship`);
152 submitReview(app.db, { issueId: pull.id, authorId: id("quill"), state: "approved", commitOid: pull.headOid });
153 const free = await (await get(`/alice/garden/pulls/${pull.number}`, "studio")).text();
154 expect(free).toContain(`/pulls/${pull.number}/ship`);
155 });
156
157 test("the terminal's merge box says the sentence, and m toasts it rather than offering a merge", async () => {
158 const pull = await pullNaming();
159 const { app: tui, session } = createForgeApp(
160 app,
161 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:alice", user: alice },
162 { terminal: headlessTerminal(140, 44), exitHooks: false },
163 );
164 tui.start();
165 const until = async (ok: () => boolean): Promise<void> => {
166 const end = Date.now() + 20_000;
167 while (!ok()) {
168 if (Date.now() > end) throw new Error(tui.screen.toText());
169 await settleApp(tui);
170 await Bun.sleep(20);
171 }
172 };
173 try {
174 tui.ctx.push(pullScreen(session, tui.ctx, local(session, repo), pull.number));
175 await until(() => tui.screen.toText().includes(WAIT));
176 const before = tui.screen.toText().split(WAIT).length;
177 tui.dispatch({ type: "key", key: "m", ctrl: false, alt: false, shift: false });
178 // The toast is a second telling of the sentence; no merge confirm opens.
179 await until(() => tui.screen.toText().split(WAIT).length > before);
180 expect(tui.screen.toText()).not.toContain(`Merge #${pull.number}`);
181 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).toBeNull();
182 } finally {
183 tui.stop();
184 }
185 }, 60_000);
186 });
test/team-merge-gate.test.ts added +139
@@ -0,0 +1,139 @@
1 /**

Only the core gate is covered. Add tests for the API 409 body, the terminal path (m toast, merge-box line, gated) and the web merge box / studio ship decision; each would fail without the change.

2 * The team gate (#9930): a pull whose issue names a team that has a crew
3 * reviewer here does not land until that team approves its head. A team
4 * with nobody to ask does not hold it, and the owner's break-glass skips it.
5 */
6
7 import { seatAs } from "./helpers/seat.ts";
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 { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { nameTeams } from "../src/actions/issue_teams.ts";
14 import { openIssue } from "../src/actions/issues.ts";
15 import { mergePull, openPull } from "../src/actions/pulls.ts";
16 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
17 import { createApp, type App } from "../src/app.ts";
18 import { teamWait } from "../src/core/issue_teams.ts";
19 import { getPull, type Pull } from "../src/core/pulls.ts";
20 import type { Repo } from "../src/core/repos.ts";
21 import { submitReview } from "../src/core/reviews.ts";
22 import { saveTeam } from "../src/core/teams.ts";
23 import { createUser, getUserByName, type User } from "../src/core/users.ts";
24 import { mergeFailure } from "../src/web/pages/pull.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26
27 quietLogs();
28
29 describe("the team merge gate", () => {
30 let dataDir = "";
31 let app: App;
32 let alice: User;
33 let repo: Repo;
34 let n = 0;
35 const id = (name: string) => getUserByName(app.db, name)!.id;
36
37 const push = async (branch: string): Promise<void> => {
38 const c = await commitToBranch(app, alice, repo, {
39 branch,
40 base: "main",
41 message: `${branch} ${++n}`,
42 files: [{ path: `${branch}-${n}.md`, content: "x\n" }],
43 });
44 if (!c.ok) throw new Error(JSON.stringify(c.error));
45 };
46 const pullNaming = async (teams: string[]): Promise<Pull> => {
47 const issue = openIssue(app, alice, repo, { title: "A chart" });
48 if (!issue.ok) throw new Error(issue.error);
49 const named = nameTeams(app, alice, repo, issue.value, teams);
50 if (!named.ok) throw new Error(named.error);
51 const branch = `b${++n}`;
52 await push(branch);
53 const o = await openPull(app, alice, repo, {
54 title: branch,
55 body: `Closes #${issue.value.number}`,
56 baseBranch: "main",
57 headBranch: branch,
58 });
59 if (!o.ok) throw new Error(String(o.error));
60 return o.value;
61 };
62 const approve = (pull: Pull, who: string) =>
63 submitReview(app.db, { issueId: pull.id, authorId: id(who), state: "approved", commitOid: pull.headOid });
64 const merge = (pull: Pull, pastGate = false) =>
65 mergePull(app, alice, repo, getPull(app.db, repo.id, pull.number) ?? pull, "merge", undefined, { pastGate });
66
67 beforeAll(async () => {
68 dataDir = await mkdtemp(join(tmpdir(), "forge-team-gate-"));
69 app = createApp({ dataDir, port: 0 });
70 const made = await createUser(app.db, {
71 origin: "seed",
72 trusted: true,
73 username: "alice",
74 email: "[email protected]",
75 password: "a-good-passphrase",
76 adminIfFirst: true,
77 });
78 if (!made.ok) throw new Error(made.error);
79 alice = made.value;
80 const r = await createRepo(app, alice, { name: "garden", visibility: "private" });
81 if (!r.ok) throw new Error(String(r.error));
82 repo = r.value;
83 const seeded = await commitToBranch(app, alice, repo, {
84 message: "seed",
85 files: [{ path: "README.md", content: "# garden\n" }],
86 });
87 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
88 for (const name of ["quill", "rook"]) {
89 const agent = await createAgent(app, alice, { username: name });
90 if (!agent.ok) throw new Error(String(agent.error));
91 }
92 // quill reviews here; rook is an agent but no reviewer on this crew.
93 addToCrew(app, alice, repo, "quill");
94 seatAs(app.db, repo.id, id("quill"), "reviewer");
95 saveTeam(app.db, "design", { charter: "", dial: 0, members: [id("quill")] });
96 saveTeam(app.db, "platform", { charter: "", dial: 0, members: [id("rook")] });
97 }, 120_000);
98
99 afterAll(async () => {
100 for (let i = 0; i < 20; i++) await new Promise((done) => setImmediate(done));
101 await Bun.sleep(100);
102 app?.close();
103 if (dataDir !== "") await rm(dataDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
104 }, 30_000);
105
106 test("held while the team's review is awaited, in one sentence", async () => {
107 const pull = await pullNaming(["design"]);
108 const merged = await merge(pull);
109 expect(merged).toEqual({ ok: false, error: { kind: "team_review_required", teams: ["Design"] } });
110 expect(teamWait(["Design"])).toBe("Waiting on Design's review");
111 if (!merged.ok) expect(mergeFailure(merged.error)).toBe("Waiting on Design's review. Nothing was merged.");
112 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).toBeNull();
113 });
114
115 test("lands once the team approves the head", async () => {
116 const pull = await pullNaming(["design"]);
117 approve(pull, "quill");
118 expect((await merge(pull)).ok).toBe(true);
119 });
120
121 test("an approval of an older head holds", async () => {
122 const pull = await pullNaming(["design"]);
123 approve(pull, "quill");
124 await push(pull.headBranch);
125 const merged = await merge(pull);
126 expect(merged.ok).toBe(false);
127 if (!merged.ok) expect(merged.error).toEqual({ kind: "team_review_required", teams: ["Design"] });
128 });
129
130 test("a team with no reviewer here does not hold the pull", async () => {
131 const pull = await pullNaming(["platform"]);
132 expect((await merge(pull)).ok).toBe(true);
133 });
134
135 test("the owner's break-glass passes the team gate", async () => {
136 const pull = await pullNaming(["design"]);
137 expect((await merge(pull, true)).ok).toBe(true);
138 });
139 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs