diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index a3c9d23f40d..999226683ad 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -102,6 +102,14 @@ Tasks have parentage. Every task exists in service of a parent task, all the way The current issue model includes stable issue identifiers, parent/sub-issues, blockers, a single assignee, comments, issue documents, attachments and work products, and review/approval handoffs. That structure keeps work inspectable by both the board and agents while still allowing agents to decompose work into smaller tasks. +A native agent that stops for a human decision must save an answerable request +and cite its receipt in the blocker report. A comment that says “decision needed” +does not create a question. The request must require a human response and resume +the work after the answer. Agents can reuse a current request, linked approval, +or open decision. Muse's first-party task catalog also supports these durable +human-input requests. Answered, dismissed, expired, and unrelated requests do +not justify another wait. + Task lists load additional pages as you scroll, with a **Load more tasks** button available as well. This applies to personal views, including Mine, Recent, Unread, Everything, and Blocked, and to organization views and their board layouts. diff --git a/server/src/__tests__/muse-control.test.ts b/server/src/__tests__/muse-control.test.ts index 81e2bc22dd0..85683a4c904 100644 --- a/server/src/__tests__/muse-control.test.ts +++ b/server/src/__tests__/muse-control.test.ts @@ -35,6 +35,7 @@ import { ensureHumanRoleDefaultGrants } from "../services/principal-access-compa import { subscribeCompanyLiveEvents } from "../services/live-events.js"; import { LOW_TRUST_QUARANTINED_BODY, buildLowTrustSourceTrust, buildPromotedSourceTrust, sanitizeQuarantinedCommentForHigherTrust } from "../services/source-trust.js"; import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js"; +import { nativeCompletionFeedback } from "../services/native-runtime/native-completion-feedback.js"; import { documentService } from "../services/documents.js"; import { assertNoExternalOverlap, withExternalAdmissionGuard } from "../modules/external-agents/index.js"; import { digestPaperclipSemanticContent, externalOperationDigest, parseNativeExecutionInput, canonicalNativeRuntimeContextDigest, nativeRuntimePromptDigest, NATIVE_RUNTIME_ASSET_SCHEMA, PAPERCLIP_EXECUTION_PROMPT, PAPERCLIP_EXECUTION_PROMPT_REVISION, type ExternalProviderOperation } from "../vendor/paperclip-runner/index.js"; @@ -710,6 +711,36 @@ describe("personal Muse control plane",()=>{ expect(assertBridgeAuthority).not.toHaveBeenCalled(); }finally{release();await Promise.allSettled([holder,native]);await f.detach();} }); + it("lets the native Muse profile save the human request required to report a blocker", async () => { + const f = await active(await oauthFixture(true)); + await ensureHumanRoleDefaultGrants(db, { companyId: f.company.id, principalId: f.operatorId, membershipRole: "owner", grantedByUserId: f.operatorId }); + try { + await f.broker.act(f.subject, { version: 1, command: "accept", assignmentId: f.assignment.id, requestId: randomUUID() }); + const execution = { binding: { companyId: f.company.id, agentId: f.agent.id, runId: f.runId }, provider: { binding: f.ref } }; + const authority = new PaperclipRunnerToolAuthority(db, { ...execution.binding, issueId: f.issue.id, + museRuntime: true, externalAuthorizingUserId: f.operatorId, + assertBridgeAuthority: (database = db) => f.broker.assertRunAuthority(execution, database) }); + const result = { schema: "paperclip.run_result.v1" as const, reportedWorkDisposition: "blocked" as const, + summary: "Choose the release path.", completionClaim: { contractRevision: "test", objectiveSatisfied: false, criteria: [], remainingWork: [] }, + evidence: [], verification: [], artifacts: [], attentionRequests: [], + blocker: { owner: { kind: "user" as const, name: f.operatorId }, scope: "task_wide" as const, + reasonCode: "product_decision_required", unblockAction: "Choose upgrade or defer" } }; + await expect(nativeCompletionFeedback(db, f.runId, result)).rejects.toThrow("request_human_input"); + const names = authority.definitions().map(tool => tool.name); + expect(names).toContain("request_human_input"); + expect(names).not.toContain("call_api"); + expect(names).not.toContain("prepare_repository"); + const call = { tool: "request_human_input", callId: randomUUID(), arguments: { idempotencyKey: "release-path", + interactionKind: "questions", title: "Choose release path", prompt: "Upgrade changes the deployment. Defer keeps the current version.", + resolverPolicy: "human_only", continuationPolicy: "wake_assignee", payload: { questionSet: { schema: "paperclip.question_set.v1", + questions: [{ id: "path", prompt: "Which release path should I use?", answerMode: "single_select", required: true, + options: [{ id: "upgrade", label: "Upgrade" }, { id: "defer", label: "Defer" }] }] } } } }; + const saved = await authority.execute(call) as { interaction: { id: string } }; + await expect(nativeCompletionFeedback(db, f.runId, { ...result, evidence: [{ ref: `interaction:${saved.interaction.id}` }] })) + .resolves.toContain(`Pending request: ${saved.interaction.id}`); + await expect(authority.execute({ ...call, callId: randomUUID() })).resolves.toMatchObject({ interaction: { id: saved.interaction.id } }); + } finally { await f.detach(); } + }); it("serializes native and idle child creation without a privacy-tree deadlock",async()=>{ const f=await active(await oauthFixture(true)); await ensureHumanRoleDefaultGrants(db,{companyId:f.company.id,principalId:f.operatorId,membershipRole:"owner",grantedByUserId:f.operatorId}); diff --git a/server/src/services/native-runtime/historical-task-questions.test.ts b/server/src/services/native-runtime/historical-task-questions.test.ts index 8be07e309b1..00242054afc 100644 --- a/server/src/services/native-runtime/historical-task-questions.test.ts +++ b/server/src/services/native-runtime/historical-task-questions.test.ts @@ -69,14 +69,12 @@ describe("historical task questions", () => { expect(feedback).not.toContain("waiting for a response"); expect(feedback).not.toContain("Tell the user"); expect(feedback).not.toContain(f.question.id); - const blockedFeedback = await nativeCompletionFeedback(db, f.runId, { + await expect(nativeCompletionFeedback(db, f.runId, { ...done, reportedWorkDisposition: "blocked", completionClaim: { ...done.completionClaim, objectiveSatisfied: false }, blocker: { reasonCode: "missing_access", reason: "Missing test environment access", owner: { name: "Environment owner", kind: "user" }, unblockAction: "Grant test access", scope: "task_wide" }, - }); - expect(blockedFeedback).toContain("Explain why work cannot continue"); - expect(blockedFeedback).not.toContain(f.question.id); + })).rejects.toThrow("request_human_input"); const authority = new PaperclipRunnerToolAuthority(db, f); expect(await authority.execute({ tool: "get_task_context", callId: "context", arguments: {} })) .toMatchObject({ taskQuestionContext: { questions: [{ id: f.question.id, historical: true }], truncated: false } }); diff --git a/server/src/services/native-runtime/native-completion-feedback.test.ts b/server/src/services/native-runtime/native-completion-feedback.test.ts index 7cc8d2e36df..4379b7c55ec 100644 --- a/server/src/services/native-runtime/native-completion-feedback.test.ts +++ b/server/src/services/native-runtime/native-completion-feedback.test.ts @@ -330,7 +330,8 @@ describe("native final-response feedback", () => { // Neither a similar description nor another run's card is identity proof. await expect(nativeCompletionFeedback(db, value.runId, { ...report, blocker: undefined, summary: "Wait for a separate approval" })).resolves.toContain("report accepted"); await db.update(issueThreadInteractions).set({ sourceRunId: null }).where(eq(issueThreadInteractions.id, interactionId)); - await expect(nativeCompletionFeedback(db, value.runId, report)).resolves.toContain("report accepted"); + if (disposition === "blocked") await expect(nativeCompletionFeedback(db, value.runId, report)).rejects.toThrow("request_human_input"); + else await expect(nativeCompletionFeedback(db, value.runId, report)).resolves.toContain("report accepted"); }); it.each(["accepted", "rejected"] as const)("allows a new question after a %s tool approval cited as completed evidence", async (status) => { const value = await fixture(), interactionId = randomUUID(), questionId = randomUUID(); @@ -580,7 +581,7 @@ describe("native final-response feedback", () => { await expect(nativeCompletionFeedback(db, value.runId, { ...report, blocker: { ...report.blocker!, reasonCode: "missing_access" } })) .resolves.toContain("Blocker report accepted"); await expect(nativeCompletionFeedback(db, value.runId, { ...report, blocker: { ...report.blocker!, owner: { kind: "user", name: "Owner" } } })) - .resolves.toContain("Blocker report accepted"); + .rejects.toThrow("request_human_input"); const [hold] = await db.insert(issueTreeHolds).values({ companyId: value.companyId, rootIssueId: value.issueId, mode: "pause" }).returning(); await expect(nativeCompletionFeedback(db, value.runId, report)).resolves.toContain("Blocker report accepted"); await db.update(issueTreeHolds).set({ status: "released" }).where(eq(issueTreeHolds.id, hold.id)); @@ -628,20 +629,24 @@ describe("native final-response feedback", () => { await expect(nativeCompletionFeedback(db, other.runId, { ...report, blocker: { ...report.blocker!, owner: { kind: "system", name: "GitHub API" } } })) .resolves.toContain("Blocker report accepted"); await expect(nativeCompletionFeedback(db, other.runId, { ...report, blocker: { ...report.blocker!, owner: { kind: "user", name: "Paperclip admin" } } })) - .resolves.toContain("Blocker report accepted"); + .rejects.toThrow("request_human_input"); await expect(nativeCompletionFeedback(db, other.runId, { ...report, blocker: { ...report.blocker!, reasonCode: "missing_access" } })) .resolves.toContain("Blocker report accepted"); await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, other.runId)); await expect(nativeCompletionFeedback(db, other.runId, report)).resolves.toContain("Blocker report accepted"); }); - it("asks a blocked provider to explain the cause and action instead of describing completed work", async () => { + it("rejects a human decision blocker without a saved answerable request", async () => { const value = await fixture(); - const feedback = await nativeCompletionFeedback(db, value.runId, { ...done, reportedWorkDisposition: "blocked", + const report: PrpStructuredRunResult = { ...done, reportedWorkDisposition: "blocked", completionClaim: { ...done.completionClaim, objectiveSatisfied: false }, - blocker: { reasonCode: "missing_access", reason: "Missing release access", owner: { name: "Release Owner", kind: "user" }, unblockAction: "Grant deployment access", scope: "task_wide" }, - }); - expect(feedback).toBe("Blocker report accepted. Explain why work cannot continue, name the blocker owner and give the unblock action in your final response; do not describe the task as completed."); - expect(feedback).not.toContain("Describe the completed work"); + blocker: { reasonCode: "product_decision_required", owner: { name: "Release Owner", kind: "user" }, + unblockAction: "Choose A: upgrade the deployment, or B: keep the current version", scope: "task_wide" }, + }; + await expect(nativeCompletionFeedback(db, value.runId, report)).rejects.toThrow("request_human_input"); + await expect(nativeCompletionFeedback(db, value.runId, { ...report, + attentionRequests: [{ kind: "human_input", ownerClass: "human", summary: report.blocker!.unblockAction }], + })).rejects.toThrow("request_human_input"); + expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, value.issueId)))).toHaveLength(0); }); it("gates completion on resultSchemaRef across summary, report_progress, description, agentMessage, and persisted final comments", async () => { diff --git a/server/src/services/native-runtime/native-completion-feedback.ts b/server/src/services/native-runtime/native-completion-feedback.ts index b2498e2753d..14a069c1d6d 100644 --- a/server/src/services/native-runtime/native-completion-feedback.ts +++ b/server/src/services/native-runtime/native-completion-feedback.ts @@ -9,6 +9,7 @@ import { findAutomaticCompletionReviews } from "./automatic-completion-reviews.j import { findSupersededExternalReviewRequests } from "./superseded-external-review-requests.js"; import { evaluateAgentInvokabilityFromDb } from "../agent-invokability.js"; import { resolveNativeBlockerOwner } from "./blocker-owner.js"; +import { assertNativeHumanBlockerRequest } from "./native-human-blocker-feedback.js"; import { issueService } from "../issues.js"; import { isConversation } from "../agent-conversations.js"; import { completionReviewStageEntry } from "../issue-execution-policy.js"; @@ -357,6 +358,9 @@ export async function nativeCompletionFeedback( } } } + await assertNativeHumanBlockerRequest(db, { + companyId: run.companyId, issueId: issue.id, runId, agentId: run.agentId, conversationMode: isConversation(issue), + }, result); if (interaction) { if (interaction.dismissedAt) { return `Completion report accepted; a deferred authorization request remains in conversation history (${interaction.id}). Do not repeat a reminder, reopen the request, or ask the user to dismiss it again. Dismissal does not authorize the protected action. Continue independent work; retain the existing gate until an authorized decision is recorded. Do not claim the gated work is complete.`; diff --git a/server/src/services/native-runtime/native-execution-input.ts b/server/src/services/native-runtime/native-execution-input.ts index 5f8b6beeaa2..a90067c13a0 100644 --- a/server/src/services/native-runtime/native-execution-input.ts +++ b/server/src/services/native-runtime/native-execution-input.ts @@ -245,7 +245,7 @@ export function buildNativeExecutionInput(input: BuildNativeExecutionInput): Nat wakePrompt, // Durable task questions must survive the current provider turn. // Keep routing visible before deferred tool discovery; usage belongs in the tool schema. - "Use Paperclip's request_human_input for durable task questions.", + "Use Paperclip's request_human_input for durable task questions. Before reporting a human-owned blocker, save the exact question or choices with resolverPolicy:human_only and continuationPolicy:wake_assignee. Cite interaction: from its saved receipt in evidence. Reuse an existing active request; a blocker description alone does not ask the user.", externalChatTurn && wake?.externalChatProvider === "github" ? NATIVE_GITHUB_ATTACHMENT_RECOVERY_GUIDANCE : "", diff --git a/server/src/services/native-runtime/native-human-blocker-feedback.test.ts b/server/src/services/native-runtime/native-human-blocker-feedback.test.ts new file mode 100644 index 00000000000..5dcee218281 --- /dev/null +++ b/server/src/services/native-runtime/native-human-blocker-feedback.test.ts @@ -0,0 +1,152 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, approvals, companies, companyMemberships, createDb, decisions, heartbeatRuns, issueApprovals, issueComments, issueQuestionResponseDeliveries, issues, issueThreadInteractions } from "@paperclipai/db"; +import type { PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js"; +import { startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js"; +import { assertNativeHumanBlockerRequest } from "./native-human-blocker-feedback.js"; +import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; +import { nativeCompletionFeedback } from "./native-completion-feedback.js"; +import { issueThreadInteractionService } from "../issue-thread-interactions.js"; + +const report: PrpStructuredRunResult = { + schema: "paperclip.run_result.v1", reportedWorkDisposition: "blocked", summary: "Choose the release path.", + completionClaim: { contractRevision: "test", objectiveSatisfied: false, criteria: [], + remainingWork: [{ description: "Wait for the release decision", blocksCompletion: true }] }, + blocker: { owner: { kind: "user", name: "release-owner" }, scope: "task_wide", + reasonCode: "product_decision_required", unblockAction: "Choose upgrade or defer" }, + evidence: [], verification: [], artifacts: [], attentionRequests: [], +}; + +describe("human blocker request admission", () => { + let temporary: Awaited>; + let db: ReturnType; + beforeAll(async () => { temporary = await startRecoveryPostgres("human-blocker-feedback-"); db = createDb(temporary.connectionString); }); + afterAll(async () => { await temporary?.cleanup(); }); + + async function fixture() { + const companyId = randomUUID(), issueId = randomUUID(), agentId = randomUUID(), runId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Release", issuePrefix: `R${companyId.slice(0, 8)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Worker", status: "active", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Prepare release", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId, + runtimeMode: "native", status: "running", contextSnapshot: { issueId } }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "release-owner", status: "active" }); + return { companyId, issueId, agentId, runId, conversationMode: false }; + } + + async function question(binding: Awaited>) { + const [request] = await db.insert(issueThreadInteractions).values({ companyId: binding.companyId, issueId: binding.issueId, + sourceRunId: binding.runId, createdByAgentId: binding.agentId, kind: "ask_user_questions", status: "pending", + effectiveResolverPolicy: "human_only", continuationPolicy: "wake_assignee", payload: { version: 1, questions: [{ + id: "path", prompt: "Choose the release path", selectionMode: "single", required: true, + options: [{ id: "upgrade", label: "Upgrade" }, { id: "defer", label: "Defer" }], + }] }, + }).returning(); + return request!; + } + + const cited = (kind: string, id: string): PrpStructuredRunResult => ({ ...report, evidence: [{ ref: `${kind}:${id}` }] }); + + it("accepts the saved native question and reuses its receipt without another card", async () => { + const binding = await fixture(); + const authority = new PaperclipRunnerToolAuthority(db, binding); + const call = { tool: "request_human_input", callId: randomUUID(), arguments: { + idempotencyKey: "release-path", interactionKind: "questions", title: "Choose release path", + prompt: "Upgrade changes the deployment. Defer keeps the current version. Choose one path.", + resolverPolicy: "human_only", continuationPolicy: "wake_assignee", + payload: { questionSet: { schema: "paperclip.question_set.v1", questions: [{ id: "path", + prompt: "Which release path should I use?", answerMode: "single_select", required: true, + options: [{ id: "upgrade", label: "Upgrade" }, { id: "defer", label: "Defer" }], + }] } }, + } }; + const saved = await authority.execute(call) as { interaction: { id: string } }; + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.interaction.id))).resolves.toBeUndefined(); + await expect(nativeCompletionFeedback(db, binding.runId, cited("interaction", saved.interaction.id))).resolves.toContain(`Pending request: ${saved.interaction.id}`); + await expect(authority.execute({ ...call, callId: randomUUID() })).resolves.toMatchObject({ interaction: { id: saved.interaction.id } }); + expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, binding.issueId))).toHaveLength(1); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, binding.runId)); + await db.update(issues).set({ status: "blocked", executionRunId: null }).where(eq(issues.id, binding.issueId)); + const answered = await issueThreadInteractionService(db).answerQuestions({ id: binding.issueId, companyId: binding.companyId }, + saved.interaction.id, { answers: [{ questionId: "path", optionIds: ["defer"] }] }, { userId: "release-owner" }); + expect(answered).toMatchObject({ status: "answered", resolvedByUserId: "release-owner" }); + expect(await db.select().from(issueQuestionResponseDeliveries).where(eq(issueQuestionResponseDeliveries.interactionId, saved.interaction.id))) + .toHaveLength(1); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.interaction.id))).rejects.toThrow("request_human_input"); + }); + + it.each([ + { status: "answered" }, { status: "rejected" }, { status: "cancelled" }, + { dismissedAt: new Date("2020-01-01") }, { effectiveResolverPolicy: "anyone" as const }, + { continuationPolicy: "none" }, { continuationPolicy: "wake_assignee_on_accept" }, + { addresseeUserId: "another-user" }, { kind: "suggest_tasks" }, + ])("rejects a request that cannot answer and resume this human blocker: %j", async patch => { + const binding = await fixture(), saved = await question(binding); + await db.update(issueThreadInteractions).set(patch).where(eq(issueThreadInteractions.id, saved.id)); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.id))).rejects.toThrow("request_human_input"); + }); + + it("does not accept an uncited question or evidence of completed work", async () => { + const binding = await fixture(), saved = await question(binding); + await expect(assertNativeHumanBlockerRequest(db, binding, report)).rejects.toThrow("request_human_input"); + const criteria = [{ criterionId: "decision", status: "satisfied" as const, evidenceRefs: [`interaction:${saved.id}`] }]; + await expect(assertNativeHumanBlockerRequest(db, binding, { ...report, + completionClaim: { ...report.completionClaim, criteria } })).rejects.toThrow("request_human_input"); + await expect(assertNativeHumanBlockerRequest(db, binding, { ...report, + completionClaim: { ...report.completionClaim, criteria: [{ ...criteria[0]!, status: "not_satisfied" }] } })).resolves.toBeUndefined(); + }); + + it("rejects another task, company, or agent's request", async () => { + const binding = await fixture(), other = await fixture(), saved = await question(other); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.id))).rejects.toThrow("request_human_input"); + await db.update(issueThreadInteractions).set({ companyId: binding.companyId, issueId: binding.issueId }) + .where(eq(issueThreadInteractions.id, saved.id)); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.id))).rejects.toThrow("request_human_input"); + await db.update(issueThreadInteractions).set({ createdByAgentId: binding.agentId, addresseeAgentId: other.agentId }) + .where(eq(issueThreadInteractions.id, saved.id)); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.id))).rejects.toThrow("request_human_input"); + }); + + it("reuses a prior run's active question but rejects it after later human direction", async () => { + const binding = await fixture(), saved = await question(binding); + await db.update(issueThreadInteractions).set({ sourceRunId: null }).where(eq(issueThreadInteractions.id, saved.id)); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.id))).resolves.toBeUndefined(); + await db.insert(issueComments).values({ companyId: binding.companyId, issueId: binding.issueId, + authorUserId: "release-owner", authorType: "user", body: "Keep the current version.", createdAt: new Date(saved.createdAt.getTime() + 1) }); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("interaction", saved.id))).rejects.toThrow("request_human_input"); + }); + + it("accepts an explicitly linked pending approval and rejects a resolved approval", async () => { + const binding = await fixture(); + const [saved] = await db.insert(approvals).values({ companyId: binding.companyId, type: "release", + requestedByAgentId: binding.agentId, status: "pending", payload: {} }).returning(); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("approval", saved!.id))).rejects.toThrow("request_human_input"); + await db.insert(issueApprovals).values({ companyId: binding.companyId, issueId: binding.issueId, approvalId: saved!.id }); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("approval", saved!.id))).resolves.toBeUndefined(); + await db.update(approvals).set({ status: "approved" }).where(eq(approvals.id, saved!.id)); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("approval", saved!.id))).rejects.toThrow("request_human_input"); + }); + + it("accepts an open decision with continuation, then rejects expiry or a completed decision", async () => { + const binding = await fixture(); + const [saved] = await db.insert(decisions).values({ companyId: binding.companyId, originIssueId: binding.issueId, + originAgentId: binding.agentId, originRunId: binding.runId, title: "Release path", body: "Choose a path", + options: [], signedSpec: "test", targetSnapshots: {}, expiresAt: new Date("2099-01-01"), continuationPolicy: "wake_origin_agent" }).returning(); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("decision", saved!.id))).resolves.toBeUndefined(); + for (const patch of [{ continuationPolicy: "none" }, { expiresAt: new Date("2020-01-01") }, { status: "decided" }]) { + await db.update(decisions).set({ continuationPolicy: "wake_origin_agent", expiresAt: new Date("2099-01-01"), status: "open", ...patch }) + .where(eq(decisions.id, saved!.id)); + await expect(assertNativeHumanBlockerRequest(db, binding, cited("decision", saved!.id))).rejects.toThrow("request_human_input"); + } + }); + + it("preserves non-human blockers and non-blocked reports", async () => { + const binding = await fixture(); + for (const kind of ["agent", "system"] as const) { + await expect(assertNativeHumanBlockerRequest(db, binding, { ...report, + blocker: { ...report.blocker!, owner: { kind, name: "Dependency" } } })).resolves.toBeUndefined(); + } + await expect(assertNativeHumanBlockerRequest(db, binding, { ...report, reportedWorkDisposition: "yielded" })).resolves.toBeUndefined(); + }); +}); diff --git a/server/src/services/native-runtime/native-human-blocker-feedback.ts b/server/src/services/native-runtime/native-human-blocker-feedback.ts new file mode 100644 index 00000000000..e687f682598 --- /dev/null +++ b/server/src/services/native-runtime/native-human-blocker-feedback.ts @@ -0,0 +1,59 @@ +import { and, eq, gt, inArray, isNull, or } from "drizzle-orm"; +import { approvals, decisions, issueApprovals, issueThreadInteractions, type Db } from "@paperclipai/db"; +import type { PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js"; +import { activeIssueInteractionCondition } from "../issue-question-context.js"; +import { nativeBlockerUserId } from "./native-blocker-owner.js"; + +export async function assertNativeHumanBlockerRequest(db: Db, binding: { + companyId: string; + issueId: string; + runId: string; + agentId: string; + conversationMode: boolean; +}, result: PrpStructuredRunResult): Promise { + if (result.reportedWorkDisposition !== "blocked" || result.blocker?.owner.kind !== "user") return; + const refs = [ + ...result.evidence.map(entry => entry.ref), + ...result.completionClaim.criteria.filter(entry => entry.status !== "satisfied").flatMap(entry => entry.evidenceRefs), + ]; + const ids = (kind: string) => refs.flatMap(ref => { + if (typeof ref !== "string") return []; + const match = new RegExp(`^${kind}:([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$`, "i").exec(ref); + return match ? [match[1]!] : []; + }); + const interactionIds = ids("interaction"), approvalIds = ids("approval"), decisionIds = ids("decision"); + if (interactionIds.length) { + const ownerUserId = await nativeBlockerUserId({ db, ...binding, owner: result.blocker.owner }); + const [request] = await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.companyId, binding.companyId), eq(issueThreadInteractions.issueId, binding.issueId), + inArray(issueThreadInteractions.id, interactionIds), eq(issueThreadInteractions.createdByAgentId, binding.agentId), + eq(issueThreadInteractions.status, "pending"), isNull(issueThreadInteractions.dismissedAt), + eq(issueThreadInteractions.effectiveResolverPolicy, "human_only"), + eq(issueThreadInteractions.continuationPolicy, "wake_assignee"), isNull(issueThreadInteractions.addresseeAgentId), + ownerUserId ? or(isNull(issueThreadInteractions.addresseeUserId), eq(issueThreadInteractions.addresseeUserId, ownerUserId)) : undefined, + inArray(issueThreadInteractions.kind, ["ask_user_questions", "request_confirmation", "request_checkbox_confirmation", "request_item_verdicts"]), + activeIssueInteractionCondition({ runId: binding.runId, conversationMode: binding.conversationMode }), + )).limit(1); + if (request) return; + } + if (approvalIds.length) { + const [request] = await db.select({ id: approvals.id }).from(issueApprovals).innerJoin(approvals, and( + eq(approvals.id, issueApprovals.approvalId), eq(approvals.companyId, binding.companyId), + )).where(and( + eq(issueApprovals.companyId, binding.companyId), eq(issueApprovals.issueId, binding.issueId), + inArray(approvals.id, approvalIds), eq(approvals.requestedByAgentId, binding.agentId), + inArray(approvals.status, ["pending", "revision_requested"]), + )).limit(1); + if (request) return; + } + if (decisionIds.length) { + const [request] = await db.select({ id: decisions.id }).from(decisions).where(and( + eq(decisions.companyId, binding.companyId), eq(decisions.originIssueId, binding.issueId), + eq(decisions.originAgentId, binding.agentId), inArray(decisions.id, decisionIds), + eq(decisions.status, "open"), gt(decisions.expiresAt, new Date()), + eq(decisions.continuationPolicy, "wake_origin_agent"), + )).limit(1); + if (request) return; + } + throw new Error("A human-owned blocker requires a saved, answerable request. Call request_human_input with the exact question or choices, resolverPolicy:human_only, continuationPolicy:wake_assignee, and a stable idempotencyKey. Cite interaction: from its saved receipt in evidence, then report the wait. Reuse an existing active request instead of creating a duplicate. A linked pending approval: or open decision: with automatic continuation also qualifies. A blocker description or attentionRequests entry alone does not ask the user. If the request was answered or dismissed, read that outcome and reassess; do not repeat the request."); +} diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 14a356b897d..0e9e2c16fc6 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -181,6 +181,7 @@ const IMPLEMENTED_OPERATIONS = new Set([ /** Closed first-party native Muse profile. No connector, generic API, credential or workspace grants. */ export const MUSE_NATIVE_OPERATIONS = new Set([ "get_identity", "list_people", + "request_human_input", "submit_complaint", "submit_suggestion", "get_task_context", "get_task_history", "search_tasks", "report_progress", "set_task_title", "set_task_monitor", "create_task", "handoff_case", ...NATIVE_CASE_OPERATIONS, "reassign_task", "set_dependencies", "create_project", "list_projects", "list_documents", "read_document", "list_document_revisions", "write_document", "list_agents", "get_agent", "list_approvals", "get_approval", "get_approval_context", "read_current_wake_comments", "resolve_review",