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/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/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/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__/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/__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/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); } 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/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-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/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) 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" }], }; 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 bb69c0b91f7..0b686588bf5 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-"))); @@ -752,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); 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"