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: attribute primary-checkout drift by patch-id before failing a run (#3703)
Adam Eivyf6e4436b9d49
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex a9897d76b0..c0d93d3473 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Stability+- **[issue-3703] A worktree agent is no longer failed for commits it didn't write.** The primary-checkout guard used to fail any worktree agent whose run window overlapped commits landing on the shared primary checkout — but a concurrent coding-on-main agent, your own terminal, or `update.sh`'s pull can move it too, so read-only reasoners and correctly-behaved agents were being blamed and escalated to you. The guard now attributes the stranded commits by patch-id (`git cherry`, so a cherry-picked or rebased copy still counts) to the agent's own branch: only commits actually traceable to that agent fail the run. Everything else is warn-logged — the unreviewed commits on the primary are still surfaced — but a run that didn't cause them stays a success.+- **[issue-3704] The UI no longer goes blank when iCloud offloads a synced file** — macOS "Optimize Mac Storage" can evict MortalLoom and Obsidian files to the cloud. Reading one of those offloaded files used to stall indefinitely, and a handful of stalls was enough to freeze every page in PortOS while the server still looked healthy — pages simply never loaded and only a restart brought them back. PortOS now detects an offloaded file up front, skips the read, asks iCloud to download it in the background, and reports "temporarily unavailable" for just that record until it arrives.## Addeddiff --git a/server/lib/primaryCheckoutGuard.js b/server/lib/primaryCheckoutGuard.jsindex e3b699c581..08d5c94bdf 100644--- a/server/lib/primaryCheckoutGuard.js+++ b/server/lib/primaryCheckoutGuard.js@@ -26,6 +26,21 @@* A branch with no upstream to compare against can't be cleared, so it still* reports (an unpushed commit is unreviewed by definition).*+ * 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`,+ * or any background flow can strand commits on it — so before blaming the run,+ * the guard asks whether THIS agent could have produced them (#3703). It+ * attributes the stranded commits to the agent's own worktree branch by PATCH-ID+ * (`git cherry`, not raw SHA, so a cherry-picked or rebased copy still matches).+ * Only an attributed drift downgrades a successful run; anything the agent+ * demonstrably did not author — a read-only reasoner that never branched, or+ * commits with no patch-equivalent on the agent's branch — is carried as+ * `{ drifted: false, unattributed: true }`: warn-logged (unreviewed commits on+ * `main` are worth surfacing) but not failed. The asymmetry is deliberate — a+ * missed branch-jack still leaves a warn log and recoverable commits, while a+ * false failure escalates to a human and dents the task type's success rate.+ ** 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@@ -136,15 +151,61 @@ async function resolveUpstreamRef(checkoutPath, branch) {}/**- * 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".+ * Resolve the agent's own worktree branch to a ref that exists in the primary+ * checkout — the local branch first, then its `origin/<branch>` remote-tracking+ * form (the agent may have pushed and had its local ref pruned). Returns null+ * when neither resolves, the name is empty, or git could not be run — every one+ * of which the caller treats as "cannot attribute, so do not blame".+ */+async function resolveAgentBranchRef(checkoutPath, agentBranch) {+ if (!agentBranch || typeof agentBranch !== 'string') return null;+ for (const ref of [agentBranch, `refs/remotes/origin/${agentBranch}`]) {+ const result = await execGit(+ ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`],+ checkoutPath,+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },+ ).catch(() => null);+ if (firstLine(result)) return ref;+ }+ return null;+}++/**+ * Was the drift plausibly THIS agent's doing (#3703)? Compares the stranded+ * commits (everything the drifted checkout carries past `strandedBase`) against+ * the agent's own worktree branch by PATCH-ID via `git cherry`, so a+ * cherry-picked or rebased copy still matches — a raw-SHA check would miss+ * exactly the case the original #3680 incident could have produced.+ *+ * Returns true when AT LEAST ONE stranded commit is the agent's own — either+ * literally on its branch (same SHA) or patch-equivalent to one there (a+ * cherry-picked / rebased copy). Every uncertain outcome — no branch name, a+ * branch that does not resolve, a branch with no commits of its own (Case A: a+ * read-only reasoner that never branched), or a failed git call — returns FALSE+ * (unattributed), failing open by design. NON-THROWING, like the rest of the+ * module.*/-async function countUnpushedCommits(checkoutPath, branch) {- const upstream = await resolveUpstreamRef(checkoutPath, branch);- if (!upstream) return null;- return await countCommitsAhead(checkoutPath, upstream, branch);+async function isDriftAttributableToAgent(checkoutPath, { strandedBase, driftedHead, strandedCount, agentBranch }) {+ const agentRef = await resolveAgentBranchRef(checkoutPath, agentBranch);+ if (!agentRef) return false;+ // A read-only reasoner's worktree branch resolves but carries no commit of its+ // own (it never left the base), so it cannot have authored a stranded commit.+ const ownCommits = await countCommitsAhead(checkoutPath, strandedBase, agentRef);+ if (!ownCommits) return false;+ // `git cherry <upstream> <head> <limit>` walks the stranded commits (`limit..head`)+ // and prints a line for each that <upstream> (the agent's branch) does NOT already+ // contain: `-` when a patch-equivalent copy exists there, `+` when the commit is+ // foreign to it. Commits the agent's branch holds outright (same SHA) are omitted+ // entirely. So a stranded commit is the agent's UNLESS git cherry marks it `+`;+ // the drift is attributed unless EVERY stranded commit is foreign.+ const cherry = await execGit(+ ['cherry', agentRef, driftedHead, strandedBase],+ checkoutPath,+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },+ ).catch(() => null);+ if (!cherry || cherry.exitCode !== 0) return false;+ const foreign = (cherry.stdout || '').split('\n').filter(line => line.startsWith('+')).length;+ return strandedCount > foreign;}/** Short SHA for human-readable prose. */@@ -162,13 +223,20 @@ const short = sha => String(sha || '').slice(0, 9);* 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.+ * - `{ drifted: false, unattributed: true, … }` — commits WERE stranded, but+ * none are patch-equivalent to a commit on the agent's own branch, so this+ * run demonstrably did not put them there (a concurrent actor did). Carries+ * the `message` so the caller can warn-log the unreviewed commits without+ * failing the run. See the module header on the fail-open asymmetry.+ * - `{ drifted: true, … }` — the checkout ended on a different branch, or it+ * carries commits the upstream does not have AND those commits are+ * attributable to the agent's own branch by patch-id.** @param {{path: string, branch: string, head: string}|null} baseline stamped by* `capturePrimaryCheckoutState` at spawn time* @param {{ agentBranch?: string|null }} [options] the agent's own worktree- * branch, named in the recovery prose because it is where the same commits+ * branch, used both to ATTRIBUTE the stranded commits by patch-id and, once+ * attributed, named in the recovery prose because it is where the same commits* almost certainly also live*/export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null } = {}) {@@ -179,9 +247,13 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = nullif (!current) return { drifted: false };if (current.branch === baseline.branch && current.head === baseline.head) return { drifted: false };+ const upstream = await resolveUpstreamRef(baseline.path, current.branch);const [commitCount, unpushedCount] = await Promise.all([countCommitsAhead(baseline.path, baseline.head, current.head),- countUnpushedCommits(baseline.path, current.branch),+ // Commits the branch carries that its upstream does not — the only commits a+ // branch-jack actually strands. Null (not 0) when there is no upstream to+ // compare against, so "verified clean" never masquerades as "could not check".+ upstream ? countCommitsAhead(baseline.path, upstream, current.branch) : Promise.resolve(null),]);// Same branch, nothing local-only: the checkout was pulled forward onto commits@@ -191,6 +263,24 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = nullreturn { drifted: false, fastForwarded: true, baseline, current, commitCount };}+ const message = formatDriftMessage({ baseline, current, commitCount });++ // Second gate (#3703): stranded commits are only a failure if THIS agent could+ // have produced them. A pure branch switch strands nothing (nothing to blame on+ // anyone), so attribution runs only when there is a resolvable stranded commit.+ const strandedCount = unpushedCount === null ? commitCount : unpushedCount;+ if (strandedCount > 0) {+ const attributed = await isDriftAttributableToAgent(baseline.path, {+ strandedBase: upstream || baseline.head,+ driftedHead: current.head,+ strandedCount,+ agentBranch,+ });+ if (!attributed) {+ return { drifted: false, unattributed: true, baseline, current, commitCount, unpushedCount, message };+ }+ }+return {drifted: true,reason: PRIMARY_CHECKOUT_MUTATED_REASON,@@ -199,7 +289,7 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = nullcurrent,commitCount,unpushedCount,- message: formatDriftMessage({ baseline, current, commitCount }),+ message,suggestedFix: formatDriftRecovery({ current, baseline, commitCount, unpushedCount, agentBranch }),};}diff --git a/server/lib/primaryCheckoutGuard.test.js b/server/lib/primaryCheckoutGuard.test.jsindex aedf87c53c..2355e8551e 100644--- a/server/lib/primaryCheckoutGuard.test.js+++ b/server/lib/primaryCheckoutGuard.test.js@@ -94,12 +94,21 @@ describe('detectPrimaryCheckoutDrift', () => {expect(verdict).toEqual({ drifted: false });});- it('detects commits landed on the primary checkout during the run', async () => {+ it('detects commits landed on the primary checkout when they are the agent\'s own', async () => {+ const agentBranch = 'cos/task-x/agent-y';const baseline = await capturePrimaryCheckoutState(repo);+ // The agent made its two commits on its OWN worktree branch...+ await execGit(['checkout', '-b', agentBranch], repo);await commit('branch jacked one');await commit('branch jacked two');+ const agentTip = (await capturePrimaryCheckoutState(repo)).head;+ // ...and a stray `/do:pr` from the worktree applied patch-equivalent copies+ // onto the PRIMARY's main (cherry-pick → different SHAs, so only the patch-id+ // gate attributes them — a raw-SHA check would miss this).+ await execGit(['checkout', 'main'], repo);+ await execGit(['cherry-pick', `${baseline.head}..${agentTip}`], repo);- const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: 'cos/task-x/agent-y' });+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });expect(verdict.drifted).toBe(true);expect(verdict.reason).toBe(PRIMARY_CHECKOUT_MUTATED_REASON);expect(verdict.category).toBe(PRIMARY_CHECKOUT_MUTATED_CATEGORY);@@ -108,10 +117,67 @@ describe('detectPrimaryCheckoutDrift', () => {expect(verdict.message).toContain('main');expect(verdict.message).toContain('2 new commits');// ...and the fix names the agent branch plus the exact recovery command.- expect(verdict.suggestedFix).toContain('cos/task-x/agent-y');+ expect(verdict.suggestedFix).toContain(agentBranch);expect(verdict.suggestedFix).toContain(`git -C ${repo} reset --hard origin/main`);});+ it('does NOT blame the agent for a stranded commit it did not author (unattributed)', async () => {+ await addOrigin();+ const agentBranch = 'cos/task-x/agent-y';+ const baseline = await capturePrimaryCheckoutState(repo);+ // The agent's own branch carries an UNRELATED commit of its own...+ await execGit(['checkout', '-b', agentBranch], repo);+ await commit('the agent\'s actual work');+ await execGit(['checkout', 'main'], repo);+ // ...while a different actor stranded a commit on the primary's main.+ await commit('someone else\'s commit');++ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });+ // Stranded, but no patch-equivalent on the agent branch → surfaced, not failed.+ expect(verdict.drifted).toBe(false);+ expect(verdict.unattributed).toBe(true);+ expect(verdict.unpushedCount).toBe(1);+ expect(verdict.message).toContain('main');+ expect(verdict.suggestedFix).toBeUndefined();+ });++ 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.+ await commit('a big commit from elsewhere');++ // The reasoner carried no worktree branch at all — it is structurally+ // impossible for it to have authored the commit, so it must not be blamed.+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: null });+ expect(verdict.drifted).toBe(false);+ expect(verdict.unattributed).toBe(true);+ expect(verdict.commitCount).toBe(1);+ });++ it('never attributes when the agent branch has zero commits of its own', async () => {+ await addOrigin();+ const agentBranch = 'cos/task-x/agent-y';+ // Branch exists but points at the same commit as origin/main — no own commits.+ await execGit(['branch', agentBranch, 'origin/main'], repo);+ const baseline = await capturePrimaryCheckoutState(repo);+ await commit('a commit from another actor');++ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });+ expect(verdict.drifted).toBe(false);+ expect(verdict.unattributed).toBe(true);+ });++ it('degrades to unattributed when the agent branch cannot be resolved', async () => {+ await addOrigin();+ const baseline = await capturePrimaryCheckoutState(repo);+ await commit('stranded by an unknown actor');++ // A branch name that resolves to nothing is uncertainty, not proof — fail open.+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: 'cos/never-created' });+ expect(verdict.drifted).toBe(false);+ expect(verdict.unattributed).toBe(true);+ });+it('detects a branch switch even with no new commits', async () => {const baseline = await capturePrimaryCheckoutState(repo);await execGit(['checkout', '-b', 'someone-elses-branch'], repo);@@ -139,11 +205,19 @@ describe('detectPrimaryCheckoutDrift', () => {it('still reports the agent\'s own commit when a pull landed alongside it', async () => {await addOrigin();+ const agentBranch = 'cos/task-x/agent-y';const baseline = await capturePrimaryCheckoutState(repo);- await pullFromOrigin('landed via a merged PR');+ // The agent's real commit lives on its own branch...+ await execGit(['checkout', '-b', agentBranch], repo);await commit('branch jacked');+ const agentTip = (await capturePrimaryCheckoutState(repo)).head;+ await execGit(['checkout', 'main'], repo);+ // ...a pull brought an unrelated merged commit onto main...+ await pullFromOrigin('landed via a merged PR');+ // ...and the agent's own commit was (wrongly) applied to main too.+ await execGit(['cherry-pick', agentTip], repo);- const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: 'cos/task-x/agent-y' });+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });expect(verdict.drifted).toBe(true);// HEAD moved 2, but only 1 is stranded — the recovery prose quotes the// stranded count, not the movement.@@ -166,13 +240,18 @@ describe('detectPrimaryCheckoutDrift', () => {expect(verdict.suggestedFix).not.toContain('reset --hard');});- it('reports movement on a branch with no upstream to clear it against', async () => {+ it('reports an attributed commit 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.+ // guard must not go quiet just because it cannot compare against an upstream —+ // it attributes against the run baseline instead. The commit IS the agent's.+ const agentBranch = 'cos/task-x/agent-y';const baseline = await capturePrimaryCheckoutState(repo);+ await execGit(['checkout', '-b', agentBranch], repo);await commit('branch jacked, nowhere to push');+ await execGit(['checkout', 'main'], repo);+ await execGit(['merge', '--ff-only', agentBranch], repo);- const verdict = await detectPrimaryCheckoutDrift(baseline);+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch });expect(verdict.drifted).toBe(true);expect(verdict.unpushedCount).toBeNull();expect(verdict.commitCount).toBe(1);diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 912072d45e..8b593d3a2a 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -595,6 +595,15 @@ 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.unattributed) {+ // #3703: commits WERE stranded on the primary, but none are patch-equivalent+ // to this agent's own branch — another actor (a coding-on-main agent, the+ // human's terminal, `update.sh`'s pull) moved it. Unreviewed commits on the+ // primary are still worth surfacing, but this run did not cause them, so it is+ // warn-logged WITHOUT downgrading an otherwise-successful run to a failure.+ emitLog('warn', `⚠️ ${drift.message} — not attributable to ${agentId}; surfacing without failing the run`, {+ agentId, taskId: task?.id+ });} 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.diff --git a/server/services/agentFinalization.primaryCheckoutDrift.test.js b/server/services/agentFinalization.primaryCheckoutDrift.test.jsindex f3463495d7..425354d24a 100644--- a/server/services/agentFinalization.primaryCheckoutDrift.test.js+++ b/server/services/agentFinalization.primaryCheckoutDrift.test.js@@ -75,6 +75,7 @@ vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async ()vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));import { checkPrimaryCheckoutDrift, finalizeAgent } from './agentFinalization.js';+import { emitLog } from './cosEvents.js';import { PRIMARY_CHECKOUT_MUTATED_CATEGORY, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';const BASELINE = { path: '/example/repo', branch: 'main', head: 'a'.repeat(40) };@@ -90,6 +91,18 @@ const DRIFT = {suggestedFix: 'git -C /example/repo reset --hard origin/main',};+// #3703: commits were stranded on the primary, but none are patch-equivalent to+// this agent's own branch — a concurrent actor moved it. Warn-logged, not failed.+const UNATTRIBUTED_DRIFT = {+ drifted: false,+ unattributed: true,+ baseline: BASELINE,+ current: { path: '/example/repo', branch: 'main', head: 'b'.repeat(40) },+ commitCount: 1,+ unpushedCount: 1,+ message: 'Worktree agent mutated the primary checkout /example/repo: branch main, HEAD aaaaaaaaa → bbbbbbbbb (1 new commit)',+};+const task = () => ({ id: 'task-1', taskType: 'internal', description: 'ship something', metadata: {} });const finalize = (overrides = {}) => finalizeAgent({@@ -191,4 +204,19 @@ describe('finalizeAgent — a worktree run that mutated the primary is not a sucawait finalize();expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));});++ it('warn-logs an unattributed drift but does NOT downgrade a successful run', async () => {+ // #3703: the primary moved and stranded commits, but they are not this agent's+ // (no patch-equivalent on its branch). Surfacing without failing the run is the+ // whole point — a false failure escalates to a human and dents the success rate.+ detectPrimaryCheckoutDriftMock.mockResolvedValue(UNATTRIBUTED_DRIFT);+ await finalize({ runId: 'run-1' });++ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');+ // The run record is a clean success — no error analysis, not force-failed.+ expect(completeAgentRunMock).toHaveBeenCalledWith('run-1', 'done', 0, 1000, null, null);+ // ...but the unreviewed commits are still surfaced.+ expect(emitLog).toHaveBeenCalledWith('warn', expect.stringContaining('not attributable to agent-1'), expect.anything());+ });});