fix(git): keep a worktree branch's base right through agent creation and restacks

Worktrees made through the agent tool showed master as their base: the Git
view's Re-integrate commits target came from in-memory metadata only the UI
dialogs set, then fell back to the project root's branch, and offered to move
the parent branch's commits too. A branch started from HEAD (multi-run,
extensions, the agent tool without startRef) recorded no parent at all. After
a restack made outside OpenChamber (git rebase --onto in a terminal) the base
kept the stale recorded parent, so Changes counted the new parent's commits as
the branch's own. The unpublished-commits counter counted a branch made from a
feature branch against main. A startRef such as refs/heads/feat was parsed as
remote "refs" and failed the creation. Worktree creation in a repository cloned
from a local path or file:// failed its bootstrap with "Git transport remote
binding changed".

Every new branch now records the branch it starts from in
branch.<name>.gh-merge-base, the primary checkout's branch for a HEAD start,
on the web server and in the VS Code service. getBranchBase reads the branch's
own reflog: when its latest rebase landed on a commit the recorded parent never
pointed at, the one branch that moved there becomes the base; backups created
at that commit, the branch's own remote copy and ambiguous candidates do not.
Re-integrate commits starts on the same base Changes and pull requests use.
Status counts an upstream-less branch from that base. Checkout hydration no
longer names a remote whose fetch or push address is on disk, which source
control transport leaves out by design.

Testing: new service tests for HEAD and full-ref starts, terminal restacks,
backups, deleted parents, the ahead counter and disk remotes, all failing on
the old code; full git service suite and the VS Code worktree tests pass. In an
isolated dev instance, an agent-created worktree from a feature branch shows
that branch in Re-integrate and Changes, a terminal restack onto master moves
the Changes base to master, and worktrees are created through both the dialog
and the agent tool for https, path and file:// clones.
This commit is contained in:
Bohdan Triapitsyn committed 2026-11-22 12:43:07 +02:00
1 parent 2e020f118e
commit e301f5b6e9
9 files changed
+308 -78

No files matched your search

