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>
This commit is contained in:
Dottaandlucktastic authored and GitHub committed 2026-11-25 22:06:37 +00:00
1 parent e18fe61c8f
commit a74b4f8196
9 files changed
+487 -6

No files matched your search

+3 -1
View File
@@ -19,7 +19,9 @@ This document describes the server defaults for an ordinary, standard trust agen
## Not granted by default
These permission keys have no blanket grant for new standard agents: `agents:create` (the flag above is separate), `environments:manage`, `tools:admin`, `users:invite`, `users:manage_permissions`, and `joins:approve`. Existing agents keep their current permissions. The defaults above apply when a new standard agent is created or a pending new hire is activated. Some actions have separate bounded paths; the absence of a grant row does not describe every route decision.
These permission keys have no blanket grant for new standard agents: `agents:create` (the flag above is separate), `environments:manage`, `tools:admin`, `users:invite`, `users:manage_permissions`, `tasks:retry`, and `joins:approve`. Existing agents keep their current permissions. The defaults above apply when a new standard agent is created or a pending new hire is activated. Some actions have separate bounded paths; the absence of a grant row does not describe every route decision.
`tasks:retry` lets one agent press a task's Retry (`POST /api/issues/{id}/retry`) for the board user who granted it. Only a grant saved by a board user without a scope counts. The agent's own key scope, trust boundary and company policy still apply. The Retry runs with that person's authority and gates, so the agent can press it only where the person could. Chat tasks stay with their conversation owner. Each agent can request at most 3 Retries per task in a rolling day, and each request is logged as `issue.retry_requested_by_agent` with the agent and the granting user.
The new direct grants do not grant company administration, user permission management, blanket tool administration, or cross-company access. The responsible user's permissions, route checks, and the normal approval gates still apply.
+9 -1
View File
@@ -208,7 +208,7 @@ POST /api/issues/{issueId}/release
Releases your ownership of the task.
## Retry a Stopped Task (Board)
## Retry a Stopped Task (Board, or an Agent with a Retry Grant)
```
POST /api/issues/{issueId}/retry
@@ -226,6 +226,14 @@ Saves a Retry request for the task's latest stopped run. The same `idempotencyKe
Every answer includes `presentation`, the task's current interruption state.
An agent can call this endpoint only when a board user granted it `tasks:retry` without a scope. A grant that an agent saved, or a grant with a scope, does not count. The agent's call must:
- come from one of the agent's own runs in the company (`X-Paperclip-Run-Id` for an agent API key). Another run gives `403`.
- use an unscoped key. A skill-test or task-bridge key gives `403`.
- be on a task that the agent itself can read and that its own trust limits and company policy let it change. Only the rule about the task's assignee does not apply.
The Retry then runs as the user who granted it, with that user's access and Retry checks. Chat tasks give `403`. Each agent can save at most 3 Retry requests on one task in a rolling day. A replay of the same `idempotencyKey` counts once. The fourth request gives `429` with `details.code: "agent_task_retry_cap_reached"`. Each request is logged as `issue.retry_requested_by_agent`, with the agent, its run and the granting user.
## Check Now
```
+1
View File
@@ -1205,6 +1205,7 @@ export const PERMISSION_KEYS = [
"tasks:assign",
"tasks:assign_scope",
"tasks:manage_active_checkouts",
"tasks:retry",
"joins:approve",
] as const;
export type PermissionKey = (typeof PERMISSION_KEYS)[number];
@@ -172,6 +172,7 @@ const mockObserveCrossIssueInfluence = vi.hoisted(() => vi.fn(async () => null))
const mockRetryWorkspaceExport = vi.hoisted(() => vi.fn());
const mockRequestWorkspaceRecovery = vi.hoisted(() => vi.fn());
const mockRequestTaskRetry = vi.hoisted(() => vi.fn());
const mockAgentTaskRetryActor = vi.hoisted(() => vi.fn());
const mockOnboardingFirstTaskDependenciesAllowed = vi.hoisted(() => vi.fn(async () => undefined));
const mockGetExperimental = vi.hoisted(() => vi.fn());
const mockResumeWorkspaceFinalization = vi.hoisted(() => vi.fn());
@@ -185,6 +186,8 @@ function registerRouteMocks() {
}) };
});
vi.doMock("../services/task-retry.js", () => ({ requestTaskRetry: mockRequestTaskRetry }));
vi.doMock("../services/agent-task-retry.js", () => ({ agentOwnsRun: async () => true,
agentTaskRetryActor: mockAgentTaskRetryActor, recordAgentTaskRetry: async () => undefined }));
vi.doMock("../services/onboarding-first-task-admission.js", async () => ({
...await vi.importActual<typeof import("../services/onboarding-first-task-admission.js")>("../services/onboarding-first-task-admission.js"),
assertOnboardingFirstTaskDependenciesAllowed: mockOnboardingFirstTaskDependenciesAllowed,
@@ -542,6 +545,7 @@ describe("agent issue mutation checkout ownership", () => {
mockChatRunRetries.prepareFailedChatRunRetry.mockReset();
mockChatRunRetries.processFailedChatRunRetry.mockReset();
mockRequestTaskRetry.mockReset().mockResolvedValue({ requestId: recoveryActionId, accepted: true, stale: false });
mockAgentTaskRetryActor.mockReset().mockResolvedValue(null);
mockGetExperimental.mockReset().mockResolvedValue({ enableAgentChat: true });
mockAccessService.canUser.mockReset();
mockAccessService.decide.mockReset();
@@ -918,7 +922,7 @@ describe("agent issue mutation checkout ownership", () => {
it("admits ordinary Retry only for a board actor with task mutation permission", async () => {
const body = { idempotencyKey: recoveryActionId, observedRunId: ownerRunId };
const deniedAgent = await request(createApp(peerActor())).post(`/api/issues/${issueId}/retry`).send(body);
expect(deniedAgent.status).toBe(403);
expect(deniedAgent.status, JSON.stringify(deniedAgent.body)).toBe(403);
expect(mockRequestTaskRetry).not.toHaveBeenCalled();
mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({
allowed: input.action !== "issue:mutate", action: input.action, reason: "test_gate", explanation: "Task is read-only.",
@@ -934,6 +938,21 @@ describe("agent issue mutation checkout ownership", () => {
}));
});
it("keeps a granted agent's own write boundary on Retry", async () => {
mockAgentTaskRetryActor.mockResolvedValue({ ...boardActor(), source: "board_key",
memberships: [{ companyId, membershipRole: "owner", status: "active" }] });
mockAccessService.decide.mockImplementation(async (input: { action: string; actor: { type: string } }) =>
input.actor.type === "agent" && input.action === "issue:mutate"
? { allowed: false, action: input.action, reason: "deny_low_trust_boundary", explanation: "Issue is outside this low-trust boundary." }
: { allowed: true, action: input.action, reason: "allow_test", explanation: "Allowed." });
const body = { idempotencyKey: recoveryActionId, observedRunId: ownerRunId };
const denied = await request(createApp(peerActor())).post(`/api/issues/${issueId}/retry`).send(body);
expect(denied.status, JSON.stringify(denied.body)).toBe(403);
expect(mockRequestTaskRetry).not.toHaveBeenCalled();
});
it("rejects client-selected workspace strategy and certifications on ordinary Retry", async () => {
const response = await request(createApp(boardActor())).post(`/api/issues/${issueId}/retry`).send({
idempotencyKey: recoveryActionId, observedRunId: ownerRunId,
@@ -17,6 +17,7 @@ import {
activityLog,
agents,
agentWakeupRequests,
authUsers,
companies,
companyMemberships,
createDb,
@@ -28,11 +29,14 @@ import {
issueRelations,
issueTreeHolds,
issues,
principalPermissionGrants,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/index.js";
import { issueRoutes } from "../routes/issues.js";
import { runningProcesses } from "../adapters/index.js";
@@ -75,8 +79,10 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(principalPermissionGrants);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(authUsers);
await db.delete(companies);
});
@@ -114,6 +120,7 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {
agentId,
companyId,
runId: randomUUID(),
keyScope: { kind: "standard" },
source: "agent_jwt",
};
}
@@ -994,6 +1001,327 @@ describeEmbeddedPostgres("issue scheduled retry routes", () => {
});
});
describe("agent Retry with a board user's tasks:retry grant", () => {
async function grant(f: { companyId: string; agentId: string }, grantedByUserId: string | null,
scope: Record<string, unknown> | null = null) {
await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "agent",
principalId: f.agentId, permissionKey: "tasks:retry", grantedByUserId, scope });
}
function retry(f: { companyId: string; agentId: string; issueId: string; sourceRunId: string; retryRunId: string },
opts: { runId?: string; idempotencyKey?: string; actor?: Partial<Express.Request["actor"]> } = {}) {
return request(createApp({ ...agentActor(f.companyId, f.agentId), runId: opts.runId ?? f.sourceRunId, ...opts.actor } as Express.Request["actor"]))
.post(`/api/issues/${f.issueId}/retry`)
.send({ idempotencyKey: opts.idempotencyKey ?? randomUUID(), observedRunId: f.retryRunId });
}
async function retryRunStatus(f: { retryRunId: string }) {
return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId)).then(rows => rows[0]!.status);
}
it("refuses an agent without the grant", async () => {
const f = await seedIssueWithRetry();
const res = await retry(f);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("refuses a grant that no board user saved", async () => {
const f = await seedIssueWithRetry();
await grant(f, null);
const res = await retry(f);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("presses Retry as the granting person and logs the agent and the person", async () => {
const f = await seedIssueWithRetry();
await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") })
.where(eq(heartbeatRuns.id, f.retryRunId));
await grant(f, "board-user");
const res = await retry(f);
expect(res.status, JSON.stringify(res.body)).toBe(202);
expect(res.body).toMatchObject({ accepted: true, scheduledRetry: { outcome: "promoted" } });
expect(await retryRunStatus(f)).toBe("queued");
const events = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId),
eq(activityLog.action, "issue.retry_requested_by_agent")));
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ actorType: "agent", actorId: f.agentId, agentId: f.agentId,
runId: f.sourceRunId, details: { grantedByUserId: "board-user" } });
});
it("admits a granted agent authenticated through actorMiddleware with normalized standard keyScope", async () => {
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "agent-task-retry-jwt-test-secret");
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default");
try {
const f = await seedIssueWithRetry();
const now = new Date("2026-05-06T18:00:00.000Z");
await db.insert(authUsers).values({
id: "board-user",
name: "Board User",
email: "board-user@example.com",
emailVerified: true,
createdAt: now,
updatedAt: now,
});
await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") })
.where(eq(heartbeatRuns.id, f.retryRunId));
await grant(f, "board-user");
const token = createLocalAgentJwt(f.agentId, f.companyId, "codex_local", f.sourceRunId, "board-user");
expect(token).not.toBeNull();
const app = express();
app.use(express.json());
app.use(actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null }));
app.use("/api", issueRoutes(db, {} as any));
app.use(errorHandler);
const res = await request(app)
.post(`/api/issues/${f.issueId}/retry`)
.set("Authorization", `Bearer ${token!}`)
.send({ idempotencyKey: randomUUID(), observedRunId: f.retryRunId });
expect(res.status, JSON.stringify(res.body)).toBe(202);
expect(res.body).toMatchObject({ accepted: true, scheduledRetry: { outcome: "promoted" } });
expect(await retryRunStatus(f)).toBe("queued");
} finally {
vi.unstubAllEnvs();
}
});
it("enforces the agent's responsible-user write ceiling when acting on behalf of a viewer", async () => {
const f = await seedIssueWithRetry();
const now = new Date("2026-05-06T18:00:00.000Z");
await db.insert(authUsers).values({
id: "viewer-user",
name: "Viewer User",
email: "viewer-user@example.com",
emailVerified: true,
createdAt: now,
updatedAt: now,
});
await db.insert(companyMemberships).values({
companyId: f.companyId,
principalType: "user",
principalId: "viewer-user",
status: "active",
membershipRole: "viewer",
});
await grant(f, "board-user");
const res = await retry(f, {
actor: {
onBehalfOfUserId: "viewer-user",
onBehalfOfMemberships: [{ companyId: f.companyId, membershipRole: "viewer", status: "active" }],
},
});
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body).toMatchObject({ details: { code: "RESPONSIBLE_USER_UNAUTHORIZED" } });
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("preserves pause gates when a granted agent presses Retry on a paused assignee", async () => {
const f = await seedIssueWithRetry({ agentStatus: "paused" });
await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") })
.where(eq(heartbeatRuns.id, f.retryRunId));
await grant(f, "board-user");
const res = await retry(f);
expect(res.status, JSON.stringify(res.body)).toBe(202);
expect(res.body).toMatchObject({
accepted: true,
scheduledRetry: { outcome: "gate_suppressed" },
});
const [run] = await db.select({ status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode })
.from(heartbeatRuns).where(eq(heartbeatRuns.id, f.retryRunId));
expect(run).toEqual({ status: "cancelled", errorCode: "agent_not_invokable" });
});
it("applies the granting person's gates", async () => {
const f = await seedIssueWithRetry();
await db.update(issues).set({ visibility: "private", createdByUserId: "task-owner", responsibleUserId: "task-owner" })
.where(eq(issues.id, f.issueId));
await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: "other-member",
status: "active", membershipRole: "member" });
await grant(f, "other-member");
const res = await retry(f);
expect([403, 404], JSON.stringify(res.body)).toContain(res.status);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("fails closed when the grant is revoked or the granting member is no longer active", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user");
await db.update(companyMemberships).set({ status: "suspended" }).where(and(
eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "board-user")));
const suspendedRes = await retry(f);
expect(suspendedRes.status, JSON.stringify(suspendedRes.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
await db.update(companyMemberships).set({ status: "active" }).where(and(
eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, "board-user")));
await db.delete(principalPermissionGrants).where(and(
eq(principalPermissionGrants.companyId, f.companyId),
eq(principalPermissionGrants.principalId, f.agentId),
eq(principalPermissionGrants.permissionKey, "tasks:retry")));
const revokedRes = await retry(f);
expect(revokedRes.status, JSON.stringify(revokedRes.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("fails closed with 404 for a cross-company task even with a grant in the agent's own company", async () => {
const f = await seedIssueWithRetry();
const other = await seedIssueWithRetry();
await grant(f, "board-user");
const res = await request(createApp({ ...agentActor(f.companyId, f.agentId), runId: f.sourceRunId }))
.post(`/api/issues/${other.issueId}/retry`)
.send({ idempotencyKey: randomUUID(), observedRunId: other.retryRunId });
expect(res.status, JSON.stringify(res.body)).toBe(404);
expect(await retryRunStatus(other)).toBe("scheduled_retry");
});
it("refuses chat tasks even when the agent holds a tasks:retry grant", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user");
await db.update(issues).set({
conversationAgentId: f.agentId,
conversationUserId: "board-user",
conversationState: "waiting",
}).where(eq(issues.id, f.issueId));
const res = await retry(f);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("caps an agent's Retries on one task per day", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user");
for (let i = 0; i < 3; i += 1) expect((await retry(f)).status).not.toBe(429);
const res = await retry(f);
expect(res.status, JSON.stringify(res.body)).toBe(429);
expect(res.body).toMatchObject({ details: { code: "agent_task_retry_cap_reached" } });
});
it("counts a replayed request once toward the cap", async () => {
const f = await seedIssueWithRetry();
await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") })
.where(eq(heartbeatRuns.id, f.retryRunId));
await grant(f, "board-user");
const idempotencyKey = randomUUID();
for (let i = 0; i < 4; i += 1) expect((await retry(f, { idempotencyKey })).status).toBe(202);
const events = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId),
eq(activityLog.action, "issue.retry_requested_by_agent")));
expect(events).toHaveLength(1);
});
it("does not let an old unsaved idempotency key from yesterday bypass today's daily cap", async () => {
const f = await seedIssueWithRetry();
await db.update(heartbeatRuns).set({ createdAt: new Date("2026-05-06T18:00:01.000Z") })
.where(eq(heartbeatRuns.id, f.retryRunId));
await grant(f, "board-user");
const oldUnsavedKey = randomUUID();
await db.insert(activityLog).values({
companyId: f.companyId,
actorType: "agent",
actorId: f.agentId,
agentId: f.agentId,
runId: f.sourceRunId,
action: "issue.retry_requested_by_agent",
entityType: "issue",
entityId: f.issueId,
details: { grantedByUserId: "board-user", idempotencyKey: oldUnsavedKey },
createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
});
for (let i = 0; i < 3; i += 1) expect((await retry(f)).status).not.toBe(429);
const res = await retry(f, { idempotencyKey: oldUnsavedKey });
expect(res.status, JSON.stringify(res.body)).toBe(429);
expect(res.body).toMatchObject({ details: { code: "agent_task_retry_cap_reached" } });
});
it("deduplicates overlapping calls with the same idempotencyKey within the current 24h window", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user");
const duplicateKey = randomUUID();
await db.insert(activityLog).values({
companyId: f.companyId,
actorType: "agent",
actorId: f.agentId,
agentId: f.agentId,
runId: f.sourceRunId,
action: "issue.retry_requested_by_agent",
entityType: "issue",
entityId: f.issueId,
details: { grantedByUserId: "board-user", idempotencyKey: duplicateKey },
});
for (let i = 0; i < 4; i += 1) expect((await retry(f, { idempotencyKey: duplicateKey })).status).not.toBe(429);
const events = await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId),
eq(activityLog.action, "issue.retry_requested_by_agent")));
expect(events).toHaveLength(1);
});
it("refuses a run id that is not the agent's own run", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user");
const res = await retry(f, { runId: randomUUID() });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("refuses a grant saved with a scope", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user", { projectIds: [randomUUID()] });
const res = await retry(f);
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("keeps a low-trust agent within its own task boundary", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user");
await db.update(agents).set({ permissions: { trustPreset: "low_trust_review", authorizationPolicy: {
trustBoundary: { mode: "low_trust_review", companyId: f.companyId, rootIssueId: randomUUID() } } } })
.where(eq(agents.id, f.agentId));
const res = await retry(f);
expect([403, 404], JSON.stringify(res.body)).toContain(res.status);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
it("keeps a scoped key within its own limits", async () => {
const f = await seedIssueWithRetry();
await grant(f, "board-user");
const res = await retry(f, { actor: { source: "agent_key", keyId: randomUUID(),
keyScope: { kind: "skill_test", issueId: randomUUID() } } as Partial<Express.Request["actor"]> });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(await retryRunStatus(f)).toBe("scheduled_retry");
});
});
it("requires board access for retry-now", async () => {
const { companyId, agentId, issueId } = await seedIssueWithRetry();
+35
View File
@@ -10103,11 +10103,46 @@ export function issueRoutes(
});
router.post("/issues/:id/retry", validate(taskRetrySchema), async (req, res) => {
// An agent holding a board user's tasks:retry grant presses Retry as that
// person, so the person's gates apply, within a per-task daily cap.
let agentRetry: { companyId: string; agentId: string; runId: string } | null = null;
if (req.actor.type === "agent" && req.actor.agentId && req.actor.companyId) {
const { agentOwnsRun, agentTaskRetryActor } = await import("../services/agent-task-retry.js");
const grantor = await agentTaskRetryActor(db, { companyId: req.actor.companyId, agentId: req.actor.agentId,
runId: req.actor.runId });
if (grantor) {
// The agent's own limits apply first: scoped keys never use the grant,
// the run must be the agent's, and the agent's own issue:read and
// issue:mutate checks (trust boundary, company policy, interaction
// rules, and responsible-user ceiling) must pass. The grant lifts only
// the board-only gate and task-assignee ownership rule.
if (req.actor.keyScope && req.actor.keyScope.kind !== "standard")
throw forbidden("Scoped credentials cannot use the Retry grant");
const runId = requireAgentRunId(req, res);
if (!runId) return;
if (!(await agentOwnsRun(db, { companyId: req.actor.companyId, agentId: req.actor.agentId, runId })))
throw forbidden("Run does not belong to this agent");
const own = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Issue not found");
if (!own || !(await assertIssueReadAllowed(req, res, own))) return;
const ownWrite = await decideIssueAccess(req, own, "issue:mutate");
if (!ownWrite.allowed)
throw forbidden(ownWrite.explanation, authorizationDeniedDetails(ownWrite));
agentRetry = { companyId: req.actor.companyId, agentId: req.actor.agentId, runId };
req.actor = grantor;
}
}
assertBoard(req);
const issue = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Issue not found");
if (!issue || !(await assertIssueReadAllowed(req, res, issue))) return;
if (agentRetry && issue.companyId !== agentRetry.companyId) throw notFound("Issue not found");
const decision = await decideIssueAccess(req, issue, "issue:mutate");
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
if (agentRetry) {
if (issue.conversationAgentId) throw forbidden("Only the conversation owner can retry a chat run");
const { recordAgentTaskRetry } = await import("../services/agent-task-retry.js");
await recordAgentTaskRetry(db, { issueId: issue.id, ...agentRetry, grantedByUserId: req.actor.userId!,
idempotencyKey: req.body.idempotencyKey });
}
if (issue.conversationAgentId) {
if (!req.actor.userId || req.actor.userId !== issue.conversationUserId)
throw forbidden("Only the conversation owner can retry a chat run");
+1 -2
View File
@@ -1517,7 +1517,6 @@ const BOARD_ONLY_OPERATIONS = new Set([
// Cancelling a question is board-only (routes/issues.ts rejects agent actors). Withdraw is not listed here: its
// route admits the card's creator agent and the task's assignee, so agents withdraw their own pending card there.
"POST /api/issues/{id}/interactions/{interactionId}/cancel",
"POST /api/issues/{id}/retry",
"GET /api/companies/{companyId}/prompt-injection-prevention",
"PUT /api/companies/{companyId}/prompt-injection-prevention",
"GET /api/companies/{companyId}/prompt-injection-prevention/models",
@@ -11957,7 +11956,7 @@ registerCurrentRoute({
tags: ["issues"],
summary: "Request one durable task retry from current input and preserved results",
body: taskRetrySchema,
responses: { 200: r.ok(), 202: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
responses: { 200: r.ok(), 202: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 429: r.tooManyRequests },
});
registerCurrentRoute({
+89
View File
@@ -0,0 +1,89 @@
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);
}
@@ -237,7 +237,7 @@
"packages/shared/src/connector-availability.ts": "7797798bc989b774e8b6e62748ad689f66ab4193",
"packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a",
"packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955",
"packages/shared/src/constants.ts": "3f1500b70505cd586f5430ad1acb1851bf053fb1",
"packages/shared/src/constants.ts": "6204293794b5ef24159e1f0e01f686b6847ee6c2",
"packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c",
"packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2",
"packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe",