mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
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:
1 parent
fcb8fc5deb
commit
0434e7f3aa
30 files changed
+5985
-67
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user