Files
PaperClipAI/server/src/services/headless-channel-admin.ts
T
Dotta 0434e7f3aa feat(board): add task assign, atomic handoff, claim filters, cancel/reopen, mid-flight deps, and channel admin (#23415)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Headless channels, fenced task queues, `@paperclipai/shared/sdk`,
and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and
inbox/queue patterns.
> - Real multi-stage workflows immediately hit gaps: there was no
`assign` command to push existing channel posts to managed agents, no
atomic `handoff`/`move` across channels with CAS labels and lease
release, `claim --ready` could not opt into `backlog`/`in_review` or
`--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs`
dependency linking, and `pc channels` could not update queue config,
manage private members, or bind event-driven managed pools.
> - Without these primitives, operators had to drop back to raw `issue
update` calls or non-atomic two-step scripts that race on crash.
> - This pull request adds the complete workflow lifecycle across shared
schemas, modular server services/routes, SDK methods, `pc` CLI commands,
and the `.agents/skills/channels-queues-and-workflows` skill.
> - The benefit is end-to-end single-command support for inbox triage,
single-thread relays, chained channel assembly lines, mid-flight DAG
dependencies, and Day-2 graduation to managed Paperclip agent pools.

## Linked Issues or Issue Description

Refs #23330

**Subsystem affected**
Cross-cutting (multiple of the above)

**Problem or motivation**
Building multi-agent queues and chained workflows on Paperclip channels
required workarounds: assigning an existing post to a registered agent
required raw `issue update --assignee-agent-id <uuid>`; moving an issue
across stage channels with a label update and lease release required
non-atomic multi-step calls; triage or review workers could not opt into
claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`);
tasks could not be cancelled, reopened, or given mid-flight `--needs`
blockers; and channels lacked CLI/API administration for `queueConfig`,
private `channel_access_members`, and `managedPool` auto-dispatch.

**Proposed solution**
Add cohesive REST endpoints, modular services
(`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK
methods, `pc` CLI subcommands, and the `channels-queues-and-workflows`
skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block
--needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels
update`/`members` with event-driven `managedPool` dispatch.

**Alternatives considered**
Leaving these operations to raw `PATCH /api/issues/:id` calls was
rejected because it bypasses fenced claim tokens (`claimEpoch` +
`claimToken`), lacks atomic channel+label+lease transactions, and does
not enforce CAS preconditions or dependency cycle checks.

**Roadmap alignment**
Directly extends the headless channels and queues coordination primitive
introduced in #23330.

## What Changed

- **Shared schemas & SDK (`packages/shared/src/headless/`,
`packages/shared/src/sdk/`):**
- Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and
`TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded
`TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and
`TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and
added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`,
`TaskReopenSchema`, `TaskDependenciesMutationSchema`,
`updateChannelInputSchema`, and `channelMemberInputSchema`.
- Added `task.assigned`, `task.handed_off`, `task.cancelled`,
`task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`.
- Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`,
and `paperclip().channels`.
- **Server services & routes (`server/src/services/`,
`server/src/routes/`):**
- Upgraded `claimTask` and `releaseTaskClaim` in
`headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`,
`in_review` excluding pending interactions), `assignee` (`unassigned`,
`me`, `any`), and atomic channel/label/status updates on release.
- Added `server/src/services/headless-task-workflows.ts` implementing
`assignTask`, `handoffTask`, `cancelTask`, `reopenTask`,
`listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle
detection and fenced lease release).
- Added `server/src/services/headless-channel-admin.ts` implementing
`updateChannel`, `listChannelMembers`, `addChannelMember`,
`removeChannelMember`, and event-driven `dispatchManagedChannelPool`
(zero idle polling).
- Wired routes in `headless-queues-events.ts` and
`headless-channels-schemas.ts`.
- **CLI (`cli/src/commands/board/`):**
- Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`,
`handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`).
- Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`),
`pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc
tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members
list|add|remove`).
- **Skill & Tests:**
- Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and
`examples.md`.
- Added `server/src/__tests__/headless-task-workflows.test.ts` and
updated `tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/server typecheck && pnpm --filter paperclipai typecheck` —
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/headless-task-workflows.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests
passed.
- Live headless CLI test-drive (`pc up --port 3299` in isolated
`PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`,
`tasks claim --mine`, `tasks handoff`, `tasks release --status
in_review`, `tasks claim --status in_review`, `tasks block --needs`,
`tasks deps list`, blocker completion auto-unblock, `tasks cancel`,
`tasks reopen`, `tasks claim --status backlog`, `channels members
add/list/remove`, and `channels update --managed-pool` — all 11
scenarios passed.

## Risks

- Low risk. No database migrations are required; existing
`channels.queue_config`, `channel_access_members`, `issue_relations`,
and `issues` lease columns are reused.
- Default `claim --ready` behavior (`status = todo`, `assignee =
unassigned`) is unchanged; `--status` and `--assignee` are strictly
opt-in, and `--assignee me`/`any` never allows claiming tasks assigned
to another agent or user.
- Note on file size: `server/src/services/headless-task-queue.ts` and
`cli/src/commands/board/tasks.ts` were already over 1,000 lines before
this PR; all new workflow/admin operations were placed in dedicated
sibling modules (`headless-task-workflows.ts`,
`headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing
files bounded.

