fix: repair dirty/foreign-branch execution worktrees (#9297)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Execution workspaces are the bridge between Paperclip's control
plane and a local agent's checked-out repository state.
> - When a workspace is restored after a failed or interrupted run, the
recorded branch can disagree with the branch currently checked out on
disk.
> - A clean branch mismatch can be reconciled safely, but a dirty
mismatch needs a lossless path that does not discard uncommitted agent
work.
> - This pull request adds a quarantine-and-restore path that saves
dirty work to a rescue branch, restores the recorded branch, and exposes
the repair from the board UI and run page.
> - The benefit is that operators can recover wedged execution
workspaces without losing work or moving another live branch
unexpectedly.

## Linked Issues or Issue Description

No public GitHub issue exists for this workspace-recovery failure, so
this PR includes the bug report inline.

**What happened**

A git worktree-backed execution workspace could become wedged when
Paperclip expected one branch but found a different checked-out branch
with dirty tracked or untracked files. The existing safe repair path
refused the restore, leaving the source task blocked with no lossless
one-click recovery path.

**Expected behavior**

Paperclip should preserve dirty work before restoring the recorded
workspace branch. If another live workspace claims the checked-out
branch, or an attached runtime service is active, the repair should
refuse with clear operator-facing evidence instead of risking work loss
or file contention.

**Steps to reproduce**

Create a git worktree execution workspace whose persisted branch name
differs from the checked-out branch, add dirty tracked or untracked
files in that worktree, then trigger workspace validation or use the
branch reconcile endpoint. Before this change, the dirty mismatch
remained blocked because Paperclip had no quarantine restore mode.

**Paperclip version or commit**

Observed on the pre-fix workspace-recovery implementation. Verified on
this PR head after rebasing onto current `master`.

**Deployment mode**

Local trusted development/worktree deployments using git worktree
execution workspaces and optional workspace runtime services.

## What Changed

- Added dirty-worktree quarantine repair that creates a rescue branch,
commits dirty tracked and untracked files there, restores the recorded
branch, writes audit comments/activity, and preserves the live foreign
branch ref.
- Added `quarantine_restore` branch reconcile API support,
recovery-action resolution, source-task wake behavior, execution-review
preservation, claimant refusal, runtime-service refusal, and coverage
for the non-transactional git ordering.
- Added board UI controls for the repair action in the recovery card
plus a compact failed-run workspace recovery surface that uses the same
reconcile handlers.
- Hardened Greptile follow-up cases by best-effort restoring the
recorded branch after a mid-sequence rescue commit failure and by
refusing quarantine restore while attached runtime services are active.

## Verification

- `pnpm exec vitest run
server/src/__tests__/execution-workspaces-service.test.ts -t
"quarantine_restore"`
- `pnpm exec vitest run server/src/__tests__/workspace-runtime.test.ts
-t "workspace dirty quarantine branch repair"`
- `pnpm exec vitest run
server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts -t
"repairs clean unrecorded branch drift|adopts unrecorded forward branch
drift"`
- `pnpm exec vitest run
server/src/__tests__/workspace-runtime-routes-authz.test.ts`
- `pnpm --filter @paperclipai/server typecheck`
- Earlier PR verification covered the route, service, heartbeat, UI
component, and run-page recovery surfaces; Cutter posted public preview
screenshots for the repair popover and run-page panel at
https://github.com/paperclipai/paperclip/pull/9297#issuecomment-4926934211.
- GitHub PR checks are green on
`dcac76b05f4cf6e1ee16544c2831d83c7857e475`.
- Greptile is 5/5 with zero annotations and no unresolved review threads
on `dcac76b05f4cf6e1ee16544c2831d83c7857e475`.

## Risks

- Moderate risk because the change intentionally runs git commands
against local worktrees; the implementation refuses dirty repair when
another claimant or active runtime service is detected and records
rescue refs for auditability.
- Compatibility / release-note callout for self-hosted operators:
existing instances that left `enableWorkspaceBranchReconcileForward`
unset now get automatic forward branch reconciliation during heartbeat
workspace recovery. Operators who want the previous advisory-only
behavior can set `experimental.enableWorkspaceBranchReconcileForward` to
`false`; dirty quarantine repair can likewise be disabled with
`experimental.enableWorkspaceDirtyQuarantineRepair: false`.
- If the git rescue succeeds but a later database write fails, the
worktree may already be restored while the recovery action remains open;
this ordering is documented in code because git side effects cannot
participate in the database transaction.
- UI risk is limited to the workspace recovery surfaces and covered by
component tests plus the existing Cutter visual preview.

## Model Used

OpenAI Codex coding agent based on GPT-5, with repository tool use,
shell execution, and local test execution. Earlier preserved commits on
this branch also show Claude Code / Claude Opus 4.8 assistance in their
commit metadata.

## 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] Branch naming exception documented: this PR preserves the existing
worktree branch requested for publication while keeping the PR title and
body public-facing
- [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 <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-07-09 18:19:49 -05:00
1 parent 4d898aa7af
commit f3ca4d24bc
29 files changed
+3783 -140

No files matched your search

+417 -50
View File
@@ -3,9 +3,9 @@ import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
import { and, asc, desc, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { executionWorkspaces, issueComments, issues, projects, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
import { executionWorkspaces, heartbeatRuns, issueComments, issues, projects, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
import type {
ExecutionWorkspace,
ExecutionWorkspaceSummary,
@@ -25,6 +25,11 @@ import type {
} from "@paperclipai/shared";
import { deriveProjectUrlKey, WORKSPACE_OVERVIEW_LINKED_ISSUE_LIMIT } from "@paperclipai/shared";
import { conflict, notFound, unprocessable } from "../errors.js";
import {
applyIssueExecutionPolicyTransition,
normalizeIssueExecutionPolicy,
parseIssueExecutionState,
} from "./issue-execution-policy.js";
import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js";
import { issueRecoveryActionService } from "./issue-recovery-actions.js";
import { visibleIssueCondition } from "./issue-visibility.js";
@@ -42,7 +47,7 @@ const TERMINAL_ISSUE_STATUSES = new Set(["done", "cancelled"]);
const WORKSPACE_BRANCH_INCOHERENCE_REASON = "git_worktree_branch_incoherence";
const WORKSPACE_VALIDATION_RECOVERY_CAUSE = "workspace_validation_failed";
export type ExecutionWorkspaceBranchReconcileMode = "forward" | "override";
export type ExecutionWorkspaceBranchReconcileMode = "forward" | "override" | "quarantine_restore";
export type ExecutionWorkspaceBranchReconcileActor = {
actorType: "agent" | "user" | "system";
@@ -70,8 +75,34 @@ export type ExecutionWorkspaceBranchReconcileResult = {
inspection: ExecutionWorkspaceBranchReconcileInspection;
recoveryAction: IssueRecoveryAction | null;
auditCommentId: string | null;
rescueRef: {
branchName: string;
commitSha: string;
fileCount: number;
sourceAuditCommentId: string | null;
claimantAuditCommentId: string | null;
} | null;
restoredSourceIssue: {
id: string;
companyId: string;
status: string;
assigneeAgentId: string | null;
} | null;
sourceIssueStatusChanged: boolean;
};
export type ExecutionWorkspaceGitWorktreeContention = {
claimedByWorkspaceId: string;
claimedByIssueId: string | null;
claimedByIssueIdentifier: string | null;
activeRun: {
id: string;
status: "queued" | "running";
issueId: string | null;
issueIdentifier: string | null;
} | null;
} | null;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -87,6 +118,37 @@ function cloneRecord(value: unknown): Record<string, unknown> | null {
return { ...value };
}
function assigneeMatchesExecutionPrincipal(input: {
assigneeAgentId: string | null;
assigneeUserId: string | null;
}, principal: { type: string; agentId?: string | null; userId?: string | null } | null): boolean {
if (!principal) return false;
if (principal.type === "agent") {
return input.assigneeAgentId === principal.agentId && input.assigneeUserId === null;
}
if (principal.type === "user") {
return input.assigneeAgentId === null && input.assigneeUserId === principal.userId;
}
return false;
}
function quarantineRestoreRequestedSourceStatus(input: {
status: string;
assigneeAgentId: string | null;
assigneeUserId: string | null;
executionState: unknown;
}): "todo" | undefined {
const state = parseIssueExecutionState(input.executionState);
if (
state?.status === "pending" &&
input.status === "in_review" &&
assigneeMatchesExecutionPrincipal(input, state.currentParticipant)
) {
return undefined;
}
return "todo";
}
function readDesiredState(value: unknown): WorkspaceRuntimeDesiredState | null {
return value === "running" || value === "stopped" || value === "manual" ? value : null;
}
@@ -279,6 +341,7 @@ function formatBranchReconcileAuditComment(input: {
workspaceId: string;
inspection: ExecutionWorkspaceBranchReconcileInspection;
recoveryActionId: string | null;
rescueRef: ExecutionWorkspaceBranchReconcileResult["rescueRef"];
}) {
return [
"Execution workspace branch reconciled.",
@@ -292,10 +355,31 @@ function formatBranchReconcileAuditComment(input: {
`- Verdict: \`${input.inspection.ancestryVerdict}\``,
`- Fingerprint: \`${input.inspection.fingerprint}\``,
`- Recovery action: ${input.recoveryActionId ? `\`${input.recoveryActionId}\`` : "none matched"}`,
...(input.rescueRef
? [
`- Rescue ref: \`${input.rescueRef.branchName}\``,
`- Rescue commit: \`${input.rescueRef.commitSha}\``,
`- Rescued file count: \`${input.rescueRef.fileCount}\``,
]
: []),
...(input.reason ? [`- Operator reason: ${input.reason}`] : []),
].join("\n");
}
function isWorkspaceRuntimeValidationFailure(error: unknown): error is {
code: "workspace_validation_failed";
message: string;
resultJson: Record<string, unknown>;
} {
if (!error || typeof error !== "object") return false;
const maybe = error as { code?: unknown; resultJson?: unknown; message?: unknown };
return maybe.code === "workspace_validation_failed" &&
typeof maybe.message === "string" &&
Boolean(maybe.resultJson) &&
typeof maybe.resultJson === "object" &&
!Array.isArray(maybe.resultJson);
}
function assertBranchReconcileWorkspaceIsSafe(input: {
workspaceStatus: ExecutionWorkspace["status"];
inspection: ExecutionWorkspaceBranchReconcileInspection;
@@ -316,6 +400,16 @@ function assertBranchReconcileWorkspaceIsSafe(input: {
});
}
assertBranchReconcileRuntimeServicesStopped({
inspection: input.inspection,
runtimeServices: input.runtimeServices,
});
}
function assertBranchReconcileRuntimeServicesStopped(input: {
inspection: ExecutionWorkspaceBranchReconcileInspection;
runtimeServices: WorkspaceRuntimeService[];
}) {
const activeRuntimeServices = input.runtimeServices.filter((service) => service.status !== "stopped");
if (activeRuntimeServices.length > 0) {
throw unprocessable("Execution workspace branch reconciliation requires all runtime services to be stopped", {
@@ -364,6 +458,66 @@ function assertLockedBranchReconcileWorkspaceStillMatchesInspection(input: {
}
}
async function quarantineRestoreDirtyWorkspaceBranch(input: {
db: Db;
workspace: Pick<ExecutionWorkspace, "id" | "sourceIssueId">;
inspection: ExecutionWorkspaceBranchReconcileInspection;
actor: ExecutionWorkspaceBranchReconcileActor;
}): Promise<NonNullable<ExecutionWorkspaceBranchReconcileResult["rescueRef"]>> {
const sourceIssue = await input.db
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
workMode: issues.workMode,
})
.from(issues)
.where(eq(issues.id, input.workspace.sourceIssueId!))
.then((rows) => rows[0] ?? null);
if (!sourceIssue) throw notFound("Source issue not found");
const { ensureGitWorktreeBranchCoherent } = await import("./workspace-runtime.js");
try {
const result = await ensureGitWorktreeBranchCoherent({
db: input.db,
repoRoot: input.inspection.repoRoot,
worktreePath: input.inspection.worktreePath,
expectedBranchName: input.inspection.fromBranch,
actualBranchName: input.inspection.toBranch,
sourceIssue,
executionWorkspaceId: input.workspace.id,
heartbeatRunId: input.actor.runId,
enableWorkspaceBranchReconcileForward: false,
enableWorkspaceDirtyQuarantineRepair: true,
persistForwardReconcile: false,
reconcileOperationPhase: "worktree_prepare",
recorder: null,
});
if (!result.dirtyQuarantineRepair) {
throw unprocessable("Quarantine restore requires a dirty foreign-branch worktree to repair", {
inspection: input.inspection,
});
}
return {
branchName: result.dirtyQuarantineRepair.rescueBranch,
commitSha: result.dirtyQuarantineRepair.rescueCommitSha,
fileCount: result.dirtyQuarantineRepair.fileCount,
sourceAuditCommentId: result.dirtyQuarantineRepair.sourceAuditCommentId,
claimantAuditCommentId: result.dirtyQuarantineRepair.claimantAuditCommentId,
};
} catch (error) {
if (isWorkspaceRuntimeValidationFailure(error)) {
throw unprocessable(error.message, {
code: error.code,
...error.resultJson,
});
}
throw error;
}
}
async function inspectGitCloseReadiness(workspace: ExecutionWorkspace): Promise<{
git: ExecutionWorkspaceCloseGitReadiness | null;
warnings: string[];
@@ -1049,6 +1203,124 @@ export function executionWorkspaceService(db: Db) {
return rows.map((row) => toExecutionWorkspaceSummary(row));
},
findGitWorktreeContention: async (input: {
companyId: string;
worktreePath: string;
liveBranchName: string | null;
excludingExecutionWorkspaceId?: string | null;
}): Promise<ExecutionWorkspaceGitWorktreeContention> => {
const resolvedWorktreePath = path.resolve(input.worktreePath);
const pathOrBranchConditions = [
eq(executionWorkspaces.providerRef, input.worktreePath),
eq(executionWorkspaces.cwd, input.worktreePath),
];
if (input.liveBranchName) {
pathOrBranchConditions.push(eq(executionWorkspaces.branchName, input.liveBranchName));
}
const candidates = await db
.select({
id: executionWorkspaces.id,
cwd: executionWorkspaces.cwd,
providerRef: executionWorkspaces.providerRef,
branchName: executionWorkspaces.branchName,
sourceIssueId: executionWorkspaces.sourceIssueId,
sourceIssueIdentifier: issues.identifier,
})
.from(executionWorkspaces)
.leftJoin(
issues,
and(
eq(issues.companyId, executionWorkspaces.companyId),
eq(issues.id, executionWorkspaces.sourceIssueId),
),
)
.where(and(
eq(executionWorkspaces.companyId, input.companyId),
isNull(executionWorkspaces.closedAt),
ne(executionWorkspaces.status, "archived"),
input.excludingExecutionWorkspaceId
? ne(executionWorkspaces.id, input.excludingExecutionWorkspaceId)
: sql`true`,
or(...pathOrBranchConditions),
))
.orderBy(desc(executionWorkspaces.lastUsedAt), desc(executionWorkspaces.updatedAt))
.limit(20);
for (const candidate of candidates) {
const candidatePath = readNullableString(candidate.providerRef) ?? readNullableString(candidate.cwd);
const matchesPath = candidatePath ? path.resolve(candidatePath) === resolvedWorktreePath : false;
const matchesBranch = Boolean(input.liveBranchName && candidate.branchName === input.liveBranchName);
if (!matchesPath && !matchesBranch) continue;
const linkedIssueConditions = [eq(issues.executionWorkspaceId, candidate.id)];
if (candidate.sourceIssueId) linkedIssueConditions.push(eq(issues.id, candidate.sourceIssueId));
const linkedIssueRows = await db
.select({
id: issues.id,
identifier: issues.identifier,
checkoutRunId: issues.checkoutRunId,
executionRunId: issues.executionRunId,
})
.from(issues)
.where(and(
eq(issues.companyId, input.companyId),
isNull(issues.hiddenAt),
linkedIssueConditions.length === 1 ? linkedIssueConditions[0]! : or(...linkedIssueConditions),
))
.orderBy(desc(issues.updatedAt))
.limit(20);
const runToIssue = new Map<string, { id: string; identifier: string | null }>();
for (const issue of linkedIssueRows) {
if (issue.executionRunId) runToIssue.set(issue.executionRunId, { id: issue.id, identifier: issue.identifier ?? null });
if (issue.checkoutRunId) runToIssue.set(issue.checkoutRunId, { id: issue.id, identifier: issue.identifier ?? null });
}
let activeRun: NonNullable<ExecutionWorkspaceGitWorktreeContention>["activeRun"] = null;
const runIds = [...runToIssue.keys()];
if (runIds.length > 0) {
const [row] = await db
.select({
id: heartbeatRuns.id,
status: heartbeatRuns.status,
})
.from(heartbeatRuns)
.where(and(
eq(heartbeatRuns.companyId, input.companyId),
inArray(heartbeatRuns.id, runIds),
inArray(heartbeatRuns.status, ["queued", "running"]),
))
.orderBy(desc(heartbeatRuns.startedAt), desc(heartbeatRuns.createdAt))
.limit(1);
if (row && (row.status === "queued" || row.status === "running")) {
const issue = runToIssue.get(row.id) ?? null;
activeRun = {
id: row.id,
status: row.status,
issueId: issue?.id ?? null,
issueIdentifier: issue?.identifier ?? null,
};
}
}
const claimedIssue =
linkedIssueRows.find((issue) => issue.id === candidate.sourceIssueId)
?? linkedIssueRows[0]
?? null;
return {
claimedByWorkspaceId: candidate.id,
claimedByIssueId: claimedIssue?.id ?? candidate.sourceIssueId ?? null,
claimedByIssueIdentifier:
claimedIssue?.identifier ?? candidate.sourceIssueIdentifier ?? null,
activeRun,
};
}
return null;
},
getById: async (id: string) => {
const row = await db
.select()
@@ -1363,6 +1635,29 @@ export function executionWorkspaceService(db: Db) {
}
const reason = readNullableString(input.reason);
const rescueRef = input.mode === "quarantine_restore"
? await (async () => {
const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(
db,
existing.companyId,
[existingRow],
);
assertBranchReconcileRuntimeServicesStopped({
inspection,
runtimeServices: (runtimeServicesByWorkspaceId.get(existing.id) ?? []).map(toRuntimeService),
});
// The git rescue has to happen before the DB transaction because the
// transaction may be retried/rolled back, while git side effects cannot.
// The preflight runtime-service guard above keeps known local services
// from holding files open during the non-transactional git sequence.
return quarantineRestoreDirtyWorkspaceBranch({
db,
workspace: existing,
inspection,
actor: input.actor,
});
})()
: null;
const now = new Date();
const allowActiveWorkspace =
input.mode === "forward" &&
@@ -1427,57 +1722,62 @@ export function executionWorkspaceService(db: Db) {
if (!lockedWorkspace.sourceIssueId) {
throw unprocessable("Execution workspace needs a source issue before Paperclip can audit branch reconciliation");
}
assertBranchReconcileWorkspaceIsSafe({
workspaceStatus: lockedWorkspace.status,
inspection,
runtimeServices: lockedRuntimeServices,
allowActiveWorkspace,
});
if (lockedWorkspace.branchName !== inspection.fromBranch) {
throw unprocessable("Execution workspace branch changed during reconciliation; retry with a fresh inspection", {
workspaceBranch: lockedWorkspace.branchName,
inspection,
});
}
const updatePatch: Partial<typeof executionWorkspaces.$inferInsert> = {
branchName: inspection.toBranch,
updatedAt: now,
};
if (lockedWorkspace.name === inspection.fromBranch) {
updatePatch.name = inspection.toBranch;
}
const [updatedRow] = await tx
.update(executionWorkspaces)
.set(updatePatch)
.where(
and(
eq(executionWorkspaces.id, lockedWorkspace.id),
allowActiveWorkspace
? inArray(executionWorkspaces.status, ["idle", "active"])
: eq(executionWorkspaces.status, "idle"),
eq(executionWorkspaces.branchName, inspection.fromBranch),
noActiveRuntimeServicesForWorkspaceCondition(lockedRow),
),
)
.returning();
if (!updatedRow) {
const latestRuntimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(
txDb,
lockedRow.companyId,
[lockedRow],
);
const latestRuntimeServices = (latestRuntimeServicesByWorkspaceId.get(lockedRow.id) ?? []).map(toRuntimeService);
let updatedRow: ExecutionWorkspaceRow = lockedRow;
if (input.mode !== "quarantine_restore") {
assertBranchReconcileWorkspaceIsSafe({
workspaceStatus: lockedWorkspace.status,
inspection,
runtimeServices: latestRuntimeServices,
runtimeServices: lockedRuntimeServices,
allowActiveWorkspace,
});
throw unprocessable("Execution workspace branch reconciliation requires the workspace to stay idle with stopped runtime services during the update", {
inspection,
});
if (lockedWorkspace.branchName !== inspection.fromBranch) {
throw unprocessable("Execution workspace branch changed during reconciliation; retry with a fresh inspection", {
workspaceBranch: lockedWorkspace.branchName,
inspection,
});
}
const updatePatch: Partial<typeof executionWorkspaces.$inferInsert> = {
branchName: inspection.toBranch,
updatedAt: now,
};
if (lockedWorkspace.name === inspection.fromBranch) {
updatePatch.name = inspection.toBranch;
}
const [branchUpdatedRow] = await tx
.update(executionWorkspaces)
.set(updatePatch)
.where(
and(
eq(executionWorkspaces.id, lockedWorkspace.id),
allowActiveWorkspace
? inArray(executionWorkspaces.status, ["idle", "active"])
: eq(executionWorkspaces.status, "idle"),
eq(executionWorkspaces.branchName, inspection.fromBranch),
noActiveRuntimeServicesForWorkspaceCondition(lockedRow),
),
)
.returning();
if (!branchUpdatedRow) {
const latestRuntimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(
txDb,
lockedRow.companyId,
[lockedRow],
);
const latestRuntimeServices = (latestRuntimeServicesByWorkspaceId.get(lockedRow.id) ?? []).map(toRuntimeService);
assertBranchReconcileWorkspaceIsSafe({
workspaceStatus: lockedWorkspace.status,
inspection,
runtimeServices: latestRuntimeServices,
allowActiveWorkspace,
});
throw unprocessable("Execution workspace branch reconciliation requires the workspace to stay idle with stopped runtime services during the update", {
inspection,
});
}
updatedRow = branchUpdatedRow;
}
let recoveryAction = await recoveryActionsSvc.resolveActiveForIssue(
@@ -1489,7 +1789,9 @@ export function executionWorkspaceService(db: Db) {
fingerprint: inspection.fingerprint,
status: "resolved",
outcome: "restored",
resolutionNote: `Execution workspace branch record reconciled from "${inspection.fromBranch}" to "${inspection.toBranch}".`,
resolutionNote: input.mode === "quarantine_restore" && rescueRef
? `Execution workspace dirty worktree quarantined on "${rescueRef.branchName}" and restored recorded branch "${inspection.fromBranch}".`
: `Execution workspace branch record reconciled from "${inspection.fromBranch}" to "${inspection.toBranch}".`,
},
tx,
);
@@ -1505,7 +1807,9 @@ export function executionWorkspaceService(db: Db) {
fingerprint: alternateFingerprint,
status: "resolved",
outcome: "restored",
resolutionNote: `Execution workspace branch record reconciled from "${inspection.fromBranch}" to "${inspection.toBranch}".`,
resolutionNote: input.mode === "quarantine_restore" && rescueRef
? `Execution workspace dirty worktree quarantined on "${rescueRef.branchName}" and restored recorded branch "${inspection.fromBranch}".`
: `Execution workspace branch record reconciled from "${inspection.fromBranch}" to "${inspection.toBranch}".`,
},
tx,
);
@@ -1513,6 +1817,65 @@ export function executionWorkspaceService(db: Db) {
}
}
let restoredSourceIssue: ExecutionWorkspaceBranchReconcileResult["restoredSourceIssue"] = null;
let sourceIssueStatusChanged = false;
if (input.mode === "quarantine_restore") {
const [sourceBefore] = await tx
.select({
id: issues.id,
companyId: issues.companyId,
status: issues.status,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
executionPolicy: issues.executionPolicy,
executionState: issues.executionState,
monitorNextCheckAt: issues.monitorNextCheckAt,
monitorWakeRequestedAt: issues.monitorWakeRequestedAt,
monitorLastTriggeredAt: issues.monitorLastTriggeredAt,
monitorAttemptCount: issues.monitorAttemptCount,
monitorNotes: issues.monitorNotes,
monitorScheduledBy: issues.monitorScheduledBy,
})
.from(issues)
.where(eq(issues.id, lockedWorkspace.sourceIssueId))
.for("update");
if (!sourceBefore) throw notFound("Source issue not found");
const requestedStatus = quarantineRestoreRequestedSourceStatus(sourceBefore);
const policy = normalizeIssueExecutionPolicy(sourceBefore.executionPolicy ?? null);
const transition = applyIssueExecutionPolicyTransition({
issue: sourceBefore,
policy,
previousPolicy: policy,
requestedStatus,
requestedAssigneePatch: {},
actor: {
agentId: input.actor.agentId ?? null,
userId: input.actor.actorType === "user" ? input.actor.actorId : null,
},
commentBody: null,
});
const { issueService } = await import("./issues.js");
const updatedIssue = await issueService(db).update(
lockedWorkspace.sourceIssueId,
{
...(requestedStatus ? { status: requestedStatus } : {}),
...transition.patch,
actorAgentId: input.actor.agentId ?? null,
actorUserId: input.actor.actorType === "user" ? input.actor.actorId : null,
},
tx,
);
if (!updatedIssue) throw notFound("Source issue not found");
restoredSourceIssue = {
id: updatedIssue.id,
companyId: updatedIssue.companyId,
status: updatedIssue.status,
assigneeAgentId: updatedIssue.assigneeAgentId,
};
sourceIssueStatusChanged = sourceBefore.status !== updatedIssue.status;
}
const [auditComment] = await tx
.insert(issueComments)
.values({
@@ -1528,6 +1891,7 @@ export function executionWorkspaceService(db: Db) {
workspaceId: existing.id,
inspection,
recoveryActionId: recoveryAction?.id ?? null,
rescueRef,
}),
})
.returning({ id: issueComments.id });
@@ -1542,6 +1906,9 @@ export function executionWorkspaceService(db: Db) {
inspection,
recoveryAction,
auditCommentId: auditComment?.id ?? null,
rescueRef,
restoredSourceIssue,
sourceIssueStatusChanged,
};
});
},
+12 -1
View File
@@ -3726,15 +3726,18 @@ export function resolveTaskSessionConfigFreshness(input: {
};
}
function shouldAutoCheckoutIssueForWake(input: {
export function shouldAutoCheckoutIssueForWake(input: {
contextSnapshot: Record<string, unknown> | null | undefined;
issueStatus: string | null;
issueAssigneeAgentId: string | null;
issueExecutionState?: unknown;
isDependencyReady: boolean;
agentId: string;
}) {
if (input.issueAssigneeAgentId !== input.agentId) return false;
if (!input.isDependencyReady) return false;
const executionState = parseIssueExecutionState(input.issueExecutionState);
if (executionState?.status === "pending") return false;
const issueStatus = readNonEmptyString(input.issueStatus);
if (
@@ -5231,6 +5234,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
assigneeAgentId: issues.assigneeAgentId,
assigneeAdapterOverrides: issues.assigneeAdapterOverrides,
executionPolicy: issues.executionPolicy,
executionState: issues.executionState,
executionWorkspaceSettings: issues.executionWorkspaceSettings,
parentId: issues.parentId,
createdByUserId: issues.createdByUserId,
@@ -10428,6 +10432,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
contextSnapshot: context,
issueStatus: issueContext.status,
issueAssigneeAgentId: issueContext.assigneeAgentId,
issueExecutionState: issueContext.executionState,
isDependencyReady: issueDependencyReadiness?.isDependencyReady ?? true,
agentId: agent.id,
})
@@ -11171,6 +11176,8 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
heartbeatRunId: run.id,
enableWorkspaceBranchReconcileForward:
resolvedInstanceSettings.experimental.enableWorkspaceBranchReconcileForward,
enableWorkspaceDirtyQuarantineRepair:
resolvedInstanceSettings.experimental.enableWorkspaceDirtyQuarantineRepair,
recorder: workspaceOperationRecorder,
})
: null,
@@ -11187,6 +11194,8 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
heartbeatRunId: run.id,
enableWorkspaceBranchReconcileForward:
resolvedInstanceSettings.experimental.enableWorkspaceBranchReconcileForward,
enableWorkspaceDirtyQuarantineRepair:
resolvedInstanceSettings.experimental.enableWorkspaceDirtyQuarantineRepair,
recorder: workspaceOperationRecorder,
}),
});
@@ -12022,6 +12031,8 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
heartbeatRunId: run.id,
enableWorkspaceBranchReconcileForward:
resolvedInstanceSettings.experimental.enableWorkspaceBranchReconcileForward,
enableWorkspaceDirtyQuarantineRepair:
resolvedInstanceSettings.experimental.enableWorkspaceDirtyQuarantineRepair,
persistForwardReconcile: false,
reconcileOperationPhase: "workspace_finalize",
recorder: workspaceOperationRecorder,
+4 -2
View File
@@ -59,7 +59,8 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
enableServerInfoDebugView: parsed.data.enableServerInfoDebugView ?? false,
autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false,
enableIssueGraphLivenessAutoRecovery: parsed.data.enableIssueGraphLivenessAutoRecovery ?? false,
enableWorkspaceBranchReconcileForward: parsed.data.enableWorkspaceBranchReconcileForward ?? false,
enableWorkspaceBranchReconcileForward: parsed.data.enableWorkspaceBranchReconcileForward ?? true,
enableWorkspaceDirtyQuarantineRepair: parsed.data.enableWorkspaceDirtyQuarantineRepair ?? true,
enableWorktreeRunExecution: parsed.data.enableWorktreeRunExecution ?? false,
issueGraphLivenessAutoRecoveryLookbackHours:
parsed.data.issueGraphLivenessAutoRecoveryLookbackHours ??
@@ -82,7 +83,8 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
enableServerInfoDebugView: false,
autoRestartDevServerWhenIdle: false,
enableIssueGraphLivenessAutoRecovery: false,
enableWorkspaceBranchReconcileForward: false,
enableWorkspaceBranchReconcileForward: true,
enableWorkspaceDirtyQuarantineRepair: true,
enableWorktreeRunExecution: false,
issueGraphLivenessAutoRecoveryLookbackHours:
DEFAULT_ISSUE_GRAPH_LIVENESS_AUTO_RECOVERY_LOOKBACK_HOURS,
+679 -6
View File
@@ -7,15 +7,17 @@ import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import type { AdapterRuntimeServiceReport } from "@paperclipai/adapter-utils";
import type { Db } from "@paperclipai/db";
import { executionWorkspaces, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
import { executionWorkspaces, issueComments, issues, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
import {
listWorkspaceServiceCommandDefinitions,
type GitWorktreeBranchAncestryVerdict,
type GitWorktreeBranchIncoherenceEvidence as SharedGitWorktreeBranchIncoherenceEvidence,
type GitWorktreeInProgressOperation,
type WorkspaceOperationPhase,
type WorkspaceRuntimeDesiredState,
type WorkspaceRuntimeServiceStateMap,
} from "@paperclipai/shared";
import { and, desc, eq, inArray } from "drizzle-orm";
import { and, desc, eq, inArray, ne } from "drizzle-orm";
import { asNumber, asString, parseObject, renderTemplate } from "../adapters/utils.js";
import { resolveHomeAwarePath } from "../home-paths.js";
import {
@@ -661,13 +663,25 @@ type GitWorktreeCleanliness = SharedGitWorktreeBranchIncoherenceEvidence["cleanl
type GitWorktreeBranchIncoherenceEvidence = SharedGitWorktreeBranchIncoherenceEvidence;
type GitWorktreeBranchContention = NonNullable<GitWorktreeBranchIncoherenceEvidence["contention"]>;
type GitWorktreeBranchCoherenceResult = {
branchName: string | null;
reconciledForward: boolean;
pendingForwardBranchReconcile?: PendingForwardBranchReconcile | null;
dirtyQuarantineRepair?: DirtyQuarantineRepairResult | null;
warnings: string[];
};
type DirtyQuarantineRepairResult = {
rescueBranch: string;
rescueCommitSha: string;
fileCount: number;
clearedInProgressOperation: GitWorktreeInProgressOperation | null;
sourceAuditCommentId: string | null;
claimantAuditCommentId: string | null;
};
export type PendingForwardBranchReconcile = {
recordedBranchName: string;
adoptedBranchName: string;
@@ -679,6 +693,186 @@ function formatBranchForMessage(branch: string | null | undefined) {
return branch && branch.length > 0 ? branch : "<detached>";
}
const GIT_IN_PROGRESS_OPERATION_MARKERS: ReadonlyArray<{
operation: GitWorktreeInProgressOperation;
marker: string;
}> = [
{ operation: "rebase", marker: "rebase-merge" },
{ operation: "rebase", marker: "rebase-apply" },
{ operation: "merge", marker: "MERGE_HEAD" },
{ operation: "cherry_pick", marker: "CHERRY_PICK_HEAD" },
{ operation: "revert", marker: "REVERT_HEAD" },
{ operation: "bisect", marker: "BISECT_LOG" },
];
const GIT_IN_PROGRESS_OPERATION_LABELS: Record<GitWorktreeInProgressOperation, string> = {
rebase: "rebase",
merge: "merge",
cherry_pick: "cherry-pick",
revert: "revert",
bisect: "bisect",
};
// `--quit` clears the interrupted operation's state directory without touching
// the working tree or moving HEAD, unlike `--abort` which resets both.
const GIT_IN_PROGRESS_OPERATION_QUIT_ARGS: Record<GitWorktreeInProgressOperation, string[]> = {
rebase: ["rebase", "--quit"],
merge: ["merge", "--quit"],
cherry_pick: ["cherry-pick", "--quit"],
revert: ["revert", "--quit"],
bisect: ["bisect", "reset", "HEAD"],
};
async function detectGitWorktreeInProgressOperation(
worktreePath: string,
): Promise<GitWorktreeInProgressOperation | null> {
for (const { operation, marker } of GIT_IN_PROGRESS_OPERATION_MARKERS) {
const markerPath = await runGit(["rev-parse", "--git-path", marker], worktreePath).catch(() => null);
if (!markerPath) continue;
if (existsSync(path.resolve(worktreePath, markerPath))) return operation;
}
return null;
}
const DIRTY_PATH_SAMPLE_LIMIT = 5;
function parseGitPorcelainPath(line: string) {
const raw = line.trimEnd();
if (raw.trim().length <= 3) return raw.trim();
if (raw[1] === " " && raw[2] !== " ") return raw.slice(2).trim();
return raw.slice(3).trim();
}
function sampleDirtyStatusPaths(statusLines: string[] | null) {
return (statusLines ?? [])
.map(parseGitPorcelainPath)
.filter((value) => value.length > 0)
.slice(0, DIRTY_PATH_SAMPLE_LIMIT);
}
function formatUtcBranchTimestamp(date = new Date()) {
return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
}
function buildDirtyQuarantineRescueBranch(sourceIssue: ExecutionWorkspaceIssueRef | null) {
const issueComponent = sanitizeBranchName(sourceIssue?.identifier ?? sourceIssue?.id ?? "issue");
return sanitizeBranchName(`paperclip/rescue/${issueComponent}/${formatUtcBranchTimestamp()}`);
}
function formatIssueReference(issueId: string | null | undefined, identifier: string | null | undefined) {
if (!identifier) return issueId ? `\`${issueId}\`` : "`unknown`";
const match = identifier.match(/^([A-Z]+)-\d+$/);
if (!match) return `\`${identifier}\``;
return `[${identifier}](/${match[1]}/issues/${identifier})`;
}
async function readIssueCompanyId(db: Db, issueId: string | null | undefined): Promise<string | null> {
if (!issueId) return null;
return db
.select({ companyId: issues.companyId })
.from(issues)
.where(eq(issues.id, issueId))
.then((rows) => rows[0]?.companyId ?? null);
}
async function findGitWorktreeBranchContention(input: {
db: Db | null | undefined;
sourceIssue: ExecutionWorkspaceIssueRef | null;
executionWorkspaceId: string | null;
worktreePath: string;
actualBranchName: string | null;
}): Promise<GitWorktreeBranchContention | null> {
if (!input.db) return null;
const companyId = await readIssueCompanyId(input.db, input.sourceIssue?.id);
if (!companyId) return null;
return executionWorkspaceService(input.db).findGitWorktreeContention({
companyId,
worktreePath: input.worktreePath,
liveBranchName: input.actualBranchName,
excludingExecutionWorkspaceId: input.executionWorkspaceId,
});
}
function executionWorkspaceUsesInheritedProjectRuntimeServices(
row: typeof executionWorkspaces.$inferSelect,
) {
if (row.mode !== "shared_workspace" || !row.projectWorkspaceId) return false;
return !readExecutionWorkspaceConfig((row.metadata as Record<string, unknown> | null) ?? null)?.workspaceRuntime;
}
async function findActiveRuntimeServiceBlockingDirtyQuarantine(input: {
db: Db;
workspace: typeof executionWorkspaces.$inferSelect;
}) {
const inheritedProjectWorkspaceId = executionWorkspaceUsesInheritedProjectRuntimeServices(input.workspace)
? input.workspace.projectWorkspaceId
: null;
const serviceScopeCondition = inheritedProjectWorkspaceId
? and(
eq(workspaceRuntimeServices.companyId, input.workspace.companyId),
eq(workspaceRuntimeServices.projectWorkspaceId, inheritedProjectWorkspaceId),
eq(workspaceRuntimeServices.scopeType, "project_workspace"),
)
: and(
eq(workspaceRuntimeServices.companyId, input.workspace.companyId),
eq(workspaceRuntimeServices.executionWorkspaceId, input.workspace.id),
);
const [service] = await input.db
.select({
id: workspaceRuntimeServices.id,
serviceName: workspaceRuntimeServices.serviceName,
status: workspaceRuntimeServices.status,
scopeType: workspaceRuntimeServices.scopeType,
})
.from(workspaceRuntimeServices)
.where(and(serviceScopeCondition, ne(workspaceRuntimeServices.status, "stopped")))
.orderBy(desc(workspaceRuntimeServices.updatedAt), desc(workspaceRuntimeServices.createdAt))
.limit(1);
return service ?? null;
}
async function assertDirtyQuarantineRuntimeServicesStopped(input: {
db: Db;
executionWorkspaceId: string | null;
evidence: GitWorktreeBranchIncoherenceEvidence;
}) {
if (!input.executionWorkspaceId) {
input.evidence.safeRepair.eligible = false;
input.evidence.safeRepair.reason = "dirty quarantine repair requires an execution workspace id for runtime-service checks";
throw branchIncoherenceValidationFailure(input.evidence);
}
const [workspace] = await input.db
.select()
.from(executionWorkspaces)
.where(eq(executionWorkspaces.id, input.executionWorkspaceId));
if (!workspace) {
input.evidence.safeRepair.eligible = false;
input.evidence.safeRepair.reason = "dirty quarantine repair requires a persisted execution workspace for runtime-service checks";
throw branchIncoherenceValidationFailure(input.evidence);
}
const activeService = await findActiveRuntimeServiceBlockingDirtyQuarantine({
db: input.db,
workspace,
});
if (!activeService) return;
input.evidence.safeRepair.eligible = false;
input.evidence.safeRepair.reason =
`dirty quarantine repair requires runtime service "${activeService.serviceName}" (${activeService.id}) to be stopped; current status is ${activeService.status}`;
throw branchIncoherenceValidationFailure(input.evidence);
}
async function assertGitIndexIsUnlocked(worktreePath: string) {
const indexLockPath = await runGit(["rev-parse", "--git-path", "index.lock"], worktreePath)
.catch(() => null);
if (indexLockPath && existsSync(indexLockPath)) {
throw new Error(`git index lock exists at ${indexLockPath}`);
}
}
function fingerprintWorkspaceBranchIncoherence(input: {
sourceIssueId: string | null;
executionWorkspaceId: string | null;
@@ -749,6 +943,7 @@ function explainGitWorktreeBranchIncoherence(input: {
}
async function inspectGitWorktreeBranchIncoherence(input: {
db?: Db | null;
repoRoot: string;
worktreePath: string;
expectedBranchName: string;
@@ -762,9 +957,11 @@ async function inspectGitWorktreeBranchIncoherence(input: {
).catch(() => null);
const statusLines = status === null
? null
: status.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
: status.split(/\r?\n/).map((line) => line.trimEnd()).filter((line) => line.trim().length > 0);
const dirtyPathSample = sampleDirtyStatusPaths(statusLines);
const cleanliness: GitWorktreeCleanliness =
status === null ? "unknown" : status.trim().length > 0 ? "dirty" : "clean";
const inProgressOperation = await detectGitWorktreeInProgressOperation(input.worktreePath);
const expectedHeadSha = await runGit(
["rev-parse", "--verify", `refs/heads/${input.expectedBranchName}^{commit}`],
input.repoRoot,
@@ -784,7 +981,7 @@ async function inspectGitWorktreeBranchIncoherence(input: {
expectedHeadSha,
actualHeadSha,
});
const plainLanguageReason = explainGitWorktreeBranchIncoherence({
const basePlainLanguageReason = explainGitWorktreeBranchIncoherence({
expectedBranchName: input.expectedBranchName,
actualBranchName: input.actualBranchName,
expectedHeadSha,
@@ -792,6 +989,9 @@ async function inspectGitWorktreeBranchIncoherence(input: {
sameHead,
ancestryVerdict,
});
const plainLanguageReason = inProgressOperation
? `${basePlainLanguageReason} An interrupted git ${GIT_IN_PROGRESS_OPERATION_LABELS[inProgressOperation]} is still in progress in this worktree.`
: basePlainLanguageReason;
const canCheckoutRecordedBranch =
cleanliness === "clean" && expectedBranchExists && sameHead && registeredBranchMatchesHead;
const canAdoptForwardActualBranch =
@@ -817,7 +1017,9 @@ async function inspectGitWorktreeBranchIncoherence(input: {
? "clean worktree and checked-out branch is forward of the recorded branch"
: "clean detached worktree HEAD is forward of the recorded branch"
: cleanliness !== "clean"
? "worktree is not clean"
? inProgressOperation
? `worktree is not clean and a git ${GIT_IN_PROGRESS_OPERATION_LABELS[inProgressOperation]} is in progress`
: "worktree is not clean"
: !registered
? "worktree path is not registered"
: !registeredBranchMatchesHead
@@ -837,6 +1039,13 @@ async function inspectGitWorktreeBranchIncoherence(input: {
expectedHeadSha,
actualHeadSha,
});
const contention = await findGitWorktreeBranchContention({
db: input.db ?? null,
sourceIssue: input.sourceIssue,
executionWorkspaceId: input.executionWorkspaceId ?? null,
worktreePath: input.worktreePath,
actualBranchName: input.actualBranchName,
});
return {
reason: GIT_WORKTREE_BRANCH_INCOHERENCE_REASON,
@@ -849,7 +1058,10 @@ async function inspectGitWorktreeBranchIncoherence(input: {
expectedBranch: input.expectedBranchName,
actualBranch: input.actualBranchName,
cleanliness,
inProgressOperation,
statusEntryCount: statusLines?.length ?? null,
dirtyPathSample,
contention,
provenance: {
expectedBranchRef: `refs/heads/${input.expectedBranchName}`,
actualBranchRef,
@@ -882,6 +1094,407 @@ function branchIncoherenceValidationFailure(evidence: GitWorktreeBranchIncoheren
);
}
function formatDirtyQuarantineContentionRefusal(contention: GitWorktreeBranchContention) {
const activeRunText = contention.activeRun
? ` with active run ${contention.activeRun.id}`
: " with no active run";
return `dirty quarantine repair refused because workspace ${contention.claimedByWorkspaceId} already claims the live branch${activeRunText}`;
}
function formatDirtyQuarantineFailure(error: unknown) {
const message = error instanceof Error ? error.message : String(error);
if (
gitErrorIncludes(error, "index.lock") ||
gitErrorIncludes(error, "index lock") ||
gitErrorIncludes(error, "another git process") ||
gitErrorIncludes(error, "Unable to create")
) {
return `dirty quarantine repair aborted because git reported index contention: ${message}`;
}
return `dirty quarantine repair failed: ${message}`;
}
function formatDirtyQuarantineAuditComment(input: {
evidence: GitWorktreeBranchIncoherenceEvidence;
rescueBranch: string;
rescueCommitSha: string;
fileCount: number;
sourceIssue: ExecutionWorkspaceIssueRef | null;
claimant: GitWorktreeBranchContention | null;
}) {
const dirtySample = input.evidence.dirtyPathSample.length > 0
? input.evidence.dirtyPathSample.map((entry) => `\`${entry}\``).join(", ")
: "`none captured`";
return [
"Execution workspace dirty worktree quarantined before restore.",
"",
`- Source issue: ${formatIssueReference(input.evidence.sourceIssueId, input.evidence.sourceIdentifier ?? input.sourceIssue?.identifier ?? null)}`,
`- Workspace: \`${input.evidence.executionWorkspaceId ?? "unpersisted"}\``,
`- Worktree: \`${input.evidence.worktreePath}\``,
`- Recorded branch: \`${input.evidence.expectedBranch}\``,
`- Live branch: \`${formatBranchForMessage(input.evidence.actualBranch)}\``,
`- Rescue branch: \`${input.rescueBranch}\``,
`- Rescue commit: \`${input.rescueCommitSha}\``,
`- Dirty file count: \`${input.fileCount}\``,
`- Dirty path sample: ${dirtySample}`,
...(input.evidence.inProgressOperation
? [`- Interrupted operation: \`git ${GIT_IN_PROGRESS_OPERATION_LABELS[input.evidence.inProgressOperation]}\` (state cleared after rescue; resolution preserved on the rescue branch)`]
: []),
`- Fingerprint: \`${input.evidence.fingerprint}\``,
input.claimant
? `- Claimant: workspace \`${input.claimant.claimedByWorkspaceId}\` on issue ${formatIssueReference(input.claimant.claimedByIssueId, input.claimant.claimedByIssueIdentifier)}${input.claimant.activeRun ? ` with active run \`${input.claimant.activeRun.id}\`` : " with no active run"}`
: "- Claimant: none",
].join("\n");
}
async function writeDirtyQuarantineAuditComments(input: {
db: Db;
companyId: string;
evidence: GitWorktreeBranchIncoherenceEvidence;
sourceIssue: ExecutionWorkspaceIssueRef | null;
rescueBranch: string;
rescueCommitSha: string;
fileCount: number;
heartbeatRunId: string | null;
}): Promise<{ sourceAuditCommentId: string | null; claimantAuditCommentId: string | null }> {
const body = formatDirtyQuarantineAuditComment({
evidence: input.evidence,
rescueBranch: input.rescueBranch,
rescueCommitSha: input.rescueCommitSha,
fileCount: input.fileCount,
sourceIssue: input.sourceIssue,
claimant: input.evidence.contention,
});
let sourceAuditCommentId: string | null = null;
let claimantAuditCommentId: string | null = null;
const now = new Date();
if (input.evidence.sourceIssueId) {
const [sourceComment] = await input.db
.insert(issueComments)
.values({
companyId: input.companyId,
issueId: input.evidence.sourceIssueId,
authorAgentId: null,
authorUserId: null,
authorType: "system",
createdByRunId: input.heartbeatRunId,
body,
})
.returning({ id: issueComments.id });
sourceAuditCommentId = sourceComment?.id ?? null;
await input.db
.update(issues)
.set({ updatedAt: now })
.where(eq(issues.id, input.evidence.sourceIssueId));
}
const claimantIssueId = input.evidence.contention?.claimedByIssueId ?? null;
if (claimantIssueId && claimantIssueId !== input.evidence.sourceIssueId) {
const [claimantComment] = await input.db
.insert(issueComments)
.values({
companyId: input.companyId,
issueId: claimantIssueId,
authorAgentId: null,
authorUserId: null,
authorType: "system",
createdByRunId: input.heartbeatRunId,
body,
})
.returning({ id: issueComments.id });
claimantAuditCommentId = claimantComment?.id ?? null;
await input.db
.update(issues)
.set({ updatedAt: now })
.where(eq(issues.id, claimantIssueId));
}
return { sourceAuditCommentId, claimantAuditCommentId };
}
async function logDirtyQuarantineActivity(input: {
db: Db;
companyId: string;
evidence: GitWorktreeBranchIncoherenceEvidence;
rescueBranch: string;
rescueCommitSha: string;
fileCount: number;
heartbeatRunId: string | null;
sourceAuditCommentId: string | null;
claimantAuditCommentId: string | null;
}) {
await logActivity(input.db, {
companyId: input.companyId,
actorType: "system",
actorId: "workspace_runtime",
runId: input.heartbeatRunId,
action: "execution_workspace.dirty_worktree_quarantined",
entityType: input.evidence.executionWorkspaceId ? "execution_workspace" : "issue",
entityId: input.evidence.executionWorkspaceId ?? input.evidence.sourceIssueId ?? input.companyId,
details: {
reason: GIT_WORKTREE_BRANCH_INCOHERENCE_REASON,
sourceIssueId: input.evidence.sourceIssueId,
executionWorkspaceId: input.evidence.executionWorkspaceId,
worktreePath: input.evidence.worktreePath,
expectedBranch: input.evidence.expectedBranch,
actualBranch: input.evidence.actualBranch,
rescueBranch: input.rescueBranch,
rescueCommitSha: input.rescueCommitSha,
fileCount: input.fileCount,
dirtyPathSample: input.evidence.dirtyPathSample,
fingerprint: input.evidence.fingerprint,
contention: input.evidence.contention,
sourceAuditCommentId: input.sourceAuditCommentId,
claimantAuditCommentId: input.claimantAuditCommentId,
actor: {
type: "system",
id: "workspace_runtime",
source: "workspace_runtime",
},
},
});
}
async function recordDirtyQuarantineOperation(input: {
recorder?: WorkspaceOperationRecorder | null;
phase?: "worktree_prepare" | "workspace_finalize";
cwd: string;
evidence: GitWorktreeBranchIncoherenceEvidence;
rescueBranch: string;
rescueCommitSha: string;
fileCount: number;
sourceAuditCommentId: string | null;
claimantAuditCommentId: string | null;
}) {
if (!input.recorder) return;
await input.recorder.recordOperation({
phase: input.phase ?? "worktree_prepare",
cwd: input.cwd,
metadata: {
repoRoot: input.evidence.repoRoot,
worktreePath: input.evidence.worktreePath,
expectedBranchName: input.evidence.expectedBranch,
actualBranchName: input.evidence.actualBranch,
branchIncoherenceDirtyQuarantineRepair: true,
rescueBranch: input.rescueBranch,
rescueCommitSha: input.rescueCommitSha,
fileCount: input.fileCount,
dirtyPathSample: input.evidence.dirtyPathSample,
fingerprint: input.evidence.fingerprint,
sourceIssueId: input.evidence.sourceIssueId,
executionWorkspaceId: input.evidence.executionWorkspaceId,
sourceAuditCommentId: input.sourceAuditCommentId,
claimantAuditCommentId: input.claimantAuditCommentId,
},
run: async () => ({
status: "succeeded",
system:
`Quarantined dirty git worktree state on ${input.rescueBranch} (${formatShortSha(input.rescueCommitSha)}) and restored recorded branch ${input.evidence.expectedBranch}.\n`,
}),
});
}
async function quarantineDirtyWorktreeBranchIncoherence(input: {
db: Db;
repoRoot: string;
worktreePath: string;
expectedBranchName: string;
sourceIssue: ExecutionWorkspaceIssueRef | null;
executionWorkspaceId: string | null;
heartbeatRunId: string | null;
evidence: GitWorktreeBranchIncoherenceEvidence;
phase?: "worktree_prepare" | "workspace_finalize";
recorder?: WorkspaceOperationRecorder | null;
}): Promise<DirtyQuarantineRepairResult> {
const companyId = await readIssueCompanyId(input.db, input.evidence.sourceIssueId);
if (!companyId) {
input.evidence.safeRepair.eligible = false;
input.evidence.safeRepair.reason = "dirty quarantine repair requires a source issue company for audit";
throw branchIncoherenceValidationFailure(input.evidence);
}
const freshContention = await findGitWorktreeBranchContention({
db: input.db,
sourceIssue: input.sourceIssue,
executionWorkspaceId: input.executionWorkspaceId,
worktreePath: input.worktreePath,
actualBranchName: input.evidence.actualBranch,
});
input.evidence.contention = freshContention;
if (freshContention) {
input.evidence.safeRepair.eligible = false;
input.evidence.safeRepair.reason = formatDirtyQuarantineContentionRefusal(freshContention);
throw branchIncoherenceValidationFailure(input.evidence);
}
const rescueBranch = buildDirtyQuarantineRescueBranch(input.sourceIssue);
const fileCount = input.evidence.statusEntryCount ?? input.evidence.dirtyPathSample.length;
const baseMetadata = {
repoRoot: input.repoRoot,
worktreePath: input.worktreePath,
expectedBranchName: input.expectedBranchName,
actualBranchName: input.evidence.actualBranch,
branchIncoherenceDirtyQuarantineRepair: true,
rescueBranch,
fingerprint: input.evidence.fingerprint,
sourceIssueId: input.evidence.sourceIssueId,
executionWorkspaceId: input.evidence.executionWorkspaceId,
fileCount,
dirtyPathSample: input.evidence.dirtyPathSample,
contention: input.evidence.contention,
};
let rescueBranchCreated = false;
let expectedBranchRestored = false;
try {
await assertGitIndexIsUnlocked(input.worktreePath);
await recordGitOperation(input.recorder, {
phase: input.phase ?? "worktree_prepare",
args: ["checkout", "-b", rescueBranch],
cwd: input.worktreePath,
metadata: baseMetadata,
successMessage: `Created rescue branch ${rescueBranch} for dirty git worktree state at ${input.worktreePath}\n`,
failureLabel: `git checkout -b ${rescueBranch}`,
});
rescueBranchCreated = true;
await recordGitOperation(input.recorder, {
phase: input.phase ?? "worktree_prepare",
args: ["add", "-A"],
cwd: input.worktreePath,
metadata: baseMetadata,
successMessage: `Staged dirty git worktree state for rescue branch ${rescueBranch}\n`,
failureLabel: "git add -A",
});
await recordGitOperation(input.recorder, {
phase: input.phase ?? "worktree_prepare",
args: [
"commit",
"-m",
"Paperclip dirty workspace rescue",
"-m",
[
`Source-Issue: ${input.evidence.sourceIdentifier ?? input.evidence.sourceIssueId ?? "unknown"}`,
`Run-Id: ${input.heartbeatRunId ?? "unknown"}`,
`Recorded-Branch: ${input.expectedBranchName}`,
`Live-Branch: ${formatBranchForMessage(input.evidence.actualBranch)}`,
`Fingerprint: ${input.evidence.fingerprint}`,
].join("\n"),
],
cwd: input.worktreePath,
metadata: baseMetadata,
successMessage: `Committed dirty git worktree state to rescue branch ${rescueBranch}\n`,
failureLabel: "git commit dirty workspace rescue",
});
const rescueCommitSha = await runGit(["rev-parse", "HEAD"], input.worktreePath);
await recordGitOperation(input.recorder, {
phase: input.phase ?? "worktree_prepare",
args: ["checkout", input.expectedBranchName],
cwd: input.worktreePath,
metadata: {
...baseMetadata,
rescueCommitSha,
},
successMessage: `Restored recorded branch ${input.expectedBranchName} after dirty workspace rescue ${rescueBranch}\n`,
failureLabel: `git checkout ${input.expectedBranchName}`,
});
expectedBranchRestored = true;
// A run that died mid-rebase (or mid-merge/cherry-pick/revert/bisect)
// leaves the operation's state directory behind even after the recorded
// branch is checked out, which wedges the next git command in the
// worktree. The rescue commit above already preserved the in-flight
// resolution, so clearing the state metadata here loses nothing.
let clearedInProgressOperation: GitWorktreeInProgressOperation | null = null;
const lingeringOperation = await detectGitWorktreeInProgressOperation(input.worktreePath);
if (lingeringOperation) {
const operationLabel = GIT_IN_PROGRESS_OPERATION_LABELS[lingeringOperation];
const quitArgs = GIT_IN_PROGRESS_OPERATION_QUIT_ARGS[lingeringOperation];
await recordGitOperation(input.recorder, {
phase: input.phase ?? "worktree_prepare",
args: quitArgs,
cwd: input.worktreePath,
metadata: {
...baseMetadata,
clearedInProgressOperation: lingeringOperation,
},
successMessage: `Cleared interrupted git ${operationLabel} state after dirty workspace rescue ${rescueBranch}\n`,
failureLabel: `git ${quitArgs.join(" ")}`,
});
const stillInProgress = await detectGitWorktreeInProgressOperation(input.worktreePath);
if (stillInProgress) {
input.evidence.safeRepair.succeeded = false;
input.evidence.safeRepair.reason =
`dirty quarantine repair could not clear the interrupted git ${GIT_IN_PROGRESS_OPERATION_LABELS[stillInProgress]} state`;
throw branchIncoherenceValidationFailure(input.evidence);
}
clearedInProgressOperation = lingeringOperation;
}
const repairedBranch = await runGit(["symbolic-ref", "--quiet", "--short", "HEAD"], input.worktreePath)
.catch(() => null);
if (repairedBranch !== input.expectedBranchName) {
input.evidence.safeRepair.succeeded = false;
input.evidence.safeRepair.reason =
`dirty quarantine repair checked out ${formatBranchForMessage(repairedBranch)} instead of ${input.expectedBranchName}`;
throw branchIncoherenceValidationFailure(input.evidence);
}
const repairedStatus = await runGit(["status", "--porcelain", "--untracked-files=all"], input.worktreePath);
if (repairedStatus.trim().length > 0) {
input.evidence.safeRepair.succeeded = false;
input.evidence.safeRepair.reason = "dirty quarantine repair completed but the worktree is still dirty";
throw branchIncoherenceValidationFailure(input.evidence);
}
const comments = await writeDirtyQuarantineAuditComments({
db: input.db,
companyId,
evidence: input.evidence,
sourceIssue: input.sourceIssue,
rescueBranch,
rescueCommitSha,
fileCount,
heartbeatRunId: input.heartbeatRunId,
});
await logDirtyQuarantineActivity({
db: input.db,
companyId,
evidence: input.evidence,
rescueBranch,
rescueCommitSha,
fileCount,
heartbeatRunId: input.heartbeatRunId,
sourceAuditCommentId: comments.sourceAuditCommentId,
claimantAuditCommentId: comments.claimantAuditCommentId,
});
await recordDirtyQuarantineOperation({
recorder: input.recorder,
phase: input.phase,
cwd: input.worktreePath,
evidence: input.evidence,
rescueBranch,
rescueCommitSha,
fileCount,
sourceAuditCommentId: comments.sourceAuditCommentId,
claimantAuditCommentId: comments.claimantAuditCommentId,
});
return {
rescueBranch,
rescueCommitSha,
fileCount,
clearedInProgressOperation,
...comments,
};
} catch (error) {
if (rescueBranchCreated && !expectedBranchRestored) {
await runGit(["checkout", input.expectedBranchName], input.worktreePath).catch(() => null);
}
if (error instanceof WorkspaceRuntimeValidationFailure) throw error;
input.evidence.safeRepair.succeeded = false;
input.evidence.safeRepair.reason = formatDirtyQuarantineFailure(error);
throw branchIncoherenceValidationFailure(input.evidence);
}
}
async function recordForwardBranchReconcileOperation(input: {
recorder?: WorkspaceOperationRecorder | null;
phase?: "worktree_prepare" | "workspace_finalize";
@@ -1047,6 +1660,7 @@ export async function ensureGitWorktreeBranchCoherent(input: {
actualBranchName?: string | null;
heartbeatRunId?: string | null;
enableWorkspaceBranchReconcileForward?: boolean;
enableWorkspaceDirtyQuarantineRepair?: boolean;
persistForwardReconcile?: boolean;
reconcileOperationPhase?: "worktree_prepare" | "workspace_finalize";
recorder?: WorkspaceOperationRecorder | null;
@@ -1062,6 +1676,7 @@ export async function ensureGitWorktreeBranchCoherent(input: {
}
const evidence = await inspectGitWorktreeBranchIncoherence({
db: input.db ?? null,
repoRoot: input.repoRoot,
worktreePath: input.worktreePath,
expectedBranchName,
@@ -1070,9 +1685,63 @@ export async function ensureGitWorktreeBranchCoherent(input: {
executionWorkspaceId: input.executionWorkspaceId ?? null,
});
if (evidence.cleanliness === "dirty" && input.enableWorkspaceDirtyQuarantineRepair === true) {
if (!input.db) {
evidence.safeRepair.reason = "dirty quarantine repair requires database access for claimant checks and audit";
throw branchIncoherenceValidationFailure(evidence);
}
if (!evidence.provenance.registeredPathFound) {
evidence.safeRepair.reason = "dirty quarantine repair requires a registered git worktree path";
throw branchIncoherenceValidationFailure(evidence);
}
if (!evidence.provenance.expectedBranchExists) {
evidence.safeRepair.reason = "dirty quarantine repair requires the recorded branch to exist";
throw branchIncoherenceValidationFailure(evidence);
}
if (evidence.contention) {
evidence.safeRepair.eligible = false;
evidence.safeRepair.reason = formatDirtyQuarantineContentionRefusal(evidence.contention);
throw branchIncoherenceValidationFailure(evidence);
}
await assertDirtyQuarantineRuntimeServicesStopped({
db: input.db,
executionWorkspaceId: input.executionWorkspaceId ?? null,
evidence,
});
evidence.safeRepair.eligible = true;
evidence.safeRepair.attempted = true;
evidence.safeRepair.reason = "dirty worktree can be quarantined on a rescue branch before restoring the recorded branch";
const result = await quarantineDirtyWorktreeBranchIncoherence({
db: input.db,
repoRoot: input.repoRoot,
worktreePath: input.worktreePath,
expectedBranchName,
sourceIssue: input.sourceIssue,
executionWorkspaceId: input.executionWorkspaceId ?? null,
heartbeatRunId: input.heartbeatRunId ?? null,
evidence,
phase: input.reconcileOperationPhase,
recorder: input.recorder ?? null,
});
evidence.safeRepair.succeeded = true;
evidence.safeRepair.reason = result.clearedInProgressOperation
? `dirty worktree quarantined on ${result.rescueBranch} at ${formatShortSha(result.rescueCommitSha)}; interrupted git ${GIT_IN_PROGRESS_OPERATION_LABELS[result.clearedInProgressOperation]} state cleared`
: `dirty worktree quarantined on ${result.rescueBranch} at ${formatShortSha(result.rescueCommitSha)}`;
return {
branchName: expectedBranchName,
reconciledForward: false,
dirtyQuarantineRepair: result,
warnings: [
`Execution workspace dirty worktree state was quarantined on rescue branch "${result.rescueBranch}" (${formatShortSha(result.rescueCommitSha)}; ${result.fileCount} ${result.fileCount === 1 ? "file" : "files"}) before restoring recorded branch "${expectedBranchName}".${result.clearedInProgressOperation ? ` An interrupted git ${GIT_IN_PROGRESS_OPERATION_LABELS[result.clearedInProgressOperation]} was also cleared; its in-flight state is preserved on the rescue branch.` : ""}`,
],
};
}
if (
input.enableWorkspaceBranchReconcileForward === true &&
evidence.provenance.ancestryVerdict === "ancestor" &&
!evidence.provenance.sameHead &&
evidence.cleanliness === "clean" &&
currentBranch
) {
const reason = "Automatic forward reconciliation: recorded branch is an ancestor of the checked-out branch.";
@@ -1747,7 +2416,7 @@ async function runWorkspaceCommand(input: {
async function recordGitOperation(
recorder: WorkspaceOperationRecorder | null | undefined,
input: {
phase: "worktree_prepare" | "worktree_cleanup";
phase: WorkspaceOperationPhase;
args: string[];
cwd: string;
metadata?: Record<string, unknown> | null;
@@ -1970,6 +2639,7 @@ export async function realizeExecutionWorkspace(input: {
agent: ExecutionWorkspaceAgentRef;
heartbeatRunId?: string | null;
enableWorkspaceBranchReconcileForward?: boolean;
enableWorkspaceDirtyQuarantineRepair?: boolean;
recorder?: WorkspaceOperationRecorder | null;
}): Promise<RealizedExecutionWorkspace> {
const rawStrategy = parseObject(input.config.workspaceStrategy);
@@ -2100,6 +2770,7 @@ export async function realizeExecutionWorkspace(input: {
executionWorkspaceId: null,
heartbeatRunId: input.heartbeatRunId ?? null,
enableWorkspaceBranchReconcileForward: input.enableWorkspaceBranchReconcileForward === true,
enableWorkspaceDirtyQuarantineRepair: input.enableWorkspaceDirtyQuarantineRepair === true,
reconcileOperationPhase: "worktree_prepare",
recorder: input.recorder ?? null,
});
@@ -2240,6 +2911,7 @@ export async function ensurePersistedExecutionWorkspaceAvailable(input: {
agent: ExecutionWorkspaceAgentRef;
heartbeatRunId?: string | null;
enableWorkspaceBranchReconcileForward?: boolean;
enableWorkspaceDirtyQuarantineRepair?: boolean;
recorder?: WorkspaceOperationRecorder | null;
}): Promise<RealizedExecutionWorkspace | null> {
const cwd = asString(input.workspace.cwd ?? input.workspace.providerRef, "").trim();
@@ -2285,6 +2957,7 @@ export async function ensurePersistedExecutionWorkspaceAvailable(input: {
executionWorkspaceId: input.workspace.id ?? null,
heartbeatRunId: input.heartbeatRunId ?? null,
enableWorkspaceBranchReconcileForward: input.enableWorkspaceBranchReconcileForward === true,
enableWorkspaceDirtyQuarantineRepair: input.enableWorkspaceDirtyQuarantineRepair === true,
persistForwardReconcile: false,
reconcileOperationPhase: "worktree_prepare",
recorder: input.recorder ?? null,