From 936687ca55827121b6adb3a86584ae91ca59d089 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Thu, 2 Jul 2026 20:58:26 -0700 Subject: [PATCH] fix(workspace): restore clean branch drift on finalize (#8914) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent runs can execute inside reusable, runtime-created git worktree execution workspaces. > - Those managed worktrees record the expected branch so later dispatches do not accidentally run an agent in the wrong checkout. > - Successful run finalization already checked branch coherence, but it treated every unrecorded branch switch as fatal. > - A common publishing flow can briefly switch a clean worktree to a PR/publish branch that points at the same commit as the recorded issue branch, leaving no divergent work to protect. > - This pull request keeps the strict finalization guard for unsafe drift, but lets finalization restore the recorded branch when same-commit repair is provably safe. > - The benefit is fewer false failed runs after harmless branch switches while preserving hard failures for divergent or dirty worktrees. ## Linked Issues or Issue Description No public issue exists for this exact finalization failure. Related public worktree-recovery context: #3087 and #3056, but those address different worktree realization/reuse recovery paths rather than successful-run finalization branch repair. Bug report details: **What happened?** When an adapter run succeeded after switching a managed git worktree from its recorded issue branch to a publish/PR branch, finalization failed with a managed worktree branch mismatch even when the publish branch and recorded branch pointed at the same commit and the worktree was clean. **Expected behavior** Finalization should restore the recorded branch only when it can prove the worktree is clean, registered, and the recorded branch points at the current `HEAD`. If the actual branch has different commits or unsafe state, finalization should continue to fail with bounded validation evidence. **Steps to reproduce** 1. Create a runtime-managed `git_worktree` execution workspace for an issue run. 2. During the adapter run, create and check out a new publish branch without committing new changes. 3. Return adapter success and let heartbeat finalization run. 4. Before this change, finalization records a failed branch check and fails the run even though the branches point at the same commit. 5. With this change, finalization records the repair operation, restores the recorded branch, and records a successful finalize row. 6. Repeat with a commit on the publish branch; finalization still fails because the branch heads differ. **Paperclip version or commit** Reproduced against `master` at `bac7307ec`; fixed by this PR at `64ec605cf`. **Deployment mode** Local dev / built from source. **Agent adapter(s) involved** Not adapter-specific. This is core heartbeat/workspace finalization behavior. **Database mode** Embedded test Postgres in the focused server test. **Access context** Agent run finalization. **Node.js version** `v25.6.1` **Operating system** `Darwin 24.6.0 arm64` **Relevant logs or output** The new focused test intentionally exercises both outcomes: ```text Test Files 1 passed (1) Tests 3 passed (3) ``` **Relevant config** Runtime-created `git_worktree` execution workspace. **Additional context** The unsafe divergent branch case still fails with `workspace_validation_failed` and `git_worktree_branch_incoherence` evidence. **Privacy checklist** Reviewed; this description avoids internal task links, local workspace paths, credentials, and instance-specific URLs. ## What Changed - Reused the existing guarded branch-coherence repair helper during heartbeat finalization when the final branch inspection finds clean same-commit branch drift. - Recorded repair metadata in the `workspace_finalize` operation so reviewers/operators can audit whether finalization repaired branch drift. - Preserved failure behavior for divergent branch heads and surfaced the bounded workspace validation evidence from the repair helper. - Added focused server coverage for safe finalization repair and unsafe divergent branch failure. - Updated execution semantics docs to describe the narrower finalization rule. ## Verification - `pnpm exec vitest run server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts` - `pnpm --filter @paperclipai/server typecheck` - `git diff --check` ## Risks Low to medium risk. The change affects successful-run finalization for runtime-created git worktree execution workspaces. The repair path is constrained to clean, registered, same-commit branch drift, and the focused test confirms divergent branch heads still fail instead of being restored silently. ## Model Used OpenAI Codex, GPT-5-based coding agent. Exact hosted model ID was not exposed in the runtime; tool use and local shell execution were enabled. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/execution-semantics.md | 2 +- ...eartbeat-workspace-finalize-branch.test.ts | 133 ++++++++++++++++-- server/src/services/heartbeat.ts | 84 ++++++++++- server/src/services/workspace-runtime.ts | 2 +- 4 files changed, 200 insertions(+), 21 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 929f5a80235..1fc4fcac366 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -315,7 +315,7 @@ The state `projectWorkspaceId` plus `executionWorkspaceId` without `projectId` i Workspace incoherence feeds into the same non-terminal liveness and stranded assigned-work model as a disappeared run. The recovery path should first fail or reject the incoherent wake, then either repair and requeue one bounded continuation for the same assignee or surface an explicit recovery action. It must not leave an agent-owned `in_progress` issue healthy solely because a wake record exists that would invoke the adapter in the wrong cwd, a non-git directory where git is required, an unrelated project workspace, or an unrecoverable missing worktree. -For runtime-created `git_worktree` execution workspaces, branch coherence is part of workspace coherence. The persisted execution workspace branch is the recorded branch for future dispatch. Reusing that workspace must verify that the worktree is still registered and that `HEAD` is on the recorded branch. Successful run finalization must perform the same check before recording `workspace_finalize=succeeded`; if the run switched to a publishing/PR branch without updating the execution workspace record, finalization records a failed workspace finalize and the run fails with the expected and actual branch. A branch change is sanctioned only when a control-plane path updates the execution workspace record before finalization, or when publishing work happens in a separate worktree and the managed issue worktree remains on its recorded branch. +For runtime-created `git_worktree` execution workspaces, branch coherence is part of workspace coherence. The persisted execution workspace branch is the recorded branch for future dispatch. Reusing that workspace must verify that the worktree is still registered and that `HEAD` is on the recorded branch. Successful run finalization must perform the same check before recording `workspace_finalize=succeeded`. If the run switched to a publishing/PR branch without updating the execution workspace record, finalization may auto-restore the recorded branch only when the worktree is clean, still registered, and the recorded branch points at the current `HEAD`; the repair is recorded as a workspace operation before the successful finalize row. If that safe repair cannot be proven, finalization records a failed workspace finalize and the run fails with bounded evidence for the expected and actual branch. A branch change is sanctioned when a control-plane path updates the execution workspace record before finalization, when publishing work happens in a separate worktree and the managed issue worktree remains on its recorded branch, or when the finalizer performs this clean same-commit restoration. ### Explicit recovery actions diff --git a/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts b/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts index 031d70f9803..13fe1a77f6e 100644 --- a/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts +++ b/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts @@ -238,6 +238,14 @@ async function listFinalizeOperations(db: Db, runId: string) { .orderBy(asc(workspaceOperations.startedAt), asc(workspaceOperations.createdAt)); } +async function listRunWorkspaceOperations(db: Db, runId: string) { + return db + .select() + .from(workspaceOperations) + .where(eq(workspaceOperations.heartbeatRunId, runId)) + .orderBy(asc(workspaceOperations.startedAt), asc(workspaceOperations.createdAt)); +} + describeEmbeddedPostgres("heartbeat workspace finalization branch guard", () => { let db!: Db; let tempDb: Awaited> | null = null; @@ -291,18 +299,20 @@ describeEmbeddedPostgres("heartbeat workspace finalization branch guard", () => await tempDb?.cleanup(); }); - it("fails a successful adapter run when the managed worktree branch drift was not recorded", async () => { + it("repairs clean unrecorded branch drift before recording workspace finalization", async () => { const repoRoot = await createGitRepo(); tempRoots.push(repoRoot); const { agentId, issueId } = await seedRunTarget(db, repoRoot); const publishBranch = `publish-${issueId.slice(0, 8)}`; let recordedBranch: string | null = null; let executionWorkspaceId: string | null = null; + let workspaceCwd: string | null = null; adapterExecute.mockImplementationOnce(async (input) => { const workspace = readAdapterWorkspace(input); recordedBranch = workspace.branchName; executionWorkspaceId = workspace.executionWorkspaceId; + workspaceCwd = workspace.cwd; await runGit(workspace.cwd, ["checkout", "-b", publishBranch]); await db.update(issues).set({ status: "done", updatedAt: new Date() }).where(eq(issues.id, issueId)); return { @@ -319,23 +329,117 @@ describeEmbeddedPostgres("heartbeat workspace finalization branch guard", () => const run = await wakeIssue(heartbeat, agentId, issueId); expect(run).not.toBeNull(); + const finishedRun = await waitForRunToFinish(heartbeat, run!.id); + expect(finishedRun).toMatchObject({ + status: "succeeded", + errorCode: null, + error: null, + }); + await waitForRuntimeStateLastRun(db, agentId, run!.id); + expect(adapterExecute).toHaveBeenCalledTimes(1); + await expect(execFileAsync("git", ["branch", "--show-current"], { cwd: workspaceCwd! })) + .resolves.toMatchObject({ stdout: `${recordedBranch}\n` }); + + const operations = await listRunWorkspaceOperations(db, run!.id); + expect(operations).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + phase: "worktree_prepare", + command: `git checkout ${recordedBranch}`, + status: "succeeded", + executionWorkspaceId, + metadata: expect.objectContaining({ + branchIncoherenceRepair: true, + expectedBranchName: recordedBranch, + actualBranchName: publishBranch, + executionWorkspaceId, + sourceIssueId: issueId, + }), + }), + ]), + ); + + const finalizeOps = await listFinalizeOperations(db, run!.id); + expect(finalizeOps).toHaveLength(1); + expect(finalizeOps[0]).toMatchObject({ + status: "succeeded", + executionWorkspaceId, + }); + expect(finalizeOps[0]?.metadata).toMatchObject({ + managedGitWorktreeBranch: { + executionWorkspaceId, + valid: true, + reasonCode: null, + expectedBranchName: recordedBranch, + actualBranchName: recordedBranch, + }, + managedGitWorktreeBranchRepair: { + attempted: true, + succeeded: true, + initial: expect.objectContaining({ + valid: false, + reasonCode: "branch_mismatch", + expectedBranchName: recordedBranch, + actualBranchName: publishBranch, + }), + }, + }); + }, 20_000); + + it("fails unrecorded branch drift when the checked-out branch has different commits", async () => { + const repoRoot = await createGitRepo(); + tempRoots.push(repoRoot); + const { agentId, issueId } = await seedRunTarget(db, repoRoot); + const publishBranch = `publish-${issueId.slice(0, 8)}`; + let recordedBranch: string | null = null; + let executionWorkspaceId: string | null = null; + + adapterExecute.mockImplementationOnce(async (input) => { + const workspace = readAdapterWorkspace(input); + recordedBranch = workspace.branchName; + executionWorkspaceId = workspace.executionWorkspaceId; + await runGit(workspace.cwd, ["checkout", "-b", publishBranch]); + await writeFile(path.join(workspace.cwd, "publish.txt"), "publish branch work\n", "utf8"); + await runGit(workspace.cwd, ["add", "publish.txt"]); + await runGit(workspace.cwd, ["commit", "-m", "Add publish branch work"]); + await db.update(issues).set({ status: "done", updatedAt: new Date() }).where(eq(issues.id, issueId)); + return { + exitCode: 0, + signal: null, + timedOut: false, + summary: "Adapter completed after switching to a publish branch with commits.", + provider: "test", + model: "test-model", + }; + }); + + const heartbeat = heartbeatService(db); + const run = await wakeIssue(heartbeat, agentId, issueId); + expect(run).not.toBeNull(); + const finishedRun = await waitForRunToFinish(heartbeat, run!.id); expect(finishedRun).toMatchObject({ status: "failed", errorCode: "workspace_validation_failed", - error: expect.stringContaining("Record a sanctioned execution-workspace branch transition"), }); const workspaceValidation = (finishedRun?.resultJson as Record | null)?.workspaceValidation; expect(workspaceValidation).toMatchObject({ - reason: "git_worktree_branch_mismatch_after_run", - fingerprint: expect.stringMatching(/^workspace_finalize_branch_mismatch:v1:sha256:/), - issueId, - persistedExecutionWorkspaceId: executionWorkspaceId, - managedGitWorktreeBranch: expect.objectContaining({ - executionWorkspaceId, - reasonCode: "branch_mismatch", - expectedBranchName: recordedBranch, - actualBranchName: publishBranch, + reason: "git_worktree_branch_incoherence", + sourceIssueId: issueId, + executionWorkspaceId, + expectedBranch: recordedBranch, + actualBranch: publishBranch, + cleanliness: "clean", + provenance: expect.objectContaining({ + expectedBranchExists: true, + actualBranchExists: true, + sameHead: false, + }), + safeRepair: expect.objectContaining({ + eligible: false, + attempted: false, + succeeded: false, + reason: "expected branch and current HEAD differ", }), }); await waitForRuntimeStateLastRun(db, agentId, run!.id); @@ -349,13 +453,16 @@ describeEmbeddedPostgres("heartbeat workspace finalization branch guard", () => stderrExcerpt: expect.stringContaining("Managed git worktree branch check failed"), }); expect(finalizeOps[0]?.metadata).toMatchObject({ - managedGitWorktreeBranch: { + managedGitWorktreeBranch: expect.objectContaining({ executionWorkspaceId, valid: false, reasonCode: "branch_mismatch", expectedBranchName: recordedBranch, actualBranchName: publishBranch, - }, + }), + workspaceValidation: expect.objectContaining({ + reason: "git_worktree_branch_incoherence", + }), }); }, 20_000); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 67eb46f7bda..bd963ada977 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -96,6 +96,7 @@ import { logActivity, publishPluginDomainEvent, type LogActivityInput } from "./ import { buildWorkspaceReadyComment, cleanupExecutionWorkspaceArtifacts, + ensureGitWorktreeBranchCoherent, ensurePersistedExecutionWorkspaceAvailable, ensureRuntimeServicesForRun, formatManagedGitWorktreeBranchInspection, @@ -1200,7 +1201,7 @@ function fingerprintFinalizeWorkspaceBranchValidation(input: { const digest = createHash("sha256") .update(stableStringifyForFingerprint({ version: 1, - reason: "git_worktree_branch_mismatch_after_run", + reason: "git_worktree_branch_incoherence", issueId: input.issueId, executionWorkspaceId: input.executionWorkspaceId, worktreePath: input.inspection.worktreePath ? path.resolve(input.inspection.worktreePath) : null, @@ -10796,15 +10797,84 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {}) ) => { if (adapterFinalizeOutcome) return; let finalizeBranchMetadata: Record | null = null; + let finalizeBranchRepairMetadata: Record | null = null; if (status === "succeeded") { const branchInspection = await inspectFinalizeWorkspaceBranch(); if (branchInspection) { - const managedGitWorktreeBranch = formatManagedGitWorktreeBranchInspection(branchInspection.inspection); + let inspection = branchInspection.inspection; + const initialManagedGitWorktreeBranch = formatManagedGitWorktreeBranchInspection(inspection); + if (!inspection.valid && inspection.reasonCode === "branch_mismatch" && inspection.repoRoot) { + try { + await ensureGitWorktreeBranchCoherent({ + repoRoot: inspection.repoRoot, + worktreePath: inspection.worktreePath, + expectedBranchName: inspection.expectedBranchName, + actualBranchName: inspection.actualBranchName, + sourceIssue: issueRef + ? { + id: issueRef.id, + identifier: issueRef.identifier, + title: issueRef.title, + workMode: issueRef.workMode, + } + : null, + executionWorkspaceId: branchInspection.workspaceRecord.id, + recorder: workspaceOperationRecorder, + }); + } catch (repairErr) { + const workspaceValidationFailure = isWorkspaceValidationFailure(repairErr) ? repairErr : null; + finalizeBranchMetadata = { + executionWorkspaceId: branchInspection.workspaceRecord.id, + ...initialManagedGitWorktreeBranch, + }; + finalizeBranchRepairMetadata = { + attempted: true, + succeeded: false, + initial: initialManagedGitWorktreeBranch, + reason: repairErr instanceof Error ? repairErr.message : String(repairErr), + }; + await workspaceOperationRecorder.recordOperation({ + phase: "workspace_finalize", + cwd: executionWorkspace.cwd, + metadata: { + adapterType: agent.adapterType, + executionTargetKind: executionTarget?.kind ?? "local", + ...metadata, + managedGitWorktreeBranch: finalizeBranchMetadata, + managedGitWorktreeBranchRepair: finalizeBranchRepairMetadata, + ...(workspaceValidationFailure?.resultJson + ? { workspaceValidation: workspaceValidationFailure.resultJson.workspaceValidation ?? workspaceValidationFailure.resultJson } + : {}), + }, + run: async () => ({ + status: "failed", + stderr: `Managed git worktree branch check failed: ${repairErr instanceof Error ? repairErr.message : String(repairErr)}\n`, + }), + }); + adapterFinalizeOutcome = "failed"; + throw repairErr; + } + + const repairedInspection = await inspectManagedGitWorktreeBranch({ + worktreePath: inspection.worktreePath, + expectedBranchName: inspection.expectedBranchName, + repoRoot: inspection.repoRoot, + }); + finalizeBranchRepairMetadata = { + attempted: true, + succeeded: repairedInspection.valid, + initial: initialManagedGitWorktreeBranch, + repaired: formatManagedGitWorktreeBranchInspection(repairedInspection), + }; + inspection = repairedInspection; + } + + const managedGitWorktreeBranch = formatManagedGitWorktreeBranchInspection(inspection); finalizeBranchMetadata = { executionWorkspaceId: branchInspection.workspaceRecord.id, ...managedGitWorktreeBranch, }; - if (!branchInspection.inspection.valid) { + if (!inspection.valid) { const workspaceValidationFingerprint = fingerprintFinalizeWorkspaceBranchValidation({ issueId: issueRef?.id ?? null, executionWorkspaceId: branchInspection.workspaceRecord.id, @@ -10818,18 +10888,19 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {}) executionTargetKind: executionTarget?.kind ?? "local", ...metadata, managedGitWorktreeBranch: finalizeBranchMetadata, + ...(finalizeBranchRepairMetadata ? { managedGitWorktreeBranchRepair: finalizeBranchRepairMetadata } : {}), }, run: async () => ({ status: "failed", - stderr: `Managed git worktree branch check failed: ${branchInspection.inspection.reason ?? "unknown branch mismatch"}\n`, + stderr: `Managed git worktree branch check failed: ${inspection.reason ?? "unknown branch mismatch"}\n`, }), }); adapterFinalizeOutcome = "failed"; throw new WorkspaceValidationFailure( - `Execution workspace ${branchInspection.workspaceRecord.id} expected git worktree branch "${branchInspection.inspection.expectedBranchName}" at "${branchInspection.inspection.worktreePath}", but ${branchInspection.inspection.reason ?? "the checked-out branch could not be verified"}. Record a sanctioned execution-workspace branch transition or restore the workspace branch before completing the run.`, + `Execution workspace ${branchInspection.workspaceRecord.id} expected git worktree branch "${inspection.expectedBranchName}" at "${inspection.worktreePath}", but ${inspection.reason ?? "the checked-out branch could not be verified"}. Record a sanctioned execution-workspace branch transition or restore the workspace branch before completing the run.`, { workspaceValidation: { - reason: "git_worktree_branch_mismatch_after_run", + reason: "git_worktree_branch_incoherence", fingerprint: workspaceValidationFingerprint, adapterType: agent.adapterType, issueId: issueRef?.id ?? null, @@ -10851,6 +10922,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {}) executionTargetKind: executionTarget?.kind ?? "local", ...metadata, ...(finalizeBranchMetadata ? { managedGitWorktreeBranch: finalizeBranchMetadata } : {}), + ...(finalizeBranchRepairMetadata ? { managedGitWorktreeBranchRepair: finalizeBranchRepairMetadata } : {}), }, run: async () => ({ status }), }); diff --git a/server/src/services/workspace-runtime.ts b/server/src/services/workspace-runtime.ts index d7e87effde9..866e1898317 100644 --- a/server/src/services/workspace-runtime.ts +++ b/server/src/services/workspace-runtime.ts @@ -816,7 +816,7 @@ function branchIncoherenceValidationFailure(evidence: GitWorktreeBranchIncoheren ); } -async function ensureGitWorktreeBranchCoherent(input: { +export async function ensureGitWorktreeBranchCoherent(input: { repoRoot: string; worktreePath: string; expectedBranchName: string | null;