fix(native): preserve named human unblock owners (#22438)

## Thinking Path

> - Paperclip manages work carried out by agents and people.
> - Native finalization converts a runner result into a durable task
status and follow-up effects.
> - A blocked result can name the person who must decide what happens
next.
> - The classifier discarded that identity, and the arbiter saved a
generic board owner.
> - This could replace an explicit user owner saved through the task API
and leave the decision outside that person's inbox.
> - This pull request resolves human owners against active company
membership and preserves them through commit.
> - The named person receives the existing blocker card, and the blocked
worker does not get another wake.

## Linked Issues or Issue Description

**What happened?**

Native finalization replaced a named human unblock owner with `board`.
It also overwrote an explicit user owner saved through the task API
during the turn.

**Expected behavior**

Keep a valid human unblock owner and route the blocker card to that
person's inbox. Use the board when the reference is unknown, inactive,
ambiguous, or outside the company.

**Steps to reproduce**

1. Create an active company member with a distinct display name.
2. Have a native worker report a human blocker using that name.
3. Finalize the run and read the task's unblock owner and the member's
inbox.

Related: #21265 covers named agent handoffs and retains board ownership
for people. This change covers human member routing and does not add
agent handoffs.

## What Changed

- Resolve a human owner from an explicit user ID, an API-bound user, or
one matching company member by ID, full name, or email.
- Preserve the user owner for both blocker scopes and durable dependency
waits.
- Recheck the accepted result and active membership under the status
commit lock, including board fallbacks. Rebuild the assessment on every
status retry so a newly saved owner or revoked membership cannot be
overwritten by stale evidence.
- Enforce `canAssignTasksToHumans` before binding a human owner,
including dependency waits that do not emit a `bind_blocker` effect.
- Validate the result before retiring automatic completion reviews.
Invalid results leave existing reviews pending; valid results retain the
normal cleanup path.
- Keep human blocker routing out of the agent wake queue.
- Add embedded Postgres regressions for finalization, replay, personal
attention, invalid owners, late API ownership changes, membership
revocation, permission denial, and answer continuation for human-owned
blockers.
- Make the answer-continuation fixture persist the same result it
classifies, so commit-time evidence validation sees realistic saved
evidence. Assert the resolved user owner in both blocker scopes.
- Let the recovery census clock advance at real-time pace during
delivery I/O waits. This handles callbacks and nested timers without
jumping to maintenance deadlines. Preserve the existing real-clock
timeout and recovery assertions, and name pending queues in failures.
- Document human blocker resolution and compatibility.

## Verification

- Red-green reproduction: three ownership regressions failed on the
original implementation and passed with the fix.
- Red-green race reproduction: late API ownership changes and membership
revocation failed before the commit recheck and per-retry reassessment
fixes. Each finalization invocation now has to commit; a later replay
cannot hide an exhausted retry.
- Red-green review-retirement reproduction: a new invalid result
cancelled a proven automatic review before throwing
`native_result_invalid_disposition`. The new invalid/valid regression
pair verifies that invalid results preserve the pending review and task
decision, while valid completion still retires the card.
- Red-green answer-continuation reproduction: both human-owner cases
failed with `native_status_race` while saved evidence was empty.
Persisting the classified result and asserting `{ userId }` restored all
13 answer-continuation cases, including worker resumption.
- Red-green permission reproduction: an agent with
`canAssignTasksToHumans: false` could bind a human blocker before the
permission check. Direct and dependency cases now refuse finalization
without creating a personal blocker card.
- On refreshed head `a6d37916546`, `pnpm --filter @paperclipai/server
exec node scripts/typecheck-layers.mjs` passed on macOS with Node 24.
- On refreshed head `a6d37916546`, from the repository root, `CI=true
node node_modules/vitest/vitest.mjs run
server/src/services/native-runtime/native-agent-blocker.integration.test.ts
server/src/services/native-runtime/status-arbiter.test.ts
server/src/services/native-runtime/evidence-classifier.test.ts
server/src/__tests__/native-status-reassessment-work.test.ts
server/src/__tests__/routable-blocked.test.ts
server/src/__tests__/native-status-arbiter-corpus.test.ts
server/src/services/native-runtime/native-environment-blocker.integration.test.ts
server/src/__tests__/heartbeat-blocked-question-answer.test.ts
server/src/__tests__/issue-recovery-live-run-agent-census.test.ts`
passed: 292 tests in nine files on macOS with Node 24.
- Red-green census reproduction: both post-I/O callbacks and nested
timers must settle without jumping to a future maintenance deadline. The
nested case timed out under a zero-only clock pump; the shared
automatically advancing census clock handles both.
- Final CI at `a6d37916546`: [run 44848053016, attempt
2](https://github.com/paperclipai/paperclip/actions/runs/44848053016/attempts/2)
completed successfully. Build, Canary Dry Run, policy, every server and
workspace test shard, Runner checks, serialized suites, e2e, and verify
are green. Greptile review 7 is 5/5 on the same head, Superagent and
other security checks pass, and no review threads remain unresolved. A
local merge-tree check against master `621c5577cdf` also passed with no
conflicts.
- Current CI at `a6d37916546`, [run
44848053016](https://github.com/paperclipai/paperclip/actions/runs/44848053016):
attempt 1 finished with 13 interrupted nonaggregate jobs, each with an
explicit runner shutdown signal in its log. Nine signals occurred within
three seconds on separate m6a.xlarge hosts in us-east-1a; Build and
Canary also shut down later. Aggregate e2e and verify failed on those
dependency results. The underlying termination cause remains unknown.
Shared CI settings are unchanged.
- The [automatic recovery
run](https://github.com/paperclipai/paperclip/actions/runs/44849704877)
skipped retry because Build had only the annotation `Process completed
with exit code 143.` The classifier reads logs for cancellation
annotations, but did not read this job's log. That log explicitly
records a runner shutdown at 01:10:49 UTC. The other 12 failed jobs were
recognized as runner loss. After verifying all 13 logs, manually
requested failed-job attempt 2; it completed successfully without source
or configuration changes between attempts. The shared recovery
classifier is unchanged; this false negative remains a documented
follow-up.
- Historical CI at `cf601ba`: all server shards (including the census),
Runner checks, typecheck/release registry, serialized suites, e2e, and
canary dry run passed. Build received runner shutdown signals on
attempts 1–7; aggregate verify failed because Build failed. Attempt 5
diagnostics show shutdown while the job lease was valid. Attempt 7
stopped after server dependency preparation, without a compiler error.
The termination cause remains unknown. Three recent PRs completed Build
on the same AWS fleet; this is not evidence of a fleet-wide outage.
Shared CI settings are unchanged.
- Diagnostic comparison at `cf601ba`: the server compiler passed locally
on macOS with four checkers, full typechecking, and
declaration/JavaScript emission (`node ../scripts/run-tsc.mjs --checkers
4 --extendedDiagnostics` under Node 24). The monitored process group
peaked at about 10.5 GiB RSS and finished in 25.8 seconds. This does not
establish the cause of the Linux runner shutdowns.
- Refreshed the branch onto master `611dc68581c` without conflicts; the
PR source diff is unchanged. Greptile review 7 scored head `a6d37916546`
5/5 with no new actionable findings and no unresolved review threads.
All applicable CI gates passed on attempt 2.
- Full local workspace build at `cf601ba` passed on macOS using Node 24
and the documented single-thread compiler mode:
`PAPERCLIP_TYPECHECK_LOW_MEMORY=1 npx --yes --package=node@24
--package=pnpm@9.15.4 pnpm build`. This includes typechecking and
artifact emission. The tracked working tree stayed clean.
- `pnpm verify --explain` returned exit 2 because this documentation
path requires broad CI coverage. Fresh CI will supply that coverage; the
full local test suite was not run.
- Earlier CI build and canary jobs received runner shutdown signals. The
server shard also exposed an answer-continuation fixture that saved an
empty result while classifying a named human. That mismatch was
reproduced locally, and the fixture now persists the classified result
and checks the user owner. Fresh CI is required for this revision.
- `git diff --check` and the staged gitleaks scan passed. The diff was
also checked for private issue references, identifiers, URLs, and
personal data.

## Risks

- Name and email matching ignore case. Several matches fall back to the
board. Invalid explicit IDs never fall through to another person.
- Resolution adds bounded reads only when a native result reports a
human blocker. It adds no worker, timer, or idle scan.
- No database or result-schema migration is required. Existing board and
agent decisions remain readable. Committed historical decisions are not
rewritten; new finalizations use current membership.
- This changes human routing only. It grants no access and changes no
merge, approval, or dependency policy.

## Model Used

- OpenAI GPT-6.1 Sol (`gpt-6.1-sol`) through Codex in T3 Code, with
xhigh reasoning effort, code editing, shell tools, and test execution.

## 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 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:
Devin FoleyandPaperclip authored and GitHub committed 2026-11-20 17:45:45 -08:00
1 parent 621c5577cd
commit 18978bdc1d
11 files changed
+382 -42

No files matched your search

@@ -92,9 +92,15 @@ describeEmbeddedPostgres("an answer to the agent's own question continues the ta
await db.insert(heartbeatRuns).values({ id: runId, companyId: input.companyId, agentId: input.agentId,
status: "running", runtimeMode: "native", nativeIssueId: input.issueId, invocationSource: "automation",
triggerDetail: "system", completionContractId: contractId, contextSnapshot: { issueId: input.issueId } });
const result = { schema: "paperclip.run_result.v1", reportedWorkDisposition: "blocked",
summary: "Waiting for the codename answer.", blocker: input.blocker,
completionClaim: { contractRevision: "1", objectiveSatisfied: false,
criteria: [{ criterionId: "objective", status: "not_satisfied", evidenceRefs: [] }],
remainingWork: [{ description: "Write the brief after the answer.", blocksCompletion: true }] },
evidence: [], verification: [], attentionRequests: [], artifacts: [] };
await db.insert(nativeRunResults).values({ id: resultId, companyId: input.companyId, issueId: input.issueId,
runId, completionContractId: contractId, serverFingerprint: resultId, schemaStatus: "accepted",
resultJson: {}, canonicalSha256: resultId });
resultJson: { result }, canonicalSha256: resultId });
const [snapshot] = await db.select().from(issues).where(eq(issues.id, input.issueId));
await db.insert(workAssessments).values({ id: assessmentId, companyId: input.companyId, issueId: input.issueId,
runId, contractId, resultId, triggerKind: "native_result", triggerActorCompanyId: input.companyId,
@@ -105,12 +111,7 @@ describeEmbeddedPostgres("an answer to the agent's own question continues the ta
const decision: NativeStatusDecision = input.blocker ? arbitrateNativeStatus({
assessment: await classifyNativeEvidence({ db, companyId: input.companyId, issueId: input.issueId, runId,
contract: { revision: "1", objective: "Write the brief", criteria: [{ id: "objective", requirement: "Write the brief" }] },
result: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "blocked",
summary: "Waiting for the codename answer.", blocker: input.blocker,
completionClaim: { contractRevision: "1", objectiveSatisfied: false,
criteria: [{ criterionId: "objective", status: "not_satisfied", evidenceRefs: [] }],
remainingWork: [{ description: "Write the brief after the answer.", blocksCompletion: true }] },
evidence: [], verification: [], attentionRequests: [], artifacts: [] } }),
result }),
terminalState: "succeeded", workspaceFinalizeStatus: "succeeded", agentId: input.agentId,
priorIssueStatus: snapshot!.status as "in_review",
...input.arbiter,
@@ -173,7 +174,7 @@ describeEmbeddedPostgres("an answer to the agent's own question continues the ta
await agentReportsBlocker({ companyId, agentId, issueId, blocker: { owner, scope,
reasonCode: "awaiting_codename_answer", unblockAction: `Answer the existing codename question (${question.id}).` } });
const [blocked] = await db.select().from(issues).where(eq(issues.id, issueId));
expect(blocked).toMatchObject({ status: "blocked", unblockDescriptor: { owner: scope === "task_wide" && owner.kind === "external" ? { agentId } : "board" } });
expect(blocked).toMatchObject({ status: "blocked", unblockDescriptor: { owner: owner.kind === "user" ? { userId } : { agentId } } });
await answer(question);
const run = await deliverAnswer({ agentId, issueId, questionId: question.id });
expect({ status: run?.status, errorCode: run?.errorCode ?? null }).toEqual({ status: "succeeded", errorCode: null });
@@ -28,6 +28,37 @@ function bounded<T>(work: Promise<T>, waitingFor: () => string): Promise<T> {
return Promise.race([work, expired]).finally(() => realClearTimeout(timer));
}
async function settlePasses(passes: ReadonlySet<Promise<unknown>>, waitingFor: () => string) {
await bounded(Promise.allSettled([...passes]), waitingFor);
}
function useCensusClock() {
// Database I/O can schedule nested timers after an explicit clock advance.
// Let time pass at real-time pace during the wait, without jumping to the
// next maintenance deadline. bounded() still enforces its real-clock limit.
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
}
it.each([false, true])("settles delivery callbacks scheduled after I/O without jumping to recovery deadlines (nested: %s)", async nested => {
useCensusClock();
await vi.advanceTimersByTimeAsync(1000);
const now = Date.now();
const future = vi.fn();
setTimeout(future, MINUTE);
const pass = immediate().then(() => new Promise<void>(resolve => setTimeout(() => {
if (nested) setTimeout(resolve, 0);
else resolve();
}, 0)));
try {
await settlePasses(new Set([pass]), () => "a delivery callback scheduled after I/O");
expect(Date.now() - now).toBeLessThan(STEP_TIMEOUT_MS);
expect(future).not.toHaveBeenCalled();
} finally {
await vi.runOnlyPendingTimersAsync();
vi.useRealTimers();
}
}, 30_000);
/**
* Staging shape: about 860 settled assigned tasks, most of them held by the
* same few agents, and one agent whose native run stays live for the whole
@@ -46,8 +77,8 @@ describeIssueRecovery("stranded-task checks beside one long live run (census)",
await bounded(onTick(), () => `the run event at simulated ${at} to commit`);
nextTick = Date.now() + 10_000;
}
await bounded(vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now())), () => `simulated time to advance past ${at}`);
await bounded(Promise.allSettled([...state.passes]), () => `${state.passes.size} delivery passes started by simulated ${at} to settle`);
await bounded(vi.advanceTimersByTimeAsync(Math.max(0, Math.min(1000, until - Date.now()))), () => `simulated time to advance past ${at}`);
await settlePasses(state.passes, () => `${state.passes.size} delivery passes (${state.pendingPassQueues().join(", ")}) started by simulated ${at} to settle`);
await immediate();
}
}
@@ -107,7 +138,7 @@ describeIssueRecovery("stranded-task checks beside one long live run (census)",
async function boot() {
const f = await bounded(seed(), () => "the fixture to be seeded");
const events = record();
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
useCensusClock();
await bounded(state.start({}), () => "the recovery workers to start");
await advance(10 * MINUTE);
events.length = 0;
@@ -3052,6 +3052,31 @@ describe("P6-31 Section 18.13 executable status-authority corpus", () => {
});
});
it.each(["invalid", "done"] as const)("validates a new %s result before retiring an existing automatic review", async disposition => {
const seeded = await seedAutomaticReview();
const runId = randomUUID(), resultId = randomUUID();
const [sourceRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId));
const [sourceResult] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, seeded.resultId!));
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native",
nativeIssueId: seeded.issueId, contextSnapshot: { issueId: seeded.issueId },
completionContractId: seeded.contractId!, completionContractSha256: sourceRun!.completionContractSha256 });
await db.insert(nativeRunResults).values({ id: resultId, companyId, issueId: seeded.issueId, runId,
completionContractId: seeded.contractId!, serverFingerprint: resultId, canonicalSha256: resultId, schemaStatus: "accepted",
resultJson: { ...sourceResult!.resultJson,
result: { ...(sourceResult!.resultJson.result as object), reportedWorkDisposition: disposition } } });
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId: seeded.issueId, phase: "observed", resultId });
const finalizing = finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded" });
if (disposition === "invalid") await expect(finalizing).rejects.toThrow("native_result_invalid_disposition");
else expect((await finalizing)?.phase).toBe("committed");
const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, seeded.interaction.id));
if (disposition === "invalid") {
expect(card).toMatchObject({ status: "pending", result: null, resolvedAt: null });
const [issue] = await db.select().from(issues).where(eq(issues.id, seeded.issueId));
expect(issue).toMatchObject({ status: "in_review", lastStatusDecisionId: seeded.decision.id });
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId))).toEqual([]);
} else expect(card).toMatchObject({ status: "cancelled", result: { reason: "automatic_completion_review_removed" } });
}, 30_000);
it("retires a proven automatic review and applies the current successful completion exactly once", async () => {
const seeded = await seedAutomaticReview();
// The persisted result is done, while its old assessment/decision required a review.
@@ -1,5 +1,6 @@
import { and, eq, or } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { nativeBlockerUserId } from "./native-blocker-owner.js";
import {
approvals,
caseHandoffs,
@@ -74,6 +75,7 @@ export interface NativeEvidenceAssessment {
unblockAction: string;
boardOwned: boolean;
ownerKind?: NativeBlockerOwnerKind;
ownerUserId?: string;
scope: "current_track" | "task_wide";
} | null;
continuation: {
@@ -286,6 +288,8 @@ export async function classifyNativeEvidence(input: {
const reported = input.result.reportedWorkDisposition;
const blocker = record(input.result.blocker);
const blockerOwner = record(blocker.owner);
const ownerUserId = reported === "blocked" && typeof blocker.unblockAction === "string"
? await nativeBlockerUserId({ ...input, owner: blockerOwner }) : null;
const continuation = record(input.result.continuation);
if (!["done", "blocked", "needs_review", "yielded"].includes(String(reported))) {
throw new Error("native_result_invalid_disposition");
@@ -427,6 +431,7 @@ export async function classifyNativeEvidence(input: {
? {
unblockAction: blocker.unblockAction,
boardOwned: ["board", "user"].includes(String(blockerOwner.kind)) || blockerOwner.owner === "board",
...(ownerUserId ? { ownerUserId } : {}),
ownerKind: nativeBlockerOwnerKind(blockerOwner),
scope: blocker.scope === "task_wide" ? "task_wide" : "current_track",
}
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, companies, companyMemberships, completionContracts, createDb, heartbeatRuns, issues,
import { agents, agentWakeupRequests, authUsers, companies, companyMemberships, completionContracts, createDb, heartbeatRuns, issueRelations, issues,
nativeRunFinalizations, statusDecisions } from "@paperclipai/db";
import type { ControlPlanePort, NativeExecutionInputV1, PrpStructuredRunResult, PrpTerminalState } from "@paperclipai/paperclip-runner";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
@@ -20,6 +20,9 @@ import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_HANDOFF_CO
import { taskInterruptionPresentation } from "../task-interruption-presentation.js";
import { requestTaskRetry } from "../task-retry.js";
import { heartbeatService } from "../heartbeat.js";
import { attentionService } from "../attention.js";
import * as statusCommitter from "./status-decision-committer.js";
import * as evidenceClassifier from "./evidence-classifier.js";
type Blocker = NonNullable<PrpStructuredRunResult["blocker"]>;
@@ -36,6 +39,8 @@ describe("native run that reports a task-wide blocker it owns", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
const companyId = randomUUID(), agentId = randomUUID(), boardUserId = "ledger-board-user";
const namedUserId = "named-dependency-reviewer";
const foreignCompanyId = randomUUID();
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("native-agent-blocker-");
db = createDb(temporary.connectionString);
@@ -43,6 +48,19 @@ describe("native run that reports a task-wide blocker it owns", () => {
await db.insert(agents).values({ id: agentId, companyId, name: "Ledger worker", status: "active", adapterType: "paperclip_runner",
adapterConfig: { provider: "opencode", model: "test-model" } });
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: boardUserId, status: "active", membershipRole: "member" });
await db.insert(authUsers).values({ id: namedUserId, name: "Dependency Reviewer", email: "reviewer@example.test",
createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: namedUserId, status: "active", membershipRole: "member" });
await db.insert(companies).values({ id: foreignCompanyId, name: "Other company", issuePrefix: "OTHER" });
for (const [id, name, membershipCompany, status] of [
["foreign-reviewer", "Foreign Reviewer", foreignCompanyId, "active"],
["inactive-reviewer", "Inactive Reviewer", companyId, "inactive"],
["ambiguous-reviewer-one", "Shared Reviewer", companyId, "active"],
["ambiguous-reviewer-two", "Shared Reviewer", companyId, "active"],
]) {
await db.insert(authUsers).values({ id, name, email: `${id}@example.test`, createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values({ companyId: membershipCompany, principalType: "user", principalId: id, status, membershipRole: "member" });
}
});
afterAll(async () => { await temporary?.cleanup(); });
@@ -53,7 +71,8 @@ describe("native run that reports a task-wide blocker it owns", () => {
return issueId;
}
async function runTurn(issueId: string, report: { blocker: Blocker } | { done: true }, runId: string = randomUUID()) {
async function runTurn(issueId: string, report: { blocker: Blocker } | { done: true }, runId: string = randomUUID(),
beforeFinalize?: () => Promise<unknown>, expectedPhase: "committed" | "terminal_failure" = "committed") {
const [existing] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
if (!existing) await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: boardUserId, contextSnapshot: { issueId } });
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
@@ -95,7 +114,13 @@ describe("native run that reports a task-wide blocker it owns", () => {
});
const unexpected = async () => { throw new Error("Unexpected provider call"); };
await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { descriptor: unexpected, openSession: unexpected } });
for (let replay = 0; replay < 2; replay++) await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
await beforeFinalize?.();
for (let replay = 0; replay < (expectedPhase === "committed" ? 2 : 1); replay++) {
const finalized = await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect(finalized?.phase).toBe(expectedPhase);
}
if (expectedPhase === "terminal_failure") await expect(finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded" }))
.rejects.toThrow("native_finalization_terminal_failure");
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId));
const retries = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId)));
const [settled] = await db.select().from(issues).where(eq(issues.id, issueId));
@@ -105,6 +130,137 @@ describe("native run that reports a task-wide blocker it owns", () => {
const ownerWakes = async (issueId: string) => (await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId)))
.filter(wake => wake.payload?.issueId === issueId && wake.requestedByActorId === "native-status-committer");
it.each(["task_wide", "current_track"] as const)("routes a %s human blocker to the named company member through finalization and replay", async scope => {
const issueId = await createTask();
const blocked = await runTurn(issueId, { blocker: { ...selfBlocker, scope,
owner: { kind: "user", name: "Dependency Reviewer" }, unblockAction: "Decide whether to defer this dependency upgrade." } });
expect(blocked.issue).toMatchObject({ status: "blocked", unblockDescriptor: {
owner: { userId: namedUserId }, action: "Decide whether to defer this dependency upgrade." } });
expect(blocked.retries).toEqual([]);
expect(await ownerWakes(issueId)).toEqual([]);
const mine = await attentionService(db).list(companyId, { userId: namedUserId, view: "mine" });
expect(mine.items).toEqual(expect.arrayContaining([expect.objectContaining({
sourceKind: "blocker_attention", subject: expect.objectContaining({ id: issueId }),
audience: expect.objectContaining({ kind: "user", userId: namedUserId }),
})]));
const others = await attentionService(db).list(companyId, { userId: boardUserId, view: "mine" });
expect(others.items.some(item => item.dedupKey.startsWith("blocked-owner:") && item.subject.id === issueId)).toBe(false);
}, 120_000);
it("preserves a typed human unblock owner saved by an API call during the turn", async () => {
const issueId = await createTask();
const blocked = await runTurn(issueId, { blocker: { ...selfBlocker,
owner: { kind: "user", name: "the decision owner" } } }, randomUUID(), async () => {
await db.update(issues).set({ status: "blocked", unblockDescriptor: {
owner: { userId: namedUserId }, action: selfBlocker.unblockAction } }).where(eq(issues.id, issueId));
});
expect(blocked.issue.unblockDescriptor?.owner).toEqual({ userId: namedUserId });
expect(await ownerWakes(issueId)).toEqual([]);
}, 120_000);
it("rebuilds a board assessment when a human owner is bound before the authoritative issue read", async () => {
const issueId = await createTask();
const classify = evidenceClassifier.classifyNativeEvidence;
let bound = false;
const spy = vi.spyOn(evidenceClassifier, "classifyNativeEvidence").mockImplementation(async input => {
const assessment = await classify(input);
if (!bound && input.issueId === issueId) {
bound = true;
await db.update(issues).set({ status: "blocked", statusVersion: 1, unblockDescriptor: {
owner: { userId: namedUserId }, action: selfBlocker.unblockAction } }).where(eq(issues.id, issueId));
}
return assessment;
});
try {
const blocked = await runTurn(issueId, { blocker: { ...selfBlocker, owner: { kind: "user", name: "the decision owner" } } });
expect(bound).toBe(true);
expect(blocked.issue.unblockDescriptor?.owner).toEqual({ userId: namedUserId });
expect(await ownerWakes(issueId)).toEqual([]);
} finally { spy.mockRestore(); }
}, 120_000);
it("rechecks a board fallback when its human owner changes without changing the status version", async () => {
const issueId = await createTask();
await db.update(issues).set({ status: "blocked", unblockDescriptor: {
owner: "board", action: selfBlocker.unblockAction } }).where(eq(issues.id, issueId));
const commit = statusCommitter.commitNativeStatusDecision;
let rebound = false;
const spy = vi.spyOn(statusCommitter, "commitNativeStatusDecision").mockImplementation(async input => {
if (!rebound && input.issueId === issueId && input.decision.unblockDescriptor?.owner === "board") {
rebound = true;
await db.update(issues).set({ unblockDescriptor: {
owner: { userId: namedUserId }, action: selfBlocker.unblockAction } }).where(eq(issues.id, issueId));
}
return commit(input);
});
try {
const blocked = await runTurn(issueId, { blocker: { ...selfBlocker, owner: { kind: "user", name: "the decision owner" } } });
expect(rebound).toBe(true);
expect(blocked.issue.unblockDescriptor?.owner).toEqual({ userId: namedUserId });
expect(await ownerWakes(issueId)).toEqual([]);
} finally { spy.mockRestore(); }
}, 120_000);
it("keeps an unknown human blocker with the board instead of assigning the task creator", async () => {
const blocked = await runTurn(await createTask(), { blocker: { ...selfBlocker,
owner: { kind: "user", name: "Unknown Reviewer" } } });
expect(blocked.issue.unblockDescriptor?.owner).toBe("board");
expect(blocked.retries).toEqual([]);
}, 120_000);
it.each([false, true])("refuses human blocker routing when the agent cannot assign tasks to humans (dependency: %s)", async dependency => {
const issueId = await createTask();
if (dependency) await db.insert(issueRelations).values({ companyId, issueId: await createTask(), relatedIssueId: issueId, type: "blocks" });
await db.update(agents).set({ permissions: { interactions: { canAssignTasksToHumans: false } } }).where(eq(agents.id, agentId));
try {
const blocked = await runTurn(issueId, { blocker: { ...selfBlocker,
owner: { kind: "user", name: "Dependency Reviewer" } } }, undefined, undefined, "terminal_failure");
expect(blocked.issue.unblockDescriptor).toBeNull();
expect(blocked.decision).toBeUndefined();
const [finalized] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, blocked.runId));
expect(finalized).toMatchObject({ phase: "terminal_failure", failureCode: "agent_interaction_denied", nextAttemptAt: null });
const feed = await attentionService(db).list(companyId, { userId: namedUserId, view: "mine" });
expect(feed.items.some(item => item.dedupKey.startsWith("blocked-owner:") && item.subject.id === issueId)).toBe(false);
} finally { await db.update(agents).set({ permissions: {} }).where(eq(agents.id, agentId)); }
}, 120_000);
it.each(["Foreign Reviewer", "Inactive Reviewer", "Shared Reviewer"])("does not route a human blocker through an unsafe name: %s", async name => {
const blocked = await runTurn(await createTask(), { blocker: { ...selfBlocker, owner: { kind: "user", name } } });
expect(blocked.issue.unblockDescriptor?.owner).toBe("board");
}, 120_000);
it("uses an explicit opaque member ID and does not guess a replacement for an invalid ID", async () => {
for (const userId of [namedUserId, "foreign-reviewer", "inactive-reviewer", "", 42]) {
const blocked = await runTurn(await createTask(), { blocker: { ...selfBlocker,
owner: { kind: "user", name: "Dependency Reviewer", ...{ userId } } } });
expect(blocked.issue.unblockDescriptor?.owner).toEqual(userId === namedUserId ? { userId: namedUserId } : "board");
}
}, 120_000);
it("reclassifies a human owner whose membership is revoked between assessment and commit", async () => {
const commit = statusCommitter.commitNativeStatusDecision;
let revoked = false;
const spy = vi.spyOn(statusCommitter, "commitNativeStatusDecision").mockImplementation(async input => {
if (!revoked && typeof input.decision.unblockDescriptor?.owner === "object"
&& "userId" in input.decision.unblockDescriptor.owner) {
revoked = true;
await db.update(companyMemberships).set({ status: "inactive" }).where(and(
eq(companyMemberships.companyId, companyId), eq(companyMemberships.principalId, namedUserId)));
}
return commit(input);
});
try {
const blocked = await runTurn(await createTask(), { blocker: { ...selfBlocker,
owner: { kind: "user", name: "Dependency Reviewer" } } });
expect(revoked).toBe(true);
expect(blocked.issue.unblockDescriptor?.owner).toBe("board");
} finally {
spy.mockRestore();
await db.update(companyMemberships).set({ status: "active" }).where(and(
eq(companyMemberships.companyId, companyId), eq(companyMemberships.principalId, namedUserId)));
}
}, 120_000);
it("continues a tool-output blocker in a fresh session, and the continuation finishes the task", async () => {
const issueId = await createTask();
const first = await runTurn(issueId, { blocker: toolOutputBlocker });
@@ -0,0 +1,44 @@
import { and, eq, inArray, or, sql } from "drizzle-orm";
import { authUsers, companyMemberships, issues, type Db } from "@paperclipai/db";
const text = (value: unknown) => typeof value === "string" && value.trim() ? value.trim() : null;
/** Resolve human routing from current company membership, never from a name alone. */
export async function nativeBlockerUserId(input: {
db: Db;
companyId: string;
issueId: string;
owner: Record<string, unknown>;
lockSources?: boolean;
}): Promise<string | null> {
if (!["user", "board"].includes(String(input.owner.kind)) && input.owner.owner !== "board") return null;
if ("userId" in input.owner && !text(input.owner.userId)) return null;
const [issue] = await input.db.select({ unblockDescriptor: issues.unblockDescriptor }).from(issues)
.where(and(eq(issues.companyId, input.companyId), eq(issues.id, input.issueId))).limit(1);
const savedOwner = issue?.unblockDescriptor?.owner;
// An API-bound user is authoritative when a provider only reports a generic name.
// An explicit provider userId must stand on its own; never fall back after a bad ID.
const userId = text(input.owner.userId)
?? (savedOwner && typeof savedOwner === "object" && "userId" in savedOwner ? savedOwner.userId : null);
const name = text(input.owner.name);
if (!userId && (!name || input.owner.kind !== "user")) return null;
const matchingUsers = input.db.select({ id: authUsers.id }).from(authUsers).where(or(
sql`lower(${authUsers.name}) = lower(${name})`,
sql`lower(${authUsers.email}) = lower(${name})`,
));
const query = input.db.select({ userId: companyMemberships.principalId }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, input.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.status, "active"),
userId ? eq(companyMemberships.principalId, userId) : or(
eq(companyMemberships.principalId, name!),
inArray(companyMemberships.principalId, matchingUsers),
),
)).limit(2);
// Evidence is reclassified under the status transaction. Retain membership
// until that transaction commits, so revocation cannot race the projection.
const candidates = await (input.lockSources ? query.for("share", { noWait: true }) : query);
return candidates.length === 1 ? candidates[0]!.userId : null;
}
@@ -1585,28 +1585,10 @@ export async function finalizeNativeRun(input: {
eq(nativeRunFinalizations.leaseOwner, claim.leaseOwner!),
),
);
const classifiedAssessment = await classifyNativeEvidence({
db: input.db,
companyId: run.companyId,
issueId: coordinator.issueId,
runId: run.id,
contract: record(contractRow.contractJson),
result,
});
const persistedIgnoredAttention = record(
envelope.normalizationDiagnostics,
).ignoredAttentionRequests;
const assessment = {
...classifiedAssessment,
ignoredAttentionRequests: [
...(Array.isArray(persistedIgnoredAttention)
? (persistedIgnoredAttention as PrpIgnoredAttentionRequest[])
: []),
...classifiedAssessment.ignoredAttentionRequests,
],
};
await dismissAutomaticCompletionReviews(input.db, coordinator.issueId);
const sourceWake = run.wakeupRequestId ? await input.db.select({ payload: agentWakeupRequests.payload })
.from(agentWakeupRequests).where(and(eq(agentWakeupRequests.id, run.wakeupRequestId),
eq(agentWakeupRequests.companyId, run.companyId))).then((rows) => rows[0]) : null;
@@ -1632,6 +1614,29 @@ export async function finalizeNativeRun(input: {
.then((rows) => rows[0] ?? null);
if (!authoritativeIssue)
throw new Error("native_finalization_issue_missing");
// A status retry must rebuild ownership and evidence too. Reusing the
// earlier assessment can overwrite an API-bound owner or exhaust every
// retry after a membership change, despite reading a fresh issue version.
const classifiedAssessment = await classifyNativeEvidence({
db: input.db,
companyId: run.companyId,
issueId: coordinator.issueId,
runId: run.id,
contract: record(contractRow.contractJson),
result,
});
// A malformed result must not withdraw a pending review. Keep cleanup
// after validation while rebuilding the assessment on every status retry.
if (attempt === 0) await dismissAutomaticCompletionReviews(input.db, coordinator.issueId);
const assessment = {
...classifiedAssessment,
ignoredAttentionRequests: [
...(Array.isArray(persistedIgnoredAttention)
? (persistedIgnoredAttention as PrpIgnoredAttentionRequest[])
: []),
...classifiedAssessment.ignoredAttentionRequests,
],
};
const preservedResultFinalization = run.status !== "running"
? await readPreservedNativeResultFinalization(input.db, {
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
@@ -568,6 +568,18 @@ describe("native status authority", () => {
);
});
it.each(["task_wide", "current_track"] as const)("keeps a resolved human owner for a %s block without waking the worker again", scope => {
const blocked = assessment({ reportedDisposition: "blocked", blocker: {
boardOwned: true, ownerKind: "user", ownerUserId: "named-member", scope, unblockAction: "Decide the dependency exception",
} });
const decision = arbitrate({ assessment: blocked });
expect(decision.unblockDescriptor?.owner).toEqual({ userId: "named-member" });
expect(decision.effects).toEqual([{ kind: "bind_blocker", owner: { userId: "named-member" }, action: "Decide the dependency exception" }]);
expect(arbitrate({ assessment: blocked, hasUnresolvedIssueBlockers: true })).toMatchObject({
reasonCode: "durable_dependency_blocker_bound", unblockDescriptor: { owner: { userId: "named-member" } }, effects: [],
});
});
it("blocks only for a task-wide blocker with a named owner and action", () => {
expect(
arbitrate({
@@ -1,5 +1,6 @@
import { COMPLETION_REVIEW_STAGE_REASON, COMPLETION_REVIEW_STAGE_REJECTED_REASON, type CompletionReviewStageEntry } from "../issue-execution-policy.js";
import type { NativeEvidenceAssessment } from "./evidence-classifier.js";
import type { IssueUnblockDescriptor } from "@paperclipai/shared";
import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js";
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
@@ -55,7 +56,7 @@ export type NativeStatusEffect =
}
| {
kind: "bind_blocker";
owner: { agentId: string } | "board";
owner: IssueUnblockDescriptor["owner"];
action: string;
}
| { kind: "schedule_retry"; cause: string; summary: string; agentId: string }
@@ -98,13 +99,17 @@ export interface NativeStatusDecision {
toStatus: NativeAuthoritativeIssueStatus;
reasonCode: string | null;
unblockDescriptor: {
owner: { agentId: string } | "board";
owner: IssueUnblockDescriptor["owner"];
action: string;
} | null;
effects: NativeStatusEffect[];
blockerOwnerKind?: string;
}
function humanBlockerOwner(blocker: NativeEvidenceAssessment["blocker"]): IssueUnblockDescriptor["owner"] {
return blocker?.ownerUserId ? { userId: blocker.ownerUserId } : "board";
}
/**
* 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,
@@ -519,7 +524,7 @@ export function arbitrateNativeStatus(input: {
(["done", "blocked"].includes(input.assessment.reportedDisposition) || unfinishedResponseWait || input.assessment.continuation?.kind === "monitor")
) {
const owner = input.assessment.blocker?.boardOwned
? ("board" as const)
? humanBlockerOwner(input.assessment.blocker)
: { agentId: input.agentId };
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
@@ -712,7 +717,7 @@ export function arbitrateNativeStatus(input: {
input.assessment.blocker
) {
const owner = input.assessment.blocker.boardOwned
? ("board" as const)
? humanBlockerOwner(input.assessment.blocker)
: { agentId: input.agentId };
if (input.assessment.blocker.scope === "task_wide") {
return {
@@ -731,11 +736,11 @@ export function arbitrateNativeStatus(input: {
owner,
action: input.assessment.blocker.unblockAction,
},
{
...(input.assessment.blocker.ownerUserId ? [] : [{
kind: "notify_owner",
agentId: input.agentId,
reason: "task_wide_blocker_bound",
},
} as const]),
],
};
}
@@ -749,13 +754,13 @@ export function arbitrateNativeStatus(input: {
// authorized, productive track exists. Bind the actual unblock request
// without waking the same agent to repeat the blocked work or old title.
unblockDescriptor: {
owner: "board",
owner: humanBlockerOwner(input.assessment.blocker),
action: input.assessment.blocker.unblockAction,
},
effects: [
{
kind: "bind_blocker",
owner: "board",
owner: humanBlockerOwner(input.assessment.blocker),
action: input.assessment.blocker.unblockAction,
},
],
@@ -6,6 +6,7 @@ import { forbidden, HttpError } from "../../errors.js";
import { agentInteractionDeliveryDenial, agentWakeInteractionTexts, INTERACTION_DELIVERY_DENIED, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js";
import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js";
import { lockCurrentNativeWorkAssessmentEvidence } from "./work-assessments.js";
import { nativeBlockerUserId } from "./native-blocker-owner.js";
import { hasNativeWorkspaceFinalizationOwner } from "./native-workspace-finalization-recovery-state.js";
import { tryLockNativeWorkspaceFinalization } from "./native-workspace-finalization-ownership.js";
import { lockCurrentNativeCompletionContract } from "./completion-contracts.js";
@@ -872,7 +873,9 @@ async function materializeDecisionEffect(input: {
if (effect.kind === "bind_blocker") {
failAt("blocker_materialization", input.failpoint);
await assertAgentInteraction(input.tx, { companyId: input.companyId, actorAgentId: input.actorAgentId,
operation: "assign", issueId: input.issue.id, targetAgentId: typeof effect.owner === "object" ? effect.owner.agentId : null,
operation: "assign", issueId: input.issue.id,
targetAgentId: typeof effect.owner === "object" && "agentId" in effect.owner ? effect.owner.agentId : null,
assigneeUserId: typeof effect.owner === "object" && "userId" in effect.owner ? effect.owner.userId : null,
texts: [effect.action], lock: true });
const [bound] = await input.tx
.update(issues)
@@ -889,7 +892,7 @@ async function materializeDecisionEffect(input: {
.returning({ id: issues.id });
if (!bound) throw new Error("native_blocker_binding_not_persisted");
let wakeId: string | null = null;
if (effect.owner !== "board") {
if (effect.owner !== "board" && "agentId" in effect.owner) {
wakeId = await enqueueWake({
tx: input.tx,
originRunId: input.runId,
@@ -1877,6 +1880,36 @@ export async function commitNativeStatusDecision(input: {
) {
throw new NativeStatusRaceError();
}
const unblockOwner = input.decision.unblockDescriptor?.owner;
const assessedUserId = unblockOwner && typeof unblockOwner === "object" && "userId" in unblockOwner
? unblockOwner.userId : null;
// A board fallback is also an assessed resolution. A late API-bound
// human owner must invalidate it before any blocker effects are saved.
const boardBlocker = unblockOwner === "board" && [
"task_wide_blocker_bound", "current_track_blocker_waiting", "durable_dependency_blocker_bound",
].includes(reasonCode);
if (assessedUserId || boardBlocker) {
try {
const [saved] = await tx.select({ envelope: nativeRunResults.resultJson }).from(nativeRunResults).where(and(
eq(nativeRunResults.id, coordinator.resultId!), eq(nativeRunResults.companyId, input.companyId),
eq(nativeRunResults.issueId, input.issueId), eq(nativeRunResults.runId, input.runId),
eq(nativeRunResults.schemaStatus, "accepted"),
)).limit(1).for("share", { noWait: true });
const owner = record(record(record(saved?.envelope).result).blocker).owner;
if (!saved || await nativeBlockerUserId({ db: tx as unknown as Db, companyId: input.companyId,
issueId: input.issueId, owner: record(owner), lockSources: true }) !== assessedUserId) {
throw new NativeStatusRaceError();
}
// Dependency waits can project an owner without a bind_blocker
// effect, so enforce the human-assignment permission here too.
if (assessedUserId) await assertAgentInteraction(tx, { companyId: input.companyId,
actorAgentId: originRun?.agentId ?? null, operation: "assign", issueId: input.issueId,
assigneeUserId: assessedUserId, texts: [input.decision.unblockDescriptor!.action], lock: true });
} catch (error) {
if (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, {