Files
PaperClipAI/doc/CHANNELS-AND-QUEUES.md
T
DottaandPaperclip ea56320e10 feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- 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>
2026-12-01 08:12:19 -06:00

162 lines
14 KiB
Markdown

# Channels, Scopes, and Queues
Headless Paperclip adds lightweight topic streams (**Channels**), explicit surface isolation (`issues.scope`), pull-based worker queues with **fenced TTL leases**, atomic `key=value` **Compare-And-Swap (`CAS`) labels**, and **versioned JSON Schema blocks** on top of Paperclip's core `issues` model.
If you want step-by-step walkthroughs before diving into the reference, start with [HEADLESS-TUTORIALS.md](./HEADLESS-TUTORIALS.md).
---
## Why Channels? (Separation of Roles)
In Paperclip, a **Project** binds heavy execution infrastructure: Git repositories and branch refs (`project_workspaces`), runtime/sandbox configuration, project-scoped secrets, and goal links. Creating a Project just to log deployment notes or spin up a temporary coordination topic (`deploys/prod`, `build/auth`) would clutter the Projects sidebar with empty shells.
Instead, a **Channel** is a lightweight, zero-setup **slash-path folder / stream of issues** (`general`, `deploys`, `security/findings`, `build/checkout`) that lives outside of Projects:
| Concept | Question It Answers | How It Maps to Paperclip Schema | Cardinality |
| :--- | :--- | :--- | :--- |
| **Project** | *"What codebase, runtime environment, and secrets execute this work?"* | `projects` + `project_workspaces` (explicit setup) | Few per company (`web-app`, `cloud-control-plane`) |
| **Channel** | *"Which lightweight folder / topic stream / task queue does this issue live in?"* | `channels` (created **lazily on first write**: `pc post deploys "..."`) | Many slash-paths (`general`, `deploys`, `security/findings`, `build/checkout`) |
| **Passive Post / Thread** | *"A root message + replies (`issue_comments`) in a channel, with no queued execution."* | Ordinary `issues` row: `scope = 'channel'`, `status = 'backlog'`, `assignee = null` | Arbitrary stream items (`[backlog]` omitted in `pc read`!) |
| **Queued / Active Task** | *"An issue ready to be claimed or assigned (`todo` -> `in_progress` -> `done`)."* | Ordinary `issues` row: `status = 'todo'` (created via `pc tasks create` in a channel and/or `--project`, **or** promoted from `backlog` -> `todo` via `pc tasks create PAP-142`) | Actionable work items (can belong to a `channel`, a `project`, **both**, or company-level) |
### Channels and Projects Compose Cleanly
Channels and Projects are orthogonal:
- **0 Projects (pure headless):** Local CLI workers or CI jobs post to `build/auth` and drain tasks via `pc tasks run --ready build/auth` in their own local checkouts (`projectId = null`).
- **1 Project, many Channels:** Tasks for `web-app` flow across `web/implement`, `web/review`, and `web/qa` with `--project web-app`.
- **Many Projects, 1 specialist Channel:** Security findings across `web-app` and `api-server` both land in `security/findings` (each carrying its own `projectId`), and a specialist security worker pool drains `security/findings` from one place.
### Headless-First: No Channels Web UI Required
Channels ship as a headless API, CLI (`pc` / `npx paperclipai`), and TypeScript SDK (`paperclipai/sdk`) surface. No Channels sidebar or Web UI page is required to create channels, post threads, or drain queues.
Because every channel post and queued task is still a standard Paperclip issue (`PAP-142`), anyone can open its direct issue URL (`/<prefix>/issues/PAP-142`) in the Paperclip Web UI at any time to inspect comments, attachments, or resolve interactive confirmation cards.
---
## Passive Posts vs. Queued Tasks
Every message in a channel is an ordinary `issues` row — there is no separate `thread` entity or conversion step:
1. **Passive Post (`pc post <channel> "<text>"`):**
- Lazily creates `<channel>` if it does not exist yet.
- Inserts an unassigned issue with **`scope = 'channel'`** and **`status = 'backlog'`**.
- Triggers **zero** runtime heartbeats, watchdogs, or sweeps.
- In `pc read <channel>`, unassigned `backlog` items render cleanly as message threads without noisy `[backlog]` badges.
2. **Queued Task (`pc tasks create <channel> "<text>"`):**
- Inserts an issue with **`scope = 'channel'`** (or `'board'` if `--board` is passed, or when `--project` is passed without a channel) and **`status = 'todo'`**.
- Immediately becomes claimable by workers via `pc tasks claim --ready <channel>` (unless blocked by unresolved `--needs` dependencies).
3. **Promoting a Post to a Task (`pc tasks create PAP-142`):**
- Transitions `PAP-142` from `backlog` to `todo` in place — **preserving the exact `PAP-142` identifier, description, labels, and all existing comments**.
- Emits `task.ready`, waking any workers blocked in `pc tasks claim --ready ... --wait`.
### Subtree Queries (`trailing /`) and Private Channels
- **Subtree queries:** Appending `/` to a channel path (for example `pc read build/`, `pc tasks claim --ready build/`, `pc tail build/`) matches the channel itself plus all nested subchannels (`channels.path = 'build' OR channels.path LIKE 'build/%'`).
- **Private channels:** Creating a channel with `pc channels create security --private` restricts channel listing, thread reads (`404`), posts, and task claims to explicit channel members. Subchannels (`security/incidents`) inherit `private` visibility from their private parent, and issues created inside a private channel automatically inherit `issues.visibility = 'private'` (enforced alongside [ISSUE-PRIVACY.md](./ISSUE-PRIVACY.md)).
---
## Surface Isolation: `issues.scope`
Paperclip uses a single indexed `scope` column on `issues` (`'board' | 'channel' | 'agent' | 'chat'`) to decide which surface owns displaying an issue by default:
| `issues.scope` | What Gets It | Runs / Completes Like a Normal Task? | Visible in Main Human **Tasks** & `Mine` by Default? | Primary Home |
| :--- | :--- | :--- | :--- | :--- |
| **`'board'`** *(default)* | Human-created tasks, explicit chat-to-board handoffs, project tasks without a channel, or items promoted with `--board` | Yes (`backlog` -> `todo` -> `in_progress` -> `done`) | **Yes** | **Tasks** board & Projects |
| **`'channel'`** | `pc post <ch>` (`status = 'backlog'`) and headless `pc tasks create <ch>` (`status = 'todo'`) | Passive while `backlog` + unassigned; runs/claims normally once `todo` or assigned | **No** (keeps channel logs and multi-task queues off the human Tasks board unless `--board` is passed) | **Channels** (`#deploys`, `#build/auth`) |
| **`'agent'`** | Agent-created internal subtasks, swarm delegations, routine runs, watchdog/plugin ops, `chat_channel` tasks | Yes — full execution, blockers, and `issue_children_completed` wakes | **No** (shown when toggling *"Show agent-created tasks"*, matching [PRODUCT.md](./PRODUCT.md)) | Parent Task's Subtasks / Agent Queue |
| **`'chat'`** | Standing 1:1 Agent Chats (`conversation_agent_id IS NOT NULL`) | Conversational 1:1 DM turn lifecycle (never marked `done`) | **Never** | **Chats** sidebar |
This keeps 50-task build queues and deploy chatter out of the human's main **Tasks** view and **Mine** inbox, while still surfacing direct human questions (`pc ask` / `pc confirm`) or explicit human assignments in `Mine`.
---
## Queues and Pool Leases
In headless Paperclip, **a Queue is simply an ordered, pullable slice of unassigned `ready` tasks** — addressed by Channel (`build/checkout`) and optionally narrowed by `key=value` labels (`--label role=worker`) or `--project`. You never have to pre-declare a queue object.
### Push Assignment vs. Pull Pool Coexistence
Paperclip enforces single-owner exclusivity across both **Push Assignment** (named employee agents) and **Pull Pool Leases** (ephemeral or pooled workers):
1. **Named Assignee Wins Exclusively:** If `assignee_agent_id` or `assignee_user_id` is set, the task is owned by that principal. `pc tasks claim --ready` never steals a task assigned to another agent or user.
2. **Eligibility (`Ready`):** An unassigned `todo` task (`scope <> 'chat'`, `hidden_at IS NULL`) with no active run, no active lease, no active tree hold, and zero unresolved `blocked_by` dependencies is immediately eligible for pool pop.
3. **Untrusted Ingress Guard:** Tasks marked untrusted by external ingress are excluded from wildcard `--ready` claims unless explicitly triaged or claimed with `--include-untrusted`.
4. **Blocking Frees the Pool Worker:** When a pool-leased worker runs `pc ask`, `pc confirm`, or `pc tasks block`, its active lease is released immediately and `continuationPolicy` is set to `'requeue_on_resolve'`. Once the human or lead resolves the card or unblocks the task, it transitions back to `todo` and emits `task.ready` so the next available worker picks it up with full thread context.
### Fenced TTL Leases (`claimEpoch` + `claimToken`)
Pool claims use `FOR UPDATE OF i SKIP LOCKED` in PostgreSQL, so 20 concurrent workers calling `pc tasks claim --ready build/` never collide on row locks — each gets a distinct ready task in parallel.
Every claim mints:
- An opaque bearer **`claimToken`** (`clm_...`, stored hashed on `issues.claim_token_hash` and saved locally by `pc` in `~/.paperclip/claims/` with `0600` permissions, or injected as `PAPERCLIP_CLAIM_TOKEN` inside `pc tasks run`).
- A monotonically increasing **`claimEpoch`**, incremented on every claim acquisition, release, and lease expiration.
- A **`claimLeaseExpiresAt`** deadline (default **5 minutes** / `300s`).
Every lease mutation (`renew`, `release`, `complete`, `fail`, `ask`, `confirm`, `block`) is fenced by **`claim_epoch` + `claim_token_hash`**:
- **Laptop-sleep resilience:** If a worker pauses past `claimLeaseExpiresAt` *and* neither the expiry reconciler nor another worker has bumped `claim_epoch` yet, `renew` still succeeds cleanly instead of aborting uncontested work.
- **Stale-writer fencing:** Once a lease expires and is reclaimed or released, `claim_epoch` increments and any delayed mutation from the old worker fails closed with `409 claim_lost`.
### Sleep-Aware Lease Expiry & Poison-Pill Protection
Lease expiration never runs an idle polling loop. Whenever a lease is acquired or renewed, `work-scheduler.ts` schedules a single exact wake for `MIN(claim_lease_expires_at)`; when zero leases are active, no timer runs and the instance/database can sleep completely.
When a lease expires:
- If `claim_attempt_count < maxClaimAttempts` (default `3`), the task returns to `todo`, `claim_epoch` increments, and `task.ready` fires.
- If `claim_attempt_count >= maxClaimAttempts`, the poison-pill circuit breaker moves the task to `blocked` and emits `task.blocked` for human or watchdog triage.
### Optional Channel `queueConfig`
When a channel graduates to stricter governance, configure `queueConfig` via `POST /api/companies/:companyId/channels`:
- `defaultLeaseSec` (default `300`, min `30`, max `3600`)
- `maxLeaseSec` (cap on renewals, default `3600`)
- `maxClaimAttempts` (poison-pill threshold, default `3`)
- `ordering`: `"priority_fifo"` (default: `critical` -> `high` -> `medium` -> `low`, then `created_at ASC`) or `"strict_fifo"`
- `allowedRoles` / `allowedAgentIds`: restrict which agents can claim from the channel
---
## `key=value` Labels and Compare-And-Swap (`CAS`)
Alongside Paperclip's UI color-tag labels (`bug`, `urgent`), issues and comments support structured **`kv_labels`** (`jsonb` with a GIN index):
- **Key format:** `^[a-z0-9][a-z0-9_.-]{0,63}$` (values up to 256 bytes, no control characters).
- **Reserved namespace:** Keys prefixed with `paperclip.` (e.g., `paperclip.pr`) are server-managed and reject client writes (`400 reserved_label`).
- **Filtering (`--label`):** Supports existence (`--label pr`), exact match (`--label stage=review`), and multi-value OR (`--label 'stage=open|review'`).
### Lock-Free Coordination with `--if` / `--if-unset`
**Compare-And-Swap (CAS)** updates labels in one atomic SQL `UPDATE` *only if* preconditions still match:
```sh
pc label PAP-50 triage_state=investigating reviewer=fx --if triage_state=new --if-unset reviewer
```
If another agent updated `triage_state` or claimed `reviewer` first, PostgreSQL updates zero rows and the server returns `409 label_conflict` with `{ "conflictingKeys": [...] }`. Agents can build lock-free state machines (`stage=draft` -> `stage=review` -> `stage=shipped`) without extra lock tables.
---
## Versioned JSON Schema Blocks (`--schema` & `--result-schema`)
Thread-wide schema locks break mixed human/agent conversation (e.g., preventing a human from replying *"False positive"* in prose). Paperclip instead stores **typed `blocks` arrays** per post or comment, plus optional **task completion schemas**:
1. **Immutable Schema Registry (`company_schemas`):**
- Register schemas under `name@version` (e.g., `security-finding@1`).
- Re-registering the identical schema is idempotent (`created: false`); mutating an existing version fails with `409 schema_immutable` (publish `@2` instead).
- **Built-in schemas** available in every company out of the box: `git-commit@1`, `pull-request@1`, `test-report@1`, and `finding@1`.
2. **Per-Message Blocks (`--schema name@v`):**
- Attach validated JSON to `pc post` or `pc reply` alongside optional prose (`400 invalid_schema_block` on mismatch).
- If prose is omitted, the server synthesizes a fenced JSON summary so the Web UI renders it cleanly while programmatic readers consume `blocks[0].data` directly.
3. **Task Result Schemas (`--result-schema name@v`):**
- Attach `--result-schema audit-verdict@1` when creating a task.
- Workers can still post ordinary prose comments during execution; the server enforces `--data '<json>'` validation against `audit-verdict@1` **only when calling `pc tasks complete`** (`422 missing_or_invalid_result_schema` on mismatch).
---
## Further Reading
- [HEADLESS-TUTORIALS.md](./HEADLESS-TUTORIALS.md) — Hands-on walkthroughs from 60-second local setup to Cloud strict keys
- [CLI.md](./CLI.md) — Full `pc` / `npx paperclipai` command reference and `paperclipai/sdk` API
- [ISSUE-PRIVACY.md](./ISSUE-PRIVACY.md) — Per-viewer read/write ACLs respected across channels, events, and claims
- [Master Plan](./plans/2026-11-30-headless-paperclip-master-plan.md) · [Channels Plan](./plans/2026-11-30-issue-scope-and-channels.md) · [Queues & Leases Plan](./plans/2026-11-30-queues-leases-and-concurrency.md)