fix: match slashed branch names in worktree branch search (#5687)

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: brennanb2025 <brennankbenson@gmail.com>
This commit is contained in:
Trevin Chow
2026-06-18 14:57:10 -07:00
committed by GitHub
co-authored by Cursor brennanb2025
parent 1652f8ede1
commit 6d0b5734e7
5 changed files with 310 additions and 58 deletions
+108
View File
@@ -64,6 +64,32 @@ describe('buildSearchBaseRefsArgv', () => {
expect(argv).toContain('--count=40')
expect(argv).toContain('refs/remotes/*upstream*/*main*')
expect(argv).toContain('refs/heads/*upstream*/*main*')
expect(argv).toContain('refs/remotes/*/upstream/main*')
expect(argv).toContain('refs/heads/upstream/main*')
})
it('anchors local-branch-name searches below configured remotes', () => {
const argv = buildSearchBaseRefsArgv('plan/docs', 10, { remoteNames: ['origin', 'foo/bar'] })
expect(argv).toContain('refs/remotes/origin/plan/docs*')
expect(argv).toContain('refs/remotes/foo/bar/plan/docs*')
expect(argv).not.toContain('refs/remotes/**/*plan/docs*')
})
it('can build display-format and branch-root patterns separately', () => {
const segmentedArgv = buildSearchBaseRefsArgv('upstream/feat', 10, {
remoteNames: ['origin', 'upstream'],
patternGroup: 'segmented'
})
const argv = buildSearchBaseRefsArgv('upstream/feat', 10, {
remoteNames: ['origin', 'upstream'],
patternGroup: 'branchRoot'
})
expect(segmentedArgv).toContain('refs/remotes/*upstream*/*feat*')
expect(segmentedArgv).not.toContain('refs/remotes/origin/upstream/feat*')
expect(argv).toContain('refs/remotes/origin/upstream/feat*')
expect(argv).not.toContain('refs/remotes/*upstream*/*feat*')
})
it('adds fallback headroom when remote HEAD cannot be excluded by git', () => {
@@ -351,6 +377,88 @@ describe('searchBaseRefs (widened glob)', () => {
expect(await searchBaseRefs(tmpDir, '/upstream')).toContain('upstream/main')
expect(await searchBaseRefs(tmpDir, 'upstream//main')).toContain('upstream/main')
})
it('finds a remote branch when the query is the local branch name with slashes', async () => {
const sha = getHeadSha(tmpDir)
git(tmpDir, ['remote', 'add', 'origin', 'https://example.invalid/repo.git'])
createRemoteRef(tmpDir, 'origin/plan/unified-brainstorm-plan-docs', sha)
const results = await searchBaseRefs(tmpDir, 'plan/unified-brainstorm-plan-docs')
expect(results).toContain('origin/plan/unified-brainstorm-plan-docs')
})
it('finds a remote branch by local branch name when the remote name has slashes', async () => {
const sha = getHeadSha(tmpDir)
git(tmpDir, ['remote', 'add', 'foo/bar', 'https://example.invalid/repo.git'])
createRemoteRef(tmpDir, 'foo/bar/plan/unified-brainstorm-plan-docs', sha)
const results = await searchBaseRefs(tmpDir, 'plan/unified-brainstorm-plan-docs')
expect(results).toContain('foo/bar/plan/unified-brainstorm-plan-docs')
})
it('does not match slash queries inside unrelated nested branch paths', async () => {
const sha = getHeadSha(tmpDir)
git(tmpDir, ['remote', 'add', 'origin', 'https://example.invalid/repo.git'])
git(tmpDir, ['remote', 'add', 'upstream', 'https://example.invalid/upstream.git'])
createRemoteRef(tmpDir, 'origin/upstream/feature-x', sha)
createRemoteRef(tmpDir, 'origin/foo/upstream/feature-x', sha)
createRemoteRef(tmpDir, 'upstream/feature-y', sha)
const results = await searchBaseRefs(tmpDir, 'upstream/feat')
expect(results).toContain('upstream/feature-y')
expect(results).toContain('origin/upstream/feature-x')
expect(results).not.toContain('origin/foo/upstream/feature-x')
})
it('keeps display-format matches when many branch-root matches share the query', async () => {
const sha = getHeadSha(tmpDir)
git(tmpDir, ['remote', 'add', 'origin', 'https://example.invalid/repo.git'])
git(tmpDir, ['remote', 'add', 'upstream', 'https://example.invalid/upstream.git'])
for (let i = 0; i < 12; i += 1) {
createRemoteRef(tmpDir, `origin/upstream/feature-${i}`, sha)
}
createRemoteRef(tmpDir, 'upstream/feature-target', sha)
const results = await searchBaseRefs(tmpDir, 'upstream/feature', 2)
expect(results).toContain('upstream/feature-target')
})
it('still finds a local-branch-name match when the first segment is also a remote name', async () => {
const sha = getHeadSha(tmpDir)
git(tmpDir, ['remote', 'add', 'origin', 'https://example.invalid/repo.git'])
git(tmpDir, ['remote', 'add', 'plan', 'https://example.invalid/plan.git'])
createRemoteRef(tmpDir, 'origin/plan/docs', sha)
const results = await searchBaseRefs(tmpDir, 'plan/docs')
expect(results).toContain('origin/plan/docs')
})
it('keeps branch-root matches when many display-format matches share the query', async () => {
const sha = getHeadSha(tmpDir)
git(tmpDir, ['remote', 'add', 'origin', 'https://example.invalid/repo.git'])
git(tmpDir, ['remote', 'add', 'plan', 'https://example.invalid/plan.git'])
for (let i = 0; i < 12; i += 1) {
createRemoteRef(tmpDir, `plan/docs-${i}`, sha)
}
createRemoteRef(tmpDir, 'origin/plan/docs', sha)
const results = await searchBaseRefs(tmpDir, 'plan/docs', 2)
expect(results).toContain('origin/plan/docs')
})
it('finds a local slashed branch when the query repeats the full branch name', async () => {
git(tmpDir, ['branch', 'plan/unified-brainstorm-plan-docs'])
const results = await searchBaseRefs(tmpDir, 'plan/unified-brainstorm-plan-docs')
expect(results).toContain('plan/unified-brainstorm-plan-docs')
})
})
describe('getDefaultBaseRef (regression — unchanged behavior)', () => {
+110 -17
View File
@@ -504,6 +504,12 @@ async function getDefaultBaseRefAsync(
const REF_SEARCH_CANDIDATE_MULTIPLIER = 4
const REF_SEARCH_LEGACY_HEADROOM = 100
type RefSearchPatternGroup = 'all' | 'segmented' | 'branchRoot'
function getRefSearchTokens(normalizedQuery: string): string[] {
return normalizedQuery.split('/').filter((t) => t.length > 0)
}
function getRefSearchCandidateCount(limit: number, excludesRemoteHead: boolean): number {
if (!Number.isInteger(limit) || limit <= 0) {
throw new Error('invalid_limit')
@@ -515,7 +521,11 @@ function getRefSearchCandidateCount(limit: number, excludesRemoteHead: boolean):
export function buildSearchBaseRefsArgv(
normalizedQuery: string,
limit: number,
options: { excludeRemoteHead?: boolean } = {}
options: {
excludeRemoteHead?: boolean
remoteNames?: readonly string[]
patternGroup?: RefSearchPatternGroup
} = {}
): string[] {
const excludeRemoteHead = options.excludeRemoteHead ?? true
const candidateCount = getRefSearchCandidateCount(limit, excludeRemoteHead)
@@ -541,7 +551,7 @@ export function buildSearchBaseRefsArgv(
// patterns. A single remaining token means the user hasn't committed
// to a remote-plus-branch query yet — route through the widened
// single-segment globs below instead of pinning to one segment.
const tokens = normalizedQuery.split('/').filter((t) => t.length > 0)
const tokens = getRefSearchTokens(normalizedQuery)
if (tokens.length <= 1) {
const q = tokens[0] ?? ''
// Why `**`, not `*`: git for-each-ref globs are fnmatch-style where a
@@ -563,7 +573,82 @@ export function buildSearchBaseRefsArgv(
// as `<remote>/<branch>`, so users naturally retype that format; this
// branch is what makes re-typing a visible result actually find it.
const segmented = tokens.map((token) => `*${token}*`).join('/')
return [...base, `refs/remotes/${segmented}`, `refs/heads/${segmented}`]
const substringQuery = tokens.join('/')
const remoteBranchRootPatterns =
options.remoteNames && options.remoteNames.length > 0
? options.remoteNames.flatMap((remote) => [
`refs/remotes/${remote}/${substringQuery}*`,
`refs/remotes/${remote}/${substringQuery}*/**`
])
: [`refs/remotes/*/${substringQuery}*`, `refs/remotes/*/${substringQuery}*/**`]
const segmentedPatterns = [`refs/remotes/${segmented}`, `refs/heads/${segmented}`]
const branchRootPatterns = [
// Why: branch names often contain slashes (`plan/docs`). Segment-wise
// display-format globs only align with `<remote>/<branch>`; these root
// patterns also match the local branch name beneath any configured remote.
`refs/heads/${substringQuery}*`,
`refs/heads/${substringQuery}*/**`,
...remoteBranchRootPatterns
]
const patterns =
options.patternGroup === 'segmented'
? segmentedPatterns
: options.patternGroup === 'branchRoot'
? branchRootPatterns
: [...segmentedPatterns, ...branchRootPatterns]
return [...base, ...patterns]
}
async function runSearchBaseRefsGit(
path: string,
normalizedQuery: string,
limit: number,
options: { remoteNames: readonly string[]; patternGroup?: RefSearchPatternGroup }
): Promise<{ stdout: string }> {
try {
return await gitExecFileAsync(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
remoteNames: options.remoteNames,
patternGroup: options.patternGroup
}),
{ cwd: path }
)
} catch (err) {
if (!isForEachRefExcludeUnsupportedError(err)) {
throw err
}
return gitExecFileAsync(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
excludeRemoteHead: false,
remoteNames: options.remoteNames,
patternGroup: options.patternGroup
}),
{ cwd: path }
)
}
}
export function mergeBaseRefSearchResultGroups(
groups: readonly BaseRefSearchResult[][],
limit: number
): BaseRefSearchResult[] {
const seen = new Set<string>()
const merged: BaseRefSearchResult[] = []
const maxLength = Math.max(0, ...groups.map((group) => group.length))
for (let index = 0; index < maxLength && merged.length < limit; index += 1) {
for (const group of groups) {
const entry = group[index]
if (!entry || seen.has(entry.refName)) {
continue
}
seen.add(entry.refName)
merged.push(entry)
if (merged.length >= limit) {
break
}
}
}
return merged
}
export function isForEachRefExcludeUnsupportedError(error: unknown): boolean {
@@ -655,23 +740,31 @@ export async function searchBaseRefDetails(
try {
// Why: argv (including the two-remote-glob rationale) lives in
// buildSearchBaseRefsArgv so the SSH sibling cannot drift.
const remotesPromise = listRemoteNames(path)
let result: { stdout: string }
try {
result = await gitExecFileAsync(buildSearchBaseRefsArgv(normalizedQuery, limit), {
cwd: path
})
} catch (err) {
if (!isForEachRefExcludeUnsupportedError(err)) {
throw err
}
result = await gitExecFileAsync(
buildSearchBaseRefsArgv(normalizedQuery, limit, { excludeRemoteHead: false }),
{ cwd: path }
const remotes = await listRemoteNames(path)
const tokens = getRefSearchTokens(normalizedQuery)
if (tokens.length > 1) {
// Why: ambiguous slash queries need both display-format matches
// (`upstream/feat`) and local branch-name matches (`plan/docs`).
// Parse and merge buckets before the final limit so neither side starves.
const results = await Promise.all([
runSearchBaseRefsGit(path, normalizedQuery, limit, {
remoteNames: remotes,
patternGroup: 'segmented'
}),
runSearchBaseRefsGit(path, normalizedQuery, limit, {
remoteNames: remotes,
patternGroup: 'branchRoot'
})
])
return mergeBaseRefSearchResultGroups(
results.map((entry) => parseAndFilterSearchRefDetails(entry.stdout, limit, remotes)),
limit
)
}
const remotes = await remotesPromise
const result = await runSearchBaseRefsGit(path, normalizedQuery, limit, {
remoteNames: remotes
})
return parseAndFilterSearchRefDetails(result.stdout, limit, remotes)
} catch (err) {
// Why: surface the failure for diagnostics; callers treat `[]` as "no
+12 -7
View File
@@ -2561,17 +2561,22 @@ describe('repos:searchBaseRefs SSH relay', () => {
await handlers.get('repos:searchBaseRefs')!(null, { repoId: 'r1', query: 'upstream/main' })
expect(mockGitProvider.exec).toHaveBeenCalledTimes(2)
const [argv] = mockGitProvider.exec.mock.calls.find(
expect(mockGitProvider.exec).toHaveBeenCalledTimes(3)
const forEachRefCalls = mockGitProvider.exec.mock.calls.filter(
(call) => (call[0] as string[])[0] === 'for-each-ref'
)!
expect(argv).toContain('refs/remotes/*upstream*/*main*')
expect(argv).toContain('refs/heads/*upstream*/*main*')
)
expect(forEachRefCalls).toHaveLength(2)
const segmentedArgv = forEachRefCalls[0][0] as string[]
const branchRootArgv = forEachRefCalls[1][0] as string[]
expect(segmentedArgv).toContain('refs/remotes/*upstream*/*main*')
expect(segmentedArgv).toContain('refs/heads/*upstream*/*main*')
expect(branchRootArgv).toContain('refs/remotes/*/upstream/main*')
expect(branchRootArgv).toContain('refs/heads/upstream/main*')
// Regression guard: the literal slash must never appear inside a
// single segmented glob (would be `refs/remotes/*upstream/main*`),
// which fnmatch cannot match because `*` doesn't cross `/`.
expect(argv).not.toContain('refs/remotes/*upstream/main*/*')
expect(argv).not.toContain('refs/remotes/*/*upstream/main*')
expect(segmentedArgv).not.toContain('refs/remotes/*upstream/main*/*')
expect(segmentedArgv).not.toContain('refs/remotes/*/*upstream/main*')
expect(mockGitProvider.exec).toHaveBeenCalledWith(['remote'], '/remote/repo')
})
+42 -19
View File
@@ -69,6 +69,7 @@ import {
resolveDefaultBaseRefViaExec,
buildSearchBaseRefsArgv,
isForEachRefExcludeUnsupportedError,
mergeBaseRefSearchResultGroups,
searchBaseRefDetails
} from '../git/repo'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
@@ -2423,29 +2424,51 @@ async function searchBaseRefDetailsForRepo(
try {
// Why: argv (including the two-remote-glob rationale) lives in
// buildSearchBaseRefsArgv so the SSH and local paths cannot drift.
const remotesPromise = provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' }))
let result: { stdout: string }
try {
result = await provider.exec(buildSearchBaseRefsArgv(normalizedQuery, limit), repo.path)
} catch (err) {
if (!isForEachRefExcludeUnsupportedError(err)) {
throw err
}
result = await provider.exec(
buildSearchBaseRefsArgv(normalizedQuery, limit, { excludeRemoteHead: false }),
repo.path
)
}
const remotesResult = await remotesPromise
// Why: delegate the NUL-parse + HEAD filter + dedup + limit pipeline
// to the shared helper so the SSH and local paths cannot diverge.
// See parseAndFilterSearchRefs in ../git/repo.ts for the dedup +
// HEAD-filter rationale.
const remotesResult = await provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' }))
const remotes = remotesResult.stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
return parseAndFilterSearchRefDetails(result.stdout, limit, remotes)
const runSearch = async (patternGroup?: 'segmented' | 'branchRoot'): Promise<string> => {
try {
return (
await provider.exec(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
remoteNames: remotes,
patternGroup
}),
repo.path
)
).stdout
} catch (err) {
if (!isForEachRefExcludeUnsupportedError(err)) {
throw err
}
return (
await provider.exec(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
excludeRemoteHead: false,
remoteNames: remotes,
patternGroup
}),
repo.path
)
).stdout
}
}
// Why: delegate the NUL-parse + HEAD filter + dedup + limit pipeline
// to the shared helper so the SSH and local paths cannot diverge.
// See parseAndFilterSearchRefs in ../git/repo.ts for the dedup +
// HEAD-filter rationale.
const searchTokens = normalizedQuery.split('/').filter((token) => token.length > 0)
if (searchTokens.length > 1) {
const results = await Promise.all([runSearch('segmented'), runSearch('branchRoot')])
return mergeBaseRefSearchResultGroups(
results.map((stdout) => parseAndFilterSearchRefDetails(stdout, limit, remotes)),
limit
)
}
return parseAndFilterSearchRefDetails(await runSearch(), limit, remotes)
} catch (err) {
console.warn('[repos:searchBaseRefs] SSH for-each-ref failed', {
path: repo.path,
+38 -15
View File
@@ -518,6 +518,7 @@ import {
resolveDefaultBaseRefViaExec,
buildSearchBaseRefsArgv,
isForEachRefExcludeUnsupportedError,
mergeBaseRefSearchResultGroups,
getRemoteDrift,
getRecentDriftSubjects
} from '../git/repo'
@@ -8284,25 +8285,47 @@ export class OrcaRuntimeService {
}
const normalizedQuery = normalizeRefSearchQuery(query)
try {
const remotesPromise = provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' }))
let result: { stdout: string }
try {
result = await provider.exec(buildSearchBaseRefsArgv(normalizedQuery, limit), repo.path)
} catch (err) {
if (!isForEachRefExcludeUnsupportedError(err)) {
throw err
}
result = await provider.exec(
buildSearchBaseRefsArgv(normalizedQuery, limit, { excludeRemoteHead: false }),
repo.path
)
}
const remotesResult = await remotesPromise
const remotesResult = await provider.exec(['remote'], repo.path).catch(() => ({ stdout: '' }))
const remotes = remotesResult.stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
return parseAndFilterSearchRefDetails(result.stdout, limit, remotes)
const runSearch = async (patternGroup?: 'segmented' | 'branchRoot'): Promise<string> => {
try {
return (
await provider.exec(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
remoteNames: remotes,
patternGroup
}),
repo.path
)
).stdout
} catch (err) {
if (!isForEachRefExcludeUnsupportedError(err)) {
throw err
}
return (
await provider.exec(
buildSearchBaseRefsArgv(normalizedQuery, limit, {
excludeRemoteHead: false,
remoteNames: remotes,
patternGroup
}),
repo.path
)
).stdout
}
}
const searchTokens = normalizedQuery.split('/').filter((token) => token.length > 0)
if (searchTokens.length > 1) {
const results = await Promise.all([runSearch('segmented'), runSearch('branchRoot')])
return mergeBaseRefSearchResultGroups(
results.map((stdout) => parseAndFilterSearchRefDetails(stdout, limit, remotes)),
limit
)
}
return parseAndFilterSearchRefDetails(await runSearch(), limit, remotes)
} catch (err) {
console.warn('[runtime:repo.searchRefs] SSH for-each-ref failed', {
path: repo.path,