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>
This commit is contained in:
authored and GitHub committed 2026-11-25 15:31:46 -06:00
1 parent bff0f6dab5
commit f237785766
14 files changed
+799 -40

No files matched your search

@@ -22,6 +22,9 @@ import {
assets,
caseHandoffs,
cases,
chatConversations,
chatEndpointResources,
chatEndpoints,
heartbeatRunEvents,
issueAttachments,
approvals,
@@ -42,6 +45,8 @@ import {
nativeRunResults,
statusDecisionEffects,
statusDecisions,
toolApplications,
toolConnections,
workAssessments,
workspaceOperations,
} from "@paperclipai/db";
@@ -90,6 +95,7 @@ import {
import * as activityLog from "../services/activity-log.js";
import { dismissObsoleteNativePolicyReviews, registerObsoletePolicyReviewWork } from "../services/native-runtime/obsolete-policy-reviews.js";
import { issueService } from "../services/issues.js";
import { heartbeatService } from "../services/heartbeat.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
@@ -3357,6 +3363,180 @@ describe("P6-31 Section 18.13 executable status-authority corpus", () => {
expect((await issueThreadInteractionService(db).getById(seeded.interaction.id))!.status).toBe("cancelled");
}, 30_000);
it.each([
{ scope: "current_track", owner: { kind: "agent", name: "ESCD" }, saved: () => ({ agentId: delegateAgentId }) },
{ scope: "task_wide", owner: { kind: "agent", name: "Eligible status corpus delegate" }, saved: () => ({ agentId: delegateAgentId }) },
{ scope: "task_wide", owner: { kind: "user", name: "Avery Example" }, saved: () => "board" },
])("saves the unblock owner a $scope blocked report names ($owner.kind $owner.name) and wakes an agent owner", async ({ scope, owner, saved }) => {
const seeded = await seedFixture({ ...corpus.fixtures.find((fixture) => fixture.id === "real-task-wide-blocker")!, id: `named-blocker-owner-${randomUUID()}` });
const [stored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, seeded.resultId!));
const result = stored!.resultJson.result as { completionClaim: Record<string, unknown> };
const named = {
...result,
reportedWorkDisposition: "blocked",
completionClaim: { ...result.completionClaim, objectiveSatisfied: false,
remainingWork: [{ description: "Review the release notes draft.", blocksCompletion: true }] },
blocker: { reasonCode: "review_required", owner, unblockAction: "Review the release notes draft.", scope },
};
await db.update(nativeRunResults).set({ resultJson: { ...stored!.resultJson, result: named } })
.where(eq(nativeRunResults.id, seeded.resultId!));
await expect(nativeCompletionFeedback(db, seeded.runId, named as never)).resolves.toContain("Blocker report accepted");
await finalizeNativeRun({ db, runId: seeded.runId, workspaceFinalizeStatus: "succeeded" });
const issue = (await issueService(db).getById(seeded.issueId))!;
expect(issue.status).toBe("blocked");
expect(issue.unblockDescriptor).toEqual(expect.objectContaining({ owner: saved() }));
// Only the assignee's wake is dispatched, so a named agent owner must hold the task.
expect(issue.assigneeAgentId).toBe(owner.kind === "agent" ? delegateAgentId : agentId);
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
const ownerWakes = wakes.filter((wake) => (wake.payload as Record<string, unknown> | null)?.issueId === seeded.issueId && wake.agentId === delegateAgentId);
expect(ownerWakes).toHaveLength(owner.kind === "agent" ? 1 : 0);
if (owner.kind !== "agent") return;
// Dispatch admits the owner's wake instead of skipping it as another
// assignee's, or as a wake with no committed source.
await db.update(issues).set({ responsibleUserId: "corpus-board-user" }).where(eq(issues.id, seeded.issueId));
await heartbeatService(db).dispatchPendingNativeStatusWakeups({ companyId, requestId: ownerWakes[0]!.id });
const [dispatched] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, ownerWakes[0]!.id));
expect({ status: dispatched!.status, error: dispatched!.error }).toEqual({ status: "coalesced", error: null });
}, 30_000);
it("rejects a blocker owner agent name that matches no agent, before saving the block", async () => {
const seeded = await seedFixture({ ...corpus.fixtures.find((fixture) => fixture.id === "real-task-wide-blocker")!, id: `unknown-blocker-owner-${randomUUID()}` });
const [stored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, seeded.resultId!));
const result = stored!.resultJson.result as Record<string, unknown>;
await expect(nativeCompletionFeedback(db, seeded.runId, {
...result, reportedWorkDisposition: "blocked",
blocker: { reasonCode: "review_required", owner: { kind: "agent", name: "Nonexistent Reviewer" }, unblockAction: "Review the draft.", scope: "task_wide" },
} as never)).rejects.toThrow("matches no agent in this company");
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, seeded.runId))).toHaveLength(0);
}, 30_000);
it("rejects handing off an external-chat-bound task to another agent and falls back to board if bound before commit", async () => {
const seeded = await seedFixture({ ...corpus.fixtures.find((fixture) => fixture.id === "real-task-wide-blocker")!, id: `chat-locked-blocker-owner-${randomUUID()}` });
const [stored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, seeded.resultId!));
const result = stored!.resultJson.result as { completionClaim: Record<string, unknown> };
const named = {
...result,
reportedWorkDisposition: "blocked",
completionClaim: { ...result.completionClaim, objectiveSatisfied: false,
remainingWork: [{ description: "Review the release notes draft.", blocksCompletion: true }] },
blocker: { reasonCode: "review_required", owner: { kind: "agent", name: "ESCD" }, unblockAction: "Review the release notes draft.", scope: "task_wide" },
};
const appId = randomUUID(), connId = randomUUID(), endpointId = randomUUID(), resourceId = randomUUID();
await db.insert(toolApplications).values({ id: appId, companyId, applicationKey: `chat:slack:${endpointId}`, name: "Slack", type: "chat", status: "active" });
await db.insert(toolConnections).values({ id: connId, companyId, applicationId: appId, name: "Slack", uid: `chat-slack-${endpointId}`, connectionPurpose: "channel", transport: "chat_sdk", status: "active", enabled: true });
await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId: connId, provider: "slack", publicId: randomUUID(), assignedAgentId: agentId, status: "active", providerAccountId: "slack-bot", allowDirectMessages: true, allowUnlinkedPeople: false });
await db.insert(chatEndpointResources).values({ id: resourceId, companyId, endpointId, type: "direct_message", providerResourceId: `dm-${endpointId}`, label: "Slack DM", availability: "available", enabled: true });
await db.insert(chatConversations).values({ id: randomUUID(), companyId, endpointId, resourceId, issueId: seeded.issueId, externalConversationId: `conv-${endpointId}`, externalThreadId: `slack:${endpointId}`, sessionGeneration: 1, externalLabel: "Slack DM", isDirectMessage: true, state: "active" });
// Report-time feedback refuses the handoff while the agent can still correct it.
await expect(nativeCompletionFeedback(db, seeded.runId, named as never))
.rejects.toThrow("bound to a conversation or external chat channel");
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, seeded.runId))).toHaveLength(0);
// Even if a chat binding arrives before commit, finalization falls back to board
// instead of failing with chat_binding_agent_locked or queueing an unwakeable wake.
await db.update(nativeRunResults).set({ resultJson: { ...stored!.resultJson, result: named } })
.where(eq(nativeRunResults.id, seeded.resultId!));
await finalizeNativeRun({ db, runId: seeded.runId, workspaceFinalizeStatus: "succeeded" });
const issue = (await issueService(db).getById(seeded.issueId))!;
expect(issue.status).toBe("blocked");
expect(issue.assigneeAgentId).toBe(agentId);
expect(issue.unblockDescriptor).toEqual(expect.objectContaining({ owner: "board" }));
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
expect(wakes.filter((wake) => (wake.payload as Record<string, unknown> | null)?.issueId === seeded.issueId && wake.agentId === delegateAgentId)).toHaveLength(0);
}, 30_000);
it("hands off a dependency-gated blocker to its named agent without waking early, and falls back to board on interaction denial", async () => {
const depSeeded = await seedFixture({ ...corpus.fixtures.find((fixture) => fixture.id === "real-task-wide-blocker")!, id: `dep-named-blocker-${randomUUID()}` });
const [blockerIssue] = await db.insert(issues).values({
companyId, title: "Upstream prerequisite", status: "in_progress", workMode: "standard", assigneeAgentId: agentId,
}).returning();
await db.insert(issueRelations).values({ companyId, issueId: blockerIssue!.id, relatedIssueId: depSeeded.issueId, type: "blocks" });
const [depStored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, depSeeded.resultId!));
const depNamed = {
...(depStored!.resultJson.result as Record<string, unknown>),
reportedWorkDisposition: "blocked",
blocker: { reasonCode: "review_required", owner: { kind: "agent", name: "ESCD" }, unblockAction: "Review once upstream finishes.", scope: "current_track" },
};
await db.update(nativeRunResults).set({ resultJson: { ...depStored!.resultJson, result: depNamed } })
.where(eq(nativeRunResults.id, depSeeded.resultId!));
await finalizeNativeRun({ db, runId: depSeeded.runId, workspaceFinalizeStatus: "succeeded" });
const depIssue = (await issueService(db).getById(depSeeded.issueId))!;
expect(depIssue.status).toBe("blocked");
expect(depIssue.assigneeAgentId).toBe(delegateAgentId);
expect(depIssue.unblockDescriptor).toEqual(expect.objectContaining({ owner: { agentId: delegateAgentId } }));
const depWakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId));
expect(depWakes.filter((wake) => (wake.payload as Record<string, unknown> | null)?.issueId === depSeeded.issueId && wake.agentId === delegateAgentId)).toHaveLength(0);
// If agent-to-agent assignment permission is disabled before commit, finalization
// falls back cleanly to board instead of failing settlement.
const deniedSeeded = await seedFixture({ ...corpus.fixtures.find((fixture) => fixture.id === "real-task-wide-blocker")!, id: `denied-named-blocker-${randomUUID()}` });
const [deniedStored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, deniedSeeded.resultId!));
const deniedNamed = {
...(deniedStored!.resultJson.result as Record<string, unknown>),
reportedWorkDisposition: "blocked",
blocker: { reasonCode: "review_required", owner: { kind: "agent", name: "ESCD" }, unblockAction: "Review the release notes draft.", scope: "task_wide" },
};
await db.update(nativeRunResults).set({ resultJson: { ...deniedStored!.resultJson, result: deniedNamed } })
.where(eq(nativeRunResults.id, deniedSeeded.resultId!));
await db.update(agents).set({ permissions: { interactions: { canAssignTasksToAgents: false } } }).where(eq(agents.id, agentId));
try {
await finalizeNativeRun({ db, runId: deniedSeeded.runId, workspaceFinalizeStatus: "succeeded" });
const deniedIssue = (await issueService(db).getById(deniedSeeded.issueId))!;
expect(deniedIssue.status).toBe("blocked");
expect(deniedIssue.assigneeAgentId).toBe(agentId);
expect(deniedIssue.unblockDescriptor).toEqual(expect.objectContaining({ owner: "board" }));
} finally {
await db.update(agents).set({ permissions: {} }).where(eq(agents.id, agentId));
}
// Protected target-agent assignmentPolicy (tasks:assign authorization) also
// rejects handoff at report time and falls back cleanly to board on commit.
const policySeeded = await seedFixture({ ...corpus.fixtures.find((fixture) => fixture.id === "real-task-wide-blocker")!, id: `policy-denied-blocker-${randomUUID()}` });
const [policyStored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, policySeeded.resultId!));
const policyNamed = {
...(policyStored!.resultJson.result as Record<string, unknown>),
reportedWorkDisposition: "blocked",
blocker: { reasonCode: "review_required", owner: { kind: "agent", name: "ESCD" }, unblockAction: "Review the release notes draft.", scope: "task_wide" },
};
await db.update(agents).set({
permissions: { authorizationPolicy: { assignmentPolicy: { mode: "protected" } } },
}).where(eq(agents.id, delegateAgentId));
try {
await expect(nativeCompletionFeedback(db, policySeeded.runId, policyNamed as never))
.rejects.toThrow("cannot be assigned this task");
await db.update(nativeRunResults).set({ resultJson: { ...policyStored!.resultJson, result: policyNamed } })
.where(eq(nativeRunResults.id, policySeeded.resultId!));
await finalizeNativeRun({ db, runId: policySeeded.runId, workspaceFinalizeStatus: "succeeded" });
const policyIssue = (await issueService(db).getById(policySeeded.issueId))!;
expect(policyIssue.status).toBe("blocked");
expect(policyIssue.assigneeAgentId).toBe(agentId);
expect(policyIssue.unblockDescriptor).toEqual(expect.objectContaining({ owner: "board" }));
} finally {
await db.update(agents).set({ permissions: {} }).where(eq(agents.id, delegateAgentId));
}
// Skill-test runs carry a restricted keyScope and cannot hand off via blocker.
const skillSeeded = await seedFixture({ ...corpus.fixtures.find((fixture) => fixture.id === "real-task-wide-blocker")!, id: `skill-test-blocker-${randomUUID()}` });
const [skillStored] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, skillSeeded.resultId!));
const skillNamed = {
...(skillStored!.resultJson.result as Record<string, unknown>),
reportedWorkDisposition: "blocked",
blocker: { reasonCode: "review_required", owner: { kind: "agent", name: "ESCD" }, unblockAction: "Review the release notes draft.", scope: "task_wide" },
};
await db.update(heartbeatRuns).set({ contextSnapshot: { paperclipSkillTest: true } }).where(eq(heartbeatRuns.id, skillSeeded.runId));
await expect(nativeCompletionFeedback(db, skillSeeded.runId, skillNamed as never))
.rejects.toThrow("cannot be assigned this task");
await db.update(nativeRunResults).set({ resultJson: { ...skillStored!.resultJson, result: skillNamed } })
.where(eq(nativeRunResults.id, skillSeeded.resultId!));
await finalizeNativeRun({ db, runId: skillSeeded.runId, workspaceFinalizeStatus: "succeeded" });
const skillIssue = (await issueService(db).getById(skillSeeded.issueId))!;
expect(skillIssue.status).toBe("blocked");
expect(skillIssue.assigneeAgentId).toBe(agentId);
expect(skillIssue.unblockDescriptor).toEqual(expect.objectContaining({ owner: "board" }));
}, 30_000);
it("withdraws obsolete policy reviews, restores the prior status, and is idempotent", async () => {
const seeded = await seedPolicyReview();
await reconcileNativeFinalizations(db, [seeded.runId]);
@@ -21,3 +21,4 @@ export function createDotPrincipalHttp(oauth: Parameters<typeof dotPrincipalCont
}
export { notifyMuseContactVerification, pendingMuseContactVerifications, parseMuseVerificationHint, type MuseVerificationScope } from "./muse-verification-work.js";
export { resolveExternalRunAuthorizingUser, type ExternalRunAuthorizingUser } from "./run-authorizer.js";
@@ -0,0 +1,52 @@
import type { Db } from "@paperclipai/db";
import { HttpError } from "../../errors.js";
import { museExternalAgents } from "./muse.js";
export type ExternalRunAuthorizingUser =
| { status: "none" }
| { status: "authorized"; userId: string }
| { status: "unavailable" };
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown> : {};
}
/** Resolve the pinned external authorizer for an external-agent run, failing closed if missing or revoked. */
export async function resolveExternalRunAuthorizingUser(
db: Db,
input: {
companyId: string;
agentId: string;
driverKind?: string | null;
runnerProfileJson?: unknown;
},
): Promise<ExternalRunAuthorizingUser> {
const execution = record(record(input.runnerProfileJson).nativeExecutionInput);
const provider = record(execution.provider);
const isMuse = input.driverKind === "muse_external"
|| execution.schema === "paperclip.native-execution-input.v8"
|| provider.kind === "muse";
if (!isMuse) return { status: "none" };
const binding = record(provider.binding);
if (
binding.companyId !== input.companyId ||
binding.agentId !== input.agentId ||
typeof binding.bindingId !== "string" ||
typeof binding.bindingGeneration !== "number"
) {
return { status: "unavailable" };
}
try {
const userId = await museExternalAgents(db).authorizingUserIdForBinding({
companyId: binding.companyId,
agentId: binding.agentId,
bindingId: binding.bindingId,
bindingGeneration: binding.bindingGeneration,
});
return { status: "authorized", userId };
} catch (error) {
if (error instanceof HttpError) return { status: "unavailable" };
throw error;
}
}
@@ -143,9 +143,18 @@ export async function readChatControlNativeParent(
// A committed continuation or failed-turn retry effect that targets
// this intent is its proof. Refusing the retry stranded the task
// with no queued work.
inArray(statusDecisionEffects.effectKind, NATIVE_STATUS_WAKE_EFFECT_KINDS),
eq(statusDecisionEffects.targetType, "agent_wakeup_request"),
eq(statusDecisionEffects.targetId, intent.id),
// A bound blocker records the owner wake it queued in its payload.
or(
and(
inArray(statusDecisionEffects.effectKind, NATIVE_STATUS_WAKE_EFFECT_KINDS),
eq(statusDecisionEffects.targetType, "agent_wakeup_request"),
eq(statusDecisionEffects.targetId, intent.id),
),
and(
eq(statusDecisionEffects.effectKind, "bind_blocker"),
sql`${statusDecisionEffects.payload}->>'wakeId' = ${intent.id}`,
),
),
eq(statusDecisionEffects.deliveryState, "delivered"),
),
)
@@ -0,0 +1,199 @@
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 };
}
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { matchBlockerOwnerAgent } from "./blocker-owner.js";
const lead = { id: "00000000-0000-4000-8000-000000000101", name: "Release Desk Lead" };
const writer = { id: "00000000-0000-4000-8000-000000000102", name: "Writer" };
const rows = [lead, writer];
describe("matchBlockerOwnerAgent", () => {
it.each([
["exact ID", lead.id],
["full name", "Release Desk Lead"],
["name in another case", "release desk lead"],
["name initials", "RDL"],
])("resolves an agent by %s", (_label, reference) => {
expect(matchBlockerOwnerAgent(rows, reference)).toEqual({ agentId: lead.id });
});
it("resolves a non-ASCII full name", () => {
const named = { id: "00000000-0000-4000-8000-000000000105", name: "王明" };
expect(matchBlockerOwnerAgent([...rows, named], " 王明 ")).toEqual({ agentId: named.id });
});
it("does not resolve an unknown name or another company's ID", () => {
expect(matchBlockerOwnerAgent(rows, "Nonexistent Reviewer")).toEqual({ agentId: null, ambiguous: false });
expect(matchBlockerOwnerAgent(rows, "00000000-0000-4000-8000-000000000999")).toEqual({ agentId: null, ambiguous: false });
});
it("reports an ambiguous name instead of picking one agent", () => {
const twin = { id: "00000000-0000-4000-8000-000000000103", name: "Regional Desk Lead" };
expect(matchBlockerOwnerAgent([...rows, twin], "RDL")).toEqual({ agentId: null, ambiguous: true });
});
it("prefers a full-name match over another agent's initials", () => {
const short = { id: "00000000-0000-4000-8000-000000000104", name: "RDL" };
expect(matchBlockerOwnerAgent([...rows, short], "RDL")).toEqual({ agentId: short.id });
});
});
@@ -0,0 +1,79 @@
import { agents, type Db } from "@paperclipai/db";
import { isUuidLike, normalizeAgentUrlKey } from "@paperclipai/shared";
import { and, eq, ne } from "drizzle-orm";
/**
* The owner a blocked report names, resolved against the company.
* `board` covers the board and named people; `agent` is a resolved agent;
* `unresolved` is an agent name that matches no agent or more than one.
*/
export type NativeBlockerOwnerResolution =
| { kind: "board" }
| { kind: "agent"; agentId: string }
| { kind: "unresolved"; name: string | null; ambiguous: boolean }
| { kind: "unspecified" };
type AgentRow = { id: string; name: string };
function record(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown> : {};
}
function initials(name: string): string | null {
const words = normalizeAgentUrlKey(name)?.split("-") ?? [];
return words.length > 1 ? words.map((word) => word[0]).join("") : null;
}
function foldName(name: string): string {
return name.trim().normalize("NFC").toLocaleLowerCase();
}
/**
* Match an agent reference by exact ID, then by exact name (case-folded, so
* non-ASCII names match), then by URL-key name, then by the name's initials
* ("RDL" for "Release Desk Lead"). A tier with several matches is ambiguous;
* it never falls through to a looser tier.
*/
export function matchBlockerOwnerAgent(rows: readonly AgentRow[], reference: string):
{ agentId: string; ambiguous?: never } | { agentId: null; ambiguous: boolean } {
const raw = reference.trim();
if (isUuidLike(raw)) {
const byId = rows.find((row) => row.id.toLowerCase() === raw.toLowerCase());
return byId ? { agentId: byId.id } : { agentId: null, ambiguous: false };
}
const folded = foldName(raw);
const key = normalizeAgentUrlKey(raw);
if (!folded) return { agentId: null, ambiguous: false };
for (const tier of [
(row: AgentRow) => foldName(row.name) === folded,
(row: AgentRow) => Boolean(key) && normalizeAgentUrlKey(row.name) === key,
(row: AgentRow) => Boolean(key) && initials(row.name) === key,
]) {
const matches = rows.filter(tier);
if (matches.length === 1) return { agentId: matches[0]!.id };
if (matches.length > 1) return { agentId: null, ambiguous: true };
}
return { agentId: null, ambiguous: false };
}
/** Resolve a provider-reported `blocker.owner` without trusting its shape. */
export async function resolveNativeBlockerOwner(
db: Db,
input: { companyId: string; owner: unknown; lockSources?: boolean },
): Promise<NativeBlockerOwnerResolution> {
const owner = record(input.owner);
if (owner.kind === "board" || owner.owner === "board") return { kind: "board" };
// A person cannot be woken as an agent; the board is where people act.
if (owner.kind === "user") return { kind: "board" };
if (owner.kind !== "agent") return { kind: "unspecified" };
const name = typeof owner.name === "string" && owner.name.trim() ? owner.name.trim() : null;
if (!name) return { kind: "unresolved", name: null, ambiguous: false };
const query = db.select({ id: agents.id, name: agents.name }).from(agents)
.where(and(eq(agents.companyId, input.companyId), ne(agents.status, "terminated")));
const rows = await (input.lockSources ? query.for("share", { noWait: true }) : query);
const match = matchBlockerOwnerAgent(rows, name);
return match.agentId
? { kind: "agent", agentId: match.agentId }
: { kind: "unresolved", name, ambiguous: match.ambiguous ?? false };
}
@@ -131,4 +131,36 @@ describe("classifyNativeEvidence", () => {
reasonCode: "interaction_resolved",
});
});
describe("blocker owner", () => {
const reviewerId = "00000000-0000-4000-8000-000000000201";
const agentRows = [{ id: reviewerId, name: "Chief of Review" }];
const agentsDb = {
select: () => ({
from: () => ({
where: () => Object.assign(Promise.resolve(agentRows), { limit: () => Promise.resolve(agentRows) }),
}),
}),
} as unknown as Db;
const blocked = (owner: Record<string, unknown>, scope = "current_track") => ({
reportedWorkDisposition: "blocked",
summary: "Waiting for review",
completionClaim: { contractRevision: "1", objectiveSatisfied: false, criteria: [], remainingWork: [{ description: "Review", blocksCompletion: true }] },
blocker: { reasonCode: "review_required", owner, unblockAction: "Review the draft.", scope },
});
it("keeps the agent the report names, resolved from its short name", async () => {
const assessment = await classifyNativeEvidence({ ...input, db: agentsDb, result: blocked({ kind: "agent", name: "COR" }) });
expect(assessment.blocker).toEqual({
unblockAction: "Review the draft.", boardOwned: false, ownerKind: "agent", ownerAgentId: reviewerId, scope: "current_track",
});
});
it("gives a person owner to the board instead of the reporting agent", async () => {
const assessment = await classifyNativeEvidence({ ...input, db: agentsDb, result: blocked({ kind: "user", name: "Avery Example" }, "task_wide") });
expect(assessment.blocker).toEqual({
unblockAction: "Review the draft.", boardOwned: true, ownerKind: "user", ownerAgentId: null, scope: "task_wide",
});
});
});
});
@@ -1,6 +1,7 @@
import { and, eq, or } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { nativeBlockerUserId } from "./native-blocker-owner.js";
import { resolveNativeBlockerOwner } from "./blocker-owner.js";
import {
approvals,
caseHandoffs,
@@ -76,6 +77,8 @@ export interface NativeEvidenceAssessment {
boardOwned: boolean;
ownerKind?: NativeBlockerOwnerKind;
ownerUserId?: string;
/** The agent the report named as unblock owner, when it resolved to one. */
ownerAgentId?: string | null;
scope: "current_track" | "task_wide";
} | null;
continuation: {
@@ -402,6 +405,14 @@ export async function classifyNativeEvidence(input: {
actionableAttentionRequests.push(request);
}
const resolvedOwner = reported === "blocked" && typeof blocker.unblockAction === "string"
? await resolveNativeBlockerOwner(input.db, {
companyId: input.companyId,
owner: blocker.owner,
lockSources: input.lockSources,
})
: { kind: "unspecified" as const };
return {
objectiveClaimSatisfied: claim.objectiveSatisfied === true,
objectiveSatisfied: claim.objectiveSatisfied === true && allCriteriaSatisfied,
@@ -430,9 +441,13 @@ export async function classifyNativeEvidence(input: {
blocker: reported === "blocked" && typeof blocker.unblockAction === "string"
? {
unblockAction: blocker.unblockAction,
boardOwned: ["board", "user"].includes(String(blockerOwner.kind)) || blockerOwner.owner === "board",
// A person owner is acted on by the board (or resolved company member).
// An agent name that cannot be resolved stays visible to the board
// rather than silently falling back to the reporting agent.
boardOwned: resolvedOwner.kind === "board" || resolvedOwner.kind === "unresolved",
...(ownerUserId ? { ownerUserId } : {}),
ownerKind: nativeBlockerOwnerKind(blockerOwner),
ownerAgentId: resolvedOwner.kind === "agent" ? resolvedOwner.agentId : null,
scope: blocker.scope === "task_wide" ? "task_wide" : "current_track",
}
: null,
@@ -8,6 +8,8 @@ import { publishedTaskDocuments, validateNativeDeliverableEvidence } from "./nat
import { findAutomaticCompletionReviews } from "./automatic-completion-reviews.js";
import { findSupersededExternalReviewRequests } from "./superseded-external-review-requests.js";
import { evaluateAgentInvokabilityFromDb } from "../agent-invokability.js";
import { resolveNativeBlockerOwner } from "./blocker-owner.js";
import { evaluateBlockerAgentHandoff } from "./blocker-owner-handoff.js";
import { issueService } from "../issues.js";
import { isConversation } from "../agent-conversations.js";
import { completionReviewStageEntry } from "../issue-execution-policy.js";
@@ -173,6 +175,28 @@ export async function nativeCompletionFeedback(
throw new Error("A monitor wait requires a persisted, eligible monitor on this task. Call set_task_monitor for the current task, confirm its schedule, then report yielded with continuation.kind monitor.");
}
}
if (result.reportedWorkDisposition === "blocked" && result.blocker?.owner.kind === "agent") {
// The saved owner must be the agent the report named, so it can be woken.
const owner = await resolveNativeBlockerOwner(db, { companyId: run.companyId, owner: result.blocker.owner });
if (owner.kind !== "agent") {
throw new Error(`blocker.owner names agent ${JSON.stringify(result.blocker.owner.name)}, which ${owner.kind === "unresolved" && owner.ambiguous ? "matches more than one agent" : "matches no agent"} in this company. Set blocker.owner.name to the owner's exact agent ID or full agent name, or use kind "user" for a person.`);
}
if (owner.agentId !== run.agentId) {
const handoff = await evaluateBlockerAgentHandoff(db, {
companyId: run.companyId,
issue,
runId: run.id,
actorAgentId: run.agentId,
responsibleUserId: run.responsibleUserId,
driverKind: run.driverKind,
contextSnapshot: run.contextSnapshot,
runnerProfileJson: run.runnerProfileJson,
targetAgentId: owner.agentId,
unblockAction: result.blocker.unblockAction,
});
if (!handoff.allowed) throw new Error(handoff.message);
}
}
const signals = normalizePrpResultSignals(result);
if (
result.reportedWorkDisposition === "done" &&
@@ -76,6 +76,7 @@ import {
type NativeAuthoritativeIssueStatus,
gateDoneOnConfiguredReview,
} from "./status-arbiter.js";
import { evaluateBlockerAgentHandoff } from "./blocker-owner-handoff.js";
import { recordNativeWorkAssessment } from "./work-assessments.js";
import {
commitNativeStatusDecision,
@@ -1820,6 +1821,21 @@ export async function finalizeNativeRun(input: {
const reviewStage = isConversation(authoritativeIssue) || reviewContext
? { kind: "none" as const } : completionReviewStageEntry(authoritativeIssue, run.agentId);
await cancelStoppedRunContinuation(input.db, { companyId: run.companyId, resultJson: savedStop }, toolCallLoopContinuationKey(run.id));
const namedBlockerAgentId = assessment.blocker?.ownerAgentId && assessment.blocker.ownerAgentId !== run.agentId
? assessment.blocker.ownerAgentId : null;
const blockerHandoffLocked = namedBlockerAgentId !== null && !(await evaluateBlockerAgentHandoff(input.db, {
companyId: run.companyId,
issue: authoritativeIssue,
runId: run.id,
actorAgentId: run.agentId,
responsibleUserId: run.responsibleUserId,
driverKind: run.driverKind,
contextSnapshot: run.contextSnapshot,
runnerProfileJson: run.runnerProfileJson,
targetAgentId: namedBlockerAgentId,
unblockAction: assessment.blocker!.unblockAction,
requireTaskOwner: true,
})).allowed;
const statusInput: Parameters<typeof resolveNativeFinalizerStatus>[0] = {
requiredQualityReviewSatisfied: qualityReview.satisfied,
executionStageApprovedByRun: await executionStageApprovedByRun(input.db, run, authoritativeIssue),
@@ -1841,6 +1857,7 @@ export async function finalizeNativeRun(input: {
&& isNativeEnvironmentBlocker(result),
agentBlockerRecoverable: terminalState === "succeeded" && ownsProviderFailureDecision && !reviewContext && !stopRequested
&& result.reportedWorkDisposition === "blocked",
blockerHandoffLocked,
hasQueuedChatRequest: terminalState === "succeeded" && result.reportedWorkDisposition === "blocked"
&& await hasQueuedChatRequest(input.db, { companyId: run.companyId, issueId: authoritativeIssue.id, agentId: run.agentId }),
failureRetryCount: executionFailureRetryCount(run),
@@ -821,4 +821,74 @@ describe("native status authority", () => {
expect(arbitrate({ assessment: blocked("agent"), agentBlockerRecoverable: true, ...held })).toMatchObject({ reasonCode: "task_wide_blocker_bound" });
}
});
it.each(["current_track", "task_wide"] as const)("saves and wakes the agent a %s blocker names as its owner", (scope) => {
const action = "Review the release notes draft.";
expect(
arbitrate({
agentBlockerRecoverable: true,
assessment: assessment({
reportedDisposition: "blocked",
hasBlockingRemainingWork: true,
blocker: { boardOwned: false, ownerKind: "agent", ownerAgentId: "reviewer", scope, unblockAction: action },
}),
}),
).toEqual(
expect.objectContaining({
toStatus: "blocked",
handoffAgentId: "reviewer",
unblockDescriptor: { owner: { agentId: "reviewer" }, action },
// bind_blocker wakes a non-board owner; the reporting agent is not re-woken.
effects: [{ kind: "bind_blocker", owner: { agentId: "reviewer" }, action }],
}),
);
});
it.each(["current_track", "task_wide"] as const)("falls back to board without handoff when a %s named-agent blocker is assignment-locked", (scope) => {
const action = "Review the release notes draft.";
const decision = arbitrate({
agentBlockerRecoverable: true,
blockerHandoffLocked: true,
assessment: assessment({
reportedDisposition: "blocked",
hasBlockingRemainingWork: true,
blocker: { boardOwned: false, ownerKind: "agent", ownerAgentId: "reviewer", scope, unblockAction: action },
}),
});
expect(decision).toEqual(
expect.objectContaining({
toStatus: "blocked",
unblockDescriptor: { owner: "board", action },
effects: [{ kind: "bind_blocker", owner: "board", action }],
}),
);
expect(decision.handoffAgentId).toBeUndefined();
});
it("carries named-agent handoff on a dependency-gated block while preserving the dependency gate", () => {
const action = "Review after upstream finishes.";
const blocked = assessment({
reportedDisposition: "blocked",
blocker: { boardOwned: false, ownerKind: "agent", ownerAgentId: "reviewer", scope: "current_track", unblockAction: action },
});
expect(arbitrate({ assessment: blocked, hasUnresolvedIssueBlockers: true })).toEqual(
expect.objectContaining({
toStatus: "blocked",
reasonCode: "durable_dependency_blocker_bound",
handoffAgentId: "reviewer",
unblockDescriptor: { owner: { agentId: "reviewer" }, action },
effects: [],
}),
);
const locked = arbitrate({ assessment: blocked, hasUnresolvedIssueBlockers: true, blockerHandoffLocked: true });
expect(locked).toEqual(
expect.objectContaining({
toStatus: "blocked",
reasonCode: "durable_dependency_blocker_bound",
unblockDescriptor: { owner: "board", action },
effects: [],
}),
);
expect(locked.handoffAgentId).toBeUndefined();
});
});
@@ -105,12 +105,24 @@ export interface NativeStatusDecision {
} | null;
effects: NativeStatusEffect[];
blockerOwnerKind?: string;
/** Hand the task to this agent when a blocked report names another agent owner. */
handoffAgentId?: string;
}
function humanBlockerOwner(blocker: NativeEvidenceAssessment["blocker"]): IssueUnblockDescriptor["owner"] {
return blocker?.ownerUserId ? { userId: blocker.ownerUserId } : "board";
}
/** Resolve the saved unblock owner and optional handoff target for a blocker. */
function resolveBlockerHandoff(blocker: NativeEvidenceAssessment["blocker"], agentId: string, handoffLocked?: boolean):
{ owner: IssueUnblockDescriptor["owner"]; handoffAgentId?: string; namedOtherAgent: boolean } {
const raw = blocker?.ownerAgentId ? { agentId: blocker.ownerAgentId }
: blocker?.boardOwned ? humanBlockerOwner(blocker) : { agentId };
const namedOtherAgent = typeof raw === "object" && "agentId" in raw && raw.agentId !== agentId;
if (!namedOtherAgent) return { owner: raw, namedOtherAgent: false };
return handoffLocked ? { owner: "board", namedOtherAgent: true } : { owner: raw, handoffAgentId: raw.agentId, namedOtherAgent: true };
}
/**
* Completion is the current owner's decision. A run whose task was reassigned
* away (to another agent or to a user) keeps its accepted result as history,
@@ -199,7 +211,10 @@ export function supersedeHandedOffDecision(
&& !(effect.kind === "record_finalization_error" && effect.cause !== "workspace_finalization_failed"));
const governed = effects.some(effect => effect.kind === "create_interaction");
if (decision.statusAction === "preserve" || governed) {
return effects.length === decision.effects.length ? decision : { ...decision, effects };
const { handoffAgentId: _handoff, ...rest } = decision;
return effects.length === decision.effects.length && !decision.handoffAgentId
? decision
: { ...rest, effects };
}
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
@@ -274,6 +289,8 @@ export function arbitrateNativeStatus(input: {
/** The current owner's blocked report names a system-owned environment or tool outage. */
environmentBlocker?: boolean;
agentBlockerRecoverable?: boolean;
/** The task cannot change agent assignee (conversation, external chat binding, non-owner run, or unassignable owner). */
blockerHandoffLocked?: boolean;
/** A chat request for this task and agent is waiting as a deferred wake behind this run. */
hasQueuedChatRequest?: boolean;
failureRetryCount?: number;
@@ -526,22 +543,23 @@ export function arbitrateNativeStatus(input: {
input.hasUnresolvedIssueBlockers === true &&
(["done", "blocked"].includes(input.assessment.reportedDisposition) || unfinishedResponseWait || input.assessment.continuation?.kind === "monitor")
) {
const owner = input.assessment.blocker?.boardOwned
? humanBlockerOwner(input.assessment.blocker)
: { agentId: input.agentId };
const { owner, handoffAgentId } = resolveBlockerHandoff(
input.assessment.blocker, input.agentId, input.blockerHandoffLocked,
);
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "blocked",
toStatus: "blocked",
reasonCode: "durable_dependency_blocker_bound",
...(handoffAgentId ? { handoffAgentId } : {}),
unblockDescriptor: {
owner,
action:
input.assessment.blocker?.unblockAction ??
"Wait for the issue's durable dependency blockers to complete.",
},
// Dependency completion owns the wake. Do not immediately rerun the
// blocked issue merely because the provider mislabeled its scope/status.
// Dependency completion owns the wake (and wakes the current assignee,
// which becomes handoffAgentId when a named agent takes over).
effects: [],
};
}
@@ -650,11 +668,12 @@ export function arbitrateNativeStatus(input: {
// an external owner, or one whose automatic continuations are spent, is still
// bound now.
const blocker = input.assessment.blocker;
const namedOtherAgent = Boolean(blocker?.ownerAgentId && blocker.ownerAgentId !== input.agentId);
const retries = input.failureRetryCount ?? 0;
const continuesAutomatically = Boolean(blocker) && !input.isConversation && !input.hasActivePauseHold && (
(input.environmentBlocker === true && retries < NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES) ||
(input.agentBlockerRecoverable === true && blocker!.scope === "task_wide" && !blocker!.boardOwned &&
blocker!.ownerKind === "agent" && retries < NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS));
!namedOtherAgent && blocker!.ownerKind === "agent" && retries < NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS));
if (input.assessment.reportedDisposition === "blocked" && input.hasQueuedChatRequest && continuesAutomatically) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
@@ -692,6 +711,7 @@ export function arbitrateNativeStatus(input: {
input.assessment.reportedDisposition === "blocked" &&
input.assessment.blocker?.scope === "task_wide" &&
!input.assessment.blocker.boardOwned &&
!namedOtherAgent &&
input.agentBlockerRecoverable &&
!input.isConversation
) {
@@ -719,9 +739,10 @@ export function arbitrateNativeStatus(input: {
input.assessment.reportedDisposition === "blocked" &&
input.assessment.blocker
) {
const owner = input.assessment.blocker.boardOwned
? humanBlockerOwner(input.assessment.blocker)
: { agentId: input.agentId };
const { owner, handoffAgentId, namedOtherAgent } = resolveBlockerHandoff(
input.assessment.blocker, input.agentId, input.blockerHandoffLocked,
);
const action = input.assessment.blocker.unblockAction;
if (input.assessment.blocker.scope === "task_wide") {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
@@ -729,44 +750,31 @@ export function arbitrateNativeStatus(input: {
toStatus: "blocked",
reasonCode: "task_wide_blocker_bound",
blockerOwnerKind: input.assessment.blocker.ownerKind,
unblockDescriptor: {
owner,
action: input.assessment.blocker.unblockAction,
},
...(handoffAgentId ? { handoffAgentId } : {}),
unblockDescriptor: { owner, action },
effects: [
{
kind: "bind_blocker",
owner,
action: input.assessment.blocker.unblockAction,
},
...(input.assessment.blocker.ownerUserId ? [] : [{
kind: "notify_owner",
agentId: input.agentId,
reason: "task_wide_blocker_bound",
} as const]),
{ kind: "bind_blocker", owner, action },
// A named human or other-agent owner owns the next action; do not
// also wake the reporting agent to repeat the blocked work.
...(input.assessment.blocker.ownerUserId || namedOtherAgent ? [] : [{
kind: "notify_owner" as const, agentId: input.agentId, reason: "task_wide_blocker_bound",
}]),
],
};
}
const currentTrackOwner = handoffAgentId ? owner : humanBlockerOwner(input.assessment.blocker);
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "blocked",
toStatus: "blocked",
reasonCode: "current_track_blocker_waiting",
blockerOwnerKind: input.assessment.blocker.ownerKind,
...(handoffAgentId ? { handoffAgentId } : {}),
// A provider's current_track label is not evidence that another
// authorized, productive track exists. Bind the actual unblock request
// without waking the same agent to repeat the blocked work or old title.
unblockDescriptor: {
owner: humanBlockerOwner(input.assessment.blocker),
action: input.assessment.blocker.unblockAction,
},
effects: [
{
kind: "bind_blocker",
owner: humanBlockerOwner(input.assessment.blocker),
action: input.assessment.blocker.unblockAction,
},
],
unblockDescriptor: { owner: currentTrackOwner, action },
effects: [{ kind: "bind_blocker", owner: currentTrackOwner, action }],
};
}
if (input.assessment.reportedDisposition === "yielded" && input.assessment.continuation?.kind === "monitor") {
@@ -8,6 +8,7 @@ import { agentInteractionDeliveryDenial, agentWakeInteractionTexts, INTERACTION_
import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js";
import { lockCurrentNativeWorkAssessmentEvidence } from "./work-assessments.js";
import { nativeBlockerUserId } from "./native-blocker-owner.js";
import { evaluateBlockerAgentHandoff } from "./blocker-owner-handoff.js";
import { hasNativeWorkspaceFinalizationOwner } from "./native-workspace-finalization-recovery-state.js";
import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js";
import { lockCurrentNativeCompletionContract } from "./completion-contracts.js";
@@ -1780,7 +1781,13 @@ export async function commitNativeStatusDecision(input: {
.limit(1)
.then((rows) => rows[0] ?? null);
if (!issue) throw new NativeStatusRaceError();
const [originRun] = await tx.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns)
const [originRun] = await tx.select({
agentId: heartbeatRuns.agentId,
responsibleUserId: heartbeatRuns.responsibleUserId,
driverKind: heartbeatRuns.driverKind,
contextSnapshot: heartbeatRuns.contextSnapshot,
runnerProfileJson: heartbeatRuns.runnerProfileJson,
}).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId)));
if (input.requireReassessmentSource) {
const expected = input.requireReassessmentSource;
@@ -1911,6 +1918,30 @@ export async function commitNativeStatusDecision(input: {
throw error;
}
}
if (input.decision.handoffAgentId) {
try {
const handoff = await evaluateBlockerAgentHandoff(tx as unknown as Db, {
companyId: input.companyId,
issue,
runId: input.runId,
actorAgentId: originRun?.agentId ?? null,
responsibleUserId: originRun?.responsibleUserId ?? null,
driverKind: originRun?.driverKind ?? null,
contextSnapshot: originRun?.contextSnapshot,
runnerProfileJson: originRun?.runnerProfileJson,
targetAgentId: input.decision.handoffAgentId,
unblockAction: input.decision.unblockDescriptor?.action ?? "",
requireTaskOwner: true,
lockSources: true,
});
if (!handoff.allowed) throw new NativeStatusRaceError();
} catch (error) {
if (error instanceof NativeStatusRaceError || record(error).code === "55P03" || record(record(error).cause).code === "55P03") {
throw new NativeStatusRaceError();
}
throw error;
}
}
// Recheck under the issue lock, retaining run/proposal/document proof until
// commit. A newer decision cannot race an earlier first-task Done assessment.
if (input.decision.statusAction === "done" && !await onboardingFirstTaskCompletionAllowed(tx as unknown as Db, {
@@ -2439,6 +2470,11 @@ export async function commitNativeStatusDecision(input: {
statusVersion: input.priorStatusVersion + 1,
lastStatusDecisionId: decisionRow.id,
unblockDescriptor: input.decision.unblockDescriptor,
// A blocker naming another agent hands it the task, so its blocker
// wake is delivered. Only the reporting assignee can hand it off.
...(input.decision.handoffAgentId && !issue.assigneeUserId &&
originRun?.agentId && issue.assigneeAgentId === originRun.agentId
? { assigneeAgentId: input.decision.handoffAgentId } : {}),
actorAgentId: originRun?.agentId ?? null,
actorUserId: null,
},