Files
PaperClipAI/server/src/services/issue-review-policy.ts
T
DottaandPaperclip 10d0555189 fix(interactions): authorize resolvers consistently (#11376)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Issue interactions give agents and people a structured decision
record.
> - Resolver routes used different authorization rules.
> - Some routes blocked valid agents, including task watchdogs with
normal issue access.
> - The API did not show who could resolve a pending interaction.
> - This pull request gives every interaction kind one resolver policy
evaluator.
> - The benefit is a clear decision path with consistent governance and
company isolation.

## Linked Issues or Issue Description

Fixes: #8087

Refs: #7403

Related PR: #11082 proposes board-only confirmation rules. This change
keeps human-only review as an explicit policy.

**What happened?**

Agents could create issue interactions. Some resolver routes still
required board access.

This left valid agent confirmations pending. Task watchdogs could see
the same problem without board identity.

**Expected behavior**

Every interaction kind must use one resolver policy contract.

The contract must support `anyone`, `not_creator`, and `human_only`. It
must also apply all normal governance controls.

**Steps to reproduce**

1. Create a `request_confirmation` interaction as an agent.
2. Resolve it with another authorized agent.
3. Observe the board-only denial.

**Paperclip version or commit**

The problem exists on `master` before this change.

**Deployment mode**

Local development with `pnpm dev`.

## What Changed

- Add canonical policies for `anyone`, `not_creator`, and `human_only`.
- Use one server evaluator for every interaction kind.
- Apply named addressees, company limits, review rules, and task
watchdog scope.
- Charge cross-issue resolutions to the existing per-run action limit.
- Return the effective resolver audience in attention and interaction
data.
- Show the audience, governance choices, and denial reasons in the board
UI.
- Add telemetry, API documents, product documents, and regression
fixtures.
- Add migration provenance for safe legacy behavior.
- Make migration `0218` safe for complete replays and partial prior
runs.

## Product Rules

- An interaction records a response. It does not grant authority for the
next action.
- `anyone` lets any authorized issue participant respond.
- `not_creator` requires a responder other than the interaction creator.
- `human_only` requires an authorized person.
- A named addressee, company policy, or governed action can narrow the
audience.
- These controls cannot widen the audience.
- A task watchdog uses the same rules as an ordinary agent.
- A task watchdog does not receive board authority.
- An agent resolution on another issue uses the shared cross-issue
action limit.
- Legacy pending interactions keep their earlier restrictions.
- The UI shows the effective audience and a permanent denial reason.

## Verification

- `pnpm --filter @paperclipai/db check:migrations`
- `pnpm --filter @paperclipai/db typecheck`
- `pnpm exec vitest run
packages/db/src/issue-thread-interaction-resolver-policy-migration.test.ts`
- The focused PostgreSQL test applies migration `0218` twice.
- The test also completes a partial prior run and preserves existing
provenance.
- The latest GitHub head has 29 successful checks.
- The opt-in Storybook visual check skipped as expected.
- Greptile reports 5/5 with no open comments.

## Risks

- New interaction writes use `anyone` by default.
- Callers must select `not_creator` or `human_only` when they need
stricter review.
- Legacy pending interactions keep the old creator and human
restrictions.
- Migration `0218` fills only missing provenance fields during recovery.
- Cross-issue resolutions can reach the existing action limit.
- The shared evaluator affects every interaction kind.
- Route, service, database, shared contract, and UI tests cover these
rules.

> This work matches the Agent Reviews and Approvals direction in
`ROADMAP.md`. It does not duplicate a planned item.

## Model Used

OpenAI Codex, GPT-5. The runtime does not expose the exact deployment ID
or context window.

The agent used reasoning, repository tools, shell commands, and test
execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either linked public issues or described the issue with the
required labels
- [x] I have not referenced internal Paperclip issues or links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented the risks
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open comments
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-08-16 13:46:50 -05:00

148 lines
5.1 KiB
TypeScript

import { and, desc, eq, sql } from "drizzle-orm";
import { activityLog, type Db } from "@paperclipai/db";
import type { IssueReviewPolicy } from "@paperclipai/shared";
import { forbidden } from "../errors.js";
export interface IssueReviewVerdictActor {
type: "agent" | "user";
id: string;
}
export interface IssueReviewRequester extends IssueReviewVerdictActor {
reviewInteractionId: string | null;
}
interface ReviewPolicyIssue {
id: string;
companyId: string;
reviewPolicy?: IssueReviewPolicy | null;
createdByAgentId?: string | null;
createdByUserId?: string | null;
}
export async function resolveIssueReviewRequester(
db: Db,
issue: ReviewPolicyIssue,
): Promise<IssueReviewRequester | null> {
const transition = await db
.select({
actorType: activityLog.actorType,
actorId: activityLog.actorId,
details: activityLog.details,
})
.from(activityLog)
.where(and(
eq(activityLog.companyId, issue.companyId),
eq(activityLog.entityType, "issue"),
eq(activityLog.entityId, issue.id),
eq(activityLog.action, "issue.updated"),
sql`(
(
${activityLog.details} ->> 'status' = 'in_review'
AND ${activityLog.details} -> '_previous' ->> 'status' IS NOT NULL
AND ${activityLog.details} -> '_previous' ->> 'status' <> 'in_review'
)
OR
(
${activityLog.details} -> 'changes' -> 'status' ->> 'to' = 'in_review'
AND ${activityLog.details} -> 'changes' -> 'status' ->> 'from' IS NOT NULL
AND ${activityLog.details} -> 'changes' -> 'status' ->> 'from' <> 'in_review'
)
)`,
))
.orderBy(desc(activityLog.createdAt), desc(activityLog.id))
.limit(1)
.then((rows) => rows[0] ?? null);
if (transition?.actorType === "agent" || transition?.actorType === "user") {
const reviewInteractionId = typeof transition.details?.reviewInteractionId === "string"
? transition.details.reviewInteractionId
: null;
return { type: transition.actorType, id: transition.actorId, reviewInteractionId };
}
if (issue.createdByAgentId && !issue.createdByUserId) {
return { type: "agent", id: issue.createdByAgentId, reviewInteractionId: null };
}
if (issue.createdByUserId && !issue.createdByAgentId) {
return { type: "user", id: issue.createdByUserId, reviewInteractionId: null };
}
return null;
}
export async function isIssueReviewVerdictInteraction(
db: Db,
input: {
issue: ReviewPolicyIssue;
interaction: {
id: string;
createdByAgentId?: string | null;
createdByUserId?: string | null;
};
},
): Promise<boolean> {
const requester = await resolveIssueReviewRequester(db, input.issue);
if (!requester) return false;
if (requester.reviewInteractionId && requester.reviewInteractionId !== input.interaction.id) return false;
// Older review transitions did not persist the interaction binding. In that
// case, an unattributed confirmation is ambiguous and must fail closed.
// Confirmations attributed to an unrelated writer remain independently
// resolvable, while requester-created confirmations inherit the issue policy.
if (!requester.reviewInteractionId
&& !input.interaction.createdByAgentId
&& !input.interaction.createdByUserId) {
return true;
}
return requester.type === "agent"
? input.interaction.createdByAgentId === requester.id
: input.interaction.createdByUserId === requester.id;
}
export async function assertIssueReviewVerdictActorAllowed(
db: Db,
input: {
issue: ReviewPolicyIssue;
actor: IssueReviewVerdictActor;
reviewPolicy?: IssueReviewPolicy | null;
},
): Promise<void> {
const policy = input.reviewPolicy ?? input.issue.reviewPolicy ?? "anyone";
if (policy === "anyone") return;
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.",
{
code: "review_policy_denied",
policy,
allowedActor: "authenticated_user_with_issue_write_access",
remediation: "Have an authenticated user with issue write access submit the verdict.",
},
);
}
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.",
{
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.",
},
);
}
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.",
{
code: "review_policy_denied",
policy,
allowedActor: "writer_other_than_review_requester",
remediation: "Have another writer with issue write access submit the verdict.",
},
);
}