Files
PaperClipAI/packages/paperclip-runner/src/semantic-tools/discovery.ts
T
575ef12575 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>
2026-11-19 09:30:49 -06:00

166 lines
8.6 KiB
TypeScript

import { CAPABILITY_SEMANTIC_TOOL_CATALOG } from "./catalog.js";
import { decideCapabilitySemanticAuthorization } from "./policy.js";
import type {
CapabilitySemanticOperationId,
CapabilitySemanticPolicyContext,
CapabilitySemanticToolDefinition,
CapabilitySemanticToolDescriptor,
} from "./types.js";
export type CapabilityToolExposureMode = "eager" | "lazy";
export interface CapabilityDiscoveryResult {
readonly schema: "paperclip.capability-discovery.v1";
readonly query: string;
readonly namespace: string | null;
readonly operations: readonly CapabilitySemanticToolDefinition[];
readonly truncated: boolean;
}
const MAX_DISCOVERY_RESULTS = 10;
const NAMESPACE: Readonly<Record<CapabilitySemanticOperationId, string>> = Object.freeze({
set_task_title: "active_task",
send_chat_message: "active_task",
handoff_case: "delegation",
read_case: "delegation", update_case: "delegation",
create_case: "delegation",
list_workflows: "delegation", read_workflow: "delegation", create_workflow: "delegation", update_workflow: "delegation",
set_task_monitor: "continuation",
search_api: "api_fallback",
call_api: "api_fallback",
get_task_context: "active_task", get_task_history: "active_task",
list_documents: "documents", read_document: "documents", list_document_revisions: "documents",
report_progress: "active_task", answer_status_question: "active_task", write_document: "documents",
request_human_input: "documents", register_deliverable: "documents", finish_task: "active_task",
block_task: "active_task", request_review: "active_task", search_tasks: "discovery",
list_agents: "discovery", get_agent: "discovery",
read_agent_instructions: "agent_instructions",
update_agent_instructions: "agent_instructions",
get_agent_instruction_history: "agent_instructions",
restore_agent_instructions: "agent_instructions",
create_skill: "skills", update_skill: "skills", create_task: "delegation", get_workspace: "workspace", list_workspaces: "workspace", select_workspace: "workspace", prepare_repository: "workspace", create_project: "projects", list_project_repositories: "projects", list_projects: "projects",
list_responsibilities: "responsibilities", get_responsibility: "responsibilities", find_responsibilities_for: "responsibilities",
create_area: "responsibilities", update_area: "responsibilities", delete_area: "responsibilities",
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",
get_workspace_runtime: "workspace", control_workspace_service: "workspace",
schedule_wake: "continuation", generic_api_request: "test_infrastructure",
submit_complaint: "feedback", submit_suggestion: "feedback",
});
export const CAPABILITY_DISCOVERY_NAMESPACES = Object.freeze([
{ name: "api_fallback", description: "API escape hatch for work unsupported by available dedicated tools." },
{ name: "discovery", description: "Find company tasks and agents." },
{ name: "delegation", description: "Task assignment, parentage, and dependencies." },
{ name: "governance", description: "Read, request, discuss, and decide approvals." },
{ name: "workspace", description: "Inspect task files, prepare repositories, select workspaces, and control workspace services." },
{ name: "continuation", description: "Schedule a bounded continuation wake." },
{ name: "feedback", description: "Submit internal complaints and improvement suggestions." },
]);
export const CAPABILITY_DISCOVERY_GATEWAY_DEFINITIONS = Object.freeze([{
name: "discover_capabilities",
title: "Discover optional capabilities",
description: `Search authorized optional Paperclip capabilities. Namespaces: ${CAPABILITY_DISCOVERY_NAMESPACES.map((item) => `${item.name} (${item.description})`).join("; ")}`,
inputSchema: {
type: "object", properties: {
query: { type: "string", minLength: 1, maxLength: 500 },
namespace: { type: "string" },
limit: { type: "integer", minimum: 1, maximum: MAX_DISCOVERY_RESULTS },
}, required: ["query"], additionalProperties: false,
},
outputSchema: {
type: "object", properties: {
schema: { const: "paperclip.capability-discovery.v1" },
query: { type: "string" }, namespace: { type: ["string", "null"] },
operations: { type: "array", items: { type: "object", additionalProperties: true } },
truncated: { type: "boolean" },
}, required: ["schema", "query", "namespace", "operations", "truncated"], additionalProperties: false,
},
}, {
name: "invoke_discovered_capability",
title: "Invoke a discovered capability",
description: "Invoke one optional Paperclip operation returned by discover_capabilities. Authority is rechecked at invocation.",
inputSchema: {
type: "object", properties: {
operationId: { type: "string" }, input: { type: "object", additionalProperties: true },
}, required: ["operationId", "input"], additionalProperties: false,
},
outputSchema: {
type: "object", properties: {
success: { type: "boolean" },
contentItems: { type: "array", items: { type: "object", additionalProperties: true } },
}, required: ["success", "contentItems"], additionalProperties: false,
},
}] as const);
export function capabilityToolNamespace(operationId: CapabilitySemanticOperationId): string {
return NAMESPACE[operationId];
}
export function alwaysCapabilityDefinitions(): readonly CapabilitySemanticToolDefinition[] {
return CAPABILITY_SEMANTIC_TOOL_CATALOG.filter((item) => item.exposure === "always").map(toDefinition);
}
export function discoverCapabilityDefinitions(
query: string,
context: CapabilitySemanticPolicyContext,
options: { namespace?: string; limit?: number } = {},
): CapabilityDiscoveryResult {
const normalized = query.trim().toLowerCase();
if (normalized.length === 0) throw new Error("discovery_query_empty");
const limit = Math.max(
1,
Math.min(options.limit ?? 5, MAX_DISCOVERY_RESULTS),
);
const tokens = normalized.split(/[^a-z0-9]+/).filter((token) => token.length > 1);
const permitted = CAPABILITY_SEMANTIC_TOOL_CATALOG
.filter((descriptor) => descriptor.exposure === "optional")
// Retain dispatch support for pre-upgrade sessions, but do not advertise
// revision history/restore as a capability of current agent directories.
.filter((descriptor) => descriptor.operationId !== "get_agent_instruction_history" && descriptor.operationId !== "restore_agent_instructions")
.filter((descriptor) => options.namespace === undefined || capabilityToolNamespace(descriptor.operationId) === options.namespace)
.filter((descriptor) => decideCapabilitySemanticAuthorization(descriptor, context, "exposure").allowed)
.map((descriptor) => ({ descriptor, score: score(descriptor, tokens, normalized) }))
.filter((candidate) => candidate.score > 0)
.sort((left, right) => right.score - left.score || left.descriptor.operationId.localeCompare(right.descriptor.operationId));
return Object.freeze({
schema: "paperclip.capability-discovery.v1",
query,
namespace: options.namespace ?? null,
operations: Object.freeze(permitted.slice(0, limit).map(({ descriptor }) => toDefinition(descriptor))),
truncated: permitted.length > limit,
});
}
function score(descriptor: CapabilitySemanticToolDescriptor, tokens: readonly string[], query: string): number {
const namespace = capabilityToolNamespace(descriptor.operationId);
const id = descriptor.operationId.toLowerCase();
const haystack = `${id} ${descriptor.title} ${descriptor.description} ${namespace}`.toLowerCase();
let value = id === query ? 100 : namespace === query ? 50 : 0;
for (const token of tokens) {
if (id.includes(token)) value += 12;
if (namespace.includes(token)) value += 8;
if (haystack.includes(token)) value += 3;
}
return value;
}
function toDefinition(descriptor: CapabilitySemanticToolDescriptor): CapabilitySemanticToolDefinition {
return {
name: descriptor.operationId, description: descriptor.description,
inputSchema: descriptor.inputSchema, outputSchema: descriptor.outputSchema,
annotations: {
semanticContract: descriptor.schema, operationId: descriptor.operationId,
version: descriptor.version, exposure: descriptor.exposure,
requiredClaims: descriptor.requiredClaims,
},
};
}