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
157 lines
4.8 KiB
TypeScript
157 lines
4.8 KiB
TypeScript
export const CHANNEL_PATH_REGEX = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*$/;
|
|
|
|
export const CLAIMABLE_TASK_STATUSES = ["todo", "backlog", "in_review"] as const;
|
|
export type ClaimableTaskStatus = (typeof CLAIMABLE_TASK_STATUSES)[number];
|
|
|
|
export const TASK_CLAIM_ASSIGNEE_MODES = ["unassigned", "me", "any"] as const;
|
|
export type TaskClaimAssigneeMode = (typeof TASK_CLAIM_ASSIGNEE_MODES)[number];
|
|
|
|
export interface NormalizedChannelPath {
|
|
path: string;
|
|
isSubtreePrefix: boolean;
|
|
}
|
|
|
|
export function normalizeChannelPath(
|
|
input: string,
|
|
opts?: { allowSubtreePrefix?: boolean },
|
|
): NormalizedChannelPath {
|
|
const allowSubtreePrefix = opts?.allowSubtreePrefix ?? true;
|
|
let trimmed = input.trim();
|
|
if (trimmed.startsWith("#")) {
|
|
trimmed = trimmed.slice(1).trim();
|
|
}
|
|
trimmed = trimmed.toLowerCase();
|
|
|
|
const isSubtreePrefix = trimmed.endsWith("/");
|
|
if (isSubtreePrefix && !allowSubtreePrefix) {
|
|
throw new Error(
|
|
`Invalid channel path "${input}": trailing '/' is only allowed for subtree queries`,
|
|
);
|
|
}
|
|
|
|
const candidate = isSubtreePrefix ? trimmed.slice(0, -1) : trimmed;
|
|
if (!CHANNEL_PATH_REGEX.test(candidate)) {
|
|
throw new Error(
|
|
`Invalid channel path "${input}": segments must be lowercase alphanumeric with '-' or '_' separated by '/'`,
|
|
);
|
|
}
|
|
|
|
return { path: candidate, isSubtreePrefix };
|
|
}
|
|
|
|
const TITLE_MAX_LEN = 120;
|
|
|
|
function truncateTitle(raw: string, maxLen = TITLE_MAX_LEN): string {
|
|
if (raw.length <= maxLen) return raw;
|
|
const slice = raw.slice(0, maxLen - 1);
|
|
const lastSpace = slice.lastIndexOf(" ");
|
|
if (lastSpace > Math.floor(maxLen * 0.6)) {
|
|
return `${slice.slice(0, lastSpace).trimEnd()}…`;
|
|
}
|
|
return `${slice.trimEnd()}…`;
|
|
}
|
|
|
|
export function splitMessageIntoTitleAndDescription(
|
|
text: string,
|
|
fallbackLabel?: string,
|
|
): { title: string; description: string | null } {
|
|
const normalized = text.replace(/\r\n/g, "\n").trim();
|
|
if (!normalized) {
|
|
const fallback = fallbackLabel?.trim() || "Untitled post";
|
|
return {
|
|
title: truncateTitle(fallback, TITLE_MAX_LEN),
|
|
description: null,
|
|
};
|
|
}
|
|
|
|
const nonEmptyLines = normalized
|
|
.split("\n")
|
|
.map((line) => line.trim())
|
|
.filter((line) => line.length > 0);
|
|
|
|
const firstRaw = nonEmptyLines[0] ?? normalized;
|
|
const withoutHeading = firstRaw.replace(/^#{1,6}\s+/, "").trim();
|
|
const baseLine = withoutHeading.length > 0 ? withoutHeading : firstRaw;
|
|
const title = truncateTitle(baseLine, TITLE_MAX_LEN);
|
|
|
|
if (nonEmptyLines.length === 1 && baseLine.length <= TITLE_MAX_LEN) {
|
|
return { title, description: null };
|
|
}
|
|
|
|
return { title, description: normalized };
|
|
}
|
|
|
|
export const SCHEMA_NAME_REGEX = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
export const SCHEMA_REF_REGEX = /^([a-z0-9][a-z0-9_-]{0,63})@([1-9][0-9]*)$/;
|
|
|
|
export interface ParsedSchemaRef {
|
|
name: string;
|
|
version: number;
|
|
ref: string;
|
|
}
|
|
|
|
export function parseSchemaRef(ref: string): ParsedSchemaRef {
|
|
const trimmed = ref.trim();
|
|
const match = SCHEMA_REF_REGEX.exec(trimmed);
|
|
if (!match) {
|
|
throw new Error(
|
|
`Invalid schema reference "${ref}": expected <name>@<positive-integer> (e.g. security-finding@1)`,
|
|
);
|
|
}
|
|
const name = match[1]!;
|
|
const version = Number.parseInt(match[2]!, 10);
|
|
if (!Number.isSafeInteger(version) || version < 1) {
|
|
throw new Error(`Invalid schema version in "${ref}"`);
|
|
}
|
|
return { name, version, ref: `${name}@${version}` };
|
|
}
|
|
|
|
const DURATION_RE = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)$/i;
|
|
|
|
const UNIT_MULTIPLIERS_MS: Record<string, number> = {
|
|
ms: 1,
|
|
s: 1_000,
|
|
m: 60_000,
|
|
h: 3_600_000,
|
|
d: 86_400_000,
|
|
};
|
|
|
|
export function parseDurationMs(input: string | number): number {
|
|
if (typeof input === "number") {
|
|
if (!Number.isFinite(input) || input < 0) {
|
|
throw new Error(`Invalid duration number: ${input}`);
|
|
}
|
|
return Math.floor(input);
|
|
}
|
|
const trimmed = input.trim();
|
|
const match = DURATION_RE.exec(trimmed);
|
|
if (!match) {
|
|
throw new Error(
|
|
`Invalid duration "${input}": expected <number><ms|s|m|h|d> (e.g. "30s", "5m", "2h", "7d")`,
|
|
);
|
|
}
|
|
const amount = Number.parseFloat(match[1]!);
|
|
const unit = match[2]!.toLowerCase();
|
|
const multiplier = UNIT_MULTIPLIERS_MS[unit];
|
|
if (!Number.isFinite(amount) || amount < 0 || multiplier === undefined) {
|
|
throw new Error(`Invalid duration "${input}"`);
|
|
}
|
|
return Math.floor(amount * multiplier);
|
|
}
|
|
|
|
const EVENT_CURSOR_RE = /^evt_([0-9]+)$/;
|
|
|
|
export function formatEventCursor(seq: number): string {
|
|
if (!Number.isSafeInteger(seq) || seq < 0) {
|
|
throw new Error(`Invalid event sequence number: ${seq}`);
|
|
}
|
|
return `evt_${seq}`;
|
|
}
|
|
|
|
export function parseEventCursor(cursor: string): number | null {
|
|
const match = EVENT_CURSOR_RE.exec(cursor.trim());
|
|
if (!match) return null;
|
|
const parsed = Number.parseInt(match[1]!, 10);
|
|
return Number.isSafeInteger(parsed) ? parsed : null;
|
|
}
|