Files
PaperClipAI/server/src/services/agent-task-retry.ts
T
Dottaandlucktastic a74b4f8196 feat(retry): let a board user grant one agent the task Retry (#22988)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When a run stops in a state that needs board approval, Paperclip
holds the task until a board user presses Retry (`POST
/api/issues/{id}/retry`).
> - Some companies run an operations agent that reviews stopped tasks
and identifies routine Retries, but the route currently rejects every
agent with `403 Board access required`.
> - The only workaround is sharing a board key with the agent, which
grants unrelated board powers and hides which agent requested the Retry.
> - This pull request adds one narrow, opt-in permission key
(`tasks:retry`) that a board user can grant to a named agent so the
agent can call `POST /api/issues/{id}/retry` as that person, under all
existing gates and a per-task daily cap.
> - The benefit is that routine Retries stop waiting on manual clicks
while preserving least privilege, existing pause/budget/hold gates, and
full audit attribution for both the agent and the granting person.

## Linked Issues or Issue Description

- Closes #21633
- Supersedes #21634 (rebased cleanly onto current `master` with synced
SDK public input pins, OpenAPI `429` response documentation, and
additional route integration coverage for pause gates, revoked grants,
inactive grantors, cross-company isolation, and chat tasks)
- Refs #20081 and #18599 (broader delegate proposals; this change stays
narrow to one action, one grant per agent, and a per-task daily cap)

## What Changed

- `packages/shared/src/constants.ts`: add `tasks:retry` to
`PERMISSION_KEYS`. New agents do not receive it by default.
- `server/src/services/agent-task-retry.ts` (new):
- `agentTaskRetryActor`: resolves the agent's unscoped `tasks:retry`
grant and the active same-company board member who saved it. Grants
without a granting user (for example, agent-written rows), grants saved
with a scope, revoked grants, and inactive grantors return `null` and
fail closed. Returns a board actor scoped strictly to the agent's
company with `isInstanceAdmin: false`.
- `agentOwnsRun`: verifies that the supplied run ID is a valid UUID
belonging to the calling agent in the same company.
- `recordAgentTaskRetry`: under a per-task PostgreSQL transaction
advisory lock (`agent-task-retry:{issueId}`), enforces a rolling 24-hour
cap of 3 Retries per agent per task (`429` with `details.code:
"agent_task_retry_cap_reached"`), counts replays of the same
`idempotencyKey` once, and writes `issue.retry_requested_by_agent` to
`activity_log` with the agent, run ID, `grantedByUserId`, and
`idempotencyKey`.
- `server/src/routes/issues.ts` (`POST /issues/:id/retry`; small
+33-line delegation calling into
`server/src/services/agent-task-retry.ts` so the existing >1,000-line
route module does not absorb service logic): for an agent with a valid
`tasks:retry` grant, enforces the agent's own limits first (refuses
scoped `skill_test`/`task_bridge` keys, requires the agent's own run ID,
enforces `issue:read` and actor-class/interaction `issue:mutate`
boundaries), then runs the existing board Retry checks as the granting
person (preserving visibility, `issue:mutate`, pause, budget, hold, and
blocker gates). Refuses chat tasks (`403`) and cross-company tasks
(`404`). Agents without a valid grant keep getting `403`.
- `server/src/routes/openapi.ts`: remove `POST /api/issues/{id}/retry`
from `BOARD_ONLY_OPERATIONS` so granted agents can discover it via API
search, and document `429` in the endpoint responses.
- `doc/agent-permission-defaults.md` and `docs/api/issues.md`: document
`tasks:retry`, its default-off behavior, run/key requirements, daily
cap, and activity attribution.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the pin for
`packages/shared/src/constants.ts`.
- `server/src/__tests__/issue-scheduled-retry-routes.test.ts` and
`server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`:
add 14 embedded-Postgres route integration tests and 1 mocked-boundary
test covering default refusal, agent-written grant refusal,
board-granted Retry promotion + activity attribution, pause-gate
preservation, grantor visibility gates, revoked grant / suspended
grantor fail-closed, cross-company 404, chat task 403, daily cap 429,
idempotency replay counting, foreign run ID refusal, scoped grant
refusal, low-trust read/write boundary enforcement, and scoped key
refusal.

