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: undo the worktree add when the upstream guard refuses, and fail closed on an unreadable upstream (#4172)

[._.]/ Adam Eivy06c3e19c6161
diff --git a/server/lib/README.md b/server/lib/README.md
index 537beebfaf..73a06287f0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -203,7 +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`. |
+| `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. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. 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.js
index dbbc3ab59b..6672152881 100644
--- a/server/lib/branchUpstreamGuard.js
+++ b/server/lib/branchUpstreamGuard.js
@@ -43,13 +43,22 @@ import { execGit } from './execGit.js';
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.
+ * Read a branch's configured upstream as raw config values.
+ *
+ * Three outcomes, deliberately NOT collapsed (see CLAUDE.md, "Sentinel +
+ * validate"): `''` is UNSET (a healthy untracked branch), a string is the
+ * configured ref, and `null` is COULD NOT READ. Folding the third into `''`
+ * would let a wedged git, a timeout, or an unreadable repo report a branch that
+ * really does track `main` as untracked — the guard would then wave through
+ * exactly the branch it exists to catch. Non-throwing; the caller decides what
+ * an unreadable answer means.
+ *
+ * `git config --get` exits 1 for an unset key (the common case, not an error)
+ * and 128 for a bad repo, which is what separates the two.
*
* @param {string} repo - repository (or worktree) path to read config from
* @param {string} branchName
- * @returns {Promise<{remote: string, merge: string}>}
+ * @returns {Promise<{remote: string|null, merge: string|null}>}
*/
export async function readBranchUpstream(repo, branchName) {
if (!repo || !branchName) return { remote: '', merge: '' };
@@ -59,8 +68,9 @@ export async function readBranchUpstream(repo, branchName) {
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() : '';
+ if (!result) return null;
+ if (result.exitCode === 0) return (result.stdout || '').trim();
+ return result.exitCode === 1 ? '' : null;
};
const [remote, merge] = await Promise.all([read('remote'), read('merge')]);
return { remote, merge };
@@ -75,11 +85,15 @@ export async function readBranchUpstream(repo, branchName) {
* qualified `refs/heads/main` that git actually writes, so a hand-edited config
* is judged the same way.
*
+ * A `null` merge (could not read, per `readBranchUpstream`) is NOT safe: an
+ * unanswered safety question is not a pass.
+ *
* @param {string} branchName
- * @param {string} merge - the `branch.<name>.merge` value
+ * @param {string|null} merge - the `branch.<name>.merge` value
*/
export function isSafeBranchUpstream(branchName, merge) {
- if (!merge) return true;
+ if (merge === null || merge === undefined) return false;
+ if (merge === '') return true;
return merge === `refs/heads/${branchName}` || merge === branchName;
}
@@ -107,6 +121,11 @@ 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 };
+ // 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) {
+ throw new Error(`Refusing to hand off branch ${branchName}: its upstream config could not be read, so a config-derived push (git push <remote> HEAD:<merge>) cannot be shown to be safe`);
+ }
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, {
@@ -116,7 +135,8 @@ export async function enforceSafeBranchUpstream(repo, branchName) {
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`);
+ 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`);
}
return { safe: true, repaired: true, upstream: merge };
}
diff --git a/server/lib/branchUpstreamGuard.test.js b/server/lib/branchUpstreamGuard.test.js
index 9c4a2cadf1..21af773374 100644
--- a/server/lib/branchUpstreamGuard.test.js
+++ b/server/lib/branchUpstreamGuard.test.js
@@ -92,6 +92,14 @@ describe('isSafeBranchUpstream', () => {
// else's branch is the same class of mistake, one blast radius smaller.
expect(isSafeBranchUpstream('cos/task/agent', 'refs/heads/release')).toBe(false);
});
+
+ it('rejects an UNREADABLE upstream — an unanswered safety question is not a pass', () => {
+ // `null` is readBranchUpstream's could-not-read sentinel. Treating it as ''
+ // would wave through a branch that really does track main whenever git is
+ // wedged, which is the one moment the guard most needs to hold.
+ expect(isSafeBranchUpstream('cos/task/agent', null)).toBe(false);
+ expect(isSafeBranchUpstream('cos/task/agent', undefined)).toBe(false);
+ });
});
describe('readBranchUpstream', () => {
@@ -104,8 +112,11 @@ describe('readBranchUpstream', () => {
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: '' });
+ it('reports null — NOT empty — when the config cannot be read at all', async () => {
+ // The distinction that matters: `''` means "no upstream configured", `null`
+ // means "we could not find out". Collapsing them lets an unreadable repo
+ // masquerade as a healthy untracked branch.
+ expect(await readBranchUpstream(join(scratch, 'nope'), 'main')).toEqual({ remote: null, merge: null });
});
});
@@ -172,6 +183,13 @@ describe('enforceSafeBranchUpstream', () => {
expect(await enforceSafeBranchUpstream(repo, '')).toEqual({ safe: true, repaired: false, upstream: '' });
});
+ it('refuses a branch whose upstream config cannot be read', async () => {
+ // Fail CLOSED: nothing here verified the branch is safe, and reporting it as
+ // untracked would hand an agent a branch that may still push to main.
+ await expect(enforceSafeBranchUpstream(join(scratch, 'nope'), 'cos/task/agent'))
+ .rejects.toThrow(/could not be read/);
+ });
+
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
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index ef15386c60..00dded14dd 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -217,6 +217,32 @@ export async function forceRemoveWorktreeDir(repo, worktreePath, { label, log =
});
}
+/**
+ * Run the upstream guard on a branch whose worktree ALREADY exists, undoing the
+ * add if the guard refuses (#4172).
+ *
+ * `enforceSafeBranchUpstream` throws when a branch's upstream still aims at a
+ * foreign ref after repair — correct, because every downstream push helper would
+ * land there. But the throw happens AFTER `git worktree add` succeeded, so
+ * without this the caller gets a failed create while a registered worktree (and,
+ * for a fresh `-b` add, an orphan branch) stays on disk: exactly the debris
+ * `cleanupOrphanBranch` already prevents on the add itself.
+ *
+ * `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) => {
+ await forceRemoveWorktreeDir(sourceWorkspace, worktreePath, {
+ label: `Undoing worktree add for ${branchName} after an unsafe upstream`,
+ log: 'all',
+ subject: branchName,
+ }).catch(() => {});
+ if (deleteBranch) await cleanupOrphanBranch(sourceWorkspace, branchName, err);
+ throw err;
+ });
+}
+
/**
* Classify a `git status --porcelain` blob into real changes vs auto-generated
* lockfile churn. Pure (testable) — callers decide what to do with the result.
@@ -393,7 +419,7 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
// 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);
+ await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch: false });
console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);
return { worktreePath, branchName, baseBranch: null, existingBranch: true, instanceId };
}
@@ -437,7 +463,7 @@ async function createWorktreeUnlocked(agentId, sourceWorkspace, taskId, options
// 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);
+ await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePath, { deleteBranch: true });
console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} (branch: ${branchName}, base: ${baseRef})`);
@@ -790,7 +816,7 @@ async function createPersistentWorktreeUnlocked(featureAgentId, sourceWorkspace,
}
// Covers all three arms above, including a branch a prior run left mis-tracked.
- await enforceSafeBranchUpstream(sourceWorkspace, branchName);
+ await enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, FA_WORKTREES, { deleteBranch: !localBranchExists });
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.js
index 48026324e2..ef1d6109f3 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -39,6 +39,7 @@ const {
removeWorktree,
adoptWorktree,
createWorktree,
+ createPersistentWorktree,
} = await import('./worktreeManager.js');
const { isPathInsideDir } = await import('../lib/fileUtils.js');
const { win32 } = await import('path');
@@ -970,6 +971,30 @@ describe('createWorktree upstream safety (#4172)', () => {
expect(argsFor(a => a[0] === 'branch' && a[1] === '--unset-upstream')).toHaveLength(0);
});
+ it('undoes the add when the upstream cannot be made safe, instead of stranding a worktree', async () => {
+ // The guard throws AFTER `worktree add` succeeded, so without an undo the
+ // caller sees a failed create while a registered worktree and an orphan
+ // branch stay on disk — the debris cleanupOrphanBranch prevents on the add.
+ scriptGit({ mergeReadings: ['refs/heads/main', 'refs/heads/main'] });
+
+ await expect(createWorktree('agent-5', '/repo', 'task-5')).rejects.toThrow(/still resolves to/);
+
+ expect(argsFor(a => a[0] === 'worktree' && a[1] === 'remove')).toHaveLength(1);
+ expect(argsFor(a => a[0] === 'branch' && a[1] === '-D')).toHaveLength(1);
+ });
+
+ it('does NOT delete the branch when undoing an existingBranch attach', async () => {
+ // That branch pre-dates this add and may hold real commits — same
+ // distinction cleanupOrphanBranch draws.
+ scriptGit({ mergeReadings: ['refs/heads/main', 'refs/heads/main'] });
+
+ await expect(createWorktree('agent-6', '/repo', 'task-6', { existingBranch: 'cos/task-0/agent-0' }))
+ .rejects.toThrow(/still resolves to/);
+
+ expect(argsFor(a => a[0] === 'worktree' && a[1] === 'remove')).toHaveLength(1);
+ expect(argsFor(a => a[0] === 'branch' && a[1] === '-D')).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.
@@ -979,4 +1004,26 @@ describe('createWorktree upstream safety (#4172)', () => {
expect(argsFor(a => a[0] === 'branch' && a[1] === '--unset-upstream')).toHaveLength(1);
});
+
+ // The persistent feature-agent tree needs its own coverage, not just the CoS
+ // one: it lives OUTSIDE `WORKTREES_DIR`, so neither `cleanupOrphanedWorktrees`
+ // nor `reapMergedWorktrees` reaps it, and its only caller does not catch. A
+ // stranded tree there blocks every retry with "already exists" until a human
+ // prunes it, so the undo has to happen here rather than being left to a sweeper.
+ it('creates the persistent feature-agent branch with --no-track too', async () => {
+ await createPersistentWorktree('fa-1', '/repo', 'feature/x', 'main');
+
+ const [add] = argsFor(a => a[0] === 'worktree' && a[1] === 'add');
+ expect(add).toContain('--no-track');
+ });
+
+ it('undoes the persistent add when the upstream cannot be made safe', async () => {
+ scriptGit({ mergeReadings: ['refs/heads/main', 'refs/heads/main'] });
+
+ await expect(createPersistentWorktree('fa-2', '/repo', 'feature/y', 'main'))
+ .rejects.toThrow(/still resolves to/);
+
+ expect(argsFor(a => a[0] === 'worktree' && a[1] === 'remove')).toHaveLength(1);
+ expect(argsFor(a => a[0] === 'branch' && a[1] === '-D')).toHaveLength(1);
+ });
});