From 1838de8c6c85b806e4af660c71db3445cfa403b4 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 9 Nov 2026 15:02:54 -0800 Subject: [PATCH 1/5] Pause agents automatically when moving to a plugin environment (#20375) ## Thinking Path > - Paperclip manages AI agents and their execution environments. > - Core owns agent lifecycle state and controls when work can run. > - A plugin environment can need a computer that belongs to the agent. > - Moving a ready agent to that environment currently requires manual pause and resume actions. > - Saving the environment is sufficient intent to perform those routine steps. > - This change records the pause with the environment update and uses the existing lifecycle worker. > - Work can resume only after execution stops, the plugin starts its resources, and verification passes. ## Linked Issues or Issue Description Related: #19173 introduced environment-scoped plugin selection and the manual-pause requirement. I searched for related pull requests and found no duplicate fix. No separate issue is linked. **What happened?** Saving a ready agent with an environment whose lifecycle plugin is not selected returns a conflict. The error tells the user to pause the agent, change its environment, and resume it. **Expected behavior** Saving the environment change starts the required pause, resource setup, and verification automatically. Existing manual, budget, and company holds still block resume. **Steps to reproduce** 1. Use an agent in `ready` on an environment without an agent-owned plugin. 2. Select an agent-owned plugin environment in the agent configuration. 3. Save without first pausing the agent. Before this fix, the save fails. With this fix, the agent moves through `pausing`, `resuming`, and `verifying` before `ready`. ## What Changed - Save the new environment and automatic pause in the same transaction. Keep the existing plugin selection during stop. - Use the existing completion of a pause without holds to resume automatically. Set the saved resume target to `verifying` so the new environment must pass its test. - Preserve independent pause holds, lifecycle version checks, notifications, resource status events, and worker recovery. - Add migration tests for idle and running agents, real process-stop proof across a worker restart, added holds, failed verification, and route authorization. - Update the lifecycle and development docs. Keep the feature maps unchanged, as required for a small behavior fix. ## Verification - Current revision: `300f57539bce9b198406c3793ab3c2de46492659`. - Lifecycle and case API discovery suites passed after updating the branch to master. The final environment-plugin suite passed all 22 tests, including four real-route authorization cases for users and agents. Coverage includes real process-stop proof across worker replacement, independent holds, and failed migration verification. - Server typecheck: passed on the current base. All workspace typechecks and `pnpm build` passed before the base update; fresh CI covers the updated base. - `node scripts/check-module-boundaries.mjs`, `node scripts/check-maps.mjs`, and `git diff --check`: passed. - Reviewed the diff for secrets, personal data, private addresses, and run artifacts before each push. - [Current CI](https://github.com/paperclipai/paperclip/actions/runs/42714733533): passed on `300f57539bce9b198406c3793ab3c2de46492659` (52 successful jobs; the optional test-selection optimization was skipped). Standard Greptile: 5/5 on the current revision, with no unresolved findings. The security scanner accepted the documented configuration-authority policy. - Earlier CI failed the `case-history-api-discovery` assertion for the query `case for task`. It also failed locally. The branch now includes master's fix #20382, and that test passes. The migration implementation did not change. The superseded CI attempt was cancelled after recording the failure. - Full local `pnpm test:run`: incomplete; stopped after two passing chat partitions. The focused suites passed, and required CI supplies broad coverage, as specified in the repository instructions. - Local target: isolated source checkout on macOS ARM64, Node 26, disposable PostgreSQL, fixture lifecycle plugin. Initial database startup failed because the bundled macOS PostgreSQL package lacked dylib aliases. Temporary dependency aliases repaired startup; the focused database tests then passed. The installed Rust toolchain also needed to be added to PATH. - The pending-stop test retains a live process ID in the cancelled run. The real host stop check blocks plugin setup. After stop acknowledgment and worker replacement, the saved migration reaches readiness. ## Risks - Saving this environment change can stop current execution. The system performs that pause as part of the requested migration. - A failed stop, plugin call, or verification keeps the agent blocked and uses existing retry behavior. - Editing a shared environment or the instance default still uses its existing conflict checks. This change covers the individual agent environment update. - Configuration permission authorizes the temporary system pause needed for the resource move. Separate manual-pause authority is not required for this configuration operation. Real route tests cover authorized and denied users and agents. - No schema migration or deployment is included. A fixture plugin does not prove live computer provisioning or model execution. ## Model Used OpenAI Codex, based on GPT-6, with code execution and tool use. The exact runtime model ID and context limit are not exposed in this session. ## 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 --------- Co-authored-by: Paperclip --- doc/AGENT-LIFECYCLE.md | 17 ++- doc/DEVELOPING.md | 4 + .../__tests__/environment-plugins.test.ts | 103 +++++++++++++++++- .../agent-lifecycle/adapters/configuration.ts | 14 ++- 4 files changed, 124 insertions(+), 14 deletions(-) diff --git a/doc/AGENT-LIFECYCLE.md b/doc/AGENT-LIFECYCLE.md index 99601bea647..8da664e1a35 100644 --- a/doc/AGENT-LIFECYCLE.md +++ b/doc/AGENT-LIFECYCLE.md @@ -198,11 +198,22 @@ plugins are selected for all agents, including a sandbox provider that declares `requiresAgent: true`. When an agent moves to such an environment, the host adds the plugin at the next -`preparing` or `resuming` step. An agent in `ready` cannot move to it until it is -paused, because the plugin must finish its work before the agent uses that -environment. An agent in `verifying` returns to `preparing`. An agent that moves away keeps the selection until it is terminated, +`preparing` or `resuming` step. Moving a `ready` agent to an environment that +needs a new plugin automatically pauses execution, waits for the host and +existing plugins to stop, resumes with the new plugin, and verifies the saved +configuration before admitting work. The change and pause request commit +together; retries and server restarts retain the pending operation. Manual, +budget, and company holds still prevent automatic resume. An agent in +`verifying` returns to `preparing`. An agent that moves away keeps the selection until it is terminated, so the plugin keeps its resources until then. +The existing agent configuration permission authorizes this move, including its +temporary system pause. That permission already controls environment selection +and resource allocation. Separate permission to issue a manual pause is not +required for the migration. Configuration and company access checks still run +before the change; an unauthorized request cannot save the environment or pause +the agent. + Saving an environment or the instance default that gives such a plugin to `ready` or `verifying` agents without that selection returns a conflict. Pause those agents, save the change, and then resume them. diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 8318e22e2c4..5727800977e 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -3189,6 +3189,10 @@ Saved OpenCode agents keep their runner and runtime policies. Plugin environment drivers can declare `requiresAgent: true` when their leases need an agent-owned resource. The host selects that plugin's lifecycle work only for agents on that environment. See [Required plugin work](./AGENT-LIFECYCLE.md#required-plugin-work). +Moving a ready agent to an environment that needs a new plugin automatically +pauses execution, waits for stop completion, starts the required resources, and +verifies the saved configuration before allowing work. Existing pause holds +still apply; the user does not need to pause or resume the agent for this move. Setup saves the draft and environment, runs its existing lifecycle preparation, and waits in `verifying` with the `setup` hold. The worker becomes idle there until the user finishes hiring. Connection tests diff --git a/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts b/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts index c4b48cedfde..96a87845273 100644 --- a/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts @@ -1,6 +1,10 @@ import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; -import { agents, companies, environments, instanceSettings, plugins, createDb, type Db } from "@paperclipai/db"; +import { agents, companies, companyMemberships, environments, heartbeatRuns, instanceSettings, plugins, principalPermissionGrants, createDb, type Db } from "@paperclipai/db"; +import express from "express"; +import request from "supertest"; +import { agentRoutes } from "../../../routes/agents.js"; +import { errorHandler } from "../../../middleware/error-handler.js"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; import { configureAgentLifecycle, createAgentLifecycle, createAgentLifecycleEffects } from "../../../services/agent-lifecycle.js"; @@ -8,6 +12,7 @@ import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver. import { agentService as agentConfiguration } from "../../../services/agents.js"; import { assertAgentsReadyForEnvironmentChange } from "../../../services/plugin-environment-driver.js"; import { createLifecycleStore } from "../adapters/postgres.js"; +import type { LifecycleAgent, LifecycleDriver } from "../application/ports.js"; const support = await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("environment-bound lifecycle plugins", () => { @@ -38,8 +43,8 @@ const support = await getEmbeddedPostgresTestSupport(); ]); }); - function worker() { - const work = configureAgentLifecycle(db, { ...createLifecycleDriver(db, { call } as never), runHost: async () => "complete" as const }); + function worker(runHost: LifecycleDriver["runHost"] = async () => "complete") { + const work = configureAgentLifecycle(db, { ...createLifecycleDriver(db, { call } as never), runHost }); workers.push(work); return work; } @@ -49,6 +54,11 @@ const support = await getEmbeddedPostgresTestSupport(); return id; } async function current(id: string) { return (await db.select().from(agents).where(eq(agents.id, id)))[0]!; } + function app(actor: Express.Request["actor"]) { + const value = express(); value.use(express.json()); + value.use((req, _res, next) => { req.actor = actor; next(); }); + value.use("/api", agentRoutes(db)); value.use(errorHandler); return value; + } async function selection(id: string) { return createLifecycleDriver(db, { call } as never).requiredPluginIds((await createLifecycleStore(db, createAgentLifecycleEffects()).get(id))!); } @@ -147,10 +157,91 @@ const support = await getEmbeddedPostgresTestSupport(); expect((await current(id)).lifecycleState).toBe("verifying"); }); - it("refuses to move a ready agent to an environment whose plugin it has not selected", async () => { + it.each(["idle", "running"])("automatically pauses an %s agent, prepares its new environment, and verifies before readiness", async status => { + const id = await agent(otherEnvironmentId, { status, lifecycleRequiredPluginIds: [] }); + const saved = await agentConfiguration(db).update(id, { defaultEnvironmentId: boundEnvironmentId }); + expect(saved).toMatchObject({ defaultEnvironmentId: boundEnvironmentId, lifecycleState: "pausing", status: "paused" }); + expect(await current(id)).toMatchObject({ lifecycleHolds: [], lifecycleOperation: { resumeState: "verifying" } }); + + const phases: string[] = []; + const runHost = vi.fn(async (row: LifecycleAgent) => { phases.push(row.lifecycleState); return "complete" as const; }); + await worker(runHost).process(id); + expect(phases).toEqual(["pausing", "resuming", "verifying"]); + expect(call.mock.calls.map(args => args[2].phase)).toEqual(["resuming", "verifying"]); + expect(await current(id)).toMatchObject({ lifecycleState: "ready", status: "idle", lifecycleRequiredPluginIds: [boundPluginId] }); + }); + + it.each(["board", "agent"] as const)("lets a configuration-authorized %s migrate without separate manual-pause authority", async type => { + const id = await agent(otherEnvironmentId, { status: "running", adapterType: "paperclip_runner", + adapterConfig: { provider: "codex" }, lifecycleRequiredPluginIds: [] }); + const principalId = type === "agent" ? await agent(otherEnvironmentId) : randomUUID(); + await db.insert(companyMemberships).values({ companyId, principalType: type === "board" ? "user" : "agent", + principalId, membershipRole: "member", status: "active" }); + await db.insert(principalPermissionGrants).values({ companyId, principalType: type === "board" ? "user" : "agent", + principalId, permissionKey: "agents:configure" }); + const actor: Express.Request["actor"] = type === "board" + ? { type, source: "session", userId: principalId, companyIds: [companyId], + memberships: [{ companyId, membershipRole: "member", status: "active" }] } + : { type, source: "agent_key", agentId: principalId, companyId }; + await request(app(actor)).post(`/api/agents/${id}/pause`).send({}).expect(403); + const response = await request(app(actor)).patch(`/api/agents/${id}`).send({ defaultEnvironmentId: boundEnvironmentId }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + expect(await current(id)).toMatchObject({ defaultEnvironmentId: boundEnvironmentId, lifecycleState: "pausing", status: "paused" }); + }); + + it.each(["board", "agent"] as const)("rejects a %s without configuration permission before saving the environment or pausing", async type => { + const id = await agent(otherEnvironmentId, { status: "running", adapterType: "paperclip_runner", + adapterConfig: { provider: "codex" }, lifecycleRequiredPluginIds: [] }); + const principalId = type === "agent" ? await agent(otherEnvironmentId) : randomUUID(); + await db.insert(companyMemberships).values({ companyId, principalType: type === "board" ? "user" : "agent", principalId, membershipRole: "member", status: "active" }); + const actor: Express.Request["actor"] = type === "board" + ? { type, source: "session", userId: principalId, companyIds: [companyId], + memberships: [{ companyId, membershipRole: "member", status: "active" }] } + : { type, source: "agent_key", agentId: principalId, companyId }; + const before = await current(id); + await request(app(actor)).patch(`/api/agents/${id}`).send({ defaultEnvironmentId: boundEnvironmentId }).expect(403); + expect(await current(id)).toMatchObject({ defaultEnvironmentId: otherEnvironmentId, lifecycleState: "ready", status: "running", + lifecycleVersion: before.lifecycleVersion, lifecycleOperation: before.lifecycleOperation }); + expect(call).not.toHaveBeenCalled(); + }); + + it("retains the migration across a pending stop and worker restart without starting the new plugin early", async () => { + const id = await agent(otherEnvironmentId, { status: "running", lifecycleRequiredPluginIds: [] }); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: id, + status: "cancelled", invocationSource: "on_demand", runtimeMode: "legacy", + startedAt: new Date(), finishedAt: new Date(), processPid: process.pid }).returning(); + await agentConfiguration(db).update(id, { defaultEnvironmentId: boundEnvironmentId }); + const driver = createLifecycleDriver(db, { call } as never); + const stopping = worker(row => row.lifecycleState === "pausing" ? driver.runHost(row) : Promise.resolve("complete")); + await stopping.process(id); + expect((await current(id)).lifecycleState).toBe("pausing"); + expect(call).not.toHaveBeenCalled(); + await stopping.stop(); + await db.update(heartbeatRuns).set({ processPid: null, + resultJson: { executionCancellation: { state: "acknowledged" } } }).where(eq(heartbeatRuns.id, run.id)); + await createAgentLifecycle(db).retry(id); + await worker().process(id); + expect(await current(id)).toMatchObject({ lifecycleState: "ready", lifecycleRequiredPluginIds: [boundPluginId] }); + }); + + it.each(["manual", "budget", "company_paused"])("preserves a %s hold added while migration is pausing", async reason => { const id = await agent(otherEnvironmentId, { lifecycleRequiredPluginIds: [] }); - await expect(agentConfiguration(db).update(id, { defaultEnvironmentId: boundEnvironmentId })).rejects.toThrow("Pause the agent"); - expect((await current(id)).defaultEnvironmentId).toBe(otherEnvironmentId); + await agentConfiguration(db).update(id, { defaultEnvironmentId: boundEnvironmentId }); + await createAgentLifecycle(db).pauseAgent(id, reason); + await worker().process(id); + expect(await current(id)).toMatchObject({ lifecycleState: "paused", status: "paused", lifecycleHolds: [reason] }); + expect(call).not.toHaveBeenCalled(); + }); + + it("keeps the agent blocked when verification of the new environment fails", async () => { + const id = await agent(otherEnvironmentId, { lifecycleRequiredPluginIds: [] }); + await agentConfiguration(db).update(id, { defaultEnvironmentId: boundEnvironmentId }); + await worker(vi.fn(async (row: LifecycleAgent) => { + if (row.lifecycleState === "verifying") throw Object.assign(new Error("Fixture verification failed"), { code: "harness_test_failed" }); + return "complete" as const; + })).process(id); + expect(await current(id)).toMatchObject({ lifecycleState: "verifying", status: "paused", lifecycleRequiredPluginIds: [boundPluginId] }); + expect((await current(id)).lifecycleError).toBeTruthy(); }); it("lets a ready agent move when the plugin is selected, and keeps the selection when it leaves", async () => { diff --git a/server/src/modules/agent-lifecycle/adapters/configuration.ts b/server/src/modules/agent-lifecycle/adapters/configuration.ts index 38af7db7013..0af6a7ab986 100644 --- a/server/src/modules/agent-lifecycle/adapters/configuration.ts +++ b/server/src/modules/agent-lifecycle/adapters/configuration.ts @@ -29,9 +29,7 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects && Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId") && patch.defaultEnvironmentId !== current.defaultEnvironmentId && await effects.environmentRequiresNewPlugin(tx, patch.defaultEnvironmentId, current.lifecycleRequiredPluginIds); - if (needsNewPlugin && current.lifecycleState === "ready") { - throw new AgentLifecycleConflict("This environment needs setup for the agent. Pause the agent, change its environment, and then resume it."); - } + const pauseForEnvironment = needsNewPlugin && current.lifecycleState === "ready"; const prepareEnvironment = needsNewPlugin && !current.lifecycleHolds.includes("setup"); const prepareSetup = changed && current.lifecycleHolds.length === 1 && current.lifecycleHolds[0] === "setup" && ["paused", "preparing", "verifying"].includes(current.lifecycleState) @@ -39,19 +37,25 @@ export async function updateAgentConfiguration(tx: Db, effects: LifecycleEffects Object.prototype.hasOwnProperty.call(patch, "defaultEnvironmentId") ? patch.defaultEnvironmentId : current.defaultEnvironmentId, { adapterType: patch.adapterType ?? current.adapterType, adapterConfig: Object.prototype.hasOwnProperty.call(patch, "adapterConfig") ? patch.adapterConfig : current.adapterConfig }); - const invalidate = changed && (["preparing", "verifying", "resuming"].includes(current.lifecycleState) || prepareSetup); + const invalidate = changed && (["preparing", "verifying", "resuming"].includes(current.lifecycleState) || prepareSetup || pauseForEnvironment); if(prepareSetup&&!canConfigureAgentConnection(current))await effects.beforeConnectionEligibilityRestore?.(tx,current.companyId,current.id); + if (pauseForEnvironment) await effects.beforeStatusChange(tx, current.companyId, id, current.status, "paused"); if (invalidate) await effects.notifyWork(tx); const [updated] = await tx.update(agents).set({ ...patch, updatedAt: new Date(), ...(invalidate ? { lifecycleVersion: current.lifecycleVersion + 1, lifecycleError: null, ...(prepareSetup || prepareEnvironment ? { lifecycleState: "preparing" as const } : {}), + ...(pauseForEnvironment ? { lifecycleState: "pausing" as const, status: "paused", pausedAt: new Date() } : {}), ...(!prepareSetup && current.lifecycleHolds.includes("setup") && ["preparing", "verifying"].includes(current.lifecycleState) ? { lifecycleState: "pausing" as const } : {}), lifecycleOperation: { ...current.lifecycleOperation!, id: randomUUID(), hostComplete: false, completedPluginIds: [], attempts: 0, leaseOwner: undefined, leaseUntil: undefined, leaseHolder: undefined, retryAt: undefined, retryRequired: undefined, verificationFailures: undefined, - waitingForSignal: undefined, recheckRequested: undefined }, + waitingForSignal: undefined, recheckRequested: undefined, + // With no new hold, completed pause work resumes automatically, then verifies the new environment. + ...(pauseForEnvironment ? { resumeState: "verifying" as const, + pauseCause: { holds: current.lifecycleHolds, companyPauseReason: null } } : {}) }, } : {}) }).where(eq(agents.id, id)).returning(); + if (pauseForEnvironment) await effects.recordStatus(tx, current.companyId, id, "idle", "paused"); await effects.completeConfiguration(tx, current, updated, patch, options, publications); return agentRecordQueries(tx).getById(id); } From 302ada90dfda0e8fbcd8a514d506d310c9843bcb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:05:17 -0600 Subject: [PATCH 2/5] fix(workspace): refresh source admission proofs on import resume (#20394) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip preserves agent work and recovery obligations across server replacement. > - Online workspace imports keep durable operation and snapshot journals for interrupted work. > - A recovery admission fingerprint hashes complete run, finalizer, and lease rows. > - Accounting updates can change that hash while every saved recovery reference remains identical. > - Resume currently treats that expired admission observation as immutable source identity and refuses the existing journal. > - This pull request refreshes only that observation after exact identity checks and finalization fencing, preserving the original archive and journal. ## Linked Issues or Issue Description **What happened?** An interrupted import whose saved recovery sources have no changing online recovery hold can fail on its next attempt with `remote_workspace_migration_source_changed`. A change to a run's accounting fields changes `onlineProof.fingerprint`, even when all eight saved recovery records have the same typed references and ownership fields. **Expected behavior** For source-only admission drift, resume must compare every saved recovery source field exactly, except the supported ephemeral admission fingerprint. It must inspect the current source again, acquire the existing finalization fence, and retain strict full-proof checks through publication. It must keep the original operation, snapshot, archive, nested-child scope, and cohort identity. **Steps to reproduce** 1. Save a journal for an online import with eight recovery sources and no active online recovery holds. Interrupt after real authenticated restore of its uploaded snapshot. 2. Change only accounting fields on source 6's saved run. 3. Resume the same journal. The unchanged importer refuses it. The fixed importer preserves the original identities and commits after fresh guarded inspection. **Paperclip version or commit** Reproduced on master `9c634e42e449e91f3935cf59036981852f94a65e`. **Deployment mode** Online administrative imports with PostgreSQL. Related preservation work: https://github.com/paperclipai/paperclip/pull/20311 and https://github.com/paperclipai/paperclip/pull/20370. The independent readonly parallelism work in https://github.com/paperclipai/paperclip/pull/20387 changes different loops. ## What Changed - Compare the complete `legacyRecoverySources` records at resume, neutralizing only a valid fingerprint under the supported proof schema. Preserve every other field and refuse unsupported proof versions by name. - Reuse the current canonical full proofs. Persist them with an operation metadata compare-and-swap only after the existing finalization lock and strict reinspection succeed. - Keep strict full-proof checks within each attempt and before publication. Preserve all journal, snapshot, archive, nested-child, and cohort identities. - Add focused real PostgreSQL regressions in the existing online-source fixture, including exactly eight saved sources and repeat-apply idempotence. ## Verification - Genuine baseline RED: singleton and cohort resume both fail after accounting-only changes on the unchanged product. - `pnpm exec vitest run server/src/services/remote-workspace-online-source.test.ts -t 'eight saved recovery|changed saved recovery|recovery accounting changes|saved recovery proof'`: 8 passed. - Controls refuse changed valid references, a matched run/lease allocation change, competing ownership, and unsupported proof versions. They also prove that bookkeeping changes within an admitted attempt still refuse and a busy finalization fence prevents proof refresh. - Successful resumes preserve the operation/snapshot IDs, cipher SHA, manifest digest, byte size, nested scope, and cohort. Repeat apply creates no duplicate operation or snapshot. - Server layered typecheck, module boundaries, and whitespace checks passed. All applicable exact-head CI passed (including typecheck, build, all test shards and aggregate verify); hosted acceptance remains owned by the deployment workstream. Greptile re-reviewed the narrowed scope at 5/5. Ponytail scored 4/5, recommending a regression for the unchanged hold-bearing refusal; the maintainer explicitly kept that separate behavior outside this source-only fix. ## Risks This changes only source-proof resume admission. `onlineRecoveryHolds` and their action/intent fingerprints remain compared exactly, as on the baseline: a hold-bearing journal whose hold proof changes still refuses. Supporting that separate case would require preserving and validating the hold owner’s complete intent facts; this PR deliberately retains that safety check. Bookkeeping that changes during an active attempt still causes the existing strict publication checks to refuse that attempt. Older unsupported proof shapes remain refused. The metadata update uses the existing company/workspace/operation identity, running/unfinished status, and metadata compare-and-swap. No schema, provider, or storage format changes are included. ## Model Used OpenAI Codex, based on GPT-6, with tool use and code execution. The exact deployment identifier and context-window size are not exposed in this session. ## 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 Co-authored-by: Paperclip --- .../services/remote-workspace-migration.ts | 25 +++- .../remote-workspace-online-source.test.ts | 113 +++++++++++++++++- 2 files changed, 135 insertions(+), 3 deletions(-) diff --git a/server/src/services/remote-workspace-migration.ts b/server/src/services/remote-workspace-migration.ts index bb69c0b91f7..6819091b8ac 100644 --- a/server/src/services/remote-workspace-migration.ts +++ b/server/src/services/remote-workspace-migration.ts @@ -27,7 +27,7 @@ import { createNestedWorkspaceImportVerifier, onlineOrdinarySourceBlockers, offl import { inspectOnlineWorkspaceSource, requiresOnlineWorkspaceSource, type OnlineWorkspaceSource } from "./online-workspace-source.js"; import { withWorkspaceSourceLocks, withIndependentWorkspaceSourceLocks, IsolatedRepositorySourceBusy } from "./workspace-source-lock.js"; -import { inspectOnlineLegacyWorkspaceRecoverySource, inspectOnlineLegacyWorkspaceRecoveryHold, lockOnlineLegacyWorkspaceRecoverySources, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js"; +import { inspectOnlineLegacyWorkspaceRecoverySource, inspectOnlineLegacyWorkspaceRecoveryHold, lockOnlineLegacyWorkspaceRecoverySources, ONLINE_LEGACY_WORKSPACE_PRESERVATION, type OnlineLegacyWorkspaceRecoveryHold } from "./online-legacy-workspace-recovery.js"; import { inspectNativeWorkspaceMigration, nativeWorkspaceMigrationMarker } from "./native-runtime/native-workspace-migration.js"; const SCHEMA = "paperclip.remote-workspace-migration.v1"; @@ -341,6 +341,17 @@ async function resolveMigrationSource(input: MigrationInput) { return onlineSource; } +function recoverySourcesResumeIdentity(value: unknown): unknown { + if (!Array.isArray(value)) return value; + return value.map(source => { + if (!source || typeof source !== "object" || source.onlineProof == null) return source; + const proof = object(source.onlineProof); + if (proof.schema !== ONLINE_LEGACY_WORKSPACE_PRESERVATION || typeof proof.fingerprint !== "string" + || !/^[a-f0-9]{64}$/.test(proof.fingerprint)) throw new Error("remote_workspace_migration_recovery_proof_invalid"); + return { ...source, onlineProof: { ...proof, fingerprint: null } }; + }); +} + async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWorkspaceSource, cohort?: WorkspaceMigrationCohort, expectedSourceFingerprint?: string) { return input.db.transaction(async tx => { @@ -374,7 +385,8 @@ async function reserveMigration(input: MigrationInput, onlineSource?: OnlineWork if (Boolean(operation.metadata?.retainedDirectory) !== Boolean(current.retainedDirectory)) throw new Error("remote_workspace_migration_source_changed"); if (canonical(operation.metadata?.archivedGitSource ?? null) !== canonical(gitSourceProof(current.archivedGitSource))) throw new Error("remote_workspace_migration_source_changed"); if (canonical(operation.metadata?.finalizedRecoveryHolds ?? []) !== canonical(current.finalizedRecoveryHolds)) throw new Error("remote_workspace_migration_source_changed"); - if (canonical(operation.metadata?.legacyRecoverySources ?? []) !== canonical(current.legacyRecoverySources)) throw new Error("remote_workspace_migration_source_changed"); + if (canonical(recoverySourcesResumeIdentity(operation.metadata?.legacyRecoverySources ?? [])) + !== canonical(recoverySourcesResumeIdentity(current.legacyRecoverySources))) throw new Error("remote_workspace_migration_source_changed"); if (canonical(operation.metadata?.onlineRecoveryHolds ?? []) !== canonical(current.onlineRecoveryHolds)) throw new Error("remote_workspace_migration_source_changed"); return { workspace, authority: null, operation, source, sourceFingerprint, issueBinding, retainedDirectory: current.retainedDirectory, archivedGitSource: current.archivedGitSource, legacyRecoverySources: current.legacyRecoverySources, finalizedRecoveryHolds: current.finalizedRecoveryHolds, onlineRecoveryHolds: current.onlineRecoveryHolds }; } @@ -434,6 +446,15 @@ function createMigrationChildVerifier(input: MigrationInput, onlineSource: Onlin async function captureMigration(input: MigrationInput, reserved: ReservedMigration, onlineSource?: OnlineWorkspaceSource, childVerifier?: ReturnType) { let operation = reserved.operation!; + if (canonical(operation.metadata?.legacyRecoverySources ?? []) !== canonical(reserved.legacyRecoverySources)) { + const [refreshed] = await input.db.update(workspaceOperations).set({ metadata: { ...operation.metadata, + legacyRecoverySources: reserved.legacyRecoverySources }, updatedAt: new Date() }).where(and( + eq(workspaceOperations.companyId, input.companyId), eq(workspaceOperations.executionWorkspaceId, input.workspaceId), + eq(workspaceOperations.id, operation.id), eq(workspaceOperations.phase, "remote_workspace_migration"), eq(workspaceOperations.status, "running"), + sql`${workspaceOperations.finishedAt} is null`, eq(workspaceOperations.metadata, operation.metadata!))).returning(); + if (!refreshed) throw new Error("remote_workspace_migration_operation_changed"); + operation = refreshed; + } const snapshot = await beginWorkspaceSnapshot(input.db, { companyId: input.companyId, workspaceId: input.workspaceId, operationId: operation.id, generation: 1, epoch: 1 }); const scratch = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "pc-workspace-migration-"))); diff --git a/server/src/services/remote-workspace-online-source.test.ts b/server/src/services/remote-workspace-online-source.test.ts index 85527595038..c8af7667b7f 100644 --- a/server/src/services/remote-workspace-online-source.test.ts +++ b/server/src/services/remote-workspace-online-source.test.ts @@ -13,9 +13,10 @@ import { resolveManagedProjectWorkspaceDir, resolvePaperclipInstanceRoot } from import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; import { createStorageService } from "../storage/service.js"; import type { StorageService } from "../storage/types.js"; -import { inventoryRemoteWorkspaceMigration, migrateRemoteWorkspace } from "./remote-workspace-migration.js"; +import { inventoryRemoteWorkspaceMigration, migrateRemoteWorkspace, migrateRemoteWorkspaceCohort } from "./remote-workspace-migration.js"; import { getWorkspaceSnapshot, loadWorkspaceSnapshotArchive } from "./remote-workspace-snapshot-storage.js"; import { restoreRemoteWorkspaceArchive } from "./remote-workspace-snapshot-archive.js"; +import * as workspaceArchive from "./remote-workspace-snapshot-archive.js"; import { materializeManagedProjectWorkspace } from "./managed-repository-checkout.js"; import { withExecutionWorkspaceLifecycleLock } from "./execution-workspace-lifecycle-lock.js"; import { IsolatedRepositorySourceBusy, withIsolatedRepositorySourceLock, withWorkspaceSourceLocks } from "./workspace-source-lock.js"; @@ -528,6 +529,116 @@ describe.skipIf(!support.supported)("online ordinary physical source fence", () status: "active", evidence: { runId } }); return { ...f, run, owner, lease, warning }; } + async function interruptedRecoveryFixture(cohort = false) { + const f = await recoveryFixture(); + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.warning.id)); + const reference = f.run.runnerProfileJson!.nativeWorkspaceSync as Record; + const extra = Array.from({ length: 7 }, () => ({ runId: randomUUID(), leaseId: randomUUID(), providerLeaseId: randomUUID() })); + await db.insert(heartbeatRuns).values(extra.map(row => ({ id: row.runId, companyId: f.companyId, agentId: f.run.agentId, + nativeIssueId: f.run.nativeIssueId, status: "failed", runtimeMode: "native", finishedAt: new Date(), + runnerProfileJson: { nativeWorkspaceSync: { ...reference, leaseId: row.leaseId, providerLeaseId: row.providerLeaseId } } }))); + await db.insert(nativeRunFinalizations).values(extra.map(row => ({ companyId: f.companyId, + issueId: f.run.nativeIssueId!, runId: row.runId, phase: "terminal_failure" }))); + await db.insert(environmentLeases).values(extra.map(row => ({ id: row.leaseId, companyId: f.companyId, + environmentId: f.lease.environmentId, executionWorkspaceId: f.workspaceId, issueId: f.run.nativeIssueId, + heartbeatRunId: row.runId, provider: "daytona", providerLeaseId: row.providerLeaseId, + status: "retained", leasePolicy: "retain_on_failure", metadata: { remoteCwd: reference.remoteCwd } }))); + const apply = () => cohort ? migrateRemoteWorkspaceCohort({ db, storage, companyId: f.companyId, + workspaceIds: [f.workspaceId], apply: true, signal: AbortSignal.timeout(30_000) }) + : migrateRemoteWorkspace({ db, storage, companyId: f.companyId, workspaceId: f.workspaceId, apply: true }); + const restore = workspaceArchive.restoreRemoteWorkspaceArchive; + const interrupt = vi.spyOn(workspaceArchive, "restoreRemoteWorkspaceArchive").mockImplementationOnce(async input => { + await restore(input); + expect(await db.select().from(executionWorkspaceSnapshots)).toEqual([expect.objectContaining({ status: "uploaded" })]); + throw new Error("interrupted after verified upload"); + }); + try { await expect(apply()).rejects.toThrow("interrupted after verified upload"); } + finally { interrupt.mockRestore(); } + const [operation] = await db.select().from(workspaceOperations), [snapshot] = await db.select().from(executionWorkspaceSnapshots); + const sources = operation.metadata!.legacyRecoverySources as Array<{ runId: string; issueId: string; + reference: Record; onlineProof: { schema: string; fingerprint: string } }>; + expect(sources).toHaveLength(8); + expect(operation.status).toBe("running"); expect(snapshot.status).toBe("uploaded"); + return { ...f, apply, operation, snapshot, sources, changed: sources[6] }; + } + it.each([false, true])("resumes eight saved recovery sources after accounting changes (cohort=%s)", async cohort => { + const f = await interruptedRecoveryFixture(cohort); + await db.update(heartbeatRuns).set({ accountingAttemptCount: 1, accountingLastAttemptAt: new Date(), + accountingLastError: "retry scheduled", updatedAt: new Date() }).where(eq(heartbeatRuns.id, f.changed.runId)); + await expect(f.apply()).resolves.toMatchObject({ applied: true }); + const operations = await db.select().from(workspaceOperations), snapshots = await db.select().from(executionWorkspaceSnapshots); + expect(operations).toEqual([expect.objectContaining({ id: f.operation.id, status: "succeeded" })]); + expect(snapshots).toEqual([expect.objectContaining({ id: f.snapshot.id, sourceOperationId: f.operation.id, status: "committed", + objectKey: f.snapshot.objectKey, sha256: f.snapshot.sha256, manifestDigest: f.snapshot.manifestDigest, byteSize: f.snapshot.byteSize })]); + expect(operations[0].metadata!.nestedWorkspaceScope).toEqual(f.operation.metadata!.nestedWorkspaceScope); + expect(operations[0].metadata!.cohortMigration).toEqual(f.operation.metadata!.cohortMigration); + const sources = operations[0].metadata!.legacyRecoverySources as typeof f.sources; + expect(sources.map(source => ({ ...source, onlineProof: { ...source.onlineProof, fingerprint: null } }))) + .toEqual(f.sources.map(source => ({ ...source, onlineProof: { ...source.onlineProof, fingerprint: null } }))); + expect(sources[6].onlineProof.fingerprint).not.toBe(f.changed.onlineProof.fingerprint); + expect(sources.filter((_, index) => index !== 6)).toEqual(f.sources.filter((_, index) => index !== 6)); + expect(readRemoteWorkspaceAuthority((await stored(f.workspaceId)).metadata)?.snapshotId).toBe(f.snapshot.id); + expect(await fs.readFile(path.join(f.cwd, "saved.txt"), "utf8")).toBe("saved legacy edits\n"); + await expect(f.apply()).resolves.toMatchObject({ applied: true, replayed: true }); + expect(await db.select().from(workspaceOperations)).toHaveLength(1); + expect(await db.select().from(executionWorkspaceSnapshots)).toHaveLength(1); + }); + it.each(["reference", "allocation", "owner", "proof-version"] as const)("refuses a changed saved recovery %s on resume", async change => { + const f = await interruptedRecoveryFixture(); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.changed.runId)); + if (change === "reference" || change === "allocation") { + const reference: Record = { ...f.changed.reference, ...(change === "reference" ? { baselineSha256: "56".repeat(32) } : { providerLeaseId: randomUUID() }) }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { ...run.runnerProfileJson, nativeWorkspaceSync: reference } }) + .where(eq(heartbeatRuns.id, run.id)); + if (change === "allocation") await db.update(environmentLeases).set({ providerLeaseId: reference.providerLeaseId as string }) + .where(eq(environmentLeases.id, reference.leaseId as string)); + expect(await inspectOnlineLegacyWorkspaceRecoverySource(db, { workspace: await stored(f.workspaceId), runId: run.id })).not.toBeNull(); + } + if (change === "owner") await db.update(nativeRunFinalizations).set({ leaseOwner: "competing-finalizer", + leaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(nativeRunFinalizations.runId, run.id)); + if (change === "proof-version") { + const sources = f.sources.map((source, index) => index === 6 ? { ...source, onlineProof: { ...source.onlineProof, schema: "unsupported.v2" } } : source); + await db.update(workspaceOperations).set({ metadata: { ...f.operation.metadata, legacyRecoverySources: sources } }) + .where(eq(workspaceOperations.id, f.operation.id)); + } + const [before] = await db.select().from(workspaceOperations); + await expect(f.apply()).rejects.toThrow(change === "proof-version" ? "remote_workspace_migration_recovery_proof_invalid" + : change === "owner" ? "remote_copyback_unresolved" : "remote_workspace_migration_source_changed"); + expect(await db.select().from(workspaceOperations)).toEqual([before]); + expect(await db.select().from(executionWorkspaceSnapshots)).toEqual([f.snapshot]); + expect(readRemoteWorkspaceAuthority((await stored(f.workspaceId)).metadata)).toBeNull(); + expect(await fs.readFile(path.join(f.cwd, "saved.txt"), "utf8")).toBe("saved legacy edits\n"); + }); + it("still refuses recovery accounting changes within one admitted attempt", async () => { + const f = await recoveryFixture(), put = storage.putFile.bind(storage); + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.warning.id)); + vi.spyOn(storage, "putFile").mockImplementationOnce(async input => { + const result = await put(input); + await db.update(heartbeatRuns).set({ accountingAttemptCount: 1 }).where(eq(heartbeatRuns.id, f.run.id)); + return result; + }); + await expect(migrateRemoteWorkspace({ db, storage, ...f, apply: true })).rejects.toThrow("remote_workspace_migration_source_changed"); + expect(readRemoteWorkspaceAuthority((await stored(f.workspaceId)).metadata)).toBeNull(); + expect((await db.select().from(workspaceOperations))[0].status).toBe("running"); + }); + it("does not refresh a saved recovery proof before its finalization fence is acquired", async () => { + const f = await interruptedRecoveryFixture(), other = createDb(database.connectionString); + await db.update(heartbeatRuns).set({ accountingAttemptCount: 1 }).where(eq(heartbeatRuns.id, f.changed.runId)); + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const pending = new Promise(resolve => { release = resolve; }); + const held = other.transaction(async tx => { + expect(await tryLockNativeWorkspaceFinalization(tx as unknown as Db, { companyId: f.companyId, runId: f.changed.runId })).toBe(true); + entered(); await pending; + }); + await ready; + try { + await expect(f.apply()).rejects.toThrow("remote_copyback_owned"); + expect(await db.select().from(workspaceOperations)).toEqual([f.operation]); + expect(await db.select().from(executionWorkspaceSnapshots)).toEqual([f.snapshot]); + expect(readRemoteWorkspaceAuthority((await stored(f.workspaceId)).metadata)).toBeNull(); + } finally { release(); await held; await other.$client.end({ timeout: 1 }); } + }); async function artifactFailureFixture(descendant = false, cause: "runner_remote_provider_artifact_incompatible" | "native_session_interrupted" = "runner_remote_provider_artifact_incompatible") { const f = await recoveryFixture(descendant), statusVersion = 2; const profile = { ...f.run.runnerProfileJson, sessionCheckpoint: cause === "native_session_interrupted" From 09241442ea1d700b7e9dcb8cb1b627c29d81584e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:11:42 -0600 Subject: [PATCH 3/5] fix(server): let a native reviewer approve its review stage (#20373) 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 > - Execution policies can require an independent review stage before a task is done > - A native (Runner) agent that is the active reviewer had no way to record its decision > - `PATCH status: "done"` is refused for a native run that owns the task (#18411), and `paperclip_finish` accepts the report but leaves the stage pending > - The reviewer then searches the API until a deadline, and the task stays in review with nobody able to decide it > - This pull request records the final-stage approval on `PATCH` without releasing the run's lock, and lets the run's own finish report set the final status > - The benefit is that an agent reviewer can actually approve its review stage, in one short turn ## Linked Issues or Issue Description Refs #18411 (added the native status guard). Related: #20264 (explicit stage-decision operation, still open; this change is narrower and compatible with it). **What happened?** A native reviewer agent was woken as the active `review` participant. It read the deliverable and wrote its review in about 100 seconds. It then called `paperclip_finish` with `done`. The tool answered "Completion report accepted; the task's configured review stage is still pending". It then tried `PATCH /api/issues/{id}` with `status: "done"` and a comment. The route refused it with `native_run_status_reported_by_finish`. The agent searched the API for 2 more minutes and found no other path. The stage stayed pending. When the run ends with `done`, the status arbiter sees the pending stage and keeps the task in review (`governed_gate_pending`), so the stage can never resolve. **Expected behavior** The active review/approval participant can approve its stage from a native run. The task reaches `done` after the approval. The implementer still cannot approve. A run that is not the active participant still cannot change the task status. **Steps to reproduce** 1. Create a task with an execution policy that has one `review` stage with a native agent participant. 2. Move the task to `in_review` so the stage is pending and the reviewer agent wakes. 3. In the reviewer run, call `PATCH /api/issues/{id}` with `{ "status": "done", "comment": "Approved: ..." }`. 4. Observe `409 native_run_status_reported_by_finish`. Call `paperclip_finish` with `done` and observe that the stage stays pending. ## What Changed - `PATCH /api/issues/:id`: when the requester is the native run that holds the task lock and is the active participant, a `status: "done"` request on the final stage now records the approval decision (`executionState` completed, decision row, activity). The route removes `status` from the write, so the task stays `in_review` and the run keeps its execution lock. The run's `paperclip_finish` report then sets `done` through the normal status arbiter. - An intermediate-stage approval (which would hand the task to the next participant) and every other status change from such a run keep the existing `native_run_status_reported_by_finish` refusal. - `paperclip_finish` from the active participant (`done` or `needs_review`) while its stage is still pending is now rejected with the exact decision path, instead of being accepted with "stage still pending". - The native finalizer now treats the final-stage approval that the run itself recorded (read from the `issue_execution_decisions` row, bound to this run and agent) as the completion authority for its clean `done` report. Before this, a reviewer that cited free-text evidence had its report graded as incomplete, and the task was reopened as `in_progress` with a new wake for the reviewer. Failed verification, blocking remaining work, attention requests, other dispositions, and a still-pending stage keep the old outcome. - The reviewer/approver wake text names the decision path (`PATCH` with `status` and a required decision comment) and says a completion report does not record the decision. A Runner reviewer that needs changes is told to report them with `paperclip_block`, because a changes request from the run that owns the task is a reassignment that stops that run. - The locked review-policy recheck treats the deferred approval as a verdict, so a policy changed to `human_only` before the locked write still refuses it. ## Verification - `pnpm exec vitest run server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts server/src/__tests__/issue-execution-policy-routes.test.ts server/src/__tests__/issue-comment-reopen-routes.test.ts server/src/__tests__/issue-execution-policy.test.ts packages/adapter-utils/src/server-utils.test.ts`: 5 files, 595 tests pass. - `pnpm exec vitest run server/src/services/native-runtime/native-completion-feedback.test.ts`: 29 tests pass (embedded PostgreSQL), including the decision-row binding for `executionStageApprovedByRun`. - `pnpm exec vitest run server/src/services/native-runtime/status-arbiter.test.ts server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts server/src/services/native-runtime/native-stale-owner-completion.test.ts`: 72 tests pass. - New route tests fail without the route change (409 instead of 200/422) and pass with it. The new feedback test fails without the feedback change ("Completion report accepted" instead of a rejection). - `npx tsc --noEmit -p server` and `-p packages/adapter-utils`: pass. - A route test changes the review policy to `human_only` between the first check and the locked write; the deferred approval is refused (403). - Live full-stack chat eval `task-coordination.independent-review` (Runner, OpenCode) with this change: passed in GitHub Actions run 42705964209 (eval branch with the first two commits cherry-picked). The reviewer run recorded its approval 24 s after its review brief was released, reported `done` 14 s later, and the finalizer set the task to `done` with reason `execution_stage_approved`; total reviewer run 73 s. The earlier run 42702224713 exposed the finalizer evidence issue that the second commit fixes. ## Risks - Low to medium. The change is limited to one request shape: a native run, holding the lock, that is the active participant of a pending final stage, sending `status: "done"`. All other requests keep the old guard. - Between the approval and the finish report, the task shows `in_review` with a completed `executionState`. If the run fails before it reports, the existing native recovery owns the task, as for any other run. - Previous-release story: no persisted shape changes. A reviewer run that started before the deploy could not have recorded a deferred approval (the old route refused it), so the new finalizer input is false for it and the old outcome applies. - Intermediate-stage approvals and changes requests from native runs are still refused by the route. A Runner reviewer reports required changes with `paperclip_block`, which keeps the stage pending for a person. A self-service changes request needs the deferred handoff semantics in #20264. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code execution in Claude Code. ## 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 - [ ] All Paperclip CI gates are green - [ ] 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: Claude Opus 5.5 --- packages/adapter-utils/src/server-utils.ts | 3 + ...ue-agent-mutation-ownership-routes.test.ts | 86 +++++++++++++++++++ server/src/routes/issues.ts | 42 +++++++-- .../native-completion-feedback.test.ts | 34 +++++++- .../native-completion-feedback.ts | 11 +++ .../native-runtime/native-run-finalizer.ts | 25 ++++++ .../native-runtime/status-arbiter.test.ts | 19 ++++ .../services/native-runtime/status-arbiter.ts | 22 ++++- 8 files changed, 232 insertions(+), 10 deletions(-) diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.ts index 4fbd4ae8938..0e0da0d06c5 100644 --- a/packages/adapter-utils/src/server-utils.ts +++ b/packages/adapter-utils/src/server-utils.ts @@ -2983,6 +2983,9 @@ function renderPaperclipWakePromptBody( `You are waking as the active ${executionStage.wakeRole} for this issue.`, "Do not execute the task itself or continue executor work.", "Review the issue and choose one of the allowed actions above.", + "Record your decision on this issue with PATCH /api/issues/{issueId} and a required decision comment: approve with {\"status\":\"done\",\"comment\":\"...\"}, or request changes with {\"status\":\"in_progress\",\"comment\":\"...\"}.", + "A Paperclip Runner run cannot hand the task back itself; to request changes from one, report the required changes as a blocker with paperclip_block.", + "A run completion report does not record the decision; record it before you report.", "If you request changes, the workflow routes back to the stored return assignee.", "", ); diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts index 804847e4429..3aa93293e45 100644 --- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts +++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts @@ -3135,6 +3135,92 @@ describe("agent issue mutation checkout ownership", () => { expect(mockHeartbeatService.cancelRun).not.toHaveBeenCalled(); }); + describe("as the active review participant", () => { + const reviewStage = (id: string) => ({ id, type: "review", approvalsNeeded: 1, + participants: [{ id: `${id.slice(0, -1)}f`, type: "agent", agentId: ownerAgentId, userId: null }] }); + const reviewIssue = (stageIds: string[]) => makeIssue({ + status: "in_review", executionRunId: ownerRunId, checkoutRunId: ownerRunId, + executionPolicy: { mode: "normal", commentRequired: true, stages: stageIds.map(reviewStage) }, + executionState: { + status: "pending", currentStageId: stageIds[0], currentStageIndex: 0, currentStageType: "review", + currentParticipant: { type: "agent", agentId: ownerAgentId }, + returnAssignee: { type: "agent", agentId: peerAgentId }, + completedStageIds: [], lastDecisionId: null, lastDecisionOutcome: null, + }, + }); + const finalStage = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", laterStage = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + + it("records its final-stage approval and leaves the final status to its finish report", async () => { + const issue = reviewIssue([finalStage]); + mockIssueService.getById.mockResolvedValue(issue); + mockIssueService.update.mockImplementation(async (_id: string, patch: Record) => ({ ...issue, ...patch })); + const db = createRunContextDb(); + const inserted: Array<{ table: string; values: Record }> = []; + db.insert = vi.fn((table: Parameters[0]) => ({ values: vi.fn(async (values: Record) => { + inserted.push({ table: getTableName(table), values }); + }) })) as typeof db.insert; + + const res = await request(createApp(runActor(), db)).patch(`/api/issues/${issueId}`) + .send({ status: "done", comment: "Approved: verified the heading and signup action." }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + const patch = mockIssueService.update.mock.calls[0]?.[1] as Record; + // No status in the write: the service would otherwise release this + // run's execution lock before paperclip_finish reports the outcome. + expect(patch).not.toHaveProperty("status"); + expect(patch.executionState).toMatchObject({ status: "completed", lastDecisionOutcome: "approved", lastDecisionId: expect.any(String) }); + // The finalizer's completion authority reads exactly this row (executionStageApprovedByRun). + const decision = inserted.find(row => row.table === "issue_execution_decisions")?.values; + expect(decision).toMatchObject({ id: patch.executionState.lastDecisionId, companyId, issueId, stageId: finalStage, outcome: "approved", + actorAgentId: ownerAgentId, createdByRunId: ownerRunId, body: "Approved: verified the heading and signup action." }); + }); + + it("rechecks the review policy under the issue lock for the deferred approval", async () => { + const issue = reviewIssue([finalStage]); + mockIssueService.getById.mockResolvedValue(issue); + // The policy becomes human-only after the first check, before the locked write. + mockIssueService.getByIdForUpdate.mockResolvedValue({ ...issue, reviewPolicy: "human_only" }); + + const res = await request(createApp(runActor())).patch(`/api/issues/${issueId}`) + .send({ status: "done", comment: "Approved: verified." }); + + expect(res.status, JSON.stringify(res.body)).toBe(403); + expect(mockIssueService.update).not.toHaveBeenCalled(); + }); + + it("still requires the decision comment", async () => { + mockIssueService.getById.mockResolvedValue(reviewIssue([finalStage])); + + const res = await request(createApp(runActor())).patch(`/api/issues/${issueId}`).send({ status: "done" }); + + expect(res.status, JSON.stringify(res.body)).toBe(422); + expect(mockIssueService.update).not.toHaveBeenCalled(); + }); + + it("keeps refusing an intermediate approval that would hand the task to the next participant", async () => { + mockIssueService.getById.mockResolvedValue(reviewIssue([finalStage, laterStage])); + + const res = await request(createApp(runActor())).patch(`/api/issues/${issueId}`) + .send({ status: "done", comment: "Approved." }); + + expect(res.status, JSON.stringify(res.body)).toBe(409); + expect(res.body.details).toMatchObject({ code: "native_run_status_reported_by_finish", requestedStatus: "done" }); + expect(mockIssueService.update).not.toHaveBeenCalled(); + }); + + it("keeps refusing the approval when this run is not the active participant", async () => { + const issue = reviewIssue([finalStage]); + mockIssueService.getById.mockResolvedValue({ ...issue, + executionState: { ...(issue.executionState as unknown as Record), currentParticipant: { type: "agent", agentId: peerAgentId } } }); + + const res = await request(createApp(runActor())).patch(`/api/issues/${issueId}`) + .send({ status: "done", comment: "Approved." }); + + expect(res.status, JSON.stringify(res.body)).toBe(409); + expect(mockIssueService.update).not.toHaveBeenCalled(); + }); + }); + it("still lets the run edit other fields of its task", async () => { const res = await request(createApp(runActor())).patch(`/api/issues/${issueId}`).send({ title: "Renamed by its run" }); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index d377db61f49..88f2e545dc3 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -14540,12 +14540,21 @@ export function issueRoutes( * Conversation tasks are excluded: a conversation turn settles from its final * reply (nativeConversationReplyResult), not from a runner tool, so a reply * that moves the conversation to review still settles without the lock. + * + * The one status-shaped request a run must be able to send is the active + * review/approval participant's approval (`status: "done"` with its decision + * comment): no runner tool records a stage decision, so refusing it leaves + * the stage pending forever. With `allowStageApproval` the guard returns + * "defer_final_status" for that request instead of refusing it. The caller + * records the decision and keeps the task (and the run's lock) in review; + * the run's own paperclip_finish report then sets the final status. */ async function assertNativeRunKeepsOwnExecutionLock( req: Request, - issue: { companyId: string; status: string; parentId: string | null; assigneeAgentId: string | null; assigneeUserId: string | null; checkoutRunId: string | null; executionRunId: string | null; conversationAgentId?: string | null; conversationUserId?: string | null }, + issue: { companyId: string; status: string; parentId: string | null; assigneeAgentId: string | null; assigneeUserId: string | null; checkoutRunId: string | null; executionRunId: string | null; conversationAgentId?: string | null; conversationUserId?: string | null; executionState?: unknown }, requestedStatus: unknown = req.body.status, - ) { + options: { allowStageApproval?: boolean } = {}, + ): Promise<"defer_final_status" | undefined> { const runId = req.actor.type === "agent" ? req.actor.runId : null; if (!runId || !req.actor.agentId || req.actor.agentId !== issue.assigneeAgentId) return; if (runId !== issue.executionRunId && runId !== issue.checkoutRunId) return; @@ -14558,6 +14567,10 @@ export function issueRoutes( const run = await heartbeat.getRun(runId); if (!run || run.runtimeMode !== "native" || run.status !== "running" || run.agentId !== req.actor.agentId || run.companyId !== issue.companyId) return; + if (options.allowStageApproval && requestedStatus === "done" && issue.status === "in_review" && + activeExecutionParticipantAgentId(issue) === req.actor.agentId) { + return "defer_final_status"; + } // A blocker that the dependency rules reject anyway keeps its specific // error; otherwise the run reports the block with paperclip_block. if (Array.isArray(req.body.blockedByIssueIds) && req.body.blockedByIssueIds.length > 0) { @@ -14566,7 +14579,11 @@ export function issueRoutes( blockedByIssueIds: req.body.blockedByIssueIds, parentIssueId: issue.parentId, }); } - throw conflict( + throw nativeRunStatusReportedByFinish(requestedStatus); + } + + function nativeRunStatusReportedByFinish(requestedStatus: unknown) { + return conflict( "This run owns the task's execution, so it cannot change the task status directly; doing so would end its access to the task before it reports. " + "Report the outcome with paperclip_finish instead: reportedWorkDisposition \"needs_review\" for review, \"done\" when complete, or \"yielded\" with continuation.kind \"monitor\" to wait on a scheduled monitor. " + "Use paperclip_block for a blocker. Paperclip sets the task status from that report.", @@ -14682,7 +14699,7 @@ export function issueRoutes( ); if (!existing) return; if (!(await assertIssueReadAllowed(req, res, existing))) return; - await assertNativeRunKeepsOwnExecutionLock(req, existing); + const nativeStageApproval = await assertNativeRunKeepsOwnExecutionLock(req, existing, req.body.status, { allowStageApproval: true }); if (req.body.expectedStatusVersion !== undefined && ( existing.statusVersion !== req.body.expectedStatusVersion || existing.status !== "backlog" )) { @@ -15233,6 +15250,18 @@ export function issueRoutes( throw unprocessable("Snapshot-guarded policy updates cannot change task status or ownership"); } Object.assign(updateFields, transition.patch); + let deferredNativeStageApproval = false; + if (nativeStageApproval === "defer_final_status") { + // Only the final stage's approval is deferred. Anything else this + // request would do (an intermediate approval that hands the task to the + // next participant, or no decision at all) keeps the ordinary refusal. + const finalApproval = transition.decision?.outcome === "approved" && updateFields.status === "done" && + (transition.patch.assigneeAgentId === undefined || transition.patch.assigneeAgentId === existing.assigneeAgentId) && + transition.patch.assigneeUserId === undefined; + if (!finalApproval) throw nativeRunStatusReportedByFinish(req.body.status); + delete updateFields.status; + deferredNativeStageApproval = true; + } const nextStatus = updateFields.status ?? existing.status; if (updateFields.unblockDescriptor && nextStatus !== "blocked") { @@ -15659,10 +15688,13 @@ export function issueRoutes( const lockedPolicyChangeRequested = req.body.reviewPolicy !== undefined && req.body.reviewPolicy !== lockedExisting.reviewPolicy; + // A deferred native approval is still a review verdict even though + // its status write is left to the run's finish report. const lockedReviewVerdictRequested = lockedExisting.status === "in_review" && (updateFields.status === "done" || - updateFields.status === "cancelled"); + updateFields.status === "cancelled" || + deferredNativeStageApproval); if ( (lockedReviewVerdictRequested || lockedPolicyChangeRequested) && lockedExisting.reviewPolicy != null && diff --git a/server/src/services/native-runtime/native-completion-feedback.test.ts b/server/src/services/native-runtime/native-completion-feedback.test.ts index ad9ba109e86..e5b3132393c 100644 --- a/server/src/services/native-runtime/native-completion-feedback.test.ts +++ b/server/src/services/native-runtime/native-completion-feedback.test.ts @@ -1,11 +1,12 @@ import { createHash, randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { agents, companies, createDb, documentRevisions, executionWorkspaces, executionWorkspaceRepositories, heartbeatRuns, issues, issueThreadInteractions, issueTreeHolds, issueDocuments } from "@paperclipai/db"; +import { agents, companies, createDb, documentRevisions, executionWorkspaces, executionWorkspaceRepositories, heartbeatRuns, issueExecutionDecisions, issues, issueThreadInteractions, issueTreeHolds, issueDocuments } from "@paperclipai/db"; import { startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js"; import type { PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js"; import { documentService } from "../documents.js"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; +import { executionStageApprovedByRun } from "./native-run-finalizer.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; const done: PrpStructuredRunResult = { @@ -43,6 +44,37 @@ describe("native final-response feedback", () => { } }) as { downloadPath: string }; return { ...done, evidence: [{ ref: `${receipt.downloadPath}#download` }] }; } + it("sends the active review participant to record its stage decision before reporting", async () => { + const value = await fixture(), stageId = randomUUID(), otherAgentId = randomUUID(); + await db.insert(agents).values({ id: otherAgentId, companyId: value.companyId, name: "Implementer", adapterType: "paperclip_runner", status: "active" }); + const pending = { status: "pending", currentStageId: stageId, currentStageIndex: 0, currentStageType: "review", + currentParticipant: { type: "agent", agentId: value.agentId }, returnAssignee: { type: "agent", agentId: otherAgentId }, + completedStageIds: [], lastDecisionId: null, lastDecisionOutcome: null }; + await db.update(issues).set({ status: "in_review", executionState: pending }).where(eq(issues.id, value.issueId)); + // The retained failure: the reviewer's finish was accepted while its own + // stage stayed pending, and nothing it could call afterwards decided it. + await expect(nativeCompletionFeedback(db, value.runId, done)).rejects.toThrow(/active review participant[\s\S]*PATCH \/api\/issues\/\{id\}/); + await expect(nativeCompletionFeedback(db, value.runId, { ...done, reportedWorkDisposition: "needs_review" })).rejects.toThrow("does not record your review decision"); + // Someone else's pending stage is still explained, not attributed to this run. + await db.update(issues).set({ executionState: { ...pending, currentParticipant: { type: "agent", agentId: otherAgentId } } }).where(eq(issues.id, value.issueId)); + await expect(nativeCompletionFeedback(db, value.runId, done)).resolves.toContain("configured review stage is still pending"); + // Once the participant's approval is recorded, its report is accepted. + await db.update(issues).set({ executionState: { ...pending, status: "completed", completedStageIds: [stageId], lastDecisionId: randomUUID(), lastDecisionOutcome: "approved" } }).where(eq(issues.id, value.issueId)); + await expect(nativeCompletionFeedback(db, value.runId, done)).resolves.not.toContain("review stage"); + }); + it("binds final-stage approval authority to the decision row this run wrote", async () => { + const value = await fixture(), stageId = randomUUID(), decisionId = randomUUID(); + const run = { id: value.runId, companyId: value.companyId, agentId: value.agentId }; + const completed = { status: "completed", currentStageId: null, completedStageIds: [stageId], lastDecisionId: decisionId, lastDecisionOutcome: "approved" }; + await db.insert(issueExecutionDecisions).values({ id: decisionId, companyId: value.companyId, issueId: value.issueId, stageId, stageType: "review", + actorAgentId: value.agentId, outcome: "approved", body: "Approved: verified.", createdByRunId: value.runId }); + expect(await executionStageApprovedByRun(db, run, { id: value.issueId, executionState: completed })).toBe(true); + // Another run's decision, a pending stage, or a changes request grants nothing. + expect(await executionStageApprovedByRun(db, { ...run, id: randomUUID() }, { id: value.issueId, executionState: completed })).toBe(false); + expect(await executionStageApprovedByRun(db, run, { id: value.issueId, executionState: { ...completed, status: "pending" } })).toBe(false); + expect(await executionStageApprovedByRun(db, run, { id: value.issueId, executionState: { ...completed, lastDecisionOutcome: "changes_requested" } })).toBe(false); + expect(await executionStageApprovedByRun(db, run, { id: value.issueId, executionState: { ...completed, lastDecisionId: randomUUID() } })).toBe(false); + }); it("rejects a duplicate approval report for the exact pending tool-action card", async () => { const value = await fixture(), interactionId = randomUUID(); await db.insert(issueThreadInteractions).values({ id: interactionId, companyId: value.companyId, issueId: value.issueId, diff --git a/server/src/services/native-runtime/native-completion-feedback.ts b/server/src/services/native-runtime/native-completion-feedback.ts index 941edb16daf..4b9f4c2c87e 100644 --- a/server/src/services/native-runtime/native-completion-feedback.ts +++ b/server/src/services/native-runtime/native-completion-feedback.ts @@ -151,6 +151,17 @@ export async function nativeCompletionFeedback( "The done report includes unfinished work, failed verification, or an outstanding decision. Finish the work or report the concrete blocker/reviewer request. No human completion approval was created.", ); } + const stage = record(issue.executionState), participant = record(stage.currentParticipant); + if (stage.status === "pending" && participant.type === "agent" && participant.agentId === run.agentId && + issue.executionRunId === run.id && ["done", "needs_review"].includes(result.reportedWorkDisposition)) { + // The active review/approval participant decides the stage on the task + // itself. A finish report cannot record that decision, so accepting it + // would leave the stage pending with nobody left to decide it. + const stageType = typeof stage.currentStageType === "string" ? stage.currentStageType : "review"; + throw new Error(`You are the active ${stageType} participant on this task. A finish report does not record your ${stageType} decision, so this report was not accepted. ` + + `To approve, record the decision first with paperclip_call_api operationId "PATCH /api/issues/{id}" for this task and {"status":"done","comment":""}, then report this run with paperclip_finish. ` + + "To request changes, or if you cannot decide, report the required changes or the concrete blocker with paperclip_block."); + } if (["done", "cancelled"].includes(issue.status)) { return `Report accepted; task is already ${issue.status}. This report will not reopen it.`; } diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 52d3aa178fc..7937e7dceb5 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -45,6 +45,7 @@ import { heartbeatRuns, heartbeatRunEvents, issueComments, + issueExecutionDecisions, issueThreadInteractions, issues, nativeRunFinalizations, @@ -162,6 +163,29 @@ export function resolveNativeFinalizerStatus( export { pendingNativeGovernance } from "./native-governance.js"; +/** + * Whether this run recorded the approval that completed the issue's final + * execution-policy stage. Read from the saved decision row, never from the + * model's report. + */ +export async function executionStageApprovedByRun( + db: Db, + run: { id: string; companyId: string; agentId: string }, + issue: { id: string; executionState: unknown }, +): Promise { + const state = record(issue.executionState); + if (state.status !== "completed" || state.lastDecisionOutcome !== "approved" || typeof state.lastDecisionId !== "string") return false; + const [decision] = await db.select({ id: issueExecutionDecisions.id }).from(issueExecutionDecisions).where(and( + eq(issueExecutionDecisions.id, state.lastDecisionId), + eq(issueExecutionDecisions.companyId, run.companyId), + eq(issueExecutionDecisions.issueId, issue.id), + eq(issueExecutionDecisions.outcome, "approved"), + eq(issueExecutionDecisions.actorAgentId, run.agentId), + eq(issueExecutionDecisions.createdByRunId, run.id), + )).limit(1); + return Boolean(decision); +} + async function acceptedInteractionFromRun(input: { db: Db; companyId: string; @@ -1548,6 +1572,7 @@ export async function finalizeNativeRun(input: { const qualityReview = await readRequiredQualityReview(input.db, authoritativeIssue); const statusInput: Parameters[0] = { requiredQualityReviewSatisfied: qualityReview.satisfied, + executionStageApprovedByRun: await executionStageApprovedByRun(input.db, run, authoritativeIssue), caseHandoffAuthorized: Boolean(await assertNativeCaseHandoffResult(input.db, run.id, authoritativeIssue.id, result)), monitorWaitDispatched: monitorDelivery !== null, monitorWaitPreserved: preservedMonitorWait !== null, diff --git a/server/src/services/native-runtime/status-arbiter.test.ts b/server/src/services/native-runtime/status-arbiter.test.ts index a90d98eadc3..0eb079e508d 100644 --- a/server/src/services/native-runtime/status-arbiter.test.ts +++ b/server/src/services/native-runtime/status-arbiter.test.ts @@ -44,6 +44,25 @@ function arbitrate( } describe("native status authority", () => { + it("completes a reviewer's done report from its own recorded final-stage approval", () => { + // Retained live failure: the reviewer approved its stage, then cited free-text + // evidence; the report was graded as incomplete and the task reopened. + const freeText = assessment({ objectiveSatisfied: false, allCriteriaSatisfied: false, verificationPassed: false }); + expect(arbitrate({ assessment: freeText, priorIssueStatus: "in_review" })) + .toMatchObject({ toStatus: "in_progress", reasonCode: "completion_evidence_incomplete" }); + expect(arbitrate({ assessment: freeText, priorIssueStatus: "in_review", executionStageApprovedByRun: true })) + .toMatchObject({ toStatus: "done", reasonCode: "execution_stage_approved" }); + // The decision authorizes completion only for a clean done report. + expect(arbitrate({ assessment: { ...freeText, hasBlockingRemainingWork: true }, priorIssueStatus: "in_review", executionStageApprovedByRun: true })) + .not.toMatchObject({ toStatus: "done" }); + expect(arbitrate({ assessment: { ...freeText, hasFailedVerification: true }, priorIssueStatus: "in_review", executionStageApprovedByRun: true })) + .not.toMatchObject({ toStatus: "done" }); + expect(arbitrate({ assessment: { ...freeText, reportedDisposition: "needs_review" }, priorIssueStatus: "in_review", executionStageApprovedByRun: true })) + .not.toMatchObject({ toStatus: "done" }); + // A still-pending stage keeps governing the task. + expect(arbitrate({ assessment: freeText, priorIssueStatus: "in_review", executionStageApprovedByRun: true, governanceGate: { kind: "execution_stage", id: "run" } })) + .toMatchObject({ toStatus: "in_review", reasonCode: "governed_gate_pending" }); + }); it("cannot complete an explicitly required quality review from claims or file evidence", () => { expect(arbitrate({ completionClaimPolicyAccepted: true, requiredQualityReviewSatisfied: false })) .toMatchObject({ toStatus: "in_progress", reasonCode: "required_quality_review_incomplete" }); diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index ba5bf640d92..89b62d3028c 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -168,6 +168,12 @@ export function arbitrateNativeStatus(input: { reviewOwnerUserId?: string | null; /** Review decisions own task state; a reviewer's finish report cannot override them. */ nativeReviewOutcome?: "resolved" | "pending" | "stale"; + /** + * This run, as the configured participant, recorded the approval that + * completed the task's final execution-policy stage. That durable decision is + * the completion authority for its done report, as the policy intends. + */ + executionStageApprovedByRun?: boolean; /** Re-derived from the committed runner terminal and pinned execution identity. */ providerModelRejected?: boolean; providerOverloaded?: boolean; @@ -439,7 +445,13 @@ export function arbitrateNativeStatus(input: { !input.assessment.hasFailedVerification && input.assessment.attentionRequests.length === 0 && !input.assessment.hasBlockingRemainingWork; - const complete = evidenceComplete || policyClaimComplete; + const stageApprovalComplete = + input.executionStageApprovedByRun === true && + input.assessment.reportedDisposition === "done" && + !input.assessment.hasFailedVerification && + input.assessment.attentionRequests.length === 0 && + !input.assessment.hasBlockingRemainingWork; + const complete = evidenceComplete || policyClaimComplete || stageApprovalComplete; if (complete && input.hasPendingChildCompletion) { return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, @@ -456,9 +468,11 @@ export function arbitrateNativeStatus(input: { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, statusAction: "done", toStatus: "done", - reasonCode: input.completionClaimPolicyAccepted - ? "completion_claim_policy_accepted" - : "completion_contract_satisfied", + reasonCode: !evidenceComplete && !policyClaimComplete + ? "execution_stage_approved" + : input.completionClaimPolicyAccepted + ? "completion_claim_policy_accepted" + : "completion_contract_satisfied", unblockDescriptor: null, effects: [{ kind: "release_checkout" }], }; From d95fdd8d79e0db0e9e83386f1162cbf01ef44e2f Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 9 Nov 2026 15:27:58 -0800 Subject: [PATCH 4/5] feat(observability): span the unnamed gaps in run preparation (#20396) 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 task reaches the agent, the server prepares the run: it reads the task, the workspace and the configuration, and then hands the run to the native controller > - With an OTLP endpoint, each preparation step emits a `heartbeat.prepare.` or `native.controller.` span > - On a hosted test deployment, 0.3 to 0.5 s of each `task.prepare` sits between those spans, and about 0.5 s more sits between `execution.dispatch_admission` and `native.coordinator.claim` > - Nobody can say which step is slow in that time, so latency work in this area is guesswork > - This pull request adds spans around the existing awaited work in those gaps, with the existing timing helpers and naming conventions > - The benefit is that a trace of a slow preparation now names the step that used the time ## Linked Issues or Issue Description **What existing behavior does this improve?** The OpenTelemetry trace of task preparation. Today it has unnamed gaps between the named preparation spans. **Subsystem affected** Server: heartbeat run preparation and the native controller (`server/src/services/heartbeat.ts`, `server/src/services/native-runtime/native-session-executor.ts`). **Current behavior** On a hosted test deployment (8 runs per group), `task.prepare` takes 2.6 to 3.4 s. Between `heartbeat.prepare.runtime_state` and `heartbeat.prepare.run_identity`, about 0.25 s has no span. Between `execution.dispatch_admission` and `native.coordinator.claim`, about 0.5 s has no span, and in one pair of runs it was 1.4 s. Nobody can tell which step used that time. **Proposed behavior** Spans name the existing awaited reads and writes in those gaps. The change adds no reads and records no content. The operator endpoint gate and the no-operation behaviour stay. **Reason and benefit** Latency work in this area needs a measurement. With these spans, a trace of a slow preparation names the step that used the time, so a fix can be confirmed or rejected after deployment. **Breaking changes** None. The change adds span names to the closed list. It changes no API, schema or behaviour. **Additional context** The server uses postgres.js, which the auto-instrumentation does not cover, so database spans do not fill these gaps. ## What Changed - `server/src/services/execution-preparation-timing.ts`: add the new closed phase names. - `server/src/services/heartbeat.ts`: add `heartbeat.prepare.*` spans for `chat_retry_admission`, `workspace_selection`, `dependency_readiness`, `issue_checkout`, `instance_settings`, `workspace_context`, `project_context`, `plan_wake_routing`, `routine_environment`, `responsible_user` and `execution_start`. The re-reads of the issue after a checkout use the existing `issue_context` name. - `server/src/services/native-runtime/native-session-executor.ts`: add `native.controller.*` spans for `attachment_staging`, `warm_restore`, `span_persistence` (persistence of the preparation spans to the run log) and `state_migration` before the coordinator claim. - `doc/observability.md`: list the new spans. - `server/src/__tests__/heartbeat-preparation-gap-spans.test.ts`: run a real heartbeat through native preparation with an in-memory span exporter. Check that each new span is emitted and that the new preparation spans are children of `task.execution_attempt`. ## Verification - `pnpm --filter @paperclipai/server typecheck` - `npx vitest run src/__tests__/heartbeat-preparation-gap-spans.test.ts` (fails without the source change, passes with it) - `npx vitest run src/services/heartbeat/preparation-timing-context.test.ts src/services/execution-preparation-timing.test.ts src/services/native-runtime/native-session-executor.test.ts src/__tests__/heartbeat-context-compaction-execution.test.ts` ## Risks - Low risk. The change only wraps existing awaited calls. Values and errors pass through the timing helper unchanged, and a checkout conflict still reaches the same `catch`. - Phases of 50 ms or more inside `heartbeat.prepare.*` are also written to the run log, as for the existing phases. This adds a few run-log rows on slow runs. - Without an OTLP endpoint, the helpers keep their current no-operation behaviour. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, test runs) and extended thinking. ## 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: Claude Opus 5.5 --- doc/observability.md | 10 +- .../heartbeat-preparation-gap-spans.test.ts | 138 ++++++++++++++++++ .../services/execution-preparation-timing.ts | 6 +- server/src/services/heartbeat.ts | 110 +++++++------- .../native-runtime/native-session-executor.ts | 43 +++--- 5 files changed, 234 insertions(+), 73 deletions(-) create mode 100644 server/src/__tests__/heartbeat-preparation-gap-spans.test.ts diff --git a/doc/observability.md b/doc/observability.md index c68ca2820e3..69c9d899cdf 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -236,6 +236,12 @@ Early context preparation also records `agent_read`, `chat_completion`, `conversation`, `runtime_state`, `issue_context`, `run_identity`, `trust_preset`, and `task_context` beneath `heartbeat.prepare`. These time the existing awaited operations before environment selection; they do not add reads or record content. +The work between those phases is named too: `chat_retry_admission`, +`workspace_selection`, `dependency_readiness`, `issue_checkout`, +`instance_settings`, `workspace_context`, `project_context`, +`plan_wake_routing`, `routine_environment` and `responsible_user`. +`execution_start` times the run and agent status writes and the "run started" +event before run output starts. A repeated read or write has its own span. Execution configuration also records separate phases for mentioned skills, GitHub identity selection, secret resolution, managed AI runtime preparation, @@ -297,7 +303,9 @@ The `paperclip.native-controller` tracer records backend construction, connector assignments, assigned MCP discovery, tool authority, companion selection and Runner binary resolution. It also records GitHub shutdown, coordinator release, instruction checkpoints and collection, -and warm-session release. These intervals can occur between the existing native +and warm-session release. Before the coordinator claim it also records +attachment staging, warm controller restore, persistence of the preparation +spans to the run log, and Runner state migration. These intervals can occur between the existing native preparation, execution and settlement spans. They are controller work, not model turn time, and carry only the existing run hash. Nested phases overlap their containing backend or lifecycle intervals; do not add both durations. diff --git a/server/src/__tests__/heartbeat-preparation-gap-spans.test.ts b/server/src/__tests__/heartbeat-preparation-gap-spans.test.ts new file mode 100644 index 00000000000..e9e63f45ee1 --- /dev/null +++ b/server/src/__tests__/heartbeat-preparation-gap-spans.test.ts @@ -0,0 +1,138 @@ +import { randomUUID } from "node:crypto"; +import { context, trace } from "@opentelemetry/api"; +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"; +import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace"; +import { eq } from "drizzle-orm"; +import { agents, authUsers, companyMemberships, createDb, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import type { NativeRunIdentity, NativeSession, NativeSessionBackend, PrpEvent } from "@paperclipai/paperclip-runner"; +import { describe, expect, it, vi } from "vitest"; +import { heartbeatService, type HeartbeatServiceOptions } from "../services/heartbeat.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; +import { closeIdleWarmNativeSessionsForRestart } from "../services/native-runtime/native-session-executor.js"; +import { nativeRestartFixture, waitForCondition } from "./helpers/native-restart-fixture.js"; +import { getRecoveryPostgresSupport } from "./helpers/recovery-postgres-fixture.js"; + +const support = await getRecoveryPostgresSupport({}); + +function completingBackend(db: ReturnType): NonNullable { + return execution => { + let identity: NativeRunIdentity; + let sourceInstanceId = ""; + let turn = Promise.withResolvers(); + const capabilities = { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }; + const session: NativeSession = { + identity: () => identity, + capabilities: async () => capabilities, + attachRun: async input => { identity = input.identity; }, + startTurn: async () => { + const turnId = randomUUID(); + turn.resolve(turnId); + return { turnId }; + }, + async *events() { + const turnId = await turn.promise; + const event = (sourceSeq: number, eventType: PrpEvent["eventType"], payload: Record): PrpEvent => ({ + schema: "paperclip.prp.event.v1", sourceKind: "runner", sourceInstanceId, + sourceEventId: `${sourceInstanceId}:${identity.runId}:${sourceSeq}`, sourceSeq, + runId: identity.runId, normalizedSessionId: identity.sessionId, turnId, + schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), eventType, payload, + }); + yield event(1, "turn.started", {}); + yield event(2, "item.completed", { kind: "agentMessage", channel: "final", text: "Done." }); + turn = Promise.withResolvers(); + yield event(3, "turn.completed", { status: "completed" }); + }, + result: async () => null, + snapshot: async () => ({ backendKind: "mock", sessionId: "gap-spans-session", identity, + providerSessionId: "gap-spans-provider-session", cursor: null, activeTurnId: null, pendingRuntimeRequests: [], lineage: [] }), + close: async () => {}, + }; + const backend: NativeSessionBackend = { + descriptor: async () => { + const [run] = await db.select({ runnerInstanceId: heartbeatRuns.runnerInstanceId }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, execution.binding.runId)); + if (!run?.runnerInstanceId) throw new Error("Normal native admission did not persist a runner identity"); + sourceInstanceId = run.runnerInstanceId; + return { kind: "mock", name: "preparation-gap-spans", version: "1", capabilities, + runtimeContextCapabilities: { instructions: "native", skills: "native", mcp: "native" } }; + }, + openSession: async input => { identity = input.identity; return session; }, + recoverSession: async snapshot => { identity = snapshot.identity; return { recovered: true, session }; }, + }; + return backend; + }; +} + +describe.skipIf(!support.supported)("heartbeat preparation gap spans", () => { + const fixture = nativeRestartFixture({}); + + it("emits spans for the work between the named preparation phases", async () => { + const { companyId, agentId, temporary } = fixture.current; + const db = createDb(temporary.connectionString, { maxConnections: 4 }); + const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT; + vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test"); + const manager = new AsyncLocalStorageContextManager().enable(); + const exporter = new InMemorySpanExporter(); + const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter })] }); + expect(context.setGlobalContextManager(manager)).toBe(true); + expect(trace.setGlobalTracerProvider(provider)).toBe(true); + const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: completingBackend(db) }); + try { + const userId = randomUUID(); + await db.insert(authUsers).values({ id: userId, name: "Task owner", email: `${userId}@example.invalid`, + createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, membershipRole: "owner" }); + await db.update(agents).set({ status: "idle", adapterConfig: { provider: "codex", lifecycleMode: "warm", idleTimeoutMs: 60_000 } }) + .where(eq(agents.id, agentId)); + await instanceSettingsService(db).updateExperimental({ enableAgentChat: true, enableNativeRunner: true }); + const [issue] = await db.insert(issues).values({ companyId, title: "Trace the preparation gaps", status: "in_progress", + assigneeAgentId: agentId, responsibleUserId: userId, conversationAgentId: agentId, conversationUserId: userId, + conversationState: "active" }).returning(); + const [message] = await db.insert(issueComments).values({ companyId, issueId: issue!.id, + authorType: "user", authorUserId: userId, body: "Start." }).returning(); + const run = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", reason: "issue_commented", + requestedByActorType: "user", requestedByActorId: userId, manualUserWake: true, + payload: { issueId: issue!.id, commentId: message!.id }, + contextSnapshot: { issueId: issue!.id, taskKey: issue!.id, wakeCommentId: message!.id } }); + expect(run).not.toBeNull(); + await waitForCondition("the run to settle", () => heartbeat.getTaskDrainStatus().quiescent); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id)))[0]) + .toMatchObject({ status: "succeeded" }); + + await provider.forceFlush(); + const spans = exporter.getFinishedSpans(); + const names = new Set(spans.map(span => span.name)); + const preparation = [ + "heartbeat.prepare.chat_retry_admission", + "heartbeat.prepare.workspace_selection", + "heartbeat.prepare.dependency_readiness", + "heartbeat.prepare.instance_settings", + "heartbeat.prepare.workspace_context", + "heartbeat.prepare.plan_wake_routing", + "heartbeat.prepare.routine_environment", + "heartbeat.prepare.responsible_user", + "heartbeat.prepare.execution_start", + ]; + const controller = [ + "native.controller.attachment_staging", + "native.controller.warm_restore", + "native.controller.span_persistence", + "native.controller.state_migration", + ]; + for (const name of [...preparation, ...controller]) expect(names, name).toContain(name); + const attempts = spans.filter(span => span.name === "task.execution_attempt"); + expect(attempts).toHaveLength(1); + for (const span of spans.filter(span => preparation.includes(span.name))) { + expect(span.parentSpanContext?.spanId, span.name).toBe(attempts[0]!.spanContext().spanId); + } + } finally { + await heartbeat.drainActiveRunExecutions(); + await closeIdleWarmNativeSessionsForRestart(); + await db.$client.end(); + vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", endpoint); + trace.disable(); + context.disable(); + await provider.shutdown(); + } + }, 60_000); +}); diff --git a/server/src/services/execution-preparation-timing.ts b/server/src/services/execution-preparation-timing.ts index d8753197a72..01041233d1a 100644 --- a/server/src/services/execution-preparation-timing.ts +++ b/server/src/services/execution-preparation-timing.ts @@ -7,6 +7,9 @@ import { isSpanContextValid, ROOT_CONTEXT, SpanStatusCode, trace, type Context } type PreparationPhase = "environment_selection" | "execution_configuration" | "session" | "agent_read" | "chat_completion" | "conversation" | "runtime_state" | "issue_context" | "run_identity" | "trust_preset" | "task_context" + | "chat_retry_admission" | "workspace_selection" | "dependency_readiness" | "issue_checkout" + | "instance_settings" | "workspace_context" | "project_context" | "plan_wake_routing" + | "routine_environment" | "responsible_user" | "execution_start" | "workspace" | "github_environment" | "github_launchers" | "run_output" | "workspace_validation" | "runtime_services" | "instructions" | "runtime_selection" | "configuration_mentions" | "configuration_github_identity" | "configuration_secrets" @@ -34,7 +37,8 @@ type PreparationPhase = "environment_selection" | "execution_configuration" | "s | "github_access" | "wake_binding" | "backend_setup" | "connector_assignments" | "assigned_mcp" | "tool_authority" | "companion_selection" | "runner_binary" | "github_stop" | "coordinator_release" | "instruction_checkpoint" - | "instruction_changes" | "warm_release" | "instruction_collection"; + | "instruction_changes" | "warm_release" | "instruction_collection" + | "attachment_staging" | "warm_restore" | "span_persistence" | "state_migration"; export type ExecutionPhase = | "skills.inventory" | "skills.inventory.wait" | "skills.inventory.bundled" | "skills.inventory.releases" diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index e00e1c6f1c1..bb08881e332 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -2153,7 +2153,7 @@ export function heartbeatService( contextSnapshot: context, })); }); - const isFailedChatRunRetry = await authorizeFailedChatRetryExecution(); + const isFailedChatRunRetry = await timePreparation("chat_retry_admission", () => authorizeFailedChatRetryExecution()); // Never adopt a chat-execution attestation supplied in a wake payload. // Reviewed chat turns rebuild it from the current durable owner below. delete context[PAPERCLIP_EXTERNAL_CHAT_EXECUTION_BOUND_KEY]; @@ -2208,28 +2208,31 @@ export function heartbeatService( const taskKey = deriveTaskKeyWithHeartbeatFallback(context, null); const sessionCodec = getAdapterSessionCodec(agent.adapterType); const issueId = readNonEmptyString(context.issueId); - const freshWorkspace = await readFreshWorkspaceReadiness(db, run); - if (issueId && canApplyTaskWorkspaceSelectionAtAdmission({ admittedInput: parseObject(run.runnerProfileJson).nativeExecutionInput, restarting: Boolean(runOptions.nativeRestartRecovery), hasLeaseOwner: Boolean(runOptions.nativeLeaseOwner) })) { - const changed = await executionWorkspacesSvc.applyPendingTaskWorkspaceSelection({ companyId: agent.companyId, - issueId, runId: run.id, actor: { type: "agent", agentId: agent.id, companyId: agent.companyId, source: "agent_key" } }); - // A subtask an older release bound to its parent's workspace gets its own - // here. A process-loss retry or a continuation that keeps the current - // workspace still finishes the interrupted attempt there first. - const released = run.processLossRetryCount > 0 || (freshWorkspace && freshWorkspace.mode !== "fresh_isolated_workspace") ? false - : await executionWorkspacesSvc.releaseAncestorWorkspaceBindingAtAdmission({ companyId: agent.companyId, issueId, runId: run.id }); - if (changed || released) { - delete context.resumeSessionParams; - delete context.resumeSessionDisplayId; - context.workspaceSelectionChanged = true; + const freshWorkspace = await timePreparation("workspace_selection", async () => { + const readiness = await readFreshWorkspaceReadiness(db, run); + if (issueId && canApplyTaskWorkspaceSelectionAtAdmission({ admittedInput: parseObject(run.runnerProfileJson).nativeExecutionInput, restarting: Boolean(runOptions.nativeRestartRecovery), hasLeaseOwner: Boolean(runOptions.nativeLeaseOwner) })) { + const changed = await executionWorkspacesSvc.applyPendingTaskWorkspaceSelection({ companyId: agent.companyId, + issueId, runId: run.id, actor: { type: "agent", agentId: agent.id, companyId: agent.companyId, source: "agent_key" } }); + // A subtask an older release bound to its parent's workspace gets its own + // here. A process-loss retry or a continuation that keeps the current + // workspace still finishes the interrupted attempt there first. + const released = run.processLossRetryCount > 0 || (readiness && readiness.mode !== "fresh_isolated_workspace") ? false + : await executionWorkspacesSvc.releaseAncestorWorkspaceBindingAtAdmission({ companyId: agent.companyId, issueId, runId: run.id }); + if (changed || released) { + delete context.resumeSessionParams; + delete context.resumeSessionDisplayId; + context.workspaceSelectionChanged = true; + } } - } + return readiness; + }); let issueContext = issueId ? await timePreparation("issue_context", () => getIssueExecutionContext(agent.companyId, issueId)) : null; const issueDependencyReadiness = issueId - ? await issuesSvc + ? await timePreparation("dependency_readiness", () => issuesSvc .listDependencyReadiness(agent.companyId, [issueId]) - .then((rows) => rows.get(issueId) ?? null) + .then((rows) => rows.get(issueId) ?? null)) : null; const dependencyResponse = issueId && issueContext?.status === "blocked" && context.dependencyBlockedInteraction === true @@ -2247,14 +2250,17 @@ export function heartbeatService( // dispatch: an operator parking the issue after claim but before this // checkout must not be overwritten by the continuation. A todo task // that has never started has nothing parked, so it may start here. - const startsUnstartedTask = issueContext.status === "todo" && - await isUnstartedTaskQuestionAnswer(db, { companyId: agent.companyId, issueId, interactionId: context.interactionId }); - await issuesSvc.checkout( - issueId, - agent.id, - [...resolvedInteractionCheckoutExpectedStatuses(), ...(startsUnstartedTask ? ["todo"] : [])], - run.id, - ); + const issueStatus = issueContext.status; + await timePreparation("issue_checkout", async () => { + const startsUnstartedTask = issueStatus === "todo" && + await isUnstartedTaskQuestionAnswer(db, { companyId: agent.companyId, issueId, interactionId: context.interactionId }); + await issuesSvc.checkout( + issueId, + agent.id, + [...resolvedInteractionCheckoutExpectedStatuses(), ...(startsUnstartedTask ? ["todo"] : [])], + run.id, + ); + }); context[PAPERCLIP_HARNESS_CHECKOUT_KEY] = true; } catch (error) { if (!isCheckoutConflictError(error)) throw error; @@ -2269,7 +2275,7 @@ export function heartbeatService( } throw error; } - issueContext = await getIssueExecutionContext(agent.companyId, issueId); + issueContext = await timePreparation("issue_context", () => getIssueExecutionContext(agent.companyId, issueId)); } if ( issueId && @@ -2286,18 +2292,18 @@ export function heartbeatService( }) ) { try { - await issuesSvc.checkout( + await timePreparation("issue_checkout", () => issuesSvc.checkout( issueId, agent.id, typeof context.workspaceReconstructionActionId === "string" ? ["todo"] : ["todo", "backlog", "blocked"], run.id, - ); + )); context[PAPERCLIP_HARNESS_CHECKOUT_KEY] = true; } catch (error) { if (!isCheckoutConflictError(error)) throw error; context[PAPERCLIP_HARNESS_CHECKOUT_KEY] = false; } - issueContext = await getIssueExecutionContext(agent.companyId, issueId); + issueContext = await timePreparation("issue_context", () => getIssueExecutionContext(agent.companyId, issueId)); } if ( issueId && @@ -2338,7 +2344,7 @@ export function heartbeatService( ) : null; const experimentalInstanceSettings = - await instanceSettings.getExperimental(); + await timePreparation("instance_settings", () => instanceSettings.getExperimental()); const isolatedWorkspacesEnabled = experimentalInstanceSettings.enableIsolatedWorkspaces; // Inert on its own: the operator default only reaches the resolver when @@ -2349,16 +2355,18 @@ export function heartbeatService( experimentalInstanceSettings.enableIsolatedWorkspacesByDefault; const providerApiPlacement = resolveProviderApiPlacement({ run, agent }); const externalProvider = heartbeatExternalProvider({ run, agent }) ?? providerApiPlacement?.provider; - const [taskWorkspaceIntentRow] = issueId && !externalProvider ? await db.select({ intent: issues.workspaceSelection }).from(issues) - .where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))) : []; + const [taskWorkspaceIntentRow] = issueId && !externalProvider ? await timePreparation("workspace_context", () => db.select({ intent: issues.workspaceSelection }).from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId)))) : []; const contextProjectId = readNonEmptyString(context.projectId); - const boundSourceWorkspace = !externalProvider && issueContext?.executionWorkspaceId - ? await executionWorkspacesSvc.getStoredById(agent.companyId, issueContext.executionWorkspaceId) : null; - const [selectedWorkspaceSource] = !externalProvider && !boundSourceWorkspace && issueContext?.projectWorkspaceId - ? await db.select({ projectId: projectWorkspaces.projectId }).from(projectWorkspaces) - .where(and(eq(projectWorkspaces.id, issueContext.projectWorkspaceId), eq(projectWorkspaces.companyId, agent.companyId))) : []; + const executionWorkspaceId = issueContext?.executionWorkspaceId; + const boundSourceWorkspace = !externalProvider && executionWorkspaceId + ? await timePreparation("workspace_context", () => executionWorkspacesSvc.getStoredById(agent.companyId, executionWorkspaceId)) : null; + const projectWorkspaceId = issueContext?.projectWorkspaceId; + const [selectedWorkspaceSource] = !externalProvider && !boundSourceWorkspace && projectWorkspaceId + ? await timePreparation("workspace_context", () => db.select({ projectId: projectWorkspaces.projectId }).from(projectWorkspaces) + .where(and(eq(projectWorkspaces.id, projectWorkspaceId), eq(projectWorkspaces.companyId, agent.companyId)))) : []; const loadProjectContext = async (projectId: string | null | undefined) => projectId - ? await db + ? await timePreparation("project_context", () => db .select({ id: projects.id, executionWorkspacePolicy: projects.executionWorkspacePolicy, @@ -2385,7 +2393,7 @@ export function heartbeatService( eq(projects.companyId, agent.companyId), ), ) - .then((rows) => rows[0] ?? null) + .then((rows) => rows[0] ?? null)) : null; const taskProjectId = issueContext ? issueContext.projectId : contextProjectId; const taskProjectContext = await loadProjectContext(taskProjectId); @@ -2407,14 +2415,14 @@ export function heartbeatService( readNonEmptyString(context.interactionStatus) === "accepted") : false; const acceptedPlanWakeRoutingDecision = issueContext - ? await resolveAcceptedPlanWakeRoutingDecision({ + ? await timePreparation("plan_wake_routing", () => resolveAcceptedPlanWakeRoutingDecision({ db, companyId: agent.companyId, agentId: agent.id, issueId, acceptedPlanContinuationWake, contextSnapshot: context, - }) + })) : null; if (acceptedPlanWakeRoutingDecision) { context.forceFreshSession = true; @@ -2434,17 +2442,17 @@ export function heartbeatService( } else { delete context.acceptedPlanWakeRouting; } - const routineEnvContext = await getRoutineEnvForExecutionIssue( + const routineEnvContext = await timePreparation("routine_environment", () => getRoutineEnvForExecutionIssue( agent.companyId, issueContext, - ); + )); let responsibleUserId: string | null = - await resolveResponsibleUserIdForRun({ + await timePreparation("responsible_user", () => resolveResponsibleUserIdForRun({ run, contextSnapshot: context, issueContext, routineEnvContext, - }); + })); const identityContext = await timePreparation("run_identity", () => initializeRunIdentity(db, { companyId: agent.companyId, runId: run.id, @@ -3231,7 +3239,7 @@ export function heartbeatService( } = { current: null }; try { const startedAt = run.startedAt ?? new Date(); - const runningWithSession = await db + const runningWithSession = await timePreparation("execution_start", () => db .update(heartbeatRuns) .set({ startedAt, @@ -3242,12 +3250,12 @@ export function heartbeatService( }) .where(eq(heartbeatRuns.id, run.id)) .returning() - .then((rows) => rows[0] ?? null); + .then((rows) => rows[0] ?? null)); if (runningWithSession) run = runningWithSession; // Pause Durability: flip to "running" ONLY if the agent is still invokable. // Atomic conditional UPDATE is the sole gate (no read-then-write); 0 rows => abort. - const runningAgent = await db + const runningAgent = await timePreparation("execution_start", () => db .update(agents) .set({ status: "running", updatedAt: new Date() }) .where( @@ -3258,7 +3266,7 @@ export function heartbeatService( ), ) .returning() - .then((rows) => rows[0] ?? null); + .then((rows) => rows[0] ?? null)); if (!runningAgent) { logger.warn( @@ -3300,12 +3308,12 @@ export function heartbeatService( }); const currentRun = run; - await appendRunEvent(currentRun, { + await timePreparation("execution_start", () => appendRunEvent(currentRun, { eventType: "lifecycle", stream: "system", level: "info", message: "run started", - }); + })); const { currentUserRedactionOptions, appendIdentityRedactedLog, onLog, onPersistedNativeLog, onAdapterMeta, onAdapterEvent } = await timePreparation("run_output", () => runOutput.begin(currentRun)); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index e8df4b0b52f..f0e9a0e335f 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -9533,9 +9533,10 @@ export async function executePaperclipNativeSession(input: { } return preparedInput; }; + const stageAttachments = () => createRunPreparationTiming(runId, "native.controller")("attachment_staging", prepareAttachments); return needsWarmRetirement - ? await executePaperclipNativeSessionWithinScope(input, prepareAttachments, false, ownDiagnosticLease) - : await executePaperclipNativeSessionWithinScope(await prepareAttachments(), undefined, false, ownDiagnosticLease); + ? await executePaperclipNativeSessionWithinScope(input, stageAttachments, false, ownDiagnosticLease) + : await executePaperclipNativeSessionWithinScope(await stageAttachments(), undefined, false, ownDiagnosticLease); } catch (error) { executionFailure = error; if (error instanceof NativeControllerRecoveryWaitingError) { @@ -9692,7 +9693,8 @@ async function executePaperclipNativeSessionAttempt( : null; const stagedRestart = input.restartRecovery?.kind === "reattach_remote_runner" ? await verifyStagedAttachmentRestart(input) : null; - if (input.useRunnerd) await restoreWarmRunnerdController(input); + const timeController = createRunPreparationTiming(input.execution.binding.runId, "native.controller"); + if (input.useRunnerd) await timeController("warm_restore", () => restoreWarmRunnerdController(input)); const identityRedactor = createAgentIdentityRedactor(input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY); const redactIdentityText = (text: string) => redactSensitiveText( identityRedactor.chunk("diagnostic", text) + identityRedactor.finish("diagnostic"), @@ -9718,7 +9720,6 @@ async function executePaperclipNativeSessionAttempt( "paperclip_runner_provider_unsupported: ACPX candidate requires exact host qualification authorization", ); } - const timeController = createRunPreparationTiming(input.execution.binding.runId, "native.controller"); const preparationSpans = input.preparationSpans ?? []; const preparationStarts = nativeRunPreparationStarts( preparationSpans, @@ -9772,20 +9773,22 @@ async function executePaperclipNativeSessionAttempt( startedAtMs: environmentStartedAtMs, }) : null; - for (const span of preparationSpans) { - const rootMilestone = isNativeRunRootHistoricalSpan(span.name); - await trace.record({ - ...span, - parentName: rootMilestone - ? "task.provider_session" - : environmentSpans.includes(span) - ? "environment.startup" - : "task.prepare", - }); - } - if (environmentScope) { - await trace.end(environmentScope, { endedAtMs: environmentEndedAtMs }); - } + await timeController("span_persistence", async () => { + for (const span of preparationSpans) { + const rootMilestone = isNativeRunRootHistoricalSpan(span.name); + await trace.record({ + ...span, + parentName: rootMilestone + ? "task.provider_session" + : environmentSpans.includes(span) + ? "environment.startup" + : "task.prepare", + }); + } + if (environmentScope) { + await trace.end(environmentScope, { endedAtMs: environmentEndedAtMs }); + } + }); let retainedTransition: VerifiedWarmTransitionBinding | undefined; let remoteWarmRecovery: RemoteWarmSessionRecovery | undefined; const cachedReleasedOwner = warmNativeSessions.get(nativeSessionScopeKey(input.execution)); @@ -9870,7 +9873,7 @@ async function executePaperclipNativeSessionAttempt( } } if (input.useRunnerd) { - retainedTransition = await migrateRunnerdStateRootForExecution({ + retainedTransition = await timeController("state_migration", () => migrateRunnerdStateRootForExecution({ db: input.db, execution: input.execution, preparedExecutionAdmission: input.preparedExecutionAdmission, @@ -9881,7 +9884,7 @@ async function executePaperclipNativeSessionAttempt( restartRecovery: input.restartRecovery, runnerExecutionTarget: input.runnerExecutionTarget, bootstrapRetryLeaseOwner: input.leaseOwner, - }); + })); } const durableRunnerBinding = input.useRunnerd ? loadRunnerdDurableBinding(input.execution, retainedTransition) From bf818280f2806366f23013e127232bbc1597fd62 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:28:23 -0600 Subject: [PATCH 5/5] perf(workspaces): reserve cohort members concurrently (#20401) ## Thinking Path > - Paperclip controls agent work and preserves its workspaces. > - The online importer moves up to eight shared-source leaves under one source fence. > - Each member must have a durable reservation before capture starts. > - Serial reservations repeat the same validation cost before any archive work. > - This pull request reserves members in parallel through their existing independent transactions. > - Every reservation finishes before an error can release the fence or start capture. ## Linked Issues or Issue Description Refs: #19873, #20387, #20394. **Current behavior** A measured six-member cohort spent about 110 seconds in serial reservations. Each reservation keeps its existing source, task, recovery and journal checks. **Proposed behavior** Start the bounded member reservations together. Join all outcomes, retain member order, and refuse capture if any member fails. Keep the exact partial-journal resume contract. **Reason and benefit** This removes serial metadata work before capture. Hosted speedup has not been measured for this change. ## What Changed - Replace only the cohort reservation caller loop with `Promise.allSettled`. - Preserve the existing per-member transaction, preassigned operation ID, source fingerprint and all source fences. - Extend the real PostgreSQL failure fixture to require overlapping reservations and complete peer closure before fence release. - Document the unchanged partial-journal and atomic publication contract. ## Verification - Canonical cached worktree preflight and plugin SDK prerequisites passed on Node 24.22.2. - The unchanged production baseline failed the new reservation overlap assertion: one reader entered instead of two. The canonical PostgreSQL wrapper cleaned up. The other 21 tests were intentionally not selected. - The first baseline command failed before PostgreSQL because root-level `tsx` resolution was absent. The corrected command uses the checkout's explicit `cli/node_modules/tsx/dist/loader.mjs`. - The four focused PostgreSQL controls passed before the final rebase: overlap/join failure, exact partial-journal resume, parallel capture with both cold restores, and atomic outer-commit rollback. Eighteen tests were intentionally not selected. Server TypeScript passed. - The final branch is based on merged #20394 at `302ada90dfda0e8fbcd8a514d506d310c9843bcb`. The two directly affected PostgreSQL reservation/resume controls passed again on final head `06d436e45705da3b616a2b91725960f6e0ea52c0` (2 passed, 20 intentionally not selected; 100.56 seconds). Server TypeScript passed again. The canonical wrapper completed cleanup. - The separate Ponytail review remains 4/5. Its nonblocking fan-out warning was resolved as the documented phase contract; no source change was required. Optional multi-error aggregation is outside this change. - Fresh Greptile review is 5/5 on `06d436e45705da3b616a2b91725960f6e0ea52c0`, with no actionable findings or unresolved threads: https://github.com/paperclipai/paperclip/pull/20401#issuecomment-6754025480. - Exact-head CI is complete: 56 success, 4 skipped and 1 neutral, with no failed or pending checks. Aggregate `ci / verify` passed: https://github.com/paperclipai/paperclip/actions/runs/42718439355. - Reproduce the final focused cases on Node 24: `node --import ./cli/node_modules/tsx/dist/loader.mjs packages/db/src/test-postgres-command.ts pnpm exec vitest run server/src/services/remote-workspace-cohort-migration.test.ts -t "joins concurrent reservation validation readers|resumes the exact membership after reservation stops halfway"`. Run `pnpm --filter @paperclipai/server exec tsc --noEmit` for TypeScript. ## Risks - API phase contract: `concurrency` limits capture workers. Preflight, reservation and post-finalizer validation fan out over the exact selected member set, with the canonical maximum of eight. The original DB pool bounds connections. `concurrency: 1` does not promise one metadata query or transaction at a time. - Up to eight reservations can use independent pool connections at once. Members that pass can leave durable journals when a peer fails. The existing exact-member resume path retains those journals; this change does not retry automatically. - Capture and publication remain blocked until every reservation settles. Publication stays serial in one transaction. Saved journal schemas, singleton behavior and recovery proof checks do not change. - This does not change concurrency inside the publication transaction. One PostgreSQL connection serializes that SQL, and changing its row-lock order has no measured benefit here. ## Model Used OpenAI GPT-6 (Codex), with tool use and code execution. The runtime does not expose a more specific model identifier or context-window size. ## 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 Co-authored-by: Paperclip --- doc/plans/2026-11-07-online-git-source-fence.md | 4 ++++ .../remote-workspace-cohort-migration.test.ts | 7 ++++--- server/src/services/remote-workspace-migration.ts | 11 +++++++---- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/doc/plans/2026-11-07-online-git-source-fence.md b/doc/plans/2026-11-07-online-git-source-fence.md index 434287d7276..e67165c3406 100644 --- a/doc/plans/2026-11-07-online-git-source-fence.md +++ b/doc/plans/2026-11-07-online-git-source-fence.md @@ -38,6 +38,10 @@ their existing reconstruction path. Preparation, lifecycle, runtime-service, expiration, and reopen owners retain the same physical keys before filesystem mutation or lifecycle exclusion. The importer holds all cohort task/project and lifecycle keys through publication. +Each cohort reserves its at most eight members in independent transactions in +parallel. It joins every reservation before starting capture or releasing the +source fence, including on failure. Partial journals keep the full exact member +and operation set for resume; publication stays serial in one transaction. It also holds the existing per-run physical finalizer keys for each exact native recovery proof. It re-inspects the complete source proof before capture and publication. Changed descriptors, allocations, owners, aliases, or Git metadata diff --git a/server/src/services/remote-workspace-cohort-migration.test.ts b/server/src/services/remote-workspace-cohort-migration.test.ts index 25fe135d197..21cb2de46ba 100644 --- a/server/src/services/remote-workspace-cohort-migration.test.ts +++ b/server/src/services/remote-workspace-cohort-migration.test.ts @@ -313,10 +313,10 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () => expect.soft(await db.select().from(workspaceOperations)).toHaveLength(1); await assertLocal(f); }); - it.each(["preflight", "recovery"] as const)("joins concurrent %s validation readers before releasing the fence", async phase => { + it.each(["preflight", "reservation", "recovery"] as const)("joins concurrent %s validation readers before releasing the fence", async phase => { const f = await fixture(), held = await recoverable(f), inspect = onlineWorkspaceSource.inspectOnlineWorkspaceSource; const counts = new Map(), selected = new Set(f.leaves.map(row => row.id)); - const phaseCall = phase === "preflight" ? 2 : 4; + const phaseCall = phase === "preflight" ? 2 : phase === "reservation" ? 3 : 4; let entered = 0, settled = false, bothEntered!: () => void, release!: () => void, firstFailed!: () => void; const both = new Promise(resolve => { bothEntered = resolve; }), peer = new Promise(resolve => { release = resolve; }); const failed = new Promise(resolve => { firstFailed = resolve; }), timer = setTimeout(() => bothEntered(), 5000); @@ -344,7 +344,8 @@ describe.skipIf(!support.supported)("bounded workspace cohort migration", () => await expect(withWorkspaceSourceLocks(db, { companyId: f.companyId, projectIds: [f.projectId] }, async () => true, true)).resolves.toBe(true); expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, held.runId)))[0]).toEqual(held.owner); await assertLocal(f); - expect(await db.select().from(workspaceOperations)).toHaveLength(phase === "preflight" ? 0 : 2); + expect(await db.select().from(workspaceOperations)).toHaveLength(phase === "preflight" ? 0 : phase === "reservation" ? 1 : 2); + expect(await db.select().from(executionWorkspaceSnapshots)).toHaveLength(0); expect(await db.select().from(activityLog)).toHaveLength(0); }); it.each(["failure", "cancel"] as const)("joins active capture peers and keeps the fence on %s", async mode => { diff --git a/server/src/services/remote-workspace-migration.ts b/server/src/services/remote-workspace-migration.ts index 6819091b8ac..0b686588bf5 100644 --- a/server/src/services/remote-workspace-migration.ts +++ b/server/src/services/remote-workspace-migration.ts @@ -773,13 +773,16 @@ export async function migrateRemoteWorkspaceCohort(input: { if (!await tryAcquireExecutionWorkspaceLifecycleLock(lock, workspaceId)) throw new IsolatedRepositorySourceBusy("workspace_source_busy"); } await preflight(input.db); - const plans: MigrationPlan[] = []; - for (const member of members) { + const reservations = await Promise.allSettled(members.map(async member => { const reserved = await reserveMigration(member.input, member.onlineSource, cohort, fingerprint(initial.find(workspace => workspace.id === member.input.workspaceId)!)); if (reserved.authority) throw new Error("workspace_cohort_membership_changed"); - plans.push({ ...member, reserved }); - } + return { ...member, reserved }; + })); + const plans: MigrationPlan[] = reservations.map(reservation => { + if (reservation.status === "rejected") throw reservation.reason; + return reservation.value; + }); await lockMigrationRecovery(lock, plans, cohort); const captures: Array = Array(plans.length); const childVerifier = createMigrationChildVerifier(plans[0].input, plans[0].onlineSource, lock);