## Verification

- RED check on base `2d065677959b585065ff3fec8718156a4cf6f41d` before
production changes:
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scheduled-retry-routes.test.ts -t "agent Retry with
a board user's tasks:retry grant"` failed because granted agents
received `403 Board access required` instead of `202` / `429` / `404`
and logged 0 `issue.retry_requested_by_agent` events.
- GREEN checks on head `14b5591073ea591251f2d24710a32e3c725a090c`:
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/server
typecheck`: passed (0 errors across `@paperclipai/shared` and all 7
`@paperclipai/server` typecheck layers).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scheduled-retry-routes.test.ts
src/__tests__/openapi-routes.test.ts
src/__tests__/agent-default-configure-grants.test.ts`: passed (112/112
tests, including all 14 embedded-Postgres `agent Retry with a board
user's tasks:retry grant` tests and default-grant verification).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-agent-mutation-ownership-routes.test.ts`: passed
(229/229 tests).
- `pnpm exec vitest run --root tests/runner-e2e
source-sdk-public-inputs.test.mjs source-sdk-evidence.test.ts
source-sdk-public-type.test.ts
chat-catalog-domains/identity-accounting.test.ts`: passed (4 files,
98/98 tests).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check`: passed (`changed: false`, 578 inputs in sync).
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-scheduled-retry-routes.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`:
passed (`110 nightly suites validated, 2 test file(s) checked`).
- `pnpm verify --base 2d06567795
--explain`: exited 2 (`Global CI input changed:
doc/agent-permission-defaults.md`); sharded PR CI covers the full suite.

## Risks

- A granted agent acts with the granting board user's authority on `POST
/api/issues/{id}/retry` within the agent's company. Revoking the grant
or deactivating the granting user immediately closes access.
- The per-task daily cap counts `issue.retry_requested_by_agent` rows in
`activity_log`; pruning `activity_log` within 24 hours would reset that
window early.
- Downstream Retry domain records name the granting user; the initiating
agent and run are recorded in the corresponding
`issue.retry_requested_by_agent` activity entry.
- Sandboxed agents using the sandbox callback bridge remain blocked from
this route; this change does not widen the bridge.

## Model Used

- Google Gemini (Antigravity agentic coding assistant with extended
reasoning, shell execution, file editing, and automated test
verification), building on #21634 (originally co-authored by lucktastic
and Claude Opus 5.5).

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: lucktastic <13757243+lucktastic@users.noreply.github.com>
2026-11-25 22:06:37 +00:00

90 lines
5.5 KiB
TypeScript

import { and, count, eq, gt, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { isUuidLike } from "@paperclipai/shared";
import { activityLog, agentWakeupRequests, companyMemberships, heartbeatRuns, principalPermissionGrants } from "@paperclipai/db";
import { HttpError } from "../errors.js";
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
/** Retries one granted agent may request on one task in a rolling day. */
export const AGENT_TASK_RETRY_DAILY_CAP = 3;
export const AGENT_TASK_RETRY_ACTION = "issue.retry_requested_by_agent";
/**
* The board actor an agent presses Retry as: the active member whose
* tasks:retry grant names this agent. Only a grant a board user saved counts;
* a grant row written by an agent has no granting user. A grant saved with a
* scope does not count, since the Retry runs with the person's full task
* access and could reach outside that scope. The actor covers only
* the agent's company, so every Retry gate the person meets applies unchanged.
*/
export async function agentTaskRetryActor(db: Db, agent: { companyId: string; agentId: string; runId?: string }) {
const [grantor] = await db.select({ userId: companyMemberships.principalId, membershipRole: companyMemberships.membershipRole })
.from(principalPermissionGrants)
.innerJoin(companyMemberships, and(eq(companyMemberships.companyId, principalPermissionGrants.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, principalPermissionGrants.grantedByUserId),
eq(companyMemberships.status, "active")))
.where(and(
eq(principalPermissionGrants.companyId, agent.companyId),
eq(principalPermissionGrants.principalType, "agent"),
eq(principalPermissionGrants.principalId, agent.agentId),
eq(principalPermissionGrants.permissionKey, "tasks:retry"),
sql`coalesce(${principalPermissionGrants.scope}, '{}'::jsonb) = '{}'::jsonb`))
.limit(1);
if (!grantor) return null;
return {
type: "board", userId: grantor.userId, companyIds: [agent.companyId], isInstanceAdmin: false,
memberships: [{ companyId: agent.companyId, membershipRole: grantor.membershipRole, status: "active" }],
source: "board_key", runId: agent.runId,
} satisfies Express.Request["actor"];
}
/** Whether the run id the agent sent names one of its own runs in its company. */
export async function agentOwnsRun(db: Db, input: { companyId: string; agentId: string; runId: string }) {
if (!isUuidLike(input.runId)) return false;
const [run] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId)));
return Boolean(run);
}
/**
* Count an agent's Retry toward its daily cap on the task. The activity row
* names the agent and the grantor, and is written before the Retry so refused
* and failed attempts count too. A replay of an idempotency key that already
* has a saved Retry receipt for this task and grantor, or was already counted
* for this agent within the current 24-hour window, counts once; an old
* unsaved attempt from outside the window cannot bypass today's cap.
*/
export async function recordAgentTaskRetry(db: Db, input: {
companyId: string; issueId: string; agentId: string; runId: string; grantedByUserId: string; idempotencyKey: string;
}) {
const publications: ActivityPublication[] = [];
await db.transaction(async tx => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${`agent-task-retry:${input.issueId}`}))`);
const [savedReceipt] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, input.companyId),
eq(agentWakeupRequests.idempotencyKey, `task-retry:${input.idempotencyKey}`),
eq(agentWakeupRequests.requestedByActorId, input.grantedByUserId),
sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`)).limit(1);
if (savedReceipt) return;
const [recentReplay] = await tx.select({ id: activityLog.id }).from(activityLog).where(and(
eq(activityLog.companyId, input.companyId), eq(activityLog.entityType, "issue"),
eq(activityLog.entityId, input.issueId), eq(activityLog.action, AGENT_TASK_RETRY_ACTION),
eq(activityLog.actorId, input.agentId), gt(activityLog.createdAt, sql`now() - interval '1 day'`),
sql`${activityLog.details}->>'idempotencyKey' = ${input.idempotencyKey}`)).limit(1);
if (recentReplay) return;
const [{ value: recent }] = await tx.select({ value: count() }).from(activityLog).where(and(
eq(activityLog.companyId, input.companyId), eq(activityLog.entityType, "issue"),
eq(activityLog.entityId, input.issueId), eq(activityLog.action, AGENT_TASK_RETRY_ACTION),
eq(activityLog.actorId, input.agentId), gt(activityLog.createdAt, sql`now() - interval '1 day'`)));
if (recent >= AGENT_TASK_RETRY_DAILY_CAP)
throw new HttpError(429, `An agent can request at most ${AGENT_TASK_RETRY_DAILY_CAP} Retries on a task per day`,
{ code: "agent_task_retry_cap_reached" });
await logActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "agent", actorId: input.agentId,
agentId: input.agentId, runId: input.runId, action: AGENT_TASK_RETRY_ACTION, entityType: "issue",
entityId: input.issueId, details: { grantedByUserId: input.grantedByUserId, idempotencyKey: input.idempotencyKey } },
publications);
});
for (const publication of publications) publishActivity(publication);
}