Files
PaperClipAI/cli/src/commands/up.ts
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

392 lines
13 KiB
TypeScript

import fs from "node:fs";
import path from "node:path";
import { createServer } from "node:net";
import * as p from "@clack/prompts";
import pc from "picocolors";
import { Option, type Command } from "commander";
import { type Company } from "@paperclipai/shared";
import { paperclip, type ChannelView } from "@paperclipai/shared/sdk";
import { PaperclipApiClient } from "../client/http.js";
import { readContext, setCurrentProfile, upsertProfile } from "../client/context.js";
import {
expandHomePrefix,
resolveDefaultConfigPath,
resolveDefaultContextPath,
resolvePaperclipHomeDir,
resolvePaperclipInstanceId,
} from "../config/home.js";
import { readConfig } from "../config/store.js";
import { detectGitWorkspaceInfo } from "./git-workspace.js";
import { runCommand, type StartedServer } from "./run.js";
import { resolveTestDriveServerPort } from "./test-drive.js";
export const UP_BIND_MODES = ["loopback", "tailnet", "lan"] as const;
export type UpBindMode = (typeof UP_BIND_MODES)[number];
export interface UpOptions {
local?: boolean;
dataDir?: string;
port?: number | string;
bind?: UpBindMode;
companyName?: string;
context?: boolean;
}
export type UpApi = Pick<PaperclipApiClient, "get" | "post">;
export interface UpBootstrapResult {
reused: boolean;
company: Company;
issuePrefix: string;
channel: ChannelView | null;
}
export interface UpDependencies {
run: typeof runCommand;
createApi: (apiBase: string) => UpApi;
ensureGeneralChannel: (apiBase: string, companyId: string) => Promise<ChannelView | null>;
updateContext: (input: {
apiBase: string;
companyId: string;
contextPath?: string;
}) => string;
}
export function deriveCompanyIssuePrefix(companyName: string): string {
const cleaned = companyName
.toUpperCase()
.replace(/[^A-Z0-9]+/g, "");
if (cleaned.length >= 3) {
return cleaned.slice(0, 3);
}
if (cleaned.length > 0) {
return cleaned.padEnd(3, "P");
}
return "PAP";
}
export function resolveUpCompanyName(options: Pick<UpOptions, "companyName" | "local">, cwd = process.cwd()): string {
const explicit = options.companyName?.trim();
if (explicit) return explicit;
if (options.local) {
const git = detectGitWorkspaceInfo(cwd);
const root = git?.root ?? path.resolve(cwd);
const base = path.basename(root).trim();
if (base) return base;
}
return "Workspace";
}
export function checkLocalGitignore(workspaceRoot: string): {
isGitRepo: boolean;
ignored: boolean;
gitignorePath: string;
} {
const git = detectGitWorkspaceInfo(workspaceRoot);
const gitignorePath = path.join(workspaceRoot, ".gitignore");
if (!git) {
return { isGitRepo: false, ignored: true, gitignorePath };
}
if (!fs.existsSync(gitignorePath)) {
return { isGitRepo: true, ignored: false, gitignorePath };
}
const content = fs.readFileSync(gitignorePath, "utf8");
const lines = content.split(/\r?\n/).map((line) => line.trim());
const ignored = lines.some(
(line) =>
!line.startsWith("#") &&
(line === ".paperclip" ||
line === ".paperclip/" ||
line === "/.paperclip" ||
line === "/.paperclip/" ||
line === ".paperclip/board" ||
line === ".paperclip/board/"),
);
return { isGitRepo: true, ignored, gitignorePath };
}
async function checkPortAvailable(port: number, host = "127.0.0.1"): Promise<boolean> {
return await new Promise<boolean>((resolve) => {
const server = createServer();
server.unref();
server.once("error", () => resolve(false));
server.listen(port, host, () => {
server.close(() => resolve(true));
});
});
}
function parseExplicitPort(raw: number | string | undefined): number | undefined {
if (raw === undefined) return undefined;
const num = typeof raw === "number" ? raw : Number.parseInt(String(raw).trim(), 10);
if (!Number.isInteger(num) || num < 1 || num > 65535) {
throw new Error(`Invalid --port "${String(raw)}": expected an integer between 1 and 65535.`);
}
return num;
}
export async function prepareUpEnvironment(
options: UpOptions,
cwd = process.cwd(),
): Promise<{
dataDir: string;
workspaceRoot: string | null;
contextPath: string;
port: number;
bind: UpBindMode;
gitignoreMissing: boolean;
}> {
if (options.local && options.dataDir?.trim()) {
throw new Error("--local and --data-dir cannot be combined.");
}
const bind: UpBindMode = options.bind ?? "loopback";
if (!UP_BIND_MODES.includes(bind)) {
throw new Error(`Invalid --bind "${String(bind)}": expected one of ${UP_BIND_MODES.join(", ")}.`);
}
let workspaceRoot: string | null = null;
let dataDir: string;
let contextPath: string;
if (options.local) {
const git = detectGitWorkspaceInfo(cwd);
workspaceRoot = git?.root ?? path.resolve(cwd);
dataDir = path.join(workspaceRoot, ".paperclip", "board");
contextPath = path.join(workspaceRoot, ".paperclip", "context.json");
process.env.PAPERCLIP_HOME = dataDir;
process.env.PAPERCLIP_INSTANCE_ID = "default";
process.env.PAPERCLIP_CONFIG = resolveDefaultConfigPath("default");
process.env.PAPERCLIP_CONTEXT = contextPath;
} else if (options.dataDir?.trim()) {
dataDir = path.resolve(expandHomePrefix(options.dataDir.trim()));
process.env.PAPERCLIP_HOME = dataDir;
const instanceId = resolvePaperclipInstanceId();
process.env.PAPERCLIP_INSTANCE_ID = instanceId;
process.env.PAPERCLIP_CONFIG = resolveDefaultConfigPath(instanceId);
contextPath = process.env.PAPERCLIP_CONTEXT?.trim()
? path.resolve(process.env.PAPERCLIP_CONTEXT.trim())
: resolveDefaultContextPath();
process.env.PAPERCLIP_CONTEXT = contextPath;
} else {
dataDir = resolvePaperclipHomeDir();
const instanceId = resolvePaperclipInstanceId();
process.env.PAPERCLIP_INSTANCE_ID = instanceId;
process.env.PAPERCLIP_CONFIG = process.env.PAPERCLIP_CONFIG?.trim() || resolveDefaultConfigPath(instanceId);
contextPath = process.env.PAPERCLIP_CONTEXT?.trim()
? path.resolve(process.env.PAPERCLIP_CONTEXT.trim())
: resolveDefaultContextPath();
process.env.PAPERCLIP_CONTEXT = contextPath;
}
process.env.PAPERCLIP_OPEN_ON_LISTEN = "false";
if (bind !== "loopback") {
process.env.PAPERCLIP_BIND = bind;
}
const explicitPort = parseExplicitPort(options.port);
let port: number;
if (explicitPort !== undefined) {
if (!(await checkPortAvailable(explicitPort))) {
throw new Error(`Port ${explicitPort} is already in use.`);
}
port = explicitPort;
} else {
let preferredPort = 3100;
try {
preferredPort = readConfig(process.env.PAPERCLIP_CONFIG)?.server.port ?? preferredPort;
} catch {
// Doctor handles invalid config diagnostics on startup.
}
port = await resolveTestDriveServerPort(preferredPort);
}
process.env.PORT = String(port);
const gitignoreCheck = workspaceRoot ? checkLocalGitignore(workspaceRoot) : null;
const gitignoreMissing = Boolean(gitignoreCheck?.isGitRepo && !gitignoreCheck.ignored);
return {
dataDir,
workspaceRoot,
contextPath,
port,
bind,
gitignoreMissing,
};
}
export async function bootstrapUpBoard(input: {
api: UpApi;
apiBase: string;
companyName: string;
ensureGeneralChannel: (apiBase: string, companyId: string) => Promise<ChannelView | null>;
}): Promise<UpBootstrapResult> {
const companies = (await input.api.get<Company[]>("/api/companies")) ?? [];
const activeCompanies = companies.filter((c) => c.status !== "archived");
let company = activeCompanies[0];
let reused = true;
if (!company) {
reused = false;
const created = await input.api.post<Company>("/api/companies", {
name: input.companyName,
});
if (!created) {
throw new Error("Paperclip returned no result while creating the default company.");
}
company = created;
}
const issuePrefix =
typeof company.issuePrefix === "string" && company.issuePrefix.trim().length > 0
? company.issuePrefix.trim()
: deriveCompanyIssuePrefix(company.name);
const channel = await input.ensureGeneralChannel(input.apiBase, company.id);
return { reused, company, issuePrefix, channel };
}
function formatReadyUrl(server: StartedServer): string {
const rawHost =
server.host === "0.0.0.0" || server.host === "::" || server.host === "[::]"
? "127.0.0.1"
: server.host;
const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost;
return `http://${host}:${server.listenPort}`;
}
export function formatUpReadyBanner(input: {
url: string;
companyName: string;
issuePrefix: string;
deploymentMode: string;
dataDir: string;
contextUpdated: boolean;
contextPath: string;
companyId: string;
}): string[] {
const lines = [
`Paperclip ready at ${input.url} (Company: ${input.companyName} [${input.issuePrefix}], mode: ${input.deploymentMode})`,
`Channel: #general | Data: ${input.dataDir}`,
input.contextUpdated
? `Context: ${input.contextPath} (company=${input.companyId})`
: `Context: skipped (--no-context)`,
`Next: pc post general "Hello board" | pc tasks create general "First task"`,
];
return lines;
}
const defaultUpDependencies: UpDependencies = {
run: runCommand,
createApi: (apiBase) => new PaperclipApiClient({ apiBase }),
ensureGeneralChannel: async (apiBase, companyId) => {
const client = paperclip({ apiBase, company: companyId });
return await client.channels.ensure("general");
},
updateContext: ({ apiBase, companyId, contextPath }) => {
const existing = readContext(contextPath);
const targetProfile = existing.currentProfile || "default";
upsertProfile(
targetProfile,
{
apiBase,
companyId,
},
contextPath,
);
setCurrentProfile(targetProfile, contextPath);
return contextPath ?? resolveDefaultContextPath();
},
};
export async function upCommand(
options: UpOptions,
dependencies: UpDependencies = defaultUpDependencies,
cwd = process.cwd(),
): Promise<void> {
const dataDir = resolvePaperclipHomeDir();
const companyName = resolveUpCompanyName(options, cwd);
const contextPath = process.env.PAPERCLIP_CONTEXT ?? resolveDefaultContextPath();
const bind: UpBindMode = options.bind ?? "loopback";
const skipContext = options.context === false;
if (options.local) {
const git = detectGitWorkspaceInfo(cwd);
const root = git?.root ?? path.resolve(cwd);
const check = checkLocalGitignore(root);
if (check.isGitRepo && !check.ignored) {
p.log.warn(
`Local board state lives at ${path.join(root, ".paperclip", "board")} — add ".paperclip/" to ${check.gitignorePath} to keep it out of git.`,
);
}
}
await dependencies.run({
repair: true,
yes: true,
bind,
installService: false,
skipServiceManagerCheck: Boolean(options.local || options.dataDir?.trim()),
introLabel: "paperclipai up",
afterStart: async (server) => {
const url = formatReadyUrl(server);
const api = dependencies.createApi(url);
const result = await bootstrapUpBoard({
api,
apiBase: url,
companyName,
ensureGeneralChannel: dependencies.ensureGeneralChannel,
});
let savedContextPath = contextPath;
if (!skipContext) {
savedContextPath = dependencies.updateContext({
apiBase: url,
companyId: result.company.id,
contextPath,
});
}
const config = readConfig(process.env.PAPERCLIP_CONFIG);
const mode = config?.server.deploymentMode ?? (bind === "loopback" ? "local_trusted" : "authenticated");
const bannerLines = formatUpReadyBanner({
url,
companyName: result.company.name,
issuePrefix: result.issuePrefix,
deploymentMode: mode,
dataDir,
contextUpdated: !skipContext,
contextPath: savedContextPath,
companyId: result.company.id,
});
console.log("");
for (const line of bannerLines) {
console.log(pc.green(line));
}
},
});
}
export function registerUpCommand(
program: Command,
dependencies: UpDependencies = defaultUpDependencies,
): void {
program
.command("up")
.description("Start a ready-to-use local Paperclip board with zero prompts or LLM keys")
.option("--local", "Store board state in <git-root-or-cwd>/.paperclip/board")
.option("-d, --data-dir <path>", "Paperclip data directory root")
.option("-p, --port <port>", "Server listen port (defaults to 3100 or next free port)")
.addOption(
new Option("--bind <mode>", "Reachability preset (loopback, tailnet, lan)")
.choices(UP_BIND_MODES)
.default("loopback"),
)
.option("--company-name <name>", "Initial company name when bootstrapping a fresh board")
.option("--no-context", "Do not update local CLI context with the started board URL and company")
.action(async (options: UpOptions) => {
await upCommand(options, dependencies);
});
}