import { and, eq, inArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { channels, companies, issues, primeDatabaseWorkTransactionId, projects, } from "@paperclipai/db"; import type { BoardEventView, HeadlessIssueView, IssuePriority, IssueScope, IssueStatus, SchemaBlock, } from "@paperclipai/shared"; import { conflict, notFound } from "../errors.js"; import { logger } from "../middleware/logger.js"; import { createActivityDetailsRedactor, logActivitiesBatch, publishActivity, type ActivityPublication, type LogActivityInput, } from "./activity-log.js"; import { createAdaptiveCompanyBatcher, type PendingEntry, } from "./adaptive-company-batcher.js"; import { forEachPostCommitSafely } from "./headless-board-events-write.js"; import { attachTagLabelsToIssues, collectChannelAndAncestorPaths, ensureChannel, resolveAssigneeAgent, validateChannelPathWriteFromMap, } from "./headless-channel-write-helpers.js"; import { appendBoardEvents, assertChannelAccess, assertProjectReadAccess, buildNextIssueCounterSql, loadHeadlessIssueView, mintTimeOrderedUuid, publishCommittedBoardEvent, resolveProjectReference, serializeCreatedHeadlessIssueView, touchChannelsLastActivity, type AppendBoardEventInput, type DbOrTx, type HeadlessActorContext, } from "./headless-common.js"; export interface CoalescedChannelPostInput { actor: HeadlessActorContext; channelPath: string; requestedStatus: IssueStatus; resolvedTitle: string; resolvedDescription: string | null; projectIdInput: string | null | undefined; board: boolean; priority: IssuePriority; forInput: string | undefined; assigneeAgentIdInput: string | null | undefined; mergedKvLabels: Record; tagLabelsInput: string[]; validatedBlocks: SchemaBlock[]; resolvedResultSchemaRef: string | null; originId?: string | null; requestHash?: string | null; } export interface CoalescedChannelPostResult { issue: HeadlessIssueView; created: boolean; } interface PrevalidatedPostItem { entry: PendingEntry; existingChannel: typeof channels.$inferSelect | null; explicitProjectId: string | null | undefined; assigneeAgentId: string | null; } async function prevalidateChannelPostItem( tx: DbOrTx, companyId: string, entry: PendingEntry, channelByPath: ReadonlyMap, ): Promise { const { item } = entry; const { existingChannel } = await validateChannelPathWriteFromMap( tx, item.actor, item.channelPath, channelByPath, ); let explicitProjectId: string | null | undefined = undefined; if (item.projectIdInput !== undefined) { explicitProjectId = item.projectIdInput === null ? null : await resolveProjectReference( tx, companyId, item.projectIdInput, item.actor, ); } else if (existingChannel?.defaultProjectId) { await assertProjectReadAccess( tx, companyId, existingChannel.defaultProjectId, item.actor, ); } const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, { assigneeAgentId: item.assigneeAgentIdInput, for: item.forInput, }); return { entry, existingChannel, explicitProjectId, assigneeAgentId, }; } async function runCoalescedChannelPostsBatch( db: Db, companyId: string, entries: Array>, allowFallback: boolean, ): Promise { const publications: ActivityPublication[] = []; const committedEvents: BoardEventView[] = []; const rejectedEntries: Array<{ entry: PendingEntry; error: unknown; }> = []; let resolvedOutcomes: Array<{ entry: PendingEntry; result: CoalescedChannelPostResult; }>; try { const activityRedactor = await createActivityDetailsRedactor(db); resolvedOutcomes = await db.transaction(async (tx) => { if (entries.length === 1 && entries[0]!.item.originId) { const singleItem = entries[0]!.item; const originId = singleItem.originId!; await tx.execute( sql`select pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${"post:" + originId}))`, ); const [existingInTx] = await tx .select({ id: issues.id, channelId: issues.channelId, originFingerprint: issues.originFingerprint, }) .from(issues) .where( and( eq(issues.companyId, companyId), eq(issues.originKind, "manual"), eq(issues.originId, originId), ), ) .limit(1); if (existingInTx) { if (existingInTx.channelId) { const [ch] = await tx .select() .from(channels) .where(eq(channels.id, existingInTx.channelId)) .limit(1); if (ch) await assertChannelAccess(tx, ch, singleItem.actor); } if ( existingInTx.originFingerprint && existingInTx.originFingerprint !== singleItem.requestHash ) { throw conflict( "Idempotency key has already been used for a different payload", { error: "idempotency_conflict", code: "idempotency_conflict", }, ); } const view = await loadHeadlessIssueView(tx, existingInTx.id); return [{ entry: entries[0]!, result: { issue: view, created: false } }]; } } const lookupPaths = collectChannelAndAncestorPaths( entries.map((e) => e.item.channelPath), ); const existingRows = lookupPaths.length === 0 ? [] : lookupPaths.length === 1 ? await tx .select() .from(channels) .where( and( eq(channels.companyId, companyId), eq(channels.path, lookupPaths[0]!), ), ) .limit(1) : await tx .select() .from(channels) .where( and( eq(channels.companyId, companyId), inArray(channels.path, lookupPaths), ), ); const channelByPath = new Map(); for (const row of existingRows) { channelByPath.set(row.path, row); } const prevalidated: PrevalidatedPostItem[] = []; for (const entry of entries) { try { prevalidated.push( await prevalidateChannelPostItem(tx, companyId, entry, channelByPath), ); } catch (err) { rejectedEntries.push({ entry, error: err }); } } if (prevalidated.length === 0) { return []; } const missingPaths = Array.from( new Set( prevalidated .filter((p) => !p.existingChannel) .map((p) => p.entry.item.channelPath), ), ).sort(); for (const missingPath of missingPaths) { const candidates = prevalidated.filter( (p) => !p.existingChannel && p.entry.item.channelPath === missingPath, ); for (const candidate of candidates) { if (channelByPath.has(missingPath)) break; try { const createdCh = await ensureChannel( tx, companyId, candidate.entry.item.actor, { path: missingPath }, { publications }, ); channelByPath.set(missingPath, createdCh); } catch (err) { rejectedEntries.push({ entry: candidate.entry, error: err }); } } } const rejectedEntrySet = new Set(rejectedEntries.map((r) => r.entry)); const activeItems: Array<{ entry: PendingEntry; channel: typeof channels.$inferSelect; projectId: string | null; assigneeAgentId: string | null; }> = []; for (const p of prevalidated) { if (rejectedEntrySet.has(p.entry)) continue; try { const channel = p.existingChannel ?? channelByPath.get(p.entry.item.channelPath); if (!channel) { throw notFound(`Channel '${p.entry.item.channelPath}' not found`); } if (!p.existingChannel && channel.visibility === "private") { await assertChannelAccess(tx, channel, p.entry.item.actor); } const projectId = p.explicitProjectId !== undefined ? p.explicitProjectId : (channel.defaultProjectId ?? null); if (!p.existingChannel && p.explicitProjectId === undefined && projectId) { await assertProjectReadAccess(tx, companyId, projectId, p.entry.item.actor); } activeItems.push({ entry: p.entry, channel, projectId, assigneeAgentId: p.assigneeAgentId, }); } catch (err) { rejectedEntries.push({ entry: p.entry, error: err }); } } if (activeItems.length === 0) { return []; } const projectIdsToCheck = Array.from( new Set( activeItems .filter((x) => x.channel.visibility !== "private" && x.projectId !== null) .map((x) => x.projectId!), ), ); const privateProjectIds = new Set(); if (projectIdsToCheck.length > 0) { const projRows = await tx .select({ id: projects.id, visibility: projects.visibility }) .from(projects) .where( and( eq(projects.companyId, companyId), inArray(projects.id, projectIdsToCheck), ), ); for (const r of projRows) { if (r.visibility === "private") { privateProjectIds.add(r.id); } } } const nextCounterExpr = buildNextIssueCounterSql(companyId, activeItems.length); const [companyRow] = await tx .update(companies) .set({ issueCounter: nextCounterExpr, updatedAt: sql`now()`, }) .where(eq(companies.id, companyId)) .returning({ issueCounter: companies.issueCounter, issuePrefix: companies.issuePrefix, xid: sql`pg_current_xact_id()::text`, }); const now = new Date(); const nowMs = now.getTime(); if (companyRow?.xid) { primeDatabaseWorkTransactionId(tx, companyRow.xid); } const firstIssueNumber = companyRow!.issueCounter - activeItems.length + 1; const preparedIssues = activeItems.map((active, idx) => { const { item } = active.entry; const issueNumber = firstIssueNumber + idx; const identifier = `${companyRow!.issuePrefix}-${issueNumber}`; const newIssueId = mintTimeOrderedUuid(nowMs); const scope: IssueScope = item.board ? "board" : "channel"; const issueVisibility: "open" | "private" = active.channel.visibility === "private" || (active.projectId !== null && privateProjectIds.has(active.projectId)) ? "private" : "open"; const privacyRootIssueId = issueVisibility === "private" ? newIssueId : null; return { ...active, newIssueId, issueNumber, identifier, createdAt: now, scope, issueVisibility, privacyRootIssueId, }; }); await tx.insert(issues).values( preparedIssues.map((pi) => { const { item } = pi.entry; return { id: pi.newIssueId, companyId, projectId: pi.projectId, channelId: pi.channel.id, visibility: pi.issueVisibility, privacyRootIssueId: pi.privacyRootIssueId, title: item.resolvedTitle, description: item.resolvedDescription, status: item.requestedStatus, scope: pi.scope, priority: item.priority, assigneeAgentId: pi.assigneeAgentId, createdByAgentId: item.actor.agentId, createdByUserId: item.actor.agentId ? null : item.actor.userId, createdByProfile: item.actor.actorProfile, responsibleUserId: item.actor.responsibleUserId, kvLabels: item.mergedKvLabels, schemaBlocks: item.validatedBlocks, resultSchemaRef: item.resolvedResultSchemaRef, issueNumber: pi.issueNumber, identifier: pi.identifier, originKind: "manual" as const, originId: item.originId ?? null, originFingerprint: item.requestHash ?? "default", createdAt: pi.createdAt, updatedAt: pi.createdAt, }; }), ); await touchChannelsLastActivity( tx, preparedIssues.map((pi) => pi.channel.id), now, ); const attachedTagsByIssueId = await attachTagLabelsToIssues( tx, companyId, preparedIssues.map((pi) => ({ issueId: pi.newIssueId, tagNames: pi.entry.item.tagLabelsInput, })), ); const activityInputs: LogActivityInput[] = preparedIssues.map((pi) => { const { item } = pi.entry; return { companyId, actorType: item.actor.principalType === "agent" ? "agent" : "user", actorId: item.actor.principalType === "agent" ? item.actor.agentId! : (item.actor.userId ?? "local-board"), agentId: item.actor.agentId, issueId: pi.newIssueId, responsibleUserIdOverride: item.actor.responsibleUserId, action: item.requestedStatus === "todo" ? "issue.created" : "channel.post_created", entityType: "issue", entityId: pi.newIssueId, details: { identifier: pi.identifier, channel: pi.channel.path, status: item.requestedStatus, scope: pi.scope, }, }; }); await logActivitiesBatch(tx as unknown as Db, activityInputs, publications, { redactor: activityRedactor, }); const eventInputs: AppendBoardEventInput[] = []; const lastEventIndexByItem: number[] = []; for (const pi of preparedIssues) { const { item } = pi.entry; const attachedTagNames = attachedTagsByIssueId.get(pi.newIssueId) ?? []; const isReadyTask = item.requestedStatus === "todo" && pi.assigneeAgentId === null; eventInputs.push({ companyId, type: item.requestedStatus === "todo" ? "task.created" : "thread.posted", channelId: pi.channel.id, channelPath: pi.channel.path, issueId: pi.newIssueId, identifier: pi.identifier, actor: item.actor, payload: { title: item.resolvedTitle, ...(item.resolvedDescription ? { description: item.resolvedDescription.slice(0, 4000) } : {}), blocks: item.validatedBlocks, labels: item.mergedKvLabels, kvLabels: item.mergedKvLabels, tagLabels: attachedTagNames, ...(isReadyTask ? { ready: true } : {}), }, }); if (isReadyTask) { eventInputs.push({ companyId, type: "task.ready", channelId: pi.channel.id, channelPath: pi.channel.path, issueId: pi.newIssueId, identifier: pi.identifier, actor: item.actor, payload: { kvLabels: item.mergedKvLabels, tagLabels: attachedTagNames, }, }); } lastEventIndexByItem.push(eventInputs.length - 1); } const appendedEvents = await appendBoardEvents(tx, eventInputs); committedEvents.push(...appendedEvents); return preparedIssues.map((pi, idx) => { const { item } = pi.entry; const attachedTagNames = attachedTagsByIssueId.get(pi.newIssueId) ?? []; const lastCursor = appendedEvents[lastEventIndexByItem[idx]!]!.cursor; const view = serializeCreatedHeadlessIssueView({ id: pi.newIssueId, companyId, identifier: pi.identifier, title: item.resolvedTitle, description: item.resolvedDescription, status: item.requestedStatus, scope: pi.scope, priority: item.priority, channelId: pi.channel.id, channel: pi.channel.path, projectId: pi.projectId, assigneeAgentId: pi.assigneeAgentId, assigneeUserId: null, actorProfile: item.actor.actorProfile, kvLabels: item.mergedKvLabels, tagLabels: attachedTagNames, blocks: item.validatedBlocks, resultSchemaRef: item.resolvedResultSchemaRef, blockedByIssueIds: [], cursor: lastCursor, createdAt: pi.createdAt, updatedAt: pi.createdAt, }); return { entry: pi.entry, result: { issue: view, created: true } }; }); }); } catch (err) { if (allowFallback && entries.length > 1) { for (const single of entries) { await runCoalescedChannelPostsBatch(db, companyId, [single], false); } return; } for (const rej of rejectedEntries) { rej.entry.reject(rej.error); } const unsettled = new Set( entries.filter((e) => !rejectedEntries.some((r) => r.entry === e)), ); for (const entry of unsettled) { entry.reject(err); } return; } for (const rej of rejectedEntries) { rej.entry.reject(rej.error); } forEachPostCommitSafely(publications, publishActivity, (pub, err) => { logger.warn({ err, companyId: pub.companyId }, "post-commit activity listener failed"); }); forEachPostCommitSafely(committedEvents, publishCommittedBoardEvent, (evt, err) => { logger.warn({ err, companyId: evt.companyId, seq: evt.seq }, "post-commit board event listener failed"); }); for (const outcome of resolvedOutcomes) { outcome.entry.resolve(outcome.result); } } export const executeCoalescedChannelPost = createAdaptiveCompanyBatcher< CoalescedChannelPostInput, CoalescedChannelPostResult >(runCoalescedChannelPostsBatch, { backpressureMessage: "Too many concurrent channel posts queued for this company; retry shortly", }); export function executeImmediateChannelPost( db: Db, companyId: string, item: CoalescedChannelPostInput, ): Promise { return new Promise((resolve, reject) => { void runCoalescedChannelPostsBatch( db, companyId, [{ item, resolve, reject }], false, ); }); }