From cde944ed75648adfb569e86133adc8b118b55dd6 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:40:25 -0500 Subject: [PATCH] fix(workspaces): keep retained readers valid after cross-task wake coalescing (#16928) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Before a run starts, repository admission checks every retained reader of the physical repository root and of overlapping roots. > - Each retained reader records the run, task, agent and responsible user that the server admitted. > - A wake for another task can coalesce into a running run. The merge replaces `contextSnapshot.issueId` and `taskId` with the other task. > - The retained-reader check used that mutable context task before the run's immutable task binding. The old reader then looked like a changed identity. > - When a later run admits an overlapping root, such as a shared project checkout that contains earlier task worktrees, every admission on that root fails. The root stays blocked and no operator action can repair it. > - This pull request accepts a retained reader when its task matches the run's immutable binding or its current context task. > - The benefit is that legitimate wake coalescing no longer blocks a shared root, and missing or truly mismatched identities still fail closed. ## Linked Issues or Issue Description Refs #16717 and #16832. Those cover retained readers whose run, agent or task was deleted. This pull request covers a different cause: every identity still exists, but wake coalescing changed the run's context task. #16832 keeps identity mismatches fail-closed, so it does not fix this case. Both pull requests change the same condition in `execution-workspace-root-readers.ts`. The pull request that merges second must rebase. **What happened?** A scheduled routine run failed in setup with `Repository root retains a reader whose identity is no longer available` (403). Every later run of the routine failed in the same way, for eight hours in a row. Two earlier runs of the same agent were the retained readers. Each run started for its own task and recorded its reader. About 10 to 16 minutes later, a monitor wake for a different task coalesced into the running run with reason `issue_execution_same_name`. `mergeCoalescedContextSnapshot` set `contextSnapshot.issueId` to the other task. `heartbeat_runs.issue_id` stayed on the original task, because the `heartbeat_runs_set_scope_kind` trigger makes the binding immutable. The readers were on per-task worktree roots, so nothing failed at first. Then the routine's tasks changed to the shared project checkout. That root contains those worktrees, so admission loaded the two readers, compared them with the changed context task, and threw. **Expected behavior** A retained reader stays valid while its run, agent, task and responsible user still exist and still match what the server admitted. A context change from wake coalescing must not make the reader unavailable. A reader whose task matches neither the run's binding nor its context must still be rejected. **Steps to reproduce** 1. Admit run R for task A on a nested root, for example `/.paperclip/worktrees/a`. 2. Coalesce a wake for task B into R. `contextSnapshot.issueId` becomes B. `heartbeat_runs.issue_id` stays A. 3. Admit or publish another task on the parent root ``. 4. Observe the 403 `Repository root retains a reader whose identity is no longer available`. Every later admission on that root fails in the same way. **Paperclip version or commit** Reproduced on `master` at b44871098 with the new regression test. ## What Changed - Add `runRetainsIssueIdentity(run, issueId)` in `server/src/services/execution-workspace-root-readers.ts`. It accepts the previous derived identity (`nativeIssueId ?? context issueId ?? context taskId ?? issueId`) or the immutable binding (`nativeIssueId ?? issueId`). - Use the helper for the three retained-run identity checks: `loadRepositoryRootReaders`, `requiresAnonymousRepositoryAcquisition` and `assertRootProjectTrust`. - Add a real PostgreSQL regression. A reader on a nested worktree root is admitted for task A. The test builds the coalesced context with the real `mergeCoalescedContextSnapshot`. Publication on the parent root must succeed. A reader whose task matches neither the binding nor the context must still fail. - Move one existing row. The old "rejects" test changed only the context task, which is now the legitimate coalescing case. The test now changes the reader's recorded task to a different existing task, so the mismatch path still fails closed. - Update the retained-reader contract in `doc/DATABASE.md`. ## Verification - Red before the fix: `pnpm exec vitest run --project @paperclipai/server --maxWorkers=1 --fileParallelism=false server/src/__tests__/repository-root-reader-queries.test.ts` fails 1 of 9 tests. The new test passes its first publication. It fails after the coalesced context with `Repository root retains a reader whose identity is no longer available` (403), which is the production error. - Green after the fix: the same command passes 9 of 9 tests. - One intermediate attempt failed and is kept here. My first test draft changed `heartbeat_runs.issue_id`. The database trigger rejected it with `run task binding is immutable`. That rejection confirms the binding this fix relies on. The final test uses a separate run for the negative case. - Related suites: `task-workspace-repositories*.test.ts`, `task-workspace-source-copy-privacy.test.ts`, `project-workspace-root-provenance.test.ts`, `workspace-authorization-query.test.ts`, `execution-transaction-timing.test.ts`, `execution-workspace-reopen.test.ts`, `file-resources.test.ts`, `heartbeat-project-repositories.test.ts`, `heartbeat-workspace-source-trust.test.ts` and `heartbeat/workspace-preparation.test.ts`. All 13 files pass on the fixed head. The first invocation passed 8 files. The other 5 files failed to import `@paperclipai/plugin-sdk`, because its `dist` was not built in this fresh checkout. That run reported 37 failed tests, all from the import error, not from this change. After `pnpm --filter @paperclipai/plugin-sdk... build`, the same 5 files passed 206 of 206 tests. - Production evidence (read-only SQL on the affected instance): exactly two readers in the company fail the current check. Both are on the blocked root. For both, `heartbeat_runs.issue_id` equals the reader's task and the context task is a different task after a coalesced `issue_execution_same_name` wake. Both pass the new rule, so the blocked root recovers after deployment without data repair. - Not run: full `pnpm -r typecheck`, `pnpm test:run` and `pnpm build`. The sandbox has 4 GB of memory. CI runs these checks. ## Risks - The rule now also accepts a reader whose task equals the run's immutable binding while the context points to another task. The binding is the run's privacy binding. The database sets it at insert and does not let it change, and it requires `native_issue_id` to agree with it. The reader's own recorded task is still the authorization context. - The rule keeps the previous context identity. A run that coalesced a wake before it started and then coalesced another one later could still produce an unavailable reader. I did not find that sequence in the affected data. The cross-task coalesce targets a run that already holds the other task's execution lock, and that happens after admission. - No schema, migration or API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code in a Paperclip agent run, with tool use, code execution and read-only SQL diagnostics. The context window and reasoning settings are managed by the runtime. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Paperclip --- doc/DATABASE.md | 2 +- .../repository-root-reader-queries.test.ts | 40 +++++++++++++++++-- .../execution-workspace-repositories.ts | 5 +-- .../execution-workspace-root-readers.ts | 13 ++++-- 4 files changed, 50 insertions(+), 10 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index d7d4577f534..5d69f5356e5 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 e6bd755a326..be96d556732 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>; @@ -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 4996e365860..e8337fde8b7 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 74986fc7b30..fc05d73bd91 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>`jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', 'taskId', ${heartbeatRuns.contextSnapshot}->'taskId', 'executionPolicy', ${heartbeatRuns.contextSnapshot}->'executionPolicy')`, }; +type ReaderRunIdentity = Pick; + +// 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(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,