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(cos): stop the primary-checkout guard from blaming merged agent branches
[._.]/ Adam Eivya1cf3b2ff25f
diff --git a/.changelog/next/fixed-primary-checkout-guard-merged-branch.md b/.changelog/next/fixed-primary-checkout-guard-merged-branch.mdnew file mode 100644index 0000000000..9278d1a7d1--- /dev/null+++ b/.changelog/next/fixed-primary-checkout-guard-merged-branch.md@@ -0,0 +1 @@+- Primary-checkout guard no longer fails a worktree agent whose PR already merged: attribution now asks its patch-id question only about the commits the upstream genuinely lacks, and the recovery command names the branch's real upstream instead of assuming origin/<branch>diff --git a/server/lib/primaryCheckoutGuard.js b/server/lib/primaryCheckoutGuard.jsindex 53afb1af09..5c47ca2cfb 100644--- a/server/lib/primaryCheckoutGuard.js+++ b/server/lib/primaryCheckoutGuard.js@@ -38,6 +38,19 @@* the attribution side; the two must agree, or the mismatch itself manufactures* failures.*+ * They did not agree, and it did (#4098). Attribution asked its patch-id question+ * over the whole `upstream..head` window instead of over the stranded set the+ * exclusion had just computed. Once an agent's PR MERGES, its branch is an ancestor+ * of the upstream, so `git cherry <agentBranch> …` marks every commit whose patch is+ * anywhere in upstream history — including the primary's own local copies of merged+ * work, which the exclusion had already cleared. A human's unpushed WIP branch was+ * failed as a branch-jack on two such commits, with recovery prose pointing at an+ * `origin/<branch>` that does not exist (the branch tracked `origin/main`), while the+ * accurate reset would have discarded 41 of the human's commits. Attribution now+ * intersects with the stranded set, which is also what makes the patch test sound+ * without a freshness filter: a stranded commit has no patch-equivalent upstream, so+ * a patch-equivalent on the agent's branch can only be the agent's own commit.+ ** Movement that survives the checks above is still not enough to FAIL the run.* The primary checkout is a shared global resource — a concurrent coding-on-main* agent, the human's own terminal, `update.sh`'s `git pull --rebase --autostash`,@@ -173,6 +186,24 @@ async function resolveUpstreamSha(checkoutPath, branch) {return firstLine(result);}+/**+ * The SYMBOLIC name of that same upstream (`origin/main`) — what the recovery prose+ * has to quote, because a branch does NOT necessarily track a remote branch of its+ * own name. A local WIP branch cut from `main` with `branch.autoSetupMerge` on+ * tracks `origin/main`, so the prose's old hardcoded `origin/<branch>` named a ref+ * that does not exist (#4098): the "recovery" command errors out, and the reader who+ * corrects it to the real upstream discards every local commit on the branch.+ * Null when there is no upstream or git could not be run.+ */+async function resolveUpstreamRef(checkoutPath, branch) {+ const result = await execGit(+ ['rev-parse', '--abbrev-ref', `${branch}@{upstream}`],+ checkoutPath,+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },+ ).catch(() => null);+ return firstLine(result);+}+/*** Resolve the agent's own worktree branch to an IMMUTABLE commit SHA — trying the* local branch first, then its `origin/<branch>` remote-tracking form (the agent@@ -233,6 +264,29 @@ async function listStrandedByPatch(checkoutPath, { runBase, upstream, driftedHea.filter(Boolean);}+/**+ * The commits in `limit..head` that DO have a patch-equivalent somewhere in `of`'s+ * history — the `-` lines of `git cherry -v <of> <head> <limit>`. The mirror of+ * `listStrandedByPatch`, used on the attribution side to ask "is this commit a+ * rebased/cherry-picked copy of one on the agent's branch?".+ *+ * Returns null when the walk could not run, which every caller must treat as "no+ * verdict available" and never as "nothing matched". NON-THROWING.+ */+async function listPatchEquivalentShas(checkoutPath, { of, head, limit }) {+ const result = await execGit(+ ['cherry', '-v', of, head, limit],+ checkoutPath,+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },+ ).catch(() => null);+ if (!result || result.exitCode !== 0) return null;+ return (result.stdout || '')+ .split('\n')+ .filter(line => line.startsWith('- '))+ .map(line => line.split(' ')[1])+ .filter(Boolean);+}+/*** Is `descendant` STRICTLY ahead of `ancestor` — reachable from it, and not the same* commit? Non-throwing; an unresolvable comparison returns false, which the caller@@ -283,8 +337,12 @@ async function isAncestorOrSame(checkoutPath, ancestor, descendant) {* leaves a warn log and recoverable commits, while a false failure escalates to a* human and dents the task type's success rate. NON-THROWING, like the rest of the* module.+ *+ * `strandedShas` — the caller's patch-level stranded set — is what makes the second+ * half of that window trustworthy, and its absence is what made #4098 fail a run+ * whose PR had merged. See the comment on the preferred path below.*/-async function isDriftAttributableToAgent(checkoutPath, { runBase, upstream, driftedHead, agentBranch }) {+async function isDriftAttributableToAgent(checkoutPath, { runBase, upstream, driftedHead, agentBranch, strandedShas = null, baselineRewritten = false }) {const agentSha = await resolveAgentBranchSha(checkoutPath, agentBranch);if (!agentSha) return false;// The agent's branch is BUILT ON TOP OF the drifted head, so the stranded commits are@@ -301,6 +359,42 @@ async function isDriftAttributableToAgent(checkoutPath, { runBase, upstream, dri// miss (an agent that jacks and then keeps committing to its branch) is the documented// fail-open trade in the module header, and its commits are on a pushed branch anyway.if (await isStrictlyAhead(checkoutPath, driftedHead, agentSha)) return false;++ // Preferred path (#4098): the caller already resolved WHICH commits are stranded,+ // by patch-id — the set that excludes, by content, everything the upstream has.+ // Attribution then only ever asks about THOSE commits.+ //+ // That restriction is what keeps a MERGED agent branch from indicting the whole of+ // `main`. Once the agent's PR lands, its branch is an ancestor of the upstream, so+ // `git cherry <agentSha> …` marks `-` every commit in the window whose patch is+ // anywhere in upstream history — including the primary's own local copies of+ // already-merged work, which are nobody's branch-jack. The observed run failed on+ // exactly that: two commits the stranded set had ALREADY cleared as upstream+ // content were matched against the agent's merged branch and read as its own. The+ // module header says the two sides must agree; intersecting them is how.+ //+ // Restricted this way, the patch test is sound with no freshness filter: a stranded+ // commit has NO patch-equivalent upstream, so a patch-equivalent on the agent's+ // branch can only be one of the agent's OWN commits.+ if (Array.isArray(strandedShas)) {+ if (strandedShas.length === 0) return false;+ // Literal branch-jack: the agent's branch carries a stranded commit outright.+ for (const sha of strandedShas) {+ if (await isAncestorOrSame(checkoutPath, sha, agentSha)) return true;+ }+ // Patch-equivalent branch-jack: a cherry-picked / rebased copy, different sha.+ const equivalents = await listPatchEquivalentShas(checkoutPath, {+ of: agentSha,+ head: driftedHead,+ limit: upstream || runBase,+ });+ if (!equivalents) return false;+ const stranded = new Set(strandedShas);+ return equivalents.some(sha => stranded.has(sha));+ }++ // Fallback: no patch-level stranded set (no upstream to compare against, or the+ // walk failed). Approximate it with the sha window below.// Candidate branch-jack commits (set S): new this run (`^runBase`) AND unpushed// (`^upstream`, when there is an upstream to compare against), non-merge only — a// merge commit reaches the primary via a human's `git merge` / non-ff pull, never a@@ -321,17 +415,19 @@ async function isDriftAttributableToAgent(checkoutPath, { runBase, upstream, dri// by the reachability check). `git cherry <upstream> <head> <limit>` marks such a// commit `-`. Walk unpushed commits (limit = upstream), then keep only a `-` commit// that is new this run — a pre-run copy is a prior run's problem, not this one's.- const cherry = await execGit(- ['cherry', '-v', agentSha, driftedHead, upstream || runBase],- checkoutPath,- { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },- ).catch(() => null);- if (!cherry || cherry.exitCode !== 0) return false;- const equivalentShas = (cherry.stdout || '')- .split('\n')- .filter(line => line.startsWith('- '))- .map(line => line.split(' ')[1])- .filter(Boolean);+ //+ // That "new this run" test is reachability against `runBase`, so a mid-run `git pull+ // --rebase` on the primary breaks it: the replayed commits get new shas, the baseline+ // is orphaned, and NOTHING on the current history is an ancestor of it — every `-`+ // commit then reads as fresh, whenever it was really made. An unanswerable check must+ // fail open (the module's contract), not answer "yes" by default.+ if (baselineRewritten) return false;+ const equivalentShas = await listPatchEquivalentShas(checkoutPath, {+ of: agentSha,+ head: driftedHead,+ limit: upstream || runBase,+ });+ if (!equivalentShas) return false;for (const sha of equivalentShas) {const ancestor = await execGit(['merge-base', '--is-ancestor', sha, runBase],@@ -441,6 +537,8 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = nullupstream,driftedHead: current.head,agentBranch,+ strandedShas: strandedByPatch,+ baselineRewritten,});if (!attributed) {return { drifted: false, unattributed: true, baseline, current, commitCount, unpushedCount, message };@@ -456,7 +554,16 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = nullcommitCount,unpushedCount,message,- suggestedFix: formatDriftRecovery({ current, baseline, commitCount, unpushedCount, strandedCount, agentBranch }),+ suggestedFix: formatDriftRecovery({+ current,+ baseline,+ commitCount,+ unpushedCount,+ strandedCount,+ agentBranch,+ // Symbolic, not the pinned sha: this goes into a command a human runs later.+ upstreamRef: await resolveUpstreamRef(baseline.path, current.branch),+ }),};}@@ -484,8 +591,13 @@ export function formatDriftMessage({ baseline, current, commitCount, baselineRew* on the WRONG BRANCH with nothing local-only just needs checking back out (no* reset, nothing to discard, no reason to scare the reader with `--hard`), while* stranded commits need the inspect-then-reset flow. Pure.+ *+ * `upstreamRef` is the branch's ACTUAL upstream (`git rev-parse --abbrev-ref+ * <branch>@{upstream}`), not an assumption that it is `origin/<branch>`; see+ * `resolveUpstreamRef`. It falls back to `origin/<branch>` only when the caller could+ * not resolve one, which is the pre-#4098 wording.*/-export function formatDriftRecovery({ current, baseline = null, commitCount, unpushedCount = null, strandedCount = null, agentBranch }) {+export function formatDriftRecovery({ current, baseline = null, commitCount, unpushedCount = null, strandedCount = null, agentBranch, upstreamRef = null }) {if (unpushedCount === 0 && baseline?.branch && baseline.branch !== current.branch) {return [`A worktree-isolated agent left the PRIMARY checkout on \`${current.branch}\` instead of \`${baseline.branch}\`.`,@@ -503,10 +615,17 @@ export function formatDriftRecovery({ current, baseline = null, commitCount, unp? (unpushedCount === null ? commitCount : unpushedCount): strandedCount;const countPhrase = stranded === null ? 'commits' : `${stranded} commit${stranded === 1 ? '' : 's'}`;+ const resetTarget = upstreamRef || `origin/${current.branch}`;+ // A branch tracking something other than its own remote counterpart (a local WIP+ // branch cut from `main` tracks `origin/main`) rewinds ONTO THAT — which is most of+ // the branch, not just the drift. Say so where the reader is about to type it.+ const trackingCaveat = upstreamRef && upstreamRef !== `origin/${current.branch}`+ ? ` Note that \`${current.branch}\` tracks \`${upstreamRef}\` rather than a remote branch of its own, so that reset rewinds it onto \`${upstreamRef}\` and drops every local commit on it, not only the agent's.`+ : '';return [`A worktree-isolated agent committed to the PRIMARY checkout instead of its worktree, leaving \`${current.branch}\` carrying ${countPhrase} PortOS never reviewed.`,alsoOn,- `Inspect them with \`git -C ${current.path} log --oneline origin/${current.branch}..${current.branch}\`, and once you have confirmed the content is upstream (or preserved on the agent branch) restore the checkout with \`git -C ${current.path} reset --hard origin/${current.branch}\`.`,- 'That reset DISCARDS those commits, so PortOS will not run it for you.',+ `Inspect them with \`git -C ${current.path} log --oneline ${resetTarget}..${current.branch}\`, and once you have confirmed the content is upstream (or preserved on the agent branch) restore the checkout with \`git -C ${current.path} reset --hard ${resetTarget}\`.`,+ `That reset DISCARDS those commits, so PortOS will not run it for you.${trackingCaveat}`,].join(' ');}diff --git a/server/lib/primaryCheckoutGuard.test.js b/server/lib/primaryCheckoutGuard.test.jsindex 8f9233a9cd..acb3920289 100644--- a/server/lib/primaryCheckoutGuard.test.js+++ b/server/lib/primaryCheckoutGuard.test.js@@ -327,6 +327,103 @@ describe('detectPrimaryCheckoutDrift', () => {expect(verdict.suggestedFix).toContain('1 commit ');});+ /**+ * Put `repo`'s current HEAD content upstream under a DIFFERENT sha, the way a+ * rebase-merged PR does: push it to a scratch remote branch, then have a+ * contributor cherry-pick that onto `main` and push. Leaves `repo` fetched.+ */+ async function mergeHeadUpstreamRebased(label) {+ const slug = label.replace(/\W+/g, '-');+ await execGit(['push', 'origin', `HEAD:refs/heads/pr-${slug}`], repo);+ const contributor = join(scratch, `contributor-${slug}`);+ await execGit(['clone', join(scratch, 'origin.git'), contributor], scratch);+ await execGit(['config', 'user.email', '[email protected]'], contributor);+ await execGit(['config', 'user.name', 'Other Contributor'], contributor);+ await execGit(['cherry-pick', `origin/pr-${slug}`], contributor);+ await execGit(['push', 'origin', 'main'], contributor);+ await execGit(['fetch', 'origin'], repo);+ }++ it('does not blame an agent whose branch MERGED for the primary\'s own upstream copies (#4098)', async () => {+ // The observed false failure. The primary sat on a human's local WIP branch that+ // TRACKS `origin/main` (no remote branch of its own), carrying commits that are+ // unpushed by design. The agent's PR then merged, which makes its branch an+ // ancestor of `origin/main` — at which point "patch-equivalent to the agent's+ // branch" is indistinguishable from "patch-equivalent to anything in main's+ // history", and the primary's own local copy of already-merged work reads as the+ // agent's branch-jack. Attribution has to ask only about the STRANDED commits,+ // which by construction have no patch-equivalent upstream.+ await addOrigin();+ const agentBranch = 'cos/task-x/agent-y';+ await execGit(['checkout', '-b', 'fix/wip', '--track', 'origin/main'], repo);+ await commit('human wip, never pushed');++ const baseline = await capturePrimaryCheckoutState(repo);+ // During the run the human commits work that ALSO lands upstream via a PR (rebase+ // -merged, so origin/main carries a patch-equivalent under a different sha)...+ await commit('human work that also lands upstream');+ await mergeHeadUpstreamRebased('lands-upstream');+ // ...and a commit that lands nowhere, which is the only genuinely stranded one.+ await commit('human work that stays local');+ // The agent's own PR merged too, so its branch is now an ancestor of origin/main.+ await execGit(['branch', agentBranch, 'origin/main'], repo);++ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });+ expect(verdict.drifted).toBe(false);+ expect(verdict.unattributed).toBe(true);+ expect(verdict.suggestedFix).toBeUndefined();+ });++ it('does not read a rewritten baseline as proof every patch-equivalent commit is new (#4098)', async () => {+ // The fallback path (no upstream to compare against) keeps a pre-run copy out of+ // the attributed set by asking "is this commit an ancestor of the run baseline?".+ // A mid-run rewrite on the primary — `pull --rebase`, an amend, an interactive+ // rebase — orphans that baseline, so NOTHING on the current history is an ancestor+ // of it and the filter answers "created during the run" for every commit, whenever+ // it was really made. The run is surfaced (warn-logged) rather than failed, per the+ // module's fail-open contract for a check that could not run.+ const agentBranch = 'cos/task-x/agent-y';+ // A PRE-RUN copy of the agent branch's work already sits on the primary's main.+ await execGit(['checkout', '-b', agentBranch], repo);+ await commit('the agent\'s work');+ const agentTip = (await capturePrimaryCheckoutState(repo)).head;+ await execGit(['checkout', 'main'], repo);+ await execGit(['cherry-pick', agentTip], repo);+ const baseline = await capturePrimaryCheckoutState(repo);+ // Mid-run the human rewords that commit, rewriting its sha (same patch) and+ // orphaning the baseline stamped at spawn.+ await execGit(['commit', '--amend', '-m', 'reworded by the human mid-run'], repo);+ expect(await execGit(['merge-base', '--is-ancestor', baseline.head, 'HEAD'], repo,+ { ignoreExitCode: true }).then(r => r.exitCode)).not.toBe(0);++ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });+ expect(verdict.drifted).toBe(false);+ expect(verdict.unattributed).toBe(true);+ });++ it('names the branch\'s REAL upstream in the recovery command, not origin/<branch> (#4098)', async () => {+ // `fix/wip` tracks `origin/main` and has no remote branch of its own, so the old+ // hardcoded `origin/fix/wip` named a ref that does not exist — the "recovery"+ // command errors out, and correcting it to the real upstream discards the human's+ // unpushed commits along with the agent's.+ await addOrigin();+ const agentBranch = 'cos/task-x/agent-y';+ await execGit(['checkout', '-b', 'fix/wip', '--track', 'origin/main'], repo);+ const baseline = await capturePrimaryCheckoutState(repo);+ await execGit(['checkout', '-b', agentBranch], repo);+ await commit('the agent\'s own work');+ const agentTip = (await capturePrimaryCheckoutState(repo)).head;+ await execGit(['checkout', 'fix/wip'], repo);+ await execGit(['cherry-pick', agentTip], repo);++ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });+ expect(verdict.drifted).toBe(true);+ expect(verdict.suggestedFix).toContain(`git -C ${repo} reset --hard origin/main`);+ expect(verdict.suggestedFix).not.toContain('origin/fix/wip');+ // ...and it warns that the reset rewinds onto a ref that is not this branch.+ expect(verdict.suggestedFix).toContain('tracks `origin/main`');+ });+it('does not quote a commit count spanning a baseline a mid-run rebase rewrote (#3744)', async () => {// `git pull --rebase` on the primary replays its local commits under new shas,// orphaning the baseline stamped at spawn. `rev-list ^baseline` then counts the@@ -504,6 +601,13 @@ describe('prose helpers', () => {expect(formatDriftRecovery({ current, commitCount: 1, agentBranch: null })).toContain('1 commit ');});+ it('falls back to origin/<branch> only when no upstream was resolved', () => {+ expect(formatDriftRecovery({ current, commitCount: 1, agentBranch: null }))+ .toContain('reset --hard origin/main');+ expect(formatDriftRecovery({ current, commitCount: 1, agentBranch: null, upstreamRef: 'upstream/trunk' }))+ .toContain('reset --hard upstream/trunk');+ });+it('never tells the user PortOS already fixed it', () => {const fix = formatDriftRecovery({ current, commitCount: 3, agentBranch: 'claim/issue-3680' });expect(fix).toContain('DISCARDS');