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 | undefined, opts: { issueId: string; assigneeAgentId: string; reason: string; actor: HeadlessActorContext; channelPath?: string | null; }, ): Promise { 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; authorizeTargetAssignee?: (tx: DbOrTx, targetAgentId: string | null) => Promise; }, ): Promise { 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; authorizeTargetAssignee?: (tx: DbOrTx, targetAgentId: string | null) => Promise; }, ): Promise { 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; 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 { 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 }, ): Promise { 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; }