Files
PaperClipAI/server/src/__tests__/routine-tools.test.ts
T
b7319eb581 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>
2026-11-19 09:30:03 -06:00

131 lines
8.0 KiB
TypeScript

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/);
});
});