Skip to content

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

fix(workspaces): keep retained readers valid after cross-task wake coalescing (#16928)

Dottacde944ed7564
diff --git a/doc/DATABASE.md b/doc/DATABASE.md
index d7d4577f53..5d69f5356e 100644
--- a/doc/DATABASE.md
+++ b/doc/DATABASE.md
@@ -940,7 +940,7 @@ Migration [0336_big_crystal.sql](../packages/db/src/migrations/0336_big_crystal.
Migration [0337_exotic_proemial_gods.sql](../packages/db/src/migrations/0337_exotic_proemial_gods.sql) adds internal `execution_workspace_repository_roots` records. A company and hash of its canonical physical path uniquely identify a sticky `anonymous_only` or `managed` acquisition reservation. Short transactions serialize reservations with repository requests and credential promotion, preventing private publication after low-trust admission checks. Records have no workspace foreign key: mutable workspace metadata, relocation, archival or deletion cannot release a physical folder still accessible to an admitted run. There is no automatic mode change or reservation deletion.
-Migration [0338_absurd_vengeance.sql](../packages/db/src/migrations/0338_absurd_vengeance.sql) adds internal `execution_workspace_repository_access` provenance. Company/canonical-root source entries retain execution-workspace and source-project identities; reader entries retain the exact admitted run, task, agent and responsible user. New repository receipts also record their root at creation; legacy receipts receive no inferred origin. Shared project-source entries retain which physical owners require workspace write authority. Current admission, selection, requests and publication check the current task’s writer against those owners; retained past readers and file APIs still require only read authority. Genuine isolated copies retain source read access without requiring shared-folder write access. An existing linked worktree can recover a missing isolated-copy proof only after Git registration and its captured source owner are verified. Configured local sibling copies retain deny-only task/project source ownership on the bound task root before materialization; ordinary repository clones create no isolation proof. The shared root fence checks every reader against every source before admission and future publication, including tasks without repository requests. File APIs apply the same source privacy without writing provenance. These entries grant no authority and have no workspace or run deletion cascade; unavailable retained identity fails closed. Automatic provenance release is deferred, so a newly incompatible permission scope requires a separate physical root.
+Migration [0338_absurd_vengeance.sql](../packages/db/src/migrations/0338_absurd_vengeance.sql) adds internal `execution_workspace_repository_access` provenance. Company/canonical-root source entries retain execution-workspace and source-project identities; reader entries retain the exact admitted run, task, agent and responsible user. A retained reader's task must match the run's immutable task binding or its current context task; a wake coalesced into a running run can replace the context task without changing that binding. New repository receipts also record their root at creation; legacy receipts receive no inferred origin. Shared project-source entries retain which physical owners require workspace write authority. Current admission, selection, requests and publication check the current task’s writer against those owners; retained past readers and file APIs still require only read authority. Genuine isolated copies retain source read access without requiring shared-folder write access. An existing linked worktree can recover a missing isolated-copy proof only after Git registration and its captured source owner are verified. Configured local sibling copies retain deny-only task/project source ownership on the bound task root before materialization; ordinary repository clones create no isolation proof. The shared root fence checks every reader against every source before admission and future publication, including tasks without repository requests. File APIs apply the same source privacy without writing provenance. These entries grant no authority and have no workspace or run deletion cascade; unavailable retained identity fails closed. Automatic provenance release is deferred, so a newly incompatible permission scope requires a separate physical root.
Repository admission loads retained workspace and task sources in bounded batches. Readers share source rows and privacy evaluation for identical principals, but each retained run receives its own trust and responsible-user decision. The snapshot lasts only for one read batch; later admission and publication reload current authority. Keep source-loading query counts bounded as both workspace history and retained reader counts grow.
diff --git a/server/src/__tests__/repository-root-reader-queries.test.ts b/server/src/__tests__/repository-root-reader-queries.test.ts
index e6bd755a32..be96d55673 100644
--- a/server/src/__tests__/repository-root-reader-queries.test.ts
+++ b/server/src/__tests__/repository-root-reader-queries.test.ts
@@ -11,6 +11,7 @@ import { agents, authUsers, companies, companyMemberships, createDb, executionWo
import { executionWorkspaceRepositoryService } from "../services/execution-workspace-repositories.js";
import { loadRepositoryRootReaders } from "../services/execution-workspace-root-readers.js";
import { authorizationService, type AuthorizationActor } from "../services/authorization.js";
+import { mergeCoalescedContextSnapshot } from "../services/heartbeat/run-preparation.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
@@ -65,12 +66,12 @@ it("bounds repeated-principal queries without loading retained run payloads", as
it("rejects missing, foreign-company and mismatched retained run identities", async () => {
const invalidId = runIds[31];
- const otherCompanyId = randomUUID();
+ const otherCompanyId = randomUUID(), otherIssueId = randomUUID();
await db.insert(companies).values({ id: otherCompanyId, name: "Foreign readers", issuePrefix: "FRQ" });
+ await db.insert(issues).values({ id: otherIssueId, companyId, projectId, title: "Other task", assigneeAgentId: agentId });
const service = executionWorkspaceRepositoryService(db);
for (const change of [
{ companyId: otherCompanyId },
- { contextSnapshot: { issueId: randomUUID(), taskId: issueId } },
{ responsibleUserId: randomUUID() },
]) {
try {
@@ -81,7 +82,7 @@ it("rejects missing, foreign-company and mismatched retained run identities", as
.where(eq(heartbeatRuns.id, invalidId));
}
}
- for (const change of [{ scopeId: randomUUID() }, { agentId: randomUUID() }, { issueId: randomUUID() }]) {
+ for (const change of [{ scopeId: randomUUID() }, { agentId: randomUUID() }, { issueId: randomUUID() }, { issueId: otherIssueId }]) {
try {
await db.update(executionWorkspaceRepositoryAccess).set(change).where(eq(executionWorkspaceRepositoryAccess.scopeId, invalidId));
await expect(service.guardForPublication(input())).rejects.toThrow("identity");
@@ -90,6 +91,39 @@ it("rejects missing, foreign-company and mismatched retained run identities", as
.where(eq(executionWorkspaceRepositoryAccess.scopeId, "scopeId" in change ? change.scopeId : invalidId));
}
}
+ await db.delete(issues).where(eq(issues.id, otherIssueId));
+ await expect(service.guardForPublication(input())).resolves.toBeUndefined();
+});
+
+it("keeps a nested retained reader valid after another task's wake coalesces into its run", async () => {
+ const runId = randomUUID(), otherRunId = randomUUID(), otherIssueId = randomUUID();
+ const nested = path.join(cwd, ".paperclip", "worktrees", "earlier-task");
+ await fs.mkdir(nested, { recursive: true });
+ const admitted = { issueId, taskId: issueId, taskKey: issueId, wakeReason: "issue_assigned" };
+ const coalesced = mergeCoalescedContextSnapshot(admitted, { issueId: otherIssueId, taskId: otherIssueId,
+ taskKey: otherIssueId, wakeReason: "issue_monitor_due", source: "issue.monitor" });
+ expect(coalesced.issueId).toBe(otherIssueId);
+ await db.insert(issues).values({ id: otherIssueId, companyId, projectId, title: "Monitored task", assigneeAgentId: agentId });
+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: userId, issueId,
+ status: "succeeded", contextSnapshot: admitted });
+ await db.insert(executionWorkspaceRepositoryAccess).values({ companyId, rootKey: createHash("sha256").update(nested).digest("hex"),
+ canonicalCwd: nested, kind: "reader", scopeId: runId, issueId, agentId, responsibleUserId: userId });
+ const service = executionWorkspaceRepositoryService(db);
+ try {
+ await expect(service.guardForPublication(input())).resolves.toBeUndefined();
+ await db.update(heartbeatRuns).set({ contextSnapshot: coalesced }).where(eq(heartbeatRuns.id, runId));
+ await expect(service.guardForPublication(input())).resolves.toBeUndefined();
+ // A reader whose task matches neither the run's binding nor its context stays unavailable.
+ await db.insert(heartbeatRuns).values({ id: otherRunId, companyId, agentId, responsibleUserId: userId,
+ status: "succeeded", contextSnapshot: { issueId: otherIssueId } });
+ await db.update(executionWorkspaceRepositoryAccess).set({ scopeId: otherRunId }).where(eq(executionWorkspaceRepositoryAccess.scopeId, runId));
+ await expect(service.guardForPublication(input())).rejects.toThrow("identity");
+ } finally {
+ await db.delete(executionWorkspaceRepositoryAccess).where(inArray(executionWorkspaceRepositoryAccess.scopeId, [runId, otherRunId]));
+ await db.delete(heartbeatRuns).where(inArray(heartbeatRuns.id, [runId, otherRunId]));
+ await db.delete(issues).where(eq(issues.id, otherIssueId));
+ await rm(path.join(cwd, ".paperclip"), { recursive: true, force: true });
+ }
await expect(service.guardForPublication(input())).resolves.toBeUndefined();
});
diff --git a/server/src/services/execution-workspace-repositories.ts b/server/src/services/execution-workspace-repositories.ts
index 4996e36586..e8337fde8b 100644
--- a/server/src/services/execution-workspace-repositories.ts
+++ b/server/src/services/execution-workspace-repositories.ts
@@ -21,7 +21,7 @@ import { toolAccessService } from "./tool-access.js";
import { normalizeProjectRepositoryUrl } from "./project-repositories.js";
import { buildGitAuthInvocation, createGitRemoteAuthProvider } from "./git-credentials.js";
import { materializeManagedProjectWorkspace, ensureManagedRepositoriesIgnored } from "./managed-repository-checkout.js";
-import { loadRepositoryRootReaders, requiresAnonymousRepositoryAcquisition, rootReaderRunColumns } from "./execution-workspace-root-readers.js";
+import { loadRepositoryRootReaders, requiresAnonymousRepositoryAcquisition, rootReaderRunColumns, runRetainsIssueIdentity } from "./execution-workspace-root-readers.js";
import { canonicalRepositoryRoot, resolveRepositoryRoots, repositoryRootsOverlap, legacyRepositoryRootMayMatch, configuredWorkspaceRoot, verifiedIsolatedWorktree, unusedIsolatedCopyTarget, isolatedWorkspaceSourceRoots, type WorkspaceSourceCopyKind } from "./execution-workspace-source-roots.js";
export { canonicalRepositoryRoot } from "./execution-workspace-source-roots.js";
@@ -420,8 +420,7 @@ async function assertRootProjectTrust(db: Db | DbTransaction, input: {
const workspaceId = input.sourceWorkspaceId ?? issue?.executionWorkspaceId;
const [workspace] = workspaceId ? await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, workspaceId), eq(executionWorkspaces.companyId, input.companyId))) : [];
const [source] = workspace?.projectId ? await db.select().from(projects).where(and(eq(projects.id, workspace.projectId), eq(projects.companyId, input.companyId))) : [];
- if ((agentId && !agent) || (runId && (!run || run.agentId !== agentId || !issue
- || (run.nativeIssueId ?? run.contextSnapshot?.issueId ?? run.contextSnapshot?.taskId ?? run.issueId) !== issue.id))) throw incompatible();
+ if ((agentId && !agent) || (runId && (!run || run.agentId !== agentId || !issue || !runRetainsIssueIdentity(run, issue.id)))) throw incompatible();
const retainedPolicy = run?.contextSnapshot?.executionPolicy;
const current = resolveCoreTrustPreset({ companyId: input.companyId, agent, project, workspaceSourceProject: source, issue,
run: run ? { companyId: input.companyId, executionPolicy: retainedPolicy } : null });
diff --git a/server/src/services/execution-workspace-root-readers.ts b/server/src/services/execution-workspace-root-readers.ts
index 74986fc7b3..fc05d73bd9 100644
--- a/server/src/services/execution-workspace-root-readers.ts
+++ b/server/src/services/execution-workspace-root-readers.ts
@@ -16,6 +16,14 @@ export const rootReaderRunColumns = {
responsibleUserId: heartbeatRuns.responsibleUserId, nativeIssueId: heartbeatRuns.nativeIssueId, issueId: heartbeatRuns.issueId,
contextSnapshot: sql<Record<string, unknown>>`jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', 'taskId', ${heartbeatRuns.contextSnapshot}->'taskId', 'executionPolicy', ${heartbeatRuns.contextSnapshot}->'executionPolicy')`,
};
+type ReaderRunIdentity = Pick<typeof heartbeatRuns.$inferSelect, "nativeIssueId" | "issueId" | "contextSnapshot">;
+
+// A wake for another task can coalesce into a running run and replace its context
+// task after admission. The run's bound task still identifies its retained reader.
+export function runRetainsIssueIdentity(run: ReaderRunIdentity, issueId: string) {
+ return issueId === (run.nativeIssueId ?? run.contextSnapshot?.issueId ?? run.contextSnapshot?.taskId ?? run.issueId)
+ || issueId === (run.nativeIssueId ?? run.issueId);
+}
// This snapshot belongs to one guarded operation. Never retain it across admissions
// or publications: identities and permissions must be read again next time.
@@ -46,7 +54,7 @@ export async function loadRepositoryRootReaders<T extends ReaderEntry>(db: Reade
const agent = entry.agentId ? agentRows.get(entry.agentId) : undefined;
const issue = entry.issueId ? issueRows.get(entry.issueId) : undefined;
if (!run || !agent || !issue || run.agentId !== entry.agentId || run.responsibleUserId !== entry.responsibleUserId
- || (run.nativeIssueId ?? run.contextSnapshot?.issueId ?? run.contextSnapshot?.taskId ?? run.issueId) !== entry.issueId) {
+ || !runRetainsIssueIdentity(run, issue.id)) {
throw forbidden("Repository root retains a reader whose identity is no longer available");
}
const actor: AuthorizationActor = { type: "agent", source: "agent_jwt", companyId,
@@ -68,8 +76,7 @@ export function requiresAnonymousRepositoryAcquisition(input: {
}) {
const { companyId, issue, agent, project, workspaceSourceProject, run, agentId, runId } = input;
if (agentId && !agent) throw forbidden("Task repository agent is unavailable");
- if (runId && (!run || (input.explicitRunId && run.agentId !== agentId)
- || (run.nativeIssueId ?? run.contextSnapshot?.issueId ?? run.contextSnapshot?.taskId ?? run.issueId) !== issue.id)) {
+ if (runId && (!run || (input.explicitRunId && run.agentId !== agentId) || !runRetainsIssueIdentity(run, issue.id))) {
throw forbidden("Task repository run identity is unavailable");
}
const trust = resolveCoreTrustPreset({ companyId, agent, project, workspaceSourceProject, issue,