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

514 lines
15 KiB
TypeScript

import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
channels,
issueComments,
issueRelations,
issues,
} from "@paperclipai/db";
import {
TaskDependenciesMutationSchema,
type IssueStatus,
type TaskDependenciesView,
type TaskDependencyItemView,
} from "@paperclipai/shared";
import { badRequest, conflict, notFound } from "../errors.js";
import { authorizationService, type AuthorizationActor } from "./authorization.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import {
allowsUnchanneledScope,
appendBoardEvent,
assertIssueChannelScopeAccess,
canAccessChannel,
enforceHeadlessScopes,
getLatestCompanyEventCursor,
publishCommittedBoardEvent,
resolveIssueByIdOrIdentifier,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js";
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 ?? "board",
agentId: actor.agentId ?? null,
responsibleUserId: actor.responsibleUserId ?? null,
};
}
function commentAuthorFields(actor: HeadlessActorContext) {
return {
authorType: actor.principalType === "agent" ? ("agent" as const) : ("user" as const),
authorAgentId: actor.agentId ?? null,
authorUserId: actor.agentId ? null : (actor.userId ?? null),
actorProfile: actor.actorProfile ?? null,
};
}
function isChannelAllowedByScopes(
actor: Pick<HeadlessActorContext, "scopes" | "keyScope">,
channelPath: string,
): boolean {
try {
enforceHeadlessScopes(actor, { channelPath });
return true;
} catch {
return false;
}
}
function toAuthorizationActor(actor: HeadlessActorContext): AuthorizationActor {
if (actor.principalType === "agent" && actor.agentId) {
return {
type: "agent",
agentId: actor.agentId,
companyId: actor.companyId,
};
}
if (actor.principalType === "local_trusted") {
return {
type: "board",
userId: actor.userId ?? "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
return {
type: "board",
userId: actor.userId ?? "unknown-user",
source: "session",
isInstanceAdmin: actor.isInstanceAdmin,
};
}
async function canReadDependencyIssue(
dbOrTx: DbOrTx,
actor: HeadlessActorContext,
companyId: string,
row: {
id: string;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
},
): Promise<boolean> {
const decision = await authorizationService(dbOrTx as unknown as Db).decide({
action: "issue:read",
actor: toAuthorizationActor(actor),
resource: {
type: "issue",
companyId,
issueId: row.id,
projectId: row.projectId,
parentIssueId: row.parentId,
assigneeAgentId: row.assigneeAgentId,
assigneeUserId: row.assigneeUserId,
},
scope: { companyId },
});
return decision.allowed;
}
async function filterVisibleDependencyItems(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
rows: Array<{
id: string;
identifier: string | null;
title: string;
status: string;
channelId: string | null;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
}>,
): Promise<TaskDependencyItemView[]> {
if (rows.length === 0) return [];
const channelIds = Array.from(
new Set(rows.map((r) => r.channelId).filter((id): id is string => Boolean(id))),
);
const channelMap = new Map<string, typeof channels.$inferSelect>();
if (channelIds.length > 0) {
const chRows = await dbOrTx
.select()
.from(channels)
.where(inArray(channels.id, channelIds));
for (const ch of chRows) {
channelMap.set(ch.id, ch);
}
}
const unchanneledAllowed = allowsUnchanneledScope(actor);
const visible: TaskDependencyItemView[] = [];
for (const row of rows) {
if (row.channelId) {
const ch = channelMap.get(row.channelId);
if (ch) {
if (!isChannelAllowedByScopes(actor, ch.path)) continue;
if (!(await canAccessChannel(dbOrTx, ch, actor))) continue;
}
} else if (!unchanneledAllowed) {
continue;
}
if (!(await canReadDependencyIssue(dbOrTx, actor, companyId, row))) {
continue;
}
visible.push({
id: row.id,
identifier: row.identifier ?? row.id,
title: row.title,
status: row.status as IssueStatus,
});
}
return visible;
}
async function loadDependenciesView(
dbOrTx: DbOrTx,
issue: typeof issues.$inferSelect,
actor: HeadlessActorContext,
cursor: string,
): Promise<TaskDependenciesView> {
const [incoming, outgoing] = await Promise.all([
dbOrTx
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
status: issues.status,
channelId: issues.channelId,
projectId: issues.projectId,
parentId: issues.parentId,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
})
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.issueId))
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.relatedIssueId, issue.id),
eq(issueRelations.type, "blocks"),
),
),
dbOrTx
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
status: issues.status,
channelId: issues.channelId,
projectId: issues.projectId,
parentId: issues.parentId,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
})
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.relatedIssueId))
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.issueId, issue.id),
eq(issueRelations.type, "blocks"),
),
),
]);
const [blockedBy, blocks] = await Promise.all([
filterVisibleDependencyItems(dbOrTx, issue.companyId, actor, incoming),
filterVisibleDependencyItems(dbOrTx, issue.companyId, actor, outgoing),
]);
return {
issueId: issue.id,
identifier: issue.identifier ?? issue.id,
status: issue.status as IssueStatus,
blockedBy,
blocks,
cursor,
};
}
async function wouldIntroduceDependencyCycle(
tx: DbOrTx,
companyId: string,
targetIssueId: string,
candidateBlockerIds: string[],
): Promise<boolean> {
// Adding edge: blocker -> targetIssueId.
// A cycle exists iff targetIssueId can already reach any candidateBlocker via existing `blocks` edges.
const targetSet = new Set(candidateBlockerIds);
if (targetSet.has(targetIssueId)) return true;
const visited = new Set<string>([targetIssueId]);
let frontier: string[] = [targetIssueId];
while (frontier.length > 0) {
const rows = await tx
.select({ relatedIssueId: issueRelations.relatedIssueId })
.from(issueRelations)
.where(
and(
eq(issueRelations.companyId, companyId),
inArray(issueRelations.issueId, frontier),
eq(issueRelations.type, "blocks"),
),
);
const nextFrontier: string[] = [];
for (const row of rows) {
if (targetSet.has(row.relatedIssueId)) return true;
if (!visited.has(row.relatedIssueId)) {
visited.add(row.relatedIssueId);
nextFrontier.push(row.relatedIssueId);
}
}
frontier = nextFrontier;
}
return false;
}
export async function listTaskDependencies(
db: Db,
issueId: string,
actor: HeadlessActorContext,
): Promise<TaskDependenciesView> {
enforceHeadlessScopes(actor, { action: "read" });
const [issue] = await db
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)))
.limit(1);
if (!issue) {
throw notFound("Issue not found");
}
await assertIssueChannelScopeAccess(db, issue, actor);
const cursor = await getLatestCompanyEventCursor(db, issue.companyId);
return loadDependenciesView(db, issue, actor, cursor);
}
export async function mutateTaskDependencies(
db: Db,
issueId: string,
actor: HeadlessActorContext,
rawInput: unknown,
headerToken?: string,
): Promise<TaskDependenciesView> {
enforceHeadlessScopes(actor, { action: "tasks.dependencies" });
const parsed = TaskDependenciesMutationSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const token = extractClaimToken(input.claimToken, headerToken);
// Resolve and authorize bounded, deduplicated dependency references BEFORE
// taking the company-wide dependency advisory lock so per-element lookups
// and authorization checks never hold the lock.
const uniqueAddRefs = Array.from(new Set((input.add ?? []).map((r) => r.trim()).filter(Boolean)));
const uniqueRemoveRefs = Array.from(
new Set((input.remove ?? []).map((r) => r.trim()).filter(Boolean)),
);
const addIds: string[] = [];
for (const ref of uniqueAddRefs) {
const dep = await resolveIssueByIdOrIdentifier(db, ref, actor.companyId);
await assertIssueChannelScopeAccess(db, dep, actor);
if (!(await canReadDependencyIssue(db, actor, actor.companyId, dep))) {
throw notFound(`Issue '${ref}' not found`);
}
if (dep.id === issueId) {
throw badRequest("A task cannot depend on itself", {
code: "cyclic_dependencies",
});
}
addIds.push(dep.id);
}
const removeIds: string[] = [];
for (const ref of uniqueRemoveRefs) {
const dep = await resolveIssueByIdOrIdentifier(db, ref, actor.companyId);
await assertIssueChannelScopeAccess(db, dep, actor);
if (!(await canReadDependencyIssue(db, actor, actor.companyId, dep))) {
throw notFound(`Issue '${ref}' not found`);
}
removeIds.push(dep.id);
}
const committed = await db.transaction(async (tx) => {
// Serialize company dependency graph mutations before locking/checking cycles
// so concurrent requests on different target issues cannot create a cycle.
await tx.execute(
sql`SELECT pg_advisory_xact_lock(hashtextextended(${`${actor.companyId}:issue_deps`}, 0))`,
);
await tx.execute(
sql`SELECT id FROM issues WHERE id = ${issueId} AND company_id = ${actor.companyId} FOR UPDATE`,
);
const [issue] = await tx
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)));
if (!issue) {
throw notFound("Issue not found");
}
const { channel: targetChannel } = await assertIssueChannelScopeAccess(
tx,
issue,
actor,
);
const epochMatches =
input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch;
const hadActiveLease = issue.claimTokenHash !== null;
if (hadActiveLease) {
if (input.releaseLease || token !== undefined || input.claimEpoch !== undefined) {
if (
issue.status !== "in_progress" ||
!verifyClaimToken(issue.claimTokenHash, token) ||
!epochMatches
) {
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
}
} else if (token !== undefined || !epochMatches) {
// Reject stale supplied credentials even when no lease currently exists,
// while allowing `releaseLease: true` with no credentials on an unclaimed task.
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
if (addIds.length > 0) {
const hasCycle = await wouldIntroduceDependencyCycle(
tx,
issue.companyId,
issue.id,
addIds,
);
if (hasCycle) {
throw badRequest("Adding dependency would create a cycle", {
code: "cyclic_dependencies",
});
}
await tx
.insert(issueRelations)
.values(
Array.from(new Set(addIds)).map((blockerId) => ({
companyId: issue.companyId,
issueId: blockerId,
relatedIssueId: issue.id,
type: "blocks" as const,
createdByAgentId: actor.agentId ?? null,
createdByUserId: actor.agentId ? null : (actor.userId ?? null),
})),
)
.onConflictDoNothing();
}
if (removeIds.length > 0) {
if (issue.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
}
await tx
.delete(issueRelations)
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.relatedIssueId, issue.id),
eq(issueRelations.type, "blocks"),
inArray(issueRelations.issueId, removeIds),
),
);
}
let currentIssue = issue;
if (input.releaseLease && issue.claimTokenHash !== null) {
const now = new Date();
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
const [updated] = await tx
.update(issues)
.set({
status: "todo",
claimEpoch: Number(issue.claimEpoch ?? 0) + 1,
claimTokenHash: null,
claimLeasedAt: null,
claimLeaseExpiresAt: null,
claimHolderAgentId: null,
claimHolderUserId: null,
claimHolderProfile: null,
claimAttemptCount: Math.max(0, (issue.claimAttemptCount ?? 0) - 1),
updatedAt: now,
})
.where(eq(issues.id, issue.id))
.returning();
currentIssue = updated!;
}
if (input.comment?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
issueId: issue.id,
body: input.comment.trim(),
...commentAuthorFields(actor),
});
}
await tx.insert(activityLog).values({
companyId: issue.companyId,
...activityActorFields(actor),
action: "issue.dependencies_changed",
entityType: "issue",
entityId: issue.id,
details: {
added: addIds,
removed: removeIds,
releasedLease: Boolean(input.releaseLease && issue.claimTokenHash !== null),
},
});
const event = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.dependencies_changed",
channelId: currentIssue.channelId,
channelPath: targetChannel?.path ?? null,
issueId: currentIssue.id,
identifier: currentIssue.identifier ?? currentIssue.id,
actor,
payload: {
added: addIds,
removed: removeIds,
status: currentIssue.status,
},
});
const view = await loadDependenciesView(tx, currentIssue, actor, event.cursor);
return { view, event };
});
publishCommittedBoardEvent(committed.event);
return committed.view;
}