@devries-cameron20 / t3code-1 / commits / 39f6e2b2a2
Fork 0

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

refactor(source-control): git and process behaviour comes from forge hooks (#23995)

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

Julius Marminge committed Oct 24, 2026 at 04:24 UTC 39f6e2b2a22678013ed691512e6703e99c7d0861
26 files changed +630 -565
apps/server/src/git/GitManager.test.ts
+84 -57
@@ -3053,6 +3053,47 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
3053 }),
3054 );
3055
3056 + it.effect("hands the branch base to the host when a failed first push is retried", () =>
3057 + Effect.gen(function* () {
3058 + const repoDir = yield* makeTempDir("t3code-git-manager-");
3059 + yield* initRepo(repoDir);
3060 + const remoteDir = yield* createBareRemote();
3061 + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
3062 + yield* runGit(repoDir, ["push", "-u", "origin", "HEAD:main"]);
3063 + yield* runGit(repoDir, ["checkout", "-b", "feature/retried-push", "--track", "origin/main"]);
3064 + NodeFS.writeFileSync(NodePath.join(repoDir, "retried.txt"), "retried\n");
3065 + yield* runGit(repoDir, ["add", "retried.txt"]);
3066 + yield* runGit(repoDir, ["commit", "-m", "Retried push"]);
3067 + const rejectOnce = NodePath.join(remoteDir, "reject-once");
3068 + NodeFS.writeFileSync(rejectOnce, "");
3069 + NodeFS.writeFileSync(
3070 + NodePath.join(remoteDir, "hooks", "pre-receive"),
3071 + `#!/bin/sh\nif [ -f "${rejectOnce}" ]; then rm "${rejectOnce}"; exit 1; fi\n`,
3072 + { mode: 0o755 },
3073 + );
3074 +
3075 + const recorded: Array<{ branch: string; baseBranch: string }> = [];
3076 + const { service } = createGitHubProviderWithFakeGh();
3077 + const { manager } = yield* makeManager({
3078 + sourceControlProvider: {
3079 + ...service,
3080 + recordBranchBase: ({ branch, baseBranch }) =>
3081 + Effect.sync(() => {
3082 + recorded.push({ branch, baseBranch });
3083 + }),
3084 + },
3085 + });
3086 + const failed = yield* runStackedAction(manager, { cwd: repoDir, action: "push" }).pipe(
3087 + Effect.flip,
3088 + );
3089 + expect(failed).toBeDefined();
3090 + const result = yield* runStackedAction(manager, { cwd: repoDir, action: "push" });
3091 +
3092 + expect(result.push.status).toBe("pushed");
3093 + expect(recorded).toEqual([{ branch: "feature/retried-push", baseBranch: "main" }]);
3094 + }),
3095 + );
3096 +
3097 it.effect("create_pr targets the remote default branch when it is not main", () =>
3098 Effect.gen(function* () {
3099 const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -4576,63 +4617,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
4617 }),
4618 );
4619
4579 - it.effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () =>
4580 - Effect.gen(function* () {
4581 - const repoDir = yield* makeTempDir("t3code-git-manager-");
4582 - yield* initRepo(repoDir);
4583 - const originDir = yield* createBareRemote();
4584 - const forkDir = yield* createBareRemote();
4585 - yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
4586 - yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
4587 - yield* runGit(repoDir, ["remote", "add", "binbandit-seed", forkDir]);
4588 - yield* runGit(repoDir, ["checkout", "-b", "fix/git-action-default-without-origin"]);
4589 - NodeFS.writeFileSync(NodePath.join(repoDir, "derived-fork.txt"), "derived fork\n");
4590 - yield* runGit(repoDir, ["add", "derived-fork.txt"]);
4591 - yield* runGit(repoDir, ["commit", "-m", "Derived fork PR branch"]);
4592 - yield* runGit(repoDir, [
4593 - "push",
4594 - "-u",
4595 - "binbandit-seed",
4596 - "fix/git-action-default-without-origin",
4597 - ]);
4598 - yield* runGit(repoDir, ["checkout", "main"]);
4599 - yield* runGit(repoDir, ["branch", "-D", "fix/git-action-default-without-origin"]);
4600 -
4601 - const { manager } = yield* makeManager({
4602 - ghScenario: {
4603 - pullRequest: {
4604 - number: 642,
4605 - title: "fix: use commit as the default git action without origin",
4606 - url: "https://github.com/pingdotgg/t3code/pull/642",
4607 - baseRefName: "main",
4608 - headRefName: "fix/git-action-default-without-origin",
4609 - state: "open",
4610 - isCrossRepository: true,
4611 - headRepositoryOwnerLogin: "binbandit",
4612 - },
4613 - repositoryCloneUrls: {
4614 - "binbandit/t3code": {
4615 - url: forkDir,
4616 - sshUrl: forkDir,
4617 - },
4618 - },
4619 - },
4620 - });
4621 -
4622 - const result = yield* preparePullRequestThread(manager, {
4623 - cwd: repoDir,
4624 - reference: "642",
4625 - mode: "local",
4626 - });
4627 -
4628 - expect(result.branch).toBe("fix/git-action-default-without-origin");
4629 - expect(result.worktreePath).toBeNull();
4630 - expect(
4631 - (yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"])).stdout.trim(),
4632 - ).toBe("binbandit-seed/fix/git-action-default-without-origin");
4633 - }),
4634 - );
4635 -
4620 it.effect("refreshes a reused PR worktree onto the updated pull request head", () =>
4621 Effect.gen(function* () {
4622 const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -5058,6 +5042,49 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
5042 }),
5043 );
5044
5045 + it.effect("creates a merge request worktree from the host's own head ref", () =>
5046 + Effect.gen(function* () {
5047 + const repoDir = yield* makeTempDir("t3code-git-manager-");
5048 + yield* initRepo(repoDir);
5049 + const remoteDir = yield* createBareRemote();
5050 + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
5051 + yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
5052 + yield* runGit(repoDir, ["checkout", "-b", "feature/mr-ref-only"]);
5053 + NodeFS.writeFileSync(NodePath.join(repoDir, "mr.txt"), "merge request\n");
5054 + yield* runGit(repoDir, ["add", "mr.txt"]);
5055 + yield* runGit(repoDir, ["commit", "-m", "Merge request ref only"]);
5056 + const head = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim();
5057 + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/merge-requests/93/head"]);
5058 + yield* runGit(repoDir, ["checkout", "main"]);
5059 + yield* runGit(repoDir, ["branch", "-D", "feature/mr-ref-only"]);
5060 +
5061 + const { service } = createGitHubProviderWithFakeGh({
5062 + pullRequest: {
5063 + number: 93,
5064 + title: "Merge request ref only",
5065 + url: "https://gitlab.com/pingdotgg/codething-mvp/-/merge_requests/93",
5066 + baseRefName: "main",
5067 + headRefName: "feature/mr-ref-only",
5068 + state: "open",
5069 + },
5070 + });
5071 + const { manager } = yield* makeManager({
5072 + sourceControlProvider: { ...service, kind: SourceControlProviderKind.make("gitlab") },
5073 + });
5074 +
5075 + const result = yield* preparePullRequestThread(manager, {
5076 + cwd: repoDir,
5077 + reference: "93",
5078 + mode: "worktree",
5079 + });
5080 +
5081 + expect(result.isOnPullRequestHead).toBe(true);
5082 + expect(
5083 + (yield* runGit(result.worktreePath as string, ["rev-parse", "HEAD"])).stdout.trim(),
5084 + ).toBe(head);
5085 + }),
5086 + );
5087 +
5088 it.effect("preserves an unrelated local branch and upstream that share the fork head name", () =>
5089 Effect.gen(function* () {
5090 const repoDir = yield* makeTempDir("t3code-git-manager-");
apps/server/src/git/GitManager.ts
+194 -233
@@ -1,4 +1,3 @@
1 -import { SourceControlProviderKind } from "@t3tools/contracts";
1 import * as Arr from "effect/Array";
2 import * as Cache from "effect/Cache";
3 import * as Clock from "effect/Clock";
@@ -54,16 +53,11 @@ import {
53 sanitizeBranchFragment,
54 sanitizeFeatureBranchName,
55 } from "@t3tools/shared/git";
56 +import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
57 import {
58 - getChangeRequestTerminologyForKind,
59 - isSshRemoteUrl,
58 type ChangeRequestTerminology,
61 -} from "@t3tools/shared/sourceControl";
62 -import * as HostProcess from "@t3tools/shared/HostProcess";
63 -import {
64 - parseGitHubRepositorySelector,
65 - resolveGitHubRepository,
66 -} from "@t3tools/source-control-github/server/gitHubRepositoryResolution";
59 + UNKNOWN_SOURCE_CONTROL_CLIENT,
60 +} from "@t3tools/source-control-core/client/definition";
61 import {
62 normalizeThreadPullRequestKey,
63 threadPullRequestKeyOf,
@@ -255,48 +249,15 @@ interface BranchHeadContext {
249 }
250
251 export function pullRequestRepositoryKey(value: string): string | null {
258 - try {
259 - const url = new URL(value);
260 - const match =
261 - /^(.*)(?:\/pulls?\/|\/-\/merge_requests\/|\/pull-requests\/|\/pullrequest\/)\d+(?:\/.*)?$/iu.exec(
262 - url.pathname,
263 - );
264 - if (match?.[1] === undefined) return null;
265 - url.pathname = match[1];
266 - url.search = "";
267 - url.hash = "";
268 - return sourceControlClients.repositoryKeyFromRemote(url.toString());
269 - } catch {
270 - return null;
271 - }
252 + const repositoryUrl = sourceControlClients.parseChangeRequestUrl(value)?.link.repositoryUrl;
253 + return repositoryUrl === undefined
254 + ? null
255 + : sourceControlClients.repositoryKeyFromRemote(repositoryUrl);
256 }
257
274 -function parseRepositoryNameFromPullRequestUrl(url: string): string | null {
275 - const trimmed = url.trim();
276 - const match = /^https?:\/\/[^/]+\/[^/]+\/([^/]+)\/pull\/\d+(?:\/.*)?$/i.exec(trimmed);
277 - const repositoryName = match?.[1]?.trim() ?? "";
278 - return repositoryName.length > 0 ? repositoryName : null;
279 -}
280 -
281 -function resolveHeadRepositoryNameWithOwner(
282 - pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
283 -): string | null {
284 - const explicitRepository = pullRequest.headRepositoryNameWithOwner?.trim() ?? "";
285 - if (explicitRepository.length > 0) {
286 - return explicitRepository;
287 - }
288 -
289 - if (!pullRequest.isCrossRepository) {
290 - return null;
291 - }
292 -
293 - const ownerLogin = pullRequest.headRepositoryOwnerLogin?.trim() ?? "";
294 - const repositoryName = parseRepositoryNameFromPullRequestUrl(pullRequest.url);
295 - if (ownerLogin.length === 0 || !repositoryName) {
296 - return null;
297 - }
298 -
299 - return `${ownerLogin}/${repositoryName}`;
258 +/** Null when the host did not name the repository the head lives in. */
259 +function resolveHeadRepositoryNameWithOwner(pullRequest: PullRequestHeadRemoteInfo): string | null {
260 + return normalizeOptionalString(pullRequest.headRepositoryNameWithOwner);
261 }
262
263 function resolvePullRequestWorktreeLocalBranchName(
@@ -331,7 +292,8 @@ function parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null
292 if (trimmed.length === 0) {
293 return null;
294 }
334 - // GitLab reports the top-level group as owner. The full path distinguishes subgroups.
295 + // The first segment only: a nested path's owner is its top-level group. The full path
296 + // distinguishes subgroups.
297 const [ownerLogin] = trimmed.split("/");
298 const normalizedOwnerLogin = ownerLogin?.trim() ?? "";
299 return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;
@@ -352,27 +314,6 @@ function normalizeOptionalOwnerLogin(value: string | null | undefined): string |
314 return normalized ? normalized.toLowerCase() : null;
315 }
316
355 -function resolvePullRequestHeadRepositoryNameWithOwner(
356 - pr: PullRequestHeadRemoteInfo & { url: string },
357 -) {
358 - const explicitRepository = normalizeOptionalString(pr.headRepositoryNameWithOwner);
359 - if (explicitRepository) {
360 - return explicitRepository;
361 - }
362 -
363 - if (!pr.isCrossRepository) {
364 - return null;
365 - }
366 -
367 - const ownerLogin = normalizeOptionalString(pr.headRepositoryOwnerLogin);
368 - const repositoryName = parseRepositoryNameFromPullRequestUrl(pr.url);
369 - if (!ownerLogin || !repositoryName) {
370 - return null;
371 - }
372 -
373 - return `${ownerLogin}/${repositoryName}`;
374 -}
375 -
317 interface PullRequestHeadIdentity {
318 readonly repositoryNameWithOwner: string | null;
319 readonly ownerLogin: string | null;
@@ -394,7 +335,7 @@ function resolveExpectedHeadIdentity(
335
336 function resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {
337 const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(
397 - resolvePullRequestHeadRepositoryNameWithOwner(pr),
338 + resolveHeadRepositoryNameWithOwner(pr),
339 );
340 return {
341 repositoryNameWithOwner,
@@ -634,11 +575,6 @@ function headBranchProbe(
575 );
576 }
577
637 -/** A URL's host as `new URL` reads it: lowercased, any non-default port kept, `:443` dropped. */
638 -function urlHost(url: string): string | null {
639 - return URL.canParse(url) ? new URL(url).host : null;
640 -}
641 -
578 function appendUnique(values: string[], next: string | null | undefined): void {
579 const trimmed = next?.trim() ?? "";
580 if (trimmed.length === 0 || values.includes(trimmed)) {
@@ -726,9 +662,16 @@ export const make = Effect.gen(function* () {
662 const crypto = yield* Crypto.Crypto;
663 const fileSystem = yield* FileSystem.FileSystem;
664 const path = yield* Path.Path;
729 - const environment = yield* HostProcess.Environment;
665
666 const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
667 + const changeRequestTermsFor = Effect.fn("GitManager.changeRequestTermsFor")(function* (
668 + cwd: string,
669 + ) {
670 + return yield* sourceControlProvider(cwd).pipe(
671 + Effect.map((provider) => sourceControlClients.get(provider.kind).changeRequest),
672 + Effect.orElseSucceed(() => UNKNOWN_SOURCE_CONTROL_CLIENT.changeRequest),
673 + );
674 + });
675 const serverSettingsService = yield* ServerSettings.ServerSettingsService;
676 const threads = yield* ProjectionStore.ProjectionStoreV2;
677 const projects = yield* ProjectStore.ProjectStoreV2;
@@ -775,6 +718,31 @@ export const make = Effect.gen(function* () {
718 ),
719 ),
720 );
721 + // Hands the base T3 recorded for a branch to the host, whose own tools may keep it elsewhere.
722 + // Best-effort: nothing T3 does reads it back from there.
723 + const shareBranchBase = Effect.fn("GitManager.shareBranchBase")(function* (
724 + cwd: string,
725 + branch: string,
726 + ) {
727 + const baseBranch = yield* gitCore
728 + .readBranchBase(cwd, branch)
729 + .pipe(Effect.orElseSucceed(() => null));
730 + if (baseBranch === null) return;
731 + const provider = yield* sourceControlProvider(cwd).pipe(Effect.orElseSucceed(() => null));
732 + yield* provider?.recordBranchBase?.({ cwd, branch, baseBranch }) ?? Effect.void;
733 + });
734 + // Publishing a branch that tracks its base records that base first, even when the push then
735 + // fails, so the host hears of it after every successful push rather than the first attempt.
736 + const pushCurrentBranch = Effect.fn("GitManager.pushCurrentBranch")(function* (
737 + cwd: string,
738 + branch: string | null,
739 + ) {
740 + const result = yield* gitCore.pushCurrentBranch(cwd, branch);
741 + if (result.status === "pushed" && result.branch) {
742 + yield* shareBranchBase(cwd, result.branch);
743 + }
744 + return result;
745 + });
746 const readWorktreesDirectory = serverSettingsService.getSettings.pipe(
747 Effect.map((settings) => settings.worktreesDirectory),
748 Effect.orElseSucceed(() => ""),
@@ -790,7 +758,15 @@ export const make = Effect.gen(function* () {
758 Effect.orElseSucceed(() => null),
759 );
760 const worktreesDirectory = yield* readWorktreesDirectory;
793 - return yield* gitCore.createWorktree(input, { worktreesDirectory, ...options, submodules });
761 + const result = yield* gitCore.createWorktree(input, {
762 + worktreesDirectory,
763 + ...options,
764 + submodules,
765 + });
766 + if (input.newRefName && input.baseRefName) {
767 + yield* shareBranchBase(input.cwd, input.newRefName);
768 + }
769 + return result;
770 });
771
772 const readRepositoryInstructions = Effect.fn("GitManager.readRepositoryInstructions")(
@@ -990,6 +966,31 @@ export const make = Effect.gen(function* () {
966 ),
967 );
968
969 + // The kind comes from the provider, not the remote alone: an unrecognised remote can resolve
970 + // to a known host.
971 + const changeRequestHeadRef = Effect.fn("GitManager.changeRequestHeadRef")(function* (
972 + cwd: string,
973 + number: number,
974 + ) {
975 + const provider = yield* sourceControlProvider(cwd);
976 + const ref = sourceControlClients.get(provider.kind).changeRequestHeadRef?.(number);
977 + if (ref === undefined) {
978 + return yield* new GitManagerError({
979 + operation: "changeRequestHeadRef",
980 + cwd,
981 + detail: "This host publishes no ref for a change request's head.",
982 + });
983 + }
984 + return ref;
985 + });
986 +
987 + const fetchChangeRequestHeadIntoBranch = Effect.fn("GitManager.fetchChangeRequestHeadIntoBranch")(
988 + function* (cwd: string, number: number, branch: string) {
989 + const ref = yield* changeRequestHeadRef(cwd, number);
990 + yield* gitCore.fetchRefIntoBranch({ cwd, ref, branch });
991 + },
992 + );
993 +
994 const materializePullRequestHeadBranchBase = Effect.fn("materializePullRequestHeadBranch")(
995 function* (
996 cwd: string,
@@ -999,47 +1000,38 @@ export const make = Effect.gen(function* () {
1000 const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? "";
1001
1002 if (repositoryNameWithOwner.length === 0) {
1002 - yield* gitCore
1003 - .fetchPullRequestBranch({
1004 - cwd,
1005 - prNumber: pullRequest.number,
1006 - branch: localBranch,
1007 - })
1008 - .pipe(
1009 - // Azure DevOps, GitLab and Bitbucket publish no `refs/pull/<n>/head`. A head in the
1010 - // same repository is a branch on the primary remote, so it is fetched by name instead,
1011 - // but only when that remote is the pull request's own repository: Azure finds a pull
1012 - // request by number anywhere in the organization. Only while it is open, too: the
1013 - // branch of a closed one may have moved on past the head it was closed with.
1014 - Effect.catch((cause) =>
1015 - pullRequest.isCrossRepository === true || pullRequest.state !== "open"
1016 - ? Effect.fail(cause)
1017 - : Effect.gen(function* () {
1018 - const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
1019 - const remoteUrl = yield* gitCore.readConfigValue(
1020 - cwd,
1021 - `remote.${remoteName}.url`,
1022 - );
1023 - const pullRequestKey = pullRequestRepositoryKey(pullRequest.url);
1024 - if (
1025 - remoteUrl === null ||
1026 - pullRequestKey === null ||
1027 - sourceControlClients.canonicalRepositoryKey(pullRequestKey) !==
1028 - sourceControlClients.canonicalRepositoryKey(
1029 - sourceControlClients.repositoryKeyFromRemote(remoteUrl),
1030 - )
1031 - ) {
1032 - return yield* cause;
1033 - }
1034 - yield* gitCore.fetchRemoteBranch({
1035 - cwd,
1036 - remoteName,
1037 - remoteBranch: pullRequest.headBranch,
1038 - localBranch,
1039 - });
1040 - }),
1041 - ),
1042 - );
1003 + yield* fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
1004 + // Without the host's head ref, a head in the same repository is a branch on the
1005 + // primary remote, so it is fetched by name instead, but only when that remote is the
1006 + // pull request's own repository: a host can find a change request by number outside
1007 + // the checkout's repository. Only while it is open, too: the branch of a closed one
1008 + // may have moved on past the head it was closed with.
1009 + Effect.catch((cause) =>
1010 + pullRequest.isCrossRepository === true || pullRequest.state !== "open"
1011 + ? Effect.fail(cause)
1012 + : Effect.gen(function* () {
1013 + const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);
1014 + const remoteUrl = yield* gitCore.readConfigValue(cwd, `remote.${remoteName}.url`);
1015 + const pullRequestKey = pullRequestRepositoryKey(pullRequest.url);
1016 + if (
1017 + remoteUrl === null ||
1018 + pullRequestKey === null ||
1019 + sourceControlClients.canonicalRepositoryKey(pullRequestKey) !==
1020 + sourceControlClients.canonicalRepositoryKey(
1021 + sourceControlClients.repositoryKeyFromRemote(remoteUrl),
1022 + )
1023 + ) {
1024 + return yield* cause;
1025 + }
1026 + yield* gitCore.fetchRemoteBranch({
1027 + cwd,
1028 + remoteName,
1029 + remoteBranch: pullRequest.headBranch,
1030 + localBranch,
1031 + });
1032 + }),
1033 + ),
1034 + );
1035 return;
1036 }
1037
@@ -1081,29 +1073,23 @@ export const make = Effect.gen(function* () {
1073 ) =>
1074 materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe(
1075 Effect.catch((primaryCause) =>
1084 - gitCore
1085 - .fetchPullRequestBranch({
1086 - cwd,
1087 - prNumber: pullRequest.number,
1088 - branch: localBranch,
1089 - })
1090 - .pipe(
1091 - Effect.mapError(
1092 - (fallbackCause) =>
1093 - new GitPullRequestMaterializationError({
1094 - cwd,
1095 - pullRequestNumber: pullRequest.number,
1096 - headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
1097 - headBranch: pullRequest.headBranch,
1098 - localBranch,
1099 - cause: new AggregateError(
1100 - [primaryCause, fallbackCause],
1101 - `Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
1102 - { cause: primaryCause },
1103 - ),
1104 - }),
1105 - ),
1076 + fetchChangeRequestHeadIntoBranch(cwd, pullRequest.number, localBranch).pipe(
1077 + Effect.mapError(
1078 + (fallbackCause) =>
1079 + new GitPullRequestMaterializationError({
1080 + cwd,
1081 + pullRequestNumber: pullRequest.number,
1082 + headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),
1083 + headBranch: pullRequest.headBranch,
1084 + localBranch,
1085 + cause: new AggregateError(
1086 + [primaryCause, fallbackCause],
1087 + `Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,
1088 + { cause: primaryCause },
1089 + ),
1090 + }),
1091 ),
1092 + ),
1093 ),
1094 );
1095 const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
@@ -1437,39 +1423,27 @@ export const make = Effect.gen(function* () {
1423 const readConfigValueNullable = (cwd: string, key: string) =>
1424 gitCore.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
1425
1440 - // Whether the GitHub provider creates PRs in the only remote. It picks GH_REPO when that
1441 - // parses, else what resolveGitHubRepository makes of the remote and its gh-resolved mark from
1442 - // `gh repo set-default`, given the host the provider's context gets from the remote URL. An
1443 - // HTTPS remote keeps a non-default port there, and the provider then ignores the mark. With no
1444 - // answer at all, the provider falls back to the remote itself.
1426 + // Whether the remote's host creates change requests in the only remote. A host's tools can let
1427 + // configuration outside the remotes name another repository; the remote itself otherwise.
1428 const targetsOnlyRemote = Effect.fn("targetsOnlyRemote")(function* (
1429 cwd: string,
1430 remoteName: string,
1431 remote: { readonly remoteUrl: string | null; readonly repositoryNameWithOwner: string | null },
1432 ) {
1450 - const baseUrl =
1451 - remote.remoteUrl === null
1452 - ? undefined
1453 - : sourceControlClients.recognizeRemote(remote.remoteUrl)?.baseUrl;
1454 - const host = baseUrl === undefined ? null : urlHost(baseUrl);
1455 - const repository = remote.repositoryNameWithOwner?.toLowerCase();
1456 - const fromEnvironment = parseGitHubRepositorySelector(environment.GH_REPO ?? "", host ?? "");
1457 - if (fromEnvironment !== null) {
1458 - const { host: targetHost, owner, name } = fromEnvironment;
1459 - return (
1460 - host !== null &&
1461 - urlHost(`https://${targetHost}`) === host &&
1462 - `${owner}/${name}`.toLowerCase() === repository
1463 - );
1464 - }
1465 - const mark = yield* readConfigValueNullable(cwd, `remote.${remoteName}.gh-resolved`);
1466 - const { locator } = resolveGitHubRepository({
1467 - remotes: remote.remoteUrl === null ? "" : `${remoteName}\t${remote.remoteUrl} (fetch)`,
1468 - resolved: mark === null ? "" : `remote.${remoteName}.gh-resolved ${mark}`,
1469 - hostHint: host ?? undefined,
1470 - defaultHost: host ?? "github.com",
1433 + const provider =
1434 + remote.remoteUrl === null ? null : sourceControlClients.recognizeRemote(remote.remoteUrl);
1435 + if (remote.remoteUrl === null || provider === null) return true;
1436 + const context = { provider, remoteName, remoteUrl: remote.remoteUrl };
1437 + const handle = yield* sourceControlProviders
1438 + .resolveHandle({ cwd, context })
1439 + .pipe(Effect.orElseSucceed(() => null));
1440 + const createsChangeRequestsIn = handle?.provider.createsChangeRequestsIn;
1441 + if (createsChangeRequestsIn === undefined) return true;
1442 + return yield* createsChangeRequestsIn({
1443 + cwd,
1444 + context: handle?.context ?? context,
1445 + repository: remote.repositoryNameWithOwner,
1446 });
1472 - return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === repository;
1447 });
1448
1449 const resolveHostingProvider = Effect.fn("resolveHostingProvider")(function* (
@@ -1564,9 +1538,9 @@ export const make = Effect.gen(function* () {
1538 remoteName,
1539 );
1540
1567 - // With no origin to compare against, the only remote is the repository gh targets
1568 - // unless GH_REPO or `gh repo set-default` (gh-resolved) names another, so a branch on it
1569 - // is not a fork. With several remotes, or with that other target, it may still be a fork.
1541 + // With no origin to compare against, the only remote is the repository change requests
1542 + // are created in unless the host's own configuration names another, so a branch on it is
1543 + // not a fork. With several remotes, or with that other target, it may still be a fork.
1544 const isOnlyRemote =
1545 remoteName !== null &&
1546 remoteName !== "origin" &&
@@ -1928,12 +1902,7 @@ export const make = Effect.gen(function* () {
1902 cwd: string,
1903 result: Pick<GitRunStackedActionResult, "action" | "branch" | "commit" | "push" | "pr">,
1904 ) {
1931 - const terms = yield* sourceControlProvider(cwd).pipe(
1932 - Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
1933 - Effect.orElseSucceed(() =>
1934 - getChangeRequestTerminologyForKind(SourceControlProviderKind.make("unknown")),
1935 - ),
1936 - );
1905 + const terms = yield* changeRequestTermsFor(cwd);
1906 const summary = summarizeGitActionResult(result, terms);
1907 let latestOpenPr: PullRequestInfo | null = null;
1908 let currentBranchIsDefault = false;
@@ -2032,7 +2001,7 @@ export const make = Effect.gen(function* () {
2001 if (configuredBranch) return { baseBranch: configuredBranch, baseRef: configuredRef };
2002 }
2003
2035 - const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);
2004 + const configured = yield* gitCore.readBranchBase(cwd, branch);
2005 if (configured) {
2006 const localRef = configured.startsWith("refs/") ? configured : `refs/heads/${configured}`;
2007 const localBranch = yield* gitCore.resolveBranchName(cwd, localRef);
@@ -2278,7 +2247,7 @@ export const make = Effect.gen(function* () {
2247 emit: GitActionProgressEmitter,
2248 ) {
2249 const provider = yield* sourceControlProvider(cwd);
2281 - const terms = getChangeRequestTerminologyForKind(provider.kind);
2250 + const terms = sourceControlClients.get(provider.kind).changeRequest;
2251 const details = yield* gitCore.statusDetails(cwd);
2252 const branch = details.branch ?? fallbackBranch;
2253 if (!branch) {
@@ -2871,53 +2840,52 @@ export const make = Effect.gen(function* () {
2840
2841 yield* ensureExistingWorktreeUpstream(worktreePath);
2842
2874 - const refreshed = yield* gitCore
2875 - // The pull request's own ref, because it is the only thing that certainly names its
2876 - // head. The branch's upstream does not: configuring it is best-effort, so a branch cut
2877 - // from `origin/main` whose head branch has since been deleted still resolves — and
2878 - // following it would move the checkout onto main and call that the pull request.
2879 - .fetchPullRequestHeadCommit({ cwd: worktreePath, prNumber: pullRequest.number })
2880 - .pipe(
2881 - // A host that publishes no `refs/pull/<n>/head` leaves the remote-tracking branch,
2882 - // taken only where it is the head branch's own rather than whatever the checkout
2883 - // happened to be cut from.
2884 - Effect.catch(() =>
2885 - Effect.gen(function* () {
2886 - const details = yield* gitCore.statusDetails(worktreePath);
2887 - if (
2888 - details.upstreamRef === null ||
2889 - !details.upstreamRef.endsWith(`/${pullRequest.headBranch}`)
2890 - ) {
2891 - return yield* new GitManagerError({
2892 - operation: "preparePullRequestThread",
2893 - cwd: worktreePath,
2894 - detail: "The pull request head could not be resolved for this checkout.",
2895 - });
2896 - }
2897 - return yield* gitCore.resolveCommit({
2843 + // The pull request's own ref, because it is the only thing that certainly names its
2844 + // head. The branch's upstream does not: configuring it is best-effort, so a branch cut
2845 + // from `origin/main` whose head branch has since been deleted still resolves — and
2846 + // following it would move the checkout onto main and call that the pull request.
2847 + const refreshed = yield* changeRequestHeadRef(worktreePath, pullRequest.number).pipe(
2848 + Effect.flatMap((ref) => gitCore.fetchRefCommit({ cwd: worktreePath, ref })),
2849 + // A host that publishes no head ref leaves the remote-tracking branch,
2850 + // taken only where it is the head branch's own rather than whatever the checkout
2851 + // happened to be cut from.
2852 + Effect.catch(() =>
2853 + Effect.gen(function* () {
2854 + const details = yield* gitCore.statusDetails(worktreePath);
2855 + if (
2856 + details.upstreamRef === null ||
2857 + !details.upstreamRef.endsWith(`/${pullRequest.headBranch}`)
2858 + ) {
2859 + return yield* new GitManagerError({
2860 + operation: "preparePullRequestThread",
2861 cwd: worktreePath,
2899 - revision: details.upstreamRef,
2862 + detail: "The pull request head could not be resolved for this checkout.",
2863 });
2901 - }),
2902 - ),
2903 - Effect.flatMap((target) =>
2904 - gitCore.refreshCheckedOutBranch({
2864 + }
2865 + return yield* gitCore.resolveCommit({
2866 cwd: worktreePath,
2906 - targetCommit: target.commitSha,
2907 - resetWhenHeadCommit: upstreamCommitBeforeFetch,
2908 - }),
2909 - ),
2910 - Effect.catch((error) =>
2911 - Effect.logWarning(
2912 - "GitManager.preparePullRequestThread reused worktree refresh failed",
2913 - {
2914 - worktreePath,
2915 - localBranch: localPullRequestBranch,
2916 - cause: error,
2917 - },
2918 - ).pipe(Effect.as({ moved: false, onTarget: false })),
2919 - ),
2920 - );
2867 + revision: details.upstreamRef,
2868 + });
2869 + }),
2870 + ),
2871 + Effect.flatMap((target) =>
2872 + gitCore.refreshCheckedOutBranch({
2873 + cwd: worktreePath,
2874 + targetCommit: target.commitSha,
2875 + resetWhenHeadCommit: upstreamCommitBeforeFetch,
2876 + }),
2877 + ),
2878 + Effect.catch((error) =>
2879 + Effect.logWarning(
2880 + "GitManager.preparePullRequestThread reused worktree refresh failed",
2881 + {
2882 + worktreePath,
2883 + localBranch: localPullRequestBranch,
2884 + cause: error,
2885 + },
2886 + ).pipe(Effect.as({ moved: false, onTarget: false })),
2887 + ),
2888 + );
2889
2890 // Only when the checkout actually moved: another thread may be running in this worktree,
2891 // and re-running the setup script under it buys nothing when the code did not change.
@@ -3189,14 +3157,7 @@ export const make = Effect.gen(function* () {
3157
3158 const currentBranch = branchStep.name ?? initialStatus.branch;
3159 const commitAction = isCommitAction(input.action) ? input.action : null;
3192 - const changeRequestTerms = wantsPr
3193 - ? yield* sourceControlProvider(input.cwd).pipe(
3194 - Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),
3195 - Effect.orElseSucceed(() =>
3196 - getChangeRequestTerminologyForKind(SourceControlProviderKind.make("unknown")),
3197 - ),
3198 - )
3199 - : null;
3160 + const changeRequestTerms = wantsPr ? yield* changeRequestTermsFor(input.cwd) : null;
3161
3162 const commit = commitAction
3163 ? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
@@ -3225,7 +3186,7 @@ export const make = Effect.gen(function* () {
3186 })
3187 .pipe(
3188 Effect.tap(() => Ref.set(currentPhase, Option.some("push"))),
3228 - Effect.flatMap(() => gitCore.pushCurrentBranch(input.cwd, currentBranch)),
3189 + Effect.flatMap(() => pushCurrentBranch(input.cwd, currentBranch)),
3190 )
3191 : { status: "skipped_not_requested" as const };
3192
apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts
+4 -7
@@ -94,6 +94,7 @@ const makeRepositories = Effect.gen(function* () {
94
95 const detail = (workspaceRoot: string, headSha: string): PullRequestDetail =>
96 ({
97 + provider: "github",
98 number: 7,
99 title: "Add the feature",
100 body: "Adds the feature.",
@@ -385,13 +386,7 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic
386 name: "a head no source has",
387 reportedHead: () => "e".repeat(40),
388 shadow: "none",
388 - expected: [
389 - "local objects:",
390 - "the commit:",
391 - "branch feature:",
392 - "refs/pull/7/head:",
393 - "refs/merge-requests/7/head:",
394 - ],
389 + expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"],
390 },
391 ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) =>
392 Effect.scoped(
@@ -415,6 +410,8 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic
410 assert.strictEqual(result.run?._tag, "Failed");
411 const detail = result.run?._tag === "Failed" ? result.run.detail : "";
412 for (const part of expected) assert.include(detail, part);
413 + // Only the host's own head ref is tried.
414 + assert.notInclude(detail, "refs/merge-requests/");
415 assert.deepStrictEqual(run.observed, []);
416 assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
417 const fs = yield* FileSystem.FileSystem;
apps/server/src/pullRequest/PullRequestReviewGuideService.ts
+2 -5
@@ -251,6 +251,7 @@ const make = Effect.gen(function* () {
251 ),
252 );
253 const fetchAndResolve = (ref: string) => fetch([ref]).pipe(Effect.andThen(resolveHead));
254 + const headRef = sourceControlClients.get(detail.provider).changeRequestHeadRef?.(number);
255 const branchRef = `refs/heads/${branch}`;
256 const checkBranch = git.execute({
257 operation: "PullRequestReviewGuideService.checkHeadBranch",
@@ -266,11 +267,7 @@ const make = Effect.gen(function* () {
267 source: `branch ${branch}`,
268 head: checkBranch.pipe(Effect.andThen(fetchAndResolve(branchRef))),
269 },
269 - { source: `refs/pull/${number}/head`, head: fetchAndResolve(`refs/pull/${number}/head`) },
270 - {
271 - source: `refs/merge-requests/${number}/head`,
272 - head: fetchAndResolve(`refs/merge-requests/${number}/head`),
273 - },
270 + ...(headRef === undefined ? [] : [{ source: headRef, head: fetchAndResolve(headRef) }]),
271 ];
272 const failures: Array<string> = [];
273 for (const { source, head } of sources) {
apps/server/src/vcs/GitVcsDriver.ts
+16 -12
@@ -201,15 +201,10 @@ export interface GitRenameBranchResult {
201 branch: string;
202 }
203
204 -export interface GitFetchPullRequestBranchInput {
204 +export interface GitFetchRefInput {
205 cwd: string;
206 - prNumber: number;
207 - branch: string;
208 -}
209 -
210 -export interface GitFetchPullRequestHeadCommitInput {
211 - cwd: string;
212 - prNumber: number;
206 + /** A ref on the primary remote, such as a host's change request head ref. */
207 + ref: string;
208 }
209
210 export interface GitResolveCommitInput {
@@ -342,6 +337,14 @@ export class GitVcsDriver extends Context.Service<
337 cwd: string,
338 key: string,
339 ) => Effect.Effect<string | null, GitCommandError>;
340 + /**
341 + * The branch, named as on the host, that T3 recorded `branch` was cut from. Null when none
342 + * was recorded.
343 + */
344 + readonly readBranchBase: (
345 + cwd: string,
346 + branch: string,
347 + ) => Effect.Effect<string | null, GitCommandError>;
348 readonly resolveBranchName: (
349 cwd: string,
350 refName: string,
@@ -354,11 +357,12 @@ export class GitVcsDriver extends Context.Service<
357 input: VcsCreateWorktreeInput,
358 options?: CreateWorktreeOptions,
359 ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
357 - readonly fetchPullRequestBranch: (
358 - input: GitFetchPullRequestBranchInput,
360 + /** Force-updates local `branch` to the primary remote's `ref`. */
361 + readonly fetchRefIntoBranch: (
362 + input: GitFetchRefInput & { readonly branch: string },
363 ) => Effect.Effect<void, GitCommandError>;
360 - readonly fetchPullRequestHeadCommit: (
361 - input: GitFetchPullRequestHeadCommitInput,
364 + readonly fetchRefCommit: (
365 + input: GitFetchRefInput,
366 ) => Effect.Effect<GitResolveCommitResult, GitCommandError>;
367 readonly resolveCommit: (
368 input: GitResolveCommitInput,
apps/server/src/vcs/GitVcsDriverCore.test.ts
+7 -7
@@ -3066,7 +3066,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3066 yield* git(cwd, ["rev-parse", "HEAD"]),
3067 );
3068 assert.equal(
3069 - yield* git(cwd, ["config", "branch.feature/parallel.gh-merge-base"]),
3069 + yield* git(cwd, ["config", "branch.feature/parallel.t3-merge-base"]),
3070 initialBranch,
3071 );
3072 for (const [configured, expected] of [
@@ -3117,7 +3117,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3117
3118 assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), commit);
3119 assert.equal(
3120 - yield* driver.readConfigValue(cwd, "branch.feature/revision.gh-merge-base"),
3120 + yield* driver.readConfigValue(cwd, "branch.feature/revision.t3-merge-base"),
3121 null,
3122 );
3123 }),
@@ -3142,7 +3142,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3142 });
3143
3144 assert.equal(
3145 - yield* driver.readConfigValue(cwd, "branch.feature/branch.gh-merge-base"),
3145 + yield* driver.readConfigValue(cwd, "branch.feature/branch.t3-merge-base"),
3146 baseBranch,
3147 );
3148 }),
@@ -3465,7 +3465,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3465 "# test\n",
3466 );
3467 assert.equal(
3468 - yield* driver.readConfigValue(worktreePath, "branch.feature/locked-config.gh-merge-base"),
3468 + yield* driver.readConfigValue(worktreePath, "branch.feature/locked-config.t3-merge-base"),
3469 null,
3470 );
3471 assert.equal(yield* fileSystem.exists(pathService.join(cwd, ".git/config.lock")), true);
@@ -3737,7 +3737,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
3737 assert.equal(yield* driver.resolvePrimaryRemoteName(cwd), remoteName);
3738 yield* driver.fetchRemoteTrackingBranch({ cwd, remoteName, remoteBranch: initialBranch });
3739 yield* driver.fetchRemote({ cwd, remoteName });
3740 - const head = yield* driver.fetchPullRequestHeadCommit({ cwd, prNumber: 7 });
3740 + const head = yield* driver.fetchRefCommit({ cwd, ref: "refs/pull/7/head" });
3741
3742 assert.isFalse(yield* fileSystem.exists((yield* Path.Path).join(cwd, "t3-marker")));
3743 assert.equal(head.commitSha, yield* git(cwd, ["rev-parse", "HEAD"]));
@@ -4133,7 +4133,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4133 assert.strictEqual(status.branchChanges?.deletions, 0);
4134 // gh pr create consumes this setting verbatim as the hosted target branch.
4135 assert.equal(
4136 - yield* driver.readConfigValue(worktreePath, "branch.feature/from-upstream.gh-merge-base"),
4136 + yield* driver.readConfigValue(worktreePath, "branch.feature/from-upstream.t3-merge-base"),
4137 "release",
4138 );
4139 assert.equal(changes.baseRef, "upstream/release");
@@ -4362,7 +4362,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
4362 yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]),
4363 "origin/feature/x",
4364 );
4365 - assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.gh-merge-base"), "dev");
4365 + assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.t3-merge-base"), "dev");
4366
4367 const preview = yield* driver.getReviewDiffPreview({ cwd });
4368 const changes = preview.sources.find((source) => source.kind === "branch-range")!;
apps/server/src/vcs/GitVcsDriverCore.ts
+60 -50
@@ -53,6 +53,13 @@ import * as ServerConfig from "../config.ts";
53 import { sourceControlClients } from "../sourceControl/sourceControlClients.ts";
54
55 const DEFAULT_TIMEOUT_MS = 30_000;
56 +/** T3's record of the branch, named as on the host, that a branch was cut from. */
57 +const branchBaseConfigKey = (branch: string) => `branch.${branch}.t3-merge-base`;
58 +/**
59 + * Where T3 kept that record before it had a key of its own, for every host alike: the GitHub
60 + * CLI's key, which branches cut before then still carry instead.
61 + */
62 +const legacyBranchBaseConfigKey = (branch: string) => `branch.${branch}.gh-merge-base`;
63 const gitProcesses = Semaphore.makeUnsafe(8);
64 const WORKTREE_ADD_TIMEOUT_MS = 300_000;
65 const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
@@ -1818,8 +1825,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
1825 }
1826 }
1827
1821 - const configuredBaseBranch =
1822 - (yield* readConfigValue(cwd, `branch.${refName}.gh-merge-base`)) ?? "";
1828 + const configuredBaseBranch = (yield* readBranchBase(cwd, refName)) ?? "";
1829 const configuredBase = yield* resolveComparisonBaseRef(cwd, configuredBaseBranch);
1830 if (
1831 configuredBase !== null &&
@@ -2638,16 +2644,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
2644 const remoteName = publishRemoteName ?? currentUpstream.remoteName;
2645 const publishBranch = yield* resolvePublishBranchName(cwd, branch);
2646 // Publishing retargets the upstream, so preserve its comparison base first.
2641 - const configuredMergeBase = yield* runGitStdout(
2642 - "GitVcsDriver.pushCurrentBranch.readMergeBase",
2643 - cwd,
2644 - ["config", "--get", `branch.${branch}.gh-merge-base`],
2645 - true,
2646 - ).pipe(Effect.map((stdout) => stdout.trim()));
2647 - if (configuredMergeBase.length === 0) {
2647 + if ((yield* readBranchBase(cwd, branch)) === null) {
2648 yield* runGit("GitVcsDriver.pushCurrentBranch.recordMergeBase", cwd, [
2649 "config",
2650 - `branch.${branch}.gh-merge-base`,
2650 + branchBaseConfigKey(branch),
2651 currentUpstream.branchName,
2652 ]);
2653 if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) {
@@ -3369,6 +3369,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3369 Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
3370 );
3371
3372 + const readBranchBase: GitVcsDriver.GitVcsDriver["Service"]["readBranchBase"] = Effect.fn(
3373 + "GitVcsDriver.readBranchBase",
3374 + )(function* (cwd, branch) {
3375 + const base = yield* readConfigValue(cwd, branchBaseConfigKey(branch));
3376 + return base ?? (yield* readConfigValue(cwd, legacyBranchBaseConfigKey(branch)));
3377 + });
3378 +
3379 const resolveBranchBase = Effect.fn("GitVcsDriver.resolveBranchBase")(function* (
3380 cwd: string,
3381 refName: string,
@@ -3842,17 +3849,18 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3849 );
3850 }
3851
3845 - if (input.newRefName && input.baseRefName) {
3852 + const newRefName = input.newRefName;
3853 + if (newRefName && input.baseRefName) {
3854 const base = yield* resolveBranchBase(input.cwd, input.baseRefName);
3855 if (base) {
3856 yield* Effect.gen(function* () {
3857 yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [
3858 "config",
3851 - `branch.${input.newRefName}.gh-merge-base`,
3859 + branchBaseConfigKey(newRefName),
3860 base.branchName,
3861 ]);
3862 if (base.baseRef.startsWith("refs/remotes/")) {
3855 - // gh consumes its key as a provider branch; T3 also needs the selected remote.
3863 + // The base key names a branch on the host; this one keeps the remote it came from.
3864 yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [
3865 "config",
3866 `branch.${input.newRefName}.t3-merge-base-ref`,
@@ -3878,25 +3886,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3886 };
3887 });
3888
3881 - const fetchPullRequestBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchPullRequestBranch"] =
3882 - Effect.fn("fetchPullRequestBranch")(function* (input) {
3883 - const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
3884 - yield* executeGit(
3885 - "GitVcsDriver.fetchPullRequestBranch",
3886 - input.cwd,
3887 - [
3888 - "fetch",
3889 - "--quiet",
3890 - "--no-tags",
3891 - "--",
3892 - remoteName,
3893 - `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`,
3894 - ],
3895 - {
3896 - fallbackErrorDetail: "git fetch pull request branch failed",
3897 - },
3898 - );
3899 - });
3889 + const fetchRefIntoBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRefIntoBranch"] = Effect.fn(
3890 + "GitVcsDriver.fetchRefIntoBranch",
3891 + )(function* (input) {
3892 + const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
3893 + yield* executeGit(
3894 + "GitVcsDriver.fetchRefIntoBranch",
3895 + input.cwd,
3896 + [
3897 + "fetch",
3898 + "--quiet",
3899 + "--no-tags",
3900 + "--",
3901 + remoteName,
3902 + `+${input.ref}:refs/heads/${input.branch}`,
3903 + ],
3904 + {
3905 + fallbackErrorDetail: "git fetch ref into branch failed",
3906 + },
3907 + );
3908 + });
3909
3910 const resolveCommit: GitVcsDriver.GitVcsDriver["Service"]["resolveCommit"] = Effect.fn(
3911 "resolveCommit",
@@ -3910,22 +3919,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
3919 return { commitSha };
3920 });
3921
3913 - const fetchPullRequestHeadCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchPullRequestHeadCommit"] =
3914 - Effect.fn("fetchPullRequestHeadCommit")(function* (input) {
3915 - const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
3916 - // No refspec destination: the pull head lands in FETCH_HEAD (per worktree) instead of a
3917 - // branch, which is the only way to read it while that branch is checked out somewhere.
3918 - yield* executeGit(
3919 - "GitVcsDriver.fetchPullRequestHeadCommit",
3920 - input.cwd,
3921 - ["fetch", "--quiet", "--no-tags", "--", remoteName, `refs/pull/${input.prNumber}/head`],
3922 - {
3923 - fallbackErrorDetail: "git fetch pull request head failed",
3924 - },
3925 - );
3922 + const fetchRefCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchRefCommit"] = Effect.fn(
3923 + "GitVcsDriver.fetchRefCommit",
3924 + )(function* (input) {
3925 + const remoteName = yield* resolvePrimaryRemoteName(input.cwd);
3926 + // No refspec destination: the ref lands in FETCH_HEAD (per worktree) instead of a branch,
3927 + // which is the only way to read it while that branch is checked out somewhere.
3928 + yield* executeGit(
3929 + "GitVcsDriver.fetchRefCommit",
3930 + input.cwd,
3931 + ["fetch", "--quiet", "--no-tags", "--", remoteName, input.ref],
3932 + {
3933 + fallbackErrorDetail: "git fetch ref failed",
3934 + },
3935 + );
3936
3927 - return yield* resolveCommit({ cwd: input.cwd, revision: "FETCH_HEAD" });
3928 - });
3937 + return yield* resolveCommit({ cwd: input.cwd, revision: "FETCH_HEAD" });
3938 + });
3939
3940 const refreshCheckedOutBranch: GitVcsDriver.GitVcsDriver["Service"]["refreshCheckedOutBranch"] =
3941 Effect.fn("refreshCheckedOutBranch")(function* (input) {
@@ -4507,13 +4517,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4517 getReviewDiffPreview,
4518 getReviewDiffFileContents,
4519 readConfigValue,
4520 + readBranchBase,
4521 resolveBranchName,
4522 listRefs,
4523 createWorktree: (input, options) =>
4524 withListRefsInvalidation(input.cwd, createWorktree(input, options)),
4514 - fetchPullRequestBranch: (input) =>
4515 - withListRefsInvalidation(input.cwd, fetchPullRequestBranch(input)),
4516 - fetchPullRequestHeadCommit,
4525 + fetchRefIntoBranch: (input) => withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input)),
4526 + fetchRefCommit,
4527 resolveCommit,
4528 refreshCheckedOutBranch: (input) =>
4529 withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)),
apps/server/src/vcs/VcsProcess.test.ts
+28 -3
@@ -258,7 +258,7 @@ describe("VcsProcess.run", () => {
258 }),
259 );
260
261 - it.effect("bounds a synthetic burst of GitHub API processes", () =>
261 + it.effect("bounds a burst of processes that share a concurrency key", () =>
262 Effect.gen(function* () {
263 const gate = yield* Deferred.make<void>();
264 const starts = yield* Queue.unbounded<number>();
@@ -294,10 +294,11 @@ describe("VcsProcess.run", () => {
294 const burst = yield* Effect.all(
295 Array.from({ length: 32 }, (_, index) =>
296 service.run({
297 - operation: `synthetic.github.${index}`,
298 - command: "gh",
297 + operation: `synthetic.cli.${index}`,
298 + command: "host-cli",
299 args: ["api", "user"],
300 cwd: "/workspace",
301 + concurrency: { key: "host-cli", limit: 4 },
302 }),
303 ),
304 { concurrency: "unbounded" },
@@ -391,6 +392,30 @@ describe("VcsProcess.run", () => {
392 }).pipe(provideLive),
393 );
394
395 + it.effect("reads a failure with the command's own classifier and names it in its terms", () =>
396 + Effect.gen(function* () {
397 + const fail = (input: Partial<VcsProcess.VcsProcessInput>) =>
398 + run({
399 + operation: "test.classify",
400 + command: "node",
401 + args: ["-e", "process.stderr.write('HTTP 404: 404 Not Found'); process.exit(1)"],
402 + cwd: process.cwd(),
403 + ...input,
404 + }).pipe(Effect.flip);
405 +
406 + expect(yield* fail({})).toMatchObject({
407 + failureKind: "command-failed",
408 + detail: "Process exited with a non-zero status.",
409 + });
410 + expect(
411 + yield* fail({
412 + classifyFailure: (stderr) => (stderr.includes("404") ? "not-found" : null),
413 + notFoundDetail: "Merge request not found.",
414 + }),
415 + ).toMatchObject({ failureKind: "not-found", detail: "Merge request not found." });
416 + }).pipe(provideLive),
417 + );
418 +
419 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
420 Effect.gen(function* () {
421 const secretArgument = "--token=super-secret-token";
apps/server/src/vcs/VcsProcess.ts
+33 -31
@@ -20,6 +20,7 @@ import {
20 VcsProcessTimeoutError,
21 } from "@t3tools/contracts";
22 import * as HostProcess from "@t3tools/shared/HostProcess";
23 +import type { SourceControlProcessInput } from "@t3tools/source-control-core/server/SourceControlHost";
24
25 import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
26 import * as ProcessRunner from "../processRunner.ts";
@@ -38,6 +39,9 @@ export interface VcsProcessInput {
39 readonly maxOutputBytes?: number;
40 readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"];
41 readonly appendTruncationMarker?: boolean;
42 + readonly classifyFailure?: SourceControlProcessInput["classifyFailure"];
43 + readonly notFoundDetail?: string;
44 + readonly concurrency?: SourceControlProcessInput["concurrency"];
45 }
46
47 export interface VcsProcessOutput {
@@ -61,7 +65,6 @@ const DEFAULT_TIMEOUT_MS = 30_000;
65 const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
66 const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
67 const VCS_PROCESS_CONCURRENCY = 8;
64 -const GITHUB_PROCESS_CONCURRENCY = 4;
68
69 /** Shown to users when a Git command fails because another process holds the index lock. */
70 export const GIT_INDEX_LOCKED_DETAIL =
@@ -132,22 +135,23 @@ export const gitConfigEnv = (
135 * Git otherwise opens any folder holding `HEAD`, `objects/` and `refs/` as a
136 * bare repository and applies its `config`, including commands such as
137 * `core.fsmonitor`. Files saved in a project or checked out from a clone can
135 - * form one, so git started by T3 (or by gh and friends) only opens a bare
138 + * form one, so git started by T3 (or by a host CLI) only opens a bare
139 * repository named with `--git-dir` or `GIT_DIR`. Git before 2.38 ignores it.
140 */
141 export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) =>
142 gitConfigEnv(env, "safe.bareRepository", "explicit", platform);
143
141 -const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
144 +const classifyNonZeroExit = (
145 + stderr: string,
146 + classifyFailure: VcsProcessInput["classifyFailure"],
147 +): VcsProcessExitFailureKind => {
148 const normalized = stderr.toLowerCase();
149 + const commandKind = classifyFailure?.(stderr) ?? null;
150
151 if (
152 + commandKind === "authentication" ||
153 normalized.includes("authentication failed") ||
154 normalized.includes("not logged in") ||
147 - normalized.includes("gh auth login") ||
148 - normalized.includes("glab auth login") ||
149 - normalized.includes("az devops login") ||
150 - normalized.includes("please run az login") ||
155 normalized.includes("no oauth token") ||
156 normalized.includes("unauthorized")
157 ) {
@@ -155,6 +159,7 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai
159 }
160
161 if (
162 + commandKind === "rate-limited" ||
163 normalized.includes("api rate limit") ||
164 normalized.includes("rate limit exceeded") ||
165 normalized.includes("secondary rate limit") ||
@@ -164,24 +169,7 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai
169 return "rate-limited";
170 }
171
167 - if (
168 - (command === "gh" &&
169 - (normalized.includes("could not resolve to a pullrequest") ||
170 - normalized.includes("repository.pullrequest") ||
171 - normalized.includes("no pull requests found for branch") ||
172 - normalized.includes("pull request not found"))) ||
173 - (command === "glab" &&
174 - (normalized.includes("merge request not found") ||
175 - normalized.includes("not found") ||
176 - normalized.includes("404"))) ||
177 - (command === "az" &&
178 - normalized.includes("pull request") &&
179 - (normalized.includes("not found") || normalized.includes("does not exist")))
180 - ) {
181 - return "not-found";
182 - }
183 -
184 - return "command-failed";
172 + return commandKind ?? "command-failed";
173 };
174
175 // Classify before discarding stderr; keep paths and process output out of errors.
@@ -204,7 +192,15 @@ export const make = Effect.gen(function* () {
192 const processRunner = yield* ProcessRunner.ProcessRunner;
193 const hostPlatform = yield* HostProcess.Platform;
194 const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
207 - const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY);
195 + const keyedProcesses = new Map<string, Semaphore.Semaphore>();
196 + const keyedPermit = (concurrency: NonNullable<VcsProcessInput["concurrency"]>) => {
197 + let semaphore = keyedProcesses.get(concurrency.key);
198 + if (semaphore === undefined) {
199 + semaphore = Semaphore.makeUnsafe(concurrency.limit);
200 + keyedProcesses.set(concurrency.key, semaphore);
201 + }
202 + return semaphore.withPermits(1);
203 + };
204
205 const spawn = Effect.fn("VcsProcess.spawn")(function* (
206 input: VcsProcessInput,
@@ -315,7 +311,7 @@ export const make = Effect.gen(function* () {
311 }
312
313 if (!input.allowNonZeroExit && result.code !== 0) {
318 - const failureKind = classifyNonZeroExit(input.command, result.stderr);
314 + const failureKind = classifyNonZeroExit(result.stderr, input.classifyFailure);
315 const error = VcsProcessExitError.fromProcessExit(
316 baseError,
317 {
@@ -324,9 +320,13 @@ export const make = Effect.gen(function* () {
320 stderrTruncated: result.stderrTruncated,
321 },
322 failureKind,
327 - input.command === "git" &&
328 - failureKind === "command-failed" &&
329 - isTransientGitExit(result.stderr),
323 + {
324 + retryable:
325 + input.command === "git" &&
326 + failureKind === "command-failed" &&
327 + isTransientGitExit(result.stderr),
328 + ...(input.notFoundDetail === undefined ? {} : { notFoundDetail: input.notFoundDetail }),
329 + },
330 );
331 if (
332 input.command === "git" &&
@@ -374,7 +374,9 @@ export const make = Effect.gen(function* () {
374 }),
375 );
376 }
377 - return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded;
377 + return yield* input.concurrency === undefined
378 + ? bounded
379 + : keyedPermit(input.concurrency)(bounded);
380 });
381
382 return VcsProcess.of({ run });
apps/server/src/vcs/VcsStatusBroadcaster.ts
+1 -1
@@ -243,7 +243,7 @@ export const make = Effect.gen(function* () {
243 );
244 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
245 // One permit per cwd for remote reads that write the cache. Without it a
246 - // periodic poll that started before `gh pr create` can finish after the
246 + // periodic poll that started before an agent creates a PR can finish after the
247 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
248 const remoteWriteLocks = yield* KeyedLock.make<string>();
249 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
packages/contracts/src/vcs.ts
+3 -7
@@ -132,7 +132,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
132 context: VcsProcessErrorContext,
133 error: VcsProcessExitFailure,
134 failureKind: VcsProcessExitFailureKind,
135 - retryable?: boolean,
135 + options?: { readonly retryable?: boolean; readonly notFoundDetail?: string },
136 ) {
137 const detail =
138 failureKind === "authentication"
@@ -140,11 +140,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
140 : failureKind === "rate-limited"
141 ? "API rate limit exceeded."
142 : failureKind === "not-found"
143 - ? context.command === "glab"
144 - ? "Merge request not found."
145 - : context.command === "gh" || context.command === "az"
146 - ? "Pull request not found."
147 - : "VCS resource not found."
143 + ? (options?.notFoundDetail ?? "VCS resource not found.")
144 : "Process exited with a non-zero status.";
145
146 return new VcsProcessExitError({
@@ -152,7 +148,7 @@ export class VcsProcessExitError extends Schema.TaggedError<VcsProcessExitError>
148 exitCode: error.exitCode,
149 detail,
150 failureKind,
155 - ...(retryable === true ? { retryable: true } : {}),
151 + ...(options?.retryable === true ? { retryable: true } : {}),
152 stderrLength: error.stderr.length,
153 stderrTruncated: error.stderrTruncated,
154 });
packages/shared/src/sourceControl.test.ts deleted
-11
@@ -1,11 +0,0 @@
1 -import { SourceControlProviderKind } from "@t3tools/contracts";
2 -import { expect, it } from "vite-plus/test";
3 -
4 -import { getChangeRequestTerminologyForKind } from "./sourceControl.ts";
5 -
6 -it("calls a Forgejo change request a pull request", () => {
7 - expect(getChangeRequestTerminologyForKind(SourceControlProviderKind.make("forgejo"))).toEqual({
8 - shortLabel: "PR",
9 - singular: "pull request",
10 - });
11 -});
packages/shared/src/sourceControl.ts
-138
@@ -1,141 +1,3 @@
1 -import type { SourceControlProviderInfo, SourceControlProviderKind } from "@t3tools/contracts";
2 -
3 -export interface ChangeRequestPresentation {
4 - readonly icon:
5 - | "github"
6 - | "gitlab"
7 - | "forgejo"
8 - | "azure-devops"
9 - | "bitbucket"
10 - | "gitcafe"
11 - | "change-request";
12 - readonly providerName: string;
13 - readonly shortName: string;
14 - readonly longName: string;
15 - readonly pluralLongName: string;
16 - readonly providerLongName: string;
17 - readonly checkoutCommandExample?: string;
18 - readonly urlExample: string;
19 -}
20 -
21 -export interface ChangeRequestTerminology {
22 - readonly shortLabel: string;
23 - readonly singular: string;
24 -}
25 -
26 -const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
27 - icon: "github",
28 - providerName: "GitHub",
29 - shortName: "PR",
30 - longName: "pull request",
31 - pluralLongName: "pull requests",
32 - providerLongName: "GitHub pull request",
33 - checkoutCommandExample: "gh pr checkout 123",
34 - urlExample: "https://github.com/owner/repo/pull/42",
35 -};
36 -
37 -const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
38 - icon: "gitlab",
39 - providerName: "GitLab",
40 - shortName: "MR",
41 - longName: "merge request",
42 - pluralLongName: "merge requests",
43 - providerLongName: "GitLab merge request",
44 - checkoutCommandExample: "glab mr checkout 123",
45 - urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
46 -};
47 -
48 -const FORGEJO_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
49 - icon: "forgejo",
50 - providerName: "Forgejo",
51 - shortName: "PR",
52 - longName: "pull request",
53 - pluralLongName: "pull requests",
54 - providerLongName: "Forgejo pull request",
55 - checkoutCommandExample: "tea pr checkout 123",
56 - urlExample: "https://codeberg.org/owner/repo/pulls/42",
57 -};
58 -
59 -const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
60 - icon: "azure-devops",
61 - providerName: "Azure DevOps",
62 - shortName: "PR",
63 - longName: "pull request",
64 - pluralLongName: "pull requests",
65 - providerLongName: "Azure DevOps pull request",
66 - checkoutCommandExample: "az repos pr checkout --id 123",
67 - urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
68 -};
69 -
70 -const BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
71 - icon: "bitbucket",
72 - providerName: "Bitbucket",
73 - shortName: "PR",
74 - longName: "pull request",
75 - pluralLongName: "pull requests",
76 - providerLongName: "Bitbucket pull request",
77 - urlExample: "https://bitbucket.org/workspace/repo/pull-requests/42",
78 -};
79 -
80 -const GITCAFE_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
81 - icon: "gitcafe",
82 - providerName: "GitCafe",
83 - shortName: "PR",
84 - longName: "pull request",
85 - pluralLongName: "pull requests",
86 - providerLongName: "GitCafe pull request",
87 - checkoutCommandExample: "cafe pr checkout 123",
88 - urlExample: "https://git.cafe/owner/repo/pulls/42",
89 -};
90 -
91 -const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
92 - icon: "change-request",
93 - providerName: "source control",
94 - shortName: "change request",
95 - longName: "change request",
96 - pluralLongName: "change requests",
97 - providerLongName: "change request",
98 - urlExample: "#42",
99 -};
100 -
101 -function resolveChangeRequestPresentation(
102 - provider: SourceControlProviderInfo | null | undefined,
103 -): ChangeRequestPresentation {
104 - switch (provider?.kind) {
105 - case "github":
106 - case undefined:
107 - return GITHUB_CHANGE_REQUEST_PRESENTATION;
108 - case "gitlab":
109 - return GITLAB_CHANGE_REQUEST_PRESENTATION;
110 - case "forgejo":
111 - return FORGEJO_CHANGE_REQUEST_PRESENTATION;
112 - case "azure-devops":
113 - return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
114 - case "bitbucket":
115 - return BITBUCKET_CHANGE_REQUEST_PRESENTATION;
116 - case "gitcafe":
117 - return GITCAFE_CHANGE_REQUEST_PRESENTATION;
118 - default:
119 - return GENERIC_CHANGE_REQUEST_PRESENTATION;
120 - }
121 -}
122 -
123 -function resolveChangeRequestPresentationForKind(
124 - kind: SourceControlProviderKind,
125 -): ChangeRequestPresentation {
126 - return resolveChangeRequestPresentation({ kind, name: "", baseUrl: "" });
127 -}
128 -
129 -export function getChangeRequestTerminologyForKind(
130 - kind: SourceControlProviderKind,
131 -): ChangeRequestTerminology {
132 - const presentation = resolveChangeRequestPresentationForKind(kind);
133 - return {
134 - shortLabel: presentation.shortName,
135 - singular: presentation.longName,
136 - };
137 -}
138 -
1 const SCP_SSH_REMOTE_PATTERN = /^[a-zA-Z0-9._-]+@([^:/]+):/;
2
3 export function isSshRemoteUrl(remoteUrl: string): boolean {
packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts
+15 -1
@@ -70,7 +70,20 @@ describe("AzureDevOpsCli.layer", () => {
70 assert.strictEqual(result.headSha, "a".repeat(40));
71 assert.strictEqual(result.state, "open");
72 assert.deepStrictEqual(result.updatedAt._tag, Option.some(1)._tag);
73 - assert.deepStrictEqual(mockRun.mock.calls.at(-1)?.[0], {
73 + const { classifyFailure, ...call } = mockRun.mock.calls.at(-1)?.[0] ?? {};
74 + assert.strictEqual(
75 + classifyFailure?.("Please run az login to setup account."),
76 + "authentication",
77 + );
78 + assert.strictEqual(
79 + classifyFailure?.("Please run 'az login' to setup account."),
80 + "authentication",
81 + );
82 + assert.strictEqual(
83 + classifyFailure?.("TF401180: The requested pull request was not found."),
84 + "not-found",
85 + );
86 + assert.deepStrictEqual(call, {
87 operation: "AzureDevOpsCli.execute",
88 command: "az",
89 args: [
@@ -86,6 +99,7 @@ describe("AzureDevOpsCli.layer", () => {
99 "json",
100 ],
101 cwd: "/repo",
102 + notFoundDetail: "Pull request not found.",
103 timeoutMs: 30_000,
104 });
105 assert.strictEqual(result.isCrossRepository, false);
packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts
+14
@@ -9,6 +9,7 @@ import {
9 TrimmedNonEmptyString,
10 type SourceControlRepositoryVisibility,
11 type VcsError,
12 + type VcsProcessExitFailureKind,
13 } from "@t3tools/contracts";
14
15 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
@@ -350,6 +351,17 @@ function decodeAzureDevOpsJson<S extends Schema.Top>(
351 );
352 }
353
354 +const classifyAzFailure = (stderr: string): VcsProcessExitFailureKind | null => {
355 + const normalized = stderr.toLowerCase();
356 + if (normalized.includes("az devops login") || /please run '?az login'?/.test(normalized)) {
357 + return "authentication";
358 + }
359 + return normalized.includes("pull request") &&
360 + (normalized.includes("not found") || normalized.includes("does not exist"))
361 + ? "not-found"
362 + : null;
363 +};
364 +
365 /** @public Service construction is part of the canonical Effect module API. */
366 export const make = Effect.gen(function* () {
367 const { process } = yield* SourceControlHost.SourceControlHost;
@@ -361,6 +373,8 @@ export const make = Effect.gen(function* () {
373 command: "az",
374 args: input.args,
375 cwd: input.cwd,
376 + classifyFailure: classifyAzFailure,
377 + notFoundDetail: "Pull request not found.",
378 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
379 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),
380 })
packages/source-control-core/src/client/definition.ts
+5
@@ -125,6 +125,11 @@ export interface SourceControlClientDefinition {
125 link: ChangeRequestLink,
126 ) => boolean;
127 readonly checkoutChangeRequestHost: (identity: ChangeRequestProjectIdentity) => string | null;
128 + /**
129 + * The ref the target repository publishes change request `number`'s head under, which names the
130 + * head even when it lives in a fork. Absent for a host that publishes none.
131 + */
132 + readonly changeRequestHeadRef?: (number: number) => string;
133 /** Null when this host does not claim the remote. Asked in the registry's recognition order. */
134 readonly recognizeRemote: (remote: GitRemoteHost) => SourceControlProviderInfo | null;
135 /** The host change requests in the project are listed and keyed under. */
packages/source-control-core/src/server/SourceControlHost.ts
+13
@@ -4,6 +4,7 @@ import type {
4 ServerSettingsError,
5 VcsError,
6 VcsListRemotesResult,
7 + VcsProcessExitFailureKind,
8 VcsSwitchRefInput,
9 VcsSwitchRefResult,
10 } from "@t3tools/contracts";
@@ -25,6 +26,18 @@ export interface SourceControlProcessInput {
26 readonly maxOutputBytes?: number;
27 readonly outputMode?: "error" | "truncate" | undefined;
28 readonly appendTruncationMarker?: boolean;
29 + /**
30 + * Reads a failure the generic rules cannot, such as a host CLI's sign-in hint, from its stderr.
31 + * Null leaves it to them.
32 + */
33 + readonly classifyFailure?: (stderr: string) => VcsProcessExitFailureKind | null;
34 + /** The error's detail when the command reports something it was asked for as missing. */
35 + readonly notFoundDetail?: string;
36 + /**
37 + * Runs sharing a key run at most `limit` at a time, for a host that throttles bursts of its CLI.
38 + * The first run of a key fixes its limit.
39 + */
40 + readonly concurrency?: { readonly key: string; readonly limit: number };
41 }
42
43 export interface SourceControlProcessOutput {
packages/source-control-core/src/server/SourceControlProvider.ts
+19
@@ -142,6 +142,25 @@ export class SourceControlProvider extends Context.Service<
142 }) => Effect.Effect<SourceControlProviderContext | null, SourceControlProviderError>;
143 }) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
144 readonly resolveLink?: ResolveSourceControlLink;
145 + /**
146 + * Whether `createChangeRequest` from `cwd` targets `repository`, the `owner/name` of the
147 + * context's remote, for a host whose tools let configuration outside the remotes name another
148 + * repository. Absent means it does.
149 + */
150 + readonly createsChangeRequestsIn?: (input: {
151 + readonly cwd: string;
152 + readonly context: SourceControlProviderContext;
153 + readonly repository: string | null;
154 + }) => Effect.Effect<boolean>;
155 + /**
156 + * Told when T3 records `baseBranch`, a branch name on the host, as the base `branch` was cut
157 + * from, for a host whose own tools keep that in git config of their own.
158 + */
159 + readonly recordBranchBase?: (input: {
160 + readonly cwd: string;
161 + readonly branch: string;
162 + readonly baseBranch: string;
163 + }) => Effect.Effect<void>;
164 readonly listChangeRequests: (input: {
165 readonly cwd: string;
166 readonly context?: SourceControlProviderContext;
packages/source-control-forgejo/src/client/definition.ts
+4 -1
@@ -21,6 +21,8 @@ const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u;
21
22 const KIND = SourceControlProviderKind.make("forgejo");
23
24 +const changeRequestHeadRef = (number: number) => `refs/pull/${number}/head`;
25 +
26 /**
27 * The repository's browser URL the server resolved from the signed-in account, which is the
28 * only place a Forgejo mounted below a path says so.
@@ -77,7 +79,7 @@ export const definition = defineSourceControlClient({
79 // Neither `fj` nor `tea` checks out by number, so fetch the pull ref from the repository itself.
80 checkoutCommand: ({ number, repositoryUrl }) =>
81 repositoryUrl
80 - ? `git fetch '${repositoryUrl.replaceAll("'", "'\\''")}' refs/pull/${number}/head && git checkout -B pulls/${number} FETCH_HEAD`
82 + ? `git fetch '${repositoryUrl.replaceAll("'", "'\\''")}' ${changeRequestHeadRef(number)} && git checkout -B pulls/${number} FETCH_HEAD`
83 : null,
84 authorProfileUrl: () => null,
85 // Forgejo refuses a change request review without a summary, even with inline comments.
@@ -86,6 +88,7 @@ export const definition = defineSourceControlClient({
88 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
89 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
90 checkoutChangeRequestHost: () => null,
91 + changeRequestHeadRef,
92 recognizeRemote: ({ remoteUrl, host, hostname }) =>
93 hostname === "codeberg.org" ||
94 hostname.split(".").includes("forgejo") ||
packages/source-control-github/src/client/definition.ts
+1
@@ -121,6 +121,7 @@ export const definition = defineSourceControlClient({
121 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
122 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
123 checkoutChangeRequestHost: (identity) => projectChangeRequestHost(identity, KIND),
124 + changeRequestHeadRef: (number) => `refs/pull/${number}/head`,
125 // `*.ghe.com` is GitHub Enterprise Cloud with data residency, one subdomain per enterprise.
126 recognizeRemote: ({ host, hostname }) =>
127 hostname === "github.com" ||
packages/source-control-github/src/server/GitHubCredentials.ts
+7
@@ -19,6 +19,12 @@ import type { ServerSettings } from "@t3tools/contracts";
19
20 import * as GitHubClient from "../client/definition.ts";
21
22 +/**
23 + * Every gh run on the server shares this. A burst of them (a status poll across many checkouts)
24 + * otherwise starts enough at once to trip GitHub's secondary rate limit.
25 + */
26 +export const GH_PROCESS_CONCURRENCY = { key: "gh", limit: 4 } as const;
27 +
28 const TOKEN_TTL = Duration.minutes(5);
29 const MISSING_TTL = Duration.seconds(10);
30
@@ -146,6 +152,7 @@ export const make = Effect.gen(function* () {
152 // Never let gh print the token into a debug log.
153 env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },
154 timeoutMs: 10_000,
155 + concurrency: GH_PROCESS_CONCURRENCY,
156 })
157 .pipe(
158 Effect.mapError((error) =>
packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
+28
@@ -1051,3 +1051,31 @@ it.effect.each([
1051 );
1052 },
1053 );
1054 +
1055 +it.effect("says a GH_REPO naming an unparseable host targets no remote rather than failing", () => {
1056 + const { layer } = harness({
1057 + remotes: remotesOutput(["upstream", "git@github.com:acme/web.git"]),
1058 + resolved: "",
1059 + api: {},
1060 + });
1061 + return Effect.gen(function* () {
1062 + const provider = yield* GitHubSourceControlProvider.make;
1063 + const targets = yield* provider.createsChangeRequestsIn!({
1064 + cwd: "/repo",
1065 + context: {
1066 + provider: {
1067 + kind: SourceControlProviderKind.make("github"),
1068 + name: "GitHub",
1069 + baseUrl: "https://github.com",
1070 + },
1071 + remoteName: "upstream",
1072 + remoteUrl: "git@github.com:acme/web.git",
1073 + },
1074 + repository: "acme/web",
1075 + });
1076 + assert.isFalse(targets);
1077 + }).pipe(
1078 + Effect.provide(layer),
1079 + Effect.provideService(HostProcess.Environment, { GH_REPO: "bad host/acme/web" }),
1080 + );
1081 +});
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+53 -1
@@ -26,6 +26,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
26 import { decodeJsonResult } from "@t3tools/shared/schemaJson";
27 import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
28
29 +import { GH_PROCESS_CONCURRENCY } from "./GitHubCredentials.ts";
30 import * as GitHubRest from "./GitHubRest.ts";
31 import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
32 import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
@@ -235,7 +236,9 @@ export const makeDiscovery = Effect.gen(function* () {
236 );
237 const cli = yield* probeSourceControlProvider({
238 cwd,
238 - process,
239 + process: {
240 + run: (input) => process.run({ ...input, concurrency: GH_PROCESS_CONCURRENCY }),
241 + },
242 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
243 });
244 const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";
@@ -893,6 +896,55 @@ export const make = Effect.gen(function* () {
896 }),
897 readChangeRequestTemplate: ({ cwd, treeish }) =>
898 GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute),
899 + // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
900 + // the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a
901 + // non-default port in the context's host, and the mark is then ignored.
902 + createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
903 + function* ({ cwd, context, repository }) {
904 + const host = URL.canParse(context.provider.baseUrl)
905 + ? new URL(context.provider.baseUrl).host
906 + : null;
907 + const target = repository?.toLowerCase();
908 + const fromEnvironment = parseGitHubRepositorySelector(
909 + environment.GH_REPO ?? "",
910 + host ?? "",
911 + );
912 + if (fromEnvironment !== null) {
913 + const { host: targetHost, owner, name } = fromEnvironment;
914 + return (
915 + host !== null &&
916 + URL.canParse(`https://${targetHost}`) &&
917 + new URL(`https://${targetHost}`).host === host &&
918 + `${owner}/${name}`.toLowerCase() === target
919 + );
920 + }
921 + const mark = yield* git
922 + .readConfigValue(cwd, `remote.${context.remoteName}.gh-resolved`)
923 + .pipe(Effect.orElseSucceed(() => null));
924 + const { locator } = resolveGitHubRepository({
925 + remotes: `${context.remoteName}\t${context.remoteUrl} (fetch)`,
926 + resolved: mark === null ? "" : `remote.${context.remoteName}.gh-resolved ${mark}`,
927 + hostHint: host ?? undefined,
928 + defaultHost: host ?? "github.com",
929 + });
930 + return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
931 + },
932 + ),
933 + // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
934 + // from this key.
935 + recordBranchBase: ({ cwd, branch, baseBranch }) =>
936 + git
937 + .execute({
938 + operation: "GitHubSourceControlProvider.recordBranchBase",
939 + cwd,
940 + args: ["config", `branch.${branch}.gh-merge-base`, baseBranch],
941 + })
942 + .pipe(
943 + Effect.asVoid,
944 + Effect.catch((cause) =>
945 + Effect.logWarning("Could not record the branch base for gh", { cause }),
946 + ),
947 + ),
948 resolveLink: (input) => {
949 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
950 if (input.url.host !== "github.com") return undefined;
packages/source-control-github/src/server/gitHubPullRequests.test.ts new
+27
@@ -0,0 +1,27 @@
1 +import * as Result from "effect/Result";
2 +import { expect, it } from "vite-plus/test";
3 +
4 +import { decodeGitHubPullRequestListJson } from "./gitHubPullRequests.ts";
5 +
6 +// gh before 2.47 names the head repository without its owner, and a fork's checkout needs both.
7 +it("names a fork's head repository from its owner when gh leaves nameWithOwner out", () => {
8 + const decoded = decodeGitHubPullRequestListJson(
9 + JSON.stringify([
10 + {
11 + number: 642,
12 + title: "fix: use commit as the default git action without origin",
13 + url: "https://github.com/pingdotgg/t3code/pull/642",
14 + baseRefName: "main",
15 + headRefName: "fix/git-action-default-without-origin",
16 + isCrossRepository: true,
17 + headRepository: { id: "R_1", name: "t3code" },
18 + headRepositoryOwner: { login: "binbandit" },
19 + },
20 + ]),
21 + );
22 +
23 + expect(Result.getOrThrow(decoded)[0]).toMatchObject({
24 + headRepositoryNameWithOwner: "binbandit/t3code",
25 + headRepositoryOwnerLogin: "binbandit",
26 + });
27 +});
packages/source-control-gitlab/src/client/definition.ts
+1
@@ -52,6 +52,7 @@ export const definition = defineSourceControlClient({
52 checkoutCommandArgument: (input) => CHECKOUT_COMMAND.exec(input)?.[1]?.trim() ?? null,
53 isChangeRequestReference: (url) => CHANGE_REQUEST_REFERENCE.test(url),
54 checkoutChangeRequestHost: () => null,
55 + changeRequestHeadRef: (number) => `refs/merge-requests/${number}/head`,
56 recognizeRemote: ({ host, hostname }) =>
57 hostname === "gitlab.com" || hostname.split(".").includes("gitlab")
58 ? {
packages/source-control-gitlab/src/server/GitLabCli.ts
+11
@@ -11,6 +11,7 @@ import {
11 TrimmedNonEmptyString,
12 type SourceControlRepositoryVisibility,
13 type VcsError,
14 + type VcsProcessExitFailureKind,
15 } from "@t3tools/contracts";
16
17 import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
@@ -409,6 +410,14 @@ function parseRepositoryPath(repository: string): {
410 return { namespacePath, projectPath };
411 }
412
413 +// glab prints a missing project or merge request as a bare 404.
414 +const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null => {
415 + const normalized = stderr.toLowerCase();
416 + if (normalized.includes("glab auth login")) return "authentication";
417 + if (normalized.includes("not found") || normalized.includes("404")) return "not-found";
418 + return null;
419 +};
420 +
421 /** @public Service construction is part of the canonical Effect module API. */
422 export const make = Effect.gen(function* () {
423 const { process } = yield* SourceControlHost.SourceControlHost;
@@ -423,6 +432,8 @@ export const make = Effect.gen(function* () {
432 command: "glab",
433 args: input.args,
434 cwd: input.cwd,
435 + classifyFailure: classifyGlabFailure,
436 + notFoundDetail: "Merge request not found.",
437 timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
438 ...(input.stdin === undefined ? {} : { stdin: input.stdin }),
439 ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }),