The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { expect, it } from "@effect/vitest"; |
| 2 | import * as Layer from "effect/Layer"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Schema from "effect/Schema"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Redacted from "effect/Redacted"; |
| 7 | import { HttpClient, HttpClientResponse } from "effect/http"; |
| 8 | import { ChildProcessSpawner } from "effect/process"; |
| 9 | import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; |
| 10 | import * as GitHubRest from "./GitHubRest.ts"; |
| 11 | import * as GitHubCredentials from "./GitHubCredentials.ts"; |
| 12 | import * as GitHubQuota from "./GitHubQuota.ts"; |
| 13 | import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts"; |
| 14 | import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; |
| 15 | import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts"; |
| 16 | import * as GitHubAppAccess from "./GitHubAppAccess.ts"; |
| 17 | import * as GitHubAppSignIn from "./GitHubAppSignIn.ts"; |
| 18 | |
| 19 | const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ |
| 20 | enabled: false, |
| 21 | token: () => Effect.succeedNone, |
| 22 | invalidate: () => Effect.void, |
| 23 | }); |
| 24 | |
| 25 | type Call = ReadonlyArray<string>; |
| 26 | type Send = (call: Call, kind: "graphql" | "rest") => Effect.Effect<unknown>; |
| 27 | |
| 28 | let gitCalls: Array<ReadonlyArray<string>> = []; |
| 29 | const fakeGit = Layer.mergeAll( |
| 30 | TestSourceControlHost.layer({ |
| 31 | process: { |
| 32 | run: (input) => |
| 33 | Effect.sync(() => { |
| 34 | gitCalls.push(input.args); |
| 35 | const stdout = |
| 36 | input.args[0] === "rev-parse" || input.args[0] === "merge-base" ? "new-sha\n" : ""; |
| 37 | return { |
| 38 | exitCode: ChildProcessSpawner.ExitCode(0), |
| 39 | stdout, |
| 40 | stderr: "", |
| 41 | stdoutTruncated: false, |
| 42 | stderrTruncated: false, |
| 43 | }; |
| 44 | }), |
| 45 | }, |
| 46 | }), |
| 47 | FileSystem.layerNoop({ makeTempDirectoryScoped: () => Effect.succeed("/tmp/scratch") }), |
| 48 | ); |
| 49 | |
| 50 | const graphQlHttp = (send: Send) => |
| 51 | HttpClient.make((request) => |
| 52 | Effect.gen(function* () { |
| 53 | const sent = |
| 54 | request.body._tag === "Uint8Array" |
| 55 | ? (JSON.parse(new TextDecoder().decode(request.body.body)) as { |
| 56 | readonly query: string; |
| 57 | readonly variables: Readonly<Record<string, unknown>>; |
| 58 | }) |
| 59 | : { query: "", variables: {} }; |
| 60 | const data = yield* send(words(sent.query, sent.variables), "graphql"); |
| 61 | return HttpClientResponse.fromWeb( |
| 62 | request, |
| 63 | new Response(encodeJson({ data }), { headers: { "content-type": "application/json" } }), |
| 64 | ); |
| 65 | }), |
| 66 | ); |
| 67 | |
| 68 | const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackAction>[0]) => |
| 69 | runStackAction(input).pipe( |
| 70 | Effect.provide( |
| 71 | Layer.mergeAll( |
| 72 | fakeGit, |
| 73 | Layer.mock(GitHubRest.GitHubRest)({ |
| 74 | credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }), |
| 75 | rest: (request) => |
| 76 | send(words(request.path, request.body), "rest").pipe( |
| 77 | Effect.map((body) => ({ |
| 78 | status: 200, |
| 79 | headers: {}, |
| 80 | body: encodeJson(body), |
| 81 | truncated: false, |
| 82 | invalidUtf8: false, |
| 83 | })), |
| 84 | ), |
| 85 | }), |
| 86 | GitHubRequestPolicy.layer.pipe( |
| 87 | Layer.provide( |
| 88 | Layer.mergeAll( |
| 89 | Layer.succeed(GitHubCredentials.GitHubCredentials, { |
| 90 | get: (host) => |
| 91 | Effect.succeed({ |
| 92 | host, |
| 93 | token: Redacted.make("token"), |
| 94 | source: "gh" as const, |
| 95 | fingerprint: "fp", |
| 96 | }), |
| 97 | saved: () => Effect.succeedNone, |
| 98 | fingerprint: (host, token) => Effect.succeed(`${host}:${token}`), |
| 99 | invalidate: () => Effect.void, |
| 100 | }), |
| 101 | GitHubQuota.layer, |
| 102 | SourceControlRateLimit.layer, |
| 103 | appSignedOut, |
| 104 | ), |
| 105 | ), |
| 106 | ), |
| 107 | Layer.mock(GitHubAppAccess.GitHubAppAccess)({ |
| 108 | credentialFor: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }), |
| 109 | }), |
| 110 | Layer.succeed(HttpClient.HttpClient, graphQlHttp(send)), |
| 111 | ), |
| 112 | ), |
| 113 | ); |
| 114 | |
| 115 | const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); |
| 116 | |
| 117 | function words(head: string, fields: unknown): Call { |
| 118 | return [ |
| 119 | head, |
| 120 | ...Object.entries((fields ?? {}) as Record<string, unknown>).map( |
| 121 | ([key, value]) => `${key}=${typeof value === "string" ? value : encodeJson(value)}`, |
| 122 | ), |
| 123 | ]; |
| 124 | } |
| 125 | |
| 126 | const isMutation = (call: Call) => call[0]!.startsWith("mutation"); |
| 127 | |
| 128 | const stack = [ |
| 129 | { |
| 130 | number: 50, |
| 131 | url: "https://api.github.com/repos/acme/web/stacks/50", |
| 132 | base: { ref: "main" }, |
| 133 | pull_requests: [ |
| 134 | { |
| 135 | number: 1, |
| 136 | title: "Base", |
| 137 | head: { ref: "base", sha: "aaa" }, |
| 138 | state: "closed", |
| 139 | merged_at: "2026-01-01T00:00:00Z", |
| 140 | }, |
| 141 | { |
| 142 | number: 2, |
| 143 | title: "Middle", |
| 144 | head: { ref: "middle", sha: "bbb" }, |
| 145 | state: "open", |
| 146 | draft: false, |
| 147 | }, |
| 148 | { number: 3, title: "Top", head: { ref: "top", sha: "ccc" }, state: "open", draft: false }, |
| 149 | ], |
| 150 | }, |
| 151 | ]; |
| 152 | const input = { |
| 153 | cwd: "/repo", |
| 154 | repository: "acme/web", |
| 155 | host: "github.com", |
| 156 | number: 3, |
| 157 | stackNumber: 50, |
| 158 | expectedStackHeads: [ |
| 159 | { number: 2, headSha: "bbb" }, |
| 160 | { number: 3, headSha: "ccc" }, |
| 161 | ], |
| 162 | action: "merge" as const, |
| 163 | }; |
| 164 | const writable = { headRepository: { viewerPermission: "WRITE" }, maintainerCanModify: false }; |
| 165 | const accessOf = (...pullRequests: ReadonlyArray<unknown>) => |
| 166 | Object.fromEntries( |
| 167 | pullRequests.map((pullRequest, index) => [`_${index}_repository`, { pullRequest }]), |
| 168 | ); |
| 169 | const access = accessOf(writable, writable); |
| 170 | |
| 171 | const branch = (number: number, headRefOid: string, behindBy = 1, processed: string[] = []) => ({ |
| 172 | data: { |
| 173 | processed: processed.map((headRefOid) => ({ headRefOid })), |
| 174 | repository: { |
| 175 | pullRequest: { id: `PR_${number}`, headRefOid, baseRef: { compare: { behindBy } } }, |
| 176 | }, |
| 177 | }, |
| 178 | }); |
| 179 | const rebased = { |
| 180 | data: { updatePullRequestBranch: { pullRequest: { headRefOid: "rebased-sha" } } }, |
| 181 | }; |
| 182 | const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased]; |
| 183 | |
| 184 | function fake(responses: readonly unknown[]) { |
| 185 | const calls: Call[] = []; |
| 186 | const execute: Send = (call) => |
| 187 | Effect.sync(() => { |
| 188 | calls.push(call); |
| 189 | const value = responses[calls.length - 1]; |
| 190 | if (value === undefined) throw new Error("Unexpected GitHub request"); |
| 191 | return value; |
| 192 | }); |
| 193 | return { execute, calls }; |
| 194 | } |
| 195 | |
| 196 | it.effect("submits one atomic merge with the reviewed head and respects the merge queue", () => |
| 197 | Effect.gen(function* () { |
| 198 | const api = fake([stack, { status: "enqueued", details: {} }]); |
| 199 | yield* runGitHubStackAction(api.execute, { ...input, mergeMethod: "squash" }); |
| 200 | expect(api.calls).toHaveLength(2); |
| 201 | expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async"); |
| 202 | expect(api.calls[1]).toContain("sha=ccc"); |
| 203 | expect(api.calls[1]).toContain("merge_action=default"); |
| 204 | expect(api.calls[1]).toContain("merge_method=squash"); |
| 205 | }), |
| 206 | ); |
| 207 | |
| 208 | it.effect("merges through the selected layer without including later draft layers", () => |
| 209 | Effect.gen(function* () { |
| 210 | const fiveLayers = [ |
| 211 | { |
| 212 | ...stack[0], |
| 213 | pull_requests: Array.from({ length: 5 }, (_, index) => ({ |
| 214 | number: index + 1, |
| 215 | head: { ref: `layer-${index + 1}`, sha: `sha-${index + 1}` }, |
| 216 | state: "open", |
| 217 | draft: index >= 3, |
| 218 | })), |
| 219 | }, |
| 220 | ]; |
| 221 | const api = fake([fiveLayers, { status: "merged", details: {} }]); |
| 222 | yield* runGitHubStackAction(api.execute, { |
| 223 | ...input, |
| 224 | number: 3, |
| 225 | expectedStackHeads: [1, 2, 3].map((number) => ({ number, headSha: `sha-${number}` })), |
| 226 | }); |
| 227 | expect(api.calls).toHaveLength(2); |
| 228 | expect(api.calls[1]).toContain("repos/acme/web/pulls/3/merge-async"); |
| 229 | expect(api.calls[1]).toContain("sha=sha-3"); |
| 230 | expect(api.calls[1]).toContain("merge_action=default"); |
| 231 | }), |
| 232 | ); |
| 233 | |
| 234 | it.effect("rejects stale reviewed heads below a selected middle layer", () => |
| 235 | Effect.gen(function* () { |
| 236 | const api = fake([stack]); |
| 237 | const result = yield* runGitHubStackAction(api.execute, { |
| 238 | ...input, |
| 239 | number: 2, |
| 240 | expectedStackHeads: [{ number: 2, headSha: "old-head" }], |
| 241 | }).pipe(Effect.result); |
| 242 | expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: "GitHubStackChangedError" } }); |
| 243 | expect(api.calls).toHaveLength(1); |
| 244 | }), |
| 245 | ); |
| 246 | |
| 247 | it.effect("does not merge from an already merged layer", () => |
| 248 | Effect.gen(function* () { |
| 249 | const api = fake([stack]); |
| 250 | const result = yield* runGitHubStackAction(api.execute, { |
| 251 | ...input, |
| 252 | number: 1, |
| 253 | expectedStackHeads: [], |
| 254 | }).pipe(Effect.result); |
| 255 | expect(result).toMatchObject({ |
| 256 | _tag: "Failure", |
| 257 | failure: { _tag: "GitHubStackUnsupportedError" }, |
| 258 | }); |
| 259 | expect(api.calls).toHaveLength(1); |
| 260 | }), |
| 261 | ); |
| 262 | |
| 263 | it.effect("retains stack identity and a rejection response without a message", () => |
| 264 | Effect.gen(function* () { |
| 265 | const rejection = { status: "failed", details: {} }; |
| 266 | const api = fake([stack, rejection]); |
| 267 | const result = yield* runGitHubStackAction(api.execute, input).pipe(Effect.result); |
| 268 | expect(result).toMatchObject({ |
| 269 | _tag: "Failure", |
| 270 | failure: { |
| 271 | _tag: "GitHubStackMergeRejectedError", |
| 272 | repository: input.repository, |
| 273 | number: input.number, |
| 274 | stackNumber: input.stackNumber, |
| 275 | cause: rejection, |
| 276 | }, |
| 277 | }); |
| 278 | }), |
| 279 | ); |
| 280 | |
| 281 | it.effect("refuses the entire rebase before mutation when a later fork denies write access", () => |
| 282 | Effect.gen(function* () { |
| 283 | const api = fake([ |
| 284 | stack, |
| 285 | accessOf(writable, { |
| 286 | headRepository: { viewerPermission: "READ" }, |
| 287 | maintainerCanModify: false, |
| 288 | }), |
| 289 | ]); |
| 290 | const result = yield* runGitHubStackAction(api.execute, { |
| 291 | ...input, |
| 292 | action: "update-branch", |
| 293 | }).pipe(Effect.result); |
| 294 | expect(result).toMatchObject({ |
| 295 | _tag: "Failure", |
| 296 | failure: { _tag: "GitHubStackPermissionError" }, |
| 297 | }); |
| 298 | expect(api.calls).toHaveLength(2); |
| 299 | }), |
| 300 | ); |
| 301 | |
| 302 | it.effect("allows a fork that explicitly permits maintainer updates", () => |
| 303 | Effect.gen(function* () { |
| 304 | const api = fake([ |
| 305 | stack, |
| 306 | accessOf(writable, { |
| 307 | headRepository: { viewerPermission: "READ" }, |
| 308 | maintainerCanModify: true, |
| 309 | }), |
| 310 | ...rebaseResponses, |
| 311 | ]); |
| 312 | yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" }); |
| 313 | expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2); |
| 314 | }), |
| 315 | ); |
| 316 | |
| 317 | it.effect("rebases for a GitHub App, which GitHub gives no permission to read", () => |
| 318 | Effect.gen(function* () { |
| 319 | gitCalls = []; |
| 320 | const api = fake([ |
| 321 | stack, |
| 322 | accessOf( |
| 323 | { headRepository: { viewerPermission: null }, maintainerCanModify: false }, |
| 324 | { headRepository: { viewerPermission: null }, maintainerCanModify: false }, |
| 325 | ), |
| 326 | ...rebaseResponses, |
| 327 | ]); |
| 328 | yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" }); |
| 329 | expect(gitCalls.filter((args) => args[0] === "push")).toHaveLength(2); |
| 330 | }), |
| 331 | ); |
| 332 | |
| 333 | it.effect("rebases the open layers bottom to top in a scratch clone, each onto the one below", () => |
| 334 | Effect.gen(function* () { |
| 335 | gitCalls = []; |
| 336 | const api = fake([stack, access]); |
| 337 | yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" }); |
| 338 | expect(api.calls[1]).toEqual( |
| 339 | expect.arrayContaining(["_0_number=2", "_1_number=3", "_0_owner=acme", "_0_name=web"]), |
| 340 | ); |
| 341 | expect(api.calls.some(isMutation)).toBe(false); |
| 342 | const rebases = gitCalls.filter((args) => args[0] === "rebase"); |
| 343 | expect(rebases).toEqual([ |
| 344 | ["rebase", "--quiet", "--onto", "origin/main", "aaa"], |
| 345 | ["rebase", "--quiet", "--onto", "new-sha", "bbb"], |
| 346 | ]); |
| 347 | expect(gitCalls.filter((args) => args[0] === "push")).toEqual([ |
| 348 | [ |
| 349 | "push", |
| 350 | "--quiet", |
| 351 | "--force-with-lease=refs/heads/middle:bbb", |
| 352 | "origin", |
| 353 | "new-sha:refs/heads/middle", |
| 354 | ], |
| 355 | [ |
| 356 | "push", |
| 357 | "--quiet", |
| 358 | "--force-with-lease=refs/heads/top:ccc", |
| 359 | "origin", |
| 360 | "new-sha:refs/heads/top", |
| 361 | ], |
| 362 | ]); |
| 363 | }), |
| 364 | ); |