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:
Dotta authored and GitHub committed 2026-12-01 23:54:54 +00:00
1 parent fcb8fc5deb
commit 0434e7f3aa
30 files changed
+5985 -67

No files matched your search

+204 -1
View File
@@ -1,6 +1,6 @@
import pc from "picocolors";
import type { Command } from "commander";
import type { ChannelPage, ChannelView, ThreadDetailView } from "@paperclipai/shared/sdk";
import { parseDurationMs, type ChannelPage, type ChannelView, type ThreadDetailView } from "@paperclipai/shared/sdk";
import { channelsCommand } from "../channels.js";
import {
addBoardClientOptions,
@@ -350,6 +350,209 @@ function configureChannelsSubtree(cmd: Command, opts: { forceBoard: boolean }):
}
}),
);
addBoardClientOptions(
cmd
.command("update")
.alias("config")
.description("Update channel description, default project, archive state, or queue/managed-pool config")
.argument("<path>", "Channel path (e.g. build/auth)")
.option("--description <text>", "Channel description")
.option("--project <id-or-slug>", "Default project ID or slug")
.option("--clear-project", "Clear default project")
.option("--archive", "Archive channel")
.option("--unarchive", "Unarchive channel")
.option("--lease <dur>", "Default lease duration (e.g. 5m)")
.option("--max-lease <dur>", "Maximum lease duration (e.g. 1h)")
.option("--max-attempts <n>", "Max claim attempts before poison-pill block", (v) => Number.parseInt(v, 10))
.option("--ordering <mode>", "Queue ordering (priority_fifo or strict_fifo)")
.option("--managed-pool <agent>", "Bind a managed Paperclip agent to auto-drain this channel")
.option("--max-concurrency <n>", "Max concurrent tasks for --managed-pool (default: 1)", (v) => Number.parseInt(v, 10))
.option("--clear-managed-pool", "Remove managed pool binding from this channel")
.action(
async (
channelPath: string,
updateOpts: BoardCommonOptions & {
description?: string;
project?: string;
clearProject?: boolean;
archive?: boolean;
unarchive?: boolean;
lease?: string;
maxLease?: string;
maxAttempts?: number;
ordering?: string;
managedPool?: string;
maxConcurrency?: number;
clearManagedPool?: boolean;
},
) => {
try {
const resolved = resolveBoardClient(updateOpts);
const queueConfig: Record<string, unknown> = {};
if (updateOpts.lease) {
queueConfig.defaultLeaseSec = Math.max(
30,
Math.round(parseDurationMs(updateOpts.lease) / 1000),
);
}
if (updateOpts.maxLease) {
queueConfig.maxLeaseSec = Math.max(
30,
Math.round(parseDurationMs(updateOpts.maxLease) / 1000),
);
}
if (updateOpts.maxAttempts !== undefined && Number.isFinite(updateOpts.maxAttempts)) {
queueConfig.maxClaimAttempts = updateOpts.maxAttempts;
}
if (updateOpts.ordering) {
if (updateOpts.ordering !== "priority_fifo" && updateOpts.ordering !== "strict_fifo") {
throw new Error('Invalid --ordering: expected "priority_fifo" or "strict_fifo"');
}
queueConfig.ordering = updateOpts.ordering;
}
const updated = await resolved.client.channels.update(channelPath, {
...(updateOpts.description !== undefined
? { description: updateOpts.description }
: {}),
...(updateOpts.clearProject
? { defaultProjectId: null }
: updateOpts.project
? { defaultProjectId: updateOpts.project }
: {}),
...(updateOpts.archive
? { archived: true }
: updateOpts.unarchive
? { archived: false }
: {}),
...(Object.keys(queueConfig).length > 0 ? { queueConfig } : {}),
...(updateOpts.clearManagedPool
? { managedPool: null }
: updateOpts.managedPool
? {
managedPool: {
agent: updateOpts.managedPool,
maxConcurrency: updateOpts.maxConcurrency ?? 1,
},
}
: {}),
});
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.path);
return;
}
console.log(pc.green(`Updated channel #${updated.path}.`));
} catch (err) {
handleBoardError(err, updateOpts);
}
},
),
);
const membersCmd = cmd
.command("members")
.description("Manage access members on a channel (e.g. --private channels)");
addBoardClientOptions(
membersCmd
.command("list")
.description("List explicit access members on a channel")
.argument("<path>", "Channel path")
.action(async (channelPath: string, listOpts: BoardCommonOptions) => {
try {
const resolved = resolveBoardClient(listOpts);
const members = await resolved.client.channels.members.list(channelPath);
if (resolved.json) {
console.log(JSON.stringify({ items: members }, null, 2));
return;
}
if (members.length === 0) {
console.log(pc.dim(`No explicit members on #${channelPath}.`));
return;
}
for (const m of members) {
const label = m.displayName ? `${m.displayName} (${m.subjectId})` : m.subjectId;
console.log(` [${m.subjectType}] ${label}`);
}
} catch (err) {
handleBoardError(err, listOpts);
}
}),
);
addBoardClientOptions(
membersCmd
.command("add")
.description("Grant an agent or user access to a private channel")
.argument("<path>", "Channel path")
.argument("<target>", "Agent (@name, slug, or UUID) or user ID (with --user)")
.option("--user", "Treat <target> as a user ID instead of an agent")
.action(
async (
channelPath: string,
target: string,
addOpts: BoardCommonOptions & { user?: boolean },
) => {
try {
const resolved = resolveBoardClient(addOpts);
const added = await resolved.client.channels.members.add(
channelPath,
addOpts.user ? { userId: target } : { agent: target },
);
if (resolved.json) {
console.log(JSON.stringify(added, null, 2));
return;
}
console.log(
pc.green(`Added ${added.subjectType} ${added.displayName ?? added.subjectId} to #${channelPath}.`),
);
} catch (err) {
handleBoardError(err, addOpts);
}
},
),
);
addBoardClientOptions(
membersCmd
.command("remove")
.description("Revoke an agent or user's access to a private channel")
.argument("<path>", "Channel path")
.argument("<target>", "Agent (@name, slug, or UUID) or user ID (with --user)")
.option("--user", "Treat <target> as a user ID instead of an agent")
.action(
async (
channelPath: string,
target: string,
rmOpts: BoardCommonOptions & { user?: boolean },
) => {
try {
const resolved = resolveBoardClient(rmOpts);
const res = await resolved.client.channels.members.remove(
channelPath,
rmOpts.user ? { userId: target } : { agent: target },
);
if (resolved.json) {
console.log(JSON.stringify(res, null, 2));
return;
}
console.log(
res.removed
? pc.yellow(`Removed ${target} from #${channelPath}.`)
: pc.dim(`${target} was not a member of #${channelPath}.`),
);
} catch (err) {
handleBoardError(err, rmOpts);
}
},
),
);
}
export function registerBoardChannelCommands(program: Command): void {
+446
View File
@@ -0,0 +1,446 @@
import type { Command } from "commander";
import pc from "picocolors";
import { ISSUE_PRIORITIES, type IssuePriority } from "@paperclipai/shared";
import {
CLAIMABLE_TASK_STATUSES,
type ClaimableTaskStatus,
type HeadlessIssueView,
type TaskDependenciesView,
} from "@paperclipai/shared/sdk";
import {
addBoardClientOptions,
collectOption,
handleBoardError,
isScriptOutput,
parseLabelsList,
resolveBoardClient,
splitCsvValues,
type BoardCommonOptions,
} from "./client.js";
import { deleteClaimRecord, resolveClaimCredentials } from "./store.js";
interface TasksAssignOptions extends BoardCommonOptions {
unassign?: boolean;
keepStatus?: boolean;
force?: boolean;
comment?: string;
message?: string;
}
interface TasksHandoffOptions extends BoardCommonOptions {
channel?: string;
label?: string[];
unset?: string[];
if?: string[];
status?: string;
assignee?: string;
unassign?: boolean;
priority?: string;
resultSchema?: string;
clearResultSchema?: boolean;
comment?: string;
message?: string;
}
interface TasksCancelOptions extends BoardCommonOptions {
reason?: string;
message?: string;
force?: boolean;
}
interface TasksReopenOptions extends BoardCommonOptions {
status?: string;
comment?: string;
message?: string;
}
interface TasksDepsMutateOptions extends BoardCommonOptions {
needs?: string[];
release?: boolean;
comment?: string;
message?: string;
}
function parseOptionalClaimableStatus(raw?: string): ClaimableTaskStatus | undefined {
if (!raw) return undefined;
const trimmed = raw.trim().toLowerCase();
if (!CLAIMABLE_TASK_STATUSES.includes(trimmed as ClaimableTaskStatus)) {
throw new Error(
`Invalid status "${raw}": expected one of ${CLAIMABLE_TASK_STATUSES.join(", ")}`,
);
}
return trimmed as ClaimableTaskStatus;
}
function parseIfPairs(rawPairs: string[] | undefined): Record<string, string | null> | undefined {
if (!rawPairs || rawPairs.length === 0) return undefined;
const out: Record<string, string | null> = {};
for (const expr of rawPairs) {
const idx = expr.indexOf("=");
if (idx <= 0) {
throw new Error(`Invalid --if expression "${expr}": expected key=value or key=null`);
}
const key = expr.slice(0, idx).trim();
const val = expr.slice(idx + 1).trim();
out[key] = val === "" || val === "null" ? null : val;
}
return out;
}
function formatDependencies(deps: TaskDependenciesView): void {
console.log(`${pc.cyan(deps.identifier)} (status=${deps.status})`);
if (deps.blockedBy.length === 0) {
console.log(` blocked by: ${pc.dim("(none)")}`);
} else {
console.log(" blocked by:");
for (const item of deps.blockedBy) {
console.log(` - ${pc.cyan(item.identifier)} [${item.status}] ${item.title}`);
}
}
if (deps.blocks.length === 0) {
console.log(` blocks: ${pc.dim("(none)")}`);
} else {
console.log(" blocks:");
for (const item of deps.blocks) {
console.log(` - ${pc.cyan(item.identifier)} [${item.status}] ${item.title}`);
}
}
}
export function registerTaskWorkflowCommands(tasksCmd: Command): void {
addBoardClientOptions(
tasksCmd
.command("assign")
.description("Assign an existing task or channel post to a registered agent (or --unassign)")
.argument("<id>", "Issue identifier or UUID")
.argument("[agent]", "Target agent (@name, slug, or UUID)")
.option("--unassign", "Clear assignee and return task to the unassigned pool")
.option("--keep-status", "Do not auto-promote a passive backlog post to todo")
.option("--force", "Fence and clear an active worker lease if currently claimed")
.option("--comment <text>", "Optional handoff note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, agent: string | undefined, opts: TasksAssignOptions) => {
try {
const resolved = resolveBoardClient(opts);
if (!opts.unassign && !agent) {
throw new Error("Specify an <agent> or pass --unassign.");
}
const comment = opts.comment ?? opts.message;
const updated: HeadlessIssueView = await resolved.client.tasks.assign(
id,
opts.unassign ? null : agent!,
{
...(opts.unassign ? { unassign: true } : {}),
...(opts.keepStatus ? { keepStatus: true } : {}),
...(opts.force ? { force: true } : {}),
...(comment !== undefined ? { comment } : {}),
},
);
const companyId = await resolved.resolveCompanyId();
if (opts.force) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
const targetDesc = opts.unassign
? "unassigned pool"
: pc.bold(agent!);
console.log(
`${pc.green("Assigned")} ${pc.cyan(updated.identifier)} -> ${targetDesc} (status=${updated.status}, ${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
tasksCmd
.command("handoff")
.alias("move")
.description("Atomically move channel, update labels/assignee/status, and release any active lease")
.argument("<id>", "Issue identifier or UUID")
.argument("[channel]", "Optional target channel path")
.option("--channel <path>", "Target channel path")
.option("--label <k=v>", "Set key=value label(s) (repeatable)", collectOption, [])
.option("--unset <key>", "Unset label key(s) (repeatable)", collectOption, [])
.option("--if <k=v>", "CAS precondition (key=value or key=null, repeatable)", collectOption, [])
.option("--status <status>", "Target status (todo, backlog, in_review; default: todo)")
.option("--assignee <agent>", "Push-assign to a registered agent (@name, slug, or UUID)")
.option("--unassign", "Clear assignee so the target queue pool can claim it")
.option("--priority <level>", "Update priority (critical, high, medium, low)")
.option("--result-schema <ref>", "Require structured result schema (<name>@<version>)")
.option("--clear-result-schema", "Clear required result schema")
.option("--comment <text>", "Handoff note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, channelArg: string | undefined, opts: TasksHandoffOptions) => {
try {
const resolved = resolveBoardClient(opts);
const companyId = await resolved.resolveCompanyId();
const claim = resolveClaimCredentials({
companyId,
issueRef: id,
activeProfile: resolved.profile,
requireClaim: false,
});
const { kvLabels: labels } = parseLabelsList(opts.label);
const ifLabels = parseIfPairs(opts.if);
const status = parseOptionalClaimableStatus(opts.status);
let priority: IssuePriority | undefined;
if (opts.priority) {
if (!ISSUE_PRIORITIES.includes(opts.priority as IssuePriority)) {
throw new Error(
`Invalid priority "${opts.priority}": expected one of ${ISSUE_PRIORITIES.join(", ")}`,
);
}
priority = opts.priority as IssuePriority;
}
const targetChannel = opts.channel ?? channelArg;
const comment = opts.comment ?? opts.message;
const updated = await resolved.client.tasks.handoff(id, {
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(targetChannel ? { channel: targetChannel } : {}),
...(status ? { status } : {}),
...(Object.keys(labels).length > 0 ? { labels } : {}),
...(opts.unset && opts.unset.length > 0 ? { unsetLabels: opts.unset } : {}),
...(ifLabels ? { ifLabels } : {}),
...(opts.unassign
? { unassign: true }
: opts.assignee !== undefined
? { assignee: opts.assignee }
: {}),
...(priority ? { priority } : {}),
...(opts.clearResultSchema
? { resultSchema: null }
: opts.resultSchema !== undefined
? { resultSchema: opts.resultSchema }
: {}),
...(comment !== undefined ? { comment } : {}),
});
if (claim) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
const chLabel = updated.channel ? `#${updated.channel}` : "board";
console.log(
`${pc.green("Handed off")} ${pc.cyan(updated.identifier)} -> ${chLabel} (status=${updated.status}, ${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
tasksCmd
.command("cancel")
.description("Cancel a task (status=cancelled), releasing any active lease")
.argument("<id>", "Issue identifier or UUID")
.argument("[reason...]", "Optional cancellation reason")
.option("--reason <text>", "Cancellation reason")
.option("-m, --message <text>", "Alias for --reason")
.option("--force", "Force-cancel even if another worker currently holds a lease")
.action(async (id: string, reasonParts: string[], opts: TasksCancelOptions) => {
try {
const resolved = resolveBoardClient(opts);
const companyId = await resolved.resolveCompanyId();
const claim = resolveClaimCredentials({
companyId,
issueRef: id,
activeProfile: resolved.profile,
requireClaim: false,
});
const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined;
const reason = opts.reason ?? opts.message ?? positional;
const updated = await resolved.client.tasks.cancel(id, {
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(reason !== undefined ? { reason } : {}),
...(opts.force ? { force: true } : {}),
});
if (claim || opts.force) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
console.log(
`${pc.yellow("Cancelled")} ${pc.cyan(updated.identifier)} (${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
tasksCmd
.command("reopen")
.description("Reopen a completed, cancelled, or blocked task back to todo (or backlog)")
.argument("<id>", "Issue identifier or UUID")
.argument("[comment...]", "Optional reopen note")
.option("--status <status>", "Target status (todo or backlog; default: todo)")
.option("--comment <text>", "Reopen note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, commentParts: string[], opts: TasksReopenOptions) => {
try {
const resolved = resolveBoardClient(opts);
const positional = commentParts.length > 0 ? commentParts.join(" ") : undefined;
const comment = opts.comment ?? opts.message ?? positional;
let status: "todo" | "backlog" | undefined;
if (opts.status) {
const s = opts.status.trim().toLowerCase();
if (s !== "todo" && s !== "backlog") {
throw new Error(`Invalid reopen status "${opts.status}": expected todo or backlog`);
}
status = s;
}
const updated = await resolved.client.tasks.reopen(id, {
...(status ? { status } : {}),
...(comment !== undefined ? { comment } : {}),
});
if (resolved.json) {
console.log(JSON.stringify(updated, null, 2));
return;
}
if (isScriptOutput(resolved)) {
console.log(updated.identifier);
return;
}
console.log(
`${pc.green("Reopened")} ${pc.cyan(updated.identifier)} (status=${updated.status}, ${updated.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
const depsCmd = tasksCmd
.command("deps")
.description("Inspect or modify task dependencies (blocked_by / blocks)");
addBoardClientOptions(
depsCmd
.command("list")
.description("List blockers and dependents for a task")
.argument("<id>", "Issue identifier or UUID")
.action(async (id: string, opts: BoardCommonOptions) => {
try {
const resolved = resolveBoardClient(opts);
const deps = await resolved.client.tasks.dependencies(id);
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
formatDependencies(deps);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
depsCmd
.command("add")
.description("Add one or more prerequisite blockers (--needs) to a task")
.argument("<id>", "Issue identifier or UUID")
.argument("[needs...]", "Blocker issue identifier(s) or UUID(s)")
.option("--needs <id>", "Blocker issue ID/identifier (repeatable or comma-separated)", collectOption, [])
.option("--release", "Release any active lease so the task waits in todo until blockers finish")
.option("--comment <text>", "Optional note")
.option("-m, --message <text>", "Alias for --comment")
.action(async (id: string, needsArgs: string[], opts: TasksDepsMutateOptions) => {
try {
const resolved = resolveBoardClient(opts);
const add = [...splitCsvValues(opts.needs), ...splitCsvValues(needsArgs)];
if (add.length === 0) {
throw new Error("Specify at least one blocker via positional <needs...> or --needs <id>.");
}
const companyId = await resolved.resolveCompanyId();
const claim = opts.release
? resolveClaimCredentials({
companyId,
issueRef: id,
activeProfile: resolved.profile,
requireClaim: false,
})
: undefined;
const comment = opts.comment ?? opts.message;
const deps = await resolved.client.tasks.updateDependencies(id, {
add,
...(opts.release ? { releaseLease: true } : {}),
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(comment !== undefined ? { comment } : {}),
});
if (claim && opts.release) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
formatDependencies(deps);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
addBoardClientOptions(
depsCmd
.command("remove")
.description("Remove one or more prerequisite blockers from a task")
.argument("<id>", "Issue identifier or UUID")
.argument("[needs...]", "Blocker issue identifier(s) or UUID(s) to remove")
.option("--needs <id>", "Blocker issue ID/identifier to remove (repeatable or comma-separated)", collectOption, [])
.action(async (id: string, needsArgs: string[], opts: TasksDepsMutateOptions) => {
try {
const resolved = resolveBoardClient(opts);
const remove = [...splitCsvValues(opts.needs), ...splitCsvValues(needsArgs)];
if (remove.length === 0) {
throw new Error("Specify at least one blocker to remove.");
}
const deps = await resolved.client.tasks.updateDependencies(id, { remove });
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
formatDependencies(deps);
} catch (err) {
handleBoardError(err, opts);
}
}),
);
}
+92 -6
View File
@@ -4,14 +4,19 @@ import type { Command } from "commander";
import { ISSUE_PRIORITIES, type IssuePriority, type IssueStatus } from "@paperclipai/shared";
import {
CHANNEL_PATH_REGEX,
CLAIMABLE_TASK_STATUSES,
parseDurationMs,
PaperclipError,
TASK_CLAIM_ASSIGNEE_MODES,
type BatchCreateIssuesResult,
type ClaimableTaskStatus,
type HeadlessIssueView,
type PlanTaskInput,
type TaskClaimAssigneeMode,
type TaskClaimView,
type ThreadDetailView,
} from "@paperclipai/shared/sdk";
import { registerTaskWorkflowCommands } from "./tasks-workflows.js";
import {
addBoardClientOptions,
collectOption,
@@ -65,6 +70,9 @@ interface TasksClaimOptions extends BoardCommonOptions {
channel?: string;
label?: string[];
project?: string;
status?: string[];
assignee?: string;
mine?: boolean;
lease?: string;
wait?: string;
includeUntrusted?: boolean;
@@ -82,6 +90,10 @@ interface TasksRenewOptions extends BoardCommonOptions {
interface TasksReleaseOptions extends BoardCommonOptions {
comment?: string;
message?: string;
channel?: string;
label?: string[];
unset?: string[];
status?: string;
}
interface TasksCompleteOptions extends BoardCommonOptions {
@@ -102,6 +114,7 @@ interface TasksFailOptions extends BoardCommonOptions {
interface TasksBlockOptions extends BoardCommonOptions {
reason?: string;
message?: string;
needs?: string[];
}
function isIssueRef(value: string): boolean {
@@ -224,18 +237,39 @@ async function performClaim(
throw new Error("Pass either a specific task <id> or --ready/--channel, not both.");
}
const claimStatuses = splitCsvValues(opts.status);
for (const s of claimStatuses) {
if (!CLAIMABLE_TASK_STATUSES.includes(s as ClaimableTaskStatus)) {
throw new Error(
`Invalid claim --status "${s}": expected one of ${CLAIMABLE_TASK_STATUSES.join(", ")}`,
);
}
}
const rawAssignee = opts.mine ? "me" : opts.assignee?.trim().toLowerCase();
if (
rawAssignee !== undefined &&
!TASK_CLAIM_ASSIGNEE_MODES.includes(rawAssignee as TaskClaimAssigneeMode)
) {
throw new Error(
`Invalid --assignee "${opts.assignee}": expected one of ${TASK_CLAIM_ASSIGNEE_MODES.join(", ")}`,
);
}
const claim = await resolved.client.tasks.claim(
id ?? {
ready: true,
...(readyChannel ? { channel: readyChannel } : {}),
...(opts.project ? { projectId: opts.project } : {}),
...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}),
...(claimStatuses.length > 0 ? { statuses: claimStatuses as ClaimableTaskStatus[] } : {}),
...(rawAssignee ? { assignee: rawAssignee as TaskClaimAssigneeMode } : {}),
...(opts.lease ? { lease: opts.lease } : {}),
...(opts.wait ? { wait: opts.wait } : {}),
...(opts.includeUntrusted ? { includeUntrusted: true } : {}),
},
id
? {
...(claimStatuses.length > 0 ? { statuses: claimStatuses as ClaimableTaskStatus[] } : {}),
...(opts.lease ? { lease: opts.lease } : {}),
...(opts.wait ? { wait: opts.wait } : {}),
}
@@ -814,6 +848,9 @@ export function registerBoardTaskCommands(program: Command): void {
.option("--channel <channel>", "Channel or prefix/ queue to claim from (implies --ready)")
.option("--label <expr>", "Filter by label expression (repeatable)", collectOption, [])
.option("--project <id-or-slug>", "Filter by project ID or slug")
.option("--status <status>", "Claimable status filter (todo, backlog, in_review; repeatable)", collectOption, [])
.option("--assignee <mode>", "Assignee filter (unassigned, me, any; default: unassigned)")
.option("--mine", "Shorthand for --assignee me (claim tasks assigned to you)")
.option("--lease <dur>", "Lease duration (e.g. 5m, 60s)")
.option("--wait <dur>", "Wait up to duration if queue is empty (e.g. 10m, 5s)")
.option("--include-untrusted", "Include tasks marked untrusted on wildcard --ready claims")
@@ -874,6 +911,9 @@ export function registerBoardTaskCommands(program: Command): void {
.option("--channel <channel>", "Channel or prefix/ queue to claim from (implies --ready)")
.option("--label <expr>", "Filter by label expression (repeatable)", collectOption, [])
.option("--project <id-or-slug>", "Filter by project ID or slug")
.option("--status <status>", "Claimable status filter (todo, backlog, in_review; repeatable)", collectOption, [])
.option("--assignee <mode>", "Assignee filter (unassigned, me, any; default: unassigned)")
.option("--mine", "Shorthand for --assignee me (claim tasks assigned to you)")
.option("--lease <dur>", "Lease duration (e.g. 5m, 60s)")
.option("--wait <dur>", "Wait up to duration if queue is empty (e.g. 10m, 5s)")
.option("--result <text>", "Completion message when command exits 0 without settling itself")
@@ -957,6 +997,10 @@ export function registerBoardTaskCommands(program: Command): void {
.argument("[comment...]", "Optional release note")
.option("--comment <text>", "Optional release note")
.option("-m, --message <text>", "Alias for --comment")
.option("--channel <path>", "Atomically move task to another channel on release")
.option("--label <k=v>", "Atomically set key=value label(s) on release (repeatable)", collectOption, [])
.option("--unset <key>", "Atomically unset label key(s) on release (repeatable)", collectOption, [])
.option("--status <status>", "Target status on release (todo, backlog, in_review; default: todo)")
.action(async (id: string, commentParts: string[], opts: TasksReleaseOptions) => {
try {
const resolved = resolveBoardClient(opts);
@@ -969,6 +1013,17 @@ export function registerBoardTaskCommands(program: Command): void {
})!;
const positional = commentParts.length > 0 ? commentParts.join(" ") : undefined;
const comment = opts.comment ?? opts.message ?? positional;
const { kvLabels } = parseLabelsList(opts.label);
let targetStatus: ClaimableTaskStatus | undefined;
if (opts.status) {
const s = opts.status.trim().toLowerCase();
if (!CLAIMABLE_TASK_STATUSES.includes(s as ClaimableTaskStatus)) {
throw new Error(
`Invalid --status "${opts.status}": expected one of ${CLAIMABLE_TASK_STATUSES.join(", ")}`,
);
}
targetStatus = s as ClaimableTaskStatus;
}
const result = await resolved.requestJson<{ released: boolean; cursor: string }>(
`/api/issues/${encodeURIComponent(id)}/claim/release`,
{
@@ -978,6 +1033,10 @@ export function registerBoardTaskCommands(program: Command): void {
claimToken: claim.claimToken,
...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(comment !== undefined ? { comment } : {}),
...(opts.channel ? { channel: opts.channel } : {}),
...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}),
...(opts.unset && opts.unset.length > 0 ? { unsetLabels: opts.unset } : {}),
...(targetStatus ? { status: targetStatus } : {}),
}),
},
);
@@ -986,7 +1045,9 @@ export function registerBoardTaskCommands(program: Command): void {
console.log(JSON.stringify(result, null, 2));
return;
}
console.log(`${pc.yellow("Released")} ${pc.cyan(id)} back to todo (${result.cursor})`);
console.log(
`${pc.yellow("Released")} ${pc.cyan(id)} back to ${targetStatus ?? "todo"} (${result.cursor})`,
);
} catch (err) {
handleBoardError(err, opts);
}
@@ -1118,18 +1179,20 @@ export function registerBoardTaskCommands(program: Command): void {
addBoardClientOptions(
tasksCmd
.command("block")
.description("Mark a task as blocked with a reason (releasing any active pool lease)")
.description("Mark a task as blocked with a reason, or park it waiting on --needs dependencies")
.argument("<id>", "Issue identifier or UUID")
.argument("[reason...]", "Blocking reason")
.option("--reason <text>", "Blocking reason")
.option("-m, --message <text>", "Alias for --reason")
.option("--needs <id>", "Add blocker dependency ID/identifier and release lease to wait in todo (repeatable)", collectOption, [])
.action(async (id: string, reasonParts: string[], opts: TasksBlockOptions) => {
try {
const resolved = resolveBoardClient(opts);
const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined;
const reason = (opts.reason ?? opts.message ?? positional)?.trim();
if (!reason) {
throw new Error("Specify a blocking reason via positional <reason> or --reason <text>.");
const needs = splitCsvValues(opts.needs);
if (!reason && needs.length === 0) {
throw new Error("Specify a blocking reason or at least one --needs <id> dependency.");
}
const companyId = await resolved.resolveCompanyId();
const claim = resolveClaimCredentials({
@@ -1139,6 +1202,27 @@ export function registerBoardTaskCommands(program: Command): void {
requireClaim: false,
});
if (needs.length > 0) {
const deps = await resolved.client.tasks.updateDependencies(id, {
add: needs,
releaseLease: true,
...(claim ? { claimToken: claim.claimToken } : {}),
...(claim?.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
...(reason ? { comment: reason } : {}),
});
if (claim) {
deleteClaimRecord(companyId, id);
}
if (resolved.json) {
console.log(JSON.stringify(deps, null, 2));
return;
}
console.log(
`${pc.yellow("Waiting")} ${pc.cyan(deps.identifier)} on ${needs.join(", ")} (${deps.cursor})`,
);
return;
}
let updated: HeadlessIssueView;
if (claim) {
updated = await resolved.requestJson<HeadlessIssueView>(
@@ -1149,7 +1233,7 @@ export function registerBoardTaskCommands(program: Command): void {
body: JSON.stringify({
claimToken: claim.claimToken,
...(claim.claimEpoch !== undefined ? { claimEpoch: claim.claimEpoch } : {}),
reason,
reason: reason!,
requeue: false,
}),
},
@@ -1163,7 +1247,7 @@ export function registerBoardTaskCommands(program: Command): void {
body: JSON.stringify({ status: "blocked" }),
},
);
await resolved.client.reply(id, reason);
await resolved.client.reply(id, reason!);
}
if (resolved.json) {
@@ -1202,4 +1286,6 @@ export function registerBoardTaskCommands(program: Command): void {
}
}),
);
registerTaskWorkflowCommands(tasksCmd);
}