## Model Used

- Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium,
extended thinking 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
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-01 23:54:54 +00:00

587 lines
17 KiB
TypeScript

import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channelAccessMembers,
channels,
companyMemberships,
} from "@paperclipai/db";
import {
channelMemberInputSchema,
channelQueueConfigSchema,
isUuidLike,
updateChannelInputSchema,
type ChannelMemberView,
type ChannelQueueConfig,
type ChannelView,
} from "@paperclipai/shared";
import { badRequest, forbidden, notFound } from "../errors.js";
import { logger } from "../middleware/logger.js";
import {
logActivity,
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import type { heartbeatService } from "./heartbeat.js";
import {
buildChannelViews,
normalizeChannelPathOrThrow,
resolveAssigneeAgent,
} from "./headless-channels.js";
import {
assertChannelAccess,
enforceHeadlessScopes,
resolveProjectReference,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import {
assertCanConfigureManagedPool,
dispatchManagedChannelPool,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssue,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
} from "./headless-managed-pool.js";
import {
createManagedChannelPoolWorker,
recoverManagedChannelPools,
} from "./headless-managed-pool-worker.js";
export {
assertCanConfigureManagedPool,
createManagedChannelPoolWorker,
dispatchManagedChannelPool,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssue,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
recoverManagedChannelPools,
};
function activityActorFields(actor: HeadlessActorContext) {
return {
actorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const),
actorId:
actor.principalType === "agent"
? actor.agentId ?? "unknown-agent"
: actor.userId ?? "local-board",
agentId: actor.agentId ?? null,
responsibleUserIdOverride: actor.responsibleUserId ?? null,
};
}
export async function resolveChannelByIdOrPath(
dbOrTx: DbOrTx,
companyId: string,
channelRef: string,
): Promise<typeof channels.$inferSelect> {
const trimmed = channelRef.trim();
if (!trimmed) {
throw badRequest("Channel path or ID is required");
}
if (isUuidLike(trimmed)) {
const [byId] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.id, trimmed)))
.limit(1);
if (byId) return byId;
}
const normalized = normalizeChannelPathOrThrow(trimmed, {
allowSubtreePrefix: false,
});
const [byPath] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (!byPath) {
throw notFound(`Channel '${normalized.path}' not found`, {
error: "channel_not_found",
code: "channel_not_found",
});
}
return byPath;
}
async function assertCanManageChannel(
dbOrTx: DbOrTx,
companyId: string,
channel: typeof channels.$inferSelect,
actor: HeadlessActorContext,
): Promise<void> {
enforceHeadlessScopes(actor, {
action: "channels.manage",
channelPath: channel.path,
});
await assertChannelAccess(dbOrTx, channel, actor);
const isOwnerOrCreator =
actor.isInstanceAdmin ||
actor.principalType === "local_trusted" ||
(Boolean(actor.userId) && channel.createdByUserId === actor.userId) ||
(Boolean(actor.agentId) && channel.createdByAgentId === actor.agentId);
let canManage = isOwnerOrCreator;
if (!canManage && actor.userId && actor.principalType === "user") {
const [membership] = await dbOrTx
.select({ role: companyMemberships.membershipRole })
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, actor.userId),
eq(companyMemberships.status, "active"),
inArray(companyMemberships.membershipRole, ["owner", "admin"]),
),
)
.limit(1);
canManage = Boolean(membership);
}
if (!canManage) {
throw forbidden(
"Only the channel creator or a company admin can update channel settings or membership",
{ code: "channel_manage_denied" },
);
}
}
export async function updateChannel(
db: Db,
companyId: string,
channelRef: string,
actor: HeadlessActorContext,
rawInput: unknown,
opts?: { heartbeat?: ReturnType<typeof heartbeatService> },
): Promise<ChannelView> {
const parsed = updateChannelInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsed.error.issues,
},
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const committed = await db.transaction(async (tx) => {
const resolved = await resolveChannelByIdOrPath(tx, companyId, channelRef);
await tx.execute(
sql`SELECT id FROM channels WHERE id = ${resolved.id} AND company_id = ${companyId} FOR UPDATE`,
);
const [existing] = await tx
.select()
.from(channels)
.where(and(eq(channels.id, resolved.id), eq(channels.companyId, companyId)))
.limit(1);
if (!existing) {
throw notFound(`Channel '${channelRef}' not found`);
}
await assertCanManageChannel(tx, companyId, existing, actor);
const updates: Partial<typeof channels.$inferInsert> = {};
if (input.description !== undefined) {
updates.description = input.description;
}
if (input.defaultProjectId !== undefined) {
updates.defaultProjectId =
input.defaultProjectId === null
? null
: await resolveProjectReference(tx, companyId, input.defaultProjectId, actor);
}
if (input.queueConfig !== undefined || input.managedPool !== undefined) {
let nextQueueConfig: ChannelQueueConfig =
input.queueConfig === null
? {}
: input.queueConfig !== undefined
? { ...(existing.queueConfig ?? {}), ...input.queueConfig }
: { ...(existing.queueConfig ?? {}) };
if (input.managedPool !== undefined) {
if (input.managedPool === null) {
const { managedPool: _removed, ...rest } = nextQueueConfig;
nextQueueConfig = rest;
} else {
const resolvedAgentId = await resolveAssigneeAgent(tx, companyId, {
for: input.managedPool.agent,
});
if (!resolvedAgentId) {
throw notFound(`Agent '${input.managedPool.agent}' not found`);
}
nextQueueConfig = {
...nextQueueConfig,
managedPool: {
agentId: resolvedAgentId,
maxConcurrency: input.managedPool.maxConcurrency,
},
};
}
}
const validatedQc = channelQueueConfigSchema.safeParse(nextQueueConfig);
if (!validatedQc.success) {
throw badRequest(
validatedQc.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: validatedQc.error.issues,
},
);
}
if (validatedQc.data.managedPool) {
const effectiveDefaultProjectId =
updates.defaultProjectId !== undefined
? updates.defaultProjectId
: existing.defaultProjectId;
await assertCanConfigureManagedPool(
tx,
companyId,
{
id: existing.id,
visibility: existing.visibility,
createdByAgentId: existing.createdByAgentId,
defaultProjectId: effectiveDefaultProjectId,
},
validatedQc.data.managedPool.agentId,
actor,
);
}
updates.queueConfig = validatedQc.data;
}
const now = new Date();
if (input.archived !== undefined) {
updates.archivedAt = input.archived ? (existing.archivedAt ?? now) : null;
}
updates.updatedAt = now;
const effectiveQueueConfig =
(updates.queueConfig as ChannelQueueConfig | undefined) ?? existing.queueConfig;
const effectiveArchivedAt =
updates.archivedAt !== undefined ? updates.archivedAt : existing.archivedAt;
if (effectiveQueueConfig?.managedPool && !effectiveArchivedAt) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, existing.id);
}
const [updated] = await tx
.update(channels)
.set(updates)
.where(eq(channels.id, existing.id))
.returning();
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.updated",
entityType: "channel",
entityId: updated!.id,
details: {
path: updated!.path,
archived: Boolean(updated!.archivedAt),
hasManagedPool: Boolean(updated!.queueConfig?.managedPool),
},
},
publications,
);
const views = await buildChannelViews(tx, companyId, [updated!]);
return { view: views[0]!, channel: updated! };
});
for (const pub of publications) {
publishActivity(pub);
}
if (
committed.channel.queueConfig?.managedPool &&
!committed.channel.archivedAt &&
opts?.heartbeat
) {
await dispatchManagedChannelPool(db, companyId, committed.channel.id, {
heartbeat: opts.heartbeat,
actor,
}).catch((err) => {
logger.warn(
{ err, companyId, channelId: committed.channel.id },
"managed channel pool dispatch after channel update failed; background worker will retry",
);
});
}
return committed.view;
}
export async function listChannelMembers(
db: Db,
companyId: string,
channelRef: string,
actor: HeadlessActorContext,
): Promise<ChannelMemberView[]> {
const ch = await resolveChannelByIdOrPath(db, companyId, channelRef);
enforceHeadlessScopes(actor, {
action: "read",
channelPath: ch.path,
});
await assertChannelAccess(db, ch, actor);
const rows = await db
.select()
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, ch.id),
),
);
const agentIds = rows
.filter((r) => r.subjectType === "agent")
.map((r) => r.subjectId);
const agentNameMap = new Map<string, string>();
if (agentIds.length > 0) {
const agentRows = await db
.select({ id: agents.id, name: agents.name })
.from(agents)
.where(and(eq(agents.companyId, companyId), inArray(agents.id, agentIds)));
for (const a of agentRows) {
agentNameMap.set(a.id, a.name);
}
}
return rows.map((r) => ({
id: r.id,
channelId: r.channelId,
subjectType: r.subjectType === "agent" ? "agent" : "user",
subjectId: r.subjectId,
displayName:
r.subjectType === "agent" ? (agentNameMap.get(r.subjectId) ?? null) : null,
createdAt: r.createdAt.toISOString(),
}));
}
async function resolveChannelMemberTarget(
dbOrTx: DbOrTx,
companyId: string,
input: {
agent?: string;
userId?: string;
subjectType?: "user" | "agent";
subjectId?: string;
},
): Promise<{ subjectType: "user" | "agent"; subjectId: string; displayName: string | null }> {
if (input.agent) {
const agentId = await resolveAssigneeAgent(dbOrTx, companyId, {
for: input.agent,
});
if (!agentId) {
throw notFound(`Agent '${input.agent}' not found`);
}
const [agentRow] = await dbOrTx
.select({ name: agents.name })
.from(agents)
.where(eq(agents.id, agentId))
.limit(1);
return {
subjectType: "agent",
subjectId: agentId,
displayName: agentRow?.name ?? null,
};
}
if (input.userId) {
return { subjectType: "user", subjectId: input.userId.trim(), displayName: null };
}
if (input.subjectType && input.subjectId) {
if (input.subjectType === "agent") {
const agentId = await resolveAssigneeAgent(dbOrTx, companyId, {
for: input.subjectId,
});
if (!agentId) {
throw notFound(`Agent '${input.subjectId}' not found`);
}
const [agentRow] = await dbOrTx
.select({ name: agents.name })
.from(agents)
.where(eq(agents.id, agentId))
.limit(1);
return {
subjectType: "agent",
subjectId: agentId,
displayName: agentRow?.name ?? null,
};
}
return {
subjectType: "user",
subjectId: input.subjectId.trim(),
displayName: null,
};
}
throw badRequest("Provide 'agent', 'userId', or both 'subjectType' and 'subjectId'");
}
export async function addChannelMember(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawInput: unknown,
): Promise<ChannelMemberView> {
const parsed = channelMemberInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const view = await db.transaction(async (tx) => {
const ch = await resolveChannelByIdOrPath(tx, companyId, input.channel);
await assertCanManageChannel(tx, companyId, ch, actor);
const target = await resolveChannelMemberTarget(tx, companyId, input);
const [inserted] = await tx
.insert(channelAccessMembers)
.values({
companyId,
channelId: ch.id,
subjectType: target.subjectType,
subjectId: target.subjectId,
})
.onConflictDoNothing({
target: [
channelAccessMembers.channelId,
channelAccessMembers.subjectType,
channelAccessMembers.subjectId,
],
})
.returning();
const row =
inserted ??
(
await tx
.select()
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, target.subjectType),
eq(channelAccessMembers.subjectId, target.subjectId),
),
)
.limit(1)
)[0]!;
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.member_added",
entityType: "channel",
entityId: ch.id,
details: {
path: ch.path,
subjectType: target.subjectType,
subjectId: target.subjectId,
},
},
publications,
);
return {
id: row.id,
channelId: row.channelId,
subjectType: row.subjectType === "agent" ? ("agent" as const) : ("user" as const),
subjectId: row.subjectId,
displayName: target.displayName,
createdAt: row.createdAt.toISOString(),
};
});
for (const pub of publications) {
publishActivity(pub);
}
return view;
}
export async function removeChannelMember(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawInput: unknown,
): Promise<{ removed: boolean }> {
const parsed = channelMemberInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const removed = await db.transaction(async (tx) => {
const ch = await resolveChannelByIdOrPath(tx, companyId, input.channel);
await assertCanManageChannel(tx, companyId, ch, actor);
const target = await resolveChannelMemberTarget(tx, companyId, input);
const deleted = await tx
.delete(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, target.subjectType),
eq(channelAccessMembers.subjectId, target.subjectId),
),
)
.returning({ id: channelAccessMembers.id });
if (deleted.length > 0) {
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.member_removed",
entityType: "channel",
entityId: ch.id,
details: {
path: ch.path,
subjectType: target.subjectType,
subjectId: target.subjectId,
},
},
publications,
);
}
return deleted.length > 0;
});
for (const pub of publications) {
publishActivity(pub);
}
return { removed };
}