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: detect worktree agents that mutate the primary checkout (#3680)

[._.]/ Adam Eivy4e4770cf393a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2ff449169e..86e035b873 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,6 +20,8 @@
## Fixed
+- **A CoS agent that commits to the primary checkout instead of its own worktree is now reported instead of recorded as a success.** A worktree-isolated agent running `/do:pr` applied its commits onto the primary checkout's local `main`, where they sat unpushed and unreviewed — on an unprotected branch, so any later push would have landed them without a PR — while PortOS recorded the run as completed. Every worktree run now stamps the primary checkout's branch and HEAD at spawn and re-reads them in the shared finalize path (so all three spawn modes are covered, not just TUI). A checkout that moved fails the run as `primary-checkout-mutated`, naming the drifted branch, the commit count, and the exact recovery command — and noting the commits are almost certainly on the agent's branch too. PortOS deliberately does not repair it: the repair is `git reset --hard`, which discards commits, and that stays your call. Runs that leave the primary alone are unaffected.
+
- **Universe Canon — "AI: differentiate cast" and per-character "AI: differentiate" now run.** Both threw `Stage pipeline-character-differentiate-cast not found` / `Stage pipeline-character-refine not found` on every install since they shipped: the prompt templates landed in `data.reference/prompts/stages/` but their `stage-config.json` entries were never authored, and `buildPrompt()` resolves the config entry first. Arc-verification **auto-resolve** (`pipeline-arc-resolve`) was dead the same way. All three entries now ship, migration 232 seeds them onto existing installs, and a new catalog-parity guard fails the build if a prompt template ever ships without its config entry again (or the reverse). The inverse gap on the Digital Twin side — ten stages whose config entry ships with no template, so each soul/twin AI pass silently runs its fallback — is tracked in #3644.
- A manual Autonomous-mode run now uses the series' own configured AI provider (the picker in the series header), matching scheduled runs and every other Pipeline action. It previously ignored `series.llm` and ran on the install's active provider, so the series header said one thing and the run did another. It stays a *soft* default: a stage pinned in Prompts keeps its pin, and an unavailable provider falls back instead of failing the run.
diff --git a/server/lib/README.md b/server/lib/README.md
index 695f02e7f5..a05459a483 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -189,6 +189,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`. |
+| `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. |
| `ytdlp.js` | `findYtDlp()` — cached discovery of the `yt-dlp` binary on PATH, mirrors `findFfmpeg()` in `ffmpeg.js`. Used by the track YouTube-import job. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 9be6b7e9ce..04913b1316 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -183,6 +183,7 @@ export * from './goalFeatureMap.js';
export * from './killWithEscalation.js';
export * from './openFolder.js';
export * from './processEnv.js';
+export * from './primaryCheckoutGuard.js';
export * from './pythonSetup.js';
export * from './vttTranscript.js';
export * from './ytdlp.js';
diff --git a/server/lib/primaryCheckoutGuard.js b/server/lib/primaryCheckoutGuard.js
new file mode 100644
index 0000000000..69fb9629fd
--- /dev/null
+++ b/server/lib/primaryCheckoutGuard.js
@@ -0,0 +1,181 @@
+/**
+ * Primary-checkout branch-jack detector (#3680).
+ *
+ * A CoS agent spawned with a worktree must only ever write inside that
+ * worktree. On 2026-08-09 one didn't: running `/do:pr` from its worktree it
+ * applied its three commits onto the PRIMARY checkout's local `main`, where
+ * they sat unpushed and unreviewed. `main` is unprotected on this repo, so a
+ * later `git push` from the primary would have landed them without a PR.
+ *
+ * The chosen remedy is DETECT-AND-REPORT, not prevention and not auto-repair:
+ *
+ * - Prevention (making the primary read-only for the duration of a run) would
+ * break the many legitimate flows that read and write the primary checkout.
+ * - Auto-repair means `git reset --hard`, which DISCARDS commits. That stays a
+ * human decision, so the failure message states the recovery command instead
+ * of running it — and notes that the same work also exists on the agent's
+ * own branch, which is what makes the reset safe.
+ *
+ * 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
+ * in the shared finalize path (`agentFinalization.js`) — the one chokepoint all
+ * three spawn modes (TUI, direct CLI, runner) already funnel through, so the
+ * guard is not TUI-only without triplicating it.
+ *
+ * Every function here is NON-THROWING, for the same reason `gitCommitProbe.js`
+ * is: it runs on the agent-completion path, outside the Express request
+ * lifecycle, where a rejection has nothing to bubble to. An unreadable or
+ * missing checkout, or a wedged git, degrades to "no drift observed" — the guard
+ * never manufactures a failure out of a check that could not run.
+ */
+
+import { execGit } from './execGit.js';
+
+/**
+ * The completion reason a drifted run is recorded under. Registered in
+ * `COMPLETION_REASON_ANALYSES` (agentErrorAnalysis.js) so the analyzer has a
+ * verdict for it instead of falling through to a keyword sweep of the
+ * transcript.
+ */
+export const PRIMARY_CHECKOUT_MUTATED_REASON = 'primary-checkout-mutated';
+
+/**
+ * The taxonomy token the drift is classified under. Reuses the pre-existing
+ * `git-error` category rather than minting a new one, so every downstream
+ * consumer (auto-fix tiers, learning buckets, the failure ledger) keeps
+ * classifying it with no new token to teach them. Deliberately NOT in
+ * `ENVIRONMENTAL_ERROR_CATEGORIES`: this is the run's own misbehavior, and it
+ * should dent the task type's measured success rate.
+ */
+export const PRIMARY_CHECKOUT_MUTATED_CATEGORY = 'git-error';
+
+/**
+ * What a human has to do before this task may run again. Lives here so the
+ * finalize-path analysis and the `COMPLETION_REASON_ANALYSES` registration can't
+ * drift apart on it. A retry cannot repair a mutated checkout, so this
+ * deliberately escalates rather than blind-retrying.
+ */
+export const PRIMARY_CHECKOUT_MUTATED_ESCALATION =
+ 'A worktree agent committed to the primary checkout. Confirm the commits are preserved (agent branch / open PR), restore the primary, then approve the retry.';
+
+/** Bound on every git call here — this sits on finalize; nothing may wedge it. */
+const GIT_TIMEOUT_MS = 10_000;
+
+/** First line of a probe-shaped execGit result, or null. */
+function firstLine(result) {
+ if (!result || result.exitCode !== 0) return null;
+ const value = (result.stdout || '').trim();
+ return value || null;
+}
+
+/**
+ * Read a checkout's current branch + HEAD SHA. Returns null when the path is
+ * absent, is not a repo, has no commits yet, or git could not be run.
+ *
+ * A DETACHED head reports its branch as the literal `HEAD` and is kept as-is
+ * (rather than nulled, the way `resolveWorkspaceBranch` does it) — this value is
+ * only ever compared against a later reading of itself, and "detached, then on a
+ * branch" is exactly the kind of movement worth reporting.
+ *
+ * @param {string} checkoutPath
+ * @returns {Promise<{path: string, branch: string, head: string}|null>}
+ */
+export async function capturePrimaryCheckoutState(checkoutPath) {
+ if (!checkoutPath || typeof checkoutPath !== 'string') return null;
+ const options = { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS };
+ const [branchResult, headResult] = await Promise.all([
+ execGit(['rev-parse', '--abbrev-ref', 'HEAD'], checkoutPath, options).catch(() => null),
+ execGit(['rev-parse', 'HEAD'], checkoutPath, options).catch(() => null),
+ ]);
+ const branch = firstLine(branchResult);
+ const head = firstLine(headResult);
+ if (!branch || !head) return null;
+ return { path: checkoutPath, branch, head };
+}
+
+/**
+ * How many commits `head` is ahead of `baseHead`. Returns null (not 0) when the
+ * range can't be resolved — a rewritten/pruned baseline commit, or a git that
+ * timed out — so the prose can say "moved" without asserting a count it doesn't
+ * have.
+ */
+async function countCommitsAhead(checkoutPath, baseHead, head) {
+ const result = await execGit(
+ ['rev-list', '--count', `${baseHead}..${head}`],
+ checkoutPath,
+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },
+ ).catch(() => null);
+ const value = firstLine(result);
+ const count = value === null ? NaN : parseInt(value, 10);
+ return Number.isFinite(count) ? count : null;
+}
+
+/** Short SHA for human-readable prose. */
+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:
+ * - `{ 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.
+ *
+ * @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
+ * almost certainly also live
+ */
+export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null } = {}) {
+ if (!baseline?.path || !baseline?.branch || !baseline?.head) return { drifted: false };
+ const current = await capturePrimaryCheckoutState(baseline.path);
+ // Unreadable now (deleted, mid-rebase, git wedged): we verified nothing, so we
+ // report nothing rather than inventing a failure.
+ if (!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);
+ return {
+ drifted: true,
+ reason: PRIMARY_CHECKOUT_MUTATED_REASON,
+ category: PRIMARY_CHECKOUT_MUTATED_CATEGORY,
+ baseline,
+ current,
+ commitCount,
+ message: formatDriftMessage({ baseline, current, commitCount }),
+ suggestedFix: formatDriftRecovery({ current, commitCount, agentBranch }),
+ };
+}
+
+/** Human-readable "what moved". Pure. */
+export function formatDriftMessage({ baseline, current, commitCount }) {
+ 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'}`;
+ return `Worktree agent mutated the primary checkout ${baseline.path}: ${branchPart}, HEAD ${short(baseline.head)} → ${short(current.head)} (${countPart})`;
+}
+
+/**
+ * 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.
+ */
+export function formatDriftRecovery({ current, commitCount, agentBranch }) {
+ 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'}`;
+ 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.',
+ ].join(' ');
+}
diff --git a/server/lib/primaryCheckoutGuard.test.js b/server/lib/primaryCheckoutGuard.test.js
new file mode 100644
index 0000000000..e8b473a3f5
--- /dev/null
+++ b/server/lib/primaryCheckoutGuard.test.js
@@ -0,0 +1,132 @@
+/**
+ * Branch-jack detector tests (#3680).
+ *
+ * Run against REAL git repositories in a temp dir rather than a mocked
+ * `execGit`: the whole value of this module is that it reads git state
+ * correctly, and a mock that returns whatever the test author expected `git
+ * rev-parse` to print proves nothing about that.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execGit } from './execGit.js';
+import {
+ capturePrimaryCheckoutState,
+ detectPrimaryCheckoutDrift,
+ formatDriftMessage,
+ formatDriftRecovery,
+ PRIMARY_CHECKOUT_MUTATED_CATEGORY,
+ PRIMARY_CHECKOUT_MUTATED_REASON,
+} from './primaryCheckoutGuard.js';
+
+let repo;
+let scratch;
+
+async function commit(subject) {
+ await writeFile(join(repo, `${subject.replace(/\W+/g, '-')}.txt`), subject);
+ await execGit(['add', '-A'], repo);
+ await execGit(['commit', '-m', subject], repo);
+}
+
+beforeEach(async () => {
+ scratch = await mkdtemp(join(tmpdir(), 'portos-branch-jack-'));
+ repo = join(scratch, 'primary');
+ await execGit(['init', '-b', 'main', repo], scratch);
+ // Local identity so the suite doesn't depend on (or read) the host's git config.
+ await execGit(['config', 'user.email', '[email protected]'], repo);
+ await execGit(['config', 'user.name', 'Example Agent'], repo);
+ await commit('initial');
+});
+
+afterEach(async () => {
+ await rm(scratch, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('capturePrimaryCheckoutState', () => {
+ it('reads the current branch and HEAD', async () => {
+ const state = await capturePrimaryCheckoutState(repo);
+ expect(state.path).toBe(repo);
+ expect(state.branch).toBe('main');
+ expect(state.head).toMatch(/^[0-9a-f]{40}$/);
+ });
+
+ it('returns null for a missing path, a non-repo, and a non-string', async () => {
+ expect(await capturePrimaryCheckoutState(join(scratch, 'nope'))).toBeNull();
+ expect(await capturePrimaryCheckoutState(scratch)).toBeNull();
+ expect(await capturePrimaryCheckoutState(null)).toBeNull();
+ expect(await capturePrimaryCheckoutState('')).toBeNull();
+ });
+});
+
+describe('detectPrimaryCheckoutDrift', () => {
+ it('reports no drift when the primary checkout is untouched', async () => {
+ const baseline = await capturePrimaryCheckoutState(repo);
+ // Simulate the run happening entirely elsewhere: nothing touches `repo`.
+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: 'claim/issue-1' });
+ expect(verdict).toEqual({ drifted: false });
+ });
+
+ it('detects commits landed on the primary checkout during the run', async () => {
+ const baseline = await capturePrimaryCheckoutState(repo);
+ await commit('branch jacked one');
+ await commit('branch jacked two');
+
+ const verdict = await detectPrimaryCheckoutDrift(baseline, { agentBranch: 'cos/task-x/agent-y' });
+ expect(verdict.drifted).toBe(true);
+ expect(verdict.reason).toBe(PRIMARY_CHECKOUT_MUTATED_REASON);
+ expect(verdict.category).toBe(PRIMARY_CHECKOUT_MUTATED_CATEGORY);
+ expect(verdict.commitCount).toBe(2);
+ // The message names the drifted branch and the commit count...
+ 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(`git -C ${repo} reset --hard origin/main`);
+ });
+
+ it('detects a branch switch even with no new commits', async () => {
+ const baseline = await capturePrimaryCheckoutState(repo);
+ await execGit(['checkout', '-b', 'someone-elses-branch'], repo);
+
+ const verdict = await detectPrimaryCheckoutDrift(baseline);
+ expect(verdict.drifted).toBe(true);
+ expect(verdict.commitCount).toBe(0);
+ expect(verdict.message).toContain('main → someone-elses-branch');
+ });
+
+ 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 });
+ // A checkout that vanished mid-run verified nothing, so it must not
+ // manufacture a failure.
+ const baseline = await capturePrimaryCheckoutState(repo);
+ await rm(repo, { recursive: true, force: true });
+ expect(await detectPrimaryCheckoutDrift(baseline)).toEqual({ drifted: false });
+ });
+
+ it('still reports the drift when the commit count is unresolvable', async () => {
+ const baseline = { path: repo, branch: 'main', head: 'f'.repeat(40) };
+ const verdict = await detectPrimaryCheckoutDrift(baseline);
+ expect(verdict.drifted).toBe(true);
+ expect(verdict.commitCount).toBeNull();
+ expect(verdict.message).toContain('commit count unresolved');
+ });
+});
+
+describe('prose helpers', () => {
+ const baseline = { path: '/example/repo', branch: 'main', head: 'a'.repeat(40) };
+ const current = { path: '/example/repo', branch: 'main', head: 'b'.repeat(40) };
+
+ it('singularizes a one-commit drift', () => {
+ expect(formatDriftMessage({ baseline, current, commitCount: 1 })).toContain('(1 new commit)');
+ expect(formatDriftRecovery({ current, commitCount: 1, agentBranch: null })).toContain('1 commit ');
+ });
+
+ it('never tells the user PortOS already fixed it', () => {
+ const fix = formatDriftRecovery({ current, commitCount: 3, agentBranch: 'claim/issue-3680' });
+ expect(fix).toContain('DISCARDS');
+ expect(fix).toContain('PortOS will not run it for you');
+ });
+});
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index 34d2e77f82..d48225d6a5 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -13,6 +13,7 @@ import { redactOutput } from '../lib/commandSecurity.js';
import { stripAnsi } from '../lib/ansiStrip.js';
import { retryHoldMetadata } from '../lib/taskRetryHold.js';
import { isTruthyMeta } from './agentState.js';
+import { PRIMARY_CHECKOUT_MUTATED_CATEGORY, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';
// Max retries before blocking a task
export const MAX_TASK_RETRIES = 3;
@@ -668,6 +669,21 @@ export const COMPLETION_REASON_ANALYSES = {
// task for a human would park work that a plain retry fixes. A genuinely
// misconfigured command still surfaces — it fails identically every attempt
// and blocks on MAX_TASK_RETRIES, with the runner's own message attached.
+ // #3680: a worktree-isolated agent committed to the PRIMARY checkout instead
+ // of its worktree, leaving unreviewed commits on an unprotected branch. The
+ // finalize path (agentFinalization.js) builds a richer analysis naming the
+ // actual branch, commit count, and recovery command; this registration is the
+ // fallback for anything that re-analyzes the reason without that context (a
+ // recovered/archived run), and keeps the reason from falling through to a
+ // keyword sweep of the transcript. Reuses the existing `git-error` token
+ // rather than minting one, so the downstream taxonomies keep classifying it.
+ [PRIMARY_CHECKOUT_MUTATED_REASON]: {
+ category: PRIMARY_CHECKOUT_MUTATED_CATEGORY,
+ actionable: true,
+ escalation: PRIMARY_CHECKOUT_MUTATED_ESCALATION,
+ message: 'Worktree agent mutated the primary checkout',
+ suggestedFix: 'The agent was given its own git worktree and committed to the primary checkout anyway, so the primary is carrying commits nothing reviewed. The same work is almost certainly on the agent\'s branch too. Inspect the primary with `git log --oneline origin/<branch>..<branch>` and, once the content is confirmed preserved, restore it with `git reset --hard origin/<branch>` — PortOS will not run that for you, because it discards commits.'
+ },
'spawn-rejected': {
category: 'spawn-error',
actionable: false,
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index fb561b5e84..3761ef9ec5 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -24,7 +24,7 @@ import { emitLog } from './cosEvents.js';
// `agentManagement.js`. This module is a LEAF that both transition modules
// import, which puts it inside the facade's closure, so the facade is out of
// reach here.
-import { getAgent, updateAgent, completeAgent } from './cosAgentLifecycle.js';
+import { getAgent, getAgentRecord, updateAgent, completeAgent } from './cosAgentLifecycle.js';
import { updateTask } from './cos.js';
import { getActiveProvider } from './providers.js';
import { markProviderUsageLimit, markProviderUnavailable } from './providerStatus.js';
@@ -34,6 +34,7 @@ import { completeExecution, errorExecution } from './toolStateMachine.js';
import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
+import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';
import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion } from './taskTypeHooks.js';
import { processAgentCompletion } from './agentCompletion.js';
import { extractSimplifySummaries } from './agentSummaryExtraction.js';
@@ -290,6 +291,47 @@ export async function verifyPrClaim({ task, workspacePath, success, prExpected }
};
}
+/**
+ * Branch-jack check (#3680): did this WORKTREE agent commit to the primary
+ * checkout instead of its own worktree?
+ *
+ * Reads the `primaryCheckoutBaseline` that `agentLifecycle.js` stamped onto the
+ * agent record at spawn time and re-reads that checkout now. Living here rather
+ * than in the TUI spawner is what makes the guard apply to all three spawn modes
+ * — TUI `finish()`, direct-CLI `close`, and runner-mode `handleAgentCompletion`
+ * all funnel through `finalizeAgent` — without triplicating it.
+ *
+ * Non-worktree runs carry no baseline (they legitimately work IN the primary),
+ * so they short-circuit to "no drift" before any git call.
+ *
+ * @returns {Promise<{drifted: boolean, message?: string, suggestedFix?: string, category?: string}>}
+ */
+export async function checkPrimaryCheckoutDrift(agentId) {
+ const agent = await getAgentRecord(agentId).catch(() => null);
+ const baseline = agent?.metadata?.primaryCheckoutBaseline || null;
+ if (!baseline) return { drifted: false };
+ return await detectPrimaryCheckoutDrift(baseline, { agentBranch: agent?.metadata?.worktreeBranch || null });
+}
+
+/**
+ * The `errorAnalysis` shape for a detected branch-jack. `actionable` because a
+ * human has to decide whether to discard the primary's commits — a retry cannot
+ * repair this, and silently retrying would leave the mutated checkout in place.
+ */
+function primaryCheckoutDriftAnalysis(drift) {
+ return {
+ category: drift.category,
+ // Observed by the spawner from the checkout's own git state, not scraped out
+ // of the transcript — the same provenance rule the structural analyses use.
+ origin: 'runner',
+ completionReason: PRIMARY_CHECKOUT_MUTATED_REASON,
+ actionable: true,
+ escalation: PRIMARY_CHECKOUT_MUTATED_ESCALATION,
+ message: drift.message,
+ suggestedFix: drift.suggestedFix
+ };
+}
+
/**
* The `errorAnalysis` shape for a failed PR verification. Non-actionable so the
* task RETRIES (a re-run can open the missing PR, or find the forge back) rather
@@ -541,8 +583,30 @@ export async function finalizeAgent({
return { ok: true };
});
- const success = reportedSuccess && prVerdict.ok;
- const errorAnalysis = prVerdict.ok ? reportedErrorAnalysis : prVerificationAnalysis(prVerdict);
+ // #3680: a worktree agent that committed to the PRIMARY checkout left
+ // unreviewed commits on an unprotected branch. Same posture as the PR check —
+ // a throw is not a verdict, so fall back to "no drift" rather than
+ // manufacturing a failure out of a check that never ran.
+ const drift = await checkPrimaryCheckoutDrift(agentId).catch(err => {
+ emitLog('warn', `⚠️ Primary-checkout drift check failed for ${agentId}: ${err.message}`, { agentId });
+ return { drifted: false };
+ });
+ if (drift.drifted) {
+ emitLog('warn', `⚠️ ${drift.message} — reported by ${agentId}; PortOS will not repair it automatically`, {
+ agentId, taskId: task?.id, category: drift.category
+ });
+ }
+ // 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
+ // the better diagnosis of why it failed, and the branch-jack is already on the
+ // record via the warn above — replacing it would trade a real cause for a
+ // side effect. Same reason `terminatedByUser` keeps its own verdict.
+ const driftDowngrade = drift.drifted && reportedSuccess && !terminatedByUser;
+
+ const success = reportedSuccess && prVerdict.ok && !driftDowngrade;
+ const errorAnalysis = driftDowngrade
+ ? primaryCheckoutDriftAnalysis(drift)
+ : prVerdict.ok ? reportedErrorAnalysis : prVerificationAnalysis(prVerdict);
if (!prVerdict.ok) {
emitLog('warn', `⚠️ ${prVerdict.message} — recording ${agentId} as needs-attention (${prVerdict.category}) rather than complete`, {
agentId, taskId: task?.id, branch: prVerdict.branch, category: prVerdict.category
@@ -612,8 +676,14 @@ export async function finalizeAgent({
// A PR-verification downgrade carries its own error text + reason: without
// them the agent card would render a bare "Failed" for a run that actually
// did everything but land its PR (or simply couldn't reach the forge).
- const finalError = prVerdict.ok ? error : prVerdict.message;
- const finalCompletionReason = prVerdict.ok ? completionReason : prVerdict.category;
+ // A branch-jack downgrade (#3680) carries its own text + reason for the same
+ // reason the PR downgrade does, and outranks it: the run may well have opened
+ // its PR fine and still mutated the primary, and THAT is the thing a human has
+ // to act on.
+ const finalError = driftDowngrade ? drift.message : prVerdict.ok ? error : prVerdict.message;
+ const finalCompletionReason = driftDowngrade
+ ? PRIMARY_CHECKOUT_MUTATED_REASON
+ : prVerdict.ok ? completionReason : prVerdict.category;
await completeAgent(agentId, {
success,
@@ -630,7 +700,7 @@ export async function finalizeAgent({
// Pass the downgrade explicitly: this run exited 0, so the run record would
// otherwise keep saying "success" for the one run we just concluded did not
// land its PR (#3358).
- await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis, prVerdict.ok ? null : false);
+ await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis, prVerdict.ok && !driftDowngrade ? null : false);
}
// LI hand-off execution verdict (#2779): stamp the per-proposal execution outcome into
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index e7f4eb461d..0c6ae84451 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -5,6 +5,7 @@ import { fileURLToPath } from 'url';
vi.mock('./cosAgentLifecycle.js', () => ({
getAgent: vi.fn(),
+ getAgentRecord: vi.fn(async () => null),
updateAgent: vi.fn(),
completeAgent: vi.fn(),
}));
diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.js
index bdc65268ac..28d09fd86b 100644
--- a/server/services/agentFinalization.prVerification.test.js
+++ b/server/services/agentFinalization.prVerification.test.js
@@ -37,6 +37,7 @@ vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
const completeAgentMock = vi.fn();
vi.mock('./cosAgentLifecycle.js', () => ({
getAgent: vi.fn(async () => null),
+ getAgentRecord: vi.fn(async () => null),
updateAgent: vi.fn(async () => null),
completeAgent: (...args) => completeAgentMock(...args),
}));
diff --git a/server/services/agentFinalization.primaryCheckoutDrift.test.js b/server/services/agentFinalization.primaryCheckoutDrift.test.js
new file mode 100644
index 0000000000..f3463495d7
--- /dev/null
+++ b/server/services/agentFinalization.primaryCheckoutDrift.test.js
@@ -0,0 +1,194 @@
+/**
+ * Tests for the branch-jack downgrade finalizeAgent applies (#3680).
+ *
+ * The bug: a CoS agent given its own git worktree ran `/do:pr` and applied its
+ * commits onto the PRIMARY checkout's local `main`, where they sat unpushed and
+ * unreviewed on an unprotected branch — while PortOS recorded the run as
+ * "completed". Detection lives in the SHARED finalize path so all three spawn
+ * modes (TUI, direct CLI, runner) are covered by one check.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../lib/execGit.js', () => ({
+ execGit: vi.fn(async () => ({ stdout: 'claim/issue-3680\n', stderr: '', exitCode: 0 })),
+}));
+
+vi.mock('./github.js', () => ({
+ findPullRequestForBranch: vi.fn(async () => ({ status: 'found', number: 7, url: 'https://example.com/pr/7' })),
+ ensureForgeReachable: vi.fn(async () => ({ ok: true, status: 'ok' })),
+}));
+vi.mock('./gitlab.js', () => ({ findMergeRequestForBranch: vi.fn() }));
+vi.mock('./git.js', () => ({ resolveForgeForRepo: vi.fn(async () => ({ cli: 'gh' })) }));
+vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
+
+const detectPrimaryCheckoutDriftMock = vi.fn(async () => ({ drifted: false }));
+vi.mock('../lib/primaryCheckoutGuard.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ detectPrimaryCheckoutDrift: (...args) => detectPrimaryCheckoutDriftMock(...args),
+}));
+
+const getAgentRecordMock = vi.fn(async () => null);
+const completeAgentMock = vi.fn();
+vi.mock('./cosAgentLifecycle.js', () => ({
+ getAgent: vi.fn(async () => null),
+ getAgentRecord: (...args) => getAgentRecordMock(...args),
+ updateAgent: vi.fn(async () => null),
+ completeAgent: (...args) => completeAgentMock(...args),
+}));
+
+const updateTaskMock = vi.fn(async () => ({}));
+vi.mock('./cos.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));
+vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => null) }));
+vi.mock('./providerStatus.js', () => ({
+ markProviderUsageLimit: vi.fn(async () => null),
+ markProviderRateLimited: vi.fn(async () => null),
+ markProviderUnavailable: vi.fn(async () => null),
+}));
+vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));
+vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));
+
+const resolveFailedTaskUpdateMock = vi.fn(async (_task, analysis) => ({
+ status: 'pending',
+ metadata: { lastErrorCategory: analysis?.category || null },
+}));
+vi.mock('./agentErrorAnalysis.js', () => ({
+ resolveFailedTaskUpdate: (...args) => resolveFailedTaskUpdateMock(...args),
+ resolveTypeFailureSignal: vi.fn(() => ({ record: 'skip' })),
+}));
+
+const completeAgentRunMock = vi.fn(async () => null);
+vi.mock('../lib/gitCommitProbe.js', () => ({ committedDuringRun: vi.fn(async () => true) }));
+vi.mock('./agentRunTracking.js', () => ({
+ createAgentRun: vi.fn(),
+ completeAgentRun: (...args) => completeAgentRunMock(...args),
+}));
+vi.mock('./taskTypeHooks.js', () => ({
+ canRunTaskOutputHookWithoutPayload: vi.fn(() => false),
+ isProgrammaticIoTaskType: vi.fn(() => false),
+ resolveTaskHookType: vi.fn(() => null),
+ declaresNoCommitCriterion: vi.fn(() => false),
+ getTaskOutputHook: vi.fn(async () => null),
+ getTaskOutputPayloadPredicate: vi.fn(async () => null),
+}));
+vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));
+vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));
+
+import { checkPrimaryCheckoutDrift, finalizeAgent } from './agentFinalization.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) };
+
+const DRIFT = {
+ drifted: true,
+ reason: PRIMARY_CHECKOUT_MUTATED_REASON,
+ category: PRIMARY_CHECKOUT_MUTATED_CATEGORY,
+ baseline: BASELINE,
+ current: { path: '/example/repo', branch: 'main', head: 'b'.repeat(40) },
+ commitCount: 3,
+ message: 'Worktree agent mutated the primary checkout /example/repo: branch main, HEAD aaaaaaaaa → bbbbbbbbb (3 new commits)',
+ suggestedFix: 'git -C /example/repo reset --hard origin/main',
+};
+
+const task = () => ({ id: 'task-1', taskType: 'internal', description: 'ship something', metadata: {} });
+
+const finalize = (overrides = {}) => finalizeAgent({
+ agentId: 'agent-1',
+ task: task(),
+ runId: null,
+ providerId: 'claude-code',
+ success: true,
+ exitCode: 0,
+ duration: 1000,
+ outputBuffer: 'done',
+ errorAnalysis: null,
+ workspacePath: '/example/worktree',
+ prExpected: false,
+ ...overrides,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ detectPrimaryCheckoutDriftMock.mockResolvedValue({ drifted: false });
+ getAgentRecordMock.mockResolvedValue({
+ id: 'agent-1',
+ metadata: { isWorktree: true, worktreeBranch: 'claim/issue-3680', primaryCheckoutBaseline: BASELINE },
+ });
+});
+
+describe('checkPrimaryCheckoutDrift', () => {
+ it('checks the baseline the spawner stamped, naming the agent branch', async () => {
+ await checkPrimaryCheckoutDrift('agent-1');
+ expect(detectPrimaryCheckoutDriftMock).toHaveBeenCalledWith(BASELINE, { agentBranch: 'claim/issue-3680' });
+ });
+
+ it('short-circuits a non-worktree run before any git call', async () => {
+ // A run that legitimately works IN the primary carries no baseline; checking
+ // it would fail every ordinary coding-on-main run.
+ getAgentRecordMock.mockResolvedValue({ id: 'agent-1', metadata: { isWorktree: false } });
+ expect(await checkPrimaryCheckoutDrift('agent-1')).toEqual({ drifted: false });
+ expect(detectPrimaryCheckoutDriftMock).not.toHaveBeenCalled();
+ });
+
+ it('reports no drift when the agent record is unreadable', async () => {
+ getAgentRecordMock.mockRejectedValue(new Error('state read failed'));
+ expect(await checkPrimaryCheckoutDrift('agent-1')).toEqual({ drifted: false });
+ });
+});
+
+describe('finalizeAgent — a worktree run that mutated the primary is not a success', () => {
+ it('records the drifted run as a FAILURE naming branch, count and recovery', async () => {
+ detectPrimaryCheckoutDriftMock.mockResolvedValue(DRIFT);
+ await finalize();
+
+ const [, result] = completeAgentMock.mock.calls[0];
+ expect(result.success).toBe(false);
+ expect(result.completionReason).toBe(PRIMARY_CHECKOUT_MUTATED_REASON);
+ expect(result.error).toBe(DRIFT.message);
+ expect(result.errorAnalysis.category).toBe(PRIMARY_CHECKOUT_MUTATED_CATEGORY);
+ // A human has to decide whether to discard the primary's commits, so this
+ // escalates rather than blind-retrying.
+ expect(result.errorAnalysis.actionable).toBe(true);
+ expect(result.errorAnalysis.suggestedFix).toContain('reset --hard origin/main');
+ expect(updateTaskMock).not.toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');
+ });
+
+ it('marks the RUN record failed too, even though the process exited 0', async () => {
+ detectPrimaryCheckoutDriftMock.mockResolvedValue(DRIFT);
+ await finalize({ runId: 'run-1' });
+ expect(completeAgentRunMock).toHaveBeenCalledWith('run-1', 'done', 0, 1000, expect.anything(), false);
+ });
+
+ it('leaves an undrifted run completely unaffected', async () => {
+ await finalize({ runId: 'run-1' });
+ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));
+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');
+ expect(completeAgentRunMock).toHaveBeenCalledWith('run-1', 'done', 0, 1000, null, null);
+ });
+
+ it('does not overwrite the diagnosis of a run that already failed', async () => {
+ // The original analysis is the better answer to "why did this fail"; the
+ // branch-jack is already on the record via the warn log.
+ detectPrimaryCheckoutDriftMock.mockResolvedValue(DRIFT);
+ const originalAnalysis = { category: 'test-failure', actionable: true, message: 'tests failed' };
+ await finalize({ success: false, exitCode: 1, errorAnalysis: originalAnalysis, error: 'tests failed' });
+
+ const [, result] = completeAgentMock.mock.calls[0];
+ expect(result.success).toBe(false);
+ expect(result.errorAnalysis).toBe(originalAnalysis);
+ expect(result.completionReason).toBeUndefined();
+ });
+
+ it('does not turn a user-terminated run into a drift failure', async () => {
+ detectPrimaryCheckoutDriftMock.mockResolvedValue(DRIFT);
+ await finalize({ terminatedByUser: true });
+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'blocked' }), 'internal');
+ });
+
+ it('falls back to "no drift" when the check itself throws', async () => {
+ // A check that never ran is not a verdict — it must not manufacture a failure.
+ detectPrimaryCheckoutDriftMock.mockRejectedValue(new Error('git wedged'));
+ await finalize();
+ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));
+ });
+});
diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.js
index 073835d8c3..88ce239edd 100644
--- a/server/services/agentFinalization.providerBench.test.js
+++ b/server/services/agentFinalization.providerBench.test.js
@@ -32,6 +32,7 @@ vi.mock('./git.js', () => ({ resolveForgeForRepo: vi.fn(async () => ({ cli: 'gh'
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
vi.mock('./cosAgentLifecycle.js', () => ({
getAgent: vi.fn(async () => null),
+ getAgentRecord: vi.fn(async () => null),
updateAgent: vi.fn(async () => null),
completeAgent: vi.fn(async () => null),
}));
diff --git a/server/services/agentFinalization.transcriptRescue.test.js b/server/services/agentFinalization.transcriptRescue.test.js
index 66280e6477..aafa95c442 100644
--- a/server/services/agentFinalization.transcriptRescue.test.js
+++ b/server/services/agentFinalization.transcriptRescue.test.js
@@ -32,6 +32,7 @@ vi.mock('../lib/fileUtils.js', async () => {
vi.mock('./cosAgentLifecycle.js', () => ({
getAgent: vi.fn(async () => ({ id: 'agent-example', status: 'running', metadata: {} })),
+ getAgentRecord: vi.fn(async () => ({ id: 'agent-example', status: 'running', metadata: {} })),
updateAgent: vi.fn(async () => ({})),
completeAgent: vi.fn(async () => ({})),
}));
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 42d24f4803..c0660376ca 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -51,6 +51,7 @@ import { determineLane, acquire, release } from './executionLanes.js';
import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { createAgentRun } from './agentRunTracking.js';
import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';
+import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';
import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
@@ -431,10 +432,24 @@ async function runAgentSpawn(task) {
//
// `instanceId` was resolved up front via `ensureInstanceId()` for the claim
// guard, and is reused here so the warm-path cached read happens once.
+ // The checkout the worktree was cut FROM (null for a non-worktree run, which
+ // works in the primary directly and so has nothing to protect).
+ const sourceWorkspace = worktreeInfo
+ ? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR)
+ : null;
+
await registerAgent(agentId, task.id, {
instanceId,
workspacePath,
- sourceWorkspace: worktreeInfo ? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR) : null,
+ sourceWorkspace,
+ // Branch-jack baseline (#3680): the primary checkout's branch + HEAD at the
+ // instant this worktree agent started. finalizeAgent re-reads it at the end
+ // of the run — every spawn mode funnels through that one chokepoint — and
+ // fails the run when the primary moved, instead of recording a silent
+ // "completed" for an agent that wrote unreviewed commits outside its
+ // worktree. Non-throwing: an unreadable checkout yields null, which the
+ // detector reads as "nothing to check".
+ primaryCheckoutBaseline: sourceWorkspace ? await capturePrimaryCheckoutState(sourceWorkspace) : null,
worktreeBranch: worktreeInfo?.branchName || null,
isWorktree: !!worktreeInfo,
isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,