Files
PaperClipAI/server/src/services/headless-managed-pool-worker.ts
T
Dotta 0434e7f3aa feat(board): add task assign, atomic handoff, claim filters, cancel/reopen, mid-flight deps, and channel admin (#23415)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Headless channels, fenced task queues, `@paperclipai/shared/sdk`,
and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and
inbox/queue patterns.
> - Real multi-stage workflows immediately hit gaps: there was no
`assign` command to push existing channel posts to managed agents, no
atomic `handoff`/`move` across channels with CAS labels and lease
release, `claim --ready` could not opt into `backlog`/`in_review` or
`--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs`
dependency linking, and `pc channels` could not update queue config,
manage private members, or bind event-driven managed pools.
> - Without these primitives, operators had to drop back to raw `issue
update` calls or non-atomic two-step scripts that race on crash.
> - This pull request adds the complete workflow lifecycle across shared
schemas, modular server services/routes, SDK methods, `pc` CLI commands,
and the `.agents/skills/channels-queues-and-workflows` skill.
> - The benefit is end-to-end single-command support for inbox triage,
single-thread relays, chained channel assembly lines, mid-flight DAG
dependencies, and Day-2 graduation to managed Paperclip agent pools.

## Linked Issues or Issue Description

Refs #23330

**Subsystem affected**
Cross-cutting (multiple of the above)

**Problem or motivation**
Building multi-agent queues and chained workflows on Paperclip channels
required workarounds: assigning an existing post to a registered agent
required raw `issue update --assignee-agent-id <uuid>`; moving an issue
across stage channels with a label update and lease release required
non-atomic multi-step calls; triage or review workers could not opt into
claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`);
tasks could not be cancelled, reopened, or given mid-flight `--needs`
blockers; and channels lacked CLI/API administration for `queueConfig`,
private `channel_access_members`, and `managedPool` auto-dispatch.

**Proposed solution**
Add cohesive REST endpoints, modular services
(`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK
methods, `pc` CLI subcommands, and the `channels-queues-and-workflows`
skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block
--needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels
update`/`members` with event-driven `managedPool` dispatch.

**Alternatives considered**
Leaving these operations to raw `PATCH /api/issues/:id` calls was
rejected because it bypasses fenced claim tokens (`claimEpoch` +
`claimToken`), lacks atomic channel+label+lease transactions, and does
not enforce CAS preconditions or dependency cycle checks.

**Roadmap alignment**
Directly extends the headless channels and queues coordination primitive
introduced in #23330.

## What Changed

- **Shared schemas & SDK (`packages/shared/src/headless/`,
`packages/shared/src/sdk/`):**
- Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and
`TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded
`TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and
`TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and
added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`,
`TaskReopenSchema`, `TaskDependenciesMutationSchema`,
`updateChannelInputSchema`, and `channelMemberInputSchema`.
- Added `task.assigned`, `task.handed_off`, `task.cancelled`,
`task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`.
- Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`,
and `paperclip().channels`.
- **Server services & routes (`server/src/services/`,
`server/src/routes/`):**
- Upgraded `claimTask` and `releaseTaskClaim` in
`headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`,
`in_review` excluding pending interactions), `assignee` (`unassigned`,
`me`, `any`), and atomic channel/label/status updates on release.
- Added `server/src/services/headless-task-workflows.ts` implementing
`assignTask`, `handoffTask`, `cancelTask`, `reopenTask`,
`listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle
detection and fenced lease release).
- Added `server/src/services/headless-channel-admin.ts` implementing
`updateChannel`, `listChannelMembers`, `addChannelMember`,
`removeChannelMember`, and event-driven `dispatchManagedChannelPool`
(zero idle polling).
- Wired routes in `headless-queues-events.ts` and
`headless-channels-schemas.ts`.
- **CLI (`cli/src/commands/board/`):**
- Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`,
`handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`).
- Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`),
`pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc
tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members
list|add|remove`).
- **Skill & Tests:**
- Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and
`examples.md`.
- Added `server/src/__tests__/headless-task-workflows.test.ts` and
updated `tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/server typecheck && pnpm --filter paperclipai typecheck` —
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/headless-task-workflows.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests
passed.
- Live headless CLI test-drive (`pc up --port 3299` in isolated
`PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`,
`tasks claim --mine`, `tasks handoff`, `tasks release --status
in_review`, `tasks claim --status in_review`, `tasks block --needs`,
`tasks deps list`, blocker completion auto-unblock, `tasks cancel`,
`tasks reopen`, `tasks claim --status backlog`, `channels members
add/list/remove`, and `channels update --managed-pool` — all 11
scenarios passed.

## Risks

- Low risk. No database migrations are required; existing
`channels.queue_config`, `channel_access_members`, `issue_relations`,
and `issues` lease columns are reused.
- Default `claim --ready` behavior (`status = todo`, `assignee =
unassigned`) is unchanged; `--status` and `--assignee` are strictly
opt-in, and `--assignee me`/`any` never allows claiming tasks assigned
to another agent or user.
- Note on file size: `server/src/services/headless-task-queue.ts` and
`cli/src/commands/board/tasks.ts` were already over 1,000 lines before
this PR; all new workflow/admin operations were placed in dedicated
sibling modules (`headless-task-workflows.ts`,
`headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing
files bounded.

