feat(runner): default harnesses to full auto and support task reassignment (#13686)

## Thinking Path

> - Paperclip lets people manage AI agents and their work.
> - Agent Chat uses native runners to save plans and coordinate tasks.
> - Provider defaults differed across harnesses and could stop
unattended work at a second permission gate.
> - Agents also lacked a dedicated tool to move existing work to another
agent safely.
> - This change defaults native providers to full automatic permission
for provider tools and connected tools.
> - A guarded reassignment tool preserves task identity, stops the
previous run, and schedules the new owner once.
> - Codex and Claude chat acceptance tests now use production permission
defaults.

## Linked Issues or Issue Description

**Subsystem affected**

Native runner, ACPX Claude permission policy, task authority, and Agent
Chat acceptance tests.

**Problem or motivation**

A user can authorize an agent to save a plan or create a task, but
Claude's default provider gate can still stop that action. Reassignment
needs a dedicated operation that preserves context and avoids concurrent
owners or unintended recovery runs.

**Proposed solution**

Default Claude/ACPX to `approve-all`, OpenCode to `allow`, and Codex to
`never`. Apply the defaults at configuration, execution, fresh-session,
resume, driver, and proxy boundaries. Keep explicit permission settings
and server-side company, claim, task-mode, and approval checks. Add
`reassign_task` with version checks, durable idempotency, audited
cancellation, and guarded successor scheduling.

**Alternatives considered**

A Paperclip-only allowlist still blocks provider tools and other
connections during unattended work. Full automatic permission is the
requested product default. Recreating a task discards its identity and
history. Updating assignment without stopping the previous run can leave
two agents working on the same task.

**Roadmap alignment**

This extends the existing planning, delegated work, governed tool
access, and recovery features. It adds no new service or schema
migration. Recent related tasks and open PRs were checked for duplicate
work.

**Additional context**

Related: #13678 (Agent Chat tools and recovery), #13677 (remote runner
startup). The stacked legacy-adapter companion is #13693. This also
fixes the deployed-server artifact fallback needed to stage the current
runner binary.

## What Changed

- Default Claude/ACPX to `approve-all`, OpenCode to `allow`, and Codex
to `never`, including missing settings at direct driver and proxy entry
points. These defaults cover provider tools and connected tools.
Preserve explicitly configured restrictive modes.
- Include assigned approval reads using canonical side-effect
classifications, so verifying a recorded approval does not trigger
another provider gate. Paperclip approval decisions still enforce
controller authority.
- Carry the new permission mode through server configuration, execution
contracts, recovery identity, TypeScript, and Rust. Keep
`approve-paperclip` as an optional restricted mode, with exact SDK rules
and closed unknown requests. It is not a default.
- Add `reassign_task` to the semantic catalog, controller, mock
authority, and generated contracts.
- Guard reassignment with company authorization, expected owner and
version, protected-state checks, and durable retry receipts.
- Honor explicit backlog task creation atomically with the initial plan,
without scheduling a wake. Preserve backlog holds regardless of
dependency readiness.
- Stop active work before changing ownership. Restore the prior owner
through a guarded, idempotent wake if final handoff validation fails.
Keep intentional reassignment stops out of failure recovery. Preserve
backlog and blocked states without waking them early.
- Add authorization, concurrency, replay, stop, and permission boundary
regressions. Add Codex and Claude chat reassignment cases and run native
chat cases with production defaults.
- Clarify shared runner guidance: save plans and Paperclip documents
directly with `write_document`; create and register a local file only
when a downloadable file is requested.
- Document provider defaults and the operator choices for existing
agents.

## Verification

