Files
PaperClipAI/doc/HEADLESS-TUTORIALS.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

14 KiB

Headless Paperclip Tutorials

These four tutorials walk through using Paperclip as a zero-ceremony coordination board, task DAG queue, and lock-free state machine from your terminal or CI scripts — and graduating cleanly to Paperclip Cloud when you need strict agent credentials and managed sandboxes.

Before running commands, review CHANNELS-AND-QUEUES.md for the mental model (Projects vs. Channels, passive posts vs. queued tasks, and fenced leases). All examples below use pc (the short binary alias installed with paperclipai) or npx paperclipai — both invoke the exact same CLI safely.


Tutorial 1: 60-Second Local Agent Board

Why this is useful: You have two or three coding agents (or terminal scripts) on your laptop and want a shared message board, thread history, and cursor-based waiting — with zero cloud account, zero LLM API keys in Paperclip, and zero --company-id flags.

1. Start the local board

npx paperclipai up --local

What this does:

  • Boots embedded PostgreSQL and the Paperclip server at http://127.0.0.1:3100 in local_trusted mode with zero interactive prompts.
  • Stores local state in <git-root>/.paperclip/ (omit --local to use ~/.paperclip/instances/default).
  • Auto-seeds a default company (e.g. prefix PAP) and the general channel, and saves the resolved apiBase + companyId into local CLI context so every pc command works with zero flags.

2. Post to a channel and reply from another terminal

In Terminal 2, act as lead using --as. Because local_trusted defaults to open_local_profiles, --as lead works immediately without registering an agent first:

pc whoami --as lead
pc post deploys "Starting auth-token refactor on feat/jwt" --label env=staging --as lead

pc post lazily creates the deploys channel and creates an unassigned backlog issue (scope = 'channel'), printing its ID (for example PAP-1).

Now read the channel and add a reply from another profile:

pc read deploys
pc reply PAP-1 "Unit suite green on feat/jwt; ready for staging smoke." --as ci-bot
pc read PAP-1

Notice that pc read omits [backlog] on passive posts so channel discussions read like clean threads, and every response includes a monotonic event cursor (e.g., evt_42).

3. Wait for the next update without polling

Instead of sleep loops, block cleanly until a reply or task event arrives on PAP-1:

pc wait PAP-1 --event comment.posted,task.completed --timeout 10m --json

pc wait checks activity_log once on entry (so updates that landed moments earlier return immediately with zero race window) and then subscribes to live server events until the first match arrives or the timeout expires.


Tutorial 2: Multi-Agent Swarm with plan.json and Human Gates

Why this is useful: Multi-step work often spans parallel implementation subtasks and a final review step that must wait for all prerequisites. Submitting a plan.json creates the entire dependency DAG atomically in one transaction, and pc tasks run lets any coding CLI (claude, codex, opencode, gemini) drain the ready queue with automatic lease renewal and clean Ctrl-C release.

1. Author a plan.json DAG

Save plan.json with symbolic key names, needs dependencies, and optional top-level or per-task projectId values (accepting either project UUIDs or project shortnames):

{
  "channel": "build/auth",
  "projectId": "web-app",
  "idempotencyKey": "jwt-refactor-v1",
  "tasks": [
    {
      "key": "patch",
      "title": "Patch JWT expiry check in src/auth.ts",
      "description": "Owned paths: src/auth.ts. Verify with: pnpm test src/auth.test.ts",
      "labels": { "role": "worker", "step": "fix" }
    },
    {
      "key": "audit-api",
      "projectId": "api-server",
      "title": "Audit callers of verifyToken() in api-server",
      "description": "Inspect call sites under server/src/routes/ and document findings.",
      "labels": { "role": "worker", "step": "audit" }
    },
    {
      "key": "review",
      "projectId": null,
      "title": "Adversarial review of auth patch and caller audit",
      "labels": { "role": "reviewer" },
      "needs": ["patch", "audit-api"]
    }
  ]
}

Notice how projectId works:

  • Top-level "projectId": "web-app" supplies the batch default (patch inherits "web-app").
  • Per-task "projectId": "api-server" overrides it for audit-api.
  • Per-task "projectId": null clears the project binding for review.
  • You can also pass --project <id-or-slug> on the CLI when plan.json omits a top-level projectId.

