Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(cos): isolate fork PR heads from local branch names (#12524)

[._.]/ Adam Eivyfbc9bd8dd5ee
diff --git a/server/lib/branchUpstreamGuard.js b/server/lib/branchUpstreamGuard.js
index 8f99f3ad15..0b33c3bad9 100644
--- a/server/lib/branchUpstreamGuard.js
+++ b/server/lib/branchUpstreamGuard.js
@@ -20,8 +20,9 @@
*
* The invariant this module enforces: an agent branch's upstream is either
* ABSENT or names its OWN ref (`refs/heads/<branch>` — what `git push -u origin
- * <branch>` records once the branch is published). Anything else is a
- * mis-aimed push waiting to happen.
+ * <branch>` records once the branch is published). A caller with verified fork
+ * coordinates can supply the original remote branch for a namespaced checkout.
+ * Anything else is a mis-aimed push waiting to happen.
*
* Enforcement is REPAIR-then-verify, not refuse: the fix is to drop the bogus
* upstream, and an untracked branch is exactly what makes `/do:pr`'s
@@ -115,12 +116,13 @@ export function isSafeBranchUpstream(branchName, merge) {
*
* @param {string} repo - repository path whose config holds the branch
* @param {string} branchName
+ * @param {{remoteBranch?: string}} options - explicit PR head when the local name is namespaced
* @returns {Promise<{safe: boolean, repaired: boolean, upstream: string}>}
*/
-export async function enforceSafeBranchUpstream(repo, branchName) {
+export async function enforceSafeBranchUpstream(repo, branchName, { remoteBranch = branchName } = {}) {
if (!repo || !branchName) return { safe: true, repaired: false, upstream: '' };
const { merge } = await readBranchUpstream(repo, branchName);
- if (isSafeBranchUpstream(branchName, merge)) return { safe: true, repaired: false, upstream: merge };
+ if (isSafeBranchUpstream(remoteBranch, merge)) return { safe: true, repaired: false, upstream: merge };
// Unreadable config is not a clean bill of health — the branch may well track
// the default branch, and nothing here verified otherwise.
if (merge === null) {
@@ -134,7 +136,7 @@ export async function enforceSafeBranchUpstream(repo, branchName) {
}).catch(() => {});
const after = await readBranchUpstream(repo, branchName);
- if (!isSafeBranchUpstream(branchName, after.merge)) {
+ if (!isSafeBranchUpstream(remoteBranch, after.merge)) {
const stillAt = after.merge === null ? 'an unreadable value' : after.merge;
throw new Error(`Refusing to hand off branch ${branchName}: its upstream still resolves to ${stillAt} — a config-derived push (git push <remote> HEAD:<merge>) would land there instead of opening a PR`);
}
diff --git a/server/lib/forkHead.js b/server/lib/forkHead.js
index ca00ce9de0..d9898ca396 100644
--- a/server/lib/forkHead.js
+++ b/server/lib/forkHead.js
@@ -110,3 +110,10 @@ export function forkHeadFromGithubPr(pr) {
if (!ownerLogin || !nameWithOwner || !origin) return null;
return normalizeForkHead({ remoteUrl: `${origin}/${nameWithOwner}.git`, ownerLogin });
}
+
+/** Keep a fork's checkout separate from same-named branches in the base repo. */
+export function forkLocalBranch(branch, forkHead) {
+ const coordinates = normalizeForkHead(forkHead);
+ const remote = coordinates && forkRemoteName(coordinates.ownerLogin);
+ return remote && branch ? `fork/${remote.slice(5)}/${branch}` : branch;
+}
diff --git a/server/lib/taskTargetBranch.js b/server/lib/taskTargetBranch.js
index b8786e3362..3f4ccf1e1c 100644
--- a/server/lib/taskTargetBranch.js
+++ b/server/lib/taskTargetBranch.js
@@ -1,3 +1,4 @@
+import { forkLocalBranch, resolveTaskForkHead } from './forkHead.js';
import { isTruthyMeta } from './metadataFlags.js';
/**
* Task target-branch metadata — one reader and one terminal-strip rule.
@@ -15,7 +16,7 @@ import { isTruthyMeta } from './metadataFlags.js';
* The legacy `existingBranch` wins when present; review-loop follow-ups fall back
* to their canonical PR-branch field.
*/
-export function resolveTaskTargetBranch(metadata) {
+function rawTaskTargetBranch(metadata) {
if (metadata?.existingBranch) return metadata.existingBranch;
if (isTruthyMeta(metadata?.reviewLoopFollowUp) && metadata?.reviewLoopPRBranch) {
return metadata.reviewLoopPRBranch;
@@ -31,3 +32,19 @@ export function resolveTaskTargetBranch(metadata) {
export function shouldStripTaskTargetBranch(metadata) {
return !!metadata?.resumedFromAgentId;
}
+
+/** Local checkout identity for ownership, recovery and cleanup. Retry pointers already name it. */
+export function resolveTaskTargetBranch(metadata) {
+ const branch = rawTaskTargetBranch(metadata);
+ if (metadata?.existingBranch && metadata?.resumedFromAgentId) return branch;
+ return forkLocalBranch(branch, resolveTaskForkHead(metadata));
+}
+
+/** Remote PR branch for fetching; a retry pointer stores the local namespaced branch. */
+export function resolveTaskRemoteBranch(metadata) {
+ const branch = rawTaskTargetBranch(metadata);
+ const fork = resolveTaskForkHead(metadata);
+ if (!branch || !fork || !metadata?.existingBranch || !metadata?.resumedFromAgentId) return branch;
+ const localPrefix = forkLocalBranch('__branch__', fork).slice(0, -'__branch__'.length);
+ return branch.startsWith(localPrefix) ? branch.slice(localPrefix.length) : branch;
+}
diff --git a/server/lib/taskTargetBranch.test.js b/server/lib/taskTargetBranch.test.js
index 68e11e43b0..062b9406ba 100644
--- a/server/lib/taskTargetBranch.test.js
+++ b/server/lib/taskTargetBranch.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from './taskTargetBranch.js';
+import { resolveTaskTargetBranch, resolveTaskRemoteBranch, shouldStripTaskTargetBranch } from './taskTargetBranch.js';
describe('task target branch', () => {
it('prefers a retry or legacy explicit pointer', () => {
@@ -32,3 +32,18 @@ describe('task target branch', () => {
expect(shouldStripTaskTargetBranch({ existingBranch: 'feature/x' })).toBe(false);
});
});
+
+// Local ownership and remote publication must remain distinct across persisted retries.
+it('keeps fork PR identity stable through retry pointers and terminal stripping', () => {
+ const metadata = { reviewLoopFollowUp: true, reviewLoopPRBranch: 'main',
+ forkHead: { remoteUrl: 'https://github.com/contributor/example.git', ownerLogin: 'contributor' } };
+ expect(resolveTaskTargetBranch(metadata)).toBe('fork/contributor/main');
+ expect(resolveTaskRemoteBranch(metadata)).toBe('main');
+ const retry = { ...metadata, existingBranch: 'fork/contributor/main', resumedFromAgentId: 'agent-before' };
+ expect(resolveTaskTargetBranch(retry)).toBe('fork/contributor/main');
+ expect(resolveTaskRemoteBranch(retry)).toBe('main');
+ expect(shouldStripTaskTargetBranch(retry)).toBe(true);
+ delete retry.existingBranch;
+ expect(resolveTaskTargetBranch(retry)).toBe('fork/contributor/main');
+ expect(resolveTaskRemoteBranch(retry)).toBe('main');
+});
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index ca42c741fe..c3a711901e 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -39,7 +39,7 @@ import { detectConflicts } from './taskConflict.js';
import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';
import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
-import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
+import { resolveTaskTargetBranch, resolveTaskRemoteBranch } from '../lib/taskTargetBranch.js';
import { resolveTaskForkHead } from '../lib/forkHead.js';
import { getAppWorkspace, getAppDataForTask } from './agentAppWorkspace.js';
import { createJiraTicketForTask } from './promptSections/appContext.js';
@@ -239,10 +239,8 @@ async function prepareRequestedWorktree({
const worktreeInfo = takeover?.worktreeInfo || await createWorktree(agentId, workspacePath, task.id, {
baseBranch: detectedBase || undefined,
...(baseCommit ? { baseCommit } : {}),
- existingBranch: existingBranch || undefined,
- // Only consulted when `existingBranch` names a FORK PR's head, which has no
- // `origin/<branch>` to attach to (#6064). Null for every other task, which
- // is the behavior that predates it.
+ existingBranch: resolveTaskRemoteBranch(task.metadata) || undefined,
+ // Fork coordinates select the remote head, independent of the local branch name.
forkHead: forkHead || undefined,
planId: task.metadata?.planId || undefined,
linkDependencies: !isolateDependencies,
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 9188b14755..b2c1a91099 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -444,6 +444,18 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {
findAdoptableWorktreeForBranch.mockResolvedValue(null);
});
+ it('recovers the namespaced fork holder without adopting the base repository main checkout', async () => {
+ findAdoptableWorktreeForBranch.mockResolvedValue({ path: DEAD_TREE, agentId: 'agent-dead' });
+ adoptWorktree.mockResolvedValue({ worktreePath: '/mock/worktrees/agent-new', branchName: 'fork/contributor/main', adopted: true });
+ const task = resumeTask({ existingBranch: 'fork/contributor/main',
+ forkHead: { remoteUrl: 'https://github.com/contributor/example.git', ownerLogin: 'contributor' } });
+ const result = await prepareAgentWorkspace({ agentId: 'agent-new', task });
+ expect(result.outcome).toBe('ready');
+ expect(findAdoptableWorktreeForBranch).toHaveBeenCalledWith(expect.any(String), 'fork/contributor/main', expect.any(Object));
+ expect(adoptWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), DEAD_TREE, 'fork/contributor/main');
+ expect(createWorktree).not.toHaveBeenCalled();
+ });
+
it('adopts the interrupted run’s worktree instead of creating a new one', async () => {
findAdoptableWorktreeForBranch.mockResolvedValue({ path: DEAD_TREE, agentId: 'agent-dead' });
adoptWorktree.mockResolvedValue({
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index ce8e69155f..07e44dbc33 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -24,7 +24,7 @@ import { isTruthyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { execGit } from '../lib/execGit.js';
import { isRetryHoldOwner, clearedRetryHoldMetadata } from '../lib/taskRetryHold.js';
-import { resolveTaskTargetBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';
+import { resolveTaskTargetBranch, resolveTaskRemoteBranch, shouldStripTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
import { detectForgeCli } from '../lib/gitForge.js';
import { normalizeForkHead } from '../lib/forkHead.js';
@@ -546,15 +546,19 @@ async function queueWorktreeMerge({ agentId, worktreeBranch, originalTask, descr
const preservedPrState = (pr) => (pr?.mergeHandoffQueued === true ? 'pending-merge handoff'
: pr?.autoMergeEnabled === true ? 'pending GitHub auto-merge' : 'unconfirmed PR recovery');
-async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranch, warnings, skipMerge }, disposition) {
+async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranch, warnings, skipMerge, originalTask }, disposition) {
// Default: auto-merge on success, just cleanup on failure.
// Review-loop follow-up agents pass skipMerge: true because gh pr merge already
// handled the merge upstream — re-merging the worktree branch into the local
// source workspace would duplicate the squashed commits.
const shouldMerge = disposition.merge;
if (skipMerge) {
- const pr = await import('./prProbe.js').then(({ probePrForBranch }) =>
- probePrForBranch(sourceWorkspace, worktreeBranch)).catch(() => null);
+ const meta = originalTask?.metadata;
+ const forkPrNumber = meta?.forkHead && (meta.reviewLoopPRNumber || meta.prRemediationNumber);
+ const pr = await import('./prProbe.js').then(({ probePrForBranch, probeChangeRequestState }) =>
+ meta?.forkHead
+ ? probeChangeRequestState(sourceWorkspace, { number: forkPrNumber, branch: resolveTaskRemoteBranch(meta) })
+ : probePrForBranch(sourceWorkspace, worktreeBranch)).catch(() => null);
if (!pr?.readable || (pr.prState && pr.prState !== 'MERGED')) {
// Failed/unreadable CI or unpublished commits need recovery, which needs this
// branch. Only a healthy handoff suppresses the post-cleanup audit.
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 3e386b78c8..2b817cef3f 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -209,9 +209,11 @@ vi.mock('./prWatcher.js', () => ({
// The `if-missing` net's OTHER half: a FAILED run may still have opened its PR
// before it died, and cleanup hands that orphan to the same follow-up machinery.
+const getPullRequestStateMock = vi.fn();
const findPullRequestForBranchMock = vi.fn().mockResolvedValue({ status: 'unavailable' });
vi.mock('./github.js', () => ({
- findPullRequestForBranch: (...args) => findPullRequestForBranchMock(...args)
+ findPullRequestForBranch: (...args) => findPullRequestForBranchMock(...args),
+ getPullRequestState: (...args) => getPullRequestStateMock(...args)
}));
// `deleteMergedRemoteCopy` reads the remote-tracking ref and runs its
@@ -1272,6 +1274,20 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
// --- skipMerge tests for review-loop follow-up cleanup ---
+ it.each(['OPEN', 'MERGED'])('cleans a fork local branch only after its exact PR is %s', async state => {
+ getAgent.mockResolvedValue(mockWorktreeAgent({ worktreeBranch: 'fork/contributor/main' }));
+ getPullRequestStateMock.mockResolvedValueOnce({ status: 'known', state });
+ const originalTask = { metadata: { reviewLoopFollowUp: true, reviewLoopPRNumber: 42, reviewLoopPRBranch: 'main',
+ forkHead: { remoteUrl: 'https://github.com/contributor/example.git', ownerLogin: 'contributor' } } };
+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'never', skipMerge: true, originalTask });
+ expect(getPullRequestStateMock).toHaveBeenCalledWith('42', expect.objectContaining({ cwd: '/mock/workspace' }));
+ expect(findPullRequestForBranchMock).not.toHaveBeenCalled();
+ if (state === 'MERGED') {
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'fork/contributor/main', { merge: false, preserveBranchWithCommits: false });
+ } else expect(removeWorktree).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+
it('should pass merge: false in the auto-merge fallback when skipMerge is true (review-loop follow-up cleanup)', async () => {
// The follow-up agent already merged via `gh pr merge`; re-merging the worktree
// branch into source workspace would duplicate the squashed commits.
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
index af5c4f24bf..bb6c9c1b49 100644
--- a/server/services/cosMergeAdmission.js
+++ b/server/services/cosMergeAdmission.js
@@ -3,6 +3,7 @@
* Sync, pregate, push and CI run outside the lease; it spans only the final
* verify-and-merge, so holds take seconds (#10803).
*/
+import { forkLocalBranch } from '../lib/forkHead.js';
import { randomUUID } from 'node:crypto';
import { getOriginInfo } from '../lib/gitRemote.js';
import { isPlainObject } from '../lib/objects.js';
@@ -194,12 +195,12 @@ async function verifiedReviewCoordinator(agent, repository) {
|| !isTruthyMeta(meta?.reviewLoopFollowUp) || isTruthyMeta(meta?.reviewLoopLeaveOpen)
|| resolvePrCompletion(meta) === PR_COMPLETIONS.LEAVE_OPEN || agent.metadata?.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN
|| target.url !== meta?.reviewLoopPRUrl || target.branch !== meta?.reviewLoopPRBranch
- || agent.metadata?.worktreeBranch !== target.branch || !agent.metadata?.workspacePath) return false;
+ || agent.metadata?.worktreeBranch !== forkLocalBranch(target.branch, meta.forkHead) || !agent.metadata?.workspacePath) return false;
const pr = parsePullRequestUrl(target.url);
if (!pr || repositoryKey({ host: pr.host, fullName: `${pr.owner}/${pr.repo}` }) !== repository
|| String(meta.reviewLoopPRNumber) !== String(pr.number)
|| meta.reviewLoopPRHost !== pr.host || meta.reviewLoopPROwner !== pr.owner || meta.reviewLoopPRRepo !== pr.repo) return false;
- if (!await checkoutOnBranch(agent.metadata.workspacePath, target.branch, repository)) return false;
+ if (!await checkoutOnBranch(agent.metadata.workspacePath, forkLocalBranch(target.branch, meta.forkHead), repository)) return false;
if (!meta.forkHead && !meta.reviewLoopForkTarget && !target.fork && !target.workspacePath) return true;
if (target.workspacePath !== agent.metadata.workspacePath || !agent.metadata.sourceWorkspace
|| agent.metadata.sourceWorkspace === target.workspacePath || target.fork?.url !== target.url) return false;
diff --git a/server/services/cosMergeAdmission.reviewCoordinator.test.js b/server/services/cosMergeAdmission.reviewCoordinator.test.js
index 7401255e1d..57a57f6b1a 100644
--- a/server/services/cosMergeAdmission.reviewCoordinator.test.js
+++ b/server/services/cosMergeAdmission.reviewCoordinator.test.js
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';
+import { forkLocalBranch } from '../lib/forkHead.js';
import { parsePullRequestUrl } from '../lib/gitForge.js';
const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, branch: 'feature/fix', workspaceRepo: 'example/repo', originHost: 'github.com', row: null, head: null, upstream: null, remote: null, pushRemote: null }));
@@ -37,7 +38,7 @@ vi.mock('../lib/execGit.js', () => ({ execGit: async args => {
vi.mock('./git.js', () => ({ parsePullRequestUrl, isRepo: async () => true, getRepoBranches: async () => ({ baseBranch: 'main' }) }));
vi.mock('./worktreeManager.js', () => ({ removeWorktree: vi.fn(), classifyWorktreeDirt: vi.fn(),
listWorktrees: async () => [], findAdoptableWorktreeForBranch: async () => null, releaseIdleSiblingNextHolder: async () => null,
- createWorktree: vi.fn(async (_agent, _workspace, _task, options) => ({ worktreePath: '/repos/worktree', branchName: options.existingBranch })),
+ createWorktree: vi.fn(async (_agent, _workspace, _task, options) => ({ worktreePath: '/repos/worktree', branchName: forkLocalBranch(options.existingBranch, options.forkHead) })),
}));
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
import { createWorktree } from './worktreeManager.js';
@@ -53,6 +54,7 @@ async function launch(overrides = {}) {
prUrl: 'https://github.com/example/repo/pull/42', prBranch: 'feature/fix',
sourceWorkspace: '/repos/source', reviewers: [], ...overrides });
const persisted = f.tasks[task.id];
+ f.branch = forkLocalBranch(f.row?.headRefName || 'feature/fix', overrides.forkHead);
const workspace = await prepareAgentWorkspace({ agentId: 'review-agent', task: persisted });
expect(workspace.outcome).toBe('ready');
const metadata = buildAgentRegistration({ task: persisted, provider: { id: 'test' }, modelSelection: {},
@@ -144,12 +146,14 @@ describe('fork follow-up creation through workspace, registration and admission'
// Another same-repository coordinator cannot enter while the fork holds.
const same = structuredClone(f.state.agents['review-agent']);
same.id = 'same'; same.taskId = 'same-task';
- same.metadata.reviewLoopMergeTarget = { url: f.row.url, branch: f.branch };
+ same.metadata.worktreeBranch = 'feature/fix';
+ same.metadata.reviewLoopMergeTarget = { url: f.row.url, branch: 'feature/fix' };
const sameTask = structuredClone(f.tasks[f.state.agents['review-agent'].taskId]);
sameTask.id = same.taskId; delete sameTask.metadata.forkHead; delete sameTask.metadata.reviewLoopForkTarget;
f.tasks[sameTask.id] = sameTask; f.state.agents.same = same; persist();
expect((await claimMergeAdmission({ agentId: 'same', action: 'acquire' })).admitted).toBe(false);
await admission('release', forkLease.token, { outcome: 'merged' });
+ f.branch = 'feature/fix';
const sameLease = await claimMergeAdmission({ agentId: 'same', action: 'acquire' });
expect(sameLease.admitted).toBe(true);
expect((await admission('acquire')).admitted).toBe(false);
diff --git a/server/services/forkReviewMergeTarget.js b/server/services/forkReviewMergeTarget.js
index 691ab0896c..208e80b9f5 100644
--- a/server/services/forkReviewMergeTarget.js
+++ b/server/services/forkReviewMergeTarget.js
@@ -1,7 +1,7 @@
/** Fork review authority is captured from the forge, then rechecked at admission. */
import { getOriginInfo, parseGitRemoteUrl } from '../lib/gitRemote.js';
import { detectForgeCli, parsePullRequestUrl } from '../lib/gitForge.js';
-import { forkHeadFromGithubPr, forkRemoteName, normalizeForkHead } from '../lib/forkHead.js';
+import { forkHeadFromGithubPr, forkRemoteName, normalizeForkHead, forkLocalBranch } from '../lib/forkHead.js';
import { execGit } from '../lib/execGit.js';
import { readBranchUpstream } from '../lib/branchUpstreamGuard.js';
import { safeJSONParse } from '../lib/jsonIo.js';
@@ -63,7 +63,7 @@ export async function verifyForkReviewMergeTarget({ target, taskTarget, forkHead
const live = await readTarget(target.url, sourceWorkspace);
if (!live || live.branch !== branch || live.baseBranch !== target.baseBranch
|| live.headRepositoryId !== target.headRepositoryId || !coordinatesMatch(live.forkHead, target.forkHead)) return null;
- const upstream = await readBranchUpstream(workspacePath, branch);
+ const upstream = await readBranchUpstream(workspacePath, forkLocalBranch(branch, forkHead));
const remote = forkRemoteName(target.forkHead.ownerLogin);
if (!remote || upstream.remote !== remote || upstream.merge !== `refs/heads/${branch}`) return null;
const read = args => execGit(args, workspacePath, { timeout: 10000 }).then(r => r.stdout.trim()).catch(() => null);
diff --git a/server/services/prRemediationFollowUp.js b/server/services/prRemediationFollowUp.js
index f31652b158..ef229a3601 100644
--- a/server/services/prRemediationFollowUp.js
+++ b/server/services/prRemediationFollowUp.js
@@ -42,8 +42,8 @@
import { emitLog } from './cosEvents.js';
import { addTask } from './cos.js';
-import { buildCiMergeGateSteps } from './promptSections/reviewLifecycle.js';
-import { normalizeForkHead } from '../lib/forkHead.js';
+import { buildCiMergeGateSteps, buildForkBranchInstructions } from './promptSections/reviewLifecycle.js';
+import { normalizeForkHead, forkLocalBranch } from '../lib/forkHead.js';
import { UNTRUSTED_PULL_REQUEST_NOTICE } from '../lib/promptFencing.js';
import { PR_WRITE_ACCESS } from '../lib/prHandbackPolicy.js';
@@ -51,13 +51,13 @@ import { PR_WRITE_ACCESS } from '../lib/prHandbackPolicy.js';
* The remediation procedure. `reason` names why the PR did not land, so the
* agent starts from the right end of the problem instead of re-deriving it.
*/
-function renderContext({ repoFullName, number, url, headRefName, authorLogin, reason, writeAccess }) {
+function renderContext({ repoFullName, number, url, headRefName, authorLogin, reason, writeAccess, forkHead }) {
// Both halves stay conditional: a same-repo head has no contributor who "left
// the branch writable", and saying otherwise puts a false claim about a real
// person into an operator-facing instruction.
const accessNote = writeAccess === PR_WRITE_ACCESS.OWN_REPO
? `The head branch \`${headRefName}\` lives in ${repoFullName} itself, so it is yours to push to and \`git push\` goes to origin.`
- : `@${authorLogin} left the head branch writable by maintainers ("Allow edits by maintainers"), and \`${headRefName}\` lives in their FORK. Your worktree's branch already tracks that fork, so a plain \`git push\` goes there — never re-point it at origin, and never open a second PR.`;
+ : `@${authorLogin} left the head branch writable by maintainers ("Allow edits by maintainers"), and \`${headRefName}\` lives in their FORK. Your worktree's branch already tracks that fork, so use the explicit fork push command below — never re-point it at origin, and never open a second PR.`;
// The shared gate owns everything from "wait for CI" through "confirm MERGED",
// including clearing conflicts, so step 3 stays scoped to the review itself.
const { lines: mergeGate } = buildCiMergeGateSteps(4, {
@@ -76,9 +76,10 @@ function renderContext({ repoFullName, number, url, headRefName, authorLogin, re
'## Procedure',
'',
`1. Read the review PortOS already posted: \`gh pr view ${number} --repo ${repoFullName} --comments\` and \`gh api repos/${repoFullName}/pulls/${number}/comments\`. Every finding is in scope: fix blocking findings, non-blocking findings, and nits alike, then resolve every review thread from that review after its feedback is addressed.`,
- `2. You are ALREADY in an isolated worktree with \`${headRefName}\` checked out — PortOS attached it for you. Do not check the PR out again, do not create another worktree, and do not switch branches. ${accessNote}`,
+ `2. You are ALREADY in an isolated worktree with \`${forkLocalBranch(headRefName, forkHead)}\` checked out — PortOS attached it for you. Do not check the PR out again, do not create another worktree, and do not switch branches. ${accessNote}`,
+ buildForkBranchInstructions(headRefName, forkHead),
'3. Fix everything the review asked for, including non-blocking findings and nits. Do not bundle refactors, unrelated cleanups, or your own review opinions onto a contributor\'s branch.',
- `4. Run the repo's own tests for the code you touched and confirm they pass, then commit with a message that says what you fixed and that it answers the review, and push to the PR's own branch (\`git push\` — its upstream is already the right remote). Never force-push over the contributor's commits unless a rebase you performed requires it, and never open a new PR.`,
+ `4. Run the repo's own tests for the code you touched and confirm they pass, then commit with a message that says what you fixed and that it answers the review, and push to the PR's own branch (use the explicit fork push command above for a fork, otherwise \`git push\`). Never force-push over the contributor's commits unless a rebase you performed requires it, and never open a new PR.`,
...mergeGate,
'',
'## Stop instead of merging if',
@@ -150,6 +151,7 @@ export async function spawnPrRemediationFollowUp({ app, repoFullName, pullReques
number,
url: pullRequest.url || `https://github.com/${repoFullName}/pull/${number}`,
headRefName,
+ forkHead: pullRequest.forkHead,
authorLogin,
reason: reason || 'the review did not clear it for an automatic merge',
writeAccess,
diff --git a/server/services/prRemediationFollowUp.test.js b/server/services/prRemediationFollowUp.test.js
index baaff751ab..d8f55ffb22 100644
--- a/server/services/prRemediationFollowUp.test.js
+++ b/server/services/prRemediationFollowUp.test.js
@@ -68,6 +68,8 @@ describe('spawnPrRemediationFollowUp', () => {
await spawn();
const { context } = addTaskMock.mock.calls[0][0];
+ expect(context).toContain('with `fork/contributor/contributor/update` checked out');
+ expect(context).toContain('git push fork-contributor HEAD:refs/heads/contributor/update');
expect(context).toContain('ALREADY in an isolated worktree');
expect(context).not.toContain('gh pr checkout');
expect(context).not.toContain('worktree add');
@@ -83,7 +85,7 @@ describe('spawnPrRemediationFollowUp', () => {
// A same-repo head has no contributor who "left the branch writable", so the
// prompt must not tell the agent one did — it names a real person.
it('describes push access from the head repository, not from a fork claim', async () => {
- await spawn({ writeAccess: 'own-repo' });
+ await spawn({ pullRequest: { ...PULL_REQUEST, forkHead: null }, writeAccess: 'own-repo' });
const ownRepo = addTaskMock.mock.calls[0][0].context;
expect(ownRepo).toContain('lives in o/r itself');
expect(ownRepo).not.toContain('Allow edits by maintainers');
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index fb69c49c1d..b86165a799 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -7,6 +7,7 @@ import { buildAutoMergeHandoffInstructions } from '../../lib/mergeGateContract.j
import { DEFAULT_REVIEWER, DEFAULT_REVIEW_STOP_MODE, REVIEW_UNAVAILABLE_REPORTING_NOTE, ZERO_REVIEWER_COVERAGE_NOTE, hasRequiredReviewer, isOptionalReviewer, isToolFreeReviewer, isProviderReviewer, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, reviewerEffortArgs, reviewerModelArg, reviewerModelFlag, resolveKeyedReviewers, buildReviewWithArgs, prioritizeToolFreeReviewers } from '../../lib/reviewerConfig.js';
import { oversizedBodyPointer } from '../../lib/slashdoInvocation.js';
import { detectForgeCli } from '../../lib/gitForge.js';
+import { forkLocalBranch, forkRemoteName, normalizeForkHead } from '../../lib/forkHead.js';
import { shellQuote } from '../../lib/shellQuote.js';
import { localApiBaseUrl } from '../../lib/networkExposure.js';
import { agentApiAuthNote, agentApiCurl } from '../../lib/agentApiToken.js';
@@ -750,6 +751,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const leaveOpen = isTruthyMeta(metadata.reviewLoopLeaveOpen);
const prUrl = metadata.reviewLoopPRUrl || '';
const prBranch = metadata.reviewLoopPRBranch || '';
+ const forkNote = buildForkBranchInstructions(prBranch, metadata.forkHead);
const prNumber = metadata.reviewLoopPRNumber ?? '';
const prOwner = metadata.reviewLoopPROwner ?? '';
const prRepo = metadata.reviewLoopPRRepo ?? '';
@@ -775,7 +777,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
// the whole job is CI-gate → fix → merge. Branch before any reviewer defaulting
// below, which would otherwise resolve the empty list back to `[copilot]`.
if (isMergeOnlyFollowUp(metadata)) {
- return buildMergeFollowUpSection({
+ return forkNote + buildMergeFollowUpSection({
prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,
mergeGateForge: forge.mergeGateForge, inlineWorkflowStep, localReviewers: localPhaseReviewerList, localReviewRequired: localPhaseReviewRequired,
selfReview: isSelfReviewFollowUp(metadata),
@@ -940,7 +942,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const opening = phase.opening(phaseCtx);
if (verbose && phase.supportsVerbose) {
- return `
+ return forkNote + `
${heading}
${opening}
@@ -976,7 +978,7 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
const hardStopNote = optionalConfiguredReviewers.length
? `**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, ${phase.hardStopAction(forge)}. An optional reviewer may end with an inconclusive result without blocking, but an unresolved accepted finding or rejection, failed build/test, or push failure still blocks.`
: `**Hard stop:** if a reviewer's loop is not converged after 10 rounds, ${phase.hardStopAction(forge)}.`;
- return [
+ return [forkNote,
heading,
phase.compactOpening(phaseCtx),
`**Reviewers (in order)**: ${reviewerLabel}${equiv}.`,
@@ -1273,3 +1275,10 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '
...prDetails,
].join('\n');
}
+
+/** Explicit pushes preserve fork destinations without changing repository-wide Git defaults. */
+export function buildForkBranchInstructions(branch, forkHead) {
+ const fork = normalizeForkHead(forkHead);
+ if (!fork || !branch) return '';
+ return `Fork checkout: local branch \`${forkLocalBranch(branch, fork)}\` tracks the contributor's \`${branch}\`. For every push use \`git push ${shellQuote(forkRemoteName(fork.ownerLogin))} ${shellQuote(`HEAD:refs/heads/${branch}`)}\` (add --force-with-lease only when the workflow authorizes a rebase). This destination applies to all push steps below. Keep this local branch checked out; never push it to origin or delete the contributor's remote branch.\n\n`;
+}
diff --git a/server/services/promptSections/reviewLifecycle.test.js b/server/services/promptSections/reviewLifecycle.test.js
index b6593ad6a8..7a334ea2d5 100644
--- a/server/services/promptSections/reviewLifecycle.test.js
+++ b/server/services/promptSections/reviewLifecycle.test.js
@@ -200,3 +200,11 @@ describe('public review CLI procedure sanitization', () => {
expect(body).toContain('Reviewer unavailable');
});
});
+
+it.each([{}, { verbose: true }, { reviewLoopMergeOnly: true }])('keeps fork push destinations explicit for review and merge variants %j', options => {
+ const section = buildReviewLoopFollowUpSection({ ...metadata, ...options, reviewLoopPRBranch: 'main',
+ forkHead: { remoteUrl: 'https://github.com/contributor/example.git', ownerLogin: 'contributor' } }, options);
+ expect(section).toContain('local branch `fork/contributor/main`');
+ expect(section).toContain('git push fork-contributor HEAD:refs/heads/main');
+ expect(section).toContain('never push it to origin or delete the contributor');
+});
diff --git a/server/services/worktreeManager.fork.test.js b/server/services/worktreeManager.fork.test.js
new file mode 100644
index 0000000000..d2ed7c1293
--- /dev/null
+++ b/server/services/worktreeManager.fork.test.js
@@ -0,0 +1,65 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { mkdir, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { mockPathsDataRoot, mockTestIdentity } from '../lib/mockPathsDataRoot.js';
+import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
+import { execGit } from '../lib/execGit.js';
+
+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-worktree-fork-' });
+vi.mock('../lib/fileUtils.js', async importOriginal => makeProxy(await importOriginal()));
+vi.mock('./instanceIdentity.js', () => mockTestIdentity());
+const { PATHS } = await import('../lib/fileUtils.js');
+const { createWorktree, removeWorktree } = await import('./worktreeManager.js');
+afterAll(cleanup);
+
+const git = async (repo, ...args) => (await execGit(args, repo)).stdout.trim();
+const commit = async (repo, file) => {
+ await writeFile(join(repo, file), `${file}\n`);
+ await git(repo, 'add', file);
+ await git(repo, 'commit', '-m', file);
+ return git(repo, 'rev-parse', 'HEAD');
+};
+
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('fork checkout and publication', () => {
+ it('isolates fork main from checked-out main, publishes to the fork, and preserves local retry commits', async () => {
+ const repo = join(tempRoot, 'source');
+ const origin = join(tempRoot, 'origin.git');
+ const fork = join(tempRoot, 'fork.git');
+ const contributor = join(tempRoot, 'contributor');
+ await materializeGitRepo(repo);
+ await git(repo, 'clone', '--bare', repo, origin);
+ await git(repo, 'remote', 'add', 'origin', origin);
+ await git(repo, 'clone', '--bare', repo, fork);
+ await materializeGitRepo(contributor);
+ await git(contributor, 'remote', 'add', 'origin', fork);
+ const forkHead = await commit(contributor, 'contribution.txt');
+ await git(contributor, 'push', 'origin', 'main');
+ const primaryHead = await commit(repo, 'primary-only.txt');
+ await git(repo, 'push', 'origin', 'main');
+ await mkdir(PATHS.worktrees, { recursive: true });
+ const options = { existingBranch: 'main', forkHead: { remoteUrl: fork, ownerLogin: 'contributor' }, linkDependencies: false };
+
+ const attached = await createWorktree('agent-fork', repo, 'task-fork', options);
+ expect(attached.branchName).toBe('fork/contributor/main');
+ expect(await git(attached.worktreePath, 'rev-parse', 'HEAD')).toBe(forkHead);
+ expect(await git(repo, 'symbolic-ref', '--short', 'HEAD')).toBe('main');
+ expect(await git(repo, 'rev-parse', 'main')).toBe(primaryHead);
+ expect(await git(attached.worktreePath, 'config', 'branch.fork/contributor/main.merge')).toBe('refs/heads/main');
+ expect(await git(attached.worktreePath, 'config', 'branch.fork/contributor/main.pushRemote')).toBe('fork-contributor');
+ const published = await commit(attached.worktreePath, 'review-fix.txt');
+ // This is the exact explicit destination handed to agents by both prompts.
+ await git(attached.worktreePath, 'push', 'fork-contributor', 'HEAD:refs/heads/main');
+ expect(await git(fork, 'rev-parse', 'main')).toBe(published);
+ expect(await git(origin, 'rev-parse', 'main')).toBe(primaryHead);
+ await git(repo, 'branch', 'same-repo-head', 'main');
+ const sameRepo = await createWorktree('agent-same-repo', repo, 'task-same', { existingBranch: 'same-repo-head', linkDependencies: false });
+ expect(sameRepo.branchName).toBe('same-repo-head');
+ expect(await git(sameRepo.worktreePath, 'rev-parse', 'HEAD')).toBe(primaryHead);
+ const unpublished = await commit(attached.worktreePath, 'retry-work.txt');
+ await removeWorktree('agent-fork', repo, attached.branchName, { merge: false, preserveBranchWithCommits: true });
+ const retry = await createWorktree('agent-retry', repo, 'task-fork', options);
+ expect(await git(retry.worktreePath, 'rev-parse', 'HEAD')).toBe(unpublished);
+ expect(await git(fork, 'rev-parse', 'main')).toBe(published);
+ expect(await git(origin, 'rev-parse', 'main')).toBe(primaryHead);
+ });
+});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 5e2620349b..4f3a279025 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -20,7 +20,7 @@ import { execGit } from '../lib/execGit.js';
import { clearStaleGitLock } from '../lib/gitStaleLock.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
-import { forkRemoteName, normalizeForkHead } from '../lib/forkHead.js';
+import { forkRemoteName, normalizeForkHead, forkLocalBranch } from '../lib/forkHead.js';
import { isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';
import { ensureInstanceId } from './instanceIdentity.js';
@@ -426,8 +426,16 @@ export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log =
* `deleteBranch` is false on the attach paths — that branch pre-dates this add
* and may hold real commits, the same distinction `cleanupOrphanBranch` makes.
*/
-async function enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch }) {
- return enforceSafeBranchUpstream(sourceWorkspace, branchName).catch(async (err) => {
+async function enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch, remoteBranch = branchName, forkRemote = null }) {
+ const configure = async () => {
+ if (forkRemote) {
+ await execGit(['config', `branch.${branchName}.remote`, forkRemote], worktreePath);
+ await execGit(['config', `branch.${branchName}.merge`, `refs/heads/${remoteBranch}`], worktreePath);
+ await execGit(['config', `branch.${branchName}.pushRemote`, forkRemote], worktreePath);
+ }
+ return enforceSafeBranchUpstream(sourceWorkspace, branchName, { remoteBranch });
+ };
+ return configure().catch(async (err) => {
const undone = await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
label: `Undoing worktree add for ${branchName} after an unsafe upstream`,
log: 'all',
@@ -636,10 +644,8 @@ async function ensureForkRemote(sourceWorkspace, forkHead, branchName) {
* branch instead of creating a new one — used for the Copilot review-loop follow-up
* agent that needs to address comments on a PR branch the previous agent just pushed.
*
- * That branch is resolved local → `origin/<branch>` → `options.forkHead`. The third
- * step is what makes an EXTERNAL contribution reachable: a fork PR's head has no
- * `origin/<branch>` at all, so without it every "work on this PR's branch" path
- * failed at workspace prep for exactly the PRs external contributors open (#6064).
+ * Fork heads resolve only through their fork and use a namespaced local branch.
+ * Same-repository heads retain local → origin resolution.
*
* @param {string} agentId - The agent identifier (used for branch/directory naming)
* @param {string} sourceWorkspace - The original git repository path
@@ -648,7 +654,7 @@ async function ensureForkRemote(sourceWorkspace, forkHead, branchName) {
* @param {string} options.baseBranch - Branch to base the worktree on (auto-detected if omitted)
* @param {string} options.baseCommit - Exact server-owned source commit for a fresh Deep resume
* @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy)
- * @param {{remoteUrl: string, ownerLogin: string}} options.forkHead - Where `existingBranch` lives when it is a FORK PR's head, which has no `origin/<branch>`. Consulted only after the local and origin lookups both miss; omitting it preserves today's exact behavior, error message included.
+ * @param {{remoteUrl: string, ownerLogin: string}} options.forkHead - Where `existingBranch` lives for a fork PR; checked out as fork/<owner>/<branch>.
* @param {string} options.planId - PLAN.md item slug ID — when provided, spliced into the branch name as `cos/<taskId>/<planId>/<agentId>` so other agents can detect this item is in flight by scanning branches/PRs
* @param {boolean} options.linkDependencies - Link source dependencies unless explicitly false
* @returns {{ worktreePath: string, branchName: string, baseBranch: string|null, existingBranch?: boolean }} paths for the new worktree
@@ -690,44 +696,25 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
// Existing-branch path: attach the worktree to a branch that already lives on
// the remote (e.g. the PR branch from the previous agent in a review loop).
if (options.existingBranch) {
- const branchName = options.existingBranch;
+ const remoteBranch = options.existingBranch;
+ const forkHead = normalizeForkHead(options.forkHead);
+ if (options.forkHead && !forkHead) throw new Error('Invalid fork head coordinates');
+ const branchName = forkLocalBranch(remoteBranch, forkHead);
+ // Fork identity takes precedence even when local main/origin/main exists.
+ const forkRemote = forkHead ? await ensureForkRemote(sourceWorkspace, forkHead, remoteBranch) : null;
+ if (forkHead && !forkRemote) throw new Error(`Cannot attach worktree to fork branch ${remoteBranch}: fork ref unavailable`);
const localExists = (await execGit(['branch', '--list', branchName], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();
if (localExists) {
+ // Preserve unpublished local work. Never reset an existing checkout branch.
await addWorktreeWithRetry(['worktree', 'add', worktreePath, branchName], sourceWorkspace);
} else {
- // No local copy — we need a remote ref. If `git fetch` failed AND the
- // remote ref isn't available, fail loudly rather than emit a confusing
- // "couldn't find branch" git error.
- const remoteExists = await execGit(['rev-parse', '--verify', `origin/${branchName}`], sourceWorkspace, { ignoreExitCode: true })
- .then((r) => r.exitCode === 0)
- .catch(() => false);
- // Third and last resolve step: a FORK PR's head lives in the contributor's
- // repository, so `origin/<branch>` legitimately does not exist. Reached
- // only when the caller supplied coordinates AND the two lookups above
- // missed, so a caller that passes no `forkHead` still gets the exact
- // error below rather than a new code path (#6064).
- const forkRemote = remoteExists ? null : await ensureForkRemote(sourceWorkspace, options.forkHead, branchName);
- if (!remoteExists && !forkRemote) {
- throw new Error(`Cannot attach worktree to ${branchName}: branch missing locally and origin/${branchName} unavailable${fetchSucceeded ? '' : ' (fetch failed)'}`);
- }
- // The start point decides the branch's upstream, and on the fork path that
- // is the whole point: tracking `<fork-remote>/<branch>` is what sends a
- // later `git push` to the CONTRIBUTOR's fork. Tracking origin here would
- // push their commits into the upstream repository instead — the #4172
- // failure mode, one remote over.
- const startPoint = forkRemote ? `${forkRemote}/${branchName}` : `origin/${branchName}`;
- // Use -B (force-create) so we don't fail if a stale local ref exists.
- // Attach path re-uses an existing branch, so no orphan-branch cleanup on failure.
- await addWorktreeWithRetry(['worktree', 'add', '-B', branchName, worktreePath, startPoint], sourceWorkspace);
- if (forkRemote) console.log(`🍴 Attached ${branchName} from fork remote ${forkRemote} (no origin/${branchName})`);
+ const startPoint = forkRemote ? `${forkRemote}/${remoteBranch}` : `origin/${remoteBranch}`;
+ const remoteExists = forkRemote || await execGit(['rev-parse', '--verify', startPoint], sourceWorkspace, { ignoreExitCode: true })
+ .then(r => r.exitCode === 0).catch(() => false);
+ if (!remoteExists) throw new Error(`Cannot attach worktree to ${branchName}: branch missing locally and origin/${branchName} unavailable${fetchSucceeded ? '' : ' (fetch failed)'}`);
+ await addWorktreeWithRetry(['worktree', 'add', ...(forkRemote ? ['--no-track', '-b'] : ['-B']), branchName, worktreePath, startPoint], sourceWorkspace);
}
- // Re-attaching a branch a PREVIOUS run created — which, before #4172, may
- // have been left tracking `refs/heads/main`. Repair it before the agent (and
- // its `/do:pr`) touches it. The guard's invariant is on the `merge` REF, not
- // on the remote, so `origin/<branchName>` and `<fork-remote>/<branchName>`
- // both pass untouched — which is required: dropping the fork upstream would
- // aim a config-derived push back at origin.
- await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch: false });
+ await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch: false, remoteBranch, forkRemote });
if (options.linkDependencies === false) {
await unlinkWorktreeDependencies(sourceWorkspace, worktreePath);
} else {
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index c4c6e34ae0..3dba413b51 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -1492,11 +1492,10 @@ describe('createWorktree upstream safety (#4172)', () => {
.toEqual([['remote', 'add', 'fork-contributor', 'https://github.com/contributor/widget.git']]);
expect(argsFor(a => a[0] === 'fetch' && a[1] === 'fork-contributor'))
.toEqual([['fetch', 'fork-contributor', 'contributor/fix-thing']]);
- // The start point is the whole point: it is what makes the branch track the
- // CONTRIBUTOR's fork, so a later `git push` lands there and not on upstream.
+ // The fork is the start point even though the local checkout has its own name.
const [add] = argsFor(a => a[0] === 'worktree' && a[1] === 'add');
expect(add).toEqual([
- 'worktree', 'add', '-B', 'contributor/fix-thing',
+ 'worktree', 'add', '--no-track', '-b', 'fork/contributor/contributor/fix-thing',
join(PATHS.worktrees, 'agent-fork'), 'fork-contributor/contributor/fix-thing',
]);
// ...and the #4172 guard must not "repair" that fork upstream away.
@@ -1532,8 +1531,7 @@ describe('createWorktree upstream safety (#4172)', () => {
});
it('still throws today\'s exact error when no forkHead is supplied', async () => {
- // The fork path is a third FALLBACK: a caller that passes no coordinates
- // must get the pre-#6064 behavior, message included.
+ // A caller without fork coordinates retains the origin-only behavior.
scriptGit({ originHasBranch: false });
await expect(createWorktree('agent-fork4', '/repo', 'task-fork4', { existingBranch: 'contributor/fix-thing' }))
@@ -1543,7 +1541,7 @@ describe('createWorktree upstream safety (#4172)', () => {
expect(argsFor(a => a[0] === 'worktree' && a[1] === 'add')).toHaveLength(0);
});
- it('falls back to the origin-only error when the fork fetch leaves no ref', async () => {
+ it('refuses attachment when the fork fetch leaves no ref', async () => {
// A fetch that "succeeded" but produced no remote-tracking ref must not send
// `worktree add` at a start point git would resolve somewhere else.
scriptGit({ originHasBranch: false, forkRefResolves: false });
@@ -1551,20 +1549,21 @@ describe('createWorktree upstream safety (#4172)', () => {
await expect(createWorktree('agent-fork5', '/repo', 'task-fork5', {
existingBranch: 'contributor/fix-thing',
forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },
- })).rejects.toThrow(/branch missing locally and origin\/contributor\/fix-thing unavailable/);
+ })).rejects.toThrow(/fork ref unavailable/);
expect(argsFor(a => a[0] === 'worktree' && a[1] === 'add')).toHaveLength(0);
});
- it('never consults the fork when origin already has the branch', async () => {
+ it('uses the fork even when origin already has the branch', async () => {
await createWorktree('agent-fork6', '/repo', 'task-fork6', {
existingBranch: 'shared/branch',
forkHead: { remoteUrl: 'https://github.com/contributor/widget.git', ownerLogin: 'contributor' },
});
- expect(argsFor(a => a[0] === 'remote')).toHaveLength(0);
+ expect(argsFor(a => a[0] === 'remote')).not.toHaveLength(0);
const [add] = argsFor(a => a[0] === 'worktree' && a[1] === 'add');
- expect(add).toContain('origin/shared/branch');
+ expect(add).toContain('fork-contributor/shared/branch');
+ expect(add).toContain('fork/contributor/shared/branch');
});
it('checks the re-attached branch of an existingBranch worktree too', async () => {