import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; import { and, eq, gte, inArray, isNull, ne, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { activityLog, boardEvents, channels, companySchemas, issueComments, issueLabels, issueRelations, issues, issueThreadInteractions, issueWorkProducts, labels, projects, toolActionRequests, } from "@paperclipai/db"; import { applyKvLabelMutation, BUILT_IN_COMPANY_SCHEMAS, normalizeChannelPath, parseDurationMs, parseLabelFilterExpr, parseSchemaRef, TaskClaimRequestSchema, TaskCompleteSchema, TaskFailSchema, TaskReleaseSchema, TaskRenewSchema, validateAgainstJsonSchema, type BoardEventType, type BoardEventView, type ChannelQueueConfig, type ClaimableTaskStatus, type HeadlessIssueView, type LabelFilterExpr, type SchemaBlock, type TaskClaimView, } 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"; import { validateSchemaBlocks, } from "./headless-schemas.js"; import { allowsUnchanneledScope, appendBoardEvent, assertChannelAccess, assertIssueChannelScopeAccess, canAccessChannel, enforceHeadlessScopes, loadHeadlessIssueView, publishCommittedBoardEvent, resolveIssueByIdOrIdentifier, resolveProjectReference, subscribeCompanyBoardEvents, type DbOrTx, type HeadlessActorContext, } from "./headless-common.js"; const CLAIM_WAKE_EVENTS = new Set([ "task.created", "task.ready", "task.lease_released", "task.lease_expired_requeued", "task.unblocked", "task.assigned", "task.handed_off", "task.reopened", "task.dependencies_changed", "interaction.resolved", "labels.changed", ]); const DEFAULT_LEASE_SEC = 300; const DEFAULT_MAX_LEASE_SEC = 3600; const DEFAULT_MAX_CLAIM_ATTEMPTS = 3; export function generateClaimToken(): string { return `clm_${randomBytes(24).toString("base64url")}`; } export function hashClaimToken(token: string): string { return createHash("sha256").update(token, "utf8").digest("hex"); } export function verifyClaimToken( storedHash: string | null | undefined, incomingToken: string | null | undefined, ): boolean { if (!storedHash || !incomingToken) return false; const incomingHash = hashClaimToken(incomingToken); const storedBuf = Buffer.from(storedHash, "utf8"); const incomingBuf = Buffer.from(incomingHash, "utf8"); if (storedBuf.length !== incomingBuf.length) return false; return timingSafeEqual(storedBuf, incomingBuf); } export function extractClaimToken( bodyToken?: string | null, headerToken?: string | null, ): string | undefined { const headerVal = headerToken?.trim(); if (headerVal) return headerVal; const bodyVal = bodyToken?.trim(); if (bodyVal) return bodyVal; return undefined; } function formatBlocksAsFencedJson(blocks: SchemaBlock[]): string { return blocks .map( (b) => `\`\`\`json schema=${b.schema}@${b.version}\n${JSON.stringify(b.data, null, 2)}\n\`\`\``, ) .join("\n\n"); } function isChannelAllowedByScopes( actor: HeadlessActorContext, channelPath: string, ): boolean { try { enforceHeadlessScopes(actor, { channelPath }); return true; } catch { return false; } } function checkChannelQueueEligibility( queueConfig: ChannelQueueConfig | null | undefined, actor: HeadlessActorContext, ): { ok: true } | { ok: false; code: string; message: string } { if (!queueConfig) return { ok: true }; if (queueConfig.allowedAgentIds && queueConfig.allowedAgentIds.length > 0) { if (!actor.agentId || !queueConfig.allowedAgentIds.includes(actor.agentId)) { return { ok: false, code: "channel_agent_denied", message: "Caller agent is not in channel queueConfig.allowedAgentIds", }; } } if (queueConfig.allowedRoles && queueConfig.allowedRoles.length > 0) { if (!actor.agentRole || !queueConfig.allowedRoles.includes(actor.agentRole)) { return { ok: false, code: "channel_role_denied", message: "Caller role is not in channel queueConfig.allowedRoles", }; } } return { ok: true }; } function computeEffectiveLeaseSec( requestedLeaseSec: number | undefined, queueConfig: ChannelQueueConfig | null | undefined, ): number { const defaultLeaseSec = queueConfig?.defaultLeaseSec ?? DEFAULT_LEASE_SEC; const maxLeaseSec = queueConfig?.maxLeaseSec ?? DEFAULT_MAX_LEASE_SEC; if (requestedLeaseSec !== undefined) { return Math.max(1, Math.min(requestedLeaseSec, maxLeaseSec)); } return Math.max(1, Math.min(defaultLeaseSec, maxLeaseSec)); } async function resolveJsonSchemaForRef( dbOrTx: DbOrTx, companyId: string, schemaRef: string, ): Promise | null> { const parsed = parseSchemaRef(schemaRef); const [custom] = await dbOrTx .select({ jsonSchema: companySchemas.jsonSchema }) .from(companySchemas) .where( and( eq(companySchemas.companyId, companyId), eq(companySchemas.name, parsed.name), eq(companySchemas.version, parsed.version), ), ) .limit(1); if (custom) { return custom.jsonSchema as Record; } const builtIn = BUILT_IN_COMPANY_SCHEMAS.find( (s) => s.name === parsed.name && s.version === parsed.version, ); return builtIn ? (builtIn.jsonSchema as Record) : null; } function buildSqlLabelFilterCondition(expr: LabelFilterExpr) { switch (expr.kind) { case "equals": return sql`i.kv_labels->>${expr.key} = ${expr.value}`; case "in": return sql`i.kv_labels->>${expr.key} IN (${sql.join( expr.values.map((v) => sql`${v}`), sql`, `, )})`; case "exists": return sql`(jsonb_exists(i.kv_labels, ${expr.key}) OR EXISTS ( SELECT 1 FROM ${issueLabels} il INNER JOIN ${labels} l ON l.id = il.label_id WHERE il.issue_id = i.id AND l.name = ${expr.key} ))`; } } 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, }; } export async function claimTask( db: Db, companyId: string, actor: HeadlessActorContext, rawReq: unknown, signal?: AbortSignal, opts?: { readCondition?: SQL }, ): Promise { const parsed = TaskClaimRequestSchema.parse(rawReq ?? {}); enforceHeadlessScopes(actor, { action: "tasks.claim", ...(parsed.channel ? { channelPath: parsed.channel } : {}), }); if (!parsed.issueId && parsed.ready === false) { throw badRequest("Either issueId or ready=true must be provided"); } let requestedLeaseSec: number | undefined; if (parsed.leaseSec !== undefined) { requestedLeaseSec = parsed.leaseSec; } else if (parsed.lease !== undefined) { try { requestedLeaseSec = Math.max(1, Math.round(parseDurationMs(parsed.lease) / 1000)); } catch (err) { throw badRequest(err instanceof Error ? err.message : "Invalid lease duration"); } } let waitMs = 0; if (parsed.waitSec !== undefined) { waitMs = Math.max(0, Math.floor(parsed.waitSec * 1000)); } else if (parsed.wait !== undefined) { try { waitMs = Math.max(0, parseDurationMs(parsed.wait)); } catch (err) { throw badRequest(err instanceof Error ? err.message : "Invalid wait duration"); } } let labelExprs: LabelFilterExpr[] = []; if (parsed.labels && parsed.labels.length > 0) { try { labelExprs = parsed.labels.map((expr) => parseLabelFilterExpr(expr)); } catch (err) { throw badRequest(err instanceof Error ? err.message : "Invalid label filter"); } } let normalizedChannel: { path: string; isSubtreePrefix: boolean } | null = null; if (parsed.channel) { try { normalizedChannel = normalizeChannelPath(parsed.channel, { allowSubtreePrefix: true, }); } catch (err) { throw badRequest(err instanceof Error ? err.message : "Invalid channel path"); } } const projectIdFilter = parsed.projectId ? await resolveProjectReference(db, companyId, parsed.projectId, actor) : null; const statusSet = new Set(); 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 => { const committed = await db.transaction(async (tx) => { let lockedIssue: typeof issues.$inferSelect | undefined; let targetChannel: typeof channels.$inferSelect | null = null; if (parsed.issueId) { const resolved = await resolveIssueByIdOrIdentifier( tx, parsed.issueId, companyId, ); if (opts?.readCondition) { const [readable] = await tx .select({ id: issues.id }) .from(issues) .where(and(eq(issues.id, resolved.id), opts.readCondition)) .limit(1); if (!readable) { throw notFound("Issue not found"); } } await tx.execute( sql`SELECT id FROM issues WHERE id = ${resolved.id} AND company_id = ${companyId} FOR UPDATE`, ); const [fresh] = await tx .select() .from(issues) .where(and(eq(issues.id, resolved.id), eq(issues.companyId, companyId))); if (!fresh || fresh.hiddenAt !== null) { throw conflict("task_not_claimable", { code: "task_not_claimable", status: fresh?.status ?? "hidden", }); } if (fresh.channelId) { const [ch] = await tx .select() .from(channels) .where(eq(channels.id, fresh.channelId)); if (ch) { targetChannel = ch; await assertChannelAccess(tx, ch, actor); const eligibility = checkChannelQueueEligibility(ch.queueConfig, actor); if (!eligibility.ok) { throw forbidden(eligibility.message, { code: eligibility.code }); } } } else if (!allowsUnchanneledScope(actor)) { throw forbidden("Caller scopes do not allow claiming unchanneled tasks", { code: "scope_denied", }); } if ( fresh.assigneeAgentId && fresh.assigneeAgentId !== actor.agentId ) { throw conflict("task_not_claimable", { code: "task_not_claimable", status: fresh.status, reason: "assigned_to_other_agent", }); } if (fresh.assigneeUserId && fresh.assigneeUserId !== actor.userId) { throw conflict("task_not_claimable", { code: "task_not_claimable", status: fresh.status, reason: "assigned_to_other_user", }); } 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( tx as unknown as Db, companyId, [fresh.id], false, ) ).get(fresh.id); if (readiness && !readiness.isDependencyReady) { throw conflict("task_not_claimable", { code: "task_not_claimable", status: fresh.status, reason: "blocked_by_dependencies", }); } const activePauseHold = await issueTreeControlService(db).getActivePauseHoldGate( companyId, fresh.id, ); if (activePauseHold) { throw conflict("Issue tree is currently paused", { code: "issue_paused", holdId: activePauseHold.holdId, rootIssueId: activePauseHold.rootIssueId, }); } if (fresh.projectId) { const [projectRow] = await tx .select({ id: projects.id, pausedAt: projects.pausedAt, pauseReason: projects.pauseReason, }) .from(projects) .where(and(eq(projects.id, fresh.projectId), eq(projects.companyId, companyId))) .limit(1); if (projectRow?.pausedAt) { throw conflict( projectRow.pauseReason === "budget" ? "Project is paused because its budget hard-stop was reached" : "Project is paused", { code: "project_paused", projectId: projectRow.id, }, ); } } lockedIssue = fresh; } else { // Ready pool pop via FOR UPDATE SKIP LOCKED const companyChannels = await tx .select() .from(channels) .where(and(eq(channels.companyId, companyId), isNull(channels.archivedAt))); const channelById = new Map(companyChannels.map((c) => [c.id, c])); let eligibleChannelIds: string[] | null = null; let inaccessibleChannelIds: string[] = []; let strictFifo = false; if (normalizedChannel) { const matchingChannels = companyChannels.filter((c) => normalizedChannel.isSubtreePrefix ? c.path === normalizedChannel.path || c.path.startsWith(`${normalizedChannel.path}/`) : c.path === normalizedChannel.path, ); const accessible: Array = []; for (const ch of matchingChannels) { if (!isChannelAllowedByScopes(actor, ch.path)) continue; if (!(await canAccessChannel(tx, ch, actor))) continue; if (!checkChannelQueueEligibility(ch.queueConfig, actor).ok) continue; accessible.push(ch); } if (accessible.length === 0) { return null; } eligibleChannelIds = accessible.map((c) => c.id); if ( !normalizedChannel.isSubtreePrefix && accessible.length === 1 && accessible[0]!.queueConfig?.ordering === "strict_fifo" ) { strictFifo = true; } } else { for (const ch of companyChannels) { const allowedScope = isChannelAllowedByScopes(actor, ch.path); const allowedMember = await canAccessChannel(tx, ch, actor); const allowedQueue = checkChannelQueueEligibility( ch.queueConfig, actor, ).ok; if (!allowedScope || !allowedMember || !allowedQueue) { inaccessibleChannelIds.push(ch.id); } } } const conditions = [ sql`i.company_id = ${companyId}`, 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 ( 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' )`, sql`NOT EXISTS ( WITH RECURSIVE tree_anc(id, parent_id, depth) AS ( SELECT i.id, i.parent_id, 1 UNION ALL SELECT p.id, p.parent_id, tree_anc.depth + 1 FROM tree_anc JOIN issues p ON p.id = tree_anc.parent_id AND p.company_id = i.company_id WHERE tree_anc.depth < 32 ) SELECT 1 FROM tree_anc JOIN issue_tree_holds h ON h.root_issue_id = tree_anc.id WHERE h.company_id = i.company_id AND h.status = 'active' AND h.mode = 'pause' )`, ]; 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( eligibleChannelIds.map((id) => sql`${id}`), sql`, `, )})`, ); } else { if (!allowsUnchanneledScope(actor)) { conditions.push(sql`i.channel_id IS NOT NULL`); } if (inaccessibleChannelIds.length > 0) { conditions.push( sql`(i.channel_id IS NULL OR i.channel_id NOT IN (${sql.join( inaccessibleChannelIds.map((id) => sql`${id}`), sql`, `, )}))`, ); } } if (projectIdFilter) { conditions.push(sql`i.project_id = ${projectIdFilter}`); } if (opts?.readCondition) { conditions.push( sql`EXISTS (SELECT 1 FROM issues WHERE issues.id = i.id AND ${opts.readCondition})`, ); } conditions.push( sql`(i.project_id IS NULL OR NOT EXISTS ( SELECT 1 FROM projects p WHERE p.id = i.project_id AND p.company_id = i.company_id AND p.paused_at IS NOT NULL ))`, ); if (parsed.includeUntrusted !== true) { conditions.push( sql`(i.source_trust IS NULL OR (COALESCE(i.source_trust->>'level', '') <> 'untrusted' AND COALESCE(i.source_trust->>'disposition', '') <> 'quarantined'))`, ); } for (const expr of labelExprs) { conditions.push(buildSqlLabelFilterCondition(expr)); } 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 skippedCandidateIds: string[] = []; let fresh: typeof issues.$inferSelect | undefined; while (true) { const loopConditions = skippedCandidateIds.length > 0 ? [ ...conditions, sql`i.id NOT IN (${sql.join( skippedCandidateIds.map((id) => sql`${id}`), sql`, `, )})`, ] : conditions; const candidateRows = await tx.execute<{ id: string }>(sql` SELECT i.id FROM issues i WHERE ${sql.join(loopConditions, sql` AND `)} ORDER BY ${orderClause} LIMIT 1 FOR UPDATE OF i SKIP LOCKED `); const candidateId = candidateRows[0]?.id; if (!candidateId) { return null; } const readiness = ( await listIssueDependencyReadinessMap( tx as unknown as Db, companyId, [candidateId], false, ) ).get(candidateId); if (readiness && !readiness.isDependencyReady) { skippedCandidateIds.push(candidateId); continue; } const [candidate] = await tx .select() .from(issues) .where(eq(issues.id, candidateId)); if (!candidate) return null; fresh = candidate; break; } lockedIssue = fresh; targetChannel = fresh.channelId ? channelById.get(fresh.channelId) ?? null : null; } const effectiveLeaseSec = computeEffectiveLeaseSec( requestedLeaseSec, targetChannel?.queueConfig, ); const claimToken = generateClaimToken(); const claimTokenHash = hashClaimToken(claimToken); const now = new Date(); const leaseExpiresAt = new Date(now.getTime() + effectiveLeaseSec * 1000); const nextEpoch = Number(lockedIssue.claimEpoch ?? 0) + 1; const nextAttemptCount = (lockedIssue.claimAttemptCount ?? 0) + 1; await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, lockedIssue.id); const [updated] = await tx .update(issues) .set({ status: "in_progress", startedAt: lockedIssue.startedAt ?? now, claimEpoch: nextEpoch, claimAttemptCount: nextAttemptCount, claimTokenHash, claimHolderAgentId: actor.agentId ?? null, claimHolderUserId: actor.agentId ? null : (actor.userId ?? null), claimHolderProfile: actor.actorProfile ?? null, claimLeasedAt: now, claimLeaseExpiresAt: leaseExpiresAt, updatedAt: now, }) .where(eq(issues.id, lockedIssue.id)) .returning(); const actorInfo = activityActorFields(actor); await tx.insert(activityLog).values({ companyId, ...actorInfo, action: "issue.claimed", entityType: "issue", entityId: updated!.id, details: { claimEpoch: nextEpoch, claimAttemptCount: nextAttemptCount, leaseExpiresAt: leaseExpiresAt.toISOString(), holderProfile: updated!.claimHolderProfile, }, }); const event = await appendBoardEvent(tx, { companyId, type: "task.claimed", channelId: updated!.channelId, channelPath: targetChannel?.path ?? null, issueId: updated!.id, identifier: updated!.identifier ?? updated!.id, actor, payload: { claimEpoch: nextEpoch, claimAttemptCount: nextAttemptCount, leaseExpiresAt: leaseExpiresAt.toISOString(), holderProfile: updated!.claimHolderProfile, kvLabels: updated!.kvLabels ?? {}, }, }); const issueView = await loadHeadlessIssueView(tx, updated!.id, event.cursor); return { event, claimView: { issue: issueView, claimToken, claimEpoch: nextEpoch, leaseExpiresAt: leaseExpiresAt.toISOString(), cursor: event.cursor, } satisfies TaskClaimView, }; }); if (!committed) return null; publishCommittedBoardEvent(committed.event); return committed.claimView; }; const immediate = await tryClaimOnce(); if (immediate || waitMs <= 0 || parsed.issueId) { return immediate; } const deadline = Date.now() + waitMs; while (!signal?.aborted) { const remaining = deadline - Date.now(); if (remaining <= 0) return null; let woke = false; let wakeResolve: (() => void) | null = null; const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => { if (!CLAIM_WAKE_EVENTS.has(ev.type)) return; woke = true; wakeResolve?.(); }); try { // Re-check after subscribing so events committed right before subscribe are never missed. const claimed = await tryClaimOnce(); if (claimed) return claimed; if (signal?.aborted) return null; const left = deadline - Date.now(); if (left <= 0) return null; if (!woke) { await new Promise((resolve) => { let settled = false; const finish = () => { if (settled) return; settled = true; clearTimeout(timer); signal?.removeEventListener("abort", finish); wakeResolve = null; resolve(); }; wakeResolve = finish; const timer = setTimeout(finish, left); signal?.addEventListener("abort", finish, { once: true }); }); } } finally { unsubscribe(); } } return null; } export async function renewTaskClaim( db: Db, issueId: string, actor: HeadlessActorContext, rawInput: unknown, headerToken?: string, ): Promise { enforceHeadlessScopes(actor, { action: "tasks.claim_renew" }); const input = TaskRenewSchema.parse(rawInput ?? {}); const token = extractClaimToken(input.claimToken, headerToken); let requestedLeaseSec: number | undefined; if (input.leaseSec !== undefined) { requestedLeaseSec = input.leaseSec; } else if (input.lease !== undefined) { try { requestedLeaseSec = Math.max(1, Math.round(parseDurationMs(input.lease) / 1000)); } catch (err) { throw badRequest(err instanceof Error ? err.message : "Invalid lease duration"); } } 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 conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); } const { channel: targetChannel } = await assertIssueChannelScopeAccess( tx, issue, actor, ); const epochMatches = input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; 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, }); } // Laptop-sleep-safe: even if claimLeaseExpiresAt is in the past, token + epoch still match // because the lease reconciler has not reassigned or expired this epoch yet. const effectiveLeaseSec = computeEffectiveLeaseSec( requestedLeaseSec, targetChannel?.queueConfig, ); const now = new Date(); const leaseExpiresAt = new Date(now.getTime() + effectiveLeaseSec * 1000); await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); const [updated] = await tx .update(issues) .set({ claimLeaseExpiresAt: leaseExpiresAt, updatedAt: now, }) .where(eq(issues.id, issue.id)) .returning(); const event = await appendBoardEvent(tx, { companyId: issue.companyId, type: "task.lease_renewed", channelId: updated!.channelId, channelPath: targetChannel?.path ?? null, issueId: updated!.id, identifier: updated!.identifier ?? updated!.id, actor, payload: { claimEpoch: Number(updated!.claimEpoch ?? 0), leaseExpiresAt: leaseExpiresAt.toISOString(), }, }); const issueView = await loadHeadlessIssueView(tx, updated!.id, event.cursor); return { event, claimView: { issue: issueView, claimToken: token!, claimEpoch: Number(updated!.claimEpoch ?? 0), leaseExpiresAt: leaseExpiresAt.toISOString(), cursor: event.cursor, } satisfies TaskClaimView, }; }); publishCommittedBoardEvent(committed.event); return committed.claimView; } export async function releaseTaskClaim( db: Db, issueId: string, actor: HeadlessActorContext, rawInput: unknown, headerToken?: string, ): Promise<{ released: boolean; cursor: string }> { enforceHeadlessScopes(actor, { action: "tasks.claim_release" }); const input = TaskReleaseSchema.parse(rawInput ?? {}); 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 conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); } const { channel: targetChannel } = await assertIssueChannelScopeAccess( tx, issue, actor, ); const epochMatches = input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; 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, }); } 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; 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: nextStatus, ...(finalChannel ? { channelId: finalChannel.id } : {}), ...(labelsChanged ? { kvLabels: nextKvLabels } : {}), 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), }); } const actorInfo = activityActorFields(actor); await tx.insert(activityLog).values({ companyId: issue.companyId, ...actorInfo, action: "issue.claim_released", entityType: "issue", entityId: updated!.id, details: { claimEpoch: Number(updated!.claimEpoch ?? 0), status: nextStatus, ...(finalChannel ? { channel: finalChannel.path } : {}), }, }); const releasedEvent = await appendBoardEvent(tx, { companyId: issue.companyId, type: "task.lease_released", channelId: updated!.channelId, channelPath: finalChannel?.path ?? null, issueId: updated!.id, identifier: updated!.identifier ?? updated!.id, actor, payload: { claimEpoch: Number(updated!.claimEpoch ?? 0), 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, cursor: events[events.length - 1]!.cursor, }; }); for (const ev of committed.events) { publishCommittedBoardEvent(ev); } return { released: true, cursor: committed.cursor }; } export async function completeTaskClaim( db: Db, issueId: string, actor: HeadlessActorContext, rawInput: unknown, headerToken?: string, ): Promise { enforceHeadlessScopes(actor, { action: "tasks.complete" }); const input = TaskCompleteSchema.parse(rawInput ?? {}); 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 conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); } const { channel: targetChannel } = await assertIssueChannelScopeAccess( tx, issue, actor, ); const epochMatches = input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; if (issue.claimTokenHash !== null) { 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 || issue.status === "done" || issue.status === "cancelled" ) { throw conflict("claim_lost", { code: "claim_lost", currentEpoch: Number(issue.claimEpoch ?? 0), status: issue.status, }); } await assertRequiredQualityReviewComplete(tx as unknown as Db, issue, true); if (actor.agentId) { const [pendingToolReview] = await tx .select({ id: toolActionRequests.id }) .from(toolActionRequests) .where( and( eq(toolActionRequests.companyId, issue.companyId), eq(toolActionRequests.issueId, issue.id), inArray(toolActionRequests.status, ["pending", "approved", "executing"]), ), ) .limit(1); if (pendingToolReview) { throw conflict( "This task is waiting for a connection review. Finish unrelated work, then yield in_review without retrying the governed call.", { code: "tool_review_pending", actionRequestId: pendingToolReview.id, }, ); } } if ( issue.resultSchemaRef && input.resultSchema && input.resultSchema.trim().toLowerCase() !== issue.resultSchemaRef.trim().toLowerCase() ) { throw conflict( `Task requires result schema '${issue.resultSchemaRef}' and cannot be overridden with '${input.resultSchema}'`, { code: "result_schema_mismatch", requiredResultSchema: issue.resultSchemaRef, }, ); } const schemaRef = issue.resultSchemaRef ?? input.resultSchema ?? null; const rawSchemaBlocks: SchemaBlock[] = [...(input.blocks ?? [])]; if (input.data && schemaRef) { const parsedRef = parseSchemaRef(schemaRef); const alreadyHasBlock = rawSchemaBlocks.some( (b) => b.schema === parsedRef.name && b.version === parsedRef.version, ); if (!alreadyHasBlock) { rawSchemaBlocks.push({ schema: parsedRef.name, version: parsedRef.version, data: input.data, }); } } if (schemaRef) { const parsedRef = parseSchemaRef(schemaRef); const jsonSchema = await resolveJsonSchemaForRef( tx, issue.companyId, parsedRef.ref, ); if (!jsonSchema) { throw unprocessable( `Result schema '${parsedRef.ref}' is not registered`, { code: "result_schema_validation_failed", errors: [`Schema '${parsedRef.ref}' is not registered`], next: [`pc schemas list`], }, ); } const payloadToValidate = input.data ?? rawSchemaBlocks.find( (b) => b.schema === parsedRef.name && b.version === parsedRef.version, )?.data; if (payloadToValidate === undefined) { throw unprocessable( `Task requires structured '--data' matching resultSchema '${parsedRef.ref}'`, { code: "result_schema_validation_failed", errors: [ `Completion requires structured result data matching '${parsedRef.ref}'`, ], next: [`pc schemas get ${parsedRef.ref}`], }, ); } const validation = validateAgainstJsonSchema(jsonSchema, payloadToValidate); if (!validation.valid) { throw unprocessable( `Result data failed '${parsedRef.ref}' validation: ${validation.errors.join("; ")}`, { code: "result_schema_validation_failed", errors: validation.errors, next: [`pc schemas get ${parsedRef.ref}`], }, ); } } const schemaBlocks = rawSchemaBlocks.length > 0 ? await validateSchemaBlocks(tx as unknown as Db, issue.companyId, rawSchemaBlocks) : []; const commentText = (input.message ?? input.comment)?.trim() || ""; if (commentText || schemaBlocks.length > 0 || input.prUrl) { const body = commentText || (schemaBlocks.length > 0 ? formatBlocksAsFencedJson(schemaBlocks) : `Completed (${input.prUrl})`); await tx.insert(issueComments).values({ companyId: issue.companyId, issueId: issue.id, body, schemaBlocks, ...commentAuthorFields(actor), }); } if (input.prUrl) { await tx.insert(issueWorkProducts).values({ companyId: issue.companyId, projectId: issue.projectId ?? null, issueId: issue.id, type: "pull_request", provider: "github", url: input.prUrl, title: "Pull Request", status: "ready_for_review", }); } const now = new Date(); 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) .set({ status: "done", completedAt: now, claimTokenHash: null, claimLeasedAt: null, claimLeaseExpiresAt: null, claimHolderAgentId: null, claimHolderUserId: null, claimHolderProfile: null, updatedAt: now, }) .where(eq(issues.id, issue.id)) .returning(); const actorInfo = activityActorFields(actor); await tx.insert(activityLog).values({ companyId: issue.companyId, ...actorInfo, action: "issue.completed", entityType: "issue", entityId: updated!.id, details: { claimEpoch: Number(updated!.claimEpoch ?? 0), ...(input.prUrl ? { prUrl: input.prUrl } : {}), }, }); // Check and lock dependent issues BEFORE acquiring the company board_events advisory lock // so all issue row locks precede the board_events lock consistently across transactions. const dependentLinks = await tx .select({ relatedIssueId: issueRelations.relatedIssueId }) .from(issueRelations) .where( and( eq(issueRelations.companyId, issue.companyId), eq(issueRelations.issueId, issue.id), eq(issueRelations.type, "blocks"), ), ); const pendingUnblockEvents: Array<{ dep: typeof issues.$inferSelect; depChannelPath: string | null; unblockPayload: Record; }> = []; if (dependentLinks.length > 0) { const dependentIds = Array.from( new Set(dependentLinks.map((d) => d.relatedIssueId)), ).sort(); await tx.execute( sql`SELECT id FROM issues WHERE company_id = ${issue.companyId} AND id IN (${sql.join( dependentIds.map((id) => sql`${id}`), sql`, `, )}) ORDER BY id FOR UPDATE`, ); const dependentRows = await tx .select() .from(issues) .where( and( eq(issues.companyId, issue.companyId), inArray(issues.id, dependentIds), eq(issues.status, "todo"), isNull(issues.hiddenAt), ), ); const depChannelIds = Array.from( new Set( dependentRows .map((d) => d.channelId) .filter((id): id is string => Boolean(id)), ), ); const depChannelRows = depChannelIds.length > 0 ? await tx .select({ id: channels.id, path: channels.path }) .from(channels) .where(inArray(channels.id, depChannelIds)) : []; const depChannelMap = new Map(depChannelRows.map((c) => [c.id, c.path])); const dependentReadinessMap = await listIssueDependencyReadinessMap( tx as unknown as Db, issue.companyId, dependentRows.map((d) => d.id), false, ); for (const dep of dependentRows) { const depReadiness = dependentReadinessMap.get(dep.id); if (!depReadiness || depReadiness.isDependencyReady) { const depChannelPath = dep.channelId ? depChannelMap.get(dep.channelId) ?? null : null; pendingUnblockEvents.push({ dep, depChannelPath, unblockPayload: { unblockedByIssueId: updated!.id, unblockedByIdentifier: updated!.identifier ?? updated!.id, kvLabels: dep.kvLabels ?? {}, }, }); } } } const eventsToPublish: BoardEventView[] = []; const completedEvent = await appendBoardEvent(tx, { companyId: issue.companyId, type: "task.completed", channelId: updated!.channelId, channelPath: targetChannel?.path ?? null, issueId: updated!.id, identifier: updated!.identifier ?? updated!.id, actor, payload: { claimEpoch: Number(updated!.claimEpoch ?? 0), blocks: schemaBlocks, ...(input.prUrl ? { prUrl: input.prUrl } : {}), kvLabels: updated!.kvLabels ?? {}, }, }); eventsToPublish.push(completedEvent); for (const item of pendingUnblockEvents) { eventsToPublish.push( ...(await appendPoolDependentUnblockBoardEvents(tx, { companyId: issue.companyId, dep: item.dep, channelPath: item.depChannelPath, actor, payload: item.unblockPayload, })), ); } const issueView = await loadHeadlessIssueView( tx, updated!.id, completedEvent.cursor, ); return { events: eventsToPublish, issueView }; }); for (const ev of committed.events) { publishCommittedBoardEvent(ev); } return committed.issueView; } async function appendPoolDependentUnblockBoardEvents( tx: DbOrTx, args: { companyId: string; dep: typeof issues.$inferSelect; channelPath: string | null; actor: HeadlessActorContext | { principalType: "system"; actorProfile?: string | null }; payload: Record; }, ): Promise { const unblockedEvent = await appendBoardEvent(tx, { companyId: args.companyId, type: "task.unblocked", channelId: args.dep.channelId, channelPath: args.channelPath, issueId: args.dep.id, identifier: args.dep.identifier ?? args.dep.id, actor: args.actor, payload: args.payload, }); const readyEvent = await appendBoardEvent(tx, { companyId: args.companyId, type: "task.ready", channelId: args.dep.channelId, channelPath: args.channelPath, issueId: args.dep.id, identifier: args.dep.identifier ?? args.dep.id, actor: args.actor, payload: args.payload, }); return [unblockedEvent, readyEvent]; } export async function wakeReadyPoolDependentsForBlocker( db: Db, blockerIssueId: string, ): Promise { const events = await db.transaction(async (tx) => { const [blocker] = await tx .select({ id: issues.id, companyId: issues.companyId, identifier: issues.identifier, status: issues.status, completedAt: issues.completedAt, updatedAt: issues.updatedAt, }) .from(issues) .where(eq(issues.id, blockerIssueId)) .limit(1); if (!blocker || blocker.status !== "done") { return [] as BoardEventView[]; } const dependentLinks = await tx .select({ relatedIssueId: issueRelations.relatedIssueId }) .from(issueRelations) .where( and( eq(issueRelations.companyId, blocker.companyId), eq(issueRelations.issueId, blocker.id), eq(issueRelations.type, "blocks"), ), ); if (dependentLinks.length === 0) { return [] as BoardEventView[]; } const dependentIds = Array.from( new Set(dependentLinks.map((d) => d.relatedIssueId)), ).sort(); await tx.execute( sql`SELECT id FROM issues WHERE company_id = ${blocker.companyId} AND id IN (${sql.join( dependentIds.map((id) => sql`${id}`), sql`, `, )}) ORDER BY id FOR UPDATE`, ); const dependentRows = await tx .select() .from(issues) .where( and( eq(issues.companyId, blocker.companyId), inArray(issues.id, dependentIds), eq(issues.status, "todo"), isNull(issues.assigneeAgentId), isNull(issues.assigneeUserId), isNull(issues.conversationAgentId), isNull(issues.hiddenAt), ), ); if (dependentRows.length === 0) { return [] as BoardEventView[]; } const readinessMap = await listIssueDependencyReadinessMap( tx as unknown as Db, blocker.companyId, dependentRows.map((d) => d.id), false, ); const readyDeps = dependentRows.filter((dep) => { const readiness = readinessMap.get(dep.id); return !readiness || readiness.isDependencyReady; }); if (readyDeps.length === 0) { return [] as BoardEventView[]; } const cycleStart = blocker.completedAt ?? blocker.updatedAt; const alreadyNotifiedRows = await tx .select({ issueId: boardEvents.issueId }) .from(boardEvents) .where( and( eq(boardEvents.companyId, blocker.companyId), inArray( boardEvents.issueId, readyDeps.map((d) => d.id), ), eq(boardEvents.eventType, "task.ready"), sql`${boardEvents.payload}->>'unblockedByIssueId' = ${blocker.id}`, gte(boardEvents.createdAt, cycleStart), ), ); const notifiedIds = new Set( alreadyNotifiedRows .map((r) => r.issueId) .filter((id): id is string => Boolean(id)), ); const pendingDeps = readyDeps.filter((dep) => !notifiedIds.has(dep.id)); if (pendingDeps.length === 0) { return [] as BoardEventView[]; } const depChannelIds = Array.from( new Set( pendingDeps .map((d) => d.channelId) .filter((id): id is string => Boolean(id)), ), ); const depChannelRows = depChannelIds.length > 0 ? await tx .select({ id: channels.id, path: channels.path }) .from(channels) .where(inArray(channels.id, depChannelIds)) : []; const depChannelMap = new Map(depChannelRows.map((c) => [c.id, c.path])); const systemActor = { principalType: "system" as const, actorProfile: "workspace-finalize", }; const emitted: BoardEventView[] = []; for (const dep of pendingDeps) { emitted.push( ...(await appendPoolDependentUnblockBoardEvents(tx, { companyId: blocker.companyId, dep, channelPath: dep.channelId ? depChannelMap.get(dep.channelId) ?? null : null, actor: systemActor, payload: { unblockedByIssueId: blocker.id, unblockedByIdentifier: blocker.identifier ?? blocker.id, kvLabels: dep.kvLabels ?? {}, source: "workspace.finalize", }, })), ); } return emitted; }); for (const ev of events) { publishCommittedBoardEvent(ev); } return events.length / 2; } export async function failTaskClaim( db: Db, issueId: string, actor: HeadlessActorContext, rawInput: unknown, headerToken?: string, ): Promise { enforceHeadlessScopes(actor, { action: "tasks.fail" }); const input = TaskFailSchema.parse(rawInput ?? {}); 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 conflict("claim_lost", { code: "claim_lost", currentEpoch: 0 }); } const { channel: targetChannel } = await assertIssueChannelScopeAccess( tx, issue, actor, ); const epochMatches = input.claimEpoch === undefined || Number(issue.claimEpoch ?? 0) === input.claimEpoch; 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, }); } await tx.insert(issueComments).values({ companyId: issue.companyId, issueId: issue.id, body: input.reason, ...commentAuthorFields(actor), }); const maxAttempts = targetChannel?.queueConfig?.maxClaimAttempts ?? DEFAULT_MAX_CLAIM_ATTEMPTS; const attemptCount = issue.claimAttemptCount ?? 0; const shouldRequeue = input.requeue !== false && attemptCount < maxAttempts; const now = new Date(); await notifyDeliveryWork(tx, DELIVERY_QUEUES.claimLeaseExpiry, issue.id); const [updated] = await tx .update(issues) .set({ status: shouldRequeue ? "todo" : "blocked", blockedTransitionAt: shouldRequeue ? issue.blockedTransitionAt : now, claimTokenHash: null, claimLeasedAt: null, claimLeaseExpiresAt: null, claimHolderAgentId: null, claimHolderUserId: null, claimHolderProfile: null, updatedAt: now, }) .where(eq(issues.id, issue.id)) .returning(); const actorInfo = activityActorFields(actor); await tx.insert(activityLog).values({ companyId: issue.companyId, ...actorInfo, action: shouldRequeue ? "issue.claim_failed_requeued" : "issue.claim_poison_blocked", entityType: "issue", entityId: updated!.id, details: { reason: input.reason, claimEpoch: Number(updated!.claimEpoch ?? 0), claimAttemptCount: attemptCount, maxAttempts, }, }); const eventsToPublish: BoardEventView[] = []; const failedEvent = await appendBoardEvent(tx, { companyId: issue.companyId, type: "task.failed", channelId: updated!.channelId, channelPath: targetChannel?.path ?? null, issueId: updated!.id, identifier: updated!.identifier ?? updated!.id, actor, payload: { reason: input.reason, claimAttemptCount: attemptCount, requeued: shouldRequeue, }, }); eventsToPublish.push(failedEvent); if (shouldRequeue) { eventsToPublish.push( 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 ?? {}, }, }), ); } else { eventsToPublish.push( await appendBoardEvent(tx, { companyId: issue.companyId, type: "task.lease_poison_blocked", channelId: updated!.channelId, channelPath: targetChannel?.path ?? null, issueId: updated!.id, identifier: updated!.identifier ?? updated!.id, actor, payload: { reason: input.reason, claimAttemptCount: attemptCount, maxAttempts, }, }), ); } const lastCursor = eventsToPublish[eventsToPublish.length - 1]!.cursor; const issueView = await loadHeadlessIssueView(tx, updated!.id, lastCursor); return { events: eventsToPublish, issueView }; }); for (const ev of committed.events) { publishCommittedBoardEvent(ev); } return committed.issueView; } export function createClaimLeaseExpiryWorker(db: Db) { let cachedNextDueMs: number | null = null; async function refreshNextDueAt(): Promise { const result = await db.execute<{ min_due: Date | string | null }>(sql` SELECT MIN(claim_lease_expires_at) AS min_due FROM issues WHERE status = 'in_progress' AND claim_lease_expires_at IS NOT NULL AND claim_token_hash IS NOT NULL `); const raw = result[0]?.min_due ?? null; if (!raw) { cachedNextDueMs = null; return null; } const ms = raw instanceof Date ? raw.getTime() : Date.parse(String(raw)); cachedNextDueMs = Number.isFinite(ms) ? ms : null; return cachedNextDueMs; } async function expireDueClaimLeases(signal?: AbortSignal): Promise { let totalExpired = 0; const batchLimit = 50; while (!signal?.aborted) { const committed = await db.transaction(async (tx) => { const dueResult = await tx.execute<{ id: string }>(sql` SELECT id FROM issues WHERE status = 'in_progress' AND claim_lease_expires_at IS NOT NULL AND claim_token_hash IS NOT NULL AND claim_lease_expires_at <= now() ORDER BY claim_lease_expires_at ASC LIMIT ${batchLimit} FOR UPDATE OF issues SKIP LOCKED `); const dueIds = Array.from(dueResult).map((r) => r.id); if (dueIds.length === 0) { return { expiredCount: 0, events: [] as BoardEventView[] }; } const dueRows = await tx .select() .from(issues) .where(inArray(issues.id, dueIds)); const channelIds = Array.from( new Set( dueRows .map((r) => r.channelId) .filter((id): id is string => Boolean(id)), ), ); const channelRows = channelIds.length > 0 ? await tx .select() .from(channels) .where(inArray(channels.id, channelIds)) : []; const channelMap = new Map(channelRows.map((c) => [c.id, c])); const now = new Date(); const events: BoardEventView[] = []; const systemActor = { principalType: "system" as const, actorProfile: "lease-reconciler", }; for (const row of dueRows) { const ch = row.channelId ? channelMap.get(row.channelId) ?? null : null; const maxAttempts = ch?.queueConfig?.maxClaimAttempts ?? DEFAULT_MAX_CLAIM_ATTEMPTS; const attemptCount = row.claimAttemptCount ?? 0; 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({ status: shouldRequeue ? "todo" : "blocked", blockedTransitionAt: shouldRequeue ? row.blockedTransitionAt : now, claimEpoch: nextEpoch, claimTokenHash: null, claimLeasedAt: null, claimLeaseExpiresAt: null, claimHolderAgentId: null, claimHolderUserId: null, claimHolderProfile: null, updatedAt: now, }) .where(eq(issues.id, row.id)); if (shouldRequeue) { events.push( await appendBoardEvent(tx, { companyId: row.companyId, type: "task.lease_expired_requeued", channelId: row.channelId, channelPath: ch?.path ?? null, issueId: row.id, identifier: row.identifier ?? row.id, actor: systemActor, payload: { claimEpoch: nextEpoch, claimAttemptCount: attemptCount, maxAttempts, }, }), ); events.push( await appendBoardEvent(tx, { companyId: row.companyId, type: "task.ready", channelId: row.channelId, channelPath: ch?.path ?? null, issueId: row.id, identifier: row.identifier ?? row.id, actor: systemActor, payload: { kvLabels: row.kvLabels ?? {}, }, }), ); } else { events.push( await appendBoardEvent(tx, { companyId: row.companyId, type: "task.lease_poison_blocked", channelId: row.channelId, channelPath: ch?.path ?? null, issueId: row.id, identifier: row.identifier ?? row.id, actor: systemActor, payload: { claimEpoch: nextEpoch, claimAttemptCount: attemptCount, maxAttempts, reason: "lease_expired_max_attempts", }, }), ); } } return { expiredCount: dueRows.length, events }; }); for (const ev of committed.events) { publishCommittedBoardEvent(ev); } totalExpired += committed.expiredCount; if (committed.expiredCount < batchLimit) break; } await refreshNextDueAt(); return totalExpired; } return { expireDueClaimLeases, refreshNextDueAt, nextRunAt: () => cachedNextDueMs, deliveryTask: { retryMs: 5_000, coalesceMs: 50, pausePassiveMaintenance: true, run: async (signal: AbortSignal) => { await expireDueClaimLeases(signal); }, hasPending: async (runAllowed = true) => { if (!runAllowed) return false; return cachedNextDueMs !== null && cachedNextDueMs <= Date.now(); }, nextRunAt: () => cachedNextDueMs, nextRunAtOnError: () => cachedNextDueMs, }, }; }