perf(server): coalesce concurrent channel posts and replies with debounced activity (#23448)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channels and thread replies let many agents publish
concurrent updates, tasks, and replies into shared company streams while
preserving gapless company identifiers and commit-ordered board events
> - After PR #23426 removed per-request query overhead, a fresh local
headless benchmark on merged `origin/master` (`ab2183aaed`) showed
concurrent post throughput hitting a serialization wall at 770–805 req/s
(`c=32`) and degrading to 653 req/s (`p99 = 295.9ms`) at `c=64` on a
single channel
> - Profiling showed why: every concurrent post or reply entered its own
database transaction and blocked sequentially on `UPDATE companies`,
`UPDATE channels`, and `pg_advisory_xact_lock('board_events',
company_id)`, pinning PostgreSQL pool connections and performing N
separate WAL flushes for N concurrent arrivals
> - This pull request adds adaptive in-process group commit for
non-idempotent channel posts and normal thread comments, a 250ms
debounce on `channels.last_activity_at` updates, and multi-row
`activity_log` and `board_events` batch helpers
> - The benefit is zero batching delay when idle (`442.7 req/s`, `p50 =
2.12ms` at `c=1`), `2.40x–2.55x` higher post throughput at `c=32`
(`1,849–2,055 req/s`), `3.11x–3.79x` higher post throughput at `c=64`
(`2,475–2,501 req/s`, `p99` down 85.5%), and `2.24x` higher hot-thread
reply throughput (`1,588 req/s`, `p99` down 73%), while keeping gapless
`<PREFIX>-<N>` identifiers and monotonic `evt_<seq>` cursors

## Linked Issues or Issue Description

Refs #23426

**What existing behavior does this improve?**

`POST /api/companies/:companyId/channels/posts`, `POST
/api/companies/:companyId/issues/batch`, `PATCH
/api/issues/:id/kv-labels`, and `POST /api/issues/:id/comments`
throughput, tail latency, and PostgreSQL connection-pool efficiency
under high concurrency.

**Subsystem affected**

- `server/ — REST API & orchestration services`

**Current behavior**

On `origin/master` (`ab2183aaed`, Node `v26.4.0`, `darwin-arm64`, local
`embedded-postgres` with 2 live SSE subscribers):
- Every concurrent `POST /api/companies/:companyId/channels/posts` call
opens an independent database transaction and contends on the single
`companies` counter row, the `channels` row (`SET last_activity_at =
now()`), and the per-company `board_events` advisory lock.
- At `c=32`, post throughput caps at `770.1 req/s` on a single channel
and `804.5 req/s` across 16 channels; at `c=64`, single-channel post
throughput drops to `653.1 req/s` with `p99 = 295.91ms` because waiting
write transactions exhaust the database connection pool.
- Concurrent replies on a single hot thread (`c=32`) serialize on
unconditional `UPDATE channels SET last_activity_at = now()` and
`board_events` advisory locks, capping at `710.1 req/s` (`p99 =
84.47ms`).

**Proposed behavior**

- Add `touchChannelsLastActivity` (250ms staleness guard with ascending
`channels.id` `FOR NO KEY UPDATE` lock ordering) and `appendBoardEvents`
(single `pg_advisory_xact_lock` + ordered multi-row `INSERT INTO
board_events ... RETURNING` sorted by `seq`) in
`server/src/services/headless-board-events-write.ts`, plus
`logActivitiesBatch` in `server/src/services/activity-log.ts`.
- Add `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` with a
self-cleaning `WeakMap`-backed per-company batcher
(`MAX_COALESCED_BATCH_SIZE = 64`, `MAX_PENDING_PER_COMPANY = 1024`):
- When no batch is in flight (`c=1`), the request dispatches immediately
with zero artificial timer delay.
- While one batch transaction is executing on a single database
connection for that company, concurrent arrivals queue in memory
(bounded with `429` backpressure above `1024`) and execute together in
the next multi-row transaction using real wall-clock `new Date()`
timestamps, `issues.issueNumber` thread tie-breaking in
`listChannelThreads`, and RFC-valid sub-millisecond ordered UUIDs
(`mintTimeOrderedUuid`) across both coalesced and serialized comment
paths.
- Shared `validateChannelPathWriteFromMap` checks per-item channel
access, archived-channel, project access, and assignee rules before
counter allocation so rejected siblings never abort valid siblings or
leave gaps in `<PREFIX>-<N>` issue numbers, and post-commit event
publication runs strictly outside the transaction fallback scope.
- Requests with `idempotencyKey`, `clientRequestId`, or `after` continue
through their dedicated serialized concurrency checks.

**Reason and benefit**

Matched 7-scenario local headless benchmark (`origin/master`
`ab2183aaed` vs `perf/channel-group-commit`, 2 live SSE subscribers
active throughout, 0 errors, 100% live SSE delivery):

| Scenario | Merged `master` (`req/s`) | Group Commit (`req/s`) |
Speedup | `master` `p99` | Group Commit `p99` |
| --- | ---: | ---: | ---: | ---: | ---: |
| 1. Sequential channel posts (`c=1`, 300 msgs) | 451.4 | 442.7 | 0.98x
(no idle delay) | 4.06 ms | 3.79 ms |
| 2. Single-channel posts (`c=32`, 1,000 msgs) | 770.1 | 1,849.2 |
**2.40x** | 89.23 ms | 34.67 ms |
| 3. 16-channel posts (`c=32`, 1,000 msgs) | 804.5 | 2,054.6 | **2.55x**
| 71.76 ms | 22.73 ms |
| 4. 16-thread replies (`c=32`, 1,000 msgs) | 1,045.7 | 1,486.6 |
**1.42x** | 59.53 ms | 28.91 ms |
| 5. Single hot-thread replies (`c=32`, 500 msgs) | 710.1 | 1,588.3 |
**2.24x** | 84.47 ms | 22.70 ms |
| 6. Single-channel posts (`c=64`, 2,000 msgs) | 653.1 | 2,474.7 |
**3.79x** | 295.91 ms | 42.80 ms |
| 7. 16-channel posts (`c=64`, 2,000 msgs) | 803.4 | 2,501.3 | **3.11x**
| 124.65 ms | 32.72 ms |

**Breaking changes**

None. All endpoints, request/response shapes, gapless `<PREFIX>-<N>`
identifiers, commit-ordered `evt_<seq>` cursors, idempotency semantics,
`after` optimistic concurrency checks, and channel/project/issue privacy
checks remain unchanged. `channels.lastActivityAt` updates at most once
per 250ms window under sustained traffic on the same channel.

**Additional context**

Builds on #23426 without schema migrations or external coordination
dependencies.

## What Changed

- Extracted shared activity preparation, row mapping
(`buildActivityLogRow`), side-effect notification, and publication
helpers in `server/src/services/activity-log.ts` and added
`logActivitiesBatch` for single-statement multi-row `activity_log`
inserts.
- Extracted `server/src/services/headless-board-events-write.ts`
(re-exported from `server/src/services/headless-common.ts`) with
`mintTimeOrderedUuid`, `touchChannelsLastActivity` (250ms debounce with
canonical ascending `channels.id` `FOR NO KEY UPDATE` lock ordering),
listener-isolated `subscribeCompanyBoardEvents`, and `appendBoardEvents`
(single `pg_advisory_xact_lock` acquisition with ordered multi-row
`INSERT INTO board_events ... RETURNING` sorted by `seq`).
- Extracted `server/src/services/headless-channel-write-helpers.ts`
(re-exported from `server/src/services/headless-channels.ts`) so channel
path validation, `ensureChannel`, tag upserts, and assignee resolution
are shared via normal imports without per-item callback plumbing.
- Added `server/src/services/adaptive-company-batcher.ts`,
`server/src/services/headless-post-group-commit.ts`, and
`server/src/services/headless-comment-group-commit.ts` implementing
bounded per-company write coalescing (`MAX_COALESCED_BATCH_SIZE = 64`,
`MAX_PENDING_PER_COMPANY = 1024`), post-lock wall-clock `new Date()` +
`mintTimeOrderedUuid` sampling so batches waiting behind `companies` or
`issues` row locks always receive newer `(createdAt, id)` tuples,
UUID-keyed comment `RETURNING` joins, per-item validation isolation, and
post-commit event publication strictly outside the transaction fallback
boundary.
- Updated `createChannelPost` and `listChannelThreads` in
`server/src/services/headless-channels.ts`,
`server/src/services/headless-labels-batch.ts`, and
`server/src/routes/headless-channels-schemas.ts` to tie-break equal
`createdAt` rows on `issues.issueNumber` and use
`touchChannelsLastActivity`, `appendBoardEvents`, `mintTimeOrderedUuid`,
and `executeCoalescedHeadlessComment`.
- Added regression tests in
`server/src/__tests__/adaptive-company-batcher.test.ts`,
`server/src/__tests__/headless-channels-schemas-batch.test.ts` (16-way
mixed burst with pinned per-request statuses, wall-clock bounds,
`issueNumber` thread/after ordering, real PostgreSQL insert-error solo
fallback on both posts and comments, coalesced comment batches waiting
behind active `FOR UPDATE` serialized locks, deterministic 250ms
`lastActivityAt` skip/update assertions, and post-commit throwing
subscriber isolation), and
`server/src/__tests__/activity-log-responsible-user.test.ts`
(`logActivitiesBatch` redaction, `responsibleUserId` attribution, and
`mcpEvents` work signaling).

## Verification

- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/adaptive-company-batcher.test.ts
src/__tests__/activity-log-responsible-user.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-task-workflows.test.ts
src/__tests__/experimental-channels-viewer.test.ts` (6 files, 47/47
tests passed)
- Matched 7-scenario local headless benchmark on `origin/master`
(`ab2183aaed`) vs `perf/channel-group-commit` with 2 live SSE
subscribers (`0` errors, `100%` SSE event delivery across all runs)

## Risks

- Low risk. No database migrations or API contract changes. Coalesced
batches hold canonical lock order (`companies -> issues -> channels ->
labels -> issue_labels -> board_events` for posts; `issues ->
issue_comments -> channels -> board_events` for comments), isolate
read-only validation errors per item before minting issue numbers,
delete idle per-company queue state immediately, and fall back to solo
execution if an unexpected database error occurs on a multi-item batch.

## Model Used

- Google Gemini (Antigravity agentic coding assistant, extended thinking
mode with shell, profiling, and test execution tools)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-12-02 06:13:26 -06:00
1 parent f91e05406d
commit debfa75a7a
13 files changed
+3352 -1129

No files matched your search

@@ -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,
});
}
});
});
@@ -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<void>((resolve) => {
releaseFirst = resolve;
});
const batcher = createAdaptiveCompanyBatcher<{ id: string }, string>(
async (
_db,
_companyId,
entries: Array<PendingEntry<{ id: string }, string>>,
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<void>((resolve) => {
releaseFirstBatch = resolve;
});
const batcher = createAdaptiveCompanyBatcher<number, number>(
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);
});
});
@@ -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<string, unknown>;
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<void>((resolve) => {
notifyLocked = resolve;
});
let releaseSerializedLock!: () => void;
const releaseGate = new Promise<void>((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,
);
});
});
+27 -8
View File
@@ -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,
+133 -34
View File
@@ -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<string, unknown> | 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<ReturnType<typeof prepareActivityRow>>,
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;
}
@@ -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<TItem, TResult> {
item: TItem;
resolve: (value: TResult) => void;
reject: (reason: unknown) => void;
}
export interface AdaptiveBatcherOptions {
maxBatchSize?: number;
maxPending?: number;
backpressureMessage?: string;
}
interface CompanyBatchQueue<TItem, TResult> {
inFlight: boolean;
pending: Array<PendingEntry<TItem, TResult>>;
}
export function createAdaptiveCompanyBatcher<TItem, TResult>(
runBatch: (
db: Db,
companyId: string,
entries: Array<PendingEntry<TItem, TResult>>,
allowFallback: boolean,
) => Promise<void>,
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<string, CompanyBatchQueue<TItem, TResult>>
>();
const drain = async (
db: Db,
companyId: string,
companyQueues: Map<string, CompanyBatchQueue<TItem, TResult>>,
queue: CompanyBatchQueue<TItem, TResult>,
): Promise<void> => {
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<TResult> => {
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<TResult>((resolve, reject) => {
queue.pending.push({ item, resolve, reject });
if (!queue.inFlight) {
void drain(db, companyId, companyQueues, queue);
}
});
};
}
@@ -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<Parameters<Db["transaction"]>[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<T>(
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<string | null | undefined>,
now: Date,
): Promise<void> {
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<string, unknown> {
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<string, unknown>;
}
export async function appendBoardEvents(
dbOrTx: DbOrTx,
inputs: AppendBoardEventInput[],
): Promise<BoardEventView[]> {
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, unknown> | 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, unknown> | 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<string, unknown> =
typeof inserted.payload === "string"
? (JSON.parse(inserted.payload) as Record<string, unknown>)
: 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<BoardEventView> {
const [single] = await appendBoardEvents(dbOrTx, [input]);
return single!;
}
export async function getLatestCompanyEventCursor(
dbOrTx: DbOrTx,
companyId: string,
): Promise<string> {
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);
}
@@ -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<string>();
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<string, typeof channels.$inferSelect>,
): 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<string, unknown>,
): Record<string, string> {
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<string | null> {
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<Array<{ id: string; name: string }>> {
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<Map<string, string[]>> {
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<string, string[]>();
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<string[]> {
const attachedMap = await attachTagLabelsToIssues(tx, companyId, [
{ issueId, tagNames },
]);
return attachedMap.get(issueId) ?? [];
}
async function addChannelCreatorMembership(
dbOrTx: DbOrTx,
companyId: string,
channelId: string,
actor: HeadlessActorContext,
): Promise<void> {
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<typeof channels.$inferSelect> {
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<typeof channels.$inferInsert> = {};
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;
}
File diff suppressed because it is too large. Load diff
@@ -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<string, string> | null;
};
channelPath: string | null;
authorUserId: string | null;
bodyText: string;
mergedKvLabels: Record<string, string>;
validatedBlocks: SchemaBlock[];
internal: boolean;
}
export interface CoalescedCommentResult {
comment: CommentView;
created: boolean;
}
async function runCoalescedCommentsBatch(
db: Db,
companyId: string,
entries: Array<PendingEntry<CoalescedCommentInput, CoalescedCommentResult>>,
allowFallback: boolean,
): Promise<void> {
const publications: ActivityPublication[] = [];
const committedEvents: BoardEventView[] = [];
const rejectedEntries: Array<{
entry: PendingEntry<CoalescedCommentInput, CoalescedCommentResult>;
error: unknown;
}> = [];
let outcomes: Array<{
entry: PendingEntry<CoalescedCommentInput, CoalescedCommentResult>;
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<string, Record<string, string>>();
for (const row of lockedIssues) {
currentKvByIssueId.set(
row.id,
(row.kvLabels ?? {}) as Record<string, string>,
);
}
const activeEntries: Array<
PendingEntry<CoalescedCommentInput, CoalescedCommentResult>
> = [];
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<string, string[]>();
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<string>`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",
});
+26 -184
View File
@@ -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<Parameters<Db["transaction"]>[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<string, unknown> {
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<string, unknown>;
},
): Promise<BoardEventView> {
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, unknown> | 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<string, unknown> =
typeof inserted!.payload === "string"
? (JSON.parse(inserted!.payload) as Record<string, unknown>)
: 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<string> {
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<typeof issues.$inferSelect>,
+12 -16
View File
@@ -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);
@@ -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<string, string>;
tagLabelsInput: string[];
validatedBlocks: SchemaBlock[];
resolvedResultSchemaRef: string | null;
originId?: string | null;
requestHash?: string | null;
}
export interface CoalescedChannelPostResult {
issue: HeadlessIssueView;
created: boolean;
}
interface PrevalidatedPostItem {
entry: PendingEntry<CoalescedChannelPostInput, CoalescedChannelPostResult>;
existingChannel: typeof channels.$inferSelect | null;
explicitProjectId: string | null | undefined;
assigneeAgentId: string | null;
}
async function prevalidateChannelPostItem(
tx: DbOrTx,
companyId: string,
entry: PendingEntry<CoalescedChannelPostInput, CoalescedChannelPostResult>,
channelByPath: ReadonlyMap<string, typeof channels.$inferSelect>,
): Promise<PrevalidatedPostItem> {
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<PendingEntry<CoalescedChannelPostInput, CoalescedChannelPostResult>>,
allowFallback: boolean,
): Promise<void> {
const publications: ActivityPublication[] = [];
const committedEvents: BoardEventView[] = [];
const rejectedEntries: Array<{
entry: PendingEntry<CoalescedChannelPostInput, CoalescedChannelPostResult>;
error: unknown;
}> = [];
let resolvedOutcomes: Array<{
entry: PendingEntry<CoalescedChannelPostInput, CoalescedChannelPostResult>;
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<string, typeof channels.$inferSelect>();
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<CoalescedChannelPostInput, CoalescedChannelPostResult>;
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<string>();
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<string>`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<CoalescedChannelPostResult> {
return new Promise<CoalescedChannelPostResult>((resolve, reject) => {
void runCoalescedChannelPostsBatch(
db,
companyId,
[{ item, resolve, reject }],
false,
);
});
}