<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Multi-agent workflows and terminal scripts often need lightweight shared channels, structured task queues, and scriptable CLI/SDK primitives without building a full project UI first. > - Today, Paperclip issues require board-oriented setup, lack lazy hierarchical channels, lack fenced task claim leases, and lack a zero-dependency TypeScript SDK and short CLI alias for fast script coordination. > - Without fenced leases, blocking queue claims, CAS key-value labels, and race-free event streaming, multiple headless workers collide on shared work or fall back to wasteful polling loops. > - This pull request adds headless channels, versioned JSON schemas, topological `plan.json` batch creation, fenced task queues with `FOR UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI with `paperclipai up`. > - The benefit is zero-ceremony, machine-readable, race-safe coordination across terminal agents, CI scripts, and local Paperclip servers while staying compatible with existing Web UI issue threads. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`, `doc/`, `skills/`) **Problem or motivation** Agents and terminal workflows need a fast way to post updates, queue DAG tasks, claim work without double-execution, ask humans for approval, and wait on board events without browser setup or polling loops. Existing Paperclip routes assume UI-driven projects, lack fenced claim leases for pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk` client. **Proposed solution** Build a headless coordination layer directly on top of Paperclip `issues` and `issue_comments` using `issues.scope = 'channel'`: - **Database & Contracts (`packages/db`, `packages/shared`)**: Add `0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql` for lazy hierarchical `channels`, `channel_access_members`, immutable `company_schemas`, monotonic `board_events`, `scheduled_board_posts`, `issue_batch_idempotency_keys`, scoped `board_api_keys`, `agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`), including an in-memory test backend. - **Server APIs & Workers (`server/`)**: Add routes and services for progressive `--as` actor resolution (`open_local_profiles`, `delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth challenges, lazy channels, CAS `kv-labels`, versioned schemas, topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with fenced TTL renewal/release/complete/fail, one-line `ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming (`events/wait`, `events/stream`), and sleep-aware lease expiry and scheduled post workers. - **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc` binary alias and `paperclipai/sdk` export, add the zero-prompt `paperclipai up` / `pc up` local launcher, add `pc` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add `skills/paperclip-lite/SKILL.md`. **Alternatives considered** - **Separate message and queue tables outside `issues`**: Rejected because channel posts and queued tasks would lose Paperclip identifiers (`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue URLs (`/<prefix>/issues/PC-1`). - **Advisory locks or polling loops for task workers**: Rejected because advisory locks drop on reconnect across laptop sleep, and polling wastes tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)` TTL leases with `events/wait` and `waitSec` solve both safely. **Roadmap alignment** Extends core Paperclip agent orchestration and CLI workflows with a headless board, SDK, and queue primitive without altering existing Web UI board behavior. **Additional context** This PR builds on the `issues.scope` surface visibility foundation from #23329 (included as the base commit in this stacked branch so CI and reviewers can test the full integration against `master`). ## What Changed - **Schema & Migrations (`packages/db`)**: Added online-compatible migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`), and column extensions on `issues`, `issue_comments`, `companies`, `board_api_keys`, and `cli_auth_challenges`. - **Shared Contracts & SDK (`packages/shared`)**: Added `packages/shared/src/headless/*` (channels, events, identity, labels, leases, DAG plans, schemas) and `packages/shared/src/sdk/*` (`paperclip()` client, env loader, SSE parser, and in-memory backend). - **Server Routes & Services (`server/`)**: Added `headless-channels-schemas.ts`, `headless-queues-events.ts`, `headless-identity.ts` routes and supporting services (`headless-channels.ts`, `headless-common.ts`, `headless-events-schedules-interactions.ts`, `headless-identity.ts`, `headless-labels-batch.ts`, `headless-schemas.ts`, `headless-task-queue.ts`), plus `issues.scope` visibility isolation and `board-auth.ts` extensions. - **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and `paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and `cli/src/commands/board/*` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent`). - **Docs, Skill & Runner Registry (`doc/`, `skills/`, `tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs, `skills/paperclip-lite/SKILL.md`, and synchronized `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `pnpm --filter @paperclipai/db check:migrations` — passed (`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified online-compatible, 2 new migrations since `630cf0423024`, none blocked). - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` — passed (`598` inputs, `changed: false`). - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests passed. - `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability IDs aligned). - `pnpm exec vitest run packages/shared/src/headless/headless.test.ts packages/shared/src/sdk/sdk.test.ts cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-scope-visibility.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-identity-auth.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests passed. - `pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — all passed. - `pnpm --filter paperclipai build` — passed. ## Risks - **Two new migrations (`0511`, `0512`)**: Both migrations are marked online-compatible (`NOT VALID` constraints validated afterwards, `CONCURRENTLY` index creation, idempotent statements for non-transactional execution) and checked by `check:migrations`. If #23329 lands separately with `0511` modified or renumbered, this branch will rebase on top cleanly. - **Large surface area (91 files)**: Changes are primarily additive new modules (`headless-*`, `cli/src/commands/board/*`, `packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing Web UI board behavior remains isolated via `issues.scope`. - **Full repository Vitest suite**: Only the targeted headless, SDK, CLI, server, and runner-e2e pin suites ran locally after rebasing; full cross-package CI checks will validate the remaining suite. ## Model Used - Google DeepMind Antigravity (Gemini coding agent) 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
13 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.
- 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):{ task, claimToken, claimEpoch, leaseExpiresAt, channel }.
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, clears holder/token, bumpsclaimEpoch, emitstask.lease_released+task.ready.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, and emitstask.completedplustask.unblocked/task.readyfor unblocked DAG dependents.POST /api/issues/:id/claim/fail: Fails the claim (reason). Requeues up to channelmaxClaimAttemptsunlessrequeue: false; moves toblockedand emitstask.lease_poison_blockedwhen exhausted.
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.