mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents can schedule timed task monitors with `set_task_monitor` and end their turn with `yielded` and `continuation.kind: "monitor"` to check external work later > - Tasks can also have unresolved `blockedBy` dependencies while the agent still monitors independent active work such as CI or external checks > - Previously, `arbitrateNativeStatus` overrode every monitor wait on a task with unresolved blockers into `blocked` (`durable_dependency_blocker_bound`), and the heartbeat wake admission and queued-run claim paths rejected or cancelled `issue_monitor_due` wakes while blockers remained unresolved > - This pull request preserves authorized task monitor waits in `arbitrateNativeStatus` and admits server-verified `issue_monitor_due` wakes through wake admission, queued-run claim, and run-dispatch retry gates even when unresolved blockers exist > - The benefit is that authorized task monitors stay scheduled and fire on time without relaxing the dependency gate on `done`, `blocked`, unauthorized monitor claims, blocked tasks, or forged wakeups ## Linked Issues or Issue Description **What happened?** When an agent scheduled a task monitor with `set_task_monitor` on an `in_progress` task that also had unresolved `blockedBy` dependencies and finished with `reportedDisposition: "yielded"` and `continuation.kind: "monitor"`, `arbitrateNativeStatus` overrode the status to `blocked` (`durable_dependency_blocker_bound`) and stranded the monitor. Even if the task remained `in_progress`, `enqueueWakeup` and `claimQueuedRun` skipped or cancelled the due `issue_monitor_due` wake because `isDependencyReady` was `false`. **Expected behavior** An explicit, authorized task monitor (`monitorWaitAuthorized: true`, or already dispatched/superseded/preserved) stays in `scheduled_monitor_waiting` (releasing checkout) and wakes the assignee with `issue_monitor_due` when due, while `done`, `blocked`, `unfinishedResponseWait`, unauthorized monitor claims, blocked tasks, and forged `issue_monitor_due` wakes remain gated by unresolved `blockedBy` dependencies. **Steps to reproduce** 1. Create an `in_progress` task assigned to an agent and add an unresolved `blockedBy` dependency to it. 2. Schedule a task monitor on the task with `set_task_monitor` and finish the run with `reportedDisposition: "yielded"` and `continuation.kind: "monitor"`. 3. Observe `arbitrateNativeStatus` return `blocked` (`durable_dependency_blocker_bound`) instead of `scheduled_monitor_waiting`, and observe `tickIssueMonitors` skip the due monitor with `issue_dependencies_blocked`. **Paperclip version or commit** `8403e1c4ce` (`master`) **Deployment mode** Local dev (pnpm dev) ## What Changed - Updated `arbitrateNativeStatus` in `server/src/services/native-runtime/status-arbiter.ts` to exempt authorized `yielded` monitor continuations (`monitorWaitAuthorized`, `monitorWaitDispatched`, `monitorWaitSuperseded`, `monitorWaitPreserved`) from the `durable_dependency_blocker_bound` override while keeping `done`, `blocked`, `unfinishedResponseWait`, and unauthorized monitor claims gated. - Added `verifyIssueMonitorWake` in `server/src/services/issue-monitors.ts` to verify `issue_monitor_due` wakes against durable server state (claimed non-quota monitor on an `in_progress`/`in_review` task at enqueue time; admitted non-skipped `agentWakeupRequests` row at claim and retry-gate time). - Extended `allowsDependencyBlockedWake` in `server/src/modules/run-dispatch/domain/wake-context.ts` and wired `verifyIssueMonitorWake` into `enqueueWakeup` and `claimQueuedRun` (`server/src/services/heartbeat/queue.ts`) plus `loadGateFacts` and `loadStalenessFacts` (`server/src/modules/run-dispatch/adapters/postgres.ts`). - Added unit and integration regression tests in `server/src/services/native-runtime/status-arbiter.test.ts` and `server/src/__tests__/issue-monitor-scheduler.test.ts` covering authorized monitors with blockers, unauthorized monitor claims, `done` with blockers, due monitor execution with blockers, and forged `issue_monitor_due` wakeups. ## Verification - `pnpm --filter @paperclipai/server typecheck` (passed) - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/status-arbiter.test.ts src/__tests__/issue-monitor-scheduler.test.ts src/services/native-runtime/task-monitor.integration.test.ts` (84 passed) - `pnpm --filter @paperclipai/server exec vitest run src/modules/run-dispatch/domain/wake-context.test.ts src/services/heartbeat/scheduling.test.ts` (81 passed) - Verified red-green behavior on the new regression tests before and after applying the fix. ## Risks - Low risk. The dependency-blocker bypass is scoped strictly to server-verified non-quota task monitors on `in_progress` or `in_review` tasks (`scheduledIssueMonitorWait` + claimed `monitorWakeRequestedAt` at enqueue, and admitted `agentWakeupRequests` row at claim/retry). Blocked tasks, provider quota monitors, unauthorized monitor claims, forged `issue_monitor_due` wakeups, and `done`/`blocked` transitions retain full dependency-blocker enforcement. ## Model Used - Google Gemini (Antigravity agentic coding assistant, tool use and extended reasoning) ## 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
250 lines
10 KiB
TypeScript
250 lines
10 KiB
TypeScript
import { issueExecutionMonitorPolicySchema, PROVIDER_QUOTA_MONITOR_SERVICE_NAME } from "@paperclipai/shared";
|
|
import { agentWakeupRequests, issues, type Db } from "@paperclipai/db";
|
|
import { and, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
|
|
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: Pick<typeof issues.$inferSelect, "assigneeAgentId" | "assigneeUserId" | "status" | "monitorNextCheckAt" | "executionPolicy">,
|
|
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;
|
|
}
|
|
|
|
export async function verifyIssueMonitorWake(
|
|
db: Pick<Db, "select">,
|
|
input: {
|
|
companyId: string;
|
|
issueId: string;
|
|
agentId: string;
|
|
contextSnapshot: Record<string, unknown> | null | undefined;
|
|
wakeupRequestId?: string | null;
|
|
issue?: Pick<
|
|
typeof issues.$inferSelect,
|
|
"assigneeAgentId" | "assigneeUserId" | "status" | "monitorNextCheckAt" | "monitorWakeRequestedAt"
|
|
> & { executionPolicy?: typeof issues.$inferSelect["executionPolicy"] } | null;
|
|
},
|
|
): Promise<boolean> {
|
|
const context = input.contextSnapshot;
|
|
if (!context || context.source !== "issue.monitor") return false;
|
|
const nextCheckAt = typeof context.nextCheckAt === "string" && context.nextCheckAt.length > 0 ? context.nextCheckAt : null;
|
|
if (!nextCheckAt) return false;
|
|
const serverRetry = typeof context.retryOfRunId === "string" && context.retryOfRunId.length > 0;
|
|
if (context.wakeReason !== "issue_monitor_due" && !serverRetry) return false;
|
|
if (input.issue) {
|
|
if (!input.issue.monitorWakeRequestedAt || !input.issue.monitorNextCheckAt) return false;
|
|
const executionPolicy =
|
|
input.issue.executionPolicy !== undefined
|
|
? input.issue.executionPolicy
|
|
: (await db
|
|
.select({ executionPolicy: issues.executionPolicy })
|
|
.from(issues)
|
|
.where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId)))
|
|
.limit(1))[0]?.executionPolicy ?? null;
|
|
return scheduledIssueMonitorWait({ ...input.issue, executionPolicy }, input.agentId) === nextCheckAt;
|
|
}
|
|
const [wake] = await db
|
|
.select({ id: agentWakeupRequests.id })
|
|
.from(agentWakeupRequests)
|
|
.innerJoin(issues, and(
|
|
eq(issues.id, input.issueId),
|
|
eq(issues.companyId, input.companyId),
|
|
eq(issues.assigneeAgentId, input.agentId),
|
|
isNull(issues.assigneeUserId),
|
|
inArray(issues.status, ["in_progress", "in_review"]),
|
|
))
|
|
.where(and(
|
|
eq(agentWakeupRequests.companyId, input.companyId),
|
|
eq(agentWakeupRequests.agentId, input.agentId),
|
|
eq(agentWakeupRequests.reason, "issue_monitor_due"),
|
|
notInArray(agentWakeupRequests.status, ["skipped", "cancelled"]),
|
|
eq(agentWakeupRequests.idempotencyKey, `issue-monitor:${input.issueId}:${nextCheckAt}`),
|
|
sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`,
|
|
sql`${agentWakeupRequests.payload}->>'nextCheckAt' = ${nextCheckAt}`,
|
|
!serverRetry && input.wakeupRequestId ? eq(agentWakeupRequests.id, input.wakeupRequestId) : undefined,
|
|
))
|
|
.limit(1);
|
|
return Boolean(wake);
|
|
}
|