mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-20 09:50:48 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - People keep their areas and responsibilities in Paperclip (experimental, `enableResponsibilities`). #22253 lets agents read them. > - Agents can still only propose. They cannot rename or archive an area, change an active responsibility, let one go, or move work between responsibilities in one step. > - A person who says "file my weekly routines under Sales" must then do it by hand. > - The maintainer chose this rule: an agent may make each change that its person could make, the person can undo it from the Dashboard history, and a permanent delete still needs the person's yes on a card. > - This pull request adds eight change tools and the server rules behind them. > - The benefit is that an agent maps work to responsibilities for the person, and the person keeps control through undo and the delete card. ## Linked Issues or Issue Description Refs #22253 (phase 1; this pull request is stacked on it). **Subsystem affected** Server (responsibility and area routes, Dashboard versions, native runner tool authority), shared validators and Dashboard types, the native runner tool catalog, the `paperclip` skill, and the Dashboard history UI. **Problem or motivation** An agent that works for a person can only propose areas and responsibilities. It cannot change active ones, archive or delete them, or move filed work in one step. Unfiling needs link IDs. There is no way for the person to undo an agent's change. **Proposed solution** When an agent acts for the person its run works for (`onBehalfOfUserId`) and that person directed the run (the run's own task is one they made, such as their chat, or their own message woke it; parent tasks do not count), apply that person's own rights: their own responsibilities, or anyone's for a company owner or admin; areas for any active member. Save each such change as a version of the person's Dashboard, so the existing history and Undo line show it under the agent's name. Make a permanent delete wait for an accepted confirmation card that the agent posted. Add `file` and `unfile` routes that take items by kind and ID, with an optional move. **Alternatives considered** One card for every change, or propose-only. The maintainer chose "act for me, with undo". A separate undo journal would need a new table and a new UI; Dashboard versions already have both. A new version cause needs a check-constraint migration; this change uses `change_set` with no `interactionId` instead. ## What Changed - Add tools `create_area`, `update_area`, `delete_area`, `create_responsibility`, `update_responsibility`, `delete_responsibility`, `file_under_responsibility` and `remove_from_responsibility`. They are standard-mode only and hidden while Responsibilities is off. - Add the writer rule for agents in `routes/agent-person-authz.ts` (`agentPersonInCompany`, `agentActsForResponsibilityOwner`), used by `routes/responsibilities.ts` and `routes/responsibility-areas.ts`. The person must have directed the run: a person can name anyone as a task's responsible person, and a run can also work for a routine's person or the company default, so those runs do not borrow that person's rights. An agent with no such person keeps the old propose-only rules. - The response names only the version of the responsibility's owner (for area changes, the acting person's), and `X-Paperclip-Dashboard-Owner` says whose history holds it; tools return `dashboardOwnerUserId`. A change Undo cannot reverse (the name, description, order or un-archiving of an area other people's proposed or active responsibilities share) saves no version and is not reported as undoable. - `/file` without `moveFrom` follows the `/links` rule, so `create_responsibility` with `fileItems` works for a proposal. - A title-only create is allowed for an acting agent. It is active by default and records the agent in `proposedByAgentId`. - Add `responsibility-agent-changes.ts`. In one transaction that holds each affected owner's Dashboard lock, it saves the dashboard before the change (when a person changed it by hand), runs the change on services bound to that transaction, and saves the result as a `change_set` version by that agent. The response names the version in `X-Paperclip-Dashboard-Version`. The tools say Undo only when a version was saved. - Dashboard snapshots now also hold each responsibility's filed items, description, "run by" agent, evidence, health override and note, and each area's description (optional fields). Restore puts them back. Older versions still restore as before. A matching older version is upgraded in place, so the first change after it compares and undoes in full. - Create and update accept `areaTitle`. The server finds or makes that area in the same transaction, so a refused change leaves no area. Agent creates reuse a live responsibility with the same title under a lock, so retries and parallel calls make no copies. - Add `POST /api/responsibilities/:id/file` (`items`, optional `moveFrom`: an ID or `all`) and `POST /api/responsibilities/:id/unfile` (`items`), each in one transaction. - Agent deletes need `confirmationId`: an accepted `request_confirmation` card that this agent posted, with target key `responsibility-delete:<id>` or `responsibility-area-delete:<id>`. Someone who may manage the owner must accept it, on the card or by a verified chat reply. The tools post the card (named after the item), return `awaiting_confirmation`, and delete on the next call after acceptance. - `DELETE /api/responsibility-areas/:id` accepts `moveResponsibilitiesTo`. Area changes and deletes save versions for everyone whose Dashboard shows the area. - Agent activity details now include `onBehalfOfUserId`. The Dashboard history shows "<agent>, for you" for these versions. `ResponsibilityDashboardVersionSummary` now has `interactionId`. - Update the OpenAPI registry and metadata, the `search_api` tool pointers, the skill, the API reference, the chat directive, the operation-groups spec, and the pinned counts and SDK source pins. ## Verification - Server: `vitest run` of the `responsibilit*` tests, `responsibility-tools.test.ts`, `openapi-routes`, `runner-api*`, `paperclip-runner-tool-authority` and `task-markdown` all pass. New tests cover these cases: acting-agent create, update and undo; file, move and undo; the rule for a person who may not manage the owner; delete only after an accepted card, including a verified chat reply; area delete with move and a version for the other owner; undo of a health override, an area description and an un-archived empty area; upgrade of an older version; an area by title that a refused change rolls back; parallel creates. - UI: `DashboardEditModule.test.tsx` and `responsibility-dashboard.test.ts` passed. `pnpm --filter @paperclipai/ui typecheck` passed. - Server `node scripts/typecheck-layers.mjs` passed. - Runner: catalog, semantic-tool, eval, protocol-action and permission-policy tests (284) passed. All generator checks pass. - I did not run the browser e2e suite locally. ## Risks - Medium. Agents that work for a person can now change and archive that person's responsibilities and areas without a card. Every change is a Dashboard version that the person can restore, and a delete still needs the card. - Undo restores titles, sentences, areas, order, status, filed items, description and the "run by" agent. It does not restore a bar or metric change; those stay in the metric history. - A restore of a version from before this change does not touch filed items, which matches the earlier behavior. - Undo of a rename or archive of an area that other people also use keeps its name, as the existing restore rule does for shared areas. - Manual edits do not take the Dashboard lock. A person's edit that commits while an agent's change is open can appear in that agent's version. - Changes to proposed or let-go responsibilities are not on a Dashboard, so they cannot be undone there. The tools say so. ## 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>
139 lines
7.1 KiB
TypeScript
139 lines
7.1 KiB
TypeScript
import { and, eq } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { companyMemberships, issueComments, issueThreadInteractions } from "@paperclipai/db";
|
|
import { forbidden } from "../errors.js";
|
|
import { lockDashboard, responsibilityDashboardVersionService } from "./responsibility-dashboard-versions.js";
|
|
|
|
/** Names the Dashboard version an agent's change saved, so the agent can say it can be undone. */
|
|
export const DASHBOARD_VERSION_HEADER = "X-Paperclip-Dashboard-Version";
|
|
/** Whose Dashboard history holds the version in `DASHBOARD_VERSION_HEADER`. */
|
|
export const DASHBOARD_OWNER_HEADER = "X-Paperclip-Dashboard-Owner";
|
|
|
|
/**
|
|
* An `onVersion` that names only `ownerUserId`'s version in the response. A
|
|
* change can also save versions of other people's Dashboards (a move between
|
|
* owners, an area they use); those stay in their own histories.
|
|
*/
|
|
export function reportVersionOf(res: { setHeader(name: string, value: string): unknown }, ownerUserId: string) {
|
|
return (versionId: string, owner: string) => {
|
|
if (owner !== ownerUserId) return;
|
|
res.setHeader(DASHBOARD_VERSION_HEADER, versionId);
|
|
res.setHeader(DASHBOARD_OWNER_HEADER, owner);
|
|
};
|
|
}
|
|
|
|
/** The confirmation card key that authorizes deleting one responsibility or area. */
|
|
export function responsibilityDeletionKey(kind: "responsibility" | "area", id: string) {
|
|
return kind === "responsibility" ? `responsibility-delete:${id}` : `responsibility-area-delete:${id}`;
|
|
}
|
|
|
|
/**
|
|
* Changes an agent makes for a person with its responsibility tools
|
|
* (experimental `enableResponsibilities`). Each one is saved as a version of
|
|
* the Dashboards it changes, so it shows in their history under the agent's
|
|
* name and the person can undo it there. A permanent delete is not undoable,
|
|
* so it runs only after the person accepts a confirmation card the agent
|
|
* posted.
|
|
*/
|
|
export function responsibilityAgentChangeService(db: Db) {
|
|
const versions = responsibilityDashboardVersionService(db);
|
|
|
|
return {
|
|
/**
|
|
* One transaction, holding each owner's Dashboard lock throughout: the
|
|
* dashboard as it is is saved first (when it changed by hand since), then
|
|
* `mutate` runs on the same transaction, then the result is saved as a
|
|
* `change_set` version by the agent. Nothing commits unless all of it
|
|
* does, so a change is never left without its version.
|
|
*/
|
|
async record<T>(
|
|
input: {
|
|
companyId: string;
|
|
/** Whose dashboards the change touches. */
|
|
ownerUserIds: readonly string[];
|
|
agentId: string;
|
|
/** Areas the change renames, archives or removes, so their versions hold them. */
|
|
touchedAreaIds?: readonly string[];
|
|
/** Areas the change created, so an empty one shows (and can be undone). */
|
|
createdAreaIds?: (result: T) => readonly string[];
|
|
/** Told each version the change saved and whose Dashboard it is, after it commits. */
|
|
onVersion?: (versionId: string, ownerUserId: string) => void;
|
|
},
|
|
mutate: (tx: Db) => Promise<T>,
|
|
): Promise<T> {
|
|
// A fixed lock order, so two changes that touch the same people cannot deadlock.
|
|
const owners = [...new Set(input.ownerUserIds)].sort();
|
|
const touched = [...(input.touchedAreaIds ?? [])];
|
|
const saved: Array<{ id: string; owner: string }> = [];
|
|
const result = await db.transaction(async (tx) => {
|
|
for (const owner of owners) {
|
|
await lockDashboard(tx, input.companyId, owner);
|
|
await versions.checkpoint(tx, input.companyId, owner, null, touched);
|
|
}
|
|
const value = await mutate(tx as unknown as Db);
|
|
// Touched areas are kept with the created ones, so later versions still hold them and Undo can reach them.
|
|
const kept = [...new Set([...(input.createdAreaIds?.(value) ?? []), ...touched])];
|
|
for (const owner of owners) {
|
|
const snapshot = await versions.captureSnapshot(tx, input.companyId, owner, kept, touched);
|
|
const version = await versions.save(tx, { companyId: input.companyId, ownerUserId: owner, cause: "change_set", snapshot, actorAgentId: input.agentId });
|
|
if (version.created) saved.push({ id: version.row.id, owner });
|
|
}
|
|
return value;
|
|
});
|
|
for (const version of saved) input.onVersion?.(version.id, version.owner);
|
|
return result;
|
|
},
|
|
|
|
/**
|
|
* The person accepted this agent's confirmation card for exactly this
|
|
* deletion: a `request_confirmation` in the company that the agent posted,
|
|
* whose target is the deletion's key, accepted by someone who may manage
|
|
* `ownerUserId` (themselves, or a company owner or admin), on the card or
|
|
* by a verified chat reply. Areas pass no owner: any active member of the
|
|
* company may accept.
|
|
*/
|
|
async assertConfirmedDeletion(input: {
|
|
companyId: string;
|
|
agentId: string;
|
|
interactionId: string | undefined;
|
|
key: string;
|
|
ownerUserId?: string;
|
|
}) {
|
|
const refuse = () => forbidden(
|
|
"A permanent delete needs the person's confirmation: post a confirmation card, then delete with its id after they accept it",
|
|
{ code: "responsibility_delete_confirmation_required", confirmationKey: input.key },
|
|
);
|
|
if (!input.interactionId || !/^[0-9a-f-]{36}$/i.test(input.interactionId)) throw refuse();
|
|
const [card] = await db.select().from(issueThreadInteractions).where(and(
|
|
eq(issueThreadInteractions.id, input.interactionId),
|
|
eq(issueThreadInteractions.companyId, input.companyId),
|
|
));
|
|
const target = (card?.payload as { target?: { type?: string; key?: string } } | undefined)?.target;
|
|
if (!card || card.kind !== "request_confirmation" || card.status !== "accepted"
|
|
|| card.createdByAgentId !== input.agentId || target?.type !== "custom" || target.key !== input.key) {
|
|
throw refuse();
|
|
}
|
|
// A card answered by a verified chat reply names the reply; its author is the person who decided.
|
|
let resolverUserId = card.resolvedByUserId;
|
|
const replyCommentId = (card.result as { commentId?: unknown } | null)?.commentId;
|
|
if (!resolverUserId && typeof replyCommentId === "string") {
|
|
const [reply] = await db.select({ authorUserId: issueComments.authorUserId, authorType: issueComments.authorType })
|
|
.from(issueComments)
|
|
.where(and(eq(issueComments.id, replyCommentId), eq(issueComments.companyId, input.companyId), eq(issueComments.issueId, card.issueId)));
|
|
if (reply?.authorType === "user") resolverUserId = reply.authorUserId;
|
|
}
|
|
if (!resolverUserId) throw refuse();
|
|
const [membership] = await db.select({ role: companyMemberships.membershipRole }).from(companyMemberships).where(and(
|
|
eq(companyMemberships.companyId, input.companyId),
|
|
eq(companyMemberships.principalType, "user"),
|
|
eq(companyMemberships.principalId, resolverUserId),
|
|
eq(companyMemberships.status, "active"),
|
|
));
|
|
const allowed = membership && (!input.ownerUserId || resolverUserId === input.ownerUserId
|
|
|| membership.role === "owner" || membership.role === "admin");
|
|
if (!allowed) throw refuse();
|
|
return card;
|
|
},
|
|
};
|
|
}
|