diff --git a/server/src/__tests__/activity-log-responsible-user.test.ts b/server/src/__tests__/activity-log-responsible-user.test.ts index eb4466bb68d..6ccbe580d1a 100644 --- a/server/src/__tests__/activity-log-responsible-user.test.ts +++ b/server/src/__tests__/activity-log-responsible-user.test.ts @@ -15,6 +15,7 @@ import { } from "@paperclipai/db"; import { createActivityDetailsRedactor, + logActivitiesBatch, logActivity, persistActivity, resolveResponsibleUserIdForActivity, @@ -329,4 +330,128 @@ describeEmbeddedPostgres("logActivity responsible-user stamping", () => { }); } }); + + it("persists multi-row batches via logActivitiesBatch with redaction, attribution, and mcpEvents notifications", async () => { + const companyId = randomUUID(); + const issueA = randomUUID(); + const issueB = randomUUID(); + const currentUsername = os.userInfo().username; + + await db.insert(companies).values({ + id: companyId, + name: "BatchActivityCo", + issuePrefix: `B${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, + defaultResponsibleUserId: "batch-default-user", + requireBoardApprovalForNewAgents: false, + }); + await db.insert(issues).values([ + { + id: issueA, + companyId, + title: "Batch issue A", + status: "todo", + scope: "channel", + responsibleUserId: "owner-a", + }, + { + id: issueB, + companyId, + title: "Batch issue B", + status: "todo", + scope: "channel", + responsibleUserId: "owner-b", + }, + ]); + + await instanceSettingsService(db).updateGeneral({ + censorUsernameInLogs: true, + }); + try { + const redactor = await createActivityDetailsRedactor(db); + const publications: ActivityPublication[] = []; + const settledHints: string[] = []; + const unsubscribe = subscribeDatabaseWork( + db, + DELIVERY_QUEUES.mcpEvents, + (event, hints) => { + if (event === "settled" && hints) { + settledHints.push(...hints); + } + }, + ); + + try { + await db.transaction(async (tx) => { + const nestedTxSpy = vi.spyOn(tx, "transaction"); + const inserted = await logActivitiesBatch( + tx as unknown as Db, + [ + { + companyId, + actorType: "user", + actorId: "owner-a", + action: "channel.post_created", + entityType: "issue", + entityId: issueA, + issueId: issueA, + responsibleUserIdOverride: "owner-a", + details: { + identifier: "BAT-1", + path: `/Users/${currentUsername}/alpha`, + }, + }, + { + companyId, + actorType: "user", + actorId: "owner-b", + action: "issue.created", + entityType: "issue", + entityId: issueB, + issueId: issueB, + responsibleUserIdOverride: "owner-b", + details: { + identifier: "BAT-2", + path: `/Users/${currentUsername}/beta`, + }, + }, + ], + publications, + { redactor }, + ); + expect(inserted).toHaveLength(2); + expect(nestedTxSpy).not.toHaveBeenCalled(); + }); + } finally { + unsubscribe(); + } + + expect(settledHints).toContain(`task:${issueA}`); + expect(settledHints).toContain(`task:${issueB}`); + expect(publications).toHaveLength(2); + expect(publications.map((p) => p.payload.entityId)).toEqual([issueA, issueB]); + + const stored = await db + .select({ + entityId: activityLog.entityId, + responsibleUserId: activityLog.responsibleUserId, + details: activityLog.details, + }) + .from(activityLog) + .where(eq(activityLog.companyId, companyId)); + expect(stored).toHaveLength(2); + const responsibleByEntity = new Map( + stored.map((row) => [row.entityId, row.responsibleUserId]), + ); + expect(responsibleByEntity.get(issueA)).toBe("owner-a"); + expect(responsibleByEntity.get(issueB)).toBe("owner-b"); + for (const row of stored) { + const serialized = JSON.stringify(row.details ?? {}); + expect(serialized).not.toContain(currentUsername); + } + } finally { + await instanceSettingsService(db).updateGeneral({ + censorUsernameInLogs: false, + }); + } + }); }); diff --git a/server/src/__tests__/adaptive-company-batcher.test.ts b/server/src/__tests__/adaptive-company-batcher.test.ts new file mode 100644 index 00000000000..58511872ca6 --- /dev/null +++ b/server/src/__tests__/adaptive-company-batcher.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from "vitest"; +import type { Db } from "@paperclipai/db"; +import { isUuidLike } from "@paperclipai/shared"; +import { + createAdaptiveCompanyBatcher, + type PendingEntry, +} from "../services/adaptive-company-batcher.js"; +import { mintTimeOrderedUuid } from "../services/headless-board-events-write.js"; + +describe("adaptive-company-batcher", () => { + it("dispatches idle arrivals immediately with allowFallback=false and coalesces concurrent arrivals with allowFallback=true", async () => { + const fakeDb = {} as Db; + const observedBatches: Array<{ ids: string[]; allowFallback: boolean }> = []; + let releaseFirst!: () => void; + const firstGate = new Promise((resolve) => { + releaseFirst = resolve; + }); + + const batcher = createAdaptiveCompanyBatcher<{ id: string }, string>( + async ( + _db, + _companyId, + entries: Array>, + allowFallback, + ) => { + observedBatches.push({ + ids: entries.map((e) => e.item.id), + allowFallback, + }); + if (entries[0]?.item.id === "idle-first") { + await firstGate; + } + for (const entry of entries) { + entry.resolve(`done:${entry.item.id}`); + } + }, + ); + + const pFirst = batcher(fakeDb, "co-1", { id: "idle-first" }); + const pSecond = batcher(fakeDb, "co-1", { id: "queued-a" }); + const pThird = batcher(fakeDb, "co-1", { id: "queued-b" }); + releaseFirst(); + + await expect(Promise.all([pFirst, pSecond, pThird])).resolves.toEqual([ + "done:idle-first", + "done:queued-a", + "done:queued-b", + ]); + expect(observedBatches).toEqual([ + { ids: ["idle-first"], allowFallback: false }, + { ids: ["queued-a", "queued-b"], allowFallback: true }, + ]); + }); + + it("enforces maxPending queue capacity with 429 backpressure and recovers after drain", async () => { + const fakeDb = {} as Db; + let releaseFirstBatch!: () => void; + const gate = new Promise((resolve) => { + releaseFirstBatch = resolve; + }); + + const batcher = createAdaptiveCompanyBatcher( + async (_db, _companyId, entries) => { + await gate; + for (const entry of entries) { + entry.resolve(entry.item * 2); + } + }, + { maxBatchSize: 2, maxPending: 3 }, + ); + + const p1 = batcher(fakeDb, "co-cap", 1); + const p2 = batcher(fakeDb, "co-cap", 2); + const p3 = batcher(fakeDb, "co-cap", 3); + const p4 = batcher(fakeDb, "co-cap", 4); + const overflow = batcher(fakeDb, "co-cap", 5); + + await expect(overflow).rejects.toMatchObject({ + status: 429, + details: { code: "write_queue_full" }, + }); + + releaseFirstBatch(); + await expect(Promise.all([p1, p2, p3, p4])).resolves.toEqual([2, 4, 6, 8]); + await expect(batcher(fakeDb, "co-cap", 10)).resolves.toBe(20); + }); + + it("mints RFC-valid ordered UUIDs within a single wall-clock millisecond and under stale-input interleaving", () => { + const fixedWallMs = Date.parse("2099-01-01T00:00:00.000Z"); + const sameMsIds = Array.from({ length: 128 }, () => mintTimeOrderedUuid(fixedWallMs)); + const nextMsId = mintTimeOrderedUuid(fixedWallMs + 1); + const staleInterleavedId = mintTimeOrderedUuid(fixedWallMs); + const resumedNextMsId = mintTimeOrderedUuid(fixedWallMs + 1); + + for (const id of [ + ...sameMsIds, + nextMsId, + staleInterleavedId, + resumedNextMsId, + ]) { + expect(isUuidLike(id)).toBe(true); + } + + for (let i = 1; i < sameMsIds.length; i += 1) { + expect(sameMsIds[i]! > sameMsIds[i - 1]!).toBe(true); + } + expect(nextMsId > sameMsIds[sameMsIds.length - 1]!).toBe(true); + expect(staleInterleavedId > nextMsId).toBe(true); + expect(resumedNextMsId > staleInterleavedId).toBe(true); + }); +}); diff --git a/server/src/__tests__/headless-channels-schemas-batch.test.ts b/server/src/__tests__/headless-channels-schemas-batch.test.ts index 24345ac07be..443bf6c9a81 100644 --- a/server/src/__tests__/headless-channels-schemas-batch.test.ts +++ b/server/src/__tests__/headless-channels-schemas-batch.test.ts @@ -6,9 +6,13 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { agents, authUsers, + boardEvents, + channelAccessMembers, + channels, companies, companyMemberships, createDb, + issueComments, issueRelations, issues, projects, @@ -18,7 +22,14 @@ import { actorMiddleware } from "../middleware/auth.js"; import { errorHandler } from "../middleware/error-handler.js"; import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js"; import { issueRoutes } from "../routes/issues.js"; -import { resolveHeadlessActor } from "../services/headless-common.js"; +import { + mintTimeOrderedUuid, + resolveHeadlessActor, + subscribeCompanyBoardEvents, + touchChannelsLastActivity, +} from "../services/headless-common.js"; +import { executeCoalescedHeadlessComment } from "../services/headless-comment-group-commit.js"; +import { executeCoalescedChannelPost } from "../services/headless-post-group-commit.js"; import { issueService } from "../services/issues.js"; import { getEmbeddedPostgresTestSupport, @@ -1492,4 +1503,676 @@ describeEmbeddedPostgres("headless channels, schemas, CAS labels, and batch DAG" status: 409, }); }); + + it("11. coalesces concurrent channel posts and thread replies with gapless PAP-N identifiers, per-item error isolation, and debounced channel activity", async () => { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "authenticated", + resolveSession: async (req) => { + const uid = req.header("x-test-user-id"); + if (!uid) return null; + return { + session: { id: `sess-${uid}`, userId: uid }, + user: { id: uid, name: uid, email: `${uid}@example.test` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + app.use(errorHandler); + + await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "general" }) + .expect(201); + + const vaultRes = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "vault", visibility: "private" }) + .expect(201); + + const sharedVaultRes = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "shared-vault", visibility: "private" }) + .expect(201); + await db.insert(channelAccessMembers).values({ + companyId, + channelId: sharedVaultRes.body.id as string, + subjectType: "user", + subjectId: peerUserId, + }); + + const archivedRes = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "legacy/archived" }) + .expect(201); + await db + .update(channels) + .set({ archivedAt: new Date() }) + .where(eq(channels.id, archivedRes.body.id as string)); + + const [lockedProj] = await db + .insert(projects) + .values({ companyId, name: "Secret Project", visibility: "private" }) + .returning(); + + const postBurst = [ + ...Array.from({ length: 5 }, (_, idx) => + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "general", text: `General burst ${idx}` }), + ), + ...Array.from({ length: 3 }, (_, idx) => + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "burst/auto-sub", + status: "todo", + title: `Burst task ${idx}`, + labels: { lane: "fast" }, + tagLabels: ["burst-tag-b", "burst-tag-a"], + }), + ), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "vault", text: "Authorized private post" }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "general", + text: "Idempotent sibling post", + idempotencyKey: "burst-idem-key-1", + }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "shared-vault/sub", text: "Owner creates private child" }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", peerUserId) + .send({ channel: "shared-vault/sub", text: "Peer races on private child" }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", peerUserId) + .send({ channel: "vault", text: "Unauthorized private post" }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "legacy/archived", text: "Post to archived channel" }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", peerUserId) + .send({ + channel: "general", + text: "Post with inaccessible project", + projectId: lockedProj!.id, + }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "general", + status: "todo", + title: "Unknown assignee task", + for: "missing-agent-handle", + }), + ]; + + const burstResponses = await Promise.all(postBurst); + const generalBurstRes = burstResponses.slice(0, 5); + const autoSubBurstRes = burstResponses.slice(5, 8); + const validVaultRes = burstResponses[8]!; + const validIdemRes = burstResponses[9]!; + const ownerChildRes = burstResponses[10]!; + const peerChildRes = burstResponses[11]!; + const unauthVaultRes = burstResponses[12]!; + const archivedPostRes = burstResponses[13]!; + const inaccessibleProjRes = burstResponses[14]!; + const unknownAssigneeRes = burstResponses[15]!; + + for (const res of generalBurstRes) { + expect(res.status).toBe(201); + } + for (const res of autoSubBurstRes) { + expect(res.status).toBe(201); + } + expect(validVaultRes.status).toBe(201); + expect(validIdemRes.status).toBe(201); + expect([ownerChildRes.status, peerChildRes.status].sort()).toEqual([201, 404]); + expect(unauthVaultRes.status).toBe(404); + expect(archivedPostRes.status).toBe(404); + expect(inaccessibleProjRes.status).toBe(404); + expect(unknownAssigneeRes.status).toBe(404); + + const createdPosts = burstResponses.filter((r) => r.status === 201); + expect(createdPosts).toHaveLength(11); + + const [companyRow] = await db + .select({ issuePrefix: companies.issuePrefix, issueCounter: companies.issueCounter }) + .from(companies) + .where(eq(companies.id, companyId)); + const orderedCreatedPosts = [...createdPosts].sort( + (a, b) => + Number(String(a.body.identifier).split("-").pop()) - + Number(String(b.body.identifier).split("-").pop()), + ); + const mintedNumbers = orderedCreatedPosts.map((r) => + Number(String(r.body.identifier).split("-").pop()), + ); + + expect(mintedNumbers).toEqual(Array.from({ length: 11 }, (_, idx) => idx + 1)); + expect(companyRow!.issueCounter).toBe(11); + + const postBoundMs = Date.now(); + for (const created of orderedCreatedPosts) { + expect(Date.parse(created.body.createdAt as string)).toBeLessThanOrEqual(postBoundMs); + } + + const generalThreadsRes = await request(app) + .get(`/api/companies/${companyId}/channels/threads`) + .set("x-test-user-id", ownerUserId) + .query({ channel: "general" }) + .expect(200); + const generalItems = generalThreadsRes.body.items as Array<{ + id: string; + identifier: string; + createdAt: string; + }>; + expect(generalItems).toHaveLength(6); + const generalIssueNumbers = generalItems.map((t) => + Number(String(t.identifier).split("-").pop()), + ); + for (let i = 1; i < generalIssueNumbers.length; i += 1) { + expect(generalIssueNumbers[i]!).toBeLessThan(generalIssueNumbers[i - 1]!); + } + + const oldestGeneralPost = generalItems[generalItems.length - 1]!; + const afterOldestGeneralRes = await request(app) + .get(`/api/companies/${companyId}/channels/threads`) + .set("x-test-user-id", ownerUserId) + .query({ channel: "general", after: oldestGeneralPost.id }) + .expect(200); + expect(afterOldestGeneralRes.body.items).toHaveLength(5); + + const anchorThread = autoSubBurstRes[0]!; + expect(anchorThread.body.tagLabels).toEqual(["burst-tag-a", "burst-tag-b"]); + expect(anchorThread.body.kvLabels).toEqual({ lane: "fast" }); + + const [autoSubChannel] = await db + .select() + .from(channels) + .where(and(eq(channels.companyId, companyId), eq(channels.path, "burst/auto-sub"))); + const controlledBase = new Date("2099-01-01T00:00:00.000Z"); + await db + .update(channels) + .set({ lastActivityAt: controlledBase }) + .where(eq(channels.id, autoSubChannel!.id)); + + await touchChannelsLastActivity( + db, + [autoSubChannel!.id], + new Date("2099-01-01T00:00:00.100Z"), + ); + const [withinDebounceRow] = await db + .select({ lastActivityAt: channels.lastActivityAt }) + .from(channels) + .where(eq(channels.id, autoSubChannel!.id)); + expect(withinDebounceRow!.lastActivityAt.toISOString()).toBe( + "2099-01-01T00:00:00.000Z", + ); + + await touchChannelsLastActivity( + db, + [autoSubChannel!.id], + new Date("2099-01-01T00:00:00.300Z"), + ); + const [afterDebounceRow] = await db + .select({ lastActivityAt: channels.lastActivityAt }) + .from(channels) + .where(eq(channels.id, autoSubChannel!.id)); + expect(afterDebounceRow!.lastActivityAt.toISOString()).toBe( + "2099-01-01T00:00:00.300Z", + ); + + const staleTimestamp = new Date("2000-01-01T00:00:00.000Z"); + await db + .update(channels) + .set({ lastActivityAt: staleTimestamp }) + .where(eq(channels.id, autoSubChannel!.id)); + + const replyBurst = await Promise.all( + Array.from({ length: 12 }, (_, idx) => + request(app) + .post(`/api/issues/${anchorThread.body.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .send({ + text: `Concurrent reply ${idx}`, + labels: { seq_hint: String(idx) }, + }), + ), + ); + for (const r of replyBurst) { + expect(r.status).toBe(201); + } + const replyIds = new Set(replyBurst.map((r) => r.body.id as string)); + const replyCursors = new Set(replyBurst.map((r) => r.body.cursor as string)); + expect(replyIds.size).toBe(12); + expect(replyCursors.size).toBe(12); + + const repliesSortedBySeq = [...replyBurst].sort( + (a, b) => + Number(String(a.body.cursor).replace("evt_", "")) - + Number(String(b.body.cursor).replace("evt_", "")), + ); + const replyBoundMs = Date.now(); + for (const r of repliesSortedBySeq) { + expect(Date.parse(r.body.createdAt as string)).toBeLessThanOrEqual(replyBoundMs); + } + for (let i = 1; i < repliesSortedBySeq.length; i += 1) { + const prevTime = Date.parse(repliesSortedBySeq[i - 1]!.body.createdAt as string); + const currTime = Date.parse(repliesSortedBySeq[i]!.body.createdAt as string); + expect(currTime).toBeGreaterThanOrEqual(prevTime); + if (currTime === prevTime) { + expect(String(repliesSortedBySeq[i]!.body.id) > String(repliesSortedBySeq[i - 1]!.body.id)).toBe(true); + } + } + + const latestBurstReply = repliesSortedBySeq[repliesSortedBySeq.length - 1]!; + const serializedAfterValid = await request(app) + .post(`/api/issues/${anchorThread.body.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .send({ + text: "Serialized reply after coalesced burst", + after: latestBurstReply.body.id, + }) + .expect(201); + expect(serializedAfterValid.body.identifier).toBe(anchorThread.body.identifier); + + const serializedAfterStale = await request(app) + .post(`/api/issues/${anchorThread.body.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .send({ + text: "Stale reply reusing pre-serialized cursor", + after: latestBurstReply.body.id, + }) + .expect(409); + expect(serializedAfterStale.body.code).toBe("stale_reply_cursor"); + expect(serializedAfterStale.body.details.latestCommentId).toBe( + serializedAfterValid.body.id, + ); + + const threadDetailRes = await request(app) + .get(`/api/issues/${anchorThread.body.identifier}`) + .set("x-test-user-id", ownerUserId) + .query({ view: "thread" }) + .expect(200); + const orderedThreadCommentIds = ( + threadDetailRes.body.comments as Array<{ id: string }> + ).map((c) => c.id); + expect(orderedThreadCommentIds).toEqual([ + ...repliesSortedBySeq.map((r) => r.body.id as string), + serializedAfterValid.body.id as string, + ]); + + const [afterFirstReplyBurst] = await db + .select({ lastActivityAt: channels.lastActivityAt }) + .from(channels) + .where(eq(channels.id, autoSubChannel!.id)); + expect(afterFirstReplyBurst!.lastActivityAt.getTime()).toBeGreaterThan( + staleTimestamp.getTime(), + ); + + const futurePinnedActivity = new Date("2099-06-01T00:00:00.000Z"); + await db + .update(channels) + .set({ lastActivityAt: futurePinnedActivity }) + .where(eq(channels.id, autoSubChannel!.id)); + + const immediateFollowup = await request(app) + .post(`/api/issues/${anchorThread.body.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .send({ text: "Immediate debounced followup" }) + .expect(201); + expect(immediateFollowup.body.identifier).toBe(anchorThread.body.identifier); + + const [afterSkippedTouch] = await db + .select({ lastActivityAt: channels.lastActivityAt }) + .from(channels) + .where(eq(channels.id, autoSubChannel!.id)); + expect(afterSkippedTouch!.lastActivityAt.toISOString()).toBe( + futurePinnedActivity.toISOString(), + ); + + const observedByHealthySubscriber: string[] = []; + const unsubThrowing = subscribeCompanyBoardEvents(companyId, () => { + throw new Error("simulated post-commit subscriber crash"); + }); + const unsubHealthy = subscribeCompanyBoardEvents(companyId, (evt) => { + observedByHealthySubscriber.push(evt.type); + }); + + try { + const [postWithThrowingSub1, postWithThrowingSub2] = await Promise.all([ + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "general", text: "No-dup post 1" }), + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ channel: "general", text: "No-dup post 2" }), + ]); + expect(postWithThrowingSub1.status).toBe(201); + expect(postWithThrowingSub2.status).toBe(201); + + const [replyWithThrowingSub1, replyWithThrowingSub2] = await Promise.all([ + request(app) + .post(`/api/issues/${anchorThread.body.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .send({ text: "No-dup reply 1" }), + request(app) + .post(`/api/issues/${anchorThread.body.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .send({ text: "No-dup reply 2" }), + ]); + expect(replyWithThrowingSub1.status).toBe(201); + expect(replyWithThrowingSub2.status).toBe(201); + } finally { + unsubThrowing(); + unsubHealthy(); + } + + expect(observedByHealthySubscriber).toEqual([ + "thread.posted", + "thread.posted", + "comment.posted", + "comment.posted", + ]); + + const totalIssuesInCompany = await db + .select({ id: issues.id }) + .from(issues) + .where(eq(issues.companyId, companyId)); + expect(totalIssuesInCompany).toHaveLength(13); + + const totalCommentsOnAnchor = await db + .select({ id: issueComments.id }) + .from(issueComments) + .where(eq(issueComments.issueId, anchorThread.body.id as string)); + expect(totalCommentsOnAnchor).toHaveLength(16); + + const storedEvents = await db + .select({ + seq: boardEvents.seq, + eventType: boardEvents.eventType, + issueId: boardEvents.issueId, + payload: boardEvents.payload, + }) + .from(boardEvents) + .where(eq(boardEvents.companyId, companyId)) + .orderBy(boardEvents.seq); + const seqs = storedEvents.map((e) => Number(e.seq)); + for (let i = 1; i < seqs.length; i += 1) { + expect(seqs[i]!).toBeGreaterThan(seqs[i - 1]!); + } + + const commentEventsForAnchor = storedEvents.filter( + (e) => e.eventType === "comment.posted" && e.issueId === anchorThread.body.id, + ); + expect(commentEventsForAnchor).toHaveLength(16); + for (const evt of commentEventsForAnchor) { + const payload = evt.payload as Record; + expect(payload.kvLabels).toEqual({ lane: "fast" }); + expect(payload.tagLabels).toEqual(["burst-tag-a", "burst-tag-b"]); + } + expect(vaultRes.body.visibility).toBe("private"); + }); + + it("12. replays solo items on real database insert failure and orders coalesced batches waiting behind serialized replies", async () => { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "authenticated", + resolveSession: async (req) => { + const uid = req.header("x-test-user-id"); + if (!uid) return null; + return { + session: { id: `sess-${uid}`, userId: uid }, + user: { id: uid, name: uid, email: `${uid}@example.test` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + app.use(errorHandler); + + const generalRes = await request(app) + .post(`/api/companies/${companyId}/channels`) + .set("x-test-user-id", ownerUserId) + .send({ path: "general" }) + .expect(201); + const generalChannelId = generalRes.body.id as string; + + const actor = await resolveHeadlessActor( + db, + { + actor: { + type: "board", + userId: ownerUserId, + source: "session", + companyIds: [companyId], + isInstanceAdmin: false, + }, + header: () => undefined, + } as any, + companyId, + { deploymentMode: "authenticated", requiredAction: "post" }, + ); + + const makePostInput = (title: string) => ({ + actor, + channelPath: "general", + requestedStatus: "backlog" as const, + resolvedTitle: title, + resolvedDescription: null, + projectIdInput: undefined, + board: false, + priority: "medium" as const, + forInput: undefined, + assigneeAgentIdInput: undefined, + mergedKvLabels: {}, + tagLabelsInput: [], + validatedBlocks: [], + resolvedResultSchemaRef: null, + }); + + const postWarmup = executeCoalescedChannelPost( + db, + companyId, + makePostInput("Warmup post"), + ); + const postValidA = executeCoalescedChannelPost( + db, + companyId, + makePostInput("Fallback post A"), + ); + const postNulByte = executeCoalescedChannelPost( + db, + companyId, + makePostInput("Invalid\u0000post"), + ); + const postValidB = executeCoalescedChannelPost( + db, + companyId, + makePostInput("Fallback post B"), + ); + + const [pWarmup, pA, pBad, pB] = await Promise.allSettled([ + postWarmup, + postValidA, + postNulByte, + postValidB, + ]); + expect(pWarmup.status).toBe("fulfilled"); + expect(pA.status).toBe("fulfilled"); + expect(pBad.status).toBe("rejected"); + expect(pB.status).toBe("fulfilled"); + + if ( + pWarmup.status !== "fulfilled" || + pA.status !== "fulfilled" || + pB.status !== "fulfilled" + ) { + throw new Error("Expected valid sibling posts to succeed via solo fallback"); + } + + const postNumbers = [pWarmup.value, pA.value, pB.value] + .map((r) => Number(String(r.issue.identifier).split("-").pop())) + .sort((a, b) => a - b); + expect(postNumbers).toEqual([1, 2, 3]); + + const targetIssue = { + id: pWarmup.value.issue.id, + identifier: pWarmup.value.issue.identifier, + companyId, + channelId: generalChannelId, + kvLabels: {}, + }; + const makeCommentInput = (bodyText: string) => ({ + actor, + targetIssue, + channelPath: "general", + authorUserId: ownerUserId, + bodyText, + mergedKvLabels: {}, + validatedBlocks: [], + internal: false, + }); + + const replyWarmup = executeCoalescedHeadlessComment( + db, + companyId, + makeCommentInput("Warmup reply"), + ); + const replyValidA = executeCoalescedHeadlessComment( + db, + companyId, + makeCommentInput("Fallback reply A"), + ); + const replyNulByte = executeCoalescedHeadlessComment( + db, + companyId, + makeCommentInput("Invalid\u0000reply"), + ); + const replyValidB = executeCoalescedHeadlessComment( + db, + companyId, + makeCommentInput("Fallback reply B"), + ); + + const [cWarmup, cA, cBad, cB] = await Promise.allSettled([ + replyWarmup, + replyValidA, + replyNulByte, + replyValidB, + ]); + expect(cWarmup.status).toBe("fulfilled"); + expect(cA.status).toBe("fulfilled"); + expect(cBad.status).toBe("rejected"); + expect(cB.status).toBe("fulfilled"); + + let notifyLocked!: () => void; + const lockedReady = new Promise((resolve) => { + notifyLocked = resolve; + }); + let releaseSerializedLock!: () => void; + const releaseGate = new Promise((resolve) => { + releaseSerializedLock = resolve; + }); + + const serializedTxPromise = db.transaction(async (tx) => { + await tx + .select({ id: issues.id }) + .from(issues) + .where(eq(issues.id, targetIssue.id)) + .for("update"); + notifyLocked(); + await releaseGate; + const now = new Date(); + const [inserted] = await tx + .insert(issueComments) + .values({ + id: mintTimeOrderedUuid(now.getTime()), + companyId, + issueId: targetIssue.id, + authorUserId: ownerUserId, + authorType: "user", + body: "Serialized reply holding FOR UPDATE first", + kvLabels: {}, + schemaBlocks: [], + noSync: false, + createdAt: now, + updatedAt: now, + }) + .returning({ + id: issueComments.id, + createdAt: issueComments.createdAt, + }); + await tx + .update(issues) + .set({ updatedAt: now }) + .where(eq(issues.id, targetIssue.id)); + return inserted!; + }); + + await lockedReady; + const waitingBatchPromises = [ + executeCoalescedHeadlessComment(db, companyId, makeCommentInput("Waiting batch 1")), + executeCoalescedHeadlessComment(db, companyId, makeCommentInput("Waiting batch 2")), + ]; + await new Promise((r) => setTimeout(r, 25)); + releaseSerializedLock(); + + const serializedInserted = await serializedTxPromise; + const waitingResults = await Promise.all(waitingBatchPromises); + + for (const wr of waitingResults) { + const waitMs = Date.parse(wr.comment.createdAt); + const serMs = serializedInserted.createdAt.getTime(); + expect(waitMs).toBeGreaterThanOrEqual(serMs); + if (waitMs === serMs) { + expect(wr.comment.id > serializedInserted.id).toBe(true); + } + } + + const staleCheckAfterWait = await request(app) + .post(`/api/issues/${targetIssue.identifier}/comments`) + .set("x-test-user-id", ownerUserId) + .send({ + text: "Should detect waiting batch that committed after serialized reply", + after: serializedInserted.id, + }) + .expect(409); + expect(staleCheckAfterWait.body.code).toBe("stale_reply_cursor"); + expect(staleCheckAfterWait.body.details.latestCommentId).toBe( + waitingResults[waitingResults.length - 1]!.comment.id, + ); + }); }); diff --git a/server/src/routes/headless-channels-schemas.ts b/server/src/routes/headless-channels-schemas.ts index a0aced7c6d1..9aa9e81b3c3 100644 --- a/server/src/routes/headless-channels-schemas.ts +++ b/server/src/routes/headless-channels-schemas.ts @@ -90,6 +90,7 @@ import { getLatestCompanyEventCursor, loadHeadlessIssueView, loadHeadlessIssueViews, + mintTimeOrderedUuid, publishCommittedBoardEvent, resolveHeadlessActor, resolveHeadlessIssueReadCondition, @@ -97,7 +98,9 @@ import { resolveIssueCommentTarget, resolveProjectReference, serializeCommentView, + touchChannelsLastActivity, } from "../services/headless-common.js"; +import { executeCoalescedHeadlessComment } from "../services/headless-comment-group-commit.js"; import { createBatchIssuesPlan, mutateIssueKvLabels, @@ -677,11 +680,31 @@ export function headlessChannelsSchemasRoutes( const authorUserId = actor.agentId ? null : (actor.userId ?? "local-board"); const identifier = targetIssue.identifier ?? targetIssue.id; + const needsSerializedThreadCheck = + Boolean(clientRequestId) || afterCursor !== undefined; + + if (!needsSerializedThreadCheck) { + const coalesced = await executeCoalescedHeadlessComment( + db, + targetIssue.companyId, + { + actor, + targetIssue, + channelPath, + authorUserId, + bodyText, + mergedKvLabels, + validatedBlocks, + internal: Boolean(b.internal), + }, + ); + res.status(coalesced.created ? 201 : 200).json(coalesced.comment); + return; + } + const activityRedactor = await createActivityDetailsRedactor(db); const publications: ActivityPublication[] = []; let committedEvent: BoardEventView | null = null; - const needsSerializedThreadCheck = - Boolean(clientRequestId) || afterCursor !== undefined; const txResult = await db.transaction(async (tx) => { if (needsSerializedThreadCheck) { @@ -751,6 +774,7 @@ export function headlessChannelsSchemasRoutes( const [inserted] = await tx .insert(issueComments) .values({ + id: mintTimeOrderedUuid(now.getTime()), companyId: targetIssue.companyId, issueId: targetIssue.id, authorAgentId: actor.agentId, @@ -789,12 +813,7 @@ export function headlessChannelsSchemasRoutes( .set({ updatedAt: now }) .where(eq(issues.id, targetIssue.id)); - if (targetIssue.channelId) { - await tx - .update(channels) - .set({ lastActivityAt: now, updatedAt: now }) - .where(eq(channels.id, targetIssue.channelId)); - } + await touchChannelsLastActivity(tx, [targetIssue.channelId], now); await logActivity( tx as unknown as Db, diff --git a/server/src/services/activity-log.ts b/server/src/services/activity-log.ts index 3a28c259d37..b1748c32205 100644 --- a/server/src/services/activity-log.ts +++ b/server/src/services/activity-log.ts @@ -180,11 +180,10 @@ export function publishActivity(publication: ActivityPublication) { } finally { finish(); } } -export async function persistActivity( +async function prepareActivityRow( db: Db, input: LogActivityInput, - receipt?: { id: string }, - options?: PersistActivityOptions, + redactor?: ActivityDetailsRedactor, ) { const rawDetails = input.authorization ? { @@ -193,35 +192,33 @@ export async function persistActivity( ...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}), } : (input.details ?? null); - const redactedDetails = options?.redactor - ? options.redactor(rawDetails) + const redactedDetails = redactor + ? redactor(rawDetails) : await redactActivityDetails(db, rawDetails); const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input); - const insert = (runner: Db) => runner.insert(activityLog).values({ - ...(receipt ? { id: receipt.id } : {}), - companyId: input.companyId, - actorType: input.actorType, - actorId: input.actorId, - action: input.action, - entityType: input.entityType, - entityId: input.entityId, - agentId: input.agentId ?? null, - runId: input.runId ?? null, - responsibleUserId, - details: redactedDetails, - }).returning({ id: activityLog.id }); - const insertIssueActivity = async (runner: Db) => { - await notifyDeliveryWork(runner, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`); - if (input.runId && input.action === "issue.updated" && ["done", "cancelled"].includes(String(input.details?.status))) - await notifyActiveRunSilence(runner, { companyId: input.companyId, runId: input.runId }); - return insert(runner); - }; - const [activity] = input.entityType === "issue" - ? (is(db, PgTransaction) - ? await insertIssueActivity(db) - : await db.transaction(async tx => insertIssueActivity(tx as unknown as Db))) - : await insert(db); + return { input, redactedDetails, responsibleUserId }; +} +async function notifyIssueActivitySideEffects(runner: Db, input: LogActivityInput) { + if (input.entityType !== "issue") return; + await notifyDeliveryWork(runner, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`); + if ( + input.runId && + input.action === "issue.updated" && + ["done", "cancelled"].includes(String(input.details?.status)) + ) { + await notifyActiveRunSilence(runner, { + companyId: input.companyId, + runId: input.runId, + }); + } +} + +function buildActivityPublication( + input: LogActivityInput, + redactedDetails: Record | null, + responsibleUserId: string | null, +): ActivityPublication { const payload = { issueId: input.issueId ?? (input.entityType === "issue" ? input.entityId : null), actorType: input.actorType, @@ -253,14 +250,67 @@ export async function persistActivity( }, } : null; + return { + companyId: input.companyId, + payload, + pluginEvent, + }; +} + +function buildActivityLogRow( + prepared: Awaited>, + receipt?: { id: string }, +) { + const { input, redactedDetails, responsibleUserId } = prepared; + return { + ...(receipt ? { id: receipt.id } : {}), + companyId: input.companyId, + actorType: input.actorType, + actorId: input.actorId, + action: input.action, + entityType: input.entityType, + entityId: input.entityId, + agentId: input.agentId ?? null, + runId: input.runId ?? null, + responsibleUserId, + details: redactedDetails, + }; +} + +export async function persistActivity( + db: Db, + input: LogActivityInput, + receipt?: { id: string }, + options?: PersistActivityOptions, +) { + const prepared = await prepareActivityRow( + db, + input, + options?.redactor, + ); + const insert = (runner: Db) => + runner + .insert(activityLog) + .values(buildActivityLogRow(prepared, receipt)) + .returning({ id: activityLog.id }); + const insertIssueActivity = async (runner: Db) => { + await notifyIssueActivitySideEffects(runner, input); + return insert(runner); + }; + const [activity] = + input.entityType === "issue" + ? is(db, PgTransaction) + ? await insertIssueActivity(db) + : await db.transaction(async (tx) => insertIssueActivity(tx as unknown as Db)) + : await insert(db); return { activity, - publication: { - companyId: input.companyId, - payload, - pluginEvent, - } satisfies ActivityPublication, + publication: buildActivityPublication( + input, + prepared.redactedDetails, + prepared.responsibleUserId, + ), }; } @@ -278,3 +328,52 @@ export async function logActivity( } return activity; } + +export async function logActivitiesBatch( + db: Db, + inputs: LogActivityInput[], + postCommitPublications?: ActivityPublication[], + options?: PersistActivityOptions, +) { + if (inputs.length === 0) return []; + if (inputs.length === 1) { + const single = await logActivity(db, inputs[0]!, postCommitPublications, options); + return single ? [single] : []; + } + + const redactor = options?.redactor ?? (await createActivityDetailsRedactor(db)); + const preparedRows = await Promise.all( + inputs.map((input) => prepareActivityRow(db, input, redactor)), + ); + + const insertBatch = async (runner: Db) => { + for (const { input } of preparedRows) { + await notifyIssueActivitySideEffects(runner, input); + } + return runner + .insert(activityLog) + .values(preparedRows.map((prepared) => buildActivityLogRow(prepared))) + .returning({ id: activityLog.id }); + }; + + const hasIssueEntity = preparedRows.some(({ input }) => input.entityType === "issue"); + const insertedActivities = + hasIssueEntity && !is(db, PgTransaction) + ? await db.transaction(async (tx) => insertBatch(tx as unknown as Db)) + : await insertBatch(db); + + for (const { input, redactedDetails, responsibleUserId } of preparedRows) { + const publication = buildActivityPublication( + input, + redactedDetails, + responsibleUserId, + ); + if (postCommitPublications) { + postCommitPublications.push(publication); + } else { + publishActivity(publication); + } + } + + return insertedActivities; +} diff --git a/server/src/services/adaptive-company-batcher.ts b/server/src/services/adaptive-company-batcher.ts new file mode 100644 index 00000000000..a5dc19d1ba6 --- /dev/null +++ b/server/src/services/adaptive-company-batcher.ts @@ -0,0 +1,92 @@ +import type { Db } from "@paperclipai/db"; +import { tooManyRequests } from "../errors.js"; + +export const MAX_COALESCED_BATCH_SIZE = 64; +export const MAX_PENDING_PER_COMPANY = 1024; + +export interface PendingEntry { + item: TItem; + resolve: (value: TResult) => void; + reject: (reason: unknown) => void; +} + +export interface AdaptiveBatcherOptions { + maxBatchSize?: number; + maxPending?: number; + backpressureMessage?: string; +} + +interface CompanyBatchQueue { + inFlight: boolean; + pending: Array>; +} + +export function createAdaptiveCompanyBatcher( + runBatch: ( + db: Db, + companyId: string, + entries: Array>, + allowFallback: boolean, + ) => Promise, + options?: AdaptiveBatcherOptions, +) { + const maxBatchSize = Math.max(1, options?.maxBatchSize ?? MAX_COALESCED_BATCH_SIZE); + const maxPending = Math.max(maxBatchSize, options?.maxPending ?? MAX_PENDING_PER_COMPANY); + const backpressureMessage = + options?.backpressureMessage ?? + "Too many concurrent writes queued for this company; retry shortly"; + const queuesByDb = new WeakMap< + object, + Map> + >(); + + const drain = async ( + db: Db, + companyId: string, + companyQueues: Map>, + queue: CompanyBatchQueue, + ): Promise => { + if (queue.inFlight) return; + queue.inFlight = true; + try { + while (queue.pending.length > 0) { + const batch = queue.pending.splice(0, maxBatchSize); + await runBatch(db, companyId, batch, batch.length > 1); + } + } finally { + queue.inFlight = false; + if (queue.pending.length === 0) { + companyQueues.delete(companyId); + } else { + void drain(db, companyId, companyQueues, queue); + } + } + }; + + return (db: Db, companyId: string, item: TItem): Promise => { + let companyQueues = queuesByDb.get(db); + if (!companyQueues) { + companyQueues = new Map(); + queuesByDb.set(db, companyQueues); + } + let queue = companyQueues.get(companyId); + if (!queue) { + queue = { inFlight: false, pending: [] }; + companyQueues.set(companyId, queue); + } + if (queue.pending.length >= maxPending) { + return Promise.reject( + tooManyRequests(backpressureMessage, { + error: "rate_limited", + code: "write_queue_full", + }), + ); + } + return new Promise((resolve, reject) => { + queue.pending.push({ item, resolve, reject }); + if (!queue.inFlight) { + void drain(db, companyId, companyQueues, queue); + } + }); + }; +} diff --git a/server/src/services/headless-board-events-write.ts b/server/src/services/headless-board-events-write.ts new file mode 100644 index 00000000000..44235e6a73f --- /dev/null +++ b/server/src/services/headless-board-events-write.ts @@ -0,0 +1,406 @@ +import { randomBytes } from "node:crypto"; +import { EventEmitter } from "node:events"; +import { and, asc, desc, eq, inArray, lt, sql, type SQL } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + boardEvents, + channels, + issueLabels, + issues, + labels, +} from "@paperclipai/db"; +import { + formatEventCursor, + type BoardEventType, + type BoardEventView, +} from "@paperclipai/shared"; +import { logger } from "../middleware/logger.js"; +import { publishLiveEvent } from "./live-events.js"; + +export type DbOrTx = Db | Parameters[0]>[0]; + +const MAX_SUB_MS_SEQ = 0x3ffffff; +let lastUuidWallMs = -1; +let subMsSeq = 0; + +export function mintTimeOrderedUuid(wallMs = Date.now()): string { + const ms = Math.max(0, Math.floor(wallMs)); + const effectiveMs = Math.max(ms, lastUuidWallMs); + if (effectiveMs === lastUuidWallMs && subMsSeq < MAX_SUB_MS_SEQ) { + subMsSeq += 1; + } else { + lastUuidWallMs = effectiveMs; + subMsSeq = 0; + } + + const timeHighHex = Math.floor(effectiveMs / 0x10000) + .toString(16) + .padStart(8, "0"); + const timeLowHex = (effectiveMs & 0xffff).toString(16).padStart(4, "0"); + const versionAndSeqHighHex = (0x4000 | ((subMsSeq >>> 14) & 0x0fff)) + .toString(16) + .padStart(4, "0"); + const variantAndSeqLowHex = (0x8000 | (subMsSeq & 0x3fff)) + .toString(16) + .padStart(4, "0"); + const randomTailHex = randomBytes(6).toString("hex"); + + return `${timeHighHex}-${timeLowHex}-${versionAndSeqHighHex}-${variantAndSeqLowHex}-${randomTailHex}`; +} + +export function forEachPostCommitSafely( + items: readonly T[], + publish: (item: T) => void, + onError: (item: T, err: unknown) => void, +): void { + for (const item of items) { + try { + publish(item); + } catch (err) { + onError(item, err); + } + } +} + +const boardEventEmitter = new EventEmitter(); +boardEventEmitter.setMaxListeners(0); + +export function subscribeCompanyBoardEvents( + companyId: string, + listener: (event: BoardEventView) => void, +): () => void { + const safeListener = (event: BoardEventView) => { + try { + listener(event); + } catch (err) { + logger.warn({ err, companyId, seq: event.seq }, "board event listener failed"); + } + }; + boardEventEmitter.on(companyId, safeListener); + return () => boardEventEmitter.off(companyId, safeListener); +} + +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, + }, + }); +} + +const CHANNEL_ACTIVITY_DEBOUNCE_MS = 250; + +export async function touchChannelsLastActivity( + dbOrTx: DbOrTx, + channelIds: Array, + now: Date, +): Promise { + const uniqueIds = Array.from( + new Set(channelIds.filter((id): id is string => Boolean(id))), + ).sort(); + if (uniqueIds.length === 0) return; + + const cutoff = new Date(now.getTime() - CHANNEL_ACTIVITY_DEBOUNCE_MS); + if (uniqueIds.length === 1) { + await dbOrTx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where(and(eq(channels.id, uniqueIds[0]!), lt(channels.lastActivityAt, cutoff))); + return; + } + + const staleChannels = await dbOrTx + .select({ id: channels.id }) + .from(channels) + .where(and(inArray(channels.id, uniqueIds), lt(channels.lastActivityAt, cutoff))) + .orderBy(asc(channels.id)) + .for("no key update"); + if (staleChannels.length > 0) { + await dbOrTx + .update(channels) + .set({ lastActivityAt: now, updatedAt: now }) + .where( + inArray( + channels.id, + staleChannels.map((ch) => ch.id), + ), + ); + } +} + +function isPlainObjectRecord(val: unknown): val is Record { + return Boolean(val) && typeof val === "object" && !Array.isArray(val); +} + +export interface AppendBoardEventActor { + principalType: "local_trusted" | "user" | "agent" | "system"; + userId?: string | null; + agentId?: string | null; + agentName?: string | null; + actorProfile?: string | null; +} + +export interface AppendBoardEventInput { + companyId: string; + type: BoardEventType; + channelId?: string | null; + channelPath?: string | null; + issueId?: string | null; + identifier?: string | null; + actor: AppendBoardEventActor; + payload?: Record; +} + +export async function appendBoardEvents( + dbOrTx: DbOrTx, + inputs: AppendBoardEventInput[], +): Promise { + if (inputs.length === 0) return []; + const companyId = inputs[0]!.companyId; + + const prepared = inputs.map((input, idx) => { + if (input.companyId !== companyId) { + throw new Error("appendBoardEvents requires all events to share companyId"); + } + 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 rowSql = sql`( + ${idx}::int, + ${input.companyId}::uuid, + ${input.type}::text, + ${input.channelId ?? null}::uuid, + ${input.channelPath ?? null}::text, + ${issueIdVal}::uuid, + ${input.identifier ?? null}::text, + ${actorType}::text, + ${actorId}::text, + ${actorName}::text, + ${actorProfile}::text, + ${payloadExpr}::jsonb + )`; + + return { + input, + issueIdVal, + actorType, + actorId, + actorName, + actorProfile, + payloadObj, + payloadExpr, + rowSql, + }; + }); + + const insertedRows = + prepared.length === 1 + ? 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 + ${companyId}::uuid, + ${prepared[0]!.input.type}, + ${prepared[0]!.input.channelId ?? null}::uuid, + ${prepared[0]!.input.channelPath ?? null}, + ${prepared[0]!.issueIdVal}::uuid, + ${prepared[0]!.input.identifier ?? null}, + ${prepared[0]!.actorType}, + ${prepared[0]!.actorId}, + ${prepared[0]!.actorName}, + ${prepared[0]!.actorProfile}, + ${prepared[0]!.payloadExpr} + FROM ( + SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${companyId})) + ) AS _lock + RETURNING + ${sql.raw(boardEvents.seq.name)}, + ${sql.raw(boardEvents.createdAt.name)}, + ${sql.raw(boardEvents.payload.name)} + `) + : 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 + v.company_id, + v.event_type, + v.channel_id, + v.channel_path, + v.issue_id, + v.identifier, + v.actor_type, + v.actor_id, + v.actor_name, + v.actor_profile, + v.payload + FROM ( + SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${companyId})) + ) AS _lock + CROSS JOIN ( + VALUES ${sql.join( + prepared.map((p) => p.rowSql), + sql`, `, + )} + ) AS v( + ord, + company_id, + event_type, + channel_id, + channel_path, + issue_id, + identifier, + actor_type, + actor_id, + actor_name, + actor_profile, + payload + ) + ORDER BY v.ord ASC + RETURNING + ${sql.raw(boardEvents.seq.name)}, + ${sql.raw(boardEvents.createdAt.name)}, + ${sql.raw(boardEvents.payload.name)} + `); + + const orderedInserted = + insertedRows.length <= 1 + ? insertedRows + : [...insertedRows].sort((a, b) => Number(a.seq) - Number(b.seq)); + + if (orderedInserted.length !== prepared.length) { + throw new Error( + `appendBoardEvents expected ${prepared.length} returned rows, got ${orderedInserted.length}`, + ); + } + + return prepared.map((meta, idx) => { + const inserted = orderedInserted[idx]!; + 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 + : meta.payloadObj; + return { + cursor: formatEventCursor(seq), + seq, + type: meta.input.type, + companyId: meta.input.companyId, + channel: meta.input.channelPath ?? null, + issueId: meta.issueIdVal, + identifier: meta.input.identifier ?? null, + actor: { + type: meta.actorType, + id: meta.actorId, + name: meta.actorName, + profile: meta.actorProfile, + }, + payload: persistedPayload, + createdAt: createdAtIso, + }; + }); +} + +export async function appendBoardEvent( + dbOrTx: DbOrTx, + input: AppendBoardEventInput, +): Promise { + const [single] = await appendBoardEvents(dbOrTx, [input]); + return single!; +} + +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); +} diff --git a/server/src/services/headless-channel-write-helpers.ts b/server/src/services/headless-channel-write-helpers.ts new file mode 100644 index 00000000000..250953c27a8 --- /dev/null +++ b/server/src/services/headless-channel-write-helpers.ts @@ -0,0 +1,714 @@ +import { and, eq, inArray, isNull, ne, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + agents, + channelAccessMembers, + channels, + companyMemberships, + issueLabels, + issues, + labels, +} from "@paperclipai/db"; +import { + channelQueueConfigSchema, + CHANNEL_VISIBILITIES, + deriveAgentUrlKey, + isUuidLike, + normalizeChannelPath, + writableKvLabelsRecordSchema, + type ChannelQueueConfig, + type ChannelVisibility, + type CreateChannelInput, +} from "@paperclipai/shared"; +import { badRequest, forbidden, notFound } from "../errors.js"; +import { + logActivity, + type ActivityPublication, +} from "./activity-log.js"; +import { + assertChannelAccess, + channelDescendantsCondition, + enforceHeadlessScopes, + resolveProjectReference, + type DbOrTx, + type HeadlessActorContext, +} from "./headless-common.js"; +import { assertCanConfigureManagedPool } from "./headless-managed-pool.js"; + +const DEFAULT_TAG_LABEL_COLOR = "#64748b"; + +export function collectChannelAndAncestorPaths(paths: string[]): string[] { + const all = new Set(); + for (const path of paths) { + all.add(path); + const parts = path.split("/"); + for (let i = 1; i < parts.length; i += 1) { + all.add(parts.slice(0, i).join("/")); + } + } + return Array.from(all); +} + +export async function validateChannelPathWriteFromMap( + dbOrTx: DbOrTx, + actor: HeadlessActorContext, + normalizedPath: string, + channelByPath: ReadonlyMap, +): Promise<{ + existingChannel: typeof channels.$inferSelect | null; + hasPrivateAncestor: boolean; +}> { + enforceHeadlessScopes(actor, { channelPath: normalizedPath }); + + let hasPrivateAncestor = false; + const parts = normalizedPath.split("/"); + for (let i = 1; i < parts.length; i += 1) { + const anc = channelByPath.get(parts.slice(0, i).join("/")); + if (anc && anc.archivedAt === null && anc.visibility === "private") { + await assertChannelAccess(dbOrTx, anc, actor); + hasPrivateAncestor = true; + } + } + + const existing = channelByPath.get(normalizedPath) ?? null; + if (existing) { + if (existing.archivedAt !== null) { + throw notFound(`Channel '${normalizedPath}' not found`); + } + if (existing.visibility === "private") { + await assertChannelAccess(dbOrTx, existing, actor); + } + } + + return { + existingChannel: existing, + hasPrivateAncestor, + }; +} + +export function normalizeChannelPathOrThrow( + rawPath: string, + opts?: { allowSubtreePrefix?: boolean }, +) { + try { + return normalizeChannelPath(rawPath, opts); + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : `Invalid channel path "${rawPath}"`, + { + error: "invalid_channel_path", + code: "invalid_channel_path", + }, + ); + } +} + +export function validateWritableKvLabelsOrThrow( + rawLabels: Record, +): Record { + for (const key of Object.keys(rawLabels)) { + if (key.startsWith("paperclip.")) { + throw badRequest( + "Label keys starting with 'paperclip.' are reserved", + { + error: "reserved_label", + code: "reserved_label", + key, + }, + ); + } + } + const parsed = writableKvLabelsRecordSchema.safeParse(rawLabels); + if (!parsed.success) { + throw badRequest( + parsed.error.issues + .map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsed.error.issues, + }, + ); + } + return parsed.data; +} + +export async function resolveAssigneeAgent( + dbOrTx: DbOrTx, + companyId: string, + opts: { assigneeAgentId?: string | null; for?: string }, +): Promise { + if (opts.assigneeAgentId !== undefined) { + if (opts.assigneeAgentId === null) return null; + const [agent] = await dbOrTx + .select({ id: agents.id }) + .from(agents) + .where( + and( + eq(agents.id, opts.assigneeAgentId), + eq(agents.companyId, companyId), + ne(agents.status, "terminated"), + ), + ) + .limit(1); + if (!agent) { + throw notFound(`Agent '${opts.assigneeAgentId}' not found`, { + error: "agent_not_found", + code: "agent_not_found", + }); + } + return agent.id; + } + + if (opts.for !== undefined && opts.for.trim().length > 0) { + const target = opts.for.trim().replace(/^@+/, "").toLowerCase(); + if (isUuidLike(target)) { + const [agent] = await dbOrTx + .select({ id: agents.id }) + .from(agents) + .where( + and( + eq(agents.id, target), + eq(agents.companyId, companyId), + ne(agents.status, "terminated"), + ), + ) + .limit(1); + if (!agent) { + throw notFound(`Agent '@${target}' not found`, { + error: "agent_not_found", + code: "agent_not_found", + }); + } + return agent.id; + } + + const companyAgents = await dbOrTx + .select({ id: agents.id, name: agents.name }) + .from(agents) + .where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"))); + + const match = companyAgents.find( + (a) => + a.name.trim().toLowerCase() === target || + deriveAgentUrlKey(a.name, a.id).toLowerCase() === target, + ); + if (!match) { + throw notFound(`Agent '@${target}' not found`, { + error: "agent_not_found", + code: "agent_not_found", + }); + } + return match.id; + } + + return null; +} + +export function normalizeTagLabelNames(tagNames: string[]): string[] { + return Array.from( + new Set(tagNames.map((t) => t.trim()).filter((t) => t.length > 0)), + ).sort(); +} + +export async function ensureCompanyTagLabels( + tx: DbOrTx, + companyId: string, + tagNames: string[], +): Promise> { + const uniqueNames = normalizeTagLabelNames(tagNames); + if (uniqueNames.length === 0) return []; + + await tx + .insert(labels) + .values( + uniqueNames.map((name) => ({ + companyId, + name, + color: DEFAULT_TAG_LABEL_COLOR, + })), + ) + .onConflictDoNothing({ + target: [labels.companyId, labels.name], + }); + + return tx + .select({ id: labels.id, name: labels.name }) + .from(labels) + .where(and(eq(labels.companyId, companyId), inArray(labels.name, uniqueNames))); +} + +export async function attachTagLabelsToIssues( + tx: DbOrTx, + companyId: string, + items: Array<{ issueId: string; tagNames: string[] }>, +): Promise> { + const normalizedByIssue = items.map((item) => ({ + issueId: item.issueId, + names: normalizeTagLabelNames(item.tagNames), + })); + const allTagNames = Array.from( + new Set(normalizedByIssue.flatMap((entry) => entry.names)), + ).sort(); + const result = new Map(); + for (const entry of normalizedByIssue) { + result.set(entry.issueId, []); + } + if (allTagNames.length === 0) { + return result; + } + + const labelRows = await ensureCompanyTagLabels(tx, companyId, allTagNames); + const tagIdByName = new Map(labelRows.map((row) => [row.name, row.id])); + const issueLabelValues: Array<{ + issueId: string; + labelId: string; + companyId: string; + }> = []; + + for (const entry of normalizedByIssue) { + const attached: string[] = []; + for (const name of entry.names) { + const labelId = tagIdByName.get(name); + if (labelId) { + attached.push(name); + issueLabelValues.push({ + issueId: entry.issueId, + labelId, + companyId, + }); + } + } + result.set(entry.issueId, attached); + } + + issueLabelValues.sort((a, b) => + a.issueId !== b.issueId + ? a.issueId.localeCompare(b.issueId) + : a.labelId.localeCompare(b.labelId), + ); + if (issueLabelValues.length > 0) { + await tx + .insert(issueLabels) + .values(issueLabelValues) + .onConflictDoNothing({ + target: [issueLabels.issueId, issueLabels.labelId], + }); + } + + return result; +} + +export async function attachTagLabels( + tx: DbOrTx, + companyId: string, + issueId: string, + tagNames: string[], +): Promise { + const attachedMap = await attachTagLabelsToIssues(tx, companyId, [ + { issueId, tagNames }, + ]); + return attachedMap.get(issueId) ?? []; +} + +async function addChannelCreatorMembership( + dbOrTx: DbOrTx, + companyId: string, + channelId: string, + actor: HeadlessActorContext, +): Promise { + const member = actor.agentId + ? { subjectType: "agent", subjectId: actor.agentId } + : actor.userId + ? { subjectType: "user", subjectId: actor.userId } + : null; + + if (!member) return; + + await dbOrTx + .insert(channelAccessMembers) + .values({ + companyId, + channelId, + subjectType: member.subjectType, + subjectId: member.subjectId, + }) + .onConflictDoNothing({ + target: [ + channelAccessMembers.channelId, + channelAccessMembers.subjectType, + channelAccessMembers.subjectId, + ], + }); +} + +export interface EnsureChannelInput { + path: string; + description?: string | null; + visibility?: ChannelVisibility; + defaultProjectId?: string | null; + queueConfig?: ChannelQueueConfig; +} + +export async function assertChannelPathWritePreconditions( + dbOrTx: DbOrTx, + companyId: string, + actor: HeadlessActorContext, + rawPath: string, +): Promise<{ + normalizedPath: string; + existingChannel: typeof channels.$inferSelect | null; + hasPrivateAncestor: boolean; +}> { + const normalized = normalizeChannelPathOrThrow(rawPath, { + allowSubtreePrefix: false, + }); + const lookupPaths = collectChannelAndAncestorPaths([normalized.path]); + const rows = + lookupPaths.length === 1 + ? await dbOrTx + .select() + .from(channels) + .where( + and( + eq(channels.companyId, companyId), + eq(channels.path, lookupPaths[0]!), + ), + ) + .limit(1) + : await dbOrTx + .select() + .from(channels) + .where( + and( + eq(channels.companyId, companyId), + inArray(channels.path, lookupPaths), + ), + ); + const channelByPath = new Map(rows.map((row) => [row.path, row])); + const { existingChannel, hasPrivateAncestor } = + await validateChannelPathWriteFromMap( + dbOrTx, + actor, + normalized.path, + channelByPath, + ); + return { + normalizedPath: normalized.path, + existingChannel, + hasPrivateAncestor, + }; +} + +export async function ensureChannel( + dbOrTx: DbOrTx, + companyId: string, + actor: HeadlessActorContext, + input: EnsureChannelInput | CreateChannelInput, + opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {}, +): Promise { + const { normalizedPath, existingChannel, hasPrivateAncestor } = + await assertChannelPathWritePreconditions(dbOrTx, companyId, actor, input.path); + const normalized = { path: normalizedPath }; + + let resolvedDefaultProjectId: string | null | undefined; + if (input.defaultProjectId !== undefined) { + resolvedDefaultProjectId = + input.defaultProjectId === null + ? null + : await resolveProjectReference(dbOrTx, companyId, input.defaultProjectId, actor); + } + + let validatedQueueConfig: ChannelQueueConfig | undefined; + if (input.queueConfig !== undefined) { + const parsedQc = channelQueueConfigSchema.safeParse(input.queueConfig); + if (!parsedQc.success) { + throw badRequest( + parsedQc.error.issues + .map((i) => `${i.path.join(".") || "$"}: ${i.message}`) + .join("; "), + { + error: "validation_error", + code: "validation_error", + issues: parsedQc.error.issues, + }, + ); + } + validatedQueueConfig = parsedQc.data; + } + + let visibility: ChannelVisibility | undefined = input.visibility; + if (visibility !== undefined && !CHANNEL_VISIBILITIES.includes(visibility)) { + throw badRequest(`Invalid channel visibility '${visibility}'`, { + error: "validation_error", + code: "validation_error", + }); + } + + if (hasPrivateAncestor) { + if (visibility === "open") { + throw forbidden("Cannot create or expose an open channel under a private ancestor", { + code: "private_ancestor_required", + }); + } + visibility = "private"; + } + + if (existingChannel && !opts.allowUpdateExisting) { + return existingChannel; + } + + let existing = existingChannel; + if (!existing) { + if (validatedQueueConfig?.managedPool) { + await assertCanConfigureManagedPool( + dbOrTx, + companyId, + { + visibility: visibility ?? "open", + createdByAgentId: actor.agentId, + defaultProjectId: resolvedDefaultProjectId ?? null, + }, + validatedQueueConfig.managedPool.agentId, + actor, + ); + } + + const now = new Date(); + const [inserted] = await dbOrTx + .insert(channels) + .values({ + companyId, + path: normalized.path, + description: input.description ?? null, + visibility: visibility ?? "open", + defaultProjectId: resolvedDefaultProjectId ?? null, + queueConfig: validatedQueueConfig ?? {}, + createdByAgentId: actor.agentId, + createdByUserId: actor.agentId ? null : actor.userId, + createdByProfile: actor.actorProfile, + lastActivityAt: now, + createdAt: now, + updatedAt: now, + }) + .onConflictDoNothing({ + target: [channels.companyId, channels.path], + }) + .returning(); + + if (inserted) { + if (inserted.visibility === "private") { + await addChannelCreatorMembership(dbOrTx, companyId, inserted.id, actor); + } + if (opts.publications) { + await logActivity( + dbOrTx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + responsibleUserIdOverride: actor.responsibleUserId, + action: "channel.created", + entityType: "channel", + entityId: inserted.id, + details: { + path: inserted.path, + visibility: inserted.visibility, + }, + }, + opts.publications, + ); + } + return inserted; + } + + const [raced] = await dbOrTx + .select() + .from(channels) + .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) + .limit(1); + + if (!raced || raced.archivedAt !== null) { + throw notFound(`Channel '${normalized.path}' not found`); + } + + if (raced.visibility === "private") { + await assertChannelAccess(dbOrTx, raced, actor); + } + + if (!opts.allowUpdateExisting) { + return raced; + } + existing = raced; + } + + const updates: Partial = {}; + if (input.description !== undefined && input.description !== existing.description) { + updates.description = input.description; + } + if (input.visibility !== undefined && input.visibility !== existing.visibility) { + updates.visibility = input.visibility; + } + if ( + resolvedDefaultProjectId !== undefined && + resolvedDefaultProjectId !== existing.defaultProjectId + ) { + updates.defaultProjectId = resolvedDefaultProjectId; + } + if ( + validatedQueueConfig !== undefined && + JSON.stringify(validatedQueueConfig) !== JSON.stringify(existing.queueConfig ?? {}) + ) { + updates.queueConfig = validatedQueueConfig; + } + + if (Object.keys(updates).length > 0) { + enforceHeadlessScopes(actor, { + action: "channels.manage", + channelPath: existing.path, + }); + const isOwnerOrCreator = + actor.isInstanceAdmin || + actor.principalType === "local_trusted" || + (Boolean(actor.userId) && existing.createdByUserId === actor.userId) || + (Boolean(actor.agentId) && existing.createdByAgentId === actor.agentId); + let canManage = isOwnerOrCreator; + if (!canManage && actor.userId && actor.principalType === "user") { + const [membership] = await dbOrTx + .select({ role: companyMemberships.membershipRole }) + .from(companyMemberships) + .where( + and( + eq(companyMemberships.companyId, companyId), + eq(companyMemberships.principalType, "user"), + eq(companyMemberships.principalId, actor.userId), + eq(companyMemberships.status, "active"), + inArray(companyMemberships.membershipRole, ["owner", "admin"]), + ), + ) + .limit(1); + canManage = Boolean(membership); + } + if (!canManage) { + throw forbidden("Only the channel creator or a company admin can update channel settings"); + } + + if (updates.queueConfig?.managedPool) { + await assertCanConfigureManagedPool( + dbOrTx, + companyId, + { + id: existing.id, + visibility: updates.visibility ?? existing.visibility, + createdByAgentId: existing.createdByAgentId, + defaultProjectId: + updates.defaultProjectId !== undefined + ? updates.defaultProjectId + : existing.defaultProjectId, + }, + updates.queueConfig.managedPool.agentId, + actor, + ); + } + + updates.updatedAt = new Date(); + const privatizingTree = + updates.visibility === "private" && existing.visibility !== "private"; + + let childChannels: Array<{ id: string; visibility: string }> = []; + let affectedChannelIds: string[] = []; + if (privatizingTree) { + childChannels = await dbOrTx + .select({ id: channels.id, visibility: channels.visibility }) + .from(channels) + .where( + and( + eq(channels.companyId, companyId), + isNull(channels.archivedAt), + channelDescendantsCondition(existing.path), + ), + ); + affectedChannelIds = [existing.id, ...childChannels.map((c) => c.id)].sort(); + + await dbOrTx.execute( + sql`SELECT id FROM issues WHERE company_id = ${companyId} AND channel_id IN (${sql.join( + affectedChannelIds.map((id) => sql`${id}`), + sql`, `, + )}) AND visibility <> 'private' ORDER BY id FOR UPDATE`, + ); + await dbOrTx.execute( + sql`SELECT id FROM channels WHERE company_id = ${companyId} AND id IN (${sql.join( + affectedChannelIds.map((id) => sql`${id}`), + sql`, `, + )}) ORDER BY id FOR UPDATE`, + ); + } + + const [updated] = await dbOrTx + .update(channels) + .set(updates) + .where(eq(channels.id, existing.id)) + .returning(); + if (updated?.visibility === "private" && existing.visibility !== "private") { + await addChannelCreatorMembership(dbOrTx, companyId, updated.id, actor); + const newlyPrivatizedChildIds = childChannels + .filter((c) => c.visibility !== "private") + .map((c) => c.id) + .sort(); + if (newlyPrivatizedChildIds.length > 0) { + await dbOrTx + .update(channels) + .set({ visibility: "private", updatedAt: updates.updatedAt }) + .where(inArray(channels.id, newlyPrivatizedChildIds)); + for (const childId of newlyPrivatizedChildIds) { + await addChannelCreatorMembership(dbOrTx, companyId, childId, actor); + } + } + await dbOrTx + .update(issues) + .set({ + visibility: "private", + privacyRootIssueId: sql`coalesce(${issues.privacyRootIssueId}, ${issues.id})`, + updatedAt: updates.updatedAt, + }) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.channelId, affectedChannelIds), + ne(issues.visibility, "private"), + ), + ); + } + if (updated && opts.publications) { + await logActivity( + dbOrTx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + responsibleUserIdOverride: actor.responsibleUserId, + action: "channel.updated", + entityType: "channel", + entityId: updated.id, + details: { + path: updated.path, + visibility: updated.visibility, + }, + }, + opts.publications, + ); + } + return updated ?? existing; + } + + return existing; +} diff --git a/server/src/services/headless-channels.ts b/server/src/services/headless-channels.ts index 803efff2658..f5832b49170 100644 --- a/server/src/services/headless-channels.ts +++ b/server/src/services/headless-channels.ts @@ -1,4 +1,4 @@ -import { createHash, randomUUID } from "node:crypto"; +import { createHash } from "node:crypto"; import { and, asc, @@ -7,85 +7,65 @@ import { gt, inArray, isNull, - like, - ne, or, - sql, type SQL, } from "drizzle-orm"; import { z } from "zod"; import type { Db } from "@paperclipai/db"; import { - agents, boardEvents, - channelAccessMembers, channels, - companies, - companyMemberships, issueComments, - issueLabels, issues, - labels, - primeDatabaseWorkTransactionId, - projects, } from "@paperclipai/db"; import { - channelQueueConfigSchema, - CHANNEL_VISIBILITIES, - deriveAgentUrlKey, ISSUE_PRIORITIES, isUuidLike, - matchesLabelFilter, - normalizeChannelPath, parseEventCursor, parseLabelFilterExpr, parseSchemaRef, SCHEMA_REF_REGEX, schemaBlockSchema, splitMessageIntoTitleAndDescription, - writableKvLabelsRecordSchema, - type BoardEventView, type ChannelPage, type ChannelQueueConfig, type ChannelView, - type ChannelVisibility, type CommentView, - type CreateChannelInput, type HeadlessIssueView, - type IssuePriority, - type IssueScope, type IssueStatus, type SchemaBlock, } from "@paperclipai/shared"; -import { badRequest, conflict, forbidden, notFound } from "../errors.js"; +import { badRequest, conflict } from "../errors.js"; import { - createActivityDetailsRedactor, - logActivity, - publishActivity, - type ActivityPublication, -} from "./activity-log.js"; -import { assertCanConfigureManagedPool } from "./headless-managed-pool.js"; + assertChannelPathWritePreconditions, + attachTagLabels, + collectChannelAndAncestorPaths, + ensureChannel, + ensureCompanyTagLabels, + normalizeChannelPathOrThrow, + resolveAssigneeAgent, + validateChannelPathWriteFromMap, + validateWritableKvLabelsOrThrow, + type EnsureChannelInput, +} from "./headless-channel-write-helpers.js"; import { - appendBoardEvent, assertChannelAccess, - assertProjectReadAccess, - buildNextIssueCounterSql, buildSqlIssueLabelFilterCondition, canAccessChannel, - channelDescendantsCondition, channelSubtreeCondition, enforceHeadlessScopes, getLatestCompanyEventCursor, loadHeadlessIssueView, loadHeadlessIssueViews, - publishCommittedBoardEvent, resolveIssueByIdOrIdentifier, - resolveProjectReference, serializeCommentView, - serializeCreatedHeadlessIssueView, type DbOrTx, type HeadlessActorContext, } from "./headless-common.js"; +import { + executeCoalescedChannelPost, + executeImmediateChannelPost, +} from "./headless-post-group-commit.js"; import { assertSchemaExists, formatBlocksAsFencedJson, @@ -93,7 +73,18 @@ import { } from "./headless-schemas.js"; import { listIssueDependencyReadinessMap } from "./issues.js"; -const DEFAULT_TAG_LABEL_COLOR = "#64748b"; +export { + assertChannelPathWritePreconditions, + attachTagLabels, + collectChannelAndAncestorPaths, + ensureChannel, + ensureCompanyTagLabels, + normalizeChannelPathOrThrow, + resolveAssigneeAgent, + validateChannelPathWriteFromMap, + validateWritableKvLabelsOrThrow, + type EnsureChannelInput, +}; function isChannelAllowedByScopes( actor: Pick, @@ -107,598 +98,6 @@ function isChannelAllowedByScopes( } } -export function normalizeChannelPathOrThrow( - rawPath: string, - opts?: { allowSubtreePrefix?: boolean }, -) { - try { - return normalizeChannelPath(rawPath, opts); - } catch (err) { - throw badRequest( - err instanceof Error ? err.message : `Invalid channel path "${rawPath}"`, - { - error: "invalid_channel_path", - code: "invalid_channel_path", - }, - ); - } -} - -export function validateWritableKvLabelsOrThrow( - rawLabels: Record, -): Record { - for (const key of Object.keys(rawLabels)) { - if (key.startsWith("paperclip.")) { - throw badRequest( - "Label keys starting with 'paperclip.' are reserved", - { - error: "reserved_label", - code: "reserved_label", - key, - }, - ); - } - } - const parsed = writableKvLabelsRecordSchema.safeParse(rawLabels); - if (!parsed.success) { - throw badRequest( - parsed.error.issues - .map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`) - .join("; "), - { - error: "validation_error", - code: "validation_error", - issues: parsed.error.issues, - }, - ); - } - return parsed.data; -} - -export async function resolveAssigneeAgent( - dbOrTx: DbOrTx, - companyId: string, - opts: { assigneeAgentId?: string | null; for?: string }, -): Promise { - if (opts.assigneeAgentId !== undefined) { - if (opts.assigneeAgentId === null) return null; - const [agent] = await dbOrTx - .select({ id: agents.id }) - .from(agents) - .where( - and( - eq(agents.id, opts.assigneeAgentId), - eq(agents.companyId, companyId), - ne(agents.status, "terminated"), - ), - ) - .limit(1); - if (!agent) { - throw notFound(`Agent '${opts.assigneeAgentId}' not found`, { - error: "agent_not_found", - code: "agent_not_found", - }); - } - return agent.id; - } - - if (opts.for !== undefined && opts.for.trim().length > 0) { - const target = opts.for.trim().replace(/^@+/, "").toLowerCase(); - if (isUuidLike(target)) { - const [agent] = await dbOrTx - .select({ id: agents.id }) - .from(agents) - .where( - and( - eq(agents.id, target), - eq(agents.companyId, companyId), - ne(agents.status, "terminated"), - ), - ) - .limit(1); - if (!agent) { - throw notFound(`Agent '@${target}' not found`, { - error: "agent_not_found", - code: "agent_not_found", - }); - } - return agent.id; - } - - const companyAgents = await dbOrTx - .select({ id: agents.id, name: agents.name }) - .from(agents) - .where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated"))); - - const match = companyAgents.find( - (a) => - a.name.trim().toLowerCase() === target || - deriveAgentUrlKey(a.name, a.id).toLowerCase() === target, - ); - if (!match) { - throw notFound(`Agent '@${target}' not found`, { - error: "agent_not_found", - code: "agent_not_found", - }); - } - return match.id; - } - - return null; -} - -export async function ensureCompanyTagLabels( - tx: DbOrTx, - companyId: string, - tagNames: string[], -): Promise> { - const uniqueNames = Array.from( - new Set(tagNames.map((t) => t.trim()).filter((t) => t.length > 0)), - ).sort(); - if (uniqueNames.length === 0) return []; - - await tx - .insert(labels) - .values( - uniqueNames.map((name) => ({ - companyId, - name, - color: DEFAULT_TAG_LABEL_COLOR, - })), - ) - .onConflictDoNothing({ - target: [labels.companyId, labels.name], - }); - - return tx - .select({ id: labels.id, name: labels.name }) - .from(labels) - .where(and(eq(labels.companyId, companyId), inArray(labels.name, uniqueNames))); -} - -export async function attachTagLabels( - tx: DbOrTx, - companyId: string, - issueId: string, - tagNames: string[], -): Promise { - const labelRows = await ensureCompanyTagLabels(tx, companyId, tagNames); - if (labelRows.length === 0) return []; - - await tx - .insert(issueLabels) - .values( - labelRows.map((l) => ({ - issueId, - labelId: l.id, - companyId, - })), - ) - .onConflictDoNothing({ - target: [issueLabels.issueId, issueLabels.labelId], - }); - - return labelRows.map((l) => l.name); -} - -async function addChannelCreatorMembership( - dbOrTx: DbOrTx, - companyId: string, - channelId: string, - actor: HeadlessActorContext, -): Promise { - const member = actor.agentId - ? { subjectType: "agent", subjectId: actor.agentId } - : actor.userId - ? { subjectType: "user", subjectId: actor.userId } - : null; - - if (!member) return; - - await dbOrTx - .insert(channelAccessMembers) - .values({ - companyId, - channelId, - subjectType: member.subjectType, - subjectId: member.subjectId, - }) - .onConflictDoNothing({ - target: [ - channelAccessMembers.channelId, - channelAccessMembers.subjectType, - channelAccessMembers.subjectId, - ], - }); -} - -export interface EnsureChannelInput { - path: string; - description?: string | null; - visibility?: ChannelVisibility; - defaultProjectId?: string | null; - queueConfig?: ChannelQueueConfig; -} - -export async function assertChannelPathWritePreconditions( - dbOrTx: DbOrTx, - companyId: string, - actor: HeadlessActorContext, - rawPath: string, -): Promise<{ - normalizedPath: string; - existingChannel: typeof channels.$inferSelect | null; - hasPrivateAncestor: boolean; -}> { - const normalized = normalizeChannelPathOrThrow(rawPath, { - allowSubtreePrefix: false, - }); - enforceHeadlessScopes(actor, { channelPath: normalized.path }); - - let hasPrivateAncestor = false; - const parts = normalized.path.split("/"); - if (parts.length > 1) { - const ancestorPaths: string[] = []; - for (let i = 1; i < parts.length; i += 1) { - ancestorPaths.push(parts.slice(0, i).join("/")); - } - const ancestors = await dbOrTx - .select() - .from(channels) - .where( - and( - eq(channels.companyId, companyId), - inArray(channels.path, ancestorPaths), - isNull(channels.archivedAt), - ), - ); - for (const anc of ancestors) { - if (anc.visibility === "private") { - await assertChannelAccess(dbOrTx, anc, actor); - hasPrivateAncestor = true; - } - } - } - - const [existing] = await dbOrTx - .select() - .from(channels) - .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) - .limit(1); - if (existing) { - if (existing.archivedAt !== null) { - throw notFound(`Channel '${normalized.path}' not found`); - } - if (existing.visibility === "private") { - await assertChannelAccess(dbOrTx, existing, actor); - } - return { - normalizedPath: normalized.path, - existingChannel: existing, - hasPrivateAncestor, - }; - } - - return { - normalizedPath: normalized.path, - existingChannel: null, - hasPrivateAncestor, - }; -} - -export async function ensureChannel( - dbOrTx: DbOrTx, - companyId: string, - actor: HeadlessActorContext, - input: EnsureChannelInput | CreateChannelInput, - opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {}, -): Promise { - const { normalizedPath, existingChannel, hasPrivateAncestor } = - await assertChannelPathWritePreconditions(dbOrTx, companyId, actor, input.path); - const normalized = { path: normalizedPath }; - - let resolvedDefaultProjectId: string | null | undefined; - if (input.defaultProjectId !== undefined) { - resolvedDefaultProjectId = - input.defaultProjectId === null - ? null - : await resolveProjectReference(dbOrTx, companyId, input.defaultProjectId, actor); - } - - let validatedQueueConfig: ChannelQueueConfig | undefined; - if (input.queueConfig !== undefined) { - const parsedQc = channelQueueConfigSchema.safeParse(input.queueConfig); - if (!parsedQc.success) { - throw badRequest( - parsedQc.error.issues - .map((i) => `${i.path.join(".") || "$"}: ${i.message}`) - .join("; "), - { - error: "validation_error", - code: "validation_error", - issues: parsedQc.error.issues, - }, - ); - } - validatedQueueConfig = parsedQc.data; - } - - let visibility: ChannelVisibility | undefined = input.visibility; - if (visibility !== undefined && !CHANNEL_VISIBILITIES.includes(visibility)) { - throw badRequest(`Invalid channel visibility '${visibility}'`, { - error: "validation_error", - code: "validation_error", - }); - } - - if (hasPrivateAncestor) { - if (visibility === "open") { - throw forbidden("Cannot create or expose an open channel under a private ancestor", { - code: "private_ancestor_required", - }); - } - visibility = "private"; - } - - if (existingChannel && !opts.allowUpdateExisting) { - return existingChannel; - } - - let existing = existingChannel; - if (!existing) { - if (validatedQueueConfig?.managedPool) { - await assertCanConfigureManagedPool( - dbOrTx, - companyId, - { - visibility: visibility ?? "open", - createdByAgentId: actor.agentId, - defaultProjectId: resolvedDefaultProjectId ?? null, - }, - validatedQueueConfig.managedPool.agentId, - actor, - ); - } - - const now = new Date(); - const [inserted] = await dbOrTx - .insert(channels) - .values({ - companyId, - path: normalized.path, - description: input.description ?? null, - visibility: visibility ?? "open", - defaultProjectId: resolvedDefaultProjectId ?? null, - queueConfig: validatedQueueConfig ?? {}, - createdByAgentId: actor.agentId, - createdByUserId: actor.agentId ? null : actor.userId, - createdByProfile: actor.actorProfile, - lastActivityAt: now, - createdAt: now, - updatedAt: now, - }) - .onConflictDoNothing({ - target: [channels.companyId, channels.path], - }) - .returning(); - - if (inserted) { - if (inserted.visibility === "private") { - await addChannelCreatorMembership(dbOrTx, companyId, inserted.id, actor); - } - if (opts.publications) { - await logActivity( - dbOrTx as unknown as Db, - { - companyId, - actorType: actor.principalType === "agent" ? "agent" : "user", - actorId: - actor.principalType === "agent" - ? actor.agentId! - : (actor.userId ?? "local-board"), - agentId: actor.agentId, - responsibleUserIdOverride: actor.responsibleUserId, - action: "channel.created", - entityType: "channel", - entityId: inserted.id, - details: { - path: inserted.path, - visibility: inserted.visibility, - }, - }, - opts.publications, - ); - } - return inserted; - } - - const [raced] = await dbOrTx - .select() - .from(channels) - .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) - .limit(1); - - if (!raced || raced.archivedAt !== null) { - throw notFound(`Channel '${normalized.path}' not found`); - } - - if (raced.visibility === "private") { - await assertChannelAccess(dbOrTx, raced, actor); - } - - if (!opts.allowUpdateExisting) { - return raced; - } - existing = raced; - } - - const updates: Partial = {}; - if (input.description !== undefined && input.description !== existing.description) { - updates.description = input.description; - } - if (input.visibility !== undefined && input.visibility !== existing.visibility) { - updates.visibility = input.visibility; - } - if ( - resolvedDefaultProjectId !== undefined && - resolvedDefaultProjectId !== existing.defaultProjectId - ) { - updates.defaultProjectId = resolvedDefaultProjectId; - } - if ( - validatedQueueConfig !== undefined && - JSON.stringify(validatedQueueConfig) !== JSON.stringify(existing.queueConfig ?? {}) - ) { - updates.queueConfig = validatedQueueConfig; - } - - if (Object.keys(updates).length > 0) { - enforceHeadlessScopes(actor, { - action: "channels.manage", - channelPath: existing.path, - }); - const isOwnerOrCreator = - actor.isInstanceAdmin || - actor.principalType === "local_trusted" || - (Boolean(actor.userId) && existing.createdByUserId === actor.userId) || - (Boolean(actor.agentId) && existing.createdByAgentId === actor.agentId); - let canManage = isOwnerOrCreator; - if (!canManage && actor.userId && actor.principalType === "user") { - const [membership] = await dbOrTx - .select({ role: companyMemberships.membershipRole }) - .from(companyMemberships) - .where( - and( - eq(companyMemberships.companyId, companyId), - eq(companyMemberships.principalType, "user"), - eq(companyMemberships.principalId, actor.userId), - eq(companyMemberships.status, "active"), - inArray(companyMemberships.membershipRole, ["owner", "admin"]), - ), - ) - .limit(1); - canManage = Boolean(membership); - } - if (!canManage) { - throw forbidden("Only the channel creator or a company admin can update channel settings"); - } - - if (updates.queueConfig?.managedPool) { - await assertCanConfigureManagedPool( - dbOrTx, - companyId, - { - id: existing.id, - visibility: updates.visibility ?? existing.visibility, - createdByAgentId: existing.createdByAgentId, - defaultProjectId: - updates.defaultProjectId !== undefined - ? updates.defaultProjectId - : existing.defaultProjectId, - }, - updates.queueConfig.managedPool.agentId, - actor, - ); - } - - updates.updatedAt = new Date(); - const privatizingTree = - updates.visibility === "private" && existing.visibility !== "private"; - - let childChannels: Array<{ id: string; visibility: string }> = []; - let affectedChannelIds: string[] = []; - if (privatizingTree) { - childChannels = await dbOrTx - .select({ id: channels.id, visibility: channels.visibility }) - .from(channels) - .where( - and( - eq(channels.companyId, companyId), - isNull(channels.archivedAt), - channelDescendantsCondition(existing.path), - ), - ); - affectedChannelIds = [existing.id, ...childChannels.map((c) => c.id)].sort(); - - // Lock issues BEFORE locking channels so all transactions share issues -> channels -> board_events lock order. - await dbOrTx.execute( - sql`SELECT id FROM issues WHERE company_id = ${companyId} AND channel_id IN (${sql.join( - affectedChannelIds.map((id) => sql`${id}`), - sql`, `, - )}) AND visibility <> 'private' ORDER BY id FOR UPDATE`, - ); - await dbOrTx.execute( - sql`SELECT id FROM channels WHERE company_id = ${companyId} AND id IN (${sql.join( - affectedChannelIds.map((id) => sql`${id}`), - sql`, `, - )}) ORDER BY id FOR UPDATE`, - ); - } - - const [updated] = await dbOrTx - .update(channels) - .set(updates) - .where(eq(channels.id, existing.id)) - .returning(); - if (updated?.visibility === "private" && existing.visibility !== "private") { - await addChannelCreatorMembership(dbOrTx, companyId, updated.id, actor); - const newlyPrivatizedChildIds = childChannels - .filter((c) => c.visibility !== "private") - .map((c) => c.id) - .sort(); - if (newlyPrivatizedChildIds.length > 0) { - await dbOrTx - .update(channels) - .set({ visibility: "private", updatedAt: updates.updatedAt }) - .where(inArray(channels.id, newlyPrivatizedChildIds)); - for (const childId of newlyPrivatizedChildIds) { - await addChannelCreatorMembership(dbOrTx, companyId, childId, actor); - } - } - await dbOrTx - .update(issues) - .set({ - visibility: "private", - privacyRootIssueId: sql`coalesce(${issues.privacyRootIssueId}, ${issues.id})`, - updatedAt: updates.updatedAt, - }) - .where( - and( - eq(issues.companyId, companyId), - inArray(issues.channelId, affectedChannelIds), - ne(issues.visibility, "private"), - ), - ); - } - if (updated && opts.publications) { - await logActivity( - dbOrTx as unknown as Db, - { - companyId, - actorType: actor.principalType === "agent" ? "agent" : "user", - actorId: - actor.principalType === "agent" - ? actor.agentId! - : (actor.userId ?? "local-board"), - agentId: actor.agentId, - responsibleUserIdOverride: actor.responsibleUserId, - action: "channel.updated", - entityType: "channel", - entityId: updated.id, - details: { - path: updated.path, - visibility: updated.visibility, - }, - }, - opts.publications, - ); - } - return updated ?? existing; - } - - return existing; -} - export async function buildChannelViews( dbOrTx: DbOrTx, companyId: string, @@ -1025,262 +424,29 @@ export async function createChannelPost( } } - const activityRedactor = await createActivityDetailsRedactor(db); - const publications: ActivityPublication[] = []; - const committedEvents: BoardEventView[] = []; + const postPayload = { + actor, + channelPath: normalizedChannel.path, + requestedStatus, + resolvedTitle, + resolvedDescription, + projectIdInput: input.projectId, + board: Boolean(input.board), + priority: input.priority ?? "medium", + forInput: input.for, + assigneeAgentIdInput: input.assigneeAgentId, + mergedKvLabels, + tagLabelsInput: input.tagLabels ?? [], + validatedBlocks, + resolvedResultSchemaRef, + originId, + requestHash, + }; - const txResult = await db.transaction(async (tx) => { - if (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, actor); - } - if ( - existingInTx.originFingerprint && - existingInTx.originFingerprint !== 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 { issue: view, created: false }; - } - } - - const channel = await ensureChannel( - tx, - companyId, - actor, - { - path: normalizedChannel.path, - }, - { publications }, - ); - const now = new Date(); - - let projectId: string | null = channel.defaultProjectId ?? null; - if (input.projectId !== undefined) { - projectId = - input.projectId === null - ? null - : await resolveProjectReference(tx, companyId, input.projectId, actor); - } else if (projectId) { - await assertProjectReadAccess(tx, companyId, projectId, actor); - } - - const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, { - assigneeAgentId: input.assigneeAgentId, - for: input.for, - }); - - const scope: IssueScope = input.board ? "board" : "channel"; - const priority: IssuePriority = input.priority ?? "medium"; - let issueVisibility: "open" | "private" = - channel.visibility === "private" ? "private" : "open"; - if (projectId && issueVisibility !== "private") { - const [projRow] = await tx - .select({ visibility: projects.visibility }) - .from(projects) - .where(and(eq(projects.id, projectId), eq(projects.companyId, companyId))) - .limit(1); - if (projRow?.visibility === "private") { - issueVisibility = "private"; - } - } - - const nextCounterExpr = buildNextIssueCounterSql(companyId, 1); - - const [companyRow] = await tx - .update(companies) - .set({ - issueCounter: nextCounterExpr, - updatedAt: now, - }) - .where(eq(companies.id, companyId)) - .returning({ - issueCounter: companies.issueCounter, - issuePrefix: companies.issuePrefix, - xid: sql`pg_current_xact_id()::text`, - }); - - if (companyRow?.xid) { - primeDatabaseWorkTransactionId(tx, companyRow.xid); - } - - const issueNumber = companyRow!.issueCounter; - const identifier = `${companyRow!.issuePrefix}-${issueNumber}`; - const newIssueId = randomUUID(); - const privacyRootIssueId = issueVisibility === "private" ? newIssueId : null; - - await tx.insert(issues).values({ - id: newIssueId, - companyId, - projectId, - channelId: channel.id, - visibility: issueVisibility, - privacyRootIssueId, - title: resolvedTitle, - description: resolvedDescription, - status: requestedStatus, - scope, - priority, - assigneeAgentId, - createdByAgentId: actor.agentId, - createdByUserId: actor.agentId ? null : actor.userId, - createdByProfile: actor.actorProfile, - responsibleUserId: actor.responsibleUserId, - kvLabels: mergedKvLabels, - schemaBlocks: validatedBlocks, - resultSchemaRef: resolvedResultSchemaRef, - issueNumber, - identifier, - originKind: "manual", - originId, - originFingerprint: requestHash ?? "default", - createdAt: now, - updatedAt: now, - }); - - await tx - .update(channels) - .set({ lastActivityAt: now, updatedAt: now }) - .where(eq(channels.id, channel.id)); - - const attachedTagNames = - input.tagLabels && input.tagLabels.length > 0 - ? await attachTagLabels(tx, companyId, newIssueId, input.tagLabels) - : []; - - await logActivity( - tx as unknown as Db, - { - companyId, - actorType: actor.principalType === "agent" ? "agent" : "user", - actorId: - actor.principalType === "agent" - ? actor.agentId! - : (actor.userId ?? "local-board"), - agentId: actor.agentId, - issueId: newIssueId, - responsibleUserIdOverride: actor.responsibleUserId, - action: - requestedStatus === "todo" ? "issue.created" : "channel.post_created", - entityType: "issue", - entityId: newIssueId, - details: { - identifier, - channel: channel.path, - status: requestedStatus, - scope, - }, - }, - publications, - { redactor: activityRedactor }, - ); - - const isReadyTask = requestedStatus === "todo" && assigneeAgentId === null; - const primaryEvent = await appendBoardEvent(tx, { - companyId, - type: requestedStatus === "todo" ? "task.created" : "thread.posted", - channelId: channel.id, - channelPath: channel.path, - issueId: newIssueId, - identifier, - actor, - payload: { - title: resolvedTitle, - ...(resolvedDescription ? { description: resolvedDescription.slice(0, 4000) } : {}), - blocks: validatedBlocks, - labels: mergedKvLabels, - kvLabels: mergedKvLabels, - tagLabels: attachedTagNames, - ...(isReadyTask ? { ready: true } : {}), - }, - }); - committedEvents.push(primaryEvent); - - let lastCursor = primaryEvent.cursor; - if (isReadyTask) { - const readyEvent = await appendBoardEvent(tx, { - companyId, - type: "task.ready", - channelId: channel.id, - channelPath: channel.path, - issueId: newIssueId, - identifier, - actor, - payload: { - kvLabels: mergedKvLabels, - tagLabels: attachedTagNames, - }, - }); - committedEvents.push(readyEvent); - lastCursor = readyEvent.cursor; - } - - const view = serializeCreatedHeadlessIssueView({ - id: newIssueId, - companyId, - identifier, - title: resolvedTitle, - description: resolvedDescription, - status: requestedStatus, - scope, - priority, - channelId: channel.id, - channel: channel.path, - projectId, - assigneeAgentId, - assigneeUserId: null, - actorProfile: actor.actorProfile, - kvLabels: mergedKvLabels, - tagLabels: attachedTagNames, - blocks: validatedBlocks, - resultSchemaRef: resolvedResultSchemaRef, - blockedByIssueIds: [], - cursor: lastCursor, - createdAt: now, - updatedAt: now, - }); - return { issue: view, created: true }; - }); - - for (const pub of publications) { - publishActivity(pub); + if (!originId) { + return executeCoalescedChannelPost(db, companyId, postPayload); } - for (const evt of committedEvents) { - publishCommittedBoardEvent(evt); - } - - return txResult; + return executeImmediateChannelPost(db, companyId, postPayload); } export interface ListChannelThreadsQuery { @@ -1422,7 +588,23 @@ export async function listChannelThreads( afterTrimmed, companyId, ); - issueConditions.push(gt(issues.createdAt, refIssue.createdAt)); + issueConditions.push( + refIssue.issueNumber !== null + ? (or( + gt(issues.createdAt, refIssue.createdAt), + and( + eq(issues.createdAt, refIssue.createdAt), + gt(issues.issueNumber, refIssue.issueNumber), + ), + ) as SQL) + : (or( + gt(issues.createdAt, refIssue.createdAt), + and( + eq(issues.createdAt, refIssue.createdAt), + gt(issues.id, refIssue.id), + ), + ) as SQL), + ); } else { const parsedDate = Date.parse(afterTrimmed); if (!Number.isFinite(parsedDate)) { @@ -1441,7 +623,7 @@ export async function listChannelThreads( .select() .from(issues) .where(and(...issueConditions)) - .orderBy(desc(issues.createdAt), desc(issues.id)) + .orderBy(desc(issues.createdAt), desc(issues.issueNumber), desc(issues.id)) .limit(limit); const pageViews = await loadHeadlessIssueViews(db, candidateRows); diff --git a/server/src/services/headless-comment-group-commit.ts b/server/src/services/headless-comment-group-commit.ts new file mode 100644 index 00000000000..22ca18806bd --- /dev/null +++ b/server/src/services/headless-comment-group-commit.ts @@ -0,0 +1,348 @@ +import { and, asc, eq, inArray, sql } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + issueComments, + issueLabels, + issues, + labels, + primeDatabaseWorkTransactionId, +} from "@paperclipai/db"; +import type { + BoardEventView, + CommentView, + SchemaBlock, +} from "@paperclipai/shared"; +import { 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 { + appendBoardEvents, + mintTimeOrderedUuid, + publishCommittedBoardEvent, + serializeCommentView, + touchChannelsLastActivity, + type AppendBoardEventInput, + type HeadlessActorContext, +} from "./headless-common.js"; + +export interface CoalescedCommentInput { + actor: HeadlessActorContext; + targetIssue: { + id: string; + identifier: string | null; + companyId: string; + channelId: string | null; + kvLabels: Record | null; + }; + channelPath: string | null; + authorUserId: string | null; + bodyText: string; + mergedKvLabels: Record; + validatedBlocks: SchemaBlock[]; + internal: boolean; +} + +export interface CoalescedCommentResult { + comment: CommentView; + created: boolean; +} + +async function runCoalescedCommentsBatch( + db: Db, + companyId: string, + entries: Array>, + allowFallback: boolean, +): Promise { + const publications: ActivityPublication[] = []; + const committedEvents: BoardEventView[] = []; + const rejectedEntries: Array<{ + entry: PendingEntry; + error: unknown; + }> = []; + + let outcomes: Array<{ + entry: PendingEntry; + result: CoalescedCommentResult; + }>; + + try { + const activityRedactor = await createActivityDetailsRedactor(db); + + outcomes = await db.transaction(async (tx) => { + const distinctIssueIds = Array.from( + new Set(entries.map((e) => e.item.targetIssue.id)), + ).sort(); + + const lockedIssues = + distinctIssueIds.length === 1 + ? await tx + .select({ id: issues.id, kvLabels: issues.kvLabels }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + eq(issues.id, distinctIssueIds[0]!), + ), + ) + .for("no key update") + : await tx + .select({ id: issues.id, kvLabels: issues.kvLabels }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.id, distinctIssueIds), + ), + ) + .orderBy(asc(issues.id)) + .for("no key update"); + + const currentKvByIssueId = new Map>(); + for (const row of lockedIssues) { + currentKvByIssueId.set( + row.id, + (row.kvLabels ?? {}) as Record, + ); + } + + const activeEntries: Array< + PendingEntry + > = []; + for (const entry of entries) { + if (!currentKvByIssueId.has(entry.item.targetIssue.id)) { + rejectedEntries.push({ entry, error: notFound("Issue not found") }); + } else { + activeEntries.push(entry); + } + } + + if (activeEntries.length === 0) { + return []; + } + + const activeIssueIds = Array.from( + new Set(activeEntries.map((e) => e.item.targetIssue.id)), + ); + + const tagsByIssueId = new Map(); + const tagRows = await tx + .select({ issueId: issueLabels.issueId, name: labels.name }) + .from(issueLabels) + .innerJoin(labels, eq(issueLabels.labelId, labels.id)) + .where( + and( + eq(issueLabels.companyId, companyId), + inArray(issueLabels.issueId, activeIssueIds), + ), + ) + .orderBy(asc(labels.name)); + for (const r of tagRows) { + let arr = tagsByIssueId.get(r.issueId); + if (!arr) { + arr = []; + tagsByIssueId.set(r.issueId, arr); + } + arr.push(r.name); + } + + const now = new Date(); + const nowMs = now.getTime(); + const plannedComments = activeEntries.map((entry) => ({ + entry, + commentId: mintTimeOrderedUuid(nowMs), + createdAt: now, + })); + + if (activeIssueIds.length === 1) { + await tx + .update(issues) + .set({ updatedAt: now }) + .where( + and( + eq(issues.companyId, companyId), + eq(issues.id, activeIssueIds[0]!), + ), + ); + } else { + await tx + .update(issues) + .set({ updatedAt: now }) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.id, activeIssueIds), + ), + ); + } + + const insertedRows = await tx + .insert(issueComments) + .values( + plannedComments.map(({ entry: { item }, commentId, createdAt }) => ({ + id: commentId, + companyId, + issueId: item.targetIssue.id, + authorAgentId: item.actor.agentId, + authorUserId: item.authorUserId, + authorType: item.actor.agentId ? ("agent" as const) : ("user" as const), + actorProfile: item.actor.actorProfile, + body: item.bodyText, + kvLabels: item.mergedKvLabels, + schemaBlocks: item.validatedBlocks, + noSync: item.internal, + clientRequestId: null, + createdAt, + updatedAt: createdAt, + })), + ) + .returning({ + id: issueComments.id, + issueId: issueComments.issueId, + body: issueComments.body, + authorType: issueComments.authorType, + authorUserId: issueComments.authorUserId, + authorAgentId: issueComments.authorAgentId, + actorProfile: issueComments.actorProfile, + kvLabels: issueComments.kvLabels, + schemaBlocks: issueComments.schemaBlocks, + noSync: issueComments.noSync, + createdAt: issueComments.createdAt, + xid: sql`pg_current_xact_id()::text`, + }); + + const insertedById = new Map(insertedRows.map((row) => [row.id, row])); + const firstXid = insertedRows[0]?.xid; + if (firstXid) { + primeDatabaseWorkTransactionId(tx, firstXid); + } + + await touchChannelsLastActivity( + tx, + plannedComments.map((p) => p.entry.item.targetIssue.channelId), + now, + ); + + const activityInputs: LogActivityInput[] = plannedComments.map( + ({ entry: { item }, commentId }) => { + const identifier = item.targetIssue.identifier ?? item.targetIssue.id; + 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: item.targetIssue.id, + responsibleUserIdOverride: item.actor.responsibleUserId, + action: "issue.comment_added", + entityType: "issue", + entityId: item.targetIssue.id, + details: { + commentId, + identifier, + internal: item.internal, + }, + }; + }, + ); + + await logActivitiesBatch(tx as unknown as Db, activityInputs, publications, { + redactor: activityRedactor, + }); + + const eventInputs: AppendBoardEventInput[] = plannedComments.map( + ({ entry: { item }, commentId }) => { + const identifier = item.targetIssue.identifier ?? item.targetIssue.id; + return { + companyId, + type: "comment.posted", + channelId: item.targetIssue.channelId, + channelPath: item.channelPath, + issueId: item.targetIssue.id, + identifier, + actor: item.actor, + payload: { + commentId, + body: item.bodyText.slice(0, 4000), + blocks: item.validatedBlocks, + labels: item.mergedKvLabels, + kvLabels: + currentKvByIssueId.get(item.targetIssue.id) ?? + item.targetIssue.kvLabels ?? + {}, + tagLabels: tagsByIssueId.get(item.targetIssue.id) ?? [], + internal: item.internal, + }, + }; + }, + ); + + const appendedEvents = await appendBoardEvents(tx, eventInputs); + committedEvents.push(...appendedEvents); + + return plannedComments.map((plan, idx) => { + const inserted = insertedById.get(plan.commentId)!; + const evt = appendedEvents[idx]!; + const identifier = + plan.entry.item.targetIssue.identifier ?? plan.entry.item.targetIssue.id; + return { + entry: plan.entry, + result: { + comment: serializeCommentView(inserted, identifier, evt.cursor), + created: true, + }, + }; + }); + }); + } catch (err) { + if (allowFallback && entries.length > 1) { + for (const single of entries) { + await runCoalescedCommentsBatch(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 outcomes) { + outcome.entry.resolve(outcome.result); + } +} + +export const executeCoalescedHeadlessComment = createAdaptiveCompanyBatcher< + CoalescedCommentInput, + CoalescedCommentResult +>(runCoalescedCommentsBatch, { + backpressureMessage: + "Too many concurrent channel replies queued for this company; retry shortly", +}); diff --git a/server/src/services/headless-common.ts b/server/src/services/headless-common.ts index c6fd37ecd52..2538424e8b8 100644 --- a/server/src/services/headless-common.ts +++ b/server/src/services/headless-common.ts @@ -1,6 +1,5 @@ -import { EventEmitter } from "node:events"; import type { Request } from "express"; -import { and, desc, eq, inArray, ne, or, sql, type SQL } from "drizzle-orm"; +import { and, eq, inArray, ne, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, @@ -24,8 +23,6 @@ import { normalizeIssueIdentifier, type AgentApiKeyScope, type AgentIdentityPolicy, - type BoardEventType, - type BoardEventView, type ClientScopes, type CommentView, type DeploymentMode, @@ -42,37 +39,32 @@ import { issueReadSqlCondition, type AuthorizationActor, } from "./authorization.js"; -import { publishLiveEvent } from "./live-events.js"; +import { + appendBoardEvent, + appendBoardEvents, + getLatestCompanyEventCursor, + mintTimeOrderedUuid, + publishCommittedBoardEvent, + subscribeCompanyBoardEvents, + touchChannelsLastActivity, + type AppendBoardEventActor, + type AppendBoardEventInput, + type DbOrTx, +} from "./headless-board-events-write.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 { + appendBoardEvent, + appendBoardEvents, + getLatestCompanyEventCursor, + mintTimeOrderedUuid, + publishCommittedBoardEvent, + subscribeCompanyBoardEvents, + touchChannelsLastActivity, + type AppendBoardEventActor, + type AppendBoardEventInput, + type DbOrTx, +}; export function resolveCompanyAgentIdentityPolicy( storedPolicy: AgentIdentityPolicy | null | undefined, @@ -979,6 +971,7 @@ const issueCommentTargetSelection = { status: issues.status, scope: issues.scope, conversationAgentId: issues.conversationAgentId, + kvLabels: issues.kvLabels, }; export async function resolveIssueCommentTarget( @@ -998,157 +991,6 @@ export async function resolveIssueCommentTarget( ); } -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, diff --git a/server/src/services/headless-labels-batch.ts b/server/src/services/headless-labels-batch.ts index a1e587f6b36..629aa9ef424 100644 --- a/server/src/services/headless-labels-batch.ts +++ b/server/src/services/headless-labels-batch.ts @@ -33,6 +33,7 @@ import { } from "./headless-channels.js"; import { appendBoardEvent, + appendBoardEvents, assertIssueChannelScopeAccess, assertProjectReadAccess, buildNextIssueCounterSql, @@ -41,6 +42,7 @@ import { publishCommittedBoardEvent, resolveIssueByIdOrIdentifier, resolveProjectReference, + touchChannelsLastActivity, type HeadlessActorContext, } from "./headless-common.js"; import { @@ -163,12 +165,7 @@ export async function mutateIssueKvLabels( }) .where(eq(issues.id, locked.id)); - if (locked.channelId) { - await tx - .update(channels) - .set({ lastActivityAt: now, updatedAt: now }) - .where(eq(channels.id, locked.channelId)); - } + await touchChannelsLastActivity(tx, [locked.channelId], now); await logActivity( tx as unknown as Db, @@ -569,15 +566,11 @@ export async function createBatchIssuesPlan( } } - if (channel) { - await tx - .update(channels) - .set({ lastActivityAt: now, updatedAt: now }) - .where(eq(channels.id, channel.id)); - } + await touchChannelsLastActivity(tx, [channel?.id], now); - for (const evInput of pendingEvents) { - const evt = await appendBoardEvent(tx, { + const appendedBatchEvents = await appendBoardEvents( + tx, + pendingEvents.map((evInput) => ({ companyId, type: evInput.type, channelId: channel?.id ?? null, @@ -586,9 +579,12 @@ export async function createBatchIssuesPlan( identifier: evInput.identifier, actor, payload: evInput.payload, - }); + })), + ); + for (let i = 0; i < appendedBatchEvents.length; i += 1) { + const evt = appendedBatchEvents[i]!; committedEvents.push(evt); - cursorByIssueId.set(evInput.issueId, evt.cursor); + cursorByIssueId.set(pendingEvents[i]!.issueId, evt.cursor); } const issueViews = await loadHeadlessIssueViews(tx, createdRows); diff --git a/server/src/services/headless-post-group-commit.ts b/server/src/services/headless-post-group-commit.ts new file mode 100644 index 00000000000..16f0391286b --- /dev/null +++ b/server/src/services/headless-post-group-commit.ts @@ -0,0 +1,606 @@ +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, + ); + }); +}