fix(chat): keep raw IDs and internal codes out of chat replies (#21081)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People talk to their agents in chat, and the agent replies in plain
text
> - In a full chat-eval cohort, 47 of 158 passing replies showed raw
UUIDs, error codes, field keys, tool names or server paths
> - Users must not see internal jargon or raw IDs, so these replies are
a product defect, even when the facts are correct
> - Agents copy these terms from API error messages and saved fields;
the chat directive did not tell them to translate
> - This pull request fixes the sources: the chat directive, and API
denial messages that put IDs and policy codes in the human message
> - The benefit is plain replies for every model, while machine codes
stay available in separate fields

## Linked Issues or Issue Description

**What happened?**

Chat replies quote internal names and raw IDs. Examples: run, handoff,
revision, interaction and trigger UUIDs in prose;
`native_session_retry_exhausted`, `board_access_required`,
`review_policy_denied`, `local-board`, `enableCases`; a raw user ID
inside the inbox denial message.

**Expected behavior**

Replies name records the way the person sees them (task identifier,
title or name, with a link) and explain codes in plain words. IDs stay
only in link targets, in commands the person must run, or when the
person asks for an ID.

**Steps to reproduce**

Run the chat-features OpenCode cohort (for example `cases.close-case`,
`routines.webhook-trigger`, `inbox-search.archive-without-grant`) and
read the agent replies.

**Paperclip version or commit**

`master` at f30005440b.

**Agent adapter(s) involved**

Not adapter-specific (core bug). Seen with the Paperclip runner and
OpenCode.

**Deployment mode**

Local dev server (embedded PGlite) and the CI chat-eval runner.

**Installation method**

Source checkout (`pnpm dev`).

## What Changed

- `AGENT_CHAT_DIRECTIVE`: add one rule. Name records by their
identifier, title or name and link them. Do not write raw IDs, internal
codes, field keys, tool names, process names or server paths, even in
inline code. The rule has exceptions for link targets, commands the
person runs, and IDs the person asks for. The rejection rule now asks
for the platform's reason "in plain words".
- Authorization denials (inbox management, membership, responsible user)
no longer put user or agent IDs in the explanation. The `reason` and
`code` values do not change.
- Review-policy denials explain the rule in plain words. The
`review_policy_denied` code and the `policy` and `allowedActor` fields
do not change.

## Verification

- Red/green: `server/src/__tests__/agent-conversations.test.ts`
(directive rule, and it reaches the chat task prompt),
`server/src/__tests__/authorization-service.test.ts` (inbox denials
carry no IDs), `server/src/__tests__/issue-review-policy.test.ts` and
`server/src/services/issue-thread-interaction-resolution.test.ts` (plain
review messages). Each new assertion failed before the fix.
- `pnpm verify` and the server typecheck pass locally.
- A paid OpenCode run on 8 affected chat cases is in progress; results
will be added here.

## Risks

- Low risk. Only human-readable messages and prompt text change. No
client matches the old message text; codes and machine fields stay the
same.
- The directive grows by one paragraph. A model can still copy an ID;
the rule reduces this but cannot prevent it.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code
with tool use and code 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 (e.g. `docs/...`, `fix/...`)
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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-12 09:37:07 -06:00
1 parent 8bdd53c11f
commit 9e910ff9ae
11 files changed
+201 -36

No files matched your search

@@ -987,6 +987,14 @@ describe("conversation execution wake policy", () => {
});
describe("chat prompt policy", () => {
it("tells chat to name records the way the person sees them instead of raw IDs, internal codes, tool names or server paths", () => {
expect(AGENT_CHAT_DIRECTIVE).toContain("give the specific reason returned by the platform, in plain words");
expect(AGENT_CHAT_DIRECTIVE).toContain("Write replies for the person, not for the API.");
expect(AGENT_CHAT_DIRECTIVE).toContain("Do not write raw IDs (UUIDs or their short forms for runs, revisions, handoffs, interactions, routines, triggers, attachments, workspaces, incidents, users or agents), internal codes (status, error, cause or reason codes such as native_session_retry_exhausted or board_access_required), field or setting keys, tool names, internal process names or server file paths in a reply, even in parentheses or inline code.");
expect(AGENT_CHAT_DIRECTIVE).toContain("The only exceptions are link targets, values inside a command the person must run, and an ID the person explicitly asks for.");
const prompt = buildPaperclipTaskMarkdown({ issue: { id: "chat", identifier: null, title: "Chat", workMode: "ask", conversationAgentId: "agent" } });
expect(prompt).toContain("Write replies for the person, not for the API.");
});
it("tells chat to record a person's decline with resolve-from-comment whoever created the card, and keeps withdraw for its own obsolete card", () => {
expect(AGENT_CHAT_DIRECTIVE).toContain("A person's explicit decline in chat (for example \"do not publish it\") answers a pending confirmation with reject, whoever created the card");
expect(AGENT_CHAT_DIRECTIVE).toContain("Withdraw is only for your own card that later evidence made obsolete; it never records the person's decision");
@@ -25,6 +25,7 @@ import {
authorizationService,
canActorReadIssuePrivacy,
issuePrivacyMode,
plainDelegatedUserDenial,
type AuthorizationActor,
} from "../services/authorization.js";
import { logger } from "../middleware/logger.js";
@@ -564,7 +565,69 @@ describeEmbeddedPostgres("authorization service", () => {
allowed: false,
code: "RESPONSIBLE_USER_UNAUTHORIZED",
});
expect(decision.explanation).toContain(`Responsible user ${responsibleUserId} is not authorized`);
expect(decision.explanation).toBe("The person this agent acts for does not have permission to change skills.");
expect(decision.explanation).not.toContain(responsibleUserId);
expect(decision.explanation).not.toContain("skill_config");
});
it("tells the agent that a responsible user's suggested change needs approval, not a missing permission", async () => {
const company = await createCompany(db, "ResponsibleUserSkillConsent");
const actorAgent = await createAgent(db, company.id);
const responsibleUserId = await createUser(db);
await grantAgentPermission(db, company.id, actorAgent.id, "skills:create");
await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "user",
principalId: responsibleUserId,
status: "active",
membershipRole: "viewer",
});
await db.insert(principalPermissionGrants).values({
companyId: company.id,
principalType: "user",
principalId: responsibleUserId,
permissionKey: "skills:suggest-changes",
scope: null,
grantedByUserId: "owner",
});
const decision = await authorizationService(db).decide({
actor: {
type: "agent",
agentId: actorAgent.id,
companyId: company.id,
onBehalfOfUserId: responsibleUserId,
source: "agent_jwt",
},
action: "skill_config:update",
resource: { type: "company", companyId: company.id },
});
expect(decision).toMatchObject({ allowed: false, reason: "deny_missing_consent", code: "RESPONSIBLE_USER_UNAUTHORIZED" });
expect(decision.explanation).toBe("The person this agent acts for can propose this change, but it needs approval before it is applied.");
});
it.each([
["deny_missing_membership", "The person this agent acts for is no longer an active member of this company."],
["deny_company_boundary", "The person this agent acts for cannot act in this company."],
["deny_unauthenticated", "Paperclip could not confirm who the person this agent acts for is."],
["deny_missing_grant", "The person this agent acts for does not have permission to change this task."],
["deny_no_grant", "The person this agent acts for does not have permission to change this task."],
["deny_scope", "The person this agent acts for does not have permission to change this task."],
["deny_unsupported_action", "The person this agent acts for does not have permission to change this task."],
["deny_missing_consent", "The person this agent acts for can propose this change, but it needs approval before it is applied."],
["deny_policy_restricted", "This company's access policy does not let the person this agent acts for change this task."],
["deny_low_trust_boundary", "This company's limits for this agent do not let the person this agent acts for change this task."],
["deny_agent_interaction", "Agents are not allowed to change this task in this company; a person who manages permissions can change this."],
["deny_issue_private", "The person this agent acts for cannot see this private task."],
["deny_project_private", "The person this agent acts for cannot see this private project."],
["inbox_target_user_unresolved", "Paperclip could not tell whose inbox this is."],
["inbox_management_disabled", "This person has turned off agent management of their inbox."],
["inbox_agent_not_allowed", "This agent is not on the list of agents this person allows to manage their inbox."],
] as const)("explains a delegated-user %s denial in plain words", (reason, expected) => {
const explanation = plainDelegatedUserDenial("The person this agent acts for", { reason }, "issue:mutate");
expect(explanation).toBe(expected);
expect(explanation).not.toMatch(/[a-z]+[_:][a-z]+/);
});
it("denies cross-company agent decisions before grant evaluation", async () => {
@@ -2576,6 +2639,47 @@ describeEmbeddedPostgres("authorization service", () => {
})).resolves.toMatchObject({ allowed: false, reason: "inbox_management_disabled" });
});
it("explains inbox denials without raw user or agent IDs", async () => {
const company = await createCompany(db, "InboxDenialWording");
const actorAgent = await createAgent(db, company.id);
const disabledUserId = await createUser(db);
const allowlistUserId = await createUser(db);
await db.insert(companyMemberships).values([disabledUserId, allowlistUserId].map((principalId) => ({
companyId: company.id,
principalType: "user" as const,
principalId,
status: "active" as const,
membershipRole: "operator" as const,
})));
await db.insert(userInboxAgentPolicies).values([
{ companyId: company.id, userId: disabledUserId, mode: "disabled" as const },
{ companyId: company.id, userId: allowlistUserId, mode: "allowlist" as const, allowedAgentIds: [] },
]);
const decideFor = (userId: string) => authorizationService(db).decide({
actor: {
type: "agent" as const,
agentId: actorAgent.id,
companyId: company.id,
onBehalfOfUserId: userId,
source: "agent_jwt" as const,
},
action: "inbox:manage" as const,
resource: { type: "company" as const, companyId: company.id },
});
const disabled = await decideFor(disabledUserId);
const allowlist = await decideFor(allowlistUserId);
expect(disabled).toMatchObject({ allowed: false, reason: "inbox_management_disabled" });
expect(allowlist).toMatchObject({ allowed: false, reason: "inbox_agent_not_allowed" });
for (const decision of [disabled, allowlist]) {
expect(decision.explanation).not.toContain(disabledUserId);
expect(decision.explanation).not.toContain(allowlistUserId);
expect(decision.explanation).not.toContain(actorAgent.id);
}
expect(disabled.explanation).toBe("This person has turned off agent management of their inbox.");
expect(allowlist.explanation).toBe("This agent is not on the list of agents this person allows to manage their inbox.");
});
it("enforces responsible-user inbox allowlists", async () => {
const company = await createCompany(db, "InboxAllowlist");
const allowedAgent = await createAgent(db, company.id);
@@ -119,6 +119,7 @@ describeEmbeddedPostgres("issue review verdict policy", () => {
policy: "not_creator",
allowedActor: "writer_other_than_review_requester",
}),
message: "Whoever sent this task for review cannot also approve or reject it; someone else must submit the verdict.",
});
await expect(assertIssueReviewVerdictActorAllowed(db, {
issue: seeded.issue,
@@ -233,7 +234,9 @@ describeEmbeddedPostgres("issue review verdict policy", () => {
code: "review_policy_denied",
policy: "human_only",
allowedActor: "authenticated_user_with_issue_write_access",
remediation: "Ask a person with access to this task to approve or reject it in Paperclip.",
}),
message: "Only a signed-in person can approve or reject this review; an agent cannot submit the verdict.",
});
await expect(assertIssueReviewVerdictActorAllowed(db, {
issue: seeded.issue,
@@ -319,12 +319,12 @@ describeEmbeddedPostgres("stalled review decision routes", () => {
.send({ status: "done" });
expect(requesterVerdict.status).toBe(403);
expect(requesterVerdict.body).toMatchObject({
error: expect.stringContaining("someone other than"),
error: expect.stringContaining("cannot also approve or reject it"),
details: {
code: "review_policy_denied",
policy: "not_creator",
allowedActor: "writer_other_than_review_requester",
remediation: expect.stringContaining("another writer"),
remediation: expect.stringContaining("someone else"),
},
});
@@ -350,12 +350,12 @@ describeEmbeddedPostgres("stalled review decision routes", () => {
.send({ status: "cancelled" });
expect(agentVerdict.status).toBe(403);
expect(agentVerdict.body).toMatchObject({
error: expect.stringContaining("authenticated user"),
error: expect.stringContaining("signed-in person"),
details: {
code: "review_policy_denied",
policy: "human_only",
allowedActor: "authenticated_user_with_issue_write_access",
remediation: "Have an authenticated user with issue write access submit the verdict.",
remediation: "Ask a person with access to this task to approve or reject it in Paperclip.",
},
});
@@ -386,7 +386,7 @@ describeEmbeddedPostgres("stalled review decision routes", () => {
code: "review_policy_denied",
policy: "human_only",
allowedActor: "authenticated_user_with_issue_write_access",
remediation: "Have an authenticated user with issue write access submit the verdict.",
remediation: "Ask a person with access to this task to approve or reject it in Paperclip.",
},
});
const [persisted] = await db.select({
@@ -426,7 +426,7 @@ describeEmbeddedPostgres("stalled review decision routes", () => {
code: "review_policy_denied",
policy: "not_creator",
allowedActor: "writer_other_than_review_requester",
remediation: "Have another writer with issue write access submit the verdict.",
remediation: "Have someone else with access to this task submit the verdict.",
},
});
const [persisted] = await db.select({
+1 -1
View File
@@ -1394,7 +1394,7 @@ describe("personal Muse control plane",()=>{
await db.insert(principalPermissionGrants).values({companyId:f.company.id,principalType:"agent",principalId:f.agent.id,permissionKey:"tasks:assign_scope",scope:{projectIds:[randomUUID()]}});
await expect(f.broker.act(f.subject,command)).rejects.toThrow();
await db.update(principalPermissionGrants).set({scope:{projectIds:[project.id]}}).where(and(eq(principalPermissionGrants.companyId,f.company.id),eq(principalPermissionGrants.principalId,f.agent.id)));
await expect(f.broker.act(f.subject,command)).rejects.toThrow("Authorizing user");
await expect(f.broker.act(f.subject,command)).rejects.toThrow(/the person who authorized this agent/i);
await db.insert(principalPermissionGrants).values({companyId:f.company.id,principalType:"user",principalId:f.operatorId,permissionKey:"tasks:assign_scope",scope:{projectIds:[randomUUID()]}});
await expect(f.broker.act(f.subject,command)).rejects.toThrow();
await db.update(principalPermissionGrants).set({scope:{projectIds:[project.id]}}).where(and(eq(principalPermissionGrants.companyId,f.company.id),eq(principalPermissionGrants.principalId,f.operatorId)));
+3 -1
View File
@@ -108,7 +108,7 @@ When the user directly asks you in this chat to update your own persistent instr
Paperclip keeps only each agent's current instruction files. Saving instructions does not record earlier versions, so instruction history lists only revisions saved before that change, and an empty history means no earlier text is retained. When asked to undo or revert an instruction change and no listed revision holds the earlier text, do not reconstruct it from the current file, its wording, or the activity log. Leave the instructions unchanged, say plainly that no earlier version was saved, and ask the person for the text they want or which part to remove.
When a tool or save receipt rejects an action, tell the user which action failed and give the specific reason returned by the platform. Do not claim it succeeded or describe all work as blocked by unspecified permissions. If this run lacks authority to save AGENTS.md, explain that this execution cannot change persistent instructions and that an authorized user can request the edit in their direct chat or apply it directly. Provide the proposed edit. Do not create another task to bypass that denial or suggest broadly lifting permissions. Continue any other authorized work.
When a tool or save receipt rejects an action, tell the user which action failed and give the specific reason returned by the platform, in plain words. Do not claim it succeeded or describe all work as blocked by unspecified permissions. If this run lacks authority to save AGENTS.md, explain that this execution cannot change persistent instructions and that an authorized user can request the edit in their direct chat or apply it directly. Provide the proposed edit. Do not create another task to bypass that denial or suggest broadly lifting permissions. Continue any other authorized work.
When the user asks to approve a plan before handoff, publish the plan and create a revision-bound approval card before ending the turn. With native tools, call request_human_input using interactionKind: "confirmation", targetRevisionId from the saved document's latestRevisionId, a revision-specific idempotencyKey, and continuationPolicy: "wake_assignee". Set payload.target to { type: "issue_document", key: "plan", revisionId: latestRevisionId }. Through the HTTP API, POST the equivalent request_confirmation interaction to /api/issues/{issueId}/interactions. A written request to approve in your reply does not create an approval card. After requested revisions, create a fresh card for the newly saved revision. This applies to explicitly requested plan approval; ordinary conversation replies and draft planning do not need confirmation. In Ask mode, discuss the plan without creating or revising documents or approval cards.
@@ -128,6 +128,8 @@ When a reply concerns a specific agent, such as one you paused, resumed, configu
When a reply lists many tasks, write each task identifier in full, such as RUN-12, RUN-13, RUN-14. This conversation links each full identifier to its task, but a range such as RUN-12–14 links only its first task and leaves the others without a source link. When a complete list is too long to read in the reply, save it as a document on this conversation's task and link it, such as [Open work by owner](/<prefix>/issues/<identifier>#document-<key>), keeping a short summary with the counts in the reply.
Write replies for the person, not for the API. Name each record by what the person sees in Paperclip: a task, case or approval by its identifier (such as RUN-12) or title, a person or agent by name, and link it. Do not write raw IDs (UUIDs or their short forms for runs, revisions, handoffs, interactions, routines, triggers, attachments, workspaces, incidents, users or agents), internal codes (status, error, cause or reason codes such as native_session_retry_exhausted or board_access_required), field or setting keys, tool names, internal process names or server file paths in a reply, even in parentheses or inline code. Say what each means in plain words instead, such as "automatic recovery gave up after 3 attempts" or "only a board user can do this". The only exceptions are link targets, values inside a command the person must run, and an ID the person explicitly asks for.
When the person asks what is in their inbox or what needs their attention, read their own list with GET /api/agents/me/inbox/mine?userId=<their user id>, using the authorUserId of their message. Answer from those tasks only: your own queue and a company-wide task search are not their inbox, so do not name or link tasks outside it. Link each task you cite and their list as [Mine](/<prefix>/inbox/mine), which opens their personal Mine view in every layout; do not send them to look through an inbox page for it. If that read fails, say so and link Mine instead of answering from other tasks.
A person's own display name and avatar belong to their account, and only they can change them in their profile settings at /<prefix>/company/settings/instance/profile. Agent credentials cannot edit a person's profile, and renaming an agent, a member record or the company does not change it. When the person asks to change their own name or avatar, link that page instead of attempting the change.
+59 -12
View File
@@ -190,6 +190,53 @@ function companyIdForResource(resource: AuthorizationResource) {
return resource.companyId;
}
function plainAuthorizationActionPhrase(action: AuthorizationAction): string {
switch (action) {
case "tasks:assign": return "assign this task";
case "issue:mutate": return "change this task";
case "issue:comment": return "comment on this task";
case "issue:read": return "view this task";
case "agent_config:read": return "view this agent's settings";
case "agent_config:update": return "change this agent's settings";
case "agent_instructions:update": return "change this agent's instructions";
case "skill_config:update": return "change skills";
case "secrets:read": return "read secrets";
case "secrets:propose": return "propose secrets";
case "project:read": return "view this project";
case "project:write_workspace": return "change this project's workspace";
default: return "do this";
}
}
const lowerFirst = (text: string) => `${text.charAt(0).toLowerCase()}${text.slice(1)}`;
type AuthorizationDenialReason = Exclude<AuthorizationDecision["reason"], `allow_${string}`>;
const PLAIN_DELEGATED_USER_DENIALS: Record<AuthorizationDenialReason, (subject: string, action: string) => string> = {
deny_missing_membership: (subject) => `${subject} is no longer an active member of this company.`,
deny_company_boundary: (subject) => `${subject} cannot act in this company.`,
deny_unauthenticated: (subject) => `Paperclip could not confirm who ${lowerFirst(subject)} is.`,
deny_missing_grant: (subject, action) => `${subject} does not have permission to ${action}.`,
deny_no_grant: (subject, action) => `${subject} does not have permission to ${action}.`,
deny_scope: (subject, action) => `${subject} does not have permission to ${action}.`,
deny_unsupported_action: (subject, action) => `${subject} does not have permission to ${action}.`,
deny_missing_consent: (subject) => `${subject} can propose this change, but it needs approval before it is applied.`,
deny_policy_restricted: (subject, action) => `This company's access policy does not let ${lowerFirst(subject)} ${action}.`,
deny_low_trust_boundary: (subject, action) => `This company's limits for this agent do not let ${lowerFirst(subject)} ${action}.`,
deny_agent_interaction: (_subject, action) => `Agents are not allowed to ${action} in this company; a person who manages permissions can change this.`,
deny_issue_private: (subject) => `${subject} cannot see this private task.`,
deny_project_private: (subject) => `${subject} cannot see this private project.`,
inbox_target_user_unresolved: () => "Paperclip could not tell whose inbox this is.",
inbox_management_disabled: () => "This person has turned off agent management of their inbox.",
inbox_agent_not_allowed: () => "This agent is not on the list of agents this person allows to manage their inbox.",
};
export function plainDelegatedUserDenial(subject: string, decision: Pick<AuthorizationDecision, "reason">, action: AuthorizationAction): string {
const phrase = plainAuthorizationActionPhrase(action);
const explain = decision.reason.startsWith("allow_") ? null : PLAIN_DELEGATED_USER_DENIALS[decision.reason as AuthorizationDenialReason];
return explain ? explain(subject, phrase) : `${subject} does not have permission to ${phrase}.`;
}
function permissionForAction(action: AuthorizationAction): PermissionKey | null {
if (isConnectionManagementAction(action)) return CONNECTION_MANAGEMENT_PERMISSIONS[action];
if (action === "project:write_workspace") return "tasks:assign";
@@ -1017,7 +1064,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
return deny({
action: input.action,
reason: "deny_missing_membership",
explanation: `${input.principalType} principal ${input.principalId} is not an active member of company ${input.companyId}.`,
explanation: input.principalType === "agent" ? "This agent is not an active member of this company." : "This user is not an active member of this company.",
});
}
@@ -2223,7 +2270,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
return deny({
action: input.action,
reason: "deny_missing_membership",
explanation: `user principal ${input.actor.userId} is not an active member of company ${companyId}.`,
explanation: "This user is not an active member of this company.",
});
}
if (
@@ -2265,7 +2312,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
return deny({
action: input.action,
reason: "deny_missing_membership",
explanation: `user principal ${input.actor.userId} is not an active member of company ${companyId}.`,
explanation: "This user is not an active member of this company.",
});
}
return deny({
@@ -2441,7 +2488,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
return deny({
action: input.action,
reason: "deny_missing_membership",
explanation: `Inbox target user ${targetUserId} is not an active member of company ${companyId}.`,
explanation: "The person whose inbox was requested is not an active member of this company.",
});
}
@@ -2486,14 +2533,14 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
return deny({
action: input.action,
reason: "inbox_management_disabled",
explanation: `Inbox management is disabled for user ${targetUserId}.`,
explanation: "This person has turned off agent management of their inbox.",
});
}
if (policy?.mode === "allowlist" && !policy.allowedAgentIds.includes(actorAgentId)) {
return deny({
action: input.action,
reason: "inbox_agent_not_allowed",
explanation: `Agent ${actorAgentId} is not allowed to manage user ${targetUserId}'s inbox.`,
explanation: "This agent is not on the list of agents this person allows to manage their inbox.",
});
}
if (policy?.mode === "open" || policy?.mode === "allowlist") {
@@ -2531,14 +2578,14 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
return deny({
action: input.action,
reason: "inbox_management_disabled",
explanation: `Inbox management is disabled for user ${targetUserId}.`,
explanation: "This person has turned off agent management of their inbox.",
});
}
if (policy?.mode === "allowlist" && !policy.allowedAgentIds.includes(actorAgentId)) {
return deny({
action: input.action,
reason: "inbox_agent_not_allowed",
explanation: `Agent ${actorAgentId} is not allowed to manage user ${targetUserId}'s inbox.`,
explanation: "This agent is not on the list of agents this person allows to manage their inbox.",
});
}
@@ -2822,7 +2869,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
: deny({
action: input.action,
reason: "deny_missing_membership",
explanation: `Responsible user ${responsibleUserId} is unavailable for company ${companyId}.`,
explanation: "The person this agent acts for is no longer an active member of this company.",
});
if (
@@ -2841,8 +2888,8 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
code: denyCode,
explanation:
denyCode === "RESPONSIBLE_USER_UNAVAILABLE"
? `Responsible user ${responsibleUserId} is unavailable for company ${companyId}.`
: `Responsible user ${responsibleUserId} is not authorized for ${input.action}: ${userDecision.explanation}`,
? "The person this agent acts for is no longer an active member of this company."
: plainDelegatedUserDenial("The person this agent acts for", userDecision, input.action),
grant: userDecision.grant,
});
@@ -2893,7 +2940,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
return deny({
action: input.action,
reason: userDecision.reason,
explanation: `Authorizing user is not authorized for ${input.action}: ${userDecision.explanation}`,
explanation: plainDelegatedUserDenial("The person who authorized this agent", userDecision, input.action),
grant: userDecision.grant,
});
}
+6 -6
View File
@@ -111,12 +111,12 @@ export async function assertIssueReviewVerdictActorAllowed(
if (policy === "human_only") {
if (input.actor.type === "user") return;
throw forbidden(
"Review policy `human_only` allows only an authenticated user to approve or reject this review.",
"Only a signed-in person can approve or reject this review; an agent cannot submit the verdict.",
{
code: "review_policy_denied",
policy,
allowedActor: "authenticated_user_with_issue_write_access",
remediation: "Have an authenticated user with issue write access submit the verdict.",
remediation: "Ask a person with access to this task to approve or reject it in Paperclip.",
},
);
}
@@ -124,24 +124,24 @@ export async function assertIssueReviewVerdictActorAllowed(
const requester = await resolveIssueReviewRequester(db, input.issue);
if (!requester) {
throw forbidden(
"Review policy `not_creator` requires a different writer, but the review requester could not be determined.",
"Someone other than whoever sent this task for review must decide it, and Paperclip could not tell who sent it.",
{
code: "review_policy_denied",
policy,
allowedActor: "writer_other_than_review_requester",
remediation: "Move the issue out of and back into `in_review` to record a requester before another writer submits the verdict.",
remediation: "Move the task out of review and back into review so Paperclip records who sent it, then have someone else submit the verdict.",
},
);
}
if (requester.type !== input.actor.type || requester.id !== input.actor.id) return;
throw forbidden(
"Review policy `not_creator` requires someone other than the writer who moved the issue into `in_review` to approve or reject it.",
"Whoever sent this task for review cannot also approve or reject it; someone else must submit the verdict.",
{
code: "review_policy_denied",
policy,
allowedActor: "writer_other_than_review_requester",
remediation: "Have another writer with issue write access submit the verdict.",
remediation: "Have someone else with access to this task submit the verdict.",
},
);
}
@@ -123,6 +123,7 @@ describe("issue-thread interaction resolver audience", () => {
})).toMatchObject({
allowed: false,
code: "review_policy_denied",
message: "Whoever sent this task for review cannot also approve or reject it; someone else must submit the verdict.",
details: {
policy: "not_creator",
allowedActor: "writer_other_than_review_requester",
@@ -146,14 +146,14 @@ function reviewPolicyDeniedDecision(
status: 403,
code: "review_policy_denied",
message: requesterKnown
? "Review policy `not_creator` requires someone other than the writer who moved the issue into `in_review` to approve or reject it."
: "Review policy `not_creator` requires a different writer, but the review requester could not be determined.",
? "Whoever sent this task for review cannot also approve or reject it; someone else must submit the verdict."
: "Someone other than whoever sent this task for review must decide it, and Paperclip could not tell who sent it.",
details: {
policy: "not_creator",
allowedActor: "writer_other_than_review_requester",
remediation: requesterKnown
? "Have another writer with issue write access submit the verdict, or change reviewPolicy to `anyone`."
: "Change reviewPolicy to `anyone`, or move the issue out of and back into `in_review` to record a requester before another writer submits the verdict.",
? "Have someone else with access to this task submit the verdict, or let anyone review it by setting the task's review policy to anyone."
: "Let anyone review it by setting the task's review policy to anyone, or move the task out of review and back into review so Paperclip records who sent it, then have someone else submit the verdict.",
},
};
}
@@ -402,20 +402,20 @@ describe("Muse native visibility intersection", () => {
.toEqual([{ owner: null, version: target.statusVersion }]);
expect(enqueueWakeup).not.toHaveBeenCalled();
};
await expect(authority.execute(call)).rejects.toThrow("Authorizing user is not authorized for tasks:assign");
await expect(authority.execute(call)).rejects.toThrow(/the person who authorized this agent.* assign this task\.$/i);
await assertUnchanged();
const [grant] = await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user", principalId: f.authorizer,
permissionKey: "tasks:assign_scope", scope: { agentIds: [protectedAgent.id], projectIds: [randomUUID()] } }).returning();
await expect(authority.execute(call)).rejects.toThrow("Authorizing user is not authorized for tasks:assign");
await expect(authority.execute(call)).rejects.toThrow(/the person who authorized this agent.* assign this task\.$/i);
await assertUnchanged();
await db.update(principalPermissionGrants).set({ scope: { agentIds: [randomUUID()], projectIds: [project.id] } }).where(eq(principalPermissionGrants.id, grant.id));
await expect(authority.execute(call)).rejects.toThrow("Authorizing user is not authorized for tasks:assign");
await expect(authority.execute(call)).rejects.toThrow(/the person who authorized this agent.* assign this task\.$/i);
await assertUnchanged();
await db.update(principalPermissionGrants).set({ scope: { agentIds: [protectedAgent.id], projectIds: [project.id] } }).where(eq(principalPermissionGrants.id, grant.id));
await expect(authority.execute(call)).resolves.toMatchObject({ disposition: "applied" });
expect(enqueueWakeup).toHaveBeenCalledTimes(1);
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.id, grant.id));
await expect(authority.execute(call)).rejects.toThrow("Authorizing user is not authorized for tasks:assign");
await expect(authority.execute(call)).rejects.toThrow(/the person who authorized this agent.* assign this task\.$/i);
expect(enqueueWakeup).toHaveBeenCalledTimes(1);
});
@@ -430,7 +430,7 @@ describe("Muse native visibility intersection", () => {
const authority = new PaperclipRunnerToolAuthority(db, { companyId: f.companyId, agentId: f.agentId, issueId: f.issue.id, runId,
museRuntime: true, externalAuthorizingUserId: f.authorizer, assertBridgeAuthority: async () => {} });
const call = { tool: "write_document", callId: "viewer-write", arguments: { key: "report", title: "Report", body: "Must not be written", baseRevisionId: null, idempotencyKey: "viewer-write" } };
await expect(authority.execute(call)).rejects.toThrow("Authorizing user is not authorized for issue:mutate");
await expect(authority.execute(call)).rejects.toThrow("The person who authorized this agent does not have permission to change this task.");
expect(await db.select({ id: issueDocuments.id }).from(issueDocuments).where(eq(issueDocuments.issueId, f.issue.id))).toEqual([]);
await db.update(companyMemberships).set({ membershipRole: "operator" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, f.authorizer)));
await expect(authority.execute(call)).resolves.toMatchObject({ disposition: "applied" });