Files
PaperClipAI/server/src/routes/responsibility-dashboard.ts
T
DottaandClaude Opus 5.5 ffcd49f6aa feat(responsibilities): let agents read a person's areas and responsibilities (#22253)
## 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`). Agents chat with them about
this work.
> - Agents have no dedicated tool to read a person's responsibilities.
The only path is the generic `search_api` and `call_api` fallback.
> - That path needs the person's user ID, and nothing in a chat tells
the agent that responsibilities exist. When the feature is off, every
route returns a 404 that looks like "nothing there".
> - So a chief-of-staff agent asked the person "what are your
responsibilities, or where are they written down?" when Paperclip
already had them.
> - This pull request adds three read tools, makes the owner default to
the person the run works for, and tells agents in chats how to use the
tools or that the feature is off.
> - The benefit is that an agent reads and maps a person's
responsibilities itself. This is phase 1 of 4. Later pull requests add
the change tools for areas, responsibilities, routines and skills.

## Linked Issues or Issue Description

**Subsystem affected**

Server (responsibility routes, native runner tool authority, chat
prompt), native runner tool catalog, and the `paperclip` skill.

**Problem or motivation**

An agent in a chat cannot find a person's responsibilities. It has no
dedicated tool. The list route requires `ownerUserId` from an agent, and
the chat does not give the agent that ID. The chat prompt does not
mention responsibilities. When the experiment is off, the 404 does not
tell the agent that the feature is off. The agent then asks the person
to list their responsibilities again.

**Proposed solution**

Add three optional native tools: `list_responsibilities`,
`get_responsibility` and `find_responsibilities_for`. They call the
existing routes with the run's agent token, so all route checks and the
activity log stay the same. The owner defaults to the person the run
works for. The routes return a `responsibilities_disabled` code while
the feature is off. The tools are hidden while the feature is off, and
the chat prompt then says that the feature is off.

**Alternatives considered**

Better `search_api` guidance alone still needs the user ID and many
calls. A new read service in the tool authority would copy the route
permission rules. The tools use the routes instead.

## What Changed

