The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,289 lines 91.6 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import type { Oid } from "@alchemy.run/git/Api";
3 import {
4 encodeCommit,
5 hashObject,
6 ObjectType,
7 parseCommit,
8 utf8Decode,
9 utf8Encode,
10 } from "@alchemy.run/git/Protocol/ObjectCodec";
11 import { expect } from "@alchemy.run/test";
12 import * as Test from "@alchemy.run/test/Alchemy";
13 /**
14 * THE PRIMARY SUITE — full local dev-mode coverage of git-service.
15 *
16 * `Test.make({ providers: Cloudflare.providers(), dev: true })` runs the
17 * whole service on the local RPC-sidecar topology (`alchemy dev`'s process
18 * shape): a local workerd Worker hosting the GitRepo/GitRegistry Durable
19 * Objects and the R2 simulator. No cloud API is touched — the worker serves
20 * from `http://localhost:<port>`.
21 *
22 * Coverage:
23 * (a) every REST endpooint of `GitApi` via the typed `HttpApiClient`
24 * (repos create/get/update/list/delete, refs list/get/update/remove
25 * with CAS, objects commit/log/tree/blob, tokens create/list/revoke,
26 * plus the raw blob/file streaming routes) including the typed
27 * 401/403/404/409/422 error taxonomy;
28 * (b) the real `git` CLI over the smart-HTTP wire endpoints — empty clone,
29 * first push, clone-back + `git fsck --strict`, incremental fetch,
30 * force-push CAS, branch + annotated-tag lifecycle, readOnly rejection,
31 * and the wire auth matrix.
32 */
33 import * as Alchemy from "alchemy";
34 import * as Data from "effect/Data";
35 import * as Effect from "effect/Effect";
36 import * as FileSystem from "effect/FileSystem";
37 import * as HttpApiClient from "effect/http-api/HttpApiClient";
38 import * as HttpClient from "effect/http/HttpClient";
39 import * as HttpClientRequest from "effect/http/HttpClientRequest";
40 import * as Path from "effect/Path";
41 import * as ChildProcess from "effect/process/ChildProcess";
42 import { MinimumLogLevel } from "effect/References";
43 import * as Result from "effect/Result";
44 import * as Schedule from "effect/Schedule";
45 import * as Stream from "effect/Stream";
46 import ProtectedGitHost from "./fixtures/protected-stack.ts";
47 import TestGitHost, { TEST_SECRET, TEST_SECRET_DEV, TestApi } from "./fixtures/stack.ts";
48 import { verifyPackResponse } from "./harness/pack.ts";
49
50 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
51 // matching the process topology of the real `alchemy dev` command.
52 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
53 providers: Cloudflare.providers(),
54 dev: true,
55 });
56
57 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
58
59 // The local suite must not touch the cloud, so it composes its own Stack over
60 // `Alchemy.localState()` — the same user pattern as production, just with a
61 // local state store: deploy the fixture's building-block assembly worker.
62 // Importing `./fixtures/stack.ts` above installed the TEST_SECRET into
63 // the deployer env before this plan resolves
64 // the suite fixture's `AuthenticatedTest`.
65 const LocalStack = Alchemy.Stack(
66 "GitServiceLocalStack",
67 { providers: Cloudflare.providers(), state: Alchemy.localState() },
68 Effect.gen(function* () {
69 const host = yield* TestGitHost;
70 return { url: host.url.as<string>() };
71 }),
72 );
73
74 // ── readiness ───────────────────────────────────────────────────────────────
75
76 class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
77 status: number;
78 }> {}
79
80 const boundedReadiness = Schedule.max([
81 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
82 Schedule.recurs(20),
83 ]);
84
85 /** Wait until the local worker answers the admin repo listing with a 200. */
86 const awaitReady = (url: string) =>
87 Effect.gen(function* () {
88 const client = yield* HttpClient.HttpClient;
89 yield* client
90 .get(`${url}/api/v1/repos`, {
91 headers: { authorization: `Bearer ${TEST_SECRET}` },
92 })
93 .pipe(
94 Effect.flatMap((res) =>
95 res.status === 200
96 ? Effect.void
97 : Effect.fail(new WorkerNotReady({ status: res.status })),
98 ),
99 // retries transport errors (connection refused during boot) too
100 Effect.retry({ schedule: boundedReadiness }),
101 );
102 }).pipe(Effect.orDie);
103
104 const stack = beforeAll(
105 deploy(LocalStack).pipe(
106 Effect.tap(({ url }) =>
107 Effect.gen(function* () {
108 // proof the run is local: no cloud URL, a localhost port
109 expect(url).toMatch(/^http:\/\/localhost:\d+$/);
110 yield* awaitReady(url);
111 }),
112 ),
113 logLevel,
114 ),
115 );
116 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(LocalStack));
117
118 // ── typed REST client ───────────────────────────────────────────────────────
119
120 const makeClient = (url: string, token: string) =>
121 HttpApiClient.make(TestApi, {
122 baseUrl: url,
123 transformClient: HttpClient.mapRequest((request) =>
124 request.pipe(HttpClientRequest.bearerToken(token)),
125 ),
126 });
127
128 /** A client that sends NO Authorization header — the anonymous caller. */
129 const makeAnonymousClient = (url: string) => HttpApiClient.make(TestApi, { baseUrl: url });
130
131 const asOid = (oid: string): Oid => oid as Oid;
132
133 /** Assert an effect fails with the given tagged error. */
134 const expectTag = <A, E extends { readonly _tag: string }, R>(
135 effect: Effect.Effect<A, E, R>,
136 tag: string,
137 ) =>
138 Effect.gen(function* () {
139 const result = yield* Effect.result(effect);
140 expect(Result.isFailure(result)).toBe(true);
141 if (Result.isFailure(result)) {
142 expect(result.failure._tag).toBe(tag);
143 return result.failure;
144 }
145 return yield* Effect.die("unreachable");
146 });
147
148 // ── git CLI plumbing ────────────────────────────────────────────────────────
149
150 class GitError extends Data.TaggedError("GitError")<{
151 readonly args: ReadonlyArray<string>;
152 readonly exitCode: number;
153 readonly stdout: string;
154 readonly stderr: string;
155 }> {
156 override get message() {
157 return `git ${this.args.join(" ")} → exit ${this.exitCode}\n${this.stderr.trim()}\n${this.stdout.trim()}`;
158 }
159 }
160
161 /** Run `git <args>` in `cwd`, capturing exit code and output. Bounded. */
162 const git = Effect.fn(function* (cwd: string, ...args: Array<string>) {
163 const handle = yield* ChildProcess.make("git", args, {
164 cwd,
165 env: {
166 GIT_TERMINAL_PROMPT: "0",
167 GIT_CONFIG_NOSYSTEM: "1",
168 GIT_CONFIG_GLOBAL: "/dev/null",
169 GIT_AUTHOR_NAME: "Test User",
170 GIT_AUTHOR_EMAIL: "test@example.com",
171 GIT_COMMITTER_NAME: "Test User",
172 GIT_COMMITTER_EMAIL: "test@example.com",
173 },
174 extendEnv: true,
175 });
176 const [exitCode, stdout, stderr] = yield* Effect.all(
177 [
178 handle.exitCode,
179 Stream.mkString(Stream.decodeText(handle.stdout)),
180 Stream.mkString(Stream.decodeText(handle.stderr)),
181 ],
182 { concurrency: 3 },
183 );
184 return { args, exitCode, stdout: stdout.trim(), stderr };
185 }, Effect.timeout("60 seconds"));
186
187 /** Run git and require exit 0, failing with the captured output otherwise. */
188 const mustGit = Effect.fn(function* (cwd: string, ...args: Array<string>) {
189 const result = yield* git(cwd, ...args);
190 if (result.exitCode !== 0) {
191 return yield* new GitError(result);
192 }
193 return result;
194 });
195
196 /** Run git and require a non-zero exit (an expected rejection). */
197 const mustFailGit = Effect.fn(function* (cwd: string, ...args: Array<string>) {
198 const result = yield* git(cwd, ...args);
199 if (result.exitCode === 0) {
200 return yield* new GitError(result);
201 }
202 return result;
203 });
204
205 /** `http://x:<token>@localhost:<port>/<owner>/<repo>.git` */
206 const authRemote = (url: string, token: string, owner: string, repo: string) =>
207 Effect.sync(() => {
208 const parsed = new URL(url);
209 return `${parsed.protocol}//x:${token}@${parsed.host}/${owner}/${repo}.git`;
210 });
211
212 /** `git rev-parse <rev>` → the 40-hex oid. */
213 const revParse = (cwd: string, rev: string) =>
214 Effect.map(mustGit(cwd, "rev-parse", rev), (result) => result.stdout);
215
216 const tempDir = Effect.gen(function* () {
217 const fs = yield* FileSystem.FileSystem;
218 return yield* fs.makeTempDirectory({ prefix: "git-service-local-" });
219 });
220
221 /** Create a repo via the admin REST client, returning its bootstrap token. */
222 /** Poll marker: repo still visible while its async purge drains. */
223 class StillDeleting extends Data.TaggedError("StillDeleting")<{}> {}
224
225 const createRepo = Effect.fn(function* (url: string, owner: string, name: string) {
226 const client = yield* makeClient(url, TEST_SECRET);
227 // Retry-safe: a previous (failed, runner-retried) attempt may have left
228 // the repo behind — delete it and wait out the async purge before
229 // creating, so the create below never 409s on our own leftovers.
230 yield* client.repos.delete({ params: { owner, repo: name } }).pipe(
231 Effect.flatMap(() =>
232 client.repos.get({ params: { owner, repo: name } }).pipe(
233 Effect.flatMap(() => Effect.fail(new StillDeleting())),
234 Effect.catchTag("RepoNotFound", () => Effect.void),
235 Effect.retry({
236 while: (error) => error instanceof StillDeleting,
237 schedule: Schedule.spaced("250 millis"),
238 times: 40,
239 }),
240 ),
241 ),
242 Effect.catchTag("RepoNotFound", () => Effect.void),
243 );
244 const created = yield* client.repos.create({ payload: { owner, name } });
245 return {
246 client,
247 created,
248 token: TEST_SECRET,
249 remote: yield* authRemote(url, TEST_SECRET, owner, name),
250 };
251 });
252
253 // ═══════════════════════════════════════════════════════════════════════════
254 // (a) REST management plane
255 // ═══════════════════════════════════════════════════════════════════════════
256
257 test(
258 "repos: create, duplicate 409, get, list, update, typed auth failures",
259 Effect.gen(function* () {
260 const { url } = yield* stack;
261 const admin = yield* makeClient(url, TEST_SECRET);
262
263 const created = yield* admin.repos.create({
264 payload: { owner: "acme", name: "rest-repos", description: "d0" },
265 });
266 expect(created.repo.owner).toBe("acme");
267 expect(created.repo.name).toBe("rest-repos");
268 expect(created.repo.status).toBe("ready");
269 expect(created.repo.defaultBranch).toBe("main");
270 expect(created.repo.readOnly).toBe(false);
271 expect(created.remote).toContain("/acme/rest-repos.git");
272
273 // duplicate → typed 409
274 yield* expectTag(
275 admin.repos.create({ payload: { owner: "acme", name: "rest-repos" } }),
276 "RepoAlreadyExists",
277 );
278
279 const fetched = yield* admin.repos.get({
280 params: { owner: "acme", repo: "rest-repos" },
281 });
282 expect(fetched.repoId).toBe(created.repo.repoId);
283 expect(fetched.description).toBe("d0");
284
285 // list-all is admin-only and contains the repo
286 const listed = yield* admin.repos.list({ query: {} });
287 expect(listed.items.some((r) => r.owner === "acme" && r.name === "rest-repos")).toBe(true);
288
289 // PATCH description + readOnly round-trip
290 const patched = yield* admin.repos.update({
291 params: { owner: "acme", repo: "rest-repos" },
292 payload: { description: "d1", readOnly: true },
293 });
294 expect(patched.description).toBe("d1");
295 expect(patched.readOnly).toBe(true);
296 yield* admin.repos.update({
297 params: { owner: "acme", repo: "rest-repos" },
298 payload: { readOnly: false },
299 });
300
301 // missing repo → typed 404
302 yield* expectTag(
303 admin.repos.get({ params: { owner: "acme", repo: "does-not-exist" } }),
304 "RepoNotFound",
305 );
306
307 // no credentials → typed 401 from the fixture's middleware
308 const anonymous = yield* HttpApiClient.make(TestApi, { baseUrl: url });
309 yield* expectTag(
310 anonymous.repos.get({ params: { owner: "acme", repo: "rest-repos" } }),
311 "Unauthorized",
312 );
313
314 // garbage token → typed 401 (the middleware rejects it before any route)
315 const garbage = yield* makeClient(url, "gs_garbage-token");
316 yield* expectTag(
317 garbage.repos.get({ params: { owner: "acme", repo: "rest-repos" } }),
318 "Unauthorized",
319 );
320
321 // Anonymous callers may read one public repository at a time;
322 // listing is not that, so it 401s like any other anonymous call.
323 yield* expectTag(anonymous.repos.list({ query: {} }), "Unauthorized");
324 // The engine lists everything the Registry holds; `public: true`
325 // narrows it, so a private repo is not in that view.
326 const publicListing = yield* admin.repos.list({
327 query: { public: true },
328 });
329 expect(
330 publicListing.items.some((row) => row.owner === "acme" && row.name === "rest-repos"),
331 ).toBe(false);
332 }).pipe(logLevel),
333 {
334 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
335 timeout: 120_000,
336 },
337 );
338
339 test(
340 "refs + objects: CAS writes, typed conflicts, commit/log/tree/blob reads, raw routes",
341 Effect.gen(function* () {
342 const { url } = yield* stack;
343 const { client: admin, remote } = yield* createRepo(url, "acme", "rest-refs");
344 const params = { owner: "acme", repo: "rest-refs" };
345 const fs = yield* FileSystem.FileSystem;
346 const path = yield* Path.Path;
347
348 // refs on a fresh repo are empty
349 const empty = yield* admin.refs.list({ params, query: {} });
350 expect(empty.refs).toEqual([]);
351
352 // seed real objects over the wire (2 commits)
353 const tmp = yield* tempDir;
354 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", remote, "work");
355 const work = path.join(tmp, "work");
356 yield* fs.writeFileString(path.join(work, "hello.txt"), "hello local\n");
357 yield* mustGit(work, "add", "-A");
358 yield* mustGit(work, "commit", "-m", "c1: seed");
359 yield* fs.writeFileString(path.join(work, "hello.txt"), "hello local, v2\n");
360 yield* mustGit(work, "add", "-A");
361 yield* mustGit(work, "commit", "-m", "c2: bump");
362 yield* mustGit(work, "push", "origin", "main");
363 const head = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
364 const parent = (yield* mustGit(work, "rev-parse", "HEAD~1")).stdout;
365
366 // refs.list / refs.get agree with the CLI
367 const refs = yield* admin.refs.list({
368 params,
369 query: { prefix: "refs/heads/" },
370 });
371 expect(refs.refs.map((r) => r.name)).toEqual(["refs/heads/main"]);
372 expect(refs.refs[0]!.oid).toBe(head);
373 const mainRef = yield* admin.refs.get({
374 params,
375 query: { name: "refs/heads/main" },
376 });
377 expect(mainRef.oid).toBe(head);
378 yield* expectTag(admin.refs.get({ params, query: { name: "refs/heads/nope" } }), "RefNotFound");
379
380 // CAS create (expectedOid: null = must-not-exist)
381 const branch = yield* admin.refs.update({
382 params,
383 query: { name: "refs/heads/rest-branch" },
384 payload: { newOid: asOid(parent), expectedOid: null },
385 });
386 expect(branch.oid).toBe(parent);
387 // must-not-exist against an existing ref → typed 409
388 yield* expectTag(
389 admin.refs.update({
390 params,
391 query: { name: "refs/heads/rest-branch" },
392 payload: { newOid: asOid(head), expectedOid: null },
393 }),
394 "RefConflict",
395 );
396 // stale expectedOid → typed 409
397 yield* expectTag(
398 admin.refs.update({
399 params,
400 query: { name: "refs/heads/rest-branch" },
401 payload: { newOid: asOid(head), expectedOid: asOid(head) },
402 }),
403 "RefConflict",
404 );
405 // correct CAS moves the ref
406 const moved = yield* admin.refs.update({
407 params,
408 query: { name: "refs/heads/rest-branch" },
409 payload: { newOid: asOid(head), expectedOid: asOid(parent) },
410 });
411 expect(moved.oid).toBe(head);
412
413 // pointing a ref at an object we do not have → typed 404
414 yield* expectTag(
415 admin.refs.update({
416 params,
417 query: { name: "refs/heads/rest-branch" },
418 payload: { newOid: asOid("f".repeat(40)) },
419 }),
420 "ObjectNotFound",
421 );
422 // remove with a stale CAS → 409; with the right one → gone
423 yield* expectTag(
424 admin.refs.remove({
425 params,
426 query: { name: "refs/heads/rest-branch" },
427 payload: { expectedOid: asOid(parent) },
428 }),
429 "RefConflict",
430 );
431 yield* admin.refs.remove({
432 params,
433 query: { name: "refs/heads/rest-branch" },
434 payload: { expectedOid: asOid(head) },
435 });
436 yield* expectTag(
437 admin.refs.get({ params, query: { name: "refs/heads/rest-branch" } }),
438 "RefNotFound",
439 );
440
441 // readOnly gates REST ref writes with the typed 403
442 yield* admin.repos.update({ params, payload: { readOnly: true } });
443 yield* expectTag(
444 admin.refs.update({
445 params,
446 query: { name: "refs/heads/blocked" },
447 payload: { newOid: asOid(head) },
448 }),
449 "ReadOnlyRepo",
450 );
451 yield* admin.repos.update({ params, payload: { readOnly: false } });
452
453 // objects: commit → tree → blob agree with the CLI byte-for-byte
454 const commit = yield* admin.objects.commit({
455 params: { ...params, oid: asOid(head) },
456 });
457 expect(commit.message).toContain("c2: bump");
458 expect(commit.parents).toEqual([parent]);
459 expect(commit.author.email).toBe("test@example.com");
460
461 const tree = yield* admin.objects.tree({
462 params: { ...params, oid: commit.tree },
463 });
464 const helloEntry = tree.entries.find((e) => e.name === "hello.txt")!;
465 expect(helloEntry.type).toBe("blob");
466 expect(helloEntry.mode).toBe("100644");
467
468 const blob = yield* admin.objects.blob({
469 params: { ...params, oid: helloEntry.oid },
470 });
471 expect(blob.encoding).toBe("base64");
472 const blobText = yield* Effect.sync(() => Buffer.from(blob.content, "base64").toString("utf8"));
473 expect(blobText).toBe("hello local, v2\n");
474
475 // wrong-kind reads → typed 422
476 yield* expectTag(
477 admin.objects.tree({ params: { ...params, oid: helloEntry.oid } }),
478 "WrongObjectType",
479 );
480 yield* expectTag(
481 admin.objects.blob({ params: { ...params, oid: asOid(head) } }),
482 "WrongObjectType",
483 );
484 yield* expectTag(
485 admin.objects.commit({
486 params: { ...params, oid: asOid("e".repeat(40)) },
487 }),
488 "ObjectNotFound",
489 );
490
491 // log walks the first-parent chain
492 const log = yield* admin.objects.log({
493 params,
494 query: { ref: "refs/heads/main", limit: 10 },
495 });
496 expect(log.items.map((c) => c.oid)).toEqual([head, parent]);
497
498 // raw streaming routes (outside HttpApi schema-land)
499 const http = yield* HttpClient.HttpClient;
500 const rawBlob = yield* http.get(
501 `${url}/api/v1/repos/acme/rest-refs/blobs/${helloEntry.oid}/raw`,
502 { headers: { authorization: `Bearer ${TEST_SECRET}` } },
503 );
504 expect(rawBlob.status).toBe(200);
505 expect(yield* rawBlob.text).toBe("hello local, v2\n");
506
507 const rawFile = yield* http.get(
508 `${url}/api/v1/repos/acme/rest-refs/file?ref=refs/heads/main&path=hello.txt`,
509 { headers: { authorization: `Bearer ${TEST_SECRET}` } },
510 );
511 expect(rawFile.status).toBe(200);
512 expect(yield* rawFile.text).toBe("hello local, v2\n");
513 }).pipe(logLevel),
514 {
515 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
516 timeout: 120_000,
517 },
518 );
519
520 test(
521 "repos.delete: 204 now, async purge to a typed 404",
522 Effect.gen(function* () {
523 const { url } = yield* stack;
524 const { client: admin } = yield* createRepo(url, "acme", "rest-delete");
525 const params = { owner: "acme", repo: "rest-delete" };
526
527 yield* admin.repos.delete({ params });
528
529 // status flips to 'deleting' and the alarm-driven purge ends in a 404
530 const gone = yield* admin.repos.get({ params }).pipe(
531 Effect.map((repo) => ({ deleted: false, status: repo.status })),
532 Effect.catchTag("RepoNotFound", () =>
533 Effect.succeed({ deleted: true as const, status: undefined }),
534 ),
535 Effect.repeat({
536 schedule: Schedule.spaced("1 second"),
537 until: (state) => state.deleted,
538 times: 30,
539 }),
540 );
541 expect(gone.deleted).toBe(true);
542 }).pipe(logLevel),
543 {
544 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
545 timeout: 120_000,
546 },
547 );
548
549 // ═══════════════════════════════════════════════════════════════════════════
550 // (b) real git CLI over the local wire
551 // ═══════════════════════════════════════════════════════════════════════════
552
553 test(
554 "git: empty clone, first push (exec bit + subdir), REST agreement",
555 Effect.gen(function* () {
556 const { url } = yield* stack;
557 const { client: admin, remote } = yield* createRepo(url, "acme", "wire-basic");
558 const fs = yield* FileSystem.FileSystem;
559 const path = yield* Path.Path;
560 const tmp = yield* tempDir;
561
562 // empty-repo clone succeeds (unborn HEAD advertisement)
563 const clone = yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", remote, "work");
564 expect(`${clone.stdout}\n${clone.stderr}`).toContain("empty repository");
565 const work = path.join(tmp, "work");
566
567 // three commits: plain file, subdirectory, executable
568 yield* fs.writeFileString(path.join(work, "hello.txt"), "hello wire\n");
569 yield* mustGit(work, "add", "-A");
570 yield* mustGit(work, "commit", "-m", "c1: hello");
571 yield* fs.makeDirectory(path.join(work, "sub"), { recursive: true });
572 yield* fs.writeFileString(path.join(work, "sub", "nested.txt"), "nested\n");
573 yield* mustGit(work, "add", "-A");
574 yield* mustGit(work, "commit", "-m", "c2: subdir");
575 yield* fs.writeFileString(path.join(work, "run.sh"), "#!/bin/sh\necho ok\n");
576 yield* fs.chmod(path.join(work, "run.sh"), 0o755);
577 yield* mustGit(work, "add", "-A");
578 yield* mustGit(work, "commit", "-m", "c3: executable");
579
580 yield* mustGit(work, "push", "origin", "main");
581 const head = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
582
583 // REST agrees with the CLI
584 const params = { owner: "acme", repo: "wire-basic" };
585 const refs = yield* admin.refs.list({ params, query: {} });
586 expect(refs.refs.find((r) => r.name === "refs/heads/main")?.oid).toBe(head);
587
588 const commit = yield* admin.objects.commit({
589 params: { ...params, oid: asOid(head) },
590 });
591 expect(commit.message).toContain("c3: executable");
592 const tree = yield* admin.objects.tree({
593 params: { ...params, oid: commit.tree },
594 });
595 expect(tree.entries.find((e) => e.name === "run.sh")?.mode).toBe("100755");
596 expect(tree.entries.find((e) => e.name === "sub")?.type).toBe("tree");
597
598 // ls-remote sees exactly what REST sees
599 const lsRemote = (yield* mustGit(work, "ls-remote", "origin")).stdout;
600 expect(lsRemote).toContain(`${head}\trefs/heads/main`);
601 }).pipe(logLevel),
602 {
603 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
604 timeout: 120_000,
605 },
606 );
607
608 test(
609 "git: clone-back + fsck --strict, incremental fetch fast-forwards",
610 Effect.gen(function* () {
611 const { url } = yield* stack;
612 const { remote } = yield* createRepo(url, "acme", "wire-fetch");
613 const fs = yield* FileSystem.FileSystem;
614 const path = yield* Path.Path;
615 const tmp = yield* tempDir;
616
617 // seed from clone A
618 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", remote, "a");
619 const a = path.join(tmp, "a");
620 yield* fs.writeFileString(path.join(a, "file.txt"), "v1\n");
621 yield* mustGit(a, "add", "-A");
622 yield* mustGit(a, "commit", "-m", "c1");
623 yield* fs.writeFileString(path.join(a, "file.txt"), "v2\n");
624 yield* mustGit(a, "add", "-A");
625 yield* mustGit(a, "commit", "-m", "c2");
626 yield* mustGit(a, "push", "origin", "main");
627
628 // clone-back is fsck-clean and log-identical — transitively proves
629 // advertisement, negotiation, pack emission, and object round-tripping
630 yield* mustGit(tmp, "clone", remote, "b");
631 const b = path.join(tmp, "b");
632 yield* mustGit(b, "fsck", "--strict");
633 const logA = (yield* mustGit(a, "log", "--format=%H %s")).stdout;
634 const logB = (yield* mustGit(b, "log", "--format=%H %s")).stdout;
635 expect(logB).toBe(logA);
636
637 // two more commits in A → B fetches incrementally (the haves/ACK path)
638 yield* fs.writeFileString(path.join(a, "file.txt"), "v3\n");
639 yield* mustGit(a, "add", "-A");
640 yield* mustGit(a, "commit", "-m", "c3");
641 yield* fs.writeFileString(path.join(a, "extra.txt"), "extra\n");
642 yield* mustGit(a, "add", "-A");
643 yield* mustGit(a, "commit", "-m", "c4");
644 yield* mustGit(a, "push", "origin", "main");
645 const headA = (yield* mustGit(a, "rev-parse", "HEAD")).stdout;
646
647 yield* mustGit(b, "fetch", "origin");
648 yield* mustGit(b, "merge", "--ff-only", "origin/main");
649 expect((yield* mustGit(b, "rev-parse", "HEAD")).stdout).toBe(headA);
650 expect(yield* fs.readFileString(path.join(b, "file.txt"))).toBe("v3\n");
651 }).pipe(logLevel),
652 {
653 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
654 timeout: 120_000,
655 },
656 );
657
658 test(
659 "git: force-push CAS, branch + annotated tag lifecycle",
660 Effect.gen(function* () {
661 const { url } = yield* stack;
662 const { client: admin, remote } = yield* createRepo(url, "acme", "wire-refs");
663 const fs = yield* FileSystem.FileSystem;
664 const path = yield* Path.Path;
665 const tmp = yield* tempDir;
666 const params = { owner: "acme", repo: "wire-refs" };
667
668 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", remote, "a");
669 const a = path.join(tmp, "a");
670 yield* fs.writeFileString(path.join(a, "f.txt"), "one\n");
671 yield* mustGit(a, "add", "-A");
672 yield* mustGit(a, "commit", "-m", "c1");
673 yield* fs.writeFileString(path.join(a, "f.txt"), "two\n");
674 yield* mustGit(a, "add", "-A");
675 yield* mustGit(a, "commit", "-m", "c2");
676 yield* mustGit(a, "push", "origin", "main");
677
678 // B clones now, then A advances the remote — B's next push is stale
679 yield* mustGit(tmp, "clone", remote, "b");
680 const b = path.join(tmp, "b");
681 yield* fs.writeFileString(path.join(a, "f.txt"), "three\n");
682 yield* mustGit(a, "add", "-A");
683 yield* mustGit(a, "commit", "-m", "c3");
684 yield* mustGit(a, "push", "origin", "main");
685
686 // B pushes its own commit against the stale old-oid → server-side CAS ng
687 yield* fs.writeFileString(path.join(b, "g.txt"), "divergent\n");
688 yield* mustGit(b, "add", "-A");
689 yield* mustGit(b, "commit", "-m", "divergent");
690 const rejected = yield* mustFailGit(b, "push", "origin", "main");
691 expect(`${rejected.stdout}\n${rejected.stderr}`).toContain("rejected");
692
693 // fetch + force overwrites; A fetches the forced history cleanly
694 yield* mustGit(b, "fetch", "origin");
695 yield* mustGit(b, "push", "--force", "origin", "main");
696 const headB = (yield* mustGit(b, "rev-parse", "HEAD")).stdout;
697 yield* mustGit(a, "fetch", "origin");
698 expect((yield* mustGit(a, "rev-parse", "origin/main")).stdout).toBe(headB);
699
700 // annotated tag round-trips as a tag object with a peeled advertisement
701 yield* mustGit(b, "tag", "-a", "v1", "-m", "release v1");
702 yield* mustGit(b, "push", "origin", "v1");
703 const tagOid = (yield* mustGit(b, "rev-parse", "v1")).stdout;
704 const tagRef = yield* admin.refs.get({
705 params,
706 query: { name: "refs/tags/v1" },
707 });
708 expect(tagRef.oid).toBe(tagOid);
709 expect(tagRef.peeled).toBe(headB); // peeled to the commit it annotates
710 const lsRemote = (yield* mustGit(b, "ls-remote", "--tags", "origin")).stdout;
711 expect(lsRemote).toContain(`${tagOid}\trefs/tags/v1`);
712 expect(lsRemote).toContain(`${headB}\trefs/tags/v1^{}`);
713
714 // branch push + delete-refs for branch and tag
715 yield* mustGit(b, "push", "origin", "main:feature");
716 const feature = yield* admin.refs.get({
717 params,
718 query: { name: "refs/heads/feature" },
719 });
720 expect(feature.oid).toBe(headB);
721 yield* mustGit(b, "push", "origin", "--delete", "feature");
722 yield* mustGit(b, "push", "origin", "--delete", "v1");
723 yield* expectTag(
724 admin.refs.get({ params, query: { name: "refs/heads/feature" } }),
725 "RefNotFound",
726 );
727 yield* expectTag(admin.refs.get({ params, query: { name: "refs/tags/v1" } }), "RefNotFound");
728 }).pipe(logLevel),
729 {
730 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
731 timeout: 120_000,
732 },
733 );
734
735 test(
736 "git: readOnly repos reject pushes in-band, then accept after unflag",
737 Effect.gen(function* () {
738 const { url } = yield* stack;
739 const { client: admin, remote } = yield* createRepo(url, "acme", "wire-readonly");
740 const fs = yield* FileSystem.FileSystem;
741 const path = yield* Path.Path;
742 const tmp = yield* tempDir;
743 const params = { owner: "acme", repo: "wire-readonly" };
744
745 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", remote, "work");
746 const work = path.join(tmp, "work");
747 yield* fs.writeFileString(path.join(work, "f.txt"), "one\n");
748 yield* mustGit(work, "add", "-A");
749 yield* mustGit(work, "commit", "-m", "c1");
750 yield* mustGit(work, "push", "origin", "main");
751
752 yield* admin.repos.update({ params, payload: { readOnly: true } });
753 yield* fs.writeFileString(path.join(work, "f.txt"), "two\n");
754 yield* mustGit(work, "add", "-A");
755 yield* mustGit(work, "commit", "-m", "c2");
756 const rejected = yield* mustFailGit(work, "push", "origin", "main");
757 expect(`${rejected.stdout}\n${rejected.stderr}`).toContain("rejected");
758
759 yield* admin.repos.update({ params, payload: { readOnly: false } });
760 yield* mustGit(work, "push", "origin", "main");
761 const head = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
762 const mainRef = yield* admin.refs.get({
763 params,
764 query: { name: "refs/heads/main" },
765 });
766 expect(mainRef.oid).toBe(head);
767 }).pipe(logLevel),
768 {
769 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
770 timeout: 120_000,
771 },
772 );
773
774 test(
775 "git: wire auth matrix — garbage token 401s, read token clones but cannot push",
776 Effect.gen(function* () {
777 const { url } = yield* stack;
778 const { client: admin, remote } = yield* createRepo(url, "acme", "wire-auth");
779 const fs = yield* FileSystem.FileSystem;
780 const path = yield* Path.Path;
781 const tmp = yield* tempDir;
782 const params = { owner: "acme", repo: "wire-auth" };
783
784 // seed one commit with the bootstrap write token
785 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", remote, "seed");
786 const seed = path.join(tmp, "seed");
787 yield* fs.writeFileString(path.join(seed, "f.txt"), "seed\n");
788 yield* mustGit(seed, "add", "-A");
789 yield* mustGit(seed, "commit", "-m", "c1");
790 yield* mustGit(seed, "push", "origin", "main");
791
792 // garbage token → 401 before any pack bytes flow. git surfaces the 401
793 // as "Authentication failed" (it never echoes the literal status code).
794 const badRemote = yield* authRemote(url, "gs_garbage", "acme", "wire-auth");
795 const unauthorized = yield* mustFailGit(tmp, "clone", badRemote, "nope");
796 expect(unauthorized.stderr).toContain("Authentication failed");
797
798 // a read-scope token clones (token in the remote URL) but cannot push
799
800 // the write path still works for the bootstrap token
801 yield* fs.writeFileString(path.join(seed, "f.txt"), "seed2\n");
802 yield* mustGit(seed, "add", "-A");
803 yield* mustGit(seed, "commit", "-m", "c2");
804 yield* mustGit(seed, "push", "origin", "main");
805 }).pipe(logLevel),
806 {
807 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
808 timeout: 120_000,
809 },
810 );
811
812 // ═══════════════════════════════════════════════════════════════════════════
813 // v2 storage plane: compaction (DESIGN.md §12.1)
814 // ═══════════════════════════════════════════════════════════════════════════
815
816 test(
817 "compaction: objects move into an R2 pack and clones stay byte-identical",
818 Effect.gen(function* () {
819 const { url } = yield* stack;
820 const repo = yield* createRepo(url, "acme", "compaction");
821 const fs = yield* FileSystem.FileSystem;
822 const path = yield* Path.Path;
823 const tmp = yield* tempDir;
824
825 // A history with enough distinct blobs that a compaction run has real
826 // work to do, plus one binary file whose bytes must survive exactly.
827 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", repo.remote, "work");
828 const work = path.join(tmp, "work");
829 const binary = new Uint8Array(4096);
830 for (let i = 0; i < binary.length; i++) binary[i] = (i * 31 + 7) & 0xff;
831 yield* fs.writeFile(path.join(work, "blob.bin"), binary);
832 for (let i = 0; i < 12; i++) {
833 yield* fs.writeFileString(path.join(work, `f${i}.txt`), `content ${i}\n`);
834 }
835 yield* mustGit(work, "add", "-A");
836 yield* mustGit(work, "commit", "-m", "seed");
837 yield* mustGit(work, "push", "origin", "main");
838
839 // Compaction is normally armed by size thresholds; force a run now so
840 // the test does not depend on repo size.
841 yield* repo.client.repos.compact({
842 params: { owner: "acme", repo: "compaction" },
843 });
844
845 const stats = yield* repo.client.repos
846 .get({ params: { owner: "acme", repo: "compaction" } })
847 .pipe(
848 Effect.map((found) => found.objects),
849 Effect.repeat({
850 schedule: Schedule.spaced("500 millis"),
851 until: (objects: { loose: number; packed: number }) =>
852 objects.packed > 0 && objects.loose === 0,
853 times: 40,
854 }),
855 );
856 expect(stats.packed).toBeGreaterThan(0);
857 expect(stats.loose).toBe(0);
858 // Only blobs move to R2 (Compact.ts BLOB_TYPE): commits/trees/tags stay
859 // row-resident so the fetch closure never walks pack windows.
860 expect(stats.resident).toBeGreaterThan(0);
861
862 // Everything now reads through R2 ranged GETs: a fresh clone must be
863 // fsck-clean and byte-identical, and REST blob reads must still work.
864 yield* mustGit(tmp, "clone", repo.remote, "verify");
865 const verify = path.join(tmp, "verify");
866 yield* mustGit(verify, "fsck", "--strict");
867 const round = yield* fs.readFile(path.join(verify, "blob.bin"));
868 expect(Array.from(round)).toEqual(Array.from(binary));
869 for (let i = 0; i < 12; i++) {
870 const text = yield* fs.readFileString(path.join(verify, `f${i}.txt`));
871 expect(text).toBe(`content ${i}\n`);
872 }
873
874 // ...and an incremental push on top of a fully packed repo still works.
875 yield* fs.writeFileString(path.join(work, "after.txt"), "after\n");
876 yield* mustGit(work, "add", "-A");
877 yield* mustGit(work, "commit", "-m", "after-compaction");
878 yield* mustGit(work, "push", "origin", "main");
879 yield* mustGit(verify, "pull", "origin", "main");
880 expect(yield* fs.readFileString(path.join(verify, "after.txt"))).toBe("after\n");
881 }).pipe(logLevel),
882 {
883 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
884 timeout: 120_000,
885 },
886 );
887
888 test(
889 "clone bundles: a full clone is served from the R2 bundle, byte-identically",
890 Effect.gen(function* () {
891 const { url } = yield* stack;
892 const repo = yield* createRepo(url, "acme", "bundles");
893 const fs = yield* FileSystem.FileSystem;
894 const path = yield* Path.Path;
895 const tmp = yield* tempDir;
896
897 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", repo.remote, "work");
898 const work = path.join(tmp, "work");
899 yield* fs.writeFileString(path.join(work, "a.txt"), "one\n");
900 yield* fs.makeDirectory(path.join(work, "sub"), { recursive: true });
901 yield* fs.writeFileString(path.join(work, "sub", "b.txt"), "two\n");
902 yield* mustGit(work, "add", "-A");
903 yield* mustGit(work, "commit", "-m", "c1");
904 yield* mustGit(work, "push", "origin", "main");
905 const head = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
906
907 // The bundle is cut by the post-push alarm; wait for it to land, then
908 // clone — that clone is served straight from the R2 bundle bytes.
909 yield* Effect.sleep("4 seconds");
910 yield* mustGit(tmp, "clone", repo.remote, "fromBundle");
911 const fromBundle = path.join(tmp, "fromBundle");
912 yield* mustGit(fromBundle, "fsck", "--strict");
913 expect((yield* mustGit(fromBundle, "rev-parse", "HEAD")).stdout).toBe(head);
914 expect(yield* fs.readFileString(path.join(fromBundle, "a.txt"))).toBe("one\n");
915 expect(yield* fs.readFileString(path.join(fromBundle, "sub", "b.txt"))).toBe("two\n");
916
917 // A push after the bundle was cut invalidates it: the next clone must
918 // still see the NEW commit (served dynamically, or from a fresh bundle).
919 yield* fs.writeFileString(path.join(work, "c.txt"), "three\n");
920 yield* mustGit(work, "add", "-A");
921 yield* mustGit(work, "commit", "-m", "c2");
922 yield* mustGit(work, "push", "origin", "main");
923 const head2 = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
924 yield* mustGit(tmp, "clone", repo.remote, "afterPush");
925 const afterPush = path.join(tmp, "afterPush");
926 yield* mustGit(afterPush, "fsck", "--strict");
927 expect((yield* mustGit(afterPush, "rev-parse", "HEAD")).stdout).toBe(head2);
928
929 // A single-branch clone is covered by the same (superset) bundle.
930 yield* Effect.sleep("4 seconds");
931 yield* mustGit(tmp, "clone", "--single-branch", "--branch", "main", repo.remote, "single");
932 yield* mustGit(path.join(tmp, "single"), "fsck", "--strict");
933 }).pipe(logLevel),
934 {
935 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
936 timeout: 120_000,
937 },
938 );
939
940 test(
941 "clone bundles: the wire response proves the R2 fast path served it",
942 Effect.gen(function* () {
943 const { url } = yield* stack;
944 const repo = yield* createRepo(url, "acme", "bundle-wire");
945 const fs = yield* FileSystem.FileSystem;
946 const path = yield* Path.Path;
947 const tmp = yield* tempDir;
948
949 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", repo.remote, "work");
950 const work = path.join(tmp, "work");
951 yield* fs.writeFileString(path.join(work, "f.txt"), "hello\n");
952 yield* mustGit(work, "add", "-A");
953 yield* mustGit(work, "commit", "-m", "c1");
954 yield* mustGit(work, "push", "origin", "main");
955 const head = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
956
957 yield* Effect.sleep("4 seconds");
958
959 // Hand-built v0 upload-pack request: one `want`, flush, `done` — the
960 // shape a fresh clone sends. No capabilities, so the response is
961 // `NAK` followed by the raw pack.
962 const pkt = (line: string) => `${(line.length + 4).toString(16).padStart(4, "0")}${line}`;
963 const body = `${pkt(`want ${head}\n`)}0000${pkt("done\n")}`;
964 const client = yield* HttpClient.HttpClient;
965 const response = yield* client.execute(
966 HttpClientRequest.post(`${url}/acme/bundle-wire.git/git-upload-pack`).pipe(
967 HttpClientRequest.setHeaders({
968 authorization: `Bearer ${repo.token}`,
969 "content-type": "application/x-git-upload-pack-request",
970 }),
971 HttpClientRequest.bodyText(body),
972 ),
973 );
974 expect(response.status).toBe(200);
975 // The header is only set on the bundle path (DESIGN.md §12.2).
976 expect(response.headers["x-git-bundle"]).toBeDefined();
977
978 const bytes = yield* response.arrayBuffer.pipe(Effect.map((buffer) => new Uint8Array(buffer)));
979 const text = new TextDecoder().decode(bytes.subarray(0, 8));
980 expect(text).toBe("0008NAK\n");
981 expect(new TextDecoder().decode(bytes.subarray(8, 12))).toBe("PACK");
982 }).pipe(logLevel),
983 {
984 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
985 timeout: 120_000,
986 },
987 );
988
989 test(
990 "clone bundles: sideband clones are served from the pre-framed twin, raw from the bundle — both whole packs",
991 Effect.gen(function* () {
992 const { url } = yield* stack;
993 const repo = yield* createRepo(url, "acme", "bundle-framed");
994 const fs = yield* FileSystem.FileSystem;
995 const path = yield* Path.Path;
996 const tmp = yield* tempDir;
997 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", repo.remote, "work");
998 const work = path.join(tmp, "work");
999 for (let i = 0; i < 20; i++) {
1000 yield* fs.writeFileString(path.join(work, `f${i}.txt`), `${"line\n".repeat(200)}${i}\n`);
1001 }
1002 yield* mustGit(work, "add", "-A");
1003 yield* mustGit(work, "commit", "-m", "c1");
1004 yield* mustGit(work, "push", "origin", "main");
1005 const head = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
1006
1007 const pkt = (line: string) => `${(line.length + 4).toString(16).padStart(4, "0")}${line}`;
1008 const client = yield* HttpClient.HttpClient;
1009 const fetchPack = (caps: string) =>
1010 client
1011 .execute(
1012 HttpClientRequest.post(`${url}/acme/bundle-framed.git/git-upload-pack`).pipe(
1013 HttpClientRequest.setHeaders({
1014 authorization: `Bearer ${repo.token}`,
1015 "content-type": "application/x-git-upload-pack-request",
1016 }),
1017 HttpClientRequest.bodyText(`${pkt(`want ${head}${caps}\n`)}0000${pkt("done\n")}`),
1018 ),
1019 )
1020 .pipe(
1021 Effect.flatMap((response) =>
1022 response.arrayBuffer.pipe(
1023 Effect.map((buffer) => ({
1024 status: response.status,
1025 via: response.headers["x-git-served-by"],
1026 bytes: new Uint8Array(buffer),
1027 })),
1028 ),
1029 ),
1030 );
1031
1032 // The bundle job runs after the push; wait for it to cover HEAD.
1033 const sideband = yield* fetchPack(" side-band-64k").pipe(
1034 Effect.repeat({
1035 schedule: Schedule.spaced("500 millis"),
1036 until: (r) => r.via !== undefined,
1037 times: 30,
1038 }),
1039 );
1040 expect(sideband.status).toBe(200);
1041 // Access was decided in front of the route, so a credentialed clone
1042 // takes the same DO-less path as an anonymous one.
1043 expect(sideband.via).toBe("head-snapshot:bundle+framed");
1044 const framed = verifyPackResponse(sideband.bytes, true);
1045 expect(framed.error).toBeUndefined();
1046 expect(framed.objects).toBeGreaterThan(20);
1047
1048 const raw = yield* fetchPack("");
1049 expect(raw.via).toBe("head-snapshot:bundle");
1050 const plain = verifyPackResponse(raw.bytes, false);
1051 expect(plain.error).toBeUndefined();
1052 expect(plain.objects).toBe(framed.objects);
1053
1054 // And real git agrees.
1055 yield* mustGit(tmp, "clone", repo.remote, "again");
1056 yield* mustGit(path.join(tmp, "again"), "fsck", "--strict");
1057 }),
1058 {
1059 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1060 timeout: 90_000,
1061 },
1062 );
1063
1064 test(
1065 "clone bundles: a stale bundle falls back cleanly to the dynamic path",
1066 Effect.gen(function* () {
1067 const { url } = yield* stack;
1068 const repo = yield* createRepo(url, "acme", "bundle-splice");
1069 const fs = yield* FileSystem.FileSystem;
1070 const path = yield* Path.Path;
1071 const tmp = yield* tempDir;
1072
1073 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", repo.remote, "work");
1074 const work = path.join(tmp, "work");
1075 yield* fs.writeFileString(path.join(work, "f.txt"), "hello\n");
1076 yield* mustGit(work, "add", "-A");
1077 yield* mustGit(work, "commit", "-m", "c1");
1078 yield* mustGit(work, "push", "origin", "main");
1079
1080 // Let the bundle land for THIS ref snapshot...
1081 yield* Effect.sleep("4 seconds");
1082
1083 // ...then move main past it, so every clone wants an oid the bundle
1084 // does not carry.
1085 yield* fs.writeFileString(path.join(work, "g.txt"), "world\n");
1086 yield* mustGit(work, "add", "-A");
1087 yield* mustGit(work, "commit", "-m", "c2");
1088 yield* fs.writeFileString(path.join(work, "h.txt"), "again\n");
1089 yield* mustGit(work, "add", "-A");
1090 yield* mustGit(work, "commit", "-m", "c3");
1091 yield* mustGit(work, "push", "origin", "main");
1092 const head = (yield* mustGit(work, "rev-parse", "HEAD")).stdout;
1093
1094 // Raw wire request, immediately — before the bundle job re-cuts, so
1095 // the bundle on disk is definitively stale.
1096 const pkt = (line: string) => `${(line.length + 4).toString(16).padStart(4, "0")}${line}`;
1097 const client = yield* HttpClient.HttpClient;
1098 const response = yield* client.execute(
1099 HttpClientRequest.post(`${url}/acme/bundle-splice.git/git-upload-pack`).pipe(
1100 HttpClientRequest.setHeaders({
1101 authorization: `Bearer ${repo.token}`,
1102 "content-type": "application/x-git-upload-pack-request",
1103 }),
1104 HttpClientRequest.bodyText(`${pkt(`want ${head}\n`)}0000${pkt("done\n")}`),
1105 ),
1106 );
1107 expect(response.status).toBe(200);
1108 // A stale bundle is NOT used: serving it would need a true delta, and
1109 // `computeClosure` deliberately does not subtract boundary trees (see
1110 // Closure.ts "accepted fat"), so the walk is the honest answer here.
1111 expect(response.headers["x-git-bundle"]).toBeUndefined();
1112 const bytes = yield* response.arrayBuffer.pipe(Effect.map((buffer) => new Uint8Array(buffer)));
1113 expect(new TextDecoder().decode(bytes.subarray(0, 8))).toBe("0008NAK\n");
1114 expect(new TextDecoder().decode(bytes.subarray(8, 12))).toBe("PACK");
1115
1116 // And the clone is still correct end to end through that path.
1117 yield* mustGit(tmp, "clone", repo.remote, "spliced");
1118 const spliced = path.join(tmp, "spliced");
1119 yield* mustGit(spliced, "fsck", "--strict");
1120 expect((yield* mustGit(spliced, "rev-parse", "HEAD")).stdout).toBe(head);
1121 const logWork = (yield* mustGit(work, "log", "--format=%H %s")).stdout;
1122 const logSpliced = (yield* mustGit(spliced, "log", "--format=%H %s")).stdout;
1123 expect(logSpliced).toBe(logWork);
1124 }).pipe(logLevel),
1125 {
1126 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1127 timeout: 180_000,
1128 },
1129 );
1130
1131 // ═══════════════════════════════════════════════════════════════════════════
1132 // (j) public repos — anonymous read access (GitHub model)
1133 // ═══════════════════════════════════════════════════════════════════════════
1134
1135 test(
1136 "public repos: anonymous REST reads + tokenless clone; writes still need a token",
1137 Effect.gen(function* () {
1138 const { url } = yield* stack;
1139 const admin = yield* makeClient(url, TEST_SECRET);
1140 const anonymous = yield* makeAnonymousClient(url);
1141 const tmp = yield* tempDir;
1142 const path = yield* Path.Path;
1143
1144 // A public repo with one commit pushed by its owner.
1145 const repo = yield* createRepo(url, "acme", "town-square");
1146 yield* admin.repos.update({
1147 params: { owner: "acme", repo: "town-square" },
1148 payload: { public: true },
1149 });
1150 const fs = yield* FileSystem.FileSystem;
1151 const pub = path.join(tmp, "pub");
1152 yield* fs.makeDirectory(pub, { recursive: true });
1153 yield* mustGit(pub, "init", "-q", "-b", "main");
1154 yield* fs.writeFileString(path.join(pub, "greeting.txt"), "hello anonymous\n");
1155 yield* mustGit(pub, "add", "-A");
1156 yield* mustGit(pub, "commit", "-qm", "public commit");
1157 yield* mustGit(pub, "push", "-q", repo.remote, "main");
1158
1159 // Anonymous REST: repo meta, refs, log, tree, blob — no token anywhere.
1160 const meta = yield* anonymous.repos.get({
1161 params: { owner: "acme", repo: "town-square" },
1162 });
1163 expect(meta.public).toBe(true);
1164 const refs = yield* anonymous.refs.list({
1165 params: { owner: "acme", repo: "town-square" },
1166 query: {},
1167 });
1168 expect(refs.head).toBe("refs/heads/main");
1169 const head = refs.refs.find((ref) => ref.name === "refs/heads/main")!;
1170 const commit = yield* anonymous.objects.commit({
1171 params: { owner: "acme", repo: "town-square", oid: head.oid },
1172 });
1173 expect(commit.message).toContain("public commit");
1174 const log = yield* anonymous.objects.log({
1175 params: { owner: "acme", repo: "town-square" },
1176 query: {},
1177 });
1178 expect(log.items.length).toBe(1);
1179
1180 // The public-only listing shows it.
1181 const listing = yield* admin.repos.list({ query: { public: true } });
1182 expect(listing.items.some((row) => row.name === "town-square")).toBe(true);
1183
1184 // Tokenless clone over the wire.
1185 const parsed = new URL(url);
1186 const anonymousRemote = `${parsed.protocol}//${parsed.host}/acme/town-square.git`;
1187 yield* mustGit(tmp, `clone`, `-q`, anonymousRemote, `anon-clone`);
1188 const cloned = yield* mustGit(path.join(tmp, "anon-clone"), `show`, `HEAD:greeting.txt`);
1189 expect(cloned.stdout.trim()).toBe("hello anonymous");
1190
1191 // Writes stay locked: anonymous push is rejected (401 → git fails).
1192 const anonWork = path.join(tmp, "anon-clone");
1193 yield* fs.writeFileString(path.join(anonWork, "greeting.txt"), "hello anonymous\nmore\n");
1194 yield* mustGit(anonWork, "add", "-A");
1195 yield* mustGit(anonWork, "commit", "-qm", "anon write");
1196 const push = yield* Effect.result(mustGit(anonWork, "push", "-q", "origin", "main"));
1197 expect(Result.isFailure(push)).toBe(true);
1198
1199 // Anonymous token management is rejected too.
1200 yield* expectTag(
1201 anonymous.repos.update({
1202 params: { owner: "acme", repo: "town-square" },
1203 payload: { description: "anon" },
1204 }),
1205 "Unauthorized",
1206 );
1207
1208 // Flipping back to private locks anonymous readers out again.
1209 yield* admin.repos.update({
1210 params: { owner: "acme", repo: "town-square" },
1211 payload: { public: false },
1212 });
1213 yield* expectTag(
1214 anonymous.repos.get({ params: { owner: "acme", repo: "town-square" } }),
1215 "Unauthorized",
1216 );
1217 const privateListing = yield* admin.repos.list({
1218 query: { public: true },
1219 });
1220 expect(privateListing.items.some((row) => row.name === "town-square")).toBe(false);
1221 const privateClone = yield* Effect.result(
1222 mustGit(tmp, `clone`, `-q`, anonymousRemote, `anon-clone-private`),
1223 );
1224 expect(Result.isFailure(privateClone)).toBe(true);
1225 }),
1226 {
1227 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1228 timeout: 120_000,
1229 },
1230 );
1231
1232 // ═══════════════════════════════════════════════════════════════════════════
1233 // (k) diffs & compare — server-side changed-file lists
1234 // ═══════════════════════════════════════════════════════════════════════════
1235
1236 test(
1237 "diff: adds/mods/deletes/mode change across two commits; root commit vs empty tree",
1238 Effect.gen(function* () {
1239 const { url } = yield* stack;
1240 const fs = yield* FileSystem.FileSystem;
1241 const { client, token } = yield* createRepo(url, "acme", "diffs");
1242 const work = yield* tempDir;
1243 yield* mustGit(work, "init", "-q", "-b", "main");
1244
1245 // commit 1: a.txt, dir/b.txt, script.sh (0644)
1246 yield* fs.writeFileString(`${work}/a.txt`, "one\n");
1247 yield* fs.makeDirectory(`${work}/dir`);
1248 yield* fs.writeFileString(`${work}/dir/b.txt`, "bee\n");
1249 yield* fs.writeFileString(`${work}/script.sh`, "#!/bin/sh\n");
1250 yield* mustGit(work, "add", ".");
1251 yield* mustGit(work, "commit", "-qm", "c1");
1252 const c1 = yield* revParse(work, "HEAD");
1253
1254 // commit 2: modify a.txt, delete dir/b.txt, add c.txt, chmod +x script.sh
1255 yield* fs.writeFileString(`${work}/a.txt`, "one\ntwo\n");
1256 yield* mustGit(work, "rm", "-q", "dir/b.txt");
1257 yield* fs.writeFileString(`${work}/c.txt`, "sea\n");
1258 yield* mustGit(work, "update-index", "--chmod=+x", "script.sh");
1259 yield* mustGit(work, "add", "a.txt", "c.txt");
1260 yield* mustGit(work, "commit", "-qm", "c2");
1261 const c2 = yield* revParse(work, "HEAD");
1262
1263 const remote = yield* authRemote(url, token, "acme", "diffs");
1264 yield* mustGit(work, "push", "-q", remote, "main");
1265
1266 // c2 vs c1
1267 const d2 = yield* client.objects.diff({
1268 params: { owner: "acme", repo: "diffs", oid: asOid(c2) },
1269 });
1270 expect(d2.parent).toBe(c1);
1271 expect(d2.truncated).toBe(false);
1272 const byPath = new Map(d2.files.map((f) => [f.path, f]));
1273 expect(byPath.get("a.txt")?.status).toBe("modified");
1274 expect(byPath.get("a.txt")?.oldOid).not.toBe(byPath.get("a.txt")?.newOid);
1275 expect(byPath.get("dir/b.txt")?.status).toBe("removed");
1276 expect(byPath.get("dir/b.txt")?.oldOid).toBeDefined();
1277 expect(byPath.get("dir/b.txt")?.newOid).toBeUndefined();
1278 expect(byPath.get("c.txt")?.status).toBe("added");
1279 // mode-only change: same oid, different modes, still "modified"
1280 const script = byPath.get("script.sh")!;
1281 expect(script.status).toBe("modified");
1282 expect(script.oldMode).toBe("100644");
1283 expect(script.newMode).toBe("100755");
1284 expect(script.oldOid).toBe(script.newOid);
1285 expect(d2.files.length).toBe(4);
1286 // sizes present for text blobs
1287 expect(byPath.get("a.txt")?.newSize).toBe(8);
1288
1289 // root commit: parent null, everything added
1290 const d1 = yield* client.objects.diff({
1291 params: { owner: "acme", repo: "diffs", oid: asOid(c1) },
1292 });
1293 expect(d1.parent).toBeNull();
1294 expect(d1.files.every((f) => f.status === "added")).toBe(true);
1295 expect(d1.files.map((f) => f.path).sort()).toEqual(["a.txt", "dir/b.txt", "script.sh"]);
1296
1297 // wrong object type: a tree oid on the diff endpoint → 422
1298 const treeOid = (yield* client.objects.commit({
1299 params: { owner: "acme", repo: "diffs", oid: asOid(c2) },
1300 })).tree;
1301 yield* expectTag(
1302 client.objects.diff({
1303 params: { owner: "acme", repo: "diffs", oid: treeOid },
1304 }),
1305 "WrongObjectType",
1306 );
1307 }),
1308 {
1309 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1310 timeout: 120_000,
1311 },
1312 );
1313
1314 test(
1315 "diff: compare merge base across branches, ahead/behind, three-dot files, ref names",
1316 Effect.gen(function* () {
1317 const { url } = yield* stack;
1318 const fs = yield* FileSystem.FileSystem;
1319 const { client, token } = yield* createRepo(url, "acme", "compare");
1320 const work = yield* tempDir;
1321 yield* mustGit(work, "init", "-q", "-b", "main");
1322 yield* fs.writeFileString(`${work}/base.txt`, "base\n");
1323 yield* mustGit(work, "add", ".");
1324 yield* mustGit(work, "commit", "-qm", "base");
1325 const fork = yield* revParse(work, "HEAD");
1326
1327 // feature: 1 commit touching feature.txt
1328 yield* mustGit(work, "checkout", "-qb", "feature");
1329 yield* fs.writeFileString(`${work}/feature.txt`, "feat\n");
1330 yield* mustGit(work, "add", ".");
1331 yield* mustGit(work, "commit", "-qm", "feat 1");
1332 const featTip = yield* revParse(work, "HEAD");
1333
1334 // main: 2 more commits touching main-only files
1335 yield* mustGit(work, "checkout", "-q", "main");
1336 yield* fs.writeFileString(`${work}/m1.txt`, "m1\n");
1337 yield* mustGit(work, "add", ".");
1338 yield* mustGit(work, "commit", "-qm", "m1");
1339 yield* fs.writeFileString(`${work}/m2.txt`, "m2\n");
1340 yield* mustGit(work, "add", ".");
1341 yield* mustGit(work, "commit", "-qm", "m2");
1342
1343 const remote = yield* authRemote(url, token, "acme", "compare");
1344 yield* mustGit(work, "push", "-q", remote, "main", "feature");
1345
1346 const cmp = yield* client.objects.compare({
1347 params: { owner: "acme", repo: "compare" },
1348 query: { base: "main", head: "feature" }, // short ref names
1349 });
1350 expect(cmp.mergeBase).toBe(fork);
1351 expect(cmp.head).toBe(featTip);
1352 expect(cmp.aheadBy).toBe(1);
1353 expect(cmp.behindBy).toBe(2);
1354 expect(cmp.commits.length).toBe(1);
1355 expect(cmp.commits[0]!.message).toContain("feat 1");
1356 // three-dot: only the feature-side change, none of main's m1/m2
1357 expect(cmp.files.map((f) => f.path)).toEqual(["feature.txt"]);
1358 expect(cmp.files[0]!.status).toBe("added");
1359 expect(cmp.filesTruncated).toBe(false);
1360
1361 // reversed: head is behind → empty files, counts swap
1362 const rev = yield* client.objects.compare({
1363 params: { owner: "acme", repo: "compare" },
1364 query: { base: "feature", head: fork }, // oid accepted too
1365 });
1366 expect(rev.mergeBase).toBe(fork);
1367 expect(rev.aheadBy).toBe(0);
1368 expect(rev.files.length).toBe(0);
1369
1370 // unknown ref → RefNotFound (404)
1371 yield* expectTag(
1372 client.objects.compare({
1373 params: { owner: "acme", repo: "compare" },
1374 query: { base: "main", head: "no-such-branch" },
1375 }),
1376 "RefNotFound",
1377 );
1378
1379 // disjoint history → NoMergeBase (422)
1380 yield* mustGit(work, "checkout", "-q", "--orphan", "island");
1381 yield* mustGit(work, "rm", "-rfq", "--cached", ".");
1382 yield* fs.writeFileString(`${work}/island.txt`, "alone\n");
1383 yield* mustGit(work, "add", "island.txt");
1384 yield* mustGit(work, "commit", "-qm", "island");
1385 yield* mustGit(work, "push", "-q", remote, "island");
1386 yield* expectTag(
1387 client.objects.compare({
1388 params: { owner: "acme", repo: "compare" },
1389 query: { base: "main", head: "island" },
1390 }),
1391 "NoMergeBase",
1392 );
1393 }),
1394 {
1395 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1396 timeout: 120_000,
1397 },
1398 );
1399
1400 test(
1401 "diff: anonymous read on public repos; 401 on private",
1402 Effect.gen(function* () {
1403 const { url } = yield* stack;
1404 const fs = yield* FileSystem.FileSystem;
1405 const anonymous = yield* makeAnonymousClient(url);
1406
1407 // private repo → anonymous is 401 on both endpoints
1408 const priv = yield* createRepo(url, "acme", "diff-private");
1409 const pw = yield* tempDir;
1410 yield* mustGit(pw, "init", "-q", "-b", "main");
1411 yield* fs.writeFileString(`${pw}/f.txt`, "x\n");
1412 yield* mustGit(pw, "add", ".");
1413 yield* mustGit(pw, "commit", "-qm", "c");
1414 const privTip = yield* revParse(pw, "HEAD");
1415 yield* mustGit(
1416 pw,
1417 "push",
1418 "-q",
1419 yield* authRemote(url, priv.token, "acme", "diff-private"),
1420 "main",
1421 );
1422 yield* expectTag(
1423 anonymous.objects.diff({
1424 params: { owner: "acme", repo: "diff-private", oid: asOid(privTip) },
1425 }),
1426 "Unauthorized",
1427 );
1428 yield* expectTag(
1429 anonymous.objects.compare({
1430 params: { owner: "acme", repo: "diff-private" },
1431 query: { base: "main", head: "main" },
1432 }),
1433 "Unauthorized",
1434 );
1435
1436 // public repo → anonymous reads succeed
1437 const pub = yield* createRepo(url, "acme", "diff-public");
1438 yield* pub.client.repos.update({
1439 params: { owner: "acme", repo: "diff-public" },
1440 payload: { public: true },
1441 });
1442 const ww = yield* tempDir;
1443 yield* mustGit(ww, "init", "-q", "-b", "main");
1444 yield* fs.writeFileString(`${ww}/hello.txt`, "hi\n");
1445 yield* mustGit(ww, "add", ".");
1446 yield* mustGit(ww, "commit", "-qm", "c1");
1447 yield* fs.writeFileString(`${ww}/hello.txt`, "hi there\n");
1448 yield* mustGit(ww, "add", ".");
1449 yield* mustGit(ww, "commit", "-qm", "c2");
1450 const pubTip = yield* revParse(ww, "HEAD");
1451 yield* mustGit(
1452 ww,
1453 "push",
1454 "-q",
1455 yield* authRemote(url, pub.token, "acme", "diff-public"),
1456 "main",
1457 );
1458
1459 const d = yield* anonymous.objects.diff({
1460 params: { owner: "acme", repo: "diff-public", oid: asOid(pubTip) },
1461 });
1462 expect(d.files).toEqual([expect.objectContaining({ path: "hello.txt", status: "modified" })]);
1463 const c = yield* anonymous.objects.compare({
1464 params: { owner: "acme", repo: "diff-public" },
1465 query: { base: d.parent!, head: "main" },
1466 });
1467 expect(c.aheadBy).toBe(1);
1468 expect(c.behindBy).toBe(0);
1469 expect(c.mergeBase).toBe(d.parent);
1470 }),
1471 {
1472 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1473 timeout: 120_000,
1474 },
1475 );
1476
1477 // ═══════════════════════════════════════════════════════════════════════════
1478 // (l) pull requests — lifecycle, live compare fields, merges
1479 // ═══════════════════════════════════════════════════════════════════════════
1480
1481 test(
1482 "pulls: open + numbering, typed create failures, list pagination, live detail, close/reopen/edit",
1483 Effect.gen(function* () {
1484 const { url } = yield* stack;
1485 const fs = yield* FileSystem.FileSystem;
1486 const { client, token } = yield* createRepo(url, "acme", "pulls-basic");
1487 const params = { owner: "acme", repo: "pulls-basic" };
1488 const work = yield* tempDir;
1489 yield* mustGit(work, "init", "-q", "-b", "main");
1490 yield* fs.writeFileString(`${work}/README.md`, "base\n");
1491 yield* mustGit(work, "add", ".");
1492 yield* mustGit(work, "commit", "-qm", "base");
1493 const mainTip = yield* revParse(work, "HEAD");
1494 yield* mustGit(work, "checkout", "-qb", "feature");
1495 yield* fs.writeFileString(`${work}/feature.txt`, "feat\n");
1496 yield* mustGit(work, "add", ".");
1497 yield* mustGit(work, "commit", "-qm", "feat");
1498 yield* mustGit(work, "checkout", "-qb", "feature-2", "main");
1499 yield* fs.writeFileString(`${work}/f2.txt`, "f2\n");
1500 yield* mustGit(work, "add", ".");
1501 yield* mustGit(work, "commit", "-qm", "f2");
1502 const remote = yield* authRemote(url, token, "acme", "pulls-basic");
1503 yield* mustGit(work, "push", "-q", remote, "main", "feature", "feature-2");
1504
1505 // open #1 (short names normalize to refs/heads/…)
1506 const pr1 = yield* client.pulls.create({
1507 params,
1508 payload: {
1509 title: "add feature",
1510 body: "the body",
1511 base: "main",
1512 head: "feature",
1513 },
1514 });
1515 expect(pr1.number).toBe(1);
1516 expect(pr1.state).toBe("open");
1517 expect(pr1.baseRef).toBe("refs/heads/main");
1518 expect(pr1.headRef).toBe("refs/heads/feature");
1519 expect(pr1.mergeCommit).toBeNull();
1520
1521 // typed create failures
1522 yield* expectTag(
1523 client.pulls.create({
1524 params,
1525 payload: { title: "same", base: "main", head: "main" },
1526 }),
1527 "ValidationError",
1528 );
1529 yield* expectTag(
1530 client.pulls.create({
1531 params,
1532 payload: { title: "missing", base: "main", head: "no-such-branch" },
1533 }),
1534 "BranchMissing",
1535 );
1536 yield* expectTag(
1537 client.pulls.create({
1538 params,
1539 payload: {
1540 title: "tags are not branches",
1541 base: "main",
1542 head: "refs/tags/v1",
1543 },
1544 }),
1545 "ValidationError",
1546 );
1547 const dup = yield* expectTag(
1548 client.pulls.create({
1549 params,
1550 payload: { title: "dup", base: "main", head: "feature" },
1551 }),
1552 "PullExists",
1553 );
1554 expect((dup as { number?: number }).number).toBe(1);
1555
1556 // #2 gets the next dense number
1557 const pr2 = yield* client.pulls.create({
1558 params,
1559 payload: { title: "second", base: "main", head: "feature-2" },
1560 });
1561 expect(pr2.number).toBe(2);
1562
1563 // list: newest first, keyset pagination
1564 const open = yield* client.pulls.list({ params, query: {} });
1565 expect(open.items.map((p) => p.number)).toEqual([2, 1]);
1566 expect(open.hasMore).toBe(false);
1567 const page1 = yield* client.pulls.list({ params, query: { limit: 1 } });
1568 expect(page1.items.map((p) => p.number)).toEqual([2]);
1569 expect(page1.hasMore).toBe(true);
1570 expect(page1.nextCursor).toBe("2");
1571 const page2 = yield* client.pulls.list({
1572 params,
1573 query: { limit: 1, cursor: page1.nextCursor! },
1574 });
1575 expect(page2.items.map((p) => p.number)).toEqual([1]);
1576 expect(page2.hasMore).toBe(false);
1577 const closedList = yield* client.pulls.list({
1578 params,
1579 query: { state: "closed" },
1580 });
1581 expect(closedList.items).toEqual([]);
1582
1583 // live detail: feature is 1 ahead of main and fast-forwardable
1584 const detail = yield* client.pulls.get({
1585 params: { ...params, number: 1 },
1586 });
1587 expect(detail.baseOid).toBe(mainTip);
1588 expect(detail.mergeBase).toBe(mainTip);
1589 expect(detail.aheadBy).toBe(1);
1590 expect(detail.behindBy).toBe(0);
1591 expect(detail.mergeable).toBe(true);
1592 expect(detail.mergeableReason).toBe("ff");
1593
1594 // unknown number → typed 404
1595 yield* expectTag(client.pulls.get({ params: { ...params, number: 999 } }), "PullNotFound");
1596
1597 // close → detail still computed (both refs exist) → reopen → edit
1598 const closed = yield* client.pulls.update({
1599 params: { ...params, number: 1 },
1600 payload: { state: "closed" },
1601 });
1602 expect(closed.state).toBe("closed");
1603 const closedDetail = yield* client.pulls.get({
1604 params: { ...params, number: 1 },
1605 });
1606 expect(closedDetail.mergeable).toBe(true);
1607 const reopened = yield* client.pulls.update({
1608 params: { ...params, number: 1 },
1609 payload: { state: "open" },
1610 });
1611 expect(reopened.state).toBe("open");
1612 const edited = yield* client.pulls.update({
1613 params: { ...params, number: 1 },
1614 payload: { title: "renamed", body: null },
1615 });
1616 expect(edited.title).toBe("renamed");
1617 expect(edited.body).toBeNull();
1618 expect(edited.updatedAt).toBeGreaterThanOrEqual(edited.createdAt);
1619 }),
1620 {
1621 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1622 timeout: 120_000,
1623 },
1624 );
1625
1626 test(
1627 "pulls: fast-forward merge moves the base ref; merged is terminal; up-to-date is 422; encodeCommit round-trips real git bytes",
1628 Effect.gen(function* () {
1629 const { url } = yield* stack;
1630 const fs = yield* FileSystem.FileSystem;
1631 const { client, token } = yield* createRepo(url, "acme", "pulls-ff");
1632 const params = { owner: "acme", repo: "pulls-ff" };
1633 const work = yield* tempDir;
1634 yield* mustGit(work, "init", "-q", "-b", "main");
1635 yield* fs.writeFileString(`${work}/README.md`, "hello\n");
1636 yield* mustGit(work, "add", ".");
1637 yield* mustGit(work, "commit", "-qm", "base");
1638 yield* mustGit(work, "checkout", "-qb", "feature");
1639 yield* fs.writeFileString(`${work}/feature.txt`, "feat\n");
1640 yield* mustGit(work, "add", ".");
1641 yield* mustGit(work, "commit", "-qm", "feat");
1642 const featureTip = yield* revParse(work, "HEAD");
1643 yield* mustGit(work, "checkout", "-q", "main");
1644 const remote = yield* authRemote(url, token, "acme", "pulls-ff");
1645 yield* mustGit(work, "push", "-q", remote, "main", "feature");
1646
1647 // pin encodeCommit against real git-produced bytes: `git cat-file
1648 // commit` output re-hashed must reproduce the oid (byte-exactness),
1649 // and parse→encode must reproduce those bytes.
1650 const catFile = (yield* mustGit(work, "cat-file", "commit", featureTip)).stdout;
1651 const rawCommit = `${catFile}\n`; // mustGit trims the trailing LF
1652 expect(yield* hashObject(ObjectType.commit, utf8Encode(rawCommit))).toBe(featureTip);
1653 const parsed = yield* parseCommit(utf8Encode(rawCommit));
1654 const reEncoded = yield* encodeCommit({
1655 tree: parsed.tree,
1656 parents: parsed.parents,
1657 author: parsed.author,
1658 committer: parsed.committer,
1659 message: parsed.message,
1660 });
1661 expect(utf8Decode(reEncoded)).toBe(rawCommit);
1662 expect(yield* hashObject(ObjectType.commit, reEncoded)).toBe(featureTip);
1663
1664 // open + FF merge
1665 const pr = yield* client.pulls.create({
1666 params,
1667 payload: { title: "ff me", base: "main", head: "feature" },
1668 });
1669 const merged = yield* client.pulls.merge({
1670 params: { ...params, number: pr.number },
1671 payload: {},
1672 });
1673 expect(merged.method).toBe("ff");
1674 expect(merged.oid).toBe(featureTip);
1675 expect(merged.pull.state).toBe("merged");
1676 expect(merged.pull.mergeCommit).toBe(featureTip);
1677 expect(merged.pull.mergedAt).not.toBeNull();
1678
1679 // the base ref moved to the head tip
1680 const mainRef = yield* client.refs.get({
1681 params,
1682 query: { name: "refs/heads/main" },
1683 });
1684 expect(mainRef.oid).toBe(featureTip);
1685
1686 // the clone can FF-pull the merged base
1687 yield* mustGit(work, "pull", "-q", remote, "main");
1688 expect(yield* revParse(work, "HEAD")).toBe(featureTip);
1689
1690 // merged is terminal: live fields null, re-merge and reopen are 409s
1691 const detail = yield* client.pulls.get({
1692 params: { ...params, number: pr.number },
1693 });
1694 expect(detail.state).toBe("merged");
1695 expect(detail.baseOid).toBeNull();
1696 expect(detail.headOid).toBeNull();
1697 expect(detail.mergeable).toBeNull();
1698 yield* expectTag(
1699 client.pulls.merge({
1700 params: { ...params, number: pr.number },
1701 payload: {},
1702 }),
1703 "PullStateConflict",
1704 );
1705 yield* expectTag(
1706 client.pulls.update({
1707 params: { ...params, number: pr.number },
1708 payload: { state: "open" },
1709 }),
1710 "PullStateConflict",
1711 );
1712 yield* expectTag(
1713 client.pulls.merge({ params: { ...params, number: 42 }, payload: {} }),
1714 "PullNotFound",
1715 );
1716
1717 // up-to-date: a PR whose head is already reachable from base
1718 yield* mustGit(work, "push", "-q", remote, `${featureTip}:refs/heads/already-in`);
1719 const upToDate = yield* client.pulls.create({
1720 params,
1721 payload: { title: "nothing to do", base: "main", head: "already-in" },
1722 });
1723 const upToDateDetail = yield* client.pulls.get({
1724 params: { ...params, number: upToDate.number },
1725 });
1726 expect(upToDateDetail.mergeable).toBe(false);
1727 expect(upToDateDetail.mergeableReason).toBe("up-to-date");
1728 yield* expectTag(
1729 client.pulls.merge({
1730 params: { ...params, number: upToDate.number },
1731 payload: {},
1732 }),
1733 "NothingToMerge",
1734 );
1735 }),
1736 {
1737 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1738 timeout: 120_000,
1739 },
1740 );
1741
1742 test(
1743 "pulls: trivial merge commit joins disjoint changes (fsck-clean); conflicts are typed 409; stale expectedHeadOid is RefConflict",
1744 Effect.gen(function* () {
1745 const { url } = yield* stack;
1746 const fs = yield* FileSystem.FileSystem;
1747 const path = yield* Path.Path;
1748 const { client, token } = yield* createRepo(url, "acme", "pulls-merge");
1749 const params = { owner: "acme", repo: "pulls-merge" };
1750 const work = yield* tempDir;
1751 yield* mustGit(work, "init", "-q", "-b", "main");
1752 yield* fs.writeFileString(`${work}/README.md`, "base\n");
1753 yield* mustGit(work, "add", ".");
1754 yield* mustGit(work, "commit", "-qm", "base");
1755 const baseCommit = yield* revParse(work, "HEAD");
1756 // topic-a: adds feat-a.txt
1757 yield* mustGit(work, "checkout", "-qb", "topic-a");
1758 yield* fs.writeFileString(`${work}/feat-a.txt`, "a\n");
1759 yield* mustGit(work, "add", ".");
1760 yield* mustGit(work, "commit", "-qm", "feat a");
1761 const topicATip = yield* revParse(work, "HEAD");
1762 // main advances with a disjoint file
1763 yield* mustGit(work, "checkout", "-q", "main");
1764 yield* fs.writeFileString(`${work}/b.txt`, "b\n");
1765 yield* mustGit(work, "add", ".");
1766 yield* mustGit(work, "commit", "-qm", "main b");
1767 const mainTip = yield* revParse(work, "HEAD");
1768 const remote = yield* authRemote(url, token, "acme", "pulls-merge");
1769 yield* mustGit(work, "push", "-q", remote, "main", "topic-a");
1770
1771 const pr = yield* client.pulls.create({
1772 params,
1773 payload: { title: "merge topic-a", base: "main", head: "topic-a" },
1774 });
1775 const detail = yield* client.pulls.get({
1776 params: { ...params, number: pr.number },
1777 });
1778 expect(detail.mergeBase).toBe(baseCommit);
1779 expect(detail.mergeable).toBe(true);
1780 expect(detail.mergeableReason).toBe("merge-commit");
1781
1782 // stale expectedHeadOid (a race guard) → typed 409, PR stays open
1783 yield* expectTag(
1784 client.pulls.merge({
1785 params: { ...params, number: pr.number },
1786 payload: { expectedHeadOid: asOid(baseCommit) },
1787 }),
1788 "RefConflict",
1789 );
1790
1791 const merged = yield* client.pulls.merge({
1792 params: { ...params, number: pr.number },
1793 payload: { expectedHeadOid: asOid(topicATip) },
1794 });
1795 expect(merged.method).toBe("merge-commit");
1796 expect(merged.pull.state).toBe("merged");
1797 expect(merged.pull.mergeCommit).toBe(merged.oid);
1798 const mainRef = yield* client.refs.get({
1799 params,
1800 query: { name: "refs/heads/main" },
1801 });
1802 expect(mainRef.oid).toBe(merged.oid);
1803
1804 // clone back: fsck-clean, both sides present, exactly 2 parents in order
1805 const tmp = yield* tempDir;
1806 yield* mustGit(tmp, "clone", "-q", remote, "fresh");
1807 const fresh = path.join(tmp, "fresh");
1808 yield* mustGit(fresh, "fsck", "--strict");
1809 expect(yield* revParse(fresh, "HEAD")).toBe(merged.oid);
1810 expect(yield* fs.readFileString(path.join(fresh, "feat-a.txt"))).toBe("a\n");
1811 expect(yield* fs.readFileString(path.join(fresh, "b.txt"))).toBe("b\n");
1812 expect(yield* fs.readFileString(path.join(fresh, "README.md"))).toBe("base\n");
1813 const parents = (yield* mustGit(fresh, "log", "--format=%P", "-1")).stdout;
1814 expect(parents).toBe(`${mainTip} ${topicATip}`);
1815
1816 // conflict: both sides edit README.md relative to the merge base
1817 yield* mustGit(work, "checkout", "-qb", "topic-b", baseCommit);
1818 yield* fs.writeFileString(`${work}/README.md`, "topic-b version\n");
1819 yield* mustGit(work, "add", ".");
1820 yield* mustGit(work, "commit", "-qm", "topic-b readme");
1821 yield* mustGit(work, "checkout", "-q", "main");
1822 yield* mustGit(work, "pull", "-q", remote, "main");
1823 yield* fs.writeFileString(`${work}/README.md`, "main version\n");
1824 yield* mustGit(work, "add", ".");
1825 yield* mustGit(work, "commit", "-qm", "main readme");
1826 yield* mustGit(work, "push", "-q", remote, "main", "topic-b");
1827 const mainBefore = yield* revParse(work, "HEAD");
1828
1829 const conflictPr = yield* client.pulls.create({
1830 params,
1831 payload: { title: "conflicting", base: "main", head: "topic-b" },
1832 });
1833 const conflictDetail = yield* client.pulls.get({
1834 params: { ...params, number: conflictPr.number },
1835 });
1836 expect(conflictDetail.mergeable).toBe(false);
1837 expect(conflictDetail.mergeableReason).toBe("conflict");
1838 const conflict = yield* expectTag(
1839 client.pulls.merge({
1840 params: { ...params, number: conflictPr.number },
1841 payload: {},
1842 }),
1843 "MergeConflict",
1844 );
1845 expect((conflict as { paths?: ReadonlyArray<string> }).paths).toEqual(["README.md"]);
1846 // the PR stays open and the base ref did not move
1847 const still = yield* client.pulls.get({
1848 params: { ...params, number: conflictPr.number },
1849 });
1850 expect(still.state).toBe("open");
1851 const mainAfter = yield* client.refs.get({
1852 params,
1853 query: { name: "refs/heads/main" },
1854 });
1855 expect(mainAfter.oid).toBe(mainBefore);
1856 }),
1857 {
1858 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1859 timeout: 120_000,
1860 },
1861 );
1862
1863 test(
1864 "pulls: deleted head branch degrades to nulls and BranchMissing; anonymous reads on public; writes need a write token",
1865 Effect.gen(function* () {
1866 const { url } = yield* stack;
1867 const fs = yield* FileSystem.FileSystem;
1868 const anonymous = yield* makeAnonymousClient(url);
1869 const { client, token } = yield* createRepo(url, "acme", "pulls-auth");
1870 const params = { owner: "acme", repo: "pulls-auth" };
1871 const work = yield* tempDir;
1872 yield* mustGit(work, "init", "-q", "-b", "main");
1873 yield* fs.writeFileString(`${work}/README.md`, "hi\n");
1874 yield* mustGit(work, "add", ".");
1875 yield* mustGit(work, "commit", "-qm", "base");
1876 yield* mustGit(work, "checkout", "-qb", "topic-c");
1877 yield* fs.writeFileString(`${work}/c.txt`, "c\n");
1878 yield* mustGit(work, "add", ".");
1879 yield* mustGit(work, "commit", "-qm", "c");
1880 const remote = yield* authRemote(url, token, "acme", "pulls-auth");
1881 yield* mustGit(work, "push", "-q", remote, "main", "topic-c");
1882
1883 const pr = yield* client.pulls.create({
1884 params,
1885 payload: { title: "from topic-c", base: "main", head: "topic-c" },
1886 });
1887
1888 // delete the head branch: the PR row survives, live fields go null
1889 yield* client.refs.remove({
1890 params,
1891 query: { name: "refs/heads/topic-c" },
1892 payload: {},
1893 });
1894 const detail = yield* client.pulls.get({
1895 params: { ...params, number: pr.number },
1896 });
1897 expect(detail.state).toBe("open");
1898 expect(detail.headOid).toBeNull();
1899 expect(detail.baseOid).not.toBeNull();
1900 expect(detail.mergeBase).toBeNull();
1901 expect(detail.aheadBy).toBeNull();
1902 expect(detail.mergeable).toBeNull();
1903 const missing = yield* expectTag(
1904 client.pulls.merge({
1905 params: { ...params, number: pr.number },
1906 payload: {},
1907 }),
1908 "BranchMissing",
1909 );
1910 expect((missing as { ref?: string }).ref).toBe("refs/heads/topic-c");
1911
1912 // private repo: anonymous reads are 401
1913 yield* expectTag(anonymous.pulls.list({ params, query: {} }), "Unauthorized");
1914
1915 // public repo: anonymous reads work, writes never do
1916 yield* client.repos.update({ params, payload: { public: true } });
1917 const publicList = yield* anonymous.pulls.list({ params, query: {} });
1918 expect(publicList.items.map((p) => p.number)).toEqual([pr.number]);
1919 const publicDetail = yield* anonymous.pulls.get({
1920 params: { ...params, number: pr.number },
1921 });
1922 expect(publicDetail.title).toBe("from topic-c");
1923 yield* expectTag(
1924 anonymous.pulls.create({
1925 params,
1926 payload: { title: "nope", base: "main", head: "topic-c" },
1927 }),
1928 "Unauthorized",
1929 );
1930 yield* expectTag(
1931 anonymous.pulls.merge({
1932 params: { ...params, number: pr.number },
1933 payload: {},
1934 }),
1935 "Unauthorized",
1936 );
1937 yield* expectTag(
1938 anonymous.pulls.update({
1939 params: { ...params, number: pr.number },
1940 payload: { state: "closed" },
1941 }),
1942 "Unauthorized",
1943 );
1944
1945 // a read-scoped token reads but cannot write → typed 403
1946 }),
1947 {
1948 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
1949 timeout: 120_000,
1950 },
1951 );
1952
1953 // ═══════════════════════════════════════════════════════════════════════════
1954 // (k) GitHub REST v3 compatibility facade (/api/v3 — gh api / Octokit)
1955 // ═══════════════════════════════════════════════════════════════════════════
1956
1957 /** Raw fetch against the facade with GitHub's `token` auth scheme. */
1958 const ghFetch = Effect.fn(function* (
1959 url: string,
1960 path: string,
1961 options?: {
1962 readonly method?: string;
1963 readonly token?: string | undefined;
1964 readonly body?: unknown;
1965 },
1966 ) {
1967 const client = yield* HttpClient.HttpClient;
1968 let request = HttpClientRequest.make((options?.method ?? "GET") as "GET")(`${url}/api/v3${path}`);
1969 if (options?.token !== undefined) {
1970 request = HttpClientRequest.setHeader(request, "authorization", `token ${options.token}`);
1971 }
1972 if (options?.body !== undefined) {
1973 request = HttpClientRequest.bodyJsonUnsafe(options.body)(request);
1974 }
1975 const response = yield* client.execute(request);
1976 const text = yield* response.text;
1977 return {
1978 status: response.status,
1979 headers: response.headers,
1980 json: text.length === 0 ? undefined : (JSON.parse(text) as any),
1981 };
1982 });
1983
1984 test(
1985 "ghapi: /user auth probe, repo + branches + commits + contents in GitHub shapes",
1986 Effect.gen(function* () {
1987 const { url } = yield* stack;
1988 const admin = yield* makeClient(url, TEST_SECRET);
1989 const repo = yield* createRepo(url, "acme", "gh-compat");
1990 yield* admin.repos.update({
1991 params: { owner: "acme", repo: "gh-compat" },
1992 payload: { public: true },
1993 });
1994
1995 // seed two commits on main
1996 const fs = yield* FileSystem.FileSystem;
1997 const path = yield* Path.Path;
1998 const tmp = yield* tempDir;
1999 const work = path.join(tmp, "ghc");
2000 yield* fs.makeDirectory(work, { recursive: true });
2001 yield* mustGit(work, "init", "-q", "-b", "main");
2002 yield* fs.writeFileString(path.join(work, "hello.txt"), "one\n");
2003 yield* mustGit(work, "add", "-A");
2004 yield* mustGit(work, "commit", "-qm", "c1");
2005 yield* fs.writeFileString(path.join(work, "hello.txt"), "two\n");
2006 yield* mustGit(work, "add", "-A");
2007 yield* mustGit(work, "commit", "-qm", "c2");
2008 yield* mustGit(work, "push", "-q", repo.remote, "main");
2009
2010 // /user: gh's probe — the fixture overrides the engine's route to
2011 // answer from the caller its middleware resolved (`token` scheme);
2012 // anonymous is the middleware's 401.
2013 const user = yield* ghFetch(url, "/user", { token: TEST_SECRET });
2014 expect(user.status).toBe(200);
2015 expect(user.json.login).toBe("Suite");
2016 const anonUser = yield* ghFetch(url, "/user");
2017 expect(anonUser.status).toBe(401);
2018
2019 // repo shape (anonymous — the repo is public)
2020 const repoJson = yield* ghFetch(url, "/repos/acme/gh-compat");
2021 expect(repoJson.status).toBe(200);
2022 expect(repoJson.json.full_name).toBe("acme/gh-compat");
2023 expect(repoJson.json.private).toBe(false);
2024 expect(repoJson.json.default_branch).toBe("main");
2025 expect(repoJson.json.clone_url).toContain("/acme/gh-compat.git");
2026 expect(typeof repoJson.json.id).toBe("number");
2027
2028 // branches
2029 const branches = yield* ghFetch(url, "/repos/acme/gh-compat/branches");
2030 expect(branches.status).toBe(200);
2031 expect(branches.json[0].name).toBe("main");
2032 expect(branches.json[0].commit.sha).toMatch(/^[0-9a-f]{40}$/);
2033
2034 // commits list + Link pagination
2035 const commits = yield* ghFetch(url, "/repos/acme/gh-compat/commits?per_page=1");
2036 expect(commits.status).toBe(200);
2037 expect(commits.json.length).toBe(1);
2038 expect(commits.json[0].commit.message).toContain("c2");
2039 expect(commits.headers.link).toContain('rel="next"');
2040 // follow the Link cursor like gh --paginate does
2041 const nextUrl = /<([^>]+)>/.exec(commits.headers.link ?? "")![1]!;
2042 const pathPart = nextUrl.slice(nextUrl.indexOf("/api/v3") + 7);
2043 const page2 = yield* ghFetch(url, pathPart);
2044 expect(page2.json[0].commit.message).toContain("c1");
2045
2046 // single commit incl. files
2047 const head = commits.json[0].sha as string;
2048 const one = yield* ghFetch(url, `/repos/acme/gh-compat/commits/${head}`);
2049 expect(one.status).toBe(200);
2050 expect(one.json.files[0].filename).toBe("hello.txt");
2051 expect(one.json.files[0].status).toBe("modified");
2052
2053 // contents (base64)
2054 const contents = yield* ghFetch(url, "/repos/acme/gh-compat/contents/hello.txt");
2055 expect(contents.status).toBe(200);
2056 expect(contents.json.encoding).toBe("base64");
2057 expect(atob(contents.json.content as string)).toBe("two\n");
2058
2059 // unknown repo → GitHub-shaped 404
2060 const missing = yield* ghFetch(url, "/repos/acme/nope");
2061 expect(missing.status).toBe(404);
2062 expect(missing.json.message).toBe("Not Found");
2063 }),
2064 {
2065 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
2066 timeout: 120_000,
2067 },
2068 );
2069
2070 test(
2071 "ghapi: pull lifecycle through the facade — create, list states, merge, files",
2072 Effect.gen(function* () {
2073 const { url } = yield* stack;
2074 const admin = yield* makeClient(url, TEST_SECRET);
2075 const repo = yield* createRepo(url, "acme", "gh-pulls");
2076 yield* admin.repos.update({
2077 params: { owner: "acme", repo: "gh-pulls" },
2078 payload: { public: true },
2079 });
2080
2081 const fs = yield* FileSystem.FileSystem;
2082 const path = yield* Path.Path;
2083 const tmp = yield* tempDir;
2084 const work = path.join(tmp, "ghp");
2085 yield* fs.makeDirectory(work, { recursive: true });
2086 yield* mustGit(work, "init", "-q", "-b", "main");
2087 yield* fs.writeFileString(path.join(work, "base.txt"), "base\n");
2088 yield* mustGit(work, "add", "-A");
2089 yield* mustGit(work, "commit", "-qm", "base");
2090 yield* mustGit(work, "checkout", "-qb", "topic");
2091 yield* fs.writeFileString(path.join(work, "topic.txt"), "topic\n");
2092 yield* mustGit(work, "add", "-A");
2093 yield* mustGit(work, "commit", "-qm", "topic work");
2094 yield* mustGit(work, "checkout", "-q", "main");
2095 yield* mustGit(work, "push", "-q", repo.remote, "main", "topic");
2096
2097 // POST /pulls with GitHub's field names (head/base short names)
2098 const created = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls", {
2099 method: "POST",
2100 token: TEST_SECRET,
2101 body: {
2102 title: "Topic work",
2103 head: "topic",
2104 base: "main",
2105 body: "pr body",
2106 },
2107 });
2108 expect(created.status).toBe(201);
2109 expect(created.json.number).toBe(1);
2110 expect(created.json.state).toBe("open");
2111 expect(created.json.merged).toBe(false);
2112 expect(created.json.head.ref).toBe("topic");
2113 expect(created.json.base.ref).toBe("main");
2114
2115 // anonymous write → 401
2116 const anonCreate = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls", {
2117 method: "POST",
2118 body: { title: "x", head: "topic", base: "main" },
2119 });
2120 expect(anonCreate.status).toBe(401);
2121
2122 // GET single: mergeable + shas live
2123 const single = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls/1");
2124 expect(single.json.mergeable).toBe(true);
2125 expect(single.json.head.sha).toMatch(/^[0-9a-f]{40}$/);
2126
2127 // files (three-dot)
2128 const files = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls/1/files");
2129 expect(files.json.map((f: any) => f.filename)).toEqual(["topic.txt"]);
2130 expect(files.json[0].status).toBe("added");
2131
2132 // unsupported merge method → 405
2133 const squash = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls/1/merge", {
2134 method: "PUT",
2135 token: TEST_SECRET,
2136 body: { merge_method: "squash" },
2137 });
2138 expect(squash.status).toBe(405);
2139
2140 // PUT merge (fast-forward)
2141 const merged = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls/1/merge", {
2142 method: "PUT",
2143 token: TEST_SECRET,
2144 body: {},
2145 });
2146 expect(merged.status).toBe(200);
2147 expect(merged.json.merged).toBe(true);
2148 expect(merged.json.sha).toMatch(/^[0-9a-f]{40}$/);
2149
2150 // GitHub semantics: merged PR is state=closed + merged=true
2151 const after = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls/1");
2152 expect(after.json.state).toBe("closed");
2153 expect(after.json.merged).toBe(true);
2154 expect(after.json.merge_commit_sha).toBe(merged.json.sha);
2155
2156 // list state filters: open empty; closed includes the merged PR
2157 const open = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls?state=open");
2158 expect(open.json.length).toBe(0);
2159 const closed = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls?state=closed");
2160 expect(closed.json.length).toBe(1);
2161 expect(closed.json[0].number).toBe(1);
2162
2163 // merged PR files fall back to the merge commit's diff
2164 const mergedFiles = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls/1/files");
2165 expect(mergedFiles.json.map((f: any) => f.filename)).toEqual(["topic.txt"]);
2166
2167 // PATCH validation
2168 const badState = yield* ghFetch(url, "/repos/acme/gh-pulls/pulls/1", {
2169 method: "PATCH",
2170 token: TEST_SECRET,
2171 body: { state: "merged" },
2172 });
2173 expect(badState.status).toBe(422);
2174 }),
2175 {
2176 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
2177 timeout: 120_000,
2178 },
2179 );
2180
2181 // ═══════════════════════════════════════════════════════════════════════════
2182 // (c) application ref authorization
2183 // ═══════════════════════════════════════════════════════════════════════════
2184
2185 // A second assembly, with custom native HTTP handlers sharing
2186 // one rule: `refs/heads/main` moves only for the repository's owner (the
2187 // fixture's `protectMain`). Its own entry module: a Worker's generated
2188 // entry serves its main module's DEFAULT export, so one Worker class per
2189 // entry module. Deployed inside the test so the shared fixture stays one
2190 // worker for the e2e suites.
2191 const ProtectedLocalStack = Alchemy.Stack(
2192 "GitServiceProtectedLocalStack",
2193 { providers: Cloudflare.providers(), state: Alchemy.localState() },
2194 Effect.gen(function* () {
2195 const host = yield* ProtectedGitHost;
2196 return { url: host.url.as<string>() };
2197 }),
2198 );
2199 afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(ProtectedLocalStack));
2200
2201 test(
2202 "policies: an application handler protects main — per-ref rule over the parsed updates",
2203 Effect.gen(function* () {
2204 const { url } = yield* deploy(ProtectedLocalStack);
2205 expect(url).toMatch(/^http:\/\/localhost:\d+$/);
2206 yield* awaitReady(url);
2207
2208 const fs = yield* FileSystem.FileSystem;
2209 const path = yield* Path.Path;
2210 const { created } = yield* createRepo(url, "e2e", "protected");
2211 // A second user, not the owner, does the pushing.
2212 const token = TEST_SECRET_DEV;
2213 const remote = yield* authRemote(url, token, "e2e", "protected");
2214
2215 const tmp = yield* tempDir;
2216 yield* mustGit(tmp, "-c", "init.defaultBranch=main", "clone", remote, "w");
2217 const w = path.join(tmp, "w");
2218 yield* fs.writeFileString(path.join(w, "file.txt"), "v1\n");
2219 yield* mustGit(w, "add", "-A");
2220 yield* mustGit(w, "commit", "-m", "c1");
2221
2222 // The middleware lets the user push; the policy lets any OTHER branch
2223 // through...
2224 yield* mustGit(w, "push", "origin", "HEAD:refs/heads/feature");
2225
2226 // ...but a direct push to main is refused PER-REF, after the pack is
2227 // parsed, with the reason the policy gave.
2228 const denied = yield* mustFailGit(w, "push", "origin", "HEAD:refs/heads/main");
2229 expect(denied.stderr).toContain("not permitted");
2230
2231 // The owner passes the same policy.
2232 const adminRemote = yield* authRemote(url, TEST_SECRET, "e2e", "protected");
2233 yield* mustGit(w, "push", adminRemote, "HEAD:refs/heads/main");
2234
2235 // The push advertisement is a write probe: anonymous gets the 401
2236 // (with `WWW-Authenticate`) that makes git ask for credentials.
2237 const client = yield* HttpClient.HttpClient;
2238 const probe = yield* client.get(`${url}/e2e/protected/info/refs?service=git-receive-pack`);
2239 expect(probe.status).toBe(401);
2240 expect(probe.headers["www-authenticate"]).toContain("Basic");
2241
2242 // The REST ref writes run the same policy: the user is refused on main
2243 // (a typed 403) and may still create a feature branch.
2244 const head = yield* revParse(w, "HEAD");
2245 const tokenClient = yield* makeClient(url, token);
2246 yield* expectTag(
2247 tokenClient.refs.update({
2248 params: { owner: "e2e", repo: "protected" },
2249 query: { name: "refs/heads/main" },
2250 payload: { newOid: asOid(head) },
2251 }),
2252 "PushDenied",
2253 );
2254 const moved = yield* tokenClient.refs.update({
2255 params: { owner: "e2e", repo: "protected" },
2256 query: { name: "refs/heads/feature2" },
2257 payload: { newOid: asOid(head), expectedOid: null },
2258 });
2259 expect(moved.oid).toBe(head);
2260
2261 // A policy can inspect the newly uploaded commit without publishing it.
2262 yield* fs.writeFileString(path.join(w, "new.txt"), "not published yet\n");
2263 yield* mustGit(w, "add", "-A");
2264 yield* mustGit(w, "commit", "-m", "[reject-content]");
2265 const rejectedOid = yield* revParse(w, "HEAD");
2266 const rejectedContent = yield* mustFailGit(w, "push", adminRemote, "HEAD:refs/heads/main");
2267 expect(rejectedContent.stderr).toContain("commit rejected by content policy");
2268 const ownerClient = yield* makeClient(url, TEST_SECRET);
2269 yield* expectTag(
2270 ownerClient.objects.commit({
2271 params: { owner: "e2e", repo: "protected", oid: asOid(rejectedOid) },
2272 }),
2273 "ObjectNotFound",
2274 );
2275 expect(
2276 (yield* ownerClient.refs.get({
2277 params: { owner: "e2e", repo: "protected" },
2278 query: { name: "refs/heads/main" },
2279 })).oid,
2280 ).toBe(head);
2281 // Retry with an acceptable commit: aborted staging must not poison ingestion.
2282 yield* mustGit(w, "commit", "--amend", "-m", "accepted content");
2283 yield* mustGit(w, "push", adminRemote, "HEAD:refs/heads/main");
2284 }).pipe(logLevel),
2285 {
2286 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "local"],
2287 timeout: 240_000,
2288 },
2289 );