mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Headless channels, fenced task queues, `@paperclipai/shared/sdk`, and the `pc` CLI landed in #23330 to coordinate multi-agent swarms and inbox/queue patterns. > - Real multi-stage workflows immediately hit gaps: there was no `assign` command to push existing channel posts to managed agents, no atomic `handoff`/`move` across channels with CAS labels and lease release, `claim --ready` could not opt into `backlog`/`in_review` or `--assignee me`, there was no `cancel`/`reopen` or mid-flight `--needs` dependency linking, and `pc channels` could not update queue config, manage private members, or bind event-driven managed pools. > - Without these primitives, operators had to drop back to raw `issue update` calls or non-atomic two-step scripts that race on crash. > - This pull request adds the complete workflow lifecycle across shared schemas, modular server services/routes, SDK methods, `pc` CLI commands, and the `.agents/skills/channels-queues-and-workflows` skill. > - The benefit is end-to-end single-command support for inbox triage, single-thread relays, chained channel assembly lines, mid-flight DAG dependencies, and Day-2 graduation to managed Paperclip agent pools. ## Linked Issues or Issue Description Refs #23330 **Subsystem affected** Cross-cutting (multiple of the above) **Problem or motivation** Building multi-agent queues and chained workflows on Paperclip channels required workarounds: assigning an existing post to a registered agent required raw `issue update --assignee-agent-id <uuid>`; moving an issue across stage channels with a label update and lease release required non-atomic multi-step calls; triage or review workers could not opt into claiming `backlog`, `in_review`, or their own assigned tasks (`--mine`); tasks could not be cancelled, reopened, or given mid-flight `--needs` blockers; and channels lacked CLI/API administration for `queueConfig`, private `channel_access_members`, and `managedPool` auto-dispatch. **Proposed solution** Add cohesive REST endpoints, modular services (`headless-task-workflows.ts`, `headless-channel-admin.ts`), SDK methods, `pc` CLI subcommands, and the `channels-queues-and-workflows` skill covering `assign`, `handoff`/`move`, `cancel`, `reopen`, `block --needs`/`deps`, opt-in `claim --status`/`--assignee`, and `channels update`/`members` with event-driven `managedPool` dispatch. **Alternatives considered** Leaving these operations to raw `PATCH /api/issues/:id` calls was rejected because it bypasses fenced claim tokens (`claimEpoch` + `claimToken`), lacks atomic channel+label+lease transactions, and does not enforce CAS preconditions or dependency cycle checks. **Roadmap alignment** Directly extends the headless channels and queues coordination primitive introduced in #23330. ## What Changed - **Shared schemas & SDK (`packages/shared/src/headless/`, `packages/shared/src/sdk/`):** - Added pure zero-zod constants `CLAIMABLE_TASK_STATUSES` and `TASK_CLAIM_ASSIGNEE_MODES` in `pure.ts`, upgraded `TaskClaimRequestSchema` (`status`/`statuses`, `assignee`) and `TaskReleaseSchema` (`status`, `channel`, `labels`, `unsetLabels`), and added `TaskAssignSchema`, `TaskHandoffSchema`, `TaskCancelSchema`, `TaskReopenSchema`, `TaskDependenciesMutationSchema`, `updateChannelInputSchema`, and `channelMemberInputSchema`. - Added `task.assigned`, `task.handed_off`, `task.cancelled`, `task.reopened`, and `task.dependencies_changed` to `BOARD_EVENT_TYPES`. - Exposed matching SDK methods on `paperclip().tasks`, `ClaimedTask`, and `paperclip().channels`. - **Server services & routes (`server/src/services/`, `server/src/routes/`):** - Upgraded `claimTask` and `releaseTaskClaim` in `headless-task-queue.ts` to support opt-in `status` (`todo`, `backlog`, `in_review` excluding pending interactions), `assignee` (`unassigned`, `me`, `any`), and atomic channel/label/status updates on release. - Added `server/src/services/headless-task-workflows.ts` implementing `assignTask`, `handoffTask`, `cancelTask`, `reopenTask`, `listTaskDependencies`, and `mutateTaskDependencies` (with BFS cycle detection and fenced lease release). - Added `server/src/services/headless-channel-admin.ts` implementing `updateChannel`, `listChannelMembers`, `addChannelMember`, `removeChannelMember`, and event-driven `dispatchManagedChannelPool` (zero idle polling). - Wired routes in `headless-queues-events.ts` and `headless-channels-schemas.ts`. - **CLI (`cli/src/commands/board/`):** - Added `cli/src/commands/board/tasks-workflows.ts` (`pc tasks assign`, `handoff`/`move`, `cancel`, `reopen`, `deps list|add|remove`). - Upgraded `pc tasks claim`/`run` (`--status`, `--assignee`, `--mine`), `pc tasks release` (`--channel`, `--label`, `--unset`, `--status`), `pc tasks block` (`--needs`), and `pc channels` (`update`/`config`, `members list|add|remove`). - **Skill & Tests:** - Added `.agents/skills/channels-queues-and-workflows/SKILL.md` and `examples.md`. - Added `server/src/__tests__/headless-task-workflows.test.ts` and updated `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/headless-task-workflows.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 4 files, 27 tests passed. - `pnpm --filter @paperclipai/shared exec vitest run src/headless/headless.test.ts src/sdk/sdk.test.ts` — 2 files, 20 tests passed. - Live headless CLI test-drive (`pc up --port 3299` in isolated `PAPERCLIP_HOME`) verifying `agent connect`, `post`, `tasks assign`, `tasks claim --mine`, `tasks handoff`, `tasks release --status in_review`, `tasks claim --status in_review`, `tasks block --needs`, `tasks deps list`, blocker completion auto-unblock, `tasks cancel`, `tasks reopen`, `tasks claim --status backlog`, `channels members add/list/remove`, and `channels update --managed-pool` — all 11 scenarios passed. ## Risks - Low risk. No database migrations are required; existing `channels.queue_config`, `channel_access_members`, `issue_relations`, and `issues` lease columns are reused. - Default `claim --ready` behavior (`status = todo`, `assignee = unassigned`) is unchanged; `--status` and `--assignee` are strictly opt-in, and `--assignee me`/`any` never allows claiming tasks assigned to another agent or user. - Note on file size: `server/src/services/headless-task-queue.ts` and `cli/src/commands/board/tasks.ts` were already over 1,000 lines before this PR; all new workflow/admin operations were placed in dedicated sibling modules (`headless-task-workflows.ts`, `headless-channel-admin.ts`, `tasks-workflows.ts`) to keep existing files bounded. ## Model Used - Google Gemini (Antigravity agentic runtime, Gemini 4 Neon Medium, extended thinking with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
716 lines
20 KiB
TypeScript
716 lines
20 KiB
TypeScript
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",
|
|
);
|
|
});
|
|
}
|