mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## 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
984 lines
29 KiB
TypeScript
984 lines
29 KiB
TypeScript
import { and, eq, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
activityLog,
|
|
channels,
|
|
issueComments,
|
|
issues,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
applyKvLabelMutation,
|
|
TaskAssignSchema,
|
|
TaskCancelSchema,
|
|
TaskHandoffSchema,
|
|
TaskReopenSchema,
|
|
type BoardEventView,
|
|
type HeadlessIssueView,
|
|
type IssueStatus,
|
|
} from "@paperclipai/shared";
|
|
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
|
|
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
|
import type { heartbeatService } from "./heartbeat.js";
|
|
import { issueTreeControlService } from "./issue-tree-control.js";
|
|
import {
|
|
ensureChannel,
|
|
resolveAssigneeAgent,
|
|
validateWritableKvLabelsOrThrow,
|
|
} from "./headless-channels.js";
|
|
import { dispatchManagedChannelPoolBestEffort } from "./headless-channel-admin.js";
|
|
import {
|
|
appendBoardEvent,
|
|
assertIssueChannelScopeAccess,
|
|
enforceHeadlessScopes,
|
|
loadHeadlessIssueView,
|
|
publishCommittedBoardEvent,
|
|
type DbOrTx,
|
|
type HeadlessActorContext,
|
|
} from "./headless-common.js";
|
|
import { assertSchemaExists } from "./headless-schemas.js";
|
|
import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js";
|
|
|
|
function hasActiveWork(issue: {
|
|
claimTokenHash: string | null;
|
|
checkoutRunId: string | null;
|
|
executionRunId: string | null;
|
|
}): boolean {
|
|
return (
|
|
issue.claimTokenHash !== null ||
|
|
issue.checkoutRunId !== null ||
|
|
issue.executionRunId !== null
|
|
);
|
|
}
|
|
|
|
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 assertNoReservedKeys(keys: string[]): void {
|
|
for (const key of keys) {
|
|
if (key.startsWith("paperclip.")) {
|
|
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
|
|
error: "reserved_label",
|
|
code: "reserved_label",
|
|
key,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
async function wakeAssignedAgent(
|
|
heartbeat: ReturnType<typeof heartbeatService> | undefined,
|
|
opts: {
|
|
issueId: string;
|
|
assigneeAgentId: string;
|
|
reason: string;
|
|
actor: HeadlessActorContext;
|
|
channelPath?: string | null;
|
|
},
|
|
): Promise<void> {
|
|
if (!heartbeat) return;
|
|
await heartbeat
|
|
.wakeup(opts.assigneeAgentId, {
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: opts.reason,
|
|
payload: {
|
|
issueId: opts.issueId,
|
|
...(opts.channelPath ? { channelPath: opts.channelPath } : {}),
|
|
},
|
|
idempotencyKey: `assign:${opts.issueId}:${opts.assigneeAgentId}:${Date.now()}`,
|
|
requestedByActorType: opts.actor.principalType === "agent" ? "agent" : "user",
|
|
requestedByActorId:
|
|
opts.actor.principalType === "agent"
|
|
? opts.actor.agentId ?? "unknown-agent"
|
|
: opts.actor.userId ?? "board",
|
|
contextSnapshot: {
|
|
issueId: opts.issueId,
|
|
taskId: opts.issueId,
|
|
wakeReason: opts.reason,
|
|
},
|
|
})
|
|
.catch(() => {
|
|
// Best-effort wakeup; assignment is already durably committed
|
|
});
|
|
}
|
|
|
|
export async function assignTask(
|
|
db: Db,
|
|
issueId: string,
|
|
actor: HeadlessActorContext,
|
|
rawInput: unknown,
|
|
opts?: {
|
|
heartbeat?: ReturnType<typeof heartbeatService>;
|
|
authorizeTargetAssignee?: (tx: DbOrTx, targetAgentId: string | null) => Promise<void>;
|
|
},
|
|
): Promise<HeadlessIssueView> {
|
|
enforceHeadlessScopes(actor, { action: "tasks.assign" });
|
|
const parsed = TaskAssignSchema.safeParse(rawInput ?? {});
|
|
if (!parsed.success) {
|
|
throw badRequest(
|
|
parsed.error.issues
|
|
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
|
|
.join("; "),
|
|
);
|
|
}
|
|
const input = parsed.data;
|
|
|
|
const wantsUnassign =
|
|
input.unassign === true ||
|
|
input.assignee === null ||
|
|
input.assigneeAgentId === null;
|
|
if (!wantsUnassign && !input.assignee && !input.assigneeAgentId) {
|
|
throw badRequest("Provide 'assignee', 'assigneeAgentId', or 'unassign: true'");
|
|
}
|
|
|
|
const committed = await db.transaction(async (tx) => {
|
|
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,
|
|
);
|
|
|
|
if (hasActiveWork(issue) && !input.force) {
|
|
throw conflict(
|
|
"Task currently has an active lease or execution run; pass --force to fence the active worker and reassign",
|
|
{
|
|
code: "task_claimed",
|
|
claimEpoch: Number(issue.claimEpoch ?? 0),
|
|
next: [`pc tasks assign ${issue.identifier ?? issue.id} --force`],
|
|
},
|
|
);
|
|
}
|
|
|
|
const resolvedAgentId = wantsUnassign
|
|
? null
|
|
: await resolveAssigneeAgent(tx, issue.companyId, {
|
|
...(input.assigneeAgentId ? { assigneeAgentId: input.assigneeAgentId } : {}),
|
|
...(input.assignee ? { for: input.assignee } : {}),
|
|
});
|
|
|
|
if (opts?.authorizeTargetAssignee) {
|
|
await opts.authorizeTargetAssignee(tx, resolvedAgentId);
|
|
}
|
|
|
|
const now = new Date();
|
|
const clearingLease = hasActiveWork(issue);
|
|
const shouldPromoteBacklog =
|
|
resolvedAgentId !== null && issue.status === "backlog" && !input.keepStatus;
|
|
const shouldReturnLeasedToTodo =
|
|
clearingLease && issue.status === "in_progress";
|
|
const nextStatus: IssueStatus = shouldPromoteBacklog || shouldReturnLeasedToTodo
|
|
? "todo"
|
|
: (issue.status as IssueStatus);
|
|
|
|
if (clearingLease) {
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
|
|
}
|
|
if (resolvedAgentId === null && nextStatus === "todo" && issue.channelId) {
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
|
|
}
|
|
|
|
const [updated] = await tx
|
|
.update(issues)
|
|
.set({
|
|
assigneeAgentId: resolvedAgentId,
|
|
assigneeUserId: null,
|
|
status: nextStatus,
|
|
...(clearingLease
|
|
? {
|
|
claimEpoch: Number(issue.claimEpoch ?? 0) + 1,
|
|
claimTokenHash: null,
|
|
claimLeasedAt: null,
|
|
claimLeaseExpiresAt: null,
|
|
claimHolderAgentId: null,
|
|
claimHolderUserId: null,
|
|
claimHolderProfile: null,
|
|
checkoutRunId: null,
|
|
executionRunId: null,
|
|
}
|
|
: {}),
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(issues.id, issue.id))
|
|
.returning();
|
|
|
|
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: resolvedAgentId ? "issue.assigned" : "issue.unassigned",
|
|
entityType: "issue",
|
|
entityId: updated!.id,
|
|
details: {
|
|
assigneeAgentId: resolvedAgentId,
|
|
status: nextStatus,
|
|
forcedLeaseClear: clearingLease,
|
|
},
|
|
});
|
|
|
|
const events: BoardEventView[] = [];
|
|
const assignEvent = await appendBoardEvent(tx, {
|
|
companyId: issue.companyId,
|
|
type: "task.assigned",
|
|
channelId: updated!.channelId,
|
|
channelPath: targetChannel?.path ?? null,
|
|
issueId: updated!.id,
|
|
identifier: updated!.identifier ?? updated!.id,
|
|
actor,
|
|
payload: {
|
|
assigneeAgentId: resolvedAgentId,
|
|
status: nextStatus,
|
|
kvLabels: updated!.kvLabels ?? {},
|
|
},
|
|
});
|
|
events.push(assignEvent);
|
|
|
|
if (resolvedAgentId === null && nextStatus === "todo") {
|
|
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: {
|
|
kvLabels: updated!.kvLabels ?? {},
|
|
},
|
|
});
|
|
events.push(readyEvent);
|
|
}
|
|
|
|
const view = await loadHeadlessIssueView(
|
|
tx,
|
|
updated!.id,
|
|
events[events.length - 1]!.cursor,
|
|
);
|
|
|
|
return {
|
|
view,
|
|
events,
|
|
resolvedAgentId,
|
|
nextStatus,
|
|
channelId: updated!.channelId,
|
|
channelPath: targetChannel?.path ?? null,
|
|
};
|
|
});
|
|
|
|
for (const ev of committed.events) {
|
|
publishCommittedBoardEvent(ev);
|
|
}
|
|
|
|
if (
|
|
committed.resolvedAgentId &&
|
|
(committed.nextStatus === "todo" || committed.nextStatus === "in_progress")
|
|
) {
|
|
await wakeAssignedAgent(opts?.heartbeat, {
|
|
issueId: committed.view.id,
|
|
assigneeAgentId: committed.resolvedAgentId,
|
|
reason: "issue_assigned",
|
|
actor,
|
|
channelPath: committed.channelPath,
|
|
});
|
|
} else if (
|
|
committed.resolvedAgentId === null &&
|
|
committed.nextStatus === "todo" &&
|
|
committed.channelId
|
|
) {
|
|
await dispatchManagedChannelPoolBestEffort(db, actor.companyId, committed.channelId, {
|
|
heartbeat: opts?.heartbeat,
|
|
actor,
|
|
});
|
|
}
|
|
|
|
return committed.view;
|
|
}
|
|
|
|
export async function handoffTask(
|
|
db: Db,
|
|
issueId: string,
|
|
actor: HeadlessActorContext,
|
|
rawInput: unknown,
|
|
headerToken?: string,
|
|
opts?: {
|
|
heartbeat?: ReturnType<typeof heartbeatService>;
|
|
authorizeTargetAssignee?: (tx: DbOrTx, targetAgentId: string | null) => Promise<void>;
|
|
},
|
|
): Promise<HeadlessIssueView> {
|
|
enforceHeadlessScopes(actor, { action: "tasks.handoff" });
|
|
const parsed = TaskHandoffSchema.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);
|
|
|
|
if (input.labels) {
|
|
validateWritableKvLabelsOrThrow(input.labels);
|
|
}
|
|
if (input.unsetLabels) {
|
|
assertNoReservedKeys(input.unsetLabels);
|
|
}
|
|
|
|
const committed = await db.transaction(async (tx) => {
|
|
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: sourceChannel } = await assertIssueChannelScopeAccess(
|
|
tx,
|
|
issue,
|
|
actor,
|
|
);
|
|
|
|
if (issue.status === "done" || issue.status === "cancelled") {
|
|
throw conflict("Cannot hand off a completed or cancelled task; reopen it first", {
|
|
code: "task_finished",
|
|
status: issue.status,
|
|
});
|
|
}
|
|
|
|
// Fence active lease if one exists
|
|
const epochMatches =
|
|
input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch;
|
|
const hadActiveLease = issue.claimTokenHash !== null;
|
|
if (hadActiveLease) {
|
|
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 (issue.checkoutRunId !== null || issue.executionRunId !== null) {
|
|
throw conflict("Task currently has an active execution run", {
|
|
code: "task_claimed",
|
|
status: issue.status,
|
|
});
|
|
} else if (token !== undefined || !epochMatches) {
|
|
throw conflict("claim_lost", {
|
|
code: "claim_lost",
|
|
currentEpoch: Number(issue.claimEpoch ?? 0),
|
|
status: issue.status,
|
|
});
|
|
}
|
|
|
|
let finalChannel = sourceChannel;
|
|
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) ||
|
|
input.ifLabels !== undefined
|
|
) {
|
|
const applied = applyKvLabelMutation(nextKvLabels, {
|
|
...(input.labels ? { set: input.labels } : {}),
|
|
...(input.unsetLabels ? { unset: input.unsetLabels } : {}),
|
|
...(input.ifLabels ? { if: input.ifLabels } : {}),
|
|
});
|
|
if (!applied.ok) {
|
|
throw conflict("label_conflict", {
|
|
code: "label_conflict",
|
|
conflictingKeys: applied.conflictingKeys,
|
|
});
|
|
}
|
|
nextKvLabels = applied.labels;
|
|
labelsChanged = true;
|
|
}
|
|
|
|
let nextAssigneeAgentId = issue.assigneeAgentId;
|
|
let nextAssigneeUserId = issue.assigneeUserId;
|
|
let assigneeChanging = false;
|
|
if (input.unassign || input.assignee === null) {
|
|
nextAssigneeAgentId = null;
|
|
nextAssigneeUserId = null;
|
|
assigneeChanging = true;
|
|
} else if (input.assignee !== undefined) {
|
|
nextAssigneeAgentId = await resolveAssigneeAgent(tx, issue.companyId, {
|
|
for: input.assignee,
|
|
});
|
|
nextAssigneeUserId = null;
|
|
assigneeChanging = true;
|
|
}
|
|
if (assigneeChanging && opts?.authorizeTargetAssignee) {
|
|
await opts.authorizeTargetAssignee(tx, nextAssigneeAgentId);
|
|
}
|
|
|
|
let nextResultSchemaRef = issue.resultSchemaRef;
|
|
if (input.resultSchema !== undefined) {
|
|
if (input.resultSchema === null) {
|
|
nextResultSchemaRef = null;
|
|
} else {
|
|
const verified = await assertSchemaExists(
|
|
tx as unknown as Db,
|
|
issue.companyId,
|
|
input.resultSchema,
|
|
);
|
|
nextResultSchemaRef = verified;
|
|
}
|
|
}
|
|
|
|
const nextStatus: IssueStatus = input.status ?? "todo";
|
|
const now = new Date();
|
|
if (hadActiveLease) {
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
|
|
}
|
|
if (issue.channelId) {
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
|
|
}
|
|
if (
|
|
nextStatus === "todo" &&
|
|
nextAssigneeAgentId === null &&
|
|
nextAssigneeUserId === null &&
|
|
(finalChannel?.id ?? issue.channelId)
|
|
) {
|
|
await notifyDeliveryWork(
|
|
tx,
|
|
DELIVERY_QUEUES.managedChannelPools,
|
|
(finalChannel?.id ?? issue.channelId)!,
|
|
);
|
|
}
|
|
|
|
const nextEpoch = hadActiveLease
|
|
? Number(issue.claimEpoch ?? 0) + 1
|
|
: Number(issue.claimEpoch ?? 0);
|
|
|
|
const [updated] = await tx
|
|
.update(issues)
|
|
.set({
|
|
status: nextStatus,
|
|
channelId: finalChannel ? finalChannel.id : issue.channelId,
|
|
...(labelsChanged ? { kvLabels: nextKvLabels } : {}),
|
|
assigneeAgentId: nextAssigneeAgentId,
|
|
assigneeUserId: nextAssigneeUserId,
|
|
...(input.priority !== undefined ? { priority: input.priority } : {}),
|
|
resultSchemaRef: nextResultSchemaRef,
|
|
...(hadActiveLease
|
|
? {
|
|
claimEpoch: nextEpoch,
|
|
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();
|
|
|
|
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,
|
|
issueId: issue.id,
|
|
body: input.comment.trim(),
|
|
...commentAuthorFields(actor),
|
|
});
|
|
}
|
|
|
|
await tx.insert(activityLog).values({
|
|
companyId: issue.companyId,
|
|
...activityActorFields(actor),
|
|
action: "issue.handed_off",
|
|
entityType: "issue",
|
|
entityId: updated!.id,
|
|
details: {
|
|
fromChannel: sourceChannel?.path ?? null,
|
|
toChannel: finalChannel?.path ?? null,
|
|
status: nextStatus,
|
|
assigneeAgentId: nextAssigneeAgentId,
|
|
},
|
|
});
|
|
|
|
const events: BoardEventView[] = [];
|
|
const handoffEvent = await appendBoardEvent(tx, {
|
|
companyId: issue.companyId,
|
|
type: "task.handed_off",
|
|
channelId: updated!.channelId,
|
|
channelPath: finalChannel?.path ?? null,
|
|
issueId: updated!.id,
|
|
identifier: updated!.identifier ?? updated!.id,
|
|
actor,
|
|
payload: {
|
|
fromChannel: sourceChannel?.path ?? null,
|
|
toChannel: finalChannel?.path ?? null,
|
|
status: nextStatus,
|
|
assigneeAgentId: nextAssigneeAgentId,
|
|
kvLabels: updated!.kvLabels ?? {},
|
|
},
|
|
});
|
|
events.push(handoffEvent);
|
|
|
|
if (nextStatus === "todo" && nextAssigneeAgentId === null && nextAssigneeUserId === null) {
|
|
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);
|
|
}
|
|
|
|
const view = await loadHeadlessIssueView(
|
|
tx,
|
|
updated!.id,
|
|
events[events.length - 1]!.cursor,
|
|
);
|
|
|
|
return {
|
|
view,
|
|
events,
|
|
nextAssigneeAgentId,
|
|
nextStatus,
|
|
channelId: updated!.channelId,
|
|
channelPath: finalChannel?.path ?? null,
|
|
};
|
|
});
|
|
|
|
for (const ev of committed.events) {
|
|
publishCommittedBoardEvent(ev);
|
|
}
|
|
|
|
if (committed.nextAssigneeAgentId && committed.nextStatus === "todo") {
|
|
await wakeAssignedAgent(opts?.heartbeat, {
|
|
issueId: committed.view.id,
|
|
assigneeAgentId: committed.nextAssigneeAgentId,
|
|
reason: "issue_handed_off",
|
|
actor,
|
|
channelPath: committed.channelPath,
|
|
});
|
|
} else if (
|
|
committed.nextAssigneeAgentId === null &&
|
|
committed.nextStatus === "todo" &&
|
|
committed.channelId
|
|
) {
|
|
await dispatchManagedChannelPoolBestEffort(db, actor.companyId, committed.channelId, {
|
|
heartbeat: opts?.heartbeat,
|
|
actor,
|
|
});
|
|
}
|
|
|
|
return committed.view;
|
|
}
|
|
|
|
export async function cancelTask(
|
|
db: Db,
|
|
issueId: string,
|
|
actor: HeadlessActorContext,
|
|
rawInput: unknown,
|
|
headerToken?: string,
|
|
): Promise<HeadlessIssueView> {
|
|
enforceHeadlessScopes(actor, { action: "tasks.cancel" });
|
|
const parsed = TaskCancelSchema.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);
|
|
|
|
const committed = await db.transaction(async (tx) => {
|
|
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 hadActiveLease = issue.claimTokenHash !== null;
|
|
const hadActiveRun = issue.checkoutRunId !== null || issue.executionRunId !== null;
|
|
const epochMatches =
|
|
input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch;
|
|
if (!input.force) {
|
|
if (hadActiveLease) {
|
|
if (!verifyClaimToken(issue.claimTokenHash, token) || !epochMatches) {
|
|
throw conflict(
|
|
"Task has an active lease held by another worker; pass --force to cancel anyway",
|
|
{
|
|
code: "task_claimed",
|
|
currentEpoch: Number(issue.claimEpoch ?? 0),
|
|
},
|
|
);
|
|
}
|
|
} else if (hadActiveRun) {
|
|
throw conflict(
|
|
"Task has an active execution run; pass --force to cancel anyway",
|
|
{
|
|
code: "task_claimed",
|
|
status: issue.status,
|
|
},
|
|
);
|
|
} else if (token !== undefined || !epochMatches) {
|
|
throw conflict("claim_lost", {
|
|
code: "claim_lost",
|
|
currentEpoch: Number(issue.claimEpoch ?? 0),
|
|
status: issue.status,
|
|
});
|
|
}
|
|
}
|
|
|
|
const now = new Date();
|
|
const clearingActiveWork = hadActiveLease || hadActiveRun;
|
|
if (clearingActiveWork) {
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
|
|
}
|
|
if (issue.channelId) {
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
|
|
}
|
|
|
|
const [updated] = await tx
|
|
.update(issues)
|
|
.set({
|
|
status: "cancelled",
|
|
cancelledAt: now,
|
|
...(clearingActiveWork
|
|
? {
|
|
claimEpoch: Number(issue.claimEpoch ?? 0) + 1,
|
|
claimTokenHash: null,
|
|
claimLeasedAt: null,
|
|
claimLeaseExpiresAt: null,
|
|
claimHolderAgentId: null,
|
|
claimHolderUserId: null,
|
|
claimHolderProfile: null,
|
|
checkoutRunId: null,
|
|
executionRunId: null,
|
|
}
|
|
: {}),
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(issues.id, issue.id))
|
|
.returning();
|
|
|
|
if (input.reason?.trim()) {
|
|
await tx.insert(issueComments).values({
|
|
companyId: issue.companyId,
|
|
issueId: issue.id,
|
|
body: input.reason.trim(),
|
|
...commentAuthorFields(actor),
|
|
});
|
|
}
|
|
|
|
await tx.insert(activityLog).values({
|
|
companyId: issue.companyId,
|
|
...activityActorFields(actor),
|
|
action: "issue.cancelled",
|
|
entityType: "issue",
|
|
entityId: updated!.id,
|
|
details: {
|
|
...(input.reason?.trim() ? { reason: input.reason.trim() } : {}),
|
|
},
|
|
});
|
|
|
|
const event = await appendBoardEvent(tx, {
|
|
companyId: issue.companyId,
|
|
type: "task.cancelled",
|
|
channelId: updated!.channelId,
|
|
channelPath: targetChannel?.path ?? null,
|
|
issueId: updated!.id,
|
|
identifier: updated!.identifier ?? updated!.id,
|
|
actor,
|
|
payload: {
|
|
...(input.reason?.trim() ? { reason: input.reason.trim() } : {}),
|
|
kvLabels: updated!.kvLabels ?? {},
|
|
},
|
|
});
|
|
|
|
const view = await loadHeadlessIssueView(tx, updated!.id, event.cursor);
|
|
return { view, event };
|
|
});
|
|
|
|
publishCommittedBoardEvent(committed.event);
|
|
return committed.view;
|
|
}
|
|
|
|
export async function reopenTask(
|
|
db: Db,
|
|
issueId: string,
|
|
actor: HeadlessActorContext,
|
|
rawInput: unknown,
|
|
opts?: { heartbeat?: ReturnType<typeof heartbeatService> },
|
|
): Promise<HeadlessIssueView> {
|
|
enforceHeadlessScopes(actor, { action: "tasks.reopen" });
|
|
const parsed = TaskReopenSchema.safeParse(rawInput ?? {});
|
|
if (!parsed.success) {
|
|
throw badRequest(
|
|
parsed.error.issues
|
|
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
|
|
.join("; "),
|
|
);
|
|
}
|
|
const input = parsed.data;
|
|
const targetStatus = input.status ?? "todo";
|
|
|
|
const committed = await db.transaction(async (tx) => {
|
|
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 isTerminal = issue.status === "done" || issue.status === "cancelled";
|
|
if (issue.claimTokenHash !== null || (!isTerminal && hasActiveWork(issue))) {
|
|
throw conflict("Cannot reopen a task that currently holds an active lease or run", {
|
|
code: "task_claimed",
|
|
status: issue.status,
|
|
});
|
|
}
|
|
|
|
if (actor.principalType === "agent") {
|
|
if (issue.status === "cancelled") {
|
|
throw forbidden(
|
|
"Cancelled tasks require explicit human or board restore authority to reopen",
|
|
{ code: "restore_authority_required", status: issue.status },
|
|
);
|
|
}
|
|
const trust = issue.sourceTrust as { level?: string; disposition?: string } | null;
|
|
if (trust?.level === "untrusted" || trust?.disposition === "quarantined") {
|
|
throw forbidden(
|
|
"Agents cannot reopen untrusted or quarantined tasks",
|
|
{ code: "untrusted_source_reopen_denied" },
|
|
);
|
|
}
|
|
}
|
|
|
|
const activePauseHold = await issueTreeControlService(db).getActivePauseHoldGate(
|
|
actor.companyId,
|
|
issue.id,
|
|
);
|
|
if (activePauseHold) {
|
|
throw conflict("Issue tree is currently paused", {
|
|
code: "issue_paused",
|
|
holdId: activePauseHold.holdId,
|
|
rootIssueId: activePauseHold.rootIssueId,
|
|
});
|
|
}
|
|
|
|
const blockerRows = await tx.execute<{ cnt: number }>(sql`
|
|
SELECT count(*)::int AS cnt
|
|
FROM issue_relations ir
|
|
INNER JOIN issues bi ON bi.id = ir.issue_id
|
|
WHERE ir.company_id = ${issue.companyId}
|
|
AND ir.related_issue_id = ${issue.id}
|
|
AND ir.type = 'blocks'
|
|
AND bi.status <> 'done'
|
|
`);
|
|
const hasOpenBlockers = Number(blockerRows[0]?.cnt ?? 0) > 0;
|
|
|
|
const now = new Date();
|
|
if (
|
|
targetStatus === "todo" &&
|
|
!hasOpenBlockers &&
|
|
!issue.assigneeAgentId &&
|
|
!issue.assigneeUserId &&
|
|
issue.channelId
|
|
) {
|
|
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
|
|
}
|
|
const [updated] = await tx
|
|
.update(issues)
|
|
.set({
|
|
status: targetStatus,
|
|
completedAt: null,
|
|
cancelledAt: null,
|
|
checkoutRunId: null,
|
|
executionRunId: null,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(issues.id, issue.id))
|
|
.returning();
|
|
|
|
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.reopened",
|
|
entityType: "issue",
|
|
entityId: updated!.id,
|
|
details: {
|
|
previousStatus: issue.status,
|
|
status: targetStatus,
|
|
},
|
|
});
|
|
|
|
const events: BoardEventView[] = [];
|
|
const reopenEvent = await appendBoardEvent(tx, {
|
|
companyId: issue.companyId,
|
|
type: "task.reopened",
|
|
channelId: updated!.channelId,
|
|
channelPath: targetChannel?.path ?? null,
|
|
issueId: updated!.id,
|
|
identifier: updated!.identifier ?? updated!.id,
|
|
actor,
|
|
payload: {
|
|
previousStatus: issue.status,
|
|
status: targetStatus,
|
|
kvLabels: updated!.kvLabels ?? {},
|
|
},
|
|
});
|
|
events.push(reopenEvent);
|
|
|
|
if (
|
|
targetStatus === "todo" &&
|
|
!hasOpenBlockers &&
|
|
!updated!.assigneeAgentId &&
|
|
!updated!.assigneeUserId
|
|
) {
|
|
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: {
|
|
kvLabels: updated!.kvLabels ?? {},
|
|
},
|
|
});
|
|
events.push(readyEvent);
|
|
}
|
|
|
|
const view = await loadHeadlessIssueView(
|
|
tx,
|
|
updated!.id,
|
|
events[events.length - 1]!.cursor,
|
|
);
|
|
return {
|
|
view,
|
|
events,
|
|
channelId: updated!.channelId,
|
|
assigneeAgentId: updated!.assigneeAgentId,
|
|
channelPath: targetChannel?.path ?? null,
|
|
hasOpenBlockers,
|
|
};
|
|
});
|
|
|
|
for (const ev of committed.events) {
|
|
publishCommittedBoardEvent(ev);
|
|
}
|
|
|
|
if (targetStatus === "todo" && !committed.hasOpenBlockers) {
|
|
if (committed.assigneeAgentId) {
|
|
await wakeAssignedAgent(opts?.heartbeat, {
|
|
issueId: committed.view.id,
|
|
assigneeAgentId: committed.assigneeAgentId,
|
|
reason: "issue_reopened",
|
|
actor,
|
|
channelPath: committed.channelPath,
|
|
});
|
|
} else if (committed.channelId) {
|
|
await dispatchManagedChannelPoolBestEffort(db, actor.companyId, committed.channelId, {
|
|
heartbeat: opts?.heartbeat,
|
|
actor,
|
|
});
|
|
}
|
|
}
|
|
|
|
return committed.view;
|
|
}
|