@devries-cameron20 / t3code Mirror · read-only / commits / ca140c435f
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 20:45 UTC

refactor(source-control): GitCafe creates repositories and pull requests over REST (#22495)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 20, 2026 at 14:09 UTC ca140c435f38612656dd655fc42e2f78efbfb4c9
2 files changed +170 -122
packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.test.ts
+112 -58
@@ -2,6 +2,7 @@ import { SourceControlProviderKind } from "@t3tools/contracts";
2 import { assert, describe, it } from "@effect/vitest";
3 import { GitCommandError } from "@t3tools/contracts";
4 import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
8 import * as Option from "effect/Option";
@@ -18,6 +19,7 @@ import * as GitCafeCredentials from "./GitCafeCredentials.ts";
19 import * as GitCafeSourceControlProvider from "./GitCafeSourceControlProvider.ts";
20
21 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
22 +const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
23
24 const authAnswer = (input: { stdout?: unknown; stderr?: unknown; exitCode?: number }) => ({
25 stdout: input.stdout === undefined ? "" : encodeJson(input.stdout),
@@ -29,6 +31,36 @@ const failure = (code: string, status: number | null) => ({
31 error: { code, status, message: `Failure ${code}` },
32 });
33
34 +/** Most calls touch no file; one that does fails the test. */
35 +const NoFiles = FileSystem.layerNoop({});
36 +
37 +/** A provider on git.cafe whose checkout has no remote and which may not run `cafe`. */
38 +const layerFor = (
39 + client: HttpClient.HttpClient,
40 + options: { readonly files?: Layer.Layer<FileSystem.FileSystem> } = {},
41 +) =>
42 + Layer.merge(GitCafeApi.layer, options.files ?? NoFiles).pipe(
43 + Layer.provideMerge(GitCafeCredentials.layer),
44 + Layer.provideMerge(
45 + TestSourceControlHost.layer({
46 + git: {
47 + resolvePrimaryRemoteName: () =>
48 + Effect.fail(
49 + new GitCommandError({
50 + operation: "resolvePrimaryRemoteName",
51 + command: "git remote",
52 + cwd: "/repo",
53 + detail: "No git remote is configured.",
54 + }),
55 + ),
56 + },
57 + }),
58 + ),
59 + Layer.provide(Layer.succeed(HostProcess.Environment, { CAFE_TOKEN: "env-token" })),
60 + Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")),
61 + Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
62 + );
63 +
64 describe("GitCafeSourceControlProvider", () => {
65 it("reads a signed-in account and keeps transient failures apart from sign-out", () => {
66 const { parseAuth } = GitCafeSourceControlProvider;
@@ -94,7 +126,7 @@ describe("GitCafeSourceControlProvider", () => {
126 ]);
127 }).pipe(
128 Effect.provide(
97 - GitCafeApi.layer.pipe(
129 + Layer.merge(GitCafeApi.layer, NoFiles).pipe(
130 Layer.provideMerge(GitCafeCredentials.layer),
131 Layer.provideMerge(TestSourceControlHost.layer()),
132 Layer.provide(
@@ -140,7 +172,7 @@ describe("GitCafeSourceControlProvider", () => {
172 assert.deepStrictEqual(urls, ["https://git.cafe/api/repos/team/project"]);
173 }).pipe(
174 Effect.provide(
143 - GitCafeApi.layer.pipe(
175 + Layer.merge(GitCafeApi.layer, NoFiles).pipe(
176 Layer.provideMerge(GitCafeCredentials.layer),
177 Layer.provideMerge(
178 TestSourceControlHost.layer({
@@ -222,7 +254,7 @@ describe("GitCafeSourceControlProvider", () => {
254 assert.deepStrictEqual(remotes, [expected]);
255 }).pipe(
256 Effect.provide(
225 - GitCafeApi.layer.pipe(
257 + Layer.merge(GitCafeApi.layer, NoFiles).pipe(
258 Layer.provideMerge(GitCafeCredentials.layer),
259 Layer.provideMerge(
260 TestSourceControlHost.layer({
@@ -246,22 +278,19 @@ describe("GitCafeSourceControlProvider", () => {
278 );
279 });
280
249 - it.effect("waits for a created repository's admission before handing out its URLs", () => {
250 - const urls: Array<string> = [];
251 - const states = ["running", "complete"];
281 + it.effect("creates a repository over REST and waits for its admission", () => {
282 + const sent: Array<{ method: string; url: string; body: unknown }> = [];
283 const client = HttpClient.make((request) => {
253 - urls.push(request.url);
284 + const body =
285 + request.body._tag === "Uint8Array"
286 + ? decodeJson(new TextDecoder().decode(request.body.body))
287 + : undefined;
288 + sent.push({ method: request.method, url: request.url, body });
289 + const state = request.method === "POST" ? "running" : "complete";
290 return Effect.succeed(
291 HttpClientResponse.fromWeb(
292 request,
257 - new Response(
258 - encodeJson({
259 - repoId: "repo_1",
260 - state: states.shift(),
261 - owner: "team",
262 - name: "project",
263 - }),
264 - ),
293 + new Response(encodeJson({ repoId: "repo_1", state, owner: "team", name: "project" })),
294 ),
295 );
296 });
@@ -276,51 +305,76 @@ describe("GitCafeSourceControlProvider", () => {
305 url: "https://git.cafe/team/project",
306 sshUrl: "ssh@git.cafe:team/project.git",
307 });
279 - assert.deepStrictEqual(urls, [
280 - "https://git.cafe/api/orgs/team/admissions/repo_1",
281 - "https://git.cafe/api/orgs/team/admissions/repo_1",
282 - ]);
283 - }).pipe(
284 - Effect.provide(
285 - GitCafeApi.layer.pipe(
286 - Layer.provideMerge(GitCafeCredentials.layer),
287 - Layer.provideMerge(
288 - TestSourceControlHost.layer({
289 - process: {
290 - run: () =>
291 - Effect.succeed(
292 - TestSourceControlHost.processOutput(
293 - encodeJson({
294 - schemaVersion: 1,
295 - data: {
296 - resource: {
297 - repoId: "repo_1",
298 - state: "running",
299 - owner: "team",
300 - name: "project",
301 - },
302 - },
303 - }),
304 - ),
305 - ),
306 - },
307 - git: {
308 - resolvePrimaryRemoteName: () =>
309 - Effect.fail(
310 - new GitCommandError({
311 - operation: "resolvePrimaryRemoteName",
312 - command: "git remote",
313 - cwd: "/repo",
314 - detail: "No git remote is configured.",
315 - }),
316 - ),
317 - },
318 - }),
308 + assert.deepStrictEqual(
309 + sent.map((request) => `${request.method} ${request.url}`),
310 + [
311 + "POST https://git.cafe/api/orgs/team/repos",
312 + "GET https://git.cafe/api/orgs/team/admissions/repo_1",
313 + ],
314 + );
315 + const { requestKey, ...body } = sent[0]?.body as { requestKey: string };
316 + assert.match(requestKey, /^[0-9a-f-]{36}$/u);
317 + assert.deepStrictEqual(body, {
318 + name: "project",
319 + visibility: "private",
320 + defaultBranch: "main",
321 + });
322 + }).pipe(Effect.provide(layerFor(client)));
323 + });
324 +
325 + it.effect("opens a pull request from a fork over REST with the body file's text", () => {
326 + const sent: Array<{ method: string; url: string; body: unknown }> = [];
327 + const client = HttpClient.make((request) => {
328 + const body =
329 + request.body._tag === "Uint8Array"
330 + ? decodeJson(new TextDecoder().decode(request.body.body))
331 + : undefined;
332 + sent.push({ method: request.method, url: request.url, body });
333 + return Effect.succeed(
334 + HttpClientResponse.fromWeb(
335 + request,
336 + new Response(
337 + encodeJson(
338 + request.method === "POST"
339 + ? { number: 3 }
340 + : { id: "repo_fork", name: "project", defaultBranch: "main" },
341 + ),
342 ),
320 - Layer.provide(Layer.succeed(HostProcess.Environment, { CAFE_TOKEN: "env-token" })),
321 - Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")),
322 - Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
343 ),
344 + );
345 + });
346 + return Effect.gen(function* () {
347 + const provider = yield* GitCafeSourceControlProvider.make;
348 + yield* provider.createChangeRequest({
349 + cwd: "/repo",
350 + target: { repository: "team/project", refName: "main" },
351 + baseRefName: "main",
352 + headSelector: "fork:feature",
353 + title: "Add a thing",
354 + bodyFile: "/tmp/body.md",
355 + });
356 + assert.deepStrictEqual(
357 + sent.map((request) => `${request.method} ${request.url}`),
358 + [
359 + "GET https://git.cafe/api/repos/fork/project",
360 + "POST https://git.cafe/api/repos/team/project/pulls",
361 + ],
362 + );
363 + assert.deepStrictEqual(sent[1]?.body, {
364 + repo: "repo_fork",
365 + source: "feature",
366 + target: "main",
367 + title: "Add a thing",
368 + description: "Body",
369 + });
370 + }).pipe(
371 + Effect.provide(
372 + layerFor(client, {
373 + files: FileSystem.layerNoop({
374 + readFileString: (path) =>
375 + path === "/tmp/body.md" ? Effect.succeed("Body") : Effect.die(path),
376 + }),
377 + }),
378 ),
379 );
380 });
packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts
+58 -64
@@ -1,5 +1,6 @@
1 import { SourceControlProviderKind } from "@t3tools/contracts";
2 import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 import * as Option from "effect/Option";
5 import * as Result from "effect/Result";
6 import * as Schema from "effect/Schema";
@@ -16,6 +17,7 @@ import {
17 type SourceControlCliDiscoverySpec,
18 type SourceControlManagedCliDiscoverySpec,
19 } from "@t3tools/source-control-core/server/discovery";
20 +import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid";
21 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
22 import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
23
@@ -146,10 +148,8 @@ const RepositoryAdmission = Schema.Struct({
148 owner: TrimmedNonEmptyString,
149 name: TrimmedNonEmptyString,
150 });
149 -const CreatedRepository = Schema.Struct({
150 - data: Schema.Struct({ resource: RepositoryAdmission }),
151 -});
152 -const decodeCreatedRepository = Schema.decodeEffect(Schema.fromJsonString(CreatedRepository));
151 +const RepositoryId = Schema.Struct({ id: TrimmedNonEmptyString });
152 +const CreatedPull = Schema.Struct({ number: PositiveInt });
153 const encodeBranches = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
154
155 interface Target {
@@ -171,7 +171,7 @@ const pullUrlPattern = /^https:\/\/([^/]+)\/([^/]+\/[^/]+)\/pulls\/(\d+)\/?(?:[?
171 export const make = Effect.gen(function* () {
172 const api = yield* GitCafeApi.GitCafeApi;
173 const host = yield* SourceControlHost.SourceControlHost;
174 - const credentials = yield* GitCafeCredentials.GitCafeCredentials;
174 + const fileSystem = yield* FileSystem.FileSystem;
175
176 const error = (operation: string, cwd: string, detail: string, cause?: unknown) =>
177 new SourceControlProviderError({
@@ -197,33 +197,6 @@ export const make = Effect.gen(function* () {
197 ),
198 ),
199 );
200 - const cafe = (operation: string, cwd: string, target: Target, args: ReadonlyArray<string>) =>
201 - credentials
202 - .cliEnv(target.host)
203 - .pipe(
204 - Effect.flatMap((env) =>
205 - host.process.run({
206 - operation: `GitCafeSourceControlProvider.${operation}`,
207 - command: "cafe",
208 - cwd,
209 - args: [...cliArgs(target.host), ...args],
210 - env: { CAFE_OUTPUT: "json", ...env },
211 - timeoutMs: 30_000,
212 - }),
213 - ),
214 - )
215 - .pipe(
216 - Effect.mapError((cause) =>
217 - error(
218 - operation,
219 - cwd,
220 - (cause._tag === "VcsProcessExitError" && cliFailure(cause.detail)?.message) ||
221 - "GitCafe CLI command failed.",
222 - cause,
223 - ),
224 - ),
225 - );
226 -
200 const resolveTarget = Effect.fn("GitCafeSourceControlProvider.resolveTarget")(function* (
201 operation: string,
202 input: {
@@ -371,21 +344,42 @@ export const make = Effect.gen(function* () {
344 ? `${source.owner}/${target.repository.split("/")[1]}`
345 : target.repository);
346 const branch = SourceControlProvider.sourceBranch(input);
374 - yield* cafe("createChangeRequest", input.cwd, target, [
375 - "pr",
376 - "create",
377 - "--json",
378 - "--repo",
379 - target.repository,
380 - "--head",
381 - sourceRepository === target.repository ? branch : `${sourceRepository}:${branch}`,
382 - "--base",
383 - input.target?.refName ?? input.baseRefName,
384 - "--title",
385 - input.title,
386 - "--body-file",
387 - input.bodyFile,
388 - ]);
347 + // GitCafe names the head by its repository's id, so the head repository is looked up first.
348 + const head = yield* read(
349 + "createChangeRequest",
350 + input.cwd,
351 + { host: target.host, path: `/repos/${sourceRepository}` },
352 + RepositoryId,
353 + );
354 + const description = yield* fileSystem
355 + .readFileString(input.bodyFile)
356 + .pipe(
357 + Effect.mapError((cause) =>
358 + error(
359 + "createChangeRequest",
360 + input.cwd,
361 + "Could not read the pull request description.",
362 + cause,
363 + ),
364 + ),
365 + );
366 + yield* read(
367 + "createChangeRequest",
368 + input.cwd,
369 + {
370 + host: target.host,
371 + method: "POST",
372 + path: `/repos/${target.repository}/pulls`,
373 + body: {
374 + repo: head.id,
375 + source: branch,
376 + target: input.target?.refName ?? input.baseRefName,
377 + title: input.title,
378 + ...(description.trim().length === 0 ? {} : { description }),
379 + },
380 + },
381 + CreatedPull,
382 + );
383 },
384 ),
385 getRepositoryCloneUrls: Effect.fn("GitCafeSourceControlProvider.getRepositoryCloneUrls")(
@@ -403,25 +397,25 @@ export const make = Effect.gen(function* () {
397 createRepository: Effect.fn("GitCafeSourceControlProvider.createRepository")(function* (input) {
398 const target = yield* resolveTarget("createRepository", input);
399 const [owner = "", name = ""] = target.repository.split("/");
406 - const output = yield* cafe("createRepository", input.cwd, target, [
407 - "repo",
408 - "create",
409 - name,
410 - "--org",
411 - owner,
412 - "--visibility",
413 - input.visibility,
414 - "--json",
415 - ]);
416 - const created = yield* decodeCreatedRepository(output.stdout).pipe(
417 - Effect.mapError((cause) =>
418 - error("createRepository", input.cwd, "GitCafe returned an unreadable response.", cause),
419 - ),
400 + const pending = yield* read(
401 + "createRepository",
402 + input.cwd,
403 + {
404 + host: target.host,
405 + method: "POST",
406 + path: `/orgs/${owner}/repos`,
407 + body: {
408 + name,
409 + requestKey: yield* randomUuidV4,
410 + visibility: input.visibility,
411 + defaultBranch: "main",
412 + },
413 + },
414 + RepositoryAdmission,
415 );
421 - // GitCafe admits a repository asynchronously: `cafe repo create` answers while admission is
422 - // still running, so wait for it to settle the way `cafe repo create --clone` does.
416 + // GitCafe admits a repository asynchronously and answers while admission is still running,
417 + // so wait for it to settle the way `cafe repo create --clone` does.
418 const settled = (state: string) => state === "complete" || state === "blocked";
424 - const pending = created.data.resource;
419 const resource = settled(pending.state)
420 ? pending
421 : yield* read(