@@ -311,10 +311,11 @@ the base being resolved until the base is known; it moves to the working tree
only once the branch is known to have no base, so the view never switches
under the person a moment after opening (it used to open on the working tree
and jump to Branch when the base arrived). The Git view and the pull request
view take the same base for a new pull request and for updates
(`useBranchPullRequestBase`): a base chosen for the branch, its open pull
request's target, or the parent it was made on (a lower layer of a stack),
and the worktree's own guess only when none of those answers. The Git view,
view take the same base for a new pull request, for updates and for the
target Re-integrate commits starts on (`useBranchPullRequestBase`): a base
chosen for the branch, its open pull request's target, or the parent the
server recorded or detected (a lower layer of a stack, the branch a restack
landed on), and the worktree's own guess only when none of those answers. The Git view,
Changes, mobile Changes and Walkthrough each ask for the branch's pull request
themselves (`hooks/useBranchPullRequestRequest.ts`) while shown: the base
prefers its target, and the Git header's pull request chip reads the same
+1 -27
View File
@@ -694,33 +694,6 @@ export const GitView: React.FC<GitViewProps> = ({ isActive }) => {
if (!tracking) return true;
return tracking.startsWith('origin/');
}, [status?.tracking]);
const defaultTargetBranch = React.useMemo(() => {
const fromMeta = worktreeMetadata?.createdFromBranch;
const normalizedFromMeta = typeof fromMeta === 'string' ? fromMeta.trim() : '';
const current = typeof status?.current === 'string' ? status.current.trim() : '';
const normalizedRoot = typeof rootBranchHint === 'string' ? rootBranchHint.trim() : '';
if (normalizedFromMeta) {
const looksLikeCorruptedSelfTarget =
normalizedFromMeta === current &&
normalizedFromMeta.startsWith('opencode/') &&
normalizedRoot.length > 0 &&
normalizedRoot !== normalizedFromMeta;
if (looksLikeCorruptedSelfTarget) {
return normalizedRoot;
}
return normalizedFromMeta;
}
if (normalizedRoot) {
return normalizedRoot;
}
if (current) {
return current;
}
return 'HEAD';
}, [worktreeMetadata?.createdFromBranch, status, rootBranchHint]);
const clearGeneratedHighlights = React.useCallback(() => {
setGeneratedHighlights([]);
}, []);
@@ -1503,6 +1476,7 @@ export const GitView: React.FC<GitViewProps> = ({ isActive }) => {
worktreeMetadata?.createdFromBranch,
]);
const baseBranch = useBranchPullRequestBase(gitDirectory ?? null, currentBranch, isActive, binding, branches, derivedBaseBranch);
const defaultTargetBranch = baseBranch || currentBranch || 'HEAD';
useBranchPullRequestRequest(isActive ? gitDirectory ?? null : null, isActive ? currentBranch : null, binding);
const updateTargetBranch = React.useMemo(() => {
+4 -4
View File
@@ -11,6 +11,7 @@ import { isContributorForkGitDirectory } from '../../web/server/lib/git/contribu
import { readProjectStartCommand } from '../../web/server/lib/opencode/project-start-command.js';
import { readSubmoduleState, resolveGitPathTarget, type GitPathUnavailable, type GitSubmoduleState } from './gitPathDiff';
import { parseGitRemoteListing, type GitRemote } from './gitRemoteListing';
import { recordWorktreeBranchParent } from './worktreeBranchParent';
import {
parseRawBranchListing,
parseRemoteDefaultBranches,
@@ -926,13 +927,11 @@ const parseRemoteBranchRef = (value: string) => {
const resolveRemoteBranchRef = async (primaryWorktree: string, value: string) => {
const raw = String(value || '').trim();
const parsed = parseRemoteBranchRef(raw);
if (!parsed) {
if (!parsed || (raw.startsWith('refs/') && !raw.startsWith('refs/remotes/'))) {
return null;
}
if (raw.startsWith('refs/remotes/') || raw.startsWith('remotes/')) {
return parsed;
}
if (raw.startsWith('refs/remotes/') || raw.startsWith('remotes/')) return parsed;
const localRef = `refs/heads/${raw}`;
const localExists = await runGitCommand(primaryWorktree, ['show-ref', '--verify', '--quiet', localRef]);
@@ -1992,6 +1991,7 @@ async function attachGitWorktreeToCandidate(
}
throw error;
}
if (mode === 'new') await recordWorktreeBranchParent(runGitCommand, context.primaryWorktree, localBranch, startRef);
const shouldSetUpstream = Boolean(input?.setUpstream);
const upstreamRemote = String(input?.upstreamRemote || inferredUpstream?.remote || '').trim();
@@ -144,4 +144,26 @@ describe('VS Code worktree upstream tracking', () => {
expect(readBranchConfig(created.path, 'feature/tracking', 'merge')).toBe('refs/heads/main');
});
}, 30_000);
it('records the branch a new worktree branch starts from as its parent', async () => {
if (!canRunGit()) return;
await withDataHome(async () => {
const { repository } = createRepositoryWithRemote();
runGit(repository, ['branch', 'feature/base']);
const fromHead = await createWorktree(repository, { mode: 'new', branchName: 'from-head', worktreeName: 'from-head' });
const fromFullRef = await createWorktree(repository, {
mode: 'new', branchName: 'from-full-ref', worktreeName: 'from-full-ref', startRef: 'refs/heads/feature/base',
});
const fromRemote = await createWorktree(repository, {
mode: 'new', branchName: 'from-remote', worktreeName: 'from-remote', startRef: 'origin/main',
});
await Promise.all([fromHead, fromFullRef, fromRemote].map((created) => waitForBootstrapReady(created.path)));
expect(readBranchConfig(repository, 'from-head', 'gh-merge-base')).toBe('next');
expect(readBranchConfig(repository, 'from-full-ref', 'gh-merge-base')).toBe('feature/base');
expect(readBranchConfig(repository, 'from-remote', 'gh-merge-base')).toBe('main');
});
}, 30_000);
});
@@ -0,0 +1,22 @@
type RunGit = (cwd: string, args: string[]) => Promise<{ success: boolean; stdout: string }>;
const output = async (runGit: RunGit, cwd: string, args: string[]) => {
const result = await runGit(cwd, args);
return result.success ? String(result.stdout || '').trim() : '';
};
const startBranchName = async (runGit: RunGit, primaryWorktree: string, startRef: string) => {
const fullName = await output(runGit, primaryWorktree, ['rev-parse', '--symbolic-full-name', startRef]);
if (fullName.startsWith('refs/heads/')) return fullName.slice('refs/heads/'.length);
if (!fullName.startsWith('refs/remotes/')) return null;
const remoteRef = fullName.slice('refs/remotes/'.length);
const remotes = (await output(runGit, primaryWorktree, ['remote'])).split('\n').map((name) => name.trim()).filter(Boolean);
const remote = remotes.filter((name) => remoteRef.startsWith(`${name}/`)).sort((a, b) => b.length - a.length)[0];
return remote ? remoteRef.slice(remote.length + 1) : null;
};
export async function recordWorktreeBranchParent(runGit: RunGit, primaryWorktree: string, branch: string, startRef: string) {
const parent = await startBranchName(runGit, primaryWorktree, startRef);
if (!parent || parent === branch) return;
await runGit(primaryWorktree, ['config', `branch.${branch}.gh-merge-base`, parent]);
}
+8 -3
View File
@@ -279,7 +279,7 @@ An identity is one repository's complete answer: signature, provider account (`a
A stale status row can outlive its repository. Returning empty contents would replace a real comparison with an apparently successful empty diff and poison the client cache. A quiet 409 preserves the distinction and lets the existing error views explain why the comparison is unavailable.
### Branch Operations
- `getBranchBase(directory, branch)`: The branch's recorded parent, `branch.<name>.gh-merge-base` (the key `gh pr create` also reads as its default base), while it still names a ref; else a named creation source from the reflog. `createWorktree` records the parent when a new branch starts from another branch, and `rebase` records the branch it lands on (a local or remote-tracking branch; a commit, the branch's own remote copy or a detached HEAD leave the record alone), so a stacked branch keeps its lower layer as its base through a rebase. Either answer moves up to a nearer stack layer when one exists (see *Why a stale parent moves up to the nearest stack layer*). After a rebase with no such layer, the creation source is no longer a current parent record, so return `null` and let the user choose a base. A source that is the branch's own remote copy (`git switch feat` records `Created from refs/remotes/origin/feat`) is not a parent either and also returns `null`. Explicit per-runtime, directory, and branch choices in the shared UI outrank detection.
- `getBranchBase(directory, branch)`: The branch's recorded parent, `branch.<name>.gh-merge-base` (the key `gh pr create` also reads as its default base), while it still names a ref; else a named creation source from the reflog. `createWorktree` records the parent when a new branch starts from another branch, and `rebase` records the branch it lands on (a local or remote-tracking branch; a commit, the branch's own remote copy or a detached HEAD leave the record alone), so a stacked branch keeps its lower layer as its base through a rebase. A rebase made outside OpenChamber (a terminal restack, `rebase --onto`) leaves the record behind, so when the branch's latest rebase landed on a commit the parent never pointed at, the one branch at that commit answers instead (see *Why the latest rebase outranks the record*). Otherwise either answer moves up to a nearer stack layer when one exists (see *Why a stale parent moves up to the nearest stack layer*). After a rebase onto a commit no branch names, the creation source is no longer a current parent record, so return `null` and let the user choose a base. A source that is the branch's own remote copy (`git switch feat` records `Created from refs/remotes/origin/feat`) is not a parent either and also returns `null`. Explicit per-runtime, directory, and branch choices in the shared UI outrank detection.
- `getBranches(directory, { remote })`: Get local branches and remote branches. The default answers from local refs alone, as `git branch -a` does. `remote: 'live'` (route `?remote=live`) also asks each remote with `ls-remote --heads`, described under the branch list below, and runs only when the person asks for it. On a detached HEAD, git's `(HEAD detached at <ref>)` line is left out of `all` and `branches`: listed under the tag or commit name, it looked like a branch, and picking it checked out the same ref again. `current` still carries that name.
- Commit integration is local-only: it may fast-forward to an existing local upstream ref, but never fetches implicitly. Refresh remote-tracking refs through an explicit planned Fetch operation before integration when current remote state is required.
- Ordinary worktree validation and creation from a remote branch that has no local remote-tracking ref fetch that single branch first (`git fetch <remote> +refs/heads/<branch>:refs/remotes/<remote>/<branch>`), because the branch list offers never-fetched remote branches. A failed fetch reports `Remote branch not found`. Upstream setup is local-only. Contributor worktrees retain their dedicated managed transfer and checkout-hydration operations and never take this fetch.
@@ -294,6 +294,10 @@ A stale status row can outlive its repository. Returning empty contents would re
The parent record is written once, when OpenChamber makes or rebases the branch. A stack rearranged by hand (`git rebase` in a terminal, an agent's restack) keeps the old record, and comparing against a lower layer shows the middle layer's commits as the branch's own. Rewriting the record on every terminal rebase is impossible, so `findNearerStackLayer` reads the stack from the commits: the nearest local branch whose tip sits on the branch's first-parent line above the recorded (or created-from) parent. It only looks above a named parent, so a branch made on the default branch never picks up an unrelated branch. A branch merged in from the side is off the first-parent line and does not count. A candidate must itself have been made below the branch. Its recorded parent, or a reflog creation source naming another local or remote-tracking branch, says so. A candidate made from `HEAD` (`git checkout -b` on the layer below, the usual way to stack) or a revision such as `HEAD~1` counts only when the commit it started at, the oldest entry of its reflog, is at or below the lower parent, or is a tip the lower parent's own reflog remembers (the whole stack moved onto a newer base rewrites that tip); a backup or a child of the branch started on the branch's own commits above it. Two such names at the nearest commit answer nothing new, and the record stands. Trusting the record alone was the rejected alternative; it was right until the first manual restack. Reading the topology alone, without the record, was rejected too: after OpenChamber moves a branch onto a sibling stack, no layer sits above the old parent, so only the record knows it.
#### Why the latest rebase outranks the record
A restack that does not stack upwards (a branch made on a feature branch and moved onto `main`, or made on `main` and moved onto a layer that branched off an older `main`) leaves no layer above the recorded parent, so `findNearerStackLayer` cannot see it and the stale record would win. Git itself writes where every rebase landed: `rebase (finish): refs/heads/<branch> onto <commit>` in the branch's own reflog. `findRestackedParent` takes the latest such commit that is still in the branch. When the parent points or once pointed there (its tip or reflog, without the entry that created it), the record still holds. Otherwise the parent is the one branch that pointed at that commit by its own movement (a commit, a fetch, a reset in its reflog, or its tip when it has no reflog); a branch created at that commit, such as a backup made afterwards, never was a rebase target and does not count. A local branch and its remote copy count as one, the branch's own remote copy (`pull --rebase`) says nothing, and two or more candidates leave the record standing. All candidates' reflogs are read in one `git log --walk-reflogs` call, since the lookup reruns on every status refresh. The lookup also runs when the old parent is gone or was never named (`Created from HEAD`). Guessing the parent from the nearest branch the head sits on was the rejected alternative: a branch that merged a sibling in, or a backup or child made from the branch, sits nearer than the real parent, and only the reflog says which branch the rebase targeted.
`rebase` records its destination only once the rebase finishes. A rebase stopped on a conflict keeps the pending parent in a file inside git's own `rebase-merge`/`rebase-apply` folder, which `continueRebase` reads; git deletes that folder on finish or abort, so a rebase finished or aborted in a terminal leaves no stale record behind.
### Worktree Operations
@@ -305,7 +309,8 @@ The parent record is written once, when OpenChamber makes or rebases the branch.
- `subscribeWorktreeTopologyChanges(listener)`: Listener receives `{ directories, at }`, where `directories` are every directory of that repository the server has observed, so clients can map them onto registered projects. Returns an unsubscribe function.
- `validateWorktreeCreate(directory, input)`: Validate worktree creation parameters (mode, branchName, startRef, upstream config).
- `waitForActiveWorktreeBootstrap(directory)`: Join this process's tracked checkout, hydration, and setup tasks. It awaits the existing promises, including tasks registered by early-return creation, without polling status. With no tracked task it returns immediately; callers still check `getWorktreeBootstrapStatus` to distinguish success from failure or interrupted recovery. Completion says nothing about OpenCode's agent/config discovery.
- A new branch made from a named branch (`mode: 'new'` with a local or remote-tracking `startRef`) records that branch as its parent in `branch.<name>.gh-merge-base`. A write that fails leaves the reflog to answer and never fails the creation; deleting the branch removes the key with the rest of its config.
- Checkout hydration never names a remote whose fetch or push address is a path on disk. Source control transport leaves such remotes out of every repository context (`isDiskPathRemoteUrl`), so naming one failed the bootstrap of every worktree in a repository cloned from a local path or `file://`. Hydration runs without a parent remote instead; a submodule that needs that remote's address then fails hydration on its own.
- Every new branch (`mode: 'new'`) records the branch it starts from as its parent in `branch.<name>.gh-merge-base`: a local or remote-tracking `startRef`, or, without one, the branch the primary checkout has checked out. Every creation path (the New worktree dialog, the agent tool's `session.create` and `session.moveToWorktree`, multi-run, extensions, scheduled tasks) goes through `createWorktree`, so this record is the one place the base is kept; the UI's in-memory `createdFromBranch` only fills in where a runtime cannot read it. A start at a commit or tag records nothing. A write that fails leaves the reflog to answer and never fails the creation; deleting the branch removes the key with the rest of its config.
- `createWorktree(directory, input)`: Create a new worktree (supports 'new' and 'existing' modes, upstream setup). Population never runs repository hooks or executable content filters. Contributor-fork worktrees also skip stored project setup and request setup commands during creation; they remain Git-ready and require a later exact-checkout digest-bound trust operation before executable checkout content may run. A trusted hook runs only from an operation-private mode-`0700` directory as a verified mode-`0500` content snapshot. The executor never reopens the repository hook pathname after approval, preserves `GIT_DIR`, `GIT_WORK_TREE`, arguments, and working directory in the trust digest, and removes the snapshot under a fresh bounded cleanup deadline even after cancellation.
- `createWorktree(directory, input)`: Create a new worktree (supports 'new' and 'existing' modes, upstream setup). When the current tracked branch has no unpublished commits, the UI supplies its remote-tracking ref and this operation fetches that branch once before creating the worktree. A failed fetch falls back to the local branch and reports `sourceFetchFailed`; other remote start refs still require an existing local ref when their fetch fails. After populating the worktree, the repository's `post-checkout` hook runs once with git's standard arguments (null ref as previous HEAD, the checked-out HEAD, and flag `1`) from the worktree directory, mirroring `git worktree add` without `--no-checkout`; a missing or non-executable hook is skipped and a failing hook is logged as a warning, never failing worktree creation or the session bootstrap.
- `removeWorktree(directory, input)`: Remove a worktree (optionally delete local branch). The local branch is kept, and the removal still succeeds, when another checkout holds it or a remote's `refs/remotes/<remote>/HEAD` names it as the default branch; the delete dialogs (`canDeleteWorktreeBranch`, `packages/ui/src/lib/worktrees/worktreeStatus.ts`) do not offer the branch toggles for such a branch. `--force` discards uncommitted work, so callers that must keep it snapshot first. A directory that is not a registered worktree is deleted only when it sits inside the data-dir worktree root (`<opencode data>/worktree/<projectID>`), never inside a configured `worktree.directory`, which can be shared with other projects (`".."`); inside a configured folder only a registered worktree that git failed to delete is removed; the VS Code runtime (`packages/vscode/src/gitService.ts`) applies the same guard. A registered linked worktree is released through the caller-injected `input.disposeInstance` hook after the match is confirmed and before `git worktree remove`, while the directory path still resolves; disposal is best-effort, so a failing hook is logged as a warning and never fails the removal. `DELETE /api/git/worktrees` builds that hook from the OpenCode URL/auth helpers injected into `registerGitRoutes`. The hook evicts the worktree root and every running location inside it from `GET /api/debug/location`, because a project opened on a folder of its repository runs its sessions in `<worktree>/ai`, a location of its own; when the list cannot be read it still evicts the root and rethrows the list error. The VS Code bridge does the same. The primary workspace and the orphan fallback never dispose, because neither is a registered linked worktree. From the release until the removal settles the worktree counts as being removed (see *Worktree removal and the folder's OpenCode location*), and a busy failure releases the instance again before the next attempt. A failed `git worktree remove` (run with `-c core.longpaths=true`) that got as far as deleting is followed by a registration check: git drops the registration once it starts deleting, whatever stops it then, a busy folder or a path too long for git even with long paths on (#5734). A worktree git no longer registers is finished as an orphan through `fs.rm`, which handles paths past git's limit; only a still-registered worktree with a busy failure is retried. A refusal before any deletion (a locked worktree) exits 128, as every git `die` does, and is reported as it is without the check: a registration that vanished meanwhile for another reason must not get the untouched folder deleted.
@@ -986,7 +991,7 @@ Gitea and Forgejo accept an SSH alias only when its effective `HostName` directl
- `tracking`: Upstream branch (e.g., 'origin/main').
- `ahead`: Number of commits ahead of upstream. Without an upstream, a full read counts the commits missing from the base branch instead (`origin/HEAD`, then `origin/main`, `origin/master`, `main`, `master`).
- `behind`: Number of commits behind upstream.
- `aheadBase`: The base ref `ahead` was counted against when there is no upstream; commits already on any remote-tracking branch are not counted either, so a contributor's PR checkout, whose head arrives as a fork remote branch, starts at `ahead: 0`. `null` when no such count was made (an upstream exists, light mode, detached HEAD, or no base ref found), so `ahead: 0` alone never means nothing is unpublished.
- `aheadBase`: The base ref `ahead` was counted against when there is no upstream: the branch's parent from `getBranchBase` (the base Changes compares with, so a branch made on a feature branch does not count that branch's commits), else `origin/HEAD`, `origin/main`, `origin/master`, `main` or `master`; commits already on any remote-tracking branch are not counted either, so a contributor's PR checkout, whose head arrives as a fork remote branch, starts at `ahead: 0`. `null` when no such count was made (an upstream exists, light mode, detached HEAD, or no base ref found), so `ahead: 0` alone never means nothing is unpublished.
- `upstreamComparison`: Optional comparison against `upstream/<current-branch>`, with `{ remote, branch, ahead, behind }`.
- `files`: Array of file objects with `path`, `index`, `working_dir` status codes.
- `isClean`: Boolean indicating if working tree is clean.
@@ -0,0 +1,81 @@
import type { SimpleGit } from 'simple-git';
export const BRANCH_CREATION_SOURCE_RE = /^branch: Created from (.+)$/;
const REBASE_ONTO_RE = /rebase(?: -i)? \(finish\): \S+ onto ([0-9a-f]{7,64})$/;
export async function isOwnRemoteCopy(git: SimpleGit, source: string, branchName: string) {
const fullName = await git
.raw(['rev-parse', '--symbolic-full-name', source])
.then((value) => String(value || '').trim())
.catch(() => '');
if (!fullName.startsWith('refs/remotes/')) return false;
const upstream = await git
.raw(['rev-parse', '--symbolic-full-name', `refs/heads/${branchName}@{upstream}`])
.then((value) => String(value || '').trim())
.catch(() => '');
if (upstream && fullName === upstream) return true;
return fullName.slice('refs/remotes/'.length).split('/').slice(1).join('/') === branchName;
}
const readCommit = (git: SimpleGit, ref: string) => git
.raw(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])
.then((value) => String(value || '').trim())
.catch(() => '');
async function commitsPointedAtSinceCreation(git: SimpleGit, refs: readonly string[]) {
const pointed = new Map<string, Set<string>>();
if (refs.length === 0) return pointed;
const entries = String(await git.raw(['log', '--walk-reflogs', '--format=%gD%x00%H%x00%gs', ...refs]).catch(() => ''))
.split('\n').filter(Boolean).map((entry) => entry.split('\0'));
for (const [selector = '', commit = '', subject = ''] of entries) {
const ref = selector.replace(/@\{\d+\}$/, '');
const commits = pointed.get(ref) ?? new Set<string>();
if (!BRANCH_CREATION_SOURCE_RE.test(subject)) commits.add(commit);
pointed.set(ref, commits);
}
return pointed;
}
async function refsThatWereAt(git: SimpleGit, branchName: string, commit: string) {
const tips = new Map<string, string>();
const listed = String(await git.raw(['for-each-ref', '--format=%(refname)%00%(objectname)', '--contains', commit, 'refs/heads/', 'refs/remotes/']).catch(() => ''));
for (const [ref = '', tip = ''] of listed.split('\n').filter(Boolean).map((line) => line.split('\0'))) {
if (ref !== `refs/heads/${branchName}` && !ref.endsWith('/HEAD')) tips.set(ref, tip);
}
const pointed = await commitsPointedAtSinceCreation(git, [...tips.keys()]);
return [...tips].filter(([ref, tip]) => pointed.get(ref)?.has(commit) ?? tip === commit).map(([ref]) => ref);
}
const parentName = (ref: string, localNames: ReadonlySet<string>) => {
if (ref.startsWith('refs/heads/')) return ref.slice('refs/heads/'.length);
const remoteName = ref.slice('refs/remotes/'.length);
const branch = remoteName.split('/').slice(1).join('/');
return localNames.has(branch) ? branch : remoteName;
};
export async function findRestackedParent(git: SimpleGit, branchName: string, parentRefs: readonly string[]) {
const subjects = String(await git.raw(['reflog', 'show', '--format=%gs', `refs/heads/${branchName}`]).catch(() => ''))
.split('\n').map((line) => line.trim());
for (const [, onto] of subjects.map((subject) => subject.match(REBASE_ONTO_RE)).filter((match) => match !== null)) {
const commit = await readCommit(git, onto ?? '');
const stillUnderBranch = commit
&& await git.raw(['merge-base', '--is-ancestor', commit, `refs/heads/${branchName}`]).then(() => true, () => false);
if (!stillUnderBranch) continue;
const parentHistory = [...(await commitsPointedAtSinceCreation(git, parentRefs)).values()];
const parentTips = await Promise.all(parentRefs.map((ref) => readCommit(git, ref)));
if (parentTips.includes(commit) || parentHistory.some((commits) => commits.has(commit))) return undefined;
const refs = await refsThatWereAt(git, branchName, commit);
const parents = [];
for (const ref of refs) {
if (!ref.startsWith('refs/remotes/') || !(await isOwnRemoteCopy(git, ref, branchName))) parents.push(ref);
}
const ontoOwnRemoteCopy = parents.length === 0 && refs.length > 0;
if (ontoOwnRemoteCopy) continue;
const localNames = new Set(parents.filter((ref) => ref.startsWith('refs/heads/')).map((ref) => ref.slice('refs/heads/'.length)));
const names = new Set(parents.map((ref) => parentName(ref, localNames)));
const [only] = names;
return names.size === 1 && only ? only : null;
}
return undefined;
}
+131 -3
View File
@@ -1337,6 +1337,32 @@ describe('getStatus', () => {
await expect(getStatus(repo)).resolves.toMatchObject({ tracking: null, ahead: 1, aheadBase: 'origin/main' });
});
it('counts an upstream-less branch from the branch it was made on, as Changes does', async () => {
if (!canRunGit()) return;
const repo = createTempDir();
runGit(repo, ['init', '-b', 'main']);
runGit(repo, ['config', 'user.email', 'test@example.com']);
runGit(repo, ['config', 'user.name', 'Test User']);
runGit(repo, ['commit', '--allow-empty', '-m', 'Initial commit']);
runGit(repo, ['update-ref', 'refs/remotes/origin/main', 'HEAD']);
runGit(repo, ['checkout', '-q', '-b', 'feat/form']);
runGit(repo, ['commit', '--allow-empty', '-m', 'Feature work']);
runGit(repo, ['commit', '--allow-empty', '-m', 'More feature work']);
runGit(repo, ['checkout', '-q', '-b', 'task']);
runGit(repo, ['config', 'branch.task.gh-merge-base', 'feat/form']);
runGit(repo, ['commit', '--allow-empty', '-m', 'Task work']);
// The feature branch's own commits are not this branch's unpublished work.
await expect(getStatus(repo)).resolves.toMatchObject({ current: 'task', tracking: null, ahead: 1, aheadBase: 'feat/form' });
// A revision of its own line is no parent: the commit would be lost with the branch.
runGit(repo, ['branch', 'scratch', 'HEAD~0']);
runGit(repo, ['checkout', '-q', 'scratch']);
runGit(repo, ['commit', '--allow-empty', '-m', 'Scratch work']);
await expect(getStatus(repo)).resolves.toMatchObject({ current: 'scratch', tracking: null, ahead: 4, aheadBase: 'origin/main' });
});
it('falls back to a local main as the base, but never to the branch itself', async () => {
if (!canRunGit()) return;
@@ -1350,8 +1376,8 @@ describe('getStatus', () => {
runGit(repo, ['worktree', 'add', '-q', linked, 'main']);
runGit(linked, ['commit', '--allow-empty', '-m', 'Only on main']);
// No origin: `main` must not be measured against itself.
await expect(getStatus(linked)).resolves.toMatchObject({ current: 'main', tracking: null, aheadBase: null });
// No origin: `main` is measured against the branch it was made from, never against itself.
await expect(getStatus(linked)).resolves.toMatchObject({ current: 'main', tracking: null, ahead: 1, aheadBase: 'trunk' });
runGit(repo, ['checkout', '-q', '-b', 'feature', 'main']);
await expect(getStatus(repo)).resolves.toMatchObject({ current: 'feature', tracking: null, ahead: 0, aheadBase: 'main' });
@@ -2620,6 +2646,52 @@ describe('createWorktree', () => {
expect(readBranchConfig(created.path, 'feature/from-local', 'gh-merge-base')).toBe('main');
});
it('hydrates a checkout whose remote is a path on disk without naming that remote', async () => {
if (!canRunGit()) return;
const remote = createTempDir();
const repo = createTempDir();
runGit(remote, ['init', '--bare', '-b', 'main']);
runGit(repo, ['init', '-b', 'main']);
runGit(repo, ['config', 'user.email', 'test@example.com']);
runGit(repo, ['config', 'user.name', 'Test User']);
runGit(repo, ['commit', '--allow-empty', '-m', 'init']);
runGit(repo, ['remote', 'add', 'origin', remote]);
runGit(repo, ['push', '-q', '-u', 'origin', 'main']);
// Source control transport leaves disk remotes out, so naming one fails the whole bootstrap.
const hydrateCheckout = vi.fn(async () => ({ status: 'not-needed', submodules: [], lfs: [] }));
const bootstrapStore = createWorktreeBootstrapStore({ filePath: path.join(createTempDir(), 'bootstrap.json') });
const created = await createWorktree(repo, { mode: 'new', branchName: 'on-disk', worktreeName: 'on-disk' }, { hydrateCheckout, bootstrapStore });
await expect.poll(async () => (await getWorktreeBootstrapStatus(created.path, { bootstrapStore })).status, { timeout: 5_000 }).toBe('ready');
expect(hydrateCheckout).toHaveBeenCalledWith({ directory: created.path, parentRemoteName: '' });
// A remote that fetches over HTTPS but pushes to disk is left out the same way.
runGit(repo, ['remote', 'set-url', 'origin', 'https://example.com/team/repo.git']);
runGit(repo, ['remote', 'set-url', '--push', 'origin', remote]);
const pushOnDisk = await createWorktree(repo, { mode: 'new', branchName: 'push-on-disk', worktreeName: 'push-on-disk' }, { hydrateCheckout, bootstrapStore });
await expect.poll(async () => (await getWorktreeBootstrapStatus(pushOnDisk.path, { bootstrapStore })).status, { timeout: 5_000 }).toBe('ready');
expect(hydrateCheckout).toHaveBeenLastCalledWith({ directory: pushOnDisk.path, parentRemoteName: '' });
});
it('records the parent of a branch started from HEAD or from a full branch ref', async () => {
if (!canRunGit()) return;
const repo = createTempDir();
runGit(repo, ['init', '-b', 'main']);
runGit(repo, ['config', 'user.email', 'test@example.com']);
runGit(repo, ['config', 'user.name', 'Test User']);
runGit(repo, ['commit', '--allow-empty', '-m', 'init']);
runGit(repo, ['branch', 'feat/form']);
const bootstrapStore = createWorktreeBootstrapStore({ filePath: path.join(createTempDir(), 'bootstrap.json') });
// Multi-run, extensions and the agent tool without a startRef all start from the checkout's HEAD.
const fromHead = await createWorktree(repo, { mode: 'new', branchName: 'from-head', worktreeName: 'from-head' }, { bootstrapStore });
const fromFullRef = await createWorktree(repo, {
mode: 'new', branchName: 'from-full-ref', worktreeName: 'from-full-ref', startRef: 'refs/heads/feat/form',
}, { bootstrapStore });
expect(readBranchConfig(repo, 'from-head', 'gh-merge-base')).toBe('main');
expect(readBranchConfig(repo, 'from-full-ref', 'gh-merge-base')).toBe('feat/form');
expect(await getBranchBase(fromHead.path, 'from-head')).toEqual({ base: 'main' });
expect(await getBranchBase(fromFullRef.path, 'from-full-ref')).toEqual({ base: 'feat/form' });
});
const installPostCheckoutHook = (repo, script, executable = true) => {
const hookPath = path.join(repo, '.git', 'hooks', 'post-checkout');
fs.writeFileSync(hookPath, script);
@@ -7076,7 +7148,8 @@ describe.runIf(canRunGit())('getRangeDiff', () => {
// Two layers at the same commit leave nothing to tell them apart: the record stands.
runGit(repository, ['config', 'branch.company-refs.gh-merge-base', 'status-type']);
runGit(repository, ['branch', 'twin', 'identity-refresh']);
runGit(repository, ['branch', 'twin', 'status-type']);
runGit(repository, ['branch', '-f', 'twin', 'identity-refresh']);
expect(await getBranchBase(repository, 'company-refs')).toEqual({ base: 'status-type' });
});
@@ -7106,6 +7179,61 @@ describe.runIf(canRunGit())('getRangeDiff', () => {
expect(await getBranchBase(repository, 'upper')).toEqual({ base: 'middle' });
});
it('follows a terminal restack onto a branch the recorded parent never was', async () => {
const { repository } = createRepositoryWithRemote();
const commit = (name) => {
fs.writeFileSync(path.join(repository, `${name}.txt`), `${name}\n`);
runGit(repository, ['add', '.']);
runGit(repository, ['commit', '-m', name]);
};
commit('base');
runGit(repository, ['checkout', '-b', 'feat']);
commit('feat');
// Made on a feature branch, then moved onto the main line by hand.
runGit(repository, ['checkout', '-b', 'task', 'feat']);
runGit(repository, ['config', 'branch.task.gh-merge-base', 'feat']);
commit('task');
runGit(repository, ['checkout', 'next']);
commit('next-moves');
runGit(repository, ['checkout', 'task']);
runGit(repository, ['rebase', '--onto', 'next', 'feat']);
expect(await getBranchBase(repository, 'task')).toEqual({ base: 'next' });
// The branch it landed on moving on afterwards does not change that.
runGit(repository, ['checkout', 'next']);
commit('next-moves-again');
expect(await getBranchBase(repository, 'task')).toEqual({ base: 'next' });
// A branch made later at the commit it landed on never was its target.
runGit(repository, ['branch', 'backup', 'next~1']);
expect(await getBranchBase(repository, 'task')).toEqual({ base: 'next' });
// Neither is a parent that no longer exists.
runGit(repository, ['branch', '-D', 'feat']);
expect(await getBranchBase(repository, 'task')).toEqual({ base: 'next' });
runGit(repository, ['branch', '-D', 'backup']);
// Made on the main line, then moved onto a layer that branched off before the main line moved.
runGit(repository, ['checkout', '-b', 'layer', 'next~2']);
commit('layer');
runGit(repository, ['checkout', '-b', 'upper', 'next']);
runGit(repository, ['config', 'branch.upper.gh-merge-base', 'next']);
commit('upper');
runGit(repository, ['rebase', '--onto', 'layer', 'next']);
expect(await getBranchBase(repository, 'upper')).toEqual({ base: 'layer' });
// Rebased onto the newer tip of its own parent, the parent stands, with or without a record.
runGit(repository, ['checkout', 'next']);
commit('next-moves-third');
runGit(repository, ['checkout', 'task']);
runGit(repository, ['rebase', 'next']);
expect(await getBranchBase(repository, 'task')).toEqual({ base: 'next' });
runGit(repository, ['checkout', '-b', 'unrecorded', 'next']);
commit('unrecorded');
runGit(repository, ['checkout', 'next']);
commit('next-moves-fourth');
runGit(repository, ['checkout', 'unrecorded']);
runGit(repository, ['rebase', 'next']);
expect(await getBranchBase(repository, 'unrecorded')).toEqual({ base: 'next' });
});
it('keeps the parent of a branch that merged a sibling in from the side', async () => {
const { repository } = createRepositoryWithRemote();
const commit = (name) => {
+34 -37
View File
@@ -9,7 +9,7 @@ import { execFile, spawn } from 'child_process';
import { promisify } from 'util';
import { createRequire } from 'module';
import crypto from 'node:crypto';
import { fingerprintRemoteUrl } from '../source-control/url-redaction.js';
import { fingerprintRemoteUrl, isDiskPathRemoteUrl } from '../source-control/url-redaction.js';
import { readWorktreeDirectorySetting } from '../opencode/config-files.js';
import { readProjectStartCommand } from '../opencode/project-start-command.js';
import { normalizeGitOutputPath } from './output-path.js';
@@ -18,6 +18,7 @@ import { primaryWorktreeRootFromGitDir, unsupportedRepositoryRootReason } from '
import { resolveSshAuthSock } from './ssh-auth-sock.js';
import { randomUUID } from 'crypto';
import { worktreeBootstrapFailureMessage } from './worktree-bootstrap-storage.js';
import { BRANCH_CREATION_SOURCE_RE, findRestackedParent, isOwnRemoteCopy } from './branch-restack.js';
import type { SimpleGit, BranchSummary, FileStatusResult, RemoteWithRefs } from 'simple-git';
import type { ChildProcess } from 'node:child_process';
import type { Readable } from 'node:stream';
@@ -963,6 +964,9 @@ const resolveRemoteBranchRef = async (primaryWorktree: string, value: string) =>
if (raw.startsWith('refs/remotes/') || raw.startsWith('remotes/')) {
return parsed;
}
if (raw.startsWith('refs/')) {
return null;
}
const localRef = `refs/heads/${raw}`;
const localExists = await runGitCommand(primaryWorktree, ['show-ref', '--verify', '--quiet', localRef]);
@@ -3122,7 +3126,9 @@ async function readStatus(normalizedDirectory: string, lightMode: boolean) {
}
const selectBaseRefForUnpublished = async () => {
const candidates = [];
const parent = status.current ? await readBranchBase(git, repoRoot, status.current).then(({ base }) => base, () => null) : null;
const remotes = parent ? String(await git.raw(['remote']).catch(() => '')).split('\n').map((name) => name.trim()).filter(Boolean) : [];
const candidates = parent ? [parent, ...remotes.map((remote) => `${remote}/${parent}`)] : [];
const originHead = await git
.raw(['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'])
@@ -3552,8 +3558,6 @@ export async function getRangeFileVersions(directory: string, { base, head, path
return { original: '', modified: '' };
}
const BRANCH_CREATION_SOURCE_RE = /^branch: Created from (.+)$/;
export function parseBranchCreationSource(reflogText: string) {
const { source, rebased } = readBranchCreation(reflogText);
return rebased ? null : source;
@@ -3577,20 +3581,6 @@ function readBranchCreation(reflogText: string) {
return { source: null, rebased };
}
async function isOwnRemoteCopy(git: SimpleGit, source: string, branchName: string) {
const fullName = await git
.raw(['rev-parse', '--symbolic-full-name', source])
.then((value) => String(value || '').trim())
.catch(() => '');
if (!fullName.startsWith('refs/remotes/')) return false;
const upstream = await git
.raw(['rev-parse', '--symbolic-full-name', `refs/heads/${branchName}@{upstream}`])
.then((value) => String(value || '').trim())
.catch(() => '');
if (upstream && fullName === upstream) return true;
return fullName.slice('refs/remotes/'.length).split('/').slice(1).join('/') === branchName;
}
const branchParentKey = (branch: string) => `branch.${branch}.gh-merge-base`;
async function localBranchNameOf(directory: string, ref: string) {
@@ -3664,19 +3654,29 @@ export async function getBranchBase(directory: string, branch: string) {
}
const { git, repoRoot } = await createRepositoryGitContext(directory);
return readBranchBase(git, repoRoot, branchName);
}
async function readBranchBase(git: SimpleGit, repoRoot: string, branchName: string) {
const recordedParent = await git
.raw(['config', '--get', branchParentKey(branchName)])
.then((value) => String(value || '').trim())
.catch(() => '');
if (recordedParent && recordedParent !== branchName) {
const remotes = await git.raw(['remote']).then((value) => String(value || '').split('\n').map((name) => name.trim()).filter(Boolean)).catch(() => []);
const recordedRefs = [];
for (const ref of [`refs/heads/${recordedParent}`, ...remotes.map((remote) => `refs/remotes/${remote}/${recordedParent}`)]) {
const resolves = await git
.raw(['rev-parse', '--verify', '--quiet', ref])
.then((value) => Boolean(String(value || '').trim()))
.catch(() => false);
if (resolves) return { base: (await findNearerStackLayer(git, repoRoot, branchName, ref)) ?? recordedParent };
if (resolves) recordedRefs.push(ref);
}
const [recordedRef] = recordedRefs;
if (recordedRef) {
const restacked = await findRestackedParent(git, branchName, recordedRefs);
if (restacked) return { base: restacked };
return { base: (await findNearerStackLayer(git, repoRoot, branchName, recordedRef)) ?? recordedParent };
}
}
@@ -3687,26 +3687,19 @@ export async function getBranchBase(directory: string, branch: string) {
return { base: null };
}
const { source, rebased } = readBranchCreation(reflog);
if (!source || source === branchName) {
return { base: null };
}
const resolves = await git
.raw(['rev-parse', '--verify', '--quiet', source])
.then((value) => Boolean(String(value || '').trim()))
.catch(() => false);
if (!resolves) {
return { base: null };
}
if (await isOwnRemoteCopy(git, source, branchName)) {
return { base: null };
}
const { source: createdFrom, rebased } = readBranchCreation(reflog);
const resolves = createdFrom && createdFrom !== branchName && /^refs\/(heads|remotes)\//.test(await git
.raw(['rev-parse', '--symbolic-full-name', createdFrom])
.then((value) => String(value || '').trim())
.catch(() => ''));
const source = resolves && !(await isOwnRemoteCopy(git, createdFrom, branchName)) ? createdFrom : null;
const restacked = rebased ? await findRestackedParent(git, branchName, source ? [source] : []) : undefined;
if (restacked) return { base: restacked };
if (!source) return { base: null };
const nearer = await findNearerStackLayer(git, repoRoot, branchName, source);
if (nearer) return { base: nearer };
return { base: rebased ? null : source };
return { base: restacked === null ? null : source };
}
export async function getRangeFiles(directory: string, { base, head, includeWorkingTree = false }: RangeOptions = {}) {
@@ -5521,6 +5514,10 @@ async function attachGitWorktreeToCandidateWithoutRemoteRollback(context: Worktr
if (!checkoutRemoteName) {
checkoutRemoteName = await resolveCheckoutRemoteName(context.primaryWorktree, mode === 'existing' ? localBranch : startRef) ?? '';
}
for (const urlArgs of checkoutRemoteName ? [['remote', 'get-url', checkoutRemoteName], ['remote', 'get-url', '--push', checkoutRemoteName]] : []) {
const url = await runGitCommand(context.primaryWorktree, urlArgs);
if (url.success && isDiskPathRemoteUrl(url.stdout.trim())) checkoutRemoteName = '';
}
const branchNameConflict = (mode === 'new' || createdLocalBranch)
&& await branchNameClashesWithExistingRef(context.primaryWorktree, localBranch);
@@ -5560,7 +5557,7 @@ async function attachGitWorktreeToCandidateWithoutRemoteRollback(context: Worktr
throw error;
}
await publishWorktreeTopologyChange(context.primaryWorktree);
if (mode === 'new' && startRef && startRef !== 'HEAD') {
if (mode === 'new') {
const parent = parsedStartBranch ?? await localBranchNameOf(context.primaryWorktree, startRef);
await recordBranchParent(context.primaryWorktree, localBranch, parent);
}