From e276e6ac5b861ba3ba0f2ea3ab0f46a88462f420 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 05:27:36 +0000 Subject: [PATCH 1/4] test(server): remote branch names keep non-ASCII edge whitespace (#41226) Failing repro: creating a worktree from origin/release/v2 records the base as release/v2 because remoteRefs.ts trims with String.trim(). Co-Authored-By: Claude Opus 5.5 --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 65 +++++++++++--------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d64c0ec5cbb5b..4edf2592f642d 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -7444,37 +7444,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect.each(["release/v2", "origin/release/v2", "refs/remotes/origin/release/v2"])( - "records a remote-only PR base when creating a worktree from %s", - (baseRef) => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", "HEAD:refs/heads/release/v2"]); - const commit = yield* git(cwd, ["rev-parse", "origin/release/v2"]); - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.GitVcsDriver; - const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); - yield* driver.createWorktree({ - cwd, - path: worktreePath, - refName: commit, - newRefName: "feature/remote", - baseRefName: baseRef, - }); + it.effect.each([ + "release/v2", + "origin/release/v2", + "refs/remotes/origin/release/v2", + "origin/release/v2\u3000", + ])("records a remote-only PR base when creating a worktree from %s", (baseRef) => + Effect.gen(function* () { + const branch = baseRef.replace(/^(refs\/remotes\/)?origin\//, ""); + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `HEAD:refs/heads/${branch}`]); + const commit = yield* git(cwd, ["rev-parse", `origin/${branch}`]); + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: commit, + newRefName: "feature/remote", + baseRefName: baseRef, + }); - const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); - const comparisonBase = preview.sources.find( - (source) => source.kind === "branch-range", - )!.baseRef; - assert.equal( - yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), - commit, - ); - }), + assert.equal( + yield* driver.readConfigValue(cwd, "branch.feature/remote.t3-merge-base"), + branch, + ); + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; + assert.equal(yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), commit); + }), ); it("parses checkout progress lines from git's stderr", () => { From 6bee4b7b08445a502563c18f360a65f2a52689fe Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 05:43:27 +0000 Subject: [PATCH 2/4] fix(server): branch names keep leading and trailing Unicode whitespace Git allows U+00A0 and U+3000 at the edges of a branch name, but the server read ref names from git output with String.prototype.trim, which strips them. Worktree bases, upstream lookups, default-branch matching and PR branch matching then used a branch that does not exist. Ref names read from git are now trimmed of ASCII whitespace only, in the remote-ref parsers and in the driver and GitManager readers that feed them. Fixes #41226 Co-Authored-By: Claude Fable 5.2 --- apps/server/src/git/GitManager.ts | 10 ++-- apps/server/src/git/GitWorkflowService.ts | 3 +- apps/server/src/git/remoteRefs.ts | 24 +++++++-- apps/server/src/vcs/GitVcsDriverCore.test.ts | 46 ++++++++++------- apps/server/src/vcs/GitVcsDriverCore.ts | 53 +++++++++++--------- 5 files changed, 84 insertions(+), 52 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index dedf2d19f54ed..ecb16f854b2dd 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -84,7 +84,7 @@ import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.t import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import { createdPullRequestKey } from "./linkCreatedPullRequest.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; -import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts"; +import { extractBranchNameFromRemoteRef, trimAsciiWhitespace } from "./remoteRefs.ts"; import { detachStackFrame } from "./detachStackFrame.ts"; import * as ServerSettings from "../serverSettings.ts"; import type { GitManagerServiceError } from "@t3tools/contracts"; @@ -278,7 +278,7 @@ const prLookupGitReads = Context.Reference( function parseRemoteNames(stdout: string): ReadonlyArray { return stdout .split("\n") - .map((name) => name.trim()) + .map(trimAsciiWhitespace) .filter((name) => name.length > 0); } @@ -2012,7 +2012,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, })).stdout .split("\n") - .map((ref) => ref.trim()) + .map(trimAsciiWhitespace) .filter((ref) => ref.length > 0), ); const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`)); @@ -2049,7 +2049,7 @@ export const make = Effect.gen(function* () { const oidByRef = new Map( refs.stdout .split("\n") - .map((line) => line.trim().split("\u0000")) + .map((line) => trimAsciiWhitespace(line).split("\u0000")) .filter((entry): entry is [string, string] => entry.length === 2), ); const localOid = oidByRef.get(localRef); @@ -3354,7 +3354,7 @@ export const make = Effect.gen(function* () { const refNames = new Set( trackingRefs.stdout .split("\n") - .map((remoteRef) => remoteRef.trim()) + .map(trimAsciiWhitespace) .filter((remoteRef) => remoteRef.length > 0), ); return remoteNames diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 4cf3e62d9a93f..d19716a4ee95e 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -29,6 +29,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; +import { trimAsciiWhitespace } from "./remoteRefs.ts"; import * as GitManager from "./GitManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; @@ -365,7 +366,7 @@ export const make = Effect.gen(function* () { timeoutMs: 5_000, }); if (result.exitCode === 0) { - return result.stdout.trim().replace(/^refs\/heads\//, "") || null; + return trimAsciiWhitespace(result.stdout).replace(/^refs\/heads\//, "") || null; } if (result.exitCode === 1) return null; return yield* new GitCommandError({ diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts index e3873effe475e..9f5e760bd6fb4 100644 --- a/apps/server/src/git/remoteRefs.ts +++ b/apps/server/src/git/remoteRefs.ts @@ -1,7 +1,21 @@ +// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such +// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges. +export function trimAsciiWhitespace(value: string): string { + let start = 0; + let end = value.length; + while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++; + while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--; + return value.slice(start, end); +} + +function isAsciiWhitespace(code: number): boolean { + return code === 0x20 || (code >= 0x09 && code <= 0x0d); +} + export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { const remoteNames: Array = []; for (const line of stdout.split("\n")) { - const remoteName = line.trim(); + const remoteName = trimAsciiWhitespace(line); if (remoteName.length > 0) { remoteNames.push(remoteName); } @@ -17,7 +31,7 @@ export function parseRemoteRefWithRemoteNames( ref: string, remoteNames: ReadonlyArray, ): { remoteRef: string; remoteName: string; branchName: string } | null { - const trimmedRef = ref.trim(); + const trimmedRef = trimAsciiWhitespace(ref); if (trimmedRef.length === 0) { return null; } @@ -27,7 +41,7 @@ export function parseRemoteRefWithRemoteNames( if (!trimmedRef.startsWith(remotePrefix)) { continue; } - const branchName = trimmedRef.slice(remotePrefix.length).trim(); + const branchName = trimmedRef.slice(remotePrefix.length); if (branchName.length === 0) { return null; } @@ -48,7 +62,7 @@ export function extractBranchNameFromRemoteRef( remoteNames?: ReadonlyArray; }, ): string { - const normalized = ref.trim(); + const normalized = trimAsciiWhitespace(ref); if (normalized.length === 0) { return ""; } @@ -67,5 +81,5 @@ export function extractBranchNameFromRemoteRef( if (firstSlash === -1) { return normalized; } - return normalized.slice(firstSlash + 1).trim(); + return normalized.slice(firstSlash + 1); } diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 4edf2592f642d..b7125614c0ef7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6485,24 +6485,36 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("marks the origin default ref as default when no local copy exists", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["remote", "set-head", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/only-local"]); - yield* git(cwd, ["branch", "-D", initialBranch]); - const driver = yield* GitVcsDriver.GitVcsDriver; + it.effect.each(["trunk", "feature/memo\u3000", "\u00a0release"])( + "marks the origin default ref %s as default when no local copy exists", + (defaultBranch) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", defaultBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", defaultBranch]); + yield* git(cwd, ["remote", "set-head", "origin", defaultBranch]); + const driver = yield* GitVcsDriver.GitVcsDriver; - const refs = yield* driver.listRefs({ cwd }); - const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`); - assert.equal(remoteDefault?.isRemote, true); - assert.equal(remoteDefault?.isDefault, true); - }), + const localStatus = yield* driver.statusDetails(cwd); + const remoteStatus = yield* driver.statusDetailsRemote(cwd); + for (const status of [localStatus, remoteStatus]) { + assert.equal(status.branch, defaultBranch); + assert.equal(status.upstreamRef, `origin/${defaultBranch}`); + assert.isTrue(status.isDefaultBranch); + } + + yield* git(cwd, ["checkout", "-b", "feature/only-local"]); + yield* git(cwd, ["branch", "-D", defaultBranch]); + + const refs = yield* driver.listRefs({ cwd }); + const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${defaultBranch}`); + assert.equal(remoteDefault?.isRemote, true); + assert.equal(remoteDefault?.isDefault, true); + }), ); it.effect("preserves exact custom names and refuses collisions without a suffix", () => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 9ee53e4e90ac3..4515b6e8377cb 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -55,6 +55,7 @@ import { parseRemoteNames, parseRemoteNamesInGitOrder, parseRemoteRefWithRemoteNames, + trimAsciiWhitespace, } from "../git/remoteRefs.ts"; import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts"; import * as ServerConfig from "../config.ts"; @@ -452,8 +453,8 @@ function parseUpstreamRefByFirstSeparator( return null; } - const remoteName = upstreamRef.slice(0, separatorIndex).trim(); - const branchName = upstreamRef.slice(separatorIndex + 1).trim(); + const remoteName = upstreamRef.slice(0, separatorIndex); + const branchName = upstreamRef.slice(separatorIndex + 1); if (remoteName.length === 0 || branchName.length === 0) { return null; } @@ -467,13 +468,13 @@ function parseUpstreamRefByFirstSeparator( function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null { for (const line of stdout.split("\n")) { - const trimmedLine = line.trim(); + const trimmedLine = trimAsciiWhitespace(line); if (trimmedLine.length === 0) { continue; } const [branchNameRaw, upstreamBranchRaw = ""] = trimmedLine.split("\t"); - const branchName = branchNameRaw?.trim() ?? ""; - const candidateUpstreamRef = upstreamBranchRaw.trim(); + const branchName = branchNameRaw ?? ""; + const candidateUpstreamRef = upstreamBranchRaw; if (branchName.length === 0 || candidateUpstreamRef.length === 0) { continue; } @@ -490,7 +491,7 @@ function deriveLocalBranchNameFromRemoteRef(branchName: string): string | null { if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) { return null; } - const localBranch = branchName.slice(separatorIndex + 1).trim(); + const localBranch = branchName.slice(separatorIndex + 1); return localBranch.length > 0 ? localBranch : null; } @@ -592,19 +593,19 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null { // `--short` and `--abbrev-ref` print `heads/` when a tag shares the branch's name, so // branch reads take the full ref and strip the prefix themselves. function branchNameFromHeadRef(value: string): string | null { - const ref = value.trim(); + const ref = trimAsciiWhitespace(value); return ref.startsWith("refs/heads/") && ref.length > "refs/heads/".length ? ref.slice("refs/heads/".length) : null; } function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null { - const trimmed = value.trim(); + const trimmed = trimAsciiWhitespace(value); const prefix = `refs/remotes/${remoteName}/`; if (!trimmed.startsWith(prefix)) { return null; } - const refName = trimmed.slice(prefix.length).trim(); + const refName = trimmed.slice(prefix.length); return refName.length > 0 && refName !== "HEAD" ? refName : null; } @@ -1472,7 +1473,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--symbolic-full-name", "@{upstream}"], true, - ).pipe(Effect.map((stdout) => stdout.trim().replace(/^refs\/(?:remotes|heads)\//, ""))); + ).pipe( + Effect.map((stdout) => trimAsciiWhitespace(stdout).replace(/^refs\/(?:remotes|heads)\//, "")), + ); if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { return null; @@ -2056,7 +2059,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["symbolic-ref", "--quiet", "HEAD"], true, - ).pipe(Effect.map((stdout) => stdout.trim()))); + ).pipe(Effect.map(trimAsciiWhitespace))); if (headRef.length === 0) return undefined; const upstreamRemote = yield* executeGit( "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote", @@ -2065,7 +2068,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true }, ); if (upstreamRemote.exitCode !== 0) return undefined; - const remoteName = upstreamRemote.stdout.trim(); + const remoteName = trimAsciiWhitespace(upstreamRemote.stdout); // Empty means no upstream; `.` means the upstream is a local branch. if (remoteName.length === 0 || remoteName === ".") return remoteName; const gitCommonDir = yield* resolveGitCommonDir(cwd); @@ -2202,7 +2205,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", `branch.${refName}.pushRemote`], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); if (branchPushRemote.length > 0) { return branchPushRemote; } @@ -2212,7 +2215,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get", "remote.pushDefault"], true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ).pipe(Effect.map(trimAsciiWhitespace)); return pushDefaultRemote.length > 0 ? pushDefaultRemote : null; }); @@ -2351,7 +2354,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["rev-parse", "--symbolic-full-name", `${refName}@{upstream}`], { allowNonZeroExit: true }, ); - const comparisonRef = upstream.stdout.trim(); + const comparisonRef = trimAsciiWhitespace(upstream.stdout); if (upstream.exitCode !== 0 || !comparisonRef.startsWith("refs/remotes/")) return null; return { baseRef: comparisonRef.slice("refs/remotes/".length), comparisonRef }; }); @@ -2665,7 +2668,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* headRef = ""; } else { branch = branchNameFromHeadRef(branchResult.stdout); - headRef = branchResult.stdout.trim(); + headRef = trimAsciiWhitespace(branchResult.stdout); } let upstreamRemoteName: string | undefined; if (refreshUpstream) { @@ -2945,13 +2948,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* continue; } if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.head ".length)); // `(unknown)` is printed while HEAD names no resolvable branch, e.g. mid-`git clone`. refName = value === "(detached)" || value === "(unknown)" ? null : value; continue; } if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); + const value = trimAsciiWhitespace(line.slice("# branch.upstream ".length)); upstreamRef = value.length > 0 ? value : null; continue; } @@ -4031,7 +4034,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["config", "--get-all", `branch.${refName}.merge`], true, - ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))), + ).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout).split("\n").filter(Boolean))), runGitStdout( "GitVcsDriver.pullCurrentBranch.currentBranch", cwd, @@ -5233,7 +5236,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const readConfigValue: GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"] = (cwd, key) => runGitStdout("GitVcsDriver.readConfigValue", cwd, ["config", "--get", key], true).pipe( - Effect.map((stdout) => stdout.trim()), + Effect.map(trimAsciiWhitespace), Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); @@ -5279,7 +5282,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.cwd, ["rev-parse", "--symbolic-full-name", startPoint], { allowNonZeroExit: true }, - ).pipe(Effect.map((result) => (result.exitCode === 0 ? result.stdout.trim() : ""))); + ).pipe( + Effect.map((result) => (result.exitCode === 0 ? trimAsciiWhitespace(result.stdout) : "")), + ); if (!startRef.startsWith("refs/remotes/")) return; yield* executeGitWithStableDiagnostics( `${operation}.track`, @@ -5326,7 +5331,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName } : null; } - const ref = result.stdout.trim(); + const ref = trimAsciiWhitespace(result.stdout); if (ref.startsWith("refs/heads/")) { const branchName = ref.slice("refs/heads/".length); return { baseRef: ref, branchName }; @@ -6897,7 +6902,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [ "branch", "--show-current", - ]).pipe(Effect.map((stdout) => stdout.trim() || null)); + ]).pipe(Effect.map((stdout) => trimAsciiWhitespace(stdout) || null)); return { refName }; }, @@ -6937,7 +6942,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((stdout) => { const branchNames: Array = []; for (const line of stdout.split("\n")) { - const branchName = line.trim(); + const branchName = trimAsciiWhitespace(line); if (branchName.length > 0) { branchNames.push(branchName); } From c4b9f378c14d9392c421f2c2865daa81e14d2f93 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:02:29 +0000 Subject: [PATCH 3/4] fix(contracts): branch names keep Unicode whitespace across the wire Branch, ref and remote name fields used TrimmedNonEmptyString, whose encode and decode call String.prototype.trim and so strip U+00A0 and U+3000 that Git allows at a name's edges. Clients received and sent a truncated name. Those fields now use GitRefName, which trims ASCII whitespace only. The server's trimAsciiWhitespace helper moves to contracts so both share it. Refs #41226 Co-Authored-By: Claude Fable 5.2 --- apps/server/src/git/GitManager.ts | 8 +++- apps/server/src/git/GitWorkflowService.ts | 2 +- apps/server/src/git/remoteRefs.ts | 14 +----- apps/server/src/vcs/GitVcsDriverCore.ts | 2 +- packages/contracts/src/baseSchemas.ts | 33 +++++++++++++ packages/contracts/src/git.test.ts | 28 +++++++++++ packages/contracts/src/git.ts | 51 +++++++++++---------- packages/contracts/src/orchestrationV2.ts | 21 +++++---- packages/contracts/src/pullRequest.ts | 15 +++--- packages/contracts/src/review.ts | 14 +++--- packages/contracts/src/sourceControl.ts | 8 ++-- packages/contracts/src/threadPullRequest.ts | 7 +-- packages/contracts/src/worktreeMcp.ts | 10 ++-- packages/contracts/src/worktreeSetup.ts | 12 +++-- 14 files changed, 144 insertions(+), 81 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index ecb16f854b2dd..4b23f8cd6c66f 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -66,7 +66,11 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; -import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts"; +import { + GitManagerError, + GitPullRequestMaterializationError, + trimAsciiWhitespace, +} from "@t3tools/contracts"; import { historicalMessage, renderHistory, @@ -84,7 +88,7 @@ import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.t import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import { createdPullRequestKey } from "./linkCreatedPullRequest.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; -import { extractBranchNameFromRemoteRef, trimAsciiWhitespace } from "./remoteRefs.ts"; +import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts"; import { detachStackFrame } from "./detachStackFrame.ts"; import * as ServerSettings from "../serverSettings.ts"; import type { GitManagerServiceError } from "@t3tools/contracts"; diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index d19716a4ee95e..ca7c0b03c13d4 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -29,7 +29,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; -import { trimAsciiWhitespace } from "./remoteRefs.ts"; +import { trimAsciiWhitespace } from "@t3tools/contracts"; import * as GitManager from "./GitManager.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; diff --git a/apps/server/src/git/remoteRefs.ts b/apps/server/src/git/remoteRefs.ts index 9f5e760bd6fb4..c5be08c165676 100644 --- a/apps/server/src/git/remoteRefs.ts +++ b/apps/server/src/git/remoteRefs.ts @@ -1,16 +1,4 @@ -// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such -// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges. -export function trimAsciiWhitespace(value: string): string { - let start = 0; - let end = value.length; - while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++; - while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--; - return value.slice(start, end); -} - -function isAsciiWhitespace(code: number): boolean { - return code === 0x20 || (code >= 0x09 && code <= 0x0d); -} +import { trimAsciiWhitespace } from "@t3tools/contracts"; export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray { const remoteNames: Array = []; diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 4515b6e8377cb..4981ece0979e4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -34,6 +34,7 @@ import { type ReviewDiffPreviewInput, type ReviewDiffFileStat, type ReviewDiffPreviewSource, + trimAsciiWhitespace, type VcsRef, } from "@t3tools/contracts"; import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; @@ -55,7 +56,6 @@ import { parseRemoteNames, parseRemoteNamesInGitOrder, parseRemoteRefWithRemoteNames, - trimAsciiWhitespace, } from "../git/remoteRefs.ts"; import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts"; import * as ServerConfig from "../config.ts"; diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index d8137fc8ca9ec..be27f15c58753 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -28,6 +28,39 @@ const isNonBlank = Schema.makeFilter((value: string) => value.trim().length > 0, }); export const TrimmedNonEmptyString = TrimmedString.check(isNonBlank); +// Git forbids ASCII space and control characters in ref names but allows Unicode whitespace such +// as U+00A0 and U+3000, which `String.prototype.trim` would strip from a name's edges. +export function trimAsciiWhitespace(value: string): string { + let start = 0; + let end = value.length; + while (start < end && isAsciiWhitespace(value.charCodeAt(start))) start++; + while (end > start && isAsciiWhitespace(value.charCodeAt(end - 1))) end--; + return end - start === value.length ? value : value.slice(start, end); +} + +function isAsciiWhitespace(code: number): boolean { + return code === 0x20 || (code >= 0x09 && code <= 0x0d); +} + +const isNonBlankGitRefName = Schema.makeFilter( + (value: string) => trimAsciiWhitespace(value).length > 0, + { + expected: "a non-blank string", + toJsonSchema: () => [{ minLength: 1 }, true], + arbitraryConstraint: { minLength: 1 }, + }, +); +/** A branch, ref or remote name. Unlike `TrimmedNonEmptyString`, it keeps Unicode whitespace. */ +export const GitRefName = Schema.String.pipe( + Schema.decodeTo( + Schema.String, + SchemaTransformation.transformEffect({ + decode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + encode: (value) => Effect.succeed(trimAsciiWhitespace(value)), + }), + ), +).check(isNonBlankGitRefName); + export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); export const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.ts index ae7b260c368f9..c0fdf7d312189 100644 --- a/packages/contracts/src/git.test.ts +++ b/packages/contracts/src/git.test.ts @@ -5,10 +5,16 @@ import { GitCommandError, GitPreparePullRequestThreadResult, GitRunStackedActionInput, + VcsCreateWorktreeInput, + VcsRef, } from "./git.ts"; import { PullRequestDiffFileContentsInput } from "./pullRequest.ts"; import { ReviewDiffFileContentsInput } from "./review.ts"; +const encodeVcsRef = Schema.encodeUnknownSync(VcsRef); +const decodeVcsRef = Schema.decodeUnknownSync(VcsRef); +const encodeCreateWorktreeInput = Schema.encodeUnknownSync(VcsCreateWorktreeInput); +const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput); const decodeGitCommandError = Schema.decodeUnknownSync(Schema.toCodecJson(GitCommandError)); const decodePreparePullRequestThreadResult = Schema.decodeUnknownSync( GitPreparePullRequestThreadResult, @@ -106,3 +112,25 @@ describe("Git file paths", () => { expect(encode(input)).toEqual(input); }); }); + +describe("Git ref names", () => { + it.each(["origin/release/v2\u3000", "\u00a0release", "\u3000"])( + "keeps Unicode whitespace at the edges of %j across the wire", + (name) => { + const ref = { name, upstreamRef: `refs/remotes/${name}`, current: false, isDefault: false }; + const wireRef = encodeVcsRef({ ...ref, worktreePath: null }); + expect(decodeVcsRef(wireRef)).toMatchObject(ref); + + const input = { cwd: "/repo", refName: name, newRefName: name, baseRefName: name }; + const wireInput = encodeCreateWorktreeInput({ ...input, path: null }); + expect(decodeCreateWorktreeInput(wireInput)).toMatchObject(input); + }, + ); + + it("still trims ASCII whitespace and rejects a blank name", () => { + expect( + decodeCreateWorktreeInput({ cwd: "/repo", refName: " \tmain\n", path: null }).refName, + ).toBe("main"); + expect(() => decodeCreateWorktreeInput({ cwd: "/repo", refName: " \t", path: null })).toThrow(); + }); +}); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index 751f240f0709e..e99c33c1e16b6 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -1,6 +1,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + GitRefName, ForwardCompatibleOptional, NonNegativeInt, PositiveInt, @@ -81,11 +82,11 @@ const GitRunStackedActionToast = Schema.Struct({ export type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type; export const VcsRef = Schema.Struct({ - name: TrimmedNonEmptyStringSchema, + name: GitRefName, isRemote: Schema.optional(Schema.Boolean), - remoteName: Schema.optional(TrimmedNonEmptyStringSchema), + remoteName: Schema.optional(GitRefName), // Full Git ref, for example refs/remotes/origin/feature. - upstreamRef: Schema.optional(TrimmedNonEmptyStringSchema), + upstreamRef: Schema.optional(GitRefName), current: Schema.Boolean, isDefault: Schema.Boolean, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), @@ -94,14 +95,14 @@ export type VcsRef = typeof VcsRef.Type; const VcsWorktree = Schema.Struct({ path: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); const GitResolvedPullRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseBranch: TrimmedNonEmptyStringSchema, - headBranch: TrimmedNonEmptyStringSchema, + baseBranch: GitRefName, + headBranch: GitRefName, state: GitPullRequestState, }); export type GitResolvedPullRequest = typeof GitResolvedPullRequest.Type; @@ -157,9 +158,9 @@ export type VcsListRefsInput = typeof VcsListRefsInput.Type; export const VcsCreateWorktreeInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, - newRefName: Schema.optional(TrimmedNonEmptyStringSchema), - baseRefName: Schema.optional(TrimmedNonEmptyStringSchema), + refName: GitRefName, + newRefName: Schema.optional(GitRefName), + baseRefName: Schema.optional(GitRefName), path: Schema.NullOr(TrimmedNonEmptyStringSchema), }); export type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type; @@ -187,19 +188,19 @@ export type VcsRemoveWorktreeInput = typeof VcsRemoveWorktreeInput.Type; export const VcsCreateRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, switchRef: Schema.optional(Schema.Boolean), }); export type VcsCreateRefInput = typeof VcsCreateRefInput.Type; export const VcsCreateRefResult = Schema.Struct({ - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsCreateRefResult = typeof VcsCreateRefResult.Type; export const VcsSwitchRefInput = Schema.Struct({ cwd: TrimmedNonEmptyStringSchema, - refName: TrimmedNonEmptyStringSchema, + refName: GitRefName, }); export type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type; @@ -213,8 +214,8 @@ const VcsStatusChangeRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyStringSchema, url: Schema.String, - baseRef: TrimmedNonEmptyStringSchema, - headRef: TrimmedNonEmptyStringSchema, + baseRef: GitRefName, + headRef: GitRefName, state: VcsStatusChangeRequestState, isDraft: Schema.optional(Schema.Boolean), updatedAt: Schema.optional(Schema.NullOr(Schema.String)), @@ -225,7 +226,7 @@ const VcsStatusLocalShape = { sourceControlProvider: Schema.optional(SourceControlProviderInfo), hasPrimaryRemote: Schema.Boolean, isDefaultRef: Schema.Boolean, - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), hasWorkingTreeChanges: Schema.Boolean, workingTree: Schema.Struct({ // Absolute worktree root on the environment that every files[].path is @@ -243,7 +244,7 @@ const VcsStatusLocalShape = { }), branchChanges: Schema.optional( Schema.Struct({ - baseRef: Schema.NullOr(TrimmedNonEmptyStringSchema), + baseRef: Schema.NullOr(GitRefName), insertions: NonNegativeInt, deletions: NonNegativeInt, }), @@ -313,7 +314,7 @@ export type GitResolvePullRequestResult = typeof GitResolvePullRequestResult.Typ export const GitPreparePullRequestThreadResult = Schema.Struct({ pullRequest: GitResolvedPullRequest, - branch: TrimmedNonEmptyStringSchema, + branch: GitRefName, worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), /** False when local commits or edits prevented a reused worktree from reaching the PR head. */ isOnPullRequestHead: Schema.Boolean.pipe(Schema.withDecodingDefaultKey(Effect.succeed(true))), @@ -321,7 +322,7 @@ export const GitPreparePullRequestThreadResult = Schema.Struct({ export type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type; export const VcsSwitchRefResult = Schema.Struct({ - refName: Schema.NullOr(TrimmedNonEmptyStringSchema), + refName: Schema.NullOr(GitRefName), }); export type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type; @@ -329,7 +330,7 @@ export const GitRunStackedActionResult = Schema.Struct({ action: GitStackedAction, branch: Schema.Struct({ status: GitBranchStepStatus, - name: Schema.optional(TrimmedNonEmptyStringSchema), + name: Schema.optional(GitRefName), }), commit: Schema.Struct({ status: GitCommitStepStatus, @@ -338,16 +339,16 @@ export const GitRunStackedActionResult = Schema.Struct({ }), push: Schema.Struct({ status: GitPushStepStatus, - branch: Schema.optional(TrimmedNonEmptyStringSchema), - upstreamBranch: Schema.optional(TrimmedNonEmptyStringSchema), + branch: Schema.optional(GitRefName), + upstreamBranch: Schema.optional(GitRefName), setUpstream: Schema.optional(Schema.Boolean), }), pr: Schema.Struct({ status: GitPrStepStatus, url: Schema.optional(Schema.String), number: Schema.optional(PositiveInt), - baseBranch: Schema.optional(TrimmedNonEmptyStringSchema), - headBranch: Schema.optional(TrimmedNonEmptyStringSchema), + baseBranch: Schema.optional(GitRefName), + headBranch: Schema.optional(GitRefName), title: Schema.optional(TrimmedNonEmptyStringSchema), }), toast: GitRunStackedActionToast, @@ -356,8 +357,8 @@ export type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type; export const VcsPullResult = Schema.Struct({ status: Schema.Literals(["pulled", "skipped_up_to_date"]), - refName: TrimmedNonEmptyStringSchema, - upstreamRef: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr), + refName: GitRefName, + upstreamRef: GitRefName.pipe(Schema.NullOr), }); export type VcsPullResult = typeof VcsPullResult.Type; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 33961fcf8b82b..cca241ddb33b7 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -13,6 +13,7 @@ import { AgentFeedbackTrace, } from "./agentFeedback.ts"; import { + GitRefName, CheckpointId, CheckpointRef, CheckpointScopeId, @@ -505,7 +506,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, - branch: Schema.NullOr(TrimmedNonEmptyString), + branch: Schema.NullOr(GitRefName), worktreePath: Schema.NullOr(TrimmedNonEmptyString), linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)), @@ -781,17 +782,17 @@ export type OrchestrationV2RunBackgroundWorkCancelled = export const OrchestrationV2ThreadLaunchWorkspaceStrategy = Schema.Union([ Schema.Struct({ type: Schema.Literal("root"), - branch: Schema.optional(TrimmedNonEmptyString), + branch: Schema.optional(GitRefName), }), Schema.Struct({ type: Schema.Literal("existing_worktree"), worktreePath: TrimmedNonEmptyString, - branch: Schema.optional(TrimmedNonEmptyString), + branch: Schema.optional(GitRefName), }), Schema.Struct({ type: Schema.Literal("worktree"), - baseRef: TrimmedNonEmptyString, - branch: Schema.optional(TrimmedNonEmptyString), + baseRef: GitRefName, + branch: Schema.optional(GitRefName), startFromOrigin: Schema.optional(Schema.Boolean), repositories: Schema.optional( Schema.Array(Schema.Struct({ path: TrimmedNonEmptyString })) @@ -2394,7 +2395,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, - branch: Schema.NullOr(TrimmedNonEmptyString), + branch: Schema.NullOr(GitRefName), worktreePath: Schema.NullOr(TrimmedNonEmptyString), linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), pullRequests: Schema.optional(Schema.Array(ThreadPullRequestLink)), @@ -3303,7 +3304,7 @@ export const OrchestrationV2Command = Schema.Union([ modelSelection: ModelSelection, runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, - branch: Schema.NullOr(TrimmedNonEmptyString), + branch: Schema.NullOr(GitRefName), worktreePath: Schema.NullOr(TrimmedNonEmptyString), /** Only the server sets this; a client's thread.create never carries one. */ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), @@ -3459,10 +3460,10 @@ export const OrchestrationV2Command = Schema.Union([ threadId: ThreadId, title: Schema.optional(TrimmedNonEmptyString), regenerateTitle: Schema.optional(Schema.Boolean), - branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + branch: Schema.optional(Schema.NullOr(GitRefName)), worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), expectedWorktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), - expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), + expectedBranch: Schema.optional(Schema.NullOr(GitRefName)), /** A message queued in the same commit, so a workspace change cannot settle the thread first. */ continuation: Schema.optional(Schema.Struct({ messageId: MessageId, text: Schema.String })), /** Reject unless no message or run has landed on this thread. */ @@ -3537,7 +3538,7 @@ export const OrchestrationV2Command = Schema.Union([ snapshotSequence: NonNegativeInt, expected: Schema.Struct({ workspaceRoot: TrimmedNonEmptyString, - branch: Schema.NullOr(TrimmedNonEmptyString), + branch: Schema.NullOr(GitRefName), worktreePath: Schema.NullOr(TrimmedNonEmptyString), linkedPullRequest: Schema.NullOr(ThreadLinkedPullRequest), branchPullRequest: Schema.NullOr(ThreadLinkedPullRequest), diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 0bb2858c107cf..20b2c8968c06c 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -4,6 +4,7 @@ import * as HttpServerRespondable from "effect/http/HttpServerRespondable"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; import { + GitRefName, ForwardCompatibleArray, IsoDateTime, NonNegativeInt, @@ -371,8 +372,8 @@ export const PullRequestListEntry = Schema.Struct({ title: TrimmedNonEmptyString, url: TrimmedNonEmptyString, author: Schema.NullOr(PullRequestActor), - headBranch: TrimmedNonEmptyString, - baseBranch: TrimmedNonEmptyString, + headBranch: GitRefName, + baseBranch: GitRefName, state: PullRequestState, isDraft: Schema.Boolean, mergeability: PullRequestMergeability, @@ -524,8 +525,8 @@ export const PullRequestSummary = Schema.Struct({ url: TrimmedNonEmptyString, state: PullRequestState, isDraft: Schema.optional(Schema.Boolean), - headBranch: TrimmedNonEmptyString, - baseBranch: TrimmedNonEmptyString, + headBranch: GitRefName, + baseBranch: GitRefName, closedAt: Schema.optional(Schema.NullOr(Schema.String)), mergedAt: Schema.optional(Schema.NullOr(Schema.String)), updatedAt: IsoDateTime, @@ -558,7 +559,7 @@ export const PullRequestStack = Schema.Struct({ title: Schema.optional(Schema.String), isDraft: Schema.optional(Schema.Boolean), headSha: Schema.optional(TrimmedNonEmptyString), - headBranch: TrimmedNonEmptyString, + headBranch: GitRefName, state: PullRequestState, }), ), @@ -665,10 +666,10 @@ export const PullRequestDetail = Schema.Struct({ additions: NonNegativeInt, deletions: NonNegativeInt, changedFiles: NonNegativeInt, - headBranch: TrimmedNonEmptyString, + headBranch: GitRefName, headRepositoryNameWithOwner: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), headSha: Schema.optional(TrimmedNonEmptyString), - baseBranch: TrimmedNonEmptyString, + baseBranch: GitRefName, createdAt: IsoDateTime, updatedAt: IsoDateTime, observedAt: Schema.optional(Schema.Finite), diff --git a/packages/contracts/src/review.ts b/packages/contracts/src/review.ts index d43946e217219..12292511c3a0a 100644 --- a/packages/contracts/src/review.ts +++ b/packages/contracts/src/review.ts @@ -1,5 +1,5 @@ import * as Schema from "effect/Schema"; -import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { GitRefName, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { GitCommandError } from "./git.ts"; import { VcsError } from "./vcs.ts"; @@ -19,7 +19,7 @@ export type ReviewDiffChangeType = typeof ReviewDiffChangeType.Type; export const ReviewDiffPreviewInput = Schema.Struct({ cwd: TrimmedNonEmptyString, - baseRef: Schema.optional(TrimmedNonEmptyString), + baseRef: Schema.optional(GitRefName), // A branch-range file read reuses its preview's merge base instead of resolving it again. mergeBase: Schema.optionalKey(ReviewMergeBase), commitSha: Schema.optional(TrimmedNonEmptyString), @@ -43,7 +43,7 @@ export type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type; export const ReviewBranchCommitsInput = Schema.Struct({ cwd: TrimmedNonEmptyString, - baseRef: Schema.optional(TrimmedNonEmptyString), + baseRef: Schema.optional(GitRefName), }); export type ReviewBranchCommitsInput = typeof ReviewBranchCommitsInput.Type; @@ -81,8 +81,8 @@ export const ReviewDiffPreviewSource = Schema.Struct({ kind: ReviewDiffPreviewSourceKind, title: TrimmedNonEmptyString, commitSubject: Schema.optionalKey(TrimmedNonEmptyString), - baseRef: Schema.NullOr(TrimmedNonEmptyString), - headRef: Schema.NullOr(TrimmedNonEmptyString), + baseRef: Schema.NullOr(GitRefName), + headRef: Schema.NullOr(GitRefName), // Branch-range only; older servers omit it. mergeBase: Schema.optionalKey(ReviewMergeBase), diff: Schema.String, @@ -97,8 +97,8 @@ export const ReviewDiffFileContentsInput = Schema.Struct({ cwd: TrimmedNonEmptyString, sourceKind: ReviewDiffPreviewSourceKind, changeType: ReviewDiffChangeType, - baseRef: Schema.NullOr(TrimmedNonEmptyString), - headRef: Schema.NullOr(TrimmedNonEmptyString), + baseRef: Schema.NullOr(GitRefName), + headRef: Schema.NullOr(GitRefName), oldPath: Schema.NonEmptyString, newPath: Schema.NonEmptyString, }); diff --git a/packages/contracts/src/sourceControl.ts b/packages/contracts/src/sourceControl.ts index 3138c3985a4aa..201802d03cb20 100644 --- a/packages/contracts/src/sourceControl.ts +++ b/packages/contracts/src/sourceControl.ts @@ -1,5 +1,5 @@ import * as Schema from "effect/Schema"; -import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { GitRefName, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { VcsDriverKind } from "./vcs.ts"; /** Accept unknown hosts so clients can fall back to generic presentation. */ @@ -24,8 +24,8 @@ export const ChangeRequest = Schema.Struct({ number: PositiveInt, title: TrimmedNonEmptyString, url: Schema.String, - baseRefName: TrimmedNonEmptyString, - headRefName: TrimmedNonEmptyString, + baseRefName: GitRefName, + headRefName: GitRefName, headSha: Schema.optional(TrimmedNonEmptyString), state: ChangeRequestState, isDraft: Schema.optional(Schema.Boolean), @@ -99,7 +99,7 @@ export const SourceControlPublishRepositoryResult = Schema.Struct({ repository: SourceControlRepositoryInfo, remoteName: TrimmedNonEmptyString, remoteUrl: TrimmedNonEmptyString, - branch: TrimmedNonEmptyString, + branch: GitRefName, status: SourceControlPublishStatus, }); export type SourceControlPublishRepositoryResult = typeof SourceControlPublishRepositoryResult.Type; diff --git a/packages/contracts/src/threadPullRequest.ts b/packages/contracts/src/threadPullRequest.ts index 67ffe72a41de8..e97fdc790745a 100644 --- a/packages/contracts/src/threadPullRequest.ts +++ b/packages/contracts/src/threadPullRequest.ts @@ -2,6 +2,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { + GitRefName, IsoDateTime, NonNegativeInt, PositiveInt, @@ -37,8 +38,8 @@ export type ThreadPullRequestLinkSource = typeof ThreadPullRequestLinkSource.Typ export const ThreadPullRequestSnapshot = Schema.Struct({ state: PullRequestState, title: TrimmedNonEmptyString, - headBranch: TrimmedNonEmptyString, - baseBranch: TrimmedNonEmptyString, + headBranch: GitRefName, + baseBranch: GitRefName, isDraft: Schema.Boolean, updatedAt: Schema.NullOr(IsoDateTime), syncedAt: IsoDateTime, @@ -57,7 +58,7 @@ export type ThreadPullRequestSnapshot = typeof ThreadPullRequestSnapshot.Type; export const ThreadPullRequestStackLayer = Schema.Struct({ number: PositiveInt, - headBranch: TrimmedNonEmptyString, + headBranch: GitRefName, state: PullRequestState, }); export type ThreadPullRequestStackLayer = typeof ThreadPullRequestStackLayer.Type; diff --git a/packages/contracts/src/worktreeMcp.ts b/packages/contracts/src/worktreeMcp.ts index 87f45dea27598..3b5a63f30c700 100644 --- a/packages/contracts/src/worktreeMcp.ts +++ b/packages/contracts/src/worktreeMcp.ts @@ -1,10 +1,10 @@ import * as Schema from "effect/Schema"; -import { TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { GitRefName, TrimmedNonEmptyString } from "./baseSchemas.ts"; /** Uses the managed worktree folder; handoff detaches the provider, ending this turn and resuming there next run. */ export const WorktreeMcpHandoffInput = Schema.Struct({ - branch: TrimmedNonEmptyString, + branch: GitRefName, baseRef: Schema.optional( TrimmedNonEmptyString.annotate({ description: "Default: checked-out branch.", @@ -65,8 +65,8 @@ export type WorktreeMcpContinuationStatus = typeof WorktreeMcpContinuationStatus export const WorktreeMcpHandoffResult = Schema.Struct({ worktreePath: TrimmedNonEmptyString, - branch: TrimmedNonEmptyString, - baseRef: TrimmedNonEmptyString, + branch: GitRefName, + baseRef: GitRefName, startedFromOrigin: Schema.Boolean, setupScript: WorktreeMcpSetupScriptStatus, continuation: WorktreeMcpContinuationStatus, @@ -77,7 +77,7 @@ export type WorktreeMcpHandoffResult = typeof WorktreeMcpHandoffResult.Type; export const WorktreeMcpStatusResult = Schema.Struct({ attached: Schema.Boolean, worktreePath: Schema.NullOr(TrimmedNonEmptyString), - branch: Schema.NullOr(TrimmedNonEmptyString), + branch: Schema.NullOr(GitRefName), projectWorkspaceRoot: TrimmedNonEmptyString, defaultStartFromOrigin: Schema.Boolean.annotate({ description: "`startFromOrigin` default for `t3_worktree_handoff`.", diff --git a/packages/contracts/src/worktreeSetup.ts b/packages/contracts/src/worktreeSetup.ts index e9b64e4c909e4..d6ecdea0251f9 100644 --- a/packages/contracts/src/worktreeSetup.ts +++ b/packages/contracts/src/worktreeSetup.ts @@ -1,6 +1,12 @@ import * as Schema from "effect/Schema"; -import { IsoDateTime, NonNegativeInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { + GitRefName, + IsoDateTime, + NonNegativeInt, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; /** Producers clamp free text to these before publishing so encoding never fails. */ export const WORKTREE_SETUP_DETAIL_MAX_LENGTH = 200; @@ -45,8 +51,8 @@ export const WorktreeSetupSnapshot = Schema.Struct({ phase: WorktreeSetupPhase, startedAt: IsoDateTime, endedAt: Schema.NullOr(IsoDateTime), - branch: Schema.NullOr(TrimmedNonEmptyString), - baseRef: Schema.NullOr(TrimmedNonEmptyString), + branch: Schema.NullOr(GitRefName), + baseRef: Schema.NullOr(GitRefName), worktreePath: Schema.NullOr(TrimmedNonEmptyString), setupScript: Schema.NullOr( Schema.Struct({ From 2a235bb8ad48a3e602f7e953c0ebed929224dfc8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 06:14:41 +0000 Subject: [PATCH 4/4] fix(contracts): worktree handoff base ref keeps Unicode whitespace WorktreeMcpHandoffInput.baseRef still used TrimmedNonEmptyString, so an agent starting a worktree from origin/ with U+00A0 or U+3000 at the name's edge fetched a branch that does not exist. It now uses GitRefName, as do the remaining branch fields: the pull request stack base and the head and local branch of GitPullRequestMaterializationError. Refs #41226 Co-Authored-By: Claude Fable 5.2 --- packages/contracts/src/git.test.ts | 5 +++++ packages/contracts/src/git.ts | 4 ++-- packages/contracts/src/pullRequest.ts | 4 ++-- packages/contracts/src/threadPullRequest.ts | 2 +- packages/contracts/src/worktreeMcp.ts | 2 +- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/contracts/src/git.test.ts b/packages/contracts/src/git.test.ts index c0fdf7d312189..8802b445e53ac 100644 --- a/packages/contracts/src/git.test.ts +++ b/packages/contracts/src/git.test.ts @@ -8,6 +8,7 @@ import { VcsCreateWorktreeInput, VcsRef, } from "./git.ts"; +import { WorktreeMcpHandoffInput } from "./worktreeMcp.ts"; import { PullRequestDiffFileContentsInput } from "./pullRequest.ts"; import { ReviewDiffFileContentsInput } from "./review.ts"; @@ -15,6 +16,7 @@ const encodeVcsRef = Schema.encodeUnknownSync(VcsRef); const decodeVcsRef = Schema.decodeUnknownSync(VcsRef); const encodeCreateWorktreeInput = Schema.encodeUnknownSync(VcsCreateWorktreeInput); const decodeCreateWorktreeInput = Schema.decodeUnknownSync(VcsCreateWorktreeInput); +const decodeWorktreeHandoffInput = Schema.decodeUnknownSync(WorktreeMcpHandoffInput); const decodeGitCommandError = Schema.decodeUnknownSync(Schema.toCodecJson(GitCommandError)); const decodePreparePullRequestThreadResult = Schema.decodeUnknownSync( GitPreparePullRequestThreadResult, @@ -124,6 +126,9 @@ describe("Git ref names", () => { const input = { cwd: "/repo", refName: name, newRefName: name, baseRefName: name }; const wireInput = encodeCreateWorktreeInput({ ...input, path: null }); expect(decodeCreateWorktreeInput(wireInput)).toMatchObject(input); + + const handoff = { branch: name, baseRef: name, startFromOrigin: true }; + expect(decodeWorktreeHandoffInput(handoff)).toEqual(handoff); }, ); diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts index e99c33c1e16b6..2faf0ffb8c248 100644 --- a/packages/contracts/src/git.ts +++ b/packages/contracts/src/git.ts @@ -431,8 +431,8 @@ export class GitPullRequestMaterializationError extends Schema.TaggedError