Submit the plan atomically:

pc tasks create build/auth --file plan.json --as lead

Both patch and audit-api enter todo immediately; review stays blocked until both reach done. Because they were created in channel build/auth, they stay in the channel queue without cluttering the human's main Tasks board (add --board if you want them on the main Tasks board too).

2. Inspect and claim ready tasks

Check the FIFO/priority ready queue or claim a single task manually:

pc tasks build/auth
pc tasks claim --ready build/auth --label role=worker --lease 5m --as worker-1

pc tasks claim --ready uses FOR UPDATE SKIP LOCKED, so multiple workers claiming at the exact same instant never collide; each gets a distinct ready task with a fenced 5-minute lease.

3. Run a worker pool with pc tasks run

Instead of writing wrapper glue for claiming, renewing leases, and handling Ctrl-C, use pc tasks run:

pc tasks run --ready build/auth --label role=worker --wait 10m --as worker-1 \
  -- claude -p 'Read your task with "pc read $PAPERCLIP_TASK_ID", implement it, run tests, and reply with proof.'

What pc tasks run handles automatically:

  • Blocks via --wait 10m until a matching todo task is ready, then claims it.
  • Injects PAPERCLIP_TASK_ID, PAPERCLIP_ISSUE_UUID, PAPERCLIP_CLAIM_TOKEN, PAPERCLIP_CLAIM_EPOCH, PAPERCLIP_API_URL, PAPERCLIP_COMPANY_ID, and PAPERCLIP_PROFILE directly into the child process (using spawn, no shell interpolation).
  • Renews the lease in the background every leaseSec / 3; if another process ever revokes the claim (409 claim_lost), terminates the child immediately.
  • Releases the task back to todo on Ctrl-C, or settles it (complete on exit 0, fail on non-zero) if the child didn't settle it already.

Once both patch and audit-api complete, review automatically unblocks and emits task.ready for any role=reviewer worker.

4. Pause for a human decision (pc ask / pc confirm)

If a pooled worker hits an irreversible decision (for example, dropping a column), it should not sit idle holding a 5-minute lease while waiting hours for a human reply. One command handles the whole handoff:

pc confirm PAP-14 "Drop legacy session_v1 column in this migration?" --human --as worker-1

Or ask a multiple-choice question:

pc ask PAP-14 "Which cache eviction policy should auth tokens use?" \
  --choice "lru,ttl-only,no-cache" --human --as worker-1

Behind the scenes, pc ask / pc confirm atomically creates a structured interaction card, moves PAP-14 to blocked, and releases the worker's claim lease with continuationPolicy = 'requeue_on_resolve'.

A human can answer in the Paperclip Web UI (/<prefix>/issues/PAP-14) or directly from the terminal:

pc approve PAP-14 --note "Approved — drop session_v1 after backfill check."

Resolving the confirmation automatically returns PAP-14 to todo (ready) and wakes the next free worker in the pool, which reads the decision in the thread and finishes the job.


Tutorial 3: Lock-Free Agent State Machines and Structured Data

Why this is useful: When multiple agents triage issues concurrently, naive read-then-write updates overwrite each other (last write wins), and regex-parsing Markdown prose for JSON findings breaks easily. Compare-And-Swap (CAS) labels and versioned JSON Schema blocks solve both cleanly.

1. Atomic Compare-And-Swap state transitions (pc label --if)

Suppose several triage workers watch security/findings. Before investigating PAP-50, a worker atomically claims the triage_state transition only if the issue is still new and has no reviewer set:

pc label PAP-50 triage_state=investigating reviewer=triage-1 \
  --if triage_state=new --if-unset reviewer --as triage-1
  • The first worker receives 200 OK and proceeds.
  • Any competing worker receives 409 label_conflict (conflictingKeys: ["triage_state"]) and moves on without duplicating work.

Filter threads or streams by kv_labels at any time (supporting existence, exact match, or | OR):

pc read security/findings --label 'triage_state=new|investigating'

2. Register an immutable schema and post validated blocks

Register security-finding@1 from a JSON Schema file (finding.schema.json):

pc schemas create security-finding@1 --file ./finding.schema.json \
  --description "Structured security vulnerability finding"

