fix(monitors): let low-trust reviewers schedule a self-wake on their own task (#22212)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents use the `set_task_monitor` tool to save a timed follow-up
check on their task
> - Agents that run with the `low_trust_review` preset (for example,
pull request reviewers) cannot save this check
> - The tool requires company-wide `runtime:manage` access, and the
preset denies that access
> - Thus a reviewer must wait for a different event before it can
continue its review
> - This pull request lets the assignee save or clear a self-wake
monitor on its own task, and keeps the company-wide restriction
> - The benefit is that reviewers can continue their own review on time,
with no new company-wide access

## Linked Issues or Issue Description

**What happened?**

A `low_trust_review` agent calls `set_task_monitor` on its own
in-progress task. The call fails with this error: "low_trust_review
agents cannot use company-wide or privileged runtime:manage APIs by
default." The tool is advertised to the agent, but the agent cannot use
it. The agent cannot schedule its own follow-up check.

**Expected behavior**

The assignee can schedule or clear a monitor that only wakes itself on
its own task inside its trust boundary. Monitors that create recovery
tasks or escalate to the board stay denied. Company-wide
`runtime:manage` stays denied.

**Steps to reproduce**

1. Assign an in-progress task to an agent.
2. Start a native run for that task with a `low_trust_review` execution
policy whose boundary root is the task.
3. Call `set_task_monitor` with a future `nextCheckAt` and notes.
4. See the 403 error with reason `deny_low_trust_boundary`.

**Paperclip version or commit**

`master` at 8282d386da.

## What Changed

- `assertCanManageIssueMonitor` accepts an optional own-task scope. With
this scope, a `deny_low_trust_boundary` result for `runtime:manage` does
not block the assignee when both the requested monitor and the stored
monitor are the assignee's own self-wake (`wake_owner` recovery,
scheduled by the assignee, not the provider-quota service) or are empty.
- The native `set_task_monitor` tool passes this scope only when the
agent, project and task policies alone resolve the same low-trust
boundary as the current run. A monitor wake starts a run from those
sources, not from the run snapshot. Thus the woken run keeps the same
low-trust limits. A low-trust boundary that only the run snapshot
carries is still denied.
- The tool still checks `issue:read` and `issue:mutate` on the target
first, and still requires an in-progress or in-review task assigned to
the calling agent.
- The `create_recovery_issue` and `escalate_to_board` recovery policies
still require `runtime:manage`. The assignee also cannot clear or
replace a board-scheduled, recovery, escalation or provider-quota
monitor.
- The HTTP issue routes do not change.
- `doc/LOW-TRUST-PRESETS.md` describes the new rule.

## Verification

