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): preserve fork retry branches after remote deletion (#12524)

[._.]/ Adam Eivyfe74b31d0577
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index c3a711901e..8f807badc8 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -240,6 +240,7 @@ async function prepareRequestedWorktree({
baseBranch: detectedBase || undefined,
...(baseCommit ? { baseCommit } : {}),
existingBranch: resolveTaskRemoteBranch(task.metadata) || undefined,
+ ...(task.metadata?.existingBranch && task.metadata?.resumedFromAgentId ? { resumeBranch: existingBranch } : {}),
// Fork coordinates select the remote head, independent of the local branch name.
forkHead: forkHead || undefined,
planId: task.metadata?.planId || undefined,
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
index bb6c9c1b49..4ece555b5f 100644
--- a/server/services/cosMergeAdmission.js
+++ b/server/services/cosMergeAdmission.js
@@ -3,7 +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 { resolveTaskTargetBranch, resolveTaskRemoteBranch } from '../lib/taskTargetBranch.js';
import { randomUUID } from 'node:crypto';
import { getOriginInfo } from '../lib/gitRemote.js';
import { isPlainObject } from '../lib/objects.js';
@@ -195,19 +195,20 @@ 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 !== forkLocalBranch(target.branch, meta.forkHead) || !agent.metadata?.workspacePath) return false;
+ || resolveTaskRemoteBranch(meta) !== target.branch
+ || agent.metadata?.worktreeBranch !== resolveTaskTargetBranch(meta) || !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, forkLocalBranch(target.branch, meta.forkHead), repository)) return false;
+ if (!await checkoutOnBranch(agent.metadata.workspacePath, resolveTaskTargetBranch(meta), 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;
const { verifyForkReviewMergeTarget } = await import('./forkReviewMergeTarget.js');
const headSha = await verifyForkReviewMergeTarget({ target: target.fork, taskTarget: meta.reviewLoopForkTarget,
forkHead: meta.forkHead, sourceWorkspace: agent.metadata.sourceWorkspace,
- workspacePath: target.workspacePath, branch: target.branch });
+ workspacePath: target.workspacePath, branch: target.branch, localBranch: agent.metadata.worktreeBranch });
return headSha ? { headSha } : false;
}
diff --git a/server/services/cosMergeAdmission.reviewCoordinator.test.js b/server/services/cosMergeAdmission.reviewCoordinator.test.js
index 57a57f6b1a..19ba4ac5fe 100644
--- a/server/services/cosMergeAdmission.reviewCoordinator.test.js
+++ b/server/services/cosMergeAdmission.reviewCoordinator.test.js
@@ -160,6 +160,16 @@ describe('fork follow-up creation through workspace, registration and admission'
expect(execGh).toHaveBeenCalledWith(expect.arrayContaining(['--repo', 'github.com/example/repo']), 10000, expect.objectContaining({ cwd: '/repos/source' }));
});
+ it('admits an explicitly resumed pre-namespace fork branch after verifying its original push target', async () => {
+ const task = await launch({ forkHead });
+ task.metadata.existingBranch = 'feature/fix';
+ task.metadata.resumedFromAgentId = 'prior-agent';
+ f.branch = 'feature/fix';
+ f.state.agents['review-agent'].metadata.worktreeBranch = f.branch;
+ persist();
+ expect(await admission('acquire')).toMatchObject({ admitted: true });
+ });
+
it('accepts the alternate GitHub SSH endpoint for both source and worktree origins', async () => {
f.originHost = 'ssh.github.com';
f.remote = f.pushRemote = 'ssh://[email protected]:443/contributor/repo.git';
diff --git a/server/services/forkReviewMergeTarget.js b/server/services/forkReviewMergeTarget.js
index 208e80b9f5..b713957f82 100644
--- a/server/services/forkReviewMergeTarget.js
+++ b/server/services/forkReviewMergeTarget.js
@@ -57,13 +57,13 @@ export async function captureForkReviewMergeTarget({ prUrl, prBranch, forkHead,
}
/** Returns the live exact head only when task, registration, checkout and forge agree. */
-export async function verifyForkReviewMergeTarget({ target, taskTarget, forkHead, sourceWorkspace, workspacePath, branch }) {
+export async function verifyForkReviewMergeTarget({ target, taskTarget, forkHead, sourceWorkspace, workspacePath, branch, localBranch = forkLocalBranch(branch, forkHead) }) {
if (!target || target.version !== 1 || JSON.stringify(target) !== JSON.stringify(taskTarget)
|| target.branch !== branch || !coordinatesMatch(target.forkHead, forkHead)) return null;
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, forkLocalBranch(branch, forkHead));
+ const upstream = await readBranchUpstream(workspacePath, localBranch);
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/worktreeManager.fork.test.js b/server/services/worktreeManager.fork.test.js
index d2ed7c1293..06ac3d2393 100644
--- a/server/services/worktreeManager.fork.test.js
+++ b/server/services/worktreeManager.fork.test.js
@@ -61,5 +61,19 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('fork checkout and publication', () => {
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);
+ await removeWorktree('agent-retry', repo, retry.branchName, { merge: false, preserveBranchWithCommits: true });
+ await git(fork, 'update-ref', '-d', 'refs/heads/main');
+ await git(repo, 'fetch', '--prune', 'fork-contributor');
+ const orphaned = await createWorktree('agent-local-recovery', repo, 'task-fork', options);
+ expect(await git(orphaned.worktreePath, 'rev-parse', 'HEAD')).toBe(unpublished);
+ // Retry pointers written by older installs must recover their exact local commits.
+ await git(repo, 'branch', 'legacy/fix', unpublished);
+ const legacy = await createWorktree('agent-legacy', repo, 'task-legacy', {
+ ...options, existingBranch: 'legacy/fix', resumeBranch: 'legacy/fix',
+ });
+ expect(legacy.branchName).toBe('legacy/fix');
+ expect(await git(legacy.worktreePath, 'rev-parse', 'HEAD')).toBe(unpublished);
+ expect(await git(repo, 'rev-parse', 'main')).toBe(primaryHead);
+ expect(await git(origin, 'rev-parse', 'main')).toBe(primaryHead);
});
});
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 4f3a279025..e15566f7d1 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -594,9 +594,10 @@ export function shouldRefuseDefaultBranchMerge(currentBranch, defaultBranch) {
* @param {string} sourceWorkspace - the parent git repository
* @param {unknown} forkHead - `{ remoteUrl, ownerLogin }` from the PR read
* @param {string} branchName - the PR's head branch, as named in the fork
+ * @param {{requireRef?: boolean}} options - existing local recovery needs only the remote configuration
* @returns {Promise<string|null>} the fork remote's name, or null
*/
-async function ensureForkRemote(sourceWorkspace, forkHead, branchName) {
+async function ensureForkRemote(sourceWorkspace, forkHead, branchName, { requireRef = true } = {}) {
const coordinates = normalizeForkHead(forkHead);
if (!coordinates) return null;
const remoteName = forkRemoteName(coordinates.ownerLogin);
@@ -628,7 +629,7 @@ async function ensureForkRemote(sourceWorkspace, forkHead, branchName) {
const refExists = await execGit(['rev-parse', '--verify', `${remoteName}/${branchName}`], sourceWorkspace, { ignoreExitCode: true })
.then(r => r.exitCode === 0)
.catch(() => false);
- return refExists ? remoteName : null;
+ return refExists || !requireRef ? remoteName : null;
}
/**
@@ -654,6 +655,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 {string} options.resumeBranch - Exact preserved local branch from a retry, including pre-namespace fork branches
* @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
@@ -699,11 +701,13 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
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 branchName = options.resumeBranch || forkLocalBranch(remoteBranch, forkHead);
const localExists = (await execGit(['branch', '--list', branchName], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();
+ if (options.resumeBranch && !localExists) throw new Error(`Cannot resume missing local branch ${branchName}`);
+ // Fork identity takes precedence over local main/origin/main, but a preserved
+ // namespaced branch can recover even after its contributor deletes the remote ref.
+ const forkRemote = forkHead ? await ensureForkRemote(sourceWorkspace, forkHead, remoteBranch, { requireRef: !localExists }) : null;
+ if (forkHead && !forkRemote) throw new Error(`Cannot attach worktree to fork branch ${remoteBranch}: fork ref unavailable`);
if (localExists) {
// Preserve unpublished local work. Never reset an existing checkout branch.
await addWorktreeWithRetry(['worktree', 'add', worktreePath, branchName], sourceWorkspace);