mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 09:50:48 +01:00
feat(routines): let agents list and change their person's routines in plain terms (#22274)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Routines are recurring work that an agent runs on a schedule, webhook or request. People file them under their responsibilities. > - #22253 and #22261 let agents read and change areas and responsibilities. Agents still have no dedicated routine tools, and they can change only routines assigned to themselves. > - When a person says "move my weekly digest to Monday mornings" or "map my routines to my responsibilities", the agent must use the generic API, write cron, and it is refused for the person's routines. > - This pull request adds `list_routines` and `update_routine`. It also lets an agent change routines that the person its run works for is responsible for. > - The benefit is that an agent can find routines under no responsibility, file them, and change their schedule in plain terms. Each change is a routine revision the person can restore. ## Linked Issues or Issue Description Refs #22261 (phase 2; this pull request is stacked on it), #22253 (phase 1). **Subsystem affected** Server (routine routes, native runner tool authority), the native runner tool catalog, and the `paperclip` skill. **Problem or motivation** An agent can list and change only its own routines through the generic API. It cannot change the schedule of a routine its person is responsible for. It must write cron expressions, and it cannot find the routines that are filed under no responsibility. **Proposed solution** Make the existing scenario operation `list_routines` live, with filters for words, status, agent, project, responsible person, a responsibility and "unfiled". Add `update_routine` for the title, instructions, agent, project, status, priority, a plain `schedule`, and filing under a responsibility. Let an agent manage a routine when the person its run works for is responsible for it. Handing the routine to another agent needs that person to have `tasks:assign`. **Alternatives considered** A new `routines` permission grant would add a setting with no current need. Routine revisions already give an undo path, so this change adds no new history. ## What Changed - `list_routines` is now live (it was a scenario-only mock) and keeps its scenario mock. - Add `update_routine`. A `schedule` such as `{ frequency: "weekly", dayOfWeek: "monday", time: "09:00", timezone }` maps to the routine's schedule trigger through the existing routine-offer cadence helpers. `schedule: null` turns the schedule off. `fileUnder` files the routine under a responsibility. - Add `server/src/services/routine-tools.ts`. It calls the routine routes with the run token. Fields and schedule go in one `PATCH /routines/:id` (one transaction and revision, guarded by `baseRevisionId`); filing follows, and if it fails after the routine changed the tool reports what was saved. Each part reports its own undo: the routine revision, or the Dashboard history for filing. - `PATCH /routines/:id` takes `schedule` (`{ cronExpression, timezone? }` or `null`) and replaces the schedule under the routine row lock, so racing changes leave one schedule. Without a zone it keeps the current schedule's, else uses the person's saved time zone, else answers 422. - `GET /companies/:companyId/routines` filters `q`, `status`, `assigneeAgentId`, `responsibleUserId`, `responsibilityId` and `unfiled=true` in SQL. - In `routes/routines.ts`, an agent may manage routines assigned to itself or routines its person is responsible for. On a routine the agent does not run, taking it from another agent (or handing it on), turning it on, changing its schedule (also through the trigger routes), starting a run, or restoring a revision requires that person's `tasks:assign`, as for a person. The person must have directed the run (see #22261). `routine.updated` activity records `onBehalfOfUserId`. - The routine and responsibility routes share one rule, `agentPersonInCompany` in `routes/agent-person-authz.ts`. - The catalog keeps each live action's `requiredClaims` (`list_routines` is `routines:read`). - The routine tools stay visible when Responsibilities is off. Only `responsibilityId`, `unfiled` and `fileUnder` need it. - Update `search_api` tool pointers, the routines reference, the skill section, the chat directive, the operation-groups spec and the pinned counts. ## Verification - Server: `routine-tools.test.ts` (new), `routines-routes.test.ts` (new: an agent changes its person's routine, hands it off only with `tasks:assign`, and is refused for another person's routine), the `responsibilit*` tests, `paperclip-runner-tool-authority` and `runner-api`: all pass. The first test in `routines-routes.test.ts` (Fireflies) times out at 15 s in my sandbox on a cold import, with or without this change. It passes with `--testTimeout=60000`. - Server `node scripts/typecheck-layers.mjs`: passed. - Runner: catalog, semantic-tool, eval, scenario and permission-policy tests (316) pass. All generator checks pass. ## Risks - Medium-low. Agents get write access to their person's routines. The route still checks the company, the routine revision guard and `tasks:assign` for a hand-off. The person can restore any earlier routine revision. - `list_routines` changes from a scenario-only mock to a live tool, so the reconciled catalog counts change. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
40 files changed
+1386
-337
No files matched your search
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { callRoutineTool } from "../services/routine-tools.js";
|
||||
|
||||
const COMPANY = "11111111-1111-4111-8111-111111111111";
|
||||
const ROUTINE = "44444444-4444-4444-8444-444444444444";
|
||||
const OTHER = "55555555-5555-4555-8555-555555555555";
|
||||
const RESPONSIBILITY = "33333333-3333-4333-8333-333333333333";
|
||||
const TRIGGER = "66666666-6666-4666-8666-666666666666";
|
||||
|
||||
function routine(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: ROUTINE, companyId: COMPANY, projectId: null, title: "Weekly pipeline", description: "Review the pipeline",
|
||||
assigneeAgentId: "agent-1", priority: "medium", status: "active", responsibleUserId: "person-1",
|
||||
latestRevisionId: "rev-1", latestRevisionNumber: 3, triggers: [], lastRun: null, ...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** A response with a status or headers; plain values answer 200. */
|
||||
class Reply {
|
||||
constructor(readonly body: unknown, readonly status = 200, readonly headers: Record<string, string> = {}) {}
|
||||
}
|
||||
|
||||
/** Answers by "METHOD path" or path, and records each request. */
|
||||
function fakeApi(routes: Record<string, unknown | (() => unknown)>) {
|
||||
const calls: Array<{ method: string; path: string; body?: unknown }> = [];
|
||||
const fetcher = (async (url: string | URL, init?: RequestInit) => {
|
||||
const method = init?.method ?? "GET";
|
||||
const path = String(url).replace("http://paperclip.test/api", "");
|
||||
calls.push({ method, path, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });
|
||||
const route = routes[`${method} ${path}`] ?? routes[path];
|
||||
if (route === undefined) throw new Error(`unexpected request ${method} ${path}`);
|
||||
const value = typeof route === "function" ? (route as () => unknown)() : route;
|
||||
const reply = value instanceof Reply ? value : new Reply(value);
|
||||
return new Response(JSON.stringify(reply.body), { status: reply.status, headers: { "content-type": "application/json", ...reply.headers } });
|
||||
}) as typeof fetch;
|
||||
return { calls, fetcher };
|
||||
}
|
||||
|
||||
const base = { apiUrl: "http://paperclip.test/api", token: "agent-token", companyId: COMPANY, companyPrefix: "PAP" };
|
||||
|
||||
describe("routine tools", () => {
|
||||
it("passes every filter to the routine list, so they apply before the limit", async () => {
|
||||
const query = new URLSearchParams({ q: "pipeline", status: "paused", responsibleUserId: "person-1", responsibilityId: RESPONSIBILITY, unfiled: "true" });
|
||||
const api = fakeApi({
|
||||
[`/companies/${COMPANY}/routines?${query}`]: [
|
||||
routine({ status: "paused", triggers: [{ id: TRIGGER, kind: "schedule", enabled: true, cronExpression: "0 9 * * 1", timezone: "Europe/Berlin", nextRunAt: null }] }),
|
||||
routine({ id: OTHER, status: "paused" }),
|
||||
],
|
||||
});
|
||||
const result = await callRoutineTool({ ...base, name: "list_routines", arguments: {
|
||||
query: "pipeline", status: "paused", responsibleUserId: "person-1", responsibilityId: RESPONSIBILITY, unfiled: true, limit: 1,
|
||||
} }, api.fetcher);
|
||||
expect(result).toMatchObject({
|
||||
total: 2,
|
||||
routines: [{ id: ROUTINE, title: "Weekly pipeline", triggers: [{ triggerId: TRIGGER, cronExpression: "0 9 * * 1", timezone: "Europe/Berlin" }], href: `/PAP/routines/${ROUTINE}` }],
|
||||
truncated: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("changes a routine and its schedule in one call, files it, and reports each undo", async () => {
|
||||
let reads = 0;
|
||||
const scheduled = [{ id: TRIGGER, kind: "schedule", enabled: true, cronExpression: "30 9 * * 1", timezone: "Europe/Berlin", nextRunAt: null }];
|
||||
const api = fakeApi({
|
||||
[`GET /routines/${ROUTINE}`]: () => (reads++ === 0 ? routine() : routine({ title: "Pipeline review", latestRevisionNumber: 4, triggers: scheduled })),
|
||||
[`PATCH /routines/${ROUTINE}`]: routine({ title: "Pipeline review" }),
|
||||
[`POST /responsibilities/${RESPONSIBILITY}/file`]: new Reply({ filed: [], unfiled: [] }, 200,
|
||||
{ "x-paperclip-dashboard-version": "version-7", "x-paperclip-dashboard-owner": "person-1" }),
|
||||
});
|
||||
const result = await callRoutineTool({ ...base, name: "update_routine", arguments: {
|
||||
routineId: ROUTINE, title: "Pipeline review", instructions: "Review the pipeline and flag stalled deals",
|
||||
schedule: { frequency: "weekly", dayOfWeek: "monday", time: "09:30", timezone: "Europe/Berlin" }, fileUnder: RESPONSIBILITY,
|
||||
} }, api.fetcher);
|
||||
expect(api.calls.filter((call) => call.method !== "GET")).toEqual([
|
||||
{ method: "PATCH", path: `/routines/${ROUTINE}`, body: {
|
||||
title: "Pipeline review", description: "Review the pipeline and flag stalled deals",
|
||||
schedule: { cronExpression: "30 9 * * 1", timezone: "Europe/Berlin" }, baseRevisionId: "rev-1",
|
||||
} },
|
||||
{ method: "POST", path: `/responsibilities/${RESPONSIBILITY}/file`, body: { items: [{ kind: "routine", id: ROUTINE }] } },
|
||||
]);
|
||||
expect(result).toMatchObject({
|
||||
routine: { title: "Pipeline review", revision: 4 },
|
||||
schedule: { label: "Every Monday at 9:30 AM", cronExpression: "30 9 * * 1", timezone: "Europe/Berlin" },
|
||||
filedUnder: { responsibilityId: RESPONSIBILITY, dashboardVersionId: "version-7", dashboardOwnerUserId: "person-1", undo: expect.stringContaining("Dashboard history") },
|
||||
undo: expect.stringMatching(/restoring revision 3 .*not the filing/),
|
||||
});
|
||||
});
|
||||
|
||||
it("says what was saved when filing fails after the routine changed", async () => {
|
||||
let reads = 0;
|
||||
const api = fakeApi({
|
||||
[`GET /routines/${ROUTINE}`]: () => (reads++ === 0 ? routine() : routine({ title: "Pipeline review", latestRevisionNumber: 4 })),
|
||||
[`PATCH /routines/${ROUTINE}`]: routine({ title: "Pipeline review" }),
|
||||
[`POST /responsibilities/${RESPONSIBILITY}/file`]: new Reply({ error: "Responsibilities are not enabled", code: "responsibilities_disabled" }, 404),
|
||||
});
|
||||
const result = await callRoutineTool({ ...base, name: "update_routine", arguments: { routineId: ROUTINE, title: "Pipeline review", fileUnder: RESPONSIBILITY } }, api.fetcher);
|
||||
expect(result).toMatchObject({
|
||||
routine: { title: "Pipeline review", revision: 4 },
|
||||
filedUnder: { responsibilityId: RESPONSIBILITY, failed: true, error: "Responsibilities are not enabled", note: expect.stringContaining("was saved") },
|
||||
undo: expect.stringContaining("restoring revision 3"),
|
||||
});
|
||||
|
||||
// A filing on its own still fails loudly: nothing else was saved.
|
||||
await expect(callRoutineTool({ ...base, name: "update_routine", arguments: { routineId: ROUTINE, fileUnder: RESPONSIBILITY } }, api.fetcher))
|
||||
.rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("leaves the zone to the server when none is given, and turns schedules off with null", async () => {
|
||||
const add = fakeApi({
|
||||
[`GET /routines/${ROUTINE}`]: routine(),
|
||||
[`PATCH /routines/${ROUTINE}`]: routine(),
|
||||
});
|
||||
await callRoutineTool({ ...base, name: "update_routine", arguments: { routineId: ROUTINE, schedule: { frequency: "weekdays", time: "08:00" } } }, add.fetcher);
|
||||
expect(add.calls.find((call) => call.method === "PATCH")?.body).toEqual({ schedule: { cronExpression: "0 8 * * 1-5" }, baseRevisionId: "rev-1" });
|
||||
|
||||
const off = fakeApi({
|
||||
[`GET /routines/${ROUTINE}`]: routine({ triggers: [{ id: TRIGGER, kind: "schedule", enabled: true, cronExpression: "0 9 * * 1", timezone: "UTC", nextRunAt: null }] }),
|
||||
[`PATCH /routines/${ROUTINE}`]: routine(),
|
||||
});
|
||||
const result = await callRoutineTool({ ...base, name: "update_routine", arguments: { routineId: ROUTINE, schedule: null } }, off.fetcher);
|
||||
expect(off.calls.find((call) => call.method === "PATCH")?.body).toEqual({ schedule: null, baseRevisionId: "rev-1" });
|
||||
expect(result).toMatchObject({ schedule: { turnedOff: 1 } });
|
||||
});
|
||||
|
||||
it("refuses an empty change and a weekly schedule without its day", async () => {
|
||||
const api = fakeApi({ [`GET /routines/${ROUTINE}`]: routine() });
|
||||
await expect(callRoutineTool({ ...base, name: "update_routine", arguments: { routineId: ROUTINE } }, api.fetcher)).rejects.toMatchObject({ status: 422 });
|
||||
await expect(callRoutineTool({ ...base, name: "update_routine", arguments: { routineId: ROUTINE, schedule: { frequency: "weekly", time: "09:00" } } }, api.fetcher))
|
||||
.rejects.toThrow(/dayOfWeek/);
|
||||
});
|
||||
});
|
||||
@@ -27,10 +27,14 @@ import {
|
||||
principalPermissionGrants,
|
||||
projectWorkspaces,
|
||||
projects,
|
||||
responsibilities,
|
||||
responsibilityLinks,
|
||||
routineDocuments,
|
||||
routineRevisions,
|
||||
routineRuns,
|
||||
routines,
|
||||
routineTriggers,
|
||||
userWorkspacePreferences,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
@@ -115,6 +119,9 @@ describeEmbeddedPostgres("routine routes end-to-end", () => {
|
||||
await db.delete(documentAnnotationAnchorSnapshots);
|
||||
await db.delete(documentAnnotationComments);
|
||||
await db.delete(documentAnnotationThreads);
|
||||
await db.delete(responsibilityLinks);
|
||||
await db.delete(responsibilities);
|
||||
await db.delete(userWorkspacePreferences);
|
||||
await db.delete(routineRuns);
|
||||
await db.delete(routineTriggers);
|
||||
await db.delete(heartbeatRunEvents);
|
||||
@@ -1057,4 +1064,148 @@ describeEmbeddedPostgres("routine routes end-to-end", () => {
|
||||
executionWorkspaceSettings: { mode: "isolated_workspace" },
|
||||
});
|
||||
});
|
||||
|
||||
describe("an agent acting for the routine's person", () => {
|
||||
/** A second agent, working in the person's own chat, so it acts for them. */
|
||||
async function helperFor(companyId: string, personUserId: string) {
|
||||
const [helper] = await db.insert(agents).values({
|
||||
companyId, name: "Helper", role: "general", status: "active", adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {}, permissions: {},
|
||||
}).returning();
|
||||
const [chat] = await db.insert(issues).values({ companyId, title: "Chat", createdByUserId: personUserId, responsibleUserId: personUserId }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: helper!.id, issueId: chat!.id, scopeKind: "issue", status: "running", contextSnapshot: { issueId: chat!.id } }).returning();
|
||||
const app = await createApp({
|
||||
type: "agent", agentId: helper!.id, companyId, runId: run!.id, source: "agent_jwt",
|
||||
onBehalfOfUserId: personUserId, onBehalfOfMemberships: [{ companyId, membershipRole: "owner", status: "active" }],
|
||||
});
|
||||
return { app, helperId: helper!.id };
|
||||
}
|
||||
|
||||
async function personRoutine(companyId: string, agentId: string, userId: string, values: Record<string, unknown> = {}) {
|
||||
const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true });
|
||||
const created = await request(board).post(`/api/companies/${companyId}/routines`).send({ assigneeAgentId: agentId, title: "Weekly pipeline", ...values });
|
||||
expect(created.status, JSON.stringify(created.body)).toBe(201);
|
||||
return created.body.id as string;
|
||||
}
|
||||
|
||||
it("reschedules its person's routine run by another agent in one revision, with one schedule however often it races", async () => {
|
||||
const { companyId, agentId, userId } = await seedFixture();
|
||||
const routineId = await personRoutine(companyId, agentId, userId);
|
||||
const { app } = await helperFor(companyId, userId);
|
||||
const revisions = async () => db.select().from(routineRevisions).where(eq(routineRevisions.routineId, routineId));
|
||||
const before = (await revisions()).length;
|
||||
|
||||
// No zone given, none on the routine and none saved for the person: the agent must name one.
|
||||
const unnamed = await request(app).patch(`/api/routines/${routineId}`).send({ title: "Pipeline review", schedule: { cronExpression: "30 9 * * 1" } });
|
||||
expect(unnamed.status).toBe(422);
|
||||
expect((await revisions()).length).toBe(before);
|
||||
|
||||
await db.insert(userWorkspacePreferences).values({ userId, timeZone: "Europe/Berlin" });
|
||||
const changed = await request(app).patch(`/api/routines/${routineId}`).send({ title: "Pipeline review", schedule: { cronExpression: "30 9 * * 1" } });
|
||||
expect(changed.status, JSON.stringify(changed.body)).toBe(200);
|
||||
const after = await revisions();
|
||||
expect(after.length).toBe(before + 1);
|
||||
expect(after.find((revision) => revision.revisionNumber === Math.max(...after.map((r) => r.revisionNumber)))?.changeSummary).toBe("Updated routine and schedule");
|
||||
const schedules = async () => db.select().from(routineTriggers).where(eq(routineTriggers.routineId, routineId));
|
||||
expect(await schedules()).toMatchObject([{ kind: "schedule", enabled: true, cronExpression: "30 9 * * 1", timezone: "Europe/Berlin" }]);
|
||||
|
||||
// Two changes at once: the routine lock keeps one enabled schedule.
|
||||
await db.delete(routineTriggers).where(eq(routineTriggers.routineId, routineId));
|
||||
const raced = await Promise.all([
|
||||
request(app).patch(`/api/routines/${routineId}`).send({ schedule: { cronExpression: "0 8 * * *", timezone: "UTC" } }),
|
||||
request(app).patch(`/api/routines/${routineId}`).send({ schedule: { cronExpression: "0 18 * * *", timezone: "UTC" } }),
|
||||
]);
|
||||
expect(raced.map((res) => res.status)).toEqual([200, 200]);
|
||||
expect((await schedules()).filter((trigger) => trigger.enabled)).toHaveLength(1);
|
||||
|
||||
const off = await request(app).patch(`/api/routines/${routineId}`).send({ schedule: null });
|
||||
expect(off.status).toBe(200);
|
||||
expect((await schedules()).every((trigger) => !trigger.enabled)).toBe(true);
|
||||
|
||||
// Handing the routine to another person with a new time: the time is in the new person's zone.
|
||||
const nextPerson = randomUUID();
|
||||
await accessService(db).ensureMembership(companyId, "user", nextPerson, "operator", "active");
|
||||
await db.insert(userWorkspacePreferences).values({ userId: nextPerson, timeZone: "Asia/Tokyo" });
|
||||
await db.delete(routineTriggers).where(eq(routineTriggers.routineId, routineId));
|
||||
const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true });
|
||||
const handed = await request(board).patch(`/api/routines/${routineId}`).send({ responsibleUserId: nextPerson, schedule: { cronExpression: "0 9 * * *" } });
|
||||
expect(handed.status, JSON.stringify(handed.body)).toBe(200);
|
||||
expect(await schedules()).toMatchObject([{ enabled: true, timezone: "Asia/Tokyo" }]);
|
||||
});
|
||||
|
||||
it("refuses another person's routine, and needs the person's tasks:assign to take, turn on or reschedule one it does not run", async () => {
|
||||
const { companyId, agentId, userId } = await seedFixture();
|
||||
const memberId = randomUUID();
|
||||
await accessService(db).ensureMembership(companyId, "user", memberId, "operator", "active");
|
||||
// A member who may not assign tasks, as under a restricted assignment policy.
|
||||
vi.doMock("../services/index.js", async () => {
|
||||
const [{ accessService: realAccess }, { documentAnnotationService }, { logActivity }, { routineService }] = await Promise.all([
|
||||
import("../services/access.js"), import("../services/document-annotations.js"),
|
||||
import("../services/activity-log.js"), import("../services/routines.js"),
|
||||
]);
|
||||
const accessService = (database: typeof db) => {
|
||||
const access = realAccess(database);
|
||||
return { ...access, canUser: async (...args: Parameters<typeof access.canUser>) =>
|
||||
(args[1] === memberId && args[2] === "tasks:assign" ? false : access.canUser(...args)) };
|
||||
};
|
||||
return { accessService, documentAnnotationService, logActivity, routineService };
|
||||
});
|
||||
const ownersRoutine = await personRoutine(companyId, agentId, userId);
|
||||
const membersRoutine = await personRoutine(companyId, agentId, userId, { status: "paused" });
|
||||
await db.update(routines).set({ responsibleUserId: memberId }).where(eq(routines.id, membersRoutine));
|
||||
|
||||
const { app: forMember, helperId } = await helperFor(companyId, memberId);
|
||||
// Not the member's routine: no change at all.
|
||||
expect((await request(forMember).patch(`/api/routines/${ownersRoutine}`).send({ title: "x" })).status).toBe(403);
|
||||
// The member's routine: an ordinary change is fine, but the member may not assign tasks.
|
||||
expect((await request(forMember).patch(`/api/routines/${membersRoutine}`).send({ title: "Member pipeline" })).status).toBe(200);
|
||||
expect((await request(forMember).patch(`/api/routines/${membersRoutine}`).send({ assigneeAgentId: helperId })).status).toBe(403);
|
||||
expect((await request(forMember).patch(`/api/routines/${membersRoutine}`).send({ status: "active" })).status).toBe(403);
|
||||
expect((await request(forMember).patch(`/api/routines/${membersRoutine}`).send({ schedule: { cronExpression: "0 9 * * 1", timezone: "UTC" } })).status).toBe(403);
|
||||
expect((await request(forMember).post(`/api/routines/${membersRoutine}/triggers`).send({ kind: "schedule", cronExpression: "0 9 * * 1", timezone: "UTC" })).status).toBe(403);
|
||||
// Nor change an existing trigger, start the routine, or restore a revision of it.
|
||||
const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true });
|
||||
const trigger = await request(board).post(`/api/routines/${membersRoutine}/triggers`).send({ kind: "schedule", cronExpression: "0 9 * * 1", timezone: "UTC", enabled: false });
|
||||
expect(trigger.status, JSON.stringify(trigger.body)).toBe(201);
|
||||
expect((await request(forMember).patch(`/api/routine-triggers/${trigger.body.trigger.id}`).send({ enabled: true })).status).toBe(403);
|
||||
expect((await request(forMember).delete(`/api/routine-triggers/${trigger.body.trigger.id}`)).status).toBe(403);
|
||||
expect((await request(forMember).post(`/api/routines/${membersRoutine}/run`).send({})).status).toBe(403);
|
||||
const [revision] = await db.select().from(routineRevisions).where(eq(routineRevisions.routineId, membersRoutine)).limit(1);
|
||||
expect((await request(forMember).post(`/api/routines/${membersRoutine}/revisions/${revision!.id}/restore`).send({})).status).toBe(403);
|
||||
|
||||
// The owner may assign tasks, so an agent acting for them may take the routine.
|
||||
const { app: forOwner, helperId: ownersHelper } = await helperFor(companyId, userId);
|
||||
const taken = await request(forOwner).patch(`/api/routines/${ownersRoutine}`).send({ assigneeAgentId: ownersHelper });
|
||||
expect(taken.status, JSON.stringify(taken.body)).toBe(200);
|
||||
// The agent that runs a routine still reschedules its own, also through its trigger.
|
||||
const runner = await createApp({ type: "agent", agentId, companyId });
|
||||
expect((await request(runner).patch(`/api/routines/${membersRoutine}`).send({ schedule: { cronExpression: "0 9 * * 1", timezone: "UTC" } })).status).toBe(200);
|
||||
expect((await request(runner).patch(`/api/routine-triggers/${trigger.body.trigger.id}`).send({ cronExpression: "0 10 * * 1" })).status).toBe(200);
|
||||
});
|
||||
|
||||
it("filters the list in the query: words, status and routines filed under no responsibility", async () => {
|
||||
const { companyId, agentId, userId } = await seedFixture();
|
||||
await db.delete(instanceSettings);
|
||||
await db.insert(instanceSettings).values({ experimental: { enableResponsibilities: true } });
|
||||
const filed = await personRoutine(companyId, agentId, userId, { title: "Pipeline filed" });
|
||||
const loose = await personRoutine(companyId, agentId, userId, { title: "Pipeline loose", status: "paused" });
|
||||
await personRoutine(companyId, agentId, userId, { title: "Standup" });
|
||||
const [hiring] = await db.insert(responsibilities).values({ companyId, ownerUserId: userId, title: "Hiring", status: "active" }).returning();
|
||||
await db.insert(responsibilityLinks).values({ companyId, responsibilityId: hiring!.id, routineId: filed });
|
||||
const board = await createApp({ type: "board", source: "local_implicit", userId, isInstanceAdmin: true });
|
||||
const list = async (query: string) => (await request(board).get(`/api/companies/${companyId}/routines?${query}`)).body.map((routine: { id: string }) => routine.id);
|
||||
|
||||
expect(await list("q=PIPELINE")).toEqual(expect.arrayContaining([filed, loose]));
|
||||
expect(await list("q=PIPELINE")).toHaveLength(2);
|
||||
expect(await list("q=pipeline&unfiled=true&status=paused")).toEqual([loose]);
|
||||
expect(await list(`responsibilityId=${hiring!.id}`)).toEqual([filed]);
|
||||
|
||||
// The responsibility filters are part of the Responsibilities experiment; plain searches are not.
|
||||
await db.update(instanceSettings).set({ experimental: { enableResponsibilities: false } });
|
||||
(await import("../services/instance-settings-cache.js")).invalidateInstanceSettingsCache();
|
||||
const off = await request(board).get(`/api/companies/${companyId}/routines?unfiled=true`);
|
||||
expect(off.status).toBe(404);
|
||||
expect(off.body.code).toBe("responsibilities_disabled");
|
||||
expect(await list("q=standup")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -135,6 +135,15 @@ const mockGetTelemetryClient = vi.hoisted(() => vi.fn());
|
||||
|
||||
function registerModuleMocks() {
|
||||
vi.doMock("../routes/authz.js", async () => vi.importActual("../routes/authz.js"));
|
||||
// Whether the person directed the run reads the database these tests mock away; routines-e2e covers it.
|
||||
// Here every run with a person was directed by them.
|
||||
vi.doMock("../routes/agent-person-authz.js", () => ({
|
||||
agentPersonInCompany: async (_db: unknown, req: { actor: { type: string; onBehalfOfUserId?: string; onBehalfOfMemberships?: Array<{ companyId: string; status?: string; membershipRole?: string | null }> } }, companyId: string) => {
|
||||
if (req.actor.type !== "agent" || !req.actor.onBehalfOfUserId) return null;
|
||||
const membership = req.actor.onBehalfOfMemberships?.find((item) => item.companyId === companyId && item.status === "active");
|
||||
return membership ? { userId: req.actor.onBehalfOfUserId, role: membership.membershipRole ?? null } : null;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.doMock("@paperclipai/shared/telemetry", () => ({
|
||||
trackRoutineCreated: mockTrackRoutineCreated,
|
||||
@@ -568,6 +577,35 @@ describe("routine routes", () => {
|
||||
expect(res.body).not.toHaveProperty("previousResponsibleUserId");
|
||||
});
|
||||
|
||||
it("lets an agent change a routine the person it works for is responsible for", async () => {
|
||||
const personsRoutine = { ...routine, assigneeAgentId: otherAgentId, responsibleUserId: "person-1" };
|
||||
mockRoutineService.get.mockResolvedValue(personsRoutine);
|
||||
mockRoutineService.update.mockResolvedValue({ ...personsRoutine, title: "Weekly digest" });
|
||||
const forPerson = await createApp({
|
||||
type: "agent", agentId, companyId, onBehalfOfUserId: "person-1",
|
||||
onBehalfOfMemberships: [{ companyId, membershipRole: "member", status: "active" }],
|
||||
});
|
||||
const res = await request(forPerson).patch(`/api/routines/${routineId}`).send({ title: "Weekly digest" });
|
||||
expect(res.status).toBe(200);
|
||||
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
action: "routine.updated", details: expect.objectContaining({ onBehalfOfUserId: "person-1" }),
|
||||
}));
|
||||
|
||||
// Handing it to another agent is an assignment the person must be allowed to make.
|
||||
const handOff = await request(forPerson).patch(`/api/routines/${routineId}`).send({ assigneeAgentId: projectId });
|
||||
expect(handOff.status).toBe(403);
|
||||
mockAccessService.canUser.mockResolvedValue(true);
|
||||
expect((await request(forPerson).patch(`/api/routines/${routineId}`).send({ assigneeAgentId: projectId })).status).toBe(200);
|
||||
expect(mockAccessService.canUser).toHaveBeenCalledWith(companyId, "person-1", "tasks:assign");
|
||||
|
||||
// An agent working for someone else may not.
|
||||
const forOther = await createApp({
|
||||
type: "agent", agentId, companyId, onBehalfOfUserId: "person-2",
|
||||
onBehalfOfMemberships: [{ companyId, membershipRole: "owner", status: "active" }],
|
||||
});
|
||||
expect((await request(forOther).patch(`/api/routines/${routineId}`).send({ title: "x" })).status).toBe(403);
|
||||
});
|
||||
|
||||
it("prevents even the assigned agent from transferring routine responsibility", async () => {
|
||||
const app = await createApp({ type: "agent", agentId, companyId });
|
||||
mockRoutineService.getDetail.mockResolvedValue(routine);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Router, type Request } from "express";
|
||||
import { z } from "zod";
|
||||
import { triggerUpdateActivityAction } from "../services/routine-trigger-update-plan.js";
|
||||
import { listProtectedEnvironmentKeyHolders, protectedEnvironmentKeyWarnings } from "../services/protected-environment-keys.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
createDocumentAnnotationCommentSchema,
|
||||
createDocumentAnnotationThreadSchema,
|
||||
createRoutineTriggerSchema,
|
||||
ROUTINE_STATUSES,
|
||||
rotateRoutineTriggerSecretSchema,
|
||||
runRoutineSchema,
|
||||
updateDocumentAnnotationThreadSchema,
|
||||
@@ -16,11 +18,25 @@ import {
|
||||
import { trackRoutineCreated } from "@paperclipai/shared/telemetry";
|
||||
import { validate, validateIssueMutationBody } from "../middleware/validate.js";
|
||||
import { accessService, documentAnnotationService, instanceSettingsService, logActivity, routineService } from "../services/index.js";
|
||||
import { instanceSettingsService as experimentSettings } from "../services/instance-settings.js";
|
||||
import { responsibilitiesDisabledError } from "../services/responsibilities-disabled.js";
|
||||
import { agentPersonInCompany } from "./agent-person-authz.js";
|
||||
import { assertCompanyAccess, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
|
||||
import { badRequest, forbidden, unauthorized, unprocessable, unsupportedMediaType } from "../errors.js";
|
||||
import { getTelemetryClient } from "../telemetry.js";
|
||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
|
||||
|
||||
/** Filters for the routine list; all are applied in the query, before any limit. */
|
||||
const listRoutinesQuerySchema = z.object({
|
||||
projectId: z.string().optional(),
|
||||
q: z.string().trim().min(1).max(200).optional(),
|
||||
status: z.enum(ROUTINE_STATUSES).optional(),
|
||||
assigneeAgentId: z.string().guid().optional(),
|
||||
responsibleUserId: z.string().trim().min(1).max(200).optional(),
|
||||
responsibilityId: z.string().guid().optional(),
|
||||
unfiled: z.enum(["true", "false"]).optional(),
|
||||
});
|
||||
|
||||
export function routineRoutes(
|
||||
db: Db,
|
||||
options: { pluginWorkerManager?: PluginWorkerManager } = {},
|
||||
@@ -118,14 +134,37 @@ export function routineRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The person an agent acts for on this routine: the person who directed its
|
||||
* run, when that person is responsible for the routine. Null otherwise.
|
||||
*/
|
||||
async function agentActsForRoutinePerson(req: Request, routine: { companyId: string; responsibleUserId: string | null }) {
|
||||
const person = await agentPersonInCompany(db, req, routine.companyId);
|
||||
return person && routine.responsibleUserId === person.userId ? person.userId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a person needs tasks:assign for (who runs a routine, turning it on,
|
||||
* its schedule): an agent may do it on a routine it runs and keeps running,
|
||||
* and on any other only when the person it acts for may assign tasks.
|
||||
*/
|
||||
async function assertAgentCanAssign(req: Request, routine: { companyId: string; responsibleUserId: string | null }, runsIt: boolean) {
|
||||
if (req.actor.type !== "agent" || runsIt) return;
|
||||
const actsFor = await agentActsForRoutinePerson(req, routine);
|
||||
if (!actsFor || !(await access.canUser(routine.companyId, actsFor, "tasks:assign"))) {
|
||||
throw forbidden("Agents can change who runs a routine, turn it on or change its schedule only on routines they run, unless the person they act for may assign tasks");
|
||||
}
|
||||
}
|
||||
|
||||
async function assertCanManageExistingRoutine(req: Request, routineId: string) {
|
||||
const routine = await svc.get(routineId);
|
||||
if (!routine || !hasCompanyAccess(req, routine.companyId)) return null;
|
||||
assertCompanyAccess(req, routine.companyId);
|
||||
if (req.actor.type === "board") return routine;
|
||||
if (req.actor.type !== "agent" || !req.actor.agentId) throw unauthorized();
|
||||
if (routine.assigneeAgentId !== req.actor.agentId) {
|
||||
throw forbidden("Agents can only manage routines assigned to themselves");
|
||||
// An agent manages its own routines, and those of the person its run works for.
|
||||
if (routine.assigneeAgentId !== req.actor.agentId && !(await agentActsForRoutinePerson(req, routine))) {
|
||||
throw forbidden("Agents can only manage routines assigned to themselves, or routines the person they work for is responsible for");
|
||||
}
|
||||
return routine;
|
||||
}
|
||||
@@ -162,8 +201,13 @@ export function routineRoutes(
|
||||
router.get("/companies/:companyId/routines", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const projectId = typeof req.query.projectId === "string" ? req.query.projectId : undefined;
|
||||
const result = await svc.list(companyId, { projectId });
|
||||
const { q, unfiled, ...filters } = listRoutinesQuerySchema.parse(req.query);
|
||||
// The responsibility filters read filed work, which is part of the Responsibilities experiment.
|
||||
if ((filters.responsibilityId || unfiled === "true")
|
||||
&& (await experimentSettings(db).getExperimental()).enableResponsibilities !== true) {
|
||||
throw responsibilitiesDisabledError();
|
||||
}
|
||||
const result = await svc.list(companyId, { ...filters, ...(q ? { query: q } : {}), ...(unfiled === "true" ? { unfiled: true } : {}) });
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
@@ -393,21 +437,18 @@ export function routineRoutes(
|
||||
}
|
||||
if (assigneeWillChange) {
|
||||
await assertBoardCanAssignTasks(req, routine.companyId);
|
||||
// Taking a routine from another agent, or handing one on, is an assignment the person must be allowed to make.
|
||||
await assertAgentCanAssign(req, routine, false);
|
||||
}
|
||||
const statusWillActivate =
|
||||
req.body.status !== undefined &&
|
||||
req.body.status === "active" &&
|
||||
routine.status !== "active";
|
||||
if (statusWillActivate) {
|
||||
if (statusWillActivate || req.body.schedule !== undefined) {
|
||||
await assertBoardCanAssignTasks(req, routine.companyId);
|
||||
await assertAgentCanAssign(req, routine, routine.assigneeAgentId === req.actor.agentId && !assigneeWillChange);
|
||||
}
|
||||
if (
|
||||
req.actor.type === "agent" &&
|
||||
req.body.assigneeAgentId !== undefined &&
|
||||
req.body.assigneeAgentId !== req.actor.agentId
|
||||
) {
|
||||
throw forbidden("Agents can only assign routines to themselves");
|
||||
}
|
||||
const actsFor = req.actor.type === "agent" ? await agentActsForRoutinePerson(req, routine) : null;
|
||||
const updated = await svc.update(routine.id, req.body, {
|
||||
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
||||
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
||||
@@ -426,6 +467,7 @@ export function routineRoutes(
|
||||
entityId: routine.id,
|
||||
details: {
|
||||
title: updated?.title ?? routine.title,
|
||||
...(actsFor ? { onBehalfOfUserId: actsFor } : {}),
|
||||
...(req.body.responsibleUserId !== undefined ? {
|
||||
previousResponsibleUserId: updated?.previousResponsibleUserId,
|
||||
responsibleUserId: updated?.responsibleUserId,
|
||||
@@ -460,6 +502,10 @@ export function routineRoutes(
|
||||
return;
|
||||
}
|
||||
await assertBoardCanAssignTasks(req, routine.companyId);
|
||||
// A restore can make the agent run the routine and turn it on: on a routine it does not run, the
|
||||
// person it acts for must be allowed to assign. (The service refuses any agent restore that would
|
||||
// hand the routine to another agent.)
|
||||
await assertAgentCanAssign(req, routine, routine.assigneeAgentId === req.actor.agentId);
|
||||
const result = await svc.restoreRevision(routine.id, req.params.revisionId as string, {
|
||||
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
||||
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
||||
@@ -503,6 +549,7 @@ export function routineRoutes(
|
||||
return;
|
||||
}
|
||||
await assertBoardCanAssignTasks(req, routine.companyId);
|
||||
await assertAgentCanAssign(req, routine, routine.assigneeAgentId === req.actor.agentId);
|
||||
// A standing check runs on its agent's heartbeat wake-ups, which only
|
||||
// happens while the responsibilities experiment is on.
|
||||
if (req.body.kind === "heartbeat" && (await instanceSettingsService(db).getExperimental()).enableResponsibilities !== true) {
|
||||
@@ -549,6 +596,7 @@ export function routineRoutes(
|
||||
return;
|
||||
}
|
||||
await assertBoardCanAssignTasks(req, routine.companyId);
|
||||
await assertAgentCanAssign(req, routine, routine.assigneeAgentId === req.actor.agentId);
|
||||
const updated = await svc.updateTrigger(trigger.id, req.body, {
|
||||
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
||||
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
||||
@@ -591,6 +639,8 @@ export function routineRoutes(
|
||||
res.status(404).json({ error: "Routine trigger not found" });
|
||||
return;
|
||||
}
|
||||
// Removing a schedule changes when the routine runs, like changing it.
|
||||
await assertAgentCanAssign(req, routine, routine.assigneeAgentId === req.actor.agentId);
|
||||
const deleted = await svc.deleteTrigger(trigger.id, {
|
||||
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
||||
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
||||
@@ -673,6 +723,8 @@ export function routineRoutes(
|
||||
return;
|
||||
}
|
||||
await assertBoardCanAssignTasks(req, routine.companyId);
|
||||
// Starting another agent's routine starts that agent's work, as an assignment does.
|
||||
await assertAgentCanAssign(req, routine, routine.assigneeAgentId === req.actor.agentId);
|
||||
const input = req.actor.type === "agent" ? { ...req.body, source: "manual" as const } : req.body;
|
||||
const run = await svc.runRoutine(routine.id, input, {
|
||||
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
||||
|
||||
@@ -124,7 +124,7 @@ Keep discussion here and leave the conversation available for the next message.
|
||||
/** Rendered only while the instance enables the Cases experiment. */
|
||||
export const CASES_CHAT_DIRECTIVE = `This instance has Cases enabled. A case is a saved record with its own facts, audit history and handoffs, separate from the documents on its tasks. Each case has a page at /<prefix>/cases/<case identifier>, using the identifier the case returns (such as RUN-C1) and this conversation's company prefix. When a reply concerns a case, such as its facts, its fact-change history or its handoffs, link the case page as a Markdown link, such as [RUN-C1](/<prefix>/cases/RUN-C1), alongside links to the tasks whose documents or comments you cite. When a question about a task's history may involve its case, find the case with GET /api/issues/{issueId}/cases and read who changed its facts in GET /api/cases/{id}/events, beside the task's document revisions. When the person opens a case from a brief, such as an attached file or a document here, save that brief as a document on the case's primary task with initialDocuments on POST /api/companies/{companyId}/case-handoffs, in the same request that creates the task, so it is saved before work starts. Case fields do not replace the brief: they hold the structured facts, and the document keeps the person's source for the assignee.`;
|
||||
/** Rendered only while the instance enables the Responsibilities experiment. */
|
||||
export const RESPONSIBILITIES_CHAT_DIRECTIVE = `This instance has areas and responsibilities enabled. A person's responsibilities are saved Paperclip records, grouped under areas, each with a bar (how success is measured) and the projects, tasks and routines filed under it; they are listed at /<prefix>/responsibilities. When the person mentions what they are responsible for or asks to map, sort or check work against their responsibilities or areas, read them first with list_responsibilities: it defaults to this person and also lists company work filed under no responsibility. Open one with get_responsibility, and check where a project, task or routine is filed with find_responsibilities_for. Do not ask the person what their responsibilities are or where they are written down before reading them; ask only when the list is empty. When they ask you to add, rename, move, file or let go of something, do it for them with create_area, update_area, create_responsibility, update_responsibility, file_under_responsibility and remove_from_responsibility, then say what you changed and that they can undo it from their Dashboard history. Prefer archiving or letting go over deleting; a delete waits for the person to accept a card. Link a responsibility with the href the tool returns.`;
|
||||
export const RESPONSIBILITIES_CHAT_DIRECTIVE = `This instance has areas and responsibilities enabled. A person's responsibilities are saved Paperclip records, grouped under areas, each with a bar (how success is measured) and the projects, tasks and routines filed under it; they are listed at /<prefix>/responsibilities. When the person mentions what they are responsible for or asks to map, sort or check work against their responsibilities or areas, read them first with list_responsibilities: it defaults to this person and also lists company work filed under no responsibility. Open one with get_responsibility, and check where a project, task or routine is filed with find_responsibilities_for. Do not ask the person what their responsibilities are or where they are written down before reading them; ask only when the list is empty. When they ask you to add, rename, move, file or let go of something, do it for them with create_area, update_area, create_responsibility, update_responsibility, file_under_responsibility and remove_from_responsibility (list_routines and update_routine for their routines), then say what you changed and that they can undo it from their Dashboard history. Prefer archiving or letting go over deleting; a delete waits for the person to accept a card. Link a responsibility with the href the tool returns.`;
|
||||
/** Rendered while the Responsibilities experiment is off, so an agent can tell "turned off" from "none". */
|
||||
export const RESPONSIBILITIES_OFF_CHAT_DIRECTIVE = RESPONSIBILITIES_OFF_GUIDANCE;
|
||||
/** Rendered only while the instance enables the Status Cards experiment. */
|
||||
|
||||
@@ -211,10 +211,10 @@ describe("PaperclipRunnerToolAuthority", () => {
|
||||
issueId,
|
||||
runId,
|
||||
});
|
||||
expect(authority.definitions()).toHaveLength(54);
|
||||
expect(authority.definitions()).toHaveLength(56);
|
||||
expect(authority.definitions().map(tool => tool.name)).toEqual(expect.arrayContaining([
|
||||
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository",
|
||||
"search_skills", "load_skill",
|
||||
"search_skills", "load_skill", "list_routines", "update_routine",
|
||||
]));
|
||||
// The read-only response export is its own tool, so call_api offers no save flag on writes.
|
||||
const save = authority.definitions().find(tool => tool.name === "save_api_response")!;
|
||||
|
||||
@@ -51,6 +51,7 @@ import { handoffPlanContext } from "./handoff-plan-context.js";
|
||||
import { callCreateSkillTool, callUpdateSkillTool } from "../skill-tools.js";
|
||||
import { callProjectTool } from "../project-tools.js";
|
||||
import { callResponsibilityTool, isResponsibilityTool, RESPONSIBILITY_TOOL_NAMES, responsibilityToolsDisabledError } from "../responsibility-tools.js";
|
||||
import { callRoutineTool, ROUTINE_TOOL_NAMES } from "../routine-tools.js";
|
||||
import { isConnectorTool, executeConnectorTool, type ConnectorAssignment } from "../connector-runtime.js";
|
||||
import { resolveNativeRuntimeMcpSnapshot } from "./runtime-context.js";
|
||||
import { connectionIntentService } from "../connection-intents.js";
|
||||
@@ -160,7 +161,7 @@ const IMPLEMENTED_OPERATIONS = new Set([
|
||||
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "create_skill", "update_skill", "create_task", "reassign_task", "set_dependencies", "create_project", "list_project_repositories", "list_projects", "register_deliverable",
|
||||
"list_documents", "read_document", "list_document_revisions", "write_document",
|
||||
"list_agents", "get_agent", "list_approvals", "get_approval", "get_approval_context",
|
||||
...RESPONSIBILITY_TOOL_NAMES,
|
||||
...RESPONSIBILITY_TOOL_NAMES, ...ROUTINE_TOOL_NAMES,
|
||||
]);
|
||||
|
||||
/** Closed first-party native Muse profile. No connector, generic API, credential or workspace grants. */
|
||||
@@ -982,6 +983,14 @@ export class PaperclipRunnerToolAuthority {
|
||||
companyId: this.binding.companyId, issueId: this.binding.issueId, agentId: this.binding.agentId,
|
||||
companyPrefix: await this.#companyPagePrefix() });
|
||||
}
|
||||
case "list_routines":
|
||||
case "update_routine": {
|
||||
const apiUrl = this.binding.apiUrl ?? process.env.PAPERCLIP_API_URL;
|
||||
const token = this.#apiToken(context);
|
||||
if (!apiUrl || !token) throw new Error("Routine tool authentication is unavailable");
|
||||
return callRoutineTool({ name: call.tool, arguments: input, apiUrl, token,
|
||||
companyId: this.binding.companyId, companyPrefix: await this.#companyPagePrefix() });
|
||||
}
|
||||
case "search_api": return withCompanyPagePaths(searchRunnerApi(call.arguments), await this.#companyPagePrefix());
|
||||
case "hire_agent": {
|
||||
return hireAgentResult(await this.#callApi(call.callId, hireAgentApiRequest(input, this.binding)), context.actor.adapterConfig?.provider);
|
||||
|
||||
@@ -58,6 +58,10 @@ function dedicatedTools(method: string, path: string): string[] {
|
||||
if (/\/companies\/\{[^}]+\}\/agent-hires$/.test(path) && method === "POST") return ["hire_agent"];
|
||||
if (/\/projects$/.test(path)) return method === "GET" ? ["list_projects"] : method === "POST" ? ["create_project"] : [];
|
||||
if (/\/project-repositories$/.test(path) && method === "GET") return ["list_project_repositories"];
|
||||
if (/\/companies\/\{[^}]+\}\/routines$/.test(path) && method === "GET") return ["list_routines"];
|
||||
if (/\/routines\/\{[^}]+\}$/.test(path) && method === "PATCH") return ["update_routine"];
|
||||
if (/\/routines\/\{[^}]+\}\/triggers$/.test(path) && method === "POST") return ["update_routine"];
|
||||
if (/\/routine-triggers\/\{[^}]+\}$/.test(path) && method === "PATCH") return ["update_routine"];
|
||||
if (/\/companies\/\{[^}]+\}\/responsibilities$/.test(path)) return method === "GET" ? ["list_responsibilities"] : method === "POST" ? ["create_responsibility"] : [];
|
||||
if (/\/companies\/\{[^}]+\}\/responsibility-areas$/.test(path)) return method === "GET" ? ["list_responsibilities"] : method === "POST" ? ["create_area"] : [];
|
||||
if (/\/responsibility-areas\/\{[^}]+\}$/.test(path)) return method === "PATCH" ? ["update_area"] : method === "DELETE" ? ["delete_area"] : [];
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import {
|
||||
ISSUE_PRIORITIES,
|
||||
ROUTINE_STATUSES,
|
||||
routineSuggestionCadenceLabel,
|
||||
routineSuggestionCadenceSchema,
|
||||
routineSuggestionCronExpression,
|
||||
type RoutineDetail,
|
||||
type RoutineListItem,
|
||||
type RoutineTrigger,
|
||||
} from "@paperclipai/shared";
|
||||
import { z } from "zod";
|
||||
import { HttpError } from "../errors.js";
|
||||
import { fetchPaperclipApi } from "./paperclip-api-loopback.js";
|
||||
|
||||
/**
|
||||
* Native agent tools for routines. Like the responsibility tools they call the
|
||||
* authenticated HTTP API with the run's agent token, so the routine routes'
|
||||
* rules apply: an agent manages its own routines and those of the person who
|
||||
* directed its run (when that person is responsible for them). A change to a
|
||||
* routine and its schedule is one routine revision the person can restore;
|
||||
* filing it under a responsibility is saved in their Dashboard history.
|
||||
*/
|
||||
export const ROUTINE_TOOL_NAMES = ["list_routines", "update_routine"] as const;
|
||||
export type RoutineToolName = (typeof ROUTINE_TOOL_NAMES)[number];
|
||||
|
||||
export function isRoutineTool(name: string): name is RoutineToolName {
|
||||
return (ROUTINE_TOOL_NAMES as readonly string[]).includes(name);
|
||||
}
|
||||
|
||||
const uuid = z.string().guid();
|
||||
|
||||
export const listRoutinesToolInput = z.object({
|
||||
query: z.string().trim().min(1).max(200).optional(),
|
||||
status: z.enum(ROUTINE_STATUSES).optional(),
|
||||
assigneeAgentId: uuid.optional(),
|
||||
projectId: uuid.optional(),
|
||||
responsibleUserId: z.string().trim().min(1).max(200).optional(),
|
||||
responsibilityId: uuid.optional(),
|
||||
unfiled: z.boolean().optional(),
|
||||
limit: z.number().int().min(1).max(200).optional().default(50),
|
||||
}).strict();
|
||||
|
||||
/** A cadence (the same one routine offers use) plus an optional IANA time zone. */
|
||||
function parseSchedule(value: unknown) {
|
||||
const { timezone, ...cadence } = z.object({ timezone: z.string().trim().min(1).max(100).optional() }).loose().parse(value);
|
||||
return { ...routineSuggestionCadenceSchema.parse(cadence), timezone };
|
||||
}
|
||||
|
||||
export const updateRoutineToolInput = z.object({
|
||||
routineId: uuid,
|
||||
title: z.string().trim().min(1).max(200).optional(),
|
||||
instructions: z.string().max(200_000).nullable().optional(),
|
||||
assigneeAgentId: uuid.nullable().optional(),
|
||||
projectId: uuid.nullable().optional(),
|
||||
status: z.enum(ROUTINE_STATUSES).optional(),
|
||||
priority: z.enum(ISSUE_PRIORITIES).optional(),
|
||||
schedule: z.unknown().optional(),
|
||||
fileUnder: uuid.optional(),
|
||||
}).strict();
|
||||
|
||||
/** What a write reports beside its body: the Dashboard version it saved, if any, and whose Dashboard it is. */
|
||||
type ApiMeta = { version?: string | null; owner?: string | null };
|
||||
type ApiCall = (method: "GET" | "POST" | "PATCH", path: string, body?: unknown, meta?: ApiMeta) => Promise<unknown>;
|
||||
|
||||
function apiCaller(input: { apiUrl: string; token: string }, fetcher: typeof fetch): ApiCall {
|
||||
return async (method, path, body, meta) => {
|
||||
const response = await fetchPaperclipApi({ ...input, method, path, body, fetcher });
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (meta) {
|
||||
meta.version = response.headers.get("x-paperclip-dashboard-version");
|
||||
meta.owner = response.headers.get("x-paperclip-dashboard-owner");
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new HttpError(response.status, typeof result?.error === "string" ? result.error : `Routine tool failed (${response.status})`,
|
||||
typeof result?.code === "string" ? { code: result.code } : undefined);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
function pageHref(prefix: string | null | undefined, path: string) {
|
||||
return prefix ? `/${encodeURIComponent(prefix)}${path}` : null;
|
||||
}
|
||||
|
||||
type ScheduleTrigger = Pick<RoutineTrigger, "id" | "kind" | "enabled" | "cronExpression" | "timezone" | "nextRunAt"> & { label?: string | null; archived?: boolean };
|
||||
|
||||
function schedules(triggers: readonly ScheduleTrigger[]) {
|
||||
return triggers.filter((trigger) => !trigger.archived).map((trigger) => ({
|
||||
triggerId: trigger.id, kind: trigger.kind, enabled: trigger.enabled,
|
||||
cronExpression: trigger.cronExpression, timezone: trigger.timezone, nextRunAt: trigger.nextRunAt,
|
||||
}));
|
||||
}
|
||||
|
||||
async function listRoutines(call: ApiCall, companyId: string, args: unknown, prefix: string | null | undefined) {
|
||||
const input = listRoutinesToolInput.parse(args);
|
||||
// Every filter runs in the routine list's query, so nothing is cut before it is matched.
|
||||
const params = new URLSearchParams();
|
||||
if (input.query) params.set("q", input.query);
|
||||
for (const key of ["status", "assigneeAgentId", "projectId", "responsibleUserId", "responsibilityId"] as const) {
|
||||
const value = input[key];
|
||||
if (value) params.set(key, value);
|
||||
}
|
||||
if (input.unfiled) params.set("unfiled", "true");
|
||||
const query = params.toString() ? `?${params}` : "";
|
||||
const matches = await call("GET", `/companies/${encodeURIComponent(companyId)}/routines${query}`) as RoutineListItem[];
|
||||
return {
|
||||
total: matches.length,
|
||||
routines: matches.slice(0, input.limit).map((routine) => ({
|
||||
id: routine.id,
|
||||
title: routine.title,
|
||||
status: routine.status,
|
||||
assigneeAgentId: routine.assigneeAgentId,
|
||||
projectId: routine.projectId,
|
||||
responsibleUserId: routine.responsibleUserId,
|
||||
triggers: schedules(routine.triggers),
|
||||
lastRun: routine.lastRun ? { status: routine.lastRun.status, at: routine.lastRun.triggeredAt } : null,
|
||||
href: pageHref(prefix, `/routines/${encodeURIComponent(routine.id)}`),
|
||||
})),
|
||||
truncated: matches.length > input.limit,
|
||||
};
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
async function updateRoutine(call: ApiCall, args: unknown, prefix: string | null | undefined) {
|
||||
const input = updateRoutineToolInput.parse(args);
|
||||
const schedule = input.schedule === undefined || input.schedule === null ? input.schedule : parseSchedule(input.schedule);
|
||||
const id = encodeURIComponent(input.routineId);
|
||||
const before = await call("GET", `/routines/${id}`) as RoutineDetail;
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (input.title !== undefined) patch.title = input.title;
|
||||
if (input.instructions !== undefined) patch.description = input.instructions;
|
||||
for (const key of ["assigneeAgentId", "projectId", "status", "priority"] as const) {
|
||||
if (input[key] !== undefined) patch[key] = input[key];
|
||||
}
|
||||
if (schedule !== undefined) {
|
||||
// Without a zone the server keeps the current schedule's, else uses the person's own.
|
||||
patch.schedule = schedule === null ? null
|
||||
: { cronExpression: routineSuggestionCronExpression(schedule), ...(schedule.timezone ? { timezone: schedule.timezone } : {}) };
|
||||
}
|
||||
if (Object.keys(patch).length === 0 && !input.fileUnder) {
|
||||
throw new HttpError(422, "Send at least one field to change");
|
||||
}
|
||||
// The fields and the schedule are one change and one revision; a change made since `before` makes it fail instead of mixing.
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await call("PATCH", `/routines/${id}`, { ...patch, baseRevisionId: before.latestRevisionId });
|
||||
}
|
||||
// Filing is a separate change in the person's Dashboard history. If it fails after the routine changed, say what was saved.
|
||||
let filedUnder: Record<string, unknown> | null = null;
|
||||
if (input.fileUnder) {
|
||||
const meta: ApiMeta = {};
|
||||
try {
|
||||
await call("POST", `/responsibilities/${encodeURIComponent(input.fileUnder)}/file`, { items: [{ kind: "routine", id: input.routineId }] }, meta);
|
||||
filedUnder = {
|
||||
responsibilityId: input.fileUnder,
|
||||
undo: meta.version
|
||||
? "Saved as a version in the Dashboard history of the person in dashboardOwnerUserId, where they can undo it; remove_from_responsibility also unfiles it."
|
||||
: "Not in the person's Dashboard history; remove_from_responsibility unfiles it.",
|
||||
...(meta.version ? { dashboardVersionId: meta.version, dashboardOwnerUserId: meta.owner ?? null } : {}),
|
||||
};
|
||||
} catch (error) {
|
||||
if (Object.keys(patch).length === 0) throw error;
|
||||
filedUnder = { responsibilityId: input.fileUnder, failed: true, error: errorMessage(error), note: "The routine change above was saved; only the filing failed." };
|
||||
}
|
||||
}
|
||||
const after = await call("GET", `/routines/${id}`) as RoutineDetail;
|
||||
const enabledSchedules = (triggers: readonly ScheduleTrigger[]) =>
|
||||
triggers.filter((trigger) => trigger.kind === "schedule" && trigger.enabled && !trigger.archived);
|
||||
const current = enabledSchedules(after.triggers)[0];
|
||||
return {
|
||||
routine: {
|
||||
id: after.id, title: after.title, status: after.status, assigneeAgentId: after.assigneeAgentId,
|
||||
projectId: after.projectId, priority: after.priority, responsibleUserId: after.responsibleUserId,
|
||||
triggers: schedules(after.triggers), revision: after.latestRevisionNumber,
|
||||
href: pageHref(prefix, `/routines/${encodeURIComponent(after.id)}`),
|
||||
},
|
||||
...(schedule === null ? { schedule: { turnedOff: enabledSchedules(before.triggers).length } } : {}),
|
||||
...(schedule && current ? {
|
||||
schedule: { label: routineSuggestionCadenceLabel(schedule), cronExpression: current.cronExpression, timezone: current.timezone },
|
||||
} : {}),
|
||||
...(filedUnder ? { filedUnder } : {}),
|
||||
...(after.latestRevisionNumber !== before.latestRevisionNumber ? {
|
||||
undo: `The routine${schedule !== undefined ? " and its schedule" : ""} saved as revision ${after.latestRevisionNumber}; restoring revision ${before.latestRevisionNumber} from the routine's history undoes that${input.fileUnder ? " (not the filing; see filedUnder)" : ""}.`,
|
||||
} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** All transports use the normal authenticated API, including its validation and audit path. */
|
||||
export async function callRoutineTool(input: {
|
||||
name: RoutineToolName;
|
||||
arguments: Record<string, unknown>;
|
||||
apiUrl: string;
|
||||
token: string;
|
||||
companyId: string;
|
||||
/** The company's issue prefix; results then carry page hrefs. */
|
||||
companyPrefix?: string | null;
|
||||
}, fetcher: typeof fetch = fetch) {
|
||||
const call = apiCaller(input, fetcher);
|
||||
switch (input.name) {
|
||||
case "list_routines": return listRoutines(call, input.companyId, input.arguments, input.companyPrefix);
|
||||
case "update_routine": return updateRoutine(call, input.arguments, input.companyPrefix);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { verifyAppWebhook } from "./app-webhook.js";
|
||||
import { authenticateWebhookCreationRun, validateCreationRun } from "./task-creation-provenance.js";
|
||||
import crypto from "node:crypto";
|
||||
import { verifyFirefliesWebhook } from "./fireflies-webhook.js";
|
||||
import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, ne, not, or, sql } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, ne, not, or, sql, type SQL } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
@@ -28,12 +28,15 @@ import {
|
||||
pluginManagedResources,
|
||||
plugins,
|
||||
projects,
|
||||
responsibilities,
|
||||
responsibilityLinks,
|
||||
routineRevisions,
|
||||
routineRuns,
|
||||
routineDocuments,
|
||||
routines,
|
||||
routineTriggers,
|
||||
routineWebhookTestReceipts,
|
||||
userWorkspacePreferences,
|
||||
} from "@paperclipai/db";
|
||||
import type {
|
||||
CreateRoutine,
|
||||
@@ -1035,6 +1038,64 @@ export function routineService(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes `schedule` the routine's one enabled schedule trigger, reusing its
|
||||
* first one, or turns every schedule off for null. Runs under the routine's
|
||||
* lock, so two changes cannot both add a schedule. Returns whether anything
|
||||
* changed; the caller saves the revision.
|
||||
*/
|
||||
async function replaceSchedule(
|
||||
txDb: Db,
|
||||
routine: Pick<RoutineRow, "id" | "companyId" | "responsibleUserId">,
|
||||
requested: { cronExpression: string; timezone?: string } | null,
|
||||
actor: Actor,
|
||||
) {
|
||||
const existing = await txDb.select().from(routineTriggers)
|
||||
.where(and(eq(routineTriggers.routineId, routine.id), eq(routineTriggers.kind, "schedule"), eq(routineTriggers.archived, false)))
|
||||
.orderBy(desc(routineTriggers.enabled), asc(routineTriggers.createdAt), asc(routineTriggers.id));
|
||||
const now = new Date();
|
||||
const by = { updatedByAgentId: actor.agentId ?? null, updatedByUserId: actor.userId ?? null, updatedAt: now };
|
||||
let changed = false;
|
||||
const [first] = existing;
|
||||
const keep = requested ? first?.id ?? null : null;
|
||||
if (requested) {
|
||||
// A time with no zone keeps the current schedule's, else is in the responsible person's own zone.
|
||||
const known = requested.timezone || first?.timezone || null;
|
||||
const timezone = known ?? (!routine.responsibleUserId ? null : await txDb
|
||||
.select({ timeZone: userWorkspacePreferences.timeZone })
|
||||
.from(userWorkspacePreferences)
|
||||
.where(eq(userWorkspacePreferences.userId, routine.responsibleUserId))
|
||||
.then((rows) => rows[0]?.timeZone ?? null));
|
||||
if (!timezone) {
|
||||
throw unprocessable("Name a time zone for this schedule: the routine has no schedule yet and its person has no time zone saved");
|
||||
}
|
||||
assertTimeZone(timezone);
|
||||
const schedule = { cronExpression: requested.cronExpression, timezone };
|
||||
const nextRunAt = nextCronTickInTimeZone(schedule.cronExpression, schedule.timezone, now);
|
||||
if (!first) {
|
||||
await txDb.insert(routineTriggers).values({
|
||||
companyId: routine.companyId, routineId: routine.id, kind: "schedule", label: null, enabled: true,
|
||||
cronExpression: schedule.cronExpression, timezone: schedule.timezone, nextRunAt,
|
||||
createdByAgentId: actor.agentId ?? null, createdByUserId: actor.userId ?? null,
|
||||
updatedByAgentId: actor.agentId ?? null, updatedByUserId: actor.userId ?? null,
|
||||
});
|
||||
changed = true;
|
||||
} else if (!first.enabled || first.cronExpression !== schedule.cronExpression || first.timezone !== schedule.timezone) {
|
||||
await txDb.update(routineTriggers)
|
||||
.set({ enabled: true, cronExpression: schedule.cronExpression, timezone: schedule.timezone, nextRunAt, ...by })
|
||||
.where(eq(routineTriggers.id, first.id));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
// One schedule: the others are turned off (a restore can turn them back on), so it does not also run at an old time.
|
||||
const turnOff = existing.filter((trigger) => trigger.enabled && trigger.id !== keep).map((trigger) => trigger.id);
|
||||
if (turnOff.length > 0) {
|
||||
await txDb.update(routineTriggers).set({ enabled: false, ...by }).where(inArray(routineTriggers.id, turnOff));
|
||||
changed = true;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
async function assertRoutineAccess(companyId: string, routineId: string) {
|
||||
const routine = await getRoutineById(routineId);
|
||||
if (!routine) throw notFound("Routine not found");
|
||||
@@ -2110,10 +2171,36 @@ export function routineService(
|
||||
|
||||
list: async (
|
||||
companyId: string,
|
||||
filters?: { projectId?: string | null },
|
||||
filters?: {
|
||||
projectId?: string | null;
|
||||
/** Words in the title or description, ignoring case. */
|
||||
query?: string;
|
||||
status?: string;
|
||||
assigneeAgentId?: string;
|
||||
responsibleUserId?: string;
|
||||
/** Filed under this responsibility, directly or through its project. */
|
||||
responsibilityId?: string;
|
||||
/** Filed under no proposed or active responsibility, directly or through its project. */
|
||||
unfiled?: boolean;
|
||||
},
|
||||
): Promise<RoutineListItem[]> => {
|
||||
const conditions = [eq(routines.companyId, companyId)];
|
||||
if (filters?.projectId) conditions.push(eq(routines.projectId, filters.projectId));
|
||||
if (filters?.query) {
|
||||
const pattern = `%${filters.query.replace(/[\\%_]/g, (char) => `\\${char}`)}%`;
|
||||
conditions.push(or(sql`${routines.title} ilike ${pattern}`, sql`coalesce(${routines.description}, '') ilike ${pattern}`)!);
|
||||
}
|
||||
if (filters?.status) conditions.push(eq(routines.status, filters.status));
|
||||
if (filters?.assigneeAgentId) conditions.push(eq(routines.assigneeAgentId, filters.assigneeAgentId));
|
||||
if (filters?.responsibleUserId) conditions.push(eq(routines.responsibleUserId, filters.responsibleUserId));
|
||||
// The same "filed" rule as a responsibility's detail and its loose work: a link to the routine or to its project.
|
||||
const filedUnder = (responsibility: SQL) => sql`exists (
|
||||
select 1 from ${responsibilityLinks} fl
|
||||
join ${responsibilities} fr on fr.id = fl.responsibility_id
|
||||
where ${responsibility} and fr.company_id = ${companyId}
|
||||
and (fl.routine_id = ${routines.id} or (${routines.projectId} is not null and fl.project_id = ${routines.projectId})))`;
|
||||
if (filters?.responsibilityId) conditions.push(filedUnder(sql`fr.id = ${filters.responsibilityId}`));
|
||||
if (filters?.unfiled) conditions.push(sql`not ${filedUnder(sql`fr.status in ('proposed', 'active')`)}`);
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
@@ -2517,6 +2604,12 @@ export function routineService(
|
||||
if (patch.goalId) await assertGoal(existing.companyId, patch.goalId);
|
||||
if (patch.parentIssueId) await assertParentIssue(existing.companyId, patch.parentIssueId);
|
||||
assertRoutineVariableDefinitions(nextVariables);
|
||||
if (patch.schedule) {
|
||||
if (patch.schedule.timezone) assertTimeZone(patch.schedule.timezone);
|
||||
const cronError = validateCron(patch.schedule.cronExpression);
|
||||
if (cronError) throw unprocessable(cronError);
|
||||
assertScheduleCompatibleVariables(nextVariables);
|
||||
}
|
||||
const enabledScheduleTriggers = await db
|
||||
.select({ id: routineTriggers.id })
|
||||
.from(routineTriggers)
|
||||
@@ -2604,8 +2697,12 @@ export function routineService(
|
||||
updatedByUserId: actor.userId ?? null,
|
||||
};
|
||||
|
||||
// The schedule changes under the same lock and in the same revision as the fields.
|
||||
// With the routine as it will be saved, so a schedule without a zone uses the new responsible person's.
|
||||
const scheduleChanged = patch.schedule !== undefined && await replaceSchedule(txDb, candidate, patch.schedule, actor);
|
||||
const fieldsMatch = routineCurrentFieldsMatch(locked, candidate);
|
||||
const folderChanged = patch.folderId !== undefined && locked.folderId !== candidate.folderId;
|
||||
if (locked.latestRevisionId && routineCurrentFieldsMatch(locked, candidate)) {
|
||||
if (locked.latestRevisionId && fieldsMatch && !scheduleChanged) {
|
||||
if (!folderChanged) return locked;
|
||||
const [updated] = await txDb
|
||||
.update(routines)
|
||||
@@ -2673,7 +2770,7 @@ export function routineService(
|
||||
.returning();
|
||||
if (!updated) return null;
|
||||
const { routine } = await appendRoutineRevision(txDb, updated, actor, {
|
||||
changeSummary: "Updated routine",
|
||||
changeSummary: !scheduleChanged ? "Updated routine" : fieldsMatch ? "Updated schedule" : "Updated routine and schedule",
|
||||
});
|
||||
if (patch.env !== undefined) {
|
||||
await secretsSvc.syncEnvBindingsForTarget(
|
||||
|
||||
Reference in new issue
Block a user