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

@@ -0,0 +1,570 @@
import { randomUUID } from "node:crypto";
import { createServer, type Server as HttpServer } from "node:http";
import express from "express";
import {
afterAll,
beforeAll,
describe,
expect,
it,
vi,
} from "vitest";
import { and, eq } from "drizzle-orm";
import {
activityLog,
agents,
companies,
companyMemberships,
createDb,
type Db,
} from "@paperclipai/db";
import { paperclip } from "@paperclipai/shared/sdk";
import { errorHandler } from "../middleware/error-handler.js";
import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js";
import { headlessQueuesEventsRoutes } from "../routes/headless-queues-events.js";
import type { heartbeatService } from "../services/heartbeat.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
vi.hoisted(() => {
process.env.PAPERCLIP_HOME = "/tmp/paperclip-test-home-workflows";
process.env.PAPERCLIP_INSTANCE_ID = "vitest-headless-workflows";
process.env.PAPERCLIP_LOG_DIR = "/tmp/paperclip-test-home-workflows/logs";
process.env.PAPERCLIP_IN_WORKTREE = "false";
});
const support = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = support.supported ? describe : describe.skip;
function createTestServer(db: Db, wakeupSpy: ReturnType<typeof vi.fn>) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
const actorType = req.header("x-test-actor-type");
if (actorType === "agent") {
req.actor = {
type: "agent",
agentId: req.header("x-test-agent-id") ?? undefined,
companyId: req.header("x-test-company-id") ?? undefined,
source: "agent_key",
};
} else {
req.actor = {
type: "board",
userId: req.header("x-test-user-id") ?? "board-user",
source: "local_implicit",
isInstanceAdmin: true,
};
}
next();
});
const mockHeartbeat = {
wakeup: wakeupSpy,
} as unknown as ReturnType<typeof heartbeatService>;
app.use("/api", headlessChannelsSchemasRoutes(db, { heartbeat: mockHeartbeat }));
app.use("/api", headlessQueuesEventsRoutes(db, { heartbeat: mockHeartbeat }));
app.use(errorHandler);
return createServer(app);
}
describeEmbeddedPostgres("headless task workflows, claim filters, and channel admin", () => {
let stopDb: (() => Promise<void>) | undefined;
let db: Db;
let server: HttpServer;
let apiBase: string;
let companyId: string;
let agentAId: string;
let agentBId: string;
const wakeupSpy = vi.fn().mockResolvedValue(null);
const makeAgentClient = (agentId: string) =>
paperclip({
apiBase,
company: companyId,
fetch: (input, init) => {
const headers = new Headers(init?.headers);
headers.set("x-test-actor-type", "agent");
headers.set("x-test-agent-id", agentId);
headers.set("x-test-company-id", companyId);
return fetch(input, { ...init, headers });
},
});
const makeBoardClient = () =>
paperclip({
apiBase,
company: companyId,
});
beforeAll(async () => {
const started = await startEmbeddedPostgresTestDatabase(
"paperclip-headless-workflows",
);
stopDb = started.cleanup;
db = createDb(started.connectionString);
server = createTestServer(db, wakeupSpy);
await new Promise<void>((resolve) => {
server.listen(0, "127.0.0.1", () => resolve());
});
const addr = server.address();
if (!addr || typeof addr === "string") {
throw new Error("Failed to bind test server");
}
apiBase = `http://127.0.0.1:${addr.port}`;
companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Workflow Test Co",
issuePrefix: "WFL",
});
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: "board-user",
membershipRole: "owner",
status: "active",
});
agentAId = randomUUID();
agentBId = randomUUID();
await db.insert(agents).values([
{
id: agentAId,
companyId,
name: "backend-eng",
role: "engineer",
status: "idle",
adapterType: "process",
},
{
id: agentBId,
companyId,
name: "qa-reviewer",
role: "qa",
status: "idle",
adapterType: "process",
},
]);
}, 60_000);
afterAll(async () => {
await new Promise<void>((resolve) => server?.close(() => resolve()));
await stopDb?.();
});
it("assigns passive posts (promoting backlog -> todo), enforces lease guard unless forced, and unassigns", async () => {
wakeupSpy.mockClear();
const board = makeBoardClient();
const post = await board.post("inbox/bugs", "500 on /api/checkout");
expect(post.status).toBe("backlog");
expect(post.assigneeAgentId).toBeNull();
const assigned = await board.tasks.assign(post.identifier, "@backend-eng", {
comment: "Routing to backend team",
});
expect(assigned.assigneeAgentId).toBe(agentAId);
expect(assigned.status).toBe("todo");
expect(wakeupSpy).toHaveBeenCalledWith(
agentAId,
expect.objectContaining({ reason: "issue_assigned" }),
);
// Unassign returns it to unassigned pool
const unassigned = await board.tasks.assign(post.identifier, null, {
unassign: true,
});
expect(unassigned.assigneeAgentId).toBeNull();
expect(unassigned.status).toBe("todo");
// Claim it, verify assign without force fails 409, then force succeeds & fences old claim
const claimed = await board.as("worker-1").tasks.claim(post.identifier);
expect(claimed).not.toBeNull();
await expect(
board.tasks.assign(post.identifier, "@qa-reviewer"),
).rejects.toMatchObject({ status: 409, code: "task_claimed" });
const forced = await board.tasks.assign(post.identifier, "@qa-reviewer", {
force: true,
});
expect(forced.assigneeAgentId).toBe(agentBId);
expect(forced.claimLeaseExpiresAt).toBeNull();
// Old worker's lease is fenced
await expect(claimed!.renew("5m")).rejects.toMatchObject({
status: 409,
code: "claim_lost",
});
});
it("supports claim --status (backlog, in_review excluding pending interactions) and --assignee me/any", async () => {
const board = makeBoardClient();
const agentA = makeAgentClient(agentAId);
const agentB = makeAgentClient(agentBId);
// 1. Backlog post: ignored by default claim, poppable with status: ["backlog"]
const rawPost = await board.post("triage/raw", "Raw customer alert");
const defaultPop = await board.tasks.claim({ channel: "triage/raw" });
expect(defaultPop).toBeNull();
const backlogPop = await board.tasks.claim({
channel: "triage/raw",
status: "backlog",
});
expect(backlogPop?.task.id).toBe(rawPost.id);
await backlogPop!.complete("Triaged");
// 2. in_review: excluded if pending human interaction exists, claimable if no pending interaction
const reviewWithCard = await board.tasks.create("review/queue", "Needs human confirm");
const reviewClean = await board.tasks.create("review/queue", "Ready for agent review");
const claimedCard = await board.tasks.claim(reviewWithCard.identifier);
await claimedCard!.confirm("Approve deploy?", { humanOnly: true });
const claimedClean = await board.tasks.claim(reviewClean.identifier);
await claimedClean!.release({ status: "in_review", comment: "Ready for peer review" });
const reviewPop = await agentB.tasks.claim({
channel: "review/queue",
status: "in_review",
});
expect(reviewPop?.task.id).toBe(reviewClean.id);
await reviewPop!.complete("LGTM");
// Second pop must be null because reviewWithCard has a pending human interaction
const reviewPop2 = await agentB.tasks.claim({
channel: "review/queue",
status: "in_review",
});
expect(reviewPop2).toBeNull();
// 3. --assignee me / any: agentA claims its own assigned task, never steals agentB's
const forA = await board.tasks.create("assigned/pool", "Task for A", { for: "@backend-eng" });
const forB = await board.tasks.create("assigned/pool", "Task for B", { for: "@qa-reviewer" });
const unassignedTask = await board.tasks.create("assigned/pool", "Unassigned task");
const aMine = await agentA.tasks.claim({
channel: "assigned/pool",
assignee: "me",
});
expect(aMine?.task.id).toBe(forA.id);
await aMine!.complete("Done A");
// Next --assignee me for agentA is empty (cannot steal forB)
const aMine2 = await agentA.tasks.claim({
channel: "assigned/pool",
assignee: "me",
});
expect(aMine2).toBeNull();
// --assignee any for agentA picks up unassignedTask, still never steals forB
const aAny = await agentA.tasks.claim({
channel: "assigned/pool",
assignee: "any",
});
expect(aAny?.task.id).toBe(unassignedTask.id);
await aAny!.complete("Done unassigned");
const aAny2 = await agentA.tasks.claim({
channel: "assigned/pool",
assignee: "any",
});
expect(aAny2).toBeNull();
// Verify forB is still untouched and claimable by agentB
const bMine = await agentB.tasks.claim({
channel: "assigned/pool",
assignee: "me",
});
expect(bMine?.task.id).toBe(forB.id);
await bMine!.complete("Done B");
});
it("performs atomic handoff across channels with CAS labels and fenced lease release", async () => {
const board = makeBoardClient();
const draft = await board.tasks.create("seo/drafts", "Write AEO guide", {
labels: { stage: "draft" },
});
const claimed = await board.as("writer-1").tasks.claim({ channel: "seo/drafts" });
expect(claimed?.task.id).toBe(draft.id);
// CAS mismatch rejects without releasing lease or moving channel
await expect(
claimed!.handoff({
channel: "seo/review",
labels: { stage: "review" },
ifLabels: { stage: "wrong" },
}),
).rejects.toMatchObject({ status: 409, code: "label_conflict" });
// Valid CAS handoff moves channel, updates label, and releases lease atomically
const handed = await claimed!.handoff({
channel: "seo/review",
labels: { stage: "review" },
ifLabels: { stage: "draft" },
comment: "Draft complete, ready for fact-check",
});
expect(handed.channel).toBe("seo/review");
expect(handed.status).toBe("todo");
expect(handed.kvLabels.stage).toBe("review");
expect(handed.claimLeaseExpiresAt).toBeNull();
// Old writer lease is fenced
await expect(claimed!.renew("5m")).rejects.toMatchObject({
status: 409,
code: "claim_lost",
});
// Reviewer pool can immediately pop from seo/review
const reviewClaim = await board.as("reviewer-1").tasks.claim({
channel: "seo/review",
label: "stage=review",
});
expect(reviewClaim?.task.id).toBe(draft.id);
await reviewClaim!.complete("Published");
});
it("supports cancel, reopen, and mid-flight dependencies with cycle detection", async () => {
const board = makeBoardClient();
const taskA = await board.tasks.create("ops/work", "Deploy service A");
const taskB = await board.tasks.create("ops/work", "Run DB migration B");
// Worker claims A, discovers it needs B, adds dependency and releases lease
const claimedA = await board.as("ops-1").tasks.claim(taskA.identifier);
expect(claimedA).not.toBeNull();
const deps = await board.tasks.updateDependencies(taskA.identifier, {
add: [taskB.identifier],
releaseLease: true,
claimToken: claimedA!.claimToken,
claimEpoch: claimedA!.claimEpoch,
comment: "Waiting on migration B",
});
expect(deps.status).toBe("todo");
expect(deps.blockedBy.map((d) => d.id)).toContain(taskB.id);
// Cycle detection: B cannot depend on A
await expect(
board.tasks.updateDependencies(taskB.identifier, { add: [taskA.identifier] }),
).rejects.toMatchObject({ status: 400, code: "cyclic_dependencies" });
// A cannot be claimed while B is incomplete
await expect(board.tasks.claim(taskA.identifier)).rejects.toMatchObject({
status: 409,
code: "task_not_claimable",
});
// Complete B -> A becomes claimable again
const claimedB = await board.as("ops-2").tasks.claim(taskB.identifier);
await claimedB!.complete("Migration B done");
const claimedA2 = await board.as("ops-1").tasks.claim(taskA.identifier);
expect(claimedA2?.task.id).toBe(taskA.id);
// Cancel A -> status=cancelled
const cancelled = await board.tasks.cancel(taskA.identifier, {
claimToken: claimedA2!.claimToken,
reason: "Superseded",
});
expect(cancelled.status).toBe("cancelled");
// Reopen A -> status=todo
const reopened = await board.tasks.reopen(taskA.identifier, {
comment: "Actually still needed",
});
expect(reopened.status).toBe("todo");
// Adding a dependency with releaseLease: true on an UNCLAIMED todo task succeeds (no-op release)
const taskC = await board.tasks.create("ops/work", "Unclaimed waiting task");
const unclaimedDeps = await board.tasks.updateDependencies(taskC.identifier, {
add: [taskA.identifier],
releaseLease: true,
});
expect(unclaimedDeps.blockedBy.map((d) => d.id)).toContain(taskA.id);
});
it("supports channel update, private channel members, and managedPool auto-dispatch", async () => {
wakeupSpy.mockClear();
const board = makeBoardClient();
const agentA = makeAgentClient(agentAId);
const agentB = makeAgentClient(agentBId);
// Private channel membership
await board.channels.create("sec/private", { visibility: "private" });
await expect(agentA.read("sec/private")).rejects.toMatchObject({ status: 404 });
const added = await board.channels.members.add("sec/private", {
agent: "@backend-eng",
});
expect(added.subjectId).toBe(agentAId);
const members = await board.channels.members.list("sec/private");
expect(members.some((m) => m.subjectId === agentAId)).toBe(true);
// Now agentA can read, agentB still cannot
const page = await agentA.read("sec/private");
expect(page.kind).toBe("channel");
await expect(agentB.read("sec/private")).rejects.toMatchObject({ status: 404 });
const removed = await board.channels.members.remove("sec/private", {
agent: "@backend-eng",
});
expect(removed.removed).toBe(true);
await expect(agentA.read("sec/private")).rejects.toMatchObject({ status: 404 });
// Channel update + managedPool auto-dispatch (maxConcurrency = 1)
await board.channels.create("auto/drain", { description: "Initial" });
const t1 = await board.tasks.create("auto/drain", "Task 1");
const t2 = await board.tasks.create("auto/drain", "Task 2");
const updatedCh = await board.channels.update("auto/drain", {
description: "Auto-drained by backend-eng",
queueConfig: { ordering: "strict_fifo" },
managedPool: { agent: "@backend-eng", maxConcurrency: 1 },
});
expect(updatedCh.description).toBe("Auto-drained by backend-eng");
expect(updatedCh.queueConfig.ordering).toBe("strict_fifo");
expect(updatedCh.queueConfig.managedPool).toEqual({
agentId: agentAId,
maxConcurrency: 1,
});
// Exactly 1 of the 2 ready tasks should have been auto-assigned to backend-eng and woken!
const t1View = await board.read(t1.identifier);
const t2View = await board.read(t2.identifier);
const assignedCount = [t1View, t2View].filter(
(v) => v.kind === "thread" && v.issue.assigneeAgentId === agentAId,
).length;
expect(assignedCount).toBe(1);
expect(wakeupSpy).toHaveBeenCalledWith(
agentAId,
expect.objectContaining({ reason: "issue_assigned" }),
);
// Completing task 1 frees the managedPool slot and automatically dispatches task 2!
const firstAssigned =
t1View.kind === "thread" && t1View.issue.assigneeAgentId === agentAId ? t1 : t2;
const secondTask = firstAssigned.id === t1.id ? t2 : t1;
const claimedFirst = await agentA.tasks.claim(firstAssigned.identifier);
await claimedFirst!.complete("Done 1");
const secondAfterComplete = await board.read(secondTask.identifier);
expect(secondAfterComplete.kind).toBe("thread");
if (secondAfterComplete.kind === "thread") {
expect(secondAfterComplete.issue.assigneeAgentId).toBe(agentAId);
}
// Automatic managedPool assignments must be recorded in activityLog
const autoAssignActivity = await db
.select()
.from(activityLog)
.where(
and(
eq(activityLog.companyId, companyId),
eq(activityLog.entityId, firstAssigned.id),
eq(activityLog.action, "issue.assigned"),
),
);
expect(autoAssignActivity.length).toBeGreaterThanOrEqual(1);
expect(autoAssignActivity[0]?.actorType).toBe("system");
// ManagedPool cannot target a non-member agent on a private channel
await expect(
board.channels.update("sec/private", {
managedPool: { agent: "@qa-reviewer", maxConcurrency: 1 },
}),
).rejects.toMatchObject({ status: 403 });
// ManagedPool cannot target a protected agent with blockAssignment
const protectedAgentId = randomUUID();
await db.insert(agents).values({
id: protectedAgentId,
companyId,
name: "Protected Bot",
role: "engineer",
status: "idle",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {
authorizationPolicy: {
protectedAgent: { blockAssignment: true },
},
},
});
await expect(
board.channels.update("auto/drain", {
managedPool: { agent: protectedAgentId, maxConcurrency: 1 },
}),
).rejects.toMatchObject({ status: 403 });
});
it("enforces creator/admin auth on channel admin, blocks cross-channel private dependency leaks, and fences stale cancel tokens", async () => {
const board = makeBoardClient();
const agentA = makeAgentClient(agentAId);
const agentB = makeAgentClient(agentBId);
// 1. Non-creator member cannot update channel config or manage members
await board.channels.create("sec/locked", { visibility: "private" });
await board.channels.members.add("sec/locked", { agent: "@backend-eng" });
await expect(
agentA.channels.update("sec/locked", { description: "Hijacked" }),
).rejects.toMatchObject({ status: 403, code: "channel_manage_denied" });
await expect(
agentA.channels.members.add("sec/locked", { agent: "@qa-reviewer" }),
).rejects.toMatchObject({ status: 403, code: "channel_manage_denied" });
await expect(
agentA.channels.members.remove("sec/locked", { agent: "@backend-eng" }),
).rejects.toMatchObject({ status: 403, code: "channel_manage_denied" });
// 2. Agent without access to private channel cannot attach or view private issue via dependencies
const secretTask = await board.tasks.create("sec/locked", "Secret credential rotation");
const publicTask = await board.tasks.create("pub/work", "Public task");
await expect(
agentB.tasks.updateDependencies(publicTask.identifier, {
add: [secretTask.identifier],
}),
).rejects.toMatchObject({ status: 404 });
// Even if an admin links secretTask -> publicTask, agentB's dependencies list hides secretTask
await board.tasks.updateDependencies(publicTask.identifier, {
add: [secretTask.identifier],
});
const depsForB = await agentB.tasks.dependencies(publicTask.identifier);
expect(depsForB.blockedBy).toEqual([]);
// Valid public dependency can be added and read by an agent
const publicBlocker = await board.tasks.create("pub/work", "Public blocker");
const addedByAgent = await agentB.tasks.updateDependencies(publicTask.identifier, {
add: [publicBlocker.identifier],
});
expect(addedByAgent.blockedBy.map((d) => d.id)).toEqual([publicBlocker.id]);
const listedByAgent = await agentB.tasks.dependencies(publicTask.identifier);
expect(listedByAgent.blockedBy.map((d) => d.id)).toEqual([publicBlocker.id]);
// 3. Stale worker claim token cannot cancel an already-completed task
const raceTask = await board.tasks.create("pub/work", "Race cancel test");
const staleClaim = await board.as("stale-worker").tasks.claim(raceTask.identifier);
expect(staleClaim).not.toBeNull();
await staleClaim!.complete("Finished cleanly");
await expect(
board.tasks.cancel(raceTask.identifier, {
claimToken: staleClaim!.claimToken,
claimEpoch: staleClaim!.claimEpoch,
reason: "Delayed stale cancel",
}),
).rejects.toMatchObject({ status: 409, code: "claim_lost" });
});
});
+5
View File
@@ -136,6 +136,7 @@ import { headlessIdentityRoutes } from "./routes/headless-identity.js";
import { headlessChannelsSchemasRoutes } from "./routes/headless-channels-schemas.js";
import { headlessQueuesEventsRoutes } from "./routes/headless-queues-events.js";
import { createClaimLeaseExpiryWorker } from "./services/headless-task-queue.js";
import { createManagedChannelPoolWorker } from "./services/headless-channel-admin.js";
import { createScheduledBoardPostsWorker } from "./services/headless-events-schedules-interactions.js";
import { linkPreviewRoutes } from "./routes/link-previews.js";
import { issueTreeControlRoutes } from "./routes/issue-tree-control.js";
@@ -1430,6 +1431,10 @@ export async function createApp(
registerBrowserUseCleanup(deliveryWork, browserUse, () => !isIdleTaskDrainActive());
deliveryWork.register(DELIVERY_QUEUES.claimLeaseExpiry, createClaimLeaseExpiryWorker(db).deliveryTask);
deliveryWork.register(DELIVERY_QUEUES.scheduledBoardPosts, createScheduledBoardPostsWorker(db).deliveryTask);
deliveryWork.register(
DELIVERY_QUEUES.managedChannelPools,
createManagedChannelPoolWorker(db, heartbeatService(db)).deliveryTask,
);
void companyTransferRunService
+150 -1
View File
@@ -46,6 +46,15 @@ import {
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, unprocessable } from "../errors.js";
import { authorizationService } from "../services/authorization.js";
import { heartbeatService } from "../services/heartbeat.js";
import {
addChannelMember,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
listChannelMembers,
removeChannelMember,
updateChannel,
} from "../services/headless-channel-admin.js";
import {
logActivity,
publishActivity,
@@ -195,10 +204,14 @@ function isRestrictedBoardKeyRequest(req: Request): boolean {
export function headlessChannelsSchemasRoutes(
db: Db,
opts?: { deploymentMode?: DeploymentMode },
opts?: {
deploymentMode?: DeploymentMode;
heartbeat?: ReturnType<typeof heartbeatService>;
},
): Router {
const router = Router();
const deploymentMode = opts?.deploymentMode;
const heartbeat = opts?.heartbeat ?? heartbeatService(db);
router.get(
"/companies/:companyId/channels",
@@ -256,6 +269,96 @@ export function headlessChannelsSchemasRoutes(
},
);
router.patch(
"/companies/:companyId/channels",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const body = (req.body ?? {}) as Record<string, unknown>;
const channelRef =
typeof body.channel === "string" && body.channel.trim()
? body.channel.trim()
: typeof req.query.channel === "string" && req.query.channel.trim()
? req.query.channel.trim()
: "";
if (!channelRef) {
throw badRequest("Channel path or ID is required");
}
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "channels.manage",
requiredChannel: channelRef,
});
const updated = await updateChannel(db, companyId, channelRef, actor, body, {
heartbeat,
});
res.json(updated);
},
);
router.get(
"/companies/:companyId/channels/members",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const channelRef =
typeof req.query.channel === "string" ? req.query.channel.trim() : "";
if (!channelRef) {
throw badRequest("Query parameter 'channel' is required");
}
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "read",
requiredChannel: channelRef,
});
const items = await listChannelMembers(db, companyId, channelRef, actor);
res.json({ items });
},
);
router.post(
"/companies/:companyId/channels/members",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const body = (req.body ?? {}) as Record<string, unknown>;
const channelRef =
typeof body.channel === "string" ? body.channel.trim() : "";
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "channels.manage",
...(channelRef ? { requiredChannel: channelRef } : {}),
});
const member = await addChannelMember(db, companyId, actor, body);
res.status(201).json(member);
},
);
router.delete(
"/companies/:companyId/channels/members",
async (req: Request, res: Response) => {
const companyId = req.params.companyId as string;
const body = (req.body && typeof req.body === "object"
? { ...(req.body as Record<string, unknown>) }
: {}) as Record<string, unknown>;
if (!body.channel && typeof req.query.channel === "string") {
body.channel = req.query.channel;
}
if (!body.agent && typeof req.query.agent === "string") {
body.agent = req.query.agent;
}
if (!body.userId && typeof req.query.userId === "string") {
body.userId = req.query.userId;
}
const channelRef =
typeof body.channel === "string" ? body.channel.trim() : "";
const actor = await resolveHeadlessActor(db, req, companyId, {
deploymentMode,
requiredAction: "channels.manage",
...(channelRef ? { requiredChannel: channelRef } : {}),
});
const result = await removeChannelMember(db, companyId, actor, body);
res.json(result);
},
);
router.post(
"/companies/:companyId/channels/posts",
async (req: Request, res: Response) => {
@@ -269,6 +372,18 @@ export function headlessChannelsSchemasRoutes(
});
const result = await createChannelPost(db, companyId, actor, body);
if (
result.created &&
result.issue.status === "todo" &&
!result.issue.assigneeAgentId &&
!result.issue.assigneeUserId &&
result.issue.channelId
) {
await dispatchManagedChannelPoolBestEffort(db, companyId, result.issue.channelId, {
heartbeat,
actor,
});
}
res.status(result.created ? 201 : 200).json(result.issue);
},
);
@@ -391,6 +506,21 @@ export function headlessChannelsSchemasRoutes(
actor,
req.body ?? {},
);
if (!result.idempotentReplay) {
const channelIds = Array.from(
new Set(
result.tasks
.map((t) => t.issue.channelId)
.filter((id): id is string => Boolean(id)),
),
);
for (const chId of channelIds) {
await dispatchManagedChannelPoolBestEffort(db, companyId, chId, {
heartbeat,
actor,
});
}
}
res.status(result.idempotentReplay ? 200 : 201).json(result);
},
);
@@ -1083,6 +1213,25 @@ export function headlessChannelsSchemasRoutes(
for (const evt of committedEvents) {
publishCommittedBoardEvent(evt);
}
if (nextStatus === "done") {
await dispatchManagedChannelPoolsForCompletedIssueBestEffort(
db,
targetIssue.companyId,
updatedView.id,
updatedView.channelId,
{ heartbeat, actor },
);
} else if (
updatedView.channelId &&
(nextStatus === "todo" || nextStatus === "cancelled" || nextStatus === "blocked")
) {
await dispatchManagedChannelPoolBestEffort(
db,
targetIssue.companyId,
updatedView.channelId,
{ heartbeat, actor },
);
}
res.json(updatedView);
},
+175 -1
View File
@@ -6,7 +6,8 @@ import {
type BoardEventView,
type DeploymentMode,
} from "@paperclipai/shared";
import { badRequest, notFound, unauthorized } from "../errors.js";
import { badRequest, forbidden, notFound, unauthorized } from "../errors.js";
import { authorizationDeniedDetails, authorizationService } from "../services/authorization.js";
import { heartbeatService } from "../services/heartbeat.js";
import {
assertCanonicalIssueAccess,
@@ -24,6 +25,20 @@ import {
releaseTaskClaim,
renewTaskClaim,
} from "../services/headless-task-queue.js";
import {
assignTask,
cancelTask,
handoffTask,
reopenTask,
} from "../services/headless-task-workflows.js";
import {
listTaskDependencies,
mutateTaskDependencies,
} from "../services/headless-task-dependencies.js";
import {
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
} from "../services/headless-channel-admin.js";
import {
approveOnIssue,
cancelSchedule,
@@ -175,6 +190,41 @@ export function headlessQueuesEventsRoutes(
const deploymentMode = opts?.deploymentMode;
const heartbeat = opts?.heartbeat ?? heartbeatService(db);
async function assertCanAssignTask(
txOrDb: Db | Parameters<Parameters<Db["transaction"]>[0]>[0],
req: Request,
issue: Awaited<ReturnType<typeof resolveIssueByIdOrIdentifier>>,
targetAssigneeAgentId?: string | null,
) {
const effectiveAssigneeAgentId =
targetAssigneeAgentId !== undefined ? targetAssigneeAgentId : issue.assigneeAgentId;
const effectiveAssigneeUserId =
targetAssigneeAgentId !== undefined ? null : issue.assigneeUserId;
const decision = await authorizationService(txOrDb as unknown as Db).decide({
actor: req.actor,
action: "tasks:assign",
resource: {
type: "issue",
companyId: issue.companyId,
issueId: issue.id,
projectId: issue.projectId,
parentIssueId: issue.parentId,
assigneeAgentId: effectiveAssigneeAgentId,
assigneeUserId: effectiveAssigneeUserId,
},
scope: {
issueId: issue.id,
projectId: issue.projectId,
parentIssueId: issue.parentId,
assigneeAgentId: effectiveAssigneeAgentId,
assigneeUserId: effectiveAssigneeUserId,
},
});
if (!decision.allowed) {
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
}
}
const buildWakeHandler = () => async (wake: {
companyId: string;
issueId: string;
@@ -278,6 +328,12 @@ export function headlessQueuesEventsRoutes(
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
if (issue.channelId) {
await dispatchManagedChannelPoolBestEffort(db, issue.companyId, issue.channelId, {
heartbeat,
actor,
});
}
res.json(result);
});
@@ -296,6 +352,13 @@ export function headlessQueuesEventsRoutes(
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
await dispatchManagedChannelPoolsForCompletedIssueBestEffort(
db,
issue.companyId,
result.id,
result.channelId,
{ heartbeat, actor },
);
res.json(result);
});
@@ -317,6 +380,117 @@ export function headlessQueuesEventsRoutes(
res.json(result);
});
router.post("/issues/:id/assign", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.assign",
);
const result = await assignTask(db, issue.id, actor, req.body, {
heartbeat,
authorizeTargetAssignee: (tx, targetAgentId) =>
assertCanAssignTask(tx, req, issue, targetAgentId),
});
res.json(result);
});
router.post("/issues/:id/handoff", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.handoff",
);
const result = await handoffTask(
db,
issue.id,
actor,
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
{
heartbeat,
authorizeTargetAssignee: (tx, targetAgentId) =>
assertCanAssignTask(tx, req, issue, targetAgentId),
},
);
res.json(result);
});
router.post("/issues/:id/cancel", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.cancel",
);
const result = await cancelTask(
db,
issue.id,
actor,
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
if (result.channelId) {
await dispatchManagedChannelPoolBestEffort(db, issue.companyId, result.channelId, {
heartbeat,
actor,
});
}
res.json(result);
});
router.post("/issues/:id/reopen", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.reopen",
);
if (issue.status === "done" || issue.status === "cancelled") {
await assertCanAssignTask(db, req, issue);
}
const result = await reopenTask(db, issue.id, actor, req.body, {
heartbeat,
});
res.json(result);
});
router.get("/issues/:id/dependencies", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"read",
"issue:read",
);
const result = await listTaskDependencies(db, issue.id, actor);
res.json(result);
});
router.post("/issues/:id/dependencies", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
req,
req.params.id as string,
deploymentMode,
"tasks.dependencies",
);
const result = await mutateTaskDependencies(
db,
issue.id,
actor,
req.body,
req.header("x-paperclip-claim-token") ?? undefined,
);
res.json(result);
});
router.post("/issues/:id/ask", async (req, res) => {
const { issue, actor } = await resolveIssueAndActor(
db,
+60
View File
@@ -14732,6 +14732,66 @@ for (const route of [
agentIdentityPolicy: agentIdentityPolicySchema,
}),
},
{
method: "patch",
path: "/api/companies/{companyId}/channels",
summary: "Update channel settings, archive state, queueConfig, or managedPool",
status: 200,
},
{
method: "get",
path: "/api/companies/{companyId}/channels/members",
summary: "List explicit access members on a channel",
status: 200,
},
{
method: "post",
path: "/api/companies/{companyId}/channels/members",
summary: "Grant an agent or user access to a private channel",
status: 201,
},
{
method: "delete",
path: "/api/companies/{companyId}/channels/members",
summary: "Revoke an agent or user's access to a private channel",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/assign",
summary: "Push-assign an existing task or post to a registered agent or unassign it",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/handoff",
summary: "Atomically move channel, update labels/assignee/status, and release an active lease",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/cancel",
summary: "Cancel a task and release any active lease",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/reopen",
summary: "Reopen a completed, cancelled, or blocked task back to todo or backlog",
status: 200,
},
{
method: "get",
path: "/api/issues/{id}/dependencies",
summary: "List visible blockers and dependents for a task",
status: 200,
},
{
method: "post",
path: "/api/issues/{id}/dependencies",
summary: "Add or remove task dependencies with cycle checks and optional lease release",
status: 200,
},
] as const) {
registerCurrentRoute({
method: route.method,
+5
View File
@@ -72,6 +72,11 @@ export function createAgentLifecycleEffects(_hooks: BudgetServiceHooks = {}): li
await notifyChatInboundWakeNotices(tx, { companyId });
await notifyBudgetResumeAgentReady(tx, agentId);
await readmitAgentContinuations(tx, { companyId, agentId });
await notifyDeliveryWork(
tx,
DELIVERY_QUEUES.managedChannelPools,
JSON.stringify({ companyId, agentId }),
);
}
},
reportFailure(context, error) {
+1 -1
View File
@@ -364,7 +364,7 @@ type IssueAuthorizationRow = {
originId: string | null;
};
function evaluateAuthorizationPolicyForAssignment(
export function evaluateAuthorizationPolicyForAssignment(
policy: Record<string, unknown> | null | undefined,
label: string,
): AssignmentPolicyEffect {
@@ -167,6 +167,7 @@ export const DELIVERY_QUEUES = {
nativeCheckpointExpiration: "native-checkpoint-expiration",
claimLeaseExpiry: "claim-lease-expiry",
scheduledBoardPosts: "scheduled-board-posts",
managedChannelPools: "managed-channel-pools",
} as const;
export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES];
@@ -0,0 +1,586 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channelAccessMembers,
channels,
companyMemberships,
} from "@paperclipai/db";
import {
channelMemberInputSchema,
channelQueueConfigSchema,
isUuidLike,
updateChannelInputSchema,
type ChannelMemberView,
type ChannelQueueConfig,
type ChannelView,
} from "@paperclipai/shared";
import { badRequest, forbidden, notFound } from "../errors.js";
import { logger } from "../middleware/logger.js";
import {
logActivity,
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import type { heartbeatService } from "./heartbeat.js";
import {
buildChannelViews,
normalizeChannelPathOrThrow,
resolveAssigneeAgent,
} from "./headless-channels.js";
import {
assertChannelAccess,
enforceHeadlessScopes,
resolveProjectReference,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import {
assertCanConfigureManagedPool,
dispatchManagedChannelPool,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssue,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
} from "./headless-managed-pool.js";
import {
createManagedChannelPoolWorker,
recoverManagedChannelPools,
} from "./headless-managed-pool-worker.js";
export {
assertCanConfigureManagedPool,
createManagedChannelPoolWorker,
dispatchManagedChannelPool,
dispatchManagedChannelPoolBestEffort,
dispatchManagedChannelPoolsForCompletedIssue,
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
recoverManagedChannelPools,
};
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 ?? "local-board",
agentId: actor.agentId ?? null,
responsibleUserIdOverride: actor.responsibleUserId ?? null,
};
}
export async function resolveChannelByIdOrPath(
dbOrTx: DbOrTx,
companyId: string,
channelRef: string,
): Promise<typeof channels.$inferSelect> {
const trimmed = channelRef.trim();
if (!trimmed) {
throw badRequest("Channel path or ID is required");
}
if (isUuidLike(trimmed)) {
const [byId] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.id, trimmed)))
.limit(1);
if (byId) return byId;
}
const normalized = normalizeChannelPathOrThrow(trimmed, {
allowSubtreePrefix: false,
});
const [byPath] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (!byPath) {
throw notFound(`Channel '${normalized.path}' not found`, {
error: "channel_not_found",
code: "channel_not_found",
});
}
return byPath;
}
async function assertCanManageChannel(
dbOrTx: DbOrTx,
companyId: string,
channel: typeof channels.$inferSelect,
actor: HeadlessActorContext,
): Promise<void> {
enforceHeadlessScopes(actor, {
action: "channels.manage",
channelPath: channel.path,
});
await assertChannelAccess(dbOrTx, channel, actor);
const isOwnerOrCreator =
actor.isInstanceAdmin ||
actor.principalType === "local_trusted" ||
(Boolean(actor.userId) && channel.createdByUserId === actor.userId) ||
(Boolean(actor.agentId) && channel.createdByAgentId === actor.agentId);
let canManage = isOwnerOrCreator;
if (!canManage && actor.userId && actor.principalType === "user") {
const [membership] = await dbOrTx
.select({ role: companyMemberships.membershipRole })
.from(companyMemberships)
.where(
and(
eq(companyMemberships.companyId, companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, actor.userId),
eq(companyMemberships.status, "active"),
inArray(companyMemberships.membershipRole, ["owner", "admin"]),
),
)
.limit(1);
canManage = Boolean(membership);
}
if (!canManage) {
throw forbidden(
"Only the channel creator or a company admin can update channel settings or membership",
{ code: "channel_manage_denied" },
);
}
}
export async function updateChannel(
db: Db,
companyId: string,
channelRef: string,
actor: HeadlessActorContext,
rawInput: unknown,
opts?: { heartbeat?: ReturnType<typeof heartbeatService> },
): Promise<ChannelView> {
const parsed = updateChannelInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: parsed.error.issues,
},
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const committed = await db.transaction(async (tx) => {
const resolved = await resolveChannelByIdOrPath(tx, companyId, channelRef);
await tx.execute(
sql`SELECT id FROM channels WHERE id = ${resolved.id} AND company_id = ${companyId} FOR UPDATE`,
);
const [existing] = await tx
.select()
.from(channels)
.where(and(eq(channels.id, resolved.id), eq(channels.companyId, companyId)))
.limit(1);
if (!existing) {
throw notFound(`Channel '${channelRef}' not found`);
}
await assertCanManageChannel(tx, companyId, existing, actor);
const updates: Partial<typeof channels.$inferInsert> = {};
if (input.description !== undefined) {
updates.description = input.description;
}
if (input.defaultProjectId !== undefined) {
updates.defaultProjectId =
input.defaultProjectId === null
? null
: await resolveProjectReference(tx, companyId, input.defaultProjectId, actor);
}
if (input.queueConfig !== undefined || input.managedPool !== undefined) {
let nextQueueConfig: ChannelQueueConfig =
input.queueConfig === null
? {}
: input.queueConfig !== undefined
? { ...(existing.queueConfig ?? {}), ...input.queueConfig }
: { ...(existing.queueConfig ?? {}) };
if (input.managedPool !== undefined) {
if (input.managedPool === null) {
const { managedPool: _removed, ...rest } = nextQueueConfig;
nextQueueConfig = rest;
} else {
const resolvedAgentId = await resolveAssigneeAgent(tx, companyId, {
for: input.managedPool.agent,
});
if (!resolvedAgentId) {
throw notFound(`Agent '${input.managedPool.agent}' not found`);
}
nextQueueConfig = {
...nextQueueConfig,
managedPool: {
agentId: resolvedAgentId,
maxConcurrency: input.managedPool.maxConcurrency,
},
};
}
}
const validatedQc = channelQueueConfigSchema.safeParse(nextQueueConfig);
if (!validatedQc.success) {
throw badRequest(
validatedQc.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
{
error: "validation_error",
code: "validation_error",
issues: validatedQc.error.issues,
},
);
}
if (validatedQc.data.managedPool) {
const effectiveDefaultProjectId =
updates.defaultProjectId !== undefined
? updates.defaultProjectId
: existing.defaultProjectId;
await assertCanConfigureManagedPool(
tx,
companyId,
{
id: existing.id,
visibility: existing.visibility,
createdByAgentId: existing.createdByAgentId,
defaultProjectId: effectiveDefaultProjectId,
},
validatedQc.data.managedPool.agentId,
actor,
);
}
updates.queueConfig = validatedQc.data;
}
const now = new Date();
if (input.archived !== undefined) {
updates.archivedAt = input.archived ? (existing.archivedAt ?? now) : null;
}
updates.updatedAt = now;
const effectiveQueueConfig =
(updates.queueConfig as ChannelQueueConfig | undefined) ?? existing.queueConfig;
const effectiveArchivedAt =
updates.archivedAt !== undefined ? updates.archivedAt : existing.archivedAt;
if (effectiveQueueConfig?.managedPool && !effectiveArchivedAt) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, existing.id);
}
const [updated] = await tx
.update(channels)
.set(updates)
.where(eq(channels.id, existing.id))
.returning();
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.updated",
entityType: "channel",
entityId: updated!.id,
details: {
path: updated!.path,
archived: Boolean(updated!.archivedAt),
hasManagedPool: Boolean(updated!.queueConfig?.managedPool),
},
},
publications,
);
const views = await buildChannelViews(tx, companyId, [updated!]);
return { view: views[0]!, channel: updated! };
});
for (const pub of publications) {
publishActivity(pub);
}
if (
committed.channel.queueConfig?.managedPool &&
!committed.channel.archivedAt &&
opts?.heartbeat
) {
await dispatchManagedChannelPool(db, companyId, committed.channel.id, {
heartbeat: opts.heartbeat,
actor,
}).catch((err) => {
logger.warn(
{ err, companyId, channelId: committed.channel.id },
"managed channel pool dispatch after channel update failed; background worker will retry",
);
});
}
return committed.view;
}
export async function listChannelMembers(
db: Db,
companyId: string,
channelRef: string,
actor: HeadlessActorContext,
): Promise<ChannelMemberView[]> {
const ch = await resolveChannelByIdOrPath(db, companyId, channelRef);
enforceHeadlessScopes(actor, {
action: "read",
channelPath: ch.path,
});
await assertChannelAccess(db, ch, actor);
const rows = await db
.select()
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, ch.id),
),
);
const agentIds = rows
.filter((r) => r.subjectType === "agent")
.map((r) => r.subjectId);
const agentNameMap = new Map<string, string>();
if (agentIds.length > 0) {
const agentRows = await db
.select({ id: agents.id, name: agents.name })
.from(agents)
.where(and(eq(agents.companyId, companyId), inArray(agents.id, agentIds)));
for (const a of agentRows) {
agentNameMap.set(a.id, a.name);
}
}
return rows.map((r) => ({
id: r.id,
channelId: r.channelId,
subjectType: r.subjectType === "agent" ? "agent" : "user",
subjectId: r.subjectId,
displayName:
r.subjectType === "agent" ? (agentNameMap.get(r.subjectId) ?? null) : null,
createdAt: r.createdAt.toISOString(),
}));
}
async function resolveChannelMemberTarget(
dbOrTx: DbOrTx,
companyId: string,
input: {
agent?: string;
userId?: string;
subjectType?: "user" | "agent";
subjectId?: string;
},
): Promise<{ subjectType: "user" | "agent"; subjectId: string; displayName: string | null }> {
if (input.agent) {
const agentId = await resolveAssigneeAgent(dbOrTx, companyId, {
for: input.agent,
});
if (!agentId) {
throw notFound(`Agent '${input.agent}' not found`);
}
const [agentRow] = await dbOrTx
.select({ name: agents.name })
.from(agents)
.where(eq(agents.id, agentId))
.limit(1);
return {
subjectType: "agent",
subjectId: agentId,
displayName: agentRow?.name ?? null,
};
}
if (input.userId) {
return { subjectType: "user", subjectId: input.userId.trim(), displayName: null };
}
if (input.subjectType && input.subjectId) {
if (input.subjectType === "agent") {
const agentId = await resolveAssigneeAgent(dbOrTx, companyId, {
for: input.subjectId,
});
if (!agentId) {
throw notFound(`Agent '${input.subjectId}' not found`);
}
const [agentRow] = await dbOrTx
.select({ name: agents.name })
.from(agents)
.where(eq(agents.id, agentId))
.limit(1);
return {
subjectType: "agent",
subjectId: agentId,
displayName: agentRow?.name ?? null,
};
}
return {
subjectType: "user",
subjectId: input.subjectId.trim(),
displayName: null,
};
}
throw badRequest("Provide 'agent', 'userId', or both 'subjectType' and 'subjectId'");
}
export async function addChannelMember(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawInput: unknown,
): Promise<ChannelMemberView> {
const parsed = channelMemberInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const view = await db.transaction(async (tx) => {
const ch = await resolveChannelByIdOrPath(tx, companyId, input.channel);
await assertCanManageChannel(tx, companyId, ch, actor);
const target = await resolveChannelMemberTarget(tx, companyId, input);
const [inserted] = await tx
.insert(channelAccessMembers)
.values({
companyId,
channelId: ch.id,
subjectType: target.subjectType,
subjectId: target.subjectId,
})
.onConflictDoNothing({
target: [
channelAccessMembers.channelId,
channelAccessMembers.subjectType,
channelAccessMembers.subjectId,
],
})
.returning();
const row =
inserted ??
(
await tx
.select()
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, target.subjectType),
eq(channelAccessMembers.subjectId, target.subjectId),
),
)
.limit(1)
)[0]!;
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.member_added",
entityType: "channel",
entityId: ch.id,
details: {
path: ch.path,
subjectType: target.subjectType,
subjectId: target.subjectId,
},
},
publications,
);
return {
id: row.id,
channelId: row.channelId,
subjectType: row.subjectType === "agent" ? ("agent" as const) : ("user" as const),
subjectId: row.subjectId,
displayName: target.displayName,
createdAt: row.createdAt.toISOString(),
};
});
for (const pub of publications) {
publishActivity(pub);
}
return view;
}
export async function removeChannelMember(
db: Db,
companyId: string,
actor: HeadlessActorContext,
rawInput: unknown,
): Promise<{ removed: boolean }> {
const parsed = channelMemberInputSchema.safeParse(rawInput ?? {});
if (!parsed.success) {
throw badRequest(
parsed.error.issues
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
.join("; "),
);
}
const input = parsed.data;
const publications: ActivityPublication[] = [];
const removed = await db.transaction(async (tx) => {
const ch = await resolveChannelByIdOrPath(tx, companyId, input.channel);
await assertCanManageChannel(tx, companyId, ch, actor);
const target = await resolveChannelMemberTarget(tx, companyId, input);
const deleted = await tx
.delete(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, target.subjectType),
eq(channelAccessMembers.subjectId, target.subjectId),
),
)
.returning({ id: channelAccessMembers.id });
if (deleted.length > 0) {
await logActivity(
tx as unknown as Db,
{
companyId,
...activityActorFields(actor),
action: "channel.member_removed",
entityType: "channel",
entityId: ch.id,
details: {
path: ch.path,
subjectType: target.subjectType,
subjectId: target.subjectId,
},
},
publications,
);
}
return deleted.length > 0;
});
for (const pub of publications) {
publishActivity(pub);
}
return { removed };
}
+64 -21
View File
@@ -62,6 +62,7 @@ import {
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import { assertCanConfigureManagedPool } from "./headless-managed-pool.js";
import {
appendBoardEvent,
assertChannelAccess,
@@ -426,27 +427,51 @@ export async function ensureChannel(
visibility = "private";
}
const now = new Date();
const [inserted] = await dbOrTx
.insert(channels)
.values({
companyId,
path: normalized.path,
description: input.description ?? null,
visibility: visibility ?? "open",
defaultProjectId: resolvedDefaultProjectId ?? null,
queueConfig: validatedQueueConfig ?? {},
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
lastActivityAt: now,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing({
target: [channels.companyId, channels.path],
})
.returning();
const [preExisting] = await dbOrTx
.select({ id: channels.id })
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
let inserted: typeof channels.$inferSelect | undefined;
if (!preExisting) {
if (validatedQueueConfig?.managedPool) {
await assertCanConfigureManagedPool(
dbOrTx,
companyId,
{
visibility: visibility ?? "open",
createdByAgentId: actor.agentId,
defaultProjectId: resolvedDefaultProjectId ?? null,
},
validatedQueueConfig.managedPool.agentId,
actor,
);
}
const now = new Date();
const [createdRow] = await dbOrTx
.insert(channels)
.values({
companyId,
path: normalized.path,
description: input.description ?? null,
visibility: visibility ?? "open",
defaultProjectId: resolvedDefaultProjectId ?? null,
queueConfig: validatedQueueConfig ?? {},
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
lastActivityAt: now,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing({
target: [channels.companyId, channels.path],
})
.returning();
inserted = createdRow;
}
if (inserted) {
if (inserted.visibility === "private") {
@@ -547,6 +572,24 @@ export async function ensureChannel(
throw forbidden("Only the channel creator or a company admin can update channel settings");
}
if (updates.queueConfig?.managedPool) {
await assertCanConfigureManagedPool(
dbOrTx,
companyId,
{
id: existing.id,
visibility: updates.visibility ?? existing.visibility,
createdByAgentId: existing.createdByAgentId,
defaultProjectId:
updates.defaultProjectId !== undefined
? updates.defaultProjectId
: existing.defaultProjectId,
},
updates.queueConfig.managedPool.agentId,
actor,
);
}
updates.updatedAt = new Date();
const privatizingTree =
updates.visibility === "private" && existing.visibility !== "private";
@@ -0,0 +1,456 @@
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;
},
},
};
}
@@ -0,0 +1,715 @@
import { and, eq, isNull, ne, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
channelAccessMembers,
channels,
issueRelations,
issues,
projects,
} from "@paperclipai/db";
import { type ChannelQueueConfig } from "@paperclipai/shared";
import { forbidden, notFound } from "../errors.js";
import { logger } from "../middleware/logger.js";
import {
logActivity,
publishActivity,
type ActivityPublication,
} from "./activity-log.js";
import {
authorizationService,
evaluateAuthorizationPolicyForAssignment,
type AuthorizationActor,
} from "./authorization.js";
import type { heartbeatService } from "./heartbeat.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import {
appendBoardEvent,
publishCommittedBoardEvent,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
function toAuthorizationActor(actor: HeadlessActorContext): AuthorizationActor {
if (actor.principalType === "agent" && actor.agentId) {
return {
type: "agent",
agentId: actor.agentId,
companyId: actor.companyId,
};
}
if (actor.principalType === "local_trusted") {
return {
type: "board",
userId: actor.userId ?? "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
return {
type: "board",
userId: actor.userId ?? "unknown-user",
source: "session",
isInstanceAdmin: actor.isInstanceAdmin,
};
}
function readAgentAuthorizationPolicy(
permissions: unknown,
): Record<string, unknown> | null {
if (!permissions || typeof permissions !== "object" || Array.isArray(permissions)) {
return null;
}
const policy = (permissions as Record<string, unknown>).authorizationPolicy;
if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
return null;
}
return policy as Record<string, unknown>;
}
export async function isAgentEligibleForChannelPool(
dbOrTx: DbOrTx,
ch: typeof channels.$inferSelect,
agentRow: { id: string; role: string | null; permissions: unknown },
): Promise<boolean> {
const policyEffect = evaluateAuthorizationPolicyForAssignment(
readAgentAuthorizationPolicy(agentRow.permissions),
"Managed pool agent",
);
if (policyEffect.kind !== "none") {
return false;
}
const qc = ch.queueConfig as ChannelQueueConfig | null | undefined;
if (qc?.allowedAgentIds && qc.allowedAgentIds.length > 0) {
if (!qc.allowedAgentIds.includes(agentRow.id)) {
return false;
}
}
if (qc?.allowedRoles && qc.allowedRoles.length > 0) {
if (!agentRow.role || !qc.allowedRoles.includes(agentRow.role)) {
return false;
}
}
if (ch.visibility === "private" && ch.createdByAgentId !== agentRow.id) {
const [member] = await dbOrTx
.select({ id: channelAccessMembers.id })
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, ch.companyId),
eq(channelAccessMembers.channelId, ch.id),
eq(channelAccessMembers.subjectType, "agent"),
eq(channelAccessMembers.subjectId, agentRow.id),
),
)
.limit(1);
if (!member) {
return false;
}
}
return true;
}
function readNestedAuthorizationPolicy(
container: unknown,
): Record<string, unknown> | null {
if (!container || typeof container !== "object" || Array.isArray(container)) {
return null;
}
const policy = (container as Record<string, unknown>).authorizationPolicy;
if (!policy || typeof policy !== "object" || Array.isArray(policy)) {
return null;
}
return policy as Record<string, unknown>;
}
function channelPolicyActor(
ch: Pick<typeof channels.$inferSelect, "companyId" | "createdByAgentId" | "createdByUserId">,
): AuthorizationActor {
if (ch.createdByAgentId) {
return {
type: "agent",
agentId: ch.createdByAgentId,
companyId: ch.companyId,
};
}
if (ch.createdByUserId && ch.createdByUserId !== "local-board") {
return {
type: "board",
userId: ch.createdByUserId,
source: "session",
isInstanceAdmin: false,
};
}
return {
type: "board",
userId: "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
export async function isCandidateEligibleForPoolDispatch(
dbOrTx: DbOrTx,
ch: Pick<typeof channels.$inferSelect, "companyId" | "createdByAgentId" | "createdByUserId">,
poolAgentId: string,
candidate: {
id: string;
projectId: string | null;
parentId: string | null;
executionPolicy: unknown;
},
treeControl: ReturnType<typeof issueTreeControlService>,
): Promise<boolean> {
const companyId = ch.companyId;
const pauseHold = await treeControl.getActivePauseHoldGate(companyId, candidate.id);
if (pauseHold) {
return false;
}
// Enforce issue, parent, and project assignment policies before auto-dispatch
if (
evaluateAuthorizationPolicyForAssignment(
readNestedAuthorizationPolicy(candidate.executionPolicy),
"Target issue",
).kind !== "none"
) {
return false;
}
if (candidate.projectId) {
const [proj] = await dbOrTx
.select({
pausedAt: projects.pausedAt,
executionWorkspacePolicy: projects.executionWorkspacePolicy,
})
.from(projects)
.where(and(eq(projects.id, candidate.projectId), eq(projects.companyId, companyId)))
.limit(1);
if (proj?.pausedAt) {
return false;
}
if (
evaluateAuthorizationPolicyForAssignment(
readNestedAuthorizationPolicy(proj?.executionWorkspacePolicy),
"Target project",
).kind !== "none"
) {
return false;
}
}
if (candidate.parentId && candidate.parentId !== candidate.id) {
const [parent] = await dbOrTx
.select({ executionPolicy: issues.executionPolicy })
.from(issues)
.where(and(eq(issues.id, candidate.parentId), eq(issues.companyId, companyId)))
.limit(1);
if (
evaluateAuthorizationPolicyForAssignment(
readNestedAuthorizationPolicy(parent?.executionPolicy),
"Parent issue",
).kind !== "none"
) {
return false;
}
}
const authz = authorizationService(dbOrTx as unknown as Db);
const policyActor = channelPolicyActor(ch);
const candidateResource = {
type: "issue" as const,
companyId,
issueId: candidate.id,
projectId: candidate.projectId,
parentIssueId: candidate.parentId,
assigneeAgentId: poolAgentId,
assigneeUserId: null,
};
// Enforce canonical issue:read privacy gates for both the channel owner and the pool agent
const [ownerRead, agentRead, assignDecision] = await Promise.all([
authz.decide({
action: "issue:read",
actor: policyActor,
resource: candidateResource,
scope: { companyId },
}),
authz.decide({
action: "issue:read",
actor: {
type: "agent",
agentId: poolAgentId,
companyId,
},
resource: candidateResource,
scope: { companyId },
}),
authz.decide({
action: "tasks:assign",
actor: policyActor,
resource: candidateResource,
scope: { companyId },
}),
]);
return ownerRead.allowed && agentRead.allowed && assignDecision.allowed;
}
/**
* Validates that the caller is authorized to bind `agentId` as a channel's managedPool
* worker, honoring canonical `tasks:assign` policy, protected/private agent restrictions,
* and private channel membership.
*/
export async function assertCanConfigureManagedPool(
tx: DbOrTx,
companyId: string,
channel: {
id?: string;
visibility?: string | null;
createdByAgentId?: string | null;
defaultProjectId?: string | null;
},
agentId: string,
actor: HeadlessActorContext,
): Promise<void> {
const [agentRow] = await tx
.select({
id: agents.id,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, agentId),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
),
)
.limit(1);
if (!agentRow) {
throw notFound(`Agent '${agentId}' not found`);
}
const policyEffect = evaluateAuthorizationPolicyForAssignment(
readAgentAuthorizationPolicy(agentRow.permissions),
"Managed pool agent",
);
if (policyEffect.kind !== "none") {
throw forbidden(
policyEffect.explanation ??
"Protected or restricted agents cannot be configured as a managed channel pool",
);
}
const decision = await authorizationService(tx as unknown as Db).decide({
action: "tasks:assign",
actor: toAuthorizationActor(actor),
resource: {
type: "issue",
companyId,
issueId: null,
projectId: channel.defaultProjectId ?? null,
parentIssueId: null,
assigneeAgentId: agentId,
assigneeUserId: null,
},
scope: { companyId },
});
if (!decision.allowed) {
throw forbidden(
decision.explanation ?? "Not authorized to assign work to this managed pool agent",
);
}
if (channel.visibility === "private" && channel.createdByAgentId !== agentId) {
if (!channel.id) {
throw forbidden("Managed pool agent must be a member of this private channel");
}
const [member] = await tx
.select({ id: channelAccessMembers.id })
.from(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.companyId, companyId),
eq(channelAccessMembers.channelId, channel.id),
eq(channelAccessMembers.subjectType, "agent"),
eq(channelAccessMembers.subjectId, agentId),
),
)
.limit(1);
if (!member) {
throw forbidden("Managed pool agent must be a member of this private channel");
}
}
}
/**
* When a channel has `queueConfig.managedPool = { agentId, maxConcurrency }`,
* auto-assigns ready unassigned `todo` tasks up to `maxConcurrency` active tasks
* for that agent in the channel and triggers `heartbeat.wakeup`.
*
* Uses `FOR UPDATE` on the channel row to serialize concurrent dispatchers and
* `FOR UPDATE OF i SKIP LOCKED` on candidate rows to prevent double-dispatch.
* Records both `activityLog` (`issue.assigned`) and `boardEvents` (`task.assigned`)
* in the same transaction.
*/
export async function dispatchManagedChannelPool(
db: Db,
companyId: string,
channelId: string,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<{ dispatchedIssueIds: string[] }> {
const publications: ActivityPublication[] = [];
const assignedInTx = await db.transaction(async (tx) => {
// Serialize concurrent dispatchers for this channel so activeCount + slots cannot race
await tx.execute(
sql`SELECT id FROM channels WHERE id = ${channelId} AND company_id = ${companyId} FOR UPDATE`,
);
const [ch] = await tx
.select()
.from(channels)
.where(
and(
eq(channels.id, channelId),
eq(channels.companyId, companyId),
isNull(channels.archivedAt),
),
)
.limit(1);
const pool = ch?.queueConfig?.managedPool;
if (!ch || !pool) {
return {
items: [] as Array<{ id: string; identifier: string }>,
events: [],
channel: null as typeof channels.$inferSelect | null,
poolAgentId: null as string | null,
};
}
const [agentRow] = await tx
.select({
id: agents.id,
name: agents.name,
role: agents.role,
status: agents.status,
permissions: agents.permissions,
})
.from(agents)
.where(
and(
eq(agents.id, pool.agentId),
eq(agents.companyId, companyId),
ne(agents.status, "terminated"),
ne(agents.status, "paused"),
),
)
.limit(1);
if (!agentRow || !(await isAgentEligibleForChannelPool(tx, ch, agentRow))) {
return {
items: [] as Array<{ id: string; identifier: string }>,
events: [],
channel: null as typeof channels.$inferSelect | null,
poolAgentId: null as string | null,
};
}
// Count active tasks already assigned to this managed pool agent in this channel
const activeRows = await tx.execute<{ cnt: number }>(sql`
SELECT count(*)::int AS cnt
FROM issues i
WHERE i.company_id = ${companyId}
AND i.channel_id = ${channelId}
AND i.assignee_agent_id = ${pool.agentId}
AND i.status IN ('todo', 'in_progress')
AND i.hidden_at IS NULL
`);
const activeCount = Number(activeRows[0]?.cnt ?? 0);
const slots = Math.max(0, pool.maxConcurrency - activeCount);
if (slots === 0) {
return {
items: [] as Array<{ id: string; identifier: string }>,
events: [],
channel: ch,
poolAgentId: pool.agentId,
};
}
const strictFifo = ch.queueConfig?.ordering === "strict_fifo";
const orderClause = strictFifo
? sql`i.created_at ASC`
: sql`CASE i.priority
WHEN 'critical' THEN 0
WHEN 'high' THEN 1
WHEN 'medium' THEN 2
WHEN 'low' THEN 3
ELSE 4
END ASC, i.created_at ASC`;
const now = new Date();
const items: Array<{ id: string; identifier: string }> = [];
const events = [];
const treeControl = issueTreeControlService(tx as unknown as Db);
const BATCH_SIZE = Math.max(slots * 4, 25);
const seenIds: string[] = [];
while (items.length < slots) {
const seenExclusion =
seenIds.length > 0
? sql`AND i.id NOT IN (${sql.join(
seenIds.map((id) => sql`${id}::uuid`),
sql`, `,
)})`
: sql``;
const candidates = await tx.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 = ${companyId}
AND i.channel_id = ${channelId}
AND i.status = 'todo'
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.hidden_at 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'
)
ORDER BY ${orderClause}
LIMIT ${BATCH_SIZE}
FOR UPDATE OF i SKIP LOCKED
`);
if (candidates.length === 0) {
break;
}
for (const row of candidates) {
if (items.length >= slots) break;
seenIds.push(row.id);
const eligible = await isCandidateEligibleForPoolDispatch(
tx,
ch,
pool.agentId,
{
id: row.id,
projectId: row.project_id,
parentId: row.parent_id,
executionPolicy: row.execution_policy,
},
treeControl,
);
if (!eligible) {
continue;
}
const [updated] = await tx
.update(issues)
.set({
assigneeAgentId: pool.agentId,
updatedAt: now,
})
.where(eq(issues.id, row.id))
.returning({ id: issues.id, identifier: issues.identifier, kvLabels: issues.kvLabels });
if (!updated) continue;
const identifier = updated.identifier ?? updated.id;
items.push({ id: updated.id, identifier });
await logActivity(
tx as unknown as Db,
{
companyId,
actorType: "system",
actorId: "managed_channel_pool",
action: "issue.assigned",
entityType: "issue",
entityId: updated.id,
details: {
identifier,
channelId: ch.id,
channelPath: ch.path,
assigneeAgentId: pool.agentId,
managedPool: true,
},
},
publications,
);
const ev = await appendBoardEvent(tx, {
companyId,
type: "task.assigned",
channelId: ch.id,
channelPath: ch.path,
issueId: updated.id,
identifier,
actor: opts.actor ?? {
principalType: "system" as const,
actorProfile: "managed-pool-dispatcher",
},
payload: {
assigneeAgentId: pool.agentId,
managedPool: true,
kvLabels: updated.kvLabels ?? {},
},
});
events.push(ev);
}
if (candidates.length < BATCH_SIZE) {
break;
}
}
return { items, events, channel: ch, poolAgentId: pool.agentId };
});
for (const pub of publications) {
publishActivity(pub);
}
for (const ev of assignedInTx.events) {
publishCommittedBoardEvent(ev);
}
if (opts.heartbeat && assignedInTx.channel && assignedInTx.poolAgentId) {
for (const item of assignedInTx.items) {
await opts.heartbeat
.wakeup(assignedInTx.poolAgentId, {
source: "assignment",
triggerDetail: "system",
reason: "issue_assigned",
payload: {
issueId: item.id,
channelId: assignedInTx.channel.id,
channelPath: assignedInTx.channel.path,
managedPool: true,
},
idempotencyKey: `managed-pool:${assignedInTx.channel.id}:${item.id}`,
requestedByActorType: "system",
requestedByActorId: "managed_channel_pool",
contextSnapshot: {
issueId: item.id,
taskId: item.id,
wakeReason: "issue_assigned",
},
})
.catch(() => {
// Best-effort wakeup; task stays assigned to pool agent for pickup
});
}
}
return { dispatchedIssueIds: assignedInTx.items.map((i) => i.id) };
}
/**
* Dispatches managed pools for a completed issue's own channel (freeing a concurrency slot)
* AND for the distinct channels of any dependent issues that may now be unblocked.
*/
export async function dispatchManagedChannelPoolsForCompletedIssue(
db: Db,
companyId: string,
completedIssueId: string,
completedChannelId: string | null | undefined,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<void> {
const channelIds = new Set<string>();
if (completedChannelId) {
channelIds.add(completedChannelId);
}
const depChannels = await db
.select({ channelId: issues.channelId })
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.relatedIssueId))
.where(
and(
eq(issueRelations.companyId, companyId),
eq(issueRelations.issueId, completedIssueId),
eq(issueRelations.type, "blocks"),
),
);
for (const row of depChannels) {
if (row.channelId) {
channelIds.add(row.channelId);
}
}
for (const chId of channelIds) {
await dispatchManagedChannelPool(db, companyId, chId, opts);
}
}
export async function dispatchManagedChannelPoolBestEffort(
db: Db,
companyId: string,
channelId: string,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<void> {
await dispatchManagedChannelPool(db, companyId, channelId, opts).catch((err) => {
logger.warn(
{ err, companyId, channelId },
"managed channel pool dispatch failed; background worker will retry",
);
});
}
export async function dispatchManagedChannelPoolsForCompletedIssueBestEffort(
db: Db,
companyId: string,
completedIssueId: string,
completedChannelId: string | null | undefined,
opts: {
heartbeat?: ReturnType<typeof heartbeatService>;
actor?: HeadlessActorContext;
},
): Promise<void> {
await dispatchManagedChannelPoolsForCompletedIssue(
db,
companyId,
completedIssueId,
completedChannelId,
opts,
).catch((err) => {
logger.warn(
{ err, companyId, completedIssueId, completedChannelId },
"managed channel pool completion dispatch failed; background worker will retry",
);
});
}
@@ -0,0 +1,513 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
activityLog,
channels,
issueComments,
issueRelations,
issues,
} from "@paperclipai/db";
import {
TaskDependenciesMutationSchema,
type IssueStatus,
type TaskDependenciesView,
type TaskDependencyItemView,
} from "@paperclipai/shared";
import { badRequest, conflict, notFound } from "../errors.js";
import { authorizationService, type AuthorizationActor } from "./authorization.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import {
allowsUnchanneledScope,
appendBoardEvent,
assertIssueChannelScopeAccess,
canAccessChannel,
enforceHeadlessScopes,
getLatestCompanyEventCursor,
publishCommittedBoardEvent,
resolveIssueByIdOrIdentifier,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js";
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 isChannelAllowedByScopes(
actor: Pick<HeadlessActorContext, "scopes" | "keyScope">,
channelPath: string,
): boolean {
try {
enforceHeadlessScopes(actor, { channelPath });
return true;
} catch {
return false;
}
}
function toAuthorizationActor(actor: HeadlessActorContext): AuthorizationActor {
if (actor.principalType === "agent" && actor.agentId) {
return {
type: "agent",
agentId: actor.agentId,
companyId: actor.companyId,
};
}
if (actor.principalType === "local_trusted") {
return {
type: "board",
userId: actor.userId ?? "local-board",
source: "local_implicit",
isInstanceAdmin: true,
};
}
return {
type: "board",
userId: actor.userId ?? "unknown-user",
source: "session",
isInstanceAdmin: actor.isInstanceAdmin,
};
}
async function canReadDependencyIssue(
dbOrTx: DbOrTx,
actor: HeadlessActorContext,
companyId: string,
row: {
id: string;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
},
): Promise<boolean> {
const decision = await authorizationService(dbOrTx as unknown as Db).decide({
action: "issue:read",
actor: toAuthorizationActor(actor),
resource: {
type: "issue",
companyId,
issueId: row.id,
projectId: row.projectId,
parentIssueId: row.parentId,
assigneeAgentId: row.assigneeAgentId,
assigneeUserId: row.assigneeUserId,
},
scope: { companyId },
});
return decision.allowed;
}
async function filterVisibleDependencyItems(
dbOrTx: DbOrTx,
companyId: string,
actor: HeadlessActorContext,
rows: Array<{
id: string;
identifier: string | null;
title: string;
status: string;
channelId: string | null;
projectId: string | null;
parentId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
}>,
): Promise<TaskDependencyItemView[]> {
if (rows.length === 0) return [];
const channelIds = Array.from(
new Set(rows.map((r) => r.channelId).filter((id): id is string => Boolean(id))),
);
const channelMap = new Map<string, typeof channels.$inferSelect>();
if (channelIds.length > 0) {
const chRows = await dbOrTx
.select()
.from(channels)
.where(inArray(channels.id, channelIds));
for (const ch of chRows) {
channelMap.set(ch.id, ch);
}
}
const unchanneledAllowed = allowsUnchanneledScope(actor);
const visible: TaskDependencyItemView[] = [];
for (const row of rows) {
if (row.channelId) {
const ch = channelMap.get(row.channelId);
if (ch) {
if (!isChannelAllowedByScopes(actor, ch.path)) continue;
if (!(await canAccessChannel(dbOrTx, ch, actor))) continue;
}
} else if (!unchanneledAllowed) {
continue;
}
if (!(await canReadDependencyIssue(dbOrTx, actor, companyId, row))) {
continue;
}
visible.push({
id: row.id,
identifier: row.identifier ?? row.id,
title: row.title,
status: row.status as IssueStatus,
});
}
return visible;
}
async function loadDependenciesView(
dbOrTx: DbOrTx,
issue: typeof issues.$inferSelect,
actor: HeadlessActorContext,
cursor: string,
): Promise<TaskDependenciesView> {
const [incoming, outgoing] = await Promise.all([
dbOrTx
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
status: issues.status,
channelId: issues.channelId,
projectId: issues.projectId,
parentId: issues.parentId,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
})
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.issueId))
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.relatedIssueId, issue.id),
eq(issueRelations.type, "blocks"),
),
),
dbOrTx
.select({
id: issues.id,
identifier: issues.identifier,
title: issues.title,
status: issues.status,
channelId: issues.channelId,
projectId: issues.projectId,
parentId: issues.parentId,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
})
.from(issueRelations)
.innerJoin(issues, eq(issues.id, issueRelations.relatedIssueId))
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.issueId, issue.id),
eq(issueRelations.type, "blocks"),
),
),
]);
const [blockedBy, blocks] = await Promise.all([
filterVisibleDependencyItems(dbOrTx, issue.companyId, actor, incoming),
filterVisibleDependencyItems(dbOrTx, issue.companyId, actor, outgoing),
]);
return {
issueId: issue.id,
identifier: issue.identifier ?? issue.id,
status: issue.status as IssueStatus,
blockedBy,
blocks,
cursor,
};
}
async function wouldIntroduceDependencyCycle(
tx: DbOrTx,
companyId: string,
targetIssueId: string,
candidateBlockerIds: string[],
): Promise<boolean> {
// Adding edge: blocker -> targetIssueId.
// A cycle exists iff targetIssueId can already reach any candidateBlocker via existing `blocks` edges.
const targetSet = new Set(candidateBlockerIds);
if (targetSet.has(targetIssueId)) return true;
const visited = new Set<string>([targetIssueId]);
let frontier: string[] = [targetIssueId];
while (frontier.length > 0) {
const rows = await tx
.select({ relatedIssueId: issueRelations.relatedIssueId })
.from(issueRelations)
.where(
and(
eq(issueRelations.companyId, companyId),
inArray(issueRelations.issueId, frontier),
eq(issueRelations.type, "blocks"),
),
);
const nextFrontier: string[] = [];
for (const row of rows) {
if (targetSet.has(row.relatedIssueId)) return true;
if (!visited.has(row.relatedIssueId)) {
visited.add(row.relatedIssueId);
nextFrontier.push(row.relatedIssueId);
}
}
frontier = nextFrontier;
}
return false;
}
export async function listTaskDependencies(
db: Db,
issueId: string,
actor: HeadlessActorContext,
): Promise<TaskDependenciesView> {
enforceHeadlessScopes(actor, { action: "read" });
const [issue] = await db
.select()
.from(issues)
.where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId)))
.limit(1);
if (!issue) {
throw notFound("Issue not found");
}
await assertIssueChannelScopeAccess(db, issue, actor);
const cursor = await getLatestCompanyEventCursor(db, issue.companyId);
return loadDependenciesView(db, issue, actor, cursor);
}
export async function mutateTaskDependencies(
db: Db,
issueId: string,
actor: HeadlessActorContext,
rawInput: unknown,
headerToken?: string,
): Promise<TaskDependenciesView> {
enforceHeadlessScopes(actor, { action: "tasks.dependencies" });
const parsed = TaskDependenciesMutationSchema.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);
// Resolve and authorize bounded, deduplicated dependency references BEFORE
// taking the company-wide dependency advisory lock so per-element lookups
// and authorization checks never hold the lock.
const uniqueAddRefs = Array.from(new Set((input.add ?? []).map((r) => r.trim()).filter(Boolean)));
const uniqueRemoveRefs = Array.from(
new Set((input.remove ?? []).map((r) => r.trim()).filter(Boolean)),
);
const addIds: string[] = [];
for (const ref of uniqueAddRefs) {
const dep = await resolveIssueByIdOrIdentifier(db, ref, actor.companyId);
await assertIssueChannelScopeAccess(db, dep, actor);
if (!(await canReadDependencyIssue(db, actor, actor.companyId, dep))) {
throw notFound(`Issue '${ref}' not found`);
}
if (dep.id === issueId) {
throw badRequest("A task cannot depend on itself", {
code: "cyclic_dependencies",
});
}
addIds.push(dep.id);
}
const removeIds: string[] = [];
for (const ref of uniqueRemoveRefs) {
const dep = await resolveIssueByIdOrIdentifier(db, ref, actor.companyId);
await assertIssueChannelScopeAccess(db, dep, actor);
if (!(await canReadDependencyIssue(db, actor, actor.companyId, dep))) {
throw notFound(`Issue '${ref}' not found`);
}
removeIds.push(dep.id);
}
const committed = await db.transaction(async (tx) => {
// Serialize company dependency graph mutations before locking/checking cycles
// so concurrent requests on different target issues cannot create a cycle.
await tx.execute(
sql`SELECT pg_advisory_xact_lock(hashtextextended(${`${actor.companyId}:issue_deps`}, 0))`,
);
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 epochMatches =
input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch;
const hadActiveLease = issue.claimTokenHash !== null;
if (hadActiveLease) {
if (input.releaseLease || token !== undefined || input.claimEpoch !== undefined) {
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 (token !== undefined || !epochMatches) {
// Reject stale supplied credentials even when no lease currently exists,
// while allowing `releaseLease: true` with no credentials on an unclaimed task.
throw conflict("claim_lost", {
code: "claim_lost",
currentEpoch: Number(issue.claimEpoch ?? 0),
status: issue.status,
});
}
if (addIds.length > 0) {
const hasCycle = await wouldIntroduceDependencyCycle(
tx,
issue.companyId,
issue.id,
addIds,
);
if (hasCycle) {
throw badRequest("Adding dependency would create a cycle", {
code: "cyclic_dependencies",
});
}
await tx
.insert(issueRelations)
.values(
Array.from(new Set(addIds)).map((blockerId) => ({
companyId: issue.companyId,
issueId: blockerId,
relatedIssueId: issue.id,
type: "blocks" as const,
createdByAgentId: actor.agentId ?? null,
createdByUserId: actor.agentId ? null : (actor.userId ?? null),
})),
)
.onConflictDoNothing();
}
if (removeIds.length > 0) {
if (issue.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, issue.channelId);
}
await tx
.delete(issueRelations)
.where(
and(
eq(issueRelations.companyId, issue.companyId),
eq(issueRelations.relatedIssueId, issue.id),
eq(issueRelations.type, "blocks"),
inArray(issueRelations.issueId, removeIds),
),
);
}
let currentIssue = issue;
if (input.releaseLease && issue.claimTokenHash !== null) {
const now = new Date();
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
const [updated] = await tx
.update(issues)
.set({
status: "todo",
claimEpoch: Number(issue.claimEpoch ?? 0) + 1,
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();
currentIssue = updated!;
}
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.dependencies_changed",
entityType: "issue",
entityId: issue.id,
details: {
added: addIds,
removed: removeIds,
releasedLease: Boolean(input.releaseLease && issue.claimTokenHash !== null),
},
});
const event = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.dependencies_changed",
channelId: currentIssue.channelId,
channelPath: targetChannel?.path ?? null,
issueId: currentIssue.id,
identifier: currentIssue.identifier ?? currentIssue.id,
actor,
payload: {
added: addIds,
removed: removeIds,
status: currentIssue.status,
},
});
const view = await loadDependenciesView(tx, currentIssue, actor, event.cursor);
return { view, event };
});
publishCommittedBoardEvent(committed.event);
return committed.view;
}
+187 -20
View File
@@ -10,12 +10,14 @@ import {
issueLabels,
issueRelations,
issues,
issueThreadInteractions,
issueWorkProducts,
labels,
projects,
toolActionRequests,
} from "@paperclipai/db";
import {
applyKvLabelMutation,
BUILT_IN_COMPANY_SCHEMAS,
normalizeChannelPath,
parseDurationMs,
@@ -30,6 +32,7 @@ import {
type BoardEventType,
type BoardEventView,
type ChannelQueueConfig,
type ClaimableTaskStatus,
type HeadlessIssueView,
type LabelFilterExpr,
type SchemaBlock,
@@ -37,6 +40,7 @@ import {
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { ensureChannel, validateWritableKvLabelsOrThrow } from "./headless-channels.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import { listIssueDependencyReadinessMap } from "./issues.js";
import { assertRequiredQualityReviewComplete } from "./required-quality-review.js";
@@ -65,6 +69,10 @@ const CLAIM_WAKE_EVENTS = new Set<BoardEventType>([
"task.lease_released",
"task.lease_expired_requeued",
"task.unblocked",
"task.assigned",
"task.handed_off",
"task.reopened",
"task.dependencies_changed",
"interaction.resolved",
"labels.changed",
]);
@@ -296,6 +304,18 @@ export async function claimTask(
? await resolveProjectReference(db, companyId, parsed.projectId, actor)
: null;
const statusSet = new Set<ClaimableTaskStatus>();
if (parsed.status !== undefined) {
const items = Array.isArray(parsed.status) ? parsed.status : [parsed.status];
for (const s of items) statusSet.add(s);
}
if (parsed.statuses !== undefined) {
for (const s of parsed.statuses) statusSet.add(s);
}
const allowedStatuses: ClaimableTaskStatus[] =
statusSet.size > 0 ? Array.from(statusSet) : ["todo"];
const assigneeMode = parsed.assignee ?? "unassigned";
const tryClaimOnce = async (): Promise<TaskClaimView | null> => {
const committed = await db.transaction(async (tx) => {
let lockedIssue: typeof issues.$inferSelect | undefined;
@@ -367,12 +387,44 @@ export async function claimTask(
reason: "assigned_to_other_user",
});
}
if (fresh.status !== "todo") {
if (!allowedStatuses.includes(fresh.status as ClaimableTaskStatus)) {
throw conflict("task_not_claimable", {
code: "task_not_claimable",
status: fresh.status,
});
}
if (
fresh.claimTokenHash !== null ||
fresh.claimLeaseExpiresAt !== null ||
fresh.checkoutRunId !== null ||
fresh.executionRunId !== null
) {
throw conflict("task_not_claimable", {
code: "task_not_claimable",
status: fresh.status,
reason: "already_claimed_or_running",
});
}
if (fresh.status === "in_review") {
const [pendingInteraction] = await tx
.select({ id: issueThreadInteractions.id })
.from(issueThreadInteractions)
.where(
and(
eq(issueThreadInteractions.companyId, companyId),
eq(issueThreadInteractions.issueId, fresh.id),
eq(issueThreadInteractions.status, "pending"),
),
)
.limit(1);
if (pendingInteraction) {
throw conflict("task_not_claimable", {
code: "task_not_claimable",
status: fresh.status,
reason: "pending_interaction",
});
}
}
const readiness = (
await listIssueDependencyReadinessMap(
@@ -480,9 +532,14 @@ export async function claimTask(
const conditions = [
sql`i.company_id = ${companyId}`,
sql`i.status = 'todo'`,
sql`i.assignee_agent_id IS NULL`,
sql`i.assignee_user_id IS NULL`,
sql`i.status IN (${sql.join(
allowedStatuses.map((s) => sql`${s}`),
sql`, `,
)})`,
sql`i.claim_token_hash IS NULL`,
sql`i.claim_lease_expires_at IS NULL`,
sql`i.checkout_run_id IS NULL`,
sql`i.execution_run_id IS NULL`,
sql`i.hidden_at IS NULL`,
sql`i.conversation_agent_id IS NULL`,
sql`NOT EXISTS (
@@ -512,6 +569,44 @@ export async function claimTask(
)`,
];
if (assigneeMode === "unassigned") {
conditions.push(sql`i.assignee_agent_id IS NULL`);
conditions.push(sql`i.assignee_user_id IS NULL`);
} else if (assigneeMode === "me") {
if (actor.agentId) {
conditions.push(sql`i.assignee_agent_id = ${actor.agentId}`);
} else if (actor.userId) {
conditions.push(sql`i.assignee_user_id = ${actor.userId}`);
} else {
return null;
}
} else if (assigneeMode === "any") {
if (actor.agentId) {
conditions.push(
sql`((i.assignee_agent_id IS NULL AND i.assignee_user_id IS NULL) OR i.assignee_agent_id = ${actor.agentId})`,
);
} else if (actor.userId) {
conditions.push(
sql`((i.assignee_agent_id IS NULL AND i.assignee_user_id IS NULL) OR i.assignee_user_id = ${actor.userId})`,
);
} else {
conditions.push(sql`i.assignee_agent_id IS NULL`);
conditions.push(sql`i.assignee_user_id IS NULL`);
}
}
if (allowedStatuses.includes("in_review")) {
conditions.push(
sql`(i.status <> 'in_review' OR NOT EXISTS (
SELECT 1
FROM issue_thread_interactions iti
WHERE iti.company_id = i.company_id
AND iti.issue_id = i.id
AND iti.status = 'pending'
))`,
);
}
if (eligibleChannelIds !== null) {
conditions.push(
sql`i.channel_id IN (${sql.join(
@@ -909,13 +1004,61 @@ export async function releaseTaskClaim(
}
const now = new Date();
let finalChannel = targetChannel;
if (input.channel !== undefined) {
finalChannel = await ensureChannel(tx, issue.companyId, actor, {
path: input.channel,
});
}
let nextKvLabels = (issue.kvLabels ?? {}) as Record<string, string>;
let labelsChanged = false;
if (input.labels !== undefined || (input.unsetLabels && input.unsetLabels.length > 0)) {
if (input.labels) {
validateWritableKvLabelsOrThrow(input.labels);
}
if (input.unsetLabels) {
for (const k of input.unsetLabels) {
if (k.startsWith("paperclip.")) {
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
error: "reserved_label",
code: "reserved_label",
key: k,
});
}
}
}
const applied = applyKvLabelMutation(nextKvLabels, {
...(input.labels ? { set: input.labels } : {}),
...(input.unsetLabels ? { unset: input.unsetLabels } : {}),
});
if (!applied.ok) {
throw conflict("label_conflict", {
code: "label_conflict",
conflictingKeys: applied.conflictingKeys,
});
}
nextKvLabels = applied.labels;
labelsChanged = true;
}
const nextStatus = input.status ?? "todo";
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
if (nextStatus === "todo" && (finalChannel?.id ?? issue.channelId)) {
await notifyDeliveryWork(
tx,
DELIVERY_QUEUES.managedChannelPools,
(finalChannel?.id ?? issue.channelId)!,
);
}
const nextEpoch = Number(issue.claimEpoch ?? 0) + 1;
const [updated] = await tx
.update(issues)
.set({
status: "todo",
status: nextStatus,
...(finalChannel ? { channelId: finalChannel.id } : {}),
...(labelsChanged ? { kvLabels: nextKvLabels } : {}),
claimEpoch: nextEpoch,
claimTokenHash: null,
claimLeasedAt: null,
@@ -929,6 +1072,13 @@ export async function releaseTaskClaim(
.where(eq(issues.id, issue.id))
.returning();
if (finalChannel && finalChannel.id !== issue.channelId) {
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, finalChannel.id));
}
if (input.comment?.trim()) {
await tx.insert(issueComments).values({
companyId: issue.companyId,
@@ -947,6 +1097,8 @@ export async function releaseTaskClaim(
entityId: updated!.id,
details: {
claimEpoch: Number(updated!.claimEpoch ?? 0),
status: nextStatus,
...(finalChannel ? { channel: finalChannel.path } : {}),
},
});
@@ -954,31 +1106,37 @@ export async function releaseTaskClaim(
companyId: issue.companyId,
type: "task.lease_released",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
channelPath: finalChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
claimEpoch: Number(updated!.claimEpoch ?? 0),
},
});
const readyEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.ready",
channelId: updated!.channelId,
channelPath: targetChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
status: nextStatus,
kvLabels: updated!.kvLabels ?? {},
},
});
const events: BoardEventView[] = [releasedEvent];
if (nextStatus === "todo") {
const readyEvent = await appendBoardEvent(tx, {
companyId: issue.companyId,
type: "task.ready",
channelId: updated!.channelId,
channelPath: finalChannel?.path ?? null,
issueId: updated!.id,
identifier: updated!.identifier ?? updated!.id,
actor,
payload: {
kvLabels: updated!.kvLabels ?? {},
},
});
events.push(readyEvent);
}
return {
events: [releasedEvent, readyEvent],
cursor: readyEvent.cursor,
events,
cursor: events[events.length - 1]!.cursor,
};
});
@@ -1187,6 +1345,11 @@ export async function completeTaskClaim(
if (issue.claimTokenHash !== null) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id);
}
await notifyDeliveryWork(
tx,
DELIVERY_QUEUES.managedChannelPools,
JSON.stringify({ companyId: issue.companyId, issueId: issue.id }),
);
const [updated] = await tx
.update(issues)
@@ -1760,6 +1923,10 @@ export function createClaimLeaseExpiryWorker(db: Db) {
const shouldRequeue = attemptCount < maxAttempts;
const nextEpoch = Number(row.claimEpoch ?? 0) + 1;
if (shouldRequeue && row.channelId) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.managedChannelPools, row.channelId);
}
await tx
.update(issues)
.set({
@@ -0,0 +1,983 @@
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;
}
@@ -37,6 +37,7 @@ export async function notifyIssueRecovery(transaction: object,
...(scope.issueId ? { issueId: scope.issueId } : scope.everyTask ? { everyTask: true } : {}) });
for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint);
for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, taskHint);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.managedChannelPools, taskHint);
}
/** An agent status change: the company queues, and on the task queues only
@@ -46,6 +47,7 @@ export async function notifyAgentRecovery(transaction: object, scope: { companyI
const agentHint = JSON.stringify({ companyId: scope.companyId, agentId: scope.agentId });
for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint);
for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, agentHint);
await notifyDeliveryWork(transaction, DELIVERY_QUEUES.managedChannelPools, agentHint);
}
export async function notifyCompanyRecovery(transaction: object, companyId: string) {