Files
PaperClipAI/server/src/services/headless-common.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

1209 lines
37 KiB
TypeScript

import { EventEmitter } from "node:events";
import type { Request } from "express";
import { and, desc, eq, inArray, ne, or, sql, type SQL } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
boardApiKeys,
boardEvents,
channelAccessMembers,
channels,
companies,
issueLabels,
issues,
labels,
projects,
} from "@paperclipai/db";
import {
clientScopesSchema,
deriveAgentUrlKey,
deriveProjectUrlKey,
formatEventCursor,
isUuidLike,
normalizeChannelPath,
normalizeIssueIdentifier,
type AgentApiKeyScope,
type AgentIdentityPolicy,
type BoardEventType,
type BoardEventView,
type ClientScopes,
type CommentView,
type DeploymentMode,
type HeadlessIssueView,
type IssuePriority,
type IssueScope,
type IssueStatus,
type LabelFilterExpr,
type SchemaBlock,
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound, unauthorized } from "../errors.js";
import {
authorizationService,
issueReadSqlCondition,
type AuthorizationActor,
} from "./authorization.js";
import { publishLiveEvent } from "./live-events.js";
import { listIssueDependencyReadinessMap } from "./issues.js";
export type DbOrTx = Db | Parameters<Parameters<Db["transaction"]>[0]>[0];
const boardEventEmitter = new EventEmitter();
boardEventEmitter.setMaxListeners(0);
export function subscribeCompanyBoardEvents(
companyId: string,
listener: (event: BoardEventView) => void,
): () => void {
boardEventEmitter.on(companyId, listener);
return () => boardEventEmitter.off(companyId, listener);
}
export function publishCommittedBoardEvent(event: BoardEventView): void {
boardEventEmitter.emit(event.companyId, event);
publishLiveEvent({
companyId: event.companyId,
type: "activity.logged",
payload: {
boardEventSeq: event.seq,
boardEventCursor: event.cursor,
boardEventType: event.type,
channel: event.channel,
issueId: event.issueId,
identifier: event.identifier,
},
});
}
export function resolveCompanyAgentIdentityPolicy(
storedPolicy: AgentIdentityPolicy | null | undefined,
deploymentMode: DeploymentMode = "local_trusted",
): AgentIdentityPolicy {
if (storedPolicy) return storedPolicy;
return deploymentMode === "local_trusted"
? "open_local_profiles"
: "strict_agent_keys";
}
export interface HeadlessActorContext {
companyId: string;
companyName: string;
companyPrefix: string;
agentIdentityPolicy: AgentIdentityPolicy;
principalType: "local_trusted" | "user" | "agent";
userId: string | null;
agentId: string | null;
agentName: string | null;
agentRole: string | null;
actorProfile: string | null;
scopes: ClientScopes | null;
keyId?: string | null;
keyScope?: AgentApiKeyScope | null;
isInstanceAdmin: boolean;
responsibleUserId: string | null;
}
function channelMatchesScopePattern(channelPath: string, pattern: string): boolean {
const trimmed = pattern.trim().toLowerCase().replace(/^#/, "");
if (trimmed === "*" || trimmed === "**") return true;
if (trimmed.endsWith("/*")) {
const base = trimmed.slice(0, -2);
return channelPath === base || channelPath.startsWith(`${base}/`);
}
if (trimmed.endsWith("/")) {
const base = trimmed.slice(0, -1);
return channelPath === base || channelPath.startsWith(`${base}/`);
}
return channelPath === trimmed;
}
export function actionMatchesScopePattern(action: string, pattern: string): boolean {
const trimmed = pattern.trim().toLowerCase();
if (trimmed === "*") return true;
if (trimmed.endsWith("*")) {
return action.toLowerCase().startsWith(trimmed.slice(0, -1));
}
return action.toLowerCase() === trimmed;
}
export function channelScopePatternCovers(allowedPattern: string, candidatePattern: string): boolean {
const allowed = allowedPattern.trim().toLowerCase().replace(/^#/, "");
const candidate = candidatePattern.trim().toLowerCase().replace(/^#/, "");
if (allowed === "*" || allowed === "**") return true;
if (candidate === "*" || candidate === "**") return false;
const candidateIsSubtree = candidate.endsWith("/*") || candidate.endsWith("/");
const candidateBase = candidate.replace(/\/\*?$/, "");
if (candidateIsSubtree) {
const allowedIsSubtree = allowed.endsWith("/*") || allowed.endsWith("/");
if (!allowedIsSubtree) return false;
const allowedBase = allowed.replace(/\/\*?$/, "");
return candidateBase === allowedBase || candidateBase.startsWith(`${allowedBase}/`);
}
return channelMatchesScopePattern(candidateBase, allowed);
}
export function actionScopePatternCovers(allowedPattern: string, candidatePattern: string): boolean {
const allowed = allowedPattern.trim().toLowerCase();
const candidate = candidatePattern.trim().toLowerCase();
if (allowed === "*") return true;
if (candidate === "*") return false;
if (candidate.endsWith("*")) {
if (!allowed.endsWith("*")) return false;
return candidate.slice(0, -1).startsWith(allowed.slice(0, -1));
}
return actionMatchesScopePattern(candidate, allowed);
}
function isReadOnlyHeadlessAction(action?: string): boolean {
if (!action) return true;
const normalized = action.trim().toLowerCase();
return normalized === "read" || normalized.endsWith(".read");
}
function mergeClientScopes(
keyScopes: ClientScopes | null,
headerScopes: ClientScopes | null,
): ClientScopes | null {
if (!keyScopes && !headerScopes) return null;
if (!keyScopes) return headerScopes;
if (!headerScopes) return keyScopes;
const merged: ClientScopes = {};
if (keyScopes.channels && headerScopes.channels) {
merged.channels = headerScopes.channels.filter((ch) =>
keyScopes.channels!.some((allowed) => channelScopePatternCovers(allowed, ch)),
);
} else if (keyScopes.channels) {
merged.channels = keyScopes.channels;
} else if (headerScopes.channels) {
merged.channels = headerScopes.channels;
}
if (keyScopes.actions && headerScopes.actions) {
merged.actions = headerScopes.actions.filter((act) =>
keyScopes.actions!.some((allowed) => actionScopePatternCovers(allowed, act)),
);
} else if (keyScopes.actions) {
merged.actions = keyScopes.actions;
} else if (headerScopes.actions) {
merged.actions = headerScopes.actions;
}
return merged;
}
export function enforceHeadlessScopes(
actor: Pick<HeadlessActorContext, "scopes" | "keyScope">,
check: { action?: string; channelPath?: string },
): void {
if (actor.keyScope && actor.keyScope.kind !== "standard") {
throw forbidden(
`Scoped '${actor.keyScope.kind}' agent keys cannot access headless channel or queue endpoints`,
{ code: "scope_denied" },
);
}
if (!actor.scopes) return;
if (check.action && actor.scopes.actions) {
const allowed = actor.scopes.actions.some((pattern) =>
actionMatchesScopePattern(check.action!, pattern),
);
if (!allowed) {
throw forbidden(`Caller scopes do not allow action '${check.action}'`, {
code: "scope_denied",
action: check.action,
});
}
}
if (check.channelPath && actor.scopes.channels) {
const normalized = normalizeChannelPath(check.channelPath, {
allowSubtreePrefix: true,
}).path;
const allowed = actor.scopes.channels.some((pattern) =>
channelMatchesScopePattern(normalized, pattern),
);
if (!allowed) {
throw forbidden(
`Caller scopes do not allow channel '${check.channelPath}'`,
{
code: "scope_denied",
channel: check.channelPath,
},
);
}
}
}
export async function resolveHeadlessActor(
db: Db,
req: Request,
companyId: string,
opts: {
deploymentMode?: DeploymentMode;
requiredAction?: string;
requiredChannel?: string;
} = {},
): Promise<HeadlessActorContext> {
if (!req.actor || req.actor.type === "none") {
throw unauthorized("Authentication required");
}
const [company] = await db
.select({
id: companies.id,
name: companies.name,
issuePrefix: companies.issuePrefix,
agentIdentityPolicy: companies.agentIdentityPolicy,
defaultResponsibleUserId: companies.defaultResponsibleUserId,
})
.from(companies)
.where(eq(companies.id, companyId));
if (!company) {
throw notFound("Company not found");
}
const deploymentMode: DeploymentMode =
opts.deploymentMode ??
(req.actor.source === "local_implicit" ? "local_trusted" : "authenticated");
const policy = resolveCompanyAgentIdentityPolicy(
company.agentIdentityPolicy,
deploymentMode,
);
const rawProfileHeader = req.header("x-paperclip-actor-profile")?.trim() || null;
const rawScopesHeader = req.header("x-paperclip-actor-scopes")?.trim() || null;
let headerScopes: ClientScopes | null = null;
if (rawScopesHeader) {
let parsedJson: unknown;
try {
parsedJson = JSON.parse(rawScopesHeader);
} catch {
throw badRequest("Malformed X-Paperclip-Actor-Scopes header JSON");
}
const parsed = clientScopesSchema.safeParse(parsedJson);
if (!parsed.success) {
throw badRequest("Invalid X-Paperclip-Actor-Scopes header");
}
headerScopes = parsed.data;
}
const isReadAction = isReadOnlyHeadlessAction(opts.requiredAction);
if (req.actor.type === "agent") {
if (req.actor.keyScope && req.actor.keyScope.kind !== "standard") {
throw forbidden(
`Scoped '${req.actor.keyScope.kind}' agent keys cannot access headless channel or queue endpoints`,
{ code: "scope_denied" },
);
}
const actorAgentId = req.actor.agentId;
if (!actorAgentId || req.actor.companyId !== companyId) {
throw forbidden("Agent does not belong to this company");
}
const localBoardOnBehalf =
deploymentMode === "local_trusted" && req.actor.onBehalfOfUserId === "local-board";
if (req.actor.onBehalfOfUserId?.trim() && !localBoardOnBehalf) {
const membership = req.actor.onBehalfOfMemberships?.find(
(item) => item.companyId === companyId && item.status === "active",
);
if (!membership) {
throw forbidden("Responsible user is unavailable for this company", {
code: "RESPONSIBLE_USER_UNAVAILABLE",
});
}
if (!isReadAction && membership.membershipRole === "viewer") {
throw forbidden("Responsible user is not authorized for write access", {
code: "RESPONSIBLE_USER_UNAUTHORIZED",
});
}
}
const [agentRow] = await db
.select({
id: agents.id,
name: agents.name,
role: agents.role,
status: agents.status,
})
.from(agents)
.where(and(eq(agents.id, actorAgentId), eq(agents.companyId, companyId)));
if (!agentRow || agentRow.status === "terminated" || agentRow.status === "pending_approval") {
throw unauthorized("Authenticated agent record is unavailable");
}
const derivedSlug = deriveAgentUrlKey(agentRow.name, agentRow.id);
if (
rawProfileHeader &&
rawProfileHeader.toLowerCase() !== agentRow.name.toLowerCase() &&
rawProfileHeader.toLowerCase() !== derivedSlug.toLowerCase()
) {
throw forbidden(
`Authenticated agent '@${agentRow.name}' cannot impersonate profile '${rawProfileHeader}'`,
{ code: "profile_locked" },
);
}
const ctx: HeadlessActorContext = {
companyId: company.id,
companyName: company.name,
companyPrefix: company.issuePrefix,
agentIdentityPolicy: policy,
principalType: "agent",
userId: req.actor.onBehalfOfUserId ?? null,
agentId: agentRow.id,
agentName: agentRow.name,
agentRole: agentRow.role,
actorProfile: agentRow.name,
scopes: headerScopes,
keyId: req.actor.keyId ?? null,
keyScope: req.actor.keyScope ?? null,
isInstanceAdmin: false,
responsibleUserId:
req.actor.onBehalfOfUserId ?? company.defaultResponsibleUserId ?? null,
};
enforceHeadlessScopes(ctx, {
action: opts.requiredAction,
channelPath: opts.requiredChannel,
});
return ctx;
}
// Board actor (local_implicit, session, board_key, cloud_tenant, etc.)
const isLocalImplicit = req.actor.source === "local_implicit";
if (
!isLocalImplicit &&
!req.actor.isInstanceAdmin &&
!(req.actor.companyIds ?? []).includes(companyId)
) {
throw forbidden("User does not have access to this company");
}
if (!isLocalImplicit && !req.actor.isInstanceAdmin && Array.isArray(req.actor.memberships)) {
const membership = req.actor.memberships.find((item) => item.companyId === companyId);
if (!membership || membership.status !== "active") {
throw forbidden("User does not have active company access");
}
if (!isReadAction && membership.membershipRole === "viewer") {
throw forbidden("Viewer access is read-only");
}
}
let keyScopes: ClientScopes | null = req.actor.keyScopes ?? null;
let lockedProfile: string | null = req.actor.keyLockedProfile?.trim() || null;
if (req.actor.source === "board_key" && req.actor.keyCompanyId && req.actor.keyCompanyId !== companyId) {
throw forbidden("Board API key is scoped to another company", {
code: "company_scope_denied",
});
}
if (req.actor.source === "board_key" && req.actor.keyId) {
const [keyRow] = await db
.select({
companyId: boardApiKeys.companyId,
lockedProfile: boardApiKeys.lockedProfile,
scopes: boardApiKeys.scopes,
})
.from(boardApiKeys)
.where(eq(boardApiKeys.id, req.actor.keyId));
if (keyRow?.companyId && keyRow.companyId !== companyId) {
throw forbidden("Board API key is scoped to another company", {
code: "company_scope_denied",
});
}
lockedProfile = keyRow?.lockedProfile?.trim() || lockedProfile;
keyScopes = keyRow?.scopes ?? keyScopes;
}
if (
lockedProfile &&
rawProfileHeader &&
rawProfileHeader.toLowerCase() !== lockedProfile.toLowerCase()
) {
throw forbidden(
`Board API key is locked to profile '${lockedProfile}'`,
{ code: "profile_locked" },
);
}
const effectiveProfile = lockedProfile ?? rawProfileHeader;
if (effectiveProfile) {
if (policy === "strict_agent_keys") {
throw forbidden(
`Company policy 'strict_agent_keys' requires a registered agent API key instead of ephemeral profile '${effectiveProfile}'`,
{
code: "agent_key_required",
next: [
`paperclipai agent connect ${effectiveProfile}`,
`paperclipai agent login --name ${effectiveProfile}`,
],
},
);
}
// Check whether an active registered agent with this name or derived urlKey already exists.
const profileLower = effectiveProfile.toLowerCase();
const companyAgents = await db
.select({
id: agents.id,
name: agents.name,
})
.from(agents)
.where(
and(
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
),
);
const registeredAgent = companyAgents.find(
(a) =>
a.name.trim().toLowerCase() === profileLower ||
deriveAgentUrlKey(a.name, a.id).toLowerCase() === profileLower,
);
if (registeredAgent) {
throw conflict(
`Profile '${effectiveProfile}' matches registered agent '@${registeredAgent.name}'. Use that agent's API key instead of an unverified profile header.`,
{
code: "profile_matches_registered_agent",
agentId: registeredAgent.id,
agentName: registeredAgent.name,
next: [
`paperclipai agent connect ${registeredAgent.name}`,
`paperclipai agent login --name ${registeredAgent.name}`,
],
},
);
}
}
const scopes = mergeClientScopes(keyScopes, headerScopes);
const ctx: HeadlessActorContext = {
companyId: company.id,
companyName: company.name,
companyPrefix: company.issuePrefix,
agentIdentityPolicy: policy,
principalType: isLocalImplicit ? "local_trusted" : "user",
userId: req.actor.userId ?? null,
agentId: null,
agentName: null,
agentRole: null,
actorProfile: effectiveProfile,
scopes,
isInstanceAdmin: Boolean(req.actor.isInstanceAdmin),
responsibleUserId:
req.actor.userId && req.actor.userId !== "local-board"
? req.actor.userId
: company.defaultResponsibleUserId ?? req.actor.userId ?? null,
};
enforceHeadlessScopes(ctx, {
action: opts.requiredAction,
channelPath: opts.requiredChannel,
});
return ctx;
}
export function escapeSqlLikePattern(value: string): string {
return value.replace(/[\\%_]/g, "\\$&");
}
export function channelDescendantsCondition(
path: string,
column: typeof channels.path = channels.path,
): SQL<boolean> {
const pattern = `${escapeSqlLikePattern(path)}/%`;
return sql<boolean>`${column} LIKE ${pattern} ESCAPE '\\'`;
}
export function channelSubtreeCondition(
path: string,
column: typeof channels.path = channels.path,
): SQL<boolean> {
return or(eq(column, path), channelDescendantsCondition(path, column)) as SQL<boolean>;
}
export async function findInaccessibleChannelIds(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
companyChannels: Array<{
id: string;
companyId: string;
path: string;
visibility: string;
createdByUserId: string | null;
createdByAgentId: string | null;
}>,
): Promise<string[]> {
if (companyChannels.length === 0) return [];
const bypassPrivacy =
actor.isInstanceAdmin || actor.principalType === "local_trusted";
const privateChannelIds = !bypassPrivacy
? companyChannels.filter((c) => c.visibility === "private").map((c) => c.id)
: [];
const memberChannelIds = new Set<string>();
if (privateChannelIds.length > 0 && (actor.agentId || actor.userId)) {
const subjectConditions = [];
if (actor.agentId) {
subjectConditions.push(
and(
eq(channelAccessMembers.subjectType, "agent"),
eq(channelAccessMembers.subjectId, actor.agentId),
),
);
}
if (actor.userId) {
subjectConditions.push(
and(
eq(channelAccessMembers.subjectType, "user"),
eq(channelAccessMembers.subjectId, actor.userId),
),
);
}
const rows = await dbOrTx
.select({ channelId: channelAccessMembers.channelId })
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
inArray(channelAccessMembers.channelId, privateChannelIds),
or(...subjectConditions),
),
);
for (const r of rows) {
memberChannelIds.add(r.channelId);
}
}
const inaccessible: string[] = [];
for (const ch of companyChannels) {
let scopeOk = true;
try {
enforceHeadlessScopes(actor, { channelPath: ch.path });
} catch {
scopeOk = false;
}
if (!scopeOk) {
inaccessible.push(ch.id);
continue;
}
if (ch.visibility !== "private" || bypassPrivacy) continue;
const isCreator =
(actor.agentId && ch.createdByAgentId === actor.agentId) ||
(actor.userId && ch.createdByUserId === actor.userId);
if (!isCreator && !memberChannelIds.has(ch.id)) {
inaccessible.push(ch.id);
}
}
return inaccessible;
}
export async function canAccessChannel(
dbOrTx: DbOrTx,
channel: {
id: string;
companyId: string;
visibility: string;
createdByUserId: string | null;
createdByAgentId: string | null;
},
actor: HeadlessActorContext,
): Promise<boolean> {
if (channel.companyId !== actor.companyId) return false;
if (channel.visibility !== "private") return true;
if (actor.isInstanceAdmin || actor.principalType === "local_trusted") {
return true;
}
if (actor.agentId && channel.createdByAgentId === actor.agentId) return true;
if (actor.userId && channel.createdByUserId === actor.userId) return true;
const subjectConditions = [];
if (actor.agentId) {
subjectConditions.push(
and(
eq(channelAccessMembers.subjectType, "agent"),
eq(channelAccessMembers.subjectId, actor.agentId),
),
);
}
if (actor.userId) {
subjectConditions.push(
and(
eq(channelAccessMembers.subjectType, "user"),
eq(channelAccessMembers.subjectId, actor.userId),
),
);
}
if (subjectConditions.length === 0) return false;
const [member] = await dbOrTx
.select({ id: channelAccessMembers.id })
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.channelId, channel.id),
or(...subjectConditions),
),
)
.limit(1);
return Boolean(member);
}
export async function assertCanonicalIssueAccessForActor(
dbOrTx: DbOrTx,
authActor: AuthorizationActor,
issue: {
id: string;
companyId: string;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
status: string;
},
action: "issue:read" | "issue:comment" | "issue:mutate",
): Promise<void> {
const access = authorizationService(dbOrTx as Db);
const resource = {
type: "issue" as const,
companyId: issue.companyId,
issueId: issue.id,
projectId: issue.projectId,
parentIssueId: issue.parentId,
assigneeAgentId: issue.assigneeAgentId,
assigneeUserId: issue.assigneeUserId,
status: issue.status,
};
const scope = {
issueId: issue.id,
projectId: issue.projectId,
parentIssueId: issue.parentId,
assigneeAgentId: issue.assigneeAgentId,
assigneeUserId: issue.assigneeUserId,
};
const readDecision = await access.decide({
actor: authActor,
action: "issue:read",
resource,
scope,
});
if (!readDecision.allowed) {
throw notFound("Issue not found");
}
if (action !== "issue:read") {
const writeDecision = await access.decide({
actor: authActor,
action,
resource,
scope,
});
if (!writeDecision.allowed) {
throw forbidden(writeDecision.explanation ?? "Forbidden");
}
}
}
export async function assertCanonicalIssueAccess(
db: Db,
req: Request,
issue: {
id: string;
companyId: string;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
status: string;
},
action: "issue:read" | "issue:comment" | "issue:mutate",
): Promise<void> {
return assertCanonicalIssueAccessForActor(db, req.actor, issue, action);
}
export async function resolveHeadlessIssueReadCondition(db: Db, req: Request) {
if (
req.actor.type === "agent" &&
req.actor.keyScope &&
req.actor.keyScope.kind !== "standard"
) {
return sql<boolean>`false`;
}
return issueReadSqlCondition(db, req.actor);
}
export async function assertChannelAccess(
dbOrTx: DbOrTx,
channel: {
id: string;
companyId: string;
path: string;
visibility: string;
createdByUserId: string | null;
createdByAgentId: string | null;
},
actor: HeadlessActorContext,
): Promise<void> {
enforceHeadlessScopes(actor, { channelPath: channel.path });
const allowed = await canAccessChannel(dbOrTx, channel, actor);
if (!allowed) {
throw notFound(`Channel '${channel.path}' not found`);
}
}
export function allowsUnchanneledScope(
actor: Pick<HeadlessActorContext, "scopes">,
): boolean {
const channelScopes = actor.scopes?.channels;
if (!channelScopes) return true;
return channelScopes.some((pattern) => {
const t = pattern.trim().toLowerCase();
return t === "*" || t === "**";
});
}
export async function assertIssueChannelScopeAccess(
dbOrTx: DbOrTx,
issue: { channelId: string | null },
actor: HeadlessActorContext,
): Promise<{ channel: typeof channels.$inferSelect | null; channelPath: string | null }> {
if (issue.channelId) {
const [ch] = await dbOrTx
.select()
.from(channels)
.where(eq(channels.id, issue.channelId))
.limit(1);
if (ch) {
await assertChannelAccess(dbOrTx, ch, actor);
return { channel: ch, channelPath: ch.path };
}
return { channel: null, channelPath: null };
}
if (!allowsUnchanneledScope(actor)) {
throw forbidden("Caller scopes do not allow accessing unchanneled issues", {
code: "scope_denied",
});
}
return { channel: null, channelPath: null };
}
export function buildSqlIssueLabelFilterCondition(expr: LabelFilterExpr): SQL<boolean> {
switch (expr.kind) {
case "equals":
return sql<boolean>`${issues.kvLabels}->>${expr.key} = ${expr.value}`;
case "in":
return sql<boolean>`${issues.kvLabels}->>${expr.key} IN (${sql.join(
expr.values.map((v) => sql`${v}`),
sql`, `,
)})`;
case "exists":
return sql<boolean>`(jsonb_exists(${issues.kvLabels}, ${expr.key}) OR EXISTS (
SELECT 1
FROM ${issueLabels} il
INNER JOIN ${labels} l ON l.id = il.label_id
WHERE il.issue_id = ${issues.id} AND l.name = ${expr.key}
))`;
}
}
export function buildAuthActorFromHeadless(
actor: HeadlessActorContext,
): AuthorizationActor {
if (actor.principalType === "local_trusted") {
return {
type: "board",
userId: actor.userId ?? "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
if (actor.principalType === "agent" && actor.agentId) {
return {
type: "agent",
agentId: actor.agentId,
companyId: actor.companyId,
source: "agent_key",
...(actor.keyId ? { keyId: actor.keyId } : {}),
...(actor.keyScope ? { keyScope: actor.keyScope } : {}),
...(actor.userId ? { onBehalfOfUserId: actor.userId } : {}),
};
}
return {
type: "board",
userId: actor.userId ?? undefined,
companyIds: [actor.companyId],
isInstanceAdmin: actor.isInstanceAdmin,
ignoreInstanceAdmin: !actor.isInstanceAdmin,
source: "session",
};
}
function toAuthActor(
actorOrAuth: HeadlessActorContext | AuthorizationActor,
): AuthorizationActor {
return "principalType" in actorOrAuth
? buildAuthActorFromHeadless(actorOrAuth)
: actorOrAuth;
}
export async function assertProjectReadAccess(
dbOrTx: DbOrTx,
companyId: string,
projectId: string,
actorOrAuth: HeadlessActorContext | AuthorizationActor,
displayRef = projectId,
): Promise<void> {
const decision = await authorizationService(dbOrTx as unknown as Db).decide({
actor: toAuthActor(actorOrAuth),
action: "project:read",
resource: { type: "project", companyId, projectId },
scope: { projectId },
});
if (!decision.allowed) {
throw notFound(`Project '${displayRef}' not found`);
}
}
export async function resolveProjectReference(
dbOrTx: DbOrTx,
companyId: string,
projectRef: string | null | undefined,
actorOrAuth?: HeadlessActorContext | AuthorizationActor,
): Promise<string | null> {
if (projectRef === undefined || projectRef === null) return null;
const trimmed = projectRef.trim();
if (!trimmed) return null;
let resolvedId: string;
if (isUuidLike(trimmed)) {
const [row] = await dbOrTx
.select({ id: projects.id })
.from(projects)
.where(and(eq(projects.companyId, companyId), eq(projects.id, trimmed)));
if (!row) throw notFound(`Project '${trimmed}' not found`);
resolvedId = row.id;
} else {
const companyProjects = await dbOrTx
.select({ id: projects.id, name: projects.name })
.from(projects)
.where(eq(projects.companyId, companyId));
const lower = trimmed.toLowerCase();
const match =
companyProjects.find(
(p) => deriveProjectUrlKey(p.name, p.id).toLowerCase() === lower,
) ?? companyProjects.find((p) => p.name.trim().toLowerCase() === lower);
if (!match) {
throw notFound(`Project '${trimmed}' not found`);
}
resolvedId = match.id;
}
if (actorOrAuth) {
await assertProjectReadAccess(dbOrTx, companyId, resolvedId, actorOrAuth, trimmed);
}
return resolvedId;
}
export async function resolveIssueByIdOrIdentifier(
dbOrTx: DbOrTx,
idOrIdentifier: string,
expectedCompanyId?: string,
) {
const trimmed = idOrIdentifier.trim();
let row;
if (isUuidLike(trimmed)) {
[row] = await dbOrTx
.select()
.from(issues)
.where(
expectedCompanyId
? and(eq(issues.id, trimmed), eq(issues.companyId, expectedCompanyId))
: eq(issues.id, trimmed),
);
} else {
const normalized = normalizeIssueIdentifier(trimmed) ?? trimmed.toUpperCase();
[row] = await dbOrTx
.select()
.from(issues)
.where(
expectedCompanyId
? and(
sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`,
eq(issues.companyId, expectedCompanyId),
)
: sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`,
);
}
if (!row) {
throw notFound(`Issue '${idOrIdentifier}' not found`);
}
return row;
}
export async function appendBoardEvent(
dbOrTx: DbOrTx,
input: {
companyId: string;
type: BoardEventType;
channelId?: string | null;
channelPath?: string | null;
issueId?: string | null;
identifier?: string | null;
actor: Pick<
HeadlessActorContext,
"principalType" | "userId" | "agentId" | "agentName" | "actorProfile"
> | {
principalType: "system";
userId?: null;
agentId?: null;
agentName?: null;
actorProfile?: string | null;
};
payload?: Record<string, unknown>;
},
): Promise<BoardEventView> {
const actorType: "user" | "agent" | "system" =
input.actor.principalType === "agent"
? "agent"
: input.actor.principalType === "system"
? "system"
: "user";
const actorId =
input.actor.principalType === "agent"
? input.actor.agentId ?? null
: input.actor.principalType === "system"
? "system"
: input.actor.userId ?? null;
const actorName =
input.actor.principalType === "agent"
? input.actor.agentName ?? null
: null;
const actorProfile = input.actor.actorProfile ?? null;
await dbOrTx.execute(
sql`SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${input.companyId}))`,
);
const [inserted] = await dbOrTx
.insert(boardEvents)
.values({
companyId: input.companyId,
eventType: input.type,
channelId: input.channelId ?? null,
channelPath: input.channelPath ?? null,
issueId: input.issueId ?? null,
identifier: input.identifier ?? null,
actorType,
actorId,
actorName,
actorProfile,
payload: input.payload ?? {},
})
.returning();
const seq = Number(inserted!.seq);
return {
cursor: formatEventCursor(seq),
seq,
type: input.type,
companyId: input.companyId,
channel: input.channelPath ?? null,
issueId: input.issueId ?? null,
identifier: input.identifier ?? null,
actor: {
type: actorType,
id: actorId,
name: actorName,
profile: actorProfile,
},
payload: (inserted!.payload ?? {}) as Record<string, unknown>,
createdAt: inserted!.createdAt.toISOString(),
};
}
export async function getLatestCompanyEventCursor(
dbOrTx: DbOrTx,
companyId: string,
): Promise<string> {
const [latest] = await dbOrTx
.select({ seq: boardEvents.seq })
.from(boardEvents)
.where(eq(boardEvents.companyId, companyId))
.orderBy(desc(boardEvents.seq))
.limit(1);
return formatEventCursor(latest ? Number(latest.seq) : 0);
}
export async function loadHeadlessIssueViews(
dbOrTx: DbOrTx,
issueRows: Array<typeof issues.$inferSelect>,
explicitCursor?: string,
): Promise<HeadlessIssueView[]> {
if (issueRows.length === 0) return [];
const issueIds = issueRows.map((r) => r.id);
const channelIds = Array.from(
new Set(issueRows.map((r) => r.channelId).filter((x): x is string => Boolean(x))),
);
const companyId = issueRows[0]!.companyId;
const [channelRows, labelRows, readinessMap, latestEvents, fallbackCursor] =
await Promise.all([
channelIds.length > 0
? dbOrTx
.select({ id: channels.id, path: channels.path })
.from(channels)
.where(inArray(channels.id, channelIds))
: Promise.resolve([]),
dbOrTx
.select({
issueId: issueLabels.issueId,
name: labels.name,
})
.from(issueLabels)
.innerJoin(labels, eq(issueLabels.labelId, labels.id))
.where(inArray(issueLabels.issueId, issueIds)),
listIssueDependencyReadinessMap(dbOrTx as unknown as Db, companyId, issueIds, false),
explicitCursor
? Promise.resolve([])
: dbOrTx
.select({
issueId: boardEvents.issueId,
maxSeq: sql<number>`max(${boardEvents.seq})`,
})
.from(boardEvents)
.where(
and(
eq(boardEvents.companyId, companyId),
inArray(boardEvents.issueId, issueIds),
),
)
.groupBy(boardEvents.issueId),
explicitCursor
? Promise.resolve(explicitCursor)
: getLatestCompanyEventCursor(dbOrTx, companyId),
]);
const channelMap = new Map(channelRows.map((c) => [c.id, c.path]));
const tagMap = new Map<string, string[]>();
for (const row of labelRows) {
const arr = tagMap.get(row.issueId) ?? [];
arr.push(row.name);
tagMap.set(row.issueId, arr);
}
const blockerMap = new Map<string, string[]>();
for (const [issueId, readiness] of readinessMap) {
if (readiness.unresolvedBlockerIssueIds.length > 0) {
blockerMap.set(issueId, readiness.unresolvedBlockerIssueIds);
}
}
const seqMap = new Map<string, number>();
for (const row of latestEvents) {
if (row.issueId && row.maxSeq != null) {
seqMap.set(row.issueId, Number(row.maxSeq));
}
}
return issueRows.map((row) => {
const channelPath = row.channelId ? channelMap.get(row.channelId) ?? null : null;
const isPassivePost =
row.scope === "channel" &&
row.status === "backlog" &&
!row.assigneeAgentId &&
!row.assigneeUserId;
const issueSeq = seqMap.get(row.id);
const cursor =
explicitCursor ??
(issueSeq !== undefined ? formatEventCursor(issueSeq) : fallbackCursor);
return {
id: row.id,
companyId: row.companyId,
identifier: row.identifier ?? row.id,
title: row.title,
description: row.description ?? null,
status: row.status as IssueStatus,
scope: row.scope as IssueScope,
priority: row.priority as IssuePriority,
channelId: row.channelId ?? null,
channel: channelPath,
projectId: row.projectId ?? null,
assigneeAgentId: row.assigneeAgentId ?? null,
assigneeUserId: row.assigneeUserId ?? null,
actorProfile: row.createdByProfile ?? null,
kvLabels: (row.kvLabels ?? {}) as Record<string, string>,
tagLabels: tagMap.get(row.id) ?? [],
blocks: (row.schemaBlocks ?? []) as SchemaBlock[],
resultSchemaRef: row.resultSchemaRef ?? null,
blockedByIssueIds: blockerMap.get(row.id) ?? [],
isPassivePost,
claimEpoch: Number(row.claimEpoch ?? 0),
claimHolderProfile: row.claimHolderProfile ?? null,
claimHolderAgentId: row.claimHolderAgentId ?? null,
claimHolderUserId: row.claimHolderUserId ?? null,
claimLeaseExpiresAt: row.claimLeaseExpiresAt
? row.claimLeaseExpiresAt.toISOString()
: null,
claimAttemptCount: row.claimAttemptCount ?? 0,
cursor,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
});
}
export async function loadHeadlessIssueView(
dbOrTx: DbOrTx,
issueId: string,
explicitCursor?: string,
): Promise<HeadlessIssueView> {
const [row] = await dbOrTx.select().from(issues).where(eq(issues.id, issueId));
if (!row) throw notFound("Issue not found");
const views = await loadHeadlessIssueViews(dbOrTx, [row], explicitCursor);
return views[0]!;
}
export function serializeCommentView(
row: {
id: string;
issueId: string;
body: string;
authorType?: string | null;
authorUserId?: string | null;
authorAgentId?: string | null;
actorProfile?: string | null;
kvLabels?: Record<string, string> | null;
schemaBlocks?: SchemaBlock[] | null;
blocks?: SchemaBlock[] | null;
noSync?: boolean | null;
createdAt: Date;
},
identifier: string,
cursor = "evt_0",
): CommentView {
const authorType: "user" | "agent" | "system" =
row.authorType === "agent" || row.authorAgentId
? "agent"
: row.authorType === "system"
? "system"
: "user";
return {
id: row.id,
issueId: row.issueId,
identifier,
body: row.body,
authorType,
authorUserId: row.authorUserId ?? null,
authorAgentId: row.authorAgentId ?? null,
actorProfile: row.actorProfile ?? null,
kvLabels: (row.kvLabels ?? {}) as Record<string, string>,
blocks: (row.schemaBlocks ?? row.blocks ?? []) as SchemaBlock[],
internal: Boolean(row.noSync),
cursor,
createdAt: row.createdAt.toISOString(),
};
}