mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
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
This commit is contained in:
1 parent
fcb8fc5deb
commit
0434e7f3aa
30 files changed
+5985
-67
No files matched your search
@@ -10,12 +10,14 @@ import {
|
||||
issueLabels,
|
||||
issueRelations,
|
||||
issues,
|
||||
issueThreadInteractions,
|
||||
issueWorkProducts,
|
||||
labels,
|
||||
projects,
|
||||
toolActionRequests,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
applyKvLabelMutation,
|
||||
BUILT_IN_COMPANY_SCHEMAS,
|
||||
normalizeChannelPath,
|
||||
parseDurationMs,
|
||||
@@ -30,6 +32,7 @@ import {
|
||||
type BoardEventType,
|
||||
type BoardEventView,
|
||||
type ChannelQueueConfig,
|
||||
type ClaimableTaskStatus,
|
||||
type HeadlessIssueView,
|
||||
type LabelFilterExpr,
|
||||
type SchemaBlock,
|
||||
@@ -37,6 +40,7 @@ import {
|
||||
} from "@paperclipai/shared";
|
||||
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import { ensureChannel, validateWritableKvLabelsOrThrow } from "./headless-channels.js";
|
||||
import { issueTreeControlService } from "./issue-tree-control.js";
|
||||
import { listIssueDependencyReadinessMap } from "./issues.js";
|
||||
import { assertRequiredQualityReviewComplete } from "./required-quality-review.js";
|
||||
@@ -65,6 +69,10 @@ const CLAIM_WAKE_EVENTS = new Set<BoardEventType>([
|
||||
"task.lease_released",
|
||||
"task.lease_expired_requeued",
|
||||
"task.unblocked",
|
||||
"task.assigned",
|
||||
"task.handed_off",
|
||||
"task.reopened",
|
||||
"task.dependencies_changed",
|
||||
"interaction.resolved",
|
||||
"labels.changed",
|
||||
]);
|
||||
@@ -296,6 +304,18 @@ export async function claimTask(
|
||||
? await resolveProjectReference(db, companyId, parsed.projectId, actor)
|
||||
: null;
|
||||
|
||||
const statusSet = new Set<ClaimableTaskStatus>();
|
||||
if (parsed.status !== undefined) {
|
||||
const items = Array.isArray(parsed.status) ? parsed.status : [parsed.status];
|
||||
for (const s of items) statusSet.add(s);
|
||||
}
|
||||
if (parsed.statuses !== undefined) {
|
||||
for (const s of parsed.statuses) statusSet.add(s);
|
||||
}
|
||||
const allowedStatuses: ClaimableTaskStatus[] =
|
||||
statusSet.size > 0 ? Array.from(statusSet) : ["todo"];
|
||||
const assigneeMode = parsed.assignee ?? "unassigned";
|
||||
|
||||
const tryClaimOnce = async (): Promise<TaskClaimView | null> => {
|
||||
const committed = await db.transaction(async (tx) => {
|
||||
let lockedIssue: typeof issues.$inferSelect | undefined;
|
||||
@@ -367,12 +387,44 @@ export async function claimTask(
|
||||
reason: "assigned_to_other_user",
|
||||
});
|
||||
}
|
||||
if (fresh.status !== "todo") {
|
||||
if (!allowedStatuses.includes(fresh.status as ClaimableTaskStatus)) {
|
||||
throw conflict("task_not_claimable", {
|
||||
code: "task_not_claimable",
|
||||
status: fresh.status,
|
||||
});
|
||||
}
|
||||
if (
|
||||
fresh.claimTokenHash !== null ||
|
||||
fresh.claimLeaseExpiresAt !== null ||
|
||||
fresh.checkoutRunId !== null ||
|
||||
fresh.executionRunId !== null
|
||||
) {
|
||||
throw conflict("task_not_claimable", {
|
||||
code: "task_not_claimable",
|
||||
status: fresh.status,
|
||||
reason: "already_claimed_or_running",
|
||||
});
|
||||
}
|
||||
if (fresh.status === "in_review") {
|
||||
const [pendingInteraction] = await tx
|
||||
.select({ id: issueThreadInteractions.id })
|
||||
.from(issueThreadInteractions)
|
||||
.where(
|
||||
and(
|
||||
eq(issueThreadInteractions.companyId, companyId),
|
||||
eq(issueThreadInteractions.issueId, fresh.id),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (pendingInteraction) {
|
||||
throw conflict("task_not_claimable", {
|
||||
code: "task_not_claimable",
|
||||
status: fresh.status,
|
||||
reason: "pending_interaction",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const readiness = (
|
||||
await listIssueDependencyReadinessMap(
|
||||
@@ -480,9 +532,14 @@ export async function claimTask(
|
||||
|
||||
const conditions = [
|
||||
sql`i.company_id = ${companyId}`,
|
||||
sql`i.status = 'todo'`,
|
||||
sql`i.assignee_agent_id IS NULL`,
|
||||
sql`i.assignee_user_id IS NULL`,
|
||||
sql`i.status IN (${sql.join(
|
||||
allowedStatuses.map((s) => sql`${s}`),
|
||||
sql`, `,
|
||||
)})`,
|
||||
sql`i.claim_token_hash IS NULL`,
|
||||
sql`i.claim_lease_expires_at IS NULL`,
|
||||
sql`i.checkout_run_id IS NULL`,
|
||||
sql`i.execution_run_id IS NULL`,
|
||||
sql`i.hidden_at IS NULL`,
|
||||
sql`i.conversation_agent_id IS NULL`,
|
||||
sql`NOT EXISTS (
|
||||
@@ -512,6 +569,44 @@ export async function claimTask(
|
||||
)`,
|
||||
];
|
||||
|
||||
if (assigneeMode === "unassigned") {
|
||||
conditions.push(sql`i.assignee_agent_id IS NULL`);
|
||||
conditions.push(sql`i.assignee_user_id IS NULL`);
|
||||
} else if (assigneeMode === "me") {
|
||||
if (actor.agentId) {
|
||||
conditions.push(sql`i.assignee_agent_id = ${actor.agentId}`);
|
||||
} else if (actor.userId) {
|
||||
conditions.push(sql`i.assignee_user_id = ${actor.userId}`);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else if (assigneeMode === "any") {
|
||||
if (actor.agentId) {
|
||||
conditions.push(
|
||||
sql`((i.assignee_agent_id IS NULL AND i.assignee_user_id IS NULL) OR i.assignee_agent_id = ${actor.agentId})`,
|
||||
);
|
||||
} else if (actor.userId) {
|
||||
conditions.push(
|
||||
sql`((i.assignee_agent_id IS NULL AND i.assignee_user_id IS NULL) OR i.assignee_user_id = ${actor.userId})`,
|
||||
);
|
||||
} else {
|
||||
conditions.push(sql`i.assignee_agent_id IS NULL`);
|
||||
conditions.push(sql`i.assignee_user_id IS NULL`);
|
||||
}
|
||||
}
|
||||
|
||||
if (allowedStatuses.includes("in_review")) {
|
||||
conditions.push(
|
||||
sql`(i.status <> 'in_review' OR NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM issue_thread_interactions iti
|
||||
WHERE iti.company_id = i.company_id
|
||||
AND iti.issue_id = i.id
|
||||
AND iti.status = 'pending'
|
||||
))`,
|
||||
);
|
||||
}
|
||||
|
||||
if (eligibleChannelIds !== null) {
|
||||
conditions.push(
|
||||
sql`i.channel_id IN (${sql.join(
|
||||
@@ -909,13 +1004,61 @@ export async function releaseTaskClaim(
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
let finalChannel = targetChannel;
|
||||
if (input.channel !== undefined) {
|
||||
finalChannel = await ensureChannel(tx, issue.companyId, actor, {
|
||||
path: input.channel,
|
||||
});
|
||||
}
|
||||
|
||||
let nextKvLabels = (issue.kvLabels ?? {}) as Record<string, string>;
|
||||
let labelsChanged = false;
|
||||
if (input.labels !== undefined || (input.unsetLabels && input.unsetLabels.length > 0)) {
|
||||
if (input.labels) {
|
||||
validateWritableKvLabelsOrThrow(input.labels);
|
||||
}
|
||||
if (input.unsetLabels) {
|
||||
for (const k of input.unsetLabels) {
|
||||
if (k.startsWith("paperclip.")) {
|
||||
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
|
||||
error: "reserved_label",
|
||||
code: "reserved_label",
|
||||
key: k,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const applied = applyKvLabelMutation(nextKvLabels, {
|
||||
...(input.labels ? { set: input.labels } : {}),
|
||||
...(input.unsetLabels ? { unset: input.unsetLabels } : {}),
|
||||
});
|
||||
if (!applied.ok) {
|
||||
throw conflict("label_conflict", {
|
||||
code: "label_conflict",
|
||||
conflictingKeys: applied.conflictingKeys,
|
||||
});
|
||||
}
|
||||
nextKvLabels = applied.labels;
|
||||
labelsChanged = true;
|
||||
}
|
||||
|
||||
const nextStatus = input.status ?? "todo";
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
|
||||
if (nextStatus === "todo" && (finalChannel?.id ?? issue.channelId)) {
|
||||
await notifyDeliveryWork(
|
||||
tx,
|
||||
DELIVERY_QUEUES.managedChannelPools,
|
||||
(finalChannel?.id ?? issue.channelId)!,
|
||||
);
|
||||
}
|
||||
|
||||
const nextEpoch = Number(issue.claimEpoch ?? 0) + 1;
|
||||
const [updated] = await tx
|
||||
.update(issues)
|
||||
.set({
|
||||
status: "todo",
|
||||
status: nextStatus,
|
||||
...(finalChannel ? { channelId: finalChannel.id } : {}),
|
||||
...(labelsChanged ? { kvLabels: nextKvLabels } : {}),
|
||||
claimEpoch: nextEpoch,
|
||||
claimTokenHash: null,
|
||||
claimLeasedAt: null,
|
||||
@@ -929,6 +1072,13 @@ export async function releaseTaskClaim(
|
||||
.where(eq(issues.id, issue.id))
|
||||
.returning();
|
||||
|
||||
if (finalChannel && finalChannel.id !== issue.channelId) {
|
||||
await tx
|
||||
.update(channels)
|
||||
.set({ lastActivityAt: now, updatedAt: now })
|
||||
.where(eq(channels.id, finalChannel.id));
|
||||
}
|
||||
|
||||
if (input.comment?.trim()) {
|
||||
await tx.insert(issueComments).values({
|
||||
companyId: issue.companyId,
|
||||
@@ -947,6 +1097,8 @@ export async function releaseTaskClaim(
|
||||
entityId: updated!.id,
|
||||
details: {
|
||||
claimEpoch: Number(updated!.claimEpoch ?? 0),
|
||||
status: nextStatus,
|
||||
...(finalChannel ? { channel: finalChannel.path } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -954,31 +1106,37 @@ export async function releaseTaskClaim(
|
||||
companyId: issue.companyId,
|
||||
type: "task.lease_released",
|
||||
channelId: updated!.channelId,
|
||||
channelPath: targetChannel?.path ?? null,
|
||||
channelPath: finalChannel?.path ?? null,
|
||||
issueId: updated!.id,
|
||||
identifier: updated!.identifier ?? updated!.id,
|
||||
actor,
|
||||
payload: {
|
||||
claimEpoch: Number(updated!.claimEpoch ?? 0),
|
||||
},
|
||||
});
|
||||
|
||||
const readyEvent = await appendBoardEvent(tx, {
|
||||
companyId: issue.companyId,
|
||||
type: "task.ready",
|
||||
channelId: updated!.channelId,
|
||||
channelPath: targetChannel?.path ?? null,
|
||||
issueId: updated!.id,
|
||||
identifier: updated!.identifier ?? updated!.id,
|
||||
actor,
|
||||
payload: {
|
||||
status: nextStatus,
|
||||
kvLabels: updated!.kvLabels ?? {},
|
||||
},
|
||||
});
|
||||
|
||||
const events: BoardEventView[] = [releasedEvent];
|
||||
if (nextStatus === "todo") {
|
||||
const readyEvent = await appendBoardEvent(tx, {
|
||||
companyId: issue.companyId,
|
||||
type: "task.ready",
|
||||
channelId: updated!.channelId,
|
||||
channelPath: finalChannel?.path ?? null,
|
||||
issueId: updated!.id,
|
||||
identifier: updated!.identifier ?? updated!.id,
|
||||
actor,
|
||||
payload: {
|
||||
kvLabels: updated!.kvLabels ?? {},
|
||||
},
|
||||
});
|
||||
events.push(readyEvent);
|
||||
}
|
||||
|
||||
return {
|
||||
events: [releasedEvent, readyEvent],
|
||||
cursor: readyEvent.cursor,
|
||||
events,
|
||||
cursor: events[events.length - 1]!.cursor,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1187,6 +1345,11 @@ export async function completeTaskClaim(
|
||||
if (issue.claimTokenHash !== null) {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
|
||||
}
|
||||
await notifyDeliveryWork(
|
||||
tx,
|
||||
DELIVERY_QUEUES.managedChannelPools,
|
||||
JSON.stringify({ companyId: issue.companyId, issueId: issue.id }),
|
||||
);
|
||||
|
||||
const [updated] = await tx
|
||||
.update(issues)
|
||||
@@ -1760,6 +1923,10 @@ export function createClaimLeaseExpiryWorker(db: Db) {
|
||||
const shouldRequeue = attemptCount < maxAttempts;
|
||||
const nextEpoch = Number(row.claimEpoch ?? 0) + 1;
|
||||
|
||||
if (shouldRequeue && row.channelId) {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, row.channelId);
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(issues)
|
||||
.set({
|
||||
|
||||
Reference in new issue
Block a user