Files
PaperClipAI/server/src/services/native-runtime/blocker-owner-handoff.ts
T
f237785766 fix(native): save and wake the unblock owner a blocked report names (#22962)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - An agent reports a blocked task with `paperclip_block` and names the
unblock owner in `blocker.owner` (`kind` and `name`).
> - The server dropped an agent owner's name, so current-track blocks
saved `owner: "board"` and task-wide blocks fell back to the reporting
agent or its self-blocker retry path.
> - The named agent never became the unblock owner and never received a
wake, so work waiting on another agent stopped until a person reassigned
the task by hand.
> - PR #21265 fixed agent resolution and wake dispatch, but it
conflicted with newer master changes (named human owners in #22438 and
self-blocker continuations in #22140), carried a stale runner-check
failure from before #21726, and left a Greptile P1 where
external-chat-bound tasks failed finalization with
`chat_binding_agent_locked`.
> - This pull request rebases #21265 cleanly onto master, preserves
#22438 human-owner routing and #22140 self-blocker continuations,
enforces the full assignment/authorization/chat-lock/invokability
eligibility contract (including `tasks:assign` with run `keyScope` and
external `authorizingUserId`), and falls back safely to board ownership
if eligibility changes race before commit.
> - The benefit is that a blocked task moves to the named agent owner
and wakes that owner without manual reassignment, while chat-bound,
unauthorized, and conversation tasks never fail finalization with
`chat_binding_agent_locked` or bypass assignment policy.

## Linked Issues or Issue Description

Refs #21265 (supersedes with clean rebase onto master, Greptile P1
`chat_binding_agent_locked` fix, `tasks:assign` authorization
enforcement, and compatibility with #22438 and #22140).
Related: #20969, #22140, #22438.

**What happened?**
When an agent reports `blocked` with `blocker.owner: { kind: "agent",
name: "Review Lead" }`, the server drops the owner name. Current-track
blocks save `unblockDescriptor.owner` as `"board"`, and task-wide blocks
treat the report as the reporting agent's own blocker (triggering
self-continuation or board handoff). The named agent is never saved as
the unblock owner and never receives a wake.

**What did you expect?**
The server resolves a named agent owner against non-terminated company
agents (exact ID, trimmed NFC case-folded full name, URL key, or
initials), saves that agent in `unblockDescriptor`, hands the task to
it, and wakes it so its run starts. A person owner keeps #22438
company-member routing (or `"board"` when unresolved). A self-owned
blocker keeps #22140 fresh-session continuation. Unknown, ambiguous,
unavailable, unassignable, unauthorized, interaction-denied, or
chat-locked agent handoffs fail at report time with a clear message so
the agent can correct the report.

**Steps to reproduce**
1. Create two agents in one company: a worker and a reviewer (for
example `"Eligible status corpus delegate"`).
2. Assign a task to the worker and report `blocked` with `blocker.owner:
{ kind: "agent", name: "ESCD" }` (initials) or the full name for
`current_track` or `task_wide` scope.
3. Finalize the run and inspect `issue.unblockDescriptor.owner`,
`issue.assigneeAgentId`, and `agent_wakeup_requests`. On `master`,
`current_track` saves `"board"` and `task_wide` schedules a self-retry
for the worker instead of waking the named agent.

## What Changed

- Add leaf `server/src/services/native-runtime/blocker-owner.ts` (zero
service imports) and `blocker-owner.test.ts`:
- `matchBlockerOwnerAgent` resolves an agent by exact ID, trimmed NFC
case-folded full name (supports non-ASCII names such as `王明`), URL key,
then initials without falling through an ambiguous tier.
- `resolveNativeBlockerOwner` queries non-terminated company agents
(supporting `lockSources` shared row locks).
- Add `server/src/services/native-runtime/blocker-owner-handoff.ts`:
- Centralizes `evaluateBlockerAgentHandoff` and `hasExternalChatBinding`
for report-time validation, run finalization, and under-lock commit
rechecks: conversation/external-chat lock (`chatConversations`), agent
invokability, assignability, interaction policy, and
`authorizationService(db).decide({ action: "tasks:assign", ... })` with
run `keyScope` (`nativeRunKeyScope`) and external `authorizingUserId`.
- Add `server/src/modules/external-agents/run-authorizer.ts` (exported
via `modules/external-agents/index.ts`):
- Owns external-agent execution-input payload parsing and pinned
authorizer lookup (`resolveExternalRunAuthorizingUser`), returning a
normalized `{ status: "none" | "authorized" | "unavailable" }` contract
to keep provider-specific parsing inside `modules/external-agents`.
- Update `server/src/services/native-runtime/evidence-classifier.ts`:
- Carry `ownerAgentId` on `NativeEvidenceAssessment["blocker"]` while
preserving `ownerUserId` from `nativeBlockerUserId` (#22438).
- Mark unresolved agent names `boardOwned: true` so they never silently
fall back to the reporting agent.
- Update `server/src/services/native-runtime/status-arbiter.ts` (995
lines):
- Preserve named agent owners via `resolveBlockerHandoff` across
`current_track`, `task_wide`, and `durable_dependency_blocker_bound`
(carrying `handoffAgentId` while preserving `effects: []` until
dependencies resolve).
- Skip #22140 self-blocker recovery (`agentBlockerRecoverable`) and
queued-request self-supersession when the blocker names a *different*
agent.
- Honor `blockerHandoffLocked` by falling back cleanly to `"board"`
without queueing an unwakeable agent wake; strip `handoffAgentId` in
`supersedeHandedOffDecision`.
- Update
`server/src/services/native-runtime/native-completion-feedback.ts`,
`native-run-finalizer.ts`, `status-decision-committer.ts`, and
`server/src/services/chat-control-recovery-stop.ts`:
- Reject invalid, unauthorized, or chat-locked agent handoffs at report
time; resolve and verify eligibility under lock at commit time with safe
fallback to `"board"`; dispatch the named owner wake on handoff.
- Add unit and embedded-Postgres integration tests in
`blocker-owner.test.ts`, `evidence-classifier.test.ts`,
`status-arbiter.test.ts`, and `native-status-arbiter-corpus.test.ts`
(covering initials/full-name `current_track` and `task_wide` handoff +
wake dispatch, human owner preservation,
unknown/chat-locked/dependency-gated/policy-denied/`skill_test`
`keyScope` cases).

## Verification

- **RED-before-fix on base `2d06567795`:**
- `cd server && npx vitest run
src/services/native-runtime/evidence-classifier.test.ts
src/services/native-runtime/status-arbiter.test.ts` → 4 failed | 34
passed (38).
- **Local checks on final implementation:**
  - `node scripts/check-module-boundaries.mjs` → PASS
- `node scripts/check-test-budget.mjs --base
2d065677959b585065ff3fec8718156a4cf6f41d` → PASS (`110 nightly suites
validated, 4 test file(s) checked`)
- `pnpm --filter @paperclipai/server typecheck` → PASS across all 7
layers
- `cd server && npx vitest run
src/services/native-runtime/blocker-owner.test.ts
src/services/native-runtime/evidence-classifier.test.ts
src/services/native-runtime/status-arbiter.test.ts` → 49/49 passed
- `cd server && npx vitest run --hookTimeout=120000
src/__tests__/native-status-arbiter-corpus.test.ts -t "saves the unblock
owner|rejects a blocker owner agent name|rejects handing off an
external-chat-bound task|hands off a dependency-gated blocker"` → 6/6
passed (plus full 291/291 corpus/blocker/chat suite & 39/39
`github-retry-and-recovery.integration.test.ts`)
- **CI on head `aafddae13b`:**
- **70/70** executed checks `SUCCESS` (0 failing, 0 pending, 6 skipped,
2 non-blocking neutral Paperclip Review), including `ci / verify`, `ci /
e2e` + all 16 E2E shards, all 20 General server shards + chat +
workspaces, all 9 Serialized server shards, Verify Paperclip Runner,
Runner support (1–4/4), Build, Typecheck + Release Registry, policy,
`Superagent Security Scan`, `Socket Security`, `Contributor trust`,
`commitperclip`, `Snyk`, and `Greptile Review`.
- **Greptile:** **5/5** (`The PR appears safe to merge, with the
previous module-ownership finding addressed and no new actionable issues
found.`), 0 unresolved Greptile threads.

## Risks

- Low risk: existing `owner: "board"`, `owner: "agent"` (self-owned
blockers with #22140 continuation), and `owner: { kind: "user", ... }`
(#22438 named human owners) paths keep their existing semantics when no
distinct agent is named.
- If a task becomes chat-bound, unassignable, or unauthorized between
report validation and run finalization, finalization degrades safely to
`owner: "board"` instead of failing the commit.
- No database migrations or schema changes are required.

## Model Used

Gemini 3.1 Pro (Antigravity)

## Checklist

- [x] I have tested my changes locally
- [x] I have checked for any regressions
- [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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 15:31:46 -06:00

200 lines
6.9 KiB
TypeScript

import { agents, chatConversations, type Db } from "@paperclipai/db";
import { and, eq } from "drizzle-orm";
import { HttpError } from "../../errors.js";
import { isConversation } from "../../lib/conversation-wake-policy.js";
import { resolveExternalRunAuthorizingUser } from "../../modules/external-agents/index.js";
import { assertAssignableAgent } from "../agent-assignability.js";
import { agentInteractionDenial } from "../agent-interaction-policy.js";
import { evaluateAgentInvokabilityFromDb } from "../agent-invokability.js";
import { authorizationService, type AuthorizationActor } from "../authorization.js";
import { nativeRunKeyScope } from "./native-skill-test-scope.js";
export type BlockerHandoffEligibility =
| { allowed: true }
| {
allowed: false;
reason:
| "not_task_owner"
| "conversation_or_chat_locked"
| "unavailable"
| "unassignable"
| "unauthorized"
| "interaction_denied";
message: string;
};
/** Tasks bound to an external chat channel lock their agent assignment (`chat_binding_agent_locked`). */
export async function hasExternalChatBinding(
db: Db,
companyId: string,
issueId: string,
): Promise<boolean> {
const [binding] = await db
.select({ id: chatConversations.id })
.from(chatConversations)
.where(and(eq(chatConversations.companyId, companyId), eq(chatConversations.issueId, issueId)))
.limit(1);
return Boolean(binding);
}
/**
* Single authority check for handing a blocked task to another named agent.
* Shared across report-time feedback, finalizer arbitration, and the committer's
* under-lock recheck so all three layers enforce the exact same invariants,
* including `tasks:assign` authorization with the run's full principal (`keyScope`
* and external `authorizingUserId`), assignment policy, and interaction policy.
*/
export async function evaluateBlockerAgentHandoff(
db: Db,
input: {
companyId: string;
issue: {
id: string;
projectId: string | null;
parentId: string | null;
status: string;
workMode: string;
conversationAgentId: string | null;
conversationUserId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
};
runId: string;
actorAgentId: string | null;
responsibleUserId?: string | null;
driverKind?: string | null;
contextSnapshot?: unknown;
runnerProfileJson?: unknown;
targetAgentId: string;
unblockAction: string;
requireTaskOwner?: boolean;
lockSources?: boolean;
},
): Promise<BlockerHandoffEligibility> {
if (!input.actorAgentId) {
return {
allowed: false,
reason: "not_task_owner",
message: "Only the task's current assignee can hand this task off to another agent.",
};
}
if (
input.requireTaskOwner &&
(input.issue.assigneeUserId || input.issue.assigneeAgentId !== input.actorAgentId)
) {
return {
allowed: false,
reason: "not_task_owner",
message: "Only the task's current assignee can hand this task off to another agent.",
};
}
if (isConversation(input.issue) || await hasExternalChatBinding(db, input.companyId, input.issue.id)) {
return {
allowed: false,
reason: "conversation_or_chat_locked",
message: 'This task is bound to a conversation or external chat channel, so its agent assignment cannot be handed off to another agent. Create a separate task for that agent or report a person-owned blocker with kind "user".',
};
}
const agentQuery = db.select().from(agents).where(and(
eq(agents.id, input.targetAgentId),
eq(agents.companyId, input.companyId),
)).limit(1);
const [ownerAgent] = await (input.lockSources ? agentQuery.for("share", { noWait: true }) : agentQuery);
if (!ownerAgent || ownerAgent.status === "terminated" || !(await evaluateAgentInvokabilityFromDb(db, ownerAgent)).invokable) {
return {
allowed: false,
reason: "unavailable",
message: "The named blocker owner is not available in this company. Choose an available agent or name a person.",
};
}
try {
await assertAssignableAgent(db, input.companyId, input.targetAgentId, { kind: "work" });
} catch (error) {
if (error instanceof HttpError) {
return {
allowed: false,
reason: "unassignable",
message: `The named blocker owner cannot be assigned this task: ${error.message}. Choose an available agent or name a person.`,
};
}
throw error;
}
const externalAuthorizer = await resolveExternalRunAuthorizingUser(db, {
companyId: input.companyId,
agentId: input.actorAgentId,
driverKind: input.driverKind,
runnerProfileJson: input.runnerProfileJson,
});
if (externalAuthorizer.status === "unavailable") {
return {
allowed: false,
reason: "unauthorized",
message: "The named blocker owner cannot be assigned this task: external run authorizer is unavailable. Choose another agent or name a person.",
};
}
const actor: AuthorizationActor = {
type: "agent",
agentId: input.actorAgentId,
companyId: input.companyId,
runId: input.runId,
source: "agent_jwt",
onBehalfOfUserId: input.responsibleUserId ?? null,
keyScope: nativeRunKeyScope({
issueId: input.issue.id,
workMode: input.issue.workMode,
contextSnapshot: input.contextSnapshot,
}),
...(externalAuthorizer.status === "authorized"
? { authorizingUserId: externalAuthorizer.userId }
: {}),
};
const authDecision = await authorizationService(db).decide(
{
actor,
action: "tasks:assign",
resource: {
type: "issue",
companyId: input.companyId,
issueId: input.issue.id,
projectId: input.issue.projectId,
parentIssueId: input.issue.parentId,
assigneeAgentId: input.targetAgentId,
assigneeUserId: null,
status: input.issue.status,
},
scope: {
issueId: input.issue.id,
projectId: input.issue.projectId,
parentIssueId: input.issue.parentId,
assigneeAgentId: input.targetAgentId,
assigneeUserId: null,
},
},
{ interactionPolicy: "defer_to_mutation" },
);
if (!authDecision.allowed) {
return {
allowed: false,
reason: "unauthorized",
message: `The named blocker owner cannot be assigned this task: ${authDecision.explanation} Choose another agent or name a person.`,
};
}
const denial = await agentInteractionDenial(db, {
companyId: input.companyId,
actorAgentId: input.actorAgentId,
operation: "assign",
issueId: input.issue.id,
targetAgentId: input.targetAgentId,
texts: [input.unblockAction],
lock: input.lockSources,
});
if (denial) {
return {
allowed: false,
reason: "interaction_denied",
message: `The named blocker owner cannot receive this task: agent interaction is disabled by ${denial.permission}. Choose another agent or name a person.`,
};
}
return { allowed: true };
}