Skip to content

The open-source app everyone uses to manage agents at work

feat: create company skills from runner tasks (#13538)

Dotta9fd2e5031006
diff --git a/doc/runner-created-skills.md b/doc/runner-created-skills.md
new file mode 100644
index 0000000000..cf3c49c364
--- /dev/null
+++ b/doc/runner-created-skills.md
@@ -0,0 +1,65 @@
+# Skills created by the Runner
+
+The native Runner exposes `create_skill` in Auto and skill-test work. An agent
+can save a reusable, single-file skill directly in the company's skill library.
+The tool is unavailable in Ask and pre-acceptance Plan modes.
+
+```json
+{
+ "name": "release-review",
+ "description": "Review release notes.",
+ "markdown": "---\nname: release-review\ndescription: Review release notes.\n---\n\n# Review\nCheck each release note against its change.\n",
+ "idempotencyKey": "release-review-1"
+}
+```
+
+The name is lowercase with hyphens. The complete `SKILL.md` must have matching
+name and description frontmatter and a nonempty instruction body. An optional
+`slug` must equal the name. Company, task, agent and run identity come from the
+authenticated run; they are not tool inputs.
+
+The tool uses the same company skill policy and storage as Skill Studio. Skills
+are open by default unless company policy restricts creation. Creating a skill
+does not assign it to an agent or introduce a new approval step. Once the skill
+is saved, the task can finish normally if no other work remains.
+
+The result contains the skill ID, name, slug, description, version ID and Studio
+path. Reuse the same idempotency key and inputs after a lost response. A retry
+returns the existing skill without another creation event. A key reused with
+different inputs, or a name that belongs to another skill, returns a conflict.
+Published files are never replaced as part of a competing creation request.
+Deleting a managed skill releases its name for a later creation. Deletion uses
+the same name lock as creation and retains its source files until the database
+deletion commits. Imported local and project source folders are not removed.
+
+## User interface
+
+Successful creation adds a **Skill created** card to the originating task's
+feed. The card opens a named skill tab in the task sidebar. Repeated clicks
+focus that tab. The tab reads the company skill directly, so it is not a second
+editable copy of the instructions.
+
+**Open in Skill Studio** opens that same skill for editing. After saving and
+returning to the task, the sidebar shows the latest saved version. Reloading the
+task restores the tab. The historical card remains a creation receipt even if
+the skill is later edited or removed. The sidebar reports missing skills,
+denied access and retryable load errors explicitly.
+
+## Verification
+
+Server regressions cover authenticated creation, company isolation, policy
+denials and revocation, mode restrictions, initial version/file persistence,
+idempotency, conflicting retries and concurrent creation. UI tests cover the
+creation card, saved tabs, frontmatter-free preview and error states.
+
+The companion Runner Eval case `create-skill` tests provider tool use against
+the seeded mock control plane, not production storage or company policy.
+The standalone mock uses a generated production frontmatter parser and schema
+validator. Regenerate it with
+`node packages/shared/scripts/generate-runner-skill-frontmatter.ts` after changing
+the shared frontmatter contract. A shared-package test checks synchronization.
+Invalid inputs are covered by deterministic tests: a live model should not be
+penalized for declining to send a schema-invalid request. Product E2E's
+`create-skill-studio` case checks real creation, task completion, the feed card,
+sidebar, Studio editing and the updated skill after returning to the task.
+See [the eval guide](evals.md) for the difference between these suites.
diff --git a/packages/paperclip-runner/docs/capability-semantic-tools.md b/packages/paperclip-runner/docs/capability-semantic-tools.md
index 9c3af0bbda..dff75b3b02 100644
--- a/packages/paperclip-runner/docs/capability-semantic-tools.md
+++ b/packages/paperclip-runner/docs/capability-semantic-tools.md
@@ -26,7 +26,7 @@ list, not a disposition — they are never exposed as tools. See
[capability disposition](capability-disposition.md) and
[authorization and exposure](capability-authorization-and-exposure.md).
-The catalog holds **37 tools**: 14 always-agent tools and 23 optional tools
+The catalog holds **38 tools**: 14 always-agent tools and 24 optional tools
across 10 groups.
<!-- These counts are drift-checked against src/tools/capability-semantic-tool-catalog.ts
@@ -39,7 +39,7 @@ by src/catalog/catalog-docs.test.ts; update the catalog, not the numbers. -->
`finish_task`, `block_task`, `request_review`, `write_document`,
`request_human_input`, `register_deliverable`, `inspect_operation_result`.
-### Optional tools (23), by group
+### Optional tools (24), by group
| Group | Tools |
| --- | --- |
@@ -49,7 +49,7 @@ by src/catalog/catalog-docs.test.ts; update the catalog, not the numbers. -->
| cases | `list_cases`, `upsert_case` |
| workspace_runtime | `get_workspace_runtime`, `control_workspace_service` |
| routines | `list_routines`, `manage_routine` |
-| company_skills | `list_company_skills`, `sync_company_skills` |
+| company_skills | `create_skill`, `list_company_skills`, `sync_company_skills` |
| secrets | `list_secret_metadata`, `read_secret_value` |
| portability_admin | `export_company`, `administer_company` |
| test_escape_hatch | `generic_api_request` |
diff --git a/packages/paperclip-runner/generated/capability/semantic-tool-contracts.json b/packages/paperclip-runner/generated/capability/semantic-tool-contracts.json
index 73838d8e4c..634d09c9f0 100644
--- a/packages/paperclip-runner/generated/capability/semantic-tool-contracts.json
+++ b/packages/paperclip-runner/generated/capability/semantic-tool-contracts.json
@@ -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.","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 issue-document key.","maxLength":120,"minLength":1,"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 issue-document key.","maxLength":120,"minLength":1,"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.semantic-tool.v1","version":1},"description":"Append the answer to a status-only wake without changing task disposition.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Concise status answer.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"answer_status_question","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":"write_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create or update an active-task document with optimistic revision safety.","inputSchema":{"additionalProperties":false,"properties":{"baseRevisionId":{"description":"Current revision id, or null when creating.","maxLength":20000,"type":["string","null"]},"body":{"description":"Markdown document body.","maxLength":200000,"minLength":1,"type":"string"},"changeSummary":{"description":"Optional revision summary.","maxLength":20000,"type":["string","null"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"key":{"description":"Stable issue-document key.","maxLength":120,"minLength":1,"type":"string"},"title":{"description":"Document title.","maxLength":300,"minLength":1,"type":"string"}},"required":["idempotencyKey","key","title","body","baseRevisionId"],"type":"object"},"name":"write_document","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":"request_human_input","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a typed, durable interaction on the active task.","inputSchema":{"additionalProperties":false,"properties":{"continuationPolicy":{"enum":["none","wake_assignee","wake_assignee_on_accept"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"interactionKind":{"enum":["confirmation","checkbox","questions","suggest_tasks","item_verdicts"]},"payload":{"additionalProperties":true,"description":"Kind-specific interaction data. For interactionKind='questions', use exactly {version:1, questions:[{id,prompt,selectionMode:'single'|'multi',required?,options:[{id,label,description?,freeText?}]}]}; option keys are id/label, not value, and question choice cardinality is selectionMode, not type. For confirmation, payload may be {}. Keep all ids stable across retries.","type":"object"},"prompt":{"description":"Question or decision prompt.","maxLength":10000,"minLength":1,"type":"string"},"targetRevisionId":{"description":"Optional bound document revision.","maxLength":20000,"type":["string","null"]},"title":{"description":"Interaction card title.","maxLength":300,"minLength":1,"type":"string"}},"required":["idempotencyKey","interactionKind","title","prompt","continuationPolicy"],"type":"object"},"name":"request_human_input","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":"register_deliverable","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Register attachment metadata and its artifact work product without credentials or bytes in the tool result.","inputSchema":{"additionalProperties":false,"properties":{"byteSize":{"maximum":100000000,"minimum":0,"type":"integer"},"contentRef":{"description":"Opaque package-local content reference.","maxLength":2000,"minLength":1,"type":"string"},"contentType":{"description":"Media type.","maxLength":200,"minLength":1,"type":"string"},"filename":{"description":"Display filename.","maxLength":500,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"sha256":{"pattern":"^[a-fA-F0-9]{64}$","type":"string"},"title":{"description":"Work-product title.","maxLength":500,"minLength":1,"type":"string"}},"required":["idempotencyKey","filename","contentType","byteSize","sha256","contentRef","title"],"type":"object"},"name":"register_deliverable","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":"finish_task","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Finish the active task with a durable summary.","inputSchema":{"additionalProperties":false,"properties":{"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"summary":{"description":"Completion summary.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","summary"],"type":"object"},"name":"finish_task","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":"block_task","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Block the active task with a durable reason and optional first-class dependencies.","inputSchema":{"additionalProperties":false,"properties":{"blockedByTaskIds":{"description":"Internal task ids that block this task.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"reason":{"description":"Block reason.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","reason"],"type":"object"},"name":"block_task","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":"request_review","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Move the active task to review with a durable summary.","inputSchema":{"additionalProperties":false,"properties":{"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"summary":{"description":"Review handoff summary.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","summary"],"type":"object"},"name":"request_review","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":"optional","operationId":"list_agents","requiredClaims":["discovery:agents:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List redacted actor profiles.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_agents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_agent","requiredClaims":["discovery:agents:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read one redacted actor profile.","inputSchema":{"additionalProperties":false,"properties":{"actorId":{"description":"Actor id.","maxLength":200,"minLength":1,"type":"string"}},"required":["actorId"],"type":"object"},"name":"get_agent","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"search_tasks","requiredClaims":["discovery:tasks:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Search tasks by text and status within the run company.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"},"query":{"maxLength":500,"type":"string"},"statuses":{"items":{"enum":["backlog","todo","in_progress","in_review","done","blocked","cancelled"]},"maxItems":7,"type":"array","uniqueItems":true}},"required":[],"type":"object"},"name":"search_tasks","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"list_approvals","requiredClaims":["governance:approvals:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List approvals in the run company.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_approvals","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_approval","requiredClaims":["governance:approvals:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read one approval without protected data.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"}},"required":["approvalId"],"type":"object"},"name":"get_approval","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_approval_context","requiredClaims":["governance:approvals:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read one approval, its comments, and linked tasks.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"}},"required":["approvalId"],"type":"object"},"name":"get_approval_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_workspace_runtime","requiredClaims":["workspace:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read active-task workspace services.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_workspace_runtime","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"control_workspace_service","requiredClaims":["workspace:control"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Start, stop, or fault one active-task workspace service.","inputSchema":{"additionalProperties":false,"properties":{"action":{"enum":["start","stop","fail"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"serviceId":{"description":"Workspace service id.","maxLength":200,"minLength":1,"type":"string"},"url":{"description":"Optional service URL.","maxLength":20000,"type":["string","null"]}},"required":["idempotencyKey","serviceId","action"],"type":"object"},"name":"control_workspace_service","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":"optional","operationId":"set_dependencies","requiredClaims":["dependencies:write"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Replace the active task's first-class blocker set.","inputSchema":{"additionalProperties":false,"properties":{"blockedByTaskIds":{"description":"Replacement blocker task ids.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","blockedByTaskIds"],"type":"object"},"name":"set_dependencies","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":"optional","operationId":"create_task","requiredClaims":["delegation:tasks:create"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a project task from a conversation, or a child from an ordinary task. Persist initialPlan before execution.","inputSchema":{"additionalProperties":false,"properties":{"assigneeActorId":{"description":"Optional agent assignee. Omit to assign the current agent.","maxLength":20000,"type":["string","null"]},"blockedByTaskIds":{"description":"Initial blocker task ids.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"description":{"description":"Child task description.","maxLength":20000,"type":["string","null"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"initialPlan":{"description":"Relevant markdown plan saved on the new task before execution starts.","maxLength":200000,"type":["string","null"]},"priority":{"enum":["critical","high","medium","low"]},"projectId":{"description":"Project ID for the task.","type":["string","null"]},"title":{"description":"Child task title.","maxLength":500,"minLength":1,"type":"string"}},"required":["idempotencyKey","title"],"type":"object"},"name":"create_task","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"},"task":{"additionalProperties":false,"properties":{"assigneeActorId":{"type":["string","null"]},"id":{"minLength":1,"type":"string"},"identifier":{"type":["string","null"]},"parentId":{"minLength":1,"type":["string","null"]},"projectId":{"minLength":1,"type":["string","null"]},"status":{"minLength":1,"type":"string"}},"required":["id","identifier","parentId","status","assigneeActorId"],"type":"object"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds","task"],"type":"object"}},{"annotations":{"exposure":"optional","operationId":"request_approval","requiredClaims":["governance:approvals:request"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a governed approval and waiting posture.","inputSchema":{"additionalProperties":false,"properties":{"approvalType":{"description":"Stable approval type.","maxLength":200,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"payload":{"additionalProperties":true,"type":"object"}},"required":["idempotencyKey","approvalType","payload"],"type":"object"},"name":"request_approval","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":"optional","operationId":"decide_approval","requiredClaims":["governance:approvals:decide"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Decide an approval as an explicitly authorized approver.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"},"decision":{"enum":["approved","rejected","cancelled"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"note":{"description":"Decision note.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","approvalId","decision","note"],"type":"object"},"name":"decide_approval","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":"optional","operationId":"comment_on_approval","requiredClaims":["governance:approvals:comment"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Add a durable comment to an approval.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"},"body":{"description":"Approval comment.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","approvalId","body"],"type":"object"},"name":"comment_on_approval","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":"optional","operationId":"schedule_wake","requiredClaims":["control_plane:wakes"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Schedule a deterministic continuation wake.","inputSchema":{"additionalProperties":false,"properties":{"delayTicks":{"maximum":10000,"minimum":1,"type":"integer"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"payload":{"additionalProperties":true,"type":"object"},"reason":{"enum":["manual","issue_commented","interaction_resolved","approval_resolved","blockers_resolved","scheduled_retry","resume"]}},"required":["idempotencyKey","reason","delayTicks"],"type":"object"},"name":"schedule_wake","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":"optional","operationId":"generic_api_request","requiredClaims":["test:generic_api_request"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Test-only escape hatch. Disabled unless the scenario and explicit claim both enable it.","inputSchema":{"additionalProperties":false,"properties":{"body":{"additionalProperties":true,"type":"object"},"method":{"enum":["GET","POST","PATCH"]},"path":{"maxLength":500,"pattern":"^/mock/","type":"string"}},"required":["method","path"],"type":"object"},"name":"generic_api_request","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"search_api","requiredClaims":["api:discover"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Fallback only: discover Paperclip API operations when the available dedicated tools cannot express the task. Prefer dedicated tools for common operations; do not search before using them.","inputSchema":{"additionalProperties":false,"properties":{"cursor":{"maxLength":200,"type":"string"},"limit":{"default":5,"maximum":10,"minimum":1,"type":"integer"},"query":{"maxLength":500,"minLength":1,"type":"string"}},"required":["query"],"type":"object"},"name":"search_api","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"call_api","requiredClaims":["api:call"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Fallback only: call a discovered Paperclip API operation when dedicated tools lack the required operation or parameters. Uses your existing permissions. Prefer dedicated tools; never bypass a denial or runner lifecycle tool.","inputSchema":{"additionalProperties":false,"properties":{"body":{"anyOf":[{"additionalProperties":true,"type":"object"},{"items":{},"type":"array"},{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}],"description":"Request value matching the discovered schema. For JSON object or array requests, pass the object or array directly, never a JSON-encoded string. Strings are for text bodies or endpoints whose schema explicitly accepts a string."},"contentType":{"maxLength":120,"type":"string"},"files":{"items":{"additionalProperties":false,"oneOf":[{"properties":{"artifactId":{}},"required":["artifactId"]},{"properties":{"path":{}},"required":["path"]}],"properties":{"artifactId":{"type":"string"},"field":{"type":"string"},"path":{"description":"File relative to the active issue workspace. Remote files must first be uploaded as an artifact.","type":"string"}},"type":"object"},"maxItems":10,"type":"array"},"operationId":{"description":"Exact operationId returned by search_api, for example GET /api/projects/{id}. Do not guess identifiers.","maxLength":500,"minLength":1,"type":"string"},"pathParams":{"additionalProperties":{"type":"string"},"type":"object"},"query":{"additionalProperties":true,"type":"object"}},"required":["operationId"],"type":"object"},"name":"call_api","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"create_project","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a project after considering existing projects and available repositories. repositoryIds and repositoryUrls accept multiple existing repositories. Use HTTPS GitHub repositoryUrls when an accessible repo is not in the catalog; this registers project repositories, not remote GitHub repositories. Non-code projects may omit repositories. Cannot combine repositoryIds/repositoryUrls with workspace. Reuse the idempotency key on retries.","inputSchema":{"additionalProperties":false,"properties":{"archivedAt":{"description":"Archive timestamp.","maxLength":20000,"type":["string","null"]},"color":{"description":"Project color.","maxLength":20000,"type":["string","null"]},"description":{"description":"Project outcome and context.","maxLength":20000,"type":["string","null"]},"env":{"additionalProperties":true,"type":"object"},"executionWorkspacePolicy":{"additionalProperties":true,"type":"object"},"goalId":{"description":"Goal ID.","maxLength":20000,"type":["string","null"]},"goalIds":{"description":"Goal IDs.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"icon":{"description":"Project icon.","maxLength":20000,"type":["string","null"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"leadAgentId":{"description":"Lead agent ID.","maxLength":20000,"type":["string","null"]},"name":{"description":"Project name.","maxLength":500,"minLength":1,"type":"string"},"repositoryIds":{"description":"Authorized repository IDs from list_project_repositories; may contain multiple repositories.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"repositoryUrls":{"description":"Existing HTTPS GitHub repository URLs, including repos absent from the catalog.","items":{"maxLength":2000,"pattern":"^https://github\\.com/(?!\\.{1,2}/)[A-Za-z0-9_.-]+/(?!\\.{1,2}/?$)[A-Za-z0-9_.-]+/?$","type":"string"},"maxItems":100,"type":"array"},"status":{"enum":["backlog","planned","in_progress","completed","cancelled"]},"targetDate":{"description":"Target date.","maxLength":20000,"type":["string","null"]},"workspace":{"additionalProperties":true,"type":"object"}},"required":["idempotencyKey","name"],"type":"object"},"name":"create_project","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"list_project_repositories","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List authorized repositories with stable IDs and names. Consider appropriate repositories before creating a project; never invent IDs.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_project_repositories","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"list_projects","requiredClaims":["discovery:projects:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Inspect available company projects before selecting a project for new work.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_projects","outputSchema":{"additionalProperties":true,"type":"object"}}]
+[{"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.","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 issue-document key.","maxLength":120,"minLength":1,"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 issue-document key.","maxLength":120,"minLength":1,"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.semantic-tool.v1","version":1},"description":"Append the answer to a status-only wake without changing task disposition.","inputSchema":{"additionalProperties":false,"properties":{"body":{"description":"Concise status answer.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","body"],"type":"object"},"name":"answer_status_question","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":"write_document","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create or update an active-task document with optimistic revision safety.","inputSchema":{"additionalProperties":false,"properties":{"baseRevisionId":{"description":"Current revision id, or null when creating.","maxLength":20000,"type":["string","null"]},"body":{"description":"Markdown document body.","maxLength":200000,"minLength":1,"type":"string"},"changeSummary":{"description":"Optional revision summary.","maxLength":20000,"type":["string","null"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"key":{"description":"Stable issue-document key.","maxLength":120,"minLength":1,"type":"string"},"title":{"description":"Document title.","maxLength":300,"minLength":1,"type":"string"}},"required":["idempotencyKey","key","title","body","baseRevisionId"],"type":"object"},"name":"write_document","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":"request_human_input","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a typed, durable interaction on the active task.","inputSchema":{"additionalProperties":false,"properties":{"continuationPolicy":{"enum":["none","wake_assignee","wake_assignee_on_accept"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"interactionKind":{"enum":["confirmation","checkbox","questions","suggest_tasks","item_verdicts"]},"payload":{"additionalProperties":true,"description":"Kind-specific interaction data. For interactionKind='questions', use exactly {version:1, questions:[{id,prompt,selectionMode:'single'|'multi',required?,options:[{id,label,description?,freeText?}]}]}; option keys are id/label, not value, and question choice cardinality is selectionMode, not type. For confirmation, payload may be {}. Keep all ids stable across retries.","type":"object"},"prompt":{"description":"Question or decision prompt.","maxLength":10000,"minLength":1,"type":"string"},"targetRevisionId":{"description":"Optional bound document revision.","maxLength":20000,"type":["string","null"]},"title":{"description":"Interaction card title.","maxLength":300,"minLength":1,"type":"string"}},"required":["idempotencyKey","interactionKind","title","prompt","continuationPolicy"],"type":"object"},"name":"request_human_input","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":"register_deliverable","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Register attachment metadata and its artifact work product without credentials or bytes in the tool result.","inputSchema":{"additionalProperties":false,"properties":{"byteSize":{"maximum":100000000,"minimum":0,"type":"integer"},"contentRef":{"description":"Opaque package-local content reference.","maxLength":2000,"minLength":1,"type":"string"},"contentType":{"description":"Media type.","maxLength":200,"minLength":1,"type":"string"},"filename":{"description":"Display filename.","maxLength":500,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"sha256":{"pattern":"^[a-fA-F0-9]{64}$","type":"string"},"title":{"description":"Work-product title.","maxLength":500,"minLength":1,"type":"string"}},"required":["idempotencyKey","filename","contentType","byteSize","sha256","contentRef","title"],"type":"object"},"name":"register_deliverable","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":"finish_task","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Finish the active task with a durable summary.","inputSchema":{"additionalProperties":false,"properties":{"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"summary":{"description":"Completion summary.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","summary"],"type":"object"},"name":"finish_task","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":"block_task","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Block the active task with a durable reason and optional first-class dependencies.","inputSchema":{"additionalProperties":false,"properties":{"blockedByTaskIds":{"description":"Internal task ids that block this task.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"reason":{"description":"Block reason.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","reason"],"type":"object"},"name":"block_task","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":"request_review","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Move the active task to review with a durable summary.","inputSchema":{"additionalProperties":false,"properties":{"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"summary":{"description":"Review handoff summary.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","summary"],"type":"object"},"name":"request_review","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":"optional","operationId":"list_agents","requiredClaims":["discovery:agents:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List redacted actor profiles.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_agents","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_agent","requiredClaims":["discovery:agents:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read one redacted actor profile.","inputSchema":{"additionalProperties":false,"properties":{"actorId":{"description":"Actor id.","maxLength":200,"minLength":1,"type":"string"}},"required":["actorId"],"type":"object"},"name":"get_agent","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"search_tasks","requiredClaims":["discovery:tasks:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Search tasks by text and status within the run company.","inputSchema":{"additionalProperties":false,"properties":{"limit":{"default":50,"maximum":200,"minimum":1,"type":"integer"},"query":{"maxLength":500,"type":"string"},"statuses":{"items":{"enum":["backlog","todo","in_progress","in_review","done","blocked","cancelled"]},"maxItems":7,"type":"array","uniqueItems":true}},"required":[],"type":"object"},"name":"search_tasks","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"list_approvals","requiredClaims":["governance:approvals:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List approvals in the run company.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_approvals","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_approval","requiredClaims":["governance:approvals:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read one approval without protected data.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"}},"required":["approvalId"],"type":"object"},"name":"get_approval","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_approval_context","requiredClaims":["governance:approvals:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read one approval, its comments, and linked tasks.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"}},"required":["approvalId"],"type":"object"},"name":"get_approval_context","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"get_workspace_runtime","requiredClaims":["workspace:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Read active-task workspace services.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"get_workspace_runtime","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"control_workspace_service","requiredClaims":["workspace:control"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Start, stop, or fault one active-task workspace service.","inputSchema":{"additionalProperties":false,"properties":{"action":{"enum":["start","stop","fail"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"serviceId":{"description":"Workspace service id.","maxLength":200,"minLength":1,"type":"string"},"url":{"description":"Optional service URL.","maxLength":20000,"type":["string","null"]}},"required":["idempotencyKey","serviceId","action"],"type":"object"},"name":"control_workspace_service","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":"optional","operationId":"set_dependencies","requiredClaims":["dependencies:write"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Replace the active task's first-class blocker set.","inputSchema":{"additionalProperties":false,"properties":{"blockedByTaskIds":{"description":"Replacement blocker task ids.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","blockedByTaskIds"],"type":"object"},"name":"set_dependencies","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":"optional","operationId":"create_task","requiredClaims":["delegation:tasks:create"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a project task from a conversation, or a child from an ordinary task. Persist initialPlan before execution.","inputSchema":{"additionalProperties":false,"properties":{"assigneeActorId":{"description":"Optional agent assignee. Omit to assign the current agent.","maxLength":20000,"type":["string","null"]},"blockedByTaskIds":{"description":"Initial blocker task ids.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"description":{"description":"Child task description.","maxLength":20000,"type":["string","null"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"initialPlan":{"description":"Relevant markdown plan saved on the new task before execution starts.","maxLength":200000,"type":["string","null"]},"priority":{"enum":["critical","high","medium","low"]},"projectId":{"description":"Project ID for the task.","type":["string","null"]},"title":{"description":"Child task title.","maxLength":500,"minLength":1,"type":"string"}},"required":["idempotencyKey","title"],"type":"object"},"name":"create_task","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"},"task":{"additionalProperties":false,"properties":{"assigneeActorId":{"type":["string","null"]},"id":{"minLength":1,"type":"string"},"identifier":{"type":["string","null"]},"parentId":{"minLength":1,"type":["string","null"]},"projectId":{"minLength":1,"type":["string","null"]},"status":{"minLength":1,"type":"string"}},"required":["id","identifier","parentId","status","assigneeActorId"],"type":"object"}},"required":["commandId","disposition","stateRevision","entityRefs","scheduledWakeIds","task"],"type":"object"}},{"annotations":{"exposure":"optional","operationId":"request_approval","requiredClaims":["governance:approvals:request"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a governed approval and waiting posture.","inputSchema":{"additionalProperties":false,"properties":{"approvalType":{"description":"Stable approval type.","maxLength":200,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"payload":{"additionalProperties":true,"type":"object"}},"required":["idempotencyKey","approvalType","payload"],"type":"object"},"name":"request_approval","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":"optional","operationId":"decide_approval","requiredClaims":["governance:approvals:decide"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Decide an approval as an explicitly authorized approver.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"},"decision":{"enum":["approved","rejected","cancelled"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"note":{"description":"Decision note.","maxLength":20000,"minLength":1,"type":"string"}},"required":["idempotencyKey","approvalId","decision","note"],"type":"object"},"name":"decide_approval","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":"optional","operationId":"comment_on_approval","requiredClaims":["governance:approvals:comment"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Add a durable comment to an approval.","inputSchema":{"additionalProperties":false,"properties":{"approvalId":{"description":"Approval id.","maxLength":200,"minLength":1,"type":"string"},"body":{"description":"Approval comment.","maxLength":20000,"minLength":1,"type":"string"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"}},"required":["idempotencyKey","approvalId","body"],"type":"object"},"name":"comment_on_approval","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":"optional","operationId":"schedule_wake","requiredClaims":["control_plane:wakes"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Schedule a deterministic continuation wake.","inputSchema":{"additionalProperties":false,"properties":{"delayTicks":{"maximum":10000,"minimum":1,"type":"integer"},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"payload":{"additionalProperties":true,"type":"object"},"reason":{"enum":["manual","issue_commented","interaction_resolved","approval_resolved","blockers_resolved","scheduled_retry","resume"]}},"required":["idempotencyKey","reason","delayTicks"],"type":"object"},"name":"schedule_wake","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":"optional","operationId":"generic_api_request","requiredClaims":["test:generic_api_request"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Test-only escape hatch. Disabled unless the scenario and explicit claim both enable it.","inputSchema":{"additionalProperties":false,"properties":{"body":{"additionalProperties":true,"type":"object"},"method":{"enum":["GET","POST","PATCH"]},"path":{"maxLength":500,"pattern":"^/mock/","type":"string"}},"required":["method","path"],"type":"object"},"name":"generic_api_request","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"search_api","requiredClaims":["api:discover"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Fallback only: discover Paperclip API operations when the available dedicated tools cannot express the task. Prefer dedicated tools for common operations; do not search before using them.","inputSchema":{"additionalProperties":false,"properties":{"cursor":{"maxLength":200,"type":"string"},"limit":{"default":5,"maximum":10,"minimum":1,"type":"integer"},"query":{"maxLength":500,"minLength":1,"type":"string"}},"required":["query"],"type":"object"},"name":"search_api","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"call_api","requiredClaims":["api:call"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Fallback only: call a discovered Paperclip API operation when dedicated tools lack the required operation or parameters. Uses your existing permissions. Prefer dedicated tools; never bypass a denial or runner lifecycle tool.","inputSchema":{"additionalProperties":false,"properties":{"body":{"anyOf":[{"additionalProperties":true,"type":"object"},{"items":{},"type":"array"},{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"}],"description":"Request value matching the discovered schema. For JSON object or array requests, pass the object or array directly, never a JSON-encoded string. Strings are for text bodies or endpoints whose schema explicitly accepts a string."},"contentType":{"maxLength":120,"type":"string"},"files":{"items":{"additionalProperties":false,"oneOf":[{"properties":{"artifactId":{}},"required":["artifactId"]},{"properties":{"path":{}},"required":["path"]}],"properties":{"artifactId":{"type":"string"},"field":{"type":"string"},"path":{"description":"File relative to the active issue workspace. Remote files must first be uploaded as an artifact.","type":"string"}},"type":"object"},"maxItems":10,"type":"array"},"operationId":{"description":"Exact operationId returned by search_api, for example GET /api/projects/{id}. Do not guess identifiers.","maxLength":500,"minLength":1,"type":"string"},"pathParams":{"additionalProperties":{"type":"string"},"type":"object"},"query":{"additionalProperties":true,"type":"object"}},"required":["operationId"],"type":"object"},"name":"call_api","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"create_project","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a project after considering existing projects and available repositories. repositoryIds and repositoryUrls accept multiple existing repositories. Use HTTPS GitHub repositoryUrls when an accessible repo is not in the catalog; this registers project repositories, not remote GitHub repositories. Non-code projects may omit repositories. Cannot combine repositoryIds/repositoryUrls with workspace. Reuse the idempotency key on retries.","inputSchema":{"additionalProperties":false,"properties":{"archivedAt":{"description":"Archive timestamp.","maxLength":20000,"type":["string","null"]},"color":{"description":"Project color.","maxLength":20000,"type":["string","null"]},"description":{"description":"Project outcome and context.","maxLength":20000,"type":["string","null"]},"env":{"additionalProperties":true,"type":"object"},"executionWorkspacePolicy":{"additionalProperties":true,"type":"object"},"goalId":{"description":"Goal ID.","maxLength":20000,"type":["string","null"]},"goalIds":{"description":"Goal IDs.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"icon":{"description":"Project icon.","maxLength":20000,"type":["string","null"]},"idempotencyKey":{"description":"Caller-stable retry key.","maxLength":240,"minLength":1,"type":"string"},"leadAgentId":{"description":"Lead agent ID.","maxLength":20000,"type":["string","null"]},"name":{"description":"Project name.","maxLength":500,"minLength":1,"type":"string"},"repositoryIds":{"description":"Authorized repository IDs from list_project_repositories; may contain multiple repositories.","items":{"minLength":1,"type":"string"},"maxItems":200,"type":"array","uniqueItems":true},"repositoryUrls":{"description":"Existing HTTPS GitHub repository URLs, including repos absent from the catalog.","items":{"maxLength":2000,"pattern":"^https://github\\.com/(?!\\.{1,2}/)[A-Za-z0-9_.-]+/(?!\\.{1,2}/?$)[A-Za-z0-9_.-]+/?$","type":"string"},"maxItems":100,"type":"array"},"status":{"enum":["backlog","planned","in_progress","completed","cancelled"]},"targetDate":{"description":"Target date.","maxLength":20000,"type":["string","null"]},"workspace":{"additionalProperties":true,"type":"object"}},"required":["idempotencyKey","name"],"type":"object"},"name":"create_project","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"list_project_repositories","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"List authorized repositories with stable IDs and names. Consider appropriate repositories before creating a project; never invent IDs.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_project_repositories","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"list_projects","requiredClaims":["discovery:projects:read"],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Inspect available company projects before selecting a project for new work.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"list_projects","outputSchema":{"additionalProperties":true,"type":"object"}},{"annotations":{"exposure":"optional","operationId":"create_skill","requiredClaims":[],"semanticContract":"paperclip.semantic-tool.v1","version":1},"description":"Create a reusable single-file skill in the company library. Supply a complete SKILL.md whose name and description match the inputs. This saves the skill and shows a card; it does not assign the skill to any agent. Reuse idempotencyKey on retries.","inputSchema":{"additionalProperties":false,"properties":{"description":{"maxLength":2000,"minLength":1,"type":"string"},"idempotencyKey":{"maxLength":240,"minLength":1,"type":"string"},"markdown":{"description":"Complete SKILL.md including name and description frontmatter and substantive instructions.","maxLength":200000,"minLength":1,"type":"string"},"name":{"description":"Lowercase skill name, matching SKILL.md frontmatter.","maxLength":120,"minLength":1,"pattern":"^[a-z0-9]+(?:-[a-z0-9]+)*$","type":"string"},"slug":{"description":"Optional; must equal name.","maxLength":120,"minLength":1,"pattern":"^[a-z0-9]+(?:-[a-z0-9]+)*$","type":"string"}},"required":["idempotencyKey","name","description","markdown"],"type":"object"},"name":"create_skill","outputSchema":{"additionalProperties":true,"type":"object"}}]
diff --git a/packages/paperclip-runner/generated/semantic-action-catalog.json b/packages/paperclip-runner/generated/semantic-action-catalog.json
index a08558336e..e2c48c4755 100644
--- a/packages/paperclip-runner/generated/semantic-action-catalog.json
+++ b/packages/paperclip-runner/generated/semantic-action-catalog.json
@@ -1,4 +1,64 @@
[
+ {
+ "allowedModes": [
+ "standard",
+ "skill_test"
+ ],
+ "description": "Create a reusable single-file skill in the company library. Supply a complete SKILL.md whose name and description match the inputs. This saves the skill and shows a card; it does not assign the skill to any agent. Reuse idempotencyKey on retries.",
+ "effect": "write",
+ "inputSchema": {
+ "additionalProperties": false,
+ "properties": {
+ "description": {
+ "maxLength": 2000,
+ "minLength": 1,
+ "type": "string"
+ },
+ "idempotencyKey": {
+ "maxLength": 240,
+ "minLength": 1,
+ "type": "string"
+ },
+ "markdown": {
+ "description": "Complete SKILL.md including name and description frontmatter and substantive instructions.",
+ "maxLength": 200000,
+ "minLength": 1,
+ "type": "string"
+ },
+ "name": {
+ "description": "Lowercase skill name, matching SKILL.md frontmatter.",
+ "maxLength": 120,
+ "minLength": 1,
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
+ "type": "string"
+ },
+ "slug": {
+ "description": "Optional; must equal name.",
+ "maxLength": 120,
+ "minLength": 1,
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
+ "type": "string"
+ }
+ },
+ "required": [
+ "idempotencyKey",
+ "name",
+ "description",
+ "markdown"
+ ],
+ "type": "object"
+ },
+ "operationId": "create_skill",
+ "outputSchema": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "placement": "optional",
+ "requiredClaims": [],
+ "schema": "paperclip.semantic-action.v1",
+ "title": "Create skill",
+ "version": 1
+ },
{
"allowedModes": [
"standard",
diff --git a/packages/paperclip-runner/protocol/fixtures/evals/native-execution-seeded.json b/packages/paperclip-runner/protocol/fixtures/evals/native-execution-seeded.json
index a25a034c3e..7dbc80557e 100644
--- a/packages/paperclip-runner/protocol/fixtures/evals/native-execution-seeded.json
+++ b/packages/paperclip-runner/protocol/fixtures/evals/native-execution-seeded.json
@@ -24,7 +24,7 @@
"prpVersion": 1,
"nativeExecutionVersion": 1,
"catalogVersion": 1,
- "catalogSha256": "sha256:d86fe304faa341cb46f92c93b6c80a6b8666770ebd915ffe61c7c9d3399e6524",
+ "catalogSha256": "sha256:e2491dd8cb6629b19b80ebd38a0698f7e3b8880eb8915c82c549852060419a3a",
"driverContractVersion": 1,
"driverKind": "paperclip-deterministic",
"driverVersion": "1.0.0"
diff --git a/packages/paperclip-runner/protocol/manifest.json b/packages/paperclip-runner/protocol/manifest.json
index 263d7972a6..910c75393d 100644
--- a/packages/paperclip-runner/protocol/manifest.json
+++ b/packages/paperclip-runner/protocol/manifest.json
@@ -160,7 +160,7 @@
},
{
"path": "fixtures/evals/native-execution-seeded.json",
- "sha256": "dcba9c50475b86260067a7e0789577fc7a5c0624fe3e3552bf3e111c8f9da0ac",
+ "sha256": "ffb22f6d0cdd39f5fa74220a035f4d1cc93ec2ca1cdde3d876c25dde5c82bf8b",
"expectation": "accept",
"compatibilityCase": "canonical"
},
diff --git a/packages/paperclip-runner/spec/capability/protocol-coverage.json b/packages/paperclip-runner/spec/capability/protocol-coverage.json
index 9e10df0247..b3de1393ab 100644
--- a/packages/paperclip-runner/spec/capability/protocol-coverage.json
+++ b/packages/paperclip-runner/spec/capability/protocol-coverage.json
@@ -7,10 +7,30 @@
"src/scenarios/scenario-plan.ts"
],
"counts": {
- "actions": 45,
+ "actions": 46,
"legacyRequirements": 106
},
"actions": [
+ {
+ "id": "create_skill",
+ "ownership": "optional_agent_tool",
+ "surfaces": [
+ "scenario",
+ "live"
+ ],
+ "legacyAliases": [],
+ "contractCase": "protocol-action:create_skill",
+ "contractOwner": "src/catalog/protocol-action-contracts.test.ts::create_skill has a schema-valid canonical example and every declared projection",
+ "legacyBehavioralCases": [],
+ "deterministicCases": [
+ "protocol-action:create_skill"
+ ],
+ "legacyRequirementCases": [],
+ "deterministicOwners": [
+ "src/catalog/protocol-action-contracts.test.ts::create_skill 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": "create_project",
"ownership": "optional_agent_tool",
diff --git a/packages/paperclip-runner/spec/operation-groups/source.json b/packages/paperclip-runner/spec/operation-groups/source.json
index de088ece3a..f5aa9d84ae 100644
--- a/packages/paperclip-runner/spec/operation-groups/source.json
+++ b/packages/paperclip-runner/spec/operation-groups/source.json
@@ -87,8 +87,8 @@
},
{
"id": "company_skills",
- "description": "Inspect company skills and synchronize the current agent's skills.",
- "operationIds": ["list_company_skills", "sync_company_skills"]
+ "description": "Create or inspect company skills and synchronize the current agent's skills.",
+ "operationIds": ["create_skill", "list_company_skills", "sync_company_skills"]
},
{
"id": "secrets",
@@ -264,12 +264,12 @@
"legacyGroup": 13,
"name": "Reference files",
"owner": "optional domain tools + test-only escape hatch",
- "operationIds": ["list_cases", "upsert_case", "list_routines", "manage_routine", "list_company_skills", "sync_company_skills", "list_secret_metadata", "read_secret_value", "export_company", "administer_company", "generic_api_request", "search_api", "call_api", "create_project"],
+ "operationIds": ["list_cases", "upsert_case", "list_routines", "manage_routine", "create_skill", "list_company_skills", "sync_company_skills", "list_secret_metadata", "read_secret_value", "export_company", "administer_company", "generic_api_request", "search_api", "call_api", "create_project"],
"controlPlaneOperationIds": ["append_audit_record"],
"realSurface": "project, case, routine, company-skill, secret, portability, and administration services",
"mockStateDomains": ["company", "cases", "routines", "skills", "secrets", "audit", "fault"],
"prpEvidence": "bounded domain projections, redacted broker receipts, company diffs, and audit references",
- "gap": "Project creation and API tools require the live server authority; generic_api_request is test-only and the remaining domain operations are 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."
+ "gap": "Project and skill creation and API tools require the live server authority; generic_api_request is test-only and the remaining domain operations are 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."
},
{
"id": "mh",
diff --git a/packages/paperclip-runner/spec/paperclip-agent-operation-groups.md b/packages/paperclip-runner/spec/paperclip-agent-operation-groups.md
index 7bd61080c9..8e0670ab17 100644
--- a/packages/paperclip-runner/spec/paperclip-agent-operation-groups.md
+++ b/packages/paperclip-runner/spec/paperclip-agent-operation-groups.md
@@ -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 **105 PRP events in 31 event families**, **18 controller commands in 7 command families**, **10 control-plane operations**, **45 reconciled semantic operations** (14 always, 31 optional), and **106 scenarios in 16 behavior groups**.
+The generated totals are **105 PRP events in 31 event families**, **18 controller commands in 7 command families**, **10 control-plane operations**, **46 reconciled semantic operations** (14 always, 32 optional), and **106 scenarios in 16 behavior groups**.
## Axis 1: PRP v1 event and command families
@@ -87,7 +87,7 @@ Placement has exactly three outcomes:
`answer_status_question`, `block_task`, `finish_task`, `get_task_context`, `get_task_history`, `inspect_operation_result`, `list_document_revisions`, `list_documents`, `read_document`, `register_deliverable`, `report_progress`, `request_human_input`, `request_review`, `write_document`.
-### Optional operations (31) and grant groups (13)
+### Optional operations (32) and grant groups (13)
Grant groups are documentation/exposure bundles, not additional authority. The operation descriptor's exact `requiredClaims` remains decisive.
@@ -101,7 +101,7 @@ Grant groups are documentation/exposure bundles, not additional authority. The o
| `workspace_runtime` | `get_workspace_runtime`<br>`control_workspace_service` | `workspace:control`<br>`workspace:read` | Inspect and control the active issue workspace runtime. |
| `wake_scheduling` | `schedule_wake` | `control_plane:wakes` | Schedule a bounded continuation wake when the current task owns the future check. |
| `routines` | `list_routines`<br>`manage_routine` | `routines:read`<br>`routines:write` | Inspect or manage company routines. |
-| `company_skills` | `list_company_skills`<br>`sync_company_skills` | `company_skills:read`<br>`company_skills:write` | Inspect company skills and synchronize the current agent's skills. |
+| `company_skills` | `create_skill`<br>`list_company_skills`<br>`sync_company_skills` | `company_skills:read`<br>`company_skills:write` | Create 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. |
@@ -120,6 +120,7 @@ Grant groups are documentation/exposure bundles, not additional authority. The o
| `comment_on_approval` | `optional_agent_tool` | `governance:approvals:comment` | `standard`<br>`ask`<br>`planning`<br>`skill_test` | `governance` | `required` | no | `semantic_command:comment_on_approval` | `scenario` + `live`<br>`live_codex` | `unbound`<br>approval lifecycle plus governed-wait continuation and audit events<br>catalog PRP status: `audit_pending` |
| `control_workspace_service` | `optional_agent_tool` | `workspace:control` | `standard`<br>`skill_test` | `workspace_control` | `required` | no | `semantic_command:control_workspace_service` | `scenario` + `live`<br>`live_codex` | `unbound`<br>workspace service lifecycle event<br>catalog PRP status: `audit_pending` |
| `create_project` | `optional_agent_tool` | none | `standard`<br>`skill_test` | `company_write` | `required` | no | inline/no mapping | `live`<br>`live_codex` | `PaperclipRunnerToolAuthority`<br>Authenticated project tools, persisted projects and repository workspaces, and run-bound activity.<br>catalog PRP status: `bound` |
+| `create_skill` | `optional_agent_tool` | none | `standard`<br>`skill_test` | `company_write` | `required` | no | `semantic_command:create_skill` | `scenario` + `live`<br>`live_codex` | `PaperclipRunnerToolAuthority`<br>Authenticated company skill API, saved skill and initial version, and task-bound creation activity.<br>catalog PRP status: `bound` |
| `create_task` | `optional_agent_tool` | `delegation:tasks:create` | `standard`<br>`skill_test` | `company_write` | `required` | no | `semantic_command:create_task` | `scenario` + `live`<br>`live_codex` | `issues.create / issues.createChild`<br>semantic-operation item event plus company-entity state diff and audit record<br>catalog PRP status: `bound` |
| `decide_approval` | `optional_agent_tool` | `governance:approvals:decide` | `standard`<br>`skill_test`<br>roles: `board`<br>`approver`<br>`security` | `governance` | `required` | no | `semantic_command:decide_approval` | `scenario` + `live`<br>`live_codex` | `unbound`<br>approval lifecycle plus governed-wait continuation and audit events<br>catalog PRP status: `audit_pending` |
| `export_company` | `optional_agent_tool` | `portability:export` | `standard`<br>`skill_test` | `admin` | `required` | no | `mock_extension:portability.export` | `scenario`<br>`scenario_mock` | `unbound`<br>company admin/portability item event plus audit record<br>catalog PRP status: `audit_pending` |
@@ -179,7 +180,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>`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. |
-| [`rf` — Reference files](#behavior-group-rf-reference-files) | optional domain tools + test-only escape hatch | `list_cases`<br>`upsert_case`<br>`list_routines`<br>`manage_routine`<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` | `append_audit_record` | project, case, routine, company-skill, secret, portability, and administration services | `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 | Project creation and API tools require the live server authority; generic_api_request is test-only and the remaining domain operations are 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. |
+| [`rf` — Reference files](#behavior-group-rf-reference-files) | optional domain tools + test-only escape hatch | `list_cases`<br>`upsert_case`<br>`list_routines`<br>`manage_routine`<br>`create_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` | `append_audit_record` | project, case, routine, company-skill, secret, portability, and administration services | `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 | Project and skill creation and API tools require the live server authority; generic_api_request is test-only and the remaining domain operations are 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. |
| [`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` | `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 | Production scheduling binding is unbound; control-plane routing remains non-callable. |
@@ -455,9 +456,9 @@ Current responsibility-based paths are normative. Numbered `phase-*` or mileston
### Catalog split and deliberate replacement
-- Scenario/eval catalog: **37** operations.
-- Live dispatcher catalog: **33** operations.
-- Shared: **25**; union/canonical authority: **45**.
+- Scenario/eval catalog: **38** operations.
+- Live dispatcher catalog: **34** operations.
+- Shared: **26**; union/canonical authority: **46**.
- Scenario-only: `administer_company`, `export_company`, `inspect_operation_result`, `list_cases`, `list_company_skills`, `list_goals`, `list_routines`, `list_secret_metadata`, `manage_routine`, `read_secret_value`, `sync_company_skills`, `upsert_case`.
- Live-only: `call_api`, `create_project`, `get_agent`, `get_approval`, `get_approval_context`, `list_project_repositories`, `schedule_wake`, `search_api`.
- 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.
diff --git a/packages/paperclip-runner/src/catalog/catalog-docs.test.ts b/packages/paperclip-runner/src/catalog/catalog-docs.test.ts
index fd23eb9790..56f2e1a041 100644
--- a/packages/paperclip-runner/src/catalog/catalog-docs.test.ts
+++ b/packages/paperclip-runner/src/catalog/catalog-docs.test.ts
@@ -43,7 +43,7 @@ describe("capability-semantic-tools.md stays in sync with the catalog", () => {
expect(Number(alwaysHeader)).toBe(always.length);
expect(Number(optionalHeader)).toBe(optional.length);
// Guard against the historical 36-vs-37 drift the reconciliation plan flagged.
- expect(SCENARIO_CATALOG.length).toBe(37);
+ expect(SCENARIO_CATALOG.length).toBe(38);
});
it("lists exactly the catalog's operation ids in the counts region", () => {
diff --git a/packages/paperclip-runner/src/catalog/reconciliation.test.ts b/packages/paperclip-runner/src/catalog/reconciliation.test.ts
index 417d38739f..12f46328e0 100644
--- a/packages/paperclip-runner/src/catalog/reconciliation.test.ts
+++ b/packages/paperclip-runner/src/catalog/reconciliation.test.ts
@@ -19,10 +19,10 @@ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..")
describe("canonical semantic-catalog reconciliation authority", () => {
it("pins the reconciled op-set relationship between the two catalogs", () => {
const summary = capabilityCatalogReconciliation();
- expect(summary.scenarioCount).toBe(37);
- expect(summary.liveCount).toBe(33);
- expect(summary.sharedCount).toBe(25);
- expect(summary.unionCount).toBe(45);
+ expect(summary.scenarioCount).toBe(38);
+ expect(summary.liveCount).toBe(34);
+ expect(summary.sharedCount).toBe(26);
+ expect(summary.unionCount).toBe(46);
// 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([
@@ -52,7 +52,7 @@ describe("canonical semantic-catalog reconciliation authority", () => {
});
it("is the single source both catalogs derive their operation set from", () => {
- expect(CAPABILITY_CANONICAL_OPERATIONS).toHaveLength(45);
+ expect(CAPABILITY_CANONICAL_OPERATIONS).toHaveLength(46);
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);
@@ -86,7 +86,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(45);
+ expect(CAPABILITY_CANONICAL_CATALOG).toHaveLength(46);
for (const operation of CAPABILITY_CANONICAL_CATALOG) {
expect(operation.placement).toMatch(/^(always|optional)_agent_tool$/);
expect(Array.isArray(operation.requiredClaims)).toBe(true);
@@ -112,7 +112,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: 32,
+ live_codex: 33,
scenario_mock: 12,
test_only: 1,
});
diff --git a/packages/paperclip-runner/src/catalog/semantic-action-catalog.test.ts b/packages/paperclip-runner/src/catalog/semantic-action-catalog.test.ts
index 213fa8d622..3b9ecd8ce2 100644
--- a/packages/paperclip-runner/src/catalog/semantic-action-catalog.test.ts
+++ b/packages/paperclip-runner/src/catalog/semantic-action-catalog.test.ts
@@ -57,7 +57,7 @@ describe("semantic action catalog", () => {
(action) => action.operationId,
);
- expect(operationIds).toHaveLength(32);
+ expect(operationIds).toHaveLength(33);
expect(new Set(operationIds).size).toBe(operationIds.length);
expect(operationIds).not.toContain("generic_api_request");
expect(Object.isFrozen(PAPERCLIP_SEMANTIC_ACTION_CATALOG)).toBe(true);
diff --git a/packages/paperclip-runner/src/catalog/semantic-action-catalog.ts b/packages/paperclip-runner/src/catalog/semantic-action-catalog.ts
index 86c8cfb75a..35fff0310e 100644
--- a/packages/paperclip-runner/src/catalog/semantic-action-catalog.ts
+++ b/packages/paperclip-runner/src/catalog/semantic-action-catalog.ts
@@ -4,6 +4,7 @@ import type {
PaperclipSemanticActionId,
PaperclipSemanticActionMode,
} from "./semantic-action-types.js";
+import { createSkillAction } from "../protocol-actions/create-skill.js";
import { searchApiAction } from "../protocol-actions/search-api.js";
import { callApiAction } from "../protocol-actions/call-api.js";
import { projectRepositoryUrlSchema } from "../protocol-actions/create-project.js";
@@ -108,6 +109,7 @@ function descriptor(input: DescriptorInput): PaperclipSemanticActionDescriptor {
}
const descriptors: readonly PaperclipSemanticActionDescriptor[] = [
+ descriptor({ ...createSkillAction.live.descriptor, placement: "optional", effect: "write" }),
...[searchApiAction, callApiAction].map(action => descriptor({
operationId: action.id,
title: action.live.descriptor.title,
diff --git a/packages/paperclip-runner/src/catalog/semantic-action-types.ts b/packages/paperclip-runner/src/catalog/semantic-action-types.ts
index 360bbfd356..7be978cb97 100644
--- a/packages/paperclip-runner/src/catalog/semantic-action-types.ts
+++ b/packages/paperclip-runner/src/catalog/semantic-action-types.ts
@@ -23,6 +23,7 @@ export type PaperclipSemanticActionId =
| "get_workspace_runtime"
| "control_workspace_service"
| "set_dependencies"
+ | "create_skill"
| "create_project"
| "list_project_repositories"
| "list_projects"
diff --git a/packages/paperclip-runner/src/eval/workflow-evals.test.ts b/packages/paperclip-runner/src/eval/workflow-evals.test.ts
index 58653ac45d..7870f4eb7f 100644
--- a/packages/paperclip-runner/src/eval/workflow-evals.test.ts
+++ b/packages/paperclip-runner/src/eval/workflow-evals.test.ts
@@ -466,13 +466,13 @@ describe("workflow reports and stress traceability", () => {
candidateFailures: 36,
});
expect(report.coverage).toMatchObject({
- canonicalOperations: 45,
+ canonicalOperations: 46,
capabilityCases: 106,
workflows: 12,
stressFindings: 44,
stressExclusions: 1,
});
- expect(report.coverage.operations).toHaveLength(45);
+ expect(report.coverage.operations).toHaveLength(46);
expect(report.coverage.composedWorkflows).toHaveLength(12);
expect(
report.coverage.operations.find(
@@ -480,7 +480,7 @@ describe("workflow reports and stress traceability", () => {
)?.workflowIds.length,
).toBeGreaterThan(0);
expect(renderRunnerWorkflowMarkdown(report)).toContain(
- "45 operations · 106 capability cases · 12 workflows",
+ "46 operations · 106 capability cases · 12 workflows",
);
expect(renderRunnerWorkflowJUnit(report)).toContain(
'tests="36" failures="36" skipped="0"',
diff --git a/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts b/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts
index 88e62d37eb..0fed1d2763 100644
--- a/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts
+++ b/packages/paperclip-runner/src/mock-core/capability-control-plane-types.ts
@@ -315,6 +315,8 @@ export interface CapabilityFixtureState {
outOfScopeTaskIds: string[];
comments: CapabilityFixtureComment[];
documents: CapabilityFixtureDocument[];
+ skills?: Array<{ id: string; companyId: string; name: string; slug: string; description: string; markdown: string; versionId: string }>;
+
interactions: CapabilityFixtureInteraction[];
approvals: CapabilityFixtureApproval[];
artifacts: CapabilityFixtureArtifact[];
@@ -355,6 +357,7 @@ interface CapabilityBaseCommand {
}
export type CapabilitySemanticCommand =
+ | (CapabilityBaseCommand & { kind: "create_skill"; name: string; slug?: string; description: string; markdown: string })
| (CapabilityBaseCommand & { kind: "report_progress"; body: string })
| (CapabilityBaseCommand & {
kind: "write_document";
@@ -472,6 +475,7 @@ export type CapabilityCommandOutcome =
* bypass these checks.
*/
export const CAPABILITY_COMMAND_REQUIRED_CLAIMS = {
+ create_skill: [],
report_progress: [],
write_document: [],
request_human_input: [],
@@ -521,6 +525,7 @@ export interface CapabilityFixtureSeed {
outOfScopeTaskIds?: string[];
comments?: CapabilityFixtureComment[];
documents?: CapabilityFixtureDocument[];
+ skills?: CapabilityFixtureState["skills"];
interactions?: CapabilityFixtureInteraction[];
approvals?: CapabilityFixtureApproval[];
artifacts?: CapabilityFixtureArtifact[];
@@ -600,6 +605,7 @@ export function createCapabilityFixtureState(seed: CapabilityFixtureSeed = {}):
outOfScopeTaskIds: structuredClone(seed.outOfScopeTaskIds ?? []),
comments: structuredClone(seed.comments ?? []),
documents: structuredClone(seed.documents ?? []),
+ ...(seed.skills ? { skills: structuredClone(seed.skills) } : {}),
interactions: structuredClone(seed.interactions ?? []),
approvals: structuredClone(seed.approvals ?? []),
artifacts: structuredClone(seed.artifacts ?? []),
diff --git a/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts b/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts
index 7a8e00ef66..9801d5380b 100644
--- a/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts
+++ b/packages/paperclip-runner/src/mock-core/capability-mock-control-plane-adapter.ts
@@ -36,6 +36,7 @@ import {
type CapabilitySemanticToolRuntimeSnapshot,
type CapabilityWakeContext,
} from "./capability-control-plane-types.js";
+import { parseFrontmatterMarkdown, validateSkillFrontmatter } from "./skill-frontmatter.generated.js";
const DEFAULT_WAKE: CapabilityWakeContext = { reason: "manual", payload: {} };
@@ -708,6 +709,31 @@ export class CapabilityMockControlPlaneAdapter implements CapabilityMockControlP
entityRefs.push(`comment:${comment.id}`);
break;
}
+ case "create_skill": {
+ requireText(command.name, "skill name");
+ requireText(command.markdown, "skill markdown");
+ const document = parseFrontmatterMarkdown(command.markdown);
+ const validMetadata = validateSkillFrontmatter(document.frontmatter);
+ if (!document.hasFrontmatter || !validMetadata || !document.body.trim()
+ || document.frontmatter.name !== command.name
+ || document.frontmatter.description !== command.description.trim()
+ || (command.slug !== undefined && command.slug !== command.name)) {
+ throw new CapabilityMockControlPlaneError(
+ "invalid_skill_document",
+ "Provide a complete SKILL.md with name and description matching the command inputs, a nonempty body, and slug equal to name when supplied",
+ );
+ }
+ const slug = command.slug ?? command.name;
+ const skills = this.#state.skills ??= [];
+ if (skills.some(skill => skill.companyId === run.companyId && skill.slug === slug)) {
+ throw new CapabilityMockControlPlaneError("fixture_state_invalid", "A skill with that name already exists");
+ }
+ const skill = { id: this.#id("skill"), companyId: run.companyId, name: command.name,
+ slug, description: command.description.trim(), markdown: command.markdown, versionId: this.#id("skill-version") };
+ skills.push(skill);
+ entityRefs.push(`skill:${skill.id}`);
+ break;
+ }
case "write_document": {
requireText(command.key, "document key");
requireText(command.title, "document title");
diff --git a/packages/paperclip-runner/src/mock-core/skill-frontmatter.generated.ts b/packages/paperclip-runner/src/mock-core/skill-frontmatter.generated.ts
new file mode 100644
index 0000000000..b1bac8c53e
--- /dev/null
+++ b/packages/paperclip-runner/src/mock-core/skill-frontmatter.generated.ts
@@ -0,0 +1,604 @@
+// @ts-nocheck -- generated parser and standalone schema validator.
+
+// Generated from packages/shared/src/frontmatter.ts. Do not edit by hand.
+
+// Regenerate: node packages/shared/scripts/generate-runner-skill-frontmatter.ts
+
+export interface MarkdownDoc {
+ frontmatter: Record<string, unknown>;
+ body: string;
+ hasFrontmatter: boolean;
+}
+
+export function isPlainRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function parseFrontmatterMarkdown(raw: string): MarkdownDoc {
+ const normalized = raw.replace(/\r\n/g, "\n");
+ if (!normalized.startsWith("---\n")) {
+ return { frontmatter: {}, body: normalized.trim(), hasFrontmatter: false };
+ }
+
+ const closing = normalized.indexOf("\n---\n", 4);
+ if (closing < 0) {
+ return { frontmatter: {}, body: normalized.trim(), hasFrontmatter: false };
+ }
+
+ const frontmatterRaw = normalized.slice(4, closing);
+ const body = normalized.slice(closing + 5).trim();
+ return {
+ frontmatter: parseYamlFrontmatter(frontmatterRaw),
+ body,
+ hasFrontmatter: true,
+ };
+}
+
+function parseYamlFrontmatter(raw: string): Record<string, unknown> {
+ const prepared = prepareYamlLines(raw);
+ const firstContentIndex = prepared.findIndex((line) => !line.isBlank && !line.isComment);
+ if (firstContentIndex < 0) return {};
+ const parsed = parseYamlBlock(prepared, firstContentIndex, prepared[firstContentIndex]!.indent);
+ return isPlainRecord(parsed.value) ? parsed.value : {};
+}
+
+function prepareYamlLines(raw: string) {
+ return raw
+ .split("\n")
+ .map((line) => ({
+ indent: line.match(/^ */)?.[0].length ?? 0,
+ raw: line,
+ content: line.trim(),
+ isBlank: line.trim().length === 0,
+ isComment: line.trim().startsWith("#"),
+ }));
+}
+
+function parseYamlBlock(
+ lines: Array<{ indent: number; raw: string; content: string; isBlank: boolean; isComment: boolean }>,
+ startIndex: number,
+ indentLevel: number,
+): { value: unknown; nextIndex: number } {
+ let index = startIndex;
+ while (index < lines.length && (lines[index]!.isBlank || lines[index]!.isComment)) {
+ index += 1;
+ }
+ if (index >= lines.length || lines[index]!.indent < indentLevel) {
+ return { value: {}, nextIndex: index };
+ }
+
+ const isArray = lines[index]!.indent === indentLevel && lines[index]!.content.startsWith("-");
+ if (isArray) {
+ const values: unknown[] = [];
+ while (index < lines.length) {
+ const line = lines[index]!;
+ if (line.isBlank || line.isComment) {
+ index += 1;
+ continue;
+ }
+ if (line.indent < indentLevel) break;
+ if (line.indent !== indentLevel || !line.content.startsWith("-")) break;
+
+ const remainder = line.content.slice(1).trim();
+ index += 1;
+ if (!remainder) {
+ const nested = parseYamlBlock(lines, index, indentLevel + 2);
+ values.push(nested.value);
+ index = nested.nextIndex;
+ continue;
+ }
+
+ if (isYamlBlockScalarIndicator(remainder)) {
+ const block = parseYamlBlockScalar(lines, index, indentLevel, remainder);
+ values.push(block.value);
+ index = block.nextIndex;
+ continue;
+ }
+
+ const inlineObjectSeparator = remainder.indexOf(":");
+ if (
+ inlineObjectSeparator > 0
+ && !remainder.startsWith("\"")
+ && !remainder.startsWith("{")
+ && !remainder.startsWith("[")
+ ) {
+ const key = remainder.slice(0, inlineObjectSeparator).trim();
+ const rawValue = remainder.slice(inlineObjectSeparator + 1).trim();
+ const nextObject: Record<string, unknown> = {
+ [key]: parseYamlScalar(rawValue),
+ };
+ if (index < lines.length && lines[index]!.indent > indentLevel) {
+ const nested = parseYamlBlock(lines, index, indentLevel + 2);
+ if (isPlainRecord(nested.value)) {
+ Object.assign(nextObject, nested.value);
+ }
+ index = nested.nextIndex;
+ }
+ values.push(nextObject);
+ continue;
+ }
+
+ values.push(parseYamlScalar(remainder));
+ }
+ return { value: values, nextIndex: index };
+ }
+
+ const record: Record<string, unknown> = {};
+ while (index < lines.length) {
+ const line = lines[index]!;
+ if (line.isBlank || line.isComment) {
+ index += 1;
+ continue;
+ }
+ if (line.indent < indentLevel) break;
+ if (line.indent !== indentLevel) {
+ index += 1;
+ continue;
+ }
+
+ const separatorIndex = line.content.indexOf(":");
+ if (separatorIndex <= 0) {
+ index += 1;
+ continue;
+ }
+
+ const key = line.content.slice(0, separatorIndex).trim();
+ const remainder = line.content.slice(separatorIndex + 1).trim();
+ index += 1;
+ if (!remainder) {
+ const nested = parseYamlBlock(lines, index, indentLevel + 2);
+ record[key] = nested.value;
+ index = nested.nextIndex;
+ continue;
+ }
+ if (isYamlBlockScalarIndicator(remainder)) {
+ const block = parseYamlBlockScalar(lines, index, indentLevel, remainder);
+ record[key] = block.value;
+ index = block.nextIndex;
+ continue;
+ }
+ record[key] = parseYamlScalar(remainder);
+ }
+
+ return { value: record, nextIndex: index };
+}
+
+function isYamlBlockScalarIndicator(rawValue: string) {
+ return /^[>|][+-]?$/.test(rawValue.trim());
+}
+
+function parseYamlBlockScalar(
+ lines: Array<{ indent: number; raw: string; content: string; isBlank: boolean; isComment: boolean }>,
+ startIndex: number,
+ parentIndent: number,
+ indicator: string,
+): { value: string; nextIndex: number } {
+ const trimmedIndicator = indicator.trim();
+ const style = trimmedIndicator[0];
+ const chomp = trimmedIndicator.endsWith("+")
+ ? "+"
+ : trimmedIndicator.endsWith("-")
+ ? "-"
+ : "";
+ let index = startIndex;
+ const collected: Array<{ indent: number; raw: string; isBlank: boolean }> = [];
+ while (index < lines.length) {
+ const line = lines[index]!;
+ if (!line.isBlank && line.indent <= parentIndent) break;
+ collected.push({ indent: line.indent, raw: line.raw, isBlank: line.isBlank });
+ index += 1;
+ }
+
+ const contentLines = collected.filter((line) => !line.isBlank);
+ if (contentLines.length === 0) return { value: "", nextIndex: index };
+
+ const blockIndent = Math.min(...contentLines.map((line) => line.indent));
+ const normalizedLines = collected.map((line) => (
+ line.isBlank ? "" : line.raw.slice(Math.min(blockIndent, line.raw.length))
+ ));
+
+ const baseValue = style === "|"
+ ? normalizedLines.join("\n")
+ : foldYamlBlockScalarLines(normalizedLines);
+
+ return {
+ value: applyYamlBlockChomp(baseValue, chomp),
+ nextIndex: index,
+ };
+}
+
+function foldYamlBlockScalarLines(lines: string[]) {
+ let value = "";
+ let pendingBlankLines = 0;
+ for (const line of lines) {
+ if (line === "") {
+ pendingBlankLines += 1;
+ continue;
+ }
+ if (value.length === 0) {
+ value = `${"\n".repeat(pendingBlankLines)}${line}`;
+ } else if (pendingBlankLines > 0) {
+ value += `${"\n".repeat(pendingBlankLines + 1)}${line}`;
+ } else {
+ value += ` ${line}`;
+ }
+ pendingBlankLines = 0;
+ }
+
+ if (pendingBlankLines > 0 && value.length > 0) {
+ value += "\n".repeat(pendingBlankLines);
+ }
+ return value;
+}
+
+function applyYamlBlockChomp(value: string, chomp: "" | "+" | "-") {
+ if (chomp === "+") return value;
+ if (chomp === "-") return value.replace(/\n+$/u, "");
+ if (value.length === 0) return value;
+ return value.replace(/\n+$/u, "") + "\n";
+}
+
+function parseYamlScalar(rawValue: string): unknown {
+ const trimmed = rawValue.trim();
+ if (trimmed === "") return "";
+ if (trimmed === "null" || trimmed === "~") return null;
+ if (trimmed === "true") return true;
+ if (trimmed === "false") return false;
+ if (trimmed === "[]") return [];
+ if (trimmed === "{}") return {};
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) return Number(trimmed);
+ if (
+ trimmed.startsWith("\"") ||
+ trimmed.startsWith("[") ||
+ trimmed.startsWith("{")
+ ) {
+ try {
+ return JSON.parse(trimmed);
+ } catch {
+ return trimmed;
+ }
+ }
+ return trimmed;
+}
+
+"use strict";
+export const validateSkillFrontmatter = validate10;
+const schema11 = {"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"name":{"type":"string","pattern":"^[a-z0-9]+(?:-[a-z0-9]+)*$"},"description":{"type":"string","minLength":1},"allowed-tools":{"type":"array","items":{"type":"string"}},"metadata":{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"$ref":"#/definitions/__schema0"}}},"required":["name","description"],"additionalProperties":{},"definitions":{"__schema0":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"type":"array","items":{"$ref":"#/definitions/__schema0"}},{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"$ref":"#/definitions/__schema0"}}]}}};
+const pattern0 = new RegExp("^[a-z0-9]+(?:-[a-z0-9]+)*$", "u");
+const func2 = ((value: string) => [...value].length);
+const schema12 = {"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"null"},{"type":"array","items":{"$ref":"#/definitions/__schema0"}},{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"$ref":"#/definitions/__schema0"}}]};
+const wrapper0 = {validate: validate11};
+
+function validate11(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
+let vErrors = null;
+let errors = 0;
+const _errs0 = errors;
+let valid0 = false;
+const _errs1 = errors;
+if(typeof data !== "string"){
+const err0 = {instancePath,schemaPath:"#/anyOf/0/type",keyword:"type",params:{type: "string"},message:"must be string"};
+if(vErrors === null){
+vErrors = [err0];
+}
+else {
+vErrors.push(err0);
+}
+errors++;
+}
+var _valid0 = _errs1 === errors;
+valid0 = valid0 || _valid0;
+if(!valid0){
+const _errs3 = errors;
+if(!(typeof data == "number")){
+const err1 = {instancePath,schemaPath:"#/anyOf/1/type",keyword:"type",params:{type: "number"},message:"must be number"};
+if(vErrors === null){
+vErrors = [err1];
+}
+else {
+vErrors.push(err1);
+}
+errors++;
+}
+var _valid0 = _errs3 === errors;
+valid0 = valid0 || _valid0;
+if(!valid0){
+const _errs5 = errors;
+if(typeof data !== "boolean"){
+const err2 = {instancePath,schemaPath:"#/anyOf/2/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"};
+if(vErrors === null){
+vErrors = [err2];
+}
+else {
+vErrors.push(err2);
+}
+errors++;
+}
+var _valid0 = _errs5 === errors;
+valid0 = valid0 || _valid0;
+if(!valid0){
+const _errs7 = errors;
+if(data !== null){
+const err3 = {instancePath,schemaPath:"#/anyOf/3/type",keyword:"type",params:{type: "null"},message:"must be null"};
+if(vErrors === null){
+vErrors = [err3];
+}
+else {
+vErrors.push(err3);
+}
+errors++;
+}
+var _valid0 = _errs7 === errors;
+valid0 = valid0 || _valid0;
+if(!valid0){
+const _errs9 = errors;
+if(errors === _errs9){
+if(Array.isArray(data)){
+var valid1 = true;
+const len0 = data.length;
+for(let i0=0; i0<len0; i0++){
+const _errs11 = errors;
+if(!(wrapper0.validate(data[i0], {instancePath:instancePath+"/" + i0,parentData:data,parentDataProperty:i0,rootData}))){
+vErrors = vErrors === null ? wrapper0.validate.errors : vErrors.concat(wrapper0.validate.errors);
+errors = vErrors.length;
+}
+var valid1 = _errs11 === errors;
+if(!valid1){
+break;
+}
+}
+}
+else {
+const err4 = {instancePath,schemaPath:"#/anyOf/4/type",keyword:"type",params:{type: "array"},message:"must be array"};
+if(vErrors === null){
+vErrors = [err4];
+}
+else {
+vErrors.push(err4);
+}
+errors++;
+}
+}
+var _valid0 = _errs9 === errors;
+valid0 = valid0 || _valid0;
+if(!valid0){
+const _errs12 = errors;
+if(errors === _errs12){
+if(data && typeof data == "object" && !Array.isArray(data)){
+for(const key0 in data){
+const _errs14 = errors;
+if(typeof key0 !== "string"){
+const err5 = {instancePath,schemaPath:"#/anyOf/5/propertyNames/type",keyword:"type",params:{type: "string"},message:"must be string",propertyName:key0};
+if(vErrors === null){
+vErrors = [err5];
+}
+else {
+vErrors.push(err5);
+}
+errors++;
+}
+var valid2 = _errs14 === errors;
+if(!valid2){
+const err6 = {instancePath,schemaPath:"#/anyOf/5/propertyNames",keyword:"propertyNames",params:{propertyName: key0},message:"property name must be valid"};
+if(vErrors === null){
+vErrors = [err6];
+}
+else {
+vErrors.push(err6);
+}
+errors++;
+break;
+}
+}
+if(valid2){
+for(const key1 in data){
+const _errs17 = errors;
+if(!(wrapper0.validate(data[key1], {instancePath:instancePath+"/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"),parentData:data,parentDataProperty:key1,rootData}))){
+vErrors = vErrors === null ? wrapper0.validate.errors : vErrors.concat(wrapper0.validate.errors);
+errors = vErrors.length;
+}
+var valid3 = _errs17 === errors;
+if(!valid3){
+break;
+}
+}
+}
+}
+else {
+const err7 = {instancePath,schemaPath:"#/anyOf/5/type",keyword:"type",params:{type: "object"},message:"must be object"};
+if(vErrors === null){
+vErrors = [err7];
+}
+else {
+vErrors.push(err7);
+}
+errors++;
+}
+}
+var _valid0 = _errs12 === errors;
+valid0 = valid0 || _valid0;
+}
+}
+}
+}
+}
+if(!valid0){
+const err8 = {instancePath,schemaPath:"#/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};
+if(vErrors === null){
+vErrors = [err8];
+}
+else {
+vErrors.push(err8);
+}
+errors++;
+validate11.errors = vErrors;
+return false;
+}
+else {
+errors = _errs0;
+if(vErrors !== null){
+if(_errs0){
+vErrors.length = _errs0;
+}
+else {
+vErrors = null;
+}
+}
+}
+validate11.errors = vErrors;
+return errors === 0;
+}
+
+
+function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
+let vErrors = null;
+let errors = 0;
+if(errors === 0){
+if(data && typeof data == "object" && !Array.isArray(data)){
+let missing0;
+if(((data.name === undefined) && (missing0 = "name")) || ((data.description === undefined) && (missing0 = "description"))){
+validate10.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];
+return false;
+}
+else {
+if(data.name !== undefined){
+let data0 = data.name;
+const _errs2 = errors;
+if(errors === _errs2){
+if(typeof data0 === "string"){
+if(!pattern0.test(data0)){
+validate10.errors = [{instancePath:instancePath+"/name",schemaPath:"#/properties/name/pattern",keyword:"pattern",params:{pattern: "^[a-z0-9]+(?:-[a-z0-9]+)*$"},message:"must match pattern \""+"^[a-z0-9]+(?:-[a-z0-9]+)*$"+"\""}];
+return false;
+}
+}
+else {
+validate10.errors = [{instancePath:instancePath+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type: "string"},message:"must be string"}];
+return false;
+}
+}
+var valid0 = _errs2 === errors;
+}
+else {
+var valid0 = true;
+}
+if(valid0){
+if(data.description !== undefined){
+let data1 = data.description;
+const _errs4 = errors;
+if(errors === _errs4){
+if(typeof data1 === "string"){
+if(func2(data1) < 1){
+validate10.errors = [{instancePath:instancePath+"/description",schemaPath:"#/properties/description/minLength",keyword:"minLength",params:{limit: 1},message:"must NOT have fewer than 1 characters"}];
+return false;
+}
+}
+else {
+validate10.errors = [{instancePath:instancePath+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type: "string"},message:"must be string"}];
+return false;
+}
+}
+var valid0 = _errs4 === errors;
+}
+else {
+var valid0 = true;
+}
+if(valid0){
+if(data["allowed-tools"] !== undefined){
+let data2 = data["allowed-tools"];
+const _errs6 = errors;
+if(errors === _errs6){
+if(Array.isArray(data2)){
+var valid1 = true;
+const len0 = data2.length;
+for(let i0=0; i0<len0; i0++){
+const _errs8 = errors;
+if(typeof data2[i0] !== "string"){
+validate10.errors = [{instancePath:instancePath+"/allowed-tools/" + i0,schemaPath:"#/properties/allowed-tools/items/type",keyword:"type",params:{type: "string"},message:"must be string"}];
+return false;
+}
+var valid1 = _errs8 === errors;
+if(!valid1){
+break;
+}
+}
+}
+else {
+validate10.errors = [{instancePath:instancePath+"/allowed-tools",schemaPath:"#/properties/allowed-tools/type",keyword:"type",params:{type: "array"},message:"must be array"}];
+return false;
+}
+}
+var valid0 = _errs6 === errors;
+}
+else {
+var valid0 = true;
+}
+if(valid0){
+if(data.metadata !== undefined){
+let data4 = data.metadata;
+const _errs10 = errors;
+if(errors === _errs10){
+if(data4 && typeof data4 == "object" && !Array.isArray(data4)){
+for(const key0 in data4){
+const _errs12 = errors;
+if(typeof key0 !== "string"){
+const err0 = {instancePath:instancePath+"/metadata",schemaPath:"#/properties/metadata/propertyNames/type",keyword:"type",params:{type: "string"},message:"must be string",propertyName:key0};
+if(vErrors === null){
+vErrors = [err0];
+}
+else {
+vErrors.push(err0);
+}
+errors++;
+}
+var valid2 = _errs12 === errors;
+if(!valid2){
+const err1 = {instancePath:instancePath+"/metadata",schemaPath:"#/properties/metadata/propertyNames",keyword:"propertyNames",params:{propertyName: key0},message:"property name must be valid"};
+if(vErrors === null){
+vErrors = [err1];
+}
+else {
+vErrors.push(err1);
+}
+errors++;
+validate10.errors = vErrors;
+return false;
+break;
+}
+}
+if(valid2){
+for(const key1 in data4){
+const _errs15 = errors;
+if(!(validate11(data4[key1], {instancePath:instancePath+"/metadata/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"),parentData:data4,parentDataProperty:key1,rootData}))){
+vErrors = vErrors === null ? validate11.errors : vErrors.concat(validate11.errors);
+errors = vErrors.length;
+}
+var valid3 = _errs15 === errors;
+if(!valid3){
+break;
+}
+}
+}
+}
+else {
+validate10.errors = [{instancePath:instancePath+"/metadata",schemaPath:"#/properties/metadata/type",keyword:"type",params:{type: "object"},message:"must be object"}];
+return false;
+}
+}
+var valid0 = _errs10 === errors;
+}
+else {
+var valid0 = true;
+}
+}
+}
+}
+}
+}
+else {
+validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];
+return false;
+}
+}
+validate10.errors = vErrors;
+return errors === 0;
+}
+
diff --git a/packages/paperclip-runner/src/protocol-actions/create-skill.ts b/packages/paperclip-runner/src/protocol-actions/create-skill.ts
new file mode 100644
index 0000000000..aa27450e58
--- /dev/null
+++ b/packages/paperclip-runner/src/protocol-actions/create-skill.ts
@@ -0,0 +1,238 @@
+/** Canonical definition and documentation for `create_skill`. */
+export const createSkillAction = {
+ "id": "create_skill",
+ "canonical": {
+ "operationId": "create_skill",
+ "surfaces": [
+ "scenario",
+ "live"
+ ],
+ "placement": "optional_agent_tool",
+ "optionalGroup": "company_skills",
+ "requiredClaims": [],
+ "taskModes": [
+ "standard",
+ "skill_test"
+ ],
+ "sideEffectClass": "company_write",
+ "idempotency": "required",
+ "disabledByDefault": false,
+ "realBindingStatus": "live_codex",
+ "realServiceBinding": "PaperclipRunnerToolAuthority",
+ "prpEvidence": "Authenticated company skill API, saved skill and initial version, and task-bound creation activity.",
+ "prpBindingStatus": "bound",
+ "legacyAliases": []
+ },
+ "documentation": {
+ "title": "Create skill",
+ "description": "Create a reusable single-file skill in the company library. Supply a complete SKILL.md whose name and description match the inputs. This saves the skill and shows a card; it does not assign the skill to any agent. Reuse idempotencyKey on retries.",
+ "note": null
+ },
+ "examples": {
+ "call": {
+ "operationId": "create_skill",
+ "input": {
+ "idempotencyKey": "example",
+ "name": "release-review",
+ "description": "Review release notes.",
+ "markdown": "---\nname: release-review\ndescription: Review release notes.\n---\n\n# Review\nCheck each note against the change.\n"
+ }
+ },
+ "scenarioCall": {
+ "operationId": "create_skill",
+ "idempotencyKey": "example",
+ "input": {
+ "name": "release-review",
+ "description": "Review release notes.",
+ "markdown": "---\nname: release-review\ndescription: Review release notes.\n---\n\n# Review\nCheck each note against the change.\n"
+ }
+ },
+ "success": {
+ "ok": true,
+ "operationId": "create_skill",
+ "result": {
+ "id": "skill-example",
+ "name": "release-review",
+ "slug": "release-review",
+ "description": "Review release notes.",
+ "versionId": "version-example",
+ "studioPath": "/skills/studio/skill-example"
+ }
+ }
+ },
+ "live": {
+ "order": 46,
+ "descriptor": {
+ "schema": "paperclip.semantic-tool.v1",
+ "operationId": "create_skill",
+ "version": 1,
+ "title": "Create skill",
+ "description": "Create a reusable single-file skill in the company library. Supply a complete SKILL.md whose name and description match the inputs. This saves the skill and shows a card; it does not assign the skill to any agent. Reuse idempotencyKey on retries.",
+ "exposure": "optional",
+ "requiredClaims": [],
+ "allowedModes": [
+ "standard",
+ "skill_test"
+ ],
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "idempotencyKey": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 240
+ },
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120,
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
+ "description": "Lowercase skill name, matching SKILL.md frontmatter."
+ },
+ "slug": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120,
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
+ "description": "Optional; must equal name."
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2000
+ },
+ "markdown": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200000,
+ "description": "Complete SKILL.md including name and description frontmatter and substantive instructions."
+ }
+ },
+ "required": [
+ "idempotencyKey",
+ "name",
+ "description",
+ "markdown"
+ ],
+ "additionalProperties": false
+ },
+ "outputSchema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ },
+ "scenario": {
+ "order": 46,
+ "successExample": {
+ "schema": "paperclip.capability.tool-result.v1",
+ "ok": true,
+ "operationId": "create_skill",
+ "operationResultId": "example-result",
+ "value": {
+ "commandId": "example",
+ "disposition": "applied",
+ "stateRevision": 1,
+ "entityRefs": [
+ "example"
+ ],
+ "scheduledWakeIds": [
+ "example"
+ ]
+ },
+ "commandResult": null,
+ "authorization": {}
+ },
+ "descriptor": {
+ "operationId": "create_skill",
+ "version": 1,
+ "title": "Create skill",
+ "description": "Create a reusable single-file skill in the company library. Supply a complete SKILL.md whose name and description match the inputs. This saves the skill and shows a card; it does not assign the skill to any agent. Reuse idempotencyKey on retries.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120,
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
+ "description": "Lowercase skill name, matching SKILL.md frontmatter."
+ },
+ "slug": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 120,
+ "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$",
+ "description": "Optional; must equal name."
+ },
+ "description": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2000
+ },
+ "markdown": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 200000,
+ "description": "Complete SKILL.md including name and description frontmatter and substantive instructions."
+ }
+ },
+ "required": [
+ "name",
+ "description",
+ "markdown"
+ ],
+ "additionalProperties": false
+ },
+ "outputSchema": {
+ "type": "object",
+ "properties": {
+ "schema": {
+ "type": "string",
+ "enum": [
+ "paperclip.capability.tool-result.v1"
+ ]
+ },
+ "ok": {
+ "type": "boolean"
+ },
+ "operationId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "operationResultId": {
+ "type": "string",
+ "minLength": 1
+ },
+ "value": {},
+ "commandResult": {},
+ "authorization": {}
+ },
+ "required": [
+ "schema",
+ "ok",
+ "operationId",
+ "operationResultId",
+ "value",
+ "commandResult",
+ "authorization"
+ ],
+ "additionalProperties": false
+ },
+ "disposition": "optional_agent_tool",
+ "optionalGroup": "company_skills",
+ "requiredClaims": [],
+ "taskModes": [
+ "standard",
+ "skill_test"
+ ],
+ "sideEffectClass": "company_write",
+ "idempotency": "required",
+ "redaction": [],
+ "mockCommandMapping": {
+ "kind": "semantic_command",
+ "commandKind": "create_skill"
+ }
+ }
+ }
+} as const;
diff --git a/packages/paperclip-runner/src/protocol-actions/index.ts b/packages/paperclip-runner/src/protocol-actions/index.ts
index 5b2bb29eee..c71dc4a1fd 100644
--- a/packages/paperclip-runner/src/protocol-actions/index.ts
+++ b/packages/paperclip-runner/src/protocol-actions/index.ts
@@ -1,3 +1,4 @@
+import { createSkillAction } from "./create-skill.js";
import { createProjectAction } from "./create-project.js";
import { listProjectRepositoriesAction } from "./list-project-repositories.js";
import { searchApiAction } from "./search-api.js";
@@ -46,6 +47,7 @@ import { writeDocumentAction } from "./write-document.js";
import { deepFreezeProtocolAction } from "./freeze.js";
export const PAPERCLIP_PROTOCOL_ACTIONS = deepFreezeProtocolAction([
+ createSkillAction,
createProjectAction,
listProjectRepositoriesAction,
searchApiAction,
diff --git a/packages/paperclip-runner/src/semantic-tools/discovery.ts b/packages/paperclip-runner/src/semantic-tools/discovery.ts
index 52ac9a809b..28bbcad11b 100644
--- a/packages/paperclip-runner/src/semantic-tools/discovery.ts
+++ b/packages/paperclip-runner/src/semantic-tools/discovery.ts
@@ -27,7 +27,7 @@ const NAMESPACE: Readonly<Record<CapabilitySemanticOperationId, string>> = Objec
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", create_task: "delegation", create_project: "projects", list_project_repositories: "projects", list_projects: "projects",
+ list_agents: "discovery", get_agent: "discovery", create_skill: "skills", create_task: "delegation", create_project: "projects", list_project_repositories: "projects", list_projects: "projects",
set_dependencies: "delegation", list_approvals: "governance", get_approval: "governance",
get_approval_context: "governance", request_approval: "governance",
decide_approval: "governance", comment_on_approval: "governance",
diff --git a/packages/paperclip-runner/src/semantic-tools/dispatcher.ts b/packages/paperclip-runner/src/semantic-tools/dispatcher.ts
index 0fbf36cfbf..94068d7230 100644
--- a/packages/paperclip-runner/src/semantic-tools/dispatcher.ts
+++ b/packages/paperclip-runner/src/semantic-tools/dispatcher.ts
@@ -326,6 +326,11 @@ export class CapabilitySemanticDispatcher {
case "answer_status_question":
command = { kind: "report_progress", taskId, body: requiredString(input.body) };
break;
+ case "create_skill":
+ command = { kind: "create_skill", taskId, name: requiredString(input.name),
+ slug: typeof input.slug === "string" ? input.slug : undefined,
+ description: requiredString(input.description), markdown: requiredString(input.markdown) };
+ break;
case "write_document":
command = {
kind: "write_document",
@@ -403,6 +408,14 @@ export class CapabilitySemanticDispatcher {
throw new SemanticDispatchFailure("operation_unavailable", "No mock operation is bound to this descriptor.");
}
const outcome = await this.port.tryApplyCommand({ runId, idempotencyKey, command });
+ if (operationId === "create_skill" && outcome.ok) {
+ const id = outcome.result.entityRefs.find(ref => ref.startsWith("skill:"))?.slice(6);
+ const skill = this.port.snapshot().skills?.find(candidate => candidate.id === id);
+ if (skill) return readSuccess(outcome.result.stateRevision, {
+ id: skill.id, name: skill.name, slug: skill.slug, description: skill.description,
+ versionId: skill.versionId, studioPath: `/skills/studio/${skill.id}`,
+ });
+ }
return commandOutcome(outcome);
}
diff --git a/packages/paperclip-runner/src/semantic-tools/paperclip-discovery.ts b/packages/paperclip-runner/src/semantic-tools/paperclip-discovery.ts
index 8ec7255b0d..6f255660c6 100644
--- a/packages/paperclip-runner/src/semantic-tools/paperclip-discovery.ts
+++ b/packages/paperclip-runner/src/semantic-tools/paperclip-discovery.ts
@@ -36,7 +36,7 @@ const NAMESPACE: Readonly<Record<PaperclipSemanticActionId, string>> =
get_workspace_runtime: "workspace",
control_workspace_service: "workspace",
set_dependencies: "delegation",
- create_task: "delegation", create_project: "projects", list_project_repositories: "projects", list_projects: "projects",
+ create_skill: "skills", create_task: "delegation", create_project: "projects", list_project_repositories: "projects", list_projects: "projects",
request_approval: "governance",
decide_approval: "governance",
comment_on_approval: "governance",
diff --git a/packages/paperclip-runner/src/semantic-tools/semantic-tools.test.ts b/packages/paperclip-runner/src/semantic-tools/semantic-tools.test.ts
index bc024a1f75..e02fcdccff 100644
--- a/packages/paperclip-runner/src/semantic-tools/semantic-tools.test.ts
+++ b/packages/paperclip-runner/src/semantic-tools/semantic-tools.test.ts
@@ -43,6 +43,47 @@ async function running(
}
describe("Capability semantic catalog and authorization", () => {
+ it("creates a durable skill once and returns its reference on retry", async () => {
+ const adapter = await running();
+ const dispatcher = new CapabilitySemanticDispatcher(adapter);
+ const input = { name: "release-review", description: "Review release notes.",
+ markdown: "---\nname: release-review\ndescription: Review release notes.\n---\n# Review\nCheck each note.", idempotencyKey: "create-skill-once" };
+ const call = { runId: OPEN.identity.runId, callId: "skill-1", operationId: "create_skill" as const, input };
+ const first = await dispatcher.dispatch(call);
+ expect(first).toMatchObject({ ok: true, result: { name: input.name, slug: input.name, versionId: expect.any(String) } });
+ expect(await dispatcher.dispatch({ ...call, callId: "skill-retry" })).toMatchObject({ ok: true, result: first.ok ? first.result : {} });
+ expect(adapter.snapshot().skills).toEqual([expect.objectContaining({ markdown: input.markdown })]);
+ expect(await dispatcher.dispatch({ ...call, callId: "skill-conflict", input: { ...input, markdown: input.markdown + " changed" } })).toMatchObject({ ok: false });
+ expect(adapter.snapshot().skills).toHaveLength(1);
+ });
+
+ it.each([
+ ["missing frontmatter", "# Review\nCheck each note."],
+ ["mismatched frontmatter name", "---\nname: other-skill\ndescription: Review release notes.\n---\n# Review\nCheck each note."],
+ ["mismatched frontmatter description", "---\nname: release-review\ndescription: Other description.\n---\n# Review\nCheck each note."],
+ ["empty body", "---\nname: release-review\ndescription: Review release notes.\n---\n "],
+ ["invalid YAML", "---\nname: [\ndescription: Review release notes.\n---\n# Review\nCheck each note."],
+ ["slug conflict", "---\nname: release-review\ndescription: Review release notes.\n---\n# Review\nCheck each note."],
+ ])("rejects %s without mutating the skill library", async (label, markdown) => {
+ const adapter = await running();
+ const dispatcher = new CapabilitySemanticDispatcher(adapter);
+ const input = {
+ name: label === "mismatched frontmatter name" ? "release-review" : "release-review",
+ slug: label === "slug conflict" ? "other-slug" : undefined,
+ description: "Review release notes.", markdown, idempotencyKey: `invalid-${label}`,
+ };
+ const result = await dispatcher.dispatch({ runId: OPEN.identity.runId, callId: `invalid-${label}`, operationId: "create_skill", input });
+ expect(result).toMatchObject({ ok: false });
+ expect(adapter.snapshot().skills ?? []).toHaveLength(0);
+ });
+
+ it("denies skill creation when the scenario policy forbids it", async () => {
+ const adapter = await running();
+ const dispatcher = new CapabilitySemanticDispatcher(adapter, { scenario: { id: "restricted-skills", claims: [], denyOperations: ["create_skill"] } });
+ expect(await dispatcher.dispatch({ runId: OPEN.identity.runId, callId: "denied-skill", operationId: "create_skill", input: { name: "no-create", description: "Denied", markdown: "Denied", idempotencyKey: "deny" } })).toMatchObject({ ok: false, denial: { code: "scenario_denied" } });
+ expect(adapter.snapshot().skills ?? []).toHaveLength(0);
+ });
+
it("accepts the conventional ten-result capability discovery limit", () => {
expect(
CAPABILITY_DISCOVERY_GATEWAY_DEFINITIONS[0].inputSchema.properties.limit
@@ -53,7 +94,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(33);
+ expect(names).toHaveLength(34);
expect(names).toContain("get_task_context");
expect(names).toContain("finish_task");
expect(names).not.toContain("checkout_task");
@@ -107,7 +148,7 @@ describe("Capability semantic catalog and authorization", () => {
it("does not disclose optional tools that current authority cannot invoke", async () => {
const adapter = await running();
const dispatcher = new CapabilitySemanticDispatcher(adapter);
- const found = dispatcher.discoverTools(OPEN.identity.runId, "create child task approval secret admin");
+ const found = dispatcher.discoverTools(OPEN.identity.runId, "create child task approval secret admin", { namespace: "delegation" });
expect(found.operations).toEqual([]);
expect(JSON.stringify(found.operations)).not.toMatch(/create_task|approval|secret|administer_company/);
const before = adapter.snapshot().revision;
diff --git a/packages/paperclip-runner/src/semantic-tools/types.ts b/packages/paperclip-runner/src/semantic-tools/types.ts
index 535a985489..68ac9449a8 100644
--- a/packages/paperclip-runner/src/semantic-tools/types.ts
+++ b/packages/paperclip-runner/src/semantic-tools/types.ts
@@ -40,6 +40,7 @@ export type CapabilitySemanticOperationId =
| "get_workspace_runtime"
| "control_workspace_service"
| "set_dependencies"
+ | "create_skill"
| "create_project"
| "list_project_repositories"
| "list_projects"
diff --git a/packages/paperclip-runner/src/tools/capability-semantic-tool-runtime.ts b/packages/paperclip-runner/src/tools/capability-semantic-tool-runtime.ts
index e282fffb99..fb1eab16bb 100644
--- a/packages/paperclip-runner/src/tools/capability-semantic-tool-runtime.ts
+++ b/packages/paperclip-runner/src/tools/capability-semantic-tool-runtime.ts
@@ -1,5 +1,3 @@
-import { randomUUID } from "node:crypto";
-
import type {
CapabilityCommandEnvelope,
CapabilityJsonValue,
@@ -821,7 +819,7 @@ export class CapabilitySemanticToolRuntime {
descriptor: CapabilitySemanticToolDescriptor,
invocation: CapabilityToolInvocation,
): boolean {
- const ownerId = randomUUID();
+ const ownerId = globalThis.crypto.randomUUID();
let leaseExpiresAtMs = 0;
let acquired = false;
for (let attempt = 0; attempt < RUNTIME_PERSIST_CAS_ATTEMPTS; attempt += 1) {
@@ -1541,6 +1539,10 @@ function commandForOperation(
};
case "request_review":
return { kind: "request_review", summary: requireString(input.summary) };
+ case "create_skill":
+ return { kind: "create_skill", name: requireString(input.name),
+ slug: typeof input.slug === "string" ? input.slug : undefined,
+ description: requireString(input.description), markdown: requireString(input.markdown) };
case "write_document":
return {
kind: "write_document",
diff --git a/packages/shared/scripts/generate-runner-skill-frontmatter.ts b/packages/shared/scripts/generate-runner-skill-frontmatter.ts
new file mode 100644
index 0000000000..905ce2c674
--- /dev/null
+++ b/packages/shared/scripts/generate-runner-skill-frontmatter.ts
@@ -0,0 +1,39 @@
+import { readFile, writeFile } from "node:fs/promises";
+import { z } from "zod";
+import { createRequire } from "node:module";
+
+const runnerRequire = createRequire(new URL("../../paperclip-runner/package.json", import.meta.url));
+const { Ajv } = runnerRequire("ajv");
+const standaloneCode = runnerRequire("ajv/dist/standalone").default;
+import { skillFrontmatterSchema } from "../src/frontmatter.ts";
+
+// Keep the standalone mock on the production parser and schema without adding
+// a runtime dependency on a Paperclip workspace package.
+const source = await readFile(new URL("../src/frontmatter.ts", import.meta.url), "utf8");
+function section(start: string, end?: string) {
+ const from = source.indexOf(start);
+ const to = end ? source.indexOf(end, from + start.length) : source.length;
+ if (from < 0 || to < 0) throw new Error(`Frontmatter source section missing: ${start}`);
+ return source.slice(from, to).trim();
+}
+const ajv = new Ajv({ strict: false, code: { esm: true, source: true, lines: true } });
+ajv.addSchema(z.toJSONSchema(skillFrontmatterSchema, { target: "draft-7" }), "skill-frontmatter");
+const validator = standaloneCode(ajv, { validateSkillFrontmatter: "skill-frontmatter" })
+ .replaceAll('require("ajv/dist/runtime/ucs2length").default', '((value: string) => [...value].length)');
+if (/\brequire\(/.test(validator)) throw new Error("Unexpected runtime dependency in the standalone skill validator");
+const generated = [
+ "// @ts-nocheck -- generated parser and standalone schema validator.",
+ "// Generated from packages/shared/src/frontmatter.ts. Do not edit by hand.",
+ "// Regenerate: node packages/shared/scripts/generate-runner-skill-frontmatter.ts",
+ section("export interface MarkdownDoc", "export interface FrontmatterBlock"),
+ section("export function isPlainRecord", "export function asString"),
+ section("export function parseFrontmatterMarkdown", "function assertSerializableRecord"),
+ section("function parseYamlFrontmatter"),
+ validator,
+].join("\n\n") + "\n";
+const target = new URL("../../paperclip-runner/src/mock-core/skill-frontmatter.generated.ts", import.meta.url);
+if (process.argv.includes("--check")) {
+ if (await readFile(target, "utf8") !== generated) throw new Error("Runner skill frontmatter contract is stale. Regenerate it.");
+} else {
+ await writeFile(target, generated);
+}
diff --git a/packages/shared/src/frontmatter-runner-contract.test.ts b/packages/shared/src/frontmatter-runner-contract.test.ts
new file mode 100644
index 0000000000..cd121330e1
--- /dev/null
+++ b/packages/shared/src/frontmatter-runner-contract.test.ts
@@ -0,0 +1,10 @@
+import { execFileSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { expect, it } from "vitest";
+
+it("keeps the standalone Runner parser and schema synchronized with production", () => {
+ expect(() => execFileSync(process.execPath, [
+ fileURLToPath(new URL("../scripts/generate-runner-skill-frontmatter.ts", import.meta.url)),
+ "--check",
+ ])).not.toThrow();
+});
diff --git a/packages/shared/src/types/company-skill.ts b/packages/shared/src/types/company-skill.ts
index ad8bb1fb63..1941cd4766 100644
--- a/packages/shared/src/types/company-skill.ts
+++ b/packages/shared/src/types/company-skill.ts
@@ -419,6 +419,7 @@ export interface CompanySkillProjectScanResult {
}
export interface CompanySkillCreateRequest {
+ idempotencyKey?: string;
folderId?: string | null;
name: string;
slug?: string | null;
diff --git a/packages/shared/src/validators/company-skill.ts b/packages/shared/src/validators/company-skill.ts
index 3d01903c1d..f644a01953 100644
--- a/packages/shared/src/validators/company-skill.ts
+++ b/packages/shared/src/validators/company-skill.ts
@@ -360,6 +360,7 @@ export const companySkillProjectScanResultSchema = z.object({
});
export const companySkillCreateSchema = z.object({
+ idempotencyKey: z.string().min(1).max(240).optional(),
folderId: z.string().guid().nullable().optional(),
name: z.string().min(1),
slug: z.string().min(1).nullable().optional(),
diff --git a/server/src/__tests__/company-skills-service.test.ts b/server/src/__tests__/company-skills-service.test.ts
index 00c4434022..c157a73d6a 100644
--- a/server/src/__tests__/company-skills-service.test.ts
+++ b/server/src/__tests__/company-skills-service.test.ts
@@ -207,6 +207,211 @@ describeEmbeddedPostgres("companySkillService.list", () => {
expect(await fs.readFile(path.join(next.source, "SKILL.md"), "utf8")).toContain("New local instructions");
});
+ it("serializes same-slug creates and preserves the winner's files", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Concurrent creates", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const first = companySkillService(db);
+ const second = companySkillService(db);
+ const results = await Promise.allSettled([
+ first.createLocalSkill(companyId, { name: "First", slug: "same-slug", markdown: "# first\n" }),
+ second.createLocalSkill(companyId, { name: "Second", slug: "same-slug", markdown: "# second\n" }),
+ ]);
+ expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1);
+ expect(results.filter((result) => result.status === "rejected")).toHaveLength(1);
+ const skill = await svc.getByKey(companyId, `company/${companyId}/same-slug`);
+ expect(skill).toBeTruthy();
+ expect(await fs.readFile(path.join(skill!.sourceLocator!, "SKILL.md"), "utf8"))
+ .toMatch(/^# (first|second)\n$/);
+ expect(await db.select().from(companySkillVersions).where(eq(companySkillVersions.companySkillId, skill!.id)))
+ .toHaveLength(1);
+ });
+
+ it("recovers an identical create after the outer transaction rolls back", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Rollback retry", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const input = { name: "Retryable", slug: "retryable", markdown: "# durable bytes\n" };
+ await expect(db.transaction(async (tx) => {
+ await companySkillService(tx as any).createLocalSkill(companyId, input);
+ throw new Error("simulate outer rollback");
+ })).rejects.toThrow("simulate outer rollback");
+
+ const retried = await svc.createLocalSkill(companyId, input);
+ expect(await fs.readFile(path.join(retried.sourceLocator!, "SKILL.md"), "utf8")).toBe(input.markdown);
+ expect(await db.select().from(companySkills).where(eq(companySkills.companyId, companyId))).toHaveLength(1);
+ expect(await db.select().from(companySkillVersions).where(eq(companySkillVersions.companySkillId, retried.id))).toHaveLength(1);
+ });
+
+ it("reuses a deleted managed skill name with different instructions", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Recreate skills", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const original = await svc.createLocalSkill(companyId, { name: "Recreate", slug: "recreate", markdown: "# Old instructions\n" });
+ await svc.deleteSkill(companyId, original.id);
+ const replacement = await svc.createLocalSkill(companyId, { name: "Recreate", slug: "recreate", markdown: "# New instructions\n" });
+ expect(replacement.id).not.toBe(original.id);
+ expect(await fs.readFile(path.join(replacement.sourceLocator!, "SKILL.md"), "utf8")).toBe("# New instructions\n");
+ expect(await svc.deleteSkill(companyId, original.id)).toBeNull();
+ expect(await fs.readFile(path.join(replacement.sourceLocator!, "SKILL.md"), "utf8")).toBe("# New instructions\n");
+ });
+
+ it.each(["save", "delete", "rename"] as const)("rejects a stale file %s after the skill is replaced", async (operation) => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Stale editor", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const original = await svc.createLocalSkill(companyId, { name: "Editor", slug: "stale-editor", markdown: "# Old\n" });
+ await svc.updateFile(companyId, original.id, "notes.md", "Original notes");
+ let replacement: typeof original | undefined;
+ let intercepted = false;
+ // Pause the editor after it reads the old identity, then complete a delete
+ // and recreate before allowing that stale request to continue.
+ const staleDb = new Proxy(db, {
+ get(target, property, receiver) {
+ if (property === "select") return (columns: any) => {
+ const selection = target.select(columns);
+ if (!columns?.markdown) return selection;
+ const from = selection.from.bind(selection);
+ selection.from = ((...args: any[]) => {
+ const query = (from as any)(...args);
+ const where = query.where.bind(query);
+ query.where = (...conditions: any[]) => {
+ const filtered = where(...conditions);
+ const then = filtered.then.bind(filtered);
+ filtered.then = (resolve: any, reject: any) => then(async (rows: any[]) => {
+ if (!intercepted && rows.some((row) => row.id === original.id)) {
+ intercepted = true;
+ await svc.deleteSkill(companyId, original.id);
+ replacement = await svc.createLocalSkill(companyId, { name: "Replacement", slug: original.slug, markdown: "# Replacement\n" });
+ await svc.updateFile(companyId, replacement.id, "notes.md", "Replacement notes");
+ }
+ return rows;
+ }).then(resolve, reject);
+ return filtered;
+ };
+ return query;
+ }) as typeof selection.from;
+ return selection;
+ };
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ const editor = companySkillService(staleDb);
+ const movedReplacementPaths: unknown[] = [];
+ const rename = fs.rename.bind(fs);
+ const renameSpy = vi.spyOn(fs, "rename").mockImplementation(async (source, target) => {
+ if (replacement && source === replacement.sourceLocator) movedReplacementPaths.push(source);
+ return rename(source, target);
+ });
+ try {
+ const pending = operation === "save"
+ ? editor.updateFile(companyId, original.id, "notes.md", "Stale overwrite")
+ : operation === "rename"
+ ? editor.renameSkill(companyId, original.id, { name: "Renamed", slug: "renamed-editor" })
+ : editor.deleteFile(companyId, original.id, { path: "notes.md", target: "file" });
+ await expect(pending).rejects.toMatchObject({ status: 404 });
+ } finally { renameSpy.mockRestore(); }
+ expect(movedReplacementPaths).toEqual([]);
+ expect(intercepted).toBe(true);
+ expect(replacement).toBeDefined();
+ expect(await fs.readFile(path.join(replacement!.sourceLocator!, "notes.md"), "utf8")).toBe("Replacement notes");
+ expect(await svc.getById(companyId, replacement!.id)).not.toBeNull();
+ });
+
+ it("restores managed source files when the deletion transaction fails", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Delete rollback", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const original = await svc.createLocalSkill(companyId, { name: "Retained", slug: "retained", markdown: "# Keep these instructions\n" });
+ const failingDb = new Proxy(db, {
+ get(target, property, receiver) {
+ if (property === "transaction") return (callback: (tx: any) => Promise<unknown>) => target.transaction(async (tx) => callback(new Proxy(tx, {
+ get(transaction, key, transactionReceiver) {
+ if (key === "delete") return () => { throw new Error("Deletion write failed"); };
+ return Reflect.get(transaction, key, transactionReceiver);
+ },
+ })));
+ return Reflect.get(target, property, receiver);
+ },
+ });
+ await expect(companySkillService(failingDb).deleteSkill(companyId, original.id)).rejects.toThrow("Deletion write failed");
+ expect(await svc.getById(companyId, original.id)).not.toBeNull();
+ expect(await fs.readFile(path.join(original.sourceLocator!, "SKILL.md"), "utf8")).toBe("# Keep these instructions\n");
+ });
+
+ it("serializes duplicate deletes with recreation without removing new files", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Delete concurrency", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const original = await svc.createLocalSkill(companyId, { name: "Concurrent", slug: "concurrent-delete", markdown: "# Old\n" });
+ let release!: () => void;
+ let staged!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const ready = new Promise<void>((resolve) => { staged = resolve; });
+ const rename = fs.rename.bind(fs);
+ const pause = vi.spyOn(fs, "rename").mockImplementation(async (source, target) => {
+ await rename(source, target);
+ if (source === original.sourceLocator) {
+ staged();
+ await gate;
+ }
+ });
+ try {
+ const deletion = svc.deleteSkill(companyId, original.id);
+ await ready;
+ const duplicate = svc.deleteSkill(companyId, original.id);
+ const creation = svc.createLocalSkill(companyId, { name: "Replacement", slug: original.slug, markdown: "# Replacement\n" });
+ release();
+ const [, repeatedDelete, replacement] = await Promise.all([deletion, duplicate, creation]);
+ expect(repeatedDelete).toBeNull();
+ expect(await fs.readFile(path.join(replacement.sourceLocator!, "SKILL.md"), "utf8")).toBe("# Replacement\n");
+ } finally {
+ release();
+ pause.mockRestore();
+ }
+ });
+
+ it("does not remove imported local source files when deleting a skill", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Imported source", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const source = await createManagedSkillDir(companyId, "paperclip-imported-skill-");
+ const markdown = "---\nname: external\ndescription: User-owned instructions.\n---\n# Keep this file\n";
+ await fs.writeFile(path.join(source, "SKILL.md"), markdown);
+ const imported = await svc.importFromSource(companyId, source);
+ await svc.deleteSkill(companyId, imported.imported[0]!.id);
+ expect(await fs.readFile(path.join(source, "SKILL.md"), "utf8")).toBe(markdown);
+ });
+
+ it("rejects a differing retry after rollback without changing durable bytes", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Rollback conflict", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const original = { name: "Original", slug: "rollback-conflict", markdown: "# original bytes\n" };
+ await expect(db.transaction(async (tx) => {
+ await companySkillService(tx as any).createLocalSkill(companyId, original);
+ throw new Error("simulate outer rollback");
+ })).rejects.toThrow("simulate outer rollback");
+
+ await expect(svc.createLocalSkill(companyId, {
+ name: "Different",
+ slug: original.slug,
+ markdown: "# changed bytes\n",
+ })).rejects.toMatchObject({ status: 409 });
+ const managedRoot = path.join(paperclipHome!, "instances", "default", "skills", companyId);
+ expect(await fs.readFile(path.join(managedRoot, original.slug, "SKILL.md"), "utf8")).toBe(original.markdown);
+ expect(await db.select().from(companySkills).where(eq(companySkills.companyId, companyId))).toHaveLength(0);
+ });
+
+ it("does not adopt an unrelated preexisting managed directory", async () => {
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Existing directory", issuePrefix: `T${companyId.slice(0, 6)}` });
+ const managedRoot = path.join(paperclipHome!, "instances", "default", "skills", companyId);
+ const skillDir = path.join(managedRoot, "occupied");
+ await fs.mkdir(skillDir, { recursive: true });
+ await fs.writeFile(path.join(skillDir, "SKILL.md"), "# unrelated\n", "utf8");
+
+ await expect(svc.createLocalSkill(companyId, {
+ name: "Requested",
+ slug: "occupied",
+ markdown: "# requested\n",
+ })).rejects.toMatchObject({ status: 409 });
+ expect(await fs.readFile(path.join(skillDir, "SKILL.md"), "utf8")).toBe("# unrelated\n");
+ expect(await db.select().from(companySkills).where(eq(companySkills.companyId, companyId))).toHaveLength(0);
+ });
+
it("observes supporting-only local file saves across runtime preparations and service restarts", async () => {
const companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Local supporting files", issuePrefix: `T${companyId.slice(0, 6)}` });
diff --git a/server/src/__tests__/native-session-resumption.test.ts b/server/src/__tests__/native-session-resumption.test.ts
index 14f340e3d3..fcf42d37ef 100644
--- a/server/src/__tests__/native-session-resumption.test.ts
+++ b/server/src/__tests__/native-session-resumption.test.ts
@@ -563,13 +563,12 @@ describe("P6-25 pre-result native session recovery", () => {
const captureCallsBefore = mockCaptureRunFailure.mock.calls.length;
await claimNativeSessionResumptions({ db, runnerInstanceId: "reaper", runIds: [freshRunId] });
- // The Sentry report fires without an await inside the reconciler, so a
- // follow-up round trip to the real database gives that fire-and-forget
- // call room to complete before this test reads the spy.
- await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, freshRunId));
-
+ // Reporting is deliberately fire-and-forget. An unrelated database query
+ // cannot synchronize it; wait for the actual event before checking payload.
+ await vi.waitFor(() => {
+ expect(mockCaptureRunFailure.mock.calls.slice(captureCallsBefore)).toHaveLength(1);
+ }, { timeout: 5_000 });
const newCaptures = mockCaptureRunFailure.mock.calls.slice(captureCallsBefore);
- expect(newCaptures).toHaveLength(1);
expect(newCaptures[0]?.[0]).toMatchObject({ runId: freshRunId, runStatus: "failed" });
});
diff --git a/server/src/routes/company-skills.ts b/server/src/routes/company-skills.ts
index 1aaba318e3..fca8821b74 100644
--- a/server/src/routes/company-skills.ts
+++ b/server/src/routes/company-skills.ts
@@ -1,3 +1,8 @@
+import { createHash } from "node:crypto";
+import { and, eq, sql } from "drizzle-orm";
+import { activityLog } from "@paperclipai/db";
+import { persistActivity, publishActivity } from "../services/activity-log.js";
+import { projectToolContext } from "../services/project-tool-context.js";
import { Router, type Request } from "express";
import type { Db } from "@paperclipai/db";
import {
@@ -40,7 +45,7 @@ import {
listCatalogSkillsOrEmpty,
readCatalogSkillFile,
} from "../services/skills-catalog.js";
-import { badRequest, forbidden, unauthorized } from "../errors.js";
+import { badRequest, conflict, forbidden, unauthorized } from "../errors.js";
import { assertAuthenticated, assertCompanyAccess, getActorInfo } from "./authz.js";
import { getTelemetryClient } from "../telemetry.js";
import {
@@ -1013,26 +1018,49 @@ export function companySkillRoutes(db: Db) {
await assertCanMutateCompanySkills(req, companyId, "skills.create", {
sourceType: "generated",
});
- const result = await svc.createLocalSkill(companyId, req.body, skillActor(req));
-
+ const { idempotencyKey, ...input } = req.body;
const actor = getActorInfo(req);
- await logActivity(db, {
- companyId,
- actorType: actor.actorType,
- actorId: actor.actorId,
- agentId: actor.agentId,
- runId: actor.runId,
- agentApiKeyId: actor.agentApiKeyId,
- action: "company.skill_created",
- entityType: "company_skill",
- entityId: result.id,
- details: {
- slug: result.slug,
- name: result.name,
- },
+ const runContext = req.actor.type === "agent" && req.actor.source === "agent_jwt" && req.actor.runId
+ ? await projectToolContext(db, req.actor, true, "Skill") : null;
+ const event = (skill: Awaited<ReturnType<typeof svc.createLocalSkill>>) => ({
+ companyId, actorType: actor.actorType, actorId: actor.actorId, agentId: actor.agentId,
+ runId: actor.runId, agentApiKeyId: actor.agentApiKeyId, issueId: runContext?.issue.id,
+ action: "company.skill_created", entityType: "company_skill", entityId: skill.id,
+ details: { slug: skill.slug, name: skill.name, description: skill.description,
+ sourceIssueId: runContext?.issue.id ?? null, versionId: skill.currentVersionId },
});
-
- res.status(201).json(result);
+ if (!idempotencyKey) {
+ const skill = await svc.createLocalSkill(companyId, input, skillActor(req));
+ await logActivity(db, event(skill));
+ res.status(201).json(skill);
+ return;
+ }
+ // Scope to task and actor, not run: a replacement runner must recover the
+ // same result after a lost acknowledgement. The route still reauthorizes.
+ const receiptKey = `skill:${companyId}:${actor.actorId}:${runContext?.issue.id ?? "board"}:${idempotencyKey}`;
+ const fingerprint = createHash("sha256").update(JSON.stringify(input)).digest("hex");
+ const result = await db.transaction(async tx => {
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${receiptKey}, 0))`);
+ if (runContext) await projectToolContext(tx as unknown as Db, req.actor, true, "Skill");
+ const [prior] = await tx.select().from(activityLog).where(and(
+ eq(activityLog.companyId, companyId), eq(activityLog.action, "company.skill_created"),
+ sql`${activityLog.details}->>'idempotencyKey' = ${receiptKey}`,
+ ));
+ const service = companySkillService(tx as unknown as Db);
+ if (prior) {
+ if (prior.details?.fingerprint !== fingerprint) throw conflict("Skill idempotency key was used with different inputs");
+ const skill = await service.getById(companyId, prior.entityId);
+ if (!skill) throw conflict("Previously created skill is no longer available");
+ return { skill, publication: null, duplicate: true };
+ }
+ const skill = await service.createLocalSkill(companyId, input, skillActor(req));
+ const activity = await persistActivity(tx as unknown as Db, {
+ ...event(skill), details: { ...event(skill).details, idempotencyKey: receiptKey, fingerprint },
+ });
+ return { skill, publication: activity.publication, duplicate: false };
+ });
+ if (result.publication) publishActivity(result.publication);
+ res.status(result.duplicate ? 200 : 201).json(result.skill);
},
);
diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts
index e2f289ebaf..fef52abaea 100644
--- a/server/src/services/activity.ts
+++ b/server/src/services/activity.ts
@@ -373,7 +373,7 @@ export function activityService(db: Db) {
.where(
or(
and(eq(activityLog.entityType, "issue"), eq(activityLog.entityId, issueId)),
- and(eq(activityLog.action, "project.created"), sql`${activityLog.details}->>'sourceIssueId' = ${issueId}`,
+ and(or(eq(activityLog.action, "project.created"), eq(activityLog.action, "company.skill_created")), sql`${activityLog.details}->>'sourceIssueId' = ${issueId}`,
sql`${activityLog.companyId} = (select company_id from issues where id = ${issueId})`),
),
)
diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts
index 25ecb3bc1f..cc55e1b375 100644
--- a/server/src/services/company-skills.ts
+++ b/server/src/services/company-skills.ts
@@ -393,8 +393,12 @@ type CreateVersionOptions = {
updateCurrentVersion?: boolean;
skipInventoryRefresh?: boolean;
skill?: CompanySkill;
+ database?: DbOrTransaction;
};
+type DbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
+type DbOrTransaction = Db | DbTransaction;
+
type PlannedSkillReassignment = {
agentId: string;
reassignment: CompanySkillForkReassignment;
@@ -3330,8 +3334,8 @@ export function companySkillService(db: Db) {
return rows as CompanySkillReferenceRow[];
}
- async function getById(companyId: string, id: string) {
- const row = await db
+ async function getById(companyId: string, id: string, database: DbOrTransaction = db) {
+ const row = await database
.select(selectCompanySkillColumns())
.from(companySkills)
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.id, id)))
@@ -3339,8 +3343,8 @@ export function companySkillService(db: Db) {
return row ? enrichFolderPath(companyId, toCompanySkill(row)) : null;
}
- async function getByKey(companyId: string, key: string) {
- const row = await db
+ async function getByKey(companyId: string, key: string, database: DbOrTransaction = db) {
+ const row = await database
.select(selectCompanySkillColumns())
.from(companySkills)
.where(and(eq(companySkills.companyId, companyId), eq(companySkills.key, key)))
@@ -3570,12 +3574,12 @@ export function companySkillService(db: Db) {
options: CreateVersionOptions = {},
): Promise<CompanySkillVersion> {
if (!options.skipInventoryRefresh) await ensureSkillInventoryCurrent(companyId);
- const skill = options.skill ?? await getById(companyId, skillId);
+ const skill = options.skill ?? await getById(companyId, skillId, options.database);
if (!skill) throw notFound("Skill not found");
const fileInventory = serializeVersionFileInventory(
options.fileInventory ?? await collectVersionFileInventory(companyId, skill),
);
- const versionRow = await db.transaction(async (tx) => {
+ const persist = async (tx: DbOrTransaction) => {
await tx.execute(sql`
select ${companySkills.id}
from ${companySkills}
@@ -3613,7 +3617,8 @@ export function companySkillService(db: Db) {
.where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId)));
}
return row;
- });
+ };
+ const versionRow = options.database ? await persist(options.database) : await db.transaction(persist);
if (!versionRow) throw notFound("Failed to persist skill version");
return toCompanySkillVersion(versionRow);
}
@@ -4019,153 +4024,161 @@ export function companySkillService(db: Db) {
input: CompanySkillRenameRequest,
): Promise<CompanySkillRenameResult> {
await ensureSkillInventoryCurrent(companyId);
- const skill = await getById(companyId, skillId);
- if (!skill) throw notFound("Skill not found");
+ if (!await getById(companyId, skillId)) throw notFound("Skill not found");
+ const managedRoot = resolveManagedSkillsRoot(companyId);
+ let result: CompanySkillRenameResult | undefined;
+ let restoreSource: (() => Promise<void>) | undefined;
+ // Cache lifecycle locks always precede name locks, as in deletion.
+ await removeRuntimeSkillCache(managedRoot, skillId, async () => {
+ try {
+ result = await withSkillFileMutation(companyId, skillId, async (skill, tx) => {
+ if (!isPaperclipManagedRenameTarget(skill)) {
+ throw unprocessable(
+ "Only Paperclip-managed skills can be renamed. Catalog, external, project-scanned, and unmanaged local skills are read-only.",
+ { skillId: skill.id, sourceType: skill.sourceType, sourceKind: getSkillMeta(skill).sourceKind ?? null },
+ );
+ }
- if (!isPaperclipManagedRenameTarget(skill)) {
- throw unprocessable(
- "Only Paperclip-managed skills can be renamed. Catalog, external, project-scanned, and unmanaged local skills are read-only.",
- { skillId: skill.id, sourceType: skill.sourceType, sourceKind: getSkillMeta(skill).sourceKind ?? null },
- );
- }
+ const newName = input.name.trim();
+ if (!newName) throw unprocessable("Skill name is required.");
+ const newSlug = normalizeSkillSlug(input.slug ?? null) ?? normalizeSkillSlug(newName);
+ if (!newSlug) {
+ throw unprocessable("Skill name must contain at least one letter or number to derive a slug.");
+ }
+ const newKey = `company/${companyId}/${newSlug}`;
- const newName = input.name.trim();
- if (!newName) throw unprocessable("Skill name is required.");
- const newSlug = normalizeSkillSlug(input.slug ?? null) ?? normalizeSkillSlug(newName);
- if (!newSlug) {
- throw unprocessable("Skill name must contain at least one letter or number to derive a slug.");
- }
- const newKey = `company/${companyId}/${newSlug}`;
+ const previousName = skill.name;
+ const previousSlug = skill.slug;
+ const previousKey = skill.key;
- const previousName = skill.name;
- const previousSlug = skill.slug;
- const previousKey = skill.key;
+ // Normalized no-op: nothing changes, so skip all filesystem/DB work.
+ if (newName === previousName && newSlug === previousSlug && newKey === previousKey) {
+ return { skill, previousName, previousSlug, previousKey, reassignments: [] };
+ }
- // Normalized no-op: nothing changes, so skip all filesystem/DB work.
- if (newName === previousName && newSlug === previousSlug && newKey === previousKey) {
- return { skill, previousName, previousSlug, previousKey, reassignments: [] };
- }
+ // Authoritative conflict detection against slug and key within the company.
+ if (newSlug !== previousSlug || newKey !== previousKey) {
+ const existing = await listFull(companyId);
+ for (const other of existing) {
+ if (other.id === skill.id) continue;
+ if ((normalizeSkillSlug(other.slug) ?? other.slug) === newSlug) {
+ throw conflict(`A company skill with slug "${newSlug}" already exists.`, {
+ conflict: "slug",
+ slug: newSlug,
+ });
+ }
+ if (other.key === newKey) {
+ throw conflict(`A company skill with key "${newKey}" already exists.`, {
+ conflict: "key",
+ key: newKey,
+ });
+ }
+ }
+ }
- // Authoritative conflict detection against slug and key within the company.
- if (newSlug !== previousSlug || newKey !== previousKey) {
- const existing = await listFull(companyId);
- for (const other of existing) {
- if (other.id === skill.id) continue;
- if ((normalizeSkillSlug(other.slug) ?? other.slug) === newSlug) {
- throw conflict(`A company skill with slug "${newSlug}" already exists.`, {
- conflict: "slug",
- slug: newSlug,
- });
- }
- if (other.key === newKey) {
- throw conflict(`A company skill with key "${newKey}" already exists.`, {
- conflict: "key",
- key: newKey,
- });
- }
- }
- }
+ const oldDir = normalizeSkillDirectory(skill)!;
+ const newDir = path.resolve(managedRoot, newSlug);
+ const directoryMoved = newDir !== oldDir;
- const managedRoot = resolveManagedSkillsRoot(companyId);
- const oldDir = normalizeSkillDirectory(skill)!;
- const newDir = path.resolve(managedRoot, newSlug);
- const directoryMoved = newDir !== oldDir;
+ if (directoryMoved && (await statPath(newDir))) {
+ throw conflict(`A managed skill directory already exists at ${newDir}.`, { conflict: "directory" });
+ }
- if (directoryMoved && (await statPath(newDir))) {
- throw conflict(`A managed skill directory already exists at ${newDir}.`, { conflict: "directory" });
- }
+ // Plan agent reassignments from the old key to the new key, preserving each
+ // pinned versionId. Resolve against the pre-rename reference targets so the
+ // old key still maps cleanly.
+ const referenceSkills = await listReferenceTargets(companyId);
+ const agentRows = await agents.list(companyId, { includeTerminated: true });
+ const plannedReassignments: CompanySkillForkReassignment[] = agentRows
+ .filter((agent) =>
+ resolveDesiredSkillEntries(referenceSkills, agent.adapterConfig as Record<string, unknown>)
+ .some((entry) => entry.key === previousKey))
+ .map((agent) => ({ agentId: agent.id, previousSkillKey: previousKey, nextSkillKey: newKey }));
+
+ // Reversible filesystem stage: capture the original SKILL.md so a failed DB
+ // transaction can be rolled back to the pre-rename on-disk state.
+ const originalMarkdown = await fs.readFile(path.join(oldDir, "SKILL.md"), "utf8").catch(() => null);
+ const rewrittenMarkdown = rewriteFrontmatterName(originalMarkdown ?? skill.markdown, newName);
+ let movedDir = false;
+ restoreSource = async () => {
+ if (originalMarkdown !== null) {
+ await fs.writeFile(path.join(movedDir ? newDir : oldDir, "SKILL.md"), originalMarkdown, "utf8").catch(() => {});
+ }
+ if (movedDir) await fs.rename(newDir, oldDir).catch(() => {});
+ restoreSource = undefined;
+ };
+ try {
+ if (directoryMoved) {
+ await fs.mkdir(path.dirname(newDir), { recursive: true });
+ await fs.rename(oldDir, newDir);
+ movedDir = true;
+ }
+ if (originalMarkdown !== null) {
+ if (rewrittenMarkdown !== originalMarkdown) {
+ await fs.writeFile(path.join(newDir, "SKILL.md"), rewrittenMarkdown, "utf8");
+ }
+ }
- // Plan agent reassignments from the old key to the new key, preserving each
- // pinned versionId. Resolve against the pre-rename reference targets so the
- // old key still maps cleanly.
- const referenceSkills = await listReferenceTargets(companyId);
- const agentRows = await agents.list(companyId, { includeTerminated: true });
- const plannedReassignments: CompanySkillForkReassignment[] = agentRows
- .filter((agent) =>
- resolveDesiredSkillEntries(referenceSkills, agent.adapterConfig as Record<string, unknown>)
- .some((entry) => entry.key === previousKey))
- .map((agent) => ({ agentId: agent.id, previousSkillKey: previousKey, nextSkillKey: newKey }));
-
- // Reversible filesystem stage: capture the original SKILL.md so a failed DB
- // transaction can be rolled back to the pre-rename on-disk state.
- const originalMarkdown = await fs.readFile(path.join(oldDir, "SKILL.md"), "utf8").catch(() => null);
- const rewrittenMarkdown = rewriteFrontmatterName(originalMarkdown ?? skill.markdown, newName);
- let movedDir = false;
- try {
- if (directoryMoved) {
- await fs.mkdir(path.dirname(newDir), { recursive: true });
- await fs.rename(oldDir, newDir);
- movedDir = true;
- }
- if (originalMarkdown !== null) {
- if (rewrittenMarkdown !== originalMarkdown) {
- await fs.writeFile(path.join(newDir, "SKILL.md"), rewrittenMarkdown, "utf8");
- }
- }
+ const updated = await tx
+ .update(companySkills)
+ .set({
+ name: newName,
+ slug: newSlug,
+ key: newKey,
+ sourceLocator: newDir,
+ markdown: rewrittenMarkdown,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(companySkills.id, skill.id), eq(companySkills.companyId, companyId)))
+ .returning({ id: companySkills.id })
+ .then((rows) => rows[0] ?? null);
+ if (!updated) throw notFound("Skill not found");
+
+ for (const item of plannedReassignments) {
+ const row = await tx
+ .select({ id: agentsTable.id, adapterConfig: agentsTable.adapterConfig })
+ .from(agentsTable)
+ .where(and(eq(agentsTable.companyId, companyId), eq(agentsTable.id, item.agentId)))
+ .for("update")
+ .then((rows) => rows[0] ?? null);
+ if (!row) continue;
+ const adapterConfig = row.adapterConfig as Record<string, unknown>;
+ const nextEntries = resolveDesiredSkillEntries(referenceSkills, adapterConfig).map((entry) =>
+ entry.key === previousKey
+ ? { key: newKey, versionId: entry.versionId ?? null }
+ : entry);
+ await tx
+ .update(agentsTable)
+ .set({
+ adapterConfig: writePaperclipSkillSyncPreference(adapterConfig, nextEntries),
+ updatedAt: new Date(),
+ })
+ .where(and(eq(agentsTable.companyId, companyId), eq(agentsTable.id, item.agentId)));
+ }
+ } catch (error) {
+ // Restore while the name locks are still held.
+ await restoreSource?.();
+ throw error;
+ }
- await db.transaction(async (tx) => {
- const updated = await tx
- .update(companySkills)
- .set({
- name: newName,
- slug: newSlug,
- key: newKey,
- sourceLocator: newDir,
- markdown: rewrittenMarkdown,
- updatedAt: new Date(),
- })
- .where(and(eq(companySkills.id, skill.id), eq(companySkills.companyId, companyId)))
- .returning({ id: companySkills.id })
- .then((rows) => rows[0] ?? null);
- if (!updated) throw notFound("Skill not found");
-
- for (const item of plannedReassignments) {
- const row = await tx
- .select({ id: agentsTable.id, adapterConfig: agentsTable.adapterConfig })
- .from(agentsTable)
- .where(and(eq(agentsTable.companyId, companyId), eq(agentsTable.id, item.agentId)))
- .for("update")
- .then((rows) => rows[0] ?? null);
- if (!row) continue;
- const adapterConfig = row.adapterConfig as Record<string, unknown>;
- const nextEntries = resolveDesiredSkillEntries(referenceSkills, adapterConfig).map((entry) =>
- entry.key === previousKey
- ? { key: newKey, versionId: entry.versionId ?? null }
- : entry);
- await tx
- .update(agentsTable)
- .set({
- adapterConfig: writePaperclipSkillSyncPreference(adapterConfig, nextEntries),
- updatedAt: new Date(),
- })
- .where(and(eq(agentsTable.companyId, companyId), eq(agentsTable.id, item.agentId)));
- }
- });
- } catch (error) {
- // Roll back the filesystem to its pre-rename state.
- if (originalMarkdown !== null) {
- await fs
- .writeFile(path.join(movedDir ? newDir : oldDir, "SKILL.md"), originalMarkdown, "utf8")
- .catch(() => {});
+ const renamed = await getById(companyId, skill.id, tx);
+ if (!renamed) throw notFound("Renamed skill not found");
+ return { skill: renamed, previousName, previousSlug, previousKey, reassignments: plannedReassignments };
+ }, [normalizeSkillSlug(input.slug ?? null) ?? normalizeSkillSlug(input.name) ?? ""]);
+ } catch (error) {
+ await restoreSource?.();
+ throw error;
}
- if (movedDir) {
- await fs.rename(newDir, oldDir).catch(() => {});
+ restoreSource = undefined;
+ // Database commit is complete; do not report cache cleanup as a failed rename.
+ if (result) {
+ await fs.rm(path.resolve(managedRoot, "__runtime__", buildSkillRuntimeName(result.previousKey, result.previousSlug)),
+ { recursive: true, force: true }).catch((error) => {
+ logger.warn({ err: error, companyId, skillId }, "Skill renamed; obsolete runtime cache cleanup failed");
+ });
}
- throw error;
- }
-
- // The rename has committed. Cache cleanup must not make a successful rename appear to fail.
- try {
- await fs.rm(path.resolve(managedRoot, "__runtime__", buildSkillRuntimeName(previousKey, previousSlug)),
- { recursive: true, force: true });
- await removeRuntimeSkillCache(managedRoot, skill.id);
- } catch (error) {
- logger.warn({ err: error, companyId, skillId: skill.id }, "Skill renamed; obsolete runtime cache cleanup failed");
- }
-
- const renamed = await getById(companyId, skill.id);
- if (!renamed) throw notFound("Renamed skill not found");
- return { skill: renamed, previousName, previousSlug, previousKey, reassignments: plannedReassignments };
+ });
+ return result!;
}
async function updateStatus(companyId: string, skillId: string): Promise<CompanySkillUpdateStatus | null> {
@@ -4407,10 +4420,6 @@ export function companySkillService(db: Db) {
if (input.folderId) await folderSvc.validateSkillFolder(companyId, input.folderId);
const slug = normalizeSkillSlug(input.slug ?? input.name) ?? "skill";
const key = `company/${companyId}/${slug}`;
- const existing = await getByKey(companyId, key);
- if (existing) {
- throw conflict(`A company skill with slug "${slug}" already exists.`);
- }
const forkSource = input.forkedFromSkillId
? await getById(companyId, input.forkedFromSkillId)
@@ -4421,20 +4430,6 @@ export function companySkillService(db: Db) {
const sharingScope = normalizeMutableSharingScope(input.sharingScope) ?? "company";
const managedRoot = resolveManagedSkillsRoot(companyId);
const skillDir = path.resolve(managedRoot, slug);
- const skillFilePath = path.resolve(skillDir, "SKILL.md");
-
- await fs.rm(skillDir, { recursive: true, force: true });
- await fs.mkdir(skillDir, { recursive: true });
-
- if (forkSource) {
- for (const entry of forkSource.fileInventory) {
- const detail = await readFile(companyId, forkSource.id, entry.path);
- if (!detail) continue;
- const targetPath = path.resolve(skillDir, detail.path);
- await fs.mkdir(path.dirname(targetPath), { recursive: true });
- await fs.writeFile(targetPath, detail.content, "utf8");
- }
- }
const fallbackMarkdown = [
"---",
@@ -4451,67 +4446,166 @@ export function companySkillService(db: Db) {
? input.markdown
: forkSource?.markdown ?? fallbackMarkdown;
- await fs.writeFile(skillFilePath, markdown, "utf8");
+ return db.transaction(async (tx) => {
+ await tx.execute(sql`
+ select pg_advisory_xact_lock(hashtextextended(${`${companyId}:${slug}`}, 0))
+ `);
+ const existing = await getByKey(companyId, key, tx);
+ if (existing) throw conflict(`A company skill with slug "${slug}" already exists.`);
+
+ // Stage in a unique directory. Publication is a single rename and never
+ // removes an existing directory, so a failed retry cannot clobber bytes.
+ const stagingRoot = path.join(managedRoot, ".staging");
+ await fs.mkdir(stagingRoot, { recursive: true });
+ const stagingDir = await fs.mkdtemp(path.join(stagingRoot, `${slug}-${randomUUID()}-`));
+ let published = false;
+ try {
+ if (forkSource) {
+ for (const entry of forkSource.fileInventory) {
+ const detail = await readFile(companyId, forkSource.id, entry.path);
+ if (!detail) continue;
+ const targetPath = path.resolve(stagingDir, detail.path);
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
+ await fs.writeFile(targetPath, detail.content, "utf8");
+ }
+ }
+ await fs.writeFile(path.join(stagingDir, "SKILL.md"), markdown, "utf8");
+ await fs.mkdir(managedRoot, { recursive: true });
+ const existingPublishedDir = await resolveExistingSkillDirectory(skillDir);
+ if (existingPublishedDir) {
+ // A publish can survive an outer database rollback. Recover only an
+ // exact file-for-file retry. Never silently adopt different content.
+ const existingStat = await fs.lstat(skillDir);
+ if (existingStat.isSymbolicLink() || !existingStat.isDirectory()) {
+ throw conflict(`The storage location for skill "${slug}" is unavailable.`);
+ }
+ const stagedInventory = await collectLocalSkillInventory(stagingDir);
+ const existingInventory = await collectLocalSkillInventory(skillDir);
+ const stagedPaths = stagedInventory.map(entry => entry.path).sort();
+ const existingPaths = existingInventory.map(entry => entry.path).sort();
+ if (JSON.stringify(stagedPaths) !== JSON.stringify(existingPaths)) {
+ throw conflict(`Different files already exist for skill "${slug}". Choose another name.`);
+ }
+ for (const file of stagedPaths) {
+ const target = path.join(skillDir, file);
+ const stat = await fs.lstat(target);
+ const root = await fs.realpath(skillDir);
+ const real = await fs.realpath(target);
+ if (stat.isSymbolicLink() || !stat.isFile() || !real.startsWith(`${root}${path.sep}`)
+ || !(await fs.readFile(target)).equals(await fs.readFile(path.join(stagingDir, file)))) {
+ throw conflict(`Different files already exist for skill "${slug}". Choose another name.`);
+ }
+ }
+ await fs.rm(stagingDir, { recursive: true, force: true });
+ } else {
+ await fs.rename(stagingDir, skillDir);
+ }
+ published = true;
+
+ const inventory = (forkSource || existingPublishedDir)
+ ? await collectLocalSkillInventory(skillDir)
+ : [{ path: "SKILL.md", kind: "skill" as const }];
+ const parsed = parseFrontmatterMarkdown(markdown);
+ const metadata = {
+ sourceKind: "managed_local",
+ ...(forkSource ? {
+ forkedFromSkillId: forkSource.id,
+ forkedFromCompanyId: forkSource.companyId,
+ forkedByAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
+ forkedByUserId: actor?.type === "user" ? actor.userId ?? null : null,
+ } : {}),
+ };
+ const imported = await upsertImportedSkills(companyId, [{
+ key,
+ slug,
+ name: asString(parsed.frontmatter.name) ?? input.name,
+ description: asString(parsed.frontmatter.description) ?? input.description?.trim() ?? forkSource?.description ?? null,
+ markdown,
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ sourceRef: null,
+ trustLevel: deriveTrustLevel(inventory),
+ compatibility: forkSource?.compatibility ?? "compatible",
+ fileInventory: inventory,
+ metadata,
+ }], tx);
+ const created = imported[0]!;
+ const row = await tx
+ .update(companySkills)
+ .set({
+ iconUrl: normalizeStoreText(input.iconUrl, 2000) ?? forkSource?.iconUrl ?? created.iconUrl,
+ color: normalizeStoreText(input.color, 64) ?? forkSource?.color ?? created.color,
+ tagline: normalizeStoreText(input.tagline, 120) ?? forkSource?.tagline ?? created.tagline,
+ authorName: normalizeStoreText(input.authorName, 200) ?? forkSource?.authorName ?? created.authorName,
+ homepageUrl: normalizeStoreText(input.homepageUrl, 2000) ?? forkSource?.homepageUrl ?? created.homepageUrl,
+ categories: input.categories ? normalizeCategoryList(input.categories) : forkSource?.categories ?? created.categories,
+ folderId: input.folderId ?? null,
+ sharingScope,
+ forkedFromSkillId: forkSource?.id ?? null,
+ forkedFromCompanyId: forkSource?.companyId ?? null,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(companySkills.id, created.id), eq(companySkills.companyId, companyId)))
+ .returning()
+ .then((rows) => rows[0] ?? null);
+ if (forkSource) {
+ await tx
+ .update(companySkills)
+ .set({ forkCount: sql`${companySkills.forkCount} + 1`, installCount: sql`${companySkills.installCount} + 1`, updatedAt: new Date() })
+ .where(and(eq(companySkills.id, forkSource.id), eq(companySkills.companyId, companyId)));
+ }
+ const versionInventory = await Promise.all(inventory.map(async (entry) => ({
+ ...entry,
+ content: await fs.readFile(path.join(skillDir, entry.path), "utf8"),
+ })));
+ await createVersion(companyId, created.id, { label: "Initial version" }, actor, {
+ database: tx,
+ skipInventoryRefresh: true,
+ skill: row ? toCompanySkill(row) : created,
+ fileInventory: versionInventory,
+ });
+ return (await getById(companyId, created.id, tx)) ?? (row ? toCompanySkill(row) : created);
+ } catch (error) {
+ if (!published) await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
+ throw error;
+ }
+ });
+ }
- const inventory = forkSource
- ? await collectLocalSkillInventory(skillDir)
- : [{ path: "SKILL.md", kind: "skill" as const }];
- const parsed = parseFrontmatterMarkdown(markdown);
- const metadata = {
- sourceKind: "managed_local",
- ...(forkSource ? {
- forkedFromSkillId: forkSource.id,
- forkedFromCompanyId: forkSource.companyId,
- forkedByAgentId: actor?.type === "agent" ? actor.agentId ?? null : null,
- forkedByUserId: actor?.type === "user" ? actor.userId ?? null : null,
- } : {}),
- };
- const imported = await upsertImportedSkills(companyId, [{
- key,
- slug,
- name: asString(parsed.frontmatter.name) ?? input.name,
- description: asString(parsed.frontmatter.description) ?? input.description?.trim() ?? forkSource?.description ?? null,
- markdown,
- sourceType: "local_path",
- sourceLocator: skillDir,
- sourceRef: null,
- trustLevel: deriveTrustLevel(inventory),
- compatibility: forkSource?.compatibility ?? "compatible",
- fileInventory: inventory,
- metadata,
- }]);
+ async function withSkillFileMutation<T>(
+ companyId: string,
+ skillId: string,
+ mutate: (skill: CompanySkill, tx: DbOrTransaction) => Promise<T>,
+ additionalSlugs: string[] = [],
+ ): Promise<T> {
+ await ensureSkillInventoryCurrent(companyId);
+ const initial = await getById(companyId, skillId);
+ if (!initial) throw notFound("Skill not found");
+ return db.transaction(async (tx) => {
+ // Share the creation/deletion name lock. The identity must be checked
+ // again after waiting: a new skill can now own the same source folder.
+ for (const slug of [...new Set([initial.slug, ...additionalSlugs])].filter(Boolean).sort()) {
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`${companyId}:${slug}`}, 0))`);
+ }
+ const skill = await getById(companyId, skillId, tx);
+ if (!skill) throw notFound("Skill not found");
+ if (skill.slug !== initial.slug) throw conflict("Skill was renamed. Retry the operation.");
+ return mutate(skill, tx);
+ });
+ }
- const created = imported[0]!;
- const row = await db
- .update(companySkills)
- .set({
- iconUrl: normalizeStoreText(input.iconUrl, 2000) ?? forkSource?.iconUrl ?? created.iconUrl,
- color: normalizeStoreText(input.color, 64) ?? forkSource?.color ?? created.color,
- tagline: normalizeStoreText(input.tagline, 120) ?? forkSource?.tagline ?? created.tagline,
- authorName: normalizeStoreText(input.authorName, 200) ?? forkSource?.authorName ?? created.authorName,
- homepageUrl: normalizeStoreText(input.homepageUrl, 2000) ?? forkSource?.homepageUrl ?? created.homepageUrl,
- categories: input.categories ? normalizeCategoryList(input.categories) : forkSource?.categories ?? created.categories,
- folderId: input.folderId ?? null,
- sharingScope,
- forkedFromSkillId: forkSource?.id ?? null,
- forkedFromCompanyId: forkSource?.companyId ?? null,
- updatedAt: new Date(),
- })
- .where(and(eq(companySkills.id, created.id), eq(companySkills.companyId, companyId)))
- .returning()
- .then((rows) => rows[0] ?? null);
- if (forkSource) {
- await db
- .update(companySkills)
- .set({
- forkCount: sql`${companySkills.forkCount} + 1`,
- installCount: sql`${companySkills.installCount} + 1`,
- updatedAt: new Date(),
- })
- .where(and(eq(companySkills.id, forkSource.id), eq(companySkills.companyId, companyId)));
- }
- await createVersion(companyId, created.id, { label: "Initial version" }, actor);
- return (await getById(companyId, created.id)) ?? (row ? toCompanySkill(row) : created);
+ async function refreshEditedSkillInventory(skill: CompanySkill, tx: DbOrTransaction) {
+ const entries = await collectLocalSkillInventory(normalizeSkillDirectory(skill)!, inferLocalSkillInventoryMode(skill));
+ const inventory = await Promise.all(entries.map(async (entry) => ({
+ ...entry,
+ content: await fs.readFile(path.join(normalizeSkillDirectory(skill)!, entry.path), "utf8"),
+ })));
+ await tx.update(companySkills).set({
+ fileInventory: serializeFileInventory(inventory),
+ trustLevel: deriveTrustLevel(inventory),
+ })
+ .where(and(eq(companySkills.companyId, skill.companyId), eq(companySkills.id, skill.id)));
+ return inventory;
}
async function updateFile(
@@ -4521,49 +4615,52 @@ export function companySkillService(db: Db) {
content: string,
actor: SkillActor | null = null,
): Promise<CompanySkillFileDetail> {
- await ensureSkillInventoryCurrent(companyId);
- const skill = await getById(companyId, skillId);
- if (!skill) throw notFound("Skill not found");
+ return withSkillFileMutation(companyId, skillId, async (skill, tx) => {
- const source = deriveSkillSourceInfo(skill);
- if (!source.editable || skill.sourceType !== "local_path") {
- throw unprocessable(source.editableReason ?? "This skill cannot be edited.");
- }
+ const source = deriveSkillSourceInfo(skill);
+ if (!source.editable || skill.sourceType !== "local_path") {
+ throw unprocessable(source.editableReason ?? "This skill cannot be edited.");
+ }
- const normalizedPath = normalizePortablePath(relativePath);
- const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
- if (!absolutePath) throw notFound("Skill file not found");
+ const normalizedPath = normalizePortablePath(relativePath);
+ const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
+ if (!absolutePath) throw notFound("Skill file not found");
- const previousContent = await fs.readFile(absolutePath, "utf8").catch(() => null);
- await fs.mkdir(path.dirname(absolutePath), { recursive: true });
- await fs.writeFile(absolutePath, content, "utf8");
+ const previousContent = await fs.readFile(absolutePath, "utf8").catch(() => null);
+ await fs.mkdir(path.dirname(absolutePath), { recursive: true });
+ await fs.writeFile(absolutePath, content, "utf8");
- if (normalizedPath === "SKILL.md") {
- const parsed = parseFrontmatterMarkdown(content);
- await db
- .update(companySkills)
- .set({
- name: asString(parsed.frontmatter.name) ?? skill.name,
- description: asString(parsed.frontmatter.description) ?? skill.description,
- markdown: content,
- ...readSkillStoreMetadata(parsed.frontmatter, skill.metadata),
- updatedAt: new Date(),
- })
- .where(eq(companySkills.id, skill.id));
- } else {
- await db
- .update(companySkills)
- .set({ updatedAt: new Date() })
- .where(eq(companySkills.id, skill.id));
- }
+ if (normalizedPath === "SKILL.md") {
+ const parsed = parseFrontmatterMarkdown(content);
+ await tx
+ .update(companySkills)
+ .set({
+ name: asString(parsed.frontmatter.name) ?? skill.name,
+ description: asString(parsed.frontmatter.description) ?? skill.description,
+ markdown: content,
+ ...readSkillStoreMetadata(parsed.frontmatter, skill.metadata),
+ updatedAt: new Date(),
+ })
+ .where(eq(companySkills.id, skill.id));
+ } else {
+ await tx
+ .update(companySkills)
+ .set({ updatedAt: new Date() })
+ .where(eq(companySkills.id, skill.id));
+ }
- if (previousContent !== content) {
- await createVersion(companyId, skillId, {}, actor);
- }
+ const inventory = await refreshEditedSkillInventory(skill, tx);
+ if (previousContent !== content) {
+ await createVersion(companyId, skillId, {}, actor, {
+ database: tx, skipInventoryRefresh: true, skill, fileInventory: inventory,
+ });
+ }
- const detail = await readFile(companyId, skillId, normalizedPath);
- if (!detail) throw notFound("Skill file not found");
- return detail;
+ const updated = await getById(companyId, skillId, tx);
+ const detail = updated ? await readLoadedSkillFile(updated, normalizedPath) : null;
+ if (!detail) throw notFound("Skill file not found");
+ return detail;
+ });
}
async function deleteFile(
@@ -4572,56 +4669,55 @@ export function companySkillService(db: Db) {
input: CompanySkillFileDeleteRequest,
actor: SkillActor | null = null,
): Promise<CompanySkillFileDeleteResult> {
- await ensureSkillInventoryCurrent(companyId);
- const skill = await getById(companyId, skillId);
- if (!skill) throw notFound("Skill not found");
+ return withSkillFileMutation(companyId, skillId, async (skill, tx) => {
- const source = deriveSkillSourceInfo(skill);
- if (!source.editable || skill.sourceType !== "local_path") {
- throw unprocessable(source.editableReason ?? "This skill cannot be edited.");
- }
-
- const normalizedPath = normalizePortablePath(input.path);
- if (!normalizedPath) {
- throw unprocessable("Skill file path is required.");
- }
-
- const deletedPaths = input.target === "folder"
- ? skill.fileInventory
- .map((entry) => normalizePortablePath(entry.path))
- .filter((entryPath) => entryPath.startsWith(`${normalizedPath}/`))
- : skill.fileInventory
- .map((entry) => normalizePortablePath(entry.path))
- .filter((entryPath) => entryPath === normalizedPath);
+ const source = deriveSkillSourceInfo(skill);
+ if (!source.editable || skill.sourceType !== "local_path") {
+ throw unprocessable(source.editableReason ?? "This skill cannot be edited.");
+ }
- if (deletedPaths.length === 0) {
- throw notFound(input.target === "folder" ? "Skill folder not found" : "Skill file not found");
- }
- if (deletedPaths.includes("SKILL.md")) {
- throw unprocessable("SKILL.md cannot be deleted.");
- }
+ const normalizedPath = normalizePortablePath(input.path);
+ if (!normalizedPath) {
+ throw unprocessable("Skill file path is required.");
+ }
- const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
- if (!absolutePath) throw notFound("Skill file not found");
+ const deletedPaths = input.target === "folder"
+ ? skill.fileInventory
+ .map((entry) => normalizePortablePath(entry.path))
+ .filter((entryPath) => entryPath.startsWith(`${normalizedPath}/`))
+ : skill.fileInventory
+ .map((entry) => normalizePortablePath(entry.path))
+ .filter((entryPath) => entryPath === normalizedPath);
- await fs.rm(absolutePath, {
- recursive: input.target === "folder",
- force: false,
- }).catch((error) => {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ if (deletedPaths.length === 0) {
throw notFound(input.target === "folder" ? "Skill folder not found" : "Skill file not found");
}
- throw error;
+ if (deletedPaths.includes("SKILL.md")) {
+ throw unprocessable("SKILL.md cannot be deleted.");
+ }
+
+ const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
+ if (!absolutePath) throw notFound("Skill file not found");
+
+ await fs.rm(absolutePath, {
+ recursive: input.target === "folder",
+ force: false,
+ }).catch((error) => {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
+ throw notFound(input.target === "folder" ? "Skill folder not found" : "Skill file not found");
+ }
+ throw error;
});
- await db
+ await tx
.update(companySkills)
.set({ updatedAt: new Date() })
.where(eq(companySkills.id, skill.id));
+ const inventory = await refreshEditedSkillInventory(skill, tx);
await createVersion(companyId, skillId, {
label: input.target === "folder" ? `Deleted ${normalizedPath}/` : `Deleted ${normalizedPath}`,
- }, actor);
+ }, actor, { database: tx, skipInventoryRefresh: true, skill, fileInventory: inventory });
return {
skillId: skill.id,
@@ -4629,6 +4725,7 @@ export function companySkillService(db: Db) {
target: input.target,
deletedPaths,
};
+ });
}
async function installUpdate(companyId: string, skillId: string, options: { force?: boolean } = {}): Promise<CompanySkill | null> {
@@ -6041,12 +6138,16 @@ export function companySkillService(db: Db) {
return out;
}
- async function upsertImportedSkills(companyId: string, imported: ImportedSkill[]): Promise<CompanySkill[]> {
+ async function upsertImportedSkills(
+ companyId: string,
+ imported: ImportedSkill[],
+ database: DbOrTransaction = db,
+ ): Promise<CompanySkill[]> {
const out: CompanySkill[] = [];
for (const skill of imported) {
assertImportedSkillKeyAllowed(skill);
assertImportedSkillSourceAllowed(skill);
- const existing = await getByKey(companyId, skill.key);
+ const existing = await getByKey(companyId, skill.key, database);
const existingMeta = existing ? getSkillMeta(existing) : {};
const incomingMeta = skill.metadata && isPlainRecord(skill.metadata) ? skill.metadata : {};
const incomingOwner = asString(incomingMeta.owner);
@@ -6108,13 +6209,13 @@ export function companySkillService(db: Db) {
continue;
}
const row = existing
- ? await db
+ ? await database
.update(companySkills)
.set(values)
.where(eq(companySkills.id, existing.id))
.returning()
.then((rows) => rows[0] ?? null)
- : await db
+ : await database
.insert(companySkills)
.values(values)
.returning()
@@ -6938,41 +7039,82 @@ export function companySkillService(db: Db) {
}
async function deleteSkill(companyId: string, skillId: string): Promise<CompanySkill | null> {
- const row = await db
- .select()
- .from(companySkills)
- .where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId)))
- .then((rows) => rows[0] ?? null);
- if (!row) return null;
-
- const skill = toCompanySkill(row);
- const usedByAgents = await usage(companyId, skill.key);
-
- if (usedByAgents.length > 0) {
+ const initial = await getById(companyId, skillId);
+ if (!initial) return null;
+ async function assertUnused(skill: CompanySkill) {
+ const usedByAgents = await usage(companyId, skill.key);
+ if (usedByAgents.length === 0) return;
const agentNames = usedByAgents.map((agent) => agent.name).sort((left, right) => left.localeCompare(right));
throw unprocessable(
`Cannot delete skill "${skill.name}" while it is still used by ${agentNames.join(", ")}. Detach it from those agents first.`,
{
- skillId: skill.id,
- skillKey: skill.key,
+ skillId: skill.id, skillKey: skill.key,
usedByAgents: usedByAgents.map((agent) => ({
- id: agent.id,
- name: agent.name,
- urlKey: agent.urlKey,
- adapterType: agent.adapterType,
+ id: agent.id, name: agent.name, urlKey: agent.urlKey, adapterType: agent.adapterType,
})),
},
);
}
-
- // Take the cache lifecycle lock before deleting the row. A busy publisher must not
- // turn a committed deletion into an apparent API failure, nor recreate its cache.
- await removeRuntimeSkillCache(resolveManagedSkillsRoot(companyId), skill.id, async () => {
- await fs.rm(resolveRuntimeSkillMaterializedPath(companyId, skill), { recursive: true, force: true });
- await db.delete(companySkills).where(eq(companySkills.id, skillId));
+ await assertUnused(initial);
+ const managedRoot = resolveManagedSkillsRoot(companyId);
+ let movedSource: { source: string; quarantine: string } | undefined;
+ let deleted: CompanySkill | null = null;
+ async function restoreSource() {
+ if (!movedSource) return;
+ await fs.rename(movedSource.quarantine, movedSource.source);
+ movedSource = undefined;
+ }
+ // Keep the cache lifecycle lock through database commit. A publisher must
+ // not see the old row after cache removal and republish a deleted skill.
+ await removeRuntimeSkillCache(managedRoot, initial.id, async () => {
+ try {
+ deleted = await db.transaction(async (tx) => {
+ // Share creation's name lock and re-read the ID, so a second delete
+ // cannot remove a newly recreated skill with the same name.
+ await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`${companyId}:${initial.slug}`}, 0))`);
+ const skill = await getById(companyId, skillId, tx);
+ if (!skill) return null;
+ if (skill.slug !== initial.slug) throw conflict("Skill changed during deletion. Retry the request.");
+ await assertUnused(skill);
+ try {
+ await fs.rm(resolveRuntimeSkillMaterializedPath(companyId, skill), { recursive: true, force: true });
+ if (isPaperclipManagedRenameTarget(skill)) {
+ const source = normalizeSkillDirectory(skill)!;
+ const stat = await fs.lstat(source).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return null;
+ throw error;
+ });
+ if (stat) {
+ const quarantineRoot = path.join(managedRoot, ".deleted");
+ await fs.mkdir(quarantineRoot, { recursive: true });
+ const quarantine = path.join(quarantineRoot, `${skill.id}-${randomUUID()}`);
+ // Do not follow symlinks or delete external/project sources.
+ // Retain bytes until the database deletion commits.
+ await fs.rename(source, quarantine);
+ movedSource = { source, quarantine };
+ }
+ }
+ await tx.delete(companySkills).where(and(eq(companySkills.id, skillId), eq(companySkills.companyId, companyId)));
+ } catch (error) {
+ // Restore before releasing the name lock on a failed write.
+ await restoreSource();
+ throw error;
+ }
+ return skill;
+ });
+ } catch (error) {
+ await restoreSource();
+ throw error;
+ }
});
-
- return skill;
+ // Only remove the unique quarantine path after commit. Cleanup must not
+ // remove a replacement skill or report a committed delete as failed.
+ if (movedSource) {
+ await fs.rm(movedSource.quarantine, { recursive: true, force: true }).catch((error) => {
+ logger.warn({ err: error, companyId, skillId }, "Skill deleted; quarantined source cleanup failed");
+ });
+ }
+ return deleted;
}
return {
diff --git a/server/src/services/execution-control-reconciliation.test.ts b/server/src/services/execution-control-reconciliation.test.ts
index ca9bf41673..6a0bb03dca 100644
--- a/server/src/services/execution-control-reconciliation.test.ts
+++ b/server/src/services/execution-control-reconciliation.test.ts
@@ -85,8 +85,10 @@ describeEmbeddedPostgres("reconcileAbandonedExecutionControl reports a genuine f
expect(run?.status).toBe("failed");
expect(run?.errorCode).toBe("execution_finalization_deadline_exceeded");
+ await vi.waitFor(() => {
+ expect(mockCaptureRunFailure.mock.calls.slice(captureCallsBefore)).toHaveLength(1);
+ }, { timeout: 5_000 });
const newCaptures = mockCaptureRunFailure.mock.calls.slice(captureCallsBefore);
- expect(newCaptures).toHaveLength(1);
expect(newCaptures[0]?.[0]).toMatchObject({
runId,
runStatus: "failed",
@@ -97,6 +99,11 @@ describeEmbeddedPostgres("reconcileAbandonedExecutionControl reports a genuine f
it("reports zero events for a repeated sweep over the same already-failed run", async () => {
const { runId } = await seedAbandonedRunFixture();
await reconcileAbandonedExecutionControl(db);
+ // The first report is fire-and-forget. Observe it before taking the
+ // second sweep's baseline, so a late first report is not a duplicate.
+ await vi.waitFor(() => {
+ expect(mockCaptureRunFailure.mock.calls.filter(([event]) => event.runId === runId)).toHaveLength(1);
+ }, { timeout: 5_000 });
// The first sweep already cleared executionControlDeadlineAt and moved the
// run to "failed". Restore the deadline to simulate a second sweep still
// observing the same run as a candidate.
diff --git a/server/src/services/native-runtime/create-skill.integration.test.ts b/server/src/services/native-runtime/create-skill.integration.test.ts
new file mode 100644
index 0000000000..6bb11d8f0c
--- /dev/null
+++ b/server/src/services/native-runtime/create-skill.integration.test.ts
@@ -0,0 +1,119 @@
+import { randomUUID } from "node:crypto";
+import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { and, eq } from "drizzle-orm";
+import { activityLog, companySkills, companyMemberships, heartbeatRuns, issues } from "@paperclipai/db";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { startRunnerApiTestServer } from "../../__tests__/helpers/runner-api-server.js";
+import { companySkillPolicyService } from "../company-skill-policy.js";
+import { companySkillService } from "../company-skills.js";
+import { activityService } from "../activity.js";
+
+describe("runner create_skill through the real skill API", () => {
+ let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
+ let home: string;
+ const previousSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
+ const previousHome = process.env.PAPERCLIP_HOME;
+ beforeAll(async () => {
+ process.env.PAPERCLIP_AGENT_JWT_SECRET = randomUUID();
+ home = await mkdtemp(join(tmpdir(), "paperclip-create-skill-"));
+ process.env.PAPERCLIP_HOME = home;
+ server = await startRunnerApiTestServer();
+ }, 60_000);
+ afterAll(async () => {
+ await server?.close();
+ if (previousSecret === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET;
+ else process.env.PAPERCLIP_AGENT_JWT_SECRET = previousSecret;
+ if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
+ else process.env.PAPERCLIP_HOME = previousHome;
+ if (home) await rm(home, { recursive: true, force: true });
+ });
+
+ async function fixture(options: Parameters<typeof server.fixture>[0] = {}) {
+ const result = await server.fixture(options);
+ await server.db.insert(companyMemberships).values({ companyId: result.companyId, principalType: "agent", principalId: result.agentId, status: "active", membershipRole: "member" });
+ return result;
+ }
+
+ const args = {
+ name: "release-review", description: "Review release notes.", idempotencyKey: "release-review-1",
+ markdown: "---\nname: release-review\ndescription: Review release notes.\n---\n\n# Review\nCheck each release note against the change.\n",
+ };
+
+ it("creates one skill and one task-feed event across response retries", async () => {
+ const testFixture = await fixture();
+ expect(testFixture.authority.definitions().some(tool => tool.name === "create_skill")).toBe(true);
+ const call = (callId: string) => testFixture.authority.execute({ tool: "create_skill", callId, arguments: args });
+ const first = await call("first");
+ expect(await call("lost-response-retry")).toEqual(first);
+ const skills = await server.db.select().from(companySkills).where(eq(companySkills.companyId, testFixture.companyId));
+ expect(skills).toHaveLength(1);
+ expect(skills[0]).toMatchObject({ name: args.name, markdown: args.markdown });
+ const service = companySkillService(server.db);
+ expect((await service.readFile(testFixture.companyId, skills[0]!.id, "SKILL.md"))?.content).toBe(args.markdown);
+ expect(await service.listVersions(testFixture.companyId, skills[0]!.id)).toHaveLength(1);
+ const events = (await activityService(server.db).forIssue(testFixture.issueId)).filter(e => e.action === "company.skill_created");
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ entityId: skills[0]!.id, details: { sourceIssueId: testFixture.issueId, versionId: skills[0]!.currentVersionId } });
+ await expect(testFixture.authority.execute({ tool: "create_skill", callId: "conflict", arguments: { ...args, markdown: args.markdown + "Different instructions." } })).rejects.toThrow(/different inputs/);
+ expect((await service.readFile(testFixture.companyId, skills[0]!.id, "SKILL.md"))?.content).toBe(args.markdown);
+ });
+
+ it("enforces explicit company policy before a write", async () => {
+ const testFixture = await fixture();
+ await companySkillPolicyService(server.db).replace({ companyId: testFixture.companyId, expectedRevision: 0,
+ policy: { schemaVersion: 1, defaultEffect: "deny", rules: [] },
+ activity: { actorType: "user", actorId: "test-board" } });
+ await expect(testFixture.authority.execute({ tool: "create_skill", callId: "policy-denied", arguments: args })).rejects.toThrow(/company policy/);
+ expect(await server.db.select().from(companySkills).where(eq(companySkills.companyId, testFixture.companyId))).toHaveLength(0);
+ });
+
+ it("recovers a concurrent or replacement-run retry without creating another skill", async () => {
+ const testFixture = await fixture();
+ const [first, duplicate] = await Promise.all(["first", "concurrent"].map(callId =>
+ testFixture.authority.execute({ tool: "create_skill", callId, arguments: args })));
+ expect(duplicate).toEqual(first);
+
+ const replacementRunId = randomUUID();
+ await server.db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, testFixture.runId));
+ await server.db.insert(heartbeatRuns).values({
+ id: replacementRunId, companyId: testFixture.companyId, agentId: testFixture.agentId,
+ status: "running", runtimeMode: "native", nativeIssueId: testFixture.issueId,
+ invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId: testFixture.issueId },
+ });
+ await server.db.update(issues).set({ executionRunId: replacementRunId }).where(eq(issues.id, testFixture.issueId));
+ const replacement = new PaperclipRunnerToolAuthority(server.db, { ...testFixture, runId: replacementRunId });
+ expect(await replacement.execute({ tool: "create_skill", callId: "recovered", arguments: args })).toEqual(first);
+ await expect(testFixture.authority.execute({ tool: "create_skill", callId: "stale", arguments: args })).rejects.toThrow();
+ expect(await server.db.select().from(companySkills).where(eq(companySkills.companyId, testFixture.companyId))).toHaveLength(1);
+ expect((await activityService(server.db).forIssue(testFixture.issueId)).filter(e => e.action === "company.skill_created")).toHaveLength(1);
+ });
+
+ it("rechecks company policy when a completed call is retried", async () => {
+ const testFixture = await fixture();
+ await testFixture.authority.execute({ tool: "create_skill", callId: "allowed", arguments: args });
+ await companySkillPolicyService(server.db).replace({ companyId: testFixture.companyId, expectedRevision: 0,
+ policy: { schemaVersion: 1, defaultEffect: "deny", rules: [] },
+ activity: { actorType: "user", actorId: "test-board" } });
+ await expect(testFixture.authority.execute({ tool: "create_skill", callId: "revoked-retry", arguments: args })).rejects.toThrow(/company policy/);
+ expect(await server.db.select().from(companySkills).where(eq(companySkills.companyId, testFixture.companyId))).toHaveLength(1);
+ });
+
+ it("does not create skills in planning mode", async () => {
+ const testFixture = await fixture({ mode: "planning" });
+ expect(new PaperclipRunnerToolAuthority(server.db, { ...testFixture, workMode: "planning" }).definitions().some(tool => tool.name === "create_skill")).toBe(false);
+ await expect(testFixture.authority.execute({ tool: "create_skill", callId: "plan", arguments: args })).rejects.toThrow();
+ expect(await server.db.select().from(companySkills).where(eq(companySkills.companyId, testFixture.companyId))).toHaveLength(0);
+ });
+
+ it("isolates company names and creation history", async () => {
+ const a = await fixture(), b = await fixture();
+ const first = await a.authority.execute({ tool: "create_skill", callId: "a", arguments: args }) as { id: string };
+ const second = await b.authority.execute({ tool: "create_skill", callId: "b", arguments: args }) as { id: string };
+ expect(first.id).not.toBe(second.id);
+ expect(await companySkillService(server.db).getById(b.companyId, first.id)).toBeNull();
+ expect(await server.db.select().from(activityLog).where(and(eq(activityLog.companyId, a.companyId), eq(activityLog.action, "company.skill_created")))).toHaveLength(1);
+ });
+});
diff --git a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
index 5699f58511..4eb79127f5 100644
--- a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
+++ b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
@@ -441,8 +441,10 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a
expect(run?.status).toBe("failed");
// The first write is a genuine transition into "failed": it reports
// exactly one Sentry event.
+ await vi.waitFor(() => {
+ expect(captureRunFailureCallsFrom(captureCallsBeforeFirstFinalize)).toHaveLength(1);
+ }, { timeout: 5_000 });
const firstFinalizeCaptures = captureRunFailureCallsFrom(captureCallsBeforeFirstFinalize);
- expect(firstFinalizeCaptures).toHaveLength(1);
expect(firstFinalizeCaptures[0]?.[0]).toMatchObject({
runId: fixture.runId,
runStatus: "failed",
diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts
index ea778e8ea9..83d0d64511 100644
--- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts
+++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts
@@ -90,7 +90,7 @@ describe("PaperclipRunnerToolAuthority", () => {
issueId,
runId,
});
- expect(authority.definitions()).toHaveLength(25);
+ expect(authority.definitions()).toHaveLength(26);
expect(authority.definitions().map((tool) => tool.name)).toEqual(
expect.arrayContaining([
"connections_search",
@@ -106,6 +106,7 @@ describe("PaperclipRunnerToolAuthority", () => {
"read_document",
"list_document_revisions",
"write_document",
+ "create_skill",
"list_agents",
"get_agent",
"list_approvals",
diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts
index cce1e6b1fa..6277e0bc01 100644
--- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts
+++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts
@@ -1,3 +1,4 @@
+import { callCreateSkillTool } from "../skill-tools.js";
import { callProjectTool } from "../project-tools.js";
import { isConnectorTool, executeConnectorTool, type ConnectorAssignment } from "../connector-runtime.js";
import { resolveNativeRuntimeMcpSnapshot } from "./runtime-context.js";
@@ -72,7 +73,7 @@ const IMPLEMENTED_OPERATIONS = new Set([
"search_api", "call_api",
"get_task_context", "get_task_history", "search_tasks", "report_progress",
"request_human_input",
- "create_task", "set_dependencies", "create_project", "list_project_repositories", "list_projects", "register_deliverable",
+ "create_skill", "create_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",
]);
@@ -309,6 +310,12 @@ export class PaperclipRunnerToolAuthority {
throw new Error("paperclip_runner_tool_mode_denied");
}
switch (call.tool) {
+ case "create_skill": {
+ const apiUrl = this.binding.apiUrl ?? process.env.PAPERCLIP_API_URL;
+ const token = createLocalAgentJwt(this.binding.agentId, this.binding.companyId, context.actor.adapterType, this.binding.runId, context.run.responsibleUserId);
+ if (!apiUrl || !token) throw new Error("Skill tool authentication is unavailable");
+ return callCreateSkillTool({ arguments: input, apiUrl, token, companyId: this.binding.companyId });
+ }
case "create_project":
case "list_project_repositories":
case "list_projects": {
diff --git a/server/src/services/native-runtime/runner-api-catalog.ts b/server/src/services/native-runtime/runner-api-catalog.ts
index 6052d4c881..fbdbd73b07 100644
--- a/server/src/services/native-runtime/runner-api-catalog.ts
+++ b/server/src/services/native-runtime/runner-api-catalog.ts
@@ -42,6 +42,7 @@ function words(text: string): string[] {
}
function dedicatedTools(method: string, path: string): string[] {
+ if (/\/companies\/\{[^}]+\}\/skills$/.test(path) && method === "POST") return ["create_skill"];
if (/\/projects$/.test(path)) return method === "GET" ? ["list_projects"] : method === "POST" ? ["create_project"] : [];
if (/\/project-repositories$/.test(path) && method === "GET") return ["list_project_repositories"];
if (/\/issues\/\{[^}]+\}\/comments$/.test(path)) return method === "GET" ? ["get_task_history"] : ["report_progress"];
diff --git a/server/src/services/project-tool-context.ts b/server/src/services/project-tool-context.ts
index 230ecde234..a0cc946835 100644
--- a/server/src/services/project-tool-context.ts
+++ b/server/src/services/project-tool-context.ts
@@ -5,9 +5,9 @@ import { forbidden } from "../errors.js";
import { captureRunIdentity } from "./run-identity.js";
/** Resolve authority from the authenticated run, never caller-supplied user/task IDs. */
-export async function projectToolContext(db: Db, actor: Request["actor"], write = false) {
+export async function projectToolContext(db: Db, actor: Request["actor"], write = false, resource = "Project") {
if (actor.type !== "agent" || actor.source !== "agent_jwt" || !actor.runId || !actor.agentId || !actor.companyId) {
- throw forbidden("Project tools require an authenticated agent run");
+ throw forbidden(`${resource} tools require an authenticated agent run`);
}
// Acquire task/run locks before checking mode and session generation. A reset,
// cancellation, or steering update cannot race a committing project mutation.
@@ -15,13 +15,13 @@ export async function projectToolContext(db: Db, actor: Request["actor"], write
const run = identity.run;
const snapshot = run.contextSnapshot ?? {};
const issueId = run.nativeIssueId ?? (typeof snapshot.issueId === "string" ? snapshot.issueId : null);
- if (!issueId) throw forbidden("Project tools require a task-bound run");
+ if (!issueId) throw forbidden(`${resource} tools require a task-bound run`);
const [issue] = await db.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)));
if (!issue) throw forbidden("Run task is unavailable");
if (issue.conversationAgentId && Number(snapshot.conversationSessionGeneration ?? 0) !== issue.conversationSessionGeneration) {
throw forbidden("Conversation session has changed");
}
- if (write && !["standard", "skill_test"].includes(issue.workMode)) throw forbidden("Project creation is unavailable in Ask or Plan mode");
+ if (write && !["standard", "skill_test"].includes(issue.workMode)) throw forbidden(`${resource} creation is unavailable in Ask or Plan mode`);
const userId = identity.run.responsibleUserId;
// local-board is a server-owned identity; never accepted from tool arguments.
return { run, issue, userId, localTrusted: userId === "local-board" };
diff --git a/server/src/services/skill-tools.test.ts b/server/src/services/skill-tools.test.ts
new file mode 100644
index 0000000000..a1794dbcae
--- /dev/null
+++ b/server/src/services/skill-tools.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from "vitest";
+import { callCreateSkillTool, createSkillToolInput } from "./skill-tools.js";
+
+const input = {
+ name: "release-review", description: "Review release notes.", idempotencyKey: "release-review-1",
+ markdown: "---\nname: release-review\ndescription: Review release notes.\n---\n\n# Review\nCheck each release note against the change.\n",
+};
+
+describe("create skill tool", () => {
+ it("requires a usable skill with matching frontmatter", () => {
+ expect(createSkillToolInput.parse(input)).toEqual(input);
+ for (const markdown of ["I created it", "---\nname: different\ndescription: Review release notes.\n---\nBody", "---\nname: release-review\ndescription: Review release notes.\n---\n"]) {
+ expect(createSkillToolInput.safeParse({ ...input, markdown }).success).toBe(false);
+ }
+ expect(createSkillToolInput.safeParse({ ...input, companyId: "foreign" }).success).toBe(false);
+ });
+
+ it.each([
+ { markdown: "---\nname: [broken\n---\nBody" },
+ { markdown: input.markdown.replace("description: Review release notes.", "description: Different purpose.") },
+ { slug: "another-skill" },
+ { markdown: "No frontmatter." },
+ ])("rejects invalid skill content before any API call (%j)", async (invalid) => {
+ const fetcher = vi.fn();
+ await expect(callCreateSkillTool({ arguments: { ...input, ...invalid },
+ apiUrl: "http://localhost:3100", token: "test-token", companyId: "company-1" }, fetcher)).rejects.toThrow();
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+
+ it("uses authenticated company route and returns only a portable skill reference", async () => {
+ const fetcher = vi.fn().mockResolvedValue(new Response(JSON.stringify({ id: "skill-1", name: input.name,
+ slug: input.name, description: input.description, currentVersionId: "version-1", sourceLocator: "/private/managed/skill", markdown: input.markdown }), { status: 201 }));
+ const result = await callCreateSkillTool({ arguments: input, apiUrl: "http://localhost:3100/api", token: "test-token", companyId: "company-1" }, fetcher);
+ expect(fetcher).toHaveBeenCalledWith("http://localhost:3100/api/companies/company-1/skills", expect.objectContaining({ method: "POST" }));
+ expect(JSON.parse(fetcher.mock.calls[0]![1].body)).toEqual(input);
+ expect(result).toEqual({ id: "skill-1", name: input.name, slug: input.name, description: input.description, versionId: "version-1", studioPath: "/skills/studio/skill-1" });
+ });
+});
diff --git a/server/src/services/skill-tools.ts b/server/src/services/skill-tools.ts
new file mode 100644
index 0000000000..371d507a5e
--- /dev/null
+++ b/server/src/services/skill-tools.ts
@@ -0,0 +1,35 @@
+import { parseFrontmatterMarkdown, skillFrontmatterSchema } from "@paperclipai/shared";
+import { z } from "zod";
+
+/** A complete single-file skill. Identity and permissions come from the run. */
+export const createSkillToolInput = z.object({
+ name: z.string().min(1).max(120).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
+ slug: z.string().min(1).max(120).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/).optional(),
+ description: z.string().trim().min(1).max(2000),
+ markdown: z.string().min(1).max(200000),
+ idempotencyKey: z.string().min(1).max(240),
+}).strict().superRefine((input, context) => {
+ const document = parseFrontmatterMarkdown(input.markdown);
+ const metadata = skillFrontmatterSchema.safeParse(document.frontmatter);
+ if (!document.hasFrontmatter || !metadata.success || !document.body.trim()
+ || metadata.data.name !== input.name || metadata.data.description !== input.description
+ || (input.slug !== undefined && input.slug !== input.name)) {
+ context.addIssue({ code: "custom", path: ["markdown"], message: "Provide a complete SKILL.md with name and description matching the tool inputs, a nonempty body, and slug equal to name when supplied." });
+ }
+});
+
+/** Use the same API and company skill policy as Skill Studio. */
+export async function callCreateSkillTool(input: {
+ arguments: Record<string, unknown>; apiUrl: string; token: string; companyId: string;
+}, fetcher: typeof fetch = fetch) {
+ const body = createSkillToolInput.parse(input.arguments);
+ const response = await fetcher(`${input.apiUrl.replace(/\/+$/, "").replace(/\/api$/, "")}/api/companies/${encodeURIComponent(input.companyId)}/skills`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${input.token}`, "Content-Type": "application/json" },
+ body: JSON.stringify(body), signal: AbortSignal.timeout(60_000),
+ });
+ const result = await response.json();
+ if (!response.ok) throw new Error(typeof result.error === "string" ? result.error : `Skill creation failed (${response.status})`);
+ return { id: result.id, name: result.name, slug: result.slug, description: result.description,
+ versionId: result.currentVersionId, studioPath: `/skills/studio/${encodeURIComponent(result.id)}` };
+}
diff --git a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md b/tests/runner-e2e/EVERYDAY-WORKFLOWS.md
index bd66843ac4..2f40ac3f4e 100644
--- a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md
+++ b/tests/runner-e2e/EVERYDAY-WORKFLOWS.md
@@ -17,6 +17,7 @@ exact execution ID explicitly.
| Decline a new connection | `connection-decline` | Start without service connections; match a Notion connection intent; click Not now; verify the saved rejection, no new connection or repeated request, and an explanation followed by Done. |
| Continue work after a controller restart | `recover-controller` | Observe saved source, persist a user message, restart the isolated controller, and independently test the delivered result. |
| Stop work and change direction | `stop-redirect` | Click Stop, send one new request, reload, observe exactly one stored user message and the new answer, and reach Done. |
+| Create and edit a company skill | `create-skill-studio` | Create one skill through the runner, verify its persisted library entry and activity-feed card, open Skill Studio, save an edit, and verify the edit after returning. Local Codex, local ACPX Claude, and warm Daytona cells are explicit. |
For normal completion, all story tasks must reach Done, with no active run,
pending completion confirmation, or scheduled recovery. Runs must prove native
@@ -35,10 +36,10 @@ See [controlled recovery tests](../runner-recovery/README.md).
## Matrix and running
-The local matrix has eight cases on native Codex `gpt-5.6-sol`, native ACPX Claude
-`claude-sonnet-5`, and native Codex `gpt-5.4-mini`: 24 cells. The two core profiles
-also declare build/revise, delegation, and controller-restart cases on Daytona:
-six cells. Remote runner-process killing is not supported. For remote controller
+The local matrix has nine cases on native Codex `gpt-5.6-sol`, native ACPX Claude
+`claude-sonnet-5`, and native Codex `gpt-5.4-mini`: 27 cells. The two core profiles
+also declare build/revise, delegation, controller-restart, and skill-creation cases
+on Daytona: eight cells. Remote runner-process killing is not supported. For remote controller
restart, a verified first download supplies the persistence checkpoint; the
controller is interrupted during a subsequent revision with another queued
requirement.
@@ -105,7 +106,7 @@ inputs; that is distinct from provider-side model identity verification.
Initial live results are diagnostic. They are not a reliability estimate or a
model ranking. Before promotion, freeze both source revisions and harness
-digest, run at least three independent local repetitions, qualify the six
+digest, run at least three independent local repetitions, qualify the eight
remote cells against a verified image, and review every failure. Keep model
quality, lifecycle correctness, infrastructure availability, and latency separate.
@@ -171,7 +172,7 @@ that the final response was visible.
## Recovery scope correction (14 September)
-The current catalog has **30 cells: 24 local and six remote**. Forced runner
+This correction reduced the catalog to **30 cells: 24 local and six remote**. Forced runner
crash probes are retired from paid selection. Their original attempt IDs remain
in Evalbook's Diagnostics history and Latest pages; they are excluded from the
main matrix without changing grades or deleting evidence. Reported spend still
@@ -186,3 +187,12 @@ A future user-facing crash-recovery case needs a reproducible recoverable fault,
an identified supported recovery action, and evidence through the final usable
result. A missing test premise must be reported as unexercised, not a model
failure. Do not introduce a new paid case just to replace a retired row.
+
+## Skill creation (16 September)
+
+`create-skill-studio` adds five cells: three local profiles and the two core
+profiles on Daytona. The current catalog has **35 cells: 27 local and eight
+remote**. The test opens the created skill from its task-feed card, checks the
+canonical skill identity in Studio, saves an edit, and returns to the same skill
+in the task sidebar. A model's authored document heading is not used as the
+identity check.
diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.ts
index 0f8c023418..34d66b08d9 100644
--- a/tests/runner-e2e/catalog.test.ts
+++ b/tests/runner-e2e/catalog.test.ts
@@ -41,10 +41,10 @@ describe("runner E2E catalog", () => {
expect(localIntegrityTasks).toHaveLength(2);
expect(openRouterBreadthTasks).toHaveLength(3);
expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([
- 30, 24, 42, 14, 10, 2,
+ 35, 24, 42, 14, 10, 2,
]);
- expect(validateRunnerCatalog()).toHaveLength(122);
- expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(122);
+ expect(validateRunnerCatalog()).toHaveLength(127);
+ expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(127);
expect(
runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"),
).toHaveLength(42);
diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.ts
index 2ffa5a519e..f361d82e83 100644
--- a/tests/runner-e2e/catalog.ts
+++ b/tests/runner-e2e/catalog.ts
@@ -893,9 +893,9 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [
id: "everyday-workflows", label: "Everyday Paperclip Work", manualOnly: true,
description: "Real user requests, useful downloaded work, and durable continuation using production instructions.",
groups: ["native"], profiles: everydayProfiles, environments: [localEnvironment, daytonaWarmEnvironment],
- tasks: everydayTasks, expectedMatrixSize: 30,
+ tasks: everydayTasks, expectedMatrixSize: 35,
excludedExecutionIds: [...everydayProfiles.flatMap(profile => everydayTasks
- .filter(task => !["build-revise", "delegate-feedback", "recover-controller"].includes(task.id))
+ .filter(task => !["build-revise", "delegate-feedback", "recover-controller", "create-skill-studio"].includes(task.id))
.map(task => `everyday-workflows.${profile.id}.daytona.${task.id}`))],
definitionMetadata: { version: 3, instructions: "production", grading: "outcome-and-invariants", scheduling: "explicit-only" },
},
diff --git a/tests/runner-e2e/everyday-cases.ts b/tests/runner-e2e/everyday-cases.ts
index 0015907b95..cb562cab4a 100644
--- a/tests/runner-e2e/everyday-cases.ts
+++ b/tests/runner-e2e/everyday-cases.ts
@@ -80,6 +80,12 @@ const definitions = [
SLUGIFY_REQUIREMENTS,
2,
],
+ [
+ "create-skill-studio",
+ "Create and edit a company skill",
+ "Create one company skill using this complete SKILL.md content:\n---\nname: release-readiness-checklist\ndescription: A bounded checklist for validating a release before handoff.\n---\n\n# Release Readiness Checklist\n\n1. Verify checks.\n2. Review evidence.\n3. Record the handoff.\n\nUse request key create-skill-e2e-001. After creating it, report the created skill and finish the task.",
+ 1,
+ ],
] as const;
export const everydayTasks: readonly RunnerTaskFixture[] = definitions.map(
diff --git a/tests/runner-e2e/everyday-flow.ts b/tests/runner-e2e/everyday-flow.ts
index 6c4b7d0fc6..6a8b29a89a 100644
--- a/tests/runner-e2e/everyday-flow.ts
+++ b/tests/runner-e2e/everyday-flow.ts
@@ -761,6 +761,72 @@ export async function runEverydayFlow(input: Input) {
});
}
await settled();
+ if (caseId === "create-skill-studio") {
+ const createdSkills = await api.get<Row[]>(
+ `/api/companies/${fixtures.company.id}/skills`,
+ );
+ const created = createdSkills.find(
+ (skill) => skill.slug === "release-readiness-checklist",
+ );
+ check(
+ "skill-persisted",
+ Boolean(created && String(created.name) === "release-readiness-checklist"),
+ "The runner-created skill is present in the company library after the run.",
+ );
+ if (created) {
+ await openParent();
+ const card = page.getByRole("article", {
+ name: "Skill created: release-readiness-checklist",
+ });
+ await expect(card).toHaveCount(1);
+ await expect(card).toBeVisible();
+ await card.getByRole("button").click();
+ await expect(page.getByRole("heading", { name: "release-readiness-checklist" })).toBeVisible();
+ await expect(page.getByText("Verify checks.", { exact: true })).toBeVisible();
+ check("feed-card-opened", true, "The task thread card opened the created skill sidebar.");
+ const openStudio = page.getByRole("button", { name: "Open in Skill Studio", exact: true });
+ await expect(openStudio).toBeVisible();
+ await openStudio.click();
+ await expect(page).toHaveURL(new RegExp(`/skills/studio/${created.id}$`));
+ // Studio's skill selector identifies the resource. Headings inside the
+ // authored document can differ from its canonical skill name.
+ await expect(page.getByRole("combobox").filter({ hasText: "release-readiness-checklist" })).toBeVisible();
+ const editor = page.getByRole("textbox", { name: "editable markdown", exact: true });
+ await editor.click();
+ await editor.press("ControlOrMeta+End");
+ await editor.press("Enter");
+ await editor.press("Enter");
+ await editor.pressSequentially("Studio edit marker: verified");
+ await page.getByRole("button", { name: /^Save$/ }).click();
+ await pollUntil({
+ label: "Skill Studio edit persisted",
+ deadlineAt: Math.min(input.deadlineAt, Date.now() + 30_000),
+ load: () => api.get<Row>(
+ `/api/companies/${fixtures.company.id}/skills/${encodeURIComponent(String(created.id))}`,
+ ),
+ accept: (detail) => JSON.stringify(detail).includes("Studio edit marker: verified"),
+ });
+ const detail = await api.get<Row>(
+ `/api/companies/${fixtures.company.id}/skills/${encodeURIComponent(String(created.id))}`,
+ );
+ check(
+ "studio-edit-persisted",
+ JSON.stringify(detail).includes("Studio edit marker: verified"),
+ "The Skill Studio edit remains in the persisted skill after returning to the page.",
+ );
+ check("studio-opened", true, "The skill detail opened in Skill Studio.");
+ await page.goBack();
+ await expect(page).toHaveURL(new RegExp(`/issues/`));
+ const returnedCard = page.getByRole("article", {
+ name: "Skill created: release-readiness-checklist",
+ });
+ await expect(returnedCard).toBeVisible();
+ await returnedCard.getByRole("button").click();
+ await expect(page.getByRole("heading", { name: "release-readiness-checklist" })).toBeVisible();
+ await expect(page.getByText("Studio edit marker: verified", { exact: true })).toBeVisible();
+ check("return-content-persisted", true, "Returning to the task shows the saved Skill Studio edit.");
+ }
+ }
if (declining) {
const issue = ev.issues.find((i) => i.id === parent!.id)!;
const requests = issue.interactions as Row[];
diff --git a/tests/runner-e2e/everyday.test.ts b/tests/runner-e2e/everyday.test.ts
index fb9a09fcc5..974436a102 100644
--- a/tests/runner-e2e/everyday.test.ts
+++ b/tests/runner-e2e/everyday.test.ts
@@ -17,7 +17,7 @@ describe("manual everyday workflow catalog", () => {
const selected = selectRunnerExecutions(
parseRunnerSelectors(["--suite", "everyday-workflows"]),
);
- expect(selected).toHaveLength(30);
+ expect(selected).toHaveLength(35);
expect(selected.every((e) => e.profile.generation === "native")).toBe(true);
expect(
selectRunnerExecutions(
@@ -68,9 +68,9 @@ describe("manual everyday workflow catalog", () => {
(e) =>
e.suite.id === "everyday-workflows" && e.environment.id === "daytona",
);
- expect(remote).toHaveLength(6);
+ expect(remote).toHaveLength(8);
expect(new Set(remote.map((e) => e.task.id))).toEqual(
- new Set(["build-revise", "delegate-feedback", "recover-controller"]),
+ new Set(["build-revise", "delegate-feedback", "recover-controller", "create-skill-studio"]),
);
});
});
diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx
index e02023d782..e87e7b87d4 100644
--- a/ui/src/components/TaskChatThread.tsx
+++ b/ui/src/components/TaskChatThread.tsx
@@ -1,5 +1,6 @@
import type { ActivityEvent } from "@paperclipai/shared";
import { useProjectCreatedItems } from "@/hooks/useProjectCreatedItems";
+import { skillCreatedItems } from "@/components/task-chat/skill-created-items";
import { requiresExecutionReconciliation } from "@paperclipai/shared";
import { TaskChatExpansionState } from "@/components/task-chat/expansion-state";
import { TaskChatScrollReady } from "@/components/task-chat/scroll-navigation";
@@ -401,6 +402,7 @@ export type TaskChatThreadProps = ComponentProps<typeof IssueChatThread> & {
initialHistoryPending?: boolean;
initialHistoryError?: boolean;
onRetryInitialHistory?: () => void;
+ onOpenSkill?: (skillId: string, name: string) => void;
};
type PendingComposerInput =
@@ -539,6 +541,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
liveIssueIds,
onResumeAssignee,
resumeAssigneePending = false,
+ onOpenSkill,
} = props;
const retryFailedRunHandler =
isTerminalIssueStatus(issueStatus) ||
@@ -574,6 +577,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
const canRetryFailedRun = Boolean(retryFailedRunHandler);
const queryClient = useQueryClient();
const createdProjectItems = useProjectCreatedItems(props.creationActivity ?? [], companyId);
+ const createdSkillItems = useMemo(() => skillCreatedItems(props.creationActivity ?? []), [props.creationActivity]);
const [pendingComposerAssignee, setPendingComposerAssignee] = useState<
string | null
>(null);
@@ -1308,11 +1312,15 @@ export function TaskChatThread(props: TaskChatThreadProps) {
for (const item of createdProjectItems) {
entries.push({ id: item.id, item, ms: toMs(item.timestamp), order: 2 });
}
+ for (const item of createdSkillItems) {
+ entries.push({ id: item.id, item, ms: toMs(item.timestamp), order: 2 });
+ }
return entries.sort(
(a, b) => a.ms - b.ms || a.order - b.order || a.id.localeCompare(b.id),
);
}, [
createdProjectItems,
+ createdSkillItems,
comments,
projectedComments,
commentItems,
@@ -2832,6 +2840,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
}
onRetryFailedRun={retryFailedRunHandler}
retryFailedRunId={retryFailedRunId}
+ onOpenSkill={onOpenSkill}
tail={
tailRunId ||
optimisticRunnerStartup ||
diff --git a/ui/src/components/task-chat/TaskChatSkillCreatedCard.test.tsx b/ui/src/components/task-chat/TaskChatSkillCreatedCard.test.tsx
new file mode 100644
index 0000000000..96736d75e9
--- /dev/null
+++ b/ui/src/components/task-chat/TaskChatSkillCreatedCard.test.tsx
@@ -0,0 +1,20 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import { TaskChatSkillCreatedCard } from "./TaskChatSkillCreatedCard";
+
+describe("TaskChatSkillCreatedCard", () => {
+ it("opens the persisted skill when clicked", () => {
+ const onOpen = vi.fn();
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ act(() => root.render(<TaskChatSkillCreatedCard item={{ id: "skill-created:1", kind: "skill_created", skillId: "skill-1", name: "Release helper", timestamp: "2026-09-16T12:00:00Z" }} onOpen={onOpen} />));
+ act(() => (container.querySelector("button") as HTMLButtonElement).click());
+ expect(onOpen).toHaveBeenCalledWith("skill-1", "Release helper");
+ act(() => root.unmount());
+ container.remove();
+ });
+});
diff --git a/ui/src/components/task-chat/TaskChatSkillCreatedCard.tsx b/ui/src/components/task-chat/TaskChatSkillCreatedCard.tsx
new file mode 100644
index 0000000000..8018ce926d
--- /dev/null
+++ b/ui/src/components/task-chat/TaskChatSkillCreatedCard.tsx
@@ -0,0 +1,17 @@
+import { Wrench } from "lucide-react";
+import type { TaskChatSkillCreatedItem } from "./task-chat-model";
+
+export function TaskChatSkillCreatedCard({ item, onOpen }: { item: TaskChatSkillCreatedItem; onOpen?: (skillId: string, name: string) => void }) {
+ return (
+ <article className="rounded-lg border border-border bg-card p-3" aria-label={`Skill created: ${item.name}`}>
+ <button type="button" className="flex w-full items-start gap-3 text-left" onClick={() => onOpen?.(item.skillId, item.name)}>
+ <Wrench className="mt-0.5 size-4 shrink-0 text-muted-foreground" aria-hidden />
+ <span className="min-w-0 flex-1 space-y-1">
+ <span className="block text-xs text-muted-foreground">Skill created</span>
+ <span className="block break-words text-sm font-medium hover:underline focus-visible:underline">{item.name}</span>
+ {item.description ? <span className="block line-clamp-3 text-sm text-muted-foreground">{item.description}</span> : null}
+ </span>
+ </button>
+ </article>
+ );
+}
diff --git a/ui/src/components/task-chat/TaskChatThreadView.tsx b/ui/src/components/task-chat/TaskChatThreadView.tsx
index 372ce7d051..1ac28528fd 100644
--- a/ui/src/components/task-chat/TaskChatThreadView.tsx
+++ b/ui/src/components/task-chat/TaskChatThreadView.tsx
@@ -1,4 +1,5 @@
import { TaskChatProjectCreatedCard } from "./TaskChatProjectCreatedCard";
+import { TaskChatSkillCreatedCard } from "./TaskChatSkillCreatedCard";
import { useMemo, type ReactNode } from "react";
import type { IssueAttachment } from "@paperclipai/shared";
import { cn } from "@/lib/utils";
@@ -72,6 +73,7 @@ interface TaskChatThreadViewProps {
/** When false, render the list without the scroll container (e.g. previews). */
scroll?: boolean;
attachments?: IssueAttachment[];
+ onOpenSkill?: (skillId: string, name: string) => void;
}
function renderItem(
@@ -92,9 +94,11 @@ function renderItem(
onRetryFailedRun?: (runId: string) => Promise<void> | void,
retryFailedRunId?: string | null,
attachments: IssueAttachment[] = [],
+ onOpenSkill?: (skillId: string, name: string) => void,
) {
switch (item.kind) {
case "project_created": return <TaskChatProjectCreatedCard item={item} />;
+ case "skill_created": return <TaskChatSkillCreatedCard item={item} onOpen={onOpenSkill} />;
case "message": {
// Compute the actions once: the bubble renders them for a runless reply
// (footer = actions + timestamp), while an attached turn hands them to
@@ -132,6 +136,7 @@ function renderItem(
undefined,
undefined,
attachments,
+ onOpenSkill,
)
}
/>
@@ -235,6 +240,7 @@ function renderItem(
undefined,
undefined,
attachments,
+ onOpenSkill,
)
}
/>
@@ -300,6 +306,7 @@ export function TaskChatThreadView({
className,
scroll = true,
attachments = EMPTY_ATTACHMENTS,
+ onOpenSkill,
}: TaskChatThreadViewProps) {
const streamlined = useStreamlinedTaskChatPresentation();
const retryableMarkerId =
@@ -335,6 +342,7 @@ export function TaskChatThreadView({
onRetryFailedRun,
retryFailedRunId,
attachments,
+ onOpenSkill,
),
}))
.filter((entry) => entry.content !== null)
@@ -402,7 +410,7 @@ export function TaskChatThreadView({
items, streamlined, onApprovalDecision, onRuntimeRequestDecision,
renderInteraction, renderBrief, renderMessageActions, renderQueuedAction,
onTryAgainNoLiveExecutionPath, tryAgainNoLiveExecutionPathPending,
- retryableMarkerId, onRetryFailedRun, retryFailedRunId, attachments,
+ retryableMarkerId, onRetryFailedRun, retryFailedRunId, attachments, onOpenSkill,
]);
const body = (
<div
diff --git a/ui/src/components/task-chat/skill-created-items.test.ts b/ui/src/components/task-chat/skill-created-items.test.ts
new file mode 100644
index 0000000000..5dbdd940ce
--- /dev/null
+++ b/ui/src/components/task-chat/skill-created-items.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import type { ActivityEvent } from "@paperclipai/shared";
+import { skillCreatedItems } from "./skill-created-items";
+
+const event = (overrides: Partial<ActivityEvent> = {}): ActivityEvent => ({
+ id: "activity",
+ companyId: "company",
+ actorType: "agent",
+ actorId: "agent",
+ action: "company.skill_created",
+ entityType: "company_skill",
+ entityId: "skill",
+ createdAt: new Date("2026-09-16T12:00:00Z"),
+ details: { name: "Release helper", description: "Ships releases.", slug: "release-helper", versionId: "version" },
+ ...overrides,
+} as ActivityEvent);
+
+describe("durable skill creation feed", () => {
+ it("deduplicates repeated persisted receipts and keeps metadata", () => {
+ expect(skillCreatedItems([event(), event({ id: "replay" })])).toEqual([expect.objectContaining({
+ id: "skill-created:skill", kind: "skill_created", skillId: "skill", name: "Release helper", slug: "release-helper", versionId: "version",
+ })]);
+ });
+
+ it("ignores unrelated activity and malformed receipts", () => {
+ expect(skillCreatedItems([event({ action: "issue.comment_added" }), event({ details: {} })])).toEqual([]);
+ });
+});
diff --git a/ui/src/components/task-chat/skill-created-items.ts b/ui/src/components/task-chat/skill-created-items.ts
new file mode 100644
index 0000000000..18af534d4e
--- /dev/null
+++ b/ui/src/components/task-chat/skill-created-items.ts
@@ -0,0 +1,22 @@
+import type { ActivityEvent } from "@paperclipai/shared";
+import type { TaskChatSkillCreatedItem } from "./task-chat-model";
+
+export function skillCreatedItems(events: readonly ActivityEvent[]): TaskChatSkillCreatedItem[] {
+ const seen = new Set<string>();
+ return events.flatMap((event) => {
+ if (event.action !== "company.skill_created" || event.entityType !== "company_skill" || seen.has(event.entityId)) return [];
+ const details = event.details ?? {};
+ if (typeof details.name !== "string") return [];
+ seen.add(event.entityId);
+ return [{
+ id: `skill-created:${event.entityId}`,
+ kind: "skill_created" as const,
+ skillId: event.entityId,
+ name: details.name,
+ description: typeof details.description === "string" ? details.description : null,
+ slug: typeof details.slug === "string" ? details.slug : null,
+ versionId: typeof details.versionId === "string" ? details.versionId : null,
+ timestamp: new Date(event.createdAt).toISOString(),
+ }];
+ });
+}
diff --git a/ui/src/components/task-chat/task-chat-model.ts b/ui/src/components/task-chat/task-chat-model.ts
index e489d98034..057fa7799f 100644
--- a/ui/src/components/task-chat/task-chat-model.ts
+++ b/ui/src/components/task-chat/task-chat-model.ts
@@ -542,8 +542,20 @@ export interface TaskChatProjectCreatedItem {
timestamp: string;
}
+export interface TaskChatSkillCreatedItem {
+ id: string;
+ kind: "skill_created";
+ skillId: string;
+ name: string;
+ description?: string | null;
+ slug?: string | null;
+ versionId?: string | null;
+ timestamp: string;
+}
+
export type TaskChatItem =
| TaskChatProjectCreatedItem
+ | TaskChatSkillCreatedItem
| TaskChatMessageItem
| TaskChatThinkingItem
| TaskChatToolItem
diff --git a/ui/src/components/task-side-panel/TaskSidePanel.tsx b/ui/src/components/task-side-panel/TaskSidePanel.tsx
index 86fe5b481d..a9e9617f8a 100644
--- a/ui/src/components/task-side-panel/TaskSidePanel.tsx
+++ b/ui/src/components/task-side-panel/TaskSidePanel.tsx
@@ -65,6 +65,7 @@ import {
taskPanelDocumentTab,
taskPanelFilesTab,
taskPanelPropertiesTab,
+ taskPanelSkillTab,
taskPanelSubtasksTab,
taskPanelWorkspaceFileTab,
writeTaskSidePanelState,
@@ -73,6 +74,7 @@ import {
import { cn } from "@/lib/utils";
import { TaskDocumentPanel } from "./TaskDocumentPanel";
import { TaskWorkspaceFilePanel } from "./TaskWorkspaceFilePanel";
+import { TaskSkillPanel } from "./TaskSkillPanel";
export interface TaskSidePanelProps {
issue: Issue;
@@ -99,6 +101,9 @@ export interface TaskSidePanelProps {
showSubtasksTab?: boolean;
/** Optional related-work projection; the host still owns tab layout and state. */
tasksTab?: { count: number; content: ReactNode; hasError?: boolean };
+ openSkillId?: string | null;
+ openSkillName?: string | null;
+ onSkillOpened?: (skillId: string) => void;
}
const EMPTY_ISSUE_DOCUMENTS: IssueDocument[] = [];
@@ -231,6 +236,9 @@ export function TaskSidePanel({
streamlinedTabs = false,
showSubtasksTab = false,
tasksTab,
+ openSkillId,
+ openSkillName,
+ onSkillOpened,
}: TaskSidePanelProps) {
const handleScroll = useScrollbarWhileScrolling();
const viewer = useTaskSidePanelFileRouting();
@@ -285,6 +293,13 @@ export function TaskSidePanel({
const subtasksAvailable = showSubtasksTab && (taskCount > 0 || tasksTab?.hasError === true);
const hasSubtasksTab = controller.tabs.some((tab) => tab.id === "subtasks");
+ useEffect(() => {
+ if (!openSkillId) return;
+ setLauncherOpen(false);
+ controller.openTab(taskPanelSkillTab(openSkillId, openSkillName ?? "Skill"));
+ onSkillOpened?.(openSkillId);
+ }, [controller.openTab, onSkillOpened, openSkillId, openSkillName]);
+
useEffect(() => {
if (!subtasksAvailable) {
subtasksDismissedRef.current = false;
@@ -649,6 +664,8 @@ export function TaskSidePanel({
initialDocument={documentByKey.get(activeTab.payload.documentKey)}
/>
);
+ } else if (activeTab.payload.kind === "skill") {
+ content = <TaskSkillPanel companyId={issue.companyId} skillId={activeTab.payload.skillId} />;
} else if (activeTab.payload.kind === "files-browser") {
content = (
<WorkspaceFileBrowser
diff --git a/ui/src/components/task-side-panel/TaskSkillPanel.test.tsx b/ui/src/components/task-side-panel/TaskSkillPanel.test.tsx
new file mode 100644
index 0000000000..ef2389bbcc
--- /dev/null
+++ b/ui/src/components/task-side-panel/TaskSkillPanel.test.tsx
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "@/api/client";
+import { companySkillsApi } from "@/api/companySkills";
+import { TaskSkillPanel } from "./TaskSkillPanel";
+
+const navigate = vi.fn();
+vi.mock("@/api/companySkills", () => ({ companySkillsApi: { detail: vi.fn() } }));
+vi.mock("@/lib/router", () => ({ useNavigate: () => navigate }));
+vi.mock("@/components/MarkdownBody", () => ({ MarkdownBody: ({ children }: { children: string }) => <div>{children}</div> }));
+
+const skill = { id: "skill-1", name: "Release helper", slug: "release-helper", description: "Ships releases.", markdown: "---\nname: release-helper\ndescription: Ships releases.\n---\n\n# Instructions\n\nRun the release.", currentVersion: { revisionNumber: 2 } } as never;
+let root: ReturnType<typeof createRoot>;
+let container: HTMLDivElement;
+let client: QueryClient;
+
+function renderPanel() {
+ act(() => root.render(<QueryClientProvider client={client}><TaskSkillPanel companyId="company-1" skillId="skill-1" /></QueryClientProvider>));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+});
+afterEach(() => {
+ act(() => root.unmount());
+ client.clear();
+ container.remove();
+});
+
+describe("TaskSkillPanel", () => {
+ it("renders a missing state for 404", async () => {
+ vi.mocked(companySkillsApi.detail).mockRejectedValue(new ApiError("missing", 404, null));
+ renderPanel();
+ await vi.waitFor(() => expect(container.textContent).toContain("Skill no longer available"));
+ expect(container.querySelector("button")).toBeNull();
+ });
+
+ it("offers retry for transient errors", async () => {
+ vi.mocked(companySkillsApi.detail).mockRejectedValueOnce(new Error("offline")).mockResolvedValue(skill);
+ renderPanel();
+ await vi.waitFor(() => expect(container.textContent).toContain("The skill could not be loaded"));
+ act(() => (container.querySelector("button") as HTMLButtonElement).click());
+ await vi.waitFor(() => expect(container.textContent).toContain("Release helper"));
+ expect(container.textContent).toContain("Run the release.");
+ expect(container.textContent).not.toContain("name: release-helper");
+ });
+
+ it("opens the current skill in Skill Studio", async () => {
+ vi.mocked(companySkillsApi.detail).mockResolvedValue(skill);
+ renderPanel();
+ await vi.waitFor(() => expect(container.textContent).toContain("Release helper"));
+ act(() => (container.querySelector("button") as HTMLButtonElement).click());
+ expect(navigate).toHaveBeenCalledWith("/skills/studio/skill-1");
+ });
+});
diff --git a/ui/src/components/task-side-panel/TaskSkillPanel.tsx b/ui/src/components/task-side-panel/TaskSkillPanel.tsx
new file mode 100644
index 0000000000..fe5d2ba653
--- /dev/null
+++ b/ui/src/components/task-side-panel/TaskSkillPanel.tsx
@@ -0,0 +1,81 @@
+import { useQuery } from "@tanstack/react-query";
+import { ExternalLink, FileText, Loader2, Wrench } from "lucide-react";
+import { companySkillsApi } from "@/api/companySkills";
+import { ApiError } from "@/api/client";
+import { MarkdownBody } from "@/components/MarkdownBody";
+import { Button } from "@/components/ui/button";
+import { queryKeys } from "@/lib/queryKeys";
+import { useNavigate } from "@/lib/router";
+import { parseFrontmatterMarkdown } from "@paperclipai/shared";
+
+export function TaskSkillPanel({ companyId, skillId }: { companyId: string; skillId: string }) {
+ const navigate = useNavigate();
+ const query = useQuery({
+ queryKey: queryKeys.companySkills.detail(companyId, skillId),
+ queryFn: () => companySkillsApi.detail(companyId, skillId),
+ retry: false,
+ refetchOnWindowFocus: true,
+ refetchOnMount: "always",
+ });
+ if (query.isLoading) {
+ return (
+ <div className="flex items-center gap-2 py-8 text-sm text-muted-foreground" role="status">
+ <Loader2 className="size-4 animate-spin" aria-hidden />
+ Loading skill…
+ </div>
+ );
+ }
+ if (query.isError) {
+ const status = query.error instanceof ApiError ? query.error.status : null;
+ if (status === 404) {
+ return <div className="py-8 text-sm text-muted-foreground" role="status">Skill no longer available.</div>;
+ }
+ if (status === 403) {
+ return <div className="py-8 text-sm text-muted-foreground" role="alert">You do not have access to this skill.</div>;
+ }
+ return (
+ <div className="space-y-3 py-8 text-sm text-muted-foreground" role="alert">
+ <p>The skill could not be loaded.</p>
+ <Button variant="outline" size="sm" onClick={() => void query.refetch()} disabled={query.isFetching}>
+ {query.isFetching ? "Retrying…" : "Retry"}
+ </Button>
+ </div>
+ );
+ }
+ if (!query.data) {
+ return <div className="py-8 text-sm text-muted-foreground" role="status">Skill no longer available.</div>;
+ }
+ const skill = query.data;
+ const previewMarkdown = parseFrontmatterMarkdown(skill.markdown).body;
+ return (
+ <article className="space-y-4">
+ <header className="space-y-2">
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <Wrench className="size-4 text-muted-foreground" aria-hidden />
+ <h2 className="text-lg font-semibold">{skill.name}</h2>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => navigate(`/skills/studio/${encodeURIComponent(skill.id)}`)}
+ >
+ <ExternalLink className="mr-1.5 size-3.5" aria-hidden />
+ Open in Skill Studio
+ </Button>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {skill.slug} · {skill.currentVersion ? `Revision ${skill.currentVersion.revisionNumber}` : "Current version"}
+ </p>
+ </header>
+ {skill.description ? <p className="text-sm text-muted-foreground">{skill.description}</p> : null}
+ <section className="space-y-2">
+ <h3 className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
+ <FileText className="size-3.5" aria-hidden />
+ Skill instructions
+ </h3>
+ <MarkdownBody>{previewMarkdown || "Skill instructions are empty."}</MarkdownBody>
+ </section>
+ </article>
+ );
+}
diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts
index 8626bb3f32..08f041a15c 100644
--- a/ui/src/context/LiveUpdatesProvider.test.ts
+++ b/ui/src/context/LiveUpdatesProvider.test.ts
@@ -16,6 +16,17 @@ import { __liveUpdatesTestUtils } from "./LiveUpdatesProvider";
import { queryKeys } from "../lib/queryKeys";
describe("LiveUpdatesProvider issue invalidation", () => {
+ it("refreshes the source task activity when a company skill is created", () => {
+ const client = new QueryClient();
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+ __liveUpdatesTestUtils.invalidateActivityQueries(client, "company-1", {
+ entityType: "company_skill", entityId: "skill-1", action: "company.skill_created",
+ details: { sourceIssueId: "issue-1" },
+ }, { userId: "user-1", agentId: null });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.issues.activity("issue-1") });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.companySkills.detail("company-1", "skill-1") });
+ client.clear();
+ });
it.each(["issue.attachment_added", "issue.attachment_removed", "issue.work_product_created", "issue.work_product_updated"])("refreshes visible delivered files for %s", action => {
const client = new QueryClient();
client.setQueryData(queryKeys.issues.detail("issue-1"), { id: "issue-1", companyId: "company-1", identifier: "PAP-1" });
diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx
index d0ee89f2b8..d6f365e9c5 100644
--- a/ui/src/context/LiveUpdatesProvider.tsx
+++ b/ui/src/context/LiveUpdatesProvider.tsx
@@ -1448,6 +1448,14 @@ function invalidateActivityQueries(
return;
}
+ if (entityType === "company_skill") {
+ const sourceIssueId = readString((payload.details as Record<string, unknown> | undefined)?.sourceIssueId);
+ if (sourceIssueId) queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(sourceIssueId) });
+ if (entityId) queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(companyId, entityId) });
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(companyId) });
+ return;
+ }
+
if (entityType === "goal") {
queryClient.invalidateQueries({
queryKey: queryKeys.goals.list(companyId),
diff --git a/ui/src/lib/task-side-panel-state.test.ts b/ui/src/lib/task-side-panel-state.test.ts
index efe4c30f8d..7cc2b4eb8e 100644
--- a/ui/src/lib/task-side-panel-state.test.ts
+++ b/ui/src/lib/task-side-panel-state.test.ts
@@ -6,8 +6,11 @@ import {
taskPanelDocumentTab,
taskPanelFilesTab,
taskPanelPropertiesTab,
+ taskPanelSkillTab,
taskPanelSubtasksTab,
writeTaskSidePanelState,
+ shouldSuppressTaskPanelUntilPlan,
+ openSkillPanelState,
} from "./task-side-panel-state";
describe("task side-panel persistence", () => {
@@ -27,6 +30,28 @@ describe("task side-panel persistence", () => {
});
});
+ it("persists and restores a skill tab", () => {
+ writeTaskSidePanelState("user-1", "company-1", "task-skill", {
+ state: { tabs: [taskPanelPropertiesTab(), taskPanelSkillTab("skill-1", "Release helper")], activeTabId: "skill:skill-1" },
+ launcherOpen: false,
+ userInteracted: true,
+ autoPlanHandled: false,
+ updatedAt: 1,
+ });
+ expect(readTaskSidePanelState("user-1", "company-1", "task-skill", true)?.state).toMatchObject({
+ activeTabId: "skill:skill-1",
+ tabs: [{ id: "properties" }, { id: "skill:skill-1", payload: { kind: "skill", skillId: "skill-1" } }],
+ });
+ });
+
+ it("keeps an onboarding panel open after skill acknowledgement", () => {
+ const before = { panelBeforePlanOverrideIssueId: null };
+ const opened = openSkillPanelState(before, { id: "skill-1", name: "Release helper" }, "task-1", true);
+ expect(opened.panelBeforePlanOverrideIssueId).toBe("task-1");
+ const acknowledged = { ...opened, skill: null };
+ expect(shouldSuppressTaskPanelUntilPlan({ deferredPlanAvailable: false, panelBeforePlanOverride: acknowledged.panelBeforePlanOverrideIssueId === "task-1" })).toBe(false);
+ });
+
it("isolates account and company state", () => {
writeTaskSidePanelState("user-1", "company-1", "task-1", {
state: { tabs: [taskPanelPropertiesTab()], activeTabId: "properties" },
diff --git a/ui/src/lib/task-side-panel-state.ts b/ui/src/lib/task-side-panel-state.ts
index ce5eafb7c8..a1576d832d 100644
--- a/ui/src/lib/task-side-panel-state.ts
+++ b/ui/src/lib/task-side-panel-state.ts
@@ -4,10 +4,36 @@ import type { SidePanelTabRecord, SidePanelTabsState } from "@/components/side-p
const STORAGE_VERSION = 1;
const MAX_TASK_STATES = 50;
+export function shouldSuppressTaskPanelUntilPlan(input: {
+ deferredPlanAvailable: boolean;
+ panelBeforePlanOverride: boolean;
+}) {
+ return !input.deferredPlanAvailable && !input.panelBeforePlanOverride;
+}
+
+export interface OpenSkillPanelState {
+ skill: { id: string; name: string };
+ panelBeforePlanOverrideIssueId: string | null;
+}
+
+export function openSkillPanelState(
+ current: Pick<OpenSkillPanelState, "panelBeforePlanOverrideIssueId">,
+ skill: { id: string; name: string },
+ issueId: string | null,
+ panelSuppressedUntilPlan: boolean,
+): OpenSkillPanelState {
+ return {
+ skill,
+ panelBeforePlanOverrideIssueId:
+ panelSuppressedUntilPlan && issueId ? issueId : current.panelBeforePlanOverrideIssueId,
+ };
+}
+
export type TaskSidePanelTabPayload =
| { kind: "properties" }
| { kind: "subtasks" }
| { kind: "artifacts" }
+ | { kind: "skill"; skillId: string }
| { kind: "issue-document"; documentKey: string }
| {
kind: "files-browser";
@@ -65,6 +91,9 @@ function parsePayload(value: unknown): TaskSidePanelTabPayload | null {
if (kind === "properties") return { kind };
if (kind === "subtasks") return { kind };
if (kind === "artifacts") return { kind };
+ if (kind === "skill") {
+ return typeof input.skillId === "string" && input.skillId.length > 0 ? { kind, skillId: input.skillId } : null;
+ }
if (kind === "issue-document") {
return typeof input.documentKey === "string" && input.documentKey.length > 0
? { kind, documentKey: input.documentKey }
@@ -194,6 +223,10 @@ export function taskPanelArtifactsTab(): SidePanelTabRecord<TaskSidePanelTabPayl
return { id: "artifacts", type: "artifacts", label: "Artifacts", closable: true, contentMode: "padded", payload: { kind: "artifacts" } };
}
+export function taskPanelSkillTab(skillId: string, label = "Skill"): SidePanelTabRecord<TaskSidePanelTabPayload> {
+ return { id: `skill:${skillId}`, type: "skill", label, closable: true, contentMode: "prose", payload: { kind: "skill", skillId } };
+}
+
export function taskPanelDocumentTab(documentKey: string, label: string): SidePanelTabRecord<TaskSidePanelTabPayload> {
return {
id: `document:${documentKey}`,
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index f4c3bb53bb..0cc45cb507 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -288,6 +288,7 @@ import { Textarea } from "@/components/ui/textarea";
import { formatIssueActivityAction } from "@/lib/activity-format";
import { copyTextToClipboard } from "../lib/clipboard";
import { buildIssuePropertiesPanelKey } from "../lib/issue-properties-panel-key";
+import { openSkillPanelState, shouldSuppressTaskPanelUntilPlan } from "../lib/task-side-panel-state";
import {
buildAnsweredQuestionsDeliveryText,
buildIssueThreadInteractionSummary,
@@ -1181,6 +1182,7 @@ function InboxMobileToolbar({
}
type IssueDetailChatTabProps = {
+ onOpenSkill?: (skillId: string, name: string) => void;
issueId: string;
companyId: string;
projectId: string | null;
@@ -1329,6 +1331,7 @@ type IssueDetailChatTabProps = {
};
const IssueDetailChatTab = memo(function IssueDetailChatTab({
+ onOpenSkill,
issueId,
companyId,
projectId,
@@ -2315,6 +2318,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
<ThreadComponent
key={conversationMode ? draftKey : issueId}
{...(!classicTaskInterfaceEnabled ? { creationActivity: resolvedActivity } : {})}
+ onOpenSkill={onOpenSkill}
initialHistoryPending={!!issueId && (
initialHistoryPending ||
commentsInitialLoading ||
@@ -2897,6 +2901,10 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
requestId: number;
handled?: boolean;
} | null>(null);
+ const [openSkill, setOpenSkill] = useState<{ id: string; name: string } | null>(null);
+ const handleSkillOpened = useCallback((skillId: string) => {
+ setOpenSkill((current) => current?.id === skillId ? null : current);
+ }, []);
const [documentDeepLink, setDocumentDeepLink] = useState<
(IssuePropertiesDocumentDeepLink & { issueId: string }) | null
>(null);
@@ -3576,14 +3584,26 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
panelBeforePlanOverrideIssueId === issue?.id;
const suppressPanelUntilPlan =
shouldDeferPanelUntilPlan &&
- !deferredPanelPlanDoc &&
- !panelBeforePlanOverride;
+ shouldSuppressTaskPanelUntilPlan({
+ deferredPlanAvailable: Boolean(deferredPanelPlanDoc),
+ panelBeforePlanOverride,
+ });
const openTaskSidePanel = useCallback(() => {
if (suppressPanelUntilPlan && issue?.id) {
setPanelBeforePlanOverrideIssueId(issue.id);
}
setPanelVisible(true);
}, [issue?.id, setPanelVisible, suppressPanelUntilPlan]);
+ const handleOpenSkill = useCallback((skillId: string, name: string) => {
+ const next = openSkillPanelState(
+ { panelBeforePlanOverrideIssueId },
+ { id: skillId, name }, issue?.id ?? null, suppressPanelUntilPlan,
+ );
+ setOpenSkill(next.skill);
+ setPanelBeforePlanOverrideIssueId(next.panelBeforePlanOverrideIssueId);
+ setPanelVisible(true);
+ if (isMobile) setMobilePropsOpen(true);
+ }, [isMobile, issue?.id, panelBeforePlanOverrideIssueId, setPanelVisible, suppressPanelUntilPlan]);
const revealNewArtifact = useCallback(() => {
if (!issue?.id) return;
setDocumentDeepLink(null);
@@ -5599,6 +5619,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
checkingMonitorNow: checkIssueMonitorNow.isPending,
documentDeepLink:
documentDeepLink?.issueId === panelIssue.id ? documentDeepLink : null,
+ openSkillId: openSkill?.id ?? null,
+ openSkillName: openSkill?.name ?? null,
+ onSkillOpened: handleSkillOpened,
};
if (taskChatShellEnabled) {
openPanel(
@@ -5633,6 +5656,8 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
issuePanelKey,
openNewSubIssue,
openPanel,
+ openSkill,
+ handleSkillOpened,
panelChildIssues,
panelIssue,
suppressPanelUntilPlan,
@@ -7664,6 +7689,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
)}
{resolvedDetailTab === "chat" ? (
<IssueDetailChatTab
+ onOpenSkill={handleOpenSkill}
threadHeader={<>{taskChatThreadHeader}{instanceExperimentalSettings?.enableChatConnectors && <EmailTaskActivity key={issue.id} companyId={issue.companyId} issueId={issue.id} />}</>}
issueBrief={
// Suppress the seeded-description bubble for the onboarding first
@@ -8095,6 +8121,9 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
artifactsOpenRequestId={isMobile && !artifactsOpenRequest?.handled && artifactsOpenRequest?.issueId === issue.id
? artifactsOpenRequest.requestId : undefined}
onArtifactsOpened={handleArtifactsOpened}
+ openSkillId={openSkill?.id ?? null}
+ openSkillName={openSkill?.name ?? null}
+ onSkillOpened={handleSkillOpened}
documentDeepLink={
documentDeepLink?.issueId === issue.id
? documentDeepLink