- Test 1 failing before the fix: `pnpm vitest run
src/services/native-runtime/task-monitor.integration.test.ts -t
"low-trust reviewer"` (in `server/`). The new test failed: `promise
rejected "Error: low_trust_review agents cannot use company-wide or
privileged runtime:manage APIs by default."` from
`assertCanManageIssueMonitor`, with `{ status: 403, details: { reason:
'deny_low_trust_boundary' } }`.
- Test 2 failing before the trust fix: `pnpm vitest run
src/__tests__/issue-monitor-scheduler.test.ts -t "low-trust limits"`. A
run with a low-trust policy only in its snapshot could save a monitor
(`promise resolved ... instead of rejecting`). After the fix, that call
is denied. When the task carries the policy, the monitor is saved, the
real scheduler fires it, and the woken run resolves to
`low_trust_review` with the same boundary.
- Test 3 failing before the stored-monitor fix: the extended "low-trust
reviewer" test cleared a board `escalate_to_board` monitor (`promise
resolved ... instead of rejecting`). After the fix, clear and replace
are denied for board-scheduled, `escalate_to_board`,
`create_recovery_issue` and provider-quota monitors.
- Passing after: `task-monitor.integration.test.ts`,
`issue-monitor-scheduler.test.ts` and
`native-preserved-monitor-wait.test.ts` pass (100/100).
- `pnpm run typecheck` in `server/` passes.
- I did not run the full `pnpm verify`.

## Risks

- Low risk. The change applies only to the native tool, only to the
assignee, and only to the task-scoped `wake_owner` monitor. A monitor
wake goes only to the same agent on the same task, and that run resolves
the same low-trust boundary.
- The bypass depends on the `deny_low_trust_boundary` decision reason.
Other denials (for example, a viewer responsible user, a task bridge
key, or a skill-test token) still block the call.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in an agent harness.

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-18 15:19:11 -06:00
1 parent 8a295f944d
commit 84a529df4f
5 files changed
+111 -9

No files matched your search

+9
View File
@@ -147,6 +147,15 @@ runtime boundary:
- inline sensitive environment values such as API keys and tokens are rejected
- workspace runtime-service mutations are denied unless the boundary explicitly
grants the `runtime.manage` tool class
- company-wide `runtime:manage` stays denied, but the assignee may use
`set_task_monitor` to schedule or clear a self-wake on its own in-boundary
task; monitors that create recovery tasks or escalate to the board are denied
- that self-wake is allowed only when the agent, project and task policies
alone resolve the same low-trust boundary as the run, so the woken run keeps
the same limits; a boundary carried only by the run snapshot is denied
- the assignee cannot clear or replace a monitor it does not own: a
board-scheduled, recovery, escalation or provider-quota monitor still needs
`runtime:manage`
When the task's project has no configured workspace and no layer specifies a
workspace strategy, sandbox execution uses a private directory for that company
@@ -31,6 +31,7 @@ import { heartbeatService } from "../services/heartbeat.ts";
import { deliverReconciledExecutions } from "../services/execution-recovery-resolution.ts";
import { normalizeIssueExecutionPolicy, parseIssueExecutionState } from "../services/issue-execution-policy.ts";
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
import { resolveAndRetainRunTrustPreset } from "../services/run-trust-preset.js";
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
// These process fixtures do not consume skills. Keep the real scheduler,
@@ -406,6 +407,41 @@ describeEmbeddedPostgres("issue monitor scheduler", () => {
expect(wakes.filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1);
});
it("keeps low-trust limits on the run a reviewer's self-wake starts", async () => {
const { companyId, issueId, agentId } = await seedFixture();
const runId = randomUUID();
const policy = { trustPreset: "low_trust_review", authorizationPolicy: { trustPreset: "low_trust_review",
trustBoundary: { mode: "low_trust_review", companyId, rootIssueId: issueId } } };
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId,
runtimeMode: "native", status: "running", contextSnapshot: { issueId, executionPolicy: policy } });
await db.update(issues).set({ executionRunId: runId, executionPolicy: null, executionState: null,
monitorNextCheckAt: null, monitorNotes: null, monitorScheduledBy: null }).where(eq(issues.id, issueId));
const authority = new PaperclipRunnerToolAuthority(db, { companyId, issueId, agentId, runId });
const monitor = { nextCheckAt: new Date(Date.now() + 60_000).toISOString(), notes: "Check the review again." };
const call = (idempotencyKey: string) => authority.execute({
tool: "set_task_monitor", callId: randomUUID(), arguments: { idempotencyKey, monitor },
});
try {
await expect(call("run-only-trust")).rejects.toThrow(/runtime:manage/);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.monitorNextCheckAt).toBeNull();
await db.update(issues).set({ executionPolicy: policy }).where(eq(issues.id, issueId));
await expect(call("task-trust")).resolves.toMatchObject({ monitor: { status: "scheduled" } });
} finally {
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, issueId));
}
expect((await heartbeatService(db).tickTimers(new Date(Date.parse(monitor.nextCheckAt) + 1_000))).enqueued).toBe(1);
const [woken] = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)))
.filter(run => run.id !== runId);
expect(woken).toBeDefined();
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, woken!.id));
const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
const retained = await resolveAndRetainRunTrustPreset(db, { companyId, agentId, runId: woken!.id,
agent: { companyId, permissions: agent!.permissions }, issue: { companyId, executionPolicy: issue!.executionPolicy } });
expect(retained.trustPreset).toMatchObject({ kind: "low_trust_review", boundary: { rootIssueId: issueId } });
});
it.each(["replaced", "cleared", "reassigned", "completed"] as const)("fences a monitor %s after claim but before wake admission", async (change) => {
const { companyId, issueId, agentId } = await seedFixture();
const replacementAt = new Date("2026-04-11T13:30:00.000Z");
+21 -7
View File
@@ -28,32 +28,46 @@ export function applyActorMonitorScheduledBy(
);
}
type SelfWakeMonitor = { recoveryPolicy?: string | null; serviceName?: string | null; scheduledBy?: string | null };
function isSelfWakeMonitor(monitor: SelfWakeMonitor | null) {
return !monitor || ((monitor.recoveryPolicy ?? "wake_owner") === "wake_owner"
&& monitor.serviceName !== PROVIDER_QUOTA_MONITOR_SERVICE_NAME
&& (monitor.scheduledBy ?? "assignee") === "assignee");
}
export async function assertCanManageIssueMonitor(
accessSvc: Pick<ReturnType<typeof accessService>, "decide">,
req: { actor: AuthorizationActor },
companyId: string,
assigneeAgentId: string | null,
monitorChanged: boolean,
ownTask?: { monitor: SelfWakeMonitor | null; existing: SelfWakeMonitor | null },
) {
if (!monitorChanged) return;
if (req.actor.type === "board") return;
const isAssignee =
req.actor.type === "agent" &&
!!req.actor.agentId &&
req.actor.agentId === assigneeAgentId;
const runtimeDecision = await accessSvc.decide({
actor: req.actor,
action: "runtime:manage",
resource: { type: "company", companyId },
});
if (!runtimeDecision.allowed) {
const ownTaskSelfWake =
ownTask &&
isAssignee &&
runtimeDecision.reason === "deny_low_trust_boundary" &&
isSelfWakeMonitor(ownTask.monitor) &&
isSelfWakeMonitor(ownTask.existing);
if (!runtimeDecision.allowed && !ownTaskSelfWake) {
throw forbidden(
runtimeDecision.explanation,
authorizationDeniedDetails(runtimeDecision),
);
}
if (
req.actor.type === "agent" &&
req.actor.agentId &&
req.actor.agentId === assigneeAgentId
)
return;
if (isAssignee) return;
throw forbidden(
"Only the assignee agent or a board user can manage issue monitors",
);
@@ -2574,7 +2574,7 @@ export class PaperclipRunnerToolAuthority {
let replayed = false;
let replayStatus: string | null = null;
let replayMonitor: ReturnType<typeof summarizeIssueMonitor> | null = null;
const authorizeTarget = async (tx: Db, context: { run: typeof heartbeatRuns.$inferSelect }) => {
const authorizeTarget = async (tx: Db, context: { run: typeof heartbeatRuns.$inferSelect; actor: typeof agents.$inferSelect }) => {
// A second owned task may itself be writing another task: fail on lock
// contention instead of taking opposite issue/run locks and deadlocking.
const [target] = await tx.select().from(issues).where(and(
@@ -2590,7 +2590,17 @@ export class PaperclipRunnerToolAuthority {
} });
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
await assertCanManageIssueMonitor(access, { actor }, target.companyId, target.assigneeAgentId, true);
const project = target.projectId
? (await tx.select().from(projects).where(and(eq(projects.id, target.projectId), eq(projects.companyId, this.binding.companyId))))[0] ?? null
: null;
const taskSources = { companyId: this.binding.companyId, agent: context.actor, project, issue: target };
const taskTrust = resolveCoreTrustPreset(taskSources);
const runTrust = resolveCoreTrustPreset({ ...taskSources,
run: { companyId: this.binding.companyId, executionPolicy: context.run.contextSnapshot?.executionPolicy } });
const wakeKeepsTrust = taskTrust.kind === "low_trust_review" && runTrust.kind === "low_trust_review"
&& canonicalJson(taskTrust.boundary) === canonicalJson(runTrust.boundary);
await assertCanManageIssueMonitor(access, { actor }, target.companyId, target.assigneeAgentId, true,
wakeKeepsTrust ? { monitor: input.monitor, existing: normalizeIssueExecutionPolicy(target.executionPolicy)?.monitor ?? null } : undefined);
if (target.assigneeAgentId !== this.binding.agentId || target.assigneeUserId ||
!["in_progress", "in_review"].includes(target.status)) {
throw forbidden("Monitors require an in-progress or in-review task assigned to this agent");
@@ -115,6 +115,39 @@ describeEmbeddedPostgres("native task monitors", () => {
await expect(authority.execute({ tool: "set_task_monitor", callId: randomUUID(), arguments: { idempotencyKey: "review", monitor: value.monitor } })).rejects.toThrow("review run");
});
it("lets a low-trust reviewer schedule a self-wake on its own task without company runtime access", async () => {
const value = await fixture(), otherId = randomUUID();
const policy = { trustPreset: "low_trust_review", authorizationPolicy: { trustPreset: "low_trust_review",
trustBoundary: { mode: "low_trust_review", companyId: value.companyId, rootIssueId: value.issueId } } };
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: value.issueId, executionPolicy: policy } })
.where(eq(heartbeatRuns.id, value.runId));
await db.update(issues).set({ executionPolicy: policy }).where(eq(issues.id, value.issueId));
await db.insert(issues).values({ id: otherId, companyId: value.companyId,
title: "Owned task outside the review boundary", status: "in_progress", assigneeAgentId: value.agentId });
await expect(value.call({ idempotencyKey: "review-check", monitor: value.monitor }))
.resolves.toMatchObject({ taskId: value.issueId, monitor: { status: "scheduled" }, replayed: false });
expect((await value.read()).monitorNextCheckAt?.toISOString()).toBe(value.monitor.nextCheckAt);
for (const recoveryPolicy of ["create_recovery_issue", "escalate_to_board"]) {
await expect(value.call({ idempotencyKey: `review-${recoveryPolicy}`, monitor: { ...value.monitor, recoveryPolicy } }))
.rejects.toThrow(/runtime:manage/);
}
await expect(value.call({ taskId: otherId, idempotencyKey: "review-other", monitor: value.monitor })).rejects.toThrow();
expect((await db.select().from(issues).where(eq(issues.id, otherId)))[0]!.monitorNextCheckAt).toBeNull();
await expect(value.call({ idempotencyKey: "review-clear", monitor: null }))
.resolves.toMatchObject({ taskId: value.issueId, replayed: false });
expect((await value.read()).monitorNextCheckAt).toBeNull();
for (const existing of [{ scheduledBy: "board", recoveryPolicy: "escalate_to_board" },
{ scheduledBy: "assignee", recoveryPolicy: "create_recovery_issue" }, { scheduledBy: "board" },
{ scheduledBy: "assignee", serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME }]) {
await db.update(issues).set({ executionPolicy: { ...policy, monitor: { ...value.monitor, ...existing } },
monitorNextCheckAt: new Date(value.monitor.nextCheckAt) }).where(eq(issues.id, value.issueId));
for (const monitor of [null, value.monitor]) {
await expect(value.call({ idempotencyKey: `review-replace-${randomUUID()}`, monitor })).rejects.toThrow(/runtime:manage/);
}
expect((await value.read()).monitorNextCheckAt?.toISOString()).toBe(value.monitor.nextCheckAt);
}
});
it("rechecks the responsible user's permissions before mutation and replay", async () => {
const value = await fixture(), userId = randomUUID();
await db.insert(authUsers).values({ id: userId, name: "Owner", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });