Files
PaperClipAI/server/src/services/cross-issue-influence-limit.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

204 lines
6.9 KiB
TypeScript

import { and, count, eq } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { activityLog, heartbeatRuns } from "@paperclipai/db";
import { isUuidLike, issueWriteDenialResponse } from "@paperclipai/shared";
import { forbidden } from "../errors.js";
import { logger } from "../middleware/logger.js";
export const CROSS_ISSUE_INFLUENCE_LIMIT = 20;
export const CROSS_ISSUE_INFLUENCE_ENFORCE_AT = new Date("2026-08-11T00:00:00.000Z");
const CROSS_ISSUE_INFLUENCE_ACTIVITY = "issue.cross_issue_influence_observed";
const CROSS_ISSUE_INFLUENCE_REJECTED_ACTIVITY = "issue.cross_issue_influence_cap_rejected";
/**
* Every kind shares one per-run counter. `interaction_resolution` covers the
* issue-thread accept/reject/respond/verdict routes: an open `anyone` resolver
* audience is not a licence to resolve, wake, and spawn suggested tasks across
* the whole company from one run.
*/
export type CrossIssueInfluenceKind = "comment" | "update" | "interaction_resolution";
export type CrossIssueInfluenceDecision = {
allowed: boolean;
mode: "log_only" | "enforce";
count: number;
cap: number;
enforceAt: string;
};
export function crossIssueInfluenceRunContextError() {
// Copy comes from the shared issue-write denial contract (the open cross-task write design (failure UX))
// so the agent reading this 403 is told the fix, not just the refusal.
const { body } = issueWriteDenialResponse("cross_issue_influence_run_context_required");
return forbidden(body.error, body.details);
}
function readRunSourceIssueId(contextSnapshot: unknown) {
if (!contextSnapshot || typeof contextSnapshot !== "object" || Array.isArray(contextSnapshot)) return null;
const context = contextSnapshot as Record<string, unknown>;
for (const candidate of [context.issueId, context.taskId]) {
if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
}
return null;
}
export function evaluateCrossIssueInfluenceLimit(input: {
priorCount: number;
now?: Date;
}): CrossIssueInfluenceDecision {
const now = input.now ?? new Date();
const mode = now >= CROSS_ISSUE_INFLUENCE_ENFORCE_AT ? "enforce" : "log_only";
const nextCount = input.priorCount + 1;
return {
allowed: mode === "log_only" || nextCount <= CROSS_ISSUE_INFLUENCE_LIMIT,
mode,
count: nextCount,
cap: CROSS_ISSUE_INFLUENCE_LIMIT,
enforceAt: CROSS_ISSUE_INFLUENCE_ENFORCE_AT.toISOString(),
};
}
/**
* Atomically observes one cross-issue influence attempt for a heartbeat run.
*
* Locking the run row serializes concurrent attempts from the same run. The
* observation is intentionally recorded before the route mutation: once the
* rollout reaches enforcement, failures cannot be used to race or probe past
* the fail-closed backstop.
*/
export async function observeCrossIssueInfluence(
db: Db,
input: {
companyId: string;
runId: string;
agentId: string;
responsibleUserId?: string | null;
targetIssueId: string;
targetIssueIdentifier?: string | null;
kind: CrossIssueInfluenceKind;
now?: Date;
},
): Promise<CrossIssueInfluenceDecision | null> {
// API-key callers control the run header. Reject malformed UUIDs before the
// database can turn an untrusted identifier into a PostgreSQL cast error.
if (!isUuidLike(input.runId)) throw crossIssueInfluenceRunContextError();
return db.transaction(async (tx) => {
const run = await tx
.select({
id: heartbeatRuns.id,
companyId: heartbeatRuns.companyId,
agentId: heartbeatRuns.agentId,
responsibleUserId: heartbeatRuns.responsibleUserId,
contextSnapshot: heartbeatRuns.contextSnapshot,
})
.from(heartbeatRuns)
.where(and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.companyId),
eq(heartbeatRuns.agentId, input.agentId),
))
.for("update")
.then((rows) => rows[0] ?? null);
if (
!run ||
run.companyId !== input.companyId ||
run.agentId !== input.agentId
) {
throw crossIssueInfluenceRunContextError();
}
const sourceIssueId = readRunSourceIssueId(run.contextSnapshot);
if (!sourceIssueId) throw crossIssueInfluenceRunContextError();
if (
sourceIssueId === input.targetIssueId ||
(input.targetIssueIdentifier && sourceIssueId.toUpperCase() === input.targetIssueIdentifier.toUpperCase())
) {
return null;
}
const priorCount = await tx
.select({ count: count() })
.from(activityLog)
.where(and(
eq(activityLog.companyId, input.companyId),
eq(activityLog.runId, input.runId),
eq(activityLog.action, CROSS_ISSUE_INFLUENCE_ACTIVITY),
))
.then((rows) => Number(rows[0]?.count ?? 0));
const decision = evaluateCrossIssueInfluenceLimit({ priorCount, now: input.now });
await tx.insert(activityLog).values({
companyId: input.companyId,
actorType: "agent",
actorId: input.agentId,
agentId: input.agentId,
runId: input.runId,
responsibleUserId: input.responsibleUserId ?? run.responsibleUserId ?? null,
action: decision.allowed
? CROSS_ISSUE_INFLUENCE_ACTIVITY
: CROSS_ISSUE_INFLUENCE_REJECTED_ACTIVITY,
entityType: "issue",
entityId: input.targetIssueId,
details: {
kind: input.kind,
sourceIssueId,
targetIssueId: input.targetIssueId,
targetIssueIdentifier: input.targetIssueIdentifier ?? null,
count: decision.count,
cap: decision.cap,
mode: decision.mode,
enforceAt: decision.enforceAt,
allowed: decision.allowed,
},
});
const logContext = {
event: "cross_issue_influence_cap",
companyId: input.companyId,
runId: input.runId,
agentId: input.agentId,
sourceIssueId,
targetIssueId: input.targetIssueId,
kind: input.kind,
count: decision.count,
cap: decision.cap,
mode: decision.mode,
enforceAt: decision.enforceAt,
allowed: decision.allowed,
};
if (decision.allowed) {
logger.info(logContext, "cross-issue influence observed");
} else {
logger.warn(logContext, "cross-issue influence cap exceeded");
}
return decision;
});
}
export function crossIssueInfluenceLimitError(
decision: CrossIssueInfluenceDecision,
context: { actorLabel?: string | null; assigneeLabel?: string | null; issueIdentifier?: string | null } = {},
) {
// The cap is a rate backstop, not a permission decision — the shared copy
// contract says so explicitly, and names the next run as the way forward.
const { body } = issueWriteDenialResponse("cross_issue_influence_cap_exceeded", {
...context,
cap: decision.cap,
count: decision.count,
enforceAt: decision.enforceAt,
});
return {
error: body.error,
details: {
...body.details,
cap: decision.cap,
count: decision.count,
mode: decision.mode,
enforceAt: decision.enforceAt,
},
};
}