- Current head `d82fbb0f03546d27cecf072250e4172e0b1ee662`: **55 checks
passed**, with two intentional skips. [PR
checks](https://github.com/paperclipai/paperclip/pull/13686/checks).
- Greptile reviewed that exact head at **5/5**. The security reviewer
acknowledged the intended full-auto default, and the acknowledged
discussions are resolved.
- Full workspace `pnpm -r typecheck` and `pnpm build` passed locally
after rebasing onto current master. Targeted adapter/server, runner,
API, default/resume, and heartbeat configuration tests passed.
- **All six real-provider acceptance cases passed on their first
attempt, with cleanup passing:** plan handoff, task reassignment, and
backlog creation/status, each on native Claude and Codex. Evidence
records Claude's effective `approve-all` mode. [Campaign and
downloadable
evidence](https://github.com/paperclipai/paperclip/actions/runs/35469926548).
- The live campaign tested combined revision
`a37881c824dcd7170380fc4b788732fc743e5da7`. The final PR heads add only
a heartbeat test expectation correction; application code is unchanged
from that live-tested revision.
- The campaign's result-enforcement job passed. Its separate report
publisher failed because the trusted workflow's `patchedDependencies`
configuration differs from its frozen lockfile. All six results and
screenshots remain available as GitHub artifacts. The overall manual
workflow is red for this publishing failure.
- Full-suite coverage is supplied by the passing CI partitions. The
separate unsharded local run was stopped after the corresponding CI
partitions passed; it is not counted as a completed local run.
- Reassignment tests cover stale state, cross-company access, denied
authority, cancellation failure, compensating wake, and idempotent
retries. Backlog tests verify the original creation audit, saved plan,
exact task count, and absence of task-bound runs.

## Risks

- Agents with no explicit permission mode now receive full provider tool
permission, including connected tools. This is a deliberate broad
default. Existing explicit restrictive modes still apply. Controller
authorization, company isolation, workspace boundaries, and Paperclip
governance remain in force.
- Reassignment crosses run cancellation and task ownership transactions.
Durable stop intent, revalidation, audit receipts, and guarded queue
dispatch cover interruptions and retries.
- The new permission enum requires a current runner artifact. The remote
artifact fallback uses the same resolved controller binary for upload
and execution.
- Live provider behavior remains subject to the selected model. Targeted
live results do not qualify the full catalog.

## Model Used

OpenAI Codex, based on GPT-6, with code execution and repository tools.
The exact deployment model ID 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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-19 16:49:18 -05:00
1 parent 04546c82d5
commit 7bc03e0acd
85 files changed
+1605 -178

No files matched your search

+2 -2
View File
@@ -357,12 +357,12 @@ describe("adapter routes", () => {
}),
expect.objectContaining({
key: "opencodePermissionMode",
default: "ask",
default: "allow",
meta: { visibleWhen: { key: "provider", value: "opencode" } },
}),
expect.objectContaining({
key: "acpxPermissionMode",
default: "approve-reads",
default: "approve-all",
meta: { visibleWhen: { key: "provider", value: "acpx" } },
}),
expect.objectContaining({
@@ -318,6 +318,30 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
});
}
it("releases an acknowledged native handoff without blocking or restarting the old owner", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent({ companyId });
const issueId = await seedIssue({ companyId, assigneeAgentId: agentId, status: "in_progress" });
const runId = await seedRun({ companyId, agentId, status: "cancelled", contextSnapshot: { issueId } });
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId, resultJson: {
reassignmentStopRequested: true,
nativeCancellation: { schema: "paperclip.native-cancellation.v1", runId, companyId, issueId,
scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true,
intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID() },
} }).where(eq(heartbeatRuns.id, runId));
await db.update(issues).set({ executionRunId: runId, checkoutRunId: runId }).where(eq(issues.id, issueId));
const before = (await db.select().from(issues).where(eq(issues.id, issueId)))[0];
const wakeId = await seedDeferredWake({ companyId, agentId, issueId });
const adapter = createPostgresWakeQueueAdapter(db, stubDeps);
const result = await adapter.withIssueExecutionLock({ companyId, runId, now: new Date() }, async () => { throw new Error("must not restart the outgoing owner"); });
expect(result).toMatchObject({ outcome: { kind: "released" }, postCommitEffects: [] });
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({
status: "in_progress", statusVersion: before.statusVersion, assigneeAgentId: agentId, executionRunId: null, checkoutRunId: null,
});
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)))[0].status).toBe("deferred_issue_execution");
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0);
});
it.each(["in_progress", "blocked"])("preserves recovery ownership and queued messages when a native task fails from %s", async (status) => {
const companyId = await seedCompany();
const agentId = await seedAgent({ companyId });
@@ -1,4 +1,4 @@
import { isAcknowledgedNativeStop } from "../../../services/acknowledged-native-stop.js";
import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "../../../services/acknowledged-native-stop.js";
import { instanceSettingsService } from "../../../services/instance-settings.js";
import { currentConversationCommentCondition } from "../../../services/agent-conversations.js";
import { getExecutionBlocker } from "../../../services/execution-blocker.js";
@@ -718,7 +718,7 @@ async function recordNativeTerminalRecoveryIfNeeded(tx: Db, run: HeartbeatRunRow
["failed", "timed_out", "interrupted", "cancelled"].includes(run.status) &&
issue.assigneeAgentId === run.agentId &&
!["done", "cancelled"].includes(issue.status);
if (!applies || isAcknowledgedNativeStop(run)) return false;
if (!applies || isAcknowledgedNativeStop(run) || isAcknowledgedNativeReassignmentStop(run)) return false;
const existing = await tx
.select({ id: issueRecoveryActions.id, evidence: issueRecoveryActions.evidence })
@@ -1104,9 +1104,10 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd
// next explicit wake adopts those messages atomically when it
// queues a run.
executionCancellationAcknowledged:
run.status === "cancelled" &&
isAcknowledgedNativeReassignmentStop(run) ||
(run.status === "cancelled" &&
(parseObject(run.resultJson?.executionCancellation).state === "acknowledged" || isAcknowledgedNativeStop(run)) &&
!interruptedQueue,
!interruptedQueue),
};
const preDrain = decidePreDrain(preDrainFacts);
@@ -1,5 +1,5 @@
import { expect, it } from "vitest";
import { isAcknowledgedNativeStop } from "./acknowledged-native-stop.js";
import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "./acknowledged-native-stop.js";
const run = { id: "run", companyId: "company", nativeIssueId: "issue", status: "cancelled", resultJson: {
cancelledByActorType: "user", cancelledByUserId: "board", nativeCancellation: {
schema: "paperclip.native-cancellation.v1", runId: "run", companyId: "company", issueId: "issue",
@@ -15,3 +15,16 @@ it.each([{ runId: "other" }, { companyId: "other" }, { issueId: "other" }, { dis
expect(isAcknowledgedNativeStop({ ...run, resultJson: { ...run.resultJson,
nativeCancellation: { ...run.resultJson.nativeCancellation, ...change } } })).toBe(false);
});
it("recognizes an audited handoff without granting operator Stop semantics", () => {
const handoff = { ...run, resultJson: { reassignmentStopRequested: true, nativeCancellation: run.resultJson.nativeCancellation } };
expect(isAcknowledgedNativeReassignmentStop(handoff)).toBe(true);
expect(isAcknowledgedNativeStop(handoff)).toBe(false);
expect(isAcknowledgedNativeReassignmentStop({ ...handoff, status: "running" })).toBe(false);
expect(isAcknowledgedNativeReassignmentStop(run)).toBe(false);
});
it.each([{ runId: "other" }, { companyId: "other" }, { issueId: "other" }, { dispatchState: "pending" },
{ scope: "subtree" }, { acknowledgementAuditId: undefined }])("requires an audited handoff receipt %j", change => {
expect(isAcknowledgedNativeReassignmentStop({ ...run, resultJson: { reassignmentStopRequested: true,
nativeCancellation: { ...run.resultJson.nativeCancellation, ...change } } })).toBe(false);
});
@@ -4,21 +4,34 @@ import { hasNativeLocalProcessStop } from "./native-local-process-stop.js";
import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
/** A server-recorded run-only Stop must not manufacture a recovery incident. */
export function hasAcknowledgedNativeStopIntent(run: {
function hasAcknowledgedNativeRunStopReceipt(run: {
id: string; companyId: string; status: string; nativeIssueId: string | null;
resultJson: Record<string, unknown> | null;
}): boolean {
const result = run.resultJson;
const intent = result?.nativeCancellation as Record<string, unknown> | undefined;
return result?.cancelledByActorType === "user" &&
typeof result.cancelledByUserId === "string" && Boolean(result.cancelledByUserId) &&
intent?.schema === "paperclip.native-cancellation.v1" && intent.runId === run.id &&
return intent?.schema === "paperclip.native-cancellation.v1" && intent.runId === run.id &&
intent.companyId === run.companyId && intent.issueId === run.nativeIssueId &&
intent.scope === "run" && intent.reasonCode === "cancellation_run_only" &&
intent.dispatchState === "acknowledged" && intent.dispatched === true &&
typeof intent.intentAuditId === "string" && typeof intent.acknowledgementAuditId === "string";
}
export function hasAcknowledgedNativeStopIntent(run: Parameters<typeof hasAcknowledgedNativeRunStopReceipt>[0]): boolean {
return run.resultJson?.cancelledByActorType === "user" &&
typeof run.resultJson.cancelledByUserId === "string" && Boolean(run.resultJson.cancelledByUserId) &&
hasAcknowledgedNativeRunStopReceipt(run);
}
/** An intentional handoff retains task state and deferred work for its successor. */
export function hasAcknowledgedNativeReassignmentStopIntent(run: Parameters<typeof hasAcknowledgedNativeRunStopReceipt>[0]): boolean {
return run.resultJson?.reassignmentStopRequested === true && hasAcknowledgedNativeRunStopReceipt(run);
}
export function isAcknowledgedNativeReassignmentStop(run: Parameters<typeof hasAcknowledgedNativeRunStopReceipt>[0]): boolean {
return run.status === "cancelled" && hasAcknowledgedNativeReassignmentStopIntent(run);
}
export function isAcknowledgedNativeStop(run: Parameters<typeof hasAcknowledgedNativeStopIntent>[0]): boolean {
return run.status === "cancelled" && hasAcknowledgedNativeStopIntent(run);
}
@@ -147,7 +147,7 @@ describe("Paperclip Runner native provider configuration", () => {
},
);
it("applies the safe provider permission default from adapter config", () => {
it("applies the full-auto provider permission default from adapter config", () => {
expect(
resolvePaperclipRunnerNativeProviderInput({
backend: "opencode_server",
@@ -159,7 +159,7 @@ describe("Paperclip Runner native provider configuration", () => {
).toEqual({
provider: "opencode",
model: "openrouter/deepseek/deepseek-v4-flash-0731",
opencodePermissionMode: "ask",
opencodePermissionMode: "allow",
});
});
+25 -3
View File
@@ -1,7 +1,7 @@
import { readQueuedInteractionResponse } from "./queued-interaction-response.js";
import { AGENT_CHAT_DIRECTIVE, conversationReplay, isConversation, isConversationExecutionWake, isWaitingConversation, prepareConversationTurn, settleConversationTurn } from "./agent-conversations.js";
import { PROCESS_IDENTITY_RECORDED, recordNativeLocalProcessStop } from "./native-local-process-stop.js";
import { hasAcknowledgedNativeStopIntent, isAcknowledgedNativeStop, acknowledgedNativeStopExecutionHasStopped } from "./acknowledged-native-stop.js";
import { hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, isAcknowledgedNativeStop, acknowledgedNativeStopExecutionHasStopped } from "./acknowledged-native-stop.js";
import { legacyControllerBootId, legacyControllerClaim, renewLegacyControllerLease, hasLiveLegacyController, revokeExpiredLegacyController, watchLegacyControllerLease } from "./legacy-controller-lease.js";
import { completeTerminatedRemoteNativeSessionCleanup } from "../vendor/paperclip-runner/index.js";
import { hasRemoteTerminationReceipt, remoteExecutionHasStopped, remoteTerminationReceipt, stoppedRemoteCleanupScopes } from "./remote-execution-termination.js";
@@ -3649,6 +3649,7 @@ interface WakeupOptions {
issueStateGuard?: {
statuses: string[];
assigneeAgentId: string;
statusVersion?: number;
};
/** Keep causally distinct external chat continuations out of an existing run. */
allowRunCoalescing?: boolean;
@@ -12848,7 +12849,7 @@ export function heartbeatService(
// Teardown can beat the cancellation finalizer. Preserve the acknowledged
// user intent instead of reporting an infrastructure interruption.
if (hasAcknowledgedNativeStopIntent(run)) terminalStatus = "cancelled";
if (hasAcknowledgedNativeStopIntent(run) || hasAcknowledgedNativeReassignmentStopIntent(run)) terminalStatus = "cancelled";
const message = `run terminalized on environment lease release: heartbeat_runs.status was still ${run.status} at teardown`;
// Match both "running" and "queued". A queued run has released its lease but
@@ -24093,6 +24094,21 @@ export function heartbeatService(
runnerRemoteProviderPackPath:
runtimeEnv.PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH?.trim() ||
null,
stopTaskForReassignment: async (target) => {
await settleLiveRunnerGoalBeforeInterrupt(db, target);
if (!target.runId) return;
const prior = await getRun(target.runId);
if (!prior || prior.companyId !== target.companyId || prior.agentId !== target.agentId) {
throw conflict("Reassignment run binding changed");
}
const stopped = await cancelRunInternal(target.runId, "Cancelled for task reassignment", {
errorCode: "issue_reassigned", suppressImmediateRecovery: true,
resultJson: { reassignmentStopConfirmed: true },
});
if (stopped && ["running", "queued", "scheduled_retry"].includes(stopped.status)) {
throw conflict("The previous run did not stop; reassignment was not applied");
}
},
enqueueWakeup,
onSpawn: async (meta) => {
markDispatchStarted();
@@ -26738,6 +26754,7 @@ export function heartbeatService(
conversationUserId: issues.conversationUserId,
conversationState: issues.conversationState,
status: issues.status,
statusVersion: issues.statusVersion,
projectId: issues.projectId,
projectWorkspaceId: issues.projectWorkspaceId,
executionWorkspaceId: issues.executionWorkspaceId,
@@ -26963,7 +26980,8 @@ export function heartbeatService(
if (
issueStateGuard &&
(!issueStateGuard.statuses.includes(issue.status) ||
issue.assigneeAgentId !== issueStateGuard.assigneeAgentId)
issue.assigneeAgentId !== issueStateGuard.assigneeAgentId ||
(issueStateGuard.statusVersion !== undefined && issue.statusVersion !== issueStateGuard.statusVersion))
) {
await tx.insert(agentWakeupRequests).values({
...durableReceiptFields,
@@ -28618,7 +28636,11 @@ export function heartbeatService(
// additional durable fence before its existing cancellation path.
if (run.runtimeMode === "native" || (!run.runtimeModeResolvedAt && !running && !control)) {
const [fenced] = await db.update(heartbeatRuns).set({
// Record handoff intent before native cancellation can finalize and release
// the run. Only its audited stop acknowledgement suppresses recovery.
resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ||
${JSON.stringify(options.errorCode === "issue_reassigned" && options.resultJson?.reassignmentStopConfirmed === true
? { reassignmentStopRequested: true } : {})}::jsonb ||
jsonb_build_object('startupCancellation', jsonb_build_object(
'requestedAt', ${new Date().toISOString()}::text,
'beforeNativeSelection', ${heartbeatRuns.runtimeMode} = 'legacy'
+6
View File
@@ -10819,6 +10819,12 @@ export function issueService(db: Db) {
projectGoalId: nextProjectGoalId,
defaultGoalId: defaultCompanyGoal?.id ?? null,
});
// Ownership changes invalidate observed handoff versions even if status
// stays the same, including an A -> B -> A assignment race.
if ((issueData.assigneeAgentId !== undefined && issueData.assigneeAgentId !== receiptExisting.assigneeAgentId)
|| (issueData.assigneeUserId !== undefined && issueData.assigneeUserId !== receiptExisting.assigneeUserId)) {
patch.statusVersion = sql`${issues.statusVersion} + 1` as unknown as number;
}
// Reasserting Blocked or changing its blockers is a fresh decision even
// when the status string stays the same. Invalidate recovery's prior
// status receipt without treating comment recency as blocking intent.
@@ -451,6 +451,8 @@ describe("native execution input external-chat framing", () => {
{ provider: "codex", resumedSession: true },
{ provider: "acpx", resumedSession: false },
{ provider: "acpx", resumedSession: true },
{ provider: "opencode", resumedSession: false },
{ provider: "opencode", resumedSession: true },
] as const)("keeps question documentation in the tool on $provider (resumed: $resumedSession)", ({ provider, resumedSession }) => {
const input = buildNativeExecutionInput({
companyId: "10000000-0000-4000-8000-000000000001",
@@ -462,13 +464,17 @@ describe("native execution input external-chat framing", () => {
normalizedSessionId: resumedSession ? "60000000-0000-4000-8000-000000000006" : null,
provider, resumedSession,
acpxAgent: "claude",
model: provider === "acpx" ? "claude-sonnet-5" : "gpt-5.6-sol",
model: provider === "acpx" ? "claude-sonnet-5" : provider === "opencode" ? "openai/gpt-5.5" : "gpt-5.6-sol",
completionContract: {
id: "70000000-0000-4000-8000-000000000007", sha256: `sha256:${"a".repeat(64)}`, schemaVersion: "paperclip.run-result.v1",
contract: { revision: "1", objective: "Write a welcome after the user's answer", criteria: [{ id: "objective", requirement: "Use the selected tone" }] },
},
runtimeContext: nativeRuntimeContextFixture(),
});
expect(input.provider).toMatchObject(provider === "acpx"
? { kind: "acpx", permissionMode: "approve-all" }
: provider === "opencode" ? { kind: "opencode", permissionMode: "allow" }
: { kind: "codex", approvalPolicy: "never" });
expect(input.task.prompt).not.toContain("## Questions that need a user response");
expect(input.task.prompt).toContain("Use Paperclip's request_human_input for durable task questions.");
expect(input.task.prompt).not.toContain("payload.questionSet");
@@ -240,7 +240,7 @@ export function buildNativeExecutionInput(input: {
kind: "acpx",
agent: acpxProfile!.agent,
model: input.model,
permissionMode: input.acpxPermissionMode ?? "approve-reads",
permissionMode: input.acpxPermissionMode ?? "approve-all",
profile: {
driverKind: acpxProfile!.driverKind,
protocolVersion: acpxProfile!.protocolVersion,
@@ -258,7 +258,7 @@ export function buildNativeExecutionInput(input: {
? {
kind: "opencode",
model: input.model,
permissionMode: input.opencodePermissionMode ?? "ask",
permissionMode: input.opencodePermissionMode ?? "allow",
}
: {
kind: "codex",
@@ -40,7 +40,6 @@ import {
NativeSessionCleanupQuarantinedError,
NativeProviderTerminalFailure,
NativeSessionProtocolIntegrityError,
defaultCapabilityRunnerdBinary,
} from "../../vendor/paperclip-runner/index.js";
import * as issueServiceModule from "../issues.js";
import {
@@ -84,7 +83,7 @@ type RunnerTransportOptions = {
provider?: "codex" | "opencode" | "acpx";
opencodePermissionMode?: "allow" | "ask" | "deny";
acpxAgent?: "claude" | "codex";
acpxPermissionMode?: "approve-all" | "approve-reads" | "deny-all";
acpxPermissionMode?: "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
resumeActiveTurnId?: string | null;
resumeProviderSession?: {
driverSessionId: string;
@@ -175,7 +174,6 @@ vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => {
>();
return {
...original,
defaultCapabilityRunnerdBinary: vi.fn(original.defaultCapabilityRunnerdBinary),
createNativeSessionBackend: state.createBackend,
createRunnerdCodexTransport: state.createTransport,
executeNativeSession: state.execute,
@@ -6476,11 +6474,13 @@ describe("native warm session supervision", () => {
});
describe("native session bounded recovery", () => {
it("does not turn an acknowledged Stop before completion into a failure or a retry", async () => {
it.each(["operator", "reassignment"])("does not turn an acknowledged %s Stop before completion into a failure or a retry", async (source) => {
const updates: Array<{ table: unknown; values: Record<string, unknown> }> = [];
const stop: Record<string, unknown> = {};
state.execute.mockReset().mockImplementationOnce(async () => {
Object.assign(stop, { cancelledByActorType: "user", cancelledByUserId: "board", nativeCancellation: {
Object.assign(stop, { ...(source === "operator"
? { cancelledByActorType: "user", cancelledByUserId: "board" }
: { reassignmentStopRequested: true }), nativeCancellation: {
schema: "paperclip.native-cancellation.v1", ...execution.binding, scope: "run", reasonCode: "cancellation_run_only",
dispatched: true, dispatchState: "acknowledged", intentAuditId: "intent", acknowledgementAuditId: "ack",
} });
@@ -10065,7 +10065,7 @@ describe("runnerd provider runtime wiring", () => {
const controllerArtifact = join(isolatedStateDirectory, "paperclip-runnerd");
if (staleRunner) {
await writeFile(controllerArtifact, "fixture runner artifact");
vi.mocked(defaultCapabilityRunnerdBinary).mockReturnValueOnce(controllerArtifact);
state.resolveRunnerBinary.mockReturnValueOnce(controllerArtifact);
}
const syncIn = vi.fn(async () => undefined);
const remoteExecute = vi.fn(
@@ -10141,6 +10141,7 @@ describe("runnerd provider runtime wiring", () => {
"reached-preinstalled-codex-verification",
);
if (staleRunner) {
expect(transport.runnerBinary).toBe(controllerArtifact);
expect(syncIn).toHaveBeenCalledTimes(1);
expect(syncIn).toHaveBeenCalledWith([expect.objectContaining({
files: [expect.objectContaining({
@@ -2,7 +2,7 @@ import { createLocalNativeQuestionBridge } from "./local-native-question-bridge.
import { readVerifiedRemoteWorkspaceFile } from "./remote-deliverable-file.js";
import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
import { hasAcknowledgedNativeStopIntent } from "../acknowledged-native-stop.js";
import { hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent } from "../acknowledged-native-stop.js";
import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js";
import { prepareVerifiedRemoteProviderPack } from "./remote-provider-pack.js";
import { readNativeLocalProcessStop, PROCESS_START_REQUESTED } from "../native-local-process-stop.js";
@@ -62,7 +62,6 @@ import {
acpxRuntimeSessionDirectoryName,
createNativeSessionBackend,
createRunnerdCodexTransport,
defaultCapabilityRunnerdBinary,
executeNativeSession,
applyNativeSessionGoalControl,
inspectWarmRunTransition,
@@ -5222,7 +5221,7 @@ export function providerSessionIdentityFromDurableProviderState(input: {
identity.requestedModel !== expectedModel ||
identity.effectiveModel !== expectedModel ||
identity.permissionMode !== input.execution.provider.permissionMode ||
!["approve-all", "approve-reads", "deny-all"].includes(
!["approve-all", "approve-paperclip", "approve-reads", "deny-all"].includes(
String(identity.permissionMode),
) ||
!Array.isArray(identity.providerLifetimeFenceCandidates) ||
@@ -6943,6 +6942,7 @@ export async function executePaperclipNativeSession(input: {
runnerRemoteCodexPath?: string | null;
runnerRemoteCodexNpmSpec?: string | null;
runnerRemoteProviderPackPath?: string | null;
stopTaskForReassignment?: (target: { companyId: string; issueId: string; agentId: string; runId: string | null }) => Promise<void>;
enqueueWakeup?: (
agentId: string,
options: {
@@ -8260,7 +8260,7 @@ async function executePaperclipNativeSessionWithinScope(
eq(heartbeatRuns.agentId, input.execution.binding.agentId),
eq(heartbeatRuns.nativeIssueId, input.execution.binding.issueId),
)).limit(1);
if (stoppedRun && hasAcknowledgedNativeStopIntent(stoppedRun)) {
if (stoppedRun && (hasAcknowledgedNativeStopIntent(stoppedRun) || hasAcknowledgedNativeReassignmentStopIntent(stoppedRun))) {
const [settled] = await input.db.update(nativeRunFinalizations).set({
phase: "terminal_failure", failureCode: "native_retry_cancelled", nextAttemptAt: null,
leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null, recoveryState: null,
@@ -10118,6 +10118,7 @@ export async function createRunnerdBackend(input: {
runnerRemoteProviderPackPath?: string | null;
trace?: NativeRunTrace;
onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
stopTaskForReassignment?: (target: { companyId: string; issueId: string; agentId: string; runId: string | null }) => Promise<void>;
enqueueWakeup?: (
agentId: string,
options: {
@@ -10233,6 +10234,7 @@ async function createRunnerdBackendWithinSessionClaim(
: undefined,
currentWakeComments: currentWakeComments ?? undefined,
chatAttachmentReadScope: input.chatAttachmentReadScope,
stopTaskForReassignment: input.stopTaskForReassignment,
enqueueWakeup: input.enqueueWakeup,
});
const authorityEpoch = new SessionToolAuthorityEpoch(
@@ -10623,8 +10625,10 @@ async function createRunnerdBackendWithinSessionClaim(
}
}
if (!usedPreinstalledRunner) {
const sourceBinary =
explicitRemoteBinary ?? defaultCapabilityRunnerdBinary();
// Upload the same artifact used for the controller identity. The server
// vendors the runner under vendor/paperclip-runner/bin, so the package
// development fallback cannot locate it in a deployed server.
const sourceBinary = controllerRunnerBinary;
if (!existsSync(sourceBinary)) {
throw new Error("runner_remote_artifact_unavailable");
}
@@ -2519,13 +2519,13 @@ describe("buildNativeExecutionInput wake projection", () => {
},
});
expect(defaultOpenCode).toMatchObject({
provider: { kind: "opencode", permissionMode: "ask" },
provider: { kind: "opencode", permissionMode: "allow" },
});
expect(defaultAcpx).toMatchObject({
provider: {
kind: "acpx",
agent: "codex",
permissionMode: "approve-reads",
permissionMode: "approve-all",
},
});
expect(
@@ -90,7 +90,7 @@ describe("PaperclipRunnerToolAuthority", () => {
issueId,
runId,
});
expect(authority.definitions()).toHaveLength(26);
expect(authority.definitions()).toHaveLength(27);
const questions = authority.definitions().find(tool => tool.name === "request_human_input")!;
expect(questions.description).toContain("ask only the next unanswered question");
expect(questions.description).toContain("Never infer answers");
@@ -1,3 +1,5 @@
import { assertAssignableAgent } from "../agent-assignability.js";
import { authorizationService } from "../authorization.js";
import { handoffPlanContext } from "./handoff-plan-context.js";
import { callCreateSkillTool } from "../skill-tools.js";
import { callProjectTool } from "../project-tools.js";
@@ -23,12 +25,14 @@ import { workspaceFileResourceService } from "../workspace-file-resources.js";
import { badRequest, forbidden } from "../../errors.js";
import { searchRunnerApi } from "./runner-api-catalog.js";
import { executeRunnerApi, validateRunnerApiCall, RUNNER_API_MAX_BYTES, type RunnerApiFile } from "./runner-api-client.js";
import { and, desc, eq, isNull, notInArray } from "drizzle-orm";
import { and, desc, eq, isNull, notInArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
agents,
agentWakeupRequests,
chatEndpoints,
chatConversations,
documentRevisions,
heartbeatRuns,
issueApprovals,
@@ -76,7 +80,7 @@ const IMPLEMENTED_OPERATIONS = new Set([
"search_api", "call_api",
"get_task_context", "get_task_history", "search_tasks", "report_progress",
"request_human_input",
"create_skill", "create_task", "set_dependencies", "create_project", "list_project_repositories", "list_projects", "register_deliverable",
"create_skill", "create_task", "reassign_task", "set_dependencies", "create_project", "list_project_repositories", "list_projects", "register_deliverable",
"list_documents", "read_document", "list_document_revisions", "write_document",
"list_agents", "get_agent", "list_approvals", "get_approval", "get_approval_context",
]);
@@ -106,6 +110,7 @@ type Binding = {
readRemoteWorkspaceFile?: RemoteWorkspaceFileReader;
currentWakeComments?: CurrentWakeCommentsBinding;
chatAttachmentReadScope?: NativeChatAttachmentReadScope;
stopTaskForReassignment?: (target: { companyId: string; issueId: string; agentId: string; runId: string | null }) => Promise<void>;
enqueueWakeup?: (agentId: string, options: {
source: "assignment";
triggerDetail: "system";
@@ -115,7 +120,7 @@ type Binding = {
requestedByActorType: "agent";
requestedByActorId: string;
contextSnapshot: Record<string, unknown>;
issueStateGuard?: { statuses: string[]; assigneeAgentId: string };
issueStateGuard?: { statuses: string[]; assigneeAgentId: string; statusVersion?: number };
}) => Promise<unknown>;
};
@@ -467,6 +472,7 @@ export class PaperclipRunnerToolAuthority {
(await captureRunIdentity(this.db, this.binding)).context?.id ?? null);
case "create_task": return this.#createTask(input,
(await captureRunIdentity(this.db, this.binding)).context?.id ?? null);
case "reassign_task": return this.#reassignTask(input);
case "set_dependencies": return this.#setDependencies(input);
case "register_deliverable": return this.#registerDeliverable(input);
default: throw new Error("paperclip_runner_tool_not_bound");
@@ -756,6 +762,9 @@ export class PaperclipRunnerToolAuthority {
async #createTask(input: Record<string, unknown>, identityContextId: string | null): Promise<unknown> {
const idempotencyKey = requiredString(input.idempotencyKey);
if (input.status !== undefined && input.status !== "backlog" && input.status !== "todo") {
throw new Error("paperclip_runner_tool_input_invalid");
}
const assigneeAgentId = input.assigneeActorId === null || input.assigneeActorId === undefined
? this.binding.agentId
: requiredString(input.assigneeActorId);
@@ -809,7 +818,8 @@ export class PaperclipRunnerToolAuthority {
description: input.description === null || input.description === undefined
? null
: requiredString(input.description),
status: blockedByIssueIds.length > 0 ? "blocked" as const : "todo" as const,
status: input.status === "backlog" ? "backlog" as const
: blockedByIssueIds.length > 0 ? "blocked" as const : "todo" as const,
workMode: "standard" as const,
priority,
assigneeAgentId,
@@ -909,6 +919,171 @@ export class PaperclipRunnerToolAuthority {
return result;
}
async #reassignTask(input: Record<string, unknown>): Promise<unknown> {
const key = requiredString(input.idempotencyKey);
const taskId = requiredUuid(input.taskId);
const assigneeAgentId = requiredUuid(input.assigneeActorId);
const expectedOwner = input.expectedAssigneeActorId === null ? null : requiredUuid(input.expectedAssigneeActorId);
const expectedVersion = input.expectedStatusVersion;
const reason = requiredString(input.reason);
if (!Number.isSafeInteger(expectedVersion) || Number(expectedVersion) < 0 || key.length > 240 || reason.length > 20_000) {
throw new Error("paperclip_runner_tool_input_invalid");
}
if (taskId === this.binding.issueId) {
throw new Error("paperclip_runner_reassignment_current_task: delegate with create_task; this tool cannot interrupt its own caller");
}
const durableKey = `reassign:${this.binding.issueId}:${key}`;
const fingerprint = createHash("sha256").update(canonicalJson(input)).digest("hex");
const priorReceipt = async (tx: Db): Promise<Record<string, unknown> | null> => {
const [prior] = await tx.select({ details: activityLog.details }).from(activityLog).where(and(
eq(activityLog.companyId, this.binding.companyId), eq(activityLog.action, "issue.reassigned"),
sql`${activityLog.details}->>'reassignmentKey' = ${durableKey}`,
)).limit(1);
if (!prior) return null;
if (prior.details?.inputFingerprint !== fingerprint) throw new Error("paperclip_runner_tool_idempotency_conflict");
return record(prior.details?.receipt);
};
const authorize = async (tx: Db, run: typeof heartbeatRuns.$inferSelect) => {
const [target] = await tx.select().from(issues).where(and(eq(issues.id, taskId), eq(issues.companyId, this.binding.companyId))).for("update");
if (!target) throw new Error("paperclip_runner_task_not_found");
const actor = { type: "agent" as const, source: "agent_jwt" as const, companyId: this.binding.companyId,
agentId: this.binding.agentId, runId: this.binding.runId, onBehalfOfUserId: run.responsibleUserId };
for (const action of ["issue:read", "tasks:assign"] as const) {
const decision = await authorizationService(tx).decide({ actor, action, resource: {
type: "issue", companyId: this.binding.companyId, issueId: taskId, projectId: target.projectId,
parentIssueId: target.parentId, assigneeAgentId: action === "tasks:assign" ? assigneeAgentId : target.assigneeAgentId,
assigneeUserId: action === "tasks:assign" ? null : target.assigneeUserId, status: target.status,
} });
if (!decision.allowed) throw forbidden(decision.explanation);
}
await assertAssignableAgent(tx, this.binding.companyId, assigneeAgentId, { kind: "work" });
const [externalChat] = await tx.select({ id: chatConversations.id }).from(chatConversations).where(and(
eq(chatConversations.companyId, this.binding.companyId), eq(chatConversations.issueId, taskId),
)).limit(1);
if (externalChat) throw new Error("paperclip_runner_reassignment_conversation_locked");
return target;
};
const validate = (target: typeof issues.$inferSelect) => {
if (target.conversationAgentId) throw new Error("paperclip_runner_reassignment_conversation_locked");
if (["done", "cancelled", "in_review"].includes(target.status) || record(target.executionState).status === "pending") {
throw new Error("paperclip_runner_reassignment_state_denied");
}
if (target.assigneeUserId || target.assigneeAgentId !== expectedOwner || target.statusVersion !== expectedVersion) {
throw new Error("paperclip_runner_reassignment_conflict: refresh search_tasks before deciding again");
}
};
// Stop outside row locks: the runtime needs those locks to acknowledge cancellation.
// A second locked check below prevents any intervening ownership/version change.
const prepared = await this.db.transaction(async (tx) => {
const context = await this.#lockAuthorizedMutationContext(tx as unknown as Db);
if (context.issue.workMode !== "standard") throw new Error("paperclip_runner_tool_mode_denied");
const target = await authorize(tx as unknown as Db, context.run);
if (await priorReceipt(tx as unknown as Db)) return null;
validate(target);
return target;
});
// Cancellation and ownership commit cannot share locks. If the second
// phase loses its preconditions, restore runnable work to the still-current
// prior owner. The durable wake key deduplicates retries; the state guard
// closes races with later reassignment, completion, and manual holds.
const restoreInterruptedWork = async (error: unknown) => {
if (!prepared?.executionRunId || !prepared.assigneeAgentId || !this.binding.enqueueWakeup) return;
const [stopped] = await this.db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, prepared.executionRunId), eq(heartbeatRuns.companyId, this.binding.companyId),
eq(heartbeatRuns.agentId, prepared.assigneeAgentId), eq(heartbeatRuns.status, "cancelled"),
eq(heartbeatRuns.errorCode, "issue_reassigned"),
));
if (!stopped) return;
const [current] = await this.db.select().from(issues).where(and(
eq(issues.id, taskId), eq(issues.companyId, this.binding.companyId),
));
if (!current || current.assigneeAgentId !== prepared.assigneeAgentId || current.assigneeUserId ||
current.conversationAgentId || !["todo", "in_progress"].includes(current.status) ||
record(current.executionState).status === "pending") return;
if (current.executionRunId && current.executionRunId !== prepared.executionRunId) return;
try {
await this.binding.enqueueWakeup(current.assigneeAgentId, {
source: "assignment", triggerDetail: "system", reason: "issue_assigned",
payload: { issueId: taskId, mutation: "reassign_task_rollback", interruptedRunId: prepared.executionRunId },
idempotencyKey: `${durableKey}:restore:${prepared.executionRunId}:${current.statusVersion}`,
requestedByActorType: "agent", requestedByActorId: this.binding.agentId,
contextSnapshot: { issueId: taskId, source: "paperclip_runner.reassign_task_rollback", forceFreshSession: true },
issueStateGuard: { statuses: ["todo", "in_progress"], assigneeAgentId: current.assigneeAgentId, statusVersion: current.statusVersion },
});
} catch (restoreError) {
throw new AggregateError([error, restoreError], "paperclip_runner_reassignment_restore_failed");
}
};
if (prepared && prepared.assigneeAgentId && prepared.assigneeAgentId !== assigneeAgentId) {
if (prepared.executionRunId && (!this.binding.stopTaskForReassignment || !this.binding.enqueueWakeup)) {
throw new Error("paperclip_runner_reassignment_stop_unavailable");
}
try {
await this.binding.stopTaskForReassignment?.({ companyId: this.binding.companyId, issueId: taskId,
agentId: prepared.assigneeAgentId, runId: prepared.executionRunId });
} catch (error) {
await restoreInterruptedWork(error);
throw error;
}
}
let publication: Awaited<ReturnType<typeof persistActivity>>["publication"] | null = null;
const result = await this.#withMutationReceipt("reassign_task", key, input, async (tx, context) => {
if (context.issue.workMode !== "standard") throw new Error("paperclip_runner_tool_mode_denied");
const target = await authorize(tx, context.run);
const prior = await priorReceipt(tx);
if (prior) return prior;
validate(target);
if (target.executionRunId && target.executionRunId !== prepared?.executionRunId) {
throw new Error("paperclip_runner_reassignment_conflict: a new execution started; refresh before retrying");
}
if (target.executionRunId && target.assigneeAgentId !== assigneeAgentId) {
const [run] = await tx.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, target.executionRunId));
if (run && ["running", "queued", "scheduled_retry"].includes(run.status)) throw new Error("paperclip_runner_reassignment_stop_unconfirmed");
}
const changed = target.assigneeAgentId !== assigneeAgentId;
const updated = changed ? await issueService(tx).update(taskId, {
companyGuard: this.binding.companyId, assigneeAgentId, assigneeUserId: null,
status: target.status === "in_progress" ? "todo" : target.status,
statusVersion: target.statusVersion + 1, actorAgentId: this.binding.agentId,
}, tx) : target;
if (!updated) throw new Error("paperclip_runner_task_not_found");
const receipt = {
commandId: `reassign-task:${taskId}:${updated.statusVersion}`, disposition: changed ? "applied" : "duplicate",
stateRevision: updated.statusVersion, entityRefs: [taskId],
scheduledWakeIds: changed && updated.status === "todo" ? [`${durableKey}:${updated.statusVersion}`] : [],
};
if (changed) await issueService(tx).addComment(taskId, reason, { agentId: this.binding.agentId, runId: this.binding.runId });
const activity = await persistActivity(tx, {
companyId: this.binding.companyId, actorType: "agent", actorId: this.binding.agentId,
agentId: this.binding.agentId, runId: this.binding.runId, issueId: taskId,
action: "issue.reassigned", entityType: "issue", entityId: taskId,
details: { source: "paperclip_runner_protocol", reassignmentKey: durableKey, inputFingerprint: fingerprint,
previousAssigneeAgentId: target.assigneeAgentId, assigneeAgentId, reason, changed, receipt },
});
publication = activity.publication;
return receipt;
}, { beforeReceiptReplay: async (tx, context) => { await authorize(tx, context.run); } }).catch(async (error: unknown) => {
await restoreInterruptedWork(error);
throw error;
}) as {
stateRevision: number; scheduledWakeIds: string[];
};
if (publication) publishActivity(publication);
// Replay repairs a failed dispatch. The durable wake key and state/version guard
// prevent duplicate successors and prevent waking a later, unrelated assignment.
if (result.scheduledWakeIds.length && this.binding.enqueueWakeup) {
await this.binding.enqueueWakeup(assigneeAgentId, {
source: "assignment", triggerDetail: "system", reason: "issue_assigned",
payload: { issueId: taskId, mutation: "reassign_task", reason },
idempotencyKey: result.scheduledWakeIds[0]!, requestedByActorType: "agent", requestedByActorId: this.binding.agentId,
contextSnapshot: { issueId: taskId, source: "paperclip_runner.reassign_task", reassignmentReason: reason },
issueStateGuard: { statuses: ["todo"], assigneeAgentId, statusVersion: result.stateRevision },
});
}
return result;
}
async #setDependencies(input: Record<string, unknown>): Promise<unknown> {
const idempotencyKey = requiredString(input.idempotencyKey);
if (!Array.isArray(input.blockedByTaskIds)) {
@@ -109,7 +109,7 @@ export type PaperclipRunnerNativeProviderInput =
provider: "acpx";
model: string;
acpxAgent: QualifiedPaperclipRunnerAcpxAgent;
acpxPermissionMode: "approve-all" | "approve-reads" | "deny-all";
acpxPermissionMode: "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
};
export class PaperclipRunnerProviderProfileError extends Error {
@@ -476,7 +476,7 @@ export function resolvePaperclipRunnerNativeProviderInput(input: {
acpxPermissionMode: resolvePaperclipRunnerPermissionMode(
"acpx",
config.acpxPermissionMode,
) as "approve-all" | "approve-reads" | "deny-all",
) as "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all",
};
}
if (profile.provider === "claude_managed") {
@@ -48,7 +48,7 @@ function dedicatedTools(method: string, path: string): string[] {
if (/\/issues\/\{[^}]+\}\/comments$/.test(path)) return method === "GET" ? ["get_task_history"] : ["report_progress"];
if (/\/issues\/\{[^}]+\}\/documents/.test(path)) return method === "DELETE" ? [] : method === "GET" ? ["list_documents", "read_document", "list_document_revisions"] : ["write_document"];
if (/\/issues$/.test(path)) return method === "GET" ? ["search_tasks"] : ["create_task"];
if (/\/issues\/\{[^}]+\}$/.test(path)) return method === "GET" ? ["get_task_context"] : ["set_dependencies", "finish_task", "block_task", "request_review"];
if (/\/issues\/\{[^}]+\}$/.test(path)) return method === "GET" ? ["get_task_context"] : ["reassign_task", "set_dependencies", "finish_task", "block_task", "request_review"];
if (/\/agents$/.test(path) && method === "GET") return ["list_agents"];
if (/\/agents\/(me|\{[^}]+\})$/.test(path) && method === "GET") return ["get_agent"];
if (/\/approvals$/.test(path) && method === "GET") return ["list_approvals"];
@@ -0,0 +1,68 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { and, eq } from "drizzle-orm";
import { activityLog, agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { documentService } from "../documents.js";
import { issueService } from "../issues.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
describe("runner backlog task creation", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("runner-backlog-");
db = createDb(temporary.connectionString);
});
afterAll(async () => { await temporary?.cleanup(); });
async function fixture(conversation: boolean) {
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Backlog", issuePrefix: `B${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Planner", role: "ceo", status: "active", adapterType: "paperclip_runner" });
await db.insert(issues).values({ id: issueId, companyId, title: "Coordinate", status: "in_progress", assigneeAgentId: agentId, conversationAgentId: conversation ? agentId : null, conversationUserId: conversation ? "operator" : null, conversationState: conversation ? "active" : null });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", nativeIssueId: issueId, invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
const enqueueWakeup = vi.fn().mockResolvedValue(null);
const binding = { companyId, agentId, issueId, runId, enqueueWakeup };
return { companyId, agentId, issueId, runId, binding, enqueueWakeup, authority: new PaperclipRunnerToolAuthority(db, binding) };
}
it.each([false, true])("persists the plan without waking an assigned backlog task (conversation=%s)", async conversation => {
const f = await fixture(conversation);
const call = { tool: "create_task", callId: "save-later", arguments: { idempotencyKey: "save-later", title: "Plan for later", status: "backlog", initialPlan: "1. Check status.\n2. Save the plan.\n3. Confirm creation." } };
const receipt = await f.authority.execute(call) as { task: { id: string } };
expect(receipt).toMatchObject({ scheduledWakeIds: [], task: { status: "backlog", assigneeActorId: f.agentId, parentId: conversation ? null : f.issueId } });
const [task] = await db.select().from(issues).where(eq(issues.id, receipt.task.id));
expect(task).toMatchObject({ status: "backlog", executionRunId: null, startedAt: null });
expect(await documentService(db).getIssueDocumentByKey(task!.id, "plan")).toMatchObject({ body: call.arguments.initialPlan });
expect(f.enqueueWakeup).not.toHaveBeenCalled();
await expect(f.authority.execute({ ...call, callId: "retry" })).resolves.toEqual(receipt);
const replacement = randomUUID();
await db.insert(heartbeatRuns).values({ id: replacement, companyId: f.companyId, agentId: f.agentId, status: "running", runtimeMode: "native", nativeIssueId: f.issueId, invocationSource: "assignment", triggerDetail: "system" });
await db.update(issues).set({ executionRunId: replacement }).where(eq(issues.id, f.issueId));
await expect(new PaperclipRunnerToolAuthority(db, { ...f.binding, runId: replacement }).execute(call)).resolves.toMatchObject({ task: { id: task!.id, status: "backlog" }, scheduledWakeIds: [] });
expect(f.enqueueWakeup).not.toHaveBeenCalled();
const events = await db.select().from(activityLog).where(and(eq(activityLog.entityId, task!.id), eq(activityLog.action, "issue.created")));
expect(events).toHaveLength(1);
expect(events[0]!.details).toMatchObject({ status: "backlog" });
});
it.each(["todo", "done"])("keeps an explicit backlog hold with a %s prerequisite", async status => {
const f = await fixture(true);
const blockerId = randomUUID();
await db.insert(issues).values({ id: blockerId, companyId: f.companyId, title: "Prerequisite", status });
const receipt = await f.authority.execute({ tool: "create_task", callId: "held", arguments: { idempotencyKey: "held", title: "Held task", status: "backlog", blockedByTaskIds: [blockerId] } }) as { task: { id: string } };
expect(receipt).toMatchObject({ task: { status: "backlog" }, scheduledWakeIds: [] });
expect(await issueService(db).getRelationSummaries(receipt.task.id)).toMatchObject({ blockedBy: [expect.objectContaining({ id: blockerId })] });
expect(f.enqueueWakeup).not.toHaveBeenCalled();
});
it.each(["in_progress", "done", "blocked", null])("rejects unsupported initial status %s before mutation", async status => {
const f = await fixture(true);
await expect(f.authority.execute({ tool: "create_task", callId: "invalid", arguments: { idempotencyKey: "invalid", title: "Invalid", status } })).rejects.toThrow();
expect(await db.select().from(issues).where(eq(issues.companyId, f.companyId))).toHaveLength(1);
expect(f.enqueueWakeup).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,203 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { eq, and } from "drizzle-orm";
import { activityLog, agents, companies, createDb, heartbeatRuns, issues, issueComments } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { issueService } from "../issues.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
describe("runner task reassignment", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("runner-reassign-");
db = createDb(temporary.connectionString);
});
afterAll(async () => { await temporary?.cleanup(); });
async function fixture(status = "todo") {
const companyId = randomUUID(), agentId = randomUUID(), nextId = randomUUID(), issueId = randomUUID(), targetId = randomUUID(), runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Reassignment", issuePrefix: `R${companyId.slice(0, 6)}` });
await db.insert(agents).values([
{ id: agentId, companyId, name: "Manager", role: "ceo", status: "active", adapterType: "paperclip_runner" },
{ id: nextId, companyId, name: "Engineer", role: "engineer", status: "active", adapterType: "paperclip_runner" },
]);
await db.insert(issues).values([
{ id: issueId, companyId, title: "Coordinate", status: "in_progress", assigneeAgentId: agentId },
{ id: targetId, companyId, title: "Existing work", status, assigneeAgentId: agentId, description: "Keep the existing plan and context" },
]);
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", nativeIssueId: issueId, invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
const enqueueWakeup = vi.fn().mockResolvedValue({ id: randomUUID() });
const stopTaskForReassignment = vi.fn().mockResolvedValue(undefined);
const binding = { companyId, agentId, issueId, runId, enqueueWakeup, stopTaskForReassignment };
const authority = new PaperclipRunnerToolAuthority(db, binding);
const call = { tool: "reassign_task", callId: "handoff", arguments: { taskId: targetId, assigneeActorId: nextId, expectedAssigneeActorId: agentId, expectedStatusVersion: 0, reason: "Engineer owns implementation; retain the existing plan.", idempotencyKey: "handoff" } };
const target = async () => (await db.select().from(issues).where(eq(issues.id, targetId)))[0]!;
return { companyId, agentId, nextId, issueId, targetId, runId, authority, binding, call, target, enqueueWakeup, stopTaskForReassignment };
}
it("moves existing work once, persists context and audit, and dispatches a guarded wake", async () => {
const f = await fixture();
const receipt = await f.authority.execute(f.call);
expect(await f.target()).toMatchObject({ assigneeAgentId: f.nextId, status: "todo", statusVersion: 1, description: "Keep the existing plan and context" });
await expect(f.authority.execute({ ...f.call, callId: "retry" })).resolves.toEqual(receipt);
expect(f.stopTaskForReassignment).toHaveBeenCalledTimes(1);
expect(f.enqueueWakeup).toHaveBeenCalledWith(f.nextId, expect.objectContaining({ issueStateGuard: { statuses: ["todo"], assigneeAgentId: f.nextId, statusVersion: 1 } }));
expect(f.enqueueWakeup.mock.calls[0]![1].idempotencyKey).toEqual(f.enqueueWakeup.mock.calls[1]![1].idempotencyKey);
expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), eq(activityLog.action, "issue.reassigned")))).toHaveLength(1);
expect(await db.select().from(issueComments).where(eq(issueComments.issueId, f.targetId))).toHaveLength(1);
});
it.each(["blocked", "backlog"])("preserves %s and does not wake work prematurely", async status => {
const f = await fixture(status);
await f.authority.execute(f.call);
expect(await f.target()).toMatchObject({ assigneeAgentId: f.nextId, status });
expect(f.enqueueWakeup).not.toHaveBeenCalled();
});
it("replays across a replacement caller run without a second mutation", async () => {
const f = await fixture();
const receipt = await f.authority.execute(f.call);
const replacement = randomUUID();
await db.insert(heartbeatRuns).values({ id: replacement, companyId: f.companyId, agentId: f.agentId, nativeIssueId: f.issueId, runtimeMode: "native", status: "running", invocationSource: "assignment", triggerDetail: "system" });
await db.update(issues).set({ executionRunId: replacement }).where(eq(issues.id, f.issueId));
await expect(new PaperclipRunnerToolAuthority(db, { ...f.binding, runId: replacement }).execute(f.call)).resolves.toEqual(receipt);
expect((await f.target()).statusVersion).toBe(1);
});
it("repairs a dispatch failure by replaying the committed receipt", async () => {
const f = await fixture();
f.enqueueWakeup.mockRejectedValueOnce(new Error("queue unavailable"));
await expect(f.authority.execute(f.call)).rejects.toThrow("queue unavailable");
expect((await f.target()).assigneeAgentId).toBe(f.nextId);
await f.authority.execute(f.call);
expect(f.stopTaskForReassignment).toHaveBeenCalledTimes(1);
expect(f.enqueueWakeup).toHaveBeenCalledTimes(2);
});
it("rejects key reuse with different input and stale ownership/version", async () => {
const f = await fixture();
await f.authority.execute(f.call);
await expect(f.authority.execute({ ...f.call, arguments: { ...f.call.arguments, reason: "Changed intent" } })).rejects.toThrow("idempotency_conflict");
await expect(f.authority.execute({ ...f.call, arguments: { ...f.call.arguments, idempotencyKey: "stale" } })).rejects.toThrow("reassignment_conflict");
});
it("stops active execution before transferring ownership", async () => {
const f = await fixture("in_progress");
const oldRun = randomUUID();
await db.insert(heartbeatRuns).values({ id: oldRun, companyId: f.companyId, agentId: f.agentId, nativeIssueId: f.targetId, runtimeMode: "native", status: "running", invocationSource: "assignment", triggerDetail: "system" });
await db.update(issues).set({ executionRunId: oldRun, checkoutRunId: oldRun }).where(eq(issues.id, f.targetId));
f.stopTaskForReassignment.mockImplementationOnce(async () => {
expect((await f.target()).assigneeAgentId).toBe(f.agentId);
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, oldRun));
});
await f.authority.execute(f.call);
expect(await f.target()).toMatchObject({ assigneeAgentId: f.nextId, status: "todo", executionRunId: null, checkoutRunId: null });
});
it("does not transfer ownership if stop fails or a new run races the stop", async () => {
const f = await fixture();
f.stopTaskForReassignment.mockRejectedValueOnce(new Error("stop failed"));
await expect(f.authority.execute(f.call)).rejects.toThrow("stop failed");
expect((await f.target()).assigneeAgentId).toBe(f.agentId);
f.stopTaskForReassignment.mockImplementationOnce(async () => {
const runId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", invocationSource: "assignment", triggerDetail: "system" });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, f.targetId));
});
await expect(f.authority.execute(f.call)).rejects.toThrow("reassignment_conflict");
expect(f.enqueueWakeup).not.toHaveBeenCalled();
});
it.each(["version", "caller", "stop-error"])("restores the prior owner after a cancelled handoff loses %s", async conflict => {
const f = await fixture("in_progress");
const oldRun = randomUUID();
await db.insert(heartbeatRuns).values({ id: oldRun, companyId: f.companyId, agentId: f.agentId,
nativeIssueId: f.targetId, status: "running", runtimeMode: "native", invocationSource: "assignment", triggerDetail: "system" });
await db.update(issues).set({ executionRunId: oldRun }).where(eq(issues.id, f.targetId));
f.stopTaskForReassignment.mockImplementationOnce(async () => {
await db.update(heartbeatRuns).set({ status: "cancelled", errorCode: "issue_reassigned" }).where(eq(heartbeatRuns.id, oldRun));
if (conflict === "version") await db.update(issues).set({ statusVersion: 1 }).where(eq(issues.id, f.targetId));
if (conflict === "caller") await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId));
if (conflict === "stop-error") throw new Error("stop acknowledgement failed after cancellation");
});
await expect(f.authority.execute(f.call)).rejects.toThrow();
expect((await f.target()).assigneeAgentId).toBe(f.agentId);
expect(f.enqueueWakeup).toHaveBeenCalledExactlyOnceWith(f.agentId, expect.objectContaining({
payload: { issueId: f.targetId, mutation: "reassign_task_rollback", interruptedRunId: oldRun },
issueStateGuard: { statuses: ["todo", "in_progress"], assigneeAgentId: f.agentId, statusVersion: conflict === "version" ? 1 : 0 },
}));
});
it.each(["owner", "closed", "new-run"])("does not compensate over a newer %s decision", async conflict => {
const f = await fixture("in_progress");
const oldRun = randomUUID();
await db.insert(heartbeatRuns).values({ id: oldRun, companyId: f.companyId, agentId: f.agentId,
nativeIssueId: f.targetId, status: "running", runtimeMode: "native", invocationSource: "assignment", triggerDetail: "system" });
await db.update(issues).set({ executionRunId: oldRun }).where(eq(issues.id, f.targetId));
f.stopTaskForReassignment.mockImplementationOnce(async () => {
await db.update(heartbeatRuns).set({ status: "cancelled", errorCode: "issue_reassigned" }).where(eq(heartbeatRuns.id, oldRun));
const newRun = randomUUID();
if (conflict === "new-run") await db.insert(heartbeatRuns).values({ id: newRun, companyId: f.companyId,
agentId: f.agentId, status: "running", invocationSource: "assignment", triggerDetail: "system" });
await db.update(issues).set(conflict === "owner" ? { assigneeAgentId: f.nextId, statusVersion: 1 }
: conflict === "closed" ? { status: "done" } : { executionRunId: newRun }).where(eq(issues.id, f.targetId));
});
await expect(f.authority.execute(f.call)).rejects.toThrow();
expect(f.enqueueWakeup).not.toHaveBeenCalled();
});
it.each(["done", "cancelled", "in_review"])("rejects %s before interrupting work", async status => {
const f = await fixture(status);
await expect(f.authority.execute(f.call)).rejects.toThrow("state_denied");
expect(f.stopTaskForReassignment).not.toHaveBeenCalled();
});
it("rejects conversations and the caller’s own task", async () => {
const f = await fixture();
await db.update(issues).set({ conversationAgentId: f.agentId, conversationUserId: "test-user", conversationState: "active", status: "in_progress" }).where(eq(issues.id, f.targetId));
await expect(f.authority.execute(f.call)).rejects.toThrow("conversation_locked");
await expect(f.authority.execute({ ...f.call, arguments: { ...f.call.arguments, taskId: f.issueId } })).rejects.toThrow("current_task");
expect(f.stopTaskForReassignment).not.toHaveBeenCalled();
});
it.each(["planning", "ask", "skill_test"])("denies reassignment from %s mode", async workMode => {
const f = await fixture();
await db.update(issues).set({ workMode }).where(eq(issues.id, f.issueId));
await expect(f.authority.execute(f.call)).rejects.toThrow("mode_denied");
});
it("denies foreign targets and unavailable assignees", async () => {
const f = await fixture(), foreign = await fixture();
await expect(f.authority.execute({ ...f.call, arguments: { ...f.call.arguments, taskId: foreign.targetId } })).rejects.toThrow("task_not_found");
await expect(f.authority.execute({ ...f.call, arguments: { ...f.call.arguments, assigneeActorId: foreign.agentId } })).rejects.toThrow();
await db.update(agents).set({ status: "pending_approval" }).where(eq(agents.id, f.nextId));
await expect(f.authority.execute(f.call)).rejects.toThrow();
expect(f.stopTaskForReassignment).not.toHaveBeenCalled();
});
it("rejects an ownership ABA race through the existing issue service", async () => {
const f = await fixture();
await issueService(db).update(f.targetId, { assigneeAgentId: f.nextId });
await issueService(db).update(f.targetId, { assigneeAgentId: f.agentId });
expect((await f.target()).statusVersion).toBe(2);
await expect(f.authority.execute(f.call)).rejects.toThrow("reassignment_conflict");
expect(f.stopTaskForReassignment).not.toHaveBeenCalled();
});
it("respects protected assignment policies instead of inheriting board authority", async () => {
const f = await fixture();
await db.update(agents).set({ permissions: { authorizationPolicy: { protectedAgent: { blockAssignment: true } } } }).where(eq(agents.id, f.nextId));
await expect(f.authority.execute(f.call)).rejects.toThrow();
expect((await f.target()).assigneeAgentId).toBe(f.agentId);
expect(f.stopTaskForReassignment).not.toHaveBeenCalled();
});
it("rejects writes after the caller loses its run binding", async () => {
const f = await fixture();
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, f.runId));
await expect(f.authority.execute(f.call)).rejects.toThrow("binding_not_authorized");
expect((await f.target()).assigneeAgentId).toBe(f.agentId);
});
});