feat(responsibilities): file company skills under responsibilities (#22275)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A responsibility shows the skills of the agents doing its work.
People cannot say which skills a responsibility needs.
> - The maintainer chose to file skills under responsibilities like
projects, tasks and routines.
> - Agents also need to set a skill's catalog details without rewriting
its SKILL.md.
> - This pull request lets people and agents file, move and remove
company skills under a responsibility, and adds `update_skill_details`.
> - The benefit is that a responsibility lists the skills it needs,
beside the skills its agents already hold.

## Linked Issues or Issue Description

Refs #22253, #22261 and #22274; this pull request is stacked on them.

**Subsystem affected**

Database (`responsibility_links`), shared types and validators, server
responsibility service and routes, Dashboard versions, native runner
tools, and the responsibility page UI.

**Problem or motivation**

Skills under a responsibility are only computed from the agents doing
its work. A person cannot record that "Hiring needs interviewing", and
an agent cannot file a skill when it maps work for a person.

**Proposed solution**

Add a nullable `skill_id` to `responsibility_links` and allow it as the
one target of a link. Show filed and computed skills together. Let the
file, unfile, lookup and link routes and tools take skills. Keep filed
skills in Dashboard versions so undo covers them. Add a small live tool
for a skill's tagline and categories.

**Alternatives considered**

Keeping skills computed only, and giving the skill to the agent that
runs the responsibility, was the other option. It was not chosen.
Extending `update_skill` would change its scenario contract, whose mock
needs `markdown`, so the details tool is separate.

## What Changed

- Review fixes: the default responsibility view's Skills "+" adds an
existing skill, removes a filed one, or opens an agent's skills page. A
newest Dashboard version without a skill list is upgraded in place, so
the first skill filed after it is undone. Undo files again, or removes,
only skills the restoring person can see. A read scope without a skill
condition sees no filed skill. `update_skill_details` with only
`skillId` is a no-op, as its schema allows.

- Migration `0499`: add `responsibility_links.skill_id` (FK to
`company_skills`, on delete cascade). Widen the single-target check to
four targets. Add a unique `(responsibility_id, skill_id)` index and a
`skill_id` index. The migration is idempotent and online-compatible (NOT
VALID then VALIDATE, and the indexes are built CONCURRENTLY). It is
listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`.
- Shared: `ResponsibilityLink.skillId`;
`ResponsibilitySkillSummary.linkId` and `computed`; `skillId` in the
link and lookup schemas; `skill` in `RESPONSIBILITY_FILE_ITEM_KINDS`;
optional `skillIds` in Dashboard snapshot links.
- Server: filing checks the reader's skill visibility
(`skillAccessService`). The detail merges filed and computed skills into
one card each. Lookup accepts `skillId`. Dashboard capture, restore and
summary include filed skills. A version without `skillIds` leaves filed
skills as they are when it is restored.
- Tools: `file_under_responsibility`, `remove_from_responsibility` and
`find_responsibilities_for` accept `kind: "skill"`. `get_responsibility`
returns `linkId` and `computed` for each skill. Add
`update_skill_details` (tagline and categories).
- UI: the responsibility page has "Add existing skill". A filed skill
shows "Filed here" and a remove button. Computed skills keep their
holders.

## Verification

- Server: the `responsibilit*` tests (new: file, find, move and unfile a
skill; one card for a skill that is both filed and computed; undo of a
filed skill from the Dashboard history), `skill-tools.test.ts` (new
`update_skill_details` cases), `responsibility-tools`, `routine-tools`,
`routines-routes`, `paperclip-runner-tool-authority`, `runner-api` and
`openapi-routes`: 24 files, 2723 tests passed.
- UI: responsibility page and component tests (16 files, 158 tests,
including a new filed-skill test) pass. `pnpm --filter @paperclipai/ui
typecheck` passed.
- `@paperclipai/db` `check:migrations` passes and reports the override.
The snapshot drift test passes. `tsc` passes for `db`, `shared` and the
server layers.
- Runner: catalog and semantic-tool tests (317) pass. All generator
checks pass.

## Risks

- The migration changes a check constraint on `responsibility_links`.
The replacement accepts every row that the old check accepted. It is
swapped as NOT VALID and then validated. The previous release never sets
`skill_id`.
- Deleting a company skill removes its links (cascade).
- Filed skills follow the reader's skill visibility. A skill the reader
may not see is not listed.

## 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:
authored and GitHub committed 2026-11-19 09:30:49 -06:00
1 parent b7319eb581
commit 575ef12575
51 files changed
+2964 -182

No files matched your search

+1
View File
@@ -911,6 +911,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
"0487_heartbeat_runs_settled_process_indexes.sql",
"0469_zippy_photon.sql",
"0495_tiny_rage.sql",
"0499_numerous_whizzer.sql",
"0384_funny_adam_warlock.sql",
@@ -0,0 +1,8 @@
-- paperclip:migration-compat online_compatible: the new skill_id column is nullable with no default and NULL in every existing row, so the previous release keeps reading and writing links (it never sets skill_id); the replacement single-target CHECK accepts every row the old one accepted and is swapped in one statement (catalog-only, brief lock) as NOT VALID, then validated under SHARE UPDATE EXCLUSIVE, which does not block reads or writes; the foreign key is added NOT VALID and validated the same way; both indexes are on the new column and are built CONCURRENTLY. Every statement is idempotent because this file runs outside a transaction.
ALTER TABLE "responsibility_links" ADD COLUMN IF NOT EXISTS "skill_id" uuid;--> statement-breakpoint
ALTER TABLE "responsibility_links" DROP CONSTRAINT IF EXISTS "responsibility_links_single_target_check", ADD CONSTRAINT "responsibility_links_single_target_check" CHECK (("responsibility_links"."project_id" is not null)::int + ("responsibility_links"."issue_id" is not null)::int + ("responsibility_links"."routine_id" is not null)::int + ("responsibility_links"."skill_id" is not null)::int = 1) NOT VALID;--> statement-breakpoint
ALTER TABLE "responsibility_links" VALIDATE CONSTRAINT "responsibility_links_single_target_check";--> statement-breakpoint
ALTER TABLE "responsibility_links" DROP CONSTRAINT IF EXISTS "responsibility_links_skill_id_company_skills_id_fk", ADD CONSTRAINT "responsibility_links_skill_id_company_skills_id_fk" FOREIGN KEY ("skill_id") REFERENCES "public"."company_skills"("id") ON DELETE cascade ON UPDATE no action NOT VALID;--> statement-breakpoint
ALTER TABLE "responsibility_links" VALIDATE CONSTRAINT "responsibility_links_skill_id_company_skills_id_fk";--> statement-breakpoint
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "responsibility_links_responsibility_skill_uq" ON "responsibility_links" USING btree ("responsibility_id","skill_id") WHERE "responsibility_links"."skill_id" is not null;--> statement-breakpoint
CREATE INDEX CONCURRENTLY IF NOT EXISTS "responsibility_links_skill_idx" ON "responsibility_links" USING btree ("skill_id");
+7
View File
@@ -3480,6 +3480,13 @@
"when": 1794977210244,
"tag": "0498_quiet_hardball",
"breakpoints": true
},
{
"idx": 499,
"version": "7",
"when": 1795048062306,
"tag": "0499_numerous_whizzer",
"breakpoints": true
}
]
}
+12 -5
View File
@@ -13,6 +13,7 @@ import {
} from "drizzle-orm/pg-core";
import { agents } from "./agents.js";
import { companies } from "./companies.js";
import { companySkills } from "./company_skills.js";
import { issues } from "./issues.js";
import { projects } from "./projects.js";
import { routines } from "./routines.js";
@@ -123,10 +124,10 @@ export const responsibilities = pgTable(
);
/**
* What lives under a responsibility: exactly one project, task or routine per
* row. A target can sit under several responsibilities, once each. The
* responsibilities module owns these links so the issues, projects and
* routines tables stay unchanged.
* What lives under a responsibility: exactly one project, task, routine or
* company skill per row. A target can sit under several responsibilities,
* once each. The responsibilities module owns these links so the issues,
* projects, routines and skills tables stay unchanged.
*/
export const responsibilityLinks = pgTable(
"responsibility_links",
@@ -139,6 +140,8 @@ export const responsibilityLinks = pgTable(
projectId: uuid("project_id").references(() => projects.id, { onDelete: "cascade" }),
issueId: uuid("issue_id").references(() => issues.id, { onDelete: "cascade" }),
routineId: uuid("routine_id").references(() => routines.id, { onDelete: "cascade" }),
/** A company skill filed here by hand, beside the skills of the agents doing the work. */
skillId: uuid("skill_id").references(() => companySkills.id, { onDelete: "cascade" }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => ({
@@ -152,12 +155,16 @@ export const responsibilityLinks = pgTable(
routineUq: uniqueIndex("responsibility_links_responsibility_routine_uq")
.on(table.responsibilityId, table.routineId)
.where(sql`${table.routineId} is not null`),
skillUq: uniqueIndex("responsibility_links_responsibility_skill_uq")
.on(table.responsibilityId, table.skillId)
.where(sql`${table.skillId} is not null`),
projectIdx: index("responsibility_links_project_idx").on(table.projectId),
issueIdx: index("responsibility_links_issue_idx").on(table.issueId),
routineIdx: index("responsibility_links_routine_idx").on(table.routineId),
skillIdx: index("responsibility_links_skill_idx").on(table.skillId),
singleTargetCheck: check(
"responsibility_links_single_target_check",
sql`(${table.projectId} is not null)::int + (${table.issueId} is not null)::int + (${table.routineId} is not null)::int = 1`,
sql`(${table.projectId} is not null)::int + (${table.issueId} is not null)::int + (${table.routineId} is not null)::int + (${table.skillId} is not null)::int = 1`,
),
}),
);
@@ -1 +1 @@
[{"annotations":{"exposure":"always","operationId":"get_task_context","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the active task and actor, including the exact approved Markdown revision when this issue has an accepted plan.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_task_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"get_task_history","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded comments on the active task only. Calling get_task does not change the active task. This is not a status or assignment audit. For progress chronology and handoff actors, use search_api to discover the company timeline or issue activity, then call_api.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":[],"type":"object"},"name":"get_task_history","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_documents","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List revisioned documents on the active task.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_documents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"read_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the current revision of one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"}},"required":["key"],"type":"object"},"name":"read_document","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_document_revisions","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded revision history for one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"},"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":["key"],"type":"object"},"name":"list_document_revisions","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"report_progress","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append a durable progress comment to the active task.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Multiline progress update.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"report_progress","outputSchema":{"additionalProperties":false,"properties":{"commandId":{"description":"Stable command identifier.","maxLength":200,"minLength":1,"type":"string"},"disposition":{"enum":["applied","duplicate"]},"entityRefs":{"description":"Entities affected by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"scheduledWakeIds":{"description":"Wake identifiers scheduled by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"stateRevision":{"minimum":0,"type":"integer"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds"],"type":"object"}},{"annotations":{"exposure":"always","operationId":"answer_status_question","requiredClaims":[],"semanticContract":"paperclip.Line truncated
[{"annotations":{"exposure":"always","operationId":"get_task_context","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the active task and actor, including the exact approved Markdown revision when this issue has an accepted plan.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_task_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"get_task_history","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded comments on the active task only. Calling get_task does not change the active task. This is not a status or assignment audit. For progress chronology and handoff actors, use search_api to discover the company timeline or issue activity, then call_api.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":[],"type":"object"},"name":"get_task_history","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_documents","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List revisioned documents on the active task.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_documents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"read_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read the current revision of one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"}},"required":["key"],"type":"object"},"name":"read_document","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"list_document_revisions","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read bounded revision history for one active-task document.","inputSchema":{"additionalProperties":false,"properties":{"key":{"description":"Stable document identifier, not a filename or path (for example reconciliation, not reconciliation.md). After trimming whitespace and lowercasing: 1–64 characters, starting with a letter or digit and containing only a–z, 0–9, _ or -. The raw input is limited to 120 characters.","maxLength":120,"minLength":1,"pattern":"^[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*[A-Za-z0-9\\u212a][A-Za-z0-9_\\u212a-]{0,63}[\\u0009-\\u000d\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]*$","type":"string"},"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"}},"required":["key"],"type":"object"},"name":"list_document_revisions","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"always","operationId":"report_progress","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Append a durable progress comment to the active task.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Multiline progress update.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"report_progress","outputSchema":{"additionalProperties":false,"properties":{"commandId":{"description":"Stable command identifier.","maxLength":200,"minLength":1,"type":"string"},"disposition":{"enum":["applied","duplicate"]},"entityRefs":{"description":"Entities affected by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"scheduledWakeIds":{"description":"Wake identifiers scheduled by the operation.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"stateRevision":{"minimum":0,"type":"integer"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds"],"type":"object"}},{"annotations":{"exposure":"always","operationId":"answer_status_question","requiredClaims":[],"semanticContract":"paperclip.Line truncated
@@ -2931,7 +2931,7 @@
"planning",
"skill_test"
],
"description": "Read one responsibility in full: its bar and health, area, the projects, tasks and routines under it (with link IDs for items filed directly, and items under it through a filed project), the skills of the agents doing its work, and its latest status report.",
"description": "Read one responsibility in full: its bar and health, area, the projects, tasks and routines under it (with link IDs for items filed directly, and items under it through a filed project), its skills (filed by hand, with a link ID, and computed from the agents doing its work), and its latest status report.",
"effect": "read",
"inputSchema": {
"additionalProperties": false,
@@ -2965,7 +2965,7 @@
"planning",
"skill_test"
],
"description": "List the proposed and active responsibilities a project, task or routine is filed under, directly or through its project. An empty list means it is uncovered.",
"description": "List the proposed and active responsibilities a project, task, routine or company skill is filed under, directly or (for a task or routine) through its project. An empty list means it is uncovered.",
"effect": "read",
"inputSchema": {
"additionalProperties": false,
@@ -2981,7 +2981,8 @@
"enum": [
"project",
"task",
"routine"
"routine",
"skill"
],
"type": "string"
}
@@ -3242,7 +3243,7 @@
]
},
"fileItems": {
"description": "What to file: each a project, task or routine by ID. A task can also be an identifier such as PAP-12.",
"description": "What to file: each a project, task, routine or company skill by ID. A task can also be an identifier such as PAP-12.",
"items": {
"additionalProperties": false,
"properties": {
@@ -3255,7 +3256,8 @@
"enum": [
"project",
"task",
"routine"
"routine",
"skill"
],
"type": "string"
}
@@ -3534,13 +3536,13 @@
"allowedModes": [
"standard"
],
"description": "File projects, tasks and routines under a responsibility in one step. With moveFrom it is a move: the items also leave that responsibility, or with all, every other responsibility of the same person. An item can sit under several responsibilities; filing one already there changes nothing. When the person this run works for directed it (it is their own chat or task, or their message woke you), you act for them and may do what they could; each change is saved in their Dashboard history, where they can undo it. Otherwise the change is saved as a proposal for a person to confirm.",
"description": "File projects, tasks, routines and company skills under a responsibility in one step. With moveFrom it is a move: the items also leave that responsibility, or with all, every other responsibility of the same person. An item can sit under several responsibilities; filing one already there changes nothing. When the person this run works for directed it (it is their own chat or task, or their message woke you), you act for them and may do what they could; each change is saved in their Dashboard history, where they can undo it. Otherwise the change is saved as a proposal for a person to confirm.",
"effect": "write",
"inputSchema": {
"additionalProperties": false,
"properties": {
"items": {
"description": "What to file: each a project, task or routine by ID. A task can also be an identifier such as PAP-12.",
"description": "What to file: each a project, task, routine or company skill by ID. A task can also be an identifier such as PAP-12.",
"items": {
"additionalProperties": false,
"properties": {
@@ -3553,7 +3555,8 @@
"enum": [
"project",
"task",
"routine"
"routine",
"skill"
],
"type": "string"
}
@@ -3599,13 +3602,13 @@
"allowedModes": [
"standard"
],
"description": "Unfile projects, tasks and routines from a responsibility by what they are; no link IDs needed. The items themselves are not changed. When the person this run works for directed it (it is their own chat or task, or their message woke you), you act for them and may do what they could; each change is saved in their Dashboard history, where they can undo it. Otherwise the change is saved as a proposal for a person to confirm.",
"description": "Unfile projects, tasks, routines and skills from a responsibility by what they are; no link IDs needed. The items themselves are not changed. When the person this run works for directed it (it is their own chat or task, or their message woke you), you act for them and may do what they could; each change is saved in their Dashboard history, where they can undo it. Otherwise the change is saved as a proposal for a person to confirm.",
"effect": "write",
"inputSchema": {
"additionalProperties": false,
"properties": {
"items": {
"description": "What to file: each a project, task or routine by ID. A task can also be an identifier such as PAP-12.",
"description": "What to file: each a project, task, routine or company skill by ID. A task can also be an identifier such as PAP-12.",
"items": {
"additionalProperties": false,
"properties": {
@@ -3618,7 +3621,8 @@
"enum": [
"project",
"task",
"routine"
"routine",
"skill"
],
"type": "string"
}
@@ -3863,6 +3867,54 @@
"title": "Update routine",
"version": 1
},
{
"allowedModes": [
"standard"
],
"description": "Change a company skill's catalog details outside SKILL.md: its tagline (one line) and categories; send tagline, categories or both. Its name and description are SKILL.md frontmatter; change those with update_skill. Uses the skill page's edit policy.",
"effect": "write",
"inputSchema": {
"additionalProperties": false,
"properties": {
"categories": {
"description": "Replaces its categories.",
"items": {
"maxLength": 60,
"minLength": 1,
"type": "string"
},
"maxItems": 20,
"type": "array"
},
"skillId": {
"pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$",
"type": "string"
},
"tagline": {
"description": "One line shown with the skill; null clears it.",
"maxLength": 120,
"type": [
"string",
"null"
]
}
},
"required": [
"skillId"
],
"type": "object"
},
"operationId": "update_skill_details",
"outputSchema": {
"additionalProperties": true,
"type": "object"
},
"placement": "optional",
"requiredClaims": [],
"schema": "paperclip.semantic-action.v1",
"title": "Update skill details",
"version": 1
},
{
"allowedModes": [
"standard",
@@ -24,7 +24,7 @@
"prpVersion": 1,
"nativeExecutionVersion": 1,
"catalogVersion": 1,
"catalogSha256": "sha256:93905f19b7e648e8f3326dd86bb8007105a31ce6cd20b2f1f7b2d926f1f2a1b5",
"catalogSha256": "sha256:ce5fb80bf75fd1a788c97235ead13f4d6eb878f500078a204ec6831dfdf7b442",
"driverContractVersion": 1,
"driverKind": "paperclip-deterministic",
"driverVersion": "1.0.0"
@@ -190,7 +190,7 @@
},
{
"path": "fixtures/evals/native-execution-seeded.json",
"sha256": "edac8c5ff3a97674e92455d7abf983efd57ee7abc71e2a659b72f7063f96565a",
"sha256": "d3448d1a4b043d11864eb3d5d4c839e167d14e48f92543378290a0bd384f276e",
"expectation": "accept",
"compatibilityCase": "canonical"
},
@@ -7,7 +7,7 @@
"src/scenarios/scenario-plan.ts"
],
"counts": {
"actions": 82,
"actions": 83,
"legacyRequirements": 106
},
"actions": [
@@ -564,6 +564,25 @@
"src/scenarios/scenario-explorer.test.ts::renders every scenario with exposure, control plane, authorization, diff, and parity"
]
},
{
"id": "update_skill_details",
"ownership": "optional_agent_tool",
"surfaces": [
"live"
],
"legacyAliases": [],
"contractCase": "protocol-action:update_skill_details",
"contractOwner": "src/catalog/protocol-action-contracts.test.ts::update_skill_details has a schema-valid canonical example and every declared projection",
"legacyBehavioralCases": [],
"deterministicCases": [
"protocol-action:update_skill_details"
],
"legacyRequirementCases": [],
"deterministicOwners": [
"src/catalog/protocol-action-contracts.test.ts::update_skill_details has a schema-valid canonical example and every declared projection",
"src/scenarios/scenario-explorer.test.ts::renders every scenario with exposure, control plane, authorization, diff, and parity"
]
},
{
"id": "search_api",
"ownership": "optional_agent_tool",
@@ -165,7 +165,8 @@
"create_skill",
"update_skill",
"list_company_skills",
"sync_company_skills"
"sync_company_skills",
"update_skill_details"
]
},
{
@@ -534,6 +535,7 @@
"update_routine",
"create_skill",
"update_skill",
"update_skill_details",
"list_company_skills",
"sync_company_skills",
"list_secret_metadata",
@@ -6,7 +6,7 @@ Status: canonical explanatory contract for the Paperclip runner V1 surface.
This document keeps three independent meanings of **group** separate. PRP families describe wire evidence and controller commands; capability placement decides who owns an operation; behavioral eval groups organize the 106 scenario corpus. None of the three axes can be used as a substitute for another.
The generated totals are **108 PRP events in 32 event families**, **18 controller commands in 7 command families**, **10 control-plane operations**, **82 reconciled semantic operations** (19 always, 63 optional), and **106 scenarios in 16 behavior groups**.
The generated totals are **108 PRP events in 32 event families**, **18 controller commands in 7 command families**, **10 control-plane operations**, **83 reconciled semantic operations** (19 always, 64 optional), and **106 scenarios in 16 behavior groups**.
## Axis 1: PRP v1 event and command families
@@ -88,7 +88,7 @@ Placement has exactly three outcomes:
`answer_status_question`, `block_task`, `finish_task`, `get_agent_instruction_history`, `get_task_context`, `get_task_history`, `inspect_operation_result`, `list_document_revisions`, `list_documents`, `read_agent_instructions`, `read_document`, `register_deliverable`, `report_progress`, `request_human_input`, `request_review`, `restore_agent_instructions`, `send_chat_message`, `update_agent_instructions`, `write_document`.
### Optional operations (63) and grant groups (15)
### Optional operations (64) and grant groups (15)
Grant groups are documentation/exposure bundles, not additional authority. The operation descriptor's exact `requiredClaims` remains decisive.
@@ -104,7 +104,7 @@ Grant groups are documentation/exposure bundles, not additional authority. The o
| `workspace_runtime` | `get_workspace_runtime`<br>`control_workspace_service`<br>`get_workspace`<br>`list_workspaces`<br>`select_workspace`<br>`prepare_repository` | `workspace:control`<br>`workspace:read` | Inspect and select task workspaces, prepare repositories, and control workspace runtime services. |
| `wake_scheduling` | `schedule_wake`<br>`set_task_monitor` | `control_plane:wakes` | Schedule a bounded continuation wake when the current task owns the future check. |
| `routines` | `list_routines`<br>`manage_routine`<br>`update_routine` | `routines:read`<br>`routines:write` | List routines and change them (title, instructions, agent, project, status, priority, schedule, filing) through the live company/run authority; manage_routine remains a scenario mock. |
| `company_skills` | `create_skill`<br>`update_skill`<br>`list_company_skills`<br>`sync_company_skills` | `company_skills:read`<br>`company_skills:write` | Create, update, or inspect company skills and synchronize the current agent's skills. |
| `company_skills` | `create_skill`<br>`update_skill`<br>`list_company_skills`<br>`sync_company_skills`<br>`update_skill_details` | `company_skills:read`<br>`company_skills:write` | Create, update, or inspect company skills and synchronize the current agent's skills. |
| `secrets` | `list_secret_metadata`<br>`read_secret_value` | `secrets:metadata:read`<br>`secrets:values:read` | Inspect secret metadata or use a brokered secret value without exposing plaintext evidence. |
| `portability_admin` | `export_company`<br>`administer_company` | `company:admin`<br>`portability:export` | Export portable company state; broad administration remains deferred until split into governed operations. |
| `test_escape_hatch` | `generic_api_request` | `test:generic_api_request` | Controlled skill-test transport only; never product coverage. |
@@ -195,6 +195,7 @@ Grant groups are documentation/exposure bundles, not additional authority. The o
| `update_responsibility` | `optional_agent_tool` | none | `standard` | `company_write` | `none` | no | inline/no mapping | `live`<br>`live_codex` | `callResponsibilityTool`<br>Authenticated responsibility routes with run-bound activity for the person the agent works for.<br>catalog PRP status: `bound` |
| `update_routine` | `optional_agent_tool` | none | `standard` | `company_write` | `none` | no | inline/no mapping | `live`<br>`live_codex` | `callRoutineTool`<br>Authenticated routine routes with routine revisions and run-bound activity for the person the agent works for.<br>catalog PRP status: `bound` |
| `update_skill` | `optional_agent_tool` | none | `standard`<br>`skill_test` | `company_write` | `required` | no | `semantic_command:update_skill` | `scenario` + `live`<br>`live_codex` | `PaperclipRunnerToolAuthority`<br>Authenticated skill file API with version guard, durable receipt, and attributed activity.<br>catalog PRP status: `bound` |
| `update_skill_details` | `optional_agent_tool` | none | `standard` | `company_write` | `none` | no | inline/no mapping | `live`<br>`live_codex` | `PaperclipRunnerToolAuthority`<br>Authenticated company skill update API with the company skill edit policy and attributed activity.<br>catalog PRP status: `bound` |
| `update_workflow` | `optional_agent_tool` | none | `standard` | `company_write` | `required` | no | inline/no mapping | `live`<br>`live_codex` | `executeNativeWorkflowTool`<br>Authorized case mutation and durable operation receipt<br>catalog PRP status: `bound` |
| `upsert_case` | `optional_agent_tool` | `cases:write` | `standard`<br>`skill_test` | `company_write` | `required` | no | `mock_extension:cases.upsert` | `scenario`<br>`scenario_mock` | `unbound`<br>semantic-operation item event plus company-entity state diff and audit record<br>catalog PRP status: `audit_pending` |
| `write_document` | `always_agent_tool` | none | `standard`<br>`planning`<br>`skill_test` | `task_write` | `required` | no | `semantic_command:write_document` | `scenario` + `live`<br>`live_codex` | `unbound`<br>semantic-operation item event plus active-task state diff, work-assessment, and issue-status-decision events<br>catalog PRP status: `audit_pending` |
@@ -219,7 +220,7 @@ Behavior groups describe expected outcomes and trajectories. They do not grant t
| [`ap` — Approvals](#behavior-group-ap-approvals) | optional governance tools + governed approver | `list_approvals`<br>`get_approval`<br>`get_approval_context`<br>`request_approval`<br>`decide_approval`<br>`comment_on_approval` | `route_wake`<br>`append_audit_record` | company approval, decision, issue-link, comment, and governed-action services | `company`<br>`task`<br>`approvals`<br>`actor`<br>`wake`<br>`audit`<br>`idempotency` | 6 | governed semantic receipts, audit references, and attention/continuation linkage | Production binding and additive governed-action receipts are unbound; board-only authority stays outside grants. |
| [`ar` — Artifacts](#behavior-group-ar-artifacts) | always tools + artifact/work-product services | `register_deliverable` | `append_audit_record` | attachment upload and issue work-product routes | `task`<br>`artifacts`<br>`workProducts`<br>`workspace`<br>`audit`<br>`idempotency` | 4 | artifact/work-product reference and durable inspectability receipt; never binary bytes | Production upload/register composite and additive durable-reference receipt are unbound. |
| [`er` — Errors and critical rules](#behavior-group-er-errors-and-critical-rules) | runner/control plane + optional workspace/wake tools | `get_workspace_runtime`<br>`control_workspace_service`<br>`get_workspace`<br>`list_workspaces`<br>`select_workspace`<br>`prepare_repository`<br>`schedule_wake`<br>`inspect_operation_result` | `release_task`<br>`enforce_budget`<br>`persist_run`<br>`replay_run`<br>`reconcile_run` | workspace runtime, monitor/recovery, budget, run persistence/replay, release, and terminal services | `workspace`<br>`budget`<br>`run`<br>`wake`<br>`audit`<br>`idempotency`<br>`fault` | 9 | runtime/workspace/attention/run lifecycle, typed denials, replay facts, and terminal causality | Budget stop reasons and semantic denial/conflict receipts require additive v1 envelopes; inspect_operation_result remains scenario-only. Task workspace inspection, discovery, selection and repository preparation use live authenticated service contracts; the legacy scenarios do not claim coverage for these operations. |
| [`rf` — Reference files](#behavior-group-rf-reference-files) | always instruction tools + optional domain tools + test-only escape hatch | `list_cases`<br>`upsert_case`<br>`create_case`<br>`read_case`<br>`update_case`<br>`list_workflows`<br>`read_workflow`<br>`create_workflow`<br>`update_workflow`<br>`list_routines`<br>`manage_routine`<br>`update_routine`<br>`create_skill`<br>`update_skill`<br>`list_company_skills`<br>`sync_company_skills`<br>`list_secret_metadata`<br>`read_secret_value`<br>`export_company`<br>`administer_company`<br>`generic_api_request`<br>`search_api`<br>`call_api`<br>`create_project`<br>`read_agent_instructions`<br>`update_agent_instructions`<br>`get_agent_instruction_history`<br>`restore_agent_instructions`<br>`submit_complaint`<br>`submit_suggestion`<br>`create_area`<br>`update_area`<br>`delete_area`<br>`create_responsibility`<br>`update_responsibility`<br>`delete_responsibility`<br>`file_under_responsibility`<br>`remove_from_responsibility` | `append_audit_record` | agent instruction revisions, project, case, routine, company-skill, secret, portability, and administration services, and run-attributed agent commentary; responsibility and area routes | `company`<br>`cases`<br>`routines`<br>`skills`<br>`secrets`<br>`audit`<br>`fault` | 22 | bounded domain projections, redacted broker receipts, company diffs, and audit references | Instruction read/update/history/restore require the live canonical revision service, current responsible-user permissions, and pinned base revisions for writes. Their service, authority, and product E2E tests are separate from the legacy mock scenarios. Project and skill creation and API tools require the live server authority; generic_api_request is test-only. Workflow definition tools are live-only company-scoped prompt authoring and bounded retrieval under the Cases flag. create_case, read_case and update_case are live-only authorized case creation, projections and fact mutations; list_cases and upsert_case remain scenario mocks. list_routines and update_routine are live through the routine routes for the agent's own routines and its person's; manage_routine and other domain operations remain scenario-only. Broad administer_company is deferred and cannot claim product coverage. Production API and paired dedicated-tool regressions are recorded separately in paperclip-evals/evals/runner-api-tools; the legacy scenario count is not evidence of that coverage. Feedback actions are live-only: shared persistence, authority, API, and actual Codex smoke tests cover them; the legacy scenario count does not claim feedback coverage. Responsibility and area changes are live-only and bound to the person the run works for; the mock dispatcher does not implement them. |
| [`rf` — Reference files](#behavior-group-rf-reference-files) | always instruction tools + optional domain tools + test-only escape hatch | `list_cases`<br>`upsert_case`<br>`create_case`<br>`read_case`<br>`update_case`<br>`list_workflows`<br>`read_workflow`<br>`create_workflow`<br>`update_workflow`<br>`list_routines`<br>`manage_routine`<br>`update_routine`<br>`create_skill`<br>`update_skill`<br>`update_skill_details`<br>`list_company_skills`<br>`sync_company_skills`<br>`list_secret_metadata`<br>`read_secret_value`<br>`export_company`<br>`administer_company`<br>`generic_api_request`<br>`search_api`<br>`call_api`<br>`create_project`<br>`read_agent_instructions`<br>`update_agent_instructions`<br>`get_agent_instruction_history`<br>`restore_agent_instructions`<br>`submit_complaint`<br>`submit_suggestion`<br>`create_area`<br>`update_area`<br>`delete_area`<br>`create_responsibility`<br>`update_responsibility`<br>`delete_responsibility`<br>`file_under_responsibility`<br>`remove_from_responsibility` | `append_audit_record` | agent instruction revisions, project, case, routine, company-skill, secret, portability, and administration services, and run-attributed agent commentary; responsibility and area routes | `company`<br>`cases`<br>`routines`<br>`skills`<br>`secrets`<br>`audit`<br>`fault` | 22 | bounded domain projections, redacted broker receipts, company diffs, and audit references | Instruction read/update/history/restore require the live canonical revision service, current responsible-user permissions, and pinned base revisions for writes. Their service, authority, and product E2E tests are separate from the legacy mock scenarios. Project and skill creation and API tools require the live server authority; generic_api_request is test-only. Workflow definition tools are live-only company-scoped prompt authoring and bounded retrieval under the Cases flag. create_case, read_case and update_case are live-only authorized case creation, projections and fact mutations; list_cases and upsert_case remain scenario mocks. list_routines and update_routine are live through the routine routes for the agent's own routines and its person's; manage_routine and other domain operations remain scenario-only. Broad administer_company is deferred and cannot claim product coverage. Production API and paired dedicated-tool regressions are recorded separately in paperclip-evals/evals/runner-api-tools; the legacy scenario count is not evidence of that coverage. Feedback actions are live-only: shared persistence, authority, API, and actual Codex smoke tests cover them; the legacy scenario count does not claim feedback coverage. Responsibility and area changes are live-only and bound to the person the run works for; the mock dispatcher does not implement them. |
| [`mh` — Multi-hop](#behavior-group-mh-multi-hop) | composed semantic operations + control-plane continuation | `create_task`<br>`set_dependencies`<br>`request_human_input`<br>`request_approval`<br>`register_deliverable` | `route_wake`<br>`reconcile_run` | delegation, dependency, interaction, approval, artifact, and terminal orchestration services | `task`<br>`blockers`<br>`interactions`<br>`approvals`<br>`artifacts`<br>`wake`<br>`run`<br>`audit` | 4 | correlated operation receipts, state diffs, attention hops, work assessment, status decision, and terminal outcome | No generic transaction tool is allowed; shared mock/real conformance must prove each composed effect. |
| [`rs` — Restraint and no-call](#behavior-group-rs-restraint-and-no-call) | policy/exposure layer | `answer_status_question`<br>`read_secret_value`<br>`generic_api_request` | `enforce_budget` | task-mode, secret-broker, test-scope, pause, and budget policy checks | `actor`<br>`task`<br>`budget`<br>`secrets`<br>`audit`<br>`fault` | 3 | absence of forbidden effects plus typed policy denial/redaction receipts when a call is attempted | Typed redaction/authorization receipts need additive v1 evidence; generic_api_request is never a product fallback. |
| [`wk` — Wake situations](#behavior-group-wk-wake-situations) | control plane + always context/history tools | `get_task_context`<br>`get_task_history`<br>`schedule_wake`<br>`set_task_monitor` | `select_work`<br>`route_wake` | wakeup requests, heartbeat context, comment/interaction/approval/blocker wake routing, and scheduled wake services | `wake`<br>`task`<br>`comments`<br>`interactions`<br>`approvals`<br>`blockers`<br>`run` | 8 | attention request routing/resolution plus resumed session/run causality | set_task_monitor binds the one-shot monitor scheduler in production; schedule_wake remains mock-backed. Control-plane routing remains non-callable. |
@@ -496,10 +497,10 @@ Current responsibility-based paths are normative. Numbered `phase-*` or mileston
### Catalog split and deliberate replacement
- Scenario/eval catalog: **40** operations.
- Live dispatcher catalog: **71** operations.
- Shared: **29**; union/canonical authority: **82**.
- Live dispatcher catalog: **72** operations.
- Shared: **29**; union/canonical authority: **83**.
- Scenario-only: `administer_company`, `export_company`, `inspect_operation_result`, `list_cases`, `list_company_skills`, `list_goals`, `list_secret_metadata`, `manage_routine`, `read_secret_value`, `sync_company_skills`, `upsert_case`.
- Live-only: `call_api`, `create_area`, `create_case`, `create_project`, `create_responsibility`, `create_workflow`, `delete_area`, `delete_responsibility`, `file_under_responsibility`, `find_responsibilities_for`, `get_agent`, `get_agent_instruction_history`, `get_approval`, `get_approval_context`, `get_responsibility`, `get_workspace`, `handoff_case`, `hire_agent`, `list_project_repositories`, `list_responsibilities`, `list_workflows`, `list_workspaces`, `prepare_repository`, `read_agent_instructions`, `read_case`, `read_workflow`, `remove_from_responsibility`, `restore_agent_instructions`, `schedule_wake`, `search_api`, `select_workspace`, `send_chat_message`, `set_task_monitor`, `set_task_title`, `submit_complaint`, `submit_suggestion`, `update_agent_instructions`, `update_area`, `update_case`, `update_responsibility`, `update_routine`, `update_workflow`.
- Live-only: `call_api`, `create_area`, `create_case`, `create_project`, `create_responsibility`, `create_workflow`, `delete_area`, `delete_responsibility`, `file_under_responsibility`, `find_responsibilities_for`, `get_agent`, `get_agent_instruction_history`, `get_approval`, `get_approval_context`, `get_responsibility`, `get_workspace`, `handoff_case`, `hire_agent`, `list_project_repositories`, `list_responsibilities`, `list_workflows`, `list_workspaces`, `prepare_repository`, `read_agent_instructions`, `read_case`, `read_workflow`, `remove_from_responsibility`, `restore_agent_instructions`, `schedule_wake`, `search_api`, `select_workspace`, `send_chat_message`, `set_task_monitor`, `set_task_title`, `submit_complaint`, `submit_suggestion`, `update_agent_instructions`, `update_area`, `update_case`, `update_responsibility`, `update_routine`, `update_skill_details`, `update_workflow`.
- The generated provider contract contains exactly the live catalog; the canonical union remains the migration authority until all scenario-only operations are either implemented, deferred, or removed by an explicit reconciliation decision.
- `generic_api_request` stays exported only for controlled tests and cannot be cited as real-surface, mock-parity, or PRP product coverage.
@@ -20,9 +20,9 @@ describe("canonical semantic-catalog reconciliation authority", () => {
it("pins the reconciled op-set relationship between the two catalogs", () => {
const summary = capabilityCatalogReconciliation();
expect(summary.scenarioCount).toBe(40);
expect(summary.liveCount).toBe(71);
expect(summary.liveCount).toBe(72);
expect(summary.sharedCount).toBe(29);
expect(summary.unionCount).toBe(82);
expect(summary.unionCount).toBe(83);
// Any operation added to or removed from either catalog without a
// reconciliation decision changes these exact sets and fails the gate.
expect(summary.liveOnly).toEqual([
@@ -67,6 +67,7 @@ describe("canonical semantic-catalog reconciliation authority", () => {
"update_case",
"update_responsibility",
"update_routine",
"update_skill_details",
"update_workflow",
]);
expect(summary.scenarioOnly).toEqual([
@@ -85,7 +86,7 @@ describe("canonical semantic-catalog reconciliation authority", () => {
});
it("is the single source both catalogs derive their operation set from", () => {
expect(CAPABILITY_CANONICAL_OPERATIONS).toHaveLength(82);
expect(CAPABILITY_CANONICAL_OPERATIONS).toHaveLength(83);
const canonicalIds = new Set(CAPABILITY_CANONICAL_OPERATIONS.map((operation) => operation.operationId));
// Neither catalog may contain an operation absent from the canonical source.
for (const tool of SCENARIO_CATALOG) expect(canonicalIds.has(tool.operationId)).toBe(true);
@@ -119,7 +120,7 @@ describe("canonical semantic-catalog reconciliation authority", () => {
});
it("names placement, claims, task modes, side-effect class, idempotency, redaction, mock mapping, real binding status, and PRP evidence for every operation", () => {
expect(CAPABILITY_CANONICAL_CATALOG).toHaveLength(82);
expect(CAPABILITY_CANONICAL_CATALOG).toHaveLength(83);
for (const operation of CAPABILITY_CANONICAL_CATALOG) {
expect(operation.placement).toMatch(/^(always|optional)_agent_tool$/);
expect(Array.isArray(operation.requiredClaims)).toBe(true);
@@ -145,7 +146,7 @@ describe("canonical semantic-catalog reconciliation authority", () => {
it("classifies real binding status so generic_api_request is never product coverage", () => {
const summary = capabilityCatalogReconciliation();
expect(summary.byRealBindingStatus).toEqual({
live_codex: 70,
live_codex: 71,
scenario_mock: 11,
test_only: 1,
});
@@ -160,7 +160,7 @@ describe("semantic action catalog", () => {
(action) => action.operationId,
);
expect(operationIds).toHaveLength(63);
expect(operationIds).toHaveLength(64);
expect(operationIds).toContain("set_task_monitor");
expect(operationIds).toContain("send_chat_message");
expect(new Set(operationIds).size).toBe(operationIds.length);
@@ -14,6 +14,7 @@ import { sendChatMessageAction } from "../protocol-actions/send-chat-message.js"
import { reassignTaskAction } from "../protocol-actions/reassign-task.js";
import { listRoutinesAction } from "../protocol-actions/list-routines.js";
import { updateRoutineAction } from "../protocol-actions/update-routine.js";
import { updateSkillDetailsAction } from "../protocol-actions/update-skill-details.js";
import {
createAreaAction, createResponsibilityAction, deleteAreaAction, deleteResponsibilityAction, fileUnderResponsibilityAction,
findResponsibilitiesForAction, getResponsibilityAction, listResponsibilitiesAction, removeFromResponsibilityAction,
@@ -525,7 +526,7 @@ const descriptors: readonly PaperclipSemanticActionDescriptor[] = [
createAreaAction, updateAreaAction, deleteAreaAction,
createResponsibilityAction, updateResponsibilityAction, deleteResponsibilityAction,
fileUnderResponsibilityAction, removeFromResponsibilityAction,
listRoutinesAction, updateRoutineAction,
listRoutinesAction, updateRoutineAction, updateSkillDetailsAction,
].map((action) => descriptor({
operationId: action.id,
title: action.documentation.title,
@@ -50,6 +50,7 @@ export type PaperclipSemanticActionId =
| "remove_from_responsibility"
| "list_routines"
| "update_routine"
| "update_skill_details"
| "create_task"
| "handoff_case"
| "read_case"
@@ -466,13 +466,13 @@ describe("workflow reports and stress traceability", () => {
candidateFailures: 36,
});
expect(report.coverage).toMatchObject({
canonicalOperations: 82,
canonicalOperations: 83,
capabilityCases: 106,
workflows: 12,
stressFindings: 44,
stressExclusions: 1,
});
expect(report.coverage.operations).toHaveLength(82);
expect(report.coverage.operations).toHaveLength(83);
expect(report.coverage.operations).toEqual(expect.arrayContaining(
["create_case", "read_case", "update_case", "handoff_case", "list_workflows", "read_workflow", "create_workflow", "update_workflow", "send_chat_message"].map(operationId =>
expect.objectContaining({ operationId, workflowIds: [] })),
@@ -484,7 +484,7 @@ describe("workflow reports and stress traceability", () => {
)?.workflowIds.length,
).toBeGreaterThan(0);
expect(renderRunnerWorkflowMarkdown(report)).toContain(
"82 operations · 106 capability cases · 12 workflows",
"83 operations · 106 capability cases · 12 workflows",
);
expect(renderRunnerWorkflowJUnit(report)).toContain(
'tests="36" failures="36" skipped="0"',
@@ -16,6 +16,7 @@ import { updateSkillAction } from "./update-skill.js";
import { createProjectAction } from "./create-project.js";
import { listProjectRepositoriesAction } from "./list-project-repositories.js";
import { updateRoutineAction } from "./update-routine.js";
import { updateSkillDetailsAction } from "./update-skill-details.js";
import {
createAreaAction, createResponsibilityAction, deleteAreaAction, deleteResponsibilityAction, fileUnderResponsibilityAction,
findResponsibilitiesForAction, getResponsibilityAction, listResponsibilitiesAction, removeFromResponsibilityAction,
@@ -102,6 +103,7 @@ export const PAPERCLIP_PROTOCOL_ACTIONS = deepFreezeProtocolAction([
fileUnderResponsibilityAction,
removeFromResponsibilityAction,
updateRoutineAction,
updateSkillDetailsAction,
searchApiAction,
callApiAction,
administerCompanyAction,
@@ -58,7 +58,7 @@ export const listResponsibilitiesAction = responsibilityAction({
export const getResponsibilityAction = responsibilityAction({
id: "get_responsibility", title: "Read responsibility", order: 85, write: false,
description: "Read one responsibility in full: its bar and health, area, the projects, tasks and routines under it (with link IDs for items filed directly, and items under it through a filed project), the skills of the agents doing its work, and its latest status report.",
description: "Read one responsibility in full: its bar and health, area, the projects, tasks and routines under it (with link IDs for items filed directly, and items under it through a filed project), its skills (filed by hand, with a link ID, and computed from the agents doing its work), and its latest status report.",
schema: { type: "object", additionalProperties: false, required: ["responsibilityId"], properties: {
responsibilityId: { type: "string", pattern: uuidPattern, description: "Responsibility ID from list_responsibilities or find_responsibilities_for." },
} }, example: { responsibilityId: "00000000-0000-4000-8000-000000000001" },
@@ -66,9 +66,9 @@ export const getResponsibilityAction = responsibilityAction({
export const findResponsibilitiesForAction = responsibilityAction({
id: "find_responsibilities_for", title: "Find responsibilities for an item", order: 86, write: false,
description: "List the proposed and active responsibilities a project, task or routine is filed under, directly or through its project. An empty list means it is uncovered.",
description: "List the proposed and active responsibilities a project, task, routine or company skill is filed under, directly or (for a task or routine) through its project. An empty list means it is uncovered.",
schema: { type: "object", additionalProperties: false, required: ["kind", "id"], properties: {
kind: { type: "string", enum: ["project", "task", "routine"], description: "What the item is." },
kind: { type: "string", enum: ["project", "task", "routine", "skill"], description: "What the item is." },
id: { type: "string", minLength: 1, maxLength: 200, description: "The item's ID. For a task, an identifier such as PAP-123 also works." },
} }, example: { kind: "routine", id: "00000000-0000-4000-8000-000000000002" },
});
@@ -78,9 +78,9 @@ const nullableText = (description: string) => ({ type: ["string", "null"], maxLe
const title = { type: "string", minLength: 1, maxLength: 200 } as const;
const items = {
type: "array", minItems: 1, maxItems: 50,
description: "What to file: each a project, task or routine by ID. A task can also be an identifier such as PAP-12.",
description: "What to file: each a project, task, routine or company skill by ID. A task can also be an identifier such as PAP-12.",
items: { type: "object", additionalProperties: false, required: ["kind", "id"], properties: {
kind: { type: "string", enum: ["project", "task", "routine"] },
kind: { type: "string", enum: ["project", "task", "routine", "skill"] },
id: { type: "string", minLength: 1, maxLength: 200 },
} },
} as const;
@@ -169,7 +169,7 @@ export const deleteResponsibilityAction = responsibilityAction({
export const fileUnderResponsibilityAction = responsibilityAction({
id: "file_under_responsibility", title: "File work under responsibility", order: 93, write: true,
description: `File projects, tasks and routines under a responsibility in one step. With moveFrom it is a move: the items also leave that responsibility, or with all, every other responsibility of the same person. An item can sit under several responsibilities; filing one already there changes nothing. ${actsFor}`,
description: `File projects, tasks, routines and company skills under a responsibility in one step. With moveFrom it is a move: the items also leave that responsibility, or with all, every other responsibility of the same person. An item can sit under several responsibilities; filing one already there changes nothing. ${actsFor}`,
schema: { type: "object", additionalProperties: false, required: ["responsibilityId", "items"], properties: {
responsibilityId: id("Responsibility ID to file under."), items,
moveFrom: { type: "string", description: "A responsibility ID to move the items from, or all." },
@@ -178,7 +178,7 @@ export const fileUnderResponsibilityAction = responsibilityAction({
export const removeFromResponsibilityAction = responsibilityAction({
id: "remove_from_responsibility", title: "Remove work from responsibility", order: 94, write: true,
description: `Unfile projects, tasks and routines from a responsibility by what they are; no link IDs needed. The items themselves are not changed. ${actsFor}`,
description: `Unfile projects, tasks, routines and skills from a responsibility by what they are; no link IDs needed. The items themselves are not changed. ${actsFor}`,
schema: { type: "object", additionalProperties: false, required: ["responsibilityId", "items"], properties: {
responsibilityId: id("Responsibility ID."), items,
} }, example: { responsibilityId: "00000000-0000-4000-8000-000000000001", items: [{ kind: "task", id: "PAP-12" }] },
@@ -0,0 +1,31 @@
const description = "Change a company skill's catalog details outside SKILL.md: its tagline (one line) and categories; send tagline, categories or both. Its name and description are SKILL.md frontmatter; change those with update_skill. Uses the skill page's edit policy.";
/** Canonical definition and documentation for `update_skill_details`. */
export const updateSkillDetailsAction = {
id: "update_skill_details",
canonical: {
operationId: "update_skill_details", surfaces: ["live"], placement: "optional_agent_tool",
optionalGroup: "company_skills", requiredClaims: [], taskModes: ["standard"],
sideEffectClass: "company_write", idempotency: "none", disabledByDefault: false,
realBindingStatus: "live_codex", realServiceBinding: "PaperclipRunnerToolAuthority",
prpEvidence: "Authenticated company skill update API with the company skill edit policy and attributed activity.",
prpBindingStatus: "bound", legacyAliases: [],
},
documentation: { title: "Update skill details", description, note: null },
examples: {
call: { operationId: "update_skill_details", input: { skillId: "00000000-0000-4000-8000-000000000001", tagline: "Reviews pull requests", categories: ["engineering"] } },
scenarioCall: null,
success: { ok: true, operationId: "update_skill_details", result: {} },
},
live: { order: 97, descriptor: {
schema: "paperclip.semantic-tool.v1", operationId: "update_skill_details", version: 1,
title: "Update skill details", description, exposure: "optional", requiredClaims: [], allowedModes: ["standard"],
inputSchema: { type: "object", additionalProperties: false, required: ["skillId"], properties: {
skillId: { type: "string", pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" },
tagline: { type: ["string", "null"], maxLength: 120, description: "One line shown with the skill; null clears it." },
categories: { type: "array", maxItems: 20, items: { type: "string", minLength: 1, maxLength: 60 }, description: "Replaces its categories." },
} },
outputSchema: { type: "object", additionalProperties: true },
} },
scenario: null,
} as const;
@@ -45,6 +45,7 @@ const NAMESPACE: Readonly<Record<CapabilitySemanticOperationId, string>> = Objec
create_responsibility: "responsibilities", update_responsibility: "responsibilities", delete_responsibility: "responsibilities",
file_under_responsibility: "responsibilities", remove_from_responsibility: "responsibilities",
list_routines: "routines", update_routine: "routines",
update_skill_details: "skills",
set_dependencies: "delegation", reassign_task: "delegation", list_approvals: "governance", get_approval: "governance",
get_approval_context: "governance", request_approval: "governance",
decide_approval: "governance", comment_on_approval: "governance",
@@ -210,6 +210,7 @@ export class CapabilitySemanticDispatcher {
"file_under_responsibility" as const,
"remove_from_responsibility" as const,
"update_routine" as const,
"update_skill_details" as const,
"handoff_case" as const,
"read_case" as const,
"update_case" as const,
@@ -51,6 +51,7 @@ const NAMESPACE: Readonly<Record<PaperclipSemanticActionId, string>> =
create_responsibility: "responsibilities", update_responsibility: "responsibilities", delete_responsibility: "responsibilities",
file_under_responsibility: "responsibilities", remove_from_responsibility: "responsibilities",
list_routines: "routines", update_routine: "routines",
update_skill_details: "skills",
request_approval: "governance",
decide_approval: "governance",
comment_on_approval: "governance",
@@ -113,7 +113,7 @@ describe("Capability semantic catalog and authorization", () => {
it("publishes a stable narrow catalog without credentials or control-plane-owned tools", () => {
const names = CAPABILITY_SEMANTIC_TOOL_CATALOG.map((tool) => tool.operationId);
expect(new Set(names).size).toBe(names.length);
expect(names).toHaveLength(71);
expect(names).toHaveLength(72);
expect(names).toContain("send_chat_message");
expect(names).toEqual(expect.arrayContaining(["list_workflows", "read_workflow", "create_workflow", "update_workflow"]));
expect(names).toContain("set_task_monitor");
@@ -70,6 +70,7 @@ export type CapabilitySemanticOperationId =
| "remove_from_responsibility"
| "list_routines"
| "update_routine"
| "update_skill_details"
| "create_task"
| "handoff_case"
| "read_case"
@@ -404,11 +404,13 @@ export interface ResponsibilityDashboardSnapshotArea {
description?: string | null;
}
/** The projects, tasks and routines filed directly under a responsibility, each sorted. */
/** The projects, tasks, routines and skills filed directly under a responsibility, each sorted. */
export interface ResponsibilityDashboardSnapshotLinks {
projectIds: string[];
issueIds: string[];
routineIds: string[];
/** Absent in versions saved before skills could be filed; restoring one leaves filed skills as they are. */
skillIds?: string[];
}
/**
@@ -466,6 +468,7 @@ export const responsibilityDashboardSnapshotSchema = z.object({
projectIds: z.array(z.string()),
issueIds: z.array(z.string()),
routineIds: z.array(z.string()),
skillIds: z.array(z.string()).optional(),
}).optional(),
description: z.string().nullable().optional(),
runByAgentId: z.string().nullable().optional(),
@@ -564,6 +567,7 @@ export function snapshotLinkKeys(links: ResponsibilityDashboardSnapshotLinks): s
...links.projectIds.map((id) => `project:${id}`),
...links.issueIds.map((id) => `issue:${id}`),
...links.routineIds.map((id) => `routine:${id}`),
...(links.skillIds ?? []).map((id) => `skill:${id}`),
];
}
@@ -623,8 +627,10 @@ export function responsibilityDashboardChangeSummary(
if (was.areaId !== item.areaId) moved += 1;
// Only versions that both hold these can be compared; an older version holds none.
if (was.links && item.links) {
const before = new Set(snapshotLinkKeys(was.links));
const after = new Set(snapshotLinkKeys(item.links));
// Skills compare only when both versions hold them.
const skills = was.links.skillIds !== undefined && item.links.skillIds !== undefined;
const before = new Set(snapshotLinkKeys(skills ? was.links : { ...was.links, skillIds: undefined }));
const after = new Set(snapshotLinkKeys(skills ? item.links : { ...item.links, skillIds: undefined }));
for (const key of after) if (!before.has(key)) filed += 1;
for (const key of before) if (!after.has(key)) unfiled += 1;
}
+12 -6
View File
@@ -92,7 +92,7 @@ export interface Responsibility {
updatedAt: Date;
}
/** One project, task or routine filed under a responsibility. Exactly one target id is set. */
/** One project, task, routine or company skill filed under a responsibility. Exactly one target id is set. */
export interface ResponsibilityLink {
id: string;
companyId: string;
@@ -100,6 +100,7 @@ export interface ResponsibilityLink {
projectId: string | null;
issueId: string | null;
routineId: string | null;
skillId: string | null;
createdAt: Date;
}
@@ -262,12 +263,17 @@ export interface ResponsibilityRoutineLastRun {
}
/**
* A company skill held by an agent that works under a responsibility: its
* `runByAgentId`, the assignees of its open member tasks and of its
* non-archived routines, and its linked projects' lead agents. Paperclip's
* own coordination and onboarding skills are left out.
* A company skill under a responsibility: filed there by hand (`linkId`), or
* held by an agent that works under it (`computed`): its `runByAgentId`, the
* assignees of its open member tasks and of its non-archived routines, and
* its linked projects' lead agents. A skill can be both. Paperclip's own
* coordination and onboarding skills are left out of the computed ones.
*/
export interface ResponsibilitySkillSummary {
/** The link when the skill is filed here by hand; null when it is only computed. */
linkId: string | null;
/** True when an agent that works under the responsibility holds it. */
computed: boolean;
id: string;
key: string;
slug: string;
@@ -276,7 +282,7 @@ export interface ResponsibilitySkillSummary {
tagline: string | null;
iconUrl: string | null;
color: string | null;
/** Which of those agents hold it, sorted. */
/** Which of the agents working under it hold it, sorted; empty for a filed skill no such agent holds. */
agentIds: string[];
}
@@ -169,9 +169,11 @@ export const linkResponsibilitySchema = z.object({
projectId: z.string().uuid().optional(),
issueId: z.string().uuid().optional(),
routineId: z.string().uuid().optional(),
/** A company skill in the same company. */
skillId: z.string().uuid().optional(),
}).strict().refine(
(value) => [value.projectId, value.issueId, value.routineId].filter((id) => id !== undefined).length === 1,
{ message: "Provide exactly one of projectId, issueId or routineId" },
(value) => [value.projectId, value.issueId, value.routineId, value.skillId].filter((id) => id !== undefined).length === 1,
{ message: "Provide exactly one of projectId, issueId, routineId or skillId" },
);
export type LinkResponsibility = z.infer<typeof linkResponsibilitySchema>;
@@ -229,15 +231,16 @@ export const responsibilityLinkLookupQuerySchema = z.object({
issueId: z.string().uuid().optional(),
projectId: z.string().uuid().optional(),
routineId: z.string().uuid().optional(),
skillId: z.string().uuid().optional(),
}).refine(
(value) => [value.projectId, value.issueId, value.routineId].filter((id) => id !== undefined).length === 1,
{ message: "Provide exactly one of issueId, projectId or routineId" },
(value) => [value.projectId, value.issueId, value.routineId, value.skillId].filter((id) => id !== undefined).length === 1,
{ message: "Provide exactly one of issueId, projectId, routineId or skillId" },
);
export type ResponsibilityLinkLookupQuery = z.infer<typeof responsibilityLinkLookupQuerySchema>;
/** What can be filed under a responsibility by kind and id. */
export const RESPONSIBILITY_FILE_ITEM_KINDS = ["project", "task", "routine"] as const;
export const RESPONSIBILITY_FILE_ITEM_KINDS = ["project", "task", "routine", "skill"] as const;
export type ResponsibilityFileItemKind = (typeof RESPONSIBILITY_FILE_ITEM_KINDS)[number];
const fileItem = z.object({
+109 -1
View File
@@ -11,6 +11,7 @@ import {
agentWakeupRequests,
companies,
companyMemberships,
companySkillSources,
companySkills,
createDb,
documents,
@@ -35,7 +36,8 @@ import { errorHandler } from "../middleware/index.js";
import { responsibilityRoutes } from "../routes/responsibilities.js";
import { responsibilityAreaRoutes } from "../routes/responsibility-areas.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { responsibilityDashboardVersionService } from "../services/responsibility-dashboard-versions.js";
import { dashboardSnapshotHash, responsibilityDashboardVersionService } from "../services/responsibility-dashboard-versions.js";
import { withSkillActor } from "../services/skill-access.js";
import type { IssueAssignmentWakeupDeps } from "../services/issue-assignment-wakeup.js";
import {
getEmbeddedPostgresTestSupport,
@@ -117,6 +119,7 @@ describeEmbeddedPostgres("responsibility routes", () => {
await db.delete(issues);
await db.delete(projects);
await db.delete(companySkills);
await db.delete(companySkillSources);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(instanceSettings);
@@ -946,6 +949,39 @@ describeEmbeddedPostgres("responsibility routes", () => {
expect(deleted?.entityId).toBe(area.id);
});
it("files a company skill by hand beside the computed ones, finds it, and moves or unfiles it", async () => {
await enable();
const company = await seedCompany();
const app = createApp(db, localBoardActor());
const [deck, crm] = await db.insert(companySkills).values([
{ companyId: company.id, key: "acme/skills/deck-writing", slug: "deck-writing", name: "Deck writing", markdown: "# Deck" },
{ companyId: company.id, key: "acme/skills/crm", slug: "crm", name: "CRM upkeep", markdown: "# CRM" },
]).returning();
const runner = await seedAgent(company.id, "Runner", ["acme/skills/deck-writing"]);
const fundraising = await createResponsibility(app, company.id, { runByAgentId: runner.id });
const sales = await createResponsibility(app, company.id, { title: "Sales" });
const linked = await request(app).post(`/api/responsibilities/${fundraising.id}/links`).send({ skillId: deck!.id });
expect(linked.status).toBe(201);
expect((await request(app).post(`/api/responsibilities/${fundraising.id}/file`).send({ items: [{ kind: "skill", id: crm!.id }] })).status).toBe(200);
const detail = await request(app).get(`/api/responsibilities/${fundraising.id}`);
const byName = Object.fromEntries(detail.body.skills.map((skill: { name: string }) => [skill.name, skill]));
// Filed and held by the agent that runs it: one card, both ways.
expect(byName["Deck writing"]).toMatchObject({ linkId: linked.body.link.id, computed: true, agentIds: [runner.id] });
expect(byName["CRM upkeep"]).toMatchObject({ computed: false, agentIds: [] });
expect(byName["CRM upkeep"].linkId).toEqual(expect.any(String));
const lookup = await request(app).get(`/api/companies/${company.id}/responsibility-links/lookup?skillId=${crm!.id}`);
expect(lookup.body.responsibilities).toEqual([expect.objectContaining({ id: fundraising.id, via: "direct" })]);
const moved = await request(app).post(`/api/responsibilities/${sales.id}/file`).send({ items: [{ kind: "skill", id: crm!.id }], moveFrom: fundraising.id });
expect(moved.body.unfiled).toHaveLength(1);
const unfiled = await request(app).post(`/api/responsibilities/${sales.id}/unfile`).send({ items: [{ kind: "skill", id: crm!.id }] });
expect(unfiled.body.unfiled).toEqual([expect.objectContaining({ skillId: crm!.id })]);
expect((await request(app).post(`/api/responsibilities/${sales.id}/links`).send({ skillId: randomUUID() })).status).toBe(404);
});
describe("an agent acting for the person its run works for", () => {
async function latestVersion(companyId: string, ownerUserId = OWNER) {
const rows = await db.select().from(responsibilityDashboardVersions)
@@ -1116,6 +1152,78 @@ describeEmbeddedPostgres("responsibility routes", () => {
expect(removedArea.status).toBe(200);
});
it("undoes filing a skill from the Dashboard history", async () => {
await enable();
const company = await seedCompany();
const agent = await seedAgent(company.id);
const app = await actingAgent(company.id, agent.id);
const hiring = await createResponsibility(createApp(db, localBoardActor()), company.id, { title: "Hiring" });
const [skill] = await db.insert(companySkills).values({ companyId: company.id, key: "acme/skills/interviews", slug: "interviews", name: "Interviews", markdown: "# Interviews" }).returning();
expect((await request(app).post(`/api/responsibilities/${hiring.id}/file`).send({ items: [{ kind: "skill", id: skill!.id }] })).status).toBe(200);
const version = await latestVersion(company.id);
expect(version?.summary).toMatch(/filed 1 item/i);
const versions = responsibilityDashboardVersionService(db);
await versions.restore((await versions.getById(version!.previousVersionId!))!, { userId: OWNER });
expect(await db.select().from(responsibilityLinks).where(eq(responsibilityLinks.skillId, skill!.id))).toHaveLength(0);
});
it("undoes the first skill filed after a version saved before skills could be filed", async () => {
await enable();
const company = await seedCompany();
const agent = await seedAgent(company.id);
const hiring = await createResponsibility(createApp(db, localBoardActor()), company.id, { title: "Hiring" });
const versions = responsibilityDashboardVersionService(db);
// A version from the release before: it holds filed items, but no list of filed skills.
const current = await db.transaction((tx) => versions.captureSnapshot(tx as unknown as Db, company.id, OWNER));
const older = { ...current, responsibilities: current.responsibilities.map((item) => {
const { skillIds: _skillIds, ...links } = item.links!;
return { ...item, links };
}) };
await db.insert(responsibilityDashboardVersions).values({
companyId: company.id, ownerUserId: OWNER, cause: "person", summary: "1 responsibility",
snapshot: older as unknown as Record<string, unknown>, snapshotHash: dashboardSnapshotHash(older),
});
const [skill] = await db.insert(companySkills).values({ companyId: company.id, key: "acme/skills/interviews", slug: "interviews", name: "Interviews", markdown: "# Interviews" }).returning();
const filed = await request(await actingAgent(company.id, agent.id)).post(`/api/responsibilities/${hiring.id}/file`).send({ items: [{ kind: "skill", id: skill!.id }] });
const version = (await versions.getById(filed.headers["x-paperclip-dashboard-version"]))!;
await versions.restore((await versions.getById(version.previousVersionId!))!, { userId: OWNER });
expect(await db.select().from(responsibilityLinks).where(eq(responsibilityLinks.skillId, skill!.id))).toHaveLength(0);
});
it("leaves skills the restoring person cannot see as they are on Undo, and hides them from readers who cannot see them", async () => {
await enable();
const company = await seedCompany();
const agent = await seedAgent(company.id);
const hiring = await createResponsibility(createApp(db, localBoardActor()), company.id, { title: "Hiring" });
// A skill from a source shared only with projects (none here), so no person or agent can see it.
const [source] = await db.insert(companySkillSources).values({
companyId: company.id, repositoryUrl: "https://github.com/acme/private-skills", fullName: "acme/private-skills", trackingRef: "main", accessScope: "projects",
}).returning();
const [shown, hidden] = await db.insert(companySkills).values([
{ companyId: company.id, key: "acme/skills/interviews", slug: "interviews", name: "Interviews", markdown: "# Interviews" },
{ companyId: company.id, key: "acme/private/offers", slug: "offers", name: "Offers", markdown: "# Offers", accessSourceId: source!.id },
]).returning();
await db.insert(responsibilityLinks).values([
{ companyId: company.id, responsibilityId: hiring.id, skillId: shown!.id },
{ companyId: company.id, responsibilityId: hiring.id, skillId: hidden!.id },
]);
const app = await actingAgent(company.id, agent.id);
const detail = await request(app).get(`/api/responsibilities/${hiring.id}`);
expect(detail.body.skills.map((skill: { id: string }) => skill.id)).toEqual([shown!.id]);
expect((await request(app).post(`/api/responsibilities/${hiring.id}/links`).send({ skillId: hidden!.id })).status).toBe(404);
// A change saves the dashboard as it is (both skills filed) first.
const routine = await db.insert(routines).values({ companyId: company.id, title: "Weekly sourcing" }).returning().then((r) => r[0]!);
const filed = await request(app).post(`/api/responsibilities/${hiring.id}/file`).send({ items: [{ kind: "routine", id: routine.id }] });
const versions = responsibilityDashboardVersionService(db);
const before = (await versions.getById((await versions.getById(filed.headers["x-paperclip-dashboard-version"]))!.previousVersionId!))!;
await db.delete(responsibilityLinks).where(eq(responsibilityLinks.responsibilityId, hiring.id));
await withSkillActor(sessionBoardActor(company.id, OWNER, "owner"), () => versions.restore(before, { userId: OWNER }));
const links = await db.select().from(responsibilityLinks).where(eq(responsibilityLinks.responsibilityId, hiring.id));
expect(links.map((link) => link.skillId)).toEqual([shown!.id]);
});
it("names the saved version, and undoes a health override and an area description", async () => {
await enable();
const company = await seedCompany();
+2 -2
View File
@@ -125,8 +125,8 @@ export const experimentalApiDocs: Record<string, { summary: string; description:
description: "Requires enableResponsibilities. A board user, or an agent acting for a member of the company (saved as a version of that person's Dashboard they can undo)." },
"DELETE /api/responsibility-areas/{id}": { summary: "Delete an area permanently",
description: "Requires enableResponsibilities. Its responsibilities move to moveResponsibilitiesTo (an area that is not archived) or are left with no area. A board user, or an agent acting for a member of the company with confirmationId: an accepted request_confirmation card it posted, with target { type: custom, key: responsibility-area-delete:<id> }. Returns the area and movedResponsibilities." },
"POST /api/responsibilities/{id}/links": { summary: "File a project, task or routine under a responsibility",
description: "Requires enableResponsibilities. Send exactly one of projectId, issueId or routineId. An item can sit under several responsibilities; linking it here does not remove it from any other. Returns 201 for a new link and 200 when it was already linked here." },
"POST /api/responsibilities/{id}/links": { summary: "File a project, task, routine or skill under a responsibility",
description: "Requires enableResponsibilities. Send exactly one of projectId, issueId, routineId or skillId (a company skill the caller may see). An item can sit under several responsibilities; linking it here does not remove it from any other. Returns 201 for a new link and 200 when it was already linked here." },
"DELETE /api/responsibilities/{id}/links/{linkId}": { summary: "Remove an item from a responsibility",
description: "Requires enableResponsibilities. Removes only the link; the project, task or routine is unchanged." },
"POST /api/responsibilities/{id}/delegate": { summary: "Hand work under a responsibility to an agent",
+22 -18
View File
@@ -33,6 +33,7 @@ import {
logActivity,
} from "../services/index.js";
import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "../services/issue-assignment-wakeup.js";
import { skillAccessService } from "../services/skill-access.js";
import {
reportVersionOf,
responsibilityAgentChangeService,
@@ -60,13 +61,14 @@ function fileTarget(item: { kind: ResponsibilityFileItemKind; id: string }): Res
return { kind: item.kind === "task" ? "issue" : item.kind, id: item.id };
}
function linkTargetType(link: { projectId: string | null; issueId: string | null }) {
return link.projectId ? "project" : link.issueId ? "issue" : "routine";
function linkTargetType(link: { projectId: string | null; issueId: string | null; routineId: string | null }) {
return link.projectId ? "project" : link.issueId ? "issue" : link.routineId ? "routine" : "skill";
}
function linkTarget(body: LinkResponsibility | ResponsibilityLinkLookupQuery): ResponsibilityLinkTarget {
if (body.projectId) return { kind: "project", id: body.projectId };
if (body.issueId) return { kind: "issue", id: body.issueId };
if (body.skillId) return { kind: "skill", id: body.skillId };
return { kind: "routine", id: body.routineId! };
}
@@ -141,12 +143,14 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
await assertAgentCompanyScope(req, companyId);
}
async function readScope(req: Request): Promise<ResponsibilityReadScope> {
const [issueReadCondition, projectReadCondition] = await Promise.all([
/** The reader's visibility in `companyId`, including which of its skills they may see. */
async function readScope(req: Request, companyId: string): Promise<ResponsibilityReadScope> {
const [issueReadCondition, projectReadCondition, skillReadCondition] = await Promise.all([
issueReadSqlCondition(db, req.actor),
projectReadSqlCondition(db, req.actor),
skillAccessService(db, req.actor).condition(companyId),
]);
return { issueReadCondition, projectReadCondition };
return { issueReadCondition, projectReadCondition, skillReadCondition };
}
const boardCanManageOwner = boardCanManageResponsibilityOwner;
@@ -298,7 +302,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
}
res.json(await svc.overview(companyId, ownerUserId, {
includeLetGo: query.includeLetGo,
scope: await readScope(req),
scope: await readScope(req, companyId),
}));
});
@@ -352,7 +356,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
});
if (newArea) await logAreaCreated(req, newArea);
if (!isNew) {
res.json(await svc.withRollup(created, await readScope(req)));
res.json(await svc.withRollup(created, await readScope(req, companyId)));
return;
}
await logMutation(req, companyId, "responsibility.created", created.id, {
@@ -363,21 +367,21 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
areaId: created.areaId,
});
await logAreaActivated(req, activatedArea, created.id);
res.status(201).json(await svc.withRollup(created, await readScope(req)));
res.status(201).json(await svc.withRollup(created, await readScope(req, companyId)));
});
router.get("/responsibilities/:id", async (req, res) => {
await assertResponsibilitiesEnabled();
const row = await loadForRead(req, res);
if (!row) return;
res.json(await svc.detail(row, await readScope(req), { actor: req.actor }));
res.json(await svc.detail(row, await readScope(req, row.companyId), { actor: req.actor }));
});
router.patch("/responsibilities/:id", validate(updateResponsibilitySchema), async (req, res) => {
await assertResponsibilitiesEnabled();
const row = await loadForWrite(req, res);
if (!row) return;
const scope = await readScope(req);
const scope = await readScope(req, row.companyId);
const actsFor = req.actor.type === "agent" ? await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId) : null;
const { areaTitle, ...patch } = req.body as typeof req.body & { areaTitle?: string };
if (areaTitle && patch.areaId !== undefined) throw unprocessable("Send areaId or areaTitle, not both");
@@ -458,7 +462,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
await assertAgentMayFileUnder(req, row);
const target = linkTarget(req.body);
const actsFor = req.actor.type === "agent" ? await agentActsForResponsibilityOwner(db, req, row.companyId, row.ownerUserId) : null;
const scope = await readScope(req);
const scope = await readScope(req, row.companyId);
const result = await inChange(req, res, { companyId: row.companyId, ownerUserIds: actsFor ? [row.ownerUserId] : [] },
({ svc: scoped }) => scoped.link(row, target, scope));
if (result.created) {
@@ -488,11 +492,11 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
res.status(404).json({ error: "Link not found" });
return;
}
const targetType = removed.projectId ? "project" : removed.issueId ? "issue" : "routine";
const targetType = linkTargetType(removed);
await logMutation(req, row.companyId, "responsibility.unlinked", row.id, {
linkId: removed.id,
targetType,
targetId: removed.projectId ?? removed.issueId ?? removed.routineId,
targetId: removed.projectId ?? removed.issueId ?? removed.routineId ?? removed.skillId,
});
res.json(removed);
});
@@ -524,7 +528,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
moveFromIds = [source.id];
owners.add(source.ownerUserId);
}
const scope = await readScope(req);
const scope = await readScope(req, row.companyId);
const result = await inChange(req, res, { companyId: row.companyId, ownerUserIds: req.actor.type === "agent" && !actsFor ? [] : [...owners] },
({ svc: scoped }) => scoped.fileItems(row, targets, scope, { moveFromIds }));
for (const entry of result.filed.filter((item) => item.created)) {
@@ -538,7 +542,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
await logMutation(req, row.companyId, "responsibility.unlinked", link.responsibilityId, {
linkId: link.id,
targetType: linkTargetType(link),
targetId: link.projectId ?? link.issueId ?? link.routineId,
targetId: link.projectId ?? link.issueId ?? link.routineId ?? link.skillId,
movedToResponsibilityId: row.id,
});
}
@@ -561,7 +565,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
await logMutation(req, row.companyId, "responsibility.unlinked", row.id, {
linkId: link.id,
targetType: linkTargetType(link),
targetId: link.projectId ?? link.issueId ?? link.routineId,
targetId: link.projectId ?? link.issueId ?? link.routineId ?? link.skillId,
});
}
res.json({ unfiled: removed });
@@ -596,7 +600,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
runId: actor.runId,
identityContextId: req.actor.identityContextId ?? null,
authorizationActor: req.actor,
}, await readScope(req));
}, await readScope(req, row.companyId));
await references.syncIssue(issue.id);
await logActivity(db, {
companyId: row.companyId,
@@ -635,7 +639,7 @@ export function responsibilityRoutes(db: Db, opts: { heartbeat?: IssueAssignment
const companyId = req.params.companyId as string;
await assertCompanyRead(req, companyId);
const query = responsibilityLinkLookupQuerySchema.parse(req.query);
const responsibilities = await svc.lookup(companyId, linkTarget(query), await readScope(req));
const responsibilities = await svc.lookup(companyId, linkTarget(query), await readScope(req, companyId));
res.json({ responsibilities });
});
@@ -211,10 +211,10 @@ describe("PaperclipRunnerToolAuthority", () => {
issueId,
runId,
});
expect(authority.definitions()).toHaveLength(56);
expect(authority.definitions()).toHaveLength(57);
expect(authority.definitions().map(tool => tool.name)).toEqual(expect.arrayContaining([
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository",
"search_skills", "load_skill", "list_routines", "update_routine",
"search_skills", "load_skill", "list_routines", "update_routine", "update_skill_details",
]));
// 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")!;
@@ -48,7 +48,7 @@ import { resolveCoreTrustPreset } from "../trust-preset-resolver.js";
import { normalizeIssueExecutionPolicy, redactIssueMonitorExternalRef } from "../issue-execution-policy.js";
import { buildLowTrustSourceTrust, isLowTrustQuarantined, LOW_TRUST_QUARANTINED_BODY, resolveActorSourceTrustForIssue, sanitizeQuarantinedCommentForHigherTrust } from "../source-trust.js";
import { handoffPlanContext } from "./handoff-plan-context.js";
import { callCreateSkillTool, callUpdateSkillTool } from "../skill-tools.js";
import { callCreateSkillTool, callUpdateSkillDetailsTool, 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";
@@ -158,7 +158,7 @@ const IMPLEMENTED_OPERATIONS = new Set([
"search_api", "call_api", "hire_agent",
"get_task_context", "get_task_history", "search_tasks", "report_progress", "set_task_title", "set_task_monitor",
"request_human_input", "handoff_case", ...NATIVE_CASE_OPERATIONS,
"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",
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "create_skill", "update_skill", "update_skill_details", "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, ...ROUTINE_TOOL_NAMES,
@@ -942,6 +942,12 @@ export class PaperclipRunnerToolAuthority {
if (!apiUrl || !token) throw new Error("Skill tool authentication is unavailable");
return callUpdateSkillTool({ arguments: input, apiUrl, token, companyId: this.binding.companyId });
}
case "update_skill_details": {
const apiUrl = this.binding.apiUrl ?? process.env.PAPERCLIP_API_URL;
const token = this.#apiToken(context);
if (!apiUrl || !token) throw new Error("Skill tool authentication is unavailable");
return callUpdateSkillDetailsTool({ arguments: input, apiUrl, token, companyId: this.binding.companyId });
}
case "get_workspace":
case "list_workspaces":
case "select_workspace":
@@ -55,6 +55,7 @@ function dedicatedTools(method: string, path: string): string[] {
if (/\/agents\/\{[^}]+\}\/instructions-bundle\/restore$/.test(path) && method === "POST") return ["restore_agent_instructions"];
if (/\/companies\/\{[^}]+\}\/skills$/.test(path) && method === "POST") return ["create_skill"];
if (/\/companies\/\{[^}]+\}\/skills\/\{[^}]+\}\/files$/.test(path) && method === "PATCH") return ["update_skill"];
if (/\/companies\/\{[^}]+\}\/skills\/\{[^}]+\}$/.test(path) && method === "PATCH") return ["update_skill_details"];
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"];
+60 -20
View File
@@ -4,6 +4,7 @@ import {
agents,
authUsers,
companyMemberships,
companySkills,
issues,
projects,
responsibilities,
@@ -95,12 +96,28 @@ export type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
export interface ResponsibilityReadScope {
issueReadCondition: SQL<boolean>;
projectReadCondition: SQL<boolean>;
/** Company skills the reader may see. Left out, no filed skill is visible: visibility is never dropped by omission. */
skillReadCondition?: SQL;
}
/** The skill visibility condition of a scope; none means no skill is visible. */
function skillsVisible(scope: ResponsibilityReadScope): SQL {
return scope.skillReadCondition ?? sql`false`;
}
export type ResponsibilityLinkTarget =
| { kind: "project"; id: string }
| { kind: "issue"; id: string }
| { kind: "routine"; id: string };
| { kind: "routine"; id: string }
| { kind: "skill"; id: string };
/** The link column that holds a target of this kind. */
function linkColumn(kind: ResponsibilityLinkTarget["kind"]) {
return kind === "project" ? responsibilityLinks.projectId
: kind === "issue" ? responsibilityLinks.issueId
: kind === "routine" ? responsibilityLinks.routineId
: responsibilityLinks.skillId;
}
/**
* `board` with `viaAgentId`: an agent acting for the person `userId` (the
@@ -946,6 +963,13 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
if (!row) throw notFound("Task not found");
return row;
}
if (target.kind === "skill") {
const [row] = await db.select({ id: companySkills.id }).from(companySkills)
.where(and(eq(companySkills.id, target.id), eq(companySkills.companyId, companyId), skillsVisible(scope)))
.limit(1);
if (!row) throw notFound("Skill not found");
return row;
}
const [row] = await db.select({ id: routines.id, projectId: routines.projectId }).from(routines)
.where(and(eq(routines.id, target.id), eq(routines.companyId, companyId)))
.limit(1);
@@ -979,12 +1003,11 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
projectId: target.kind === "project" ? target.id : null,
issueId: target.kind === "issue" ? target.id : null,
routineId: target.kind === "routine" ? target.id : null,
skillId: target.kind === "skill" ? target.id : null,
};
const [inserted] = await tx.insert(responsibilityLinks).values(values).onConflictDoNothing().returning();
if (inserted) return { link: toLink(inserted), created: true };
const column = target.kind === "project" ? responsibilityLinks.projectId
: target.kind === "issue" ? responsibilityLinks.issueId
: responsibilityLinks.routineId;
const column = linkColumn(target.kind);
const [existing] = await tx.select().from(responsibilityLinks)
.where(and(eq(responsibilityLinks.responsibilityId, row.id), eq(column, target.id)));
if (!existing) throw new Error("Responsibility link insert conflicted but no link exists");
@@ -1031,11 +1054,29 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
const agentIds = new Set<string>();
if (row.runByAgentId) agentIds.add(row.runByAgentId);
for (const entry of [...taskAgents, ...routineAgents, ...leadAgents]) if (entry.agentId) agentIds.add(entry.agentId);
if (agentIds.size === 0) return [];
const assigned = await companySkillService(db, { actor }).listAssignedToAgents(row.companyId, [...agentIds]);
return assigned
.filter((entry) => !PLUMBING_SKILL_KEYS.has(entry.skill.key))
.map(({ skill, agentIds: holders }): ResponsibilitySkillSummary => ({
const [assigned, filed] = await Promise.all([
agentIds.size === 0 ? Promise.resolve([]) : companySkillService(db, { actor }).listAssignedToAgents(row.companyId, [...agentIds]),
// Skills filed here by hand, as far as the reader may see them.
db.select({
linkId: responsibilityLinks.id,
id: companySkills.id,
key: companySkills.key,
slug: companySkills.slug,
name: companySkills.name,
description: companySkills.description,
tagline: companySkills.tagline,
iconUrl: companySkills.iconUrl,
color: companySkills.color,
}).from(responsibilityLinks)
.innerJoin(companySkills, and(eq(companySkills.id, responsibilityLinks.skillId), eq(companySkills.companyId, responsibilityLinks.companyId)))
.where(and(eq(responsibilityLinks.responsibilityId, row.id), skillsVisible(scope))),
]);
const byId = new Map<string, ResponsibilitySkillSummary>();
for (const { skill, agentIds: holders } of assigned) {
if (PLUMBING_SKILL_KEYS.has(skill.key)) continue;
byId.set(skill.id, {
linkId: null,
computed: true,
id: skill.id,
key: skill.key,
slug: skill.slug,
@@ -1045,8 +1086,13 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
iconUrl: skill.iconUrl,
color: skill.color,
agentIds: holders,
}))
.sort((a, b) => a.name.localeCompare(b.name) || a.key.localeCompare(b.key));
});
}
for (const { linkId, ...skill } of filed) {
const computed = byId.get(skill.id);
byId.set(skill.id, computed ? { ...computed, linkId } : { ...skill, linkId, computed: false, agentIds: [] });
}
return [...byId.values()].sort((a, b) => a.name.localeCompare(b.name) || a.key.localeCompare(b.key));
}
async function artifactsFor(row: ResponsibilityRow, scope: ResponsibilityReadScope) {
@@ -1637,9 +1683,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
const unfiled: ResponsibilityLink[] = [];
if (moveFrom.length > 0) {
for (const target of targets) {
const column = target.kind === "project" ? responsibilityLinks.projectId
: target.kind === "issue" ? responsibilityLinks.issueId
: responsibilityLinks.routineId;
const column = linkColumn(target.kind);
const removed = await tx.delete(responsibilityLinks).where(and(
eq(responsibilityLinks.companyId, row.companyId),
inArray(responsibilityLinks.responsibilityId, moveFrom),
@@ -1657,9 +1701,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
return db.transaction(async (tx) => {
const removed: ResponsibilityLink[] = [];
for (const target of targets) {
const column = target.kind === "project" ? responsibilityLinks.projectId
: target.kind === "issue" ? responsibilityLinks.issueId
: responsibilityLinks.routineId;
const column = linkColumn(target.kind);
const rows = await tx.delete(responsibilityLinks)
.where(and(eq(responsibilityLinks.responsibilityId, row.id), eq(column, target.id)))
.returning();
@@ -1699,9 +1741,7 @@ export function responsibilityService(db: Db, deps: { routines?: ReturnType<type
): Promise<ResponsibilityLinkLookupEntry[]> {
const found: { id: string; projectId?: string | null } = await assertTargetInCompany(companyId, target, scope);
const projectId: string | null = target.kind === "project" ? null : found.projectId ?? null;
const column = target.kind === "project" ? responsibilityLinks.projectId
: target.kind === "issue" ? responsibilityLinks.issueId
: responsibilityLinks.routineId;
const column = linkColumn(target.kind);
const rows = await db.select({
id: responsibilities.id,
title: responsibilities.title,
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import { and, desc, eq, inArray, ne, notInArray, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { agents, issues, projects, responsibilities, responsibilityAreas, responsibilityDashboardVersions, responsibilityLinks, routines } from "@paperclipai/db";
import { agents, companySkills, issues, projects, responsibilities, responsibilityAreas, responsibilityDashboardVersions, responsibilityLinks, routines } from "@paperclipai/db";
import {
RESPONSIBILITY_DASHBOARD_UNDO_HOURS,
RESPONSIBILITY_DASHBOARD_VERSION_LIMIT,
@@ -15,6 +15,7 @@ import {
type ResponsibilityDashboardVersionSummary,
} from "@paperclipai/shared";
import { notFound } from "../errors.js";
import { skillAccessService } from "./skill-access.js";
/**
* Versions of a person's Dashboard (experimental `enableResponsibilities`).
@@ -76,7 +77,9 @@ export function dashboardSnapshotHash(snapshot: ResponsibilityDashboardSnapshot,
.map((item) => {
const base: unknown[] = [item.id, item.title, item.standard, item.areaId, item.status, item.sortOrder];
if (opts.legacy || !item.links) return base;
return [...base, item.links, item.description ?? null, item.runByAgentId ?? null,
// No filed skills hashes like a version saved before skills could be filed.
const links = { ...item.links, skillIds: item.links.skillIds?.length ? item.links.skillIds : undefined };
return [...base, links, item.description ?? null, item.runByAgentId ?? null,
item.evidence ?? null, item.healthOverride ?? null, item.healthNote ?? null];
});
return createHash("sha256").update(JSON.stringify({ areas, items })).digest("hex");
@@ -87,6 +90,11 @@ function isLegacySnapshot(snapshot: ResponsibilityDashboardSnapshot) {
return snapshot.responsibilities.some((item) => item.links === undefined);
}
/** True for a version saved before snapshots held filed skills: restoring it would leave filed skills alone. */
function lacksFiledSkills(snapshot: ResponsibilityDashboardSnapshot) {
return snapshot.responsibilities.some((item) => item.links !== undefined && item.links.skillIds === undefined);
}
/** Serialize all dashboard writes for one person inside `tx`. */
export async function lockDashboard(tx: DashboardTransaction, companyId: string, ownerUserId: string) {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`responsibility-dashboard:${companyId}:${ownerUserId}`}, 0))`);
@@ -136,6 +144,7 @@ export function responsibilityDashboardVersionService(db: Db) {
projectId: responsibilityLinks.projectId,
issueId: responsibilityLinks.issueId,
routineId: responsibilityLinks.routineId,
skillId: responsibilityLinks.skillId,
}).from(responsibilityLinks)
.innerJoin(responsibilities, eq(responsibilities.id, responsibilityLinks.responsibilityId))
.where(and(
@@ -152,15 +161,19 @@ export function responsibilityDashboardVersionService(db: Db) {
]);
const linksBy = new Map<string, ResponsibilityDashboardSnapshotLinks>();
for (const link of linkRows) {
const entry = linksBy.get(link.responsibilityId) ?? { projectIds: [], issueIds: [], routineIds: [] };
const entry = linksBy.get(link.responsibilityId) ?? { projectIds: [], issueIds: [], routineIds: [], skillIds: [] };
if (link.projectId) entry.projectIds.push(link.projectId);
if (link.issueId) entry.issueIds.push(link.issueId);
if (link.routineId) entry.routineIds.push(link.routineId);
if (link.skillId) entry.skillIds!.push(link.skillId);
linksBy.set(link.responsibilityId, entry);
}
const sortedLinks = (id: string): ResponsibilityDashboardSnapshotLinks => {
const entry = linksBy.get(id) ?? { projectIds: [], issueIds: [], routineIds: [] };
return { projectIds: [...entry.projectIds].sort(), issueIds: [...entry.issueIds].sort(), routineIds: [...entry.routineIds].sort() };
const entry = linksBy.get(id) ?? { projectIds: [], issueIds: [], routineIds: [], skillIds: [] };
return {
projectIds: [...entry.projectIds].sort(), issueIds: [...entry.issueIds].sort(),
routineIds: [...entry.routineIds].sort(), skillIds: [...(entry.skillIds ?? [])].sort(),
};
};
const items = rows.map(({ description, runByAgentId, evidence, healthOverride, healthNote, ...item }) => ({
...item, links: sortedLinks(item.id), description, runByAgentId, evidence, healthOverride, healthNote,
@@ -229,14 +242,16 @@ export function responsibilityDashboardVersionService(db: Db) {
restoredFromVersionId?: string | null;
}): Promise<{ row: VersionRow; created: boolean }> {
const previous = await latestRow(tx, input.companyId, input.ownerUserId);
const previousSnapshot = previous ? parseDashboardSnapshot(previous.snapshot) : null;
const hash = dashboardSnapshotHash(input.snapshot);
// A version saved before snapshots held filed items is compared on what it holds.
const legacy = previous ? isLegacySnapshot(parseDashboardSnapshot(previous.snapshot)) : false;
const legacy = previousSnapshot ? isLegacySnapshot(previousSnapshot) : false;
const comparable = legacy ? dashboardSnapshotHash(input.snapshot, { legacy: true }) : hash;
if (previous && previous.snapshotHash === comparable) {
if (!legacy) return { row: previous, created: false };
// The same dashboard as an older version that held no filed items or
// details: it now holds them, so the next change compares, and undoes, in full.
// One saved before skills could be filed hashes the same (no filed skills) but must hold the empty list too.
if (!legacy && !lacksFiledSkills(previousSnapshot!)) return { row: previous, created: false };
// The same dashboard as an older version that held no filed items,
// details or skills: it now holds them, so the next change compares, and undoes, in full.
const [upgraded] = await tx.update(responsibilityDashboardVersions)
.set({ snapshot: input.snapshot as unknown as Record<string, unknown>, snapshotHash: hash })
.where(eq(responsibilityDashboardVersions.id, previous.id))
@@ -533,14 +548,27 @@ export function responsibilityDashboardVersionService(db: Db) {
});
}
if (!want.links) return events;
const current = await tx.select().from(responsibilityLinks).where(eq(responsibilityLinks.responsibilityId, row.id));
// A version saved before skills could be filed leaves filed skills as they are.
const withSkills = want.links.skillIds !== undefined;
const linked = await tx.select().from(responsibilityLinks).where(eq(responsibilityLinks.responsibilityId, row.id));
// Skills the person restoring cannot see (the request's actor) are left as they are: not filed again, not removed.
const skillIds = [...new Set([...linked.flatMap((link) => (link.skillId ? [link.skillId] : [])), ...(want.links.skillIds ?? [])])];
const visibleSkills = !withSkills || skillIds.length === 0 ? new Set<string>() : new Set(
(await tx.select({ id: companySkills.id }).from(companySkills).where(and(
eq(companySkills.companyId, companyId), inArray(companySkills.id, skillIds),
await skillAccessService(tx as unknown as Db).condition(companyId),
))).map((skill) => skill.id),
);
const current = linked.filter((link) => !link.skillId || visibleSkills.has(link.skillId));
const wanted = new Set([
...want.links.projectIds.map((id) => `project:${id}`),
...want.links.issueIds.map((id) => `issue:${id}`),
...want.links.routineIds.map((id) => `routine:${id}`),
...(want.links.skillIds ?? []).filter((id) => visibleSkills.has(id)).map((id) => `skill:${id}`),
]);
const keyOf = (link: typeof responsibilityLinks.$inferSelect) =>
link.projectId ? `project:${link.projectId}` : link.issueId ? `issue:${link.issueId}` : `routine:${link.routineId}`;
link.projectId ? `project:${link.projectId}` : link.issueId ? `issue:${link.issueId}`
: link.routineId ? `routine:${link.routineId}` : `skill:${link.skillId}`;
const have = new Set(current.map(keyOf));
for (const link of current) {
if (wanted.has(keyOf(link))) continue;
@@ -551,18 +579,21 @@ export function responsibilityDashboardVersionService(db: Db) {
const missing = [...wanted].filter((key) => !have.has(key)).map((key) => key.split(":") as [string, string]);
const idsOf = (kind: string) => missing.filter(([type]) => type === kind).map(([, id]) => id);
// Only items that still exist in the company can be filed again.
const [liveProjects, liveIssues, liveRoutines] = await Promise.all([
const [liveProjects, liveIssues, liveRoutines, liveSkills] = await Promise.all([
idsOf("project").length === 0 ? [] : tx.select({ id: projects.id }).from(projects)
.where(and(eq(projects.companyId, companyId), inArray(projects.id, idsOf("project")))),
idsOf("issue").length === 0 ? [] : tx.select({ id: issues.id }).from(issues)
.where(and(eq(issues.companyId, companyId), inArray(issues.id, idsOf("issue")))),
idsOf("routine").length === 0 ? [] : tx.select({ id: routines.id }).from(routines)
.where(and(eq(routines.companyId, companyId), inArray(routines.id, idsOf("routine")))),
idsOf("skill").length === 0 ? [] : tx.select({ id: companySkills.id }).from(companySkills)
.where(and(eq(companySkills.companyId, companyId), inArray(companySkills.id, idsOf("skill")))),
]);
const live = new Set([
...liveProjects.map((item) => `project:${item.id}`),
...liveIssues.map((item) => `issue:${item.id}`),
...liveRoutines.map((item) => `routine:${item.id}`),
...liveSkills.map((item) => `skill:${item.id}`),
]);
for (const [kind, id] of missing) {
if (!live.has(`${kind}:${id}`)) continue;
@@ -572,6 +603,7 @@ export function responsibilityDashboardVersionService(db: Db) {
projectId: kind === "project" ? id : null,
issueId: kind === "issue" ? id : null,
routineId: kind === "routine" ? id : null,
skillId: kind === "skill" ? id : null,
}).onConflictDoNothing().returning();
if (inserted) events.push({ action: "responsibility.linked", entityType: "responsibility", entityId: row.id, details: { linkId: inserted.id, targetType: kind, targetId: id, ...source } });
}
+6 -4
View File
@@ -47,7 +47,7 @@ export const listResponsibilitiesToolInput = z.object({
export const getResponsibilityToolInput = z.object({ responsibilityId: uuid }).strict();
export const findResponsibilitiesForToolInput = z.object({
kind: z.enum(["project", "task", "routine"]),
kind: z.enum(["project", "task", "routine", "skill"]),
/** A UUID; for a task, an identifier such as PAP-123 also works. */
id: z.string().trim().min(1).max(200),
}).strict();
@@ -219,10 +219,12 @@ async function getResponsibility(call: ApiCall, args: unknown, prefix: string |
linkId: routine.linkId, membership: routine.membership, id: routine.id, title: routine.title, status: routine.status,
assigneeAgentId: routine.assigneeAgentId, projectId: routine.projectId, lastRun: routine.lastRun,
})),
skills: detail.skills.map((skill) => ({ id: skill.id, key: skill.key, name: skill.name, agentIds: skill.agentIds })),
skills: detail.skills.map((skill) => ({
id: skill.id, key: skill.key, name: skill.name, linkId: skill.linkId, computed: skill.computed, agentIds: skill.agentIds,
})),
artifactsTotal: detail.artifactsTotal,
statusReport: report ? { current: report.current, reporterAgentId: report.reporterAgentId, updateRequested: report.updateRequested } : null,
membershipNote: "membership direct means the item is filed under it (linkId set); project means it is under it through a filed project.",
membershipNote: "membership direct means the item is filed under it (linkId set); project means it is under it through a filed project. A skill with linkId is filed here; computed means an agent doing the work holds it.",
};
}
@@ -267,7 +269,7 @@ function undoNote(meta: ApiMeta) {
? { undo: UNDO_NOTE, dashboardVersionId: meta.version, dashboardOwnerUserId: meta.owner ?? null }
: { undo: NOT_IN_HISTORY_NOTE };
}
const itemKind = z.enum(["project", "task", "routine"]);
const itemKind = z.enum(["project", "task", "routine", "skill"]);
const toolItem = z.object({ kind: itemKind, id: z.string().trim().min(1).max(200) }).strict();
const nullableText = z.string().trim().max(10_000).nullable();
const barInput = z.object({
+27 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { callCreateSkillTool, createSkillToolInput, callUpdateSkillTool, updateSkillToolInput } from "./skill-tools.js";
import { callCreateSkillTool, createSkillToolInput, callUpdateSkillDetailsTool, callUpdateSkillTool, updateSkillToolInput } from "./skill-tools.js";
const input = {
name: "release-review", description: "Review release notes.", idempotencyKey: "release-review-1",
@@ -62,3 +62,29 @@ describe("update skill tool", () => {
await expect(callUpdateSkillTool({ arguments: args, apiUrl: "http://localhost", token: "token", companyId: "company" }, fetcher)).rejects.toThrow("Skill version changed");
});
});
describe("update skill details tool", () => {
const skillId = "00000000-0000-4000-8000-000000000001";
it("changes only the tagline and categories through the skill update API", async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({
id: skillId, name: "review", slug: "review", tagline: "Reviews pull requests", categories: ["engineering"],
}), { status: 200 }));
const result = await callUpdateSkillDetailsTool({ arguments: { skillId, tagline: "Reviews pull requests", categories: ["engineering"] },
apiUrl: "http://localhost/api", token: "token", companyId: "company" }, fetcher);
const [url, init] = fetcher.mock.calls[0]!;
expect(url).toBe(`http://localhost/api/companies/company/skills/${skillId}`);
expect(init?.method).toBe("PATCH");
expect(JSON.parse(String(init?.body))).toEqual({ tagline: "Reviews pull requests", categories: ["engineering"] });
expect(result).toEqual({ id: skillId, name: "review", slug: "review", tagline: "Reviews pull requests", categories: ["engineering"], studioPath: `/skills/studio/${skillId}` });
});
it("changes nothing without a detail, and refuses fields that live in SKILL.md", async () => {
const fetcher = vi.fn<typeof fetch>();
// The advertised schema requires only skillId, so that call is a no-op, not an error.
await expect(callUpdateSkillDetailsTool({ arguments: { skillId }, apiUrl: "http://localhost", token: "token", companyId: "company" }, fetcher))
.resolves.toEqual({ id: skillId, changed: false, note: expect.stringContaining("send tagline, categories or both") });
await expect(callUpdateSkillDetailsTool({ arguments: { skillId, name: "renamed" }, apiUrl: "http://localhost", token: "token", companyId: "company" }, fetcher)).rejects.toThrow();
expect(fetcher).not.toHaveBeenCalled();
});
});
+31
View File
@@ -62,3 +62,34 @@ export async function callCreateSkillTool(input: {
return { id: result.id, name: result.name, slug: result.slug, description: result.description,
versionId: result.currentVersionId, studioPath: `/skills/studio/${encodeURIComponent(result.id)}` };
}
/**
* A company skill's catalog details that live outside SKILL.md. Its name and
* description are SKILL.md frontmatter, so they change through update_skill.
* Like the advertised schema, only skillId is required; without a detail the
* call changes nothing.
*/
export const updateSkillDetailsToolInput = z.object({
skillId: z.string().guid(),
tagline: z.string().trim().max(120).nullable().optional(),
categories: z.array(z.string().trim().min(1).max(60)).max(20).optional(),
}).strict();
/** Same API and company skill edit policy as the skill page. */
export async function callUpdateSkillDetailsTool(input: {
arguments: Record<string, unknown>; apiUrl: string; token: string; companyId: string;
}, fetcher: typeof fetch = fetch) {
const { skillId, ...details } = updateSkillDetailsToolInput.parse(input.arguments);
if (details.tagline === undefined && details.categories === undefined) {
return { id: skillId, changed: false, note: "Nothing changed: send tagline, categories or both." };
}
const response = await fetcher(`${input.apiUrl.replace(/\/+$/, "").replace(/\/api$/, "")}/api/companies/${encodeURIComponent(input.companyId)}/skills/${encodeURIComponent(skillId)}`, {
method: "PATCH",
headers: { Authorization: `Bearer ${input.token}`, "Content-Type": "application/json" },
body: JSON.stringify(details), signal: AbortSignal.timeout(60_000),
});
const result = await response.json();
if (!response.ok) throw new Error(typeof result.error === "string" ? result.error : `Skill update failed (${response.status})`);
return { id: result.id, name: result.name, slug: result.slug, tagline: result.tagline ?? null, categories: result.categories ?? [],
studioPath: `/skills/studio/${encodeURIComponent(result.id)}` };
}
+1 -1
View File
@@ -286,7 +286,7 @@ To change them, you act for the person your run works for when they directed it:
- `create_area`, `update_area` (rename, describe, reorder, archive or restore) and `delete_area`.
- `create_responsibility` (a title is enough; `areaTitle` reuses or creates the area; `fileItems` files work under it), `update_responsibility` (title, sentence, metric as `bar`, area, the agent that runs it, health override, or status such as `let_go`) and `delete_responsibility`.
- `file_under_responsibility` files projects, tasks and routines in one step; `moveFrom` (a responsibility ID, or `all`) makes it a move. `remove_from_responsibility` unfiles items; no link IDs are needed.
- `file_under_responsibility` files projects, tasks, routines and company skills in one step; `moveFrom` (a responsibility ID, or `all`) makes it a move. `remove_from_responsibility` unfiles items; no link IDs are needed. A responsibility's skills are those filed by hand plus those held by the agents doing its work; only filed ones can be removed. `update_skill_details` changes a skill's tagline and categories.
- To map routines to responsibilities, read them with `list_routines` (`unfiled: true` lists those under no responsibility; add `status: "active"` for the running ones), then file them; `update_routine` also changes a routine's schedule, agent or instructions (see `references/routines.md`).
Each change is saved as a version in the person's Dashboard history, where they can undo it; say so when you report what you changed. Prefer what can be undone: archive an area or let a responsibility go instead of deleting it. A delete is permanent, so the first call posts a confirmation card and returns `awaiting_confirmation`: tell the person, then stop; when they accept you are woken, and the same call deletes. Otherwise (a task someone else made for them, a routine, or no person), your changes are saved as proposals for a person to confirm.
+2 -2
View File
@@ -1508,10 +1508,10 @@ A person's responsibilities are saved records, each optionally filed under an ar
| GET | `/api/companies/:companyId/responsibilities` | One person's areas, responsibilities (with health and counts), proposals, totals and the company's work filed under no responsibility (`loose`). `ownerUserId` defaults to the person your run works for; `includeLetGo=true` adds let-go ones |
| GET | `/api/companies/:companyId/responsibility-areas` | The company's areas; `includeArchived=true` adds archived ones |
| GET | `/api/responsibilities/:responsibilityId` | One responsibility with its projects, tasks and routines (`linkId` set when filed directly) and the skills of the agents doing its work |
| GET | `/api/companies/:companyId/responsibility-links/lookup` | The responsibilities one item is under; send exactly one of `issueId`, `projectId` or `routineId` |
| GET | `/api/companies/:companyId/responsibility-links/lookup` | The responsibilities one item is under; send exactly one of `issueId`, `projectId`, `routineId` or `skillId` |
| POST | `/api/companies/:companyId/responsibilities` | Create one. Acting for the person your run works for (who may manage the owner, and who directed the run: their own chat or task, or their message woke it), a title is enough and it is active; otherwise it is a proposal with its whole bar |
| PATCH | `/api/responsibilities/:responsibilityId` | Change any field, as the person could; otherwise only a proposal, or `metricCurrent` on one you work under |
| POST | `/api/responsibilities/:responsibilityId/file` | `{ items: [{ kind: "project" \| "task" \| "routine", id }], moveFrom?: responsibilityId \| "all" }`: file items, optionally moving them |
| POST | `/api/responsibilities/:responsibilityId/file` | `{ items: [{ kind: "project" \| "task" \| "routine" \| "skill", id }], moveFrom?: responsibilityId \| "all" }`: file items, optionally moving them |
| POST | `/api/responsibilities/:responsibilityId/unfile` | `{ items }`: unfile items by kind and id |
| DELETE | `/api/responsibilities/:responsibilityId?confirmationId=` | Permanent. An agent sends the id of an accepted `request_confirmation` card it posted, with target `{ type: "custom", key: "responsibility-delete:<id>" }` |
| POST | `/api/companies/:companyId/responsibility-areas` | Create an area (or get the live one with that title) |
@@ -336,7 +336,7 @@
"packages/shared/src/responsibility-automation.test.ts": "fb9c7d1469ccc961b0b407eaae0156c45e7aef75",
"packages/shared/src/responsibility-automation.ts": "9f1f6f9b1a227db5ac6a1e02a6f76fa46660d573",
"packages/shared/src/responsibility-bars.ts": "f064ae825e78645b298746bfa02d4a82f8c2a885",
"packages/shared/src/responsibility-dashboard.ts": "e1bc2c4b957c4dd29f7f371baf48e053bcd75ca5",
"packages/shared/src/responsibility-dashboard.ts": "c5743719805c9e1b6c1707986147a8f87031a442",
"packages/shared/src/responsibility-metrics.test.ts": "e1ca760b3e42a7ab9556aeb867b8077146b92699",
"packages/shared/src/responsibility-metrics.ts": "349f8fb3ce4684fd432332b3f6a8a0a25d6f8a58",
"packages/shared/src/responsibility-runs.ts": "58e591f753b02f7ed77b5b4aa414e19598be3ffa",
@@ -439,7 +439,7 @@
"packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c",
"packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e",
"packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8",
"packages/shared/src/types/responsibility.ts": "2a0f0dafdca5daa7b49f7e66ebf4fa551a870f69",
"packages/shared/src/types/responsibility.ts": "f577647e59db25b6bba04fb2f9ab36a00afbb371",
"packages/shared/src/types/routine.ts": "6b2f2fd27187c19f98afe99f926460ded2752f20",
"packages/shared/src/types/runtime-exposure.ts": "785f053a7ad5448cde94f36738cdb90585bbc92e",
"packages/shared/src/types/search.ts": "4e208a9b1942991bfe5f29ef58ec71625e2693e9",
@@ -524,7 +524,7 @@
"packages/shared/src/validators/project.ts": "6ea168f5faf3161e6004ea47274f60634c77b219",
"packages/shared/src/validators/provider-trace.ts": "b38b6200a2e51513f5dca0f8b008f2fe68175e82",
"packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd",
"packages/shared/src/validators/responsibility.ts": "b466feab326f0ec79754962761a2fd0c26594221",
"packages/shared/src/validators/responsibility.ts": "7c61a734fca7cfb23ea386a82bf0bef0ef438819",
"packages/shared/src/validators/routine.test.ts": "1501907ade577c1ab4c4b3098397e5d080446878",
"packages/shared/src/validators/routine.ts": "01f8adabca5e89784515e55bec964013c225415a",
"packages/shared/src/validators/runtime-exposure.test.ts": "31175388dbab9f3d5dba920cd711ea6e0e6c6ece",
@@ -0,0 +1,89 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AddExistingWorkPicker } from "./AddExistingWorkPicker";
const skillsApi = vi.hoisted(() => ({ list: vi.fn() }));
const responsibilitiesApi = vi.hoisted(() => ({ link: vi.fn() }));
vi.mock("@/api/companySkills", () => ({ companySkillsApi: skillsApi }));
vi.mock("@/api/responsibilities", () => ({ responsibilitiesApi }));
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const SKILL_COUNT = 600;
const FILED_COUNT = 100;
let root: Root;
let host: HTMLDivElement;
let client: QueryClient;
const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
function type(input: HTMLInputElement, value: string) {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, value);
input.dispatchEvent(new Event("input", { bubbles: true }));
}
/** The filed-skill ids, counting each lookup and failing at once past `limit`. */
class CountedIds extends Set<string> {
lookups = 0;
constructor(ids: Iterable<string>, readonly limit: number) {
super(ids);
}
override has(id: string) {
this.lookups += 1;
if (this.lookups > this.limit) throw new Error(`linkedIds.has called ${this.lookups} times, past ${this.limit}`);
return super.has(id);
}
}
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
Element.prototype.scrollIntoView = vi.fn();
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(async () => {
await act(async () => root.unmount());
host.remove();
client.clear();
vi.unstubAllGlobals();
});
describe("AddExistingWorkPicker with a company's skills", () => {
it("lists hundreds of skills without the filed ones, searches them, and does work in proportion", async () => {
const skills = Array.from({ length: SKILL_COUNT }, (_, index) => ({
id: `skill-${index}`, name: index % 50 === 0 ? `Interview loop ${index}` : `Skill ${index}`,
}));
skillsApi.list.mockResolvedValue(skills);
// One lookup per skill each time the list is worked out; a memo that misses on every keystroke would blow this.
const linkedIds = new CountedIds(skills.slice(0, FILED_COUNT).map((skill) => skill.id), SKILL_COUNT * 2);
await act(async () => {
root.render(
<QueryClientProvider client={client}>
<AddExistingWorkPicker companyId="company-1" responsibilityId="resp-1" kind="skill" linkedIds={linkedIds} open onOpenChange={vi.fn()} />
</QueryClientProvider>,
);
});
await flush();
const items = () => document.body.querySelectorAll('[data-slot="command-item"]');
expect(items()).toHaveLength(SKILL_COUNT - FILED_COUNT);
expect(document.body.textContent).not.toContain("Interview loop 0");
const search = document.body.querySelector<HTMLInputElement>('input[aria-label="Search skills"]')!;
for (const value of ["I", "In", "Int", "Interview"]) {
await act(async () => type(search, value));
}
await flush();
// Skills 100, 150, ... 550 match; 0 and 50 are filed already.
expect([...items()].map((item) => item.textContent)).toEqual(
skills.filter((skill, index) => index >= FILED_COUNT && skill.name.startsWith("Interview")).map((skill) => skill.name),
);
expect(linkedIds.lookups).toBeLessThanOrEqual(SKILL_COUNT * 2);
});
});
@@ -5,6 +5,7 @@ import { Plus } from "lucide-react";
import { ApiError } from "@/api/client";
import { describeError } from "@/api/errors";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
import { companySkillsApi } from "@/api/companySkills";
import { issuesApi } from "@/api/issues";
import { responsibilitiesApi, type ResponsibilityLinkResult } from "@/api/responsibilities";
import { routinesApi } from "@/api/routines";
@@ -14,12 +15,12 @@ import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/compon
import { companyProjectsQuery } from "@/lib/company-projects-query";
import { queryKeys } from "@/lib/queryKeys";
export type ResponsibilityWorkKind = "project" | "task" | "routine";
export type ResponsibilityWorkKind = "project" | "task" | "routine" | "skill";
const TASK_SEARCH_LIMIT = 20;
const TASK_SEARCH_DEBOUNCE_MS = 200;
const NOUN: Record<ResponsibilityWorkKind, string> = { project: "project", task: "task", routine: "routine" };
const NOUN: Record<ResponsibilityWorkKind, string> = { project: "project", task: "task", routine: "routine", skill: "skill" };
interface PickerOption {
id: string;
@@ -41,6 +42,7 @@ export function describeLinkError(error: unknown, kind: ResponsibilityWorkKind):
function linkBody(kind: ResponsibilityWorkKind, id: string): LinkResponsibility {
if (kind === "project") return { projectId: id };
if (kind === "task") return { issueId: id };
if (kind === "skill") return { skillId: id };
return { routineId: id };
}
@@ -54,8 +56,8 @@ function useDebounced<T>(value: T, delayMs: number): T {
}
/**
* "Add existing…": search the company's projects, tasks or routines and file
* one under the responsibility (it stays wherever else it is filed). Lists
* "Add existing…": search the company's projects, tasks, routines or skills
* and file one under the responsibility (it stays wherever else it is filed). Lists
* load only while the picker is open; tasks are searched on the server. Items
* already directly under this responsibility are left out.
*
@@ -99,6 +101,11 @@ export function AddExistingWorkPicker({
queryFn: () => routinesApi.list(companyId),
enabled: open && kind === "routine",
});
const skills = useQuery({
queryKey: queryKeys.companySkills.list(companyId),
queryFn: () => companySkillsApi.list(companyId),
enabled: open && kind === "skill",
});
const tasks = useQuery({
queryKey: queryKeys.issues.search(companyId, taskQuery, undefined, TASK_SEARCH_LIMIT),
queryFn: () => issuesApi.list(companyId, { q: taskQuery || undefined, limit: TASK_SEARCH_LIMIT }),
@@ -112,11 +119,14 @@ export function AddExistingWorkPicker({
if (kind === "routine") {
return (routines.data ?? []).map((routine) => ({ id: routine.id, label: routine.title }));
}
if (kind === "skill") {
return (skills.data ?? []).map((skill) => ({ id: skill.id, label: skill.name }));
}
return (tasks.data ?? []).map((task) => ({ id: task.id, label: task.title, detail: task.identifier }));
}, [kind, projects.data, routines.data, tasks.data]);
}, [kind, projects.data, routines.data, skills.data, tasks.data]);
const available = useMemo(() => options.filter((option) => !linkedIds.has(option.id)), [options, linkedIds]);
const source = kind === "project" ? projects : kind === "routine" ? routines : tasks;
const source = kind === "project" ? projects : kind === "routine" ? routines : kind === "skill" ? skills : tasks;
const sourceView = useQueryView<unknown>({
data: source.data,
error: source.error,
@@ -1,6 +1,6 @@
import { useMemo, useRef, useState, type FormEvent, type ReactNode } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Agent, CompanyArtifact, ResponsibilityProjectSummary, ResponsibilityRoutineSummary } from "@paperclipai/shared";
import type { Agent, CompanyArtifact, ResponsibilityProjectSummary, ResponsibilityRoutineSummary, ResponsibilitySkillSummary } from "@paperclipai/shared";
import { FileText, MoreHorizontal, Plus } from "lucide-react";
import { describeError } from "@/api/errors";
import { QueryErrorState, useQueryView } from "@/components/QueryView";
@@ -143,6 +143,77 @@ function AddMenu({
);
}
/**
* The Skills "+": file an existing company skill here, remove one filed here,
* or open an agent's skills to give it one. Skills an agent holds come from
* that agent, so they are not removed here.
*/
function SkillsMenu({
onExisting,
filed,
onRemove,
removingLinkId,
agents,
}: {
onExisting: () => void;
/** Skills filed here by hand. */
filed: readonly ResponsibilitySkillSummary[];
onRemove: (skill: ResponsibilitySkillSummary) => void;
removingLinkId: string | null;
/** The agents working on this, whose skills page can give them one. */
agents: readonly Agent[];
}) {
// The picker opens once the menu has closed, so the menu's focus return does not dismiss it.
const pickExisting = useRef(false);
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" size="icon-xs" variant="ghost" className="text-muted-foreground" aria-label="Add or remove a skill" data-section-add="">
<Plus aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
onCloseAutoFocus={(event) => {
if (!pickExisting.current) return;
pickExisting.current = false;
event.preventDefault();
onExisting();
}}
>
<DropdownMenuItem onSelect={() => { pickExisting.current = true; }}>Add existing skill</DropdownMenuItem>
{filed.length > 0 ? (
<>
<DropdownMenuSeparator />
<DropdownMenuLabel>Remove from this responsibility</DropdownMenuLabel>
{filed.map((skill) => (
<DropdownMenuItem
key={skill.id}
disabled={removingLinkId === skill.linkId}
aria-label={`Remove ${skill.name} from this responsibility`}
onSelect={() => onRemove(skill)}
>
{skill.name}
</DropdownMenuItem>
))}
</>
) : null}
{agents.length > 0 ? (
<>
<DropdownMenuSeparator />
<DropdownMenuLabel>Give a skill to</DropdownMenuLabel>
{agents.map((agent) => (
<DropdownMenuItem key={agent.id} asChild>
<Link to={agentDetailHref(agentRouteRef(agent), "skills")}>{agent.name}</Link>
</DropdownMenuItem>
))}
</>
) : null}
</DropdownMenuContent>
</DropdownMenu>
);
}
/** A "+" that cannot do anything yet, with why, on hover and for screen readers. */
function DisabledAdd({ label, reason }: { label: string; reason: string }) {
return (
@@ -236,7 +307,8 @@ export function ResponsibilityOneScreenV2({
project: new Set(responsibility.projects.map((project) => project.id)),
task: new Set(responsibility.tasks.filter((task) => task.membership === "direct").map((task) => task.id)),
routine: new Set(responsibility.routines.filter((routine) => routine.membership === "direct").map((routine) => routine.id)),
}), [responsibility.projects, responsibility.tasks, responsibility.routines]);
skill: new Set(responsibility.skills.filter((skill) => skill.linkId).map((skill) => skill.id)),
}), [responsibility.projects, responsibility.tasks, responsibility.routines, responsibility.skills]);
const routines = responsibility.routines.filter((routine) => routine.status !== "archived");
const projects = responsibility.projects.filter((project) => !isFinishedProject(project));
const { open: openTasks, done: doneTasks } = useMemo(() => splitTasksForTable(responsibility.tasks), [responsibility.tasks]);
@@ -296,25 +368,16 @@ export function ResponsibilityOneScreenV2({
</DropdownMenu>
);
const skillsAdd = !editable ? null : working.length === 0 ? (
<DisabledAdd label="Give an agent a skill" reason="Skills come from the agents on this; none yet" />
) : (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" size="icon-xs" variant="ghost" className="text-muted-foreground" aria-label="Give an agent a skill" data-section-add="">
<Plus aria-hidden="true" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuLabel>Give a skill to</DropdownMenuLabel>
{working.map((agent) => (
<DropdownMenuItem key={agent.id} asChild>
<Link to={agentDetailHref(agentRouteRef(agent), "skills")}>{agent.name}</Link>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
const filedSkills = useMemo(() => responsibility.skills.filter((skill) => skill.linkId), [responsibility.skills]);
const skillsAdd = !editable ? null : picker("skill", (
<SkillsMenu
onExisting={() => setPicking("skill")}
filed={filedSkills}
removingLinkId={actions.unlinkingId}
onRemove={(skill) => actions.unlink({ linkId: skill.linkId!, label: skill.name, relink: { skillId: skill.id } })}
agents={working}
/>
));
const fileNewProject = async (project: { id: string }) => {
setFilingError(null);
@@ -414,6 +477,7 @@ export function ResponsibilityOneScreenV2({
rowData={{ "data-work-id": skill.id }}
to={skillRoute(skill)}
title={skill.name}
stat={skill.linkId ? "Filed here" : undefined}
who={skill.agentIds.length > 0 ? <SkillHolders agentIds={skill.agentIds} agentsById={agentsById} /> : null}
/>
))}
@@ -159,8 +159,9 @@ export function ResponsibilityPageLayout({
project: new Set(responsibility.projects.map((project) => project.id)),
task: new Set(responsibility.tasks.filter((task) => task.membership === "direct").map((task) => task.id)),
routine: new Set(responsibility.routines.filter((routine) => routine.membership === "direct").map((routine) => routine.id)),
skill: new Set(responsibility.skills.filter((skill) => skill.linkId).map((skill) => skill.id)),
}),
[responsibility.projects, responsibility.tasks, responsibility.routines],
[responsibility.projects, responsibility.tasks, responsibility.routines, responsibility.skills],
);
const isActive = responsibility.status === "active";
@@ -368,7 +369,12 @@ export function ResponsibilityPageLayout({
)}
</section>
<ResponsibilitySkills skills={responsibility.skills} agentsById={agentsById} />
<ResponsibilitySkills
skills={responsibility.skills}
agentsById={agentsById}
addControl={editable ? picker("skill") : null}
removeControl={(skill) => unlinkRow(skill.linkId, skill.name, { skillId: skill.id })}
/>
<section aria-labelledby="responsibility-projects-heading" className="flex flex-col gap-2">
<SectionHeading
@@ -1,3 +1,4 @@
import type { ReactNode } from "react";
import type { Agent, CompanyArtifact, ResponsibilitySkillSummary } from "@paperclipai/shared";
import { RESPONSIBILITY_ARTIFACT_COUNT_LIMIT } from "@paperclipai/shared";
import { AgentAvatar } from "@/components/AgentAvatar";
@@ -10,13 +11,16 @@ import { skillRoute } from "@/lib/company-skill-routes";
import { Link } from "@/lib/router";
import { issueUrl } from "@/lib/utils";
function SectionHeading({ id, title, count, question }: { id: string; title: string; count: number; question: string }) {
function SectionHeading({ id, title, count, question, action }: { id: string; title: string; count: number; question: string; action?: ReactNode }) {
return (
<div className="flex flex-col gap-1">
<h2 id={id} className="text-base font-semibold text-foreground">
{title} <span className="text-sm font-normal tabular-nums text-muted-foreground">{count}</span>
</h2>
<p className="text-sm text-muted-foreground">{question}</p>
<div className="flex flex-wrap items-end justify-between gap-2">
<div className="flex min-w-0 flex-col gap-1">
<h2 id={id} className="text-base font-semibold text-foreground">
{title} <span className="text-sm font-normal tabular-nums text-muted-foreground">{count}</span>
</h2>
<p className="text-sm text-muted-foreground">{question}</p>
</div>
{action}
</div>
);
}
@@ -38,16 +42,22 @@ function Holders({ agentIds, agentsById }: { agentIds: readonly string[]; agents
}
/**
* The skills held by the agents working under a responsibility: the agents
* assigned its tasks and routines and the leads of its projects, as a grid
* of cards. Derived by the server; nothing is attached by hand.
* The skills under a responsibility, as a grid of cards: those filed here by
* hand (which can be removed), and those held by the agents working under it
* (the agents assigned its tasks and routines and the leads of its projects).
*/
export function ResponsibilitySkills({
skills,
agentsById,
addControl,
removeControl,
}: {
skills: readonly ResponsibilitySkillSummary[];
agentsById: ReadonlyMap<string, Agent>;
/** Files a skill here; absent where the page cannot change it. */
addControl?: ReactNode;
/** Removes a filed skill; null for one that is only held by an agent. */
removeControl?: (skill: ResponsibilitySkillSummary) => ReactNode;
}) {
return (
<section aria-labelledby="responsibility-skills-heading" className="flex flex-col gap-2">
@@ -55,7 +65,8 @@ export function ResponsibilitySkills({
id="responsibility-skills-heading"
title="Skills"
count={skills.length}
question="What can the agents working on this do?"
question="What does this need, and what can the agents working on it do?"
action={addControl}
/>
{skills.length > 0 ? (
<ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3" data-testid="responsibility-skills">
@@ -74,15 +85,22 @@ export function ResponsibilitySkills({
) : null}
</span>
</Link>
<Holders agentIds={skill.agentIds} agentsById={agentsById} />
<div className="flex min-w-0 items-center justify-between gap-2">
{skill.agentIds.length > 0 ? (
<Holders agentIds={skill.agentIds} agentsById={agentsById} />
) : (
<span className="text-xs text-muted-foreground">Filed here</span>
)}
{skill.linkId ? removeControl?.(skill) : null}
</div>
</Card>
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground">
No skills yet. They appear here from the agents doing the work: the ones assigned its tasks and
routines, and the leads of its projects.
No skills yet. Add one this needs, or they appear here from the agents doing the work: the ones
assigned its tasks and routines, and the leads of its projects.
</p>
)}
</section>
@@ -404,6 +404,26 @@ describe("ResponsibilityDetail: the work, skills and artifacts", () => {
expect(skills.querySelector('a[href="/skills/deck-builder"]')).not.toBeNull();
});
it("shows a skill filed by hand, lets the person remove it, and offers to add one", async () => {
const filed = {
linkId: "link-skill-pitch", computed: false, id: "skill-pitch", key: "paperclip/pitch", slug: "pitch",
name: "Pitch coach", description: "Rehearses a pitch.", tagline: null, iconUrl: null, color: null, agentIds: [],
};
mocks.api.get.mockImplementation(async (id: string) => ({
...RESPONSIBILITY_DETAIL_FIXTURES[id], skills: [...RESPONSIBILITY_DETAIL_FIXTURES[id]!.skills, filed],
}));
await render();
const skills = section("Skills");
expect(skills.querySelectorAll('[data-testid="responsibility-skills"] > li [data-slot="card"]')).toHaveLength(3);
expect(skills.textContent).toContain("Filed here");
expect(buttonByText("Add existing skill", skills)).not.toBeNull();
// Only the skill filed by hand can be removed; the computed ones come from the agents.
expect(skills.querySelectorAll('button[aria-label$="from this responsibility"]')).toHaveLength(1);
await act(async () => skills.querySelector<HTMLButtonElement>('button[aria-label="Remove Pitch coach from this responsibility"]')!.click());
await flush();
expect(mocks.api.unlink).toHaveBeenCalledExactlyOnceWith("resp-fundraising", "link-skill-pitch");
});
it("lists artifacts newest first, each opening in its task, and says the list is cut short", async () => {
await render();
const artifacts = section("Artifacts");
+30 -7
View File
@@ -38,6 +38,7 @@ const mocks = vi.hoisted(() => ({
bars: { conversation: vi.fn(), start: vi.fn(), accept: vi.fn(), decline: vi.fn() },
metrics: { metrics: vi.fn(), removeMetric: vi.fn(), setDisplay: vi.fn() },
runs: { recent: vi.fn() },
skills: { list: vi.fn() },
navigate: vi.fn(),
}));
vi.mock("@/api/responsibilities", () => ({ responsibilitiesApi: mocks.api, responsibilityAreasApi: mocks.areas }));
@@ -50,6 +51,7 @@ vi.mock("@/api/routines", () => ({ routinesApi: mocks.routines }));
vi.mock("@/api/responsibility-bars", () => ({ responsibilityBarsApi: mocks.bars }));
vi.mock("@/api/responsibility-metrics", () => ({ responsibilityMetricsApi: mocks.metrics }));
vi.mock("@/api/responsibility-runs", () => ({ responsibilityRunsApi: mocks.runs }));
vi.mock("@/api/companySkills", () => ({ companySkillsApi: mocks.skills }));
// The app's own new-project form, standing in: it hands back the project it made.
vi.mock("@/components/NewProjectDialog", () => ({
NewProjectForm: ({ onCreated, onClose }: { onCreated?: (project: { id: string }) => Promise<unknown>; onClose: () => void }) => (
@@ -214,9 +216,10 @@ describe("One screen v2: the page", () => {
for (const key of ["routines", "skills", "projects", "tasks", "runs", "artifacts"]) {
expect(section(key).querySelector("p")?.textContent).toBe("None yet.");
}
// Nothing to run and nobody to give a skill to: the + says why.
// Nothing to run: the + says why. A company skill can still be added.
expect(section("runs").querySelector("[data-section-add-disabled]")?.getAttribute("title")).toBe("No routines to run yet");
expect(section("skills").querySelector("[data-section-add-disabled] button")?.hasAttribute("disabled")).toBe(true);
expect(section("skills").querySelector("[data-section-add-disabled]")).toBeNull();
expect(section("skills").querySelector("[data-section-add]")).not.toBeNull();
});
});
@@ -273,13 +276,33 @@ describe("One screen v2: each +", () => {
expect(document.body.querySelector("[data-new-project-form]")).toBeNull();
});
it("Skills: the skills page of each agent working under it", async () => {
it("Skills: add an existing company skill, remove one filed here, or open an agent's skills page", async () => {
mocks.skills.list.mockResolvedValue([{ id: "skill-pitch", name: "Pitch coach" }]);
const filed = {
linkId: "link-skill-crm", computed: false, id: "skill-crm", key: "paperclip/crm", slug: "crm",
name: "CRM upkeep", description: null, tagline: null, iconUrl: null, color: null, agentIds: [],
};
mocks.api.get.mockImplementation(async (id: string) => ({ ...DETAILS[id], skills: [...DETAILS[id]!.skills, filed] }));
await render();
expect(section("skills").querySelector('[data-work-id="skill-crm"] [data-row-stat]')?.textContent).toBe("Filed here");
await openMenu(section("skills").querySelector<HTMLElement>("[data-section-add]")!);
const links = [...document.body.querySelectorAll<HTMLAnchorElement>('[role="menuitem"]')].map((item) => [item.textContent, item.getAttribute("href")]);
expect(links).toEqual([
["CodexCoder", "/agents/codexcoder/skills"],
]);
// Only a skill filed by hand can be removed; the agents' own skills come from them.
expect(menuItems().map((item) => item.textContent)).toEqual(["Add existing skill", "CRM upkeep", "CodexCoder"]);
expect(menuItem("CodexCoder").getAttribute("href")).toBe("/agents/codexcoder/skills");
await choose(menuItem("CRM upkeep"));
expect(mocks.api.unlink).toHaveBeenCalledExactlyOnceWith("resp-fundraising", "link-skill-crm");
await openMenu(section("skills").querySelector<HTMLElement>("[data-section-add]")!);
await choose(menuItem("Add existing skill"));
await flush();
const option = await vi.waitFor(() => {
const found = [...document.body.querySelectorAll<HTMLElement>("[cmdk-item]")].find((item) => item.textContent?.includes("Pitch coach"));
if (!found) throw new Error("not yet");
return found;
});
await choose(option);
expect(mocks.api.link).toHaveBeenCalledWith("resp-fundraising", { skillId: "skill-pitch" });
});
it("Recent runs: runs one of its routines now", async () => {
@@ -493,6 +493,8 @@ export function responsibilityDetailFixture(
export const fundraisingDetail: ResponsibilityDetail = responsibilityDetailFixture(fundraisingBehind, {
skills: [
{
linkId: null,
computed: true,
id: "skill-investor-research",
key: "paperclip/investor-research",
slug: "investor-research",
@@ -504,6 +506,8 @@ export const fundraisingDetail: ResponsibilityDetail = responsibilityDetailFixtu
agentIds: ["agent-codex", RESPONSIBILITY_FIXTURE_GUIDE_AGENT_ID],
},
{
linkId: null,
computed: true,
id: "skill-deck-builder",
key: "paperclip/deck-builder",
slug: "deck-builder",
@@ -97,6 +97,8 @@ export const everyCaseDetail: ResponsibilityDetail = responsibilityDetailFixture
skills: [
...fundraisingDetail.skills,
{
linkId: null,
computed: true,
id: "skill-market-scan",
key: "paperclip/market-scan",
slug: "market-scan",