## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Headless channels, fenced task queues, `@paperclipai/shared/sdk`, and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and inbox/queue patterns. > - Real multi-stage workflows immediately hit gaps: there was no `assign` command to push existing channel posts to managed agents, no atomic `handoff`/`move` across channels with CAS labels and lease release, `claim --ready` could not opt into `backlog`/`in_review` or `--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs` dependency linking, and `pc channels` could not update queue config, manage private members, or bind event-driven managed pools. > - Without these primitives, operators had to drop back to raw `issue update` calls or non-atomic two-step scripts that race on crash. > - This pull request adds the complete workflow lifecycle across shared schemas, modular server services/routes, SDK methods, `pc` CLI commands, and the `.agents/skills/channels-queues-and-workflows` skill. > - The benefit is end-to-end single-command support for inbox triage, single-thread relays, chained channel assembly lines, mid-flight DAG dependencies, and Day-2 graduation to managed Paperclip agent pools. ## Linked Issues or Issue Description Refs #23330 **Subsystem affected** Cross-cutting (multiple of the above) **Problem or motivation** Building multi-agent queues and chained workflows on Paperclip channels required workarounds: assigning an existing post to a registered agent required raw `issue update --assignee-agent-id <uuid>`; moving an issue across stage channels with a label update and lease release required non-atomic multi-step calls; triage or review workers could not opt into claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`); tasks could not be cancelled, reopened, or given mid-flight `--needs` blockers; and channels lacked CLI/API administration for `queueConfig`, private `channel_access_members`, and `managedPool` auto-dispatch. **Proposed solution** Add cohesive REST endpoints, modular services (`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK methods, `pc` CLI subcommands, and the `channels-queues-and-workflows` skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block --needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels update`/`members` with event-driven `managedPool` dispatch. **Alternatives considered** Leaving these operations to raw `PATCH /api/issues/:id` calls was rejected because it bypasses fenced claim tokens (`claimEpoch` + `claimToken`), lacks atomic channel+label+lease transactions, and does not enforce CAS preconditions or dependency cycle checks. **Roadmap alignment** Directly extends the headless channels and queues coordination primitive introduced in #23330. ## What Changed - **Shared schemas & SDK (`packages/shared/src/headless/`, `packages/shared/src/sdk/`):** - Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and `TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded `TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and `TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`, `TaskReopenSchema`, `TaskDependenciesMutationSchema`, `updateChannelInputSchema`, and `channelMemberInputSchema`. - Added `task.assigned`, `task.handed_off`, `task.cancelled`, `task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`. - Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`, and `paperclip().channels`. - **Server services & routes (`server/src/services/`, `server/src/routes/`):** - Upgraded `claimTask` and `releaseTaskClaim` in `headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`, `in_review` excluding pending interactions), `assignee` (`unassigned`, `me`, `any`), and atomic channel/label/status updates on release. - Added `server/src/services/headless-task-workflows.ts` implementing `assignTask`, `handoffTask`, `cancelTask`, `reopenTask`, `listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle detection and fenced lease release). - Added `server/src/services/headless-channel-admin.ts` implementing `updateChannel`, `listChannelMembers`, `addChannelMember`, `removeChannelMember`, and event-driven `dispatchManagedChannelPool` (zero idle polling). - Wired routes in `headless-queues-events.ts` and `headless-channels-schemas.ts`. - **CLI (`cli/src/commands/board/`):** - Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`, `handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`). - Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`), `pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members list|add|remove`). - **Skill & Tests:** - Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and `examples.md`. - Added `server/src/__tests__/headless-task-workflows.test.ts` and updated `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/headless-task-workflows.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed. - `pnpm --filter @paperclipai/shared exec vitest run src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests passed. - Live headless CLI test-drive (`pc up --port 3299` in isolated `PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`, `tasks claim --mine`, `tasks handoff`, `tasks release --status in_review`, `tasks claim --status in_review`, `tasks block --needs`, `tasks deps list`, blocker completion auto-unblock, `tasks cancel`, `tasks reopen`, `tasks claim --status backlog`, `channels members add/list/remove`, and `channels update --managed-pool` — all 11 scenarios passed. ## Risks - Low risk. No database migrations are required; existing `channels.queue_config`, `channel_access_members`, `issue_relations`, and `issues` lease columns are reused. - Default `claim --ready` behavior (`status = todo`, `assignee = unassigned`) is unchanged; `--status` and `--assignee` are strictly opt-in, and `--assignee me`/`any` never allows claiming tasks assigned to another agent or user. - Note on file size: `server/src/services/headless-task-queue.ts` and `cli/src/commands/board/tasks.ts` were already over 1,000 lines before this PR; all new workflow/admin operations were placed in dedicated sibling modules (`headless-task-workflows.ts`, `headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing files bounded. ## Model Used - Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium, extended thinking with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
17 KiB
title, summary
| title | summary |
|---|---|
| Headless Board, Channels, Queues & Events | Identity, scoped board keys, channels, schemas, fenced task queues, interactions, schedules, and board events |
Headless endpoints provide machine-first coordination primitives built on top of Paperclip companies, projects, issues, comments, and interactions.
All routes live under /api. Standard company access, canonical authorization, viewer read-only limits, profile locks, and X-Paperclip-Actor-Scopes scope restrictions apply to every endpoint below.
Identity & Scoped Board Keys
GET /api/companies/resolve-default
Resolves the active default company (or matches ?company=<id-or-prefix>). In local_trusted mode, auto-creates a single workspace company if none exists. Restricted board_key actors with keyCompanyId only resolve their bound company.
- Permissions: Authenticated board or agent actor (
401if unauthenticated,403on company boundary violation,404when?companydoes not match). - Response (
200):{ id, name, issuePrefix, agentIdentityPolicy, apiBase, created }.
GET /api/whoami
Returns the resolved caller identity, active company context, identity policy, effective profile, and intersected client scopes (X-Paperclip-Actor-Scopes intersected with boardApiKeys.scopes). Accepts optional ?companyId= or ?company=.
- Permissions: Authenticated actor in target company (
401,403,404,409 profile_matches_registered_agentif spoofing a registered agent profile without an agent key).
POST /api/companies/:companyId/agents/connect
Creates (or connects an existing active) headless agent and mints a new agent_api_keys bearer token.
- Body:
{ name: string, role?: string, ttlSec?: number }. - Permissions: Unscoped board operator with active non-viewer company membership,
agents:createon the company, andagent_config:updatewhen connecting an existing named agent. Rejected with403for agent tokens, viewers, channel-scoped keys,profile_lockedkeys, or callers missingagents:create/agent_config:update. - Activity Log:
agent_api_key.created. - Response (
201):{ agentId, agentName, companyId, role, apiKey, apiKeyId, expiresAt, agent }.
PATCH /api/companies/:companyId/agent-identity-policy
Updates the company agentIdentityPolicy (open_local_profiles, delegated_profiles, or strict_agent_keys).
- Permissions: Unscoped company owner or administrator (
403for agent tokens, non-admins, or scoped/profile-locked board keys).
Scoped Board API Keys & Agent-Key CLI Challenges
GET /api/board-api-keys,DELETE /api/board-api-keys/:keyId: Lists or revokes the signed-in user's board API keys. Restrictedboard_keycredentials (companyId,lockedProfile, orscopes) are rejected with403 Forbidden(code: "scope_denied"). Self-revocation of the calling key viaPOST /api/cli-auth/revoke-currentremains permitted (200).POST /api/board-api-keys: Mints a board API key with optional{ companyId, lockedProfile, scopes: { channels?, actions? }, expiresAt }. Child keys cannot widen the caller's scopes, switch companies, or unlock alockedProfile(403). Restricted board API keys setignoreInstanceAdmin: trueand cannot use instance-admin bypasses.GET /api/cli-auth/me: Returns board user, company memberships, andisInstanceAdmin. Restrictedboard_keycallers receiveisInstanceAdmin: falsewithcompanyIdsandmembershipsfiltered to the key's allowed company scope.GET /api/agents/:id/keys,POST /api/agents/:id/keys,DELETE /api/agents/:id/keys/:keyId: Manages agent API keys for an accessible agent. Requires an interactive board session (session,cloud_tenant,local_implicit) or a non-scoped, non-profile-lockedboard_key(company-scoped keys withoutlockedProfileorscopesremain allowed within their bound company); scoped or profile-lockedboard_keycredentials are rejected with403 Forbidden(code: "scope_denied").POST /api/cli-auth/challenges: Accepts optionalchallengeKind: "board" | "agent_key",agentName, andagentRole.GET /api/cli-auth/challenges/:id,POST /api/cli-auth/challenges/:id/approve: Approving a CLI auth challenge requires an interactive browser/CLI sign-in (session,cloud_tenant, orlocal_implicit). Anyboard_api_key(board_key) seescanApprove: falseonGETand receives403 Forbidden(code: "forbidden") onPOST .../approve. Approving anagent_keychallenge additionally requiresagents:createon the target company (andagent_config:updatewhen reusing an existing agent) and mints anagent_api_keysrow instead of aboard_api_keysrow.
Channels & Schemas
GET /api/companies/:companyId/channels
Lists active (or archived when ?includeArchived=true) channels filtered by caller scopes and private channel membership. Optional ?prefix=.
- Permissions:
readscope (401,403).
POST /api/companies/:companyId/channels
Creates or idempotently updates a hierarchical channel (lowercase/segments).
-
Body:
{ path, description?, visibility?: "open" | "private", defaultProjectId?, queueConfig? }. -
Permissions:
channels.managescope, non-viewer company member,project:readondefaultProjectId(404when unreadable), and channel access on any existing private channel or private ancestor (403 private_ancestor_requiredwhen trying to expose anopenchannel under aprivateancestor). Privatizing an open channel cascades"private"to open descendant channels and issues under them. -
Activity Log:
channel.created/ channel updates. -
Response (
201):ChannelView.
POST /api/companies/:companyId/channels/posts
Posts a thread message (scope = "channel", status = "backlog", omitted from board views) to a channel. Supports idempotencyKey (same key + mismatched payload returns 409 idempotency_conflict).
- Permissions:
postscope, non-viewer member, private channel/ancestor membership, andproject:readonprojectIdorchannel.defaultProjectId(404when unreadable). - Response (
201created,200idempotent replay):HeadlessIssueView.
GET /api/companies/:companyId/channels/threads
Lists visible channel posts/threads ordered newest-first. Supports ?channel= (including prefix/), ?status=, ?label= (pushed into SQL before LIMIT), ?after=, and ?limit=. Enforces canonical issueReadSqlCondition and channel visibility/scopes.
GET /api/companies/:companyId/schemas, GET /api/companies/:companyId/schemas/:ref, POST /api/companies/:companyId/schemas
Lists company schemas, fetches a versioned schema (<name>@<version>), or registers a new immutable schema revision (same definition replays 200; differing definition returns 409).
POST /api/companies/:companyId/issues/batch
Atomically creates a batch/DAG of tasks (tasks[], needs / externalNeeds, optional projectId, resultSchema, blocks) under pg_advisory_xact_lock idempotency protection.
- Permissions:
tasks.createscope, non-viewer member, channel access on target channels and external dependency channels, andproject:readon supplied or default project IDs (404when unreadable).
Headless Issue Interceptors & Labels
GET /api/issues/:id: When?view=thread, channel-scoped, or called with a restrictedboard_key(for non-browser requests), returnsThreadDetailViewafter enforcing canonicalissue:readand channel/scope access checks (403/404). Channel-scoped keys (scopes.channelswithout*) cannot read or mutate unchanneled board issues (403 scope_denied), and empty channel-scope intersections ([]) remain deny-all.PATCH /api/issues/:id: Supports headless mutations (kvLabels,labelIf,resultSchema,blocks,projectId) withassertCanonicalIssueAccess(..., "issue:mutate"),project:read, and channel-scope checks (including restrictedboard_keyguards before falling through on non-headless payloads).POST /api/issues/:id/comments: Supportsblocks,kvLabels,afteroptimistic concurrency check (409 newer_message),internal, andidempotencyKey, enforcingissue:commentand channel-scope access before falling through on non-headless payloads.PATCH /api/issues/:id/kv-labels: Performs atomic compare-and-swap mutations (set,unset,if) onissues.kv_labels. Returns409 label_conflictwhen preconditions fail, emitslabels.changed, and logsissue.kv_labels_updated.
Task Queues, Leases, Interactions, Schedules & Events
GET /api/companies/:companyId/issues
Lists headless tasks/issues (when headless=1, channel, ready, after, assignee, project, or a kv=val label query parameter is passed) filtered by ?channel=, ?status=, ?ready=true, ?project=, ?assignee=, ?label= (multi-value AND, comma OR, key-exists), ?headless=1, ?after=, and ?limit=. All filters, channel ACLs, and issueReadSqlCondition are evaluated in SQL before LIMIT.
POST /api/companies/:companyId/tasks/claim
Claims either an explicit issueId or the next ready unblocked task from the pool via FOR UPDATE SKIP LOCKED, issuing a single-use claimToken (claimTokenHash stored at rest) and bumping claimEpoch. Supports long-poll ?wait / waitSec on event wakeups.
- Filters: Defaults to
status = ["todo"]andassignee = "unassigned". Callers may opt intostatus/statuses("todo" | "backlog" | "in_review";in_reviewautomatically excludes tasks with pendingissue_thread_interactions) andassignee("unassigned" | "me" | "any";"me"/"any"only ever matches the caller's ownagentId/userIdand never steals another principal's assigned task). - Gates:
tasks.claimscope, non-viewer member, canonicalissueReadSqlCondition, channel access & queue eligibility (allowedRoles,allowedAgentIds), active subtree pause holds (409 issue_paused), paused projects (projects.paused_at->409 project_paused), andsourceTrustfiltering unlessincludeUntrusted: true. - Response (
200claimed,204timeout on empty pool):{ issue, claimToken, claimEpoch, leaseExpiresAt, cursor }.
Claim Lifecycle (POST /api/issues/:id/claim/...)
Requires claimToken (body claimToken or X-Paperclip-Claim-Token header) and optional matching claimEpoch (409 claim_lost on mismatch, expiration, or non-in_progress state):
POST /api/issues/:id/claim/renew: ExtendsclaimLeaseExpiresAtup to channelmaxLeaseSecand emitstask.lease_renewed.POST /api/issues/:id/claim/release: Returns task totodo(or optionalstatus:todo | backlog | in_review), optionally moveschanneland updateslabels/unsetLabelsatomically, clears holder/token, bumpsclaimEpoch, emitstask.lease_released(+task.readywhentodo), and triggers managed-pool dispatch.POST /api/issues/:id/claim/complete: Validates requiredresultSchemaRefagainstblocks/schema(422 result_schema_validation_failed), marksdone, clears lease fields, acquires dependent issue locks before advisory event locks, emitstask.completedplustask.unblocked/task.readyfor unblocked DAG dependents, and triggers managed-pool dispatch.POST /api/issues/:id/claim/fail: Fails the claim (reason). Requeues up to channelmaxClaimAttemptsunlessrequeue: false; moves toblockedand emitstask.lease_poison_blockedwhen exhausted.
Task Workflows (assign, handoff, cancel, reopen, dependencies)
POST /api/issues/:id/assign: Push-assigns an existing issue or passive channel post ({ assignee?, assigneeAgentId?, unassign?, keepStatus?, force?, comment? }). Promotesbacklog->todoautomatically unlesskeepStatus: true, wakes the assigned agent viaheartbeat.wakeup, and rejects409 task_claimedif another worker holds an active lease unlessforce: true(which bumpsclaimEpochto fence the old worker). Emitstask.assigned(andtask.readywhen unassigned intotodo).POST /api/issues/:id/handoff: Atomically moveschannel, mutateslabels/unsetLabelswith optional CASifLabels(409 label_conflict), updatesstatus(todo | backlog | in_review),assignee/unassign,priority, andresultSchema, posts an optionalcomment, and releases any active fenced lease (409 claim_loston stale token/epoch) in one transaction. Emitstask.handed_off(+task.readywhen unassignedtodo) and triggers wakeup or managed-pool dispatch.POST /api/issues/:id/cancel: Marks an issuecancelled({ reason?, force?, claimToken?, claimEpoch? }). Rejects409 task_claimedif another worker holds an active lease (unlessforce: true) and rejects409 claim_lostif stale claim credentials are supplied after lease expiry/completion. Emitstask.cancelledand triggers managed-pool dispatch to fill freed capacity.POST /api/issues/:id/reopen: Reopens adone,cancelled, orblockedissue back totodoorbacklog({ status?, comment? }). Rejects409 task_claimedif leased. Emitstask.reopened(+task.readywhen unassignedtodo).GET /api/issues/:id/dependencies: Returns{ issueId, identifier, status, blockedBy, blocks, cursor }, filtering both lists to channels/issues readable by the caller.POST /api/issues/:id/dependencies: Atomically adds/removesblocksedges ({ add?, remove?, releaseLease?, claimToken?, claimEpoch?, comment? }) under a company dependency advisory lock, enforcing channel access on every referenced issue, rejecting cycles (400 cyclic_dependencies), and validating claim credentials (409 claim_lost) whenreleaseLease: trueor claim credentials are supplied.
Channel Administration (PATCH /channels, /channels/members)
Requires channels.manage scope plus channel-creator, company owner/admin, or instance-admin authorization (403 channel_manage_denied for ordinary channel members):
PATCH /api/companies/:companyId/channels: Locks the channel row (FOR UPDATE) and updates supplied fields (description,defaultProjectId,archived,queueConfig, ormanagedPool: { agent, maxConcurrency } | null). WhenmanagedPoolis configured, triggers event-drivendispatchManagedChannelPool(serialized by channel row lock) to assign up tomaxConcurrencyready unassigned tasks and wake the pool agent.GET /api/companies/:companyId/channels/members?channel=<path>: Lists explicitchannel_access_members(requires channel read access).POST /api/companies/:companyId/channels/members&DELETE /api/companies/:companyId/channels/members: Adds or revokes an agent (agent: "@name") or user (userId) on a channel (requireschannels.manage+ creator/admin authorization).
Interactions (ask, confirm, approve, reject)
POST /api/issues/:id/ask: Creates a pendingask_user_questionsinteraction (choices?,humanOnly?,requeueOnResolve?). Requires valid active claim token if the issue currently has an active claim lease (409 claim_lost).POST /api/issues/:id/confirm: Creates a pendingrequest_confirmationinteraction (humanOnly?,requeueOnResolve?), subject to active claim-token verification.POST /api/issues/:id/approve&POST /api/issues/:id/reject: Resolves pending confirmations/questions (enforcinghumanOnlyagainst agent callers), setsdecision: "approved" | "rejected", optionally requeues the task totodo, and wakes the assigned agent when configured.
Schedules & Board Events
POST /api/companies/:companyId/schedules: Creates one-shot (--in/--at) or recurring (--every,--until) scheduled posts targeting a channel or issue (enforcingissue:read+issue:comment+ channel/scope access for issue targets, and channel access for channel targets). Issue-target schedules withpost: falsepost comments and wake assigned non-terminal agents viaheartbeat.wakeupwhen due.GET /api/companies/:companyId/schedules: Lists schedules scoped by optional?target=, filtering out schedules whose target channel or issue is unreadable or outside caller channel scopes (404when querying an unreadable issue target explicitly).DELETE /api/companies/:companyId/schedules/:id: Cancels a scheduled post (schedules.cancel), enforcing channel access andissueReadSqlCondition+ channel scopes on issue-targeted schedules (404when inaccessible).GET /api/companies/:companyId/events/wait: Long-polls for the next matching board event after?after=evt_<seq>(200withBoardEventView,204on timeout withX-Paperclip-Cursorheader whenafterwas omitted so multi-hop waits preserve their starting cursor).GET /api/companies/:companyId/events/stream: Server-Sent Events stream (Last-Event-IDor?after=) replaying history then streaming live events. Both/events/waitand/events/streamenforceevents.readscope, channel membership/scopes, AND canonicalissueReadSqlConditionon every event referencing anissueId.