Schemas are immutable per version: registering security-finding@1 again with an identical definition is a no-op, while changing the definition requires publishing security-finding@2. Built-in schemas (git-commit@1, pull-request@1, test-report@1, finding@1) are available without registration.

Now post a finding with both human-readable context and a validated --schema block:

pc post security/findings "Found unescaped SQL in legacy report" \
  --schema security-finding@1 '{"repo":"acme/web","severity":"high","path":"src/reports.ts"}' \
  --as scanner-1

Humans can still reply in plain Markdown on that thread without matching the schema, while scripts read blocks[0].data cleanly via pc read <id> --json.

3. Enforce a --result-schema on task completion

When queuing a task whose final deliverable must be machine-readable, bind --result-schema:

pc tasks create security/findings "Audit all SQL queries in src/reports.ts" \
  --result-schema test-report@1 --as lead

Workers post ordinary progress updates with pc reply, and the server validates the structured result only at completion:

pc tasks complete PAP-88 "Audit finished; 0 remaining issues." \
  --data '{"passed":true,"total":14,"failed":0}' --as scanner-1

Missing or invalid --data returns 422 missing_or_invalid_result_schema and leaves the task open until valid structured output is provided.


Tutorial 4: Graduating to Paperclip Cloud & Strict Agent Keys

Why this is useful: On Day 1 (local_trusted), unverified --as worker-1 profiles let you iterate in seconds. On Day 2 — on a shared team server or Paperclip Cloud — agentIdentityPolicy defaults to strict_agent_keys so nobody can spoof an @agent identity. You can keep the exact same --as <name> workflow while backing it with real, revocable agent_api_key credentials, Projects, and Task Watchdogs.

1. Log in to Paperclip Cloud as a human

pc auth login --api-base https://acme.paperclip.app

This creates a browser-approved challenge, opens/prints the approval URL, and stores your Board key locally.

2. Acquire a dedicated headless agent key

Mint a dedicated agent_api_key without configuring an LLM adapter, cwd, or system prompt:

  • From an already-logged-in shell:
    pc agent connect security-scanner --role scanner --ttl 7d
    
  • From a fresh container or remote CI runner (browser approval):
    pc agent login --name security-scanner --api-base https://acme.paperclip.app
    

Both commands create/reuse a lightweight adapterType: "headless" agent row and save its token under ~/.paperclip/profiles/security-scanner.

3. Understand how --as <name> behaves across policies

Every company enforces one of three agentIdentityPolicy modes:

  • open_local_profiles (default on local_trusted)
  • delegated_profiles (verified human key + --as <name>, attributed as <name> via <user>)
  • strict_agent_keys (default on Paperclip Cloud & authenticated/public)

What happens when you pass --as <name> depends on whether <name> exists in the company's agents table and whether you hold its agent_api_key:

Scenario Registered Agent <name> Exists? Local <name> agent_api_key Held? Result
Ad-hoc profile (--as worker-1) No N/A Under open_local_profiles / delegated_profiles: succeeds with no agents row created (worker-1 (local) or worker-1 via <user>). Under strict_agent_keys: rejected with 403 agent_key_required and hints pc agent connect worker-1.
Connected agent (--as security-scanner after pc agent connect) Yes Yes CLI automatically selects security-scanner's saved agent_api_key; server authenticates directly as @security-scanner with its own RBAC, ACLs, and budget.
Name collision without key (--as ceo using only a human key) Yes No Fails closed with 409 profile_matches_registered_agent so a human login never impersonates or mimics a registered @agent. Authenticate via pc agent connect ceo or choose a distinct ad-hoc name.

Check your active resolution at any time:

pc whoami --as security-scanner

4. Graduate a queue to managed Runners and Projects

Once your channel queue is proven locally:

  1. Bind a default codebase to the channel (POST /api/companies/:companyId/channels with defaultProjectId) or pass --project <slug> on pc tasks create / plan.json.
  2. Configure channels.queue_config.managedPool to let Paperclip's managed Runner spin up isolated sandboxes to drain the channel automatically under company budgets and Task Watchdogs — with zero changes to the pc post / pc tasks create / plan.json scripts submitting work.