feat(runner): bind routine management to the live service

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-08 02:27:42 -05:00
1 parent 5717523b9e
commit 49fdc5899e
8 files changed
+278 -15

No files matched your search

@@ -0,0 +1,101 @@
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { routines, routineTriggers, type Db } from "@paperclipai/db";
import { createRoutineSchema, updateRoutineSchema, createRoutineTriggerSchema, updateRoutineTriggerSchema } from "@paperclipai/shared";
import { routineService } from "../routines.js";
import { persistActivity } from "../activity-log.js";
import { forbidden, notFound } from "../../errors.js";
export const manageRoutineInputSchema = z.object({
idempotencyKey: z.string().trim().min(1).max(240),
action: z.enum(["create", "update", "pause", "resume"]),
routineId: z.string().uuid().optional(),
baseRevisionId: z.string().uuid().optional(),
title: z.string().trim().min(1).max(200).optional(),
description: z.string().max(200_000).optional(),
projectId: z.string().uuid().optional(),
schedule: z.object({
triggerId: z.string().uuid().optional(),
cronExpression: z.string().trim().min(1).max(240),
timezone: z.string().trim().min(1).max(120),
}).strict().optional(),
}).strict().superRefine((input, ctx) => {
const error = (message: string) => ctx.addIssue({ code: "custom", message });
if (input.action === "create") {
if (!input.title || !input.schedule || input.routineId || input.baseRevisionId || input.schedule.triggerId) error("Create requires a title and schedule, without existing routine or trigger identity");
} else {
if (!input.routineId || !input.baseRevisionId) error("Read the routine first; routineId and baseRevisionId are required");
if (["pause", "resume"].includes(input.action) && [input.title, input.description, input.projectId, input.schedule].some(value => value !== undefined)) error("Pause and resume accept only the routine identity and revision");
if (input.schedule && !input.schedule.triggerId) error("Read the existing schedule first; triggerId is required when updating it");
}
});
type Binding = { companyId: string; agentId: string; issueId: string; runId: string };
export async function lockOwnedRoutine(db: Db, binding: Binding, id: string) {
const [routine] = await db.select().from(routines).where(and(eq(routines.id, id), eq(routines.companyId, binding.companyId))).for("update");
if (!routine) throw notFound("Routine not found");
if (routine.assigneeAgentId !== binding.agentId) throw forbidden("Agents can only manage routines assigned to themselves");
return routine;
}
/** Called inside the authority's run-bound idempotency/authorization transaction. */
export async function manageRoutine(db: Db, binding: Binding, input: z.infer<typeof manageRoutineInputSchema>) {
const service = routineService(db);
const actor = { agentId: binding.agentId, runId: binding.runId };
const publications: Awaited<ReturnType<typeof persistActivity>>["publication"][] = [];
const log = async (action: string, entityType: string, entityId: string, details: Record<string, unknown>) => {
const { publication } = await persistActivity(db, { companyId: binding.companyId, actorType: "agent", actorId: binding.agentId,
agentId: binding.agentId, runId: binding.runId, issueId: binding.issueId, action, entityType, entityId,
details: { ...details, source: "manage_routine" } });
publications.push(publication);
};
const logRevision = async (routineId: string, revision: { id: string; revisionNumber: number; changeSummary: string | null; snapshot: { triggers: unknown[] } }) =>
log("routine.revision_created", "routine", routineId, { revisionId: revision.id, revisionNumber: revision.revisionNumber,
changeSummary: revision.changeSummary, triggerCount: revision.snapshot.triggers.length });
let routine;
if (input.action === "create") {
routine = await service.create(binding.companyId, createRoutineSchema.parse({
title: input.title, description: input.description, projectId: input.projectId,
assigneeAgentId: binding.agentId, parentIssueId: binding.issueId,
}), actor);
await log("routine.revision_created", "routine", routine.id, { revisionId: routine.latestRevisionId,
revisionNumber: routine.latestRevisionNumber, changeSummary: "Created routine", triggerCount: 0 });
const created = await service.createTrigger(routine.id, createRoutineTriggerSchema.parse({ kind: "schedule", ...input.schedule }), actor);
await log("routine.trigger_created", "routine_trigger", created.trigger.id, { routineId: routine.id, kind: "schedule" });
await logRevision(routine.id, created.revision);
} else {
const existing = await lockOwnedRoutine(db, binding, input.routineId!);
routine = await service.update(existing.id, updateRoutineSchema.parse({
baseRevisionId: input.baseRevisionId,
...(input.action === "pause" ? { status: "paused" } : input.action === "resume" ? { status: "active" } : {
title: input.title, description: input.description, projectId: input.projectId,
}),
}), actor);
if (routine && routine.latestRevisionId !== existing.latestRevisionId) {
await log("routine.revision_created", "routine", routine.id, { revisionId: routine.latestRevisionId,
revisionNumber: routine.latestRevisionNumber, changeSummary: "Updated routine", triggerCount: null });
}
if (input.schedule) {
const [trigger] = await db.select().from(routineTriggers).where(and(
eq(routineTriggers.id, input.schedule.triggerId!), eq(routineTriggers.routineId, existing.id), eq(routineTriggers.companyId, binding.companyId),
)).for("update");
if (!trigger || trigger.kind !== "schedule" || trigger.archived) throw notFound("Routine schedule not found");
const updated = await service.updateTrigger(trigger.id, updateRoutineTriggerSchema.parse({ cronExpression: input.schedule.cronExpression, timezone: input.schedule.timezone }), actor);
if (!updated) throw notFound("Routine schedule not found");
await log("routine.trigger_updated", "routine", existing.id, { triggerId: trigger.id, kind: "schedule" });
await logRevision(existing.id, updated.revision);
}
}
if (!routine) throw notFound("Routine not found");
const current = await service.getDetail(routine.id);
if (!current) throw notFound("Routine not found");
await log(input.action === "create" ? "routine.created" : "routine.updated", "routine", current.id,
{ title: current.title, operation: input.action, revisionId: current.latestRevisionId });
return { publications, result: {
routineId: current.id, title: current.title, status: current.status,
baseRevisionId: current.latestRevisionId, assigneeAgentId: current.assigneeAgentId,
schedules: current.triggers.filter(trigger => trigger.kind === "schedule").map(trigger => ({
triggerId: trigger.id, cronExpression: trigger.cronExpression, timezone: trigger.timezone, enabled: trigger.enabled, nextRunAt: trigger.nextRunAt,
})),
} };
}
@@ -17,11 +17,15 @@ import {
issueComments,
issueThreadInteractions,
issues,
routines,
routineRuns,
routineTriggers,
} from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity } from "../run-identity.js";
import { documentService } from "../documents.js";
import { issueService } from "../issues.js";
import { routineService } from "../routines.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
import { createAssignedMcpTools } from "./assigned-mcp-tools.js";
import type { ToolGatewayService } from "../tool-gateway.js";
@@ -96,6 +100,44 @@ describe("PaperclipRunnerToolAuthority", () => {
await temporary?.cleanup();
});
it("manages self-assigned routines with durable retry and revision protection", async () => {
const userId = "routine-owner";
await db.insert(authUsers).values({ id: userId, name: "Routine owner", email: "routine-owner@example.test", createdAt: new Date(), updatedAt: new Date() });
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" });
await db.update(issues).set({ responsibleUserId: userId }).where(eq(issues.id, issueId));
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
const input = { idempotencyKey: "routine-create", action: "create", title: "Daily research",
schedule: { cronExpression: "0 9 * * 1-5", timezone: "America/Chicago" } };
const created = await authority.execute({ tool: "manage_routine", callId: "routine-create", arguments: input }) as { routineId: string; baseRevisionId: string };
expect(created).toMatchObject({ status: "active", assigneeAgentId: agentId, schedules: [{ timezone: "America/Chicago" }] });
expect(await authority.execute({ tool: "manage_routine", callId: "retry", arguments: input })).toEqual(created);
expect(await db.select().from(routineTriggers).where(eq(routineTriggers.routineId, created.routineId))).toHaveLength(1);
const paused = await authority.execute({ tool: "manage_routine", callId: "pause", arguments: {
idempotencyKey: "routine-pause", action: "pause", routineId: created.routineId, baseRevisionId: created.baseRevisionId,
} }) as { baseRevisionId: string };
expect(paused).toMatchObject({ status: "paused" });
const scheduler = routineService(db, { runtimeEnv: {}, heartbeat: { wakeup: async () => null } });
const due = new Date("2026-10-07T14:00:00Z");
await db.update(routineTriggers).set({ nextRunAt: due }).where(eq(routineTriggers.routineId, created.routineId));
expect(await scheduler.tickScheduledTriggers(due)).toEqual({ triggered: 0 });
await expect(authority.execute({ tool: "manage_routine", callId: "stale", arguments: {
idempotencyKey: "routine-stale", action: "resume", routineId: created.routineId, baseRevisionId: created.baseRevisionId,
} })).rejects.toThrow();
expect(await authority.execute({ tool: "manage_routine", callId: "resume", arguments: {
idempotencyKey: "routine-resume", action: "resume", routineId: created.routineId, baseRevisionId: paused.baseRevisionId,
} })).toMatchObject({ status: "active" });
await db.update(routineTriggers).set({ nextRunAt: due }).where(eq(routineTriggers.routineId, created.routineId));
expect(await scheduler.tickScheduledTriggers(due)).toEqual({ triggered: 1 });
expect(await scheduler.tickScheduledTriggers(due)).toEqual({ triggered: 0 });
const firings = await db.select().from(routineRuns).where(eq(routineRuns.routineId, created.routineId));
expect(firings).toMatchObject([{ status: "issue_created", source: "schedule" }]);
const [scheduledIssue] = await db.select().from(issues).where(eq(issues.id, firings[0]!.linkedIssueId!));
expect(scheduledIssue).toMatchObject({ companyId, assigneeAgentId: agentId, responsibleUserId: userId });
await db.update(routines).set({ assigneeAgentId: null }).where(eq(routines.id, created.routineId));
await expect(authority.execute({ tool: "manage_routine", callId: "reassigned-retry", arguments: input })).rejects.toThrow("assigned to themselves");
await db.update(issues).set({ responsibleUserId: null }).where(eq(issues.id, issueId));
});
it("advertises only real bindings and reads the bound task", async () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
@@ -130,6 +172,7 @@ describe("PaperclipRunnerToolAuthority", () => {
"submit_suggestion",
"request_human_input",
"create_task",
"manage_routine",
"set_dependencies",
"set_task_monitor",
"list_documents",
@@ -860,6 +903,7 @@ describe("PaperclipRunnerToolAuthority", () => {
});
it("writes a real revisioned document and replays the mutation receipt", async () => {
const before = await db.select().from(documents).where(eq(documents.companyId, companyId));
const body = credentialDocumentBody;
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
@@ -898,7 +942,7 @@ describe("PaperclipRunnerToolAuthority", () => {
.select()
.from(documents)
.where(eq(documents.companyId, companyId)),
).toHaveLength(1);
).toHaveLength(before.length + 1);
expect(await documentService(db).getIssueDocumentByKey(issueId, "plan"))
.toMatchObject({ body: credentialDocumentBody });
const documentActivity = await db
@@ -1028,6 +1072,7 @@ describe("PaperclipRunnerToolAuthority", () => {
});
it("creates ordinary children, preserves blockers, and deduplicates across runs", async () => {
const initialChildCount = (await db.select().from(issues).where(eq(issues.parentId, issueId))).length;
const wakes: Array<{ agentId: string; options: Record<string, unknown> }> =
[];
const authority = new PaperclipRunnerToolAuthority(db, {
@@ -1244,7 +1289,7 @@ describe("PaperclipRunnerToolAuthority", () => {
expect(retryWakes).toHaveLength(0);
expect(
await db.select().from(issues).where(eq(issues.parentId, issueId)),
).toHaveLength(3);
).toHaveLength(initialChildCount + 3);
});
it("rejects mutations after reassignment, run replacement, or terminalization", async () => {
@@ -5,6 +5,7 @@ import { assertCanManageIssueMonitor, prepareIssueMonitorUpdate, setTaskMonitorS
import { readTaskQuestionContext } from "../issue-question-context.js";
import { isConversation } from "../agent-conversations.js";
import { setIssueTitle } from "../issue-title.js";
import { manageRoutine, manageRoutineInputSchema, lockOwnedRoutine } from "./manage-routine.js";
import { externalObjectService } from "../external-objects.js";
import { instanceSettingsService } from "../instance-settings.js";
import { setIssueTitleSchema } from "@paperclipai/shared";
@@ -106,6 +107,7 @@ import {
const IMPLEMENTED_OPERATIONS = new Set([
"submit_complaint", "submit_suggestion",
"manage_routine",
"read_agent_instructions", "update_agent_instructions", "get_agent_instruction_history", "restore_agent_instructions",
"search_api", "call_api", "hire_agent",
"get_task_context", "get_task_history", "search_tasks", "report_progress", "set_task_title", "set_task_monitor",
@@ -486,6 +488,21 @@ export class PaperclipRunnerToolAuthority {
...parsed.data, kind: call.tool === "submit_complaint" ? "complaint" : "suggestion",
}, (tx) => this.#lockAuthorizedMutationContext(tx));
}
case "manage_routine": {
const parsed = manageRoutineInputSchema.parse(input);
let publications: Awaited<ReturnType<typeof persistActivity>>["publication"][] = [];
const result = await this.#withMutationReceipt("manage_routine", parsed.idempotencyKey, input, async tx => {
const changed = await manageRoutine(tx, this.binding, parsed);
publications = changed.publications;
return changed.result;
}, { beforeReceiptReplay: async (tx, context) => {
const prior = record(record(record(context.run.resultJson).semanticToolReceipts)[parsed.idempotencyKey]);
const routineId = parsed.routineId ?? requiredString(record(prior.result).routineId);
await lockOwnedRoutine(tx, this.binding, routineId);
} });
for (const publication of publications) publishActivity(publication);
return result;
}
case "read_agent_instructions":
case "get_agent_instruction_history":
return executeAgentInstructionTool({ db: this.db, binding: {