## Model Used

- Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium,
extended thinking with tool use and code execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-12-01 23:54:54 +00:00

457 lines
15 KiB
TypeScript

import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channels,
issueRelations,
issues,
} from "@paperclipai/db";
import { isUuidLike } from "@paperclipai/shared";
import type { heartbeatService } from "./heartbeat.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import {
dispatchManagedChannelPool,
isAgentEligibleForChannelPool,
isCandidateEligibleForPoolDispatch,
} from "./headless-managed-pool.js";
export interface ManagedPoolRecoveryScope {
channelIds?: string[];
companyIds?: string[];
agentTargets?: Array<{ companyId: string; agentId: string }>;
issueTargets?: Array<{ companyId: string; issueId: string }>;
}
/**
* Recovers managed channel pools (full scan on startup, or narrowed by scope hints
* on subsequent deliveryWork signals so unrelated writes do not scan all pools).
*/
export async function recoverManagedChannelPools(
db: Db,
heartbeat: ReturnType<typeof heartbeatService>,
scope?: ManagedPoolRecoveryScope,
signal?: AbortSignal,
): Promise<{ recoveredChannels: number; wokenIssueIds: string[]; dispatchedIssueIds: string[] }> {
const channelIdsToCheck = new Set<string>(scope?.channelIds ?? []);
const companyIdsToCheck = new Set<string>(scope?.companyIds ?? []);
const agentTargets = scope?.agentTargets ?? [];
if (scope?.issueTargets && scope.issueTargets.length > 0) {
const issueIds = [...new Set(scope.issueTargets.map((t) => t.issueId))];
const directRows = await db
.select({ channelId: issues.channelId })
.from(issues)
.where(inArray(issues.id, issueIds));
for (const r of directRows) {
if (r.channelId) channelIdsToCheck.add(r.channelId);
}
const depRows = await db
.select({ channelId: issues.channelId })
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.relatedIssueId))
.where(
and(
inArray(issueRelations.issueId, issueIds),
eq(issueRelations.type, "blocks"),
),
);
for (const r of depRows) {
if (r.channelId) channelIdsToCheck.add(r.channelId);
}
}
const scopeFilters = [];
if (scope) {
if (channelIdsToCheck.size > 0) {
scopeFilters.push(inArray(channels.id, [...channelIdsToCheck]));
}
if (companyIdsToCheck.size > 0) {
scopeFilters.push(inArray(channels.companyId, [...companyIdsToCheck]));
}
for (const target of agentTargets) {
scopeFilters.push(
and(
eq(channels.companyId, target.companyId),
sql`(${channels.queueConfig}->'managedPool'->>'agentId') = ${target.agentId}`,
),
);
}
if (scopeFilters.length === 0) {
return { recoveredChannels: 0, wokenIssueIds: [], dispatchedIssueIds: [] };
}
}
const poolChannels = await db
.select()
.from(channels)
.where(
and(
isNull(channels.archivedAt),
sql`jsonb_exists(${channels.queueConfig}, 'managedPool')`,
...(scopeFilters.length > 0 ? [or(...scopeFilters)] : []),
),
);
const wokenIssueIds: string[] = [];
const dispatchedIssueIds: string[] = [];
for (const ch of poolChannels) {
if (signal?.aborted) break;
const pool = ch.queueConfig?.managedPool;
if (!pool) continue;
// On full startup recovery only, re-wake any eligible assigned todo tasks
// whose initial wakeup was interrupted before an agent run started.
if (!scope) {
const [agentRow] = await db
.select({
id: agents.id,
role: agents.role,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, pool.agentId),
eq(agents.companyId, ch.companyId),
ne(agents.status, "terminated"),
ne(agents.status, "paused"),
),
)
.limit(1);
if (agentRow && (await isAgentEligibleForChannelPool(db, ch, agentRow))) {
const stranded = await db.execute<{ id: string }>(sql`
SELECT i.id
FROM issues i
WHERE i.company_id = ${ch.companyId}
AND i.channel_id = ${ch.id}
AND i.assignee_agent_id = ${pool.agentId}
AND i.status = 'todo'
AND i.execution_run_id IS NULL
AND i.checkout_run_id IS NULL
AND i.claim_token_hash IS NULL
AND i.claim_lease_expires_at IS NULL
AND i.conversation_agent_id IS NULL
AND i.hidden_at IS NULL
AND COALESCE(i.source_trust->>'level', '') <> 'untrusted'
AND COALESCE(i.source_trust->>'disposition', '') <> 'quarantined'
AND NOT EXISTS (
SELECT 1
FROM projects p
WHERE p.id = i.project_id
AND p.paused_at IS NOT NULL
)
AND NOT EXISTS (
SELECT 1
FROM issue_relations ir
INNER JOIN issues bi ON bi.id = ir.issue_id
WHERE ir.company_id = i.company_id
AND ir.related_issue_id = i.id
AND ir.type = 'blocks'
AND bi.status <> 'done'
)
`);
const treeControl = issueTreeControlService(db);
for (const row of stranded) {
if (signal?.aborted) break;
if (await treeControl.getActivePauseHoldGate(ch.companyId, row.id)) {
continue;
}
await heartbeat
.wakeup(pool.agentId, {
source: "assignment",
triggerDetail: "system",
reason: "issue_assigned",
payload: {
issueId: row.id,
channelId: ch.id,
channelPath: ch.path,
managedPool: true,
startupRecovery: true,
},
idempotencyKey: `managed-pool-recovery:${ch.id}:${row.id}`,
requestedByActorType: "system",
requestedByActorId: "managed_channel_pool_recovery",
contextSnapshot: {
issueId: row.id,
taskId: row.id,
wakeReason: "issue_assigned",
},
})
.catch(() => {
// Best-effort startup wakeup
});
wokenIssueIds.push(row.id);
}
}
}
if (signal?.aborted) break;
// Dispatch any remaining free capacity in this channel
const res = await dispatchManagedChannelPool(db, ch.companyId, ch.id, {
heartbeat,
});
dispatchedIssueIds.push(...res.dispatchedIssueIds);
}
return {
recoveredChannels: poolChannels.length,
wokenIssueIds,
dispatchedIssueIds,
};
}
/**
* Sleep-aware managed channel pool worker registered on the shared deliveryWork coordinator.
* Runs a full scan on startup and narrows subsequent runs using committed deliveryWork hints
* while falling back to a full scan on empty-scope retries.
*/
export function createManagedChannelPoolWorker(
db: Db,
heartbeat: ReturnType<typeof heartbeatService>,
) {
let fullScan = true;
const pendingChannelIds = new Set<string>();
const pendingCompanyIds = new Set<string>();
const pendingAgentTargets = new Map<string, { companyId: string; agentId: string }>();
const pendingIssueTargets = new Map<string, { companyId: string; issueId: string }>();
function recordHints(hints?: ReadonlySet<string>) {
if (!hints || hints.size === 0) {
fullScan = true;
return;
}
for (const raw of hints) {
if (raw === "*") {
fullScan = true;
return;
}
if (isUuidLike(raw)) {
pendingChannelIds.add(raw);
continue;
}
try {
const parsed = JSON.parse(raw) as {
companyId?: string;
channelId?: string;
agentId?: string;
issueId?: string;
reload?: boolean;
};
if (parsed.reload || !parsed.companyId) {
fullScan = true;
return;
}
if (parsed.channelId) {
pendingChannelIds.add(parsed.channelId);
} else if (parsed.agentId) {
pendingAgentTargets.set(`${parsed.companyId}:${parsed.agentId}`, {
companyId: parsed.companyId,
agentId: parsed.agentId,
});
} else if (parsed.issueId) {
pendingIssueTargets.set(`${parsed.companyId}:${parsed.issueId}`, {
companyId: parsed.companyId,
issueId: parsed.issueId,
});
} else {
pendingCompanyIds.add(parsed.companyId);
}
} catch {
fullScan = true;
return;
}
}
}
return {
recoverManagedChannelPools: () => recoverManagedChannelPools(db, heartbeat),
deliveryTask: {
retryMs: 5_000,
coalesceMs: 50,
pausePassiveMaintenance: true,
onSettled: (hints?: ReadonlySet<string>) => {
recordHints(hints);
},
run: async (signal: AbortSignal) => {
if (signal.aborted) return;
const doFull = fullScan;
const channelIds = [...pendingChannelIds];
const companyIds = [...pendingCompanyIds];
const agentTargets = [...pendingAgentTargets.values()];
const issueTargets = [...pendingIssueTargets.values()];
const hasScopedHints =
channelIds.length > 0 ||
companyIds.length > 0 ||
agentTargets.length > 0 ||
issueTargets.length > 0;
fullScan = false;
pendingChannelIds.clear();
pendingCompanyIds.clear();
pendingAgentTargets.clear();
pendingIssueTargets.clear();
try {
if (doFull || !hasScopedHints) {
await recoverManagedChannelPools(db, heartbeat, undefined, signal);
} else {
await recoverManagedChannelPools(
db,
heartbeat,
{
channelIds,
companyIds,
agentTargets,
issueTargets,
},
signal,
);
}
} catch (err) {
// Restore scope so the coordinator retry covers the interrupted work
if (doFull || !hasScopedHints) fullScan = true;
for (const id of channelIds) pendingChannelIds.add(id);
for (const id of companyIds) pendingCompanyIds.add(id);
for (const t of agentTargets) pendingAgentTargets.set(`${t.companyId}:${t.agentId}`, t);
for (const t of issueTargets) pendingIssueTargets.set(`${t.companyId}:${t.issueId}`, t);
throw err;
}
},
hasPending: async (runAllowed = true) => {
if (!runAllowed) return false;
const candidateChannels = await db
.select()
.from(channels)
.where(
and(
isNull(channels.archivedAt),
sql`jsonb_exists(${channels.queueConfig}, 'managedPool')`,
sql`EXISTS (
SELECT 1
FROM agents a
WHERE a.id = (${channels.queueConfig}->'managedPool'->>'agentId')::uuid
AND a.company_id = ${channels.companyId}
AND a.status NOT IN ('terminated', 'paused')
)`,
sql`(
SELECT count(*)::int
FROM issues active_i
WHERE active_i.company_id = ${channels.companyId}
AND active_i.channel_id = ${channels.id}
AND active_i.assignee_agent_id = (${channels.queueConfig}->'managedPool'->>'agentId')::uuid
AND active_i.status IN ('todo', 'in_progress')
AND active_i.hidden_at IS NULL
) < COALESCE((${channels.queueConfig}->'managedPool'->>'maxConcurrency')::int, 1)`,
),
);
if (candidateChannels.length === 0) return false;
const treeControl = issueTreeControlService(db);
const BATCH_SIZE = 25;
for (const ch of candidateChannels) {
const pool = ch.queueConfig?.managedPool;
if (!pool) continue;
const [agentRow] = await db
.select({
id: agents.id,
role: agents.role,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, pool.agentId),
eq(agents.companyId, ch.companyId),
ne(agents.status, "terminated"),
ne(agents.status, "paused"),
),
)
.limit(1);
if (!agentRow || !(await isAgentEligibleForChannelPool(db, ch, agentRow))) {
continue;
}
const seenIds: string[] = [];
while (true) {
const seenExclusion =
seenIds.length > 0
? sql`AND i.id NOT IN (${sql.join(
seenIds.map((id) => sql`${id}::uuid`),
sql`, `,
)})`
: sql``;
const readyRows = await db.execute<{
id: string;
project_id: string | null;
parent_id: string | null;
execution_policy: unknown;
}>(sql`
SELECT i.id, i.project_id, i.parent_id, i.execution_policy
FROM issues i
WHERE i.company_id = ${ch.companyId}
AND i.channel_id = ${ch.id}
AND i.status = 'todo'
AND i.hidden_at IS NULL
AND i.assignee_agent_id IS NULL
AND i.assignee_user_id IS NULL
AND i.claim_token_hash IS NULL
AND i.claim_lease_expires_at IS NULL
AND i.checkout_run_id IS NULL
AND i.execution_run_id IS NULL
AND i.conversation_agent_id IS NULL
AND COALESCE(i.source_trust->>'level', '') <> 'untrusted'
AND COALESCE(i.source_trust->>'disposition', '') <> 'quarantined'
${seenExclusion}
AND NOT EXISTS (
SELECT 1
FROM issue_relations ir
INNER JOIN issues bi ON bi.id = ir.issue_id
WHERE ir.company_id = i.company_id
AND ir.related_issue_id = i.id
AND ir.type = 'blocks'
AND bi.status <> 'done'
)
LIMIT ${BATCH_SIZE}
`);
if (readyRows.length === 0) break;
for (const row of readyRows) {
seenIds.push(row.id);
const eligible = await isCandidateEligibleForPoolDispatch(
db,
ch,
pool.agentId,
{
id: row.id,
projectId: row.project_id,
parentId: row.parent_id,
executionPolicy: row.execution_policy,
},
treeControl,
);
if (eligible) {
return true;
}
}
if (readyRows.length < BATCH_SIZE) break;
}
}
return false;
},
},
};
}