- Add `list_responsibilities` (areas with their responsibilities,
responsibilities with no area, totals, and company work filed under no
responsibility), `get_responsibility` (one responsibility with its filed
items, link IDs, skills and latest status report), and
`find_responsibilities_for` (where a project, task or routine is filed;
a task can be a `PAP-12` identifier).
- Add `server/src/services/responsibility-tools.ts`. It calls the routes
over HTTP with the run token and returns compact results with page
links.
- When an agent sends no `ownerUserId`, the responsibility list, create,
summary, automation and dashboard routes use the person the run works
for (`onBehalfOfUserId`). A run that works for no person still gets a
422 with a clear message.
- The nine "not enabled" checks now throw one shared error. The 404 and
its message do not change. The body now also has `code:
"responsibilities_disabled"` and a remediation line. One
`RESPONSIBILITIES_OFF_GUIDANCE` text is the remediation, the tool error
and the chat prompt note.
- `list_responsibilities` with `areaId` counts only that area. Archived
areas are listed only on request. When only proposals are hidden, the
tool says so.
- `services/paperclip-api-loopback.ts` holds the tools' authenticated
API call; the project tools use it too.
- Show the tools only while the instance has Responsibilities on. A
hidden tool that is called by name returns "Areas and responsibilities
are turned off".
- In standing chats, add an "Areas and responsibilities" prompt block:
use the tools before you ask the person, or say that the feature is off.
- `search_api` results for these routes now name the dedicated tools.
- Add an "Areas and responsibilities" section to
`skills/paperclip/SKILL.md` and to `references/api-reference.md`. Add
one line to the chief-of-staff persona.
- Register the tools in the runner catalogs. Regenerate the semantic
contracts, the action catalog, protocol coverage, the operation-groups
spec and the capability inventory. Update the pinned counts.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/catalog src/semantic-tools src/tools src/eval/workflow-evals.test.ts
src/protocol-actions src/evals/native-execution.test.ts
src/drivers/acpx/permission-policy.test.ts`: 276 passed.
- All runner generator checks pass: protocol manifest, capability
contract, capability inventory, protocol coverage, semantic contracts,
semantic action catalog, operation groups, replay goldens, workflow
traceability.
- Server: `vitest run` of `responsibilit*` route tests,
`responsibility-tools.test.ts` (new), `task-markdown.test.ts`,
`task-context*`, `paperclip-runner-tool-authority.test.ts`,
`runner-api.test.ts`, onboarding first-task tests and
`user-facing-wording-guidance.test.ts`: 20 files, 2620 tests passed.
- `node scripts/typecheck-layers.mjs` for the server: passed.
- New tests cover these items: the owner default for an agent and the
422 without a person, the `responsibilities_disabled` code on every
route, the tool projections, an identifier lookup, the "turned off"
mapping, the tool visibility switch, and the chat prompt block.

## Risks

- Low risk. The routes keep their permission checks. Agents can still
only read and propose in this phase.
- An agent that sends no `ownerUserId` now gets the responsible person's
list instead of a 422. Agents that name an owner see no change.
- The chat prompt gets one more short block in standing chats.
- The flag is pinned when a turn opens. If an admin changes it during a
turn, the tool list changes on the next turn. The routes always check
the current setting.

## 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>
2026-11-19 08:52:42 -06:00

327 lines
14 KiB
TypeScript

import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import {
acceptDashboardChangeSetSchema,
createDashboardChangeSetSchema,
declineDashboardChangeSetSchema,
responsibilityDashboardQuerySchema,
restoreDashboardVersionSchema,
startDashboardConversationSchema,
type AcceptedDashboardChangeSet,
type ProposeDashboardChangesInteraction,
type RestoredDashboardVersion,
} from "@paperclipai/shared";
import { forbidden, notFound, unprocessable } from "../errors.js";
import { validate } from "../middleware/validate.js";
import { authorizationDeniedDetails } from "../services/authorization.js";
import { accessService, heartbeatService, issueReferenceService, issueService, logActivity } from "../services/index.js";
import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "../services/issue-assignment-wakeup.js";
import { responsibilityDashboardService } from "../services/responsibility-dashboard.js";
import {
responsibilityDashboardVersionService,
toDashboardVersionSummary,
type DashboardActivityEvent,
} from "../services/responsibility-dashboard-versions.js";
import { responsibilityService } from "../services/responsibilities.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo } from "./authz.js";
import { getReadableIssue } from "./readable-issue.js";
import { boardCanManageResponsibilityOwner, defaultResponsibilityOwnerUserId } from "./responsibilities.js";
const ISSUE_NOT_FOUND = "Issue not found";
const VERSION_NOT_FOUND = "Version not found";
/**
* A person's Dashboard, made and changed by talking to an agent, with every
* applied change saved as a version (experimental `enableResponsibilities`).
* Reads follow the responsibilities overview: board users read their own by
* default, agents name the person. A person who may edit that person's
* responsibilities (themselves, or a company admin) starts the conversation,
* applies the agent's proposed changes and restores versions; only the agent
* in the conversation proposes.
*/
export function responsibilityDashboardRoutes(db: Db, opts: { heartbeat?: IssueAssignmentWakeupDeps } = {}) {
const router = Router();
const access = accessService(db);
const svc = responsibilityDashboardService(db);
const versions = responsibilityDashboardVersionService(db);
const responsibilitiesSvc = responsibilityService(db);
const issues = issueService(db);
const references = issueReferenceService(db);
const heartbeat = opts.heartbeat ?? heartbeatService(db);
async function log(req: Request, input: { companyId: string; action: string; entityType: string; entityId: string; details?: Record<string, unknown> }) {
const actor = getActorInfo(req);
await logActivity(db, {
companyId: input.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
runId: actor.runId,
agentApiKeyId: actor.agentApiKeyId,
action: input.action,
entityType: input.entityType,
entityId: input.entityId,
details: input.details,
});
}
async function logEvents(req: Request, companyId: string, events: readonly DashboardActivityEvent[]) {
for (const event of events) {
await log(req, { companyId, action: event.action, entityType: event.entityType, entityId: event.entityId, details: event.details });
}
}
/** The overview route's read rule: company access, and agents inside the company-scope boundary. */
async function assertCompanyRead(req: Request, companyId: string) {
assertCompanyAccess(req, companyId);
if (req.actor.type !== "board" && req.actor.type !== "agent") throw forbidden("Board or agent access required");
if (req.actor.type === "agent") {
const decision = await access.decide({ actor: req.actor, action: "company_scope:read", resource: { type: "company", companyId } });
if (!decision.allowed) {
throw forbidden("Responsibilities are outside this agent's authorization boundary", authorizationDeniedDetails(decision));
}
}
}
/** The overview route's ownerUserId rule: board users default to themselves, agents to the person their run works for. */
function ownerFrom(req: Request, ownerUserId: string | undefined) {
const owner = ownerUserId ?? defaultResponsibilityOwnerUserId(req);
if (!owner) {
throw unprocessable(req.actor.type === "agent"
? "ownerUserId is required: this run works for no person, so name the person whose dashboard to read"
: "ownerUserId is required");
}
return owner;
}
function assertWriter(req: Request, companyId: string, ownerUserId: string) {
if (!boardCanManageResponsibilityOwner(req, companyId, ownerUserId)) {
throw forbidden("Only the person whose dashboard this is, or a company admin, can change it");
}
}
function boardUserId(req: Request) {
return req.actor.type === "board" ? req.actor.userId ?? "board" : "board";
}
function interactionDetails(interaction: ProposeDashboardChangesInteraction) {
return {
interactionId: interaction.id,
interactionKind: interaction.kind,
interactionStatus: interaction.status,
continuationPolicy: interaction.continuationPolicy,
requestedResolverPolicy: interaction.requestedResolverPolicy,
effectiveResolverPolicy: interaction.effectiveResolverPolicy,
ownerUserId: interaction.payload.ownerUserId,
};
}
router.get("/companies/:companyId/responsibility-dashboard", async (req, res) => {
await svc.assertEnabled();
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = responsibilityDashboardQuerySchema.parse(req.query);
res.json(await svc.state(companyId, ownerFrom(req, query.ownerUserId)));
});
router.get("/companies/:companyId/responsibility-dashboard/versions", async (req, res) => {
await svc.assertEnabled();
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = responsibilityDashboardQuerySchema.parse(req.query);
const ownerUserId = ownerFrom(req, query.ownerUserId);
// Someone who may change this dashboard saves it as it is first, so the list starts with what they see.
const writer = boardCanManageResponsibilityOwner(req, companyId, ownerUserId);
const { list, saved } = await versions.list(companyId, ownerUserId, writer ? { checkpointBy: getActorInfo(req).actorId } : {});
if (saved) {
await log(req, {
companyId,
action: "responsibility_dashboard.version_saved",
entityType: "responsibility_dashboard_version",
entityId: saved.id,
details: { ownerUserId, cause: saved.cause, summary: saved.summary },
});
}
res.json(list);
});
router.post("/companies/:companyId/responsibility-dashboard/conversation", validate(startDashboardConversationSchema), async (req, res) => {
await svc.assertEnabled();
const companyId = req.params.companyId as string;
assertBoard(req);
assertCompanyAccess(req, companyId);
const ownerUserId = ownerFrom(req, req.body.ownerUserId);
assertWriter(req, companyId, ownerUserId);
if (ownerUserId !== req.actor.userId && !(await responsibilitiesSvc.isCompanyMember(companyId, ownerUserId))) {
throw notFound("Owner is not a member of this company");
}
const actor = getActorInfo(req);
const agentId = req.body.agentId ?? await svc.defaultAgentId(companyId);
if (agentId) {
// The same assignment permission the delegate and bar-conversation routes check.
const decision = await access.decide({
actor: req.actor,
action: "tasks:assign",
resource: {
type: "issue",
companyId,
issueId: null,
projectId: null,
parentIssueId: null,
assigneeAgentId: agentId,
assigneeUserId: null,
},
});
if (!decision.allowed) throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
const { issue, created, interviewPosted } = await svc.startConversation(companyId, ownerUserId, { mode: req.body.mode, agentId: agentId ?? undefined }, {
userId: actor.actorId,
runId: actor.runId,
identityContextId: req.actor.identityContextId ?? null,
authorizationActor: req.actor,
});
if (created) {
await references.syncIssue(issue.id);
await log(req, {
companyId,
action: "issue.created",
entityType: "issue",
entityId: issue.id,
details: { title: issue.title, identifier: issue.identifier, ownerUserId },
});
await log(req, {
companyId,
action: "responsibility_dashboard.conversation_started",
entityType: "issue",
entityId: issue.id,
details: { ownerUserId, mode: req.body.mode, identifier: issue.identifier, agentId: issue.assigneeAgentId },
});
// A Create conversation waits for the interview answers, which wake the agent; nothing runs until then.
if (!interviewPosted) {
void queueIssueAssignmentWakeup({
heartbeat,
issue,
reason: "issue_assigned",
mutation: "create",
contextSource: "responsibility.dashboard_conversation",
requestedByActorType: "user",
requestedByActorId: actor.actorId,
});
}
}
const body = await svc.state(companyId, ownerUserId);
if (created) {
res.status(201).json(body);
return;
}
res.json(body);
});
router.post("/issues/:id/dashboard-changes", validate(createDashboardChangeSetSchema), async (req, res) => {
await svc.assertEnabled();
const issue = await getReadableIssue(access, req, res, issues.getById(req.params.id as string), ISSUE_NOT_FOUND);
if (!issue) return;
if (req.actor.type !== "agent" || !req.actor.agentId) {
throw forbidden("Only the agent in this dashboard conversation can propose changes");
}
const { interaction, replacedIds } = await svc.propose(issue, req.body, {
agentId: req.actor.agentId,
runId: req.actor.runId ?? null,
});
await log(req, {
companyId: issue.companyId,
action: "issue.thread_interaction_created",
entityType: "issue",
entityId: issue.id,
details: { ...interactionDetails(interaction), changes: interaction.payload.changes.length, replacedInteractionIds: replacedIds },
});
res.status(201).json(interaction);
});
router.post(
"/issues/:id/dashboard-changes/:interactionId/accept",
validate(acceptDashboardChangeSetSchema),
async (req, res) => {
await svc.assertEnabled();
const issue = await getReadableIssue(access, req, res, issues.getById(req.params.id as string), ISSUE_NOT_FOUND);
if (!issue) return;
assertBoard(req);
const { ownerUserId } = await svc.ownerForConversation(issue);
assertWriter(req, issue.companyId, ownerUserId);
const accepted = await svc.accept(issue, req.params.interactionId as string, { userId: boardUserId(req) }, { keep: req.body.keep });
await logEvents(req, issue.companyId, accepted.events);
await log(req, {
companyId: issue.companyId,
action: "responsibility_dashboard.changes_applied",
entityType: "responsibility_dashboard_version",
entityId: accepted.after.id,
details: {
ownerUserId,
issueId: issue.id,
interactionId: accepted.interaction.id,
summary: accepted.after.summary,
previousVersionId: accepted.before.id,
dropped: accepted.dropped,
},
});
await log(req, {
companyId: issue.companyId,
action: "issue.thread_interaction_accepted",
entityType: "issue",
entityId: issue.id,
details: interactionDetails(accepted.interaction),
});
const body: AcceptedDashboardChangeSet = {
interaction: accepted.interaction,
version: toDashboardVersionSummary(accepted.after),
};
res.json(body);
},
);
router.post(
"/issues/:id/dashboard-changes/:interactionId/decline",
validate(declineDashboardChangeSetSchema),
async (req, res) => {
await svc.assertEnabled();
const issue = await getReadableIssue(access, req, res, issues.getById(req.params.id as string), ISSUE_NOT_FOUND);
if (!issue) return;
assertBoard(req);
const { ownerUserId } = await svc.ownerForConversation(issue);
assertWriter(req, issue.companyId, ownerUserId);
const interaction = await svc.decline(issue, req.params.interactionId as string, { userId: boardUserId(req) });
await log(req, {
companyId: issue.companyId,
action: "issue.thread_interaction_rejected",
entityType: "issue",
entityId: issue.id,
details: interactionDetails(interaction),
});
res.json(interaction);
},
);
router.post("/responsibility-dashboard-versions/:id/restore", validate(restoreDashboardVersionSchema), async (req, res) => {
await svc.assertEnabled();
const version = await getAccessibleResource(req, res, versions.getById(req.params.id as string), VERSION_NOT_FOUND);
if (!version) return;
assertBoard(req);
assertWriter(req, version.companyId, version.ownerUserId);
const restored = await versions.restore(version, { userId: getActorInfo(req).actorId });
await logEvents(req, version.companyId, restored.events);
if (restored.changed) {
await log(req, {
companyId: version.companyId,
action: "responsibility_dashboard.restored",
entityType: "responsibility_dashboard_version",
entityId: restored.version.id,
details: { ownerUserId: version.ownerUserId, restoredVersionId: version.id, summary: restored.version.summary },
});
}
const body: RestoredDashboardVersion = { version: toDashboardVersionSummary(restored.version) };
res.json(body);
});
return router;
}