Skip to content

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

Recognize delivered workspaces and reap terminal worktrees (#10908)

Dotta72b509c89539
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md
index a27d3dd21e..ca6df43c59 100644
--- a/doc/SPEC-implementation.md
+++ b/doc/SPEC-implementation.md
@@ -1037,7 +1037,10 @@ The current app also exposes V1-supporting surfaces for:
`GET /companies/:companyId/search/extract`; extraction accepts a server-escaped literal `contains`, optional
server-owned URL expansion, issue/comment/document scopes, status/date filters, issue-level pagination, a
bounded `matchesPerIssue` override for machine consumers, and explicit issue/match truncation flags
-- execution workspaces, project workspaces, workspace runtime services, and workspace operations
+- execution workspaces, project workspaces, workspace runtime services, and workspace operations. Workspace reads
+ derive `deliveryState` as `merged_via_pr | merged_by_ancestry | unmerged | unknown`; terminal issue trees with a
+ merged delivery and no active checkout run become cleanup-eligible with reason `issue_terminal` and are archived
+ through the workspace cleanup path. Reopening the source issue records activity but does not restore that workspace.
- task watchdog configuration and reusable watchdog issue orchestration for explicitly watched issue subtrees
- routines and scheduled/API/webhook triggers
- plugin installation, configuration, state, jobs, logs, webhooks, and plugin database namespace migration
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 9715de7c8a..4073b8132f 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -832,6 +832,7 @@ export type {
ExecutionWorkspaceCloseLinkedIssue,
ExecutionWorkspaceCloseReadiness,
ExecutionWorkspaceCloseReadinessState,
+ ExecutionWorkspaceDeliveryState,
WorkspaceOverviewItem,
WorkspaceOverviewLinkedIssue,
WorkspaceOverviewPrimaryService,
@@ -1746,6 +1747,7 @@ export {
reconcileExecutionWorkspaceBranchSchema,
updateExecutionWorkspaceSchema,
workspaceOverviewQuerySchema,
+ executionWorkspaceDeliveryStateSchema,
executionWorkspaceStatusSchema,
executionWorkspaceCloseActionKindSchema,
executionWorkspaceCloseActionSchema,
diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts
index e0822c7164..6745a095b8 100644
--- a/packages/shared/src/types/index.ts
+++ b/packages/shared/src/types/index.ts
@@ -351,6 +351,7 @@ export type {
ExecutionWorkspaceCloseLinkedIssue,
ExecutionWorkspaceCloseReadiness,
ExecutionWorkspaceCloseReadinessState,
+ ExecutionWorkspaceDeliveryState,
WorkspaceOverviewItem,
WorkspaceOverviewLinkedIssue,
WorkspaceOverviewPrimaryService,
diff --git a/packages/shared/src/types/workspace-runtime.ts b/packages/shared/src/types/workspace-runtime.ts
index 878374934a..f2b79f8981 100644
--- a/packages/shared/src/types/workspace-runtime.ts
+++ b/packages/shared/src/types/workspace-runtime.ts
@@ -35,6 +35,12 @@ export type ExecutionWorkspaceStatus =
| "archived"
| "cleanup_failed";
+export type ExecutionWorkspaceDeliveryState =
+ | "merged_via_pr"
+ | "merged_by_ancestry"
+ | "unmerged"
+ | "unknown";
+
export type ExecutionWorkspaceCloseReadinessState =
| "ready"
| "ready_with_warnings"
@@ -137,6 +143,7 @@ export interface ExecutionWorkspaceCloseGitReadiness {
export interface ExecutionWorkspaceCloseReadiness {
workspaceId: string;
+ deliveryState: ExecutionWorkspaceDeliveryState;
state: ExecutionWorkspaceCloseReadinessState;
blockingReasons: string[];
warnings: string[];
@@ -252,6 +259,7 @@ export interface ExecutionWorkspace {
strategyType: ExecutionWorkspaceStrategyType;
name: string;
status: ExecutionWorkspaceStatus;
+ deliveryState: ExecutionWorkspaceDeliveryState;
cwd: string | null;
repoUrl: string | null;
baseRef: string | null;
diff --git a/packages/shared/src/validators/execution-workspace.ts b/packages/shared/src/validators/execution-workspace.ts
index 61d365de74..fc03413aeb 100644
--- a/packages/shared/src/validators/execution-workspace.ts
+++ b/packages/shared/src/validators/execution-workspace.ts
@@ -12,6 +12,13 @@ export const executionWorkspaceStatusSchema = z.enum([
"cleanup_failed",
]);
+export const executionWorkspaceDeliveryStateSchema = z.enum([
+ "merged_via_pr",
+ "merged_by_ancestry",
+ "unmerged",
+ "unknown",
+]);
+
const workspaceOverviewStatusFilterSchema = z.preprocess((value) => {
if (value === undefined || value === null) return undefined;
const rawValues = Array.isArray(value) ? value : [value];
@@ -124,6 +131,7 @@ export const workspaceRuntimeServiceSchema = z.object({
}).strict();
export const executionWorkspaceCloseReadinessSchema = z.object({
workspaceId: z.string().uuid(),
+ deliveryState: executionWorkspaceDeliveryStateSchema,
state: executionWorkspaceCloseReadinessStateSchema,
blockingReasons: z.array(z.string()),
warnings: z.array(z.string()),
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index 4fc51c47ac..d93c6649dd 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -549,6 +549,7 @@ export {
reconcileExecutionWorkspaceBranchSchema,
updateExecutionWorkspaceSchema,
workspaceOverviewQuerySchema,
+ executionWorkspaceDeliveryStateSchema,
executionWorkspaceStatusSchema,
executionWorkspaceCloseActionKindSchema,
executionWorkspaceCloseActionSchema,
diff --git a/server/src/__tests__/execution-workspaces-service.test.ts b/server/src/__tests__/execution-workspaces-service.test.ts
index a1565e0f08..b2765817c9 100644
--- a/server/src/__tests__/execution-workspaces-service.test.ts
+++ b/server/src/__tests__/execution-workspaces-service.test.ts
@@ -15,7 +15,9 @@ import {
executionWorkspaces,
heartbeatRuns,
issueComments,
+ issueReferenceMentions,
issueRecoveryActions,
+ issueWorkProducts,
issues,
projectWorkspaces,
projects,
@@ -27,9 +29,11 @@ import {
} from "./helpers/embedded-postgres.js";
import {
executionWorkspaceService,
+ deriveExecutionWorkspaceDeliveryState,
mergeExecutionWorkspaceConfig,
readExecutionWorkspaceConfig,
} from "../services/execution-workspaces.ts";
+import { issueService } from "../services/issues.ts";
import {
startRuntimeServicesForWorkspaceControl,
stopRuntimeServicesForExecutionWorkspace,
@@ -37,6 +41,17 @@ import {
const execFileAsync = promisify(execFile);
+describe("execution workspace delivery state", () => {
+ it.each([
+ [{ sourceIssueTerminal: true, mergedPullRequest: true, pullRequestStateUnknown: false, isMergedIntoBase: false }, "merged_via_pr"],
+ [{ sourceIssueTerminal: false, mergedPullRequest: false, pullRequestStateUnknown: false, isMergedIntoBase: true }, "merged_by_ancestry"],
+ [{ sourceIssueTerminal: true, mergedPullRequest: false, pullRequestStateUnknown: false, isMergedIntoBase: false }, "unmerged"],
+ [{ sourceIssueTerminal: true, mergedPullRequest: false, pullRequestStateUnknown: true, isMergedIntoBase: false }, "unknown"],
+ ] as const)("derives %s as %s", (input, expected) => {
+ expect(deriveExecutionWorkspaceDeliveryState(input)).toBe(expected);
+ });
+});
+
describe("execution workspace config helpers", () => {
it("reads typed config from persisted metadata", () => {
expect(readExecutionWorkspaceConfig({
@@ -224,17 +239,29 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
let svc!: ReturnType<typeof executionWorkspaceService>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const tempDirs = new Set<string>();
+ const pullRequestDetailsByKey = new Map<string, {
+ state: "merged" | "open" | "unknown";
+ headRef: string | null;
+ headSha: string | null;
+ }>();
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-execution-workspaces-service-");
db = createDb(tempDb.connectionString);
- svc = executionWorkspaceService(db);
+ svc = executionWorkspaceService(db, {
+ resolvePullRequestDetails: vi.fn(async (companyId, reference) =>
+ pullRequestDetailsByKey.get(`${companyId}:${reference.number}`)
+ ?? { state: "unknown", headRef: null, headSha: null }
+ ),
+ });
}, 20_000);
afterEach(async () => {
await db.delete(workspaceRuntimeServices);
await db.delete(activityLog);
await db.delete(issueRecoveryActions);
+ await db.delete(issueWorkProducts);
+ await db.delete(issueReferenceMentions);
await db.delete(issueComments);
await db.delete(issues);
await db.delete(executionWorkspaces);
@@ -243,6 +270,7 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
+ pullRequestDetailsByKey.clear();
for (const dir of tempDirs) {
await fs.rm(dir, { recursive: true, force: true });
@@ -254,6 +282,487 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
await tempDb?.cleanup();
});
+ async function seedTerminalWorkspace(options: {
+ mergedPr?: boolean;
+ activeRun?: boolean;
+ childStatus?: "done" | "todo";
+ } = {}) {
+ const companyId = randomUUID();
+ const projectId = randomUUID();
+ const executionWorkspaceId = randomUUID();
+ const sourceIssueId = randomUUID();
+ const issuePrefix = `P${companyId.slice(0, 8).toUpperCase()}`;
+ const identifier = `${issuePrefix}-1`;
+ const repoRoot = await createTempRepo();
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-terminal-${randomUUID()}`);
+ tempDirs.add(repoRoot);
+ tempDirs.add(worktreePath);
+ await runGit(repoRoot, ["branch", "PAP-16015-delivery"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "PAP-16015-delivery"]);
+ await fs.writeFile(path.join(worktreePath, "delivered.txt"), "delivered\n", "utf8");
+ await runGit(worktreePath, ["add", "delivered.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Delivered change"]);
+ const headSha = await readGit(worktreePath, ["rev-parse", "HEAD"]);
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix,
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(projects).values({
+ id: projectId,
+ companyId,
+ name: "Terminal workspaces",
+ status: "in_progress",
+ });
+ await db.insert(executionWorkspaces).values({
+ id: executionWorkspaceId,
+ companyId,
+ projectId,
+ mode: "isolated_workspace",
+ strategyType: "git_worktree",
+ name: identifier,
+ status: "active",
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ providerType: "git_worktree",
+ repoUrl: "https://github.com/paperclipai/paperclip.git",
+ baseRef: "main",
+ branchName: "PAP-16015-delivery",
+ });
+ await db.insert(issues).values({
+ id: sourceIssueId,
+ companyId,
+ projectId,
+ identifier,
+ title: "Delivered source issue",
+ status: "done",
+ priority: "medium",
+ executionWorkspaceId,
+ });
+ await db
+ .update(executionWorkspaces)
+ .set({ sourceIssueId })
+ .where(eq(executionWorkspaces.id, executionWorkspaceId));
+ if (options.childStatus) {
+ await db.insert(issues).values({
+ id: randomUUID(),
+ companyId,
+ projectId,
+ parentId: sourceIssueId,
+ title: "Descendant",
+ status: options.childStatus,
+ priority: "medium",
+ });
+ }
+ if (options.mergedPr) {
+ await db.insert(issueWorkProducts).values({
+ companyId,
+ issueId: sourceIssueId,
+ executionWorkspaceId,
+ type: "pull_request",
+ provider: "github",
+ title: "Delivered PR",
+ url: "https://github.com/paperclipai/paperclip/pull/10623",
+ status: "merged",
+ });
+ }
+ pullRequestDetailsByKey.set(`${companyId}:10623`, {
+ state: "merged",
+ headRef: "PAP-16015-delivery",
+ headSha,
+ });
+ pullRequestDetailsByKey.set(`${companyId}:10624`, {
+ state: "merged",
+ headRef: "unrelated-delivery",
+ headSha,
+ });
+ pullRequestDetailsByKey.set(`${companyId}:10625`, {
+ state: "merged",
+ headRef: "descendant-delivery",
+ headSha,
+ });
+ if (options.activeRun) {
+ const agentId = randomUUID();
+ const runId = randomUUID();
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Coder",
+ role: "engineer",
+ status: "active",
+ adapterType: "codex_local",
+ adapterConfig: {},
+ runtimeConfig: {},
+ permissions: {},
+ });
+ await db.insert(heartbeatRuns).values({
+ id: runId,
+ companyId,
+ agentId,
+ status: "running",
+ });
+ await db.update(issues).set({ checkoutRunId: runId }).where(eq(issues.id, sourceIssueId));
+ }
+ return { companyId, projectId, executionWorkspaceId, sourceIssueId, identifier, repoRoot, worktreePath, headSha };
+ }
+
+ it("reports a squash cross-branch delivery as merged_via_pr and suppresses the ancestry warning", async () => {
+ const repoRoot = await createTempRepo();
+ tempDirs.add(repoRoot);
+ const worktreePath = path.join(path.dirname(repoRoot), `paperclip-delivery-${randomUUID()}`);
+ tempDirs.add(worktreePath);
+ await runGit(repoRoot, ["branch", "PAP-16015-delivery"]);
+ await runGit(repoRoot, ["worktree", "add", worktreePath, "PAP-16015-delivery"]);
+ await fs.writeFile(path.join(worktreePath, "delivered.txt"), "delivered\n", "utf8");
+ await runGit(worktreePath, ["add", "delivered.txt"]);
+ await runGit(worktreePath, ["commit", "-m", "Delivered change"]);
+
+ const seeded = await seedTerminalWorkspace();
+ pullRequestDetailsByKey.set(`${seeded.companyId}:10623`, {
+ state: "merged",
+ headRef: "PAP-16015-delivery",
+ headSha: await readGit(worktreePath, ["rev-parse", "HEAD"]),
+ });
+ await db.update(executionWorkspaces).set({
+ cwd: worktreePath,
+ providerRef: worktreePath,
+ providerType: "git_worktree",
+ baseRef: "main",
+ repoUrl: "https://github.com/paperclipai/paperclip.git",
+ branchName: "PAP-16015-delivery",
+ }).where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+ await db.insert(issueWorkProducts).values({
+ companyId: seeded.companyId,
+ issueId: seeded.sourceIssueId,
+ type: "pull_request",
+ provider: "github",
+ title: "Cross-branch delivery",
+ url: "https://github.com/paperclipai/paperclip/pull/10623",
+ status: "merged",
+ });
+
+ const readiness = await svc.getCloseReadiness(seeded.executionWorkspaceId);
+
+ expect(readiness?.deliveryState).toBe("merged_via_pr");
+ expect(readiness?.git?.isMergedIntoBase).toBe(false);
+ expect(readiness?.warnings).not.toContain(
+ "This workspace is 1 commit ahead of main and is not merged.",
+ );
+
+ const sweep = await svc.sweepTerminalWorkspaces();
+ const archived = await db
+ .select({
+ status: executionWorkspaces.status,
+ cleanupEligibleAt: executionWorkspaces.cleanupEligibleAt,
+ cleanupReason: executionWorkspaces.cleanupReason,
+ })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId))
+ .then((rows) => rows[0]);
+
+ expect(sweep.archived).toBe(1);
+ expect(archived).toMatchObject({ status: "archived", cleanupReason: "issue_terminal" });
+ expect(archived?.cleanupEligibleAt).toBeInstanceOf(Date);
+ }, 20_000);
+
+ it("does not treat an unrelated inbound issue mention as delivery evidence", async () => {
+ const seeded = await seedTerminalWorkspace();
+ const unrelatedIssueId = randomUUID();
+ await db.insert(issues).values({
+ id: unrelatedIssueId,
+ companyId: seeded.companyId,
+ projectId: seeded.projectId,
+ title: `Investigate ${seeded.identifier} follow-up`,
+ status: "done",
+ priority: "medium",
+ });
+ await db.insert(issueReferenceMentions).values({
+ companyId: seeded.companyId,
+ sourceIssueId: unrelatedIssueId,
+ targetIssueId: seeded.sourceIssueId,
+ sourceKind: "title",
+ sourceRecordId: null,
+ documentKey: null,
+ matchedText: seeded.identifier,
+ });
+ await db.insert(issueWorkProducts).values({
+ companyId: seeded.companyId,
+ issueId: unrelatedIssueId,
+ type: "pull_request",
+ provider: "github",
+ title: "Unrelated merged PR",
+ url: "https://github.com/paperclipai/paperclip/pull/10624",
+ status: "merged",
+ });
+
+ const readiness = await svc.getCloseReadiness(seeded.executionWorkspaceId);
+ const sweep = await svc.sweepTerminalWorkspaces();
+ const [workspace] = await db
+ .select({
+ status: executionWorkspaces.status,
+ cleanupEligibleAt: executionWorkspaces.cleanupEligibleAt,
+ cleanupReason: executionWorkspaces.cleanupReason,
+ })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(readiness?.deliveryState).toBe("unmerged");
+ expect(sweep).toMatchObject({ archived: 0, skippedUndelivered: 1 });
+ expect(workspace).toMatchObject({
+ status: "active",
+ cleanupEligibleAt: null,
+ cleanupReason: null,
+ });
+ });
+
+ it("does not trust directly linked merged products for a different repository or branch", async () => {
+ const seeded = await seedTerminalWorkspace();
+ await db.insert(issueWorkProducts).values([
+ {
+ companyId: seeded.companyId,
+ issueId: seeded.sourceIssueId,
+ executionWorkspaceId: seeded.executionWorkspaceId,
+ type: "pull_request",
+ provider: "github",
+ title: "Wrong branch merged PR",
+ url: "https://github.com/paperclipai/paperclip/pull/10624",
+ status: "merged",
+ },
+ {
+ companyId: seeded.companyId,
+ issueId: seeded.sourceIssueId,
+ executionWorkspaceId: seeded.executionWorkspaceId,
+ type: "pull_request",
+ provider: "github",
+ title: "Wrong repository merged PR",
+ url: "https://github.com/unrelated/paperclip/pull/10623",
+ status: "merged",
+ },
+ ]);
+
+ const readiness = await svc.getCloseReadiness(seeded.executionWorkspaceId);
+ const sweep = await svc.sweepTerminalWorkspaces();
+ const [workspace] = await db
+ .select({ status: executionWorkspaces.status })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(readiness?.deliveryState).toBe("unmerged");
+ expect(sweep).toMatchObject({ archived: 0, skippedUndelivered: 1 });
+ expect(workspace?.status).toBe("active");
+ });
+
+ it("does not trust a previously merged PR after new workspace commits", async () => {
+ const seeded = await seedTerminalWorkspace({ mergedPr: true });
+ await fs.writeFile(path.join(seeded.worktreePath, "new-work.txt"), "not delivered\n", "utf8");
+ await runGit(seeded.worktreePath, ["add", "new-work.txt"]);
+ await runGit(seeded.worktreePath, ["commit", "-m", "New undelivered work"]);
+
+ const readiness = await svc.getCloseReadiness(seeded.executionWorkspaceId);
+ const sweep = await svc.sweepTerminalWorkspaces();
+ const [workspace] = await db
+ .select({ status: executionWorkspaces.status })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(readiness?.deliveryState).toBe("unmerged");
+ expect(readiness?.warnings).toContain(
+ "This workspace is 2 commits ahead of main and is not merged.",
+ );
+ expect(sweep).toMatchObject({ archived: 0, skippedUndelivered: 1 });
+ expect(workspace?.status).toBe("active");
+ });
+
+ it("does not reap uncommitted work after the workspace HEAD was delivered", async () => {
+ const seeded = await seedTerminalWorkspace({ mergedPr: true });
+ await fs.writeFile(path.join(seeded.worktreePath, "uncommitted.txt"), "not delivered\n", "utf8");
+
+ const readiness = await svc.getCloseReadiness(seeded.executionWorkspaceId);
+ const sweep = await svc.sweepTerminalWorkspaces();
+ const [workspace] = await db
+ .select({ status: executionWorkspaces.status })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(readiness?.deliveryState).toBe("merged_via_pr");
+ expect(readiness?.warnings).toContain("The workspace has 1 untracked file.");
+ expect(sweep).toMatchObject({ archived: 0, skippedUndelivered: 1 });
+ expect(workspace?.status).toBe("active");
+ });
+
+ it("refuses cleanup when the worktree changes after delivery assessment", async () => {
+ const seeded = await seedTerminalWorkspace({ mergedPr: true });
+ await db.update(executionWorkspaces).set({
+ metadata: {
+ createdByRuntime: true,
+ config: { cleanupCommand: "rm -f late-work.txt" },
+ },
+ }).where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+ const racingService = executionWorkspaceService(db, {
+ resolvePullRequestDetails: async (_companyId, reference) =>
+ pullRequestDetailsByKey.get(`${seeded.companyId}:${reference.number}`) ?? { state: "unknown" },
+ beforeTerminalWorkspaceCleanup: async () => {
+ await fs.writeFile(path.join(seeded.worktreePath, "late-work.txt"), "not delivered\n", "utf8");
+ },
+ });
+
+ const sweep = await racingService.sweepTerminalWorkspaces();
+ const [workspace] = await db
+ .select({ status: executionWorkspaces.status, cleanupReason: executionWorkspaces.cleanupReason })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(sweep).toMatchObject({ archived: 0, cleanupFailed: 1 });
+ expect(workspace?.status).toBe("cleanup_failed");
+ expect(workspace?.cleanupReason).toContain("git worktree changed after delivery was verified");
+ await expect(fs.readFile(path.join(seeded.worktreePath, "late-work.txt"), "utf8"))
+ .resolves.toBe("not delivered\n");
+ });
+
+ it("archives terminal workspaces without running configured cleanup hooks", async () => {
+ const seeded = await seedTerminalWorkspace({ mergedPr: true });
+ const cleanupMarker = path.join(path.dirname(seeded.worktreePath), `cleanup-marker-${randomUUID()}`);
+ tempDirs.add(cleanupMarker);
+ await db.update(executionWorkspaces).set({
+ metadata: {
+ createdByRuntime: true,
+ config: { cleanupCommand: `touch ${cleanupMarker}` },
+ },
+ }).where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ const sweep = await svc.sweepTerminalWorkspaces();
+ const [workspace] = await db
+ .select({ status: executionWorkspaces.status })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(sweep).toMatchObject({ archived: 1, cleanupFailed: 0 });
+ expect(workspace?.status).toBe("archived");
+ await expect(fs.access(seeded.worktreePath)).rejects.toThrow();
+ await expect(fs.access(cleanupMarker)).rejects.toThrow();
+ });
+
+ it("holds Git index and ref locks across terminal cleanup", async () => {
+ const seeded = await seedTerminalWorkspace({ mergedPr: true });
+ await db.update(executionWorkspaces).set({
+ metadata: { createdByRuntime: true },
+ }).where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+ let commitFailure = "";
+ let refUpdateFailure = "";
+ const lockingService = executionWorkspaceService(db, {
+ resolvePullRequestDetails: async (_companyId, reference) =>
+ pullRequestDetailsByKey.get(`${seeded.companyId}:${reference.number}`) ?? { state: "unknown" },
+ beforeTerminalWorkspaceCleanup: async () => {
+ try {
+ await runGit(seeded.worktreePath, ["commit", "--allow-empty", "-m", "Late commit"]);
+ } catch (error) {
+ commitFailure = error instanceof Error ? error.message : String(error);
+ }
+ try {
+ await runGit(seeded.worktreePath, ["update-ref", "HEAD", seeded.headSha]);
+ } catch (error) {
+ refUpdateFailure = error instanceof Error ? error.message : String(error);
+ }
+ },
+ });
+
+ const sweep = await lockingService.sweepTerminalWorkspaces();
+ const [workspace] = await db
+ .select({ status: executionWorkspaces.status, cleanupReason: executionWorkspaces.cleanupReason })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(commitFailure).toContain("index.lock");
+ expect(refUpdateFailure).toMatch(/HEAD\.lock|refs\/heads\/PAP-16015-delivery\.lock/);
+ expect(sweep).toMatchObject({ archived: 1, cleanupFailed: 0 });
+ expect(workspace).toMatchObject({ status: "archived", cleanupReason: "issue_terminal" });
+ await expect(fs.access(seeded.worktreePath)).rejects.toThrow();
+ expect(await readGit(seeded.repoRoot, ["branch", "--list", "PAP-16015-delivery"])).toBeNull();
+ });
+
+ it("does not treat a descendant PR on the shared workspace as parent delivery evidence", async () => {
+ const seeded = await seedTerminalWorkspace();
+ const descendantIssueId = randomUUID();
+ await db.insert(issues).values({
+ id: descendantIssueId,
+ companyId: seeded.companyId,
+ projectId: seeded.projectId,
+ parentId: seeded.sourceIssueId,
+ title: "Delivered descendant",
+ status: "done",
+ priority: "medium",
+ executionWorkspaceId: seeded.executionWorkspaceId,
+ });
+ await db.insert(issueWorkProducts).values({
+ companyId: seeded.companyId,
+ issueId: descendantIssueId,
+ executionWorkspaceId: seeded.executionWorkspaceId,
+ type: "pull_request",
+ provider: "github",
+ title: "Descendant delivery",
+ url: "https://github.com/paperclipai/paperclip/pull/10625",
+ status: "merged",
+ });
+
+ const readiness = await svc.getCloseReadiness(seeded.executionWorkspaceId);
+ const sweep = await svc.sweepTerminalWorkspaces();
+ const [parentWorkspace] = await db
+ .select({ status: executionWorkspaces.status })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, seeded.executionWorkspaceId));
+
+ expect(readiness?.deliveryState).toBe("unmerged");
+ expect(sweep).toMatchObject({ archived: 0, skippedUndelivered: 1 });
+ expect(parentWorkspace?.status).toBe("active");
+ });
+
+ it("reaps only fully-terminal delivered workspaces without active checkout runs", async () => {
+ const eligible = await seedTerminalWorkspace({ mergedPr: true, childStatus: "done" });
+ const activeRun = await seedTerminalWorkspace({ mergedPr: true, activeRun: true });
+ const openDescendant = await seedTerminalWorkspace({ mergedPr: true, childStatus: "todo" });
+ const undelivered = await seedTerminalWorkspace();
+
+ const result = await svc.sweepTerminalWorkspaces();
+ const rows = await db
+ .select({ id: executionWorkspaces.id, status: executionWorkspaces.status, cleanupEligibleAt: executionWorkspaces.cleanupEligibleAt, cleanupReason: executionWorkspaces.cleanupReason })
+ .from(executionWorkspaces)
+ .where(inArray(executionWorkspaces.id, [
+ eligible.executionWorkspaceId,
+ activeRun.executionWorkspaceId,
+ openDescendant.executionWorkspaceId,
+ undelivered.executionWorkspaceId,
+ ]));
+ const byId = new Map(rows.map((row) => [row.id, row]));
+
+ expect(result).toMatchObject({ archived: 1, skippedActiveRun: 1, skippedNonTerminalTree: 1, skippedUndelivered: 1 });
+ expect(byId.get(eligible.executionWorkspaceId)).toMatchObject({ status: "archived", cleanupReason: "issue_terminal" });
+ expect(byId.get(eligible.executionWorkspaceId)?.cleanupEligibleAt).toBeInstanceOf(Date);
+ expect(byId.get(activeRun.executionWorkspaceId)?.status).toBe("active");
+ expect(byId.get(openDescendant.executionWorkspaceId)?.status).toBe("active");
+ expect(byId.get(undelivered.executionWorkspaceId)?.status).toBe("active");
+
+ const second = await svc.sweepTerminalWorkspaces();
+ expect(second.archived).toBe(0);
+ expect((await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, eligible.executionWorkspaceId)))[0]?.status).toBe("archived");
+
+ await issueService(db).update(eligible.sourceIssueId, {
+ status: "todo",
+ actorUserId: "local-board",
+ });
+ const reopenedWorkspace = await db
+ .select({ status: executionWorkspaces.status })
+ .from(executionWorkspaces)
+ .where(eq(executionWorkspaces.id, eligible.executionWorkspaceId))
+ .then((rows) => rows[0]);
+ const reopenActivities = await db
+ .select({ action: activityLog.action })
+ .from(activityLog)
+ .where(eq(activityLog.entityId, eligible.executionWorkspaceId));
+ expect(reopenedWorkspace?.status).toBe("archived");
+ expect(reopenActivities).toContainEqual({ action: "execution_workspace.source_issue_reopened" });
+ }, 20_000);
+
it("allows archiving shared workspace sessions with warnings even when issues are still open", async () => {
const companyId = randomUUID();
const projectId = randomUUID();
@@ -315,6 +824,7 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
expect(readiness).toMatchObject({
workspaceId: executionWorkspaceId,
+ deliveryState: "unknown",
state: "ready_with_warnings",
isSharedWorkspace: true,
isProjectPrimaryWorkspace: true,
@@ -2882,6 +3392,7 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
expect(readiness).toMatchObject({
workspaceId: executionWorkspaceId,
+ deliveryState: "unmerged",
state: "ready_with_warnings",
isSharedWorkspace: false,
isProjectPrimaryWorkspace: false,
diff --git a/server/src/__tests__/merged-pr-confirmation-sweep.test.ts b/server/src/__tests__/merged-pr-confirmation-sweep.test.ts
new file mode 100644
index 0000000000..bfafff6ca3
--- /dev/null
+++ b/server/src/__tests__/merged-pr-confirmation-sweep.test.ts
@@ -0,0 +1,319 @@
+import { randomUUID } from "node:crypto";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { inArray } from "drizzle-orm";
+import {
+ activityLog,
+ agents,
+ companies,
+ createDb,
+ goals,
+ issueThreadInteractions,
+ issues,
+} from "@paperclipai/db";
+import {
+ extractGitHubPullRequestReferences,
+ getMergeConfirmationPullRequestReferences,
+ issueThreadInteractionService,
+} from "../services/issue-thread-interactions.js";
+import {
+ PULL_REQUEST_CACHE_MAX_ENTRIES,
+ setBoundedPullRequestCacheEntry,
+} from "../services/github-pull-request-merge.js";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+
+describe("merged pull-request confirmation extraction", () => {
+ it("bounds shared pull-request state caches", () => {
+ const cache = new Map<string, number>();
+ for (let index = 0; index <= PULL_REQUEST_CACHE_MAX_ENTRIES; index += 1) {
+ setBoundedPullRequestCacheEntry(cache, `pr-${index}`, index);
+ }
+
+ expect(cache.size).toBe(PULL_REQUEST_CACHE_MAX_ENTRIES);
+ expect(cache.has("pr-0")).toBe(false);
+ expect(cache.get(`pr-${PULL_REQUEST_CACHE_MAX_ENTRIES}`)).toBe(PULL_REQUEST_CACHE_MAX_ENTRIES);
+ });
+
+ it("extracts and deduplicates full GitHub URLs and owner/repo#N shorthand", () => {
+ expect(extractGitHubPullRequestReferences([
+ "Merge https://github.com/PaperclipAI/paperclip/pull/39.",
+ "Also paperclipai/paperclip#40 and PAPERCLIPAI/paperclip#40.",
+ ])).toEqual([
+ { host: "github.com", owner: "PaperclipAI", repo: "paperclip", number: 39 },
+ { host: "github.com", owner: "paperclipai", repo: "paperclip", number: 40 },
+ ]);
+ });
+
+ it("requires merge intent and excludes document and tool-action confirmations", () => {
+ const base = {
+ kind: "request_confirmation",
+ title: "Merge PaperclipAI/paperclip#39?",
+ summary: null,
+ payload: { version: 1, prompt: "Merge the pull request?" },
+ } as const;
+ expect(getMergeConfirmationPullRequestReferences(base)).toHaveLength(1);
+ expect(getMergeConfirmationPullRequestReferences({
+ ...base,
+ title: "Approve the release?",
+ })).toEqual([]);
+ expect(getMergeConfirmationPullRequestReferences({
+ ...base,
+ payload: { ...base.payload, target: { type: "issue_document", key: "plan" } },
+ })).toEqual([]);
+ expect(getMergeConfirmationPullRequestReferences({
+ ...base,
+ payload: { ...base.payload, toolAction: { actionRequestId: "action-1" } },
+ })).toEqual([]);
+ });
+
+ it("finds references in merge-confirmation body and custom target fields", () => {
+ expect(getMergeConfirmationPullRequestReferences({
+ kind: "request_confirmation",
+ title: "Merge the linked PR?",
+ summary: "The checks are green.",
+ payload: {
+ version: 1,
+ prompt: "Merge the linked pull request?",
+ detailsMarkdown: "Primary: paperclipai/paperclip#39",
+ target: {
+ type: "custom",
+ key: "github-pr-40",
+ href: "https://github.com/paperclipai/paperclip/pull/40",
+ },
+ },
+ })).toEqual([
+ { host: "github.com", owner: "paperclipai", repo: "paperclip", number: 39 },
+ { host: "github.com", owner: "paperclipai", repo: "paperclip", number: 40 },
+ ]);
+ });
+
+ it("denies governed actions mentioned in details or custom target metadata", () => {
+ const base = {
+ kind: "request_confirmation",
+ title: "Merge the linked PR?",
+ summary: "The checks are green.",
+ } as const;
+ expect(getMergeConfirmationPullRequestReferences({
+ ...base,
+ payload: {
+ version: 1,
+ prompt: "Merge the linked pull request?",
+ detailsMarkdown: "Deploy to production after paperclipai/paperclip#39 merges.",
+ },
+ })).toEqual([]);
+ expect(getMergeConfirmationPullRequestReferences({
+ ...base,
+ payload: {
+ version: 1,
+ prompt: "Merge the linked pull request?",
+ target: {
+ type: "custom",
+ label: "Release to production",
+ href: "https://github.com/paperclipai/paperclip/pull/39",
+ },
+ },
+ })).toEqual([]);
+ });
+
+ it("fails closed when a merge confirmation includes an additional action clause", () => {
+ expect(getMergeConfirmationPullRequestReferences({
+ kind: "request_confirmation",
+ title: "Merge the linked PR?",
+ summary: null,
+ payload: {
+ version: 1,
+ prompt: "Merge paperclipai/paperclip#39?",
+ detailsMarkdown: "Erase all customer records after paperclipai/paperclip#39 merges.",
+ },
+ })).toEqual([]);
+ });
+});
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+describeEmbeddedPostgres.sequential("merged pull-request confirmation sweep", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-merged-pr-confirmations-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(activityLog);
+ await db.delete(issueThreadInteractions);
+ await db.delete(issues);
+ await db.delete(goals);
+ await db.delete(agents);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ it("accepts only all-merged cards, wakes the assignee, and audits the system actor", async () => {
+ const companyId = randomUUID();
+ const goalId = randomUUID();
+ const issueId = randomUUID();
+ const agentId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: "MPR",
+ requireBoardApprovalForNewAgents: false,
+ });
+ await db.insert(goals).values({
+ id: goalId,
+ companyId,
+ title: "Ship safely",
+ level: "task",
+ status: "active",
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Coder",
+ role: "engineer",
+ status: "active",
+ adapterType: "codex_local",
+ adapterConfig: {},
+ runtimeConfig: {},
+ permissions: {},
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ goalId,
+ title: "Land the changes",
+ status: "in_review",
+ priority: "medium",
+ assigneeAgentId: agentId,
+ });
+
+ const interactionIds = {
+ merged: randomUUID(),
+ boardOrAgents: randomUUID(),
+ someOpen: randomUUID(),
+ zeroRefs: randomUUID(),
+ toolAction: randomUUID(),
+ extraAction: randomUUID(),
+ };
+ const common = {
+ companyId,
+ issueId,
+ kind: "request_confirmation",
+ status: "pending",
+ continuationPolicy: "wake_assignee_on_accept",
+ requestedResolverPolicy: "board_only",
+ effectiveResolverPolicy: "board_only",
+ } as const;
+ await db.insert(issueThreadInteractions).values([
+ {
+ ...common,
+ id: interactionIds.merged,
+ title: "Merge https://github.com/paperclipai/paperclip/pull/39?",
+ payload: { version: 1, prompt: "Merge the PR?" },
+ },
+ {
+ ...common,
+ id: interactionIds.boardOrAgents,
+ title: "Merge paperclipai/paperclip#39?",
+ requestedResolverPolicy: "board_or_agents",
+ effectiveResolverPolicy: "board_or_agents",
+ payload: { version: 1, prompt: "Merge the PR?" },
+ },
+ {
+ ...common,
+ id: interactionIds.someOpen,
+ title: "Ready to merge paperclipai/paperclip#39 and paperclipai/paperclip#41?",
+ payload: { version: 1, prompt: "Ready to merge both PRs?" },
+ },
+ {
+ ...common,
+ id: interactionIds.zeroRefs,
+ title: "Merge the pending PR?",
+ payload: { version: 1, prompt: "Merge it?" },
+ },
+ {
+ ...common,
+ id: interactionIds.toolAction,
+ title: "Merge paperclipai/paperclip#42?",
+ payload: {
+ version: 1,
+ prompt: "Merge the PR?",
+ toolAction: { version: 1, actionRequestId: "action-1" },
+ },
+ },
+ {
+ ...common,
+ id: interactionIds.extraAction,
+ title: "Merge the linked PR?",
+ payload: {
+ version: 1,
+ prompt: "Merge paperclipai/paperclip#39?",
+ detailsMarkdown: "Erase all customer records after paperclipai/paperclip#39 merges.",
+ },
+ },
+ ]);
+
+ const wakeup = vi.fn(async () => ({ id: "wake-1" }));
+ const resolvePullRequestState = vi.fn(async (_resolvedCompanyId: string, reference: { number: number }) =>
+ reference.number === 41 ? "open" as const : "merged" as const
+ );
+ const service = issueThreadInteractionService(db, {
+ wakeup,
+ resolvePullRequestState,
+ });
+
+ await expect(service.sweepMergedPullRequestConfirmations()).resolves.toEqual({
+ checked: 6,
+ candidates: 3,
+ accepted: 2,
+ woken: 2,
+ });
+
+ const stored = await db
+ .select({ id: issueThreadInteractions.id, status: issueThreadInteractions.status })
+ .from(issueThreadInteractions)
+ .where(inArray(issueThreadInteractions.id, Object.values(interactionIds)));
+ expect(new Map(stored.map((row) => [row.id, row.status]))).toEqual(new Map([
+ [interactionIds.merged, "accepted"],
+ [interactionIds.boardOrAgents, "accepted"],
+ [interactionIds.someOpen, "pending"],
+ [interactionIds.zeroRefs, "pending"],
+ [interactionIds.toolAction, "pending"],
+ [interactionIds.extraAction, "pending"],
+ ]));
+ expect(wakeup).toHaveBeenCalledWith(agentId, expect.objectContaining({
+ requestedByActorType: "system",
+ requestedByActorId: "system:pr-merged",
+ idempotencyKey: `interaction:${interactionIds.merged}:accepted`,
+ }));
+ expect(wakeup).toHaveBeenCalledWith(agentId, expect.objectContaining({
+ requestedByActorType: "system",
+ requestedByActorId: "system:pr-merged",
+ idempotencyKey: `interaction:${interactionIds.boardOrAgents}:accepted`,
+ }));
+ expect(resolvePullRequestState).toHaveBeenCalledTimes(2);
+
+ const audit = await db.select().from(activityLog);
+ expect(audit).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ actorType: "system",
+ actorId: "system:pr-merged",
+ action: "issue.thread_interaction_accepted",
+ entityId: issueId,
+ details: expect.objectContaining({
+ interactionId: interactionIds.merged,
+ resolutionActorKind: "system",
+ pullRequests: ["paperclipai/paperclip#39"],
+ }),
+ }),
+ ]));
+ });
+});
diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts
index 790e0caab8..7c9eaf4fb0 100644
--- a/server/src/__tests__/server-startup-feedback-export.test.ts
+++ b/server/src/__tests__/server-startup-feedback-export.test.ts
@@ -17,6 +17,8 @@ const {
deriveAuthTrustedOriginsMock,
environmentCustomImagesServiceMock,
environmentCustomImagesServiceFactoryMock,
+ executionWorkspaceServiceFactoryMock,
+ executionWorkspaceServiceMock,
externalObjectsServiceMock,
externalObjectsServiceFactoryMock,
feedbackExportServiceMock,
@@ -73,12 +75,31 @@ const {
const heartbeatServiceFactoryMock = vi.fn(() => heartbeatServiceMock);
const issueThreadInteractionServiceMock = {
sweepSupersededPendingRequestConfirmations: vi.fn(async () => ({ expired: 0 })),
+ sweepMergedPullRequestConfirmations: vi.fn(async () => ({
+ checked: 0,
+ candidates: 0,
+ accepted: 0,
+ woken: 0,
+ })),
};
const issueThreadInteractionServiceFactoryMock = vi.fn(() => issueThreadInteractionServiceMock);
const environmentCustomImagesServiceMock = {
cleanupExpiredSetupSessions: vi.fn(async () => ({ scanned: 0, timedOut: 0, failed: 0 })),
};
const environmentCustomImagesServiceFactoryMock = vi.fn(() => environmentCustomImagesServiceMock);
+ const executionWorkspaceServiceMock = {
+ sweepTerminalWorkspaces: vi.fn(async () => ({
+ checked: 0,
+ eligible: 0,
+ archived: 0,
+ cleanupFailed: 0,
+ skippedActiveRun: 0,
+ skippedNonTerminalTree: 0,
+ skippedUndelivered: 0,
+ skippedRace: 0,
+ })),
+ };
+ const executionWorkspaceServiceFactoryMock = vi.fn(() => executionWorkspaceServiceMock);
const externalObjectsServiceMock = {
refreshDueObjectsForActiveCompanies: vi.fn(async () => ({ companies: 0, checked: 0, refreshed: 0 })),
};
@@ -110,6 +131,8 @@ const {
deriveAuthTrustedOriginsMock,
environmentCustomImagesServiceMock,
environmentCustomImagesServiceFactoryMock,
+ executionWorkspaceServiceFactoryMock,
+ executionWorkspaceServiceMock,
externalObjectsServiceMock,
externalObjectsServiceFactoryMock,
feedbackExportServiceMock,
@@ -241,6 +264,7 @@ vi.mock("../services/index.js", () => ({
bootstrapExecutionPolicyFromEnv: vi.fn(async () => null),
applyManagedEnvironments: vi.fn(async () => null),
environmentCustomImageService: environmentCustomImagesServiceFactoryMock,
+ executionWorkspaceService: executionWorkspaceServiceFactoryMock,
externalObjectService: externalObjectsServiceFactoryMock,
heartbeatService: heartbeatServiceFactoryMock,
issueThreadInteractionService: issueThreadInteractionServiceFactoryMock,
@@ -467,6 +491,8 @@ describe("startServer feedback export wiring", () => {
expect(heartbeatServiceMock.tickTimers).not.toHaveBeenCalled();
expect(externalObjectsServiceMock.refreshDueObjectsForActiveCompanies).toHaveBeenCalledTimes(1);
+ expect(issueThreadInteractionServiceMock.sweepMergedPullRequestConfirmations).toHaveBeenCalledTimes(1);
+ expect(executionWorkspaceServiceMock.sweepTerminalWorkspaces).toHaveBeenCalledTimes(1);
expect(routineServiceMock.tickScheduledTriggers).toHaveBeenCalledTimes(1);
expect(environmentCustomImagesServiceMock.cleanupExpiredSetupSessions).toHaveBeenCalledTimes(2);
} finally {
diff --git a/server/src/__tests__/workspace-runtime.test.ts b/server/src/__tests__/workspace-runtime.test.ts
index 447583fff7..d9726d495a 100644
--- a/server/src/__tests__/workspace-runtime.test.ts
+++ b/server/src/__tests__/workspace-runtime.test.ts
@@ -3256,6 +3256,70 @@ describe("realizeExecutionWorkspace", () => {
});
});
+ it("keeps a runtime-created branch when its tip changes after guarded worktree removal", async () => {
+ const repoRoot = await createTempRepo();
+ const workspace = await realizeExecutionWorkspace({
+ base: {
+ baseCwd: repoRoot,
+ source: "project_primary",
+ projectId: "project-1",
+ workspaceId: "workspace-1",
+ repoUrl: null,
+ repoRef: "HEAD",
+ },
+ config: {
+ workspaceStrategy: {
+ type: "git_worktree",
+ branchTemplate: "{{issue.identifier}}-{{slug}}",
+ },
+ },
+ issue: {
+ id: "issue-1",
+ identifier: "PAP-450",
+ title: "Race branch cleanup",
+ },
+ agent: {
+ id: "agent-1",
+ name: "Codex Coder",
+ companyId: "company-1",
+ },
+ });
+ const expectedHeadSha = await readGit(workspace.cwd, ["rev-parse", "HEAD"]);
+ await fs.writeFile(path.join(repoRoot, "raced.txt"), "new work\n", "utf8");
+ await runGit(repoRoot, ["add", "raced.txt"]);
+ await runGit(repoRoot, ["commit", "-m", "Raced branch update"]);
+ const racedHeadSha = await readGit(repoRoot, ["rev-parse", "HEAD"]);
+
+ const cleanup = await cleanupExecutionWorkspaceArtifacts({
+ workspace: {
+ id: "execution-workspace-1",
+ cwd: workspace.cwd,
+ providerType: "git_worktree",
+ providerRef: workspace.worktreePath,
+ branchName: workspace.branchName,
+ repoUrl: workspace.repoUrl,
+ baseRef: workspace.repoRef,
+ projectId: workspace.projectId,
+ projectWorkspaceId: workspace.workspaceId,
+ sourceIssueId: "issue-1",
+ metadata: { createdByRuntime: true },
+ },
+ projectWorkspace: {
+ cwd: repoRoot,
+ cleanupCommand: null,
+ },
+ expectedBranchHeadSha: expectedHeadSha,
+ beforeBranchDelete: async () => {
+ await runGit(repoRoot, ["update-ref", `refs/heads/${workspace.branchName}`, racedHeadSha]);
+ },
+ });
+
+ expect(cleanup.cleaned).toBe(true);
+ expect(cleanup.warnings).toHaveLength(1);
+ expect(cleanup.warnings[0]).toContain(`Skipped deleting branch "${workspace.branchName}"`);
+ expect(await readGit(repoRoot, ["rev-parse", `refs/heads/${workspace.branchName}`])).toBe(racedHeadSha);
+ });
+
it("keeps an unmerged runtime-created branch and warns instead of force deleting it", async () => {
const repoRoot = await createTempRepo();
diff --git a/server/src/index.ts b/server/src/index.ts
index 6f7f24c658..4f0c782fef 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -50,6 +50,7 @@ import {
decisionService,
decisionRetentionService,
externalObjectService,
+ executionWorkspaceService,
heartbeatService,
issueThreadInteractionService,
issueService,
@@ -969,6 +970,36 @@ export async function startServer(): Promise<StartedServer> {
const routines = routineService(db as any, { pluginWorkerManager });
const statusCards = statusCardService(db as any);
const issues = issueService(db as any);
+ const mergedPullRequestConfirmations = issueThreadInteractionService(db as any, {
+ wakeup: heartbeat.wakeup,
+ });
+ const terminalWorkspaces = executionWorkspaceService(db as any);
+ const scheduleMergedPullRequestConfirmationSweep = () => {
+ if (heartbeatSchedulerStopped) return;
+ trackHeartbeatSchedulerWork(mergedPullRequestConfirmations
+ .sweepMergedPullRequestConfirmations()
+ .then((result) => {
+ if (result.accepted > 0) {
+ logger.info(result, "accepted merge confirmations for merged pull requests");
+ }
+ })
+ .catch((err) => {
+ logger.error({ err }, "merged pull-request confirmation sweep failed");
+ }));
+ };
+ const scheduleTerminalWorkspaceSweep = () => {
+ if (heartbeatSchedulerStopped) return;
+ trackHeartbeatSchedulerWork(terminalWorkspaces
+ .sweepTerminalWorkspaces()
+ .then((result) => {
+ if (result.archived > 0 || result.cleanupFailed > 0) {
+ logger.info(result, "terminal issue workspace reaper changed workspace state");
+ }
+ })
+ .catch((err) => {
+ logger.error({ err }, "terminal issue workspace reaper failed");
+ }));
+ };
const tools = toolAccessService(db as any, {
deploymentMode: config.deploymentMode,
deploymentExposure: config.deploymentExposure,
@@ -1154,6 +1185,10 @@ export async function startServer(): Promise<StartedServer> {
if (heartbeatSchedulerStopped) return;
scheduleExternalObjectRefreshSweep(new Date());
+ if (heartbeatSchedulerStopped) return;
+ scheduleMergedPullRequestConfirmationSweep();
+ scheduleTerminalWorkspaceSweep();
+
if (heartbeatSchedulerStopped) return;
trackHeartbeatSchedulerWork(routines
.tickScheduledTriggers(new Date())
diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts
index 1dc8714f03..036ea45b22 100644
--- a/server/src/routes/issues.ts
+++ b/server/src/routes/issues.ts
@@ -5028,6 +5028,7 @@ export function issueRoutes(
strategyType: workspace.strategyType,
name: workspace.name,
status: workspace.status,
+ deliveryState: workspace.deliveryState,
cwd: workspace.cwd,
repoUrl: workspace.repoUrl,
baseRef: workspace.baseRef,
diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts
index bf94eab29d..e9bb355a0c 100644
--- a/server/src/services/execution-workspaces.ts
+++ b/server/src/services/execution-workspaces.ts
@@ -5,9 +5,19 @@ import path from "node:path";
import { promisify } from "node:util";
import { and, asc, desc, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
-import { executionWorkspaces, heartbeatRuns, issueComments, issues, projects, projectWorkspaces, workspaceRuntimeServices } from "@paperclipai/db";
+import {
+ executionWorkspaces,
+ heartbeatRuns,
+ issueComments,
+ issueWorkProducts,
+ issues,
+ projects,
+ projectWorkspaces,
+ workspaceRuntimeServices,
+} from "@paperclipai/db";
import type {
ExecutionWorkspace,
+ ExecutionWorkspaceDeliveryState,
ExecutionWorkspaceSummary,
ExecutionWorkspaceCloseAction,
ExecutionWorkspaceCloseGitReadiness,
@@ -32,6 +42,14 @@ import {
} from "./issue-execution-policy.js";
import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js";
import { issueRecoveryActionService } from "./issue-recovery-actions.js";
+import { logActivity } from "./activity-log.js";
+import {
+ createPullRequestMergeDetailsResolver,
+ extractGitHubPullRequestReferences,
+ setBoundedPullRequestCacheEntry,
+ type GitHubPullRequestReference,
+ type PullRequestMergeDetailsResolver,
+} from "./github-pull-request-merge.js";
import { visibleIssueCondition } from "./issue-visibility.js";
import { readProjectWorkspaceRuntimeConfig } from "./project-workspace-runtime-config.js";
import {
@@ -47,6 +65,44 @@ 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 const ISSUE_TERMINAL_WORKSPACE_CLEANUP_REASON = "issue_terminal";
+
+export type ExecutionWorkspaceServiceOptions = {
+ resolvePullRequestDetails?: PullRequestMergeDetailsResolver;
+ now?: () => Date;
+ beforeTerminalWorkspaceCleanup?: (workspace: ExecutionWorkspaceRow) => Promise<void>;
+};
+
+function parseGitHubRepository(repoUrl: string | null) {
+ if (!repoUrl) return null;
+ const match = /^(?:https?:\/\/(?:www\.)?github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/i.exec(repoUrl.trim());
+ if (!match) return null;
+ return { owner: match[1]!.toLowerCase(), repo: match[2]!.toLowerCase() };
+}
+
+function pullRequestMatchesWorkspaceRepository(
+ reference: GitHubPullRequestReference,
+ workspace: Pick<ExecutionWorkspaceRow, "repoUrl">,
+) {
+ const repository = parseGitHubRepository(workspace.repoUrl);
+ return Boolean(
+ repository
+ && repository.owner === reference.owner.toLowerCase()
+ && repository.repo === reference.repo.toLowerCase(),
+ );
+}
+
+export function deriveExecutionWorkspaceDeliveryState(input: {
+ sourceIssueTerminal: boolean;
+ mergedPullRequest: boolean;
+ pullRequestStateUnknown: boolean;
+ isMergedIntoBase: boolean | null;
+}): ExecutionWorkspaceDeliveryState {
+ if (input.sourceIssueTerminal && input.mergedPullRequest) return "merged_via_pr";
+ if (input.isMergedIntoBase === true) return "merged_by_ancestry";
+ if (input.isMergedIntoBase === false && !input.pullRequestStateUnknown) return "unmerged";
+ return "unknown";
+}
export type ExecutionWorkspaceBranchReconcileMode = "forward" | "override" | "quarantine_restore";
@@ -798,6 +854,7 @@ function toRuntimeService(
function toExecutionWorkspace(
row: ExecutionWorkspaceRow,
runtimeServices: WorkspaceRuntimeService[] = [],
+ deliveryState: ExecutionWorkspaceDeliveryState = "unknown",
): ExecutionWorkspace {
return {
id: row.id,
@@ -809,6 +866,7 @@ function toExecutionWorkspace(
strategyType: row.strategyType as ExecutionWorkspace["strategyType"],
name: row.name,
status: row.status as ExecutionWorkspace["status"],
+ deliveryState,
cwd: row.cwd ?? null,
repoUrl: row.repoUrl ?? null,
baseRef: row.baseRef ?? null,
@@ -992,8 +1050,299 @@ type WorkspaceOverviewIssueRow = WorkspaceOverviewLinkedIssue & {
executionWorkspaceId: string;
};
-export function executionWorkspaceService(db: Db) {
+export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServiceOptions = {}) {
const recoveryActionsSvc = issueRecoveryActionService(db);
+ const resolvePullRequestDetails = opts.resolvePullRequestDetails ?? createPullRequestMergeDetailsResolver(db);
+ const now = opts.now ?? (() => new Date());
+ const pullRequestStateCache = new Map<
+ string,
+ {
+ details: Awaited<ReturnType<PullRequestMergeDetailsResolver>>;
+ checkedAtMs: number;
+ }
+ >();
+ const pullRequestStateCacheTtlMs = 5 * 60 * 1000;
+
+ async function listWorkspaceIssueTree(workspace: Pick<ExecutionWorkspaceRow, "companyId" | "sourceIssueId">) {
+ if (!workspace.sourceIssueId) return [];
+ return db
+ .select({
+ id: issues.id,
+ status: issues.status,
+ })
+ .from(issues)
+ .where(and(
+ eq(issues.companyId, workspace.companyId),
+ sql<boolean>`
+ ${issues.id} IN (
+ WITH RECURSIVE issue_tree(id) AS (
+ SELECT ${issues.id}
+ FROM ${issues}
+ WHERE ${issues.companyId} = ${workspace.companyId}
+ AND ${issues.id} = ${workspace.sourceIssueId}
+ UNION ALL
+ SELECT child.id
+ FROM ${issues} child
+ JOIN issue_tree parent ON child.parent_id = parent.id
+ WHERE child.company_id = ${workspace.companyId}
+ )
+ SELECT id FROM issue_tree
+ )
+ `,
+ ));
+ }
+
+ async function listDeliveryPullRequestProducts(
+ workspace: Pick<ExecutionWorkspaceRow, "companyId" | "sourceIssueId">,
+ ) {
+ if (!workspace.sourceIssueId) return [];
+
+ return db
+ .select({
+ id: issueWorkProducts.id,
+ url: issueWorkProducts.url,
+ externalId: issueWorkProducts.externalId,
+ title: issueWorkProducts.title,
+ summary: issueWorkProducts.summary,
+ metadata: issueWorkProducts.metadata,
+ })
+ .from(issueWorkProducts)
+ .where(and(
+ eq(issueWorkProducts.companyId, workspace.companyId),
+ eq(issueWorkProducts.type, "pull_request"),
+ eq(issueWorkProducts.issueId, workspace.sourceIssueId),
+ ))
+ .orderBy(desc(issueWorkProducts.updatedAt))
+ .limit(100);
+ }
+
+ async function assessDelivery(
+ workspace: ExecutionWorkspaceRow,
+ git: ExecutionWorkspaceCloseGitReadiness | null,
+ ) {
+ const issueTree = await listWorkspaceIssueTree(workspace);
+ const sourceIssue = issueTree.find((issue) => issue.id === workspace.sourceIssueId) ?? null;
+ const sourceIssueTerminal = Boolean(sourceIssue && TERMINAL_ISSUE_STATUSES.has(sourceIssue.status));
+ const subtreeTerminal = Boolean(sourceIssue && issueTree.every((issue) => TERMINAL_ISSUE_STATUSES.has(issue.status)));
+ let mergedPullRequest = false;
+ let pullRequestStateUnknown = false;
+ const workspaceHeadSha = git?.repoRoot && git.workspacePath
+ ? await runGit(["rev-parse", "HEAD"], git.workspacePath)
+ .then((result) => result.stdout.trim() || null)
+ .catch(() => null)
+ : null;
+
+ if (sourceIssueTerminal) {
+ const products = await listDeliveryPullRequestProducts(workspace);
+ for (const product of products) {
+ const references = extractGitHubPullRequestReferences([
+ product.url,
+ product.externalId,
+ product.title,
+ product.summary,
+ product.metadata ? JSON.stringify(product.metadata) : null,
+ ]);
+ if (references.length === 0) continue;
+ for (const reference of references) {
+ if (!pullRequestMatchesWorkspaceRepository(reference, workspace)) continue;
+ const key = `${workspace.companyId}:${reference.owner.toLowerCase()}/${reference.repo.toLowerCase()}#${reference.number}`;
+ const cached = pullRequestStateCache.get(key);
+ let details;
+ if (cached && now().getTime() - cached.checkedAtMs < pullRequestStateCacheTtlMs) {
+ details = cached.details;
+ } else {
+ details = await resolvePullRequestDetails(workspace.companyId, reference);
+ setBoundedPullRequestCacheEntry(
+ pullRequestStateCache,
+ key,
+ { details, checkedAtMs: now().getTime() },
+ );
+ }
+ if (
+ details.state === "merged"
+ && details.headRef === workspace.branchName
+ && details.headSha === workspaceHeadSha
+ && workspaceHeadSha !== null
+ ) {
+ mergedPullRequest = true;
+ break;
+ }
+ if (
+ details.state === "unknown"
+ || (details.state === "merged" && (!details.headRef || !details.headSha || !workspaceHeadSha))
+ ) {
+ pullRequestStateUnknown = true;
+ }
+ }
+ if (mergedPullRequest) break;
+ }
+ }
+
+ return {
+ deliveryState: deriveExecutionWorkspaceDeliveryState({
+ sourceIssueTerminal,
+ mergedPullRequest,
+ pullRequestStateUnknown,
+ isMergedIntoBase: git?.isMergedIntoBase ?? null,
+ }),
+ sourceIssueTerminal,
+ subtreeTerminal,
+ workspaceDirty: Boolean(git?.hasDirtyTrackedFiles || git?.hasUntrackedFiles),
+ workspaceHeadSha,
+ };
+ }
+
+ async function assertTerminalCleanupGitStateUnchanged(
+ workspace: ExecutionWorkspaceRow,
+ expectedHeadSha: string | null,
+ ) {
+ if (workspace.providerType !== "git_worktree") return;
+ const workspacePath = readNullableString(workspace.providerRef) ?? readNullableString(workspace.cwd);
+ if (!workspacePath || !expectedHeadSha) {
+ throw new Error("Refusing terminal workspace cleanup because the expected git HEAD is unknown");
+ }
+
+ const [current, currentHeadSha, currentBranchName] = await Promise.all([
+ inspectGitCloseReadiness(toExecutionWorkspace(workspace)),
+ readGitStdout(["rev-parse", "HEAD"], workspacePath).catch(() => null),
+ readGitStdout(["symbolic-ref", "--quiet", "--short", "HEAD"], workspacePath).catch(() => null),
+ ]);
+ if (
+ !current.git?.repoRoot
+ || current.git.hasDirtyTrackedFiles
+ || current.git.hasUntrackedFiles
+ || currentHeadSha !== expectedHeadSha
+ || (workspace.branchName && currentBranchName !== workspace.branchName)
+ ) {
+ throw new Error("Refusing terminal workspace cleanup because the git worktree changed after delivery was verified");
+ }
+ }
+
+ async function hydrateWorkspace(row: ExecutionWorkspaceRow, runtimeServices: WorkspaceRuntimeService[] = []) {
+ const workspace = toExecutionWorkspace(row, runtimeServices);
+ const { git } = await inspectGitCloseReadiness(workspace);
+ const assessment = await assessDelivery(row, git);
+ return toExecutionWorkspace(row, runtimeServices, assessment.deliveryState);
+ }
+
+ async function workspaceHasActiveRun(workspace: Pick<ExecutionWorkspaceRow, "id" | "companyId" | "sourceIssueId">) {
+ const linkedIssues = await db
+ .select({
+ checkoutRunId: issues.checkoutRunId,
+ executionRunId: issues.executionRunId,
+ })
+ .from(issues)
+ .where(and(
+ eq(issues.companyId, workspace.companyId),
+ or(
+ eq(issues.executionWorkspaceId, workspace.id),
+ ...(workspace.sourceIssueId ? [eq(issues.id, workspace.sourceIssueId)] : []),
+ ),
+ ));
+ const runIds = [...new Set(linkedIssues.flatMap((issue) => [
+ issue.checkoutRunId,
+ issue.executionRunId,
+ ]).filter((runId): runId is string => Boolean(runId)))];
+ if (runIds.length === 0) return false;
+ const active = await db
+ .select({ id: heartbeatRuns.id })
+ .from(heartbeatRuns)
+ .where(and(
+ eq(heartbeatRuns.companyId, workspace.companyId),
+ inArray(heartbeatRuns.id, runIds),
+ inArray(heartbeatRuns.status, ["queued", "running"]),
+ ))
+ .limit(1);
+ return active.length > 0;
+ }
+
+ async function cleanupTerminalWorkspace(workspace: ExecutionWorkspaceRow, expectedHeadSha: string | null) {
+ const [
+ {
+ acquireGitWorktreeCleanupLock,
+ cleanupExecutionWorkspaceArtifacts,
+ stopRuntimeServicesForExecutionWorkspace,
+ },
+ { workspaceOperationService },
+ ] = await Promise.all([
+ import("./workspace-runtime.js"),
+ import("./workspace-operations.js"),
+ ]);
+ const [projectWorkspace, projectPolicy] = await Promise.all([
+ workspace.projectWorkspaceId
+ ? db
+ .select({ cwd: projectWorkspaces.cwd, cleanupCommand: projectWorkspaces.cleanupCommand })
+ .from(projectWorkspaces)
+ .where(and(
+ eq(projectWorkspaces.companyId, workspace.companyId),
+ eq(projectWorkspaces.id, workspace.projectWorkspaceId),
+ ))
+ .then((rows) => rows[0] ?? null)
+ : null,
+ db
+ .select({ executionWorkspacePolicy: projects.executionWorkspacePolicy })
+ .from(projects)
+ .where(and(eq(projects.companyId, workspace.companyId), eq(projects.id, workspace.projectId)))
+ .then((rows) => parseProjectExecutionWorkspacePolicy(rows[0]?.executionWorkspacePolicy)),
+ ]);
+ const config = readExecutionWorkspaceConfig((workspace.metadata as Record<string, unknown> | null) ?? null);
+
+ const cleanupLock = workspace.providerType === "git_worktree" && (workspace.providerRef ?? workspace.cwd)
+ ? await acquireGitWorktreeCleanupLock(workspace.providerRef ?? workspace.cwd!)
+ : null;
+ try {
+ await assertTerminalCleanupGitStateUnchanged(workspace, expectedHeadSha);
+ await opts.beforeTerminalWorkspaceCleanup?.(workspace);
+ await assertTerminalCleanupGitStateUnchanged(workspace, expectedHeadSha);
+ await stopRuntimeServicesForExecutionWorkspace({
+ db,
+ executionWorkspaceId: workspace.id,
+ workspaceCwd: workspace.cwd,
+ });
+ const cleanup = await cleanupExecutionWorkspaceArtifacts({
+ workspace,
+ projectWorkspace,
+ cleanupCommand: config?.cleanupCommand ?? null,
+ teardownCommand: config?.teardownCommand ?? projectPolicy?.workspaceStrategy?.teardownCommand ?? null,
+ recorder: workspaceOperationService(db).createRecorder({
+ companyId: workspace.companyId,
+ executionWorkspaceId: workspace.id,
+ }),
+ assertSafeToCleanup: () => assertTerminalCleanupGitStateUnchanged(workspace, expectedHeadSha),
+ beforeBranchDelete: () => cleanupLock?.releaseBranchRefLock() ?? Promise.resolve(),
+ expectedBranchHeadSha: expectedHeadSha,
+ // Git index, HEAD, and branch-ref locks prevent a clean HEAD change
+ // from crossing final validation. The branch lock is released only
+ // after non-forced worktree removal, then deletion is anchored to the
+ // verified HEAD so a raced ref update fails closed.
+ runCleanupCommands: false,
+ forceWorktreeRemoval: false,
+ });
+ if (cleanup.cleaned && workspace.mode === "shared_workspace") {
+ await db
+ .update(issues)
+ .set({ executionWorkspaceId: null, updatedAt: now() })
+ .where(and(
+ eq(issues.companyId, workspace.companyId),
+ eq(issues.executionWorkspaceId, workspace.id),
+ ));
+ }
+ const cleanupReason = [ISSUE_TERMINAL_WORKSPACE_CLEANUP_REASON, ...cleanup.warnings].join(" | ");
+ if (!cleanup.cleaned || cleanup.warnings.length > 0) {
+ await db
+ .update(executionWorkspaces)
+ .set({
+ ...(cleanup.cleaned ? {} : { status: "cleanup_failed" }),
+ cleanupReason,
+ updatedAt: now(),
+ })
+ .where(eq(executionWorkspaces.id, workspace.id));
+ }
+ return cleanup;
+ } finally {
+ await cleanupLock?.release();
+ }
+ }
function buildListConditions(
companyId: string,
@@ -1260,12 +1609,12 @@ export function executionWorkspaceService(db: Db) {
.where(and(...conditions))
.orderBy(desc(executionWorkspaces.lastUsedAt), desc(executionWorkspaces.createdAt));
const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, companyId, rows);
- return rows.map((row) =>
- toExecutionWorkspace(
+ return Promise.all(rows.map((row) =>
+ hydrateWorkspace(
row,
(runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService),
),
- );
+ ));
},
listSummaries: async (companyId: string, filters?: {
@@ -1419,7 +1768,7 @@ export function executionWorkspaceService(db: Db) {
.then((rows) => rows[0] ?? null);
if (!row) return null;
const runtimeServicesByWorkspaceId = await loadEffectiveRuntimeServicesByExecutionWorkspace(db, row.companyId, [row]);
- return toExecutionWorkspace(
+ return hydrateWorkspace(
row,
(runtimeServicesByWorkspaceId.get(row.id) ?? []).map(toRuntimeService),
);
@@ -1493,6 +1842,7 @@ export function executionWorkspaceService(db: Db) {
const executionWorkspace = toExecutionWorkspace(workspace, runtimeServices);
const config = readExecutionWorkspaceConfig((workspace.metadata as Record<string, unknown> | null) ?? null);
const { git, warnings: gitWarnings } = await inspectGitCloseReadiness(executionWorkspace);
+ const { deliveryState } = await assessDelivery(workspace, git);
const warnings = [...gitWarnings];
const blockingReasons: string[] = [];
const isSharedWorkspace = executionWorkspace.mode === "shared_workspace";
@@ -1550,7 +1900,12 @@ export function executionWorkspaceService(db: Db) {
: `The workspace has ${git.untrackedEntryCount} untracked files.`,
);
}
- if (git?.aheadCount && git.aheadCount > 0 && git.isMergedIntoBase === false) {
+ if (
+ git?.aheadCount
+ && git.aheadCount > 0
+ && git.isMergedIntoBase === false
+ && deliveryState !== "merged_via_pr"
+ ) {
warnings.push(
git.aheadCount === 1
? `This workspace is 1 commit ahead of ${git.baseRef ?? "the base ref"} and is not merged.`
@@ -1663,6 +2018,7 @@ export function executionWorkspaceService(db: Db) {
return {
workspaceId: workspace.id,
+ deliveryState,
state,
blockingReasons,
warnings,
@@ -1676,6 +2032,154 @@ export function executionWorkspaceService(db: Db) {
};
},
+ sweepTerminalWorkspaces: async (limit = 50) => {
+ const candidates = await db
+ .select()
+ .from(executionWorkspaces)
+ .where(and(
+ inArray(executionWorkspaces.status, ["active", "idle", "in_review"]),
+ isNull(executionWorkspaces.closedAt),
+ sql<boolean>`${executionWorkspaces.sourceIssueId} IS NOT NULL`,
+ ))
+ .orderBy(asc(executionWorkspaces.updatedAt), asc(executionWorkspaces.id))
+ .limit(limit);
+ const result = {
+ checked: candidates.length,
+ eligible: 0,
+ archived: 0,
+ cleanupFailed: 0,
+ skippedActiveRun: 0,
+ skippedNonTerminalTree: 0,
+ skippedUndelivered: 0,
+ skippedRace: 0,
+ };
+
+ for (const workspace of candidates) {
+ const executionWorkspace = toExecutionWorkspace(workspace);
+ const { git } = await inspectGitCloseReadiness(executionWorkspace);
+ const assessment = await assessDelivery(workspace, git);
+ if (!assessment.sourceIssueTerminal || !assessment.subtreeTerminal) {
+ result.skippedNonTerminalTree += 1;
+ continue;
+ }
+ if (assessment.workspaceDirty) {
+ result.skippedUndelivered += 1;
+ continue;
+ }
+ if (
+ assessment.deliveryState !== "merged_via_pr"
+ && assessment.deliveryState !== "merged_by_ancestry"
+ ) {
+ result.skippedUndelivered += 1;
+ continue;
+ }
+ if (await workspaceHasActiveRun(workspace)) {
+ result.skippedActiveRun += 1;
+ continue;
+ }
+ result.eligible += 1;
+ const closedAt = now();
+ const archived = await db
+ .update(executionWorkspaces)
+ .set({
+ status: "archived",
+ closedAt,
+ cleanupEligibleAt: workspace.cleanupEligibleAt ?? closedAt,
+ cleanupReason: ISSUE_TERMINAL_WORKSPACE_CLEANUP_REASON,
+ updatedAt: closedAt,
+ })
+ .where(and(
+ eq(executionWorkspaces.id, workspace.id),
+ eq(executionWorkspaces.companyId, workspace.companyId),
+ inArray(executionWorkspaces.status, ["active", "idle", "in_review"]),
+ isNull(executionWorkspaces.closedAt),
+ sql<boolean>`EXISTS (
+ SELECT 1
+ FROM ${issues} source_issue
+ WHERE source_issue.company_id = ${workspace.companyId}
+ AND source_issue.id = ${workspace.sourceIssueId}
+ AND source_issue.status IN ('done', 'cancelled')
+ )`,
+ sql<boolean>`NOT EXISTS (
+ SELECT 1
+ FROM ${issues} linked_issue
+ JOIN ${heartbeatRuns} live_run
+ ON live_run.id = linked_issue.checkout_run_id
+ OR live_run.id = linked_issue.execution_run_id
+ WHERE linked_issue.company_id = ${workspace.companyId}
+ AND (
+ linked_issue.execution_workspace_id = ${workspace.id}
+ OR linked_issue.id = ${workspace.sourceIssueId}
+ )
+ AND live_run.company_id = ${workspace.companyId}
+ AND live_run.status IN ('queued', 'running')
+ )`,
+ sql<boolean>`NOT EXISTS (
+ WITH RECURSIVE issue_tree(id, status) AS (
+ SELECT root.id, root.status
+ FROM ${issues} root
+ WHERE root.company_id = ${workspace.companyId}
+ AND root.id = ${workspace.sourceIssueId}
+ UNION ALL
+ SELECT child.id, child.status
+ FROM ${issues} child
+ JOIN issue_tree parent ON child.parent_id = parent.id
+ WHERE child.company_id = ${workspace.companyId}
+ )
+ SELECT 1 FROM issue_tree WHERE status NOT IN ('done', 'cancelled')
+ )`,
+ ))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (!archived) {
+ result.skippedRace += 1;
+ continue;
+ }
+
+ await logActivity(db, {
+ companyId: archived.companyId,
+ actorType: "system",
+ actorId: "workspace_terminality_reaper",
+ action: "execution_workspace.issue_terminal_archived",
+ entityType: "execution_workspace",
+ entityId: archived.id,
+ details: {
+ sourceIssueId: archived.sourceIssueId,
+ deliveryState: assessment.deliveryState,
+ cleanupEligibleAt: archived.cleanupEligibleAt?.toISOString() ?? null,
+ cleanupReason: ISSUE_TERMINAL_WORKSPACE_CLEANUP_REASON,
+ },
+ });
+
+ try {
+ const cleanup = await cleanupTerminalWorkspace(archived, assessment.workspaceHeadSha);
+ if (!cleanup.cleaned) result.cleanupFailed += 1;
+ else result.archived += 1;
+ } catch (error) {
+ result.cleanupFailed += 1;
+ const failure = error instanceof Error ? error.message : String(error);
+ await db
+ .update(executionWorkspaces)
+ .set({
+ status: "cleanup_failed",
+ cleanupReason: `${ISSUE_TERMINAL_WORKSPACE_CLEANUP_REASON} | ${failure}`,
+ updatedAt: now(),
+ })
+ .where(eq(executionWorkspaces.id, archived.id));
+ await logActivity(db, {
+ companyId: archived.companyId,
+ actorType: "system",
+ actorId: "workspace_terminality_reaper",
+ action: "execution_workspace.issue_terminal_cleanup_failed",
+ entityType: "execution_workspace",
+ entityId: archived.id,
+ details: { sourceIssueId: archived.sourceIssueId, failure },
+ });
+ }
+ }
+ return result;
+ },
+
create: async (data: typeof executionWorkspaces.$inferInsert) => {
const row = await db
.insert(executionWorkspaces)
diff --git a/server/src/services/github-external-object-provider.ts b/server/src/services/github-external-object-provider.ts
index 6664b6c7cf..734a093447 100644
--- a/server/src/services/github-external-object-provider.ts
+++ b/server/src/services/github-external-object-provider.ts
@@ -195,6 +195,7 @@ function pullRequestSnapshot(identity: GitHubObjectIdentity, body: Record<string
const merged = (asBoolean(body.merged) ?? false) || Boolean(asString(body.merged_at));
const authorLogin = asNestedString(body, "user", "login");
const headRef = asNestedString(body, "head", "ref");
+ const headSha = asNestedString(body, "head", "sha");
const baseRef = asNestedString(body, "base", "ref");
const reviewDecision = asString(body.review_decision);
@@ -252,6 +253,7 @@ function pullRequestSnapshot(identity: GitHubObjectIdentity, body: Record<string
draft,
...(authorLogin ? { authorLogin } : {}),
...(headRef ? { headRef } : {}),
+ ...(headSha ? { headSha } : {}),
...(baseRef ? { baseRef } : {}),
...(reviewDecision ? { reviewDecision } : {}),
},
diff --git a/server/src/services/github-pull-request-merge.ts b/server/src/services/github-pull-request-merge.ts
new file mode 100644
index 0000000000..a0a8f87260
--- /dev/null
+++ b/server/src/services/github-pull-request-merge.ts
@@ -0,0 +1,111 @@
+import type { Db } from "@paperclipai/db";
+import { createGitHubExternalObjectProvider } from "./github-external-object-provider.js";
+
+export type GitHubPullRequestReference = {
+ host: "github.com";
+ owner: string;
+ repo: string;
+ number: number;
+};
+
+export type PullRequestMergeState = "merged" | "open" | "unknown";
+
+export type PullRequestMergeDetails = {
+ state: PullRequestMergeState;
+ headRef: string | null;
+ headSha: string | null;
+};
+
+export type PullRequestMergeStateResolver = (
+ companyId: string,
+ reference: GitHubPullRequestReference,
+) => Promise<PullRequestMergeState>;
+
+export type PullRequestMergeDetailsResolver = (
+ companyId: string,
+ reference: GitHubPullRequestReference,
+) => Promise<PullRequestMergeDetails>;
+
+export const PULL_REQUEST_CACHE_MAX_ENTRIES = 1_000;
+
+export function setBoundedPullRequestCacheEntry<T>(
+ cache: Map<string, T>,
+ key: string,
+ value: T,
+) {
+ cache.delete(key);
+ while (cache.size >= PULL_REQUEST_CACHE_MAX_ENTRIES) {
+ const oldestKey = cache.keys().next().value;
+ if (oldestKey === undefined) break;
+ cache.delete(oldestKey);
+ }
+ cache.set(key, value);
+}
+
+const GITHUB_PULL_REQUEST_URL_PATTERN = /https:\/\/(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/([1-9][0-9]*)/gi;
+const GITHUB_PULL_REQUEST_SHORTHAND_PATTERN = /(^|[^A-Za-z0-9_.-])([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([1-9][0-9]*)\b/g;
+
+function addPullRequestReference(
+ references: Map<string, GitHubPullRequestReference>,
+ owner: string,
+ repo: string,
+ rawNumber: string,
+) {
+ const number = Number(rawNumber);
+ if (!Number.isSafeInteger(number) || number <= 0) return;
+ const reference = { host: "github.com", owner, repo, number } as const;
+ const key = `${owner.toLowerCase()}/${repo.toLowerCase()}#${number}`;
+ if (!references.has(key)) references.set(key, reference);
+}
+
+export function extractGitHubPullRequestReferences(values: readonly unknown[]) {
+ const references = new Map<string, GitHubPullRequestReference>();
+ for (const value of values) {
+ if (typeof value !== "string" || value.length === 0) continue;
+ GITHUB_PULL_REQUEST_URL_PATTERN.lastIndex = 0;
+ for (const match of value.matchAll(GITHUB_PULL_REQUEST_URL_PATTERN)) {
+ addPullRequestReference(references, match[1]!, match[2]!, match[3]!);
+ }
+ GITHUB_PULL_REQUEST_SHORTHAND_PATTERN.lastIndex = 0;
+ for (const match of value.matchAll(GITHUB_PULL_REQUEST_SHORTHAND_PATTERN)) {
+ addPullRequestReference(references, match[2]!, match[3]!, match[4]!);
+ }
+ }
+ return [...references.values()];
+}
+
+function readRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
+
+export function createPullRequestMergeDetailsResolver(db: Db): PullRequestMergeDetailsResolver {
+ const resolver = createGitHubExternalObjectProvider(db).resolvers
+ .find((candidate) => candidate.objectType === "pull_request") ?? null;
+
+ return async (companyId, reference) => {
+ if (!resolver) return { state: "unknown", headRef: null, headSha: null };
+ const result = await resolver.resolve({
+ companyId,
+ object: {
+ externalId: `${reference.owner}/${reference.repo}#pull/${reference.number}`,
+ sanitizedCanonicalUrl: `https://github.com/${reference.owner}/${reference.repo}/pull/${reference.number}`,
+ } as never,
+ });
+ if (!result.ok) return { state: "unknown", headRef: null, headSha: null };
+ const data = readRecord(result.snapshot.data);
+ return {
+ state: result.snapshot.statusKey === "merged" || data?.merged === true
+ ? "merged"
+ : "open",
+ headRef: typeof data?.headRef === "string" ? data.headRef : null,
+ headSha: typeof data?.headSha === "string" ? data.headSha : null,
+ };
+ };
+}
+
+export function createPullRequestMergeStateResolver(db: Db): PullRequestMergeStateResolver {
+ const resolveDetails = createPullRequestMergeDetailsResolver(db);
+ return async (companyId, reference) => (await resolveDetails(companyId, reference)).state;
+}
diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts
index ff7f001d2c..b9af68eea2 100644
--- a/server/src/services/issue-thread-interactions.ts
+++ b/server/src/services/issue-thread-interactions.ts
@@ -57,15 +57,151 @@ import {
import { z } from "zod";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { getTelemetryClient } from "../telemetry.js";
+import { logActivity } from "./activity-log.js";
import { evaluateAgentInvokabilityFromDb } from "./agent-invokability.js";
import { issueService, runWorkspaceIsFinalized } from "./issues.js";
+import {
+ createPullRequestMergeStateResolver,
+ extractGitHubPullRequestReferences,
+ setBoundedPullRequestCacheEntry,
+ type GitHubPullRequestReference,
+ type PullRequestMergeState,
+} from "./github-pull-request-merge.js";
+
+export { extractGitHubPullRequestReferences } from "./github-pull-request-merge.js";
+export type { GitHubPullRequestReference } from "./github-pull-request-merge.js";
type InteractionActor = {
agentId?: string | null;
runId?: string | null;
userId?: string | null;
+ systemId?: string | null;
+ resolutionDetails?: Record<string, unknown>;
+};
+
+type InteractionWakeup = (agentId: string, options: {
+ source: "automation";
+ triggerDetail: "system";
+ reason: "issue_commented";
+ payload: Record<string, unknown>;
+ idempotencyKey: string;
+ requestedByActorType: "system";
+ requestedByActorId: string;
+ contextSnapshot: Record<string, unknown>;
+}) => Promise<unknown>;
+
+export type IssueThreadInteractionServiceOptions = {
+ resolvePullRequestState?: (
+ companyId: string,
+ reference: GitHubPullRequestReference,
+ ) => Promise<PullRequestMergeState>;
+ wakeup?: InteractionWakeup;
+ pullRequestCacheTtlMs?: number;
+ now?: () => Date;
};
+const GITHUB_PULL_REQUEST_URL_PATTERN = /https:\/\/(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/([1-9][0-9]*)/gi;
+const GITHUB_PULL_REQUEST_SHORTHAND_PATTERN = /(^|[^A-Za-z0-9_.-])([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([1-9][0-9]*)\b/g;
+const MERGE_CONFIRMATION_INTENT_PATTERN = /^(?:please\s+)?(?:confirm(?:\s+that)?\s+.{0,80}\s+)?(?:merge|merged)\b|\bready\s+to\s+merge\b/i;
+const MERGE_CONFIRMATION_ALLOWED_WORDS = new Set([
+ "all",
+ "and",
+ "approved",
+ "are",
+ "both",
+ "checks",
+ "ci",
+ "confirm",
+ "github",
+ "green",
+ "is",
+ "it",
+ "link",
+ "linked",
+ "links",
+ "merge",
+ "merged",
+ "merging",
+ "passed",
+ "passing",
+ "please",
+ "pr",
+ "primary",
+ "prs",
+ "pull",
+ "ready",
+ "reference",
+ "references",
+ "request",
+ "requests",
+ "review",
+ "secondary",
+ "tests",
+ "that",
+ "the",
+ "these",
+ "this",
+ "to",
+ "url",
+]);
+
+function isMergeConfirmationOnlyText(value: string) {
+ GITHUB_PULL_REQUEST_URL_PATTERN.lastIndex = 0;
+ const withoutUrls = value.replace(GITHUB_PULL_REQUEST_URL_PATTERN, " pr_reference ");
+ GITHUB_PULL_REQUEST_SHORTHAND_PATTERN.lastIndex = 0;
+ const withoutReferences = withoutUrls.replace(
+ GITHUB_PULL_REQUEST_SHORTHAND_PATTERN,
+ (_match, prefix: string) => `${prefix} pr_reference `,
+ );
+ const normalized = withoutReferences
+ .replace(/\b(?:github-)?pr-[1-9][0-9]*\b/gi, " pr_reference ")
+ .replace(/[`*_\[\]{}()<>:;,.!?"'=+&|\\/-]+/g, " ")
+ .trim()
+ .toLowerCase();
+ if (!normalized) return true;
+ return normalized
+ .split(/\s+/)
+ .every((word) => word === "pr_reference" || MERGE_CONFIRMATION_ALLOWED_WORDS.has(word));
+}
+
+export function getMergeConfirmationPullRequestReferences(
+ row: Pick<IssueThreadInteractionRow, "kind" | "title" | "summary" | "payload">,
+) {
+ if (row.kind !== "request_confirmation") return [];
+ const payload = row.payload && typeof row.payload === "object" && !Array.isArray(row.payload)
+ ? row.payload as unknown as Record<string, unknown>
+ : null;
+ if (!payload || payload.toolAction !== undefined) return [];
+
+ const target = payload.target && typeof payload.target === "object" && !Array.isArray(payload.target)
+ ? payload.target as Record<string, unknown>
+ : null;
+ // Plan/document confirmations and governed action cards must never inherit
+ // merge-confirmation authority merely because their prose links to a PR.
+ if (target?.type === "issue_document") return [];
+
+ const intentValues = [row.title, row.summary, payload.prompt, payload.acceptLabel];
+ const intentText = intentValues.filter((value): value is string => typeof value === "string").join("\n");
+ if (!MERGE_CONFIRMATION_INTENT_PATTERN.test(intentText)) return [];
+
+ const trustedTextValues = [
+ ...intentValues,
+ payload.detailsMarkdown,
+ target?.key,
+ target?.label,
+ target?.href,
+ ];
+ // System acceptance is intentionally fail-closed: after replacing recognized
+ // PR references, every trusted field must contain merge-only vocabulary. This
+ // prevents an otherwise valid merge prompt from smuggling an additional action
+ // that a governed-action denylist did not anticipate.
+ if (!trustedTextValues.every((value) => typeof value !== "string" || isMergeConfirmationOnlyText(value))) {
+ return [];
+ }
+
+ return extractGitHubPullRequestReferences(trustedTextValues);
+}
+
const ISSUE_THREAD_INTERACTION_IDEMPOTENCY_CONSTRAINT =
"issue_thread_interactions_company_issue_idempotency_uq";
@@ -1020,7 +1156,37 @@ async function expireStaleRequestConfirmationTarget(db: Db | any, args: {
return expired;
}
-export function issueThreadInteractionService(db: Db) {
+export function issueThreadInteractionService(db: Db, opts: IssueThreadInteractionServiceOptions = {}) {
+ const pullRequestStateCache = new Map<string, { state: PullRequestMergeState; checkedAt: number }>();
+ const now = opts.now ?? (() => new Date());
+ const defaultPullRequestStateResolver = opts.resolvePullRequestState
+ ? null
+ : createPullRequestMergeStateResolver(db);
+
+ async function resolvePullRequestState(
+ companyId: string,
+ reference: GitHubPullRequestReference,
+ ): Promise<PullRequestMergeState> {
+ if (opts.resolvePullRequestState) return opts.resolvePullRequestState(companyId, reference);
+ return defaultPullRequestStateResolver?.(companyId, reference) ?? "unknown";
+ }
+
+ async function resolvePullRequestStates(
+ entries: Array<{ key: string; companyId: string; reference: GitHubPullRequestReference }>,
+ ) {
+ const states = new Map<string, PullRequestMergeState>();
+ const pending = entries.slice();
+ const workerCount = Math.min(8, pending.length);
+ await Promise.all(Array.from({ length: workerCount }, async () => {
+ while (pending.length > 0) {
+ const entry = pending.shift();
+ if (!entry) return;
+ const state = await resolvePullRequestState(entry.companyId, entry.reference);
+ states.set(entry.key, state);
+ }
+ }));
+ return states;
+ }
async function getIdempotentInteraction(args: {
issueId: string;
companyId: string;
@@ -1200,6 +1366,28 @@ export function issueThreadInteractionService(db: Db) {
await touchIssue(tx, args.issue.id);
}
+ if (args.actor.systemId) {
+ await logActivity(tx as unknown as Db, {
+ companyId: args.issue.companyId,
+ actorType: "system",
+ actorId: args.actor.systemId,
+ agentId: null,
+ runId: null,
+ action: "issue.thread_interaction_accepted",
+ entityType: "issue",
+ entityId: args.issue.id,
+ details: {
+ interactionId: args.current.id,
+ interactionKind: args.current.kind,
+ interactionStatus: "accepted",
+ resolutionActorKind: "system",
+ requestedResolverPolicy: args.current.requestedResolverPolicy,
+ effectiveResolverPolicy: args.current.effectiveResolverPolicy,
+ ...(args.actor.resolutionDetails ?? {}),
+ },
+ });
+ }
+
return {
interaction: hydrateInteraction(updated),
continuationIssue,
@@ -1262,6 +1450,135 @@ export function issueThreadInteractionService(db: Db) {
return {
getForIssue,
+ sweepMergedPullRequestConfirmations: async () => {
+ const rows = await db
+ .select({
+ interaction: issueThreadInteractions,
+ issue: {
+ id: issues.id,
+ companyId: issues.companyId,
+ projectId: issues.projectId,
+ goalId: issues.goalId,
+ status: issues.status,
+ assigneeAgentId: issues.assigneeAgentId,
+ },
+ })
+ .from(issueThreadInteractions)
+ .innerJoin(issues, eq(issueThreadInteractions.issueId, issues.id))
+ .where(and(
+ eq(issueThreadInteractions.kind, "request_confirmation"),
+ eq(issueThreadInteractions.status, "pending"),
+ ));
+
+ const candidates = rows.flatMap((row) => {
+ const references = getMergeConfirmationPullRequestReferences(row.interaction);
+ return references.length > 0 ? [{ ...row, references }] : [];
+ });
+ if (candidates.length === 0) {
+ return { checked: rows.length, candidates: 0, accepted: 0, woken: 0 };
+ }
+
+ const candidateIds = candidates.map(({ interaction }) => interaction.id);
+ const linkedToolActions = await db
+ .select({ interactionId: toolActionRequests.interactionId })
+ .from(toolActionRequests)
+ .where(inArray(toolActionRequests.interactionId, candidateIds));
+ const toolActionInteractionIds = new Set(linkedToolActions
+ .map((row) => row.interactionId)
+ .filter((value): value is string => Boolean(value)));
+ const eligible = candidates.filter(({ interaction }) => !toolActionInteractionIds.has(interaction.id));
+
+ const checkedAt = now().getTime();
+ const cacheTtlMs = opts.pullRequestCacheTtlMs ?? 5 * 60 * 1000;
+ const uniqueReferences = new Map<string, {
+ key: string;
+ companyId: string;
+ reference: GitHubPullRequestReference;
+ }>();
+ for (const candidate of eligible) {
+ for (const reference of candidate.references) {
+ const key = `${candidate.issue.companyId}:${reference.owner.toLowerCase()}/${reference.repo.toLowerCase()}#${reference.number}`;
+ const cached = pullRequestStateCache.get(key);
+ if (cached && checkedAt - cached.checkedAt < cacheTtlMs) continue;
+ uniqueReferences.set(key, { key, companyId: candidate.issue.companyId, reference });
+ }
+ }
+
+ const refreshedStates = await resolvePullRequestStates([...uniqueReferences.values()]);
+ for (const [key, state] of refreshedStates) {
+ setBoundedPullRequestCacheEntry(pullRequestStateCache, key, { state, checkedAt });
+ }
+
+ let accepted = 0;
+ let woken = 0;
+ for (const candidate of eligible) {
+ const allMerged = candidate.references.every((reference) => {
+ const key = `${candidate.issue.companyId}:${reference.owner.toLowerCase()}/${reference.repo.toLowerCase()}#${reference.number}`;
+ return pullRequestStateCache.get(key)?.state === "merged";
+ });
+ if (!allMerged) continue;
+
+ let resolved: Awaited<ReturnType<typeof acceptRequestConfirmation>>;
+ try {
+ resolved = await acceptRequestConfirmation({
+ issue: candidate.issue,
+ current: candidate.interaction,
+ input: {},
+ actor: {
+ systemId: "system:pr-merged",
+ resolutionDetails: {
+ source: "merged_pull_request_sweep",
+ pullRequests: candidate.references.map((reference) =>
+ `${reference.owner}/${reference.repo}#${reference.number}`
+ ),
+ },
+ },
+ });
+ } catch (error) {
+ if (error && typeof error === "object" && "status" in error && error.status === 409) continue;
+ throw error;
+ }
+ if (resolved.interaction.status !== "accepted") continue;
+ accepted += 1;
+
+ const wakeIssue = resolved.continuationIssue ?? candidate.issue;
+ const shouldWake = resolved.interaction.continuationPolicy === "wake_assignee"
+ || resolved.interaction.continuationPolicy === "wake_assignee_on_accept";
+ if (!opts.wakeup || !shouldWake || !wakeIssue.assigneeAgentId || isTerminalIssueStatus(wakeIssue.status)) {
+ continue;
+ }
+ await opts.wakeup(wakeIssue.assigneeAgentId, {
+ source: "automation",
+ triggerDetail: "system",
+ reason: "issue_commented",
+ payload: {
+ issueId: wakeIssue.id,
+ interactionId: resolved.interaction.id,
+ interactionKind: resolved.interaction.kind,
+ interactionStatus: resolved.interaction.status,
+ sourceCommentId: resolved.interaction.sourceCommentId ?? null,
+ sourceRunId: resolved.interaction.sourceRunId ?? null,
+ mutation: "interaction",
+ resolutionSource: "merged_pull_request_sweep",
+ },
+ idempotencyKey: `interaction:${resolved.interaction.id}:accepted`,
+ requestedByActorType: "system",
+ requestedByActorId: "system:pr-merged",
+ contextSnapshot: {
+ issueId: wakeIssue.id,
+ taskId: wakeIssue.id,
+ interactionId: resolved.interaction.id,
+ interactionKind: resolved.interaction.kind,
+ interactionStatus: resolved.interaction.status,
+ wakeReason: "issue_commented",
+ source: "merged_pull_request_sweep",
+ },
+ });
+ woken += 1;
+ }
+
+ return { checked: rows.length, candidates: eligible.length, accepted, woken };
+ },
listForIssue: async (issueId: string) => {
const rows = await db
.select()
diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts
index 917a941a58..6257bd2fea 100644
--- a/server/src/services/issues.ts
+++ b/server/src/services/issues.ts
@@ -7651,6 +7651,38 @@ export function issueService(db: Db) {
.then((rows: Array<typeof issues.$inferSelect>) => rows[0] ?? null);
if (!updated) return null;
if (existing.status !== updated.status) {
+ if (
+ (existing.status === "done" || existing.status === "cancelled")
+ && updated.status !== "done"
+ && updated.status !== "cancelled"
+ ) {
+ const terminalWorkspaces = await tx
+ .select({ id: executionWorkspaces.id })
+ .from(executionWorkspaces)
+ .where(and(
+ eq(executionWorkspaces.companyId, updated.companyId),
+ eq(executionWorkspaces.sourceIssueId, updated.id),
+ eq(executionWorkspaces.status, "archived"),
+ like(executionWorkspaces.cleanupReason, "issue_terminal%"),
+ ));
+ for (const workspace of terminalWorkspaces) {
+ await logActivity(tx as unknown as Db, {
+ companyId: updated.companyId,
+ actorType: actorAgentId ? "agent" : actorUserId ? "user" : "system",
+ actorId: actorAgentId ?? actorUserId ?? "issue_service",
+ agentId: actorAgentId ?? null,
+ action: "execution_workspace.source_issue_reopened",
+ entityType: "execution_workspace",
+ entityId: workspace.id,
+ details: {
+ sourceIssueId: updated.id,
+ previousIssueStatus: existing.status,
+ nextIssueStatus: updated.status,
+ workspaceAction: "left_archived",
+ },
+ });
+ }
+ }
if (updated.status === "done" || updated.status === "cancelled") {
await finalizeSummarySlotsForTerminalIssue(tx, updated);
// Every terminal transition funnels through here, including direct
diff --git a/server/src/services/workspace-runtime.ts b/server/src/services/workspace-runtime.ts
index b7e8ea5388..81a18e5be2 100644
--- a/server/src/services/workspace-runtime.ts
+++ b/server/src/services/workspace-runtime.ts
@@ -2,6 +2,7 @@ import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
import fs from "node:fs/promises";
import net from "node:net";
+import os from "node:os";
import { createHash, randomUUID } from "node:crypto";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
@@ -3218,6 +3219,106 @@ export async function ensurePersistedExecutionWorkspaceAvailable(input: {
};
}
+export async function acquireGitWorktreeCleanupLock(worktreePath: string) {
+ const branchRef = await runGit(["symbolic-ref", "--quiet", "HEAD"], worktreePath).catch(() => null);
+ const rawLocks = await Promise.all([
+ runGit(["rev-parse", "--git-path", "index.lock"], worktreePath)
+ .then((lockPath) => ({ kind: "index" as const, lockPath })),
+ runGit(["rev-parse", "--git-path", "HEAD.lock"], worktreePath)
+ .then((lockPath) => ({ kind: "head" as const, lockPath })),
+ ...(branchRef
+ ? [runGit(["rev-parse", "--git-path", `${branchRef}.lock`], worktreePath)
+ .then((lockPath) => ({ kind: "branch" as const, lockPath }))]
+ : []),
+ ]);
+ const locks = [...new Map(rawLocks.map(({ kind, lockPath }) => {
+ const resolvedLockPath = path.isAbsolute(lockPath)
+ ? lockPath
+ : path.resolve(worktreePath, lockPath);
+ return [resolvedLockPath, { kind, lockPath: resolvedLockPath }];
+ })).values()];
+ const lockHandles: Array<{
+ handle: fs.FileHandle;
+ kind: "index" | "head" | "branch";
+ lockPath: string;
+ }> = [];
+
+ async function releaseLocks(kind?: "branch") {
+ for (let index = lockHandles.length - 1; index >= 0; index -= 1) {
+ const lock = lockHandles[index];
+ if (!lock || (kind && lock.kind !== kind)) continue;
+ lockHandles.splice(index, 1);
+ await lock.handle.close().catch(() => {});
+ await fs.rm(lock.lockPath, { force: true }).catch(() => {});
+ }
+ }
+
+ try {
+ for (const lock of locks) {
+ lockHandles.push({
+ ...lock,
+ handle: await fs.open(lock.lockPath, "wx", 0o600),
+ });
+ }
+ } catch (error) {
+ await releaseLocks();
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") {
+ throw new Error("git worktree cleanup lock is already held");
+ }
+ throw error;
+ }
+
+ return {
+ // Branch deletion must acquire this native ref lock itself. Callers release
+ // only that lock after the guarded worktree removal, while retaining the
+ // index and HEAD locks until the whole cleanup transaction finishes.
+ releaseBranchRefLock: () => releaseLocks("branch"),
+ release: () => releaseLocks(),
+ };
+}
+
+async function deleteGitBranchAtVerifiedTip(input: {
+ repoRoot: string;
+ branchName: string;
+ expectedHeadSha: string;
+ recorder?: WorkspaceOperationRecorder | null;
+ metadata: Record<string, unknown>;
+}) {
+ const commonDirRaw = await runGit(["rev-parse", "--git-common-dir"], input.repoRoot);
+ const commonDir = path.isAbsolute(commonDirRaw)
+ ? commonDirRaw
+ : path.resolve(input.repoRoot, commonDirRaw);
+ const detachedGitDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-branch-delete-"));
+ const detachedWorktree = `${detachedGitDir}-worktree`;
+
+ try {
+ // `git branch -d` refuses branches checked out by another worktree and its
+ // ref transaction fails if the tip changes concurrently. A detached HEAD
+ // at the delivered SHA additionally lets squash/cross-branch deliveries
+ // delete only the exact branch history that was verified before cleanup.
+ await Promise.all([
+ fs.writeFile(path.join(detachedGitDir, "HEAD"), `${input.expectedHeadSha}\n`, "utf8"),
+ fs.writeFile(path.join(detachedGitDir, "commondir"), `${commonDir}\n`, "utf8"),
+ ]);
+ await recordGitOperation(input.recorder, {
+ phase: "worktree_cleanup",
+ args: [
+ `--git-dir=${detachedGitDir}`,
+ `--work-tree=${detachedWorktree}`,
+ "branch",
+ "-d",
+ input.branchName,
+ ],
+ cwd: input.repoRoot,
+ metadata: input.metadata,
+ successMessage: `Deleted branch ${input.branchName}\n`,
+ failureLabel: `git branch -d ${input.branchName}`,
+ });
+ } finally {
+ await fs.rm(detachedGitDir, { recursive: true, force: true }).catch(() => {});
+ }
+}
+
export async function cleanupExecutionWorkspaceArtifacts(input: {
workspace: {
id: string;
@@ -3239,6 +3340,11 @@ export async function cleanupExecutionWorkspaceArtifacts(input: {
cleanupCommand?: string | null;
teardownCommand?: string | null;
recorder?: WorkspaceOperationRecorder | null;
+ assertSafeToCleanup?: (() => Promise<void>) | null;
+ beforeBranchDelete?: (() => Promise<void>) | null;
+ expectedBranchHeadSha?: string | null;
+ runCleanupCommands?: boolean;
+ forceWorktreeRemoval?: boolean;
}) {
const warnings: string[] = [];
const workspacePath = input.workspace.providerRef ?? input.workspace.cwd;
@@ -3252,6 +3358,9 @@ export async function cleanupExecutionWorkspaceArtifacts(input: {
workspace: input.workspace,
projectWorkspaceCwd: input.projectWorkspace?.cwd ?? null,
});
+ // Callers can require the workspace to match an assessed snapshot before
+ // cleanup begins. Destructive paths recheck immediately before removal.
+ await input.assertSafeToCleanup?.();
let worktreeInstancePointer: WorktreeInstancePointer | null = null;
let expectedWorktreeInstanceId: string | null = null;
if (input.workspace.providerType === "git_worktree" && workspacePath) {
@@ -3264,13 +3373,15 @@ export async function cleanupExecutionWorkspaceArtifacts(input: {
}
}
const createdByRuntime = input.workspace.metadata?.createdByRuntime === true;
- const cleanupCommands = [
- input.cleanupCommand ?? null,
- input.projectWorkspace?.cleanupCommand ?? null,
- input.teardownCommand ?? null,
- ]
- .map((value) => asString(value, "").trim())
- .filter(Boolean);
+ const cleanupCommands = input.runCleanupCommands === false
+ ? []
+ : [
+ input.cleanupCommand ?? null,
+ input.projectWorkspace?.cleanupCommand ?? null,
+ input.teardownCommand ?? null,
+ ]
+ .map((value) => asString(value, "").trim())
+ .filter(Boolean);
for (const command of cleanupCommands) {
try {
@@ -3324,9 +3435,15 @@ export async function cleanupExecutionWorkspaceArtifacts(input: {
warnings.push(`Could not resolve git repo root for "${workspacePath}".`);
} else {
try {
+ await input.assertSafeToCleanup?.();
await recordGitOperation(input.recorder, {
phase: "worktree_cleanup",
- args: ["worktree", "remove", "--force", workspacePath],
+ args: [
+ "worktree",
+ "remove",
+ ...(input.forceWorktreeRemoval === false ? [] : ["--force"]),
+ workspacePath,
+ ],
cwd: repoRoot,
metadata: {
workspaceId: input.workspace.id,
@@ -3347,19 +3464,31 @@ export async function cleanupExecutionWorkspaceArtifacts(input: {
warnings.push(`Could not resolve git repo root to delete branch "${input.workspace.branchName}".`);
} else {
try {
- await recordGitOperation(input.recorder, {
- phase: "worktree_cleanup",
- args: ["branch", "-d", input.workspace.branchName],
- cwd: repoRoot,
- metadata: {
- workspaceId: input.workspace.id,
- workspacePath,
+ await input.beforeBranchDelete?.();
+ const metadata = {
+ workspaceId: input.workspace.id,
+ workspacePath,
+ branchName: input.workspace.branchName,
+ cleanupAction: "branch_delete",
+ };
+ if (input.expectedBranchHeadSha) {
+ await deleteGitBranchAtVerifiedTip({
+ repoRoot,
branchName: input.workspace.branchName,
- cleanupAction: "branch_delete",
- },
- successMessage: `Deleted branch ${input.workspace.branchName}\n`,
- failureLabel: `git branch -d ${input.workspace.branchName}`,
- });
+ expectedHeadSha: input.expectedBranchHeadSha,
+ recorder: input.recorder,
+ metadata,
+ });
+ } else {
+ await recordGitOperation(input.recorder, {
+ phase: "worktree_cleanup",
+ args: ["branch", "-d", input.workspace.branchName],
+ cwd: repoRoot,
+ metadata,
+ successMessage: `Deleted branch ${input.workspace.branchName}\n`,
+ failureLabel: `git branch -d ${input.workspace.branchName}`,
+ });
+ }
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
warnings.push(`Skipped deleting branch "${input.workspace.branchName}": ${message}`);
@@ -3378,6 +3507,7 @@ export async function cleanupExecutionWorkspaceArtifacts(input: {
if (containsProjectWorkspace) {
warnings.push(`Refusing to remove path "${workspacePath}" because it contains the project workspace.`);
} else {
+ await input.assertSafeToCleanup?.();
await fs.rm(resolvedWorkspacePath, { recursive: true, force: true });
if (input.recorder) {
await input.recorder.recordOperation({
diff --git a/ui/src/components/IssueProperties.test.tsx b/ui/src/components/IssueProperties.test.tsx
index 5f5fe6d541..0bb9cbc22e 100644
--- a/ui/src/components/IssueProperties.test.tsx
+++ b/ui/src/components/IssueProperties.test.tsx
@@ -292,6 +292,7 @@ function createExecutionWorkspace(overrides: Partial<ExecutionWorkspace> = {}):
strategyType: "git_worktree",
name: "PAP-1 workspace",
status: "active",
+ deliveryState: "unknown",
cwd: "/tmp/paperclip/PAP-1",
repoUrl: null,
baseRef: "master",
diff --git a/ui/src/components/IssueWorkspaceCard.test.tsx b/ui/src/components/IssueWorkspaceCard.test.tsx
index 35ee6c0bf1..cdd46c3898 100644
--- a/ui/src/components/IssueWorkspaceCard.test.tsx
+++ b/ui/src/components/IssueWorkspaceCard.test.tsx
@@ -49,6 +49,7 @@ function createExecutionWorkspace(overrides: Partial<ExecutionWorkspace> = {}):
strategyType: "git_worktree",
name: "Issue sandbox",
status: "active",
+ deliveryState: "unknown",
cwd: "/tmp/issue-sandbox",
repoUrl: null,
baseRef: null,
diff --git a/ui/src/components/RoutineRunVariablesDialog.test.tsx b/ui/src/components/RoutineRunVariablesDialog.test.tsx
index b9c337e107..d6e7b747c1 100644
--- a/ui/src/components/RoutineRunVariablesDialog.test.tsx
+++ b/ui/src/components/RoutineRunVariablesDialog.test.tsx
@@ -147,6 +147,7 @@ function createExecutionWorkspace(): ExecutionWorkspace {
strategyType: "git_worktree",
name: "PAP-1634",
status: "active",
+ deliveryState: "unknown",
cwd: "/tmp/paperclip/PAP-1634",
repoUrl: null,
baseRef: "main",
diff --git a/ui/src/lib/inbox.test.ts b/ui/src/lib/inbox.test.ts
index 06fc686aa4..67a739ab8c 100644
--- a/ui/src/lib/inbox.test.ts
+++ b/ui/src/lib/inbox.test.ts
@@ -258,6 +258,7 @@ function makeExecutionWorkspace(overrides: Partial<ExecutionWorkspace> = {}): Ex
strategyType: "git_worktree",
name: "PAP-1 branch",
status: "active",
+ deliveryState: overrides.deliveryState ?? "unknown",
cwd: "/tmp/project/worktree",
repoUrl: null,
baseRef: null,
diff --git a/ui/src/lib/issue-properties-panel-key.test.ts b/ui/src/lib/issue-properties-panel-key.test.ts
index ac7d0cf4d7..6c4631c7f8 100644
--- a/ui/src/lib/issue-properties-panel-key.test.ts
+++ b/ui/src/lib/issue-properties-panel-key.test.ts
@@ -94,6 +94,7 @@ describe("buildIssuePropertiesPanelKey", () => {
strategyType: "git_worktree",
name: "PAP-1 workspace",
status: "active",
+ deliveryState: "unknown",
cwd: "/tmp/paperclip/PAP-1",
repoUrl: null,
baseRef: "master",
diff --git a/ui/src/lib/optimistic-issue-comments.test.ts b/ui/src/lib/optimistic-issue-comments.test.ts
index c901725433..72de1ffed5 100644
--- a/ui/src/lib/optimistic-issue-comments.test.ts
+++ b/ui/src/lib/optimistic-issue-comments.test.ts
@@ -628,6 +628,7 @@ describe("optimistic issue comments", () => {
strategyType: "project_primary",
branchName: null,
status: "active",
+ deliveryState: "unknown",
name: "Execution workspace",
cwd: "/tmp/paperclip",
repoUrl: null,
diff --git a/ui/src/lib/project-workspaces-tab.test.ts b/ui/src/lib/project-workspaces-tab.test.ts
index d1013876c4..6bf3632ce9 100644
--- a/ui/src/lib/project-workspaces-tab.test.ts
+++ b/ui/src/lib/project-workspaces-tab.test.ts
@@ -76,6 +76,7 @@ function createExecutionWorkspace(overrides: Partial<ExecutionWorkspace>): Execu
strategyType: overrides.strategyType ?? "git_worktree",
name: overrides.name ?? "PAP-893",
status: overrides.status ?? "active",
+ deliveryState: overrides.deliveryState ?? "unknown",
cwd: overrides.cwd ?? "/repo/.worktrees/PAP-893",
repoUrl: overrides.repoUrl ?? null,
baseRef: overrides.baseRef ?? "public-gh/master",
diff --git a/ui/src/lib/subIssueDefaults.test.ts b/ui/src/lib/subIssueDefaults.test.ts
index 46224a09be..41f6e4bca7 100644
--- a/ui/src/lib/subIssueDefaults.test.ts
+++ b/ui/src/lib/subIssueDefaults.test.ts
@@ -10,6 +10,7 @@ function makeExecutionWorkspace(overrides: Partial<ExecutionWorkspace> = {}): Ex
projectWorkspaceId: "project-workspace-1",
sourceIssueId: null,
status: "active",
+ deliveryState: "unknown",
mode: "isolated_workspace",
strategyType: "git_worktree",
name: "Parent workspace",
diff --git a/ui/storybook/fixtures/paperclipData.ts b/ui/storybook/fixtures/paperclipData.ts
index dc619fa664..a4c8146d71 100644
--- a/ui/storybook/fixtures/paperclipData.ts
+++ b/ui/storybook/fixtures/paperclipData.ts
@@ -508,6 +508,7 @@ export const storybookExecutionWorkspaces: ExecutionWorkspace[] = [
strategyType: "git_worktree",
name: "PAP-1641 storybook worktree",
status: "active",
+ deliveryState: "unknown",
cwd: `${storybookWorktreeRoot}/PAP-1641-create-super-detailed-storybooks-for-our-project`,
repoUrl: "https://github.com/paperclipai/paperclip",
baseRef: "master",
@@ -536,6 +537,7 @@ export const storybookExecutionWorkspaces: ExecutionWorkspace[] = [
strategyType: "git_worktree",
name: "PAP-1608 release smoke cleanup",
status: "cleanup_failed",
+ deliveryState: "unknown",
cwd: `${storybookWorktreeRoot}/PAP-1608-release-smoke-cleanup`,
repoUrl: "https://github.com/paperclipai/paperclip",
baseRef: "master",
diff --git a/ui/storybook/stories/dialogs-modals.stories.tsx b/ui/storybook/stories/dialogs-modals.stories.tsx
index b721e4a897..e5757c83d4 100644
--- a/ui/storybook/stories/dialogs-modals.stories.tsx
+++ b/ui/storybook/stories/dialogs-modals.stories.tsx
@@ -137,6 +137,7 @@ const documentRevisions: DocumentRevision[] = [
const closeReadinessReady: ExecutionWorkspaceCloseReadiness = {
workspaceId: "execution-workspace-storybook",
+ deliveryState: "unmerged",
state: "ready_with_warnings",
blockingReasons: [],
warnings: [