Files
PaperClipAI/packages/shared/src/routine-suggestions.ts
T
43b2d8be22 feat(dashboard): add an experimental areas and responsibilities dashboard (#22069)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The dashboard is the first page a person sees in a company
> - The classic dashboard shows agents, runs, costs and recent tasks
> - It does not show what the person is responsible for, or if that work
goes well
> - People think in areas, such as Fundraising or Customers, and in the
things they own in each area
> - This pull request adds a dashboard built on areas and
responsibilities, behind an experimental setting that is off by default
> - The benefit is that a person sees what they own, how it is going,
and what agents do for it, on one page

## Linked Issues or Issue Description

No public issue exists for this work. The description follows the
feature request template.

**Subsystem affected**

Dashboard, navigation, the task conversation, routines, and the instance
experimental settings.

**Problem or motivation**

The classic dashboard counts agents and tasks. It does not say what a
person owns or if it goes well. People who run a company with agents
want to see their areas, the responsibilities in each area, the bar each
one must meet, and the agents and routines that serve it.

**Proposed solution**

A person owns responsibilities. Each responsibility belongs to an area
and has a bar, a number to reach. Projects, tasks and routines link to a
responsibility, and the page shows its status from those links. An agent
can interview the person and draft the dashboard. The person accepts or
declines each change, and any change can be undone from a saved version.

**Alternatives considered**

Add the same data to the classic dashboard. That page is a fixed set of
cards for company activity, so a second, person-centred page is clearer.
The setting lets a person pick one of the two.

**Roadmap alignment**

This is an experimental feature behind `enableResponsibilities`. It is
off by default and changes nothing for a person who leaves it off.

## What Changed

- Add the setting "Areas & Responsibilities dashboard"
(`enableResponsibilities`, off by default). On, Dashboard in the sidebar
opens the new page, and the classic dashboard link is not shown in the
sidebars or the command palette. Off, nothing changes.
- Add tables and migrations 0492 to 0497 for areas, responsibilities,
links to work, metrics, status reports, saved dashboard versions, and
model-call records for summaries.
- Add the API: areas, responsibilities, links, bars, metrics, status
reports, summaries, runs, automation, and the dashboard conversation
with versions and undo. Each route checks company access and writes to
the activity log.
- Add four task conversations with an agent: about a bar, about an
automation, about a routine, and about the whole dashboard. The agent
proposes a change. Nothing applies until a person accepts it.
- Add standing checks: routines that an agent carries out on its
heartbeat and reports.
- Add the Dashboard page: search, counts, areas that open and close, a
primary New area button, and a message box at the bottom of the page.
Add the responsibility page with its bar, metrics, work and routines.
- Add the Paperclip skill sections and runner API entries that let an
agent use these routes. The runner skill inventory is regenerated (166
to 174 rows).
- Keep the new runner API tests in their own file so
`runner-api.test.ts` stays at 985 lines.
- Onboarding is not changed. The onboarding changes that build on this
work are a separate pull request.

## Verification

- Type checks pass for `packages/db`, `packages/shared`, `server` (all
layers) and `ui`.
- `pnpm --filter @paperclipai/db check:migrations` passes. A new
`drizzle-kit generate` run produces no further change.
- Tests for every changed file pass: 26 server test files (3,009 tests),
116 UI test files (1,991 tests) and 28 shared test files (432 tests).
- The runner capability inventory checks pass.
- I started the app on a local database that already held earlier data.
Master's new migrations and these migrations applied without error. With
the setting on, the Dashboard and a responsibility page loaded with no
console or server errors. The More menu and the command palette show one
Dashboard.
- I did not run `pnpm verify`, the full local suite, or the browser
suites. Required CI covers them.
- The agent conversations are tested with simulated agents. No real
model has run them.

## Risks

- Medium. The change is large, and the setting is off by default. With
it off, the new routes refuse requests and the UI is unchanged.
- Migrations only add tables and columns. Two replace a CHECK
constraint, and one builds an index `CONCURRENTLY`. These two have the
`online_compatible` override with a reason in the file, and the second
one is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`.
- Master can add migrations before this merges. The migrations then need
new numbers.
- `responsibilities.ts` (1,663 lines), `responsibility-summaries.ts`
(1,239 lines) and one Storybook fixture file (1,305 lines) are new files
over 1,000 lines. They each keep one cohesive unit together: the service
for one table family, the model-call path for summaries, and the
fixtures that the stories share. No existing file crosses 1,000 lines.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude: Claude Fable 5.2 (`claude-fable-5-2`) wrote most of
the change, with Claude Sonnet 5.5 (`claude-sonnet-5-5`) for the final
steps. Both used tool use, code execution and browser checks.

## 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
- [ ] 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Scott Tong <scott@scottsmbpm5max.lan>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 20:45:44 -08:00

219 lines
8.9 KiB
TypeScript

import { z } from "zod";
/**
* Routine suggestions: after an agent finishes a task that plausibly recurs,
* it may offer, once, to repeat that task on a schedule. The offer is a
* `suggest_routine` conversation card on the finished task; accepting it
* creates a routine with the task's agent and project. Experimental, behind
* `enableResponsibilities`.
*
* The agent describes the cadence in a small structured form; the server
* derives the schedule expression and the plain-words label from it, so the
* words a person reads always match what will run.
*/
export const ROUTINE_SUGGESTION_FREQUENCIES = ["daily", "weekdays", "weekly", "monthly"] as const;
export type RoutineSuggestionFrequency = (typeof ROUTINE_SUGGESTION_FREQUENCIES)[number];
/** Index order matches cron day-of-week numbering (0 = Sunday). */
export const ROUTINE_SUGGESTION_WEEKDAYS = [
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
] as const;
export type RoutineSuggestionWeekday = (typeof ROUTINE_SUGGESTION_WEEKDAYS)[number];
/** Monthly suggestions stay on days every month has. */
export const ROUTINE_SUGGESTION_MAX_DAY_OF_MONTH = 28;
export interface RoutineSuggestionCadence {
frequency: RoutineSuggestionFrequency;
/** Required for `weekly`; ignored otherwise. */
dayOfWeek?: RoutineSuggestionWeekday | null;
/** Required for `monthly` (1-28); ignored otherwise. */
dayOfMonth?: number | null;
/** Wall-clock time in the accepting person's time zone, 24-hour `HH:MM`. */
time: string;
}
export interface SuggestRoutinePayload {
version: 1;
/** What would repeat; becomes the routine title. */
title: string;
/** What each run should do; becomes the routine description. */
instructions: string;
/** The agent's short, plain-words offer shown on the card. */
message: string | null;
cadence: RoutineSuggestionCadence;
/** Server-derived from `cadence`, for example "Every Monday at 9 AM". */
cadenceLabel: string;
/** Server-derived five-field schedule expression. */
cronExpression: string;
/** Copied from the task when the offer is made. */
assigneeAgentId: string;
projectId: string | null;
}
export const SUGGEST_ROUTINE_OUTCOMES = [
"accepted",
"declined",
"withdrawn",
"issue_closed",
"addressee_deleted",
"skipped",
] as const;
export type SuggestRoutineOutcome = (typeof SUGGEST_ROUTINE_OUTCOMES)[number];
export interface SuggestRoutineResult {
version: 1;
outcome: SuggestRoutineOutcome;
reason?: string | null;
/** Set once an accepted offer's routine exists. */
routineId?: string | null;
routineTitle?: string | null;
cadenceLabel?: string | null;
timezone?: string | null;
/** Responsibilities the new routine was filed under (empty when the task was loose). */
responsibilityIds?: string[];
}
const HH_MM = /^([01]\d|2[0-3]):([0-5]\d)$/;
export const routineSuggestionCadenceSchema = z
.object({
frequency: z.enum(ROUTINE_SUGGESTION_FREQUENCIES),
dayOfWeek: z.enum(ROUTINE_SUGGESTION_WEEKDAYS).optional().nullable(),
dayOfMonth: z.number().int().min(1).max(ROUTINE_SUGGESTION_MAX_DAY_OF_MONTH).optional().nullable(),
time: z.string().regex(HH_MM, "time must be 24-hour HH:MM, for example 09:00"),
})
.strict()
.superRefine((value, ctx) => {
if (value.frequency === "weekly" && !value.dayOfWeek) {
ctx.addIssue({ code: "custom", path: ["dayOfWeek"], message: "A weekly routine needs dayOfWeek" });
}
if (value.frequency === "monthly" && !value.dayOfMonth) {
ctx.addIssue({ code: "custom", path: ["dayOfMonth"], message: "A monthly routine needs dayOfMonth (1-28)" });
}
});
// A scheduled routine cannot ask for run inputs, so the offered text must not
// contain routine variable placeholders.
const NO_PLACEHOLDERS = (value: string) => !value.includes("{{");
const NO_PLACEHOLDERS_MESSAGE = "Write the text out in full; scheduled routines cannot use {{placeholders}}";
/** Body an agent sends to offer a routine for the task it just finished. */
export const createRoutineSuggestionSchema = z
.object({
title: z.string().trim().min(1).max(200).refine(NO_PLACEHOLDERS, NO_PLACEHOLDERS_MESSAGE),
instructions: z.string().trim().min(1).max(10_000).refine(NO_PLACEHOLDERS, NO_PLACEHOLDERS_MESSAGE),
cadence: routineSuggestionCadenceSchema,
message: z.string().trim().min(1).max(500).optional().nullable(),
})
.strict();
export type CreateRoutineSuggestion = z.infer<typeof createRoutineSuggestionSchema>;
/** Accepting may name the person's IANA time zone; the schedule runs in it. */
export const acceptRoutineSuggestionSchema = z
.object({
timezone: z.string().trim().min(1).max(100).optional(),
})
.strict();
export type AcceptRoutineSuggestion = z.infer<typeof acceptRoutineSuggestionSchema>;
export const declineRoutineSuggestionSchema = z.object({}).strict();
export type DeclineRoutineSuggestion = z.infer<typeof declineRoutineSuggestionSchema>;
export const suggestRoutinePayloadSchema = z.object({
version: z.literal(1),
title: z.string(),
instructions: z.string(),
message: z.string().nullable(),
cadence: routineSuggestionCadenceSchema,
cadenceLabel: z.string(),
cronExpression: z.string(),
assigneeAgentId: z.string(),
projectId: z.string().nullable(),
});
export const suggestRoutineResultSchema = z.object({
version: z.literal(1),
outcome: z.enum(SUGGEST_ROUTINE_OUTCOMES),
reason: z.string().nullable().optional(),
routineId: z.string().nullable().optional(),
routineTitle: z.string().nullable().optional(),
cadenceLabel: z.string().nullable().optional(),
timezone: z.string().nullable().optional(),
responsibilityIds: z.array(z.string()).optional(),
});
function normalizedCadence(cadence: RoutineSuggestionCadence) {
const [hour, minute] = cadence.time.split(":").map((part) => Number(part));
return { ...cadence, hour: hour!, minute: minute! };
}
/** Five-field cron for a cadence, evaluated in the routine trigger's time zone. */
export function routineSuggestionCronExpression(cadence: RoutineSuggestionCadence): string {
const { frequency, hour, minute, dayOfWeek, dayOfMonth } = normalizedCadence(cadence);
switch (frequency) {
case "daily":
return `${minute} ${hour} * * *`;
case "weekdays":
return `${minute} ${hour} * * 1-5`;
case "weekly":
return `${minute} ${hour} * * ${ROUTINE_SUGGESTION_WEEKDAYS.indexOf(dayOfWeek!)}`;
case "monthly":
return `${minute} ${hour} ${dayOfMonth} * *`;
}
}
function clockLabel(hour: number, minute: number) {
const suffix = hour < 12 ? "AM" : "PM";
const hour12 = hour % 12 === 0 ? 12 : hour % 12;
return minute === 0 ? `${hour12} ${suffix}` : `${hour12}:${String(minute).padStart(2, "0")} ${suffix}`;
}
function ordinal(day: number) {
const mod100 = day % 100;
if (mod100 >= 11 && mod100 <= 13) return `${day}th`;
switch (day % 10) {
case 1: return `${day}st`;
case 2: return `${day}nd`;
case 3: return `${day}rd`;
default: return `${day}th`;
}
}
/** Plain words for a cadence, for example "Every Monday at 9 AM". */
export function routineSuggestionCadenceLabel(cadence: RoutineSuggestionCadence): string {
const { frequency, hour, minute, dayOfWeek, dayOfMonth } = normalizedCadence(cadence);
const at = `at ${clockLabel(hour, minute)}`;
switch (frequency) {
case "daily":
return `Every day ${at}`;
case "weekdays":
return `Every weekday ${at}`;
case "weekly":
return `Every ${dayOfWeek!.charAt(0).toUpperCase()}${dayOfWeek!.slice(1)} ${at}`;
case "monthly":
return `On the ${ordinal(dayOfMonth!)} of every month ${at}`;
}
}
/**
* Standing instruction added to a task's prompt while routine suggestions are
* enabled (legacy adapters and native runners alike). Keep it short: it rides
* on every eligible task.
*/
export function routineSuggestionAgentGuidance(issueId: string): string {
return [
"When you finish this task, decide whether the person will plausibly want the same work again on a schedule: a recurring report, check, digest, follow-up or reconciliation, output that goes stale, or they asked for it periodically.",
`If so, offer once to repeat it as a routine with POST /api/issues/${issueId}/routine-suggestions and { title, instructions, cadence: { frequency: daily | weekdays | weekly | monthly, dayOfWeek for weekly (monday..sunday), dayOfMonth for monthly (1-28), time "HH:MM" in the person's local time }, message }. Do it right after your completion message and marking the task done, or just before finish_task.`,
"instructions must say in full what each run should do; message is one plain sentence in your voice that says task and routine, never issue or scheduling internals.",
"Do not offer for one-off work (a fix, build, migration, single document or decision, one-time research, setup) or when unsure. The person accepts or declines in the task conversation and you are not woken by the answer. A 409, 404 or 422 means no offer is possible here; carry on without it.",
].join(" ");
}