import { EventEmitter } from "node:events"; import type { Request } from "express"; import { and, desc, eq, inArray, ne, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, boardApiKeys, boardEvents, channelAccessMembers, channels, companies, issueLabels, issues, labels, projects, } from "@paperclipai/db"; import { clientScopesSchema, deriveAgentUrlKey, deriveProjectUrlKey, formatEventCursor, isUuidLike, normalizeChannelPath, normalizeIssueIdentifier, type AgentApiKeyScope, type AgentIdentityPolicy, type BoardEventType, type BoardEventView, type ClientScopes, type CommentView, type DeploymentMode, type HeadlessIssueView, type IssuePriority, type IssueScope, type IssueStatus, type LabelFilterExpr, type SchemaBlock, } from "@paperclipai/shared"; import { badRequest, conflict, forbidden, notFound, unauthorized } from "../errors.js"; import { authorizationService, issueReadSqlCondition, type AuthorizationActor, } from "./authorization.js"; import { publishLiveEvent } from "./live-events.js"; import { listIssueDependencyReadinessMap } from "./issues.js"; export type DbOrTx = Db | Parameters[0]>[0]; const boardEventEmitter = new EventEmitter(); boardEventEmitter.setMaxListeners(0); export function subscribeCompanyBoardEvents( companyId: string, listener: (event: BoardEventView) => void, ): () => void { boardEventEmitter.on(companyId, listener); return () => boardEventEmitter.off(companyId, listener); } export function publishCommittedBoardEvent(event: BoardEventView): void { boardEventEmitter.emit(event.companyId, event); publishLiveEvent({ companyId: event.companyId, type: "activity.logged", payload: { boardEventSeq: event.seq, boardEventCursor: event.cursor, boardEventType: event.type, channel: event.channel, issueId: event.issueId, identifier: event.identifier, }, }); } export function resolveCompanyAgentIdentityPolicy( storedPolicy: AgentIdentityPolicy | null | undefined, deploymentMode: DeploymentMode = "local_trusted", ): AgentIdentityPolicy { if (storedPolicy) return storedPolicy; return deploymentMode === "local_trusted" ? "open_local_profiles" : "strict_agent_keys"; } export interface HeadlessActorContext { companyId: string; companyName: string; companyPrefix: string; agentIdentityPolicy: AgentIdentityPolicy; principalType: "local_trusted" | "user" | "agent"; userId: string | null; agentId: string | null; agentName: string | null; agentRole: string | null; actorProfile: string | null; scopes: ClientScopes | null; keyId?: string | null; keyScope?: AgentApiKeyScope | null; isInstanceAdmin: boolean; responsibleUserId: string | null; } function channelMatchesScopePattern(channelPath: string, pattern: string): boolean { const trimmed = pattern.trim().toLowerCase().replace(/^#/, ""); if (trimmed === "*" || trimmed === "**") return true; if (trimmed.endsWith("/*")) { const base = trimmed.slice(0, -2); return channelPath === base || channelPath.startsWith(`${base}/`); } if (trimmed.endsWith("/")) { const base = trimmed.slice(0, -1); return channelPath === base || channelPath.startsWith(`${base}/`); } return channelPath === trimmed; } export function actionMatchesScopePattern(action: string, pattern: string): boolean { const trimmed = pattern.trim().toLowerCase(); if (trimmed === "*") return true; if (trimmed.endsWith("*")) { return action.toLowerCase().startsWith(trimmed.slice(0, -1)); } return action.toLowerCase() === trimmed; } export function channelScopePatternCovers(allowedPattern: string, candidatePattern: string): boolean { const allowed = allowedPattern.trim().toLowerCase().replace(/^#/, ""); const candidate = candidatePattern.trim().toLowerCase().replace(/^#/, ""); if (allowed === "*" || allowed === "**") return true; if (candidate === "*" || candidate === "**") return false; const candidateIsSubtree = candidate.endsWith("/*") || candidate.endsWith("/"); const candidateBase = candidate.replace(/\/\*?$/, ""); if (candidateIsSubtree) { const allowedIsSubtree = allowed.endsWith("/*") || allowed.endsWith("/"); if (!allowedIsSubtree) return false; const allowedBase = allowed.replace(/\/\*?$/, ""); return candidateBase === allowedBase || candidateBase.startsWith(`${allowedBase}/`); } return channelMatchesScopePattern(candidateBase, allowed); } export function actionScopePatternCovers(allowedPattern: string, candidatePattern: string): boolean { const allowed = allowedPattern.trim().toLowerCase(); const candidate = candidatePattern.trim().toLowerCase(); if (allowed === "*") return true; if (candidate === "*") return false; if (candidate.endsWith("*")) { if (!allowed.endsWith("*")) return false; return candidate.slice(0, -1).startsWith(allowed.slice(0, -1)); } return actionMatchesScopePattern(candidate, allowed); } function isReadOnlyHeadlessAction(action?: string): boolean { if (!action) return true; const normalized = action.trim().toLowerCase(); return normalized === "read" || normalized.endsWith(".read"); } function mergeClientScopes( keyScopes: ClientScopes | null, headerScopes: ClientScopes | null, ): ClientScopes | null { if (!keyScopes && !headerScopes) return null; if (!keyScopes) return headerScopes; if (!headerScopes) return keyScopes; const merged: ClientScopes = {}; if (keyScopes.channels && headerScopes.channels) { merged.channels = headerScopes.channels.filter((ch) => keyScopes.channels!.some((allowed) => channelScopePatternCovers(allowed, ch)), ); } else if (keyScopes.channels) { merged.channels = keyScopes.channels; } else if (headerScopes.channels) { merged.channels = headerScopes.channels; } if (keyScopes.actions && headerScopes.actions) { merged.actions = headerScopes.actions.filter((act) => keyScopes.actions!.some((allowed) => actionScopePatternCovers(allowed, act)), ); } else if (keyScopes.actions) { merged.actions = keyScopes.actions; } else if (headerScopes.actions) { merged.actions = headerScopes.actions; } return merged; } export function enforceHeadlessScopes( actor: Pick, check: { action?: string; channelPath?: string }, ): void { if (actor.keyScope && actor.keyScope.kind !== "standard") { throw forbidden( `Scoped '${actor.keyScope.kind}' agent keys cannot access headless channel or queue endpoints`, { code: "scope_denied" }, ); } if (!actor.scopes) return; if (check.action && actor.scopes.actions) { const allowed = actor.scopes.actions.some((pattern) => actionMatchesScopePattern(check.action!, pattern), ); if (!allowed) { throw forbidden(`Caller scopes do not allow action '${check.action}'`, { code: "scope_denied", action: check.action, }); } } if (check.channelPath && actor.scopes.channels) { const normalized = normalizeChannelPath(check.channelPath, { allowSubtreePrefix: true, }).path; const allowed = actor.scopes.channels.some((pattern) => channelMatchesScopePattern(normalized, pattern), ); if (!allowed) { throw forbidden( `Caller scopes do not allow channel '${check.channelPath}'`, { code: "scope_denied", channel: check.channelPath, }, ); } } } export async function resolveHeadlessActor( db: Db, req: Request, companyId: string, opts: { deploymentMode?: DeploymentMode; requiredAction?: string; requiredChannel?: string; } = {}, ): Promise { if (!req.actor || req.actor.type === "none") { throw unauthorized("Authentication required"); } const [company] = await db .select({ id: companies.id, name: companies.name, issuePrefix: companies.issuePrefix, agentIdentityPolicy: companies.agentIdentityPolicy, defaultResponsibleUserId: companies.defaultResponsibleUserId, }) .from(companies) .where(eq(companies.id, companyId)); if (!company) { throw notFound("Company not found"); } const deploymentMode: DeploymentMode = opts.deploymentMode ?? (req.actor.source === "local_implicit" ? "local_trusted" : "authenticated"); const policy = resolveCompanyAgentIdentityPolicy( company.agentIdentityPolicy, deploymentMode, ); const rawProfileHeader = req.header("x-paperclip-actor-profile")?.trim() || null; const rawScopesHeader = req.header("x-paperclip-actor-scopes")?.trim() || null; let headerScopes: ClientScopes | null = null; if (rawScopesHeader) { let parsedJson: unknown; try { parsedJson = JSON.parse(rawScopesHeader); } catch { throw badRequest("Malformed X-Paperclip-Actor-Scopes header JSON"); } const parsed = clientScopesSchema.safeParse(parsedJson); if (!parsed.success) { throw badRequest("Invalid X-Paperclip-Actor-Scopes header"); } headerScopes = parsed.data; } const isReadAction = isReadOnlyHeadlessAction(opts.requiredAction); if (req.actor.type === "agent") { if (req.actor.keyScope && req.actor.keyScope.kind !== "standard") { throw forbidden( `Scoped '${req.actor.keyScope.kind}' agent keys cannot access headless channel or queue endpoints`, { code: "scope_denied" }, ); } const actorAgentId = req.actor.agentId; if (!actorAgentId || req.actor.companyId !== companyId) { throw forbidden("Agent does not belong to this company"); } const localBoardOnBehalf = deploymentMode === "local_trusted" && req.actor.onBehalfOfUserId === "local-board"; if (req.actor.onBehalfOfUserId?.trim() && !localBoardOnBehalf) { const membership = req.actor.onBehalfOfMemberships?.find( (item) => item.companyId === companyId && item.status === "active", ); if (!membership) { throw forbidden("Responsible user is unavailable for this company", { code: "RESPONSIBLE_USER_UNAVAILABLE", }); } if (!isReadAction && membership.membershipRole === "viewer") { throw forbidden("Responsible user is not authorized for write access", { code: "RESPONSIBLE_USER_UNAUTHORIZED", }); } } const [agentRow] = await db .select({ id: agents.id, name: agents.name, role: agents.role, status: agents.status, }) .from(agents) .where(and(eq(agents.id, actorAgentId), eq(agents.companyId, companyId))); if (!agentRow || agentRow.status === "terminated" || agentRow.status === "pending_approval") { throw unauthorized("Authenticated agent record is unavailable"); } const derivedSlug = deriveAgentUrlKey(agentRow.name, agentRow.id); if ( rawProfileHeader && rawProfileHeader.toLowerCase() !== agentRow.name.toLowerCase() && rawProfileHeader.toLowerCase() !== derivedSlug.toLowerCase() ) { throw forbidden( `Authenticated agent '@${agentRow.name}' cannot impersonate profile '${rawProfileHeader}'`, { code: "profile_locked" }, ); } const ctx: HeadlessActorContext = { companyId: company.id, companyName: company.name, companyPrefix: company.issuePrefix, agentIdentityPolicy: policy, principalType: "agent", userId: req.actor.onBehalfOfUserId ?? null, agentId: agentRow.id, agentName: agentRow.name, agentRole: agentRow.role, actorProfile: agentRow.name, scopes: headerScopes, keyId: req.actor.keyId ?? null, keyScope: req.actor.keyScope ?? null, isInstanceAdmin: false, responsibleUserId: req.actor.onBehalfOfUserId ?? company.defaultResponsibleUserId ?? null, }; enforceHeadlessScopes(ctx, { action: opts.requiredAction, channelPath: opts.requiredChannel, }); return ctx; } // Board actor (local_implicit, session, board_key, cloud_tenant, etc.) const isLocalImplicit = req.actor.source === "local_implicit"; if ( !isLocalImplicit && !req.actor.isInstanceAdmin && !(req.actor.companyIds ?? []).includes(companyId) ) { throw forbidden("User does not have access to this company"); } if (!isLocalImplicit && !req.actor.isInstanceAdmin && Array.isArray(req.actor.memberships)) { const membership = req.actor.memberships.find((item) => item.companyId === companyId); if (!membership || membership.status !== "active") { throw forbidden("User does not have active company access"); } if (!isReadAction && membership.membershipRole === "viewer") { throw forbidden("Viewer access is read-only"); } } let keyScopes: ClientScopes | null = req.actor.keyScopes ?? null; let lockedProfile: string | null = req.actor.keyLockedProfile?.trim() || null; if (req.actor.source === "board_key" && req.actor.keyCompanyId && req.actor.keyCompanyId !== companyId) { throw forbidden("Board API key is scoped to another company", { code: "company_scope_denied", }); } if (req.actor.source === "board_key" && req.actor.keyId) { const [keyRow] = await db .select({ companyId: boardApiKeys.companyId, lockedProfile: boardApiKeys.lockedProfile, scopes: boardApiKeys.scopes, }) .from(boardApiKeys) .where(eq(boardApiKeys.id, req.actor.keyId)); if (keyRow?.companyId && keyRow.companyId !== companyId) { throw forbidden("Board API key is scoped to another company", { code: "company_scope_denied", }); } lockedProfile = keyRow?.lockedProfile?.trim() || lockedProfile; keyScopes = keyRow?.scopes ?? keyScopes; } if ( lockedProfile && rawProfileHeader && rawProfileHeader.toLowerCase() !== lockedProfile.toLowerCase() ) { throw forbidden( `Board API key is locked to profile '${lockedProfile}'`, { code: "profile_locked" }, ); } const effectiveProfile = lockedProfile ?? rawProfileHeader; if (effectiveProfile) { if (policy === "strict_agent_keys") { throw forbidden( `Company policy 'strict_agent_keys' requires a registered agent API key instead of ephemeral profile '${effectiveProfile}'`, { code: "agent_key_required", next: [ `paperclipai agent connect ${effectiveProfile}`, `paperclipai agent login --name ${effectiveProfile}`, ], }, ); } const profileLower = effectiveProfile.toLowerCase(); const companyAgents = await db .select({ id: agents.id, name: agents.name, }) .from(agents) .where( and( eq(agents.companyId, companyId), ne(agents.status, "terminated"), ), ); const registeredAgent = companyAgents.find( (a) => a.name.trim().toLowerCase() === profileLower || deriveAgentUrlKey(a.name, a.id).toLowerCase() === profileLower, ); if (registeredAgent) { throw conflict( `Profile '${effectiveProfile}' matches registered agent '@${registeredAgent.name}'. Use that agent's API key instead of an unverified profile header.`, { code: "profile_matches_registered_agent", agentId: registeredAgent.id, agentName: registeredAgent.name, next: [ `paperclipai agent connect ${registeredAgent.name}`, `paperclipai agent login --name ${registeredAgent.name}`, ], }, ); } } const scopes = mergeClientScopes(keyScopes, headerScopes); const ctx: HeadlessActorContext = { companyId: company.id, companyName: company.name, companyPrefix: company.issuePrefix, agentIdentityPolicy: policy, principalType: isLocalImplicit ? "local_trusted" : "user", userId: req.actor.userId ?? null, agentId: null, agentName: null, agentRole: null, actorProfile: effectiveProfile, scopes, isInstanceAdmin: Boolean(req.actor.isInstanceAdmin), responsibleUserId: req.actor.userId && req.actor.userId !== "local-board" ? req.actor.userId : company.defaultResponsibleUserId ?? req.actor.userId ?? null, }; enforceHeadlessScopes(ctx, { action: opts.requiredAction, channelPath: opts.requiredChannel, }); return ctx; } export function escapeSqlLikePattern(value: string): string { return value.replace(/[\\%_]/g, "\\$&"); } export function channelDescendantsCondition( path: string, column: typeof channels.path = channels.path, ): SQL { const pattern = `${escapeSqlLikePattern(path)}/%`; return sql`${column} LIKE ${pattern} ESCAPE '\\'`; } export function channelSubtreeCondition( path: string, column: typeof channels.path = channels.path, ): SQL { return or(eq(column, path), channelDescendantsCondition(path, column)) as SQL; } export async function findInaccessibleChannelIds( dbOrTx: DbOrTx, companyId: string, actor: HeadlessActorContext, companyChannels: Array<{ id: string; companyId: string; path: string; visibility: string; createdByUserId: string | null; createdByAgentId: string | null; }>, ): Promise { if (companyChannels.length === 0) return []; const bypassPrivacy = actor.isInstanceAdmin || actor.principalType === "local_trusted"; const privateChannelIds = !bypassPrivacy ? companyChannels.filter((c) => c.visibility === "private").map((c) => c.id) : []; const memberChannelIds = new Set(); if (privateChannelIds.length > 0 && (actor.agentId || actor.userId)) { const subjectConditions = []; if (actor.agentId) { subjectConditions.push( and( eq(channelAccessMembers.subjectType, "agent"), eq(channelAccessMembers.subjectId, actor.agentId), ), ); } if (actor.userId) { subjectConditions.push( and( eq(channelAccessMembers.subjectType, "user"), eq(channelAccessMembers.subjectId, actor.userId), ), ); } const rows = await dbOrTx .select({ channelId: channelAccessMembers.channelId }) .from(channelAccessMembers) .where( and( eq(channelAccessMembers.companyId, companyId), inArray(channelAccessMembers.channelId, privateChannelIds), or(...subjectConditions), ), ); for (const r of rows) { memberChannelIds.add(r.channelId); } } const inaccessible: string[] = []; for (const ch of companyChannels) { let scopeOk = true; try { enforceHeadlessScopes(actor, { channelPath: ch.path }); } catch { scopeOk = false; } if (!scopeOk) { inaccessible.push(ch.id); continue; } if (ch.visibility !== "private" || bypassPrivacy) continue; const isCreator = (actor.agentId && ch.createdByAgentId === actor.agentId) || (actor.userId && ch.createdByUserId === actor.userId); if (!isCreator && !memberChannelIds.has(ch.id)) { inaccessible.push(ch.id); } } return inaccessible; } export async function canAccessChannel( dbOrTx: DbOrTx, channel: { id: string; companyId: string; visibility: string; createdByUserId: string | null; createdByAgentId: string | null; }, actor: HeadlessActorContext, ): Promise { if (channel.companyId !== actor.companyId) return false; if (channel.visibility !== "private") return true; if (actor.isInstanceAdmin || actor.principalType === "local_trusted") { return true; } if (actor.agentId && channel.createdByAgentId === actor.agentId) return true; if (actor.userId && channel.createdByUserId === actor.userId) return true; const subjectConditions = []; if (actor.agentId) { subjectConditions.push( and( eq(channelAccessMembers.subjectType, "agent"), eq(channelAccessMembers.subjectId, actor.agentId), ), ); } if (actor.userId) { subjectConditions.push( and( eq(channelAccessMembers.subjectType, "user"), eq(channelAccessMembers.subjectId, actor.userId), ), ); } if (subjectConditions.length === 0) return false; const [member] = await dbOrTx .select({ id: channelAccessMembers.id }) .from(channelAccessMembers) .where( and( eq(channelAccessMembers.channelId, channel.id), or(...subjectConditions), ), ) .limit(1); return Boolean(member); } export async function assertCanonicalIssueAccessForActor( dbOrTx: DbOrTx, authActor: AuthorizationActor, issue: { id: string; companyId: string; projectId: string | null; parentId: string | null; assigneeAgentId: string | null; assigneeUserId: string | null; status: string; }, action: "issue:read" | "issue:comment" | "issue:mutate", ): Promise { const access = authorizationService(dbOrTx as Db); const resource = { type: "issue" as const, companyId: issue.companyId, issueId: issue.id, projectId: issue.projectId, parentIssueId: issue.parentId, assigneeAgentId: issue.assigneeAgentId, assigneeUserId: issue.assigneeUserId, status: issue.status, }; const scope = { issueId: issue.id, projectId: issue.projectId, parentIssueId: issue.parentId, assigneeAgentId: issue.assigneeAgentId, assigneeUserId: issue.assigneeUserId, }; const readDecision = await access.decide({ actor: authActor, action: "issue:read", resource, scope, }); if (!readDecision.allowed) { throw notFound("Issue not found"); } if (action !== "issue:read") { const writeDecision = await access.decide({ actor: authActor, action, resource, scope, }); if (!writeDecision.allowed) { throw forbidden(writeDecision.explanation ?? "Forbidden"); } } } export async function assertCanonicalIssueAccess( db: Db, req: Request, issue: { id: string; companyId: string; projectId: string | null; parentId: string | null; assigneeAgentId: string | null; assigneeUserId: string | null; status: string; }, action: "issue:read" | "issue:comment" | "issue:mutate", ): Promise { return assertCanonicalIssueAccessForActor(db, req.actor, issue, action); } export async function resolveHeadlessIssueReadCondition(db: Db, req: Request) { if ( req.actor.type === "agent" && req.actor.keyScope && req.actor.keyScope.kind !== "standard" ) { return sql`false`; } return issueReadSqlCondition(db, req.actor); } export async function assertChannelAccess( dbOrTx: DbOrTx, channel: { id: string; companyId: string; path: string; visibility: string; createdByUserId: string | null; createdByAgentId: string | null; }, actor: HeadlessActorContext, ): Promise { enforceHeadlessScopes(actor, { channelPath: channel.path }); const allowed = await canAccessChannel(dbOrTx, channel, actor); if (!allowed) { throw notFound(`Channel '${channel.path}' not found`); } } export function allowsUnchanneledScope( actor: Pick, ): boolean { const channelScopes = actor.scopes?.channels; if (!channelScopes) return true; return channelScopes.some((pattern) => { const t = pattern.trim().toLowerCase(); return t === "*" || t === "**"; }); } export async function assertIssueChannelScopeAccess( dbOrTx: DbOrTx, issue: { channelId: string | null }, actor: HeadlessActorContext, ): Promise<{ channel: typeof channels.$inferSelect | null; channelPath: string | null }> { if (issue.channelId) { const [ch] = await dbOrTx .select() .from(channels) .where(eq(channels.id, issue.channelId)) .limit(1); if (ch) { await assertChannelAccess(dbOrTx, ch, actor); return { channel: ch, channelPath: ch.path }; } return { channel: null, channelPath: null }; } if (!allowsUnchanneledScope(actor)) { throw forbidden("Caller scopes do not allow accessing unchanneled issues", { code: "scope_denied", }); } return { channel: null, channelPath: null }; } export function buildSqlIssueLabelFilterCondition(expr: LabelFilterExpr): SQL { switch (expr.kind) { case "equals": return sql`${issues.kvLabels}->>${expr.key} = ${expr.value}`; case "in": return sql`${issues.kvLabels}->>${expr.key} IN (${sql.join( expr.values.map((v) => sql`${v}`), sql`, `, )})`; case "exists": return sql`(jsonb_exists(${issues.kvLabels}, ${expr.key}) OR EXISTS ( SELECT 1 FROM ${issueLabels} il INNER JOIN ${labels} l ON l.id = il.label_id WHERE il.issue_id = ${issues.id} AND l.name = ${expr.key} ))`; } } export function buildAuthActorFromHeadless( actor: HeadlessActorContext, ): AuthorizationActor { if (actor.principalType === "local_trusted") { return { type: "board", userId: actor.userId ?? "local-board", source: "local_implicit", isInstanceAdmin: true, }; } if (actor.principalType === "agent" && actor.agentId) { return { type: "agent", agentId: actor.agentId, companyId: actor.companyId, source: "agent_key", ...(actor.keyId ? { keyId: actor.keyId } : {}), ...(actor.keyScope ? { keyScope: actor.keyScope } : {}), ...(actor.userId ? { onBehalfOfUserId: actor.userId } : {}), }; } return { type: "board", userId: actor.userId ?? undefined, companyIds: [actor.companyId], isInstanceAdmin: actor.isInstanceAdmin, ignoreInstanceAdmin: !actor.isInstanceAdmin, source: "session", }; } function toAuthActor( actorOrAuth: HeadlessActorContext | AuthorizationActor, ): AuthorizationActor { return "principalType" in actorOrAuth ? buildAuthActorFromHeadless(actorOrAuth) : actorOrAuth; } export async function assertProjectReadAccess( dbOrTx: DbOrTx, companyId: string, projectId: string, actorOrAuth: HeadlessActorContext | AuthorizationActor, displayRef = projectId, ): Promise { const decision = await authorizationService(dbOrTx as unknown as Db).decide({ actor: toAuthActor(actorOrAuth), action: "project:read", resource: { type: "project", companyId, projectId }, scope: { projectId }, }); if (!decision.allowed) { throw notFound(`Project '${displayRef}' not found`); } } export async function resolveProjectReference( dbOrTx: DbOrTx, companyId: string, projectRef: string | null | undefined, actorOrAuth?: HeadlessActorContext | AuthorizationActor, ): Promise { if (projectRef === undefined || projectRef === null) return null; const trimmed = projectRef.trim(); if (!trimmed) return null; let resolvedId: string; if (isUuidLike(trimmed)) { const [row] = await dbOrTx .select({ id: projects.id }) .from(projects) .where(and(eq(projects.companyId, companyId), eq(projects.id, trimmed))); if (!row) throw notFound(`Project '${trimmed}' not found`); resolvedId = row.id; } else { const companyProjects = await dbOrTx .select({ id: projects.id, name: projects.name }) .from(projects) .where(eq(projects.companyId, companyId)); const lower = trimmed.toLowerCase(); const match = companyProjects.find( (p) => deriveProjectUrlKey(p.name, p.id).toLowerCase() === lower, ) ?? companyProjects.find((p) => p.name.trim().toLowerCase() === lower); if (!match) { throw notFound(`Project '${trimmed}' not found`); } resolvedId = match.id; } if (actorOrAuth) { await assertProjectReadAccess(dbOrTx, companyId, resolvedId, actorOrAuth, trimmed); } return resolvedId; } export function buildNextIssueCounterSql( companyId: string, count: number, ): SQL { return sql`greatest(${companies.issueCounter}, coalesce((select max(${issues.issueNumber}) from ${issues} where ${issues.companyId} = ${companyId}), 0)) + ${count}`; } async function queryIssueByIdOrIdentifier( idOrIdentifier: string, expectedCompanyId: string | undefined, runQuery: (whereClause: SQL | undefined) => Promise, ): Promise { const trimmed = idOrIdentifier.trim(); let row: T | undefined; if (isUuidLike(trimmed)) { [row] = await runQuery( expectedCompanyId ? and(eq(issues.id, trimmed), eq(issues.companyId, expectedCompanyId)) : eq(issues.id, trimmed), ); } else { const normalizedUpper = ( normalizeIssueIdentifier(trimmed) ?? trimmed ).toUpperCase(); [row] = await runQuery( expectedCompanyId ? and( eq(issues.identifier, normalizedUpper), eq(issues.companyId, expectedCompanyId), ) : eq(issues.identifier, normalizedUpper), ); if (!row) { [row] = await runQuery( expectedCompanyId ? and( sql`upper(${issues.identifier}) = ${normalizedUpper}`, eq(issues.companyId, expectedCompanyId), ) : sql`upper(${issues.identifier}) = ${normalizedUpper}`, ); } } if (!row) { throw notFound(`Issue '${idOrIdentifier}' not found`); } return row; } export async function resolveIssueByIdOrIdentifier( dbOrTx: DbOrTx, idOrIdentifier: string, expectedCompanyId?: string, ) { return queryIssueByIdOrIdentifier( idOrIdentifier, expectedCompanyId, (whereClause) => dbOrTx.select().from(issues).where(whereClause).limit(1), ); } const issueCommentTargetSelection = { id: issues.id, identifier: issues.identifier, companyId: issues.companyId, channelId: issues.channelId, projectId: issues.projectId, parentId: issues.parentId, assigneeAgentId: issues.assigneeAgentId, assigneeUserId: issues.assigneeUserId, status: issues.status, scope: issues.scope, conversationAgentId: issues.conversationAgentId, }; export async function resolveIssueCommentTarget( dbOrTx: DbOrTx, idOrIdentifier: string, expectedCompanyId?: string, ) { return queryIssueByIdOrIdentifier( idOrIdentifier, expectedCompanyId, (whereClause) => dbOrTx .select(issueCommentTargetSelection) .from(issues) .where(whereClause) .limit(1), ); } function isPlainObjectRecord(val: unknown): val is Record { return Boolean(val) && typeof val === "object" && !Array.isArray(val); } export async function appendBoardEvent( dbOrTx: DbOrTx, input: { companyId: string; type: BoardEventType; channelId?: string | null; channelPath?: string | null; issueId?: string | null; identifier?: string | null; actor: Pick< HeadlessActorContext, "principalType" | "userId" | "agentId" | "agentName" | "actorProfile" > | { principalType: "system"; userId?: null; agentId?: null; agentName?: null; actorProfile?: string | null; }; payload?: Record; }, ): Promise { const actorType: "user" | "agent" | "system" = input.actor.principalType === "agent" ? "agent" : input.actor.principalType === "system" ? "system" : "user"; const actorId = input.actor.principalType === "agent" ? input.actor.agentId ?? null : input.actor.principalType === "system" ? "system" : input.actor.userId ?? null; const actorName = input.actor.principalType === "agent" ? input.actor.agentName ?? null : null; const actorProfile = input.actor.actorProfile ?? null; const payloadObj = input.payload ?? {}; const payloadJson = JSON.stringify(payloadObj); const issueIdVal = input.issueId ?? null; const hasExplicitIssueKv = isPlainObjectRecord(payloadObj.kvLabels) || (input.type === "labels.changed" && isPlainObjectRecord(payloadObj.current)) || ((input.type === "thread.posted" || input.type === "task.created" || input.type === "task.ready") && isPlainObjectRecord(payloadObj.labels)); const hasExplicitTagLabels = Array.isArray(payloadObj.tagLabels); let payloadExpr: SQL = sql`${payloadJson}::jsonb`; if (issueIdVal && (!hasExplicitIssueKv || !hasExplicitTagLabels)) { const kvSelectSql = sql`coalesce((select ${issues.kvLabels} from ${issues} where ${issues.id} = ${issueIdVal}::uuid and ${issues.companyId} = ${input.companyId}::uuid), '{}'::jsonb)`; const tagSelectSql = sql`coalesce((select jsonb_agg(${labels.name} order by ${labels.name}) from ${issueLabels} inner join ${labels} on ${labels.id} = ${issueLabels.labelId} where ${issueLabels.issueId} = ${issueIdVal}::uuid and ${issueLabels.companyId} = ${input.companyId}::uuid), '[]'::jsonb)`; if (!hasExplicitIssueKv && !hasExplicitTagLabels) { payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}, 'tagLabels', ${tagSelectSql}))`; } else if (!hasExplicitIssueKv) { payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}))`; } else { payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('tagLabels', ${tagSelectSql}))`; } } const [inserted] = await dbOrTx.execute<{ seq: string | number; created_at: Date | string; payload: Record | string; }>(sql` INSERT INTO ${boardEvents} ( ${sql.raw(boardEvents.companyId.name)}, ${sql.raw(boardEvents.eventType.name)}, ${sql.raw(boardEvents.channelId.name)}, ${sql.raw(boardEvents.channelPath.name)}, ${sql.raw(boardEvents.issueId.name)}, ${sql.raw(boardEvents.identifier.name)}, ${sql.raw(boardEvents.actorType.name)}, ${sql.raw(boardEvents.actorId.name)}, ${sql.raw(boardEvents.actorName.name)}, ${sql.raw(boardEvents.actorProfile.name)}, ${sql.raw(boardEvents.payload.name)} ) SELECT ${input.companyId}::uuid, ${input.type}, ${input.channelId ?? null}::uuid, ${input.channelPath ?? null}, ${issueIdVal}::uuid, ${input.identifier ?? null}, ${actorType}, ${actorId}, ${actorName}, ${actorProfile}, ${payloadExpr} FROM ( SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${input.companyId})) ) AS _lock RETURNING ${sql.raw(boardEvents.seq.name)}, ${sql.raw(boardEvents.createdAt.name)}, ${sql.raw(boardEvents.payload.name)} `); const seq = Number(inserted!.seq); const createdAtIso = inserted!.created_at instanceof Date ? inserted!.created_at.toISOString() : new Date(inserted!.created_at).toISOString(); const persistedPayload: Record = typeof inserted!.payload === "string" ? (JSON.parse(inserted!.payload) as Record) : isPlainObjectRecord(inserted!.payload) ? inserted!.payload : payloadObj; return { cursor: formatEventCursor(seq), seq, type: input.type, companyId: input.companyId, channel: input.channelPath ?? null, issueId: issueIdVal, identifier: input.identifier ?? null, actor: { type: actorType, id: actorId, name: actorName, profile: actorProfile, }, payload: persistedPayload, createdAt: createdAtIso, }; } export async function getLatestCompanyEventCursor( dbOrTx: DbOrTx, companyId: string, ): Promise { const [latest] = await dbOrTx .select({ seq: boardEvents.seq }) .from(boardEvents) .where(eq(boardEvents.companyId, companyId)) .orderBy(desc(boardEvents.seq)) .limit(1); return formatEventCursor(latest ? Number(latest.seq) : 0); } export async function loadHeadlessIssueViews( dbOrTx: DbOrTx, issueRows: Array, explicitCursor?: string, ): Promise { if (issueRows.length === 0) return []; const issueIds = issueRows.map((r) => r.id); const channelIds = Array.from( new Set(issueRows.map((r) => r.channelId).filter((x): x is string => Boolean(x))), ); const companyId = issueRows[0]!.companyId; const [channelRows, labelRows, readinessMap, latestEvents, fallbackCursor] = await Promise.all([ channelIds.length > 0 ? dbOrTx .select({ id: channels.id, path: channels.path }) .from(channels) .where(inArray(channels.id, channelIds)) : Promise.resolve([]), dbOrTx .select({ issueId: issueLabels.issueId, name: labels.name, }) .from(issueLabels) .innerJoin(labels, eq(issueLabels.labelId, labels.id)) .where(inArray(issueLabels.issueId, issueIds)), listIssueDependencyReadinessMap(dbOrTx as unknown as Db, companyId, issueIds, false), explicitCursor ? Promise.resolve([]) : dbOrTx .select({ issueId: boardEvents.issueId, maxSeq: sql`max(${boardEvents.seq})`, }) .from(boardEvents) .where( and( eq(boardEvents.companyId, companyId), inArray(boardEvents.issueId, issueIds), ), ) .groupBy(boardEvents.issueId), explicitCursor ? Promise.resolve(explicitCursor) : getLatestCompanyEventCursor(dbOrTx, companyId), ]); const channelMap = new Map(channelRows.map((c) => [c.id, c.path])); const tagMap = new Map(); for (const row of labelRows) { const arr = tagMap.get(row.issueId) ?? []; arr.push(row.name); tagMap.set(row.issueId, arr); } const blockerMap = new Map(); for (const [issueId, readiness] of readinessMap) { if (readiness.unresolvedBlockerIssueIds.length > 0) { blockerMap.set(issueId, readiness.unresolvedBlockerIssueIds); } } const seqMap = new Map(); for (const row of latestEvents) { if (row.issueId && row.maxSeq != null) { seqMap.set(row.issueId, Number(row.maxSeq)); } } return issueRows.map((row) => { const channelPath = row.channelId ? channelMap.get(row.channelId) ?? null : null; const issueSeq = seqMap.get(row.id); const cursor = explicitCursor ?? (issueSeq !== undefined ? formatEventCursor(issueSeq) : fallbackCursor); return mapHeadlessIssueRowToView(row, { channelPath, tagLabels: tagMap.get(row.id) ?? [], blockedByIssueIds: blockerMap.get(row.id) ?? [], cursor, }); }); } function mapHeadlessIssueRowToView( row: { id: string; companyId: string; identifier: string | null; title: string; description: string | null; status: string; scope: string; priority: string; channelId: string | null; projectId: string | null; assigneeAgentId: string | null; assigneeUserId: string | null; createdByProfile: string | null; kvLabels: Record | null; schemaBlocks: SchemaBlock[] | null; resultSchemaRef: string | null; claimEpoch?: number | null; claimHolderProfile?: string | null; claimHolderAgentId?: string | null; claimHolderUserId?: string | null; claimLeaseExpiresAt?: Date | null; claimAttemptCount?: number | null; createdAt: Date; updatedAt: Date; }, extra: { channelPath: string | null; tagLabels: string[]; blockedByIssueIds: string[]; cursor: string; }, ): HeadlessIssueView { const isPassivePost = row.scope === "channel" && row.status === "backlog" && !row.assigneeAgentId && !row.assigneeUserId; return { id: row.id, companyId: row.companyId, identifier: row.identifier ?? row.id, title: row.title, description: row.description ?? null, status: row.status as IssueStatus, scope: row.scope as IssueScope, priority: row.priority as IssuePriority, channelId: row.channelId ?? null, channel: extra.channelPath, projectId: row.projectId ?? null, assigneeAgentId: row.assigneeAgentId ?? null, assigneeUserId: row.assigneeUserId ?? null, actorProfile: row.createdByProfile ?? null, kvLabels: (row.kvLabels ?? {}) as Record, tagLabels: extra.tagLabels, blocks: (row.schemaBlocks ?? []) as SchemaBlock[], resultSchemaRef: row.resultSchemaRef ?? null, blockedByIssueIds: extra.blockedByIssueIds, isPassivePost, claimEpoch: Number(row.claimEpoch ?? 0), claimHolderProfile: row.claimHolderProfile ?? null, claimHolderAgentId: row.claimHolderAgentId ?? null, claimHolderUserId: row.claimHolderUserId ?? null, claimLeaseExpiresAt: row.claimLeaseExpiresAt ? row.claimLeaseExpiresAt.toISOString() : null, claimAttemptCount: row.claimAttemptCount ?? 0, cursor: extra.cursor, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString(), }; } export function serializeCreatedHeadlessIssueView(input: { id: string; companyId: string; identifier: string; title: string; description: string | null; status: IssueStatus; scope: IssueScope; priority: IssuePriority; channelId: string | null; channel: string | null; projectId: string | null; assigneeAgentId: string | null; assigneeUserId: string | null; actorProfile: string | null; kvLabels: Record; tagLabels: string[]; blocks: SchemaBlock[]; resultSchemaRef: string | null; blockedByIssueIds: string[]; cursor: string; createdAt: Date; updatedAt: Date; }): HeadlessIssueView { return mapHeadlessIssueRowToView( { id: input.id, companyId: input.companyId, identifier: input.identifier, title: input.title, description: input.description, status: input.status, scope: input.scope, priority: input.priority, channelId: input.channelId, projectId: input.projectId, assigneeAgentId: input.assigneeAgentId, assigneeUserId: input.assigneeUserId, createdByProfile: input.actorProfile, kvLabels: input.kvLabels, schemaBlocks: input.blocks, resultSchemaRef: input.resultSchemaRef, createdAt: input.createdAt, updatedAt: input.updatedAt, }, { channelPath: input.channel, tagLabels: input.tagLabels, blockedByIssueIds: input.blockedByIssueIds, cursor: input.cursor, }, ); } export async function loadHeadlessIssueView( dbOrTx: DbOrTx, issueId: string, explicitCursor?: string, ): Promise { const [row] = await dbOrTx.select().from(issues).where(eq(issues.id, issueId)); if (!row) throw notFound("Issue not found"); const views = await loadHeadlessIssueViews(dbOrTx, [row], explicitCursor); return views[0]!; } export function serializeCommentView( row: { id: string; issueId: string; body: string; authorType?: string | null; authorUserId?: string | null; authorAgentId?: string | null; actorProfile?: string | null; kvLabels?: Record | null; schemaBlocks?: SchemaBlock[] | null; blocks?: SchemaBlock[] | null; noSync?: boolean | null; createdAt: Date; }, identifier: string, cursor = "evt_0", ): CommentView { const authorType: "user" | "agent" | "system" = row.authorType === "agent" || row.authorAgentId ? "agent" : row.authorType === "system" ? "system" : "user"; return { id: row.id, issueId: row.issueId, identifier, body: row.body, authorType, authorUserId: row.authorUserId ?? null, authorAgentId: row.authorAgentId ?? null, actorProfile: row.actorProfile ?? null, kvLabels: (row.kvLabels ?? {}) as Record, blocks: (row.schemaBlocks ?? row.blocks ?? []) as SchemaBlock[], internal: Boolean(row.noSync), cursor, createdAt: row.createdAt.toISOString(), }; }