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: clear a primary-checkout commit that merged upstream under a rebased sha

[._.]/ Adam Eivybf25e66a073d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 90481c4d29..bbf4bd5642 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -219,3 +219,5 @@
- **[issue-3725] A worktree agent is no longer failed for a commit it merely rebased onto.** The primary-checkout branch-jack guard attributes stranded commits to the agent's own branch before blaming a run, but one of its two attribution paths asked only "is this commit reachable from the agent's branch tip?" — which is equally true of a commit the agent *authored and applied to `main`* and one another actor put on `main` mid-run that the agent then *rebased onto*. Since `/do:pr` rebases on `main` before pushing, every worktree run that outlived a concurrent commit to `main` inherited that commit into its branch's base and was failed with `primary-checkout-mutated`, escalating to a human and denting the task type's success rate — in the observed case the run had actually finished its work and pushed its branch. Attribution now recognizes that a branch built strictly *on top of* the drift descends from it rather than causing it, and skips the blame. A real branch-jack leaves the primary *at* a commit the agent authored, never strictly behind its own branch, so the original incident shape is still caught.
- **A CoS agent that correctly concludes "nothing to fix here" is no longer failed for not opening a pull request.** The PR-claim check asks the forge whether a run that promised a change request produced one, and recorded a bare "no" as `pr-missing`. But "no PR" only means the agent slipped if there was something to open one *for*: an agent that investigates its task, finds the reported defect already fixed on `main`, and stops without touching a file leaves a branch with zero commits — and `gh pr create` refuses that branch because there is no diff, not because anyone made a mistake. Since `pr-missing` is deliberately non-actionable so a genuine miss can retry, a correct no-op conclusion was instead re-run to the full retry budget, spending three agents to reach the same answer three times and then escalating it to a human as a failure. A missing PR on a branch that holds **no commits** is now recorded as the completion it is, logged so the run stays visible rather than passing silently, while a missing PR on a branch that holds real commits still fails exactly as before. The commit count is taken against `origin/<default>` rather than the worktree's local copy, which routinely sits behind the commit the worktree branched from and would otherwise report inherited merge commits as the agent's own work; an unreadable count is treated as unknown and leaves the failure standing, since not being able to look is not evidence of an empty branch. The advice attached to a real miss also no longer asserts the branch "is pushed" — that was never checked — and now names how many commits are waiting.
+
+- **[issue-3744] A worktree agent is no longer failed for a commit that merged upstream under a rebased sha.** The primary-checkout branch-jack guard cleared benign movement by asking whether the primary carried commits its upstream lacked — but it asked that **by sha**, while the attribution step beside it asked **by patch-id**. PortOS rebase-merges PRs, so a merged commit carries a different sha upstream than the copy a local `git merge --ff-only` puts on the primary; the sha comparison read that copy as unpushed and treated it as stranded, and attribution then matched it against the agent's branch — where it existed only because `/do:pr` had rebased onto that same upstream commit — and called that proof of authorship. The observed run had already opened *and merged* its PR, yet was failed with `primary-checkout-mutated`, escalated to a human, and told to consider `reset --hard` over a commit whose content was fully pushed. The upstream exclusion is now patch-id-precise like the attribution beside it, so a rebase-merged copy clears the checkout exactly as a zero sha count does; a genuinely unpushed commit with no upstream twin is still reported, and the original branch-jack shape is still caught. The failure prose also stopped quoting a commit count derived from a baseline that no longer exists: a mid-run `git pull --rebase` on the primary rewrites the sha stamped at spawn, which made `rev-list ^baseline` span the whole fork point and report "16 new commits" for a run that moved the primary by one and stranded none — that case now says the baseline was rewritten instead of passing the number off as movement.
diff --git a/server/lib/primaryCheckoutGuard.js b/server/lib/primaryCheckoutGuard.js
index 76eb70eb93..53afb1af09 100644
--- a/server/lib/primaryCheckoutGuard.js
+++ b/server/lib/primaryCheckoutGuard.js
@@ -26,6 +26,18 @@
* A branch with no upstream to compare against can't be cleared, so it still
* reports (an unpushed commit is unreviewed by definition).
*
+ * "The upstream does not have it" is a question about CONTENT, not SHAs (#3744).
+ * This repo rebase-merges PRs, so a commit that merged upstream carries a
+ * DIFFERENT sha there than the copy a local `git merge --ff-only <branch>` put on
+ * the primary. Comparing shas alone reads that copy as unpushed, and the
+ * patch-id attribution below then blames whichever agent's branch also carries
+ * the same upstream commit — which, after a `/do:pr` rebase, is most of them.
+ * That is how a run whose PR had already MERGED was failed for branch-jacking a
+ * commit it did not author and that was never stranded. So the upstream
+ * exclusion asks `git cherry`, matching the patch-id precision already used on
+ * the attribution side; the two must agree, or the mismatch itself manufactures
+ * failures.
+ *
* 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`,
@@ -184,6 +196,43 @@ async function resolveAgentBranchSha(checkoutPath, agentBranch) {
return null;
}
+/**
+ * The commits `driftedHead` carries that the upstream lacks BY CONTENT (#3744) —
+ * `git cherry <upstream> <driftedHead> <runBase>`, keeping only the `+` lines
+ * (no patch-equivalent upstream). Merge commits are excluded by `git cherry`
+ * itself, matching the `noMerges` counts.
+ *
+ * This is the sha-based `upstream..head` count made patch-id-precise. It matters
+ * because PortOS rebase-merges PRs: the merged commit's sha upstream differs
+ * from the copy on the primary, so a sha comparison reports "unpushed" for
+ * content that is fully pushed and reviewed.
+ *
+ * The `runBase` limit keeps a PRE-run unpushed commit out of the set (it is not
+ * this run's doing). A limit that no longer exists in the history — the baseline
+ * commit rewritten by a mid-run `git pull --rebase` on the primary — widens the
+ * walk rather than breaking it, and the patch-equivalence filter still drops
+ * every rewritten copy, since a rebase preserves patch-ids.
+ *
+ * Returns null when there is no upstream to compare against, or `git cherry`
+ * could not run — both of which the caller must treat as "no patch-level verdict
+ * available" and fall back to the sha counts, never as "verified clean".
+ * NON-THROWING.
+ */
+async function listStrandedByPatch(checkoutPath, { runBase, upstream, driftedHead }) {
+ if (!upstream) return null;
+ const result = await execGit(
+ ['cherry', upstream, driftedHead, runBase],
+ 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.slice(2).trim())
+ .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
@@ -191,6 +240,19 @@ async function resolveAgentBranchSha(checkoutPath, agentBranch) {
*/
async function isStrictlyAhead(checkoutPath, ancestor, descendant) {
if (!ancestor || !descendant || ancestor === descendant) return false;
+ return isAncestorOrSame(checkoutPath, ancestor, descendant);
+}
+
+/**
+ * Is `ancestor` still reachable from `descendant` (or the same commit)? Used to ask
+ * whether the spawn-time baseline survived the run — a mid-run `git pull --rebase`
+ * on the primary rewrites its local commits and orphans that sha. Non-throwing; an
+ * unresolvable comparison returns false, so an unreadable history reports the
+ * baseline as rewritten rather than quoting a commit count derived from it.
+ */
+async function isAncestorOrSame(checkoutPath, ancestor, descendant) {
+ if (!ancestor || !descendant) return false;
+ if (ancestor === descendant) return true;
const result = await execGit(
['merge-base', '--is-ancestor', ancestor, descendant],
checkoutPath,
@@ -334,14 +396,30 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null
upstream ? countCommitsAhead(baseline.path, upstream, current.head) : Promise.resolve(null),
]);
+ // The same question asked by patch-id rather than by sha (#3744) — null when
+ // there is no upstream or the walk failed, which must NOT read as "clean".
+ // Skipped when the sha count already cleared the checkout: it can only agree.
+ const strandedByPatch = unpushedCount === 0
+ ? []
+ : await listStrandedByPatch(baseline.path, { runBase: baseline.head, upstream, driftedHead: current.head });
+
// Same branch, nothing local-only: the checkout was pulled forward onto commits
// that are already upstream (reviewed, merged, pushed). Nothing was stranded, so
- // there is nothing for a human to recover.
- if (current.branch === baseline.branch && unpushedCount === 0) {
+ // there is nothing for a human to recover. An empty patch-level set clears it
+ // just as a zero sha count does — a rebase-merged copy is upstream content
+ // wearing a local sha, and telling a human to `reset --hard` over it is the
+ // false alarm this guard exists to avoid.
+ if (current.branch === baseline.branch && (unpushedCount === 0 || strandedByPatch?.length === 0)) {
return { drifted: false, fastForwarded: true, baseline, current, commitCount };
}
- const message = formatDriftMessage({ baseline, current, commitCount });
+ // Did the baseline commit survive the run? A `git pull --rebase` on the primary
+ // REWRITES the local commits it replays, orphaning the sha stamped at spawn — at
+ // which point `commitCount` counts the whole post-fork history rather than the
+ // run's movement, and the prose ("16 new commits") badly overstates what moved.
+ // Say so instead of quoting a number that no longer means what it says.
+ const baselineRewritten = !(await isAncestorOrSame(baseline.path, baseline.head, current.head));
+ const message = formatDriftMessage({ baseline, current, commitCount, baselineRewritten });
// Second gate (#3703): stranded commits are only a failure if THIS agent could
// have produced them. Attribution runs whenever there is (or should be) a
@@ -350,7 +428,13 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null
// manufacture a failure out of a check that could not run. Only a pure branch
// switch that stranded exactly zero commits skips it (nothing to blame on
// anyone) and keeps its benign `git checkout` report.
- const strandedCount = unpushedCount === null ? commitCount : unpushedCount;
+ // Prefer the patch-level verdict when there is one; a resolved empty set means
+ // nothing is stranded even where the sha count disagrees. Null falls back to the
+ // sha count, and a null THERE falls back to the movement count, which is
+ // unresolvable-and-therefore-fail-open below.
+ const strandedCount = strandedByPatch
+ ? strandedByPatch.length
+ : (unpushedCount === null ? commitCount : unpushedCount);
if (strandedCount === null || strandedCount > 0) {
const attributed = await isDriftAttributableToAgent(baseline.path, {
runBase: baseline.head,
@@ -372,18 +456,23 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null
commitCount,
unpushedCount,
message,
- suggestedFix: formatDriftRecovery({ current, baseline, commitCount, unpushedCount, agentBranch }),
+ suggestedFix: formatDriftRecovery({ current, baseline, commitCount, unpushedCount, strandedCount, agentBranch }),
};
}
/** Human-readable "what moved". Pure. */
-export function formatDriftMessage({ baseline, current, commitCount }) {
+export function formatDriftMessage({ baseline, current, commitCount, baselineRewritten = false }) {
const branchPart = current.branch === baseline.branch
? `branch ${current.branch}`
: `branch ${baseline.branch} → ${current.branch}`;
const countPart = commitCount === null
? 'commit count unresolved'
- : `${commitCount} new commit${commitCount === 1 ? '' : 's'}`;
+ : baselineRewritten
+ // The baseline is off the current history (a rebase replayed it under a new
+ // sha), so the count spans the fork point, not the run. Label it as such
+ // rather than passing it off as "N new commits".
+ ? `baseline rewritten by a rebase; ${commitCount} commit${commitCount === 1 ? '' : 's'} since the abandoned baseline`
+ : `${commitCount} new commit${commitCount === 1 ? '' : 's'}`;
return `Worktree agent mutated the primary checkout ${baseline.path}: ${branchPart}, HEAD ${short(baseline.head)} → ${short(current.head)} (${countPart})`;
}
@@ -396,7 +485,7 @@ export function formatDriftMessage({ baseline, current, commitCount }) {
* reset, nothing to discard, no reason to scare the reader with `--hard`), while
* stranded commits need the inspect-then-reset flow. Pure.
*/
-export function formatDriftRecovery({ current, baseline = null, commitCount, unpushedCount = null, agentBranch }) {
+export function formatDriftRecovery({ current, baseline = null, commitCount, unpushedCount = null, strandedCount = null, agentBranch }) {
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}\`.`,
@@ -408,9 +497,12 @@ export function formatDriftRecovery({ current, baseline = null, commitCount, unp
: 'Check the agent\'s own branch (and for an open PR) for the same commits before discarding anything.';
// The actionable number is what the upstream is MISSING, not how far HEAD moved
// — a pull that also carried the agent's commit moves HEAD further than the
- // damage goes.
- const strandedCount = unpushedCount === null ? commitCount : unpushedCount;
- const countPhrase = strandedCount === null ? 'commits' : `${strandedCount} commit${strandedCount === 1 ? '' : 's'}`;
+ // damage goes. `strandedCount` is the caller's patch-level tally when it has
+ // one; the sha counts are the fallback.
+ const stranded = strandedCount === null
+ ? (unpushedCount === null ? commitCount : unpushedCount)
+ : strandedCount;
+ const countPhrase = stranded === null ? 'commits' : `${stranded} commit${stranded === 1 ? '' : 's'}`;
return [
`A worktree-isolated agent committed to the PRIMARY checkout instead of its worktree, leaving \`${current.branch}\` carrying ${countPhrase} PortOS never reviewed.`,
alsoOn,
diff --git a/server/lib/primaryCheckoutGuard.test.js b/server/lib/primaryCheckoutGuard.test.js
index ffabfacf25..3bb721f9b6 100644
--- a/server/lib/primaryCheckoutGuard.test.js
+++ b/server/lib/primaryCheckoutGuard.test.js
@@ -258,6 +258,97 @@ describe('detectPrimaryCheckoutDrift', () => {
expect(verdict.reason).toBe(PRIMARY_CHECKOUT_MUTATED_REASON);
});
+ it('clears a commit whose content merged upstream under a REBASED sha (#3744)', async () => {
+ // The observed false failure on agent-347b0ca0, whose PR had already MERGED.
+ // PortOS rebase-merges PRs, so the merged commit's sha on origin/main differs
+ // from the copy a local `merge --ff-only` put on the primary. The sha-only
+ // upstream exclusion read that copy as unpushed, and the patch-id attribution
+ // then matched it against the agent's branch — which carried the same upstream
+ // commit only because `/do:pr` rebased onto it. Nothing was ever stranded.
+ await addOrigin();
+ const agentBranch = 'cos/task-x/agent-y';
+ // A commit that will merge upstream, sitting on a sibling branch for now.
+ await execGit(['checkout', '-b', 'sibling-work'], repo);
+ await commit('a commit that merges via PR');
+ const sharedCommit = (await capturePrimaryCheckoutState(repo)).head;
+ // The agent's branch carries its own patch-equivalent copy of that commit (what
+ // a `/do:pr` rebase leaves behind) plus its own real work.
+ await execGit(['checkout', '-b', agentBranch, 'main'], repo);
+ await execGit(['cherry-pick', sharedCommit], repo);
+ await commit('the agent\'s actual work');
+ await execGit(['push', 'origin', agentBranch], repo);
+ await execGit(['checkout', 'main'], repo);
+
+ const baseline = await capturePrimaryCheckoutState(repo);
+ // Mid-run: the primary fast-forwards onto the sibling branch's copy...
+ await execGit(['merge', '--ff-only', 'sibling-work'], repo);
+ // ...and the PR rebase-merges upstream, landing a THIRD sha with the same patch.
+ const contributor = join(scratch, 'contributor-rebase-merge');
+ 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', sharedCommit], contributor);
+ await execGit(['push', 'origin', 'main'], contributor);
+ await execGit(['fetch', 'origin'], repo);
+
+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });
+ // Its content is upstream, so there is nothing to recover and nothing to blame.
+ expect(verdict.drifted).toBe(false);
+ expect(verdict.fastForwarded).toBe(true);
+ expect(verdict.suggestedFix).toBeUndefined();
+ // The sha comparison alone still calls it unpushed — which is exactly why the
+ // patch-level verdict has to be the one that decides.
+ expect(await execGit(['rev-list', '--count', 'main', '^origin/main'], repo)
+ .then(r => Number(r.stdout.trim()))).toBe(1);
+ });
+
+ it('still reports a genuinely unpushed commit that no upstream copy clears (#3744 must not over-clear)', async () => {
+ // The guard rail on the test above: patch-equivalence may only clear a commit
+ // the upstream ACTUALLY has. An agent's own commit that never merged has no
+ // copy on origin/main, so it stays a failure.
+ await addOrigin();
+ const agentBranch = 'cos/task-x/agent-y';
+ const baseline = await capturePrimaryCheckoutState(repo);
+ await execGit(['checkout', '-b', agentBranch], repo);
+ await commit('never merged anywhere');
+ const agentTip = (await capturePrimaryCheckoutState(repo)).head;
+ await execGit(['checkout', 'main'], repo);
+ await execGit(['cherry-pick', agentTip], repo);
+
+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });
+ expect(verdict.drifted).toBe(true);
+ expect(verdict.reason).toBe(PRIMARY_CHECKOUT_MUTATED_REASON);
+ expect(verdict.suggestedFix).toContain('1 commit ');
+ });
+
+ 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
+ // whole post-fork history — the incident reported "16 new commits" for a run
+ // that stranded none. The prose must not pass that number off as movement.
+ await addOrigin();
+ await commit('primary local unpushed one');
+ await commit('primary local unpushed two');
+ const baseline = await capturePrimaryCheckoutState(repo);
+ // A contributor lands upstream, and the primary pulls --rebase over it, which
+ // rewrites BOTH local commits and orphans `baseline.head`.
+ const contributor = join(scratch, 'contributor-rebased-baseline');
+ 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 writeFile(join(contributor, 'landed-upstream.txt'), 'landed upstream');
+ await execGit(['add', '-A'], contributor);
+ await execGit(['commit', '-m', 'landed upstream'], contributor);
+ await execGit(['push', 'origin', 'main'], contributor);
+ await execGit(['pull', '--rebase'], 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: 'cos/task-x/agent-y' });
+ expect(verdict.message).toContain('baseline rewritten by a rebase');
+ expect(verdict.message).not.toMatch(/\d+ new commits/);
+ });
+
it('never attributes a branch-jack to a read-only reasoner that never branched (Case A)', async () => {
const baseline = await capturePrimaryCheckoutState(repo);
// A 24-file commit lands on main mid-run, authored by another actor.