The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(workspace): restore clean branch drift on finalize (#8914)
Devin Foley936687ca5582
diff --git a/doc/execution-semantics.md b/doc/execution-semantics.mdindex 929f5a8023..1fc4fcac36 100644--- a/doc/execution-semantics.md+++ b/doc/execution-semantics.md@@ -315,7 +315,7 @@ The state `projectWorkspaceId` plus `executionWorkspaceId` without `projectId` iWorkspace 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 actionsdiff --git a/server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts b/server/src/__tests__/heartbeat-workspace-finalize-branch.test.tsindex 031d70f980..13fe1a77f6 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<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | 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<string, unknown> | 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.tsindex 67eb46f7bd..bd963ada97 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<string, unknown> | null = null;+ let finalizeBranchRepairMetadata: Record<string, unknown> | 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.tsindex d7e87effde..866e189831 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;