diff --git a/doc/architecture/native-status-arbitration.md b/doc/architecture/native-status-arbitration.md index 85843264c4a..8f964ecf9d0 100644 --- a/doc/architecture/native-status-arbitration.md +++ b/doc/architecture/native-status-arbitration.md @@ -89,6 +89,29 @@ The classifier produces a `NativeEvidenceAssessment` containing: The classifier does not update the issue. +### Human unblock owners + +A human blocker keeps its explicit user ID through status arbitration and +transactional commit. An API-bound user on the current issue is preserved when +the provider gives a generic human name. A provider-supplied `owner.userId` +takes precedence and must identify an active user member of the same company. +Without either ID, `owner.name` must match exactly one active company member by +ID, full name, or email; name and email matching ignore case. Unknown, inactive, +cross-company, or ambiguous references fall back to the board. They never select +the task creator merely because that person created the work. + +Membership is rechecked and locked with the assessment evidence during commit. +Board fallback decisions are rechecked too, so a person bound after assessment +cannot be replaced by a stale board owner. Each status retry rebuilds the +assessment against current ownership and membership before it decides again. +The saved user owner supplies the existing personal blocker-attention card; +binding it does not queue another run of the blocked worker. Existing generic +board/agent decisions remain readable, and committed historical decisions are +not rewritten. No result-schema or database migration is required. +Human binding uses the existing assignment permission check. An agent whose +`canAssignTasksToHumans` interaction permission is false cannot bind a user +owner; the transaction is refused without creating that person's blocker card. + ## Completion authority The persisted completion contract controls how a `done` claim may be accepted. diff --git a/server/src/__tests__/heartbeat-blocked-question-answer.test.ts b/server/src/__tests__/heartbeat-blocked-question-answer.test.ts index 3aba0ef7572..ac08e0e0fed 100644 --- a/server/src/__tests__/heartbeat-blocked-question-answer.test.ts +++ b/server/src/__tests__/heartbeat-blocked-question-answer.test.ts @@ -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 }); diff --git a/server/src/__tests__/issue-recovery-live-run-agent-census.test.ts b/server/src/__tests__/issue-recovery-live-run-agent-census.test.ts index 1d0a90dd36a..e727a08eaf6 100644 --- a/server/src/__tests__/issue-recovery-live-run-agent-census.test.ts +++ b/server/src/__tests__/issue-recovery-live-run-agent-census.test.ts @@ -28,6 +28,37 @@ function bounded(work: Promise, waitingFor: () => string): Promise { return Promise.race([work, expired]).finally(() => realClearTimeout(timer)); } +async function settlePasses(passes: ReadonlySet>, 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(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; diff --git a/server/src/__tests__/native-status-arbiter-corpus.test.ts b/server/src/__tests__/native-status-arbiter-corpus.test.ts index 507ba04b11c..32eb405c7d2 100644 --- a/server/src/__tests__/native-status-arbiter-corpus.test.ts +++ b/server/src/__tests__/native-status-arbiter-corpus.test.ts @@ -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. diff --git a/server/src/services/native-runtime/evidence-classifier.ts b/server/src/services/native-runtime/evidence-classifier.ts index 1949bb86402..194d30b37c2 100644 --- a/server/src/services/native-runtime/evidence-classifier.ts +++ b/server/src/services/native-runtime/evidence-classifier.ts @@ -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", } diff --git a/server/src/services/native-runtime/native-agent-blocker.integration.test.ts b/server/src/services/native-runtime/native-agent-blocker.integration.test.ts index c9d99e1ad51..9098b1ee15b 100644 --- a/server/src/services/native-runtime/native-agent-blocker.integration.test.ts +++ b/server/src/services/native-runtime/native-agent-blocker.integration.test.ts @@ -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; @@ -36,6 +39,8 @@ describe("native run that reports a task-wide blocker it owns", () => { let temporary: Awaited>; let db: ReturnType; 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, 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 }); diff --git a/server/src/services/native-runtime/native-blocker-owner.ts b/server/src/services/native-runtime/native-blocker-owner.ts new file mode 100644 index 00000000000..efb4117f384 --- /dev/null +++ b/server/src/services/native-runtime/native-blocker-owner.ts @@ -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; + lockSources?: boolean; +}): Promise { + 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; +} diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 83b50a9bde2..fac6d0a6d76 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -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, diff --git a/server/src/services/native-runtime/status-arbiter.test.ts b/server/src/services/native-runtime/status-arbiter.test.ts index e013123b816..46395abe1af 100644 --- a/server/src/services/native-runtime/status-arbiter.test.ts +++ b/server/src/services/native-runtime/status-arbiter.test.ts @@ -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({ diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 3b18da0ebb1..6347122fbbe 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -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, }, ], diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index 85fc187fe6f..5f0cc7516fb 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -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, {