mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
fix(runner): restore task monitors and durable timed waits (#15446)
## Thinking Path > - Paperclip manages AI agents and their task execution. > - Agents need a durable way to return to work after a delayed check. > - The issue monitor scheduler already provides a one-shot wake for an assignee. > - Native runners reject generic execution-policy writes and had no bound monitor tool. > - Scheduling alone is insufficient because native completion also needs to accept a timed wait. > - This pull request adds an authorized monitor tool and connects it to completion and the existing scheduler. > - An agent can now schedule its next check, end the run, and resume on the same task. ## Linked Issues or Issue Description **What happened?** A native runner could not set its own task monitor. `call_api` correctly rejected execution-policy writes, while `schedule_wake` had no production binding. `paperclip_finish` also rejected monitor waits. **Expected behavior** A standard native run can set a one-shot monitor on its current task or another accessible task assigned to the same agent. After a confirmed schedule on the current task, it can yield. The scheduler later delivers `issue_monitor_due`. **Steps to reproduce** 1. Start a standard native task. 2. Ask the agent to check the task again later and end its current run. 3. Inspect available tools and try the generic issue execution-policy update. 4. Observe the missing native tool and the lifecycle-write denial. Related PRs: #14680 concerns monitor notes in the shared wake prompt. #11919 changes attempt-limit scope. This PR adds native scheduling and completion authority and retains the existing cumulative attempt bounds. It does not depend on either PR. ## What Changed - Add provider-neutral `set_task_monitor` with a default current-task target, future timestamp, required notes, existing bounds, and explicit clearing. - Check company, task visibility, ownership, runtime permissions, work mode, and active-run authority. Preserve review-only restrictions. Reject the reserved server-owned quota-recovery name before saving or accepting a native wait. - Commit the monitor, audit event, and retry receipt together. Retry receipts survive a successor run without re-arming cleared or consumed timers. - Permit `paperclip_finish` to yield to a persisted monitor. Recheck ownership and the schedule when committing final disposition. Release execution without an immediate continuation. - Preserve due monitors during native execution. Fence wake admission and consumption against replacement, clearing, reassignment, and completion. Preserve unrelated review policy. - Expose scheduled and consumed monitor instructions in task context. Update provider schemas, Rust validation, generated contracts, and execution documentation. - Add an opt-in live Codex smoke script with isolated data and explicit run/session/runner/process evidence. ## Verification - Repository `pnpm -r typecheck` and `pnpm build` passed after rebase. Server typecheck passed again after review fixes. All CI test shards pass on `3def77b1b`, including runner TypeScript/Rust, server, serialized server, workspace, and browser tests. All CI gates are green, including the canary dry run. Greptile is 5/5 on the same commit with zero unresolved threads. - The local monolithic `pnpm test:run`, started before the rebase, was interrupted after current-head CI test coverage passed. It is not counted as a standalone full-suite pass; the focused local regression suites passed. - Targeted server tests cover scheduling, replacement, clearing, policy preservation, cumulative bounds, cross-run retries, permissions, provider-neutral discovery, review restrictions, completion authority, and scheduler/finalizer races. - Runner contract/catalog/semantic tests and Rust terminal-tool tests cover the new operation and monitor completion. - Live Codex test passed twice (latest live run on `e0bcd63e6`) in a temporary database and workspace, with a 300,000 ms warm window. First run `67bd7709-c089-4d4a-9d2b-0d6b618a34b0` yielded at `2026-10-07T13:15:03.274Z`. Second run `97c323f9-595a-4cc5-a007-db5a2fbb937c` started at `13:15:30.952Z`, received `issue_monitor_due`, and completed the same task. Exactly one monitor wake was recorded. - Both live runs used native session `7b1dd753-1c9b-4e7a-b22f-a125dbc3748c`, runner `e90d9a1b-3502-4ee3-b15e-edc024c555d4`, provider session `01a11680-6d01-70c0-9a55-db7246ed66c3`, and PID `64218` with the same process start time. This proves warm reuse for that local Codex test, not only successful scheduling. - Reproduce the paid live test with `node --import ./server/node_modules/tsx/dist/loader.mjs server/scripts/smoke-native-task-monitor.ts --run`, with the installed Codex binary on `PATH` and a valid local login. ## Risks - The scheduler now defers monitor dispatch while the task has an active native run. A stuck run still depends on the existing recovery lifecycle. - Idempotency uses the existing run ledger; no table or migration is added. - Other providers share the tested tool and completion contracts. Only Codex received a live model test. - Existing `call_api` lifecycle restrictions remain enforced. Monitor waits do not bypass task blockers, reviews, or approvals. ## Model Used OpenAI Codex, GPT-6 family, with tool use, code execution, and TypeScript/Rust editing. The session does not expose the exact deployed model ID or context-window size. ## 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: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
b315580640
commit
8cfedd7df8
45 files changed
+1157
-207
No files matched your search
@@ -253,6 +253,9 @@ describeEmbeddedPostgres("issue monitor scheduler", () => {
|
||||
const { issueId, agentId } = await seedFixture();
|
||||
const heartbeat = heartbeatService(db);
|
||||
const tickAt = new Date("2026-04-11T12:31:00.000Z");
|
||||
const [before] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
const unrelatedPolicy = { commentRequired: false, futureAuthorization: { preserve: true } };
|
||||
await db.update(issues).set({ executionPolicy: { ...before.executionPolicy, ...unrelatedPolicy } }).where(eq(issues.id, issueId));
|
||||
|
||||
const result = await heartbeat.tickTimers(tickAt);
|
||||
|
||||
@@ -260,6 +263,7 @@ describeEmbeddedPostgres("issue monitor scheduler", () => {
|
||||
|
||||
const issue = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]!);
|
||||
expect(issue.monitorNextCheckAt).toBeNull();
|
||||
expect(issue.executionPolicy).toMatchObject(unrelatedPolicy);
|
||||
expect(issue.monitorAttemptCount).toBe(1);
|
||||
expect(issue.monitorLastTriggeredAt?.toISOString()).toBe(tickAt.toISOString());
|
||||
expect(normalizeIssueExecutionPolicy(issue.executionPolicy ?? null)?.monitor ?? null).toBeNull();
|
||||
@@ -284,6 +288,89 @@ describeEmbeddedPostgres("issue monitor scheduler", () => {
|
||||
expect(activity).toContain("issue.monitor_triggered");
|
||||
});
|
||||
|
||||
it("preserves a due monitor through native execution and dispatches once after release", async () => {
|
||||
const { companyId, issueId, agentId, nextCheckAt } = await seedFixture();
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId,
|
||||
runtimeMode: "native", status: "running", contextSnapshot: { issueId } });
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
const heartbeat = heartbeatService(db);
|
||||
expect((await heartbeat.tickTimers(new Date("2026-04-11T12:31:00.000Z"))).enqueued).toBe(0);
|
||||
const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
expect(waiting.monitorNextCheckAt).toEqual(nextCheckAt);
|
||||
expect(waiting.monitorWakeRequestedAt).toBeNull();
|
||||
expect(await db.select().from(agentWakeupRequests)).toHaveLength(0);
|
||||
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 heartbeat.tickTimers(new Date("2026-04-11T12:32:00.000Z"))).enqueued).toBe(1);
|
||||
expect((await heartbeat.tickTimers(new Date("2026-04-11T12:33:00.000Z"))).enqueued).toBe(0);
|
||||
const [triggered] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
expect(triggered.monitorNextCheckAt).toBeNull();
|
||||
expect(triggered.monitorAttemptCount).toBe(1);
|
||||
expect((await db.select().from(agentWakeupRequests)).filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1);
|
||||
});
|
||||
|
||||
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");
|
||||
let raced = false;
|
||||
const racingDb = new Proxy(db, {
|
||||
get(target, property, receiver) {
|
||||
if (property !== "transaction") return Reflect.get(target, property, receiver);
|
||||
return async (callback: Parameters<typeof db.transaction>[0]) => {
|
||||
const result = await db.transaction(callback);
|
||||
const claimed = result as { id?: string; monitorWakeRequestedAt?: Date } | undefined;
|
||||
if (!raced && claimed?.id === issueId && claimed.monitorWakeRequestedAt) {
|
||||
raced = true;
|
||||
await db.update(issues).set(change === "replaced" ? {
|
||||
monitorNextCheckAt: replacementAt, monitorWakeRequestedAt: null,
|
||||
executionPolicy: { monitor: { nextCheckAt: replacementAt.toISOString(), notes: "Replacement check", scheduledBy: "assignee" } },
|
||||
} : change === "cleared" ? { monitorNextCheckAt: null, monitorWakeRequestedAt: null, executionPolicy: null }
|
||||
: change === "reassigned" ? { assigneeAgentId: null } : { status: "done" })
|
||||
.where(eq(issues.id, issueId));
|
||||
}
|
||||
return result;
|
||||
};
|
||||
},
|
||||
});
|
||||
expect((await heartbeatService(racingDb).tickTimers(new Date("2026-04-11T12:31:00.000Z"))).enqueued).toBe(0);
|
||||
expect(raced).toBe(true);
|
||||
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId)))
|
||||
.filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(0);
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))).toHaveLength(0);
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
if (change === "replaced") expect(issue.monitorNextCheckAt).toEqual(replacementAt);
|
||||
if (change === "cleared") expect(issue.monitorNextCheckAt).toBeNull();
|
||||
});
|
||||
|
||||
it("does not erase a replacement scheduled after wake admission", async () => {
|
||||
const { companyId, issueId } = await seedFixture();
|
||||
const nextCheckAt = new Date("2026-04-11T13:30:00.000Z");
|
||||
let replaced = false;
|
||||
const racingDb = new Proxy(db, {
|
||||
get(target, property, receiver) {
|
||||
if (property !== "transaction") return Reflect.get(target, property, receiver);
|
||||
return async (callback: Parameters<typeof db.transaction>[0]) => {
|
||||
const result = await db.transaction(callback);
|
||||
if (!replaced && (result as { kind?: string } | undefined)?.kind === "queued") {
|
||||
replaced = true;
|
||||
await db.update(issues).set({ monitorNextCheckAt: nextCheckAt, monitorWakeRequestedAt: null,
|
||||
executionPolicy: { monitor: { nextCheckAt: nextCheckAt.toISOString(), notes: "New check", scheduledBy: "assignee" } },
|
||||
}).where(eq(issues.id, issueId));
|
||||
}
|
||||
return result;
|
||||
};
|
||||
},
|
||||
});
|
||||
await heartbeatService(racingDb).tickTimers(new Date("2026-04-11T12:31:00.000Z"));
|
||||
expect(replaced).toBe(true);
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
expect(issue.monitorNextCheckAt).toEqual(nextCheckAt);
|
||||
expect(issue.monitorWakeRequestedAt).toBeNull();
|
||||
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId)))
|
||||
.filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["unknown", "exhausted"] as const)("does not replay a quota monitor with %s execution evidence", async (kind) => {
|
||||
const sourceRunId = randomUUID();
|
||||
const { companyId, issueId, agentId } = await seedFixture({
|
||||
|
||||
@@ -2907,6 +2907,39 @@ describe("P6-31 Section 18.13 executable status-authority corpus", () => {
|
||||
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.idempotencyKey, key))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["scheduled", "cleared", "replaced", "reassigned"] as const)("revalidates a %s monitor under the final disposition lock", async (state) => {
|
||||
const template = corpus.fixtures.find(candidate => candidate.mode === "native")!;
|
||||
const fixture = { ...template, id: `monitor-commit-${state}`, given: { ...template.given, priorIssueStatus: "in_progress" } };
|
||||
const seeded = await seedFixture(fixture);
|
||||
const nextCheckAt = new Date(Date.now() + 60_000).toISOString();
|
||||
const currentCheck = state === "replaced" ? new Date(Date.now() + 120_000).toISOString() : nextCheckAt;
|
||||
await db.update(issues).set({
|
||||
executionRunId: seeded.runId, checkoutRunId: seeded.runId,
|
||||
assigneeAgentId: state === "reassigned" ? null : agentId,
|
||||
monitorNextCheckAt: state === "cleared" ? null : new Date(currentCheck),
|
||||
executionPolicy: state === "cleared" ? null : { monitor: { nextCheckAt: currentCheck, notes: "Check again" } },
|
||||
}).where(eq(issues.id, seeded.issueId));
|
||||
const decision: NativeStatusDecision = { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
|
||||
statusAction: "preserve", toStatus: "in_progress", reasonCode: "scheduled_monitor_waiting",
|
||||
unblockDescriptor: null, effects: [{ kind: "release_checkout" }] };
|
||||
const commit = () => commitNativeStatusDecision({ db, companyId, issueId: seeded.issueId, runId: seeded.runId,
|
||||
assessmentId: seeded.assessmentId, priorStatus: "in_progress", priorStatusVersion: 0, priorDecisionId: null,
|
||||
decision, requireMonitorWait: { agentId, nextCheckAt } });
|
||||
if (state !== "scheduled") {
|
||||
await expect(commit()).rejects.toThrow("native_status_race");
|
||||
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.issueId, seeded.issueId))).toHaveLength(0);
|
||||
} else {
|
||||
await commit();
|
||||
expect((await commit()).replayed).toBe(true);
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, seeded.issueId));
|
||||
expect(issue).toMatchObject({ status: "in_progress", checkoutRunId: null, executionRunId: null });
|
||||
expect(issue.monitorNextCheckAt?.toISOString()).toBe(nextCheckAt);
|
||||
const effects = await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.issueId, seeded.issueId));
|
||||
expect(effects.map(effect => effect.effectKind)).toEqual(["release_checkout"]);
|
||||
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, agentId))).filter(wake => wake.payload?.issueId === seeded.issueId)).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails the transaction closed for an unknown status effect", async () => {
|
||||
const fixture = corpus.fixtures.find((candidate) => candidate.mode === "native");
|
||||
if (!fixture) throw new Error("native corpus fixture missing");
|
||||
|
||||
Reference in new issue
Block a user