Skip to content

The open-source app everyone uses to manage agents at work

Add execution workspace branch reconciliation route (#9170)

Nicky Leachf17202b571ec
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 22cb697bfa..e724fd16b6 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1250,6 +1250,7 @@ export {
companyArtifactSourceSchema,
companyArtifactsQuerySchema,
companyArtifactsResponseSchema,
+ reconcileExecutionWorkspaceBranchSchema,
updateExecutionWorkspaceSchema,
workspaceOverviewQuerySchema,
executionWorkspaceStatusSchema,
@@ -1297,6 +1298,7 @@ export {
type UpdateIssueWorkProduct,
type UpsertIssueWatchdog,
type CompanyArtifactsQuery,
+ type ReconcileExecutionWorkspaceBranch,
type UpdateExecutionWorkspace,
type WorkspaceOverviewQuery,
type WorkspaceFileListQuery,
diff --git a/packages/shared/src/validators/execution-workspace.ts b/packages/shared/src/validators/execution-workspace.ts
index a937d44590..234c151375 100644
--- a/packages/shared/src/validators/execution-workspace.ts
+++ b/packages/shared/src/validators/execution-workspace.ts
@@ -149,5 +149,19 @@ export const updateExecutionWorkspaceSchema = z.object({
metadata: z.record(z.string(), z.unknown()).optional().nullable(),
}).strict();
+const branchReconcileReasonSchema = z.string().trim().min(1);
+
+export const reconcileExecutionWorkspaceBranchSchema = z.discriminatedUnion("mode", [
+ z.object({
+ mode: z.literal("forward"),
+ reason: branchReconcileReasonSchema.optional().nullable(),
+ }).strict(),
+ z.object({
+ mode: z.literal("override"),
+ reason: branchReconcileReasonSchema,
+ }).strict(),
+]);
+
export type UpdateExecutionWorkspace = z.infer<typeof updateExecutionWorkspaceSchema>;
+export type ReconcileExecutionWorkspaceBranch = z.infer<typeof reconcileExecutionWorkspaceBranchSchema>;
export type WorkspaceOverviewQuery = z.infer<typeof workspaceOverviewQuerySchema>;
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index 5cfe48d3cc..1dc44e0592 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -416,6 +416,7 @@ export {
export {
executionWorkspaceConfigSchema,
+ reconcileExecutionWorkspaceBranchSchema,
updateExecutionWorkspaceSchema,
workspaceOverviewQuerySchema,
executionWorkspaceStatusSchema,
@@ -425,6 +426,7 @@ export {
executionWorkspaceCloseLinkedIssueSchema,
executionWorkspaceCloseReadinessSchema,
executionWorkspaceCloseReadinessStateSchema,
+ type ReconcileExecutionWorkspaceBranch,
type UpdateExecutionWorkspace,
type WorkspaceOverviewQuery,
} from "./execution-workspace.js";
diff --git a/server/src/__tests__/execution-workspaces-routes.test.ts b/server/src/__tests__/execution-workspaces-routes.test.ts
index 1353357acd..757c4c6fe7 100644
--- a/server/src/__tests__/execution-workspaces-routes.test.ts
+++ b/server/src/__tests__/execution-workspaces-routes.test.ts
@@ -10,6 +10,7 @@ const mockExecutionWorkspaceService = vi.hoisted(() => ({
listSummaries: vi.fn(),
getById: vi.fn(),
getCloseReadiness: vi.fn(),
+ reconcileExecutionWorkspaceBranch: vi.fn(),
update: vi.fn(),
}));
@@ -30,17 +31,17 @@ vi.mock("../services/index.js", () => ({
workspaceOperationService: () => mockWorkspaceOperationService,
}));
-function createApp(companyIds = ["company-1"]) {
+function createApp(actor: Record<string, unknown> = {
+ type: "board",
+ userId: "local-board",
+ companyIds: ["company-1"],
+ source: "session",
+ isInstanceAdmin: false,
+}) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
- (req as any).actor = {
- type: "board",
- userId: "local-board",
- companyIds,
- source: "session",
- isInstanceAdmin: false,
- };
+ (req as any).actor = actor;
next();
});
app.use("/api", executionWorkspaceRoutes({} as any));
@@ -75,6 +76,7 @@ describe.sequential("execution workspace routes", () => {
},
]);
mockExecutionWorkspaceService.getById.mockResolvedValue(null);
+ mockExecutionWorkspaceService.reconcileExecutionWorkspaceBranch.mockResolvedValue(null);
});
it("uses summary mode for lightweight workspace lookups", async () => {
@@ -127,4 +129,95 @@ describe.sequential("execution workspace routes", () => {
expect(res.status).toBe(422);
expect(mockExecutionWorkspaceService.listOverview).not.toHaveBeenCalled();
});
+
+ it.each([
+ ["forward", { mode: "forward" }],
+ ["override", { mode: "override", reason: "operator break-glass" }],
+ ])("rejects agent actors for %s branch reconciliation", async (_mode, body) => {
+ mockExecutionWorkspaceService.getById.mockResolvedValue({
+ id: "workspace-1",
+ companyId: "company-1",
+ sourceIssueId: "issue-1",
+ });
+
+ const res = await request(createApp({
+ type: "agent",
+ agentId: "agent-1",
+ companyId: "company-1",
+ source: "agent_jwt",
+ runId: "run-1",
+ }))
+ .post("/api/execution-workspaces/workspace-1/reconcile-branch")
+ .send(body);
+
+ expect(res.status).toBe(403);
+ expect(mockExecutionWorkspaceService.reconcileExecutionWorkspaceBranch).not.toHaveBeenCalled();
+ expect(mockLogActivity).not.toHaveBeenCalled();
+ });
+
+ it("logs branch reconciliation activity after the service operation succeeds", async () => {
+ mockExecutionWorkspaceService.getById.mockResolvedValue({
+ id: "workspace-1",
+ companyId: "company-1",
+ sourceIssueId: "issue-1",
+ });
+ mockExecutionWorkspaceService.reconcileExecutionWorkspaceBranch.mockResolvedValue({
+ workspace: {
+ id: "workspace-1",
+ companyId: "company-1",
+ sourceIssueId: "issue-1",
+ branchName: "feature/current",
+ },
+ inspection: {
+ fingerprint: "workspace_incoherence:v1:sha256:test",
+ worktreePath: "/tmp/worktree",
+ repoRoot: "/tmp/repo",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ fromSha: "1111111",
+ toSha: "2222222",
+ ancestryVerdict: "ancestor",
+ cleanliness: "clean",
+ statusEntryCount: 0,
+ plainLanguageReason: "forward",
+ },
+ recoveryAction: {
+ id: "recovery-1",
+ },
+ auditCommentId: "comment-1",
+ });
+
+ const res = await request(createApp())
+ .post("/api/execution-workspaces/workspace-1/reconcile-branch")
+ .send({ mode: "forward" });
+
+ expect(res.status).toBe(200);
+ expect(mockExecutionWorkspaceService.reconcileExecutionWorkspaceBranch).toHaveBeenCalledWith("workspace-1", {
+ mode: "forward",
+ reason: null,
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ });
+ expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ action: "execution_workspace.branch_reconciled",
+ entityType: "execution_workspace",
+ entityId: "workspace-1",
+ details: expect.objectContaining({
+ mode: "forward",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ fromSha: "1111111",
+ toSha: "2222222",
+ ancestryVerdict: "ancestor",
+ fingerprint: "workspace_incoherence:v1:sha256:test",
+ sourceIssueId: "issue-1",
+ auditCommentId: "comment-1",
+ recoveryActionId: "recovery-1",
+ }),
+ }));
+ });
});
diff --git a/server/src/__tests__/execution-workspaces-service.test.ts b/server/src/__tests__/execution-workspaces-service.test.ts
index 710486dcce..3217626851 100644
--- a/server/src/__tests__/execution-workspaces-service.test.ts
+++ b/server/src/__tests__/execution-workspaces-service.test.ts
@@ -1,15 +1,18 @@
import { execFile } from "node:child_process";
+import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { promisify } from "node:util";
-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
-import { inArray } from "drizzle-orm";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { eq, inArray, sql } from "drizzle-orm";
import {
companies,
createDb,
executionWorkspaces,
+ issueComments,
+ issueRecoveryActions,
issues,
projectWorkspaces,
projects,
@@ -24,6 +27,10 @@ import {
mergeExecutionWorkspaceConfig,
readExecutionWorkspaceConfig,
} from "../services/execution-workspaces.ts";
+import {
+ startRuntimeServicesForWorkspaceControl,
+ stopRuntimeServicesForExecutionWorkspace,
+} from "../services/workspace-runtime.ts";
const execFileAsync = promisify(execFile);
@@ -132,6 +139,11 @@ async function runGit(cwd: string, args: string[]) {
await execFileAsync("git", ["-C", cwd, ...args], { cwd });
}
+async function readGit(cwd: string, args: string[]) {
+ const output = await execFileAsync("git", ["-C", cwd, ...args], { cwd });
+ return output.stdout.trim() || null;
+}
+
async function createTempRepo() {
const repoRoot = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-execution-workspace-"));
await runGit(repoRoot, ["init"]);
@@ -144,6 +156,62 @@ async function createTempRepo() {
return repoRoot;
}
+async function waitForPath(filePath: string, timeoutMs = 5_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ try {
+ await fs.access(filePath);
+ return;
+ } catch {
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+ }
+ throw new Error(`Timed out waiting for ${filePath}`);
+}
+
+function stableStringifyForTest(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map((entry) => stableStringifyForTest(entry)).join(",")}]`;
+ }
+ if (value && typeof value === "object") {
+ const rec = value as Record<string, unknown>;
+ return `{${Object.keys(rec).sort().map((key) => `${JSON.stringify(key)}:${stableStringifyForTest(rec[key])}`).join(",")}}`;
+ }
+ return JSON.stringify(value);
+}
+
+async function fingerprintWorkspaceBranchIncoherenceForTest(input: {
+ repoRoot: string;
+ worktreePath: string;
+ sourceIssueId: string;
+ executionWorkspaceId: string;
+ expectedBranch: string;
+ actualBranch: string | null;
+}) {
+ const status = await execFileAsync("git", ["-C", input.worktreePath, "status", "--porcelain", "--untracked-files=all"], {
+ cwd: input.worktreePath,
+ }).then((output) => output.stdout).catch(() => null);
+ const expectedHeadSha = await readGit(input.repoRoot, ["rev-parse", "--verify", `refs/heads/${input.expectedBranch}^{commit}`])
+ .catch(() => null);
+ const actualHeadSha = await readGit(input.worktreePath, ["rev-parse", "HEAD"]).catch(() => null);
+ const cleanliness = status === null ? "unknown" : status.trim().length > 0 ? "dirty" : "clean";
+ const digest = createHash("sha256")
+ .update(stableStringifyForTest({
+ version: 1,
+ reason: "git_worktree_branch_incoherence",
+ sourceIssueId: input.sourceIssueId,
+ executionWorkspaceId: input.executionWorkspaceId,
+ worktreePath: path.resolve(input.worktreePath),
+ expectedBranch: input.expectedBranch,
+ actualBranch: input.actualBranch,
+ cleanliness,
+ expectedHeadSha,
+ actualHeadSha,
+ }))
+ .digest("hex");
+ return `workspace_incoherence:v1:sha256:${digest}`;
+}
+
describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
let db!: ReturnType<typeof createDb>;
let svc!: ReturnType<typeof executionWorkspaceService>;
@@ -158,6 +226,8 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
afterEach(async () => {
await db.delete(workspaceRuntimeServices);
+ await db.delete(issueRecoveryActions);
+ await db.delete(issueComments);
await db.delete(issues);
await db.delete(executionWorkspaces);
await db.delete(projectWorkspaces);
@@ -422,6 +492,986 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
]);
});
+ it("reconciles a forward branch record, comments on the source issue, and resolves matching workspace recovery", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-reconcile-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/recorded"]);
+ await runGit(repoRoot, ["branch", "feature/current", "feature/recorded"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+ await fs.writeFile(path.join(worktreePath, "feature.txt"), "current branch\n", "utf8");
+ await runGit(worktreePath, ["add", "feature.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Current branch work"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+ const actualBranch = await readGit(worktreePath, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
+ const fingerprint = await fingerprintWorkspaceBranchIncoherenceForTest({
+ repoRoot,
+ worktreePath,
+ sourceIssueId: issueId,
+ executionWorkspaceId,
+ expectedBranch: "feature/recorded",
+ actualBranch,
+ });
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ identifier: "PAP-123",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "feature/recorded",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+ await db.insert(issueRecoveryActions).values({
+ companyId,
+ sourceIssueId: issueId,
+ kind: "workspace_validation",
+ status: "active",
+ ownerType: "board",
+ cause: "workspace_validation_failed",
+ fingerprint,
+ evidence: {
+ workspaceValidation: {
+ fingerprint,
+ },
+ },
+ nextAction: "Repair the source issue workspace link.",
+ });
+
+ const result = await svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "forward",
+ reason: null,
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ });
+
+ expect(result.workspace.branchName).toBe("feature/current");
+ expect(result.workspace.name).toBe("feature/current");
+ expect(result.inspection).toMatchObject({
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ ancestryVerdict: "ancestor",
+ fingerprint,
+ });
+ expect(result.recoveryAction).toMatchObject({
+ kind: "workspace_validation",
+ status: "resolved",
+ outcome: "restored",
+ fingerprint,
+ });
+
+ const [comment] = await db
+ .select()
+ .from(issueComments)
+ .where(eq(issueComments.issueId, issueId));
+ expect(comment).toMatchObject({
+ companyId,
+ issueId,
+ authorType: "user",
+ authorUserId: "local-board",
+ });
+ expect(comment?.body).toContain("Execution workspace branch reconciled.");
+ expect(comment?.body).toContain("- Mode: `forward`");
+ expect(comment?.body).toContain("- From branch: `feature/recorded`");
+ expect(comment?.body).toContain("- To branch: `feature/current`");
+ expect(comment?.body).toContain(`- Fingerprint: \`${fingerprint}\``);
+ expect(comment?.body).toContain(`- Recovery action: \`${result.recoveryAction?.id}\``);
+
+ const [recoveryAction] = await db
+ .select()
+ .from(issueRecoveryActions)
+ .where(eq(issueRecoveryActions.sourceIssueId, issueId));
+ expect(recoveryAction).toMatchObject({
+ status: "resolved",
+ outcome: "restored",
+ resolutionNote: "Execution workspace branch record reconciled from \"feature/recorded\" to \"feature/current\".",
+ });
+ }, 20_000);
+
+ it("rejects branch reconciliation when the worktree is dirty", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-dirty-reconcile-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/recorded"]);
+ await runGit(repoRoot, ["branch", "feature/current", "feature/recorded"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+ await fs.writeFile(path.join(worktreePath, "feature.txt"), "current branch\n", "utf8");
+ await runGit(worktreePath, ["add", "feature.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Current branch work"]);
+ await fs.writeFile(path.join(worktreePath, "dirty.txt"), "not safe to mutate\n", "utf8");
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Dirty workspace",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+
+ await expect(svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "override",
+ reason: "operator override still requires idle clean workspace",
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ })).rejects.toMatchObject({
+ status: 422,
+ message: "Execution workspace branch reconciliation requires a clean worktree",
+ details: {
+ inspection: expect.objectContaining({
+ cleanliness: "dirty",
+ statusEntryCount: 1,
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ }),
+ },
+ });
+
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(workspace?.branchName).toBe("feature/recorded");
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
+ it("rejects branch reconciliation while the workspace lifecycle is active", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-active-reconcile-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/recorded"]);
+ await runGit(repoRoot, ["branch", "feature/current", "feature/recorded"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+ await fs.writeFile(path.join(worktreePath, "feature.txt"), "current branch\n", "utf8");
+ await runGit(worktreePath, ["add", "feature.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Current branch work"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Active workspace",
+ status: "active",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+
+ await expect(svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "override",
+ reason: "operator override still requires idle workspace",
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ })).rejects.toMatchObject({
+ status: 422,
+ message: "Execution workspace branch reconciliation requires the workspace to be idle",
+ details: {
+ workspaceStatus: "active",
+ inspection: expect.objectContaining({
+ cleanliness: "clean",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ }),
+ },
+ });
+
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(workspace?.branchName).toBe("feature/recorded");
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
+ it("rejects branch reconciliation if the workspace becomes active before the branch record update", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-race-reconcile-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/recorded"]);
+ await runGit(repoRoot, ["branch", "feature/current", "feature/recorded"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+ await fs.writeFile(path.join(worktreePath, "feature.txt"), "current branch\n", "utf8");
+ await runGit(worktreePath, ["add", "feature.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Current branch work"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Race workspace",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+
+ const originalTransaction = db.transaction.bind(db);
+ const transactionSpy = vi.spyOn(db, "transaction").mockImplementation(
+ (async (...args: Parameters<typeof db.transaction>) => {
+ await db
+ .update(executionWorkspaces)
+ .set({ status: "active", updatedAt: new Date() })
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ return originalTransaction(...args);
+ }) as typeof db.transaction,
+ );
+
+ try {
+ await expect(svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "override",
+ reason: "operator override still requires idle workspace at write time",
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ })).rejects.toMatchObject({
+ status: 422,
+ message: "Execution workspace branch reconciliation requires the workspace to be idle",
+ details: {
+ workspaceStatus: "active",
+ inspection: expect.objectContaining({
+ cleanliness: "clean",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ }),
+ },
+ });
+ } finally {
+ transactionSpy.mockRestore();
+ }
+
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(workspace).toMatchObject({
+ status: "active",
+ branchName: "feature/recorded",
+ });
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
+ it("rejects branch reconciliation while runtime services are active", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-running-reconcile-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/recorded"]);
+ await runGit(repoRoot, ["branch", "feature/current", "feature/recorded"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+ await fs.writeFile(path.join(worktreePath, "feature.txt"), "current branch\n", "utf8");
+ await runGit(worktreePath, ["add", "feature.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Current branch work"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+ const runtimeServiceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Runtime workspace",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+ await db.insert(workspaceRuntimeServices).values({
+ id: runtimeServiceId,
+ companyId,
+ projectId,
+ executionWorkspaceId,
+ issueId,
+ scopeType: "execution_workspace",
+ serviceName: "web",
+ status: "running",
+ lifecycle: "shared",
+ command: "pnpm dev",
+ cwd: worktreePath,
+ provider: "local_process",
+ healthStatus: "healthy",
+ });
+
+ await expect(svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "override",
+ reason: "operator override still requires stopped services",
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ })).rejects.toMatchObject({
+ status: 422,
+ message: "Execution workspace branch reconciliation requires all runtime services to be stopped",
+ details: {
+ inspection: expect.objectContaining({
+ cleanliness: "clean",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ }),
+ runtimeServices: [
+ {
+ id: runtimeServiceId,
+ serviceName: "web",
+ status: "running",
+ },
+ ],
+ },
+ });
+
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(workspace?.branchName).toBe("feature/recorded");
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
+ it("rejects branch reconciliation when a runtime service starts before the locked update", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-raced-service-reconcile-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/recorded"]);
+ await runGit(repoRoot, ["branch", "feature/current", "feature/recorded"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+ await fs.writeFile(path.join(worktreePath, "feature.txt"), "current branch\n", "utf8");
+ await runGit(worktreePath, ["add", "feature.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Current branch work"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+ const runtimeServiceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Runtime race workspace",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+
+ let releaseBlockingTransaction: (() => void) | null = null;
+ const releaseBlockingTransactionPromise = new Promise<void>((resolve) => {
+ releaseBlockingTransaction = resolve;
+ });
+ let blockingTransactionReadyResolve: (() => void) | null = null;
+ const blockingTransactionReady = new Promise<void>((resolve) => {
+ blockingTransactionReadyResolve = resolve;
+ });
+
+ const blockingTransaction = db.transaction(async (tx) => {
+ await tx.execute(sql`select id from ${executionWorkspaces} where ${executionWorkspaces.id} = ${executionWorkspaceId} for update`);
+ await tx.insert(workspaceRuntimeServices).values({
+ id: runtimeServiceId,
+ companyId,
+ projectId,
+ executionWorkspaceId,
+ issueId,
+ scopeType: "execution_workspace",
+ serviceName: "web",
+ status: "running",
+ lifecycle: "shared",
+ command: "pnpm dev",
+ cwd: worktreePath,
+ provider: "local_process",
+ healthStatus: "healthy",
+ });
+ blockingTransactionReadyResolve?.();
+ await releaseBlockingTransactionPromise;
+ });
+
+ await blockingTransactionReady;
+
+ const reconcileExpectation = expect(svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "override",
+ reason: "operator override still requires stopped services",
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ })).rejects.toMatchObject({
+ status: 422,
+ message: "Execution workspace branch reconciliation requires all runtime services to be stopped",
+ details: {
+ inspection: expect.objectContaining({
+ cleanliness: "clean",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ }),
+ runtimeServices: [
+ {
+ id: runtimeServiceId,
+ serviceName: "web",
+ status: "running",
+ },
+ ],
+ },
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ releaseBlockingTransaction?.();
+ await reconcileExpectation;
+ await blockingTransaction;
+
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(workspace?.branchName).toBe("feature/recorded");
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
+ it("rejects branch reconciliation when runtime service activation is already spawning", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-spawning-service-reconcile-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/recorded"]);
+ await runGit(repoRoot, ["branch", "feature/current", "feature/recorded"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+ await fs.writeFile(path.join(worktreePath, "feature.txt"), "current branch\n", "utf8");
+ await runGit(worktreePath, ["add", "feature.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Current branch work"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+ const runtimeStartedMarker = path.join(os.tmpdir(), `paperclip-runtime-started-${randomUUID()}.marker`);
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Runtime activation race workspace",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+
+ const serverScript = [
+ `require("node:fs").writeFileSync(${JSON.stringify(runtimeStartedMarker)}, "started");`,
+ "setTimeout(() => {",
+ " require(\"node:http\")",
+ " .createServer((_req, res) => { res.end(\"ok\"); })",
+ " .listen(Number(process.env.PORT), \"127.0.0.1\");",
+ "}, 600);",
+ "setInterval(() => {}, 1000);",
+ ].join(" ");
+ const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(serverScript)}`;
+
+ let startedServices: Awaited<ReturnType<typeof startRuntimeServicesForWorkspaceControl>> = [];
+ try {
+ const startPromise = startRuntimeServicesForWorkspaceControl({
+ db,
+ invocationId: randomUUID(),
+ actor: {
+ id: null,
+ name: "Board",
+ companyId,
+ },
+ issue: {
+ id: issueId,
+ identifier: null,
+ title: "Source task",
+ },
+ workspace: {
+ baseCwd: worktreePath,
+ source: "task_session",
+ projectId,
+ workspaceId: null,
+ repoUrl: null,
+ repoRef: "main",
+ strategy: "git_worktree",
+ cwd: worktreePath,
+ branchName: "feature/current",
+ worktreePath,
+ warnings: [],
+ created: false,
+ },
+ executionWorkspaceId,
+ config: {
+ workspaceRuntime: {
+ services: [
+ {
+ name: "web",
+ command,
+ lifecycle: "shared",
+ reuseScope: "execution_workspace",
+ port: { type: "auto", envKey: "PORT" },
+ expose: { urlTemplate: "http://127.0.0.1:{{port}}" },
+ readiness: { type: "http", intervalMs: 50, timeoutSec: 10 },
+ },
+ ],
+ },
+ },
+ adapterEnv: {},
+ });
+
+ await Promise.race([
+ waitForPath(runtimeStartedMarker),
+ startPromise.then(
+ () => {
+ throw new Error("Runtime service activation finished before the process-start marker was observed");
+ },
+ (error) => {
+ throw error;
+ },
+ ),
+ ]);
+
+ const reconcilePromise = svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "override",
+ reason: "operator override still requires stopped services",
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ });
+
+ startedServices = await startPromise;
+ await expect(reconcilePromise).rejects.toMatchObject({
+ status: 422,
+ message: "Execution workspace branch reconciliation requires all runtime services to be stopped",
+ details: {
+ inspection: expect.objectContaining({
+ cleanliness: "clean",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ }),
+ runtimeServices: [
+ expect.objectContaining({
+ id: startedServices[0]?.id,
+ serviceName: "web",
+ status: "running",
+ }),
+ ],
+ },
+ });
+ } finally {
+ await stopRuntimeServicesForExecutionWorkspace({
+ db,
+ executionWorkspaceId,
+ workspaceCwd: worktreePath,
+ });
+ await fs.rm(runtimeStartedMarker, { force: true });
+ }
+
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(workspace?.branchName).toBe("feature/recorded");
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
+ it("rejects forward branch reconciliation for diverged branches", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-diverged-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["checkout", "-b", "feature/recorded"]);
+ await fs.writeFile(path.join(repoRoot, "recorded.txt"), "recorded branch\n", "utf8");
+ await runGit(repoRoot, ["add", "recorded.txt"]);
+ await runGit(repoRoot, ["commit", "-m", "Recorded branch work"]);
+ await runGit(repoRoot, ["checkout", "main"]);
+ await runGit(repoRoot, ["checkout", "-b", "feature/current"]);
+ await fs.writeFile(path.join(repoRoot, "current.txt"), "current branch\n", "utf8");
+ await runGit(repoRoot, ["add", "current.txt"]);
+ await runGit(repoRoot, ["commit", "-m", "Current branch work"]);
+ await runGit(repoRoot, ["checkout", "main"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Diverged workspace",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/recorded",
+ baseRef: "main",
+ });
+
+ await expect(svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "forward",
+ reason: null,
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ })).rejects.toMatchObject({
+ status: 422,
+ details: {
+ inspection: expect.objectContaining({
+ ancestryVerdict: "diverged",
+ fromBranch: "feature/recorded",
+ toBranch: "feature/current",
+ }),
+ },
+ });
+
+ const [workspace] = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ expect(workspace?.branchName).toBe("feature/recorded");
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
+ it("rejects forward branch reconciliation when branch ancestry is unknown", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-unknown-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+
+ await runGit(repoRoot, ["branch", "feature/current"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "feature/current"]);
+
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const issueId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "PAP",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Branch reconcile",
+ status: "in_progress",
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ projectId,
+ title: "Source task",
+ status: "blocked",
+ priority: "medium",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ sourceIssueId: issueId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: "Unknown workspace",
+ status: "idle",
+ providerType: "git_worktree",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ branchName: "feature/missing-recorded",
+ baseRef: "main",
+ });
+
+ await expect(svc.reconcileExecutionWorkspaceBranch(executionWorkspaceId, {
+ mode: "forward",
+ reason: null,
+ actor: {
+ actorType: "user",
+ actorId: "local-board",
+ agentId: null,
+ runId: null,
+ },
+ })).rejects.toMatchObject({
+ status: 422,
+ details: {
+ inspection: expect.objectContaining({
+ ancestryVerdict: "unknown",
+ fromBranch: "feature/missing-recorded",
+ toBranch: "feature/current",
+ fromSha: null,
+ }),
+ },
+ });
+
+ const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
+ expect(comments).toHaveLength(0);
+ }, 20_000);
+
it("returns a bounded company-scoped workspace overview with service and linked issue summaries", async () => {
const companyId = randomUUID();
const otherCompanyId = randomUUID();
diff --git a/server/src/__tests__/heartbeat-plugin-environment.test.ts b/server/src/__tests__/heartbeat-plugin-environment.test.ts
index 3a592ae92b..13f3d76c0b 100644
--- a/server/src/__tests__/heartbeat-plugin-environment.test.ts
+++ b/server/src/__tests__/heartbeat-plugin-environment.test.ts
@@ -456,24 +456,27 @@ describeEmbeddedPostgres("heartbeat plugin environments", () => {
const acquireCalls = workerManager.call.mock.calls
.filter(([, method]) => method === "environmentAcquireLease");
+ const acquirePayloads = acquireCalls.map(([, , payload]) => payload);
expect(acquireCalls).toHaveLength(2);
- expect(acquireCalls[0]?.[2]).toMatchObject({
- companyId: companyAId,
- environmentId: sharedEnvironmentId,
- config: { template: "shared" },
- agentId: agentAId,
- runId: sharedRun!.id,
- adapterType: "codex_local",
- });
- expect(acquireCalls[1]?.[2]).toMatchObject({
- companyId: companyBId,
- environmentId: overrideEnvironmentId,
- config: { template: "override" },
- agentId: agentBId,
- runId: overrideRun!.id,
- adapterType: "codex_local",
- });
+ expect(acquirePayloads).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ companyId: companyAId,
+ environmentId: sharedEnvironmentId,
+ config: { template: "shared" },
+ agentId: agentAId,
+ runId: sharedRun!.id,
+ adapterType: "codex_local",
+ }),
+ expect.objectContaining({
+ companyId: companyBId,
+ environmentId: overrideEnvironmentId,
+ config: { template: "override" },
+ agentId: agentBId,
+ runId: overrideRun!.id,
+ adapterType: "codex_local",
+ }),
+ ]));
}, 15_000);
it("ignores stale non-reused workspace environment config in favor of the assignee selection", async () => {
diff --git a/server/src/__tests__/heartbeat-worktree-suppression.test.ts b/server/src/__tests__/heartbeat-worktree-suppression.test.ts
index a85abdf2f8..71d9255eff 100644
--- a/server/src/__tests__/heartbeat-worktree-suppression.test.ts
+++ b/server/src/__tests__/heartbeat-worktree-suppression.test.ts
@@ -43,11 +43,11 @@ describeEmbeddedPostgres("heartbeat worktree suppression", () => {
afterEach(async () => {
await db.delete(heartbeatRunEvents);
- await db.delete(activityLog);
await db.delete(issueComments);
await db.delete(issueDocuments);
await db.delete(documentRevisions);
await db.delete(documents);
+ await db.delete(activityLog);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(issues);
diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts
index 97d7750a69..52b3658780 100644
--- a/server/src/__tests__/openapi-routes.test.ts
+++ b/server/src/__tests__/openapi-routes.test.ts
@@ -185,6 +185,13 @@ describe("openapi routes", () => {
actor: "board",
instanceAdmin: true,
});
+ expect(spec.paths["/api/execution-workspaces/{id}/reconcile-branch"].post.security).toEqual([
+ { BoardSessionAuth: [] },
+ { BoardApiKeyAuth: [] },
+ ]);
+ expect(spec.paths["/api/execution-workspaces/{id}/reconcile-branch"].post["x-paperclip-authorization"]).toEqual({
+ actor: "board",
+ });
expect(spec.paths["/api/companies/{companyId}/cost-events"].post.responses["201"]).toBeDefined();
expect(spec.paths["/api/companies/{companyId}/cost-events"].post.responses["403"]).toBeDefined();
expect(spec.paths["/api/instance/database-backups"].post.responses["201"]).toBeDefined();
diff --git a/server/src/routes/execution-workspaces.ts b/server/src/routes/execution-workspaces.ts
index 91b90eb4a2..42e16bfcc3 100644
--- a/server/src/routes/execution-workspaces.ts
+++ b/server/src/routes/execution-workspaces.ts
@@ -5,6 +5,7 @@ import { issues, projects, projectWorkspaces } from "@paperclipai/db";
import {
findWorkspaceCommandDefinition,
matchWorkspaceRuntimeServiceToCommand,
+ reconcileExecutionWorkspaceBranchSchema,
updateExecutionWorkspaceSchema,
workspaceOverviewQuerySchema,
workspaceRuntimeControlTargetSchema,
@@ -24,7 +25,7 @@ import {
startRuntimeServicesForWorkspaceControl,
stopRuntimeServicesForExecutionWorkspace,
} from "../services/workspace-runtime.js";
-import { assertCompanyAccess, getActorInfo } from "./authz.js";
+import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
import {
assertNoAgentHostWorkspaceCommandMutation,
collectExecutionWorkspaceCommandPaths,
@@ -491,6 +492,61 @@ export function executionWorkspaceRoutes(db: Db, opts: { pluginWorkerManager?: P
router.post("/execution-workspaces/:id/runtime-services/:action", validate(workspaceRuntimeControlTargetSchema), handleExecutionWorkspaceRuntimeCommand);
router.post("/execution-workspaces/:id/runtime-commands/:action", validate(workspaceRuntimeControlTargetSchema), handleExecutionWorkspaceRuntimeCommand);
+ router.post("/execution-workspaces/:id/reconcile-branch", validate(reconcileExecutionWorkspaceBranchSchema), async (req, res) => {
+ const id = req.params.id as string;
+ const existing = await svc.getById(id);
+ if (!existing) {
+ res.status(404).json({ error: "Execution workspace not found" });
+ return;
+ }
+ assertCompanyAccess(req, existing.companyId);
+ assertBoard(req);
+ if (!(await assertRuntimeManageAllowed(req, res, existing.companyId))) return;
+
+ const actor = getActorInfo(req);
+ const result = await svc.reconcileExecutionWorkspaceBranch(id, {
+ mode: req.body.mode,
+ reason: req.body.reason ?? null,
+ actor: {
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ },
+ });
+
+ await logActivity(db, {
+ companyId: existing.companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "execution_workspace.branch_reconciled",
+ entityType: "execution_workspace",
+ entityId: existing.id,
+ details: {
+ mode: req.body.mode,
+ reason: req.body.reason ?? null,
+ fromBranch: result.inspection.fromBranch,
+ toBranch: result.inspection.toBranch,
+ fromSha: result.inspection.fromSha,
+ toSha: result.inspection.toSha,
+ ancestryVerdict: result.inspection.ancestryVerdict,
+ fingerprint: result.inspection.fingerprint,
+ sourceIssueId: existing.sourceIssueId,
+ auditCommentId: result.auditCommentId,
+ recoveryActionId: result.recoveryAction?.id ?? null,
+ actor: {
+ type: actor.actorType,
+ id: actor.actorId,
+ source: actor.actorSource,
+ },
+ },
+ });
+
+ res.json(result);
+ });
+
router.patch("/execution-workspaces/:id", validate(updateExecutionWorkspaceSchema), async (req, res) => {
const id = req.params.id as string;
const existing = await svc.getById(id);
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index 85342b3f8b..69511eae35 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -72,6 +72,7 @@ import {
// Sidebar
upsertSidebarOrderPreferenceSchema,
// Execution workspaces
+ reconcileExecutionWorkspaceBranchSchema,
updateExecutionWorkspaceSchema,
workspaceOverviewQuerySchema,
workspaceRuntimeControlTargetSchema,
@@ -661,6 +662,7 @@ const BOARD_ONLY_OPERATIONS = new Set([
"POST /api/companies/{companyId}/members/{memberId}/archive",
"PATCH /api/companies/{companyId}/members/{memberId}/permissions",
"GET /api/companies/{companyId}/user-directory",
+ "POST /api/execution-workspaces/{id}/reconcile-branch",
"GET /api/board-api-keys",
"POST /api/board-api-keys",
"DELETE /api/board-api-keys/{keyId}",
@@ -3624,6 +3626,18 @@ registry.registerPath({
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
});
+registry.registerPath({
+ method: "post",
+ path: "/api/execution-workspaces/{id}/reconcile-branch",
+ tags: ["execution-workspaces"],
+ summary: "Reconcile an execution workspace branch record",
+ request: {
+ params: z.object({ id: z.string() }),
+ body: jsonBody(reconcileExecutionWorkspaceBranchSchema),
+ },
+ responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 422: r.unprocessable },
+});
+
registry.registerPath({
method: "post",
path: "/api/execution-workspaces/{id}/runtime-services/{action}",
diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts
index d099ca6726..4f031fa84c 100644
--- a/server/src/services/execution-workspaces.ts
+++ b/server/src/services/execution-workspaces.ts
@@ -1,10 +1,11 @@
import { execFile } from "node:child_process";
+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 type { Db } from "@paperclipai/db";
-import { executionWorkspaces, issues, projects, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
+import { executionWorkspaces, issueComments, issues, projects, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
import type {
ExecutionWorkspace,
ExecutionWorkspaceSummary,
@@ -19,9 +20,13 @@ import type {
WorkspaceRuntimeService,
WorkspaceOverviewPrimaryService,
WorkspaceOverviewQuery,
+ GitWorktreeBranchAncestryVerdict,
+ IssueRecoveryAction,
} from "@paperclipai/shared";
import { deriveProjectUrlKey, WORKSPACE_OVERVIEW_LINKED_ISSUE_LIMIT } from "@paperclipai/shared";
+import { conflict, notFound, unprocessable } from "../errors.js";
import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js";
+import { issueRecoveryActionService } from "./issue-recovery-actions.js";
import { readProjectWorkspaceRuntimeConfig } from "./project-workspace-runtime-config.js";
import {
listCurrentRuntimeServicesForExecutionWorkspaces,
@@ -30,8 +35,41 @@ import {
type ExecutionWorkspaceRow = typeof executionWorkspaces.$inferSelect;
type WorkspaceRuntimeServiceRow = typeof workspaceRuntimeServices.$inferSelect;
+type RuntimeServiceReadDb = Pick<Db, "select">;
const execFileAsync = promisify(execFile);
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 ExecutionWorkspaceBranchReconcileActor = {
+ actorType: "agent" | "user";
+ actorId: string;
+ agentId: string | null;
+ runId: string | null;
+};
+
+export type ExecutionWorkspaceBranchReconcileInspection = {
+ fingerprint: string;
+ worktreePath: string;
+ repoRoot: string;
+ fromBranch: string;
+ toBranch: string;
+ fromSha: string | null;
+ toSha: string | null;
+ ancestryVerdict: GitWorktreeBranchAncestryVerdict;
+ cleanliness: "clean" | "dirty" | "unknown";
+ statusEntryCount: number | null;
+ plainLanguageReason: string;
+};
+
+export type ExecutionWorkspaceBranchReconcileResult = {
+ workspace: ExecutionWorkspace;
+ inspection: ExecutionWorkspaceBranchReconcileInspection;
+ recoveryAction: IssueRecoveryAction | null;
+ auditCommentId: string | null;
+};
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -76,6 +114,253 @@ async function runGit(args: string[], cwd: string) {
return await execFileAsync("git", ["-C", cwd, ...args], { cwd });
}
+async function readGitStdout(args: string[], cwd: string): Promise<string | null> {
+ const output = await runGit(args, cwd);
+ return output.stdout.trim() || null;
+}
+
+function stableStringify(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
+ }
+ if (value && typeof value === "object") {
+ const rec = value as Record<string, unknown>;
+ return `{${Object.keys(rec).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(rec[key])}`).join(",")}}`;
+ }
+ return JSON.stringify(value);
+}
+
+function formatBranchForMessage(branch: string | null | undefined) {
+ return branch && branch.length > 0 ? branch : "<detached>";
+}
+
+function fingerprintWorkspaceBranchIncoherence(input: {
+ sourceIssueId: string | null;
+ executionWorkspaceId: string | null;
+ worktreePath: string;
+ expectedBranch: string;
+ actualBranch: string | null;
+ cleanliness: "clean" | "dirty" | "unknown";
+ expectedHeadSha: string | null;
+ actualHeadSha: string | null;
+}) {
+ const digest = createHash("sha256")
+ .update(stableStringify({
+ version: 1,
+ reason: WORKSPACE_BRANCH_INCOHERENCE_REASON,
+ sourceIssueId: input.sourceIssueId,
+ executionWorkspaceId: input.executionWorkspaceId,
+ worktreePath: path.resolve(input.worktreePath),
+ expectedBranch: input.expectedBranch,
+ actualBranch: input.actualBranch,
+ cleanliness: input.cleanliness,
+ expectedHeadSha: input.expectedHeadSha,
+ actualHeadSha: input.actualHeadSha,
+ }))
+ .digest("hex");
+ return `workspace_incoherence:v1:sha256:${digest}`;
+}
+
+async function getGitWorktreeBranchAncestryVerdict(input: {
+ repoRoot: string;
+ expectedHeadSha: string | null;
+ actualHeadSha: string | null;
+}): Promise<GitWorktreeBranchAncestryVerdict> {
+ if (!input.expectedHeadSha || !input.actualHeadSha) return "unknown";
+
+ try {
+ await runGit(["merge-base", "--is-ancestor", input.expectedHeadSha, input.actualHeadSha], input.repoRoot);
+ return "ancestor";
+ } catch (error) {
+ const code = typeof error === "object" && error && "code" in error
+ ? (error as { code?: unknown }).code
+ : null;
+ return code === 1 ? "diverged" : "unknown";
+ }
+}
+
+function explainGitWorktreeBranchReconcileInspection(input: {
+ fromBranch: string;
+ toBranch: string;
+ fromSha: string | null;
+ toSha: string | null;
+ ancestryVerdict: GitWorktreeBranchAncestryVerdict;
+}) {
+ if (!input.fromSha || !input.toSha) {
+ return `Paperclip could not determine branch ancestry because "${input.fromBranch}" or "${input.toBranch}" is missing a resolvable HEAD commit.`;
+ }
+ if (input.fromSha === input.toSha) {
+ return `The recorded branch "${input.fromBranch}" and checked-out branch "${input.toBranch}" resolve to the same commit.`;
+ }
+ if (input.ancestryVerdict === "ancestor") {
+ return `The recorded branch "${input.fromBranch}" is an ancestor of the checked-out branch "${input.toBranch}".`;
+ }
+ if (input.ancestryVerdict === "diverged") {
+ return `The recorded branch "${input.fromBranch}" is not an ancestor of the checked-out branch "${input.toBranch}".`;
+ }
+ return `Paperclip could not determine whether "${input.toBranch}" is forward of "${input.fromBranch}".`;
+}
+
+async function inspectExecutionWorkspaceBranchForReconcile(
+ workspace: Pick<ExecutionWorkspace, "id" | "sourceIssueId" | "cwd" | "providerRef" | "branchName">,
+): Promise<ExecutionWorkspaceBranchReconcileInspection> {
+ const fromBranch = readNullableString(workspace.branchName);
+ if (!fromBranch) {
+ throw unprocessable("Execution workspace has no recorded branch to reconcile");
+ }
+
+ const worktreePath = readNullableString(workspace.providerRef) ?? readNullableString(workspace.cwd);
+ if (!worktreePath) {
+ throw unprocessable("Execution workspace needs a local worktree path before Paperclip can reconcile its branch record");
+ }
+
+ const repoRoot = await readGitStdout(["rev-parse", "--show-toplevel"], worktreePath).catch(() => null);
+ if (!repoRoot) {
+ throw unprocessable("Execution workspace path is not inside a git repository");
+ }
+
+ const toBranch = await readGitStdout(["symbolic-ref", "--quiet", "--short", "HEAD"], worktreePath).catch(() => null);
+ if (!toBranch) {
+ throw unprocessable("Execution workspace is detached; Paperclip cannot reconcile it to a branch name");
+ }
+
+ const status = await runGit(["status", "--porcelain", "--untracked-files=all"], worktreePath)
+ .then((output) => output.stdout)
+ .catch(() => null);
+ const statusLines = status === null
+ ? null
+ : status.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
+ const cleanliness: ExecutionWorkspaceBranchReconcileInspection["cleanliness"] =
+ status === null ? "unknown" : status.trim().length > 0 ? "dirty" : "clean";
+
+ const fromSha = await readGitStdout(["rev-parse", "--verify", `refs/heads/${fromBranch}^{commit}`], repoRoot)
+ .catch(() => null);
+ const toSha = await readGitStdout(["rev-parse", "HEAD"], worktreePath).catch(() => null);
+ const ancestryVerdict = await getGitWorktreeBranchAncestryVerdict({
+ repoRoot,
+ expectedHeadSha: fromSha,
+ actualHeadSha: toSha,
+ });
+
+ return {
+ fingerprint: fingerprintWorkspaceBranchIncoherence({
+ sourceIssueId: workspace.sourceIssueId ?? null,
+ executionWorkspaceId: workspace.id,
+ worktreePath,
+ expectedBranch: fromBranch,
+ actualBranch: toBranch,
+ cleanliness,
+ expectedHeadSha: fromSha,
+ actualHeadSha: toSha,
+ }),
+ worktreePath: path.resolve(worktreePath),
+ repoRoot: path.resolve(repoRoot),
+ fromBranch,
+ toBranch,
+ fromSha,
+ toSha,
+ ancestryVerdict,
+ cleanliness,
+ statusEntryCount: statusLines?.length ?? null,
+ plainLanguageReason: explainGitWorktreeBranchReconcileInspection({
+ fromBranch,
+ toBranch,
+ fromSha,
+ toSha,
+ ancestryVerdict,
+ }),
+ };
+}
+
+function formatBranchReconcileAuditComment(input: {
+ mode: ExecutionWorkspaceBranchReconcileMode;
+ reason: string | null;
+ workspaceId: string;
+ inspection: ExecutionWorkspaceBranchReconcileInspection;
+ recoveryActionId: string | null;
+}) {
+ return [
+ "Execution workspace branch reconciled.",
+ "",
+ `- Workspace: \`${input.workspaceId}\``,
+ `- Mode: \`${input.mode}\``,
+ `- From branch: \`${formatBranchForMessage(input.inspection.fromBranch)}\``,
+ `- To branch: \`${formatBranchForMessage(input.inspection.toBranch)}\``,
+ `- From SHA: \`${input.inspection.fromSha ?? "unknown"}\``,
+ `- To SHA: \`${input.inspection.toSha ?? "unknown"}\``,
+ `- Verdict: \`${input.inspection.ancestryVerdict}\``,
+ `- Fingerprint: \`${input.inspection.fingerprint}\``,
+ `- Recovery action: ${input.recoveryActionId ? `\`${input.recoveryActionId}\`` : "none matched"}`,
+ ...(input.reason ? [`- Operator reason: ${input.reason}`] : []),
+ ].join("\n");
+}
+
+function assertBranchReconcileWorkspaceIsSafe(input: {
+ workspaceStatus: ExecutionWorkspace["status"];
+ inspection: ExecutionWorkspaceBranchReconcileInspection;
+ runtimeServices: WorkspaceRuntimeService[];
+}) {
+ if (input.workspaceStatus !== "idle") {
+ throw unprocessable("Execution workspace branch reconciliation requires the workspace to be idle", {
+ workspaceStatus: input.workspaceStatus,
+ inspection: input.inspection,
+ });
+ }
+
+ if (input.inspection.cleanliness !== "clean") {
+ throw unprocessable("Execution workspace branch reconciliation requires a clean worktree", {
+ inspection: input.inspection,
+ });
+ }
+
+ 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", {
+ inspection: input.inspection,
+ runtimeServices: activeRuntimeServices.map((service) => ({
+ id: service.id,
+ serviceName: service.serviceName,
+ status: service.status,
+ })),
+ });
+ }
+}
+
+function assertLockedBranchReconcileWorkspaceStillMatchesInspection(input: {
+ lockedRow: ExecutionWorkspaceRow;
+ inspectedRow: ExecutionWorkspaceRow;
+ inspection: ExecutionWorkspaceBranchReconcileInspection;
+}) {
+ const lockedPath = readNullableString(input.lockedRow.providerRef) ?? readNullableString(input.lockedRow.cwd);
+ const lockedBranch = readNullableString(input.lockedRow.branchName);
+ const currentPath = lockedPath ? path.resolve(lockedPath) : null;
+
+ if (
+ input.lockedRow.sourceIssueId !== input.inspectedRow.sourceIssueId ||
+ input.lockedRow.projectWorkspaceId !== input.inspectedRow.projectWorkspaceId ||
+ lockedBranch !== input.inspection.fromBranch ||
+ currentPath !== input.inspection.worktreePath
+ ) {
+ throw conflict("Execution workspace changed during branch reconciliation; retry with the latest workspace state", {
+ workspaceId: input.lockedRow.id,
+ expected: {
+ status: input.inspectedRow.status,
+ sourceIssueId: input.inspectedRow.sourceIssueId,
+ projectWorkspaceId: input.inspectedRow.projectWorkspaceId,
+ branchName: input.inspection.fromBranch,
+ worktreePath: input.inspection.worktreePath,
+ },
+ current: {
+ status: input.lockedRow.status,
+ sourceIssueId: input.lockedRow.sourceIssueId,
+ projectWorkspaceId: input.lockedRow.projectWorkspaceId,
+ branchName: lockedBranch,
+ worktreePath: currentPath,
+ },
+ });
+ }
+}
+
async function inspectGitCloseReadiness(workspace: ExecutionWorkspace): Promise<{
git: ExecutionWorkspaceCloseGitReadiness | null;
warnings: string[];
@@ -404,8 +689,25 @@ function usesInheritedProjectRuntimeServices(row: ExecutionWorkspaceRow) {
return !readExecutionWorkspaceConfig((row.metadata as Record<string, unknown> | null) ?? null)?.workspaceRuntime;
}
+function noActiveRuntimeServicesForWorkspaceCondition(row: ExecutionWorkspaceRow) {
+ const inheritedProjectWorkspaceId = usesInheritedProjectRuntimeServices(row) ? row.projectWorkspaceId : null;
+ const activeServiceConditions = inheritedProjectWorkspaceId
+ ? and(
+ eq(workspaceRuntimeServices.companyId, row.companyId),
+ eq(workspaceRuntimeServices.projectWorkspaceId, inheritedProjectWorkspaceId),
+ eq(workspaceRuntimeServices.scopeType, "project_workspace"),
+ ne(workspaceRuntimeServices.status, "stopped"),
+ )
+ : and(
+ eq(workspaceRuntimeServices.companyId, row.companyId),
+ eq(workspaceRuntimeServices.executionWorkspaceId, row.id),
+ ne(workspaceRuntimeServices.status, "stopped"),
+ );
+ return sql`not exists (select 1 from ${workspaceRuntimeServices} where ${activeServiceConditions})`;
+}
+
async function loadEffectiveRuntimeServicesByExecutionWorkspace(
- db: Db,
+ db: RuntimeServiceReadDb,
companyId: string,
rows: ExecutionWorkspaceRow[],
) {
@@ -444,6 +746,8 @@ type WorkspaceOverviewIssueRow = WorkspaceOverviewLinkedIssue & {
};
export function executionWorkspaceService(db: Db) {
+ const recoveryActionsSvc = issueRecoveryActionService(db);
+
function buildListConditions(
companyId: string,
filters?: {
@@ -1026,6 +1330,190 @@ export function executionWorkspaceService(db: Db) {
return row ? toExecutionWorkspace(row) : null;
},
+ reconcileExecutionWorkspaceBranch: async (
+ id: string,
+ input: {
+ mode: ExecutionWorkspaceBranchReconcileMode;
+ reason?: string | null;
+ actor: ExecutionWorkspaceBranchReconcileActor;
+ },
+ ): Promise<ExecutionWorkspaceBranchReconcileResult> => {
+ const existingRow = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, id))
+ .then((rows) => rows[0] ?? null);
+ if (!existingRow) throw notFound("Execution workspace not found");
+
+ const existing = toExecutionWorkspace(existingRow);
+ if (!existing.sourceIssueId) {
+ throw unprocessable("Execution workspace needs a source issue before Paperclip can audit branch reconciliation");
+ }
+
+ const inspection = await inspectExecutionWorkspaceBranchForReconcile(existing);
+ if (input.mode === "forward" && inspection.ancestryVerdict !== "ancestor") {
+ throw unprocessable(
+ "Forward branch reconciliation requires the recorded branch to be an ancestor of the checked-out branch",
+ { inspection },
+ );
+ }
+
+ const reason = readNullableString(input.reason);
+ const now = new Date();
+ return db.transaction(async (tx) => {
+ const txDb = tx as unknown as Db;
+ // Runtime-service activation takes this same row lock before spawning
+ // local services and holds it until the running service row is persisted.
+ const lockedRow = await tx
+ .select()
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, existing.id))
+ .for("update")
+ .then((rows) => rows[0] ?? null);
+ if (!lockedRow) throw notFound("Execution workspace not found");
+
+ assertLockedBranchReconcileWorkspaceStillMatchesInspection({
+ lockedRow,
+ inspectedRow: existingRow,
+ inspection,
+ });
+
+ if (usesInheritedProjectRuntimeServices(lockedRow)) {
+ await tx
+ .select({ id: projectWorkspaces.id })
+ .from(projectWorkspaces)
+ .where(
+ and(
+ eq(projectWorkspaces.companyId, lockedRow.companyId),
+ eq(projectWorkspaces.id, lockedRow.projectWorkspaceId!),
+ ),
+ )
+ .for("update");
+ }
+
+ await tx
+ .select({ id: workspaceRuntimeServices.id })
+ .from(workspaceRuntimeServices)
+ .where(
+ usesInheritedProjectRuntimeServices(lockedRow)
+ ? and(
+ eq(workspaceRuntimeServices.companyId, lockedRow.companyId),
+ eq(workspaceRuntimeServices.projectWorkspaceId, lockedRow.projectWorkspaceId!),
+ eq(workspaceRuntimeServices.scopeType, "project_workspace"),
+ )
+ : and(
+ eq(workspaceRuntimeServices.companyId, lockedRow.companyId),
+ eq(workspaceRuntimeServices.executionWorkspaceId, lockedRow.id),
+ ),
+ )
+ .for("update");
+
+ const lockedRuntimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(
+ txDb,
+ lockedRow.companyId,
+ [lockedRow],
+ );
+ const lockedRuntimeServices = (lockedRuntimeServicesByWorkspaceId.get(lockedRow.id) ?? []).map(toRuntimeService);
+ const lockedWorkspace = toExecutionWorkspace(lockedRow, lockedRuntimeServices);
+ if (!lockedWorkspace.sourceIssueId) {
+ throw unprocessable("Execution workspace needs a source issue before Paperclip can audit branch reconciliation");
+ }
+ assertBranchReconcileWorkspaceIsSafe({
+ workspaceStatus: lockedWorkspace.status,
+ inspection,
+ runtimeServices: lockedRuntimeServices,
+ });
+ 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),
+ 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);
+ assertBranchReconcileWorkspaceIsSafe({
+ workspaceStatus: lockedWorkspace.status,
+ inspection,
+ runtimeServices: latestRuntimeServices,
+ });
+ throw unprocessable("Execution workspace branch reconciliation requires the workspace to stay idle with stopped runtime services during the update", {
+ inspection,
+ });
+ }
+
+ const recoveryAction = await recoveryActionsSvc.resolveActiveForIssue(
+ {
+ companyId: lockedWorkspace.companyId,
+ sourceIssueId: lockedWorkspace.sourceIssueId,
+ kind: "workspace_validation",
+ cause: WORKSPACE_VALIDATION_RECOVERY_CAUSE,
+ fingerprint: inspection.fingerprint,
+ status: "resolved",
+ outcome: "restored",
+ resolutionNote: `Execution workspace branch record reconciled from "${inspection.fromBranch}" to "${inspection.toBranch}".`,
+ },
+ tx,
+ );
+
+ const [auditComment] = await tx
+ .insert(issueComments)
+ .values({
+ companyId: lockedWorkspace.companyId,
+ issueId: lockedWorkspace.sourceIssueId,
+ authorAgentId: input.actor.actorType === "agent" ? input.actor.agentId : null,
+ authorUserId: input.actor.actorType === "user" ? input.actor.actorId : null,
+ authorType: input.actor.actorType,
+ createdByRunId: input.actor.runId,
+ body: formatBranchReconcileAuditComment({
+ mode: input.mode,
+ reason,
+ workspaceId: existing.id,
+ inspection,
+ recoveryActionId: recoveryAction?.id ?? null,
+ }),
+ })
+ .returning({ id: issueComments.id });
+
+ await tx
+ .update(issues)
+ .set({ updatedAt: now })
+ .where(eq(issues.id, lockedWorkspace.sourceIssueId));
+
+ return {
+ workspace: toExecutionWorkspace(updatedRow, lockedRuntimeServices),
+ inspection,
+ recoveryAction,
+ auditCommentId: auditComment?.id ?? null,
+ };
+ });
+ },
+
clearEnvironmentSelection: async (companyId: string, environmentId: string) => {
return db.transaction(async (tx) => {
const rows = await tx
diff --git a/server/src/services/issue-recovery-actions.ts b/server/src/services/issue-recovery-actions.ts
index cf6083e696..3ed00bc863 100644
--- a/server/src/services/issue-recovery-actions.ts
+++ b/server/src/services/issue-recovery-actions.ts
@@ -41,6 +41,9 @@ export type ResolveIssueRecoveryActionInput = {
companyId: string;
sourceIssueId: string;
actionId?: string | null;
+ kind?: IssueRecoveryActionKind | null;
+ cause?: string | null;
+ fingerprint?: string | null;
status: Extract<IssueRecoveryActionStatus, "resolved" | "cancelled">;
outcome: IssueRecoveryActionOutcome;
resolutionNote?: string | null;
@@ -270,6 +273,15 @@ export function issueRecoveryActionService(db: Db) {
if (input.actionId) {
predicates.push(eq(issueRecoveryActions.id, input.actionId));
}
+ if (input.kind) {
+ predicates.push(eq(issueRecoveryActions.kind, input.kind));
+ }
+ if (input.cause) {
+ predicates.push(eq(issueRecoveryActions.cause, input.cause));
+ }
+ if (input.fingerprint) {
+ predicates.push(eq(issueRecoveryActions.fingerprint, input.fingerprint));
+ }
const [updated] = await dbOrTx
.update(issueRecoveryActions)
diff --git a/server/src/services/workspace-runtime-read-model.ts b/server/src/services/workspace-runtime-read-model.ts
index dba6190d48..b492f11110 100644
--- a/server/src/services/workspace-runtime-read-model.ts
+++ b/server/src/services/workspace-runtime-read-model.ts
@@ -3,6 +3,7 @@ import { workspaceRuntimeServices } from "@paperclipai/db";
import { and, desc, eq, inArray } from "drizzle-orm";
type WorkspaceRuntimeServiceRow = typeof workspaceRuntimeServices.$inferSelect;
+type RuntimeServiceReadDb = Pick<Db, "select">;
function runtimeServiceIdentityKey(row: WorkspaceRuntimeServiceRow) {
if (row.reuseKey) return row.reuseKey;
@@ -27,7 +28,7 @@ export function selectCurrentRuntimeServiceRows(rows: WorkspaceRuntimeServiceRow
}
export async function listCurrentRuntimeServicesForProjectWorkspaces(
- db: Db,
+ db: RuntimeServiceReadDb,
companyId: string,
projectWorkspaceIds: string[],
) {
@@ -62,7 +63,7 @@ export async function listCurrentRuntimeServicesForProjectWorkspaces(
}
export async function listCurrentRuntimeServicesForExecutionWorkspaces(
- db: Db,
+ db: RuntimeServiceReadDb,
companyId: string,
executionWorkspaceIds: string[],
) {
diff --git a/server/src/services/workspace-runtime.ts b/server/src/services/workspace-runtime.ts
index 14af9af6b0..a3806f9426 100644
--- a/server/src/services/workspace-runtime.ts
+++ b/server/src/services/workspace-runtime.ts
@@ -3239,7 +3239,7 @@ export async function ensureRuntimeServicesForRun(input: {
return refs;
}
-export async function startRuntimeServicesForWorkspaceControl(input: {
+type StartRuntimeServicesForWorkspaceControlInput = {
db?: Db;
invocationId?: string;
actor: ExecutionWorkspaceAgentRef;
@@ -3251,16 +3251,16 @@ export async function startRuntimeServicesForWorkspaceControl(input: {
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
serviceIndex?: number | null;
respectDesiredStates?: boolean;
-}): Promise<RuntimeServiceRef[]> {
- const rawServices = selectRuntimeServiceEntries({
- config: input.config,
- serviceIndex: input.serviceIndex,
- respectDesiredStates: input.respectDesiredStates,
- defaultDesiredState: readDesiredRuntimeState(input.config.desiredState) ?? "stopped",
- serviceStates: readConfiguredServiceStates(input.config),
- });
+};
+
+async function startRuntimeServicesForWorkspaceControlUnlocked(
+ input: StartRuntimeServicesForWorkspaceControlInput,
+ rawServices: Record<string, unknown>[],
+ invocationId: string,
+ persistenceDb = input.db,
+ registryDb = input.db,
+): Promise<RuntimeServiceRef[]> {
const refs: RuntimeServiceRef[] = [];
- const invocationId = input.invocationId ?? randomUUID();
for (const service of rawServices) {
const { scopeType, scopeId } = resolveServiceScopeId({
@@ -3292,7 +3292,7 @@ export async function startRuntimeServicesForWorkspaceControl(input: {
runtimeServiceId: existing.id,
lastSeenAt: existing.lastUsedAt,
});
- await persistRuntimeServiceRecord(input.db, existing);
+ await persistRuntimeServiceRecord(persistenceDb, existing);
refs.push(toRuntimeServiceRef(existing, { reused: true }));
continue;
}
@@ -3301,7 +3301,7 @@ export async function startRuntimeServicesForWorkspaceControl(input: {
// Manually controlled services are not tied to a heartbeat run lifecycle, so they do not
// retain a run lease and never persist a startedByRunId foreign key.
const record = await startLocalRuntimeService({
- db: input.db,
+ db: persistenceDb,
runId: invocationId,
leaseRunId: null,
startedByRunId: null,
@@ -3316,14 +3316,83 @@ export async function startRuntimeServicesForWorkspaceControl(input: {
scopeType,
scopeId,
});
- registerRuntimeService(input.db, record);
- await persistRuntimeServiceRecord(input.db, record);
+ registerRuntimeService(registryDb, record);
+ await persistRuntimeServiceRecord(persistenceDb, record);
refs.push(toRuntimeServiceRef(record));
}
return refs;
}
+export async function startRuntimeServicesForWorkspaceControl(
+ input: StartRuntimeServicesForWorkspaceControlInput,
+): Promise<RuntimeServiceRef[]> {
+ const rawServices = selectRuntimeServiceEntries({
+ config: input.config,
+ serviceIndex: input.serviceIndex,
+ respectDesiredStates: input.respectDesiredStates,
+ defaultDesiredState: readDesiredRuntimeState(input.config.desiredState) ?? "stopped",
+ serviceStates: readConfiguredServiceStates(input.config),
+ });
+ const invocationId = input.invocationId ?? randomUUID();
+
+ if (rawServices.length === 0 || !input.db || (!input.executionWorkspaceId && !input.workspace.workspaceId)) {
+ return startRuntimeServicesForWorkspaceControlUnlocked(input, rawServices, invocationId);
+ }
+
+ let startedRefs: RuntimeServiceRef[] = [];
+ try {
+ return await input.db.transaction(async (tx) => {
+ const txDb = tx as unknown as Db;
+
+ if (input.executionWorkspaceId) {
+ const [lockedExecutionWorkspace] = await tx
+ .select({ id: executionWorkspaces.id })
+ .from(executionWorkspaces)
+ .where(
+ and(
+ eq(executionWorkspaces.id, input.executionWorkspaceId),
+ eq(executionWorkspaces.companyId, input.actor.companyId),
+ ),
+ )
+ .for("update");
+ if (!lockedExecutionWorkspace) throw new Error("Execution workspace not found before starting runtime services");
+ }
+
+ if (input.workspace.workspaceId) {
+ const [lockedProjectWorkspace] = await tx
+ .select({ id: projectWorkspaces.id })
+ .from(projectWorkspaces)
+ .where(
+ and(
+ eq(projectWorkspaces.id, input.workspace.workspaceId),
+ eq(projectWorkspaces.companyId, input.actor.companyId),
+ ),
+ )
+ .for("update");
+ if (!lockedProjectWorkspace) throw new Error("Project workspace not found before starting runtime services");
+ }
+
+ // Branch reconciliation takes these same parent row locks before mutating
+ // a recorded branch. Holding them until the running service row is
+ // persisted closes the process-start window before the FK insert.
+ startedRefs = await startRuntimeServicesForWorkspaceControlUnlocked(
+ { ...input, db: txDb },
+ rawServices,
+ invocationId,
+ txDb,
+ input.db,
+ );
+ return startedRefs;
+ });
+ } catch (error) {
+ for (const ref of startedRefs) {
+ await stopRuntimeService(ref.id).catch(() => undefined);
+ }
+ throw error;
+ }
+}
+
export async function releaseRuntimeServicesForRun(runId: string) {
const acquired = runtimeServiceLeasesByRun.get(runId) ?? [];
runtimeServiceLeasesByRun.delete(runId);