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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop CoS agent worktree branches from tracking the default branch (#4172)
[._.]/ Adam Eivyddc75999f6ac
diff --git a/.changelog/next/fixed-issue-4172.md b/.changelog/next/fixed-issue-4172.mdnew file mode 100644index 0000000000..0df6e67e45--- /dev/null+++ b/.changelog/next/fixed-issue-4172.md@@ -0,0 +1 @@+- CoS agent worktree branches are no longer created tracking the default branch — `git worktree add` now passes `--no-track`, and a new upstream guard repairs any branch whose `branch.<name>.merge` names a foreign ref, so a config-derived `git push HEAD:<merge>` can't land agent work straight on main instead of opening a PR (#4172)diff --git a/server/lib/README.md b/server/lib/README.mdindex 9cf6615772..537beebfaf 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -203,6 +203,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. || `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. || `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (Malloc-stripped env, 5s timeout) returning the absolute binary path or `null`; the shared discovery probe behind `findYtDlp`/`findFfmpeg`/`detectPython`/voice `which`. `whichFirstSync(name)` — same contract without the await, for callers resolving a binary mid-spawn (`detectPythonSync`). |+| `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. || `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. || `pythonSetup.js` | Python venv / runner setup helpers. || `vttTranscript.js` | WebVTT/SRT → readable prose. `vttToPlainText(vtt)` (paragraph-joined transcript), `vttToLines(vtt)` (cleaned caption lines), `cleanCaptionLine(line)`. Collapses YouTube auto-captions' rolling repetition and strips inline `<c>`/timestamp markup. Used by the brain YouTube ingest. |diff --git a/server/lib/branchUpstreamGuard.js b/server/lib/branchUpstreamGuard.jsnew file mode 100644index 0000000000..dbbc3ab59b--- /dev/null+++ b/server/lib/branchUpstreamGuard.js@@ -0,0 +1,122 @@+/**+ * Agent-branch upstream guard (#4172).+ *+ * `git worktree add -b <branch> <path> origin/main` does NOT leave the new+ * branch untracked. With git's default `branch.autoSetupMerge=true`, branching+ * off a REMOTE-TRACKING ref records:+ *+ * branch.<name>.remote = origin+ * branch.<name>.merge = refs/heads/main <-- not the branch's own ref+ *+ * That config is load-bearing for push helpers. `/do:pr` deliberately derives+ * its push destination from it rather than from the local branch name —+ * `git push "$PUSH_REMOTE" "HEAD:$PUSH_BRANCH"` — so a branch whose upstream is+ * named differently from the branch still pushes to the right ref. With+ * `merge=refs/heads/main` that same guard resolves to `HEAD:refs/heads/main`+ * and pushes the agent's work STRAIGHT TO MAIN, skipping the PR entirely while+ * reporting success. The existing carve-outs don't catch it: the branch *has*+ * an upstream (so the "no upstream" skip doesn't apply) and the remote is a+ * real remote, not `.` (so the local-upstream guard doesn't fire).+ *+ * 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.+ *+ * 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+ * `git push -u origin <branch>` path correct. Repair is logged loudly because a+ * branch that reached this state means a creation path forgot `--no-track`.+ * `enforceSafeBranchUpstream` throws only when the repair itself doesn't take,+ * because at that point every downstream push helper is still aimed at the+ * wrong ref and handing the worktree to an agent would risk the default branch.+ *+ * Prevention lives at the creation sites (`--no-track` on every+ * `git worktree add -b … origin/<base>` in `services/worktreeManager.js`); this+ * guard is the backstop that also repairs branches created before the fix, or+ * by a path that doesn't route through the manager.+ */++import { execGit } from './execGit.js';++/** Bound on every git call here — this sits on the agent-spawn path. */+const GIT_TIMEOUT_MS = 10_000;++/**+ * Read a branch's configured upstream as raw config values. Both fields are+ * `''` when unset (an untracked branch), never null/undefined, so callers get+ * one shape to reason about. Non-throwing: an unreadable repo reads as unset.+ *+ * @param {string} repo - repository (or worktree) path to read config from+ * @param {string} branchName+ * @returns {Promise<{remote: string, merge: string}>}+ */+export async function readBranchUpstream(repo, branchName) {+ if (!repo || !branchName) return { remote: '', merge: '' };+ const read = async (key) => {+ const result = await execGit(+ ['config', '--get', `branch.${branchName}.${key}`],+ repo,+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },+ ).catch(() => null);+ // `--get` exits 1 for an unset key, which is the common case, not an error.+ return result && result.exitCode === 0 ? (result.stdout || '').trim() : '';+ };+ const [remote, merge] = await Promise.all([read('remote'), read('merge')]);+ return { remote, merge };+}++/**+ * The invariant, as a pure predicate: an upstream is safe when it is ABSENT or+ * names the branch's OWN ref. Deliberately NOT "is it the default branch" — a+ * branch tracking any ref other than its own is a push aimed somewhere the+ * branch name doesn't say, and the default branch is only the most destructive+ * instance of that. Accepts the short form (`main`) as well as the fully+ * qualified `refs/heads/main` that git actually writes, so a hand-edited config+ * is judged the same way.+ *+ * @param {string} branchName+ * @param {string} merge - the `branch.<name>.merge` value+ */+export function isSafeBranchUpstream(branchName, merge) {+ if (!merge) return true;+ return merge === `refs/heads/${branchName}` || merge === branchName;+}++/**+ * Assert — and, when violated, repair — the upstream invariant for a branch a+ * CoS agent is about to be handed.+ *+ * Returns `{ safe: true, repaired: false }` for the overwhelmingly common+ * healthy case, `{ safe: true, repaired: true, upstream }` when a bogus upstream+ * was dropped (with the offending ref carried so the caller can log what it+ * found), and THROWS when the branch still tracks a foreign ref after the+ * repair — the loud failure, because a push helper would land on it.+ *+ * Unlike the rest of the git-boundary helpers this one is allowed to throw: it+ * runs during worktree creation (inside `createWorktree`'s promise chain, whose+ * callers already handle a rejected create), and silently handing back a+ * worktree whose branch pushes to `main` is precisely the failure it exists to+ * prevent.+ *+ * @param {string} repo - repository path whose config holds the branch+ * @param {string} branchName+ * @returns {Promise<{safe: boolean, repaired: boolean, upstream: string}>}+ */+export async function enforceSafeBranchUpstream(repo, 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 };++ console.error(`❌ Branch ${branchName} tracks ${merge} instead of its own ref — dropping the upstream so a config-derived push can't land there (#4172)`);+ await execGit(['branch', '--unset-upstream', branchName], repo, {+ ignoreExitCode: true,+ timeout: GIT_TIMEOUT_MS,+ }).catch(() => {});++ const after = await readBranchUpstream(repo, branchName);+ if (!isSafeBranchUpstream(branchName, after.merge)) {+ throw new Error(`Refusing to hand off branch ${branchName}: its upstream still resolves to ${after.merge} — a config-derived push (git push <remote> HEAD:<merge>) would land there instead of opening a PR`);+ }+ return { safe: true, repaired: true, upstream: merge };+}diff --git a/server/lib/branchUpstreamGuard.test.js b/server/lib/branchUpstreamGuard.test.jsnew file mode 100644index 0000000000..9c4a2cadf1--- /dev/null+++ b/server/lib/branchUpstreamGuard.test.js@@ -0,0 +1,185 @@+/**+ * Agent-branch upstream guard tests (#4172).+ *+ * Run against REAL git repositories in a temp dir, not a mocked `execGit`. The+ * entire premise of the bug is a git DEFAULT — `branch.autoSetupMerge` quietly+ * recording `merge=refs/heads/main` on a branch created from `origin/main` — and+ * a mock that returns whatever the test author believed `git config` prints+ * would assert the author's belief rather than git's behavior. The first test+ * below is the bypass probe: it reproduces the bug with the un-fixed command, so+ * the flag the fix adds is demonstrably load-bearing.+ */++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { execGit } from './execGit.js';+import {+ enforceSafeBranchUpstream,+ isSafeBranchUpstream,+ readBranchUpstream,+} from './branchUpstreamGuard.js';++let repo;+let scratch;++async function commit(subject) {+ await writeFile(join(repo, `${subject.replace(/\W+/g, '-')}.txt`), subject);+ await execGit(['add', '-A'], repo);+ await execGit(['commit', '-m', subject], repo);+}++/** A real bare remote on disk — no network, no mocked remote-tracking refs. */+async function addOrigin() {+ const remote = join(scratch, 'origin.git');+ await execGit(['init', '--bare', '-b', 'main', remote], scratch);+ await execGit(['remote', 'add', 'origin', remote], repo);+ await execGit(['push', '-u', 'origin', 'main'], repo);+}++/** The `branch.<name>.merge` a config-derived push (`HEAD:<merge>`) would target. */+const mergeRef = async (branch) => (await readBranchUpstream(repo, branch)).merge;++beforeEach(async () => {+ scratch = await mkdtemp(join(tmpdir(), 'portos-branch-upstream-'));+ repo = join(scratch, 'primary');+ await execGit(['init', '-b', 'main', repo], scratch);+ // Local identity so the suite doesn't depend on (or read) the host's git config.+ await execGit(['config', 'user.email', '[email protected]'], repo);+ await execGit(['config', 'user.name', 'Example Agent'], repo);+ await commit('initial');+ await addOrigin();+});++afterEach(async () => {+ await rm(scratch, { recursive: true, force: true }).catch(() => {});+});++describe('the bug this guard exists for (#4172)', () => {+ it('git auto-tracks refs/heads/main when a worktree branch is cut from origin/main', async () => {+ // The UN-fixed command, verbatim. If this ever stops recording `main`, the+ // `--no-track` flag in worktreeManager.js has become unnecessary — and this+ // test is what says so.+ const path = join(scratch, 'wt-unfixed');+ await execGit(['worktree', 'add', '-b', 'cos/task-1/agent-1', path, 'origin/main'], repo);+ expect(await mergeRef('cos/task-1/agent-1')).toBe('refs/heads/main');+ });++ it('leaves the branch untracked with --no-track, so a push -u names its own ref', async () => {+ const path = join(scratch, 'wt-fixed');+ await execGit(['worktree', 'add', '--no-track', '-b', 'cos/task-2/agent-2', path, 'origin/main'], repo);+ expect(await mergeRef('cos/task-2/agent-2')).toBe('');+ });+});++describe('isSafeBranchUpstream', () => {+ it('treats an absent upstream as safe — that is the untracked shape push -u expects', () => {+ expect(isSafeBranchUpstream('cos/task/agent', '')).toBe(true);+ });++ it('accepts an upstream naming the branch\'s own ref, in either form', () => {+ expect(isSafeBranchUpstream('feature/x', 'refs/heads/feature/x')).toBe(true);+ expect(isSafeBranchUpstream('feature/x', 'feature/x')).toBe(true);+ });++ it('rejects the default branch — the ref a config-derived push must never resolve to', () => {+ expect(isSafeBranchUpstream('cos/task/agent', 'refs/heads/main')).toBe(false);+ });++ it('rejects any OTHER foreign ref too, not just the default branch', () => {+ // The invariant is "its own ref", not "not main": a push aimed at someone+ // else's branch is the same class of mistake, one blast radius smaller.+ expect(isSafeBranchUpstream('cos/task/agent', 'refs/heads/release')).toBe(false);+ });+});++describe('readBranchUpstream', () => {+ it('reports both halves of a configured upstream', async () => {+ expect(await readBranchUpstream(repo, 'main')).toEqual({ remote: 'origin', merge: 'refs/heads/main' });+ });++ it('reports empty strings — not null — for an untracked branch', async () => {+ await execGit(['branch', '--no-track', 'solo', 'main'], repo);+ expect(await readBranchUpstream(repo, 'solo')).toEqual({ remote: '', merge: '' });+ });++ it('does not throw on an unreadable repo', async () => {+ expect(await readBranchUpstream(join(scratch, 'nope'), 'main')).toEqual({ remote: '', merge: '' });+ });+});++describe('enforceSafeBranchUpstream', () => {+ it('repairs a branch left tracking the default branch', async () => {+ const path = join(scratch, 'wt-legacy');+ // A branch in the shape every pre-fix agent worktree had.+ await execGit(['worktree', 'add', '-b', 'cos/task-3/agent-3', path, 'origin/main'], repo);+ expect(await mergeRef('cos/task-3/agent-3')).toBe('refs/heads/main');++ const result = await enforceSafeBranchUpstream(repo, 'cos/task-3/agent-3');++ expect(result).toEqual({ safe: true, repaired: true, upstream: 'refs/heads/main' });+ expect(await mergeRef('cos/task-3/agent-3')).toBe('');+ });++ it('makes the config-derived push land on the branch, not on main', async () => {+ // Acceptance criterion 2, executed rather than asserted about: run the exact+ // `git push "$(git config …remote)" "HEAD:$(git config …merge)"` shape+ // /do:pr uses, and check where the commit ended up.+ const path = join(scratch, 'wt-push');+ await execGit(['worktree', 'add', '-b', 'cos/task-4/agent-4', path, 'origin/main'], repo);+ await enforceSafeBranchUpstream(repo, 'cos/task-4/agent-4');++ await writeFile(join(path, 'agent-work.txt'), 'agent work');+ await execGit(['add', '-A'], path);+ await execGit(['commit', '-m', 'agent work'], path);+ const mainBefore = (await execGit(['rev-parse', 'origin/main'], repo)).stdout.trim();++ const { remote, merge } = await readBranchUpstream(path, 'cos/task-4/agent-4');+ // Nothing left to derive a destination from — the repaired shape forces the+ // caller onto the `push -u origin <branch>` path, which names the branch.+ expect(remote).toBe('');+ expect(merge).toBe('');+ await execGit(['push', '-u', 'origin', 'cos/task-4/agent-4'], path);++ expect((await execGit(['rev-parse', 'origin/main'], repo)).stdout.trim()).toBe(mainBefore);+ expect((await execGit(['rev-parse', 'origin/cos/task-4/agent-4'], repo)).stdout.trim())+ .toBe((await execGit(['rev-parse', 'HEAD'], path)).stdout.trim());+ });++ it('leaves a branch tracking its own remote ref alone', async () => {+ // The review-loop shape: a worktree re-attached to a branch a previous agent+ // already pushed. `merge` names the branch itself, so a config-derived push+ // is correct and must not be disturbed.+ const path = join(scratch, 'wt-existing');+ await execGit(['worktree', 'add', '-b', 'cos/task-5/agent-5', path, 'origin/main'], repo);+ await execGit(['push', '-u', 'origin', 'cos/task-5/agent-5'], path);++ const result = await enforceSafeBranchUpstream(repo, 'cos/task-5/agent-5');++ expect(result).toEqual({ safe: true, repaired: false, upstream: 'refs/heads/cos/task-5/agent-5' });+ expect(await mergeRef('cos/task-5/agent-5')).toBe('refs/heads/cos/task-5/agent-5');+ });++ it('is a no-op on an already-untracked branch', async () => {+ await execGit(['branch', '--no-track', 'cos/task-6/agent-6', 'main'], repo);+ expect(await enforceSafeBranchUpstream(repo, 'cos/task-6/agent-6'))+ .toEqual({ safe: true, repaired: false, upstream: '' });+ });++ it('tolerates missing arguments rather than throwing', async () => {+ expect(await enforceSafeBranchUpstream(null, 'branch')).toEqual({ safe: true, repaired: false, upstream: '' });+ expect(await enforceSafeBranchUpstream(repo, '')).toEqual({ safe: true, repaired: false, upstream: '' });+ });++ it('throws when the bad upstream survives the repair', async () => {+ // git cannot unset an upstream it does not consider configured: set ONLY+ // `merge`, with no `remote`, and `--unset-upstream` fails with "no upstream+ // configured" while `branch.<name>.merge` — the value a config-derived push+ // reads — still says `main`. Exactly the state that must fail loudly.+ await execGit(['branch', '--no-track', 'cos/task-7/agent-7', 'main'], repo);+ await execGit(['config', 'branch.cos/task-7/agent-7.merge', 'refs/heads/main'], repo);++ await expect(enforceSafeBranchUpstream(repo, 'cos/task-7/agent-7')).rejects.toThrow(/refs\/heads\/main/);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 49e3b9c087..489ef4d69a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -179,6 +179,7 @@ export * from './agentOutputMarkers.js';export * from './agentSentinel.js';export * from './bareUrl.js';export * from './bashResolver.js';+export * from './branchUpstreamGuard.js';export * from './bufferedSpawn.js';export * from './commandExists.js';export * from './commandSecurity.js';diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 6e346025dd..07a4ffbcde 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -35,6 +35,7 @@ import * as git from './git.js';import { detectConflicts } from './taskConflict.js';import { createWorktree, adoptWorktree } from './worktreeManager.js';import { resolveSpawnCwd } from '../lib/spawnCwd.js';+import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';const ROOT_DIR = PATHS.root;@@ -198,10 +199,17 @@ export async function prepareAgentWorkspace({ agentId, task }) {}}- await git.createBranch(workspacePath, jiraBranchName).catch(err => {- emitLog('warn', `Failed to create JIRA branch ${jiraBranchName}: ${err.message}`, { taskId: task.id });- jiraBranchName = null;- });+ await git.createBranch(workspacePath, jiraBranchName)+ // `checkout -b` off a LOCAL branch doesn't auto-track under git's default+ // `branch.autoSetupMerge`, but a repo configured `always` records the base+ // branch as this one's upstream — and a config-derived push+ // (`git push <remote> HEAD:<merge>`) then lands the agent's work on the base+ // branch instead of opening a PR (#4172). Verify before handing it over.+ .then(() => enforceSafeBranchUpstream(workspacePath, jiraBranchName))+ .catch(err => {+ emitLog('warn', `Failed to create JIRA branch ${jiraBranchName}: ${err.message}`, { taskId: task.id });+ jiraBranchName = null;+ });if (jiraBranchName) {emitLog('success', `Created feature branch ${jiraBranchName}`, { taskId: task.id, ticketId: jiraTicket.ticketId });diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 1a54273712..ef15386c60 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -16,6 +16,7 @@ import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fiimport { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';import { execGit } from '../lib/execGit.js';import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';+import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { ensureInstanceId } from './instances.js';const WORKTREES_DIR = PATHS.worktrees;@@ -388,6 +389,11 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options// Attach path re-uses an existing branch, so no orphan-branch cleanup on failure.await addWorktreeWithRetry(['worktree', 'add', '-B', branchName, worktreePath, `origin/${branchName}`], 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. Tracking `origin/<branchName>` is the healthy+ // shape here and passes untouched.+ await enforceSafeBranchUpstream(sourceWorkspace, branchName);console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);return { worktreePath, branchName, baseBranch: null, existingBranch: true, instanceId };}@@ -412,16 +418,27 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options.catch(() => baseBranch);// Create worktree with a new branch based on the latest default branch.+ // `--no-track` is load-bearing, not tidiness (#4172): `baseRef` is normally the+ // remote-tracking `origin/<default>`, and git's default `branch.autoSetupMerge`+ // would record `branch.<name>.merge = refs/heads/main` on the new branch. Push+ // helpers derive their destination from that config — `/do:pr` pushes+ // `HEAD:$(git config branch.<name>.merge)` — so the agent's work lands straight+ // on main, skipping the PR. Untracked is what makes `git push -u origin <branch>`+ // the correct path. See lib/branchUpstreamGuard.js.// On final failure, delete the partially-created branch so a failed add// doesn't leave an orphan branch with no worktree (#2193).await addWorktreeWithRetry(- ['worktree', 'add', '-b', branchName, worktreePath, baseRef],+ ['worktree', 'add', '--no-track', '-b', branchName, worktreePath, baseRef],sourceWorkspace).catch(async (err) => {await cleanupOrphanBranch(sourceWorkspace, branchName, err);throw err;});+ // Backstop the flag above — an older git, or a repo-level `branch.autoSetupMerge`+ // setting, must not be able to hand an agent a branch aimed at the default branch.+ await enforceSafeBranchUpstream(sourceWorkspace, branchName);+console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName}, base: ${baseRef})`);return { worktreePath, branchName, baseBranch, instanceId };@@ -764,11 +781,17 @@ async function createPersistentWorktreeUnlocked(featureAgentId, sourceWorkspace,await addWorktreeWithRetry(['worktree', 'add', '--track', '-b', branchName, FA_WORKTREES, `origin/${branchName}`], sourceWorkspace).catch(async (err) => { await cleanupOrphanBranch(sourceWorkspace, branchName, err); throw err; });} else {- // New branch - create from base. Clean up the orphan branch on final failure (#2193).- await addWorktreeWithRetry(['worktree', 'add', '-b', branchName, FA_WORKTREES, baseRef], sourceWorkspace)+ // New branch - create from base. `--no-track` for the same reason as createWorktree:+ // `baseRef` is usually `origin/<default>`, and an auto-configured+ // `branch.<name>.merge = refs/heads/main` turns a config-derived push into a push+ // onto the default branch (#4172). Clean up the orphan branch on final failure (#2193).+ await addWorktreeWithRetry(['worktree', 'add', '--no-track', '-b', branchName, FA_WORKTREES, baseRef], sourceWorkspace).catch(async (err) => { await cleanupOrphanBranch(sourceWorkspace, branchName, err); throw err; });}+ // Covers all three arms above, including a branch a prior run left mis-tracked.+ await enforceSafeBranchUpstream(sourceWorkspace, branchName);+console.log(`🌳 Created persistent worktree for feature agent ${featureAgentId} at ${FA_WORKTREES} (branch: ${branchName})`);return { worktreePath: FA_WORKTREES, branchName, baseBranch };}diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 9e2d9abb89..48026324e2 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -38,6 +38,7 @@ const {isPreexistingRefError,removeWorktree,adoptWorktree,+ createWorktree,} = await import('./worktreeManager.js');const { isPathInsideDir } = await import('../lib/fileUtils.js');const { win32 } = await import('path');@@ -917,3 +918,65 @@ describe('adoptWorktree — resuming an interrupted run in its own worktree', ()expect(execGitMock).not.toHaveBeenCalled();});});++describe('createWorktree upstream safety (#4172)', () => {+ // Wiring-level coverage: that the branch invariant itself HOLDS against real+ // git is proved in lib/branchUpstreamGuard.test.js (real repos, real config).+ // What can only be checked here is that createWorktree actually reaches for+ // it — the flag on the add, and the guard on the result.+ function scriptGit({ mergeReadings = [] } = {}) {+ const readings = [...mergeReadings];+ execGitMock.mockReset();+ execGitMock.mockImplementation((args) => {+ if (args[0] === 'config' && args[1] === '--get' && /\.merge$/.test(args[2] || '')) {+ const answer = readings.length ? readings.shift() : '';+ // exitCode 1 mirrors `git config --get` on an unset key, which the guard+ // must read as "no upstream" rather than as an error.+ return Promise.resolve({ stdout: answer, stderr: '', exitCode: answer ? 0 : 1 });+ }+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });+ });+ }++ const argsFor = (predicate) => execGitMock.mock.calls.map(([args]) => args).filter(predicate);++ beforeEach(() => {+ getDefaultBranchMock.mockResolvedValue('main');+ scriptGit();+ });++ it('creates the branch with --no-track so git cannot record refs/heads/main as its upstream', async () => {+ await createWorktree('agent-1', '/repo', 'task-1');++ const [add] = argsFor(a => a[0] === 'worktree' && a[1] === 'add');+ expect(add).toContain('--no-track');+ // The flag has to precede -b: it configures the branch being created.+ expect(add.indexOf('--no-track')).toBeLessThan(add.indexOf('-b'));+ });++ it('drops an upstream that still points at the default branch', async () => {+ // An older git, or a repo whose config re-tracks despite the flag: the first+ // read finds `main`, the guard unsets, the re-read confirms.+ scriptGit({ mergeReadings: ['refs/heads/main'] });++ await createWorktree('agent-2', '/repo', 'task-2');++ expect(argsFor(a => a[0] === 'branch' && a[1] === '--unset-upstream')).toHaveLength(1);+ });++ it('leaves a healthy branch untouched', async () => {+ await createWorktree('agent-3', '/repo', 'task-3');++ expect(argsFor(a => a[0] === 'branch' && a[1] === '--unset-upstream')).toHaveLength(0);+ });++ it('checks the re-attached branch of an existingBranch worktree too', async () => {+ // Branches created before this fix keep their bad upstream; a review-loop+ // agent re-attaching to one must not inherit a push aimed at main.+ scriptGit({ mergeReadings: ['refs/heads/main'] });++ await createWorktree('agent-4', '/repo', 'task-4', { existingBranch: 'cos/task-0/agent-0' });++ expect(argsFor(a => a[0] === 'branch' && a[1] === '--unset-upstream')).toHaveLength(1);+ });+});