mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 07:42:38 +01:00
## 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>
193 lines
7.7 KiB
TypeScript
193 lines
7.7 KiB
TypeScript
import { issueExecutionMonitorPolicySchema, PROVIDER_QUOTA_MONITOR_SERVICE_NAME } from "@paperclipai/shared";
|
|
import type { issues } from "@paperclipai/db";
|
|
import { z } from "zod";
|
|
import { forbidden, unprocessable } from "../errors.js";
|
|
import type { accessService } from "./access.js";
|
|
import { authorizationDeniedDetails, type AuthorizationActor } from "./authorization.js";
|
|
import { applyIssueMonitorPolicyTransition, normalizeIssueExecutionPolicy, parseIssueExecutionState, redactIssueMonitorExternalRef, setIssueExecutionPolicyMonitorScheduledBy } from "./issue-execution-policy.js";
|
|
|
|
type NormalizedExecutionPolicy = ReturnType<typeof normalizeIssueExecutionPolicy>;
|
|
|
|
export function monitorPoliciesEqual(
|
|
left: NormalizedExecutionPolicy | null,
|
|
right: NormalizedExecutionPolicy | null,
|
|
) {
|
|
return (
|
|
JSON.stringify(left?.monitor ?? null) ===
|
|
JSON.stringify(right?.monitor ?? null)
|
|
);
|
|
}
|
|
|
|
export function applyActorMonitorScheduledBy(
|
|
policy: NormalizedExecutionPolicy | null,
|
|
actorType: "agent" | "user",
|
|
) {
|
|
return setIssueExecutionPolicyMonitorScheduledBy(
|
|
policy,
|
|
actorType === "user" ? "board" : "assignee",
|
|
);
|
|
}
|
|
|
|
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 },
|
|
});
|
|
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 (isAssignee) return;
|
|
throw forbidden(
|
|
"Only the assignee agent or a board user can manage issue monitors",
|
|
);
|
|
}
|
|
|
|
export function summarizeIssueMonitor(
|
|
issue: {
|
|
monitorNextCheckAt?: Date | null;
|
|
monitorLastTriggeredAt?: Date | null;
|
|
monitorAttemptCount?: number | null;
|
|
monitorNotes?: string | null;
|
|
monitorScheduledBy?: string | null;
|
|
executionState?: unknown;
|
|
},
|
|
policy: NormalizedExecutionPolicy | null,
|
|
) {
|
|
const state = parseIssueExecutionState(issue.executionState);
|
|
return {
|
|
nextCheckAt:
|
|
issue.monitorNextCheckAt?.toISOString() ??
|
|
policy?.monitor?.nextCheckAt ??
|
|
null,
|
|
lastTriggeredAt:
|
|
issue.monitorLastTriggeredAt?.toISOString() ??
|
|
state?.monitor?.lastTriggeredAt ??
|
|
null,
|
|
attemptCount:
|
|
issue.monitorAttemptCount ?? state?.monitor?.attemptCount ?? 0,
|
|
notes:
|
|
policy?.monitor?.notes ??
|
|
issue.monitorNotes ??
|
|
state?.monitor?.notes ??
|
|
null,
|
|
scheduledBy:
|
|
issue.monitorScheduledBy ??
|
|
policy?.monitor?.scheduledBy ??
|
|
state?.monitor?.scheduledBy ??
|
|
null,
|
|
kind: policy?.monitor?.kind ?? state?.monitor?.kind ?? null,
|
|
serviceName:
|
|
policy?.monitor?.serviceName ?? state?.monitor?.serviceName ?? null,
|
|
externalRef: redactIssueMonitorExternalRef(
|
|
policy?.monitor?.externalRef ?? state?.monitor?.externalRef ?? null,
|
|
),
|
|
timeoutAt: policy?.monitor?.timeoutAt ?? state?.monitor?.timeoutAt ?? null,
|
|
maxAttempts:
|
|
policy?.monitor?.maxAttempts ?? state?.monitor?.maxAttempts ?? null,
|
|
recoveryPolicy:
|
|
policy?.monitor?.recoveryPolicy ?? state?.monitor?.recoveryPolicy ?? null,
|
|
status: state?.monitor?.status ?? (policy?.monitor ? "scheduled" : null),
|
|
clearReason: state?.monitor?.clearReason ?? null,
|
|
};
|
|
}
|
|
|
|
export const setTaskMonitorSchema = z.object({
|
|
taskId: z.string().uuid().optional(),
|
|
idempotencyKey: z.string().trim().min(1).max(240),
|
|
monitor: issueExecutionMonitorPolicySchema.omit({ scheduledBy: true }).extend({
|
|
notes: z.string().trim().min(1).max(500),
|
|
}).strict().refine(monitor => monitor.serviceName !== PROVIDER_QUOTA_MONITOR_SERVICE_NAME, {
|
|
message: "This serviceName is reserved for server-owned quota recovery; use a different service name for an ordinary task check",
|
|
path: ["serviceName"],
|
|
}).nullable(),
|
|
}).strict();
|
|
|
|
/** Caller holds the issue lock; merge only monitor state, never review policy. */
|
|
export function prepareIssueMonitorUpdate(
|
|
issue: typeof issues.$inferSelect,
|
|
monitor: z.infer<typeof setTaskMonitorSchema>["monitor"],
|
|
actor: AuthorizationActor,
|
|
now = new Date(),
|
|
) {
|
|
if (monitor && Date.parse(monitor.nextCheckAt) <= now.getTime()) {
|
|
throw unprocessable("Monitor nextCheckAt must be in the future");
|
|
}
|
|
if (monitor?.timeoutAt && Date.parse(monitor.timeoutAt) <= Date.parse(monitor.nextCheckAt)) {
|
|
throw unprocessable("Monitor timeoutAt must be later than nextCheckAt");
|
|
}
|
|
const previousPolicy = normalizeIssueExecutionPolicy(issue.executionPolicy);
|
|
const policy = applyActorMonitorScheduledBy(normalizeIssueExecutionPolicy({
|
|
...previousPolicy, monitor,
|
|
}), actor.type === "board" ? "user" : "agent");
|
|
const transition = applyIssueMonitorPolicyTransition({
|
|
issue, policy, previousPolicy, requestedAssigneePatch: {},
|
|
actor: { agentId: actor.agentId ?? null, userId: actor.userId ?? null },
|
|
monitorExplicitlyUpdated: true,
|
|
});
|
|
// Normalization supplies monitor defaults, but must not rewrite unrelated
|
|
// review/authorization settings (including forward-compatible policy fields).
|
|
const storedPolicy = { ...(issue.executionPolicy ?? {}) };
|
|
if (policy?.monitor) storedPolicy.monitor = policy.monitor;
|
|
else delete storedPolicy.monitor;
|
|
return { ...transition.patch, executionPolicy: Object.keys(storedPolicy).length ? storedPolicy : null } as Partial<typeof issues.$inferInsert>;
|
|
}
|
|
|
|
/** A saved result can settle into this schedule even if its limits elapsed
|
|
* during workspace recovery. The scheduler owns applying those limits next. */
|
|
export function scheduledIssueMonitorWait(
|
|
issue: typeof issues.$inferSelect,
|
|
agentId: string,
|
|
): string | null {
|
|
if (issue.assigneeAgentId !== agentId || issue.assigneeUserId ||
|
|
!["in_progress", "in_review"].includes(issue.status) || !issue.monitorNextCheckAt) return null;
|
|
const monitor = normalizeIssueExecutionPolicy(issue.executionPolicy)?.monitor;
|
|
if (!monitor || monitor.serviceName === PROVIDER_QUOTA_MONITOR_SERVICE_NAME ||
|
|
Date.parse(monitor.nextCheckAt) !== issue.monitorNextCheckAt.getTime()) return null;
|
|
return issue.monitorNextCheckAt.toISOString();
|
|
}
|
|
|
|
/** New provider results still need an unexpired, unexhausted monitor. */
|
|
export function eligibleIssueMonitorWait(
|
|
issue: typeof issues.$inferSelect,
|
|
agentId: string,
|
|
now = new Date(),
|
|
): string | null {
|
|
const nextCheckAt = scheduledIssueMonitorWait(issue, agentId);
|
|
if (!nextCheckAt) return null;
|
|
const monitor = normalizeIssueExecutionPolicy(issue.executionPolicy)!.monitor!;
|
|
if ((monitor.timeoutAt && Date.parse(monitor.timeoutAt) <= now.getTime()) ||
|
|
(monitor.maxAttempts != null && issue.monitorAttemptCount >= monitor.maxAttempts)) return null;
|
|
return nextCheckAt;
|
|
}
|