Open History to see the last commit
1import { expect, it } from "@effect/vitest";
2import * as Layer from "effect/Layer";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as Schema from "effect/Schema";
6import * as TestClock from "effect/testing/TestClock";
7import * as FileSystem from "effect/FileSystem";
8import * as Redacted from "effect/Redacted";
9import { ChildProcessSpawner } from "effect/process";
10import * as GitHubApi from "../sourceControl/GitHubApi.ts";
11import * as VcsProcess from "../vcs/VcsProcess.ts";
12import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
13
14/**
15 * One request as the fake saw it, flattened to words: the path or document, then each variable
16 * or body field as `name=value`, so an assertion reads as "this request carried that value".
17 */
18type Call = ReadonlyArray<string>;
19type Send = (
20 call: Call,
21 kind: "graphql" | "rest",
22) => Effect.Effect<string, GitHubApi.GitHubApiError>;
23
24/** Every git command the cascade ran, in order; none actually runs. */
25let gitCalls: Array<ReadonlyArray<string>> = [];
26const fakeGit = Layer.mergeAll(
27 Layer.mock(VcsProcess.VcsProcess)({
28 run: (input) =>
29 Effect.sync(() => {
30 gitCalls.push(input.args);
31 const stdout =
32 input.args[0] === "rev-parse" || input.args[0] === "merge-base" ? "new-sha\n" : "";
33 return {
34 exitCode: ChildProcessSpawner.ExitCode(0),
35 stdout,
36 stderr: "",
37 stdoutTruncated: false,
38 stderrTruncated: false,
39 };
40 }),
41 }),
42 FileSystem.layerNoop({ makeTempDirectoryScoped: () => Effect.succeed("/tmp/scratch") }),
43);
44
45const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackAction>[0]) =>
46 runStackAction(input).pipe(
47 Effect.provide(
48 Layer.mergeAll(
49 fakeGit,
50 Layer.mock(GitHubApi.GitHubApi)({
51 credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }),
52 graphql: (request) => {
53 // GitHub refuses a document that declares a variable it never uses.
54 const declared = [...request.query.matchAll(/\$(\w+)\s*:/g)].map((match) => match[1]!);
55 const unused = declared.filter(
56 (name) => !new RegExp(`\\$${name}(?!\\w)(?!\\s*:)`).test(request.query),
57 );
58 if (unused.length > 0) {
59 return Effect.die(new Error(`Variables declared but not used: ${unused.join(", ")}`));
60 }
61 return send(words(request.query, request.variables), "graphql");
62 },
63 rest: (request) =>
64 send(words(request.path, request.body), "rest").pipe(
65 Effect.map((body) => ({
66 status: 200,
67 headers: {},
68 body,
69 truncated: false,
70 invalidUtf8: false,
71 })),
72 ),
73 }),
74 ),
75 ),
76 );
77
78const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
79
80function words(head: string, fields: unknown): Call {
81 return [
82 head,
83 ...Object.entries((fields ?? {}) as Record<string, unknown>).map(
84 ([key, value]) => `${key}=${typeof value === "string" ? value : encodeJson(value)}`,
85 ),
86 ];
87}
88
89const isMutation = (call: Call) => call[0]!.startsWith("mutation");
90
91const stack = [
92 {
93 number: 50,
94 url: "https://api.github.com/repos/acme/web/stacks/50",
95 base: { ref: "main" },
96 pull_requests: [
97 {
98 number: 1,
99 title: "Base",
100 head: { ref: "base", sha: "aaa" },
101 state: "closed",
102 merged_at: "2026-01-01T00:00:00Z",
103 },
104 {
105 number: 2,
106 title: "Middle",
107 head: { ref: "middle", sha: "bbb" },
108 state: "open",
109 draft: false,
110 },
111 { number: 3, title: "Top", head: { ref: "top", sha: "ccc" }, state: "open", draft: false },
112 ],
113 },
114];
115const input = {
116 cwd: "/repo",
117 repository: "acme/web",
118 host: "github.com",
119 number: 3,
120 stackNumber: 50,
121 expectedStackHeads: [
122 { number: 2, headSha: "bbb" },
123 { number: 3, headSha: "ccc" },
124 ],
125 action: "merge" as const,
126};
127const access = {
128 data: {
129 repository: {
130 pr2: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
131 pr3: { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false },
132 },
133 },
134};
135
136const branch = (number: number, headRefOid: string, behindBy = 1, processed: string[] = []) => ({
137 data: {
138 processed: processed.map((headRefOid) => ({ headRefOid })),
139 repository: {
140 pullRequest: { id: `PR_${number}`, headRefOid, baseRef: { compare: { behindBy } } },
141 },
142 },
143});
144const rebased = {
145 data: { updatePullRequestBranch: { pullRequest: { headRefOid: "rebased-sha" } } },
146};
147const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased];
148
149function fake(responses: readonly unknown[]) {
150 const calls: Call[] = [];
151 const execute: Send = (call) =>
152 Effect.sync(() => {
153 calls.push(call);
154 const value = responses[calls.length - 1];
155 if (value === undefined) throw new Error("Unexpected GitHub request");
156 return encodeJson(value);
157 });
158 return { execute, calls };
159}
160
161it.effect("submits one atomic merge with the reviewed head and respects the merge queue", () =>
162 Effect.gen(function* () {
163 const api = fake([stack, { status: "enqueued", details: {} }]);
164 yield* runGitHubStackAction(api.execute, { ...input, mergeMethod: "squash" });
165 expect(api.calls).toHaveLength(2);
166 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
167 expect(api.calls[1]).toContain("sha=ccc");
168 expect(api.calls[1]).toContain("merge_action=default");
169 expect(api.calls[1]).toContain("merge_method=squash");
170 }),
171);
172
173it.effect("merges through the selected layer without including later draft layers", () =>
174 Effect.gen(function* () {
175 const fiveLayers = [
176 {
177 ...stack[0],
178 pull_requests: Array.from({ length: 5 }, (_, index) => ({
179 number: index + 1,
180 head: { ref: `layer-${index + 1}`, sha: `sha-${index + 1}` },
181 state: "open",
182 draft: index >= 3,
183 })),
184 },
185 ];
186 const api = fake([fiveLayers, { status: "merged", details: {} }]);
187 yield* runGitHubStackAction(api.execute, {
188 ...input,
189 number: 3,
190 expectedStackHeads: [1, 2, 3].map((number) => ({ number, headSha: `sha-${number}` })),
191 });
192 expect(api.calls).toHaveLength(2);
193 expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async");
194 expect(api.calls[1]).toContain("sha=sha-3");
195 expect(api.calls[1]).toContain("merge_action=default");
196 }),
197);
198
199it.effect("rejects stale reviewed heads below a selected middle layer", () =>
200 Effect.gen(function* () {
201 const api = fake([stack]);
202 const result = yield* runGitHubStackAction(api.execute, {
203 ...input,
204 number: 2,
205 expectedStackHeads: [{ number: 2, headSha: "old-head" }],
206 }).pipe(Effect.result);
207 expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
208 expect(api.calls).toHaveLength(1);
209 }),
210);
211
212it.effect("does not merge from an already merged layer", () =>
213 Effect.gen(function* () {
214 const api = fake([stack]);
215 const result = yield* runGitHubStackAction(api.execute, {
216 ...input,
217 number: 1,
218 expectedStackHeads: [],
219 }).pipe(Effect.result);
220 expect(result).toMatchObject({
221 _tag: "Failure",
222 failure: { _tag: "GitHubStackUnsupportedError" },
223 });
224 expect(api.calls).toHaveLength(1);
225 }),
226);
227
228it.effect("polls an accepted merge and reports a later rule rejection", () =>
229 Effect.gen(function* () {
230 const api = fake([
231 stack,
232 { status: "pending", details: { uuid: "operation" } },
233 { status: "failed", details: { message: "Required checks have not passed" } },
234 ]);
235 const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
236 Effect.result,
237 Effect.forkChild,
238 );
239 yield* TestClock.adjust("1 second");
240 const result = yield* Fiber.join(fiber);
241 expect(result).toMatchObject({
242 _tag: "Failure",
243 failure: { _tag: "GitHubStackMergeRejectedError" },
244 });
245 expect(api.calls[2]).toContain("repos/acme/web/pulls/3/merge-async/operation");
246 }),
247);
248
249it.effect("retains stack identity and a rejection response without a message", () =>
250 Effect.gen(function* () {
251 const rejection = { status: "failed", details: {} };
252 const api = fake([stack, rejection]);
253 const result = yield* runGitHubStackAction(api.execute, input).pipe(Effect.result);
254 expect(result).toMatchObject({
255 _tag: "Failure",
256 failure: {
257 _tag: "GitHubStackMergeRejectedError",
258 repository: input.repository,
259 number: input.number,
260 stackNumber: input.stackNumber,
261 cause: rejection,
262 },
263 });
264 }),
265);
266
267it.effect("refuses a changed stack before performing any mutation", () =>
268 Effect.gen(function* () {
269 const api = fake([stack]);
270 const result = yield* runGitHubStackAction(api.execute, {
271 ...input,
272 expectedStackHeads: [
273 { number: 2, headSha: "old" },
274 { number: 3, headSha: "ccc" },
275 ],
276 }).pipe(Effect.result);
277 expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } });
278 expect(api.calls).toHaveLength(1);
279 }),
280);
281
282it.effect("refuses the entire rebase before mutation when a later fork denies write access", () =>
283 Effect.gen(function* () {
284 const api = fake([
285 stack,
286 {
287 data: {
288 repository: {
289 ...access.data.repository,
290 pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: false },
291 },
292 },
293 },
294 ]);
295 const result = yield* runGitHubStackAction(api.execute, {
296 ...input,
297 action: "update-branch",
298 }).pipe(Effect.result);
299 expect(result).toMatchObject({
300 _tag: "Failure",
301 failure: { _tag: "GitHubStackPermissionError" },
302 });
303 expect(api.calls).toHaveLength(2);
304 }),
305);
306
307it.effect("allows a fork that explicitly permits maintainer updates", () =>
308 Effect.gen(function* () {
309 const api = fake([
310 stack,
311 {
312 data: {
313 repository: {
314 ...access.data.repository,
315 pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: true },
316 },
317 },
318 },
319 ...rebaseResponses,
320 ]);
321 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
322 expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2);
323 }),
324);
325
326it.effect("bounds polling and reports a still-running merge without claiming success", () =>
327 Effect.gen(function* () {
328 const api = fake([
329 stack,
330 ...Array.from({ length: 40 }, () => ({ status: "pending", details: { uuid: "operation" } })),
331 ]);
332 const fiber = yield* runGitHubStackAction(api.execute, input).pipe(
333 Effect.result,
334 Effect.forkChild,
335 );
336 yield* TestClock.adjust("6 minutes");
337 expect(yield* Fiber.join(fiber)).toMatchObject({
338 _tag: "Failure",
339 failure: { _tag: "GitHubStackMergePendingError" },
340 });
341 expect(api.calls.length).toBeLessThan(40);
342 }),
343);
344
345it.effect("rebases the open layers bottom to top in a scratch clone, each onto the one below", () =>
346 Effect.gen(function* () {
347 gitCalls = [];
348 const api = fake([stack, access]);
349 yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
350 // GitHub is only read; every change is a git push with a lease on the reviewed head.
351 expect(api.calls.some(isMutation)).toBe(false);
352 const rebases = gitCalls.filter((args) => args[0] === "rebase");
353 expect(rebases).toEqual([
354 ["rebase", "--quiet", "--onto", "origin/main", "new-sha"],
355 ["rebase", "--quiet", "--onto", "new-sha", "bbb"],
356 ]);
357 expect(gitCalls.filter((args) => args[0] === "push")).toEqual([
358 [
359 "push",
360 "--quiet",
361 "--force-with-lease=refs/heads/middle:bbb",
362 "origin",
363 "new-sha:refs/heads/middle",
364 ],
365 [
366 "push",
367 "--quiet",
368 "--force-with-lease=refs/heads/top:ccc",
369 "origin",
370 "new-sha:refs/heads/top",
371 ],
372 ]);
373 }),
374);
375
376it.effect("checks every layer's write access before any git runs", () =>
377 Effect.gen(function* () {
378 gitCalls = [];
379 const api = fake([
380 stack,
381 {
382 data: {
383 repository: {
384 ...access.data.repository,
385 pr3: { headRepository: { viewerPermission: "READ" }, maintainerCanModify: false },
386 },
387 },
388 },
389 ]);
390 yield* Effect.flip(runGitHubStackAction(api.execute, { ...input, action: "update-branch" }));
391 expect(gitCalls).toEqual([]);
392 }),
393);