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: only flag a primary-checkout branch-jack when commits are actually stranded
[._.]/ Adam Eivycf230ab1d9aa
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 76c4d83093..587da9d9d6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -28,6 +28,8 @@## Fixed+- **A successful agent run is no longer failed just because someone pulled `main` while it worked.** The branch-jack detector — which watches whether a worktree-isolated agent committed into the primary checkout instead of its own worktree — treated *any* movement of the primary as a branch-jack. So an ordinary `git pull` landing an already-merged PR flipped a run that had shipped its own PR into a failure, and told the user to consider `git reset --hard origin/main` over commits that already *were* `origin/main`. The guard now reports what a branch-jack actually leaves behind: commits the branch's upstream does not have, or the checkout parked on a different branch than it started on. A pure fast-forward onto upstream commits is logged as movement and nothing more. When damage is real, the recovery advice is sharper too — it quotes the number of *stranded* commits rather than how far HEAD travelled, and a checkout merely left on the wrong branch with nothing stranded is told to `git checkout` back instead of being pointed at a `--hard` reset that would discard nothing. A branch with no upstream to compare against still reports, since an unpushed commit is unreviewed by definition.+- **Recovering an AI provider now affects the very next routed run.** PortOS accidentally kept two in-memory provider-status services over the same JSON file: the Providers UI updated one while the AI Toolkit's runner consulted the other. A manual “Recover now” therefore looked successful and persisted correctly, yet a run started moments later could still bypass the recovered primary and spend time on a fallback. All legacy callers and the PortOS status routes now delegate to the Toolkit-owned singleton, and provider status socket events have one broadcast path instead of being emitted twice.- **A timed-out creative stage no longer benches its provider as “quota exceeded.”** TUI finalization previously classified a hard timeout by scanning the whole terminal response, which includes the story prompt; ordinary narrative words such as “credit,” “payment,” or “billing” could therefore override exit 124 and sideline a healthy provider for an hour. The host's timeout signal is now authoritative, while non-timeout failures continue to use provider-output analysis for real usage, auth, model, and network banners.diff --git a/server/lib/primaryCheckoutGuard.js b/server/lib/primaryCheckoutGuard.jsindex 69fb9629fd..e3b699c581 100644--- a/server/lib/primaryCheckoutGuard.js+++ b/server/lib/primaryCheckoutGuard.js@@ -16,6 +16,16 @@* of running it — and notes that the same work also exists on the agent's* own branch, which is what makes the reset safe.*+ * Movement alone is NOT the signal. The primary checkout legitimately moves+ * during a run — a `git pull` on `main`, another PortOS flow fast-forwarding it+ * to commits that already merged upstream. Reporting those as branch-jacks fired+ * a false failure whose recovery prose ("commits PortOS never reviewed", `reset+ * --hard origin/main`) was actively wrong: the commits WERE `origin/main`. So the+ * guard reports only what a branch-jack actually leaves behind — commits the+ * branch's upstream does not have, or the checkout parked on a different branch.+ * A branch with no upstream to compare against can't be cleared, so it still+ * reports (an unpushed commit is unreviewed by definition).+ ** Two halves, deliberately split so they can sit on opposite ends of a run:* `capturePrimaryCheckoutState` stamps a baseline at spawn time (onto the agent* metadata, in `agentLifecycle.js`), and `detectPrimaryCheckoutDrift` re-reads it@@ -111,6 +121,32 @@ async function countCommitsAhead(checkoutPath, baseHead, head) {return Number.isFinite(count) ? count : null;}+/**+ * The branch's upstream tracking ref (`origin/main`), or null when it has none+ * configured — or when git could not be run. Both collapse to null on purpose:+ * the caller treats "no comparison available" identically either way.+ */+async function resolveUpstreamRef(checkoutPath, branch) {+ const result = await execGit(+ ['rev-parse', '--abbrev-ref', '--symbolic-full-name', `${branch}@{upstream}`],+ checkoutPath,+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },+ ).catch(() => null);+ return firstLine(result);+}++/**+ * Commits the branch carries that its upstream does not — the only commits a+ * branch-jack actually leaves stranded, and the number the recovery prose is+ * about. Returns null (not 0) when there is no upstream to compare against, so+ * "verified clean" never masquerades as "could not check".+ */+async function countUnpushedCommits(checkoutPath, branch) {+ const upstream = await resolveUpstreamRef(checkoutPath, branch);+ if (!upstream) return null;+ return await countCommitsAhead(checkoutPath, upstream, branch);+}+/** Short SHA for human-readable prose. */const short = sha => String(sha || '').slice(0, 9);@@ -118,11 +154,16 @@ const short = sha => String(sha || '').slice(0, 9);* Re-read the baseline and report whether the primary checkout moved during the* run.*- * Three outcomes, never collapsed:+ * Outcomes, never collapsed:* - `{ drifted: false }` — it didn't move, OR there was nothing to check, OR* the checkout could not be read (nothing was verified, so nothing is* claimed).- * - `{ drifted: true, … }` — the branch or HEAD moved.+ * - `{ drifted: false, fastForwarded: true, … }` — HEAD moved on the SAME+ * branch but every commit is already on that branch's upstream. That is a+ * `git pull`, not a branch-jack; carried as a distinct shape (rather than a+ * bare `false`) so a caller can log what it observed.+ * - `{ drifted: true, … }` — the checkout ended on a different branch, or its+ * branch carries commits the upstream does not have.** @param {{path: string, branch: string, head: string}|null} baseline stamped by* `capturePrimaryCheckoutState` at spawn time@@ -138,7 +179,18 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = nullif (!current) return { drifted: false };if (current.branch === baseline.branch && current.head === baseline.head) return { drifted: false };- const commitCount = await countCommitsAhead(baseline.path, baseline.head, current.head);+ const [commitCount, unpushedCount] = await Promise.all([+ countCommitsAhead(baseline.path, baseline.head, current.head),+ countUnpushedCommits(baseline.path, current.branch),+ ]);++ // 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) {+ return { drifted: false, fastForwarded: true, baseline, current, commitCount };+ }+return {drifted: true,reason: PRIMARY_CHECKOUT_MUTATED_REASON,@@ -146,8 +198,9 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = nullbaseline,current,commitCount,+ unpushedCount,message: formatDriftMessage({ baseline, current, commitCount }),- suggestedFix: formatDriftRecovery({ current, commitCount, agentBranch }),+ suggestedFix: formatDriftRecovery({ current, baseline, commitCount, unpushedCount, agentBranch }),};}@@ -165,13 +218,27 @@ export function formatDriftMessage({ baseline, current, commitCount }) {/*** The recovery advice. Names the exact commands and is explicit that the reset* discards commits — PortOS deliberately does not run it (see the module header).- * Pure.+ *+ * Two shapes, because the two failures need different commands: a checkout left+ * 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.*/-export function formatDriftRecovery({ current, commitCount, agentBranch }) {+export function formatDriftRecovery({ current, baseline = null, commitCount, unpushedCount = 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}\`.`,+ `No commits were stranded — \`${current.branch}\` carries nothing its upstream lacks — so restore it with \`git -C ${current.path} checkout ${baseline.branch}\`.`,+ ].join(' ');+ }const alsoOn = agentBranch? `The same commits were almost certainly pushed on the agent's own branch \`${agentBranch}\` too, so check there (and for an open PR) before discarding anything.`: 'Check the agent\'s own branch (and for an open PR) for the same commits before discarding anything.';- const countPhrase = commitCount === null ? 'commits' : `${commitCount} commit${commitCount === 1 ? '' : 's'}`;+ // 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'}`;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.jsindex e8b473a3f5..aedf87c53c 100644--- a/server/lib/primaryCheckoutGuard.test.js+++ b/server/lib/primaryCheckoutGuard.test.js@@ -30,6 +30,32 @@ async function commit(subject) {await execGit(['commit', '-m', subject], repo);}+/**+ * Give `repo` a real upstream to compare against — the guard now clears movement+ * only when the branch carries nothing its upstream lacks, so the benign cases+ * are untestable without one. A bare clone on disk keeps this real git (no+ * network, no mocked `rev-parse`).+ */+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);+}++/** Land a commit on the remote and fast-forward `repo` onto it, as a pull would. */+async function pullFromOrigin(subject) {+ const clone = join(scratch, `contributor-${subject.replace(/\W+/g, '-')}`);+ await execGit(['clone', join(scratch, 'origin.git'), clone], scratch);+ await execGit(['config', 'user.email', '[email protected]'], clone);+ await execGit(['config', 'user.name', 'Other Contributor'], clone);+ await writeFile(join(clone, `${subject.replace(/\W+/g, '-')}.txt`), subject);+ await execGit(['add', '-A'], clone);+ await execGit(['commit', '-m', subject], clone);+ await execGit(['push', 'origin', 'main'], clone);+ await execGit(['pull', '--ff-only'], repo);+}+beforeEach(async () => {scratch = await mkdtemp(join(tmpdir(), 'portos-branch-jack-'));repo = join(scratch, 'primary');@@ -96,6 +122,62 @@ describe('detectPrimaryCheckoutDrift', () => {expect(verdict.message).toContain('main → someone-elses-branch');});+ it('clears a plain pull: HEAD moved but every commit is already upstream', async () => {+ await addOrigin();+ const baseline = await capturePrimaryCheckoutState(repo);+ await pullFromOrigin('landed via a merged PR');++ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: 'cos/task-x/agent-y' });+ // The false failure this guard used to raise (#3702 follow-up): the commit is+ // origin/main's, so `reset --hard origin/main` would have been a no-op the+ // user was told to consider.+ expect(verdict.drifted).toBe(false);+ expect(verdict.fastForwarded).toBe(true);+ expect(verdict.commitCount).toBe(1);+ expect(verdict.message).toBeUndefined();+ });++ it('still reports the agent\'s own commit when a pull landed alongside it', async () => {+ await addOrigin();+ const baseline = await capturePrimaryCheckoutState(repo);+ await pullFromOrigin('landed via a merged PR');+ await commit('branch jacked');++ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: 'cos/task-x/agent-y' });+ expect(verdict.drifted).toBe(true);+ // HEAD moved 2, but only 1 is stranded — the recovery prose quotes the+ // stranded count, not the movement.+ expect(verdict.commitCount).toBe(2);+ expect(verdict.unpushedCount).toBe(1);+ expect(verdict.suggestedFix).toContain('1 commit ');+ expect(verdict.suggestedFix).toContain(`git -C ${repo} reset --hard origin/main`);+ });++ it('advises checkout, not reset, for a branch switch that stranded nothing', async () => {+ await addOrigin();+ await execGit(['push', 'origin', 'main:someone-elses-branch'], repo);+ const baseline = await capturePrimaryCheckoutState(repo);+ await execGit(['checkout', '-b', 'someone-elses-branch', '--track', 'origin/someone-elses-branch'], repo);++ const verdict = await detectPrimaryCheckoutDrift(baseline);+ expect(verdict.drifted).toBe(true);+ expect(verdict.unpushedCount).toBe(0);+ expect(verdict.suggestedFix).toContain(`git -C ${repo} checkout main`);+ expect(verdict.suggestedFix).not.toContain('reset --hard');+ });++ it('reports movement on a branch with no upstream to clear it against', async () => {+ // No `origin` at all: an unpushed commit is unreviewed by definition, so the+ // narrowed guard must not go quiet just because it cannot compare.+ const baseline = await capturePrimaryCheckoutState(repo);+ await commit('branch jacked, nowhere to push');++ const verdict = await detectPrimaryCheckoutDrift(baseline);+ expect(verdict.drifted).toBe(true);+ expect(verdict.unpushedCount).toBeNull();+ expect(verdict.commitCount).toBe(1);+ });+it('reports no drift when there is nothing to check', async () => {expect(await detectPrimaryCheckoutDrift(null)).toEqual({ drifted: false });expect(await detectPrimaryCheckoutDrift({ path: repo })).toEqual({ drifted: false });diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 3761ef9ec5..912072d45e 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -595,6 +595,12 @@ export async function finalizeAgent({emitLog('warn', `⚠️ ${drift.message} — reported by ${agentId}; PortOS will not repair it automatically`, {agentId, taskId: task?.id, category: drift.category});+ } else if (drift.fastForwarded) {+ // Movement without stranded commits — a pull, not a branch-jack. Logged so+ // "the primary moved during this run" stays visible without being a failure.+ emitLog('info', `↪️ Primary checkout moved ${drift.commitCount ?? '?'} commit(s) during ${agentId}, all already upstream — not a branch-jack`, {+ agentId, taskId: task?.id+ });}// A drift downgrade only OVERRIDES a run that would otherwise have been// recorded a success. On a run that already